title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to Apply K-means Clustering to Time Series Data | by Alexandra Amidon | Towards Data Science
Clustering is an unsupervised learning task where an algorithm groups similar data points without any “ground truth” labels. Similarity between data points is measured with a distance metric, commonly Euclidean distance. Clustering different time series into similar groups is a challenging clustering task because each data point is an ordered sequence. The most common approach to time series clustering is to flatten the time series into a table, with a column for each time index (or aggregation of the series) and directly apply standard clustering algorithms like k-means. (K-means is a common clustering algorithm that constructs clusters of data by splitting samples into k groups and minimizing the sum-of-squares in each cluster). As shown below, this doesn’t always work well. Each subfigure in the chart plots a cluster generated by k-means clustering with Euclidian distance. The cluster centroids in red do not capture the shape of the series. Intuitively, the distance measures used in standard clustering algorithms, such as Euclidean distance, are often not appropriate to time series. A better approach is to replace the default distance measure with a metric for comparing time series, such as Dynamic Time Warping. In this article, I will explain how to adapt the k-means clustering to time series using dynamic time warping. I will provide easy code examples from the tslearn package. But first, why is the common Euclidean distance metric is unsuitable for time series? In short, it is invariant to time shifts, ignoring the time dimension of the data. If two time series are highly correlated, but one is shifted by even one time step, Euclidean distance would erroneously measure them as further apart. Click here for a detailed example. Instead, it is better to use dynamic time warping (DTW) to compare series. DTW is a technique to measure similarity between two temporal sequences that do not align exactly in time, speed, or length. Given series X=(x0, ..., xn) and series Y=(y0, ..., ym), the DTW distance from X to Y is formulated as the following optimization problem: To summarize the DTW equation: DTW is calculated as the squared root of the sum of squared distances between each element in X and its nearest point in Y. Note that DTW(X, Y) ≠ DTW(Y, X). Let’s break this down further. DTW compares each element in series X with each element in series Y (n x m comparisons). The comparison, d(xi, yj), is just the simple subtraction xi — yj. Then for each xi in X, DTW selects the nearest point in Y for distance calculation. This creates a warped “path” between X and Y that aligns each point in X to the nearest point in Y. The path is a temporal alignment of time series that minimizes the Euclidean distance between aligned series. Dynamic Time Warping is computed using dynamic programming with complexity O(MN). Click here or here for more details about the specific algorithm. It is easy to compare two time series with DTW in python: from tslearn.metrics import dtwdtw_score = dtw(x, y) soft-DTW is a differentiable variant of DTW that replaces the non-differentiable min operation with a differentiable soft-min operation: Per the function, soft-DTW depends on a hyper-parameter γ that controls the smoothing of the resulting metric. like DTW, soft-DTW can be computed in quadratic time using dynamic programming. Footnote: The main advantage of soft-DTW stems from the fact that it is differentiable everywhere. This allows soft-DTW to be used as a neural networks loss function, comparing a ground-truth series and a predicted series. from tslearn.metrics import soft_dtwsoft_dtw_score = soft_dtw(x, y, gamma=.1) The k-means clustering algorithm can be applied to time series with dynamic time warping with the following modifications. Dynamic Time Warping (DTW) is used to collect time series of similar shapes.Cluster centroids, or barycenters, are computed with respect to DTW. A barycenter is the average sequence from a group of time series in DTW space. The DTW Barycenter Averaging (DBA) algorithm minimizes sum of squared DTW distance between the barycenter and the series in the cluster. The soft-DTW algorithm minimizes the weighted sum of soft-DTW distances between the barycenter and the series in the cluster. The weights can be tuned but must sum to 1. Dynamic Time Warping (DTW) is used to collect time series of similar shapes. Cluster centroids, or barycenters, are computed with respect to DTW. A barycenter is the average sequence from a group of time series in DTW space. The DTW Barycenter Averaging (DBA) algorithm minimizes sum of squared DTW distance between the barycenter and the series in the cluster. The soft-DTW algorithm minimizes the weighted sum of soft-DTW distances between the barycenter and the series in the cluster. The weights can be tuned but must sum to 1. As a result, the centroids have an average shape that mimics the shape of the members of the cluster, regardless of where temporal shifts occur amongst the members. Using the tslearn Python package, clustering a time series dataset with k-means and DTW simple: from tslearn.clustering import TimeSeriesKMeansmodel = TimeSeriesKMeans(n_clusters=3, metric="dtw", max_iter=10)model.fit(data) To use soft-DTW instead of DTW, simply set metric="softdtw". Note that tslearn expects a single time series to be formatted as two-dimensional array. A set of time series should be formatted as a three-dimensional array with shape (num_series, max_length, 1). If series in the set are not of equal length, the shorter series are augmented with NaN values. tslearn has easy-to-use utility functions for properly formatting data and integrates easily with other time series packages and data formats. I hope you enjoyed reading this piece. To learn about time series machine learning, please check out my other articles: link.medium.com towardsdatascience.com medium.com Understanding Dynamic Time Warping by DataBricks Paparrizos, John and Gravano, Luis, 2015. k-Shape: Efficient and Accurate Clustering of Time Series Time Series Classification and Clustering by Alex Minnaar TSLearn User Guide for Clustering Dynamic Time Warping Wikipedia article Time Series Aggregation by LumenAI
[ { "code": null, "e": 393, "s": 172, "text": "Clustering is an unsupervised learning task where an algorithm groups similar data points without any “ground truth” labels. Similarity between data points is measured with a distance metric, commonly Euclidean distance." }, { "code": null, "e": 527, "s": 393, "text": "Clustering different time series into similar groups is a challenging clustering task because each data point is an ordered sequence." }, { "code": null, "e": 913, "s": 527, "text": "The most common approach to time series clustering is to flatten the time series into a table, with a column for each time index (or aggregation of the series) and directly apply standard clustering algorithms like k-means. (K-means is a common clustering algorithm that constructs clusters of data by splitting samples into k groups and minimizing the sum-of-squares in each cluster)." }, { "code": null, "e": 1130, "s": 913, "text": "As shown below, this doesn’t always work well. Each subfigure in the chart plots a cluster generated by k-means clustering with Euclidian distance. The cluster centroids in red do not capture the shape of the series." }, { "code": null, "e": 1407, "s": 1130, "text": "Intuitively, the distance measures used in standard clustering algorithms, such as Euclidean distance, are often not appropriate to time series. A better approach is to replace the default distance measure with a metric for comparing time series, such as Dynamic Time Warping." }, { "code": null, "e": 1578, "s": 1407, "text": "In this article, I will explain how to adapt the k-means clustering to time series using dynamic time warping. I will provide easy code examples from the tslearn package." }, { "code": null, "e": 1934, "s": 1578, "text": "But first, why is the common Euclidean distance metric is unsuitable for time series? In short, it is invariant to time shifts, ignoring the time dimension of the data. If two time series are highly correlated, but one is shifted by even one time step, Euclidean distance would erroneously measure them as further apart. Click here for a detailed example." }, { "code": null, "e": 2134, "s": 1934, "text": "Instead, it is better to use dynamic time warping (DTW) to compare series. DTW is a technique to measure similarity between two temporal sequences that do not align exactly in time, speed, or length." }, { "code": null, "e": 2273, "s": 2134, "text": "Given series X=(x0, ..., xn) and series Y=(y0, ..., ym), the DTW distance from X to Y is formulated as the following optimization problem:" }, { "code": null, "e": 2462, "s": 2273, "text": "To summarize the DTW equation: DTW is calculated as the squared root of the sum of squared distances between each element in X and its nearest point in Y. Note that DTW(X, Y) ≠ DTW(Y, X)." }, { "code": null, "e": 2493, "s": 2462, "text": "Let’s break this down further." }, { "code": null, "e": 2649, "s": 2493, "text": "DTW compares each element in series X with each element in series Y (n x m comparisons). The comparison, d(xi, yj), is just the simple subtraction xi — yj." }, { "code": null, "e": 2733, "s": 2649, "text": "Then for each xi in X, DTW selects the nearest point in Y for distance calculation." }, { "code": null, "e": 2943, "s": 2733, "text": "This creates a warped “path” between X and Y that aligns each point in X to the nearest point in Y. The path is a temporal alignment of time series that minimizes the Euclidean distance between aligned series." }, { "code": null, "e": 3091, "s": 2943, "text": "Dynamic Time Warping is computed using dynamic programming with complexity O(MN). Click here or here for more details about the specific algorithm." }, { "code": null, "e": 3149, "s": 3091, "text": "It is easy to compare two time series with DTW in python:" }, { "code": null, "e": 3202, "s": 3149, "text": "from tslearn.metrics import dtwdtw_score = dtw(x, y)" }, { "code": null, "e": 3339, "s": 3202, "text": "soft-DTW is a differentiable variant of DTW that replaces the non-differentiable min operation with a differentiable soft-min operation:" }, { "code": null, "e": 3530, "s": 3339, "text": "Per the function, soft-DTW depends on a hyper-parameter γ that controls the smoothing of the resulting metric. like DTW, soft-DTW can be computed in quadratic time using dynamic programming." }, { "code": null, "e": 3753, "s": 3530, "text": "Footnote: The main advantage of soft-DTW stems from the fact that it is differentiable everywhere. This allows soft-DTW to be used as a neural networks loss function, comparing a ground-truth series and a predicted series." }, { "code": null, "e": 3831, "s": 3753, "text": "from tslearn.metrics import soft_dtwsoft_dtw_score = soft_dtw(x, y, gamma=.1)" }, { "code": null, "e": 3954, "s": 3831, "text": "The k-means clustering algorithm can be applied to time series with dynamic time warping with the following modifications." }, { "code": null, "e": 4485, "s": 3954, "text": "Dynamic Time Warping (DTW) is used to collect time series of similar shapes.Cluster centroids, or barycenters, are computed with respect to DTW. A barycenter is the average sequence from a group of time series in DTW space. The DTW Barycenter Averaging (DBA) algorithm minimizes sum of squared DTW distance between the barycenter and the series in the cluster. The soft-DTW algorithm minimizes the weighted sum of soft-DTW distances between the barycenter and the series in the cluster. The weights can be tuned but must sum to 1." }, { "code": null, "e": 4562, "s": 4485, "text": "Dynamic Time Warping (DTW) is used to collect time series of similar shapes." }, { "code": null, "e": 5017, "s": 4562, "text": "Cluster centroids, or barycenters, are computed with respect to DTW. A barycenter is the average sequence from a group of time series in DTW space. The DTW Barycenter Averaging (DBA) algorithm minimizes sum of squared DTW distance between the barycenter and the series in the cluster. The soft-DTW algorithm minimizes the weighted sum of soft-DTW distances between the barycenter and the series in the cluster. The weights can be tuned but must sum to 1." }, { "code": null, "e": 5182, "s": 5017, "text": "As a result, the centroids have an average shape that mimics the shape of the members of the cluster, regardless of where temporal shifts occur amongst the members." }, { "code": null, "e": 5278, "s": 5182, "text": "Using the tslearn Python package, clustering a time series dataset with k-means and DTW simple:" }, { "code": null, "e": 5406, "s": 5278, "text": "from tslearn.clustering import TimeSeriesKMeansmodel = TimeSeriesKMeans(n_clusters=3, metric=\"dtw\", max_iter=10)model.fit(data)" }, { "code": null, "e": 5467, "s": 5406, "text": "To use soft-DTW instead of DTW, simply set metric=\"softdtw\"." }, { "code": null, "e": 5905, "s": 5467, "text": "Note that tslearn expects a single time series to be formatted as two-dimensional array. A set of time series should be formatted as a three-dimensional array with shape (num_series, max_length, 1). If series in the set are not of equal length, the shorter series are augmented with NaN values. tslearn has easy-to-use utility functions for properly formatting data and integrates easily with other time series packages and data formats." }, { "code": null, "e": 6025, "s": 5905, "text": "I hope you enjoyed reading this piece. To learn about time series machine learning, please check out my other articles:" }, { "code": null, "e": 6041, "s": 6025, "text": "link.medium.com" }, { "code": null, "e": 6064, "s": 6041, "text": "towardsdatascience.com" }, { "code": null, "e": 6075, "s": 6064, "text": "medium.com" }, { "code": null, "e": 6124, "s": 6075, "text": "Understanding Dynamic Time Warping by DataBricks" }, { "code": null, "e": 6224, "s": 6124, "text": "Paparrizos, John and Gravano, Luis, 2015. k-Shape: Efficient and Accurate Clustering of Time Series" }, { "code": null, "e": 6282, "s": 6224, "text": "Time Series Classification and Clustering by Alex Minnaar" }, { "code": null, "e": 6316, "s": 6282, "text": "TSLearn User Guide for Clustering" }, { "code": null, "e": 6355, "s": 6316, "text": "Dynamic Time Warping Wikipedia article" } ]
Closest perfect square and its distance
30 Jun, 2022 Given a positive integer . The task is to find the perfect square number closest to N and steps required to reach this number from N.Note: The closest perfect square to N can be either less than, equal to or greater than N and steps are referred to as the difference between N and the closest perfect square.Examples: Input: N = 1500 Output: Perfect square = 1521, Steps = 21 For N = 1500 Closest perfect square greater than N is 1521. So steps required is 21. Closest perfect square less than N is 1444. So steps required is 56. The minimum of these two is 1521 with steps 21.Input: N = 2 Output: Perfect Square = 1, Steps = 1 For N = 2 Closest perfect square greater than N is 4. So steps required is 2. Closest perfect square less than N is 1. So steps required is 1. The minimum of these two is 1. Approach 1: If N is a perfect square then print N and steps as 0. Else, find the first perfect square number > N and note its difference with N. Then, find the first perfect square number < N and note its difference with N. And print the perfect square resulting in the minimum of these two differences obtained and also the difference as the minimum steps. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // CPP program to find the closest perfect square// taking minimum steps to reach from a number #include <bits/stdc++.h>using namespace std; // Function to check if a number is// perfect square or notbool isPerfect(int N){ if ((sqrt(N) - floor(sqrt(N))) != 0) return false; return true;} // Function to find the closest perfect square// taking minimum steps to reach from a numbervoid getClosestPerfectSquare(int N){ if (isPerfect(N)) { cout << N << " " << "0" << endl; return; } // Variables to store first perfect // square number // above and below N int aboveN = -1, belowN = -1; int n1; // Finding first perfect square // number greater than N n1 = N + 1; while (true) { if (isPerfect(n1)) { aboveN = n1; break; } else n1++; } // Finding first perfect square // number less than N n1 = N - 1; while (true) { if (isPerfect(n1)) { belowN = n1; break; } else n1--; } // Variables to store the differences int diff1 = aboveN - N; int diff2 = N - belowN; if (diff1 > diff2) cout << belowN << " " << diff2; else cout << aboveN << " " << diff1;} // Driver codeint main(){ int N = 1500; getClosestPerfectSquare(N);}// This code is contributed by// Surendra_Gangwar // Java program to find the closest perfect square// taking minimum steps to reach from a number class GFG { // Function to check if a number is // perfect square or not static boolean isPerfect(int N) { if ((Math.sqrt(N) - Math.floor(Math.sqrt(N))) != 0) return false; return true; } // Function to find the closest perfect square // taking minimum steps to reach from a number static void getClosestPerfectSquare(int N) { if (isPerfect(N)) { System.out.println(N + " " + "0"); return; } // Variables to store first perfect // square number // above and below N int aboveN = -1, belowN = -1; int n1; // Finding first perfect square // number greater than N n1 = N + 1; while (true) { if (isPerfect(n1)) { aboveN = n1; break; } else n1++; } // Finding first perfect square // number less than N n1 = N - 1; while (true) { if (isPerfect(n1)) { belowN = n1; break; } else n1--; } // Variables to store the differences int diff1 = aboveN - N; int diff2 = N - belowN; if (diff1 > diff2) System.out.println(belowN + " " + diff2); else System.out.println(aboveN + " " + diff1); } // Driver code public static void main(String args[]) { int N = 1500; getClosestPerfectSquare(N); }} # Python3 program to find the closest# perfect square taking minimum steps# to reach from a number # Function to check if a number is# perfect square or notfrom math import sqrt, floor def isPerfect(N): if (sqrt(N) - floor(sqrt(N)) != 0): return False return True # Function to find the closest perfect square# taking minimum steps to reach from a number def getClosestPerfectSquare(N): if (isPerfect(N)): print(N, "0") return # Variables to store first perfect # square number above and below N aboveN = -1 belowN = -1 n1 = 0 # Finding first perfect square # number greater than N n1 = N + 1 while (True): if (isPerfect(n1)): aboveN = n1 break else: n1 += 1 # Finding first perfect square # number less than N n1 = N - 1 while (True): if (isPerfect(n1)): belowN = n1 break else: n1 -= 1 # Variables to store the differences diff1 = aboveN - N diff2 = N - belowN if (diff1 > diff2): print(belowN, diff2) else: print(aboveN, diff1) # Driver codeN = 1500getClosestPerfectSquare(N) # This code is contributed# by sahishelangia // C# program to find the closest perfect square// taking minimum steps to reach from a numberusing System; class GFG { // Function to check if a number is // perfect square or not static bool isPerfect(int N) { if ((Math.Sqrt(N) - Math.Floor(Math.Sqrt(N))) != 0) return false; return true; } // Function to find the closest perfect square // taking minimum steps to reach from a number static void getClosestPerfectSquare(int N) { if (isPerfect(N)) { Console.WriteLine(N + " " + "0"); return; } // Variables to store first perfect // square number // above and below N int aboveN = -1, belowN = -1; int n1; // Finding first perfect square // number greater than N n1 = N + 1; while (true) { if (isPerfect(n1)) { aboveN = n1; break; } else n1++; } // Finding first perfect square // number less than N n1 = N - 1; while (true) { if (isPerfect(n1)) { belowN = n1; break; } else n1--; } // Variables to store the differences int diff1 = aboveN - N; int diff2 = N - belowN; if (diff1 > diff2) Console.WriteLine(belowN + " " + diff2); else Console.WriteLine(aboveN + " " + diff1); } // Driver code public static void Main() { int N = 1500; getClosestPerfectSquare(N); }}// This code is contributed by anuj_67.. <?php// PHP program to find the closest perfect// square taking minimum steps to reach// from a number // Function to check if a number is// perfect square or notfunction isPerfect($N){ if ((sqrt($N) - floor(sqrt($N))) != 0) return false; return true;} // Function to find the closest perfect square// taking minimum steps to reach from a numberfunction getClosestPerfectSquare($N){ if (isPerfect($N)) { echo $N, " ", "0", "\n"; return; } // Variables to store first perfect // square number // above and below N $aboveN = -1; $belowN = -1; $n1; // Finding first perfect square // number greater than N $n1 = $N + 1; while (true) { if (isPerfect($n1)) { $aboveN = $n1; break; } else $n1++; } // Finding first perfect square // number less than N $n1 = $N - 1; while (true) { if (isPerfect($n1)) { $belowN = $n1; break; } else $n1--; } // Variables to store the differences $diff1 = $aboveN - $N; $diff2 = $N - $belowN; if ($diff1 > $diff2) echo $belowN, " " , $diff2; else echo $aboveN, " ", $diff1;} // Driver code$N = 1500;getClosestPerfectSquare($N); // This code is contributed by ajit.?> <script> // Javascript program to find // the closest perfect square // taking minimum steps to reach // from a number // Function to check if a number is // perfect square or not function isPerfect(N) { if ((Math.sqrt(N) - Math.floor(Math.sqrt(N))) != 0) return false; return true; } // Function to find the closest perfect square // taking minimum steps to reach from a number function getClosestPerfectSquare(N) { if (isPerfect(N)) { document.write(N + " " + "0" + "</br>"); return; } // Variables to store first perfect // square number // above and below N let aboveN = -1, belowN = -1; let n1; // Finding first perfect square // number greater than N n1 = N + 1; while (true) { if (isPerfect(n1)) { aboveN = n1; break; } else n1++; } // Finding first perfect square // number less than N n1 = N - 1; while (true) { if (isPerfect(n1)) { belowN = n1; break; } else n1--; } // Variables to store the differences let diff1 = aboveN - N; let diff2 = N - belowN; if (diff1 > diff2) document.write(belowN + " " + diff2); else document.write(aboveN + " " + diff1); } let N = 1500; getClosestPerfectSquare(N); </script> 1521 21 Time Complexity: O(n), where n is the given number since we are using brute force to find the above and below perfect squares. Space Complexity: O(1), since no extra space has been taken. Approach 2: The above method might take a lot of time for bigger numbers i.e. greater than 106. We would wish to have a faster way to do that. Here, we will use maths to solve the above problem in constant time complexity. We will first find the square root of the number n. We will check if n was a perfect square, and if it was, we will return 0 there itself. Else, we will use its square root to find the just above and below perfect square numbers, and return the one which is at the minimum distance. Below is the implementation of the above approach: C++ Java Python3 // CPP program to find the closest perfect square// taking minimum steps to reach from a number #include <bits/stdc++.h>using namespace std; // Function to find the closest perfect square// taking minimum steps to reach from a numbervoid getClosestPerfectSquare(int N){ int x = sqrt(N); //Checking if N is a perfect square if((x*x)==N){ cout<<N<<" "<<0; return; } // If N is not a perfect square, // squaring x and x+1 gives us the // just below and above perfect squares // Variables to store perfect // square number just // above and below N int aboveN = (x+1)*(x+1), belowN = x*x; // Variables to store the differences int diff1 = aboveN - N; int diff2 = N - belowN; if (diff1 > diff2) cout << belowN << " " << diff2; else cout << aboveN << " " << diff1;} // Driver codeint main(){ int N = 1500; getClosestPerfectSquare(N);}// This code is contributed by// Rohit Kumar // Java program for the above approach public class GFG {// Function to find the closest perfect square// taking minimum steps to reach from a numberstatic void getClosestPerfectSquare(int N){ int x = (int)Math.sqrt(N); //Checking if N is a perfect square if((x*x)==N){ System.out.println(N); return; } // If N is not a perfect square, // squaring x and x+1 gives us the // just below and above perfect squares // Variables to store perfect // square number just // above and below N int aboveN = (x+1)*(x+1), belowN = x*x; // Variables to store the differences int diff1 = aboveN - N; int diff2 = N - belowN; if (diff1 > diff2) System.out.println(belowN+" "+diff2); else System.out.println(aboveN+" "+diff1); } // Driver Code public static void main (String[] args) { int N = 1500; getClosestPerfectSquare(N); }} // This code is contributed by aditya942003patil # Python3 program to find the closest# perfect square taking minimum steps# to reach from a number from math import sqrt, floor # Function to find the closest perfect square# taking minimum steps to reach from a number def getClosestPerfectSquare(N): x = floor(sqrt(N)) # Checking if N is itself a perfect square if (sqrt(N) - floor(sqrt(N)) == 0): print(N,0) return # Variables to store first perfect # square number above and below N aboveN = (x+1)*(x+1) belowN = x*x # Variables to store the differences diff1 = aboveN - N diff2 = N - belowN if (diff1 > diff2): print(belowN, diff2) else: print(aboveN, diff1) # Driver codeN = 1500getClosestPerfectSquare(N) # This code is contributed# by Rohit Kumar 1521 21 Time Complexity: O(1), since we have used only maths here. Space Complexity: O(1), since no extra space has been taken. vt_m SURENDRA_GANGWAR jit_t sahilshelangia rameshtravel07 sagar0719kumar rohitmishra051000 souravmahato348 aditya942003patil maths-perfect-square Java Programs Mathematical Technical Scripter Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n30 Jun, 2022" }, { "code": null, "e": 374, "s": 54, "text": "Given a positive integer . The task is to find the perfect square number closest to N and steps required to reach this number from N.Note: The closest perfect square to N can be either less than, equal to or greater than N and steps are referred to as the difference between N and the closest perfect square.Examples: " }, { "code": null, "e": 860, "s": 374, "text": "Input: N = 1500 Output: Perfect square = 1521, Steps = 21 For N = 1500 Closest perfect square greater than N is 1521. So steps required is 21. Closest perfect square less than N is 1444. So steps required is 56. The minimum of these two is 1521 with steps 21.Input: N = 2 Output: Perfect Square = 1, Steps = 1 For N = 2 Closest perfect square greater than N is 4. So steps required is 2. Closest perfect square less than N is 1. So steps required is 1. The minimum of these two is 1. " }, { "code": null, "e": 876, "s": 862, "text": "Approach 1: " }, { "code": null, "e": 930, "s": 876, "text": "If N is a perfect square then print N and steps as 0." }, { "code": null, "e": 1009, "s": 930, "text": "Else, find the first perfect square number > N and note its difference with N." }, { "code": null, "e": 1088, "s": 1009, "text": "Then, find the first perfect square number < N and note its difference with N." }, { "code": null, "e": 1222, "s": 1088, "text": "And print the perfect square resulting in the minimum of these two differences obtained and also the difference as the minimum steps." }, { "code": null, "e": 1275, "s": 1222, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1279, "s": 1275, "text": "C++" }, { "code": null, "e": 1284, "s": 1279, "text": "Java" }, { "code": null, "e": 1292, "s": 1284, "text": "Python3" }, { "code": null, "e": 1295, "s": 1292, "text": "C#" }, { "code": null, "e": 1299, "s": 1295, "text": "PHP" }, { "code": null, "e": 1310, "s": 1299, "text": "Javascript" }, { "code": "// CPP program to find the closest perfect square// taking minimum steps to reach from a number #include <bits/stdc++.h>using namespace std; // Function to check if a number is// perfect square or notbool isPerfect(int N){ if ((sqrt(N) - floor(sqrt(N))) != 0) return false; return true;} // Function to find the closest perfect square// taking minimum steps to reach from a numbervoid getClosestPerfectSquare(int N){ if (isPerfect(N)) { cout << N << \" \" << \"0\" << endl; return; } // Variables to store first perfect // square number // above and below N int aboveN = -1, belowN = -1; int n1; // Finding first perfect square // number greater than N n1 = N + 1; while (true) { if (isPerfect(n1)) { aboveN = n1; break; } else n1++; } // Finding first perfect square // number less than N n1 = N - 1; while (true) { if (isPerfect(n1)) { belowN = n1; break; } else n1--; } // Variables to store the differences int diff1 = aboveN - N; int diff2 = N - belowN; if (diff1 > diff2) cout << belowN << \" \" << diff2; else cout << aboveN << \" \" << diff1;} // Driver codeint main(){ int N = 1500; getClosestPerfectSquare(N);}// This code is contributed by// Surendra_Gangwar", "e": 2711, "s": 1310, "text": null }, { "code": "// Java program to find the closest perfect square// taking minimum steps to reach from a number class GFG { // Function to check if a number is // perfect square or not static boolean isPerfect(int N) { if ((Math.sqrt(N) - Math.floor(Math.sqrt(N))) != 0) return false; return true; } // Function to find the closest perfect square // taking minimum steps to reach from a number static void getClosestPerfectSquare(int N) { if (isPerfect(N)) { System.out.println(N + \" \" + \"0\"); return; } // Variables to store first perfect // square number // above and below N int aboveN = -1, belowN = -1; int n1; // Finding first perfect square // number greater than N n1 = N + 1; while (true) { if (isPerfect(n1)) { aboveN = n1; break; } else n1++; } // Finding first perfect square // number less than N n1 = N - 1; while (true) { if (isPerfect(n1)) { belowN = n1; break; } else n1--; } // Variables to store the differences int diff1 = aboveN - N; int diff2 = N - belowN; if (diff1 > diff2) System.out.println(belowN + \" \" + diff2); else System.out.println(aboveN + \" \" + diff1); } // Driver code public static void main(String args[]) { int N = 1500; getClosestPerfectSquare(N); }}", "e": 4360, "s": 2711, "text": null }, { "code": "# Python3 program to find the closest# perfect square taking minimum steps# to reach from a number # Function to check if a number is# perfect square or notfrom math import sqrt, floor def isPerfect(N): if (sqrt(N) - floor(sqrt(N)) != 0): return False return True # Function to find the closest perfect square# taking minimum steps to reach from a number def getClosestPerfectSquare(N): if (isPerfect(N)): print(N, \"0\") return # Variables to store first perfect # square number above and below N aboveN = -1 belowN = -1 n1 = 0 # Finding first perfect square # number greater than N n1 = N + 1 while (True): if (isPerfect(n1)): aboveN = n1 break else: n1 += 1 # Finding first perfect square # number less than N n1 = N - 1 while (True): if (isPerfect(n1)): belowN = n1 break else: n1 -= 1 # Variables to store the differences diff1 = aboveN - N diff2 = N - belowN if (diff1 > diff2): print(belowN, diff2) else: print(aboveN, diff1) # Driver codeN = 1500getClosestPerfectSquare(N) # This code is contributed# by sahishelangia", "e": 5584, "s": 4360, "text": null }, { "code": "// C# program to find the closest perfect square// taking minimum steps to reach from a numberusing System; class GFG { // Function to check if a number is // perfect square or not static bool isPerfect(int N) { if ((Math.Sqrt(N) - Math.Floor(Math.Sqrt(N))) != 0) return false; return true; } // Function to find the closest perfect square // taking minimum steps to reach from a number static void getClosestPerfectSquare(int N) { if (isPerfect(N)) { Console.WriteLine(N + \" \" + \"0\"); return; } // Variables to store first perfect // square number // above and below N int aboveN = -1, belowN = -1; int n1; // Finding first perfect square // number greater than N n1 = N + 1; while (true) { if (isPerfect(n1)) { aboveN = n1; break; } else n1++; } // Finding first perfect square // number less than N n1 = N - 1; while (true) { if (isPerfect(n1)) { belowN = n1; break; } else n1--; } // Variables to store the differences int diff1 = aboveN - N; int diff2 = N - belowN; if (diff1 > diff2) Console.WriteLine(belowN + \" \" + diff2); else Console.WriteLine(aboveN + \" \" + diff1); } // Driver code public static void Main() { int N = 1500; getClosestPerfectSquare(N); }}// This code is contributed by anuj_67..", "e": 7264, "s": 5584, "text": null }, { "code": "<?php// PHP program to find the closest perfect// square taking minimum steps to reach// from a number // Function to check if a number is// perfect square or notfunction isPerfect($N){ if ((sqrt($N) - floor(sqrt($N))) != 0) return false; return true;} // Function to find the closest perfect square// taking minimum steps to reach from a numberfunction getClosestPerfectSquare($N){ if (isPerfect($N)) { echo $N, \" \", \"0\", \"\\n\"; return; } // Variables to store first perfect // square number // above and below N $aboveN = -1; $belowN = -1; $n1; // Finding first perfect square // number greater than N $n1 = $N + 1; while (true) { if (isPerfect($n1)) { $aboveN = $n1; break; } else $n1++; } // Finding first perfect square // number less than N $n1 = $N - 1; while (true) { if (isPerfect($n1)) { $belowN = $n1; break; } else $n1--; } // Variables to store the differences $diff1 = $aboveN - $N; $diff2 = $N - $belowN; if ($diff1 > $diff2) echo $belowN, \" \" , $diff2; else echo $aboveN, \" \", $diff1;} // Driver code$N = 1500;getClosestPerfectSquare($N); // This code is contributed by ajit.?>", "e": 8603, "s": 7264, "text": null }, { "code": "<script> // Javascript program to find // the closest perfect square // taking minimum steps to reach // from a number // Function to check if a number is // perfect square or not function isPerfect(N) { if ((Math.sqrt(N) - Math.floor(Math.sqrt(N))) != 0) return false; return true; } // Function to find the closest perfect square // taking minimum steps to reach from a number function getClosestPerfectSquare(N) { if (isPerfect(N)) { document.write(N + \" \" + \"0\" + \"</br>\"); return; } // Variables to store first perfect // square number // above and below N let aboveN = -1, belowN = -1; let n1; // Finding first perfect square // number greater than N n1 = N + 1; while (true) { if (isPerfect(n1)) { aboveN = n1; break; } else n1++; } // Finding first perfect square // number less than N n1 = N - 1; while (true) { if (isPerfect(n1)) { belowN = n1; break; } else n1--; } // Variables to store the differences let diff1 = aboveN - N; let diff2 = N - belowN; if (diff1 > diff2) document.write(belowN + \" \" + diff2); else document.write(aboveN + \" \" + diff1); } let N = 1500; getClosestPerfectSquare(N); </script>", "e": 10192, "s": 8603, "text": null }, { "code": null, "e": 10200, "s": 10192, "text": "1521 21" }, { "code": null, "e": 10327, "s": 10200, "text": "Time Complexity: O(n), where n is the given number since we are using brute force to find the above and below perfect squares." }, { "code": null, "e": 10388, "s": 10327, "text": "Space Complexity: O(1), since no extra space has been taken." }, { "code": null, "e": 10402, "s": 10388, "text": "Approach 2: " }, { "code": null, "e": 10533, "s": 10402, "text": "The above method might take a lot of time for bigger numbers i.e. greater than 106. We would wish to have a faster way to do that." }, { "code": null, "e": 10613, "s": 10533, "text": "Here, we will use maths to solve the above problem in constant time complexity." }, { "code": null, "e": 10666, "s": 10613, "text": "We will first find the square root of the number n. " }, { "code": null, "e": 10753, "s": 10666, "text": "We will check if n was a perfect square, and if it was, we will return 0 there itself." }, { "code": null, "e": 10897, "s": 10753, "text": "Else, we will use its square root to find the just above and below perfect square numbers, and return the one which is at the minimum distance." }, { "code": null, "e": 10949, "s": 10897, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 10953, "s": 10949, "text": "C++" }, { "code": null, "e": 10958, "s": 10953, "text": "Java" }, { "code": null, "e": 10966, "s": 10958, "text": "Python3" }, { "code": "// CPP program to find the closest perfect square// taking minimum steps to reach from a number #include <bits/stdc++.h>using namespace std; // Function to find the closest perfect square// taking minimum steps to reach from a numbervoid getClosestPerfectSquare(int N){ int x = sqrt(N); //Checking if N is a perfect square if((x*x)==N){ cout<<N<<\" \"<<0; return; } // If N is not a perfect square, // squaring x and x+1 gives us the // just below and above perfect squares // Variables to store perfect // square number just // above and below N int aboveN = (x+1)*(x+1), belowN = x*x; // Variables to store the differences int diff1 = aboveN - N; int diff2 = N - belowN; if (diff1 > diff2) cout << belowN << \" \" << diff2; else cout << aboveN << \" \" << diff1;} // Driver codeint main(){ int N = 1500; getClosestPerfectSquare(N);}// This code is contributed by// Rohit Kumar", "e": 11910, "s": 10966, "text": null }, { "code": "// Java program for the above approach public class GFG {// Function to find the closest perfect square// taking minimum steps to reach from a numberstatic void getClosestPerfectSquare(int N){ int x = (int)Math.sqrt(N); //Checking if N is a perfect square if((x*x)==N){ System.out.println(N); return; } // If N is not a perfect square, // squaring x and x+1 gives us the // just below and above perfect squares // Variables to store perfect // square number just // above and below N int aboveN = (x+1)*(x+1), belowN = x*x; // Variables to store the differences int diff1 = aboveN - N; int diff2 = N - belowN; if (diff1 > diff2) System.out.println(belowN+\" \"+diff2); else System.out.println(aboveN+\" \"+diff1); } // Driver Code public static void main (String[] args) { int N = 1500; getClosestPerfectSquare(N); }} // This code is contributed by aditya942003patil", "e": 12912, "s": 11910, "text": null }, { "code": "# Python3 program to find the closest# perfect square taking minimum steps# to reach from a number from math import sqrt, floor # Function to find the closest perfect square# taking minimum steps to reach from a number def getClosestPerfectSquare(N): x = floor(sqrt(N)) # Checking if N is itself a perfect square if (sqrt(N) - floor(sqrt(N)) == 0): print(N,0) return # Variables to store first perfect # square number above and below N aboveN = (x+1)*(x+1) belowN = x*x # Variables to store the differences diff1 = aboveN - N diff2 = N - belowN if (diff1 > diff2): print(belowN, diff2) else: print(aboveN, diff1) # Driver codeN = 1500getClosestPerfectSquare(N) # This code is contributed# by Rohit Kumar", "e": 13690, "s": 12912, "text": null }, { "code": null, "e": 13698, "s": 13690, "text": "1521 21" }, { "code": null, "e": 13757, "s": 13698, "text": "Time Complexity: O(1), since we have used only maths here." }, { "code": null, "e": 13818, "s": 13757, "text": "Space Complexity: O(1), since no extra space has been taken." }, { "code": null, "e": 13823, "s": 13818, "text": "vt_m" }, { "code": null, "e": 13840, "s": 13823, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 13846, "s": 13840, "text": "jit_t" }, { "code": null, "e": 13861, "s": 13846, "text": "sahilshelangia" }, { "code": null, "e": 13876, "s": 13861, "text": "rameshtravel07" }, { "code": null, "e": 13891, "s": 13876, "text": "sagar0719kumar" }, { "code": null, "e": 13909, "s": 13891, "text": "rohitmishra051000" }, { "code": null, "e": 13925, "s": 13909, "text": "souravmahato348" }, { "code": null, "e": 13943, "s": 13925, "text": "aditya942003patil" }, { "code": null, "e": 13964, "s": 13943, "text": "maths-perfect-square" }, { "code": null, "e": 13978, "s": 13964, "text": "Java Programs" }, { "code": null, "e": 13991, "s": 13978, "text": "Mathematical" }, { "code": null, "e": 14010, "s": 13991, "text": "Technical Scripter" }, { "code": null, "e": 14023, "s": 14010, "text": "Mathematical" } ]
Hierarchical Clustering in R Programming
03 Dec, 2021 Hierarchical clustering in R Programming Language is an Unsupervised non-linear algorithm in which clusters are created such that they have a hierarchy(or a pre-determined ordering). For example, consider a family of up to three generations. A grandfather and mother have their children that become father and mother of their children. So, they all are grouped together to the same family i.e they form a hierarchy. Hierarchical clustering is of two types: Agglomerative Hierarchical clustering: It starts at individual leaves and successfully merges clusters together. Its a Bottom-up approach. Divisive Hierarchical clustering: It starts at the root and recursively split the clusters. It’s a top-down approach. In hierarchical clustering, Objects are categorized into a hierarchy similar to a tree-shaped structure which is used to interpret hierarchical clustering models. The algorithm is as follows: Make each data point in a single point cluster that forms N clusters.Take the two closest data points and make them one cluster that forms N-1 clusters.Take the two closest clusters and make them one cluster that forms N-2 clusters.Repeat steps 3 until there is only one cluster. Make each data point in a single point cluster that forms N clusters. Take the two closest data points and make them one cluster that forms N-1 clusters. Take the two closest clusters and make them one cluster that forms N-2 clusters. Repeat steps 3 until there is only one cluster. Dendrogram is a hierarchy of clusters in which distances are converted into heights. It clusters n units or objects each with p feature into smaller groups. Units in the same cluster are joined by a horizontal line. The leaves at the bottom represent individual units. It provides a visual representation of clusters.Thumb Rule: Largest vertical distance which doesn’t cut any horizontal line defines the optimal number of clusters. mtcars(motor trend car road test) comprise fuel consumption, performance, and 10 aspects of automobile design for 32 automobiles. It comes pre-installed with dplyr package in R. R # Installing the packageinstall.packages("dplyr") # Loading packagelibrary(dplyr) # Summary of dataset in packagehead(mtcars) Output: Using Hierarchical Clustering algorithm on the dataset using hclust() which is pre-installed in stats package when R is installed. R # Finding distance matrixdistance_mat <- dist(mtcars, method = 'euclidean')distance_mat # Fitting Hierarchical clustering Model# to training datasetset.seed(240) # Setting seedHierar_cl <- hclust(distance_mat, method = "average")Hierar_cl # Plotting dendrogramplot(Hierar_cl) # Choosing no. of clusters# Cutting tree by heightabline(h = 110, col = "green") # Cutting tree by no. of clustersfit <- cutree(Hierar_cl, k = 3 )fit table(fit)rect.hclust(Hierar_cl, k = 3, border = "green") Output: Distance matrix: The values are shown as per the distance matrix calculation with the method as euclidean. Model Hierar_cl: In the model, the cluster method is average, distance is euclidean and no. of objects are 32. Plot dendrogram: The plot dendrogram is shown with x-axis as distance matrix and y-axis as height. Cutted tree: So, Tree is cut where k = 3 and each category represents its number of clusters. Plotting dendrogram after cutting: The plot denotes dendrogram after being cut. The green lines show the number of clusters as per the thumb rule. prdpsrvn sumitgumber28 kumar_satyam R Machine-Learning Machine Learning R Language Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Naive Bayes Classifiers ML | Linear Regression Linear Regression (Python Implementation) Decision Tree Reinforcement learning Change column name of a given DataFrame in R Filter data by multiple conditions in R using Dplyr How to Replace specific values in column in R DataFrame ? Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame?
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Dec, 2021" }, { "code": null, "e": 444, "s": 28, "text": "Hierarchical clustering in R Programming Language is an Unsupervised non-linear algorithm in which clusters are created such that they have a hierarchy(or a pre-determined ordering). For example, consider a family of up to three generations. A grandfather and mother have their children that become father and mother of their children. So, they all are grouped together to the same family i.e they form a hierarchy." }, { "code": null, "e": 486, "s": 444, "text": "Hierarchical clustering is of two types: " }, { "code": null, "e": 625, "s": 486, "text": "Agglomerative Hierarchical clustering: It starts at individual leaves and successfully merges clusters together. Its a Bottom-up approach." }, { "code": null, "e": 743, "s": 625, "text": "Divisive Hierarchical clustering: It starts at the root and recursively split the clusters. It’s a top-down approach." }, { "code": null, "e": 937, "s": 743, "text": "In hierarchical clustering, Objects are categorized into a hierarchy similar to a tree-shaped structure which is used to interpret hierarchical clustering models. The algorithm is as follows: " }, { "code": null, "e": 1217, "s": 937, "text": "Make each data point in a single point cluster that forms N clusters.Take the two closest data points and make them one cluster that forms N-1 clusters.Take the two closest clusters and make them one cluster that forms N-2 clusters.Repeat steps 3 until there is only one cluster." }, { "code": null, "e": 1287, "s": 1217, "text": "Make each data point in a single point cluster that forms N clusters." }, { "code": null, "e": 1371, "s": 1287, "text": "Take the two closest data points and make them one cluster that forms N-1 clusters." }, { "code": null, "e": 1452, "s": 1371, "text": "Take the two closest clusters and make them one cluster that forms N-2 clusters." }, { "code": null, "e": 1500, "s": 1452, "text": "Repeat steps 3 until there is only one cluster." }, { "code": null, "e": 1933, "s": 1500, "text": "Dendrogram is a hierarchy of clusters in which distances are converted into heights. It clusters n units or objects each with p feature into smaller groups. Units in the same cluster are joined by a horizontal line. The leaves at the bottom represent individual units. It provides a visual representation of clusters.Thumb Rule: Largest vertical distance which doesn’t cut any horizontal line defines the optimal number of clusters." }, { "code": null, "e": 2112, "s": 1933, "text": "mtcars(motor trend car road test) comprise fuel consumption, performance, and 10 aspects of automobile design for 32 automobiles. It comes pre-installed with dplyr package in R. " }, { "code": null, "e": 2114, "s": 2112, "text": "R" }, { "code": "# Installing the packageinstall.packages(\"dplyr\") # Loading packagelibrary(dplyr) # Summary of dataset in packagehead(mtcars)", "e": 2244, "s": 2114, "text": null }, { "code": null, "e": 2252, "s": 2244, "text": "Output:" }, { "code": null, "e": 2383, "s": 2252, "text": "Using Hierarchical Clustering algorithm on the dataset using hclust() which is pre-installed in stats package when R is installed." }, { "code": null, "e": 2385, "s": 2383, "text": "R" }, { "code": "# Finding distance matrixdistance_mat <- dist(mtcars, method = 'euclidean')distance_mat # Fitting Hierarchical clustering Model# to training datasetset.seed(240) # Setting seedHierar_cl <- hclust(distance_mat, method = \"average\")Hierar_cl # Plotting dendrogramplot(Hierar_cl) # Choosing no. of clusters# Cutting tree by heightabline(h = 110, col = \"green\") # Cutting tree by no. of clustersfit <- cutree(Hierar_cl, k = 3 )fit table(fit)rect.hclust(Hierar_cl, k = 3, border = \"green\")", "e": 2870, "s": 2385, "text": null }, { "code": null, "e": 2878, "s": 2870, "text": "Output:" }, { "code": null, "e": 2895, "s": 2878, "text": "Distance matrix:" }, { "code": null, "e": 2985, "s": 2895, "text": "The values are shown as per the distance matrix calculation with the method as euclidean." }, { "code": null, "e": 3002, "s": 2985, "text": "Model Hierar_cl:" }, { "code": null, "e": 3096, "s": 3002, "text": "In the model, the cluster method is average, distance is euclidean and no. of objects are 32." }, { "code": null, "e": 3113, "s": 3096, "text": "Plot dendrogram:" }, { "code": null, "e": 3195, "s": 3113, "text": "The plot dendrogram is shown with x-axis as distance matrix and y-axis as height." }, { "code": null, "e": 3208, "s": 3195, "text": "Cutted tree:" }, { "code": null, "e": 3289, "s": 3208, "text": "So, Tree is cut where k = 3 and each category represents its number of clusters." }, { "code": null, "e": 3324, "s": 3289, "text": "Plotting dendrogram after cutting:" }, { "code": null, "e": 3436, "s": 3324, "text": "The plot denotes dendrogram after being cut. The green lines show the number of clusters as per the thumb rule." }, { "code": null, "e": 3445, "s": 3436, "text": "prdpsrvn" }, { "code": null, "e": 3459, "s": 3445, "text": "sumitgumber28" }, { "code": null, "e": 3472, "s": 3459, "text": "kumar_satyam" }, { "code": null, "e": 3491, "s": 3472, "text": "R Machine-Learning" }, { "code": null, "e": 3508, "s": 3491, "text": "Machine Learning" }, { "code": null, "e": 3519, "s": 3508, "text": "R Language" }, { "code": null, "e": 3536, "s": 3519, "text": "Machine Learning" }, { "code": null, "e": 3634, "s": 3536, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3658, "s": 3634, "text": "Naive Bayes Classifiers" }, { "code": null, "e": 3681, "s": 3658, "text": "ML | Linear Regression" }, { "code": null, "e": 3723, "s": 3681, "text": "Linear Regression (Python Implementation)" }, { "code": null, "e": 3737, "s": 3723, "text": "Decision Tree" }, { "code": null, "e": 3760, "s": 3737, "text": "Reinforcement learning" }, { "code": null, "e": 3805, "s": 3760, "text": "Change column name of a given DataFrame in R" }, { "code": null, "e": 3857, "s": 3805, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 3915, "s": 3857, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 3967, "s": 3915, "text": "Change Color of Bars in Barchart using ggplot2 in R" } ]
unordered_set size() function in C++ STL
28 Jun, 2022 The unordered_set::size() method is a builtin function in C++ STL which is used to return the number of elements in the unordered_set container. Syntax: unordered_set_name.size() Parameter: It does not accepts any parameter. Return Value: The function returns the number of elements in the container. Below programs illustrate the unordered_set::size() function: Program 1: CPP // C++ program to illustrate the// unordered_set.size() function#include <iostream>#include <unordered_set> using namespace std; int main(){ unordered_set<int> arr1 = { 1, 2, 3, 4, 5 }; // prints the size of arr1 cout << "size of arr1:" << arr1.size(); // prints the element cout << "\nThe elements are: "; for (auto it = arr1.begin(); it != arr1.end(); it++) cout << *it << " "; return 0;} size of arr1:5 The elements are: 5 1 2 3 4 Program 2: CPP // C++ program to illustrate the// unordered_set::size() function// when container is empty#include <iostream>#include <unordered_set> using namespace std; int main(){ unordered_set<int> arr2 = {}; // prints the size cout << "Size of arr2 : " << arr2.size(); return 0;} Size of arr2 : 0 Time complexity: O(1) utkarshgupta110092 CPP-Functions cpp-unordered_set cpp-unordered_set-functions C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bitwise Operators in C/C++ Priority Queue in C++ Standard Template Library (STL) vector erase() and clear() in C++ Substring in C++ Object Oriented Programming in C++ Inheritance in C++ The C++ Standard Template Library (STL) C++ Classes and Objects Sorting a vector in C++ 2D Vector In C++ With User Defined Size
[ { "code": null, "e": 53, "s": 25, "text": "\n28 Jun, 2022" }, { "code": null, "e": 206, "s": 53, "text": "The unordered_set::size() method is a builtin function in C++ STL which is used to return the number of elements in the unordered_set container. Syntax:" }, { "code": null, "e": 232, "s": 206, "text": "unordered_set_name.size()" }, { "code": null, "e": 428, "s": 232, "text": "Parameter: It does not accepts any parameter. Return Value: The function returns the number of elements in the container. Below programs illustrate the unordered_set::size() function: Program 1: " }, { "code": null, "e": 432, "s": 428, "text": "CPP" }, { "code": "// C++ program to illustrate the// unordered_set.size() function#include <iostream>#include <unordered_set> using namespace std; int main(){ unordered_set<int> arr1 = { 1, 2, 3, 4, 5 }; // prints the size of arr1 cout << \"size of arr1:\" << arr1.size(); // prints the element cout << \"\\nThe elements are: \"; for (auto it = arr1.begin(); it != arr1.end(); it++) cout << *it << \" \"; return 0;}", "e": 855, "s": 432, "text": null }, { "code": null, "e": 898, "s": 855, "text": "size of arr1:5\nThe elements are: 5 1 2 3 4" }, { "code": null, "e": 910, "s": 898, "text": "Program 2: " }, { "code": null, "e": 914, "s": 910, "text": "CPP" }, { "code": "// C++ program to illustrate the// unordered_set::size() function// when container is empty#include <iostream>#include <unordered_set> using namespace std; int main(){ unordered_set<int> arr2 = {}; // prints the size cout << \"Size of arr2 : \" << arr2.size(); return 0;}", "e": 1199, "s": 914, "text": null }, { "code": null, "e": 1216, "s": 1199, "text": "Size of arr2 : 0" }, { "code": null, "e": 1238, "s": 1216, "text": "Time complexity: O(1)" }, { "code": null, "e": 1257, "s": 1238, "text": "utkarshgupta110092" }, { "code": null, "e": 1271, "s": 1257, "text": "CPP-Functions" }, { "code": null, "e": 1289, "s": 1271, "text": "cpp-unordered_set" }, { "code": null, "e": 1317, "s": 1289, "text": "cpp-unordered_set-functions" }, { "code": null, "e": 1321, "s": 1317, "text": "C++" }, { "code": null, "e": 1325, "s": 1321, "text": "CPP" }, { "code": null, "e": 1423, "s": 1325, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1450, "s": 1423, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 1504, "s": 1450, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 1538, "s": 1504, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 1555, "s": 1538, "text": "Substring in C++" }, { "code": null, "e": 1590, "s": 1555, "text": "Object Oriented Programming in C++" }, { "code": null, "e": 1609, "s": 1590, "text": "Inheritance in C++" }, { "code": null, "e": 1649, "s": 1609, "text": "The C++ Standard Template Library (STL)" }, { "code": null, "e": 1673, "s": 1649, "text": "C++ Classes and Objects" }, { "code": null, "e": 1697, "s": 1673, "text": "Sorting a vector in C++" } ]
Custom Snackbars in Android
23 Feb, 2021 SnackBars plays a very important role in the user experience. The snack bar which may or may not contain the action button to do shows the message which had happened due to the user interaction immediately. So in this article, it’s been discussed how the SnackBars can be implemented using custom layouts. Have a look at the following image to get an idea of how can the custom-made SnackBars can be differentiated from the regular(normal) SnackBars. Note that we are going to implement this project using the Java language. Step 1: Create an empty activity project Create an empty activity Android Studio project. And select the JAVA as a programming language. Refer to Android | How to Create/Start a New Project in Android Studio? to know how to create an empty activity Android studio project. Step 2: Working with the activity_main.xml file The main layout here includes only one button which when clicked the custom SnackBar is to be shown. Invoke the following code, in 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" tools:ignore="HardcodedText"> <Button android:id="@+id/showSnackbarButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:backgroundTint="@color/colorPrimary" android:text="SHOW SNACKBAR" android:textColor="@android:color/white" /> </RelativeLayout> Step 3: Creating a custom layout for Snackbar Under layout folder create a layout for SnackBar which needs to be inflated when building the SnackBar under the MainActivity.java 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:ignore="HardcodedText"> <androidx.cardview.widget.CardView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="8dp" android:elevation="4dp" app:cardBackgroundColor="@color/colorPrimaryDark" app:cardCornerRadius="4dp" app:cardPreventCornerOverlap="true" app:cardUseCompatPadding="true"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:padding="8dp"> <ImageView android:id="@+id/imageView" android:layout_width="45dp" android:layout_height="45dp" android:layout_alignParentStart="true" android:src="@drawable/image_logo" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="4dp" android:layout_toEndOf="@id/imageView" android:text="GeeksforGeeks" android:textAlignment="center" android:textColor="@android:color/white" android:textSize="18sp" android:textStyle="bold" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/textView1" android:layout_marginStart="4dp" android:layout_toEndOf="@id/imageView" android:text="Computer Science Portal" android:textColor="@android:color/white" android:textSize="14sp" /> <!--this view separates between button and the message--> <View android:layout_width="2dp" android:layout_height="45dp" android:layout_toStartOf="@id/gotoWebsiteButton" android:background="@android:color/white" /> <Button android:id="@+id/gotoWebsiteButton" style="@style/Widget.MaterialComponents.Button.TextButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:text="GOTO WEBSITE" android:textColor="@android:color/white" android:textSize="14sp" /> </RelativeLayout> </androidx.cardview.widget.CardView></RelativeLayout> Which produces the following view: Step 4: Working with the MainActivity.java file Java import androidx.appcompat.app.AppCompatActivity;import android.graphics.Color;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast;import com.google.android.material.snackbar.Snackbar; public class MainActivity extends AppCompatActivity { Button bShowSnackbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // register the button with appropriate ID bShowSnackbar = findViewById(R.id.showSnackbarButton); bShowSnackbar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // create an instance of the snackbar final Snackbar snackbar = Snackbar.make(v, "", Snackbar.LENGTH_LONG); // inflate the custom_snackbar_view created previously View customSnackView = getLayoutInflater().inflate(R.layout.custom_snackbar_view, null); // set the background of the default snackbar as transparent snackbar.getView().setBackgroundColor(Color.TRANSPARENT); // now change the layout of the snackbar Snackbar.SnackbarLayout snackbarLayout = (Snackbar.SnackbarLayout) snackbar.getView(); // set padding of the all corners as 0 snackbarLayout.setPadding(0, 0, 0, 0); // register the button from the custom_snackbar_view layout file Button bGotoWebsite = customSnackView.findViewById(R.id.gotoWebsiteButton); // now handle the same button with onClickListener bGotoWebsite.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(), "Redirecting to Website", Toast.LENGTH_SHORT).show(); snackbar.dismiss(); } }); // add the custom snack bar layout to snackbar layout snackbarLayout.addView(customSnackView, 0); snackbar.show(); } }); }} Android-Bars Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android RecyclerView in Kotlin Broadcast Receiver in Android With Example Android SDK and it's Components Flutter - Custom Bottom Navigation Bar Arrays.sort() in Java with examples Reverse a string in Java Object Oriented Programming (OOPs) Concept in Java For-each loop in Java How to iterate any Map in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Feb, 2021" }, { "code": null, "e": 580, "s": 54, "text": "SnackBars plays a very important role in the user experience. The snack bar which may or may not contain the action button to do shows the message which had happened due to the user interaction immediately. So in this article, it’s been discussed how the SnackBars can be implemented using custom layouts. Have a look at the following image to get an idea of how can the custom-made SnackBars can be differentiated from the regular(normal) SnackBars. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 621, "s": 580, "text": "Step 1: Create an empty activity project" }, { "code": null, "e": 717, "s": 621, "text": "Create an empty activity Android Studio project. And select the JAVA as a programming language." }, { "code": null, "e": 853, "s": 717, "text": "Refer to Android | How to Create/Start a New Project in Android Studio? to know how to create an empty activity Android studio project." }, { "code": null, "e": 901, "s": 853, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 1002, "s": 901, "text": "The main layout here includes only one button which when clicked the custom SnackBar is to be shown." }, { "code": null, "e": 1060, "s": 1002, "text": "Invoke the following code, in the activity_main.xml file." }, { "code": null, "e": 1064, "s": 1060, "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\" tools:ignore=\"HardcodedText\"> <Button android:id=\"@+id/showSnackbarButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:backgroundTint=\"@color/colorPrimary\" android:text=\"SHOW SNACKBAR\" android:textColor=\"@android:color/white\" /> </RelativeLayout>", "e": 1722, "s": 1064, "text": null }, { "code": null, "e": 1768, "s": 1722, "text": "Step 3: Creating a custom layout for Snackbar" }, { "code": null, "e": 1905, "s": 1768, "text": "Under layout folder create a layout for SnackBar which needs to be inflated when building the SnackBar under the MainActivity.java file." }, { "code": null, "e": 1909, "s": 1905, "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:ignore=\"HardcodedText\"> <androidx.cardview.widget.CardView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"8dp\" android:elevation=\"4dp\" app:cardBackgroundColor=\"@color/colorPrimaryDark\" app:cardCornerRadius=\"4dp\" app:cardPreventCornerOverlap=\"true\" app:cardUseCompatPadding=\"true\"> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:padding=\"8dp\"> <ImageView android:id=\"@+id/imageView\" android:layout_width=\"45dp\" android:layout_height=\"45dp\" android:layout_alignParentStart=\"true\" android:src=\"@drawable/image_logo\" /> <TextView android:id=\"@+id/textView1\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"4dp\" android:layout_toEndOf=\"@id/imageView\" android:text=\"GeeksforGeeks\" android:textAlignment=\"center\" android:textColor=\"@android:color/white\" android:textSize=\"18sp\" android:textStyle=\"bold\" /> <TextView android:id=\"@+id/textView2\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/textView1\" android:layout_marginStart=\"4dp\" android:layout_toEndOf=\"@id/imageView\" android:text=\"Computer Science Portal\" android:textColor=\"@android:color/white\" android:textSize=\"14sp\" /> <!--this view separates between button and the message--> <View android:layout_width=\"2dp\" android:layout_height=\"45dp\" android:layout_toStartOf=\"@id/gotoWebsiteButton\" android:background=\"@android:color/white\" /> <Button android:id=\"@+id/gotoWebsiteButton\" style=\"@style/Widget.MaterialComponents.Button.TextButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentEnd=\"true\" android:text=\"GOTO WEBSITE\" android:textColor=\"@android:color/white\" android:textSize=\"14sp\" /> </RelativeLayout> </androidx.cardview.widget.CardView></RelativeLayout>", "e": 4825, "s": 1909, "text": null }, { "code": null, "e": 4860, "s": 4825, "text": "Which produces the following view:" }, { "code": null, "e": 4908, "s": 4860, "text": "Step 4: Working with the MainActivity.java file" }, { "code": null, "e": 4913, "s": 4908, "text": "Java" }, { "code": "import androidx.appcompat.app.AppCompatActivity;import android.graphics.Color;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast;import com.google.android.material.snackbar.Snackbar; public class MainActivity extends AppCompatActivity { Button bShowSnackbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // register the button with appropriate ID bShowSnackbar = findViewById(R.id.showSnackbarButton); bShowSnackbar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // create an instance of the snackbar final Snackbar snackbar = Snackbar.make(v, \"\", Snackbar.LENGTH_LONG); // inflate the custom_snackbar_view created previously View customSnackView = getLayoutInflater().inflate(R.layout.custom_snackbar_view, null); // set the background of the default snackbar as transparent snackbar.getView().setBackgroundColor(Color.TRANSPARENT); // now change the layout of the snackbar Snackbar.SnackbarLayout snackbarLayout = (Snackbar.SnackbarLayout) snackbar.getView(); // set padding of the all corners as 0 snackbarLayout.setPadding(0, 0, 0, 0); // register the button from the custom_snackbar_view layout file Button bGotoWebsite = customSnackView.findViewById(R.id.gotoWebsiteButton); // now handle the same button with onClickListener bGotoWebsite.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(), \"Redirecting to Website\", Toast.LENGTH_SHORT).show(); snackbar.dismiss(); } }); // add the custom snack bar layout to snackbar layout snackbarLayout.addView(customSnackView, 0); snackbar.show(); } }); }}", "e": 7184, "s": 4913, "text": null }, { "code": null, "e": 7197, "s": 7184, "text": "Android-Bars" }, { "code": null, "e": 7221, "s": 7197, "text": "Technical Scripter 2020" }, { "code": null, "e": 7229, "s": 7221, "text": "Android" }, { "code": null, "e": 7234, "s": 7229, "text": "Java" }, { "code": null, "e": 7253, "s": 7234, "text": "Technical Scripter" }, { "code": null, "e": 7258, "s": 7253, "text": "Java" }, { "code": null, "e": 7266, "s": 7258, "text": "Android" }, { "code": null, "e": 7364, "s": 7266, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7433, "s": 7364, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 7464, "s": 7433, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 7507, "s": 7464, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 7539, "s": 7507, "text": "Android SDK and it's Components" }, { "code": null, "e": 7578, "s": 7539, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 7614, "s": 7578, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 7639, "s": 7614, "text": "Reverse a string in Java" }, { "code": null, "e": 7690, "s": 7639, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 7712, "s": 7690, "text": "For-each loop in Java" } ]
patch - Unix, Linux Command
but usually just patch -pnum <patchfile Upon startup, patch attempts to determine the type of the diff listing, unless overruled by a -c (--context), -e (--ed), -n (--normal), or -u (--unified) option. Context diffs (old-style, new-style, and unified) and normal diffs are applied by the patch program itself, while ed diffs are simply fed to the ed(1) editor via a pipe. patch tries to skip any leading garbage, apply the diff, and then skip any trailing garbage. Thus you could feed an article or message containing a diff listing to patch, and it should work. If the entire diff is indented by a consistent amount, or if a context diff contains lines ending in CRLF or is encapsulated one or more times by prepending "- " to lines starting with "-" as specified by Internet RFC 934, this is taken into account. With context diffs, and to a lesser extent with normal diffs, patch can detect when the line numbers mentioned in the patch are incorrect, and attempts to find the correct place to apply each hunk of the patch. As a first guess, it takes the line number mentioned for the hunk, plus or minus any offset used in applying the previous hunk. If that is not the correct place, patch scans both forwards and backwards for a set of lines matching the context given in the hunk. First patch looks for a place where all lines of the context match. If no such place is found, and it’s a context diff, and the maximum fuzz factor is set to 1 or more, then another scan takes place ignoring the first and last line of context. If that fails, and the maximum fuzz factor is set to 2 or more, the first two and last two lines of context are ignored, and another scan is made. (The default maximum fuzz factor is 2.) If patch cannot find a place to install that hunk of the patch, it puts the hunk out to a reject file, which normally is the name of the output file plus a .rej suffix, or # if .rej would generate a file name that is too long (if even appending the single character # makes the file name too long, then # replaces the file name’s last character). (The rejected hunk comes out in ordinary context diff form regardless of the input patch’s form. If the input was a normal diff, many of the contexts are simply null.) The line numbers on the hunks in the reject file may be different than in the patch file: they reflect the approximate location patch thinks the failed hunks belong in the new file rather than the old one. As each hunk is completed, you are told if the hunk failed, and if so which line (in the new file) patch thought the hunk should go on. If the hunk is installed at a different line from the line number specified in the diff you are told the offset. A single large offset may indicate that a hunk was installed in the wrong place. You are also told if a fuzz factor was used to make the match, in which case you should also be slightly suspicious. If the --verbose option is given, you are also told about hunks that match exactly. If no original file origfile is specified on the command line, patch tries to figure out from the leading garbage what the name of the file to edit is, using the following rules. First, patch takes an ordered list of candidate file names as follows: Additionally, if the leading garbage contains a Prereq: line, patch takes the first word from the prerequisites line (normally a version number) and checks the original file to see if that word can be found. If not, patch asks for confirmation before proceeding. The upshot of all this is that you should be able to say, while in a news interface, something like the following: | patch -d /usr/src/local/blurfl and patch a file in the blurfl directory directly from the article containing the patch. If the patch file contains more than one patch, patch tries to apply each of them as if they came from separate patch files. This means, among other things, that it is assumed that the name of the file to patch must be determined for each diff listing, and that the garbage before each diff listing contains interesting things such as file names and revision level, as mentioned previously. /u/howard/src/blurfl/blurfl.c setting -p0 gives the entire file name unmodified, -p1 gives u/howard/src/blurfl/blurfl.c without the leading slash, -p4 gives blurfl/blurfl.c and not specifying -p at all just gives you blurfl.c. Whatever you end up with is looked for either in the current directory, or the directory specified by the -d option. If the first hunk of a patch fails, patch reverses the hunk to see if it can be applied that way. If it can, you are asked if you want to have the -R option set. If it can’t, the patch continues to be applied normally. (Note: this method cannot detect a reversed patch if it is a normal diff and if the first command is an append (i.e. it should have been a delete) since appends always succeed, due to the fact that a null context matches anywhere. Luckily, most patches add or change lines rather than delete them, so most reversed normal diffs begin with a delete, which fails, triggering the heuristic.) The value of method is like the GNU Emacs ‘version-control’ variable; patch also recognizes synonyms that are more descriptive. The valid values for method are (unique abbreviations are accepted): The -Z or --set-utc and -T or --set-time options normally refrain from setting a file’s time if the file’s original time does not match the time given in the patch header, or if its contents do not match the patch exactly. However, if the -f or --force option is given, the file time is set regardless. Due to the limitations of diff output format, these options cannot update the times of files whose contents have not changed. Also, if you use these options, you should remove (e.g. with make clean) all files that depend on the patched files, so that later invocations of make do not get confused by the patched files’ times. diff (1) diff (1) ed (1) ed (1) Create your patch systematically. A good method is the command diff -Naur old new where old and new identify the old and new directories. The names old and new should not contain any slashes. The diff command’s headers should have dates and times in Universal Time using traditional Unix format, so that patch recipients can use the -Z or --set-utc option. Here is an example command, using Bourne shell syntax: LC_ALL=C TZ=UTC0 diff -Naur gcc-2.7 gcc-2.8 Tell your recipients how to apply the patch by telling them which directory to cd to, and which patch options to use. The option string -Np1 is recommended. Test your procedure by pretending to be a recipient and applying your patch to a copy of the original files. You can save people a lot of grief by keeping a patchlevel.h file which is patched to increment the patch level as the first diff in the patch file you send out. If you put a Prereq: line in with the patch, it won’t let them apply patches out of order without some warning. You can create a file by sending out a diff that compares /dev/null or an empty file dated the Epoch (1970-01-01 00:00:00 UTC) to the file you want to create. This only works if the file you want to create doesn’t exist already in the target directory. Conversely, you can remove a file by sending out a context diff that compares the file to be deleted with an empty file dated the Epoch. The file will be removed unless patch is conforming to POSIX and the -E or --remove-empty-files option is not given. An easy way to generate patches that create and remove files is to use GNU diff’s -N or --new-file option. If the recipient is supposed to use the -pN option, do not send output that looks like this: diff -Naur v2.0.29/prog/README prog/README --- v2.0.29/prog/README Mon Mar 10 15:13:12 1997 +++ prog/README Mon Mar 17 14:58:22 1997 because the two file names have different numbers of slashes, and different versions of patch interpret the file names differently. To avoid confusion, send output that looks like this instead: diff -Naur v2.0.29/prog/README v2.0.30/prog/README --- v2.0.29/prog/README Mon Mar 10 15:13:12 1997 +++ v2.0.30/prog/README Mon Mar 17 14:58:22 1997 Avoid sending patches that compare backup file names like README.orig, since this might confuse patch into patching a backup file instead of the real file. Instead, send patches that compare the same base file names in different directories, e.g. old/README and new/README. Take care not to send out reversed patches, since it makes people wonder whether they already applied the patch. Try not to have your patch modify derived files (e.g. the file configure where there is a line configure: configure.in in your makefile), since the recipient should be able to regenerate the derived files anyway. If you must send diffs of derived files, generate the diffs using UTC, have the recipients apply the patch with the -Z or --set-utc option, and have them remove any unpatched files that depend on patched files (e.g. with make clean). While you may be able to get away with putting 582 diff listings into one file, it may be wiser to group related patches into separate files in case something goes haywire. If the --verbose option is given, the message Hmm... indicates that there is unprocessed text in the patch file and that patch is attempting to intuit whether there is a patch in that text and, if so, what kind of patch it is. patch’s exit status is 0 if all hunks are applied successfully, 1 if some hunks cannot be applied, and 2 if there is more serious trouble. When applying a set of patches in a loop it behooves you to check this exit status so you don’t apply a later patch to a partially patched file. patch cannot tell if the line numbers are off in an ed script, and can detect bad line numbers in a normal diff only when it finds a change or deletion. A context diff using fuzz factor 3 may have the same problem. Until a suitable interactive interface is added, you should probably do a context diff in these cases to see if the changes made sense. Of course, compiling without errors is a pretty good indication that the patch worked, but not always. patch usually produces the correct results, even when it has to do a lot of guessing. However, the results are guaranteed to be correct only when the patch is applied to exactly the same version of the file that the patch was generated from. Also, traditional patch simply counted slashes when stripping path prefixes; patch now counts pathname components. That is, a sequence of one or more adjacent slashes now counts as a single slash. For maximum portability, avoid sending patches containing // in file names. Conversely, in POSIX patch, backups are never made, even when there is a mismatch. In GNU patch, this behavior is enabled with the --no-backup-if-mismatch option, or by conforming to POSIX with the --posix option or by setting the POSIXLY_CORRECT environment variable. The -b suffix option of traditional patch is equivalent to the -b -z suffix options of GNU patch. -c -d dir -D define -e -l -n -N -o outfile -pnum -R -r rejectfile patch could be smarter about partial matches, excessively deviant offsets and swapped code, but that would take an extra pass. If code has been duplicated (for instance with #ifdef OLDCODE ... #else ... #endif), patch is incapable of patching both versions, and, if it works at all, will likely patch the wrong one, and tell you that it succeeded to boot. If you apply a patch you’ve already applied, patch thinks it is a reversed patch, and offers to un-apply the patch. This could be construed as a feature. Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be included in translations approved by the copyright holders instead of in the original English.
[ { "code": null, "e": 10731, "s": 10711, "text": "\n\nbut usually just\n" }, { "code": null, "e": 10757, "s": 10731, "text": "\n\npatch -pnum <patchfile " }, { "code": null, "e": 11091, "s": 10757, "text": "\nUpon startup, patch attempts to determine the type of the diff listing,\nunless overruled by a\n-c (--context),\n-e (--ed),\n-n (--normal),\nor\n-u (--unified)\noption.\nContext diffs (old-style, new-style, and unified) and\nnormal diffs are applied by the\npatch program itself, while\ned diffs are simply fed to the\ned(1)\neditor via a pipe.\n" }, { "code": null, "e": 11535, "s": 11091, "text": "\npatch tries to skip any leading garbage, apply the diff,\nand then skip any trailing garbage.\nThus you could feed an article or message containing a\ndiff listing to\npatch, and it should work.\nIf the entire diff is indented by a consistent amount,\nor if a context diff contains lines ending in CRLF\nor is encapsulated one or more times by prepending\n\"- \" to lines starting with \"-\" as specified by Internet RFC 934,\nthis is taken into account.\n" }, { "code": null, "e": 13161, "s": 11535, "text": "\nWith context diffs, and to a lesser extent with normal diffs,\npatch can detect when the line numbers mentioned in the patch are incorrect,\nand attempts to find the correct place to apply each hunk of the patch.\nAs a first guess, it takes the line number mentioned for the hunk, plus or\nminus any offset used in applying the previous hunk.\nIf that is not the correct place,\npatch scans both forwards and backwards for a set of lines matching the context\ngiven in the hunk.\nFirst\npatch looks for a place where all lines of the context match.\nIf no such place is found, and it’s a context diff, and the maximum fuzz factor\nis set to 1 or more, then another scan takes place ignoring the first and last\nline of context.\nIf that fails, and the maximum fuzz factor is set to 2 or more,\nthe first two and last two lines of context are ignored,\nand another scan is made.\n(The default maximum fuzz factor is 2.)\nIf\npatch cannot find a place to install that hunk of the patch, it puts the\nhunk out to a reject file, which normally is the name of the output file\nplus a\n.rej suffix, or\n# if\n.rej would generate a file name that is too long\n(if even appending the single character\n# makes the file name too long, then\n# replaces the file name’s last character).\n(The rejected hunk comes out in ordinary context diff form regardless of\nthe input patch’s form.\nIf the input was a normal diff, many of the contexts are simply null.)\nThe line numbers on the hunks in the reject file may be different than\nin the patch file: they reflect the approximate location patch thinks the\nfailed hunks belong in the new file rather than the old one.\n" }, { "code": null, "e": 13694, "s": 13161, "text": "\nAs each hunk is completed, you are told if the hunk\nfailed, and if so which line (in the new file)\npatch thought the hunk should go on.\nIf the hunk is installed at a different line\nfrom the line number specified in the diff you\nare told the offset.\nA single large offset\nmay indicate that a hunk was installed in the\nwrong place.\nYou are also told if a fuzz factor was used to make the match, in which\ncase you should also be slightly suspicious.\nIf the\n--verbose option is given, you are also told about hunks that match exactly.\n" }, { "code": null, "e": 13875, "s": 13694, "text": "\nIf no original file\norigfile is specified on the command line,\npatch tries to figure out from the leading garbage what the name of the file\nto edit is, using the following rules.\n" }, { "code": null, "e": 13948, "s": 13875, "text": "\nFirst,\npatch takes an ordered list of candidate file names as follows:\n" }, { "code": null, "e": 14213, "s": 13948, "text": "\nAdditionally, if the leading garbage contains a\nPrereq: line,\npatch takes the first word from the prerequisites line (normally a version\nnumber) and checks the original file to see if that word can be found.\nIf not,\npatch asks for confirmation before proceeding.\n" }, { "code": null, "e": 14330, "s": 14213, "text": "\nThe upshot of all this is that you should be able to say, while in a news\ninterface, something like the following:\n" }, { "code": null, "e": 14369, "s": 14330, "text": "\n\n | patch -d /usr/src/local/blurfl\n" }, { "code": null, "e": 14461, "s": 14369, "text": "\n\nand patch a file in the\nblurfl directory directly from the article containing\nthe patch.\n" }, { "code": null, "e": 14854, "s": 14461, "text": "\nIf the patch file contains more than one patch,\npatch tries to apply each of them as if they came from separate patch files.\nThis means, among other things, that it is assumed that the name of the file\nto patch must be determined for each diff listing,\nand that the garbage before each diff listing\ncontains interesting things such as file names and revision level, as\nmentioned previously.\n" }, { "code": null, "e": 14890, "s": 14854, "text": "\n\n /u/howard/src/blurfl/blurfl.c\n" }, { "code": null, "e": 14954, "s": 14890, "text": "\n\nsetting\n-p0 gives the entire file name unmodified,\n-p1 gives\n" }, { "code": null, "e": 14989, "s": 14954, "text": "\n\n u/howard/src/blurfl/blurfl.c\n" }, { "code": null, "e": 15029, "s": 14989, "text": "\n\nwithout the leading slash,\n-p4 gives\n" }, { "code": null, "e": 15051, "s": 15029, "text": "\n\n blurfl/blurfl.c\n" }, { "code": null, "e": 15225, "s": 15051, "text": "\n\nand not specifying\n-p at all just gives you blurfl.c.\nWhatever you end up with is looked for either in the current directory,\nor the directory specified by the\n-d option.\n" }, { "code": null, "e": 15836, "s": 15225, "text": "\n\nIf the first hunk of a patch fails,\npatch reverses the hunk to see if it can be applied that way.\nIf it can, you are asked if you want to have the\n-R option set.\nIf it can’t, the patch continues to be applied normally.\n(Note: this method cannot detect a reversed patch if it is a normal diff\nand if the first command is an append (i.e. it should have been a delete)\nsince appends always succeed, due to the fact that a null context matches\nanywhere.\nLuckily, most patches add or change lines rather than delete them, so most\nreversed normal diffs begin with a delete, which fails, triggering\nthe heuristic.)\n" }, { "code": null, "e": 16037, "s": 15836, "text": "\n\nThe value of\nmethod is like the GNU\nEmacs ‘version-control’ variable;\npatch also recognizes synonyms that\nare more descriptive. The valid values for\nmethod are (unique abbreviations are\naccepted):\n" }, { "code": null, "e": 16344, "s": 16037, "text": "\n\nThe\n-Z or\n--set-utc and\n-T or\n--set-time options normally refrain from setting a file’s time if the file’s original time\ndoes not match the time given in the patch header, or if its\ncontents do not match the patch exactly. However, if the\n-f or\n--force option is given, the file time is set regardless.\n" }, { "code": null, "e": 16674, "s": 16344, "text": "\n\nDue to the limitations of\ndiff output format, these options cannot update the times of files whose\ncontents have not changed. Also, if you use these options, you should remove\n(e.g. with\nmake clean) all files that depend on the patched files, so that later invocations of\nmake do not get confused by the patched files’ times.\n" }, { "code": null, "e": 16683, "s": 16674, "text": "diff (1)" }, { "code": null, "e": 16692, "s": 16683, "text": "diff (1)" }, { "code": null, "e": 16699, "s": 16692, "text": "ed (1)" }, { "code": null, "e": 16706, "s": 16699, "text": "ed (1)" }, { "code": null, "e": 17120, "s": 16706, "text": "\nCreate your patch systematically.\nA good method is the command\ndiff -Naur old new where\nold and\nnew identify the old and new directories.\nThe names\nold and\nnew should not contain any slashes.\nThe\ndiff command’s headers should have dates\nand times in Universal Time using traditional Unix format,\nso that patch recipients can use the\n-Z or\n--set-utc option.\nHere is an example command, using Bourne shell syntax:\n" }, { "code": null, "e": 17170, "s": 17120, "text": "\n\n LC_ALL=C TZ=UTC0 diff -Naur gcc-2.7 gcc-2.8\n" }, { "code": null, "e": 17439, "s": 17170, "text": "\nTell your recipients how to apply the patch\nby telling them which directory to\ncd to, and which\npatch options to use. The option string\n-Np1 is recommended.\nTest your procedure by pretending to be a recipient and applying\nyour patch to a copy of the original files.\n" }, { "code": null, "e": 17715, "s": 17439, "text": "\nYou can save people a lot of grief by keeping a\npatchlevel.h file which is patched to increment the patch level\nas the first diff in the patch file you send out.\nIf you put a\nPrereq: line in with the patch, it won’t let them apply\npatches out of order without some warning.\n" }, { "code": null, "e": 18331, "s": 17715, "text": "\nYou can create a file by sending out a diff that compares\n/dev/null or an empty file dated the Epoch (1970-01-01 00:00:00 UTC)\nto the file you want to create.\nThis only works if the file you want to create doesn’t exist already in\nthe target directory.\nConversely, you can remove a file by sending out a context diff that compares\nthe file to be deleted with an empty file dated the Epoch.\nThe file will be removed unless\npatch is conforming to POSIX and the\n-E or\n--remove-empty-files option is not given.\nAn easy way to generate patches that create and remove files\nis to use GNU\ndiff’s -N or\n--new-file option.\n" }, { "code": null, "e": 18426, "s": 18331, "text": "\nIf the recipient is supposed to use the\n-pN option, do not send output that looks like this:\n" }, { "code": null, "e": 18578, "s": 18426, "text": "\n\n\n diff -Naur v2.0.29/prog/README prog/README\n\n --- v2.0.29/prog/README Mon Mar 10 15:13:12 1997\n\n +++ prog/README Mon Mar 17 14:58:22 1997\n" }, { "code": null, "e": 18775, "s": 18578, "text": "\n\nbecause the two file names have different numbers of slashes,\nand different versions of\npatch interpret the file names differently.\nTo avoid confusion, send output that looks like this instead:\n" }, { "code": null, "e": 18943, "s": 18775, "text": "\n\n\n diff -Naur v2.0.29/prog/README v2.0.30/prog/README\n\n --- v2.0.29/prog/README Mon Mar 10 15:13:12 1997\n\n +++ v2.0.30/prog/README Mon Mar 17 14:58:22 1997\n" }, { "code": null, "e": 19222, "s": 18946, "text": "\nAvoid sending patches that compare backup file names like\nREADME.orig, since this might confuse\npatch into patching a backup file instead of the real file.\nInstead, send patches that compare the same base file names\nin different directories, e.g.\nold/README and\nnew/README. " }, { "code": null, "e": 19337, "s": 19222, "text": "\nTake care not to send out reversed patches, since it makes people wonder\nwhether they already applied the patch.\n" }, { "code": null, "e": 19786, "s": 19337, "text": "\nTry not to have your patch modify derived files\n(e.g. the file\nconfigure where there is a line\nconfigure: configure.in in your makefile), since the recipient should be\nable to regenerate the derived files anyway.\nIf you must send diffs of derived files,\ngenerate the diffs using UTC,\nhave the recipients apply the patch with the\n-Z or\n--set-utc option, and have them remove any unpatched files that depend on patched files\n(e.g. with\nmake clean). " }, { "code": null, "e": 19961, "s": 19786, "text": "\nWhile you may be able to get away with putting 582 diff listings into\none file, it may be wiser to group related patches into separate files in\ncase something goes haywire.\n" }, { "code": null, "e": 20190, "s": 19961, "text": "\nIf the\n--verbose option is given, the message\nHmm... indicates that there is unprocessed text in\nthe patch file and that\npatch is attempting to intuit whether there is a patch in that text and, if so,\nwhat kind of patch it is.\n" }, { "code": null, "e": 20476, "s": 20190, "text": "\npatch’s exit status is\n0 if all hunks are applied successfully,\n1 if some hunks cannot be applied,\nand 2 if there is more serious trouble.\nWhen applying a set of patches in a loop it behooves you to check this\nexit status so you don’t apply a later patch to a partially patched file.\n" }, { "code": null, "e": 20932, "s": 20476, "text": "\npatch cannot tell if the line numbers are off in an\ned script, and can detect\nbad line numbers in a normal diff only when it finds a change or deletion.\nA context diff using fuzz factor 3 may have the same problem.\nUntil a suitable interactive interface is added, you should probably do\na context diff in these cases to see if the changes made sense.\nOf course, compiling without errors is a pretty good indication that the patch\nworked, but not always.\n" }, { "code": null, "e": 21176, "s": 20932, "text": "\npatch usually produces the correct results, even when it has to do a lot of\nguessing.\nHowever, the results are guaranteed to be correct only when the patch is\napplied to exactly the same version of the file that the patch was\ngenerated from.\n" }, { "code": null, "e": 21452, "s": 21176, "text": "\n\nAlso,\ntraditional\npatch simply counted slashes when stripping path prefixes;\npatch now counts pathname components.\nThat is, a sequence of one or more adjacent slashes\nnow counts as a single slash.\nFor maximum portability, avoid sending patches containing\n// in file names.\n" }, { "code": null, "e": 21724, "s": 21452, "text": "\n\nConversely, in POSIX\npatch, backups are never made, even when there is a mismatch.\nIn GNU\npatch, this behavior is enabled with the\n--no-backup-if-mismatch option, or by conforming to POSIX with the\n--posix option or by setting the\nPOSIXLY_CORRECT environment variable.\n" }, { "code": null, "e": 21825, "s": 21724, "text": "\n\nThe\n-b suffix option\nof traditional\npatch is equivalent to the\n-b -z suffix options of GNU\npatch. " }, { "code": null, "e": 21909, "s": 21828, "text": "\n\n-c \n-d dir \n-D define \n-e \n-l \n-n \n-N \n-o outfile \n-pnum \n-R \n-r rejectfile \n\n" }, { "code": null, "e": 22038, "s": 21909, "text": "\npatch could be smarter about partial matches, excessively deviant offsets and\nswapped code, but that would take an extra pass.\n" }, { "code": null, "e": 22269, "s": 22038, "text": "\nIf code has been duplicated (for instance with\n#ifdef OLDCODE ... #else ... #endif),\npatch is incapable of patching both versions, and, if it works at all, will likely\npatch the wrong one, and tell you that it succeeded to boot.\n" }, { "code": null, "e": 22425, "s": 22269, "text": "\nIf you apply a patch you’ve already applied,\npatch thinks it is a reversed patch, and offers to un-apply the patch.\nThis could be construed as a feature.\n" }, { "code": null, "e": 22589, "s": 22425, "text": "\nPermission is granted to make and distribute verbatim copies of\nthis manual provided the copyright notice and this permission notice\nare preserved on all copies.\n" }, { "code": null, "e": 22837, "s": 22589, "text": "\nPermission is granted to copy and distribute modified versions of this\nmanual under the conditions for verbatim copying, provided that the\nentire resulting derived work is distributed under the terms of a\npermission notice identical to this one.\n" } ]
SQL – SELECT NULL
17 Jun, 2021 The word NULL is used to describe a missing value in SQL. In a table, a NULL value is a value in a field that appears to be empty. A field with a NULL value is the same as one that has no value. It’s important to grasp the difference between a NULL value and a zero value or a field of spaces. There are two possibilities: Where SQL is NULL Syntax: SELECT * FROM TABLANAME WHERE COLUMNNAME IS NULL; Where SQL is NOT NULL Syntax: SELECT * FROM TABLANAME WHERE COLUMNNAME IS NOT NULL; NOT NULL denotes that the column must always consider an explicit value of the specified data type. We did not use NOT NULL in two columns, which means these columns may be NULL. A field with a NULL value was left blank during the record creation process. Example: Here, we will first create a database named “geeks” then we will create a table “department” in that database. After, that we will execute our query on that table. CREATE DATABASE geeks; USE geeks; CREATE TABLE [dbo].[department]( [ID] [int] NULL, [SALARY] [int] NULL, [NAME] [varchar](20) NULL ) GO INSERT INTO [dbo].[department] ( ID, SALARY, NAME) VALUES ( 1, 34000, 'Neha') INSERT INTO [dbo].[department]( ID, NAME) VALUES ( 2, 'Hema') INSERT INTO [dbo].[department]( ID, SALARY, NAME) VALUES ( 3, 36000, 'Jaya' ) INSERT INTO [dbo].[department] ( ID, NAME)VALUES ( 4, 'Priya' ) INSERT INTO [dbo].[department]( ID, SALARY, NAME) VALUES ( 5, 34000, 'Ketan' )) GO This is our data inside the table: SELECT * FROM department; Select where SQL is NULL: SELECT * FROM department WHERE salary IS NULL; Output: Select where SQL is NOT NULL: SELECT * FROM department WHERE salary IS NOT NULL; Output: surinderdawra388 Picked SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? Window functions in SQL What is Temporary Table in SQL? SQL using Python SQL | Sub queries in From Clause SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter RANK() Function in SQL Server SQL Query to Convert VARCHAR to INT SQL Query to Compare Two Dates SQL Query to Insert Multiple Rows
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jun, 2021" }, { "code": null, "e": 322, "s": 28, "text": "The word NULL is used to describe a missing value in SQL. In a table, a NULL value is a value in a field that appears to be empty. A field with a NULL value is the same as one that has no value. It’s important to grasp the difference between a NULL value and a zero value or a field of spaces." }, { "code": null, "e": 351, "s": 322, "text": "There are two possibilities:" }, { "code": null, "e": 369, "s": 351, "text": "Where SQL is NULL" }, { "code": null, "e": 429, "s": 369, "text": "Syntax: \nSELECT *\nFROM TABLANAME\nWHERE COLUMNNAME IS NULL;" }, { "code": null, "e": 451, "s": 429, "text": "Where SQL is NOT NULL" }, { "code": null, "e": 515, "s": 451, "text": "Syntax: \nSELECT *\nFROM TABLANAME\nWHERE COLUMNNAME IS NOT NULL;" }, { "code": null, "e": 772, "s": 515, "text": "NOT NULL denotes that the column must always consider an explicit value of the specified data type. We did not use NOT NULL in two columns, which means these columns may be NULL. A field with a NULL value was left blank during the record creation process." }, { "code": null, "e": 782, "s": 772, "text": "Example: " }, { "code": null, "e": 946, "s": 782, "text": "Here, we will first create a database named “geeks” then we will create a table “department” in that database. After, that we will execute our query on that table." }, { "code": null, "e": 969, "s": 946, "text": "CREATE DATABASE geeks;" }, { "code": null, "e": 980, "s": 969, "text": "USE geeks;" }, { "code": null, "e": 1082, "s": 980, "text": "CREATE TABLE [dbo].[department](\n[ID] [int] NULL,\n[SALARY] [int] NULL,\n[NAME] [varchar](20) NULL\n)\nGO" }, { "code": null, "e": 1458, "s": 1082, "text": "INSERT INTO [dbo].[department] ( ID, SALARY, NAME) VALUES ( 1, 34000, 'Neha') \nINSERT INTO [dbo].[department]( ID, NAME) VALUES ( 2, 'Hema')\nINSERT INTO [dbo].[department]( ID, SALARY, NAME) VALUES ( 3, 36000, 'Jaya' )\nINSERT INTO [dbo].[department] ( ID, NAME)VALUES ( 4, 'Priya' )\nINSERT INTO [dbo].[department]( ID, SALARY, NAME) VALUES ( 5, 34000, 'Ketan' ))\nGO" }, { "code": null, "e": 1493, "s": 1458, "text": "This is our data inside the table:" }, { "code": null, "e": 1519, "s": 1493, "text": "SELECT * FROM department;" }, { "code": null, "e": 1545, "s": 1519, "text": "Select where SQL is NULL:" }, { "code": null, "e": 1592, "s": 1545, "text": "SELECT * FROM department WHERE salary IS NULL;" }, { "code": null, "e": 1600, "s": 1592, "text": "Output:" }, { "code": null, "e": 1630, "s": 1600, "text": "Select where SQL is NOT NULL:" }, { "code": null, "e": 1681, "s": 1630, "text": "SELECT * FROM department WHERE salary IS NOT NULL;" }, { "code": null, "e": 1689, "s": 1681, "text": "Output:" }, { "code": null, "e": 1706, "s": 1689, "text": "surinderdawra388" }, { "code": null, "e": 1713, "s": 1706, "text": "Picked" }, { "code": null, "e": 1717, "s": 1713, "text": "SQL" }, { "code": null, "e": 1721, "s": 1717, "text": "SQL" }, { "code": null, "e": 1819, "s": 1721, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1885, "s": 1819, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 1909, "s": 1885, "text": "Window functions in SQL" }, { "code": null, "e": 1941, "s": 1909, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 1958, "s": 1941, "text": "SQL using Python" }, { "code": null, "e": 1991, "s": 1958, "text": "SQL | Sub queries in From Clause" }, { "code": null, "e": 2069, "s": 1991, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 2099, "s": 2069, "text": "RANK() Function in SQL Server" }, { "code": null, "e": 2135, "s": 2099, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 2166, "s": 2135, "text": "SQL Query to Compare Two Dates" } ]
How to Write Data to Text File in Excel VBA?
29 Oct, 2021 This VBA Program reads an Excel Range (Sales Data) and write to a Text file (Sales.txt) Excel VBA code to read data from an Excel file (Sales Data – Range “A1:E26”). Need two “For loop” for rows and columns. Write each value with a comma in the text file till the end of columns (write without comma only the last column value). Do the above step until reach the end of rows. Sales Data in Excel: 5 columns and 25 rows Sales Data VBA code to create a text file as below Declaring Variables : 'Variable declarations Dim myFileName As String, rng As Range, cellVal As Variant, row As Integer, col As Integer Initialize variables:myFileName: The file name with the full path of the output text filerng: Excel range to read data from an excel. myFileName: The file name with the full path of the output text file rng: Excel range to read data from an excel. 'Full path of the text file myFileName = "D:\Excel\WriteText\sales.txt" 'Data range need to write on text file Set rng = ActiveSheet.Range("A1:E26") Open the output text file and assign a variable “#1” 'Open text file Open myFileName For Output As #1 ‘Nested loop to iterate both rows and columns of a given range eg: “A1:E26” [5 columns and 26 rows] 'Number of Rows For row = 1 To rng.Rows.Count 'Number of Columns For col = 1 To rng.Columns.Count Assign the value to variable cellVal cellVal = rng.Cells(row, col).Value Write cellVal with comma. If the col is equal to the last column of a row. write-only value without the comma. 'write cellVal on text file If col = rng.Columns.Count Then Write #1, cellVal Else Write #1, cellVal, End If Close both for loops Next col Next row Close the file Close #1 Step 1: Add a shape (Create Text File) to your worksheet Step 2: Right-click on “Create a Text file” and “Assign Macro..” Step 3: Select MacroToCreateTextFile Step 4: Save your excel file as “Excel Macro-Enabled Workbook” *.xlsm Step 5: Click “Create Text file” Excel-VBA Picked Excel Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Delete Blank Columns in Excel? How to Normalize Data in Excel? How to Get Length of Array in Excel VBA? How to Find the Last Used Row and Column in Excel VBA? How to make a 3 Axis Graph using Excel? How to Use Solver in Excel? Introduction to Excel Spreadsheet Macros in Excel How to Show Percentages in Stacked Column Chart in Excel? How to Create a Macro in Excel?
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Oct, 2021" }, { "code": null, "e": 116, "s": 28, "text": "This VBA Program reads an Excel Range (Sales Data) and write to a Text file (Sales.txt)" }, { "code": null, "e": 406, "s": 116, "text": "Excel VBA code to read data from an Excel file (Sales Data – Range “A1:E26”). Need two “For loop” for rows and columns. Write each value with a comma in the text file till the end of columns (write without comma only the last column value). Do the above step until reach the end of rows. " }, { "code": null, "e": 449, "s": 406, "text": "Sales Data in Excel: 5 columns and 25 rows" }, { "code": null, "e": 460, "s": 449, "text": "Sales Data" }, { "code": null, "e": 500, "s": 460, "text": "VBA code to create a text file as below" }, { "code": null, "e": 524, "s": 500, "text": "Declaring Variables : " }, { "code": null, "e": 638, "s": 524, "text": "'Variable declarations\nDim myFileName As String, rng As Range, cellVal As Variant, row As Integer, col As Integer" }, { "code": null, "e": 772, "s": 638, "text": "Initialize variables:myFileName: The file name with the full path of the output text filerng: Excel range to read data from an excel." }, { "code": null, "e": 841, "s": 772, "text": "myFileName: The file name with the full path of the output text file" }, { "code": null, "e": 886, "s": 841, "text": "rng: Excel range to read data from an excel." }, { "code": null, "e": 1035, "s": 886, "text": "'Full path of the text file\nmyFileName = \"D:\\Excel\\WriteText\\sales.txt\"\n'Data range need to write on text file\nSet rng = ActiveSheet.Range(\"A1:E26\")" }, { "code": null, "e": 1088, "s": 1035, "text": "Open the output text file and assign a variable “#1”" }, { "code": null, "e": 1137, "s": 1088, "text": "'Open text file\nOpen myFileName For Output As #1" }, { "code": null, "e": 1237, "s": 1137, "text": "‘Nested loop to iterate both rows and columns of a given range eg: “A1:E26” [5 columns and 26 rows]" }, { "code": null, "e": 1341, "s": 1237, "text": "'Number of Rows\nFor row = 1 To rng.Rows.Count\n 'Number of Columns\n For col = 1 To rng.Columns.Count" }, { "code": null, "e": 1379, "s": 1341, "text": "Assign the value to variable cellVal " }, { "code": null, "e": 1415, "s": 1379, "text": "cellVal = rng.Cells(row, col).Value" }, { "code": null, "e": 1528, "s": 1415, "text": "Write cellVal with comma. If the col is equal to the last column of a row. write-only value without the comma." }, { "code": null, "e": 1667, "s": 1528, "text": "'write cellVal on text file\n If col = rng.Columns.Count Then\n Write #1, cellVal \n Else\n Write #1, cellVal, \n End If" }, { "code": null, "e": 1688, "s": 1667, "text": "Close both for loops" }, { "code": null, "e": 1709, "s": 1688, "text": " Next col\nNext row" }, { "code": null, "e": 1724, "s": 1709, "text": "Close the file" }, { "code": null, "e": 1733, "s": 1724, "text": "Close #1" }, { "code": null, "e": 1791, "s": 1733, "text": "Step 1: Add a shape (Create Text File) to your worksheet " }, { "code": null, "e": 1856, "s": 1791, "text": "Step 2: Right-click on “Create a Text file” and “Assign Macro..”" }, { "code": null, "e": 1893, "s": 1856, "text": "Step 3: Select MacroToCreateTextFile" }, { "code": null, "e": 1964, "s": 1893, "text": "Step 4: Save your excel file as “Excel Macro-Enabled Workbook” *.xlsm" }, { "code": null, "e": 1997, "s": 1964, "text": "Step 5: Click “Create Text file”" }, { "code": null, "e": 2007, "s": 1997, "text": "Excel-VBA" }, { "code": null, "e": 2014, "s": 2007, "text": "Picked" }, { "code": null, "e": 2020, "s": 2014, "text": "Excel" }, { "code": null, "e": 2118, "s": 2020, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2156, "s": 2118, "text": "How to Delete Blank Columns in Excel?" }, { "code": null, "e": 2188, "s": 2156, "text": "How to Normalize Data in Excel?" }, { "code": null, "e": 2229, "s": 2188, "text": "How to Get Length of Array in Excel VBA?" }, { "code": null, "e": 2284, "s": 2229, "text": "How to Find the Last Used Row and Column in Excel VBA?" }, { "code": null, "e": 2324, "s": 2284, "text": "How to make a 3 Axis Graph using Excel?" }, { "code": null, "e": 2352, "s": 2324, "text": "How to Use Solver in Excel?" }, { "code": null, "e": 2386, "s": 2352, "text": "Introduction to Excel Spreadsheet" }, { "code": null, "e": 2402, "s": 2386, "text": "Macros in Excel" }, { "code": null, "e": 2460, "s": 2402, "text": "How to Show Percentages in Stacked Column Chart in Excel?" } ]
How to scale an Image in ImageView to keep the aspect ratio in Android?
This example demonstrates how to scale an Image in ImageView to keep the aspect ratio in Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout 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"> <ImageView android:id="@+id/my_image" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_centerInParent="true" android:adjustViewBounds="true" android:scaleType="fitXY" tools:ignore="MissingConstraints" /> </androidx.constraintlayout.widget.ConstraintLayout> Step 3 − Add the following code to src/MainActivity.java package com.app.sample; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.ImageView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImageView my_image = (ImageView) findViewById(R.id.my_image); my_image.setBackgroundResource(R.drawable.flower); } } Step 4 − Add the following code to Manifests/AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.app.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code.
[ { "code": null, "e": 1285, "s": 1187, "text": "This example demonstrates how to scale an Image in ImageView to keep the aspect ratio in Android." }, { "code": null, "e": 1414, "s": 1285, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1479, "s": 1414, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2185, "s": 1479, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<androidx.constraintlayout.widget.ConstraintLayout\nxmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <ImageView\n android:id=\"@+id/my_image\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\"\n android:layout_centerInParent=\"true\"\n android:adjustViewBounds=\"true\"\n android:scaleType=\"fitXY\"\n tools:ignore=\"MissingConstraints\" />\n</androidx.constraintlayout.widget.ConstraintLayout>" }, { "code": null, "e": 2242, "s": 2185, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2717, "s": 2242, "text": "package com.app.sample;\nimport androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.ImageView;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n ImageView my_image = (ImageView) findViewById(R.id.my_image);\n my_image.setBackgroundResource(R.drawable.flower);\n }\n}" }, { "code": null, "e": 2782, "s": 2717, "text": "Step 4 − Add the following code to Manifests/AndroidManifest.xml" }, { "code": null, "e": 3470, "s": 2782, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.app.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 3821, "s": 3470, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 3862, "s": 3821, "text": "Click here to download the project code." } ]
LTRIM() Function in SQL Server
16 Dec, 2020 LTRIM() function helps to return remove all the space characters found on the left-hand side of the string. Syntax : LTRIM(string, [trim_string]) Parameter : string – The string from which the leading space character would be removed. trim_string – It is an optional parameter that specifies the characters to be removed from the given string. Returns :The function will return the string after removing all left-hand side space characters. Applicable to the following versions of SQL Server : SQL Server 2017 SQL Server 2016 SQL Server 2014 SQL Server 2012 SQL Server 2008 R2 SQL Server 2008 SQL Server 2005 Example 1 :The basic usage of the LTRIM() function. SELECT LTRIM(' GeeksforGeeks'); Output : GeeksforGeeks Example 2 :Using LTRIM() function with a variable. DECLARE @str VARCHAR(50) SET @str = ' Have a nice time ahead!!' SELECT LTRIM(@str); Output : Have a nice time ahead!! Example-3 :Use of “trim_space” in LTRIM() function. SELECT LTRIM (‘000325400’, ‘0’); Output : 325400 DBMS-SQL SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? Window functions in SQL What is Temporary Table in SQL? SQL | Sub queries in From Clause SQL using Python SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter RANK() Function in SQL Server SQL Query to Convert VARCHAR to INT SQL Query to Compare Two Dates How to Write a SQL Query For a Specific Date Range and Date Time?
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Dec, 2020" }, { "code": null, "e": 136, "s": 28, "text": "LTRIM() function helps to return remove all the space characters found on the left-hand side of the string." }, { "code": null, "e": 145, "s": 136, "text": "Syntax :" }, { "code": null, "e": 174, "s": 145, "text": "LTRIM(string, [trim_string])" }, { "code": null, "e": 186, "s": 174, "text": "Parameter :" }, { "code": null, "e": 263, "s": 186, "text": "string – The string from which the leading space character would be removed." }, { "code": null, "e": 372, "s": 263, "text": "trim_string – It is an optional parameter that specifies the characters to be removed from the given string." }, { "code": null, "e": 469, "s": 372, "text": "Returns :The function will return the string after removing all left-hand side space characters." }, { "code": null, "e": 522, "s": 469, "text": "Applicable to the following versions of SQL Server :" }, { "code": null, "e": 538, "s": 522, "text": "SQL Server 2017" }, { "code": null, "e": 554, "s": 538, "text": "SQL Server 2016" }, { "code": null, "e": 570, "s": 554, "text": "SQL Server 2014" }, { "code": null, "e": 586, "s": 570, "text": "SQL Server 2012" }, { "code": null, "e": 605, "s": 586, "text": "SQL Server 2008 R2" }, { "code": null, "e": 621, "s": 605, "text": "SQL Server 2008" }, { "code": null, "e": 637, "s": 621, "text": "SQL Server 2005" }, { "code": null, "e": 689, "s": 637, "text": "Example 1 :The basic usage of the LTRIM() function." }, { "code": null, "e": 727, "s": 689, "text": "SELECT LTRIM(' GeeksforGeeks');" }, { "code": null, "e": 736, "s": 727, "text": "Output :" }, { "code": null, "e": 750, "s": 736, "text": "GeeksforGeeks" }, { "code": null, "e": 801, "s": 750, "text": "Example 2 :Using LTRIM() function with a variable." }, { "code": null, "e": 889, "s": 801, "text": "DECLARE @str VARCHAR(50)\nSET @str = ' Have a nice time ahead!!'\nSELECT LTRIM(@str);" }, { "code": null, "e": 898, "s": 889, "text": "Output :" }, { "code": null, "e": 923, "s": 898, "text": "Have a nice time ahead!!" }, { "code": null, "e": 975, "s": 923, "text": "Example-3 :Use of “trim_space” in LTRIM() function." }, { "code": null, "e": 1008, "s": 975, "text": "SELECT LTRIM (‘000325400’, ‘0’);" }, { "code": null, "e": 1017, "s": 1008, "text": "Output :" }, { "code": null, "e": 1024, "s": 1017, "text": "325400" }, { "code": null, "e": 1033, "s": 1024, "text": "DBMS-SQL" }, { "code": null, "e": 1044, "s": 1033, "text": "SQL-Server" }, { "code": null, "e": 1048, "s": 1044, "text": "SQL" }, { "code": null, "e": 1052, "s": 1048, "text": "SQL" }, { "code": null, "e": 1150, "s": 1052, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1216, "s": 1150, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 1240, "s": 1216, "text": "Window functions in SQL" }, { "code": null, "e": 1272, "s": 1240, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 1305, "s": 1272, "text": "SQL | Sub queries in From Clause" }, { "code": null, "e": 1322, "s": 1305, "text": "SQL using Python" }, { "code": null, "e": 1400, "s": 1322, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 1430, "s": 1400, "text": "RANK() Function in SQL Server" }, { "code": null, "e": 1466, "s": 1430, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 1497, "s": 1466, "text": "SQL Query to Compare Two Dates" } ]
Difference between Natural join and Inner Join in SQL
31 Aug, 2021 Prerequisite – Join (Inner, Left, Right and Full Joins) 1. Natural Join : Natural Join joins two tables based on same attribute name and datatypes. The resulting table will contain all the attributes of both the table but keep only one copy of each common column. Example: Consider the two tables given below: Student Table Marks Table Consider the given query SELECT * FROM Student NATURAL JOIN Marks; Output: 2. Inner Join : Inner Join joins two table on the basis of the column which is explicitly specified in the ON clause. The resulting table will contain all the attributes from both the tables including common column also. Example: Consider the above two tables and the query is given below: SELECT * FROM student S INNER JOIN Marks M ON S.Roll_No = M.Roll_No; Output : Difference between Natural JOIN and INNER JOIN in SQL : The Natural Joins are not supported in the SQL Server Management Studio also knowns as Microsoft SQL Server. iamsamyak DBMS-Join DBMS Difference Between GATE CS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n31 Aug, 2021" }, { "code": null, "e": 318, "s": 53, "text": "Prerequisite – Join (Inner, Left, Right and Full Joins) 1. Natural Join : Natural Join joins two tables based on same attribute name and datatypes. The resulting table will contain all the attributes of both the table but keep only one copy of each common column. " }, { "code": null, "e": 365, "s": 318, "text": "Example: Consider the two tables given below: " }, { "code": null, "e": 381, "s": 365, "text": "Student Table " }, { "code": null, "e": 395, "s": 381, "text": "Marks Table " }, { "code": null, "e": 421, "s": 395, "text": "Consider the given query " }, { "code": null, "e": 464, "s": 421, "text": "SELECT * \nFROM Student NATURAL JOIN Marks;" }, { "code": null, "e": 473, "s": 464, "text": "Output: " }, { "code": null, "e": 697, "s": 475, "text": "2. Inner Join : Inner Join joins two table on the basis of the column which is explicitly specified in the ON clause. The resulting table will contain all the attributes from both the tables including common column also. " }, { "code": null, "e": 767, "s": 697, "text": "Example: Consider the above two tables and the query is given below: " }, { "code": null, "e": 838, "s": 767, "text": "SELECT * \nFROM student S INNER JOIN Marks M ON S.Roll_No = M.Roll_No; " }, { "code": null, "e": 848, "s": 838, "text": "Output : " }, { "code": null, "e": 907, "s": 850, "text": "Difference between Natural JOIN and INNER JOIN in SQL : " }, { "code": null, "e": 1016, "s": 907, "text": "The Natural Joins are not supported in the SQL Server Management Studio also knowns as Microsoft SQL Server." }, { "code": null, "e": 1026, "s": 1016, "text": "iamsamyak" }, { "code": null, "e": 1036, "s": 1026, "text": "DBMS-Join" }, { "code": null, "e": 1041, "s": 1036, "text": "DBMS" }, { "code": null, "e": 1060, "s": 1041, "text": "Difference Between" }, { "code": null, "e": 1068, "s": 1060, "text": "GATE CS" }, { "code": null, "e": 1072, "s": 1068, "text": "SQL" }, { "code": null, "e": 1077, "s": 1072, "text": "DBMS" }, { "code": null, "e": 1081, "s": 1077, "text": "SQL" } ]
MVVM – Validations
In this chapter, we will learn about validations. We will also look at a clean way to do validation with what WPF bindings already support but tying it into MVVM components. When your application starts accepting data input from end users you need to consider validating that input. When your application starts accepting data input from end users you need to consider validating that input. Make sure it conforms to your overall requirements. Make sure it conforms to your overall requirements. WPF has some great builds and features in the binding system for validating input and you can still leverage all those features when doing MVVM. WPF has some great builds and features in the binding system for validating input and you can still leverage all those features when doing MVVM. Keep in mind that the logic that supports your validation and defines what rules exist for what properties should be part of the Model or the ViewModel, not the View itself. Keep in mind that the logic that supports your validation and defines what rules exist for what properties should be part of the Model or the ViewModel, not the View itself. You can still use all the ways of expressing validation that are supported by WPF data binding including − Throwing exceptions on a property is set. Implementing the IDataErrorInfo interface. Implementing INotifyDataErrorInfo. Use WPF validation rules. In general, INotifyDataErrorInfo is recommended and was introduced to WPF .net 4.5 and it supports querying the object for errors associated with properties and it also fixes a couple of deficiencies with all the other options. Specifically, it allows asynchronous validation. It allows properties to have more than one error associated with them. Let’s take a look at an example in which we will add validation support to our input view, and in large application you will probably need this a number of places in your application. Sometimes on Views, sometimes on ViewModels and sometimes on these helper objects there are wrappers around model objects. It’s a good practice for putting the validation support in a common base class that you can then inherit from different scenarios. The base class will support INotifyDataErrorInfo so that that validation gets triggered when properties change. Create add a new class called ValidatableBindableBase. Since we already have a base class for a property change handling, let’s derive the base class from it and also implement the INotifyDataErrorInfo interface. Following is the implementation of ValidatableBindableBase class. using System; using System.Collections.Generic; using System.ComponentModel; //using System.ComponentModel.DataAnnotations; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Windows.Controls; namespace MVVMHierarchiesDemo { public class ValidatableBindableBase : BindableBase, INotifyDataErrorInfo { private Dictionary<string, List<string>> _errors = new Dictionary<string, List<string>>(); public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged = delegate { }; public System.Collections.IEnumerable GetErrors(string propertyName) { if (_errors.ContainsKey(propertyName)) return _errors[propertyName]; else return null; } public bool HasErrors { get { return _errors.Count > 0; } } protected override void SetProperty<T>(ref T member, T val, [CallerMemberName] string propertyName = null) { base.SetProperty<T>(ref member, val, propertyName); ValidateProperty(propertyName, val); } private void ValidateProperty<T>(string propertyName, T value) { var results = new List<ValidationResult>(); //ValidationContext context = new ValidationContext(this); //context.MemberName = propertyName; //Validator.TryValidateProperty(value, context, results); if (results.Any()) { //_errors[propertyName] = results.Select(c => c.ErrorMessage).ToList(); } else { _errors.Remove(propertyName); } ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName)); } } } Now add AddEditCustomerView and AddEditCustomerViewModel in respective folders. Following is the code of AddEditCustomerView.xaml. <UserControl x:Class = "MVVMHierarchiesDemo.Views.AddEditCustomerView" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" xmlns:local = "clr-namespace:MVVMHierarchiesDemo.Views" mc:Ignorable = "d" d:DesignHeight = "300" d:DesignWidth = "300"> <Grid> <Grid.RowDefinitions> <RowDefinition Height = "Auto" /> <RowDefinition Height = "Auto" /> </Grid.RowDefinitions> <Grid x:Name = "grid1" HorizontalAlignment = "Left" DataContext = "{Binding Customer}" Margin = "10,10,0,0" VerticalAlignment = "Top"> <Grid.ColumnDefinitions> <ColumnDefinition Width = "Auto" /> <ColumnDefinition Width = "Auto" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height = "Auto" /> <RowDefinition Height = "Auto" /> <RowDefinition Height = "Auto" /> <RowDefinition Height = "Auto" /> </Grid.RowDefinitions> <Label Content = "First Name:" Grid.Column = "0" HorizontalAlignment = "Left" Margin = "3" Grid.Row = "0" VerticalAlignment = "Center" /> <TextBox x:Name = "firstNameTextBox" Grid.Column = "1" HorizontalAlignment = "Left" Height = "23" Margin = "3" Grid.Row = "0" Text = "{Binding FirstName, ValidatesOnNotifyDataErrors = True}" VerticalAlignment = "Center" Width = "120" /> <Label Content = "Last Name:" Grid.Column = "0" HorizontalAlignment = "Left" Margin = "3" Grid.Row = "1" VerticalAlignment = "Center" /> <TextBox x:Name = "lastNameTextBox" Grid.Column = "1" HorizontalAlignment = "Left" Height = "23" Margin = "3" Grid.Row = "1" Text = "{Binding LastName, ValidatesOnNotifyDataErrors = True}" VerticalAlignment = "Center" Width = "120" /> <Label Content = "Email:" Grid.Column = "0" HorizontalAlignment = "Left" Margin = "3" Grid.Row = "2" VerticalAlignment = "Center" /> <TextBox x:Name = "emailTextBox" Grid.Column = "1" HorizontalAlignment = "Left" Height = "23" Margin = "3" Grid.Row = "2" Text = "{Binding Email, ValidatesOnNotifyDataErrors = True}" VerticalAlignment = "Center" Width = "120" /> <Label Content = "Phone:" Grid.Column = "0" HorizontalAlignment = "Left" Margin = "3" Grid.Row = "3" VerticalAlignment = "Center" /> <TextBox x:Name = "phoneTextBox" Grid.Column = "1" HorizontalAlignment = "Left" Height = "23" Margin = "3" Grid.Row = "3" Text = "{Binding Phone, ValidatesOnNotifyDataErrors = True}" VerticalAlignment = "Center" Width = "120" /> </Grid> <Grid Grid.Row = "1"> <Button Content = "Save" Command = "{Binding SaveCommand}" HorizontalAlignment = "Left" Margin = "25,5,0,0" VerticalAlignment = "Top" Width = "75" /> <Button Content = "Add" Command = "{Binding SaveCommand}" HorizontalAlignment = "Left" Margin = "25,5,0,0" VerticalAlignment = "Top" Width = "75" /> <Button Content = "Cancel" Command = "{Binding CancelCommand}" HorizontalAlignment = "Left" Margin = "150,5,0,0" VerticalAlignment = "Top" Width = "75" /> </Grid> </Grid> </UserControl> Following is the AddEditCustomerViewModel implementation. using MVVMHierarchiesDemo.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MVVMHierarchiesDemo.ViewModel { class AddEditCustomerViewModel : BindableBase { public AddEditCustomerViewModel() { CancelCommand = new MyIcommand(OnCancel); SaveCommand = new MyIcommand(OnSave, CanSave); } private bool _EditMode; public bool EditMode { get { return _EditMode; } set { SetProperty(ref _EditMode, value);} } private SimpleEditableCustomer _Customer; public SimpleEditableCustomer Customer { get { return _Customer; } set { SetProperty(ref _Customer, value);} } private Customer _editingCustomer = null; public void SetCustomer(Customer cust) { _editingCustomer = cust; if (Customer != null) Customer.ErrorsChanged -= RaiseCanExecuteChanged; Customer = new SimpleEditableCustomer(); Customer.ErrorsChanged += RaiseCanExecuteChanged; CopyCustomer(cust, Customer); } private void RaiseCanExecuteChanged(object sender, EventArgs e) { SaveCommand.RaiseCanExecuteChanged(); } public MyIcommand CancelCommand { get; private set; } public MyIcommand SaveCommand { get; private set; } public event Action Done = delegate { }; private void OnCancel() { Done(); } private async void OnSave() { Done(); } private bool CanSave() { return !Customer.HasErrors; } } } Following is the implementation of SimpleEditableCustomer class. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MVVMHierarchiesDemo.Model { public class SimpleEditableCustomer : ValidatableBindableBase { private Guid _id; public Guid Id { get { return _id; } set { SetProperty(ref _id, value); } } private string _firstName; [Required] public string FirstName { get { return _firstName; } set { SetProperty(ref _firstName, value); } } private string _lastName; [Required] public string LastName { get { return _lastName; } set { SetProperty(ref _lastName, value); } } private string _email; [EmailAddress] public string Email { get { return _email; } set { SetProperty(ref _email, value); } } private string _phone; [Phone] public string Phone { get { return _phone; } set { SetProperty(ref _phone, value); } } } } When the above code is compiled and executed, you will see the following window. When you press the Add Customer button you will see the following view. When the user leaves any field empty, then it will become highlighted and the save button will become disabled. 38 Lectures 2 hours Skillbakerystudios 22 Lectures 1 hours CLEMENT OCHIENG 14 Lectures 2 hours DevTechie Print Add Notes Bookmark this page
[ { "code": null, "e": 2116, "s": 1942, "text": "In this chapter, we will learn about validations. We will also look at a clean way to do validation with what WPF bindings already support but tying it into MVVM components." }, { "code": null, "e": 2225, "s": 2116, "text": "When your application starts accepting data input from end users you need to consider validating that input." }, { "code": null, "e": 2334, "s": 2225, "text": "When your application starts accepting data input from end users you need to consider validating that input." }, { "code": null, "e": 2386, "s": 2334, "text": "Make sure it conforms to your overall requirements." }, { "code": null, "e": 2438, "s": 2386, "text": "Make sure it conforms to your overall requirements." }, { "code": null, "e": 2583, "s": 2438, "text": "WPF has some great builds and features in the binding system for validating input and you can still leverage all those features when doing MVVM." }, { "code": null, "e": 2728, "s": 2583, "text": "WPF has some great builds and features in the binding system for validating input and you can still leverage all those features when doing MVVM." }, { "code": null, "e": 2902, "s": 2728, "text": "Keep in mind that the logic that supports your validation and defines what rules exist for what properties should be part of the Model or the ViewModel, not the View itself." }, { "code": null, "e": 3076, "s": 2902, "text": "Keep in mind that the logic that supports your validation and defines what rules exist for what properties should be part of the Model or the ViewModel, not the View itself." }, { "code": null, "e": 3183, "s": 3076, "text": "You can still use all the ways of expressing validation that are supported by WPF data binding including −" }, { "code": null, "e": 3225, "s": 3183, "text": "Throwing exceptions on a property is set." }, { "code": null, "e": 3268, "s": 3225, "text": "Implementing the IDataErrorInfo interface." }, { "code": null, "e": 3303, "s": 3268, "text": "Implementing INotifyDataErrorInfo." }, { "code": null, "e": 3329, "s": 3303, "text": "Use WPF validation rules." }, { "code": null, "e": 3677, "s": 3329, "text": "In general, INotifyDataErrorInfo is recommended and was introduced to WPF .net 4.5 and it supports querying the object for errors associated with properties and it also fixes a couple of deficiencies with all the other options. Specifically, it allows asynchronous validation. It allows properties to have more than one error associated with them." }, { "code": null, "e": 3984, "s": 3677, "text": "Let’s take a look at an example in which we will add validation support to our input view, and in large application you will probably need this a number of places in your application. Sometimes on Views, sometimes on ViewModels and sometimes on these helper objects there are wrappers around model objects." }, { "code": null, "e": 4115, "s": 3984, "text": "It’s a good practice for putting the validation support in a common base class that you can then inherit from different scenarios." }, { "code": null, "e": 4227, "s": 4115, "text": "The base class will support INotifyDataErrorInfo so that that validation gets triggered when properties change." }, { "code": null, "e": 4440, "s": 4227, "text": "Create add a new class called ValidatableBindableBase. Since we already have a base class for a property change handling, let’s derive the base class from it and also implement the INotifyDataErrorInfo interface." }, { "code": null, "e": 4506, "s": 4440, "text": "Following is the implementation of ValidatableBindableBase class." }, { "code": null, "e": 6247, "s": 4506, "text": "using System; \nusing System.Collections.Generic; \nusing System.ComponentModel; \n\n//using System.ComponentModel.DataAnnotations; \nusing System.Linq; \nusing System.Runtime.CompilerServices; \nusing System.Text;\nusing System.Threading.Tasks; \nusing System.Windows.Controls;\n\nnamespace MVVMHierarchiesDemo { \n\n public class ValidatableBindableBase : BindableBase, INotifyDataErrorInfo { \n private Dictionary<string, List<string>> _errors = new Dictionary<string, List<string>>();\n\n public event EventHandler<DataErrorsChangedEventArgs> \n ErrorsChanged = delegate { };\n\n public System.Collections.IEnumerable GetErrors(string propertyName) {\n\t\t\n if (_errors.ContainsKey(propertyName)) \n return _errors[propertyName]; \n else \n return null; \n }\n \n public bool HasErrors { \n get { return _errors.Count > 0; } \n }\n\t\t\n protected override void SetProperty<T>(ref T member, T val, \n [CallerMemberName] string propertyName = null) {\n\t\t\n base.SetProperty<T>(ref member, val, propertyName);\n ValidateProperty(propertyName, val);\n }\n\t\t\n private void ValidateProperty<T>(string propertyName, T value) {\n var results = new List<ValidationResult>();\n\t\t\t\n //ValidationContext context = new ValidationContext(this); \n //context.MemberName = propertyName;\n //Validator.TryValidateProperty(value, context, results);\n\n if (results.Any()) {\n //_errors[propertyName] = results.Select(c => c.ErrorMessage).ToList(); \n } else { \n _errors.Remove(propertyName); \n }\n\t\t\t\n ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName)); \n } \n } \n}" }, { "code": null, "e": 6378, "s": 6247, "text": "Now add AddEditCustomerView and AddEditCustomerViewModel in respective folders. Following is the code of AddEditCustomerView.xaml." }, { "code": null, "e": 10652, "s": 6378, "text": "<UserControl x:Class = \"MVVMHierarchiesDemo.Views.AddEditCustomerView\"\n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:local = \"clr-namespace:MVVMHierarchiesDemo.Views\" \n mc:Ignorable = \"d\" \n d:DesignHeight = \"300\" d:DesignWidth = \"300\">\n\t\n <Grid> \n <Grid.RowDefinitions> \n <RowDefinition Height = \"Auto\" /> \n <RowDefinition Height = \"Auto\" />\n </Grid.RowDefinitions>\n\t\t\n <Grid x:Name = \"grid1\" \n HorizontalAlignment = \"Left\" \n DataContext = \"{Binding Customer}\" \n Margin = \"10,10,0,0\" \n VerticalAlignment = \"Top\">\n\t\t\t\n <Grid.ColumnDefinitions> \n <ColumnDefinition Width = \"Auto\" /> \n <ColumnDefinition Width = \"Auto\" /> \n </Grid.ColumnDefinitions>\n\t\t\n <Grid.RowDefinitions> \n <RowDefinition Height = \"Auto\" /> \n <RowDefinition Height = \"Auto\" /> \n <RowDefinition Height = \"Auto\" /> \n <RowDefinition Height = \"Auto\" /> \n </Grid.RowDefinitions>\n\t\t\n <Label Content = \"First Name:\" \n Grid.Column = \"0\" \n HorizontalAlignment = \"Left\" \n Margin = \"3\" \n Grid.Row = \"0\" \n VerticalAlignment = \"Center\" />\n\t\t\t\n <TextBox x:Name = \"firstNameTextBox\" \n Grid.Column = \"1\" \n HorizontalAlignment = \"Left\" \n Height = \"23\" \n Margin = \"3\" \n Grid.Row = \"0\" \n Text = \"{Binding FirstName, ValidatesOnNotifyDataErrors = True}\"\n VerticalAlignment = \"Center\" \n Width = \"120\" />\n\t\t\t\n <Label Content = \"Last Name:\" \n Grid.Column = \"0\" \n HorizontalAlignment = \"Left\" \n Margin = \"3\" \n Grid.Row = \"1\" \n VerticalAlignment = \"Center\" /> \n\t\t\t\n <TextBox x:Name = \"lastNameTextBox\"\n Grid.Column = \"1\" \n HorizontalAlignment = \"Left\" \n Height = \"23\" \n Margin = \"3\" \n Grid.Row = \"1\" \n Text = \"{Binding LastName, ValidatesOnNotifyDataErrors = True}\"\n VerticalAlignment = \"Center\" \n Width = \"120\" />\n\t\t\t\n <Label Content = \"Email:\" \n Grid.Column = \"0\" \n HorizontalAlignment = \"Left\" \n Margin = \"3\" \n Grid.Row = \"2\" \n VerticalAlignment = \"Center\" />\n\t\t\t\n <TextBox x:Name = \"emailTextBox\" \n Grid.Column = \"1\" \n HorizontalAlignment = \"Left\" \n Height = \"23\" \n Margin = \"3\" \n Grid.Row = \"2\" \n Text = \"{Binding Email, ValidatesOnNotifyDataErrors = True}\"\n VerticalAlignment = \"Center\" \n Width = \"120\" />\n\t\t\t\n <Label Content = \"Phone:\" \n Grid.Column = \"0\" \n HorizontalAlignment = \"Left\" \n Margin = \"3\" \n Grid.Row = \"3\" \n VerticalAlignment = \"Center\" />\n\t\t\t\n <TextBox x:Name = \"phoneTextBox\" \n Grid.Column = \"1\" \n HorizontalAlignment = \"Left\" \n Height = \"23\" \n Margin = \"3\" \n Grid.Row = \"3\" \n Text = \"{Binding Phone, ValidatesOnNotifyDataErrors = True}\"\n VerticalAlignment = \"Center\" \n Width = \"120\" />\n\t\t\t\n </Grid> \n\n <Grid Grid.Row = \"1\"> \n <Button Content = \"Save\" \n Command = \"{Binding SaveCommand}\" \n HorizontalAlignment = \"Left\" \n Margin = \"25,5,0,0\" \n VerticalAlignment = \"Top\" \n Width = \"75\" />\n\t\t\n <Button Content = \"Add\" \n Command = \"{Binding SaveCommand}\" \n HorizontalAlignment = \"Left\" \n Margin = \"25,5,0,0\" \n VerticalAlignment = \"Top\" \n Width = \"75\" /> \n\t\t\n <Button Content = \"Cancel\" \n Command = \"{Binding CancelCommand}\" \n HorizontalAlignment = \"Left\" \n Margin = \"150,5,0,0\" \n VerticalAlignment = \"Top\" \n Width = \"75\" /> \n </Grid>\n\t\t\n </Grid> \n\t\n</UserControl>" }, { "code": null, "e": 10710, "s": 10652, "text": "Following is the AddEditCustomerViewModel implementation." }, { "code": null, "e": 12377, "s": 10710, "text": "using MVVMHierarchiesDemo.Model;\n\nusing System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Text; \nusing System.Threading.Tasks;\n\nnamespace MVVMHierarchiesDemo.ViewModel { \n\n class AddEditCustomerViewModel : BindableBase { \n\t\n public AddEditCustomerViewModel() {\n CancelCommand = new MyIcommand(OnCancel); \n SaveCommand = new MyIcommand(OnSave, CanSave); \n } \n\t\t\n private bool _EditMode; \n\t\t\n public bool EditMode { \n get { return _EditMode; } \n set { SetProperty(ref _EditMode, value);} \n }\n\t\t\n private SimpleEditableCustomer _Customer;\n\t\t\n public SimpleEditableCustomer Customer { \n get { return _Customer; } \n set { SetProperty(ref _Customer, value);} \n }\n\n private Customer _editingCustomer = null;\n\t\t\n public void SetCustomer(Customer cust) {\n _editingCustomer = cust; \n\t\t\t\n if (Customer != null) Customer.ErrorsChanged -= RaiseCanExecuteChanged; \n Customer = new SimpleEditableCustomer();\n Customer.ErrorsChanged += RaiseCanExecuteChanged;\n CopyCustomer(cust, Customer); \n }\n\t\t\n private void RaiseCanExecuteChanged(object sender, EventArgs e) { \n SaveCommand.RaiseCanExecuteChanged(); \n }\n\n public MyIcommand CancelCommand { get; private set; }\n public MyIcommand SaveCommand { get; private set; }\n\n public event Action Done = delegate { };\n\t\t\n private void OnCancel() { \n Done(); \n }\n\n private async void OnSave() { \n Done(); \n }\n\t\t\n private bool CanSave() { \n return !Customer.HasErrors; \n } \n } \n}" }, { "code": null, "e": 12442, "s": 12377, "text": "Following is the implementation of SimpleEditableCustomer class." }, { "code": null, "e": 13540, "s": 12442, "text": "using System;\nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Text; \nusing System.Threading.Tasks;\n\nnamespace MVVMHierarchiesDemo.Model { \n\n public class SimpleEditableCustomer : ValidatableBindableBase { \n private Guid _id; \n\t\t\n public Guid Id { \n get { return _id; } \n set { SetProperty(ref _id, value); } \n }\n\t\t\n private string _firstName; \n [Required]\n\t\t\n public string FirstName { \n get { return _firstName; } \n set { SetProperty(ref _firstName, value); } \n }\n\t\t\n private string _lastName; \n [Required] \n\t\t\n public string LastName { \n get { return _lastName; } \n set { SetProperty(ref _lastName, value); } \n }\n\t\t\n private string _email; \n [EmailAddress] \n\t\t\n public string Email {\n get { return _email; } \n set { SetProperty(ref _email, value); } \n }\n\t\t\n private string _phone; \n [Phone] \n\t\t\n public string Phone { \n get { return _phone; } \n set { SetProperty(ref _phone, value); } \n } \n } \n}" }, { "code": null, "e": 13621, "s": 13540, "text": "When the above code is compiled and executed, you will see the following window." }, { "code": null, "e": 13805, "s": 13621, "text": "When you press the Add Customer button you will see the following view. When the user leaves any field empty, then it will become highlighted and the save button will become disabled." }, { "code": null, "e": 13838, "s": 13805, "text": "\n 38 Lectures \n 2 hours \n" }, { "code": null, "e": 13858, "s": 13838, "text": " Skillbakerystudios" }, { "code": null, "e": 13891, "s": 13858, "text": "\n 22 Lectures \n 1 hours \n" }, { "code": null, "e": 13908, "s": 13891, "text": " CLEMENT OCHIENG" }, { "code": null, "e": 13941, "s": 13908, "text": "\n 14 Lectures \n 2 hours \n" }, { "code": null, "e": 13952, "s": 13941, "text": " DevTechie" }, { "code": null, "e": 13959, "s": 13952, "text": " Print" }, { "code": null, "e": 13970, "s": 13959, "text": " Add Notes" } ]
How to Change Contrast in OpenCV using C++?
Changing brightness and contrast are frequent editing effect in image processing.Here, we will learn how to change the contrast of images. Contrast controls the sharpness of the image. Higher the contrast the sharper the image, lower the contrast the smother the image. Changing the contrast means increasing the weight of the pixels. More the contrast, sharper the image is. To change the contrast, multiply the pixel values with some constant. For example, if multiply all the pixel values of an image by 2, then the pixel's value will be doubled, and the image will look sharper. The following program demonstrates how to change the contrast of an image in OpenCV. #include<iostream> #include<opencv2/highgui/highgui.hpp> using namespace cv; using namespace std; int main() { Mat original;//Declaring a matrix to load the original image// Mat contrast;//Declaring a matrix to load the image after changing the brightness// namedWindow("Original");//Declaring window to show the original image// namedWindow("Contrast");//Declaring window for edited image// original = imread("mountain.jpg");//loading the image original.convertTo(contrast, -1, 2, 0);//changing contrast// imshow("Original", original);//showing original image// imshow("Contrast", contrast);//showing edited image// waitKey(0);//wait for keystroke// return(0); }
[ { "code": null, "e": 1332, "s": 1062, "text": "Changing brightness and contrast are frequent editing effect in image processing.Here, we will learn how to change the contrast of images. Contrast controls the sharpness of the image. Higher the contrast the sharper the image, lower the contrast the smother the image." }, { "code": null, "e": 1645, "s": 1332, "text": "Changing the contrast means increasing the weight of the pixels. More the contrast, sharper the image is. To change the contrast, multiply the pixel values with some constant. For example, if multiply all the pixel values of an image by 2, then the pixel's value will be doubled, and the image will look sharper." }, { "code": null, "e": 1730, "s": 1645, "text": "The following program demonstrates how to change the contrast of an image in OpenCV." }, { "code": null, "e": 2424, "s": 1730, "text": "#include<iostream>\n#include<opencv2/highgui/highgui.hpp>\nusing namespace cv;\nusing namespace std;\nint main() {\n Mat original;//Declaring a matrix to load the original image//\n Mat contrast;//Declaring a matrix to load the image after changing the brightness//\n namedWindow(\"Original\");//Declaring window to show the original image//\n namedWindow(\"Contrast\");//Declaring window for edited image//\n original = imread(\"mountain.jpg\");//loading the image\n original.convertTo(contrast, -1, 2, 0);//changing contrast//\n imshow(\"Original\", original);//showing original image//\n imshow(\"Contrast\", contrast);//showing edited image//\n waitKey(0);//wait for keystroke//\n return(0);\n}" } ]
Java Program to convert LocalDate to java.util.Date in UTC
Set the LocalDate to the current date − LocalDate date = LocalDate.now(); Convert to java.util.Date in UTC − Date.from(date.atStartOfDay().toInstant(ZoneOffset.UTC)) Live Demo import java.time.LocalDate; import java.time.ZoneOffset; import java.util.Date; public class Demo { public static void main(String[] args) { LocalDate date = LocalDate.now(); System.out.println("Date = "+date); System.out.println("Date (UTC) = "+Date.from(date.atStartOfDay().toInstant(ZoneOffset.UTC))); } } Date = 2019-04-19 Date (UTC) = Fri Apr 19 05:30:00 IST 2019
[ { "code": null, "e": 1102, "s": 1062, "text": "Set the LocalDate to the current date −" }, { "code": null, "e": 1136, "s": 1102, "text": "LocalDate date = LocalDate.now();" }, { "code": null, "e": 1171, "s": 1136, "text": "Convert to java.util.Date in UTC −" }, { "code": null, "e": 1228, "s": 1171, "text": "Date.from(date.atStartOfDay().toInstant(ZoneOffset.UTC))" }, { "code": null, "e": 1239, "s": 1228, "text": " Live Demo" }, { "code": null, "e": 1572, "s": 1239, "text": "import java.time.LocalDate;\nimport java.time.ZoneOffset;\nimport java.util.Date;\npublic class Demo {\n public static void main(String[] args) {\n LocalDate date = LocalDate.now();\n System.out.println(\"Date = \"+date);\n System.out.println(\"Date (UTC) = \"+Date.from(date.atStartOfDay().toInstant(ZoneOffset.UTC)));\n }\n}" }, { "code": null, "e": 1632, "s": 1572, "text": "Date = 2019-04-19\nDate (UTC) = Fri Apr 19 05:30:00 IST 2019" } ]
Recursive Program for Binary to Decimal in C++
We are given a string containing a binary number. The goal is to find the equivalent decimal number using the recursive method. A binary number can be converted to decimal using following method-: Traverse from LSB to MSB and multiply each with power of 2i Where 0<=i<=no. of digits and all previous results to it. Input − binStr[] = "110010" Output − Equivalent Decimal of given binary: 50 Explanation−If we convert 110010 to decimal then number will be:- = 0*20 +1*21+0*22+0*23+1*24+1*25 = 0+2+0+0+16+32 = 50 Input − binStr[] = "0011" Output − Equivalent Decimal of given binary: 3 Explanation − If we convert 110010 to decimal then number will be:- = 1*20+1*21 +0*22 +0*23 = 1+2+0+0 = 3 In this approach we are using the recursive function bintoDecimal(strBin,length) which takes input string and its length and for each character convert it to decimal and multiply it with 2i . Add previous results to it. Take the input string strBin[] containing a binary number. Take the input string strBin[] containing a binary number. Calculate its length using strlen(strBin). Calculate its length using strlen(strBin). Function bintoDecimal(strBin,length) takes input and returns the number calculated using a recursive approach. Function bintoDecimal(strBin,length) takes input and returns the number calculated using a recursive approach. If we are at last characterwhich is LSB, then return its decimal as it will be the same. (multiplied with 1 i.e 20 ) If we are at last characterwhich is LSB, then return its decimal as it will be the same. (multiplied with 1 i.e 20 ) Otherwise set temp=binary[i]-'0'. Its decimal value. Otherwise set temp=binary[i]-'0'. Its decimal value. Now multiply temp with 2len-i-1 using temp<<len-i-1. Now multiply temp with 2len-i-1 using temp<<len-i-1. Add the result of other digits to temp using temp=temp+bintoDecimal(binary,len,i+1). Add the result of other digits to temp using temp=temp+bintoDecimal(binary,len,i+1). At the end of recursion return temp. At the end of recursion return temp. Print the calculated decimal in main. Print the calculated decimal in main. #include<bits/stdc++.h> using namespace std; int bintoDecimal(char binary[],int len, int i=0){ if (i == len-1) return (binary[i] - '0'); int temp=binary[i]-'0'; temp=temp<<len-i-1; temp=temp+bintoDecimal(binary,len,i+1); return (temp); } int main(){ char strBin[] = "11010"; int length=strlen(strBin); cout <<"Equivalent Decimal of given binary: "<<bintoDecimal(strBin,length) << endl; return 0; } If we run the above code it will generate the following Output Equivalent Decimal of given binary: 26
[ { "code": null, "e": 1190, "s": 1062, "text": "We are given a string containing a binary number. The goal is to find the equivalent decimal number using the recursive method." }, { "code": null, "e": 1377, "s": 1190, "text": "A binary number can be converted to decimal using following method-:\nTraverse from LSB to MSB and multiply each with power of 2i Where 0<=i<=no. of digits and all previous results to it." }, { "code": null, "e": 1405, "s": 1377, "text": "Input − binStr[] = \"110010\"" }, { "code": null, "e": 1453, "s": 1405, "text": "Output − Equivalent Decimal of given binary: 50" }, { "code": null, "e": 1519, "s": 1453, "text": "Explanation−If we convert 110010 to decimal then number will be:-" }, { "code": null, "e": 1552, "s": 1519, "text": "= 0*20 +1*21+0*22+0*23+1*24+1*25" }, { "code": null, "e": 1568, "s": 1552, "text": "= 0+2+0+0+16+32" }, { "code": null, "e": 1573, "s": 1568, "text": "= 50" }, { "code": null, "e": 1599, "s": 1573, "text": "Input − binStr[] = \"0011\"" }, { "code": null, "e": 1646, "s": 1599, "text": "Output − Equivalent Decimal of given binary: 3" }, { "code": null, "e": 1714, "s": 1646, "text": "Explanation − If we convert 110010 to decimal then number will be:-" }, { "code": null, "e": 1738, "s": 1714, "text": "= 1*20+1*21 +0*22 +0*23" }, { "code": null, "e": 1748, "s": 1738, "text": "= 1+2+0+0" }, { "code": null, "e": 1752, "s": 1748, "text": "= 3" }, { "code": null, "e": 1972, "s": 1752, "text": "In this approach we are using the recursive function bintoDecimal(strBin,length) which takes input string and its length and for each character convert it to decimal and multiply it with 2i . Add previous results to it." }, { "code": null, "e": 2031, "s": 1972, "text": "Take the input string strBin[] containing a binary number." }, { "code": null, "e": 2090, "s": 2031, "text": "Take the input string strBin[] containing a binary number." }, { "code": null, "e": 2133, "s": 2090, "text": "Calculate its length using strlen(strBin)." }, { "code": null, "e": 2176, "s": 2133, "text": "Calculate its length using strlen(strBin)." }, { "code": null, "e": 2287, "s": 2176, "text": "Function bintoDecimal(strBin,length) takes input and returns the number calculated using a recursive approach." }, { "code": null, "e": 2398, "s": 2287, "text": "Function bintoDecimal(strBin,length) takes input and returns the number calculated using a recursive approach." }, { "code": null, "e": 2515, "s": 2398, "text": "If we are at last characterwhich is LSB, then return its decimal as it will be the same. (multiplied with 1 i.e 20 )" }, { "code": null, "e": 2632, "s": 2515, "text": "If we are at last characterwhich is LSB, then return its decimal as it will be the same. (multiplied with 1 i.e 20 )" }, { "code": null, "e": 2685, "s": 2632, "text": "Otherwise set temp=binary[i]-'0'. Its decimal value." }, { "code": null, "e": 2738, "s": 2685, "text": "Otherwise set temp=binary[i]-'0'. Its decimal value." }, { "code": null, "e": 2791, "s": 2738, "text": "Now multiply temp with 2len-i-1 using temp<<len-i-1." }, { "code": null, "e": 2844, "s": 2791, "text": "Now multiply temp with 2len-i-1 using temp<<len-i-1." }, { "code": null, "e": 2929, "s": 2844, "text": "Add the result of other digits to temp using temp=temp+bintoDecimal(binary,len,i+1)." }, { "code": null, "e": 3014, "s": 2929, "text": "Add the result of other digits to temp using temp=temp+bintoDecimal(binary,len,i+1)." }, { "code": null, "e": 3051, "s": 3014, "text": "At the end of recursion return temp." }, { "code": null, "e": 3088, "s": 3051, "text": "At the end of recursion return temp." }, { "code": null, "e": 3126, "s": 3088, "text": "Print the calculated decimal in main." }, { "code": null, "e": 3164, "s": 3126, "text": "Print the calculated decimal in main." }, { "code": null, "e": 3593, "s": 3164, "text": "#include<bits/stdc++.h>\nusing namespace std;\nint bintoDecimal(char binary[],int len, int i=0){\n if (i == len-1)\n return (binary[i] - '0');\n\n int temp=binary[i]-'0';\n temp=temp<<len-i-1;\n temp=temp+bintoDecimal(binary,len,i+1);\n return (temp);\n}\nint main(){\n char strBin[] = \"11010\";\n int length=strlen(strBin);\n cout <<\"Equivalent Decimal of given binary: \"<<bintoDecimal(strBin,length) << endl;\n return 0;\n}" }, { "code": null, "e": 3656, "s": 3593, "text": "If we run the above code it will generate the following Output" }, { "code": null, "e": 3695, "s": 3656, "text": "Equivalent Decimal of given binary: 26" } ]
RSA Cipher Encryption
In this chapter, we will focus on different implementation of RSA cipher encryption and the functions involved for the same. You can refer or include this python file for implementing RSA cipher algorithm implementation. The modules included for the encryption algorithm are as follows − from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP from Crypto.Signature import PKCS1_v1_5 from Crypto.Hash import SHA512, SHA384, SHA256, SHA, MD5 from Crypto import Random from base64 import b64encode, b64decode hash = "SHA-256" We have initialized the hash value as SHA-256 for better security purpose. We will use a function to generate new keys or a pair of public and private key using the following code. def newkeys(keysize): random_generator = Random.new().read key = RSA.generate(keysize, random_generator) private, public = key, key.publickey() return public, private def importKey(externKey): return RSA.importKey(externKey) For encryption, the following function is used which follows the RSA algorithm − def encrypt(message, pub_key): cipher = PKCS1_OAEP.new(pub_key) return cipher.encrypt(message) Two parameters are mandatory: message and pub_key which refers to Public key. A public key is used for encryption and private key is used for decryption. The complete program for encryption procedure is mentioned below − from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP from Crypto.Signature import PKCS1_v1_5 from Crypto.Hash import SHA512, SHA384, SHA256, SHA, MD5 from Crypto import Random from base64 import b64encode, b64decode hash = "SHA-256" def newkeys(keysize): random_generator = Random.new().read key = RSA.generate(keysize, random_generator) private, public = key, key.publickey() return public, private def importKey(externKey): return RSA.importKey(externKey) def getpublickey(priv_key): return priv_key.publickey() def encrypt(message, pub_key): cipher = PKCS1_OAEP.new(pub_key) return cipher.encrypt(message) 10 Lectures 2 hours Total Seminars 10 Lectures 2 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2513, "s": 2292, "text": "In this chapter, we will focus on different implementation of RSA cipher encryption and the functions involved for the same. You can refer or include this python file for implementing RSA cipher algorithm implementation." }, { "code": null, "e": 2580, "s": 2513, "text": "The modules included for the encryption algorithm are as follows −" }, { "code": null, "e": 2830, "s": 2580, "text": "from Crypto.PublicKey import RSA\nfrom Crypto.Cipher import PKCS1_OAEP\nfrom Crypto.Signature import PKCS1_v1_5\nfrom Crypto.Hash import SHA512, SHA384, SHA256, SHA, MD5\nfrom Crypto import Random\nfrom base64 import b64encode, b64decode\nhash = \"SHA-256\"" }, { "code": null, "e": 3011, "s": 2830, "text": "We have initialized the hash value as SHA-256 for better security purpose. We will use a function to generate new keys or a pair of public and private key using the following code." }, { "code": null, "e": 3252, "s": 3011, "text": "def newkeys(keysize):\n random_generator = Random.new().read\n key = RSA.generate(keysize, random_generator)\n private, public = key, key.publickey()\n return public, private\ndef importKey(externKey):\n return RSA.importKey(externKey)\n" }, { "code": null, "e": 3333, "s": 3252, "text": "For encryption, the following function is used which follows the RSA algorithm −" }, { "code": null, "e": 3435, "s": 3333, "text": "def encrypt(message, pub_key):\n cipher = PKCS1_OAEP.new(pub_key)\n return cipher.encrypt(message)\n" }, { "code": null, "e": 3589, "s": 3435, "text": "Two parameters are mandatory: message and pub_key which refers to Public key. A public key is used for encryption and private key is used for decryption." }, { "code": null, "e": 3656, "s": 3589, "text": "The complete program for encryption procedure is mentioned below −" }, { "code": null, "e": 4310, "s": 3656, "text": "from Crypto.PublicKey import RSA\nfrom Crypto.Cipher import PKCS1_OAEP\nfrom Crypto.Signature import PKCS1_v1_5\nfrom Crypto.Hash import SHA512, SHA384, SHA256, SHA, MD5\nfrom Crypto import Random\nfrom base64 import b64encode, b64decode\nhash = \"SHA-256\"\n\ndef newkeys(keysize):\n random_generator = Random.new().read\n key = RSA.generate(keysize, random_generator)\n private, public = key, key.publickey()\n return public, private\n\ndef importKey(externKey):\n return RSA.importKey(externKey)\n\ndef getpublickey(priv_key):\n return priv_key.publickey()\n\ndef encrypt(message, pub_key):\n cipher = PKCS1_OAEP.new(pub_key)\n return cipher.encrypt(message)" }, { "code": null, "e": 4343, "s": 4310, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 4359, "s": 4343, "text": " Total Seminars" }, { "code": null, "e": 4392, "s": 4359, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 4415, "s": 4392, "text": " Stone River ELearning" }, { "code": null, "e": 4422, "s": 4415, "text": " Print" }, { "code": null, "e": 4433, "s": 4422, "text": " Add Notes" } ]
The __index metamethod in Lua Programming
Whenever we try to access a field that hasn’t been declared in a table in Lua, the answer we get is nil. While this is true, but the reason for it is that when such access happens, the interpreter triggers a search for an __index metamethod and if it doesn’t find any method named __index, then we get nil as an answer; else we will get whatever the value of the field is set in the __index metamethod. We can explicitly put in the __index method in a table and provide it the named values that we want it to return instead of nil. Let’s consider an example. We will create several tables describing windows. Each table will describe several parameters like size, height, width of the window; and we will also have a default constructor to create a table which is initially empty and all the fields are not-set. Live Demo Window = {} Window.prototype = {x=0, y=0, width=50, height=70, } Window.mt = {} function Window.new (o) setmetatable(o, Window.mt) return o end w = Window.new{x=10, y=20} print(w.x) print(w.width) print(w.height) In the above example, we are trying to print the value of three different fields of the Window, the x, the width, and the height. We know that when we create a new object using the constructor, we pass the value of x, so x will not be nil, but since we didn’t tell Lua about the values of the width and height of the window object w, we will get nil. 10 nil nil Now, we can explicitly create a __index method in the above code to tell the interpreter that we need it to return our value instead of nil, in case it doesn’t find the field in the table. Consider the example shown below − Live Demo Window = {} Window.prototype = {x=0, y=0, width=50, height=70, } Window.mt = {} function Window.new (o) setmetatable(o, Window.mt) return o end Window.mt.__index = function (table, key) return Window.prototype[key] end w = Window.new{x=10, y=20} print(w.x) print(w.width) print(w.height) 10 50 70
[ { "code": null, "e": 1465, "s": 1062, "text": "Whenever we try to access a field that hasn’t been declared in a table in Lua, the answer we get is nil. While this is true, but the reason for it is that when such access happens, the interpreter triggers a search for an __index metamethod and if it doesn’t find any method named __index, then we get nil as an answer; else we will get whatever the value of the field is set in the __index metamethod." }, { "code": null, "e": 1594, "s": 1465, "text": "We can explicitly put in the __index method in a table and provide it the named values that we want it to return instead of nil." }, { "code": null, "e": 1874, "s": 1594, "text": "Let’s consider an example. We will create several tables describing windows. Each table will describe several parameters like size, height, width of the window; and we will also have a default constructor to create a table which is initially empty and all the fields are not-set." }, { "code": null, "e": 1885, "s": 1874, "text": " Live Demo" }, { "code": null, "e": 2104, "s": 1885, "text": "Window = {}\nWindow.prototype = {x=0, y=0, width=50, height=70, }\nWindow.mt = {}\nfunction Window.new (o)\n setmetatable(o, Window.mt)\n return o\nend\nw = Window.new{x=10, y=20}\nprint(w.x)\nprint(w.width)\nprint(w.height)" }, { "code": null, "e": 2455, "s": 2104, "text": "In the above example, we are trying to print the value of three different fields of the Window, the x, the width, and the height. We know that when we create a new object using the constructor, we pass the value of x, so x will not be nil, but since we didn’t tell Lua about the values of the width and height of the window object w, we will get nil." }, { "code": null, "e": 2466, "s": 2455, "text": "10\nnil\nnil" }, { "code": null, "e": 2655, "s": 2466, "text": "Now, we can explicitly create a __index method in the above code to tell the interpreter that we need it to return our value instead of nil, in case it doesn’t find the field in the table." }, { "code": null, "e": 2690, "s": 2655, "text": "Consider the example shown below −" }, { "code": null, "e": 2701, "s": 2690, "text": " Live Demo" }, { "code": null, "e": 2998, "s": 2701, "text": "Window = {}\nWindow.prototype = {x=0, y=0, width=50, height=70, }\nWindow.mt = {}\nfunction Window.new (o)\n setmetatable(o, Window.mt)\n return o\nend\nWindow.mt.__index = function (table, key)\n return Window.prototype[key]\nend\nw = Window.new{x=10, y=20}\nprint(w.x)\nprint(w.width)\nprint(w.height)" }, { "code": null, "e": 3007, "s": 2998, "text": "10\n50\n70" } ]
How to design Responsive card-deck with fixed width in Bootstrap ?
01 Jun, 2020 Bootstrap card provide us a lot of functionality that we can play around. We can also make them responsive and also of fixed size all depends on our need. So the code for the fixed size bootstrap card deck is given below. We have provided the code without using CSS properties so it looks much simpler and easier to understand. In this article, we will use some Bootstrap classes to design responsive card. Also you can look for the code for how to create a card and then use it according to your need. You can modify the pictures using img tag given inside the card class div. Example 1: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title> How to design Responsive card-deck with fixed width in Bootstrap ? </title> <!-- bootstrap linked--> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"></head> <body> <!-- Card design with bootstrap class mx-auto for making it centered in the div--> <div class="card mx-auto" style="width:18rem;"> <img class="card-img-top" src="https://media.geeksforgeeks.org/wp-content/uploads/20200529212604/geeks.png" alt="Card image cap"> <div class="card-body"> <h5 class="card-title"> GeeksforGeeks </h5> <p class="card-text"> Geeks for Geeks is the best place to improve your computer science knowledge. </p> <a href="#" class="btn btn-success"> Click me </a> </div> </div> <!--card end here--> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"> </script></body> </html> Output: Example 2: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title> How to design Responsive card-deck with fixed width in Bootstrap ? </title> <!-- bootstrap linked--> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"></head> <body> <div class="container-fluid p-0 m-0 align-items-center justify-content-center d-flex" style="min-height: 100vh; background-color: #498433;"> <!-- Row for the card--> <div class="row w-100 p-0 w-0"> <!-- Column for card--> <div class="col-lg-4 mb-2"> <div class="card mx-auto" style="width:18rem;"> <img class="card-img-top" src="https://media.geeksforgeeks.org/wp-content/uploads/20200529212604/geeks.png" alt="Card image cap"> <div class="card-body"> <h5 class="card-title"> Geeks for Geeks </h5> <p class="card-text"> Geeks for Geeks is the best place to improve your computer science knowledge. </p> <a href="#" class="btn btn-success"> Click me </a> </div> </div> </div> <!-- Another column for card --> <div class="col-lg-4 mb-2"> <div class="card mx-auto" style="width:18rem;"> <img class="card-img-top" src="https://media.geeksforgeeks.org/wp-content/uploads/20200529212604/geeks.png" alt="Card image cap"> <div class="card-body"> <h5 class="card-title"> Geeks for Geeks </h5> <p class="card-text"> Geeks for Geeks is the best place to improve your computer science knowledge. </p> <a href="#" class="btn btn-success"> Click me </a> </div> </div> </div> <!-- Another column for card --> <div class="col-lg-4 mb-2"> <div class="card mx-auto" style="width:18rem;"> <img class="card-img-top" src="https://media.geeksforgeeks.org/wp-content/uploads/20200529212604/geeks.png" alt="Card image cap"> <div class="card-body"> <h5 class="card-title"> Geeks for Geeks </h5> <p class="card-text"> Geeks for Geeks is the best place to improve your computer science knowledge. </p> <a href="#" class="btn btn-success"> Click me </a> </div> </div> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"> </script></body> </html> Output: Note: Example 1 represents how to make a single card while example 2 represents how to embed that card efficiently such that it is responsive. Bootstrap-4 Bootstrap-Misc HTML-Misc Picked Bootstrap HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Jun, 2020" }, { "code": null, "e": 356, "s": 28, "text": "Bootstrap card provide us a lot of functionality that we can play around. We can also make them responsive and also of fixed size all depends on our need. So the code for the fixed size bootstrap card deck is given below. We have provided the code without using CSS properties so it looks much simpler and easier to understand." }, { "code": null, "e": 436, "s": 356, "text": "In this article, we will use some Bootstrap classes to design responsive card. " }, { "code": null, "e": 607, "s": 436, "text": "Also you can look for the code for how to create a card and then use it according to your need. You can modify the pictures using img tag given inside the card class div." }, { "code": null, "e": 619, "s": 607, "text": "Example 1: " }, { "code": null, "e": 624, "s": 619, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title> How to design Responsive card-deck with fixed width in Bootstrap ? </title> <!-- bootstrap linked--> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\"></head> <body> <!-- Card design with bootstrap class mx-auto for making it centered in the div--> <div class=\"card mx-auto\" style=\"width:18rem;\"> <img class=\"card-img-top\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200529212604/geeks.png\" alt=\"Card image cap\"> <div class=\"card-body\"> <h5 class=\"card-title\"> GeeksforGeeks </h5> <p class=\"card-text\"> Geeks for Geeks is the best place to improve your computer science knowledge. </p> <a href=\"#\" class=\"btn btn-success\"> Click me </a> </div> </div> <!--card end here--> <script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\" integrity=\"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" integrity=\"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" crossorigin=\"anonymous\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" integrity=\"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" crossorigin=\"anonymous\"> </script></body> </html>", "e": 2582, "s": 624, "text": null }, { "code": null, "e": 2590, "s": 2582, "text": "Output:" }, { "code": null, "e": 2601, "s": 2590, "text": "Example 2:" }, { "code": null, "e": 2606, "s": 2601, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title> How to design Responsive card-deck with fixed width in Bootstrap ? </title> <!-- bootstrap linked--> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\"></head> <body> <div class=\"container-fluid p-0 m-0 align-items-center justify-content-center d-flex\" style=\"min-height: 100vh; background-color: #498433;\"> <!-- Row for the card--> <div class=\"row w-100 p-0 w-0\"> <!-- Column for card--> <div class=\"col-lg-4 mb-2\"> <div class=\"card mx-auto\" style=\"width:18rem;\"> <img class=\"card-img-top\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200529212604/geeks.png\" alt=\"Card image cap\"> <div class=\"card-body\"> <h5 class=\"card-title\"> Geeks for Geeks </h5> <p class=\"card-text\"> Geeks for Geeks is the best place to improve your computer science knowledge. </p> <a href=\"#\" class=\"btn btn-success\"> Click me </a> </div> </div> </div> <!-- Another column for card --> <div class=\"col-lg-4 mb-2\"> <div class=\"card mx-auto\" style=\"width:18rem;\"> <img class=\"card-img-top\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200529212604/geeks.png\" alt=\"Card image cap\"> <div class=\"card-body\"> <h5 class=\"card-title\"> Geeks for Geeks </h5> <p class=\"card-text\"> Geeks for Geeks is the best place to improve your computer science knowledge. </p> <a href=\"#\" class=\"btn btn-success\"> Click me </a> </div> </div> </div> <!-- Another column for card --> <div class=\"col-lg-4 mb-2\"> <div class=\"card mx-auto\" style=\"width:18rem;\"> <img class=\"card-img-top\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200529212604/geeks.png\" alt=\"Card image cap\"> <div class=\"card-body\"> <h5 class=\"card-title\"> Geeks for Geeks </h5> <p class=\"card-text\"> Geeks for Geeks is the best place to improve your computer science knowledge. </p> <a href=\"#\" class=\"btn btn-success\"> Click me </a> </div> </div> </div> </div> </div> <script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\" integrity=\"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" integrity=\"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" crossorigin=\"anonymous\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" integrity=\"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" crossorigin=\"anonymous\"> </script></body> </html>", "e": 6882, "s": 2606, "text": null }, { "code": null, "e": 6890, "s": 6882, "text": "Output:" }, { "code": null, "e": 7033, "s": 6890, "text": "Note: Example 1 represents how to make a single card while example 2 represents how to embed that card efficiently such that it is responsive." }, { "code": null, "e": 7045, "s": 7033, "text": "Bootstrap-4" }, { "code": null, "e": 7060, "s": 7045, "text": "Bootstrap-Misc" }, { "code": null, "e": 7070, "s": 7060, "text": "HTML-Misc" }, { "code": null, "e": 7077, "s": 7070, "text": "Picked" }, { "code": null, "e": 7087, "s": 7077, "text": "Bootstrap" }, { "code": null, "e": 7092, "s": 7087, "text": "HTML" }, { "code": null, "e": 7109, "s": 7092, "text": "Web Technologies" }, { "code": null, "e": 7136, "s": 7109, "text": "Web technologies Questions" }, { "code": null, "e": 7141, "s": 7136, "text": "HTML" } ]
Types of Observables in RxJava
21 Sep, 2021 In the model-view paradigm, this class represents an observable object, or “data.” It can be subclassed in order to represent an object that the application wishes to watch. The issue is that you’re creating software that will render data describing a three-dimensional scene in two dimensions. The application must be modular and allow for numerous, concurrent views of the same scene. One or more observers can be assigned to an observable object. An observer can be any object that implements the Observer interface. When an observable instance changes, an application that calls the Observable’s notifyObservers() method notifies all of its observers of the change through a call to their update method. Image 1. The Observables in RxJava Explained. In simple terms, An Observable is analogous to a speaker that broadcasts the value. It does various tasks and generates some values. An Operator is similar to a translator in that it converts/modifies data from one form to another. An Observer is what fetches the value. The many types of Observables in RxJava are as follows: Observable Flowable Single Maybe Completable Let’s commence creating some Observables in RxJava to better understand this, Type #1: Creating a Basic Observable Use Case: Assume you are downloading a file and need to push the current status of the download. You will have to emit more than one value in this case. Kotlin fun downloadObserervable(): Observable<Int> { return Observable.create { gfgshooter -> // Declaring an emitter in name of gfgshooter. // Beginning the task (in this case a simple download) // Your code... if (!gfgshooter.isDisposed) { // emit the progress gfgshooter.onNext(20) } // Still Downloading if (!gfgshooter.isDisposed) { // send progress gfgshooter.onNext(80) } // Progress 100, Download Over if (!gfgshooter.isDisposed) { // send progress gfgshooter.onNext(100) // send onComplete gfgshooter.onComplete() } }} Type #2: Creating a Complex Obersever using Observable Kotlin fun getObserver(): Observer<Int> { return object : Observer<Int> { override fun onStart(d: Disposable) { // Observation Started // A sample editText editText.setText("onStart") } override fun onNext(progress: Int) { // Progress Updated editText.setText("onNext : $progress") } override fun onError(e: Throwable) { // Error Thrown editText.setText("onError : ${e.message}") } override fun onComplete() { // Observation Complete editText.setText("onComplete") } }} Observer <> Flowable When the Observable emits a large number of values that cannot be absorbed by the Observer, the Flowable comes into play. In this scenario, the Observable must skip some data based on a strategy, otherwise, it will throw an exception. A strategy is used by the Flowable Observable to handle the exception. BackPressureStrategy is the strategy, and MissingBackPressureException is the exception. Geek Tip: Just like type #1, you can create Flowable using Flowable.create() similarly. Solitary<> SingleObserver When an Observable must emit only one value, such as as a response to a network request, Single is used. Type #3: Creating Single Observable Kotlin fun singleObservable(): Single<String> { return Single.create { emitter -> // any code which has a task if (!gfgEmitter.isDisposed) { gfgEmitter.onSuccess("Spandan's Code Ran!") } }} Then use it with a single observable in the following manner: Kotlin fun singleObservable(): SingleObserver<String> { return object : SingleObserver<String> { override fun onSubscribe(d: Disposable) { edittext.setText("onStart") } override fun onSuccess(data: String) { // Successfully Executed editText.setText("onSuccess : $data") } override fun onError(e: Throwable) { // Error or Exception thrown. editText.setText("onError : ${e.message}") } }} The maybe <> Observer When the Observable must emit a value or no value, maybe is used. Type #4: Creating a maybe Observer Kotlin fun maybeObservable(): Maybe<String> { return Maybe.create { gfgemitter -> // your code goes here if (!gfgemitter.isDisposed) { gfgemitter.onSuccess("Spandan's Code!") } }} Completable <> CompletableObserver When the Observable must do some job without emitting a value, it is called a Completable. Type #5: Creating a Completable Observer Kotlin fun completeObservable(): Completable { return Completable.create { gfgemitter -> // your code here if (!gfgemitter.isDisposed) { gfgemitter.onComplete() } }} Using it now in the following manner: Kotlin fun completeObservable(): gfgObserver { return object : gfgObserver { override fun onStart(d: Disposable) { // Started editText.setText("Started") } override fun onError(e: Throwable) { // Exception Thrown editText.setText("onError : ${e.message}") } override fun onComplete() { // Completed editText.setText("Done") } }} The class combines the properties of a view (it textually shows the value of the model’s current state) with a controller (it allows the user to enter a new value for the state of the model). With help of this article, you would have now known how to create an Observable in any way you want and then use it as your procured use case. sagar0719kumar adnanirshad158 Picked RxJava Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android SDK and it's Components Flutter - Custom Bottom Navigation Bar How to Communicate Between Fragments in Android? Retrofit with Kotlin Coroutine in Android How to Add Views Dynamically and Store Data in Arraylist in Android? Android UI Layouts Kotlin Array How to Communicate Between Fragments in Android? Retrofit with Kotlin Coroutine in Android
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Sep, 2021" }, { "code": null, "e": 416, "s": 28, "text": "In the model-view paradigm, this class represents an observable object, or “data.” It can be subclassed in order to represent an object that the application wishes to watch. The issue is that you’re creating software that will render data describing a three-dimensional scene in two dimensions. The application must be modular and allow for numerous, concurrent views of the same scene. " }, { "code": null, "e": 737, "s": 416, "text": "One or more observers can be assigned to an observable object. An observer can be any object that implements the Observer interface. When an observable instance changes, an application that calls the Observable’s notifyObservers() method notifies all of its observers of the change through a call to their update method." }, { "code": null, "e": 783, "s": 737, "text": "Image 1. The Observables in RxJava Explained." }, { "code": null, "e": 802, "s": 783, "text": "In simple terms, " }, { "code": null, "e": 918, "s": 802, "text": "An Observable is analogous to a speaker that broadcasts the value. It does various tasks and generates some values." }, { "code": null, "e": 1017, "s": 918, "text": "An Operator is similar to a translator in that it converts/modifies data from one form to another." }, { "code": null, "e": 1056, "s": 1017, "text": "An Observer is what fetches the value." }, { "code": null, "e": 1112, "s": 1056, "text": "The many types of Observables in RxJava are as follows:" }, { "code": null, "e": 1123, "s": 1112, "text": "Observable" }, { "code": null, "e": 1132, "s": 1123, "text": "Flowable" }, { "code": null, "e": 1139, "s": 1132, "text": "Single" }, { "code": null, "e": 1145, "s": 1139, "text": "Maybe" }, { "code": null, "e": 1157, "s": 1145, "text": "Completable" }, { "code": null, "e": 1237, "s": 1157, "text": "Let’s commence creating some Observables in RxJava to better understand this, " }, { "code": null, "e": 1274, "s": 1237, "text": "Type #1: Creating a Basic Observable" }, { "code": null, "e": 1427, "s": 1274, "text": "Use Case: Assume you are downloading a file and need to push the current status of the download. You will have to emit more than one value in this case." }, { "code": null, "e": 1434, "s": 1427, "text": "Kotlin" }, { "code": "fun downloadObserervable(): Observable<Int> { return Observable.create { gfgshooter -> // Declaring an emitter in name of gfgshooter. // Beginning the task (in this case a simple download) // Your code... if (!gfgshooter.isDisposed) { // emit the progress gfgshooter.onNext(20) } // Still Downloading if (!gfgshooter.isDisposed) { // send progress gfgshooter.onNext(80) } // Progress 100, Download Over if (!gfgshooter.isDisposed) { // send progress gfgshooter.onNext(100) // send onComplete gfgshooter.onComplete() } }}", "e": 2130, "s": 1434, "text": null }, { "code": null, "e": 2186, "s": 2130, "text": " Type #2: Creating a Complex Obersever using Observable" }, { "code": null, "e": 2193, "s": 2186, "text": "Kotlin" }, { "code": "fun getObserver(): Observer<Int> { return object : Observer<Int> { override fun onStart(d: Disposable) { // Observation Started // A sample editText editText.setText(\"onStart\") } override fun onNext(progress: Int) { // Progress Updated editText.setText(\"onNext : $progress\") } override fun onError(e: Throwable) { // Error Thrown editText.setText(\"onError : ${e.message}\") } override fun onComplete() { // Observation Complete editText.setText(\"onComplete\") } }}", "e": 2820, "s": 2193, "text": null }, { "code": null, "e": 2841, "s": 2820, "text": "Observer <> Flowable" }, { "code": null, "e": 3237, "s": 2841, "text": "When the Observable emits a large number of values that cannot be absorbed by the Observer, the Flowable comes into play. In this scenario, the Observable must skip some data based on a strategy, otherwise, it will throw an exception. A strategy is used by the Flowable Observable to handle the exception. BackPressureStrategy is the strategy, and MissingBackPressureException is the exception. " }, { "code": null, "e": 3325, "s": 3237, "text": "Geek Tip: Just like type #1, you can create Flowable using Flowable.create() similarly." }, { "code": null, "e": 3351, "s": 3325, "text": "Solitary<> SingleObserver" }, { "code": null, "e": 3456, "s": 3351, "text": "When an Observable must emit only one value, such as as a response to a network request, Single is used." }, { "code": null, "e": 3493, "s": 3456, "text": "Type #3: Creating Single Observable " }, { "code": null, "e": 3500, "s": 3493, "text": "Kotlin" }, { "code": "fun singleObservable(): Single<String> { return Single.create { emitter -> // any code which has a task if (!gfgEmitter.isDisposed) { gfgEmitter.onSuccess(\"Spandan's Code Ran!\") } }}", "e": 3721, "s": 3500, "text": null }, { "code": null, "e": 3785, "s": 3721, "text": " Then use it with a single observable in the following manner: " }, { "code": null, "e": 3792, "s": 3785, "text": "Kotlin" }, { "code": "fun singleObservable(): SingleObserver<String> { return object : SingleObserver<String> { override fun onSubscribe(d: Disposable) { edittext.setText(\"onStart\") } override fun onSuccess(data: String) { // Successfully Executed editText.setText(\"onSuccess : $data\") } override fun onError(e: Throwable) { // Error or Exception thrown. editText.setText(\"onError : ${e.message}\") } }}", "e": 4277, "s": 3792, "text": null }, { "code": null, "e": 4300, "s": 4277, "text": " The maybe <> Observer" }, { "code": null, "e": 4366, "s": 4300, "text": "When the Observable must emit a value or no value, maybe is used." }, { "code": null, "e": 4402, "s": 4366, "text": "Type #4: Creating a maybe Observer " }, { "code": null, "e": 4409, "s": 4402, "text": "Kotlin" }, { "code": "fun maybeObservable(): Maybe<String> { return Maybe.create { gfgemitter -> // your code goes here if (!gfgemitter.isDisposed) { gfgemitter.onSuccess(\"Spandan's Code!\") } }}", "e": 4620, "s": 4409, "text": null }, { "code": null, "e": 4656, "s": 4620, "text": " Completable <> CompletableObserver" }, { "code": null, "e": 4747, "s": 4656, "text": "When the Observable must do some job without emitting a value, it is called a Completable." }, { "code": null, "e": 4789, "s": 4747, "text": "Type #5: Creating a Completable Observer " }, { "code": null, "e": 4796, "s": 4789, "text": "Kotlin" }, { "code": "fun completeObservable(): Completable { return Completable.create { gfgemitter -> // your code here if (!gfgemitter.isDisposed) { gfgemitter.onComplete() } }}", "e": 4993, "s": 4796, "text": null }, { "code": null, "e": 5032, "s": 4993, "text": "Using it now in the following manner: " }, { "code": null, "e": 5039, "s": 5032, "text": "Kotlin" }, { "code": "fun completeObservable(): gfgObserver { return object : gfgObserver { override fun onStart(d: Disposable) { // Started editText.setText(\"Started\") } override fun onError(e: Throwable) { // Exception Thrown editText.setText(\"onError : ${e.message}\") } override fun onComplete() { // Completed editText.setText(\"Done\") } }}", "e": 5475, "s": 5039, "text": null }, { "code": null, "e": 5810, "s": 5475, "text": "The class combines the properties of a view (it textually shows the value of the model’s current state) with a controller (it allows the user to enter a new value for the state of the model). With help of this article, you would have now known how to create an Observable in any way you want and then use it as your procured use case." }, { "code": null, "e": 5827, "s": 5812, "text": "sagar0719kumar" }, { "code": null, "e": 5842, "s": 5827, "text": "adnanirshad158" }, { "code": null, "e": 5849, "s": 5842, "text": "Picked" }, { "code": null, "e": 5856, "s": 5849, "text": "RxJava" }, { "code": null, "e": 5864, "s": 5856, "text": "Android" }, { "code": null, "e": 5871, "s": 5864, "text": "Kotlin" }, { "code": null, "e": 5879, "s": 5871, "text": "Android" }, { "code": null, "e": 5977, "s": 5879, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6046, "s": 5977, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 6078, "s": 6046, "text": "Android SDK and it's Components" }, { "code": null, "e": 6117, "s": 6078, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 6166, "s": 6117, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 6208, "s": 6166, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 6277, "s": 6208, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 6296, "s": 6277, "text": "Android UI Layouts" }, { "code": null, "e": 6309, "s": 6296, "text": "Kotlin Array" }, { "code": null, "e": 6358, "s": 6309, "text": "How to Communicate Between Fragments in Android?" } ]
Principles of Programming Languages - GeeksforGeeks
22 Jan, 2014 Program main; Var ... Procedure A1; Var ... Call A2; End A1 Procedure A2; Var ... Procedure A21; Var ... Call A1; End A21 Call A21; End A21 Call A1; End main. I. A programming language which does not permit global variables of any kind and has no nesting of procedures/functions, but permits recursion can be implemented with static storage allocation II. Multi-level access link (or display) arrangement is needed to arrange activation records only if the programming language being implemented has nesting of procedures/functions III. Recursion in programming languages cannot be implemented with dynamic storage allocation IV. Nesting of procedures/functions and recursion require a dynamic heap allocation scheme and cannot be implemented with a stack-based allocation scheme for activation records V. Programming languages which permit a function to return a function as its result cannot be implemented with a stack-based storage allocation scheme for activation records 1) Static allocation of all data areas by a compiler makes it impossible to implement recursion. 2) Automatic garbage collection is essential to implement recursion. 3) Dynamic allocation of activation records is essential to implement recursion. 4) Both heap and stack are essential to implement recursion. subroutine swap(ix,iy) it = ix L1 : ix = iy L2 : iy = it end ia = 3 ib = 8 call swap (ia, 1b+5) print *, ia, ib end to bound cells to its subroutines, if they are already presentto unnamed temporary cells later to be bound, if they are not there to bound cells to its subroutines, if they are already present to unnamed temporary cells later to be bound, if they are not there (S1) Because the second argument is an expression, which could be evaluated easily by compiler SDT rules to a value 13, compiler itself will generate code to define and declare an unnamed temporary cell with value 13 and pass it to swap subroutine. [CORRECT] (S2) 'ix' and 'iy' are variables bound to valid mutable cells, thus there is no reason to get a run time error on line L1. [INCORRECT] (S3) Incorrect due to same reason as of S2 [INCORRECT] (S4) Due to the pass-by-reference nature of the language, the cell bound to variable 'ia' will get value 13 and the temporary unnamed cell which was allocated and passed to the swap subroutine will get value 3. Seemingly, cell bound to variable 'ib' is unchanged, thus printing 13 and 8 at the end of this routine. [CORRECT] (S5) Incorrect due to same reason as of S4 [INCORRECT] Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ... Must Do Coding Questions for Product Based Companies Split given String into substrings of size K by filling elements SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar Java Threads Top 20 Puzzles Commonly Asked During SDE Interviews Software Testing Metrics, its Types and Example Software Testing - Boundary Value Analysis TCS NQT Coding Sheet
[ { "code": null, "e": 29577, "s": 29549, "text": "\n22 Jan, 2014" }, { "code": null, "e": 29832, "s": 29577, "text": "Program main;\n Var ...\n \n Procedure A1;\n Var ...\n Call A2;\n End A1\n \n Procedure A2;\n Var ...\n \n Procedure A21;\n Var ...\n Call A1;\n End A21\n \n Call A21;\n End A21\n \n Call A1;\n End main.\n" }, { "code": null, "e": 30690, "s": 29832, "text": "I. A programming language which does not permit global variables of any\n kind and has no nesting of procedures/functions, but permits recursion \n can be implemented with static storage allocation\nII. Multi-level access link (or display) arrangement is needed to arrange \n activation records only if the programming language being implemented \n has nesting of procedures/functions\nIII. Recursion in programming languages cannot be implemented with dynamic \n storage allocation\nIV. Nesting of procedures/functions and recursion require a dynamic heap \n allocation scheme and cannot be implemented with a stack-based allocation\n scheme for activation records\nV. Programming languages which permit a function to return a function as its \n result cannot be implemented with a stack-based storage allocation scheme \n for activation records" }, { "code": null, "e": 31012, "s": 30690, "text": "1) Static allocation of all data areas by a compiler\n makes it impossible to implement recursion.\n2) Automatic garbage collection is essential \n to implement recursion.\n3) Dynamic allocation of activation records is \n essential to implement recursion.\n4) Both heap and stack are essential to implement\n recursion." }, { "code": null, "e": 31142, "s": 31012, "text": "subroutine swap(ix,iy)\n it = ix\nL1 : ix = iy\nL2 : iy = it\nend\n ia = 3\n ib = 8\n call swap (ia, 1b+5)\n print *, ia, ib\nend " }, { "code": null, "e": 31272, "s": 31142, "text": "to bound cells to its subroutines, if they are already presentto unnamed temporary cells later to be bound, if they are not there" }, { "code": null, "e": 31335, "s": 31272, "text": "to bound cells to its subroutines, if they are already present" }, { "code": null, "e": 31403, "s": 31335, "text": "to unnamed temporary cells later to be bound, if they are not there" }, { "code": null, "e": 32244, "s": 31403, "text": "(S1) Because the second argument is an expression, which could be evaluated \neasily by compiler SDT rules to a value 13, compiler itself will generate code \nto define and declare an unnamed temporary cell with value 13 and pass it to swap \nsubroutine. [CORRECT]\n\n(S2) 'ix' and 'iy' are variables bound to valid mutable cells, thus there is no \nreason to get a run time error on line L1. [INCORRECT]\n\n(S3) Incorrect due to same reason as of S2 [INCORRECT]\n\n(S4) Due to the pass-by-reference nature of the language, the cell bound to \nvariable 'ia' will get value 13 and the temporary unnamed cell which was allocated \nand passed to the swap subroutine will get value 3. Seemingly, cell bound to variable\n 'ib' is unchanged, thus printing 13 and 8 at the end of this routine. [CORRECT]\n\n(S5) Incorrect due to same reason as of S4 [INCORRECT]\n" }, { "code": null, "e": 32342, "s": 32244, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 32416, "s": 32342, "text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..." }, { "code": null, "e": 32469, "s": 32416, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 32534, "s": 32469, "text": "Split given String into substrings of size K by filling elements" }, { "code": null, "e": 32583, "s": 32534, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 32608, "s": 32583, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 32621, "s": 32608, "text": "Java Threads" }, { "code": null, "e": 32673, "s": 32621, "text": "Top 20 Puzzles Commonly Asked During SDE Interviews" }, { "code": null, "e": 32721, "s": 32673, "text": "Software Testing Metrics, its Types and Example" }, { "code": null, "e": 32764, "s": 32721, "text": "Software Testing - Boundary Value Analysis" } ]
Hide and Unhide The Window in Tkinter – Python
04 Jul, 2021 Prerequisite: Tkinter Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task. In this article, we will discuss how to hide and unhide the window in Tkinter Using Python. Functions used: Toplevel() is used to launch the second window Syntax: toplevel = Toplevel(root, bg, fg, bd, height, width, font, ..) deiconify() is used to show or unhide the window Syntax: deiconify() withdraw() is used to hide the window Syntax: withdraw() Approach: Import module Create a normal window Add buttons to perform hide and unhide actions Now create one more window Execute code Program: Python3 # Import Libraryfrom tkinter import * # Create Objectroot = Tk() # Set titleroot.title("Main Window") # Set Geometryroot.geometry("200x200") # Open New Windowdef launch(): global second second = Toplevel() second.title("Child Window") second.geometry("400x400") # Show the windowdef show(): second.deiconify() # Hide the windowdef hide(): second.withdraw() # Add ButtonsButton(root, text="launch Window", command=launch).pack(pady=10)Button(root, text="Show", command=show).pack(pady=10)Button(root, text="Hide", command=hide).pack(pady=10) # Execute Tkinterroot.mainloop() Output: simmytarika5 Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n04 Jul, 2021" }, { "code": null, "e": 75, "s": 53, "text": "Prerequisite: Tkinter" }, { "code": null, "e": 425, "s": 75, "text": "Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task." }, { "code": null, "e": 517, "s": 425, "text": "In this article, we will discuss how to hide and unhide the window in Tkinter Using Python." }, { "code": null, "e": 533, "s": 517, "text": "Functions used:" }, { "code": null, "e": 580, "s": 533, "text": "Toplevel() is used to launch the second window" }, { "code": null, "e": 588, "s": 580, "text": "Syntax:" }, { "code": null, "e": 651, "s": 588, "text": "toplevel = Toplevel(root, bg, fg, bd, height, width, font, ..)" }, { "code": null, "e": 700, "s": 651, "text": "deiconify() is used to show or unhide the window" }, { "code": null, "e": 708, "s": 700, "text": "Syntax:" }, { "code": null, "e": 720, "s": 708, "text": "deiconify()" }, { "code": null, "e": 758, "s": 720, "text": "withdraw() is used to hide the window" }, { "code": null, "e": 766, "s": 758, "text": "Syntax:" }, { "code": null, "e": 777, "s": 766, "text": "withdraw()" }, { "code": null, "e": 787, "s": 777, "text": "Approach:" }, { "code": null, "e": 801, "s": 787, "text": "Import module" }, { "code": null, "e": 824, "s": 801, "text": "Create a normal window" }, { "code": null, "e": 871, "s": 824, "text": "Add buttons to perform hide and unhide actions" }, { "code": null, "e": 898, "s": 871, "text": "Now create one more window" }, { "code": null, "e": 911, "s": 898, "text": "Execute code" }, { "code": null, "e": 920, "s": 911, "text": "Program:" }, { "code": null, "e": 928, "s": 920, "text": "Python3" }, { "code": "# Import Libraryfrom tkinter import * # Create Objectroot = Tk() # Set titleroot.title(\"Main Window\") # Set Geometryroot.geometry(\"200x200\") # Open New Windowdef launch(): global second second = Toplevel() second.title(\"Child Window\") second.geometry(\"400x400\") # Show the windowdef show(): second.deiconify() # Hide the windowdef hide(): second.withdraw() # Add ButtonsButton(root, text=\"launch Window\", command=launch).pack(pady=10)Button(root, text=\"Show\", command=show).pack(pady=10)Button(root, text=\"Hide\", command=hide).pack(pady=10) # Execute Tkinterroot.mainloop()", "e": 1520, "s": 928, "text": null }, { "code": null, "e": 1528, "s": 1520, "text": "Output:" }, { "code": null, "e": 1541, "s": 1528, "text": "simmytarika5" }, { "code": null, "e": 1556, "s": 1541, "text": "Python-tkinter" }, { "code": null, "e": 1563, "s": 1556, "text": "Python" } ]
Maximum Product Cutting | DP-36
21 Jun, 2022 Given a rope of length n meters, cut the rope in different parts of integer lengths in a way that maximizes product of lengths of all parts. You must make at least one cut. Assume that the length of rope is more than 2 meters. Examples: Input: n = 2 Output: 1 (Maximum obtainable product is 1*1) Input: n = 3 Output: 2 (Maximum obtainable product is 1*2) Input: n = 4 Output: 4 (Maximum obtainable product is 2*2) Input: n = 5 Output: 6 (Maximum obtainable product is 2*3) Input: n = 10 Output: 36 (Maximum obtainable product is 3*3*4) 1) Optimal Substructure: This problem is similar to Rod Cutting Problem. We can get the maximum product by making a cut at different positions and comparing the values obtained after a cut. We can recursively call the same function for a piece obtained after a cut.Let maxProd(n) be the maximum product for a rope of length n. maxProd(n) can be written as following.maxProd(n) = max(i*(n-i), maxProdRec(n-i)*i) for all i in {1, 2, 3 .. n} 2) Overlapping Subproblems: Following is simple recursive implementation of the problem. The implementation simply follows the recursive structure mentioned above. C++ Java Python3 C# PHP Javascript // A Naive Recursive method to find maximum product#include <iostream>using namespace std; // Utility function to get the maximum of two and three integersint max(int a, int b) { return (a > b)? a : b;}int max(int a, int b, int c) { return max(a, max(b, c));} // The main function that returns maximum product obtainable// from a rope of length nint maxProd(int n){ // Base cases if (n == 0 || n == 1) return 0; // Make a cut at different places and take the maximum of all int max_val = 0; for (int i = 1; i < n; i++) max_val = max(max_val, i*(n-i), maxProd(n-i)*i); // Return the maximum of all values return max_val;} /* Driver program to test above functions */int main(){ cout << "Maximum Product is " << maxProd(10); return 0;} // Java program to find maximum productimport java.io.*; class GFG { // The main function that returns // maximum product obtainable from // a rope of length n static int maxProd(int n) { // Base cases if (n == 0 || n == 1) return 0; // Make a cut at different places // and take the maximum of all int max_val = 0; for (int i = 1; i < n; i++) max_val = Math.max(max_val, Math.max(i * (n - i), maxProd(n - i) * i)); // Return the maximum of all values return max_val; } /* Driver program to test above functions */ public static void main(String[] args) { System.out.println("Maximum Product is " + maxProd(10)); }}// This code is contributed by Prerna Saini # The main function that returns maximum# product obtainable from a rope of length n def maxProd(n): # Base cases if (n == 0 or n == 1): return 0 # Make a cut at different places # and take the maximum of all max_val = 0 for i in range(1, n - 1): max_val = max(max_val, max(i * (n - i), maxProd(n - i) * i)) #Return the maximum of all values return max_val; # Driver program to test above functionsprint("Maximum Product is ", maxProd(10)); # This code is contributed# by Sumit Sudhakar // C# program to find maximum productusing System; class GFG { // The main function that returns // the max possible product static int maxProd(int n) { // n equals to 2 or 3 must // be handled explicitly if (n == 2 || n == 3) return (n - 1); // Keep removing parts of size // 3 while n is greater than 4 int res = 1; while (n > 4) { n -= 3; // Keep multiplying 3 to res res *= 3; } // The last part multiplied // by previous parts return (n * res); } // Driver code public static void Main() { Console.WriteLine("Maximum Product is " + maxProd(10)); }} // This code is contributed by Sam007 <?php// A Naive Recursive method to// find maximum product // Utility function to get the// maximum of two and three integersfunction max_1($a, $b, $c){ return max($a, max($b, $c));} // The main function that returns// maximum product obtainable// from a rope of length nfunction maxProd($n){ // Base cases if ($n == 0 || $n == 1) return 0; // Make a cut at different places // and take the maximum of all $max_val = 0; for ($i = 1; $i < $n; $i++) $max_val = max_1($max_val, $i * ($n - $i), maxProd($n - $i) * $i); // Return the maximum of all values return $max_val;} // Driver Codeecho "Maximum Product is " . maxProd(10); // This code is contributed// by ChitraNayal?> <script> // Javascript program to find maximum product // The main function that returns // maximum product obtainable from // a rope of length n function maxProd(n) { // Base cases if (n == 0 || n == 1) return 0; // Make a cut at different places // and take the maximum of all let max_val = 0; for (let i = 1; i < n; i++) { max_val = Math.max(max_val, Math.max(i * (n - i), maxProd(n - i) * i)); } // Return the maximum of all values return max_val; } /* Driver program to test above functions */ document.write("Maximum Product is " + maxProd(10)); // This code is contributed by rag2127 </script> Maximum Product is 36 Considering the above implementation, following is recursion tree for a Rope of length 5. In the above partial recursion tree, mP(3) is being solved twice. We can see that there are many subproblems which are solved again and again. Since same subproblems are called again, this problem has Overlapping Subproblems property. So the problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of same subproblems can be avoided by constructing a temporary array val[] in bottom up manner. C++ C Java Python3 C# Javascript // C++ code to implement the approach\ // A Dynamic Programming solution for Max Product Problemint maxProd(int n){ int val[n+1]; val[0] = val[1] = 0; // Build the table val[] in bottom up manner and return // the last entry from the table for (int i = 1; i <= n; i++) { int max_val = 0; for (int j = 1; j <= i; j++) max_val = max(max_val, (i-j)*j, j*val[i-j]); val[i] = max_val; } return val[n];} // This code is contributed by sanjoy_62. // A Dynamic Programming solution for Max Product Problemint maxProd(int n){ int val[n+1]; val[0] = val[1] = 0; // Build the table val[] in bottom up manner and return // the last entry from the table for (int i = 1; i <= n; i++) { int max_val = 0; for (int j = 1; j <= i; j++) max_val = max(max_val, (i-j)*j, j*val[i-j]); val[i] = max_val; } return val[n];} // A Dynamic Programming solution for Max Product Problemint maxProd(int n){ int val[n+1]; val[0] = val[1] = 0; // Build the table val[] in bottom up manner and return // the last entry from the table for (int i = 1; i <= n; i++) { int max_val = 0; for (int j = 1; j <= i; j++) max_val = Math.max(max_val, (i-j)*j, j*val[i-j]); val[i] = max_val; } return val[n];} // This code is contributed by umadevi9616 # A Dynamic Programming solution for Max Product Problemdef maxProd(n): val= [0 for i in range(n+1)]; # Build the table val in bottom up manner and return # the last entry from the table for i in range(1,n+1): max_val = 0; for j in range(1,i): max_val = max(max_val, (i-j)*j, j*val[i-j]); val[i] = max_val; return val[n]; # This code is contributed by gauravrajput1 // A Dynamic Programming solution for Max Product Problemint maxProd(int n){ int []val = new int[n+1]; val[0] = val[1] = 0; // Build the table val[] in bottom up manner and return // the last entry from the table for (int i = 1; i <= n; i++) { int max_val = 0; for (int j = 1; j <= i; j++) max_val = Math.Max(max_val, (i-j)*j, j*val[i-j]); val[i] = max_val; } return val[n];} // This code is contributed by umadevi9616 <script>// A Dynamic Programming solution for Max Product Problemfunction maxProd(n){ var val = Array(n+1).fill(0; val[0] = val[1] = 0; // Build the table val in bottom up manner and return // the last entry from the table for (var 1; i <= n; i++) { var max_val = 0; for ( var ; j <= i; j++) max_val = Math.max(max_val, (i-j)*j, j*val[i-j]); val[i] = max_val; } return val[n];} // This code is contributed by gauravrajput1</script> Time Complexity of the Dynamic Programming solution is O(n^2) and it requires O(n) extra space. A Tricky Solution: If we see some examples of this problems, we can easily observe following pattern. The maximum product can be obtained be repeatedly cutting parts of size 3 while size is greater than 4, keeping the last part as size of 2 or 3 or 4. For example, n = 10, the maximum product is obtained by 3, 3, 4. For n = 11, the maximum product is obtained by 3, 3, 3, 2. Following is the implementation of this approach. C++ Java Python3 C# PHP Javascript #include <iostream>using namespace std; /* The main function that returns the max possible product */int maxProd(int n){ // n equals to 2 or 3 must be handled explicitly if (n == 2 || n == 3) return (n-1); // Keep removing parts of size 3 while n is greater than 4 int res = 1; while (n > 4) { n -= 3; res *= 3; // Keep multiplying 3 to res } return (n * res); // The last part multiplied by previous parts} /* Driver program to test above functions */int main(){ cout << "Maximum Product is " << maxProd(10); return 0;} // Java program to find maximum productimport java.io.*; class GFG { /* The main function that returns the max possible product */ static int maxProd(int n) { // n equals to 2 or 3 must be handled // explicitly if (n == 2 || n == 3) return (n-1); // Keep removing parts of size 3 // while n is greater than 4 int res = 1; while (n > 4) { n -= 3; // Keep multiplying 3 to res res *= 3; } // The last part multiplied by // previous parts return (n * res); } /* Driver program to test above functions */ public static void main(String[] args) { System.out.println("Maximum Product is " + maxProd(10)); } }// This code is contributed by Prerna Saini # The main function that returns the# max possible product def maxProd(n): # n equals to 2 or 3 must # be handled explicitly if (n == 2 or n == 3): return (n - 1) # Keep removing parts of size 3 # while n is greater than 4 res = 1 while (n > 4): n -= 3; # Keep multiplying 3 to res res *= 3; # The last part multiplied # by previous parts return (n * res) # Driver program to test above functionsprint("Maximum Product is ", maxProd(10)); # This code is contributed# by Sumit Sudhakar // C# program to find maximum productusing System; class GFG { // The main function that returns // maximum product obtainable from // a rope of length n static int maxProd(int n) { // Base cases if (n == 0 || n == 1) return 0; // Make a cut at different places // and take the maximum of all int max_val = 0; for (int i = 1; i < n; i++) max_val = Math.Max(max_val, Math.Max(i * (n - i), maxProd(n - i) * i)); // Return the maximum of all values return max_val; } // Driver code public static void Main() { Console.WriteLine("Maximum Product is " + maxProd(10)); }} // This code is contributed by Sam007 <?php /* The main function that returns the max possible product */function maxProd($n){ // n equals to 2 or 3 must// be handled explicitlyif ($n == 2 || $n == 3) return ($n - 1); // Keep removing parts of size// 3 while n is greater than 4$res = 1;while ($n > 4){ $n = $n - 3; // Keep multiplying 3 to res $res = $res * 3;} // The last part multiplied// by previous partsreturn ($n * $res);} // Driver codeecho ("Maximum Product is ");echo(maxProd(10)); // This code is contributed// by Shivi_Aggarwal?> <script> // Javascript program to find maximum product /* The main function that returns the max possible product */ function maxProd(n) { // n equals to 2 or 3 must be handled // explicitly if (n == 2 || n == 3) { return (n-1); } // Keep removing parts of size 3 // while n is greater than 4 let res = 1; while (n > 4) { n -= 3; // Keep multiplying 3 to res res *= 3; } // The last part multiplied by // previous parts return (n * res); } /* Driver program to test above functions */ document.write("Maximum Product is " + maxProd(10)); // This code is contributed by avanitrachhadiya2155 </script> Maximum Product is 36 Shivi_Aggarwal ukasp rag2127 avanitrachhadiya2155 hritikbhatnagar2182 sweetyty umadevi9616 GauravRajput1 singghakshay 19i sanjoy_62 hardikkoriintern Arrays Dynamic Programming Arrays Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Window Sliding Technique Search, insert and delete in an unsorted array What is Data Structure: Types, Classifications and Applications Chocolate Distribution Problem Program for Fibonacci numbers 0-1 Knapsack Problem | DP-10 Longest Common Subsequence | DP-4 Longest Increasing Subsequence | DP-3 Longest Palindromic Substring | Set 1
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Jun, 2022" }, { "code": null, "e": 282, "s": 54, "text": "Given a rope of length n meters, cut the rope in different parts of integer lengths in a way that maximizes product of lengths of all parts. You must make at least one cut. Assume that the length of rope is more than 2 meters. " }, { "code": null, "e": 293, "s": 282, "text": "Examples: " }, { "code": null, "e": 596, "s": 293, "text": "Input: n = 2\nOutput: 1 (Maximum obtainable product is 1*1)\n\nInput: n = 3\nOutput: 2 (Maximum obtainable product is 1*2)\n\nInput: n = 4\nOutput: 4 (Maximum obtainable product is 2*2)\n\nInput: n = 5\nOutput: 6 (Maximum obtainable product is 2*3)\n\nInput: n = 10\nOutput: 36 (Maximum obtainable product is 3*3*4)" }, { "code": null, "e": 622, "s": 596, "text": "1) Optimal Substructure: " }, { "code": null, "e": 1036, "s": 622, "text": "This problem is similar to Rod Cutting Problem. We can get the maximum product by making a cut at different positions and comparing the values obtained after a cut. We can recursively call the same function for a piece obtained after a cut.Let maxProd(n) be the maximum product for a rope of length n. maxProd(n) can be written as following.maxProd(n) = max(i*(n-i), maxProdRec(n-i)*i) for all i in {1, 2, 3 .. n}" }, { "code": null, "e": 1064, "s": 1036, "text": "2) Overlapping Subproblems:" }, { "code": null, "e": 1201, "s": 1064, "text": "Following is simple recursive implementation of the problem. The implementation simply follows the recursive structure mentioned above. " }, { "code": null, "e": 1205, "s": 1201, "text": "C++" }, { "code": null, "e": 1210, "s": 1205, "text": "Java" }, { "code": null, "e": 1218, "s": 1210, "text": "Python3" }, { "code": null, "e": 1221, "s": 1218, "text": "C#" }, { "code": null, "e": 1225, "s": 1221, "text": "PHP" }, { "code": null, "e": 1236, "s": 1225, "text": "Javascript" }, { "code": "// A Naive Recursive method to find maximum product#include <iostream>using namespace std; // Utility function to get the maximum of two and three integersint max(int a, int b) { return (a > b)? a : b;}int max(int a, int b, int c) { return max(a, max(b, c));} // The main function that returns maximum product obtainable// from a rope of length nint maxProd(int n){ // Base cases if (n == 0 || n == 1) return 0; // Make a cut at different places and take the maximum of all int max_val = 0; for (int i = 1; i < n; i++) max_val = max(max_val, i*(n-i), maxProd(n-i)*i); // Return the maximum of all values return max_val;} /* Driver program to test above functions */int main(){ cout << \"Maximum Product is \" << maxProd(10); return 0;}", "e": 2004, "s": 1236, "text": null }, { "code": "// Java program to find maximum productimport java.io.*; class GFG { // The main function that returns // maximum product obtainable from // a rope of length n static int maxProd(int n) { // Base cases if (n == 0 || n == 1) return 0; // Make a cut at different places // and take the maximum of all int max_val = 0; for (int i = 1; i < n; i++) max_val = Math.max(max_val, Math.max(i * (n - i), maxProd(n - i) * i)); // Return the maximum of all values return max_val; } /* Driver program to test above functions */ public static void main(String[] args) { System.out.println(\"Maximum Product is \" + maxProd(10)); }}// This code is contributed by Prerna Saini", "e": 2831, "s": 2004, "text": null }, { "code": "# The main function that returns maximum# product obtainable from a rope of length n def maxProd(n): # Base cases if (n == 0 or n == 1): return 0 # Make a cut at different places # and take the maximum of all max_val = 0 for i in range(1, n - 1): max_val = max(max_val, max(i * (n - i), maxProd(n - i) * i)) #Return the maximum of all values return max_val; # Driver program to test above functionsprint(\"Maximum Product is \", maxProd(10)); # This code is contributed# by Sumit Sudhakar", "e": 3371, "s": 2831, "text": null }, { "code": "// C# program to find maximum productusing System; class GFG { // The main function that returns // the max possible product static int maxProd(int n) { // n equals to 2 or 3 must // be handled explicitly if (n == 2 || n == 3) return (n - 1); // Keep removing parts of size // 3 while n is greater than 4 int res = 1; while (n > 4) { n -= 3; // Keep multiplying 3 to res res *= 3; } // The last part multiplied // by previous parts return (n * res); } // Driver code public static void Main() { Console.WriteLine(\"Maximum Product is \" + maxProd(10)); }} // This code is contributed by Sam007", "e": 4160, "s": 3371, "text": null }, { "code": "<?php// A Naive Recursive method to// find maximum product // Utility function to get the// maximum of two and three integersfunction max_1($a, $b, $c){ return max($a, max($b, $c));} // The main function that returns// maximum product obtainable// from a rope of length nfunction maxProd($n){ // Base cases if ($n == 0 || $n == 1) return 0; // Make a cut at different places // and take the maximum of all $max_val = 0; for ($i = 1; $i < $n; $i++) $max_val = max_1($max_val, $i * ($n - $i), maxProd($n - $i) * $i); // Return the maximum of all values return $max_val;} // Driver Codeecho \"Maximum Product is \" . maxProd(10); // This code is contributed// by ChitraNayal?>", "e": 4878, "s": 4160, "text": null }, { "code": "<script> // Javascript program to find maximum product // The main function that returns // maximum product obtainable from // a rope of length n function maxProd(n) { // Base cases if (n == 0 || n == 1) return 0; // Make a cut at different places // and take the maximum of all let max_val = 0; for (let i = 1; i < n; i++) { max_val = Math.max(max_val, Math.max(i * (n - i), maxProd(n - i) * i)); } // Return the maximum of all values return max_val; } /* Driver program to test above functions */ document.write(\"Maximum Product is \" + maxProd(10)); // This code is contributed by rag2127 </script>", "e": 5687, "s": 4878, "text": null }, { "code": null, "e": 5709, "s": 5687, "text": "Maximum Product is 36" }, { "code": null, "e": 5801, "s": 5709, "text": "Considering the above implementation, following is recursion tree for a Rope of length 5. " }, { "code": null, "e": 6289, "s": 5801, "text": "In the above partial recursion tree, mP(3) is being solved twice. We can see that there are many subproblems which are solved again and again. Since same subproblems are called again, this problem has Overlapping Subproblems property. So the problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of same subproblems can be avoided by constructing a temporary array val[] in bottom up manner." }, { "code": null, "e": 6293, "s": 6289, "text": "C++" }, { "code": null, "e": 6295, "s": 6293, "text": "C" }, { "code": null, "e": 6300, "s": 6295, "text": "Java" }, { "code": null, "e": 6308, "s": 6300, "text": "Python3" }, { "code": null, "e": 6311, "s": 6308, "text": "C#" }, { "code": null, "e": 6322, "s": 6311, "text": "Javascript" }, { "code": "// C++ code to implement the approach\\ // A Dynamic Programming solution for Max Product Problemint maxProd(int n){ int val[n+1]; val[0] = val[1] = 0; // Build the table val[] in bottom up manner and return // the last entry from the table for (int i = 1; i <= n; i++) { int max_val = 0; for (int j = 1; j <= i; j++) max_val = max(max_val, (i-j)*j, j*val[i-j]); val[i] = max_val; } return val[n];} // This code is contributed by sanjoy_62.", "e": 6803, "s": 6322, "text": null }, { "code": "// A Dynamic Programming solution for Max Product Problemint maxProd(int n){ int val[n+1]; val[0] = val[1] = 0; // Build the table val[] in bottom up manner and return // the last entry from the table for (int i = 1; i <= n; i++) { int max_val = 0; for (int j = 1; j <= i; j++) max_val = max(max_val, (i-j)*j, j*val[i-j]); val[i] = max_val; } return val[n];}", "e": 7203, "s": 6803, "text": null }, { "code": "// A Dynamic Programming solution for Max Product Problemint maxProd(int n){ int val[n+1]; val[0] = val[1] = 0; // Build the table val[] in bottom up manner and return // the last entry from the table for (int i = 1; i <= n; i++) { int max_val = 0; for (int j = 1; j <= i; j++) max_val = Math.max(max_val, (i-j)*j, j*val[i-j]); val[i] = max_val; } return val[n];} // This code is contributed by umadevi9616", "e": 7651, "s": 7203, "text": null }, { "code": "# A Dynamic Programming solution for Max Product Problemdef maxProd(n): val= [0 for i in range(n+1)]; # Build the table val in bottom up manner and return # the last entry from the table for i in range(1,n+1): max_val = 0; for j in range(1,i): max_val = max(max_val, (i-j)*j, j*val[i-j]); val[i] = max_val; return val[n]; # This code is contributed by gauravrajput1", "e": 8054, "s": 7651, "text": null }, { "code": "// A Dynamic Programming solution for Max Product Problemint maxProd(int n){ int []val = new int[n+1]; val[0] = val[1] = 0; // Build the table val[] in bottom up manner and return // the last entry from the table for (int i = 1; i <= n; i++) { int max_val = 0; for (int j = 1; j <= i; j++) max_val = Math.Max(max_val, (i-j)*j, j*val[i-j]); val[i] = max_val; } return val[n];} // This code is contributed by umadevi9616", "e": 8514, "s": 8054, "text": null }, { "code": "<script>// A Dynamic Programming solution for Max Product Problemfunction maxProd(n){ var val = Array(n+1).fill(0; val[0] = val[1] = 0; // Build the table val in bottom up manner and return // the last entry from the table for (var 1; i <= n; i++) { var max_val = 0; for ( var ; j <= i; j++) max_val = Math.max(max_val, (i-j)*j, j*val[i-j]); val[i] = max_val; } return val[n];} // This code is contributed by gauravrajput1</script>", "e": 8987, "s": 8514, "text": null }, { "code": null, "e": 9083, "s": 8987, "text": "Time Complexity of the Dynamic Programming solution is O(n^2) and it requires O(n) extra space." }, { "code": null, "e": 9103, "s": 9083, "text": "A Tricky Solution: " }, { "code": null, "e": 9511, "s": 9103, "text": "If we see some examples of this problems, we can easily observe following pattern. The maximum product can be obtained be repeatedly cutting parts of size 3 while size is greater than 4, keeping the last part as size of 2 or 3 or 4. For example, n = 10, the maximum product is obtained by 3, 3, 4. For n = 11, the maximum product is obtained by 3, 3, 3, 2. Following is the implementation of this approach. " }, { "code": null, "e": 9515, "s": 9511, "text": "C++" }, { "code": null, "e": 9520, "s": 9515, "text": "Java" }, { "code": null, "e": 9528, "s": 9520, "text": "Python3" }, { "code": null, "e": 9531, "s": 9528, "text": "C#" }, { "code": null, "e": 9535, "s": 9531, "text": "PHP" }, { "code": null, "e": 9546, "s": 9535, "text": "Javascript" }, { "code": "#include <iostream>using namespace std; /* The main function that returns the max possible product */int maxProd(int n){ // n equals to 2 or 3 must be handled explicitly if (n == 2 || n == 3) return (n-1); // Keep removing parts of size 3 while n is greater than 4 int res = 1; while (n > 4) { n -= 3; res *= 3; // Keep multiplying 3 to res } return (n * res); // The last part multiplied by previous parts} /* Driver program to test above functions */int main(){ cout << \"Maximum Product is \" << maxProd(10); return 0;}", "e": 10102, "s": 9546, "text": null }, { "code": "// Java program to find maximum productimport java.io.*; class GFG { /* The main function that returns the max possible product */ static int maxProd(int n) { // n equals to 2 or 3 must be handled // explicitly if (n == 2 || n == 3) return (n-1); // Keep removing parts of size 3 // while n is greater than 4 int res = 1; while (n > 4) { n -= 3; // Keep multiplying 3 to res res *= 3; } // The last part multiplied by // previous parts return (n * res); } /* Driver program to test above functions */ public static void main(String[] args) { System.out.println(\"Maximum Product is \" + maxProd(10)); } }// This code is contributed by Prerna Saini", "e": 10889, "s": 10102, "text": null }, { "code": "# The main function that returns the# max possible product def maxProd(n): # n equals to 2 or 3 must # be handled explicitly if (n == 2 or n == 3): return (n - 1) # Keep removing parts of size 3 # while n is greater than 4 res = 1 while (n > 4): n -= 3; # Keep multiplying 3 to res res *= 3; # The last part multiplied # by previous parts return (n * res) # Driver program to test above functionsprint(\"Maximum Product is \", maxProd(10)); # This code is contributed# by Sumit Sudhakar", "e": 11458, "s": 10889, "text": null }, { "code": "// C# program to find maximum productusing System; class GFG { // The main function that returns // maximum product obtainable from // a rope of length n static int maxProd(int n) { // Base cases if (n == 0 || n == 1) return 0; // Make a cut at different places // and take the maximum of all int max_val = 0; for (int i = 1; i < n; i++) max_val = Math.Max(max_val, Math.Max(i * (n - i), maxProd(n - i) * i)); // Return the maximum of all values return max_val; } // Driver code public static void Main() { Console.WriteLine(\"Maximum Product is \" + maxProd(10)); }} // This code is contributed by Sam007", "e": 12253, "s": 11458, "text": null }, { "code": "<?php /* The main function that returns the max possible product */function maxProd($n){ // n equals to 2 or 3 must// be handled explicitlyif ($n == 2 || $n == 3) return ($n - 1); // Keep removing parts of size// 3 while n is greater than 4$res = 1;while ($n > 4){ $n = $n - 3; // Keep multiplying 3 to res $res = $res * 3;} // The last part multiplied// by previous partsreturn ($n * $res);} // Driver codeecho (\"Maximum Product is \");echo(maxProd(10)); // This code is contributed// by Shivi_Aggarwal?>", "e": 12781, "s": 12253, "text": null }, { "code": "<script> // Javascript program to find maximum product /* The main function that returns the max possible product */ function maxProd(n) { // n equals to 2 or 3 must be handled // explicitly if (n == 2 || n == 3) { return (n-1); } // Keep removing parts of size 3 // while n is greater than 4 let res = 1; while (n > 4) { n -= 3; // Keep multiplying 3 to res res *= 3; } // The last part multiplied by // previous parts return (n * res); } /* Driver program to test above functions */ document.write(\"Maximum Product is \" + maxProd(10)); // This code is contributed by avanitrachhadiya2155 </script>", "e": 13587, "s": 12781, "text": null }, { "code": null, "e": 13609, "s": 13587, "text": "Maximum Product is 36" }, { "code": null, "e": 13624, "s": 13609, "text": "Shivi_Aggarwal" }, { "code": null, "e": 13630, "s": 13624, "text": "ukasp" }, { "code": null, "e": 13638, "s": 13630, "text": "rag2127" }, { "code": null, "e": 13659, "s": 13638, "text": "avanitrachhadiya2155" }, { "code": null, "e": 13679, "s": 13659, "text": "hritikbhatnagar2182" }, { "code": null, "e": 13688, "s": 13679, "text": "sweetyty" }, { "code": null, "e": 13700, "s": 13688, "text": "umadevi9616" }, { "code": null, "e": 13714, "s": 13700, "text": "GauravRajput1" }, { "code": null, "e": 13727, "s": 13714, "text": "singghakshay" }, { "code": null, "e": 13731, "s": 13727, "text": "19i" }, { "code": null, "e": 13741, "s": 13731, "text": "sanjoy_62" }, { "code": null, "e": 13758, "s": 13741, "text": "hardikkoriintern" }, { "code": null, "e": 13765, "s": 13758, "text": "Arrays" }, { "code": null, "e": 13785, "s": 13765, "text": "Dynamic Programming" }, { "code": null, "e": 13792, "s": 13785, "text": "Arrays" }, { "code": null, "e": 13812, "s": 13792, "text": "Dynamic Programming" }, { "code": null, "e": 13910, "s": 13812, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13942, "s": 13910, "text": "Introduction to Data Structures" }, { "code": null, "e": 13967, "s": 13942, "text": "Window Sliding Technique" }, { "code": null, "e": 14014, "s": 13967, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 14078, "s": 14014, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 14109, "s": 14078, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 14139, "s": 14109, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 14168, "s": 14139, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 14202, "s": 14168, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 14240, "s": 14202, "text": "Longest Increasing Subsequence | DP-3" } ]
tcpdump Command in Linux with Examples
03 Jun, 2020 tcpdump is a packet sniffing and packet analyzing tool for a System Administrator to troubleshoot connectivity issues in Linux. It is used to capture, filter, and analyze network traffic such as TCP/IP packets going through your system. It is many times used as a security tool as well. It saves the captured information in a pcap file, these pcap files can then be opened through Wireshark or through the command tool itself. Many Operating Systems have tcpdump command pre-installed but to install it, use the following commands. For RedHat based linux OS yum install tcpdump For Ubuntu/Debian OS apt install tcpdump 1. To capture the packets of current network interface sudo tcpdump This will capture the packets from the current interface of the network through which the system is connected to the internet. 2. To capture packets from a specific network interface sudo tcpdump -i wlo1 This command will now capture the packets from wlo1 network interface. 3. To capture specific number of packets sudo tcpdump -c 4 -i wlo1 This command will capture only 4 packets from the wlo1 interface. 4. To print captured packages in ASCII format sudo tcpdump -A -i wlo1 This command will now print the captured packets from wlo1 to ASCII value. 5. To display all available interfaces sudo tcpdump -D This command will display all the interfaces that are available in the system. 6. To display packets in HEX and ASCII values sudo tcpdump -XX -i wlo1 This command will now print the packages captured from the wlo1 interface in the HEX and ASCII values. 7. To save captured packets into a file sudo tcpdump -w captured_packets.pcap -i wlo1 This command will now output all the captures packets in a file named as captured_packets.pcap. 8. To read captured packets from a file sudo tcpdump -r captured_packets.pcap This command will now read the captured packets from the captured_packets.pcap file. 9. To capture packets with ip address sudo tcpdump -n -i wlo1 This command will now capture the packets with IP addresses. 10. To capture only TCP packets sudo tcpdump -i wlo1 tcp This command will now capture only TCP packets from wlo1. linux-command Linux-networking-commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ZIP command in Linux with examples tar command in Linux with examples curl command in Linux with Examples SORT command in Linux/Unix with examples Conditional Statements | Shell Script TCP Server-Client implementation in C Tail command in Linux with examples Docker - COPY Instruction scp command in Linux with Examples UDP Server-Client implementation in C
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Jun, 2020" }, { "code": null, "e": 455, "s": 28, "text": "tcpdump is a packet sniffing and packet analyzing tool for a System Administrator to troubleshoot connectivity issues in Linux. It is used to capture, filter, and analyze network traffic such as TCP/IP packets going through your system. It is many times used as a security tool as well. It saves the captured information in a pcap file, these pcap files can then be opened through Wireshark or through the command tool itself." }, { "code": null, "e": 560, "s": 455, "text": "Many Operating Systems have tcpdump command pre-installed but to install it, use the following commands." }, { "code": null, "e": 586, "s": 560, "text": "For RedHat based linux OS" }, { "code": null, "e": 606, "s": 586, "text": "yum install tcpdump" }, { "code": null, "e": 627, "s": 606, "text": "For Ubuntu/Debian OS" }, { "code": null, "e": 647, "s": 627, "text": "apt install tcpdump" }, { "code": null, "e": 702, "s": 647, "text": "1. To capture the packets of current network interface" }, { "code": null, "e": 715, "s": 702, "text": "sudo tcpdump" }, { "code": null, "e": 842, "s": 715, "text": "This will capture the packets from the current interface of the network through which the system is connected to the internet." }, { "code": null, "e": 898, "s": 842, "text": "2. To capture packets from a specific network interface" }, { "code": null, "e": 919, "s": 898, "text": "sudo tcpdump -i wlo1" }, { "code": null, "e": 990, "s": 919, "text": "This command will now capture the packets from wlo1 network interface." }, { "code": null, "e": 1031, "s": 990, "text": "3. To capture specific number of packets" }, { "code": null, "e": 1057, "s": 1031, "text": "sudo tcpdump -c 4 -i wlo1" }, { "code": null, "e": 1123, "s": 1057, "text": "This command will capture only 4 packets from the wlo1 interface." }, { "code": null, "e": 1169, "s": 1123, "text": "4. To print captured packages in ASCII format" }, { "code": null, "e": 1193, "s": 1169, "text": "sudo tcpdump -A -i wlo1" }, { "code": null, "e": 1268, "s": 1193, "text": "This command will now print the captured packets from wlo1 to ASCII value." }, { "code": null, "e": 1307, "s": 1268, "text": "5. To display all available interfaces" }, { "code": null, "e": 1323, "s": 1307, "text": "sudo tcpdump -D" }, { "code": null, "e": 1402, "s": 1323, "text": "This command will display all the interfaces that are available in the system." }, { "code": null, "e": 1448, "s": 1402, "text": "6. To display packets in HEX and ASCII values" }, { "code": null, "e": 1473, "s": 1448, "text": "sudo tcpdump -XX -i wlo1" }, { "code": null, "e": 1576, "s": 1473, "text": "This command will now print the packages captured from the wlo1 interface in the HEX and ASCII values." }, { "code": null, "e": 1616, "s": 1576, "text": "7. To save captured packets into a file" }, { "code": null, "e": 1662, "s": 1616, "text": "sudo tcpdump -w captured_packets.pcap -i wlo1" }, { "code": null, "e": 1758, "s": 1662, "text": "This command will now output all the captures packets in a file named as captured_packets.pcap." }, { "code": null, "e": 1798, "s": 1758, "text": "8. To read captured packets from a file" }, { "code": null, "e": 1836, "s": 1798, "text": "sudo tcpdump -r captured_packets.pcap" }, { "code": null, "e": 1921, "s": 1836, "text": "This command will now read the captured packets from the captured_packets.pcap file." }, { "code": null, "e": 1959, "s": 1921, "text": "9. To capture packets with ip address" }, { "code": null, "e": 1983, "s": 1959, "text": "sudo tcpdump -n -i wlo1" }, { "code": null, "e": 2044, "s": 1983, "text": "This command will now capture the packets with IP addresses." }, { "code": null, "e": 2076, "s": 2044, "text": "10. To capture only TCP packets" }, { "code": null, "e": 2101, "s": 2076, "text": "sudo tcpdump -i wlo1 tcp" }, { "code": null, "e": 2159, "s": 2101, "text": "This command will now capture only TCP packets from wlo1." }, { "code": null, "e": 2173, "s": 2159, "text": "linux-command" }, { "code": null, "e": 2199, "s": 2173, "text": "Linux-networking-commands" }, { "code": null, "e": 2210, "s": 2199, "text": "Linux-Unix" }, { "code": null, "e": 2308, "s": 2210, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2343, "s": 2308, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 2378, "s": 2343, "text": "tar command in Linux with examples" }, { "code": null, "e": 2414, "s": 2378, "text": "curl command in Linux with Examples" }, { "code": null, "e": 2455, "s": 2414, "text": "SORT command in Linux/Unix with examples" }, { "code": null, "e": 2493, "s": 2455, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 2531, "s": 2493, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 2567, "s": 2531, "text": "Tail command in Linux with examples" }, { "code": null, "e": 2593, "s": 2567, "text": "Docker - COPY Instruction" }, { "code": null, "e": 2628, "s": 2593, "text": "scp command in Linux with Examples" } ]
Difference between Procedural and Non-Procedural language
28 May, 2019 Procedural Language:In procedural languages, the program code is written as a sequence of instructions. User has to specify “what to do” and also “how to do” (step by step procedure). These instructions are executed in the sequential order. These instructions are written to solve specific problems. Examples of Procedural languages: FORTRAN, COBOL, ALGOL, BASIC, C and Pascal. Non-Procedural Language:In the non-procedural languages, the user has to specify only “what to do” and not “how to do”. It is also known as an applicative or functional language. It involves the development of the functions from other functions to construct more complex functions. Examples of Non-Procedural languages: SQL, PROLOG, LISP. Difference between Procedural and Non-Procedural language: Difference Between Programming Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n28 May, 2019" }, { "code": null, "e": 353, "s": 53, "text": "Procedural Language:In procedural languages, the program code is written as a sequence of instructions. User has to specify “what to do” and also “how to do” (step by step procedure). These instructions are executed in the sequential order. These instructions are written to solve specific problems." }, { "code": null, "e": 431, "s": 353, "text": "Examples of Procedural languages:\nFORTRAN, COBOL, ALGOL, BASIC, C and Pascal." }, { "code": null, "e": 713, "s": 431, "text": "Non-Procedural Language:In the non-procedural languages, the user has to specify only “what to do” and not “how to do”. It is also known as an applicative or functional language. It involves the development of the functions from other functions to construct more complex functions." }, { "code": null, "e": 770, "s": 713, "text": "Examples of Non-Procedural languages:\nSQL, PROLOG, LISP." }, { "code": null, "e": 829, "s": 770, "text": "Difference between Procedural and Non-Procedural language:" }, { "code": null, "e": 848, "s": 829, "text": "Difference Between" }, { "code": null, "e": 869, "s": 848, "text": "Programming Language" } ]
Sum of n digit numbers divisible by a given number
02 Jun, 2022 Given n and a number, the task is to find the sum of n digit numbers that are divisible by given number. Examples: Input : n = 2, number = 7 Output : 728 There are thirteen n digit numbers that are divisible by 7. Numbers are : 14+ 21 + 28 + 35 + 42 + 49 + 56 + 63 +70 + 77 + 84 + 91 + 98. Input : n = 3, number = 7 Output : 70336 Input : n = 3, number = 4 Output : 124200 Native Approach: Traverse through all n digit numbers. For every number check for divisibility, and make the sum. C++ Java Python3 C# PHP Javascript // Simple CPP program to sum of n digit// divisible numbers.#include <cmath>#include <iostream>using namespace std; // Returns sum of n digit numbers// divisible by 'number'int totalSumDivisibleByNum(int n, int number){ // compute the first and last term int firstnum = pow(10, n - 1); int lastnum = pow(10, n); // sum of number which having // n digit and divisible by number int sum = 0; for (int i = firstnum; i < lastnum; i++) if (i % number == 0) sum += i; return sum;} // Driver codeint main(){ int n = 3, num = 7; cout << totalSumDivisibleByNum(n, num) << "\n"; return 0;} // Simple Java program to sum of n digit// divisible numbers.import java.io.*; class GFG { // Returns sum of n digit numbers // divisible by 'number' static int totalSumDivisibleByNum(int n, int number) { // compute the first and last term int firstnum = (int)Math.pow(10, n - 1); int lastnum = (int)Math.pow(10, n); // sum of number which having // n digit and divisible by number int sum = 0; for (int i = firstnum; i < lastnum; i++) if (i % number == 0) sum += i; return sum; } // Driver code public static void main (String[] args) { int n = 3, num = 7; System.out.println(totalSumDivisibleByNum(n, num)); }} // This code is contributed by Ajit. # Simple Python 3 program to sum # of n digit divisible numbers. # Returns sum of n digit numbers# divisible by 'number'def totalSumDivisibleByNum(n, number): # compute the first and last term firstnum = pow(10, n - 1) lastnum = pow(10, n) # sum of number which having # n digit and divisible by number sum = 0 for i in range(firstnum, lastnum): if (i % number == 0): sum += i return sum # Driver coden = 3; num = 7print(totalSumDivisibleByNum(n, num)) # This code is contributed by Smitha Dinesh Semwal // Simple C# program to sum of n digit// divisible numbers.using System; class GFG { // Returns sum of n digit numbers // divisible by 'number' static int totalSumDivisibleByNum(int n, int number) { // compute the first and last term int firstnum = (int)Math.Pow(10, n - 1); int lastnum = (int)Math.Pow(10, n); // sum of number which having // n digit and divisible by number int sum = 0; for (int i = firstnum; i < lastnum; i++) if (i % number == 0) sum += i; return sum; } // Driver code public static void Main () { int n = 3, num = 7; Console.WriteLine(totalSumDivisibleByNum(n, num)); }} // This code is contributed by vt_m. <?php// Simple PHP program to sum of// n digit divisible numbers. // Returns sum of n digit numbers// divisible by 'number'function totalSumDivisibleByNum($n, $number){ // compute the first and last term $firstnum = pow(10, $n - 1); $lastnum = pow(10, $n); // sum of number which having // n digit and divisible by number $sum = 0; for ($i = $firstnum; $i < $lastnum; $i++) if ($i % $number == 0) $sum += $i; return $sum;} // Driver code $n = 3;$num = 7; echo totalSumDivisibleByNum($n, $num) , "\n"; // This code is contributed by aj_36?> <script> // JavaScript program to sum of n digit// divisible numbers. // Returns sum of n digit numbers// divisible by 'number'function totalSumDivisibleByNum(n, number){ // compute the first and last term let firstnum = Math.pow(10, n - 1); let lastnum = Math.pow(10, n); // sum of number which having // n digit and divisible by number let sum = 0; for(let i = firstnum; i < lastnum; i++) if (i % number == 0) sum += i; return sum;} // Driver Codelet n = 3, num = 7; document.write(totalSumDivisibleByNum(n, num)); // This code is contributed by chinmoy1997pal </script> 70336 Time Complexity: O(10n) Auxiliary Space: O(1) Efficient Method : First, find the count of n digit numbers divisible by a given number. Then apply formula for sum of AP. count/2 * (first-term + last-term) C++ Java Python3 C# PHP Javascript // Efficient CPP program to find the sum// divisible numbers.#include <cmath>#include <iostream>using namespace std; // find the Sum of having n digit and// divisible by the numberint totalSumDivisibleByNum(int digit, int number){ // compute the first and last term int firstnum = pow(10, digit - 1); int lastnum = pow(10, digit); // first number which is divisible // by given number firstnum = (firstnum - firstnum % number) + number; // last number which is divisible // by given number lastnum = (lastnum - lastnum % number); // total divisible number int count = ((lastnum - firstnum) / number + 1); // return the total sum return ((lastnum + firstnum) * count) / 2;} int main(){ int n = 3, number = 7; cout << totalSumDivisibleByNum(n, number); return 0;} // Efficient Java program to find the sum// divisible numbers.import java.io.*; class GFG { // find the Sum of having n digit and // divisible by the number static int totalSumDivisibleByNum(int digit, int number) { // compute the first and last term int firstnum = (int)Math.pow(10, digit - 1); int lastnum = (int)Math.pow(10, digit); // first number which is divisible // by given number firstnum = (firstnum - firstnum % number) + number; // last number which is divisible // by given number lastnum = (lastnum - lastnum % number); // total divisible number int count = ((lastnum - firstnum) / number + 1); // return the total sum return ((lastnum + firstnum) * count) / 2; } // Driver code public static void main (String[] args) { int n = 3, number = 7; System.out.println(totalSumDivisibleByNum(n, number)); }} // This code is contributed by Ajit. # Efficient Python3 program to # find the sum divisible numbers. # find the Sum of having n digit# and divisible by the numberdef totalSumDivisibleByNum(digit, number): # compute the first and last term firstnum = pow(10, digit - 1) lastnum = pow(10, digit) # first number which is divisible # by given number firstnum = (firstnum - firstnum % number) + number # last number which is divisible # by given number lastnum = (lastnum - lastnum % number) # total divisible number count = ((lastnum - firstnum) / number + 1) # return the total sum return int(((lastnum + firstnum) * count) / 2) # Driver codedigit = 3; num = 7print(totalSumDivisibleByNum(digit, num)) # This code is contributed by Smitha Dinesh Semwal // Efficient Java program to find the sum// divisible numbers.using System; class GFG { // find the Sum of having n digit and // divisible by the number static int totalSumDivisibleByNum(int digit, int number) { // compute the first and last term int firstnum = (int)Math.Pow(10, digit - 1); int lastnum = (int)Math.Pow(10, digit); // first number which is divisible // by given number firstnum = (firstnum - firstnum % number) + number; // last number which is divisible // by given number lastnum = (lastnum - lastnum % number); // total divisible number int count = ((lastnum - firstnum) / number + 1); // return the total sum return ((lastnum + firstnum) * count) / 2; } // Driver code public static void Main () { int n = 3, number = 7; Console.WriteLine(totalSumDivisibleByNum(n, number)); }} // This code is contributed by vt_m. <?php// Efficient PHP program to find// the sum divisible numbers. // find the Sum of having n digit and// divisible by the numberfunction totalSumDivisibleByNum($digit, $number){ // compute the first and last term $firstnum = pow(10, $digit - 1); $lastnum = pow(10, $digit); // first number which is divisible // by given number $firstnum = ($firstnum - $firstnum % $number) + $number; // last number which is divisible // by given number $lastnum = ($lastnum - $lastnum % $number); // total divisible number $count = (($lastnum - $firstnum) / $number + 1); // return the total sum return (($lastnum + $firstnum) * $count) / 2;} // Driver Code $n = 3; $number = 7; echo totalSumDivisibleByNum($n, $number); // This code is contributed by anuj_67.?> <script> // Efficient Javascript program to find// the sum divisible numbers. // Find the Sum of having n digit and// divisible by the numberfunction totalSumDivisibleByNum(digit, number){ // Compute the first and last term let firstnum = Math.pow(10, digit - 1); let lastnum = Math.pow(10, digit); // First number which is divisible // by given number firstnum = (firstnum - firstnum % number) + number; // Last number which is divisible // by given number lastnum = (lastnum - lastnum % number); // Total divisible number let count = ((lastnum - firstnum) / number + 1); // Return the total sum return ((lastnum + firstnum) * count) / 2;} // Driver Codelet n = 3, number = 7; document.write(totalSumDivisibleByNum(n, number)); // This code is contributed by divyesh072019 </script> 70336 Time Complexity: O(1) Auxiliary Space: O(1) jit_t vt_m chinmoy1997pal divyesh072019 sidkr262001 adnanirshad158 rohitmishra051000 arithmetic progression divisibility number-digits Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n02 Jun, 2022" }, { "code": null, "e": 159, "s": 54, "text": "Given n and a number, the task is to find the sum of n digit numbers that are divisible by given number." }, { "code": null, "e": 170, "s": 159, "text": "Examples: " }, { "code": null, "e": 434, "s": 170, "text": "Input : n = 2, number = 7\nOutput : 728\nThere are thirteen n digit numbers that are divisible by 7.\n Numbers are : 14+ 21 + 28 + 35 + 42 + 49 + 56 + 63 +70 + 77 + 84 + 91 + 98.\n\nInput : n = 3, number = 7\nOutput : 70336\n\nInput : n = 3, number = 4\nOutput : 124200\n " }, { "code": null, "e": 550, "s": 434, "text": "Native Approach: Traverse through all n digit numbers. For every number check for divisibility, and make the sum. " }, { "code": null, "e": 554, "s": 550, "text": "C++" }, { "code": null, "e": 559, "s": 554, "text": "Java" }, { "code": null, "e": 567, "s": 559, "text": "Python3" }, { "code": null, "e": 570, "s": 567, "text": "C#" }, { "code": null, "e": 574, "s": 570, "text": "PHP" }, { "code": null, "e": 585, "s": 574, "text": "Javascript" }, { "code": "// Simple CPP program to sum of n digit// divisible numbers.#include <cmath>#include <iostream>using namespace std; // Returns sum of n digit numbers// divisible by 'number'int totalSumDivisibleByNum(int n, int number){ // compute the first and last term int firstnum = pow(10, n - 1); int lastnum = pow(10, n); // sum of number which having // n digit and divisible by number int sum = 0; for (int i = firstnum; i < lastnum; i++) if (i % number == 0) sum += i; return sum;} // Driver codeint main(){ int n = 3, num = 7; cout << totalSumDivisibleByNum(n, num) << \"\\n\"; return 0;}", "e": 1221, "s": 585, "text": null }, { "code": "// Simple Java program to sum of n digit// divisible numbers.import java.io.*; class GFG { // Returns sum of n digit numbers // divisible by 'number' static int totalSumDivisibleByNum(int n, int number) { // compute the first and last term int firstnum = (int)Math.pow(10, n - 1); int lastnum = (int)Math.pow(10, n); // sum of number which having // n digit and divisible by number int sum = 0; for (int i = firstnum; i < lastnum; i++) if (i % number == 0) sum += i; return sum; } // Driver code public static void main (String[] args) { int n = 3, num = 7; System.out.println(totalSumDivisibleByNum(n, num)); }} // This code is contributed by Ajit.", "e": 2009, "s": 1221, "text": null }, { "code": "# Simple Python 3 program to sum # of n digit divisible numbers. # Returns sum of n digit numbers# divisible by 'number'def totalSumDivisibleByNum(n, number): # compute the first and last term firstnum = pow(10, n - 1) lastnum = pow(10, n) # sum of number which having # n digit and divisible by number sum = 0 for i in range(firstnum, lastnum): if (i % number == 0): sum += i return sum # Driver coden = 3; num = 7print(totalSumDivisibleByNum(n, num)) # This code is contributed by Smitha Dinesh Semwal", "e": 2562, "s": 2009, "text": null }, { "code": "// Simple C# program to sum of n digit// divisible numbers.using System; class GFG { // Returns sum of n digit numbers // divisible by 'number' static int totalSumDivisibleByNum(int n, int number) { // compute the first and last term int firstnum = (int)Math.Pow(10, n - 1); int lastnum = (int)Math.Pow(10, n); // sum of number which having // n digit and divisible by number int sum = 0; for (int i = firstnum; i < lastnum; i++) if (i % number == 0) sum += i; return sum; } // Driver code public static void Main () { int n = 3, num = 7; Console.WriteLine(totalSumDivisibleByNum(n, num)); }} // This code is contributed by vt_m.", "e": 3374, "s": 2562, "text": null }, { "code": "<?php// Simple PHP program to sum of// n digit divisible numbers. // Returns sum of n digit numbers// divisible by 'number'function totalSumDivisibleByNum($n, $number){ // compute the first and last term $firstnum = pow(10, $n - 1); $lastnum = pow(10, $n); // sum of number which having // n digit and divisible by number $sum = 0; for ($i = $firstnum; $i < $lastnum; $i++) if ($i % $number == 0) $sum += $i; return $sum;} // Driver code $n = 3;$num = 7; echo totalSumDivisibleByNum($n, $num) , \"\\n\"; // This code is contributed by aj_36?>", "e": 3980, "s": 3374, "text": null }, { "code": "<script> // JavaScript program to sum of n digit// divisible numbers. // Returns sum of n digit numbers// divisible by 'number'function totalSumDivisibleByNum(n, number){ // compute the first and last term let firstnum = Math.pow(10, n - 1); let lastnum = Math.pow(10, n); // sum of number which having // n digit and divisible by number let sum = 0; for(let i = firstnum; i < lastnum; i++) if (i % number == 0) sum += i; return sum;} // Driver Codelet n = 3, num = 7; document.write(totalSumDivisibleByNum(n, num)); // This code is contributed by chinmoy1997pal </script>", "e": 4632, "s": 3980, "text": null }, { "code": null, "e": 4638, "s": 4632, "text": "70336" }, { "code": null, "e": 4664, "s": 4640, "text": "Time Complexity: O(10n)" }, { "code": null, "e": 4686, "s": 4664, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 4810, "s": 4686, "text": "Efficient Method : First, find the count of n digit numbers divisible by a given number. Then apply formula for sum of AP. " }, { "code": null, "e": 4850, "s": 4810, "text": " count/2 * (first-term + last-term)" }, { "code": null, "e": 4854, "s": 4850, "text": "C++" }, { "code": null, "e": 4859, "s": 4854, "text": "Java" }, { "code": null, "e": 4867, "s": 4859, "text": "Python3" }, { "code": null, "e": 4870, "s": 4867, "text": "C#" }, { "code": null, "e": 4874, "s": 4870, "text": "PHP" }, { "code": null, "e": 4885, "s": 4874, "text": "Javascript" }, { "code": "// Efficient CPP program to find the sum// divisible numbers.#include <cmath>#include <iostream>using namespace std; // find the Sum of having n digit and// divisible by the numberint totalSumDivisibleByNum(int digit, int number){ // compute the first and last term int firstnum = pow(10, digit - 1); int lastnum = pow(10, digit); // first number which is divisible // by given number firstnum = (firstnum - firstnum % number) + number; // last number which is divisible // by given number lastnum = (lastnum - lastnum % number); // total divisible number int count = ((lastnum - firstnum) / number + 1); // return the total sum return ((lastnum + firstnum) * count) / 2;} int main(){ int n = 3, number = 7; cout << totalSumDivisibleByNum(n, number); return 0;}", "e": 5789, "s": 4885, "text": null }, { "code": "// Efficient Java program to find the sum// divisible numbers.import java.io.*; class GFG { // find the Sum of having n digit and // divisible by the number static int totalSumDivisibleByNum(int digit, int number) { // compute the first and last term int firstnum = (int)Math.pow(10, digit - 1); int lastnum = (int)Math.pow(10, digit); // first number which is divisible // by given number firstnum = (firstnum - firstnum % number) + number; // last number which is divisible // by given number lastnum = (lastnum - lastnum % number); // total divisible number int count = ((lastnum - firstnum) / number + 1); // return the total sum return ((lastnum + firstnum) * count) / 2; } // Driver code public static void main (String[] args) { int n = 3, number = 7; System.out.println(totalSumDivisibleByNum(n, number)); }} // This code is contributed by Ajit.", "e": 6887, "s": 5789, "text": null }, { "code": "# Efficient Python3 program to # find the sum divisible numbers. # find the Sum of having n digit# and divisible by the numberdef totalSumDivisibleByNum(digit, number): # compute the first and last term firstnum = pow(10, digit - 1) lastnum = pow(10, digit) # first number which is divisible # by given number firstnum = (firstnum - firstnum % number) + number # last number which is divisible # by given number lastnum = (lastnum - lastnum % number) # total divisible number count = ((lastnum - firstnum) / number + 1) # return the total sum return int(((lastnum + firstnum) * count) / 2) # Driver codedigit = 3; num = 7print(totalSumDivisibleByNum(digit, num)) # This code is contributed by Smitha Dinesh Semwal", "e": 7646, "s": 6887, "text": null }, { "code": "// Efficient Java program to find the sum// divisible numbers.using System; class GFG { // find the Sum of having n digit and // divisible by the number static int totalSumDivisibleByNum(int digit, int number) { // compute the first and last term int firstnum = (int)Math.Pow(10, digit - 1); int lastnum = (int)Math.Pow(10, digit); // first number which is divisible // by given number firstnum = (firstnum - firstnum % number) + number; // last number which is divisible // by given number lastnum = (lastnum - lastnum % number); // total divisible number int count = ((lastnum - firstnum) / number + 1); // return the total sum return ((lastnum + firstnum) * count) / 2; } // Driver code public static void Main () { int n = 3, number = 7; Console.WriteLine(totalSumDivisibleByNum(n, number)); }} // This code is contributed by vt_m.", "e": 8739, "s": 7646, "text": null }, { "code": "<?php// Efficient PHP program to find// the sum divisible numbers. // find the Sum of having n digit and// divisible by the numberfunction totalSumDivisibleByNum($digit, $number){ // compute the first and last term $firstnum = pow(10, $digit - 1); $lastnum = pow(10, $digit); // first number which is divisible // by given number $firstnum = ($firstnum - $firstnum % $number) + $number; // last number which is divisible // by given number $lastnum = ($lastnum - $lastnum % $number); // total divisible number $count = (($lastnum - $firstnum) / $number + 1); // return the total sum return (($lastnum + $firstnum) * $count) / 2;} // Driver Code $n = 3; $number = 7; echo totalSumDivisibleByNum($n, $number); // This code is contributed by anuj_67.?>", "e": 9665, "s": 8739, "text": null }, { "code": "<script> // Efficient Javascript program to find// the sum divisible numbers. // Find the Sum of having n digit and// divisible by the numberfunction totalSumDivisibleByNum(digit, number){ // Compute the first and last term let firstnum = Math.pow(10, digit - 1); let lastnum = Math.pow(10, digit); // First number which is divisible // by given number firstnum = (firstnum - firstnum % number) + number; // Last number which is divisible // by given number lastnum = (lastnum - lastnum % number); // Total divisible number let count = ((lastnum - firstnum) / number + 1); // Return the total sum return ((lastnum + firstnum) * count) / 2;} // Driver Codelet n = 3, number = 7; document.write(totalSumDivisibleByNum(n, number)); // This code is contributed by divyesh072019 </script>", "e": 10540, "s": 9665, "text": null }, { "code": null, "e": 10546, "s": 10540, "text": "70336" }, { "code": null, "e": 10570, "s": 10548, "text": "Time Complexity: O(1)" }, { "code": null, "e": 10592, "s": 10570, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 10598, "s": 10592, "text": "jit_t" }, { "code": null, "e": 10603, "s": 10598, "text": "vt_m" }, { "code": null, "e": 10618, "s": 10603, "text": "chinmoy1997pal" }, { "code": null, "e": 10632, "s": 10618, "text": "divyesh072019" }, { "code": null, "e": 10644, "s": 10632, "text": "sidkr262001" }, { "code": null, "e": 10659, "s": 10644, "text": "adnanirshad158" }, { "code": null, "e": 10677, "s": 10659, "text": "rohitmishra051000" }, { "code": null, "e": 10700, "s": 10677, "text": "arithmetic progression" }, { "code": null, "e": 10713, "s": 10700, "text": "divisibility" }, { "code": null, "e": 10727, "s": 10713, "text": "number-digits" }, { "code": null, "e": 10740, "s": 10727, "text": "Mathematical" }, { "code": null, "e": 10753, "s": 10740, "text": "Mathematical" } ]
time.Nanoseconds() Function in Golang With Examples
21 Apr, 2020 In Go language, time packages supplies functionality for determining as well as viewing time. The Nanoseconds() function in Go language is used to find the duration of time in form of an integer nanosecond count. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions. Syntax: func (d Duration) Nanoseconds() int64 Here, d is the duration of time. Return Value: It returns the duration value as int64. Example 1: // Golang program to illustrate the usage of// Nanoseconds() function // Including main packagepackage main // Importing fmt and timeimport ( "fmt" "time") // Calling mainfunc main() { // Defining duration // of Nanoseconds method nano, _ := time.ParseDuration("8s") // Prints duration as int64 fmt.Printf("Only %d nanoseconds of"+ " task is remaining.", nano.Nanoseconds())} Output: Only 8000000000 nanoseconds of task is remaining. Example 2: // Golang program to illustrate the usage of// Nanoseconds() function // Including main packagepackage main // Importing fmt and timeimport ( "fmt" "time") // Calling mainfunc main() { // Defining duration of Nanoseconds method nano, _ := time.ParseDuration("56m7855s576567576ms") // Prints duration as int64 fmt.Printf("Only %d nanoseconds of task"+ " is remaining.", nano.Nanoseconds())} Output: Only 587782576000000 nanoseconds of task is remaining. GoLang-time Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Go Golang Maps How to Split a String in Golang? Interfaces in Golang Slices in Golang Different Ways to Find the Type of Variable in Golang How to Parse JSON in Golang? How to Trim a String in Golang? How to compare times in Golang? Inheritance in GoLang
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Apr, 2020" }, { "code": null, "e": 377, "s": 28, "text": "In Go language, time packages supplies functionality for determining as well as viewing time. The Nanoseconds() function in Go language is used to find the duration of time in form of an integer nanosecond count. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions." }, { "code": null, "e": 385, "s": 377, "text": "Syntax:" }, { "code": null, "e": 424, "s": 385, "text": "func (d Duration) Nanoseconds() int64\n" }, { "code": null, "e": 457, "s": 424, "text": "Here, d is the duration of time." }, { "code": null, "e": 511, "s": 457, "text": "Return Value: It returns the duration value as int64." }, { "code": null, "e": 522, "s": 511, "text": "Example 1:" }, { "code": "// Golang program to illustrate the usage of// Nanoseconds() function // Including main packagepackage main // Importing fmt and timeimport ( \"fmt\" \"time\") // Calling mainfunc main() { // Defining duration // of Nanoseconds method nano, _ := time.ParseDuration(\"8s\") // Prints duration as int64 fmt.Printf(\"Only %d nanoseconds of\"+ \" task is remaining.\", nano.Nanoseconds())}", "e": 931, "s": 522, "text": null }, { "code": null, "e": 939, "s": 931, "text": "Output:" }, { "code": null, "e": 990, "s": 939, "text": "Only 8000000000 nanoseconds of task is remaining.\n" }, { "code": null, "e": 1001, "s": 990, "text": "Example 2:" }, { "code": "// Golang program to illustrate the usage of// Nanoseconds() function // Including main packagepackage main // Importing fmt and timeimport ( \"fmt\" \"time\") // Calling mainfunc main() { // Defining duration of Nanoseconds method nano, _ := time.ParseDuration(\"56m7855s576567576ms\") // Prints duration as int64 fmt.Printf(\"Only %d nanoseconds of task\"+ \" is remaining.\", nano.Nanoseconds())}", "e": 1422, "s": 1001, "text": null }, { "code": null, "e": 1430, "s": 1422, "text": "Output:" }, { "code": null, "e": 1486, "s": 1430, "text": "Only 587782576000000 nanoseconds of task is remaining.\n" }, { "code": null, "e": 1498, "s": 1486, "text": "GoLang-time" }, { "code": null, "e": 1510, "s": 1498, "text": "Go Language" }, { "code": null, "e": 1608, "s": 1510, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1621, "s": 1608, "text": "Arrays in Go" }, { "code": null, "e": 1633, "s": 1621, "text": "Golang Maps" }, { "code": null, "e": 1666, "s": 1633, "text": "How to Split a String in Golang?" }, { "code": null, "e": 1687, "s": 1666, "text": "Interfaces in Golang" }, { "code": null, "e": 1704, "s": 1687, "text": "Slices in Golang" }, { "code": null, "e": 1758, "s": 1704, "text": "Different Ways to Find the Type of Variable in Golang" }, { "code": null, "e": 1787, "s": 1758, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 1819, "s": 1787, "text": "How to Trim a String in Golang?" }, { "code": null, "e": 1851, "s": 1819, "text": "How to compare times in Golang?" } ]
SQL | Remove Duplicates without Distinct
06 Apr, 2020 DISTINCT is useful in certain circumstances, but it has drawback that it can increase load on the query engine to perform the sort (since it needs to compare the result set to itself to remove duplicates) Below are alternate solutions : 1. Remove Duplicates Using Row_Number. WITH CTE (Col1, Col2, Col3, DuplicateCount) AS ( SELECT Col1, Col2, Col3, ROW_NUMBER() OVER(PARTITION BY Col1, Col2, Col3 ORDER BY Col1) AS DuplicateCount FROM MyTable ) SELECT * from CTE Where DuplicateCount = 1 2.Remove Duplicates using self JoinYourTable emp_name emp_address sex matial_status uuuu eee m s iiii iii f s uuuu eee m s SELECT emp_name, emp_address, sex, marital_status from YourTable a WHERE NOT EXISTS (select 1 from YourTable b where b.emp_name = a.emp_name and b.emp_address = a.emp_address and b.sex = a.sex and b.create_date >= a.create_date) 3. Remove Duplicates using group ByThe idea is to group according to all columns to be selected in output. For example, if we wish to print unique values of “FirstName, LastName and MobileNo”, we can simply group by all three of these. SELECT FirstName, LastName, MobileNo FROM CUSTOMER GROUP BY FirstName, LastName, MobileNo; Subha Saha SQL-basics SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Apr, 2020" }, { "code": null, "e": 257, "s": 52, "text": "DISTINCT is useful in certain circumstances, but it has drawback that it can increase load on the query engine to perform the sort (since it needs to compare the result set to itself to remove duplicates)" }, { "code": null, "e": 289, "s": 257, "text": "Below are alternate solutions :" }, { "code": null, "e": 328, "s": 289, "text": "1. Remove Duplicates Using Row_Number." }, { "code": null, "e": 554, "s": 328, "text": "WITH CTE (Col1, Col2, Col3, DuplicateCount)\nAS\n(\n SELECT Col1, Col2, Col3,\n ROW_NUMBER() OVER(PARTITION BY Col1, Col2,\n Col3 ORDER BY Col1) AS DuplicateCount\n FROM MyTable\n) SELECT * from CTE Where DuplicateCount = 1" }, { "code": null, "e": 599, "s": 554, "text": "2.Remove Duplicates using self JoinYourTable" }, { "code": null, "e": 737, "s": 599, "text": "emp_name emp_address sex matial_status \nuuuu eee m s\niiii iii f s\nuuuu eee m s" }, { "code": null, "e": 1030, "s": 737, "text": "SELECT emp_name, emp_address, sex, marital_status\nfrom YourTable a\nWHERE NOT EXISTS (select 1 \n from YourTable b\n where b.emp_name = a.emp_name and\n b.emp_address = a.emp_address and\n b.sex = a.sex and\n b.create_date >= a.create_date)" }, { "code": null, "e": 1266, "s": 1030, "text": "3. Remove Duplicates using group ByThe idea is to group according to all columns to be selected in output. For example, if we wish to print unique values of “FirstName, LastName and MobileNo”, we can simply group by all three of these." }, { "code": null, "e": 1359, "s": 1266, "text": "SELECT FirstName, LastName, MobileNo\nFROM CUSTOMER\nGROUP BY FirstName, LastName, MobileNo;\n" }, { "code": null, "e": 1370, "s": 1359, "text": "Subha Saha" }, { "code": null, "e": 1381, "s": 1370, "text": "SQL-basics" }, { "code": null, "e": 1385, "s": 1381, "text": "SQL" }, { "code": null, "e": 1389, "s": 1385, "text": "SQL" } ]
Where is an object stored if it is created inside a block in C++?
26 Nov, 2018 There are two parts of memory in which an object can be stored: stack – Memory from the stack is used by all the members which are declared inside blocks/functions. Note that the main is also a function.heap – This memory is unused and can be used to dynamically allocate the memory at runtime. stack – Memory from the stack is used by all the members which are declared inside blocks/functions. Note that the main is also a function. heap – This memory is unused and can be used to dynamically allocate the memory at runtime. The scope of the object created inside a block or a function is limited to the block in which it is created. The object created inside the block will be stored in the stack and Object is destroyed and removed from the stack when the function/block exits. But if we create the object at runtime i.e by dynamic memory allocation then the object will be stored on the heap. This is done with the help of new operator. In this case, we need to explicitly destroy the object using delete operator. Examples: Output: Inside Block1... length of rectangle is : 2 width of rectangle is :3 Destructor of rectangle with the exit of the block, destructor called automatically for the object stored in stack. ********************************************* Inside Block2 length of rectangle is : 5 width of rectangle is :6 Destructor of rectangle length of rectangle is : 0 width of rectangle is :0 Below is the program to show where the object is stored: // C++ program for required implementation#include <iostream>using namespace std; class Rectangle { int width; int length; public: Rectangle() { length = 0; width = 0; } Rectangle(int l, int w) { length = l; width = w; } ~Rectangle() { cout << "Destructor of rectangle" << endl; } int getLength() { return length; } int getWidth() { return width; }}; int main(){ // Object creation inside block { Rectangle r(2, 3); // r is stored on stack cout << "Inside Block1..." << endl; cout << "length of rectangle is : " << r.getLength() << endl; cout << "width of rectangle is :" << r.getWidth() << endl; } cout << " with the exit of the block, destructor\n" << " called automatically for the object stored in stack." << endl; /* // uncomment this code and run once you will get // the compilation error because the object is not in scope cout<<"length of rectangle is : "<< r.getLength(); cout<< "width of rectangle is :" << r.getWidth(); */ Rectangle* ptr2; { // object will be stored in heap // and pointer variable since its local // to block will be stored in the stack Rectangle* ptr3 = new Rectangle(5, 6); ptr2 = ptr3; cout << "********************************************" << endl; cout << "Inside Block2" << endl; cout << "length of rectangle is : " << ptr3->getLength() << endl; cout << "width of rectangle is :" << ptr3->getWidth() << endl; // comment below line of code and // uncomment *important line* // and then check the object will remain // alive outside the block. // explicitly destroy object stored on the heap delete ptr3; } cout << "length of rectangle is : " << ptr2->getLength() << endl; cout << "width of rectangle is :" << ptr2->getWidth() << endl; // delete ptr2; /* important line*/ return 0;} Inside Block1... length of rectangle is : 2 width of rectangle is :3 Destructor of rectangle with the exit of the block, destructor called automatically for the object stored in stack. ******************************************** Inside Block2 length of rectangle is : 5 width of rectangle is :6 Destructor of rectangle length of rectangle is : 0 width of rectangle is :0 C++-Class and Object C++-new and delete cpp-stack Picked C++ Heap Heap CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) std::string class in C++ HeapSort K'th Smallest/Largest Element in Unsorted Array | Set 1 Binary Heap Introduction to Data Structures Huffman Coding | Greedy Algo-3
[ { "code": null, "e": 53, "s": 25, "text": "\n26 Nov, 2018" }, { "code": null, "e": 117, "s": 53, "text": "There are two parts of memory in which an object can be stored:" }, { "code": null, "e": 348, "s": 117, "text": "stack – Memory from the stack is used by all the members which are declared inside blocks/functions. Note that the main is also a function.heap – This memory is unused and can be used to dynamically allocate the memory at runtime." }, { "code": null, "e": 488, "s": 348, "text": "stack – Memory from the stack is used by all the members which are declared inside blocks/functions. Note that the main is also a function." }, { "code": null, "e": 580, "s": 488, "text": "heap – This memory is unused and can be used to dynamically allocate the memory at runtime." }, { "code": null, "e": 689, "s": 580, "text": "The scope of the object created inside a block or a function is limited to the block in which it is created." }, { "code": null, "e": 835, "s": 689, "text": "The object created inside the block will be stored in the stack and Object is destroyed and removed from the stack when the function/block exits." }, { "code": null, "e": 1073, "s": 835, "text": "But if we create the object at runtime i.e by dynamic memory allocation then the object will be stored on the heap. This is done with the help of new operator. In this case, we need to explicitly destroy the object using delete operator." }, { "code": null, "e": 1083, "s": 1073, "text": "Examples:" }, { "code": null, "e": 1468, "s": 1083, "text": "Output:\nInside Block1...\nlength of rectangle is : 2\nwidth of rectangle is :3\nDestructor of rectangle\nwith the exit of the block, destructor called\nautomatically for the object stored in stack.\n*********************************************\nInside Block2\nlength of rectangle is : 5\nwidth of rectangle is :6\nDestructor of rectangle\nlength of rectangle is : 0\nwidth of rectangle is :0\n" }, { "code": null, "e": 1525, "s": 1468, "text": "Below is the program to show where the object is stored:" }, { "code": "// C++ program for required implementation#include <iostream>using namespace std; class Rectangle { int width; int length; public: Rectangle() { length = 0; width = 0; } Rectangle(int l, int w) { length = l; width = w; } ~Rectangle() { cout << \"Destructor of rectangle\" << endl; } int getLength() { return length; } int getWidth() { return width; }}; int main(){ // Object creation inside block { Rectangle r(2, 3); // r is stored on stack cout << \"Inside Block1...\" << endl; cout << \"length of rectangle is : \" << r.getLength() << endl; cout << \"width of rectangle is :\" << r.getWidth() << endl; } cout << \" with the exit of the block, destructor\\n\" << \" called automatically for the object stored in stack.\" << endl; /* // uncomment this code and run once you will get // the compilation error because the object is not in scope cout<<\"length of rectangle is : \"<< r.getLength(); cout<< \"width of rectangle is :\" << r.getWidth(); */ Rectangle* ptr2; { // object will be stored in heap // and pointer variable since its local // to block will be stored in the stack Rectangle* ptr3 = new Rectangle(5, 6); ptr2 = ptr3; cout << \"********************************************\" << endl; cout << \"Inside Block2\" << endl; cout << \"length of rectangle is : \" << ptr3->getLength() << endl; cout << \"width of rectangle is :\" << ptr3->getWidth() << endl; // comment below line of code and // uncomment *important line* // and then check the object will remain // alive outside the block. // explicitly destroy object stored on the heap delete ptr3; } cout << \"length of rectangle is : \" << ptr2->getLength() << endl; cout << \"width of rectangle is :\" << ptr2->getWidth() << endl; // delete ptr2; /* important line*/ return 0;}", "e": 3716, "s": 1525, "text": null }, { "code": null, "e": 4094, "s": 3716, "text": "Inside Block1...\nlength of rectangle is : 2\nwidth of rectangle is :3\nDestructor of rectangle\n with the exit of the block, destructor\n called automatically for the object stored in stack.\n********************************************\nInside Block2\nlength of rectangle is : 5\nwidth of rectangle is :6\nDestructor of rectangle\nlength of rectangle is : 0\nwidth of rectangle is :0\n" }, { "code": null, "e": 4115, "s": 4094, "text": "C++-Class and Object" }, { "code": null, "e": 4134, "s": 4115, "text": "C++-new and delete" }, { "code": null, "e": 4144, "s": 4134, "text": "cpp-stack" }, { "code": null, "e": 4151, "s": 4144, "text": "Picked" }, { "code": null, "e": 4155, "s": 4151, "text": "C++" }, { "code": null, "e": 4160, "s": 4155, "text": "Heap" }, { "code": null, "e": 4165, "s": 4160, "text": "Heap" }, { "code": null, "e": 4169, "s": 4165, "text": "CPP" }, { "code": null, "e": 4267, "s": 4169, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4291, "s": 4267, "text": "Sorting a vector in C++" }, { "code": null, "e": 4311, "s": 4291, "text": "Polymorphism in C++" }, { "code": null, "e": 4344, "s": 4311, "text": "Friend class and function in C++" }, { "code": null, "e": 4388, "s": 4344, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 4413, "s": 4388, "text": "std::string class in C++" }, { "code": null, "e": 4422, "s": 4413, "text": "HeapSort" }, { "code": null, "e": 4478, "s": 4422, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 4490, "s": 4478, "text": "Binary Heap" }, { "code": null, "e": 4522, "s": 4490, "text": "Introduction to Data Structures" } ]
How to check if a character in a string is a letter in Python?
You can use the isalpha() method from string class. It checks if a string consists only of alphabets. You can also use it to check if a character is an alphabet or not. For example, if you want to check if char at 5th index is letter or not, >>> s = "Hello people" >>> s[4].isalpha() True You can also check whole strings, if they are alphabetic or not. For example, >>> s = "Hello people" >>> s.isalpha() False >>> "Hello".isalpha() True
[ { "code": null, "e": 1429, "s": 1187, "text": "You can use the isalpha() method from string class. It checks if a string consists only of alphabets. You can also use it to check if a character is an alphabet or not. For example, if you want to check if char at 5th index is letter or not," }, { "code": null, "e": 1476, "s": 1429, "text": ">>> s = \"Hello people\"\n>>> s[4].isalpha()\nTrue" }, { "code": null, "e": 1554, "s": 1476, "text": "You can also check whole strings, if they are alphabetic or not. For example," }, { "code": null, "e": 1626, "s": 1554, "text": ">>> s = \"Hello people\"\n>>> s.isalpha()\nFalse\n>>> \"Hello\".isalpha()\nTrue" } ]
JavaTuples | Introduction
16 Sep, 2021 The word “tuple” means “a data structure consisting of multiple parts”. Hence Tuples can be defined as a data structure that can hold multiple values and these values may/may not be related to each other. Example: [Geeks, 123, &#*@] In this example, the values in the tuple are not at all related to each other. “Geeks” is a word that has a meaning. “123” are numbers. While “&#*@” are just some bunch of special characters. Hence the values in a tuple might or might not be related to each other. JavaTuples is a Java library that offers classes, functions and data structures to work with tuples. It is one of the simplest java library ever made. JavaTuples offers following classes to work with : JavaTuples allows maximum of 10 tuples. The classes for each are:For 1 element - Unit<A> For 2 elements - Pair<A, B> For 3 elements - Triplet<A, B, C> For 4 elements - Quartet<A, B, C, D> For 5 elements - Quintet<A, B, C, D, E> For 6 elements - Sextet<A, B, C, D, E, F> For 7 elements - Septet<A, B, C, D, E, F, G> For 8 elements - Octet<A, B, C, D, E, F, G, H> For 9 elements - Ennead<A, B, C, D, E, F, G, H, I> For 10 elements - Decade<A, B, C, D, E, F, G, H, I, J> For 1 element - Unit<A> For 2 elements - Pair<A, B> For 3 elements - Triplet<A, B, C> For 4 elements - Quartet<A, B, C, D> For 5 elements - Quintet<A, B, C, D, E> For 6 elements - Sextet<A, B, C, D, E, F> For 7 elements - Septet<A, B, C, D, E, F, G> For 8 elements - Octet<A, B, C, D, E, F, G, H> For 9 elements - Ennead<A, B, C, D, E, F, G, H, I> For 10 elements - Decade<A, B, C, D, E, F, G, H, I, J> JavaTuples also gives the 2 very common 2-element tuple classes equivalent to Pair:KeyValue<A, B> LabelValue<A, B> KeyValue<A, B> LabelValue<A, B> Note: To run the JavaTuples program, org.javatuples library needs to be added in the IDE. The IDE can be Netbeans, Eclipse, etc. Download JavaTuples Jar library here. To add a library in Netbeans, refer this. The basic characteristics of JavaTuples are: They are Typesafe They are Immutable They are Iterable They are Serializable They are Comparable (implements Comparable<Tuple>) They implement equals() and hashCode() They also implement toString() Think of a scenario where you want to store the details of a student in just one entity, like Name, Roll Number, Father’s Name, Contact Number. Now the most common approach that strikes the mind is to construct a data structure that would take the fields as required. This is where Tuples come into play. With Tuples, any separate data structure need not to be created. Instead, for this scenario, a Quartet<A, B, C, D> can be simply used. Therefore, common data structures like List, Array : Can be of a specific type only. Can be of infinite elements. Whereas, Tuples : Can be of any type, yet they are typesafe Can be of limited number only, from 1-10 JavaTuples library has many functions that help with the easy working of them. These are: Note: Below examples are shown to be as a generic approach. They can be used for any of the JavaTuple by replacing with the number of parameters and the corresponding Tuple class with values, as required. From Constructor:Syntax:NthTuple<type 1, type 2, .., type n> nthTuple = new NthTuple <type 1, type 2, .., type n>(value 1, value 2, .., value n); Example:Pair<Integer, String> pair = new Pair<Integer, String>( Integer.valurOf(1), "Geeks"); Sextet<Integer, String, Integer, String, Integer, String> sextet = new Sextet<Integer, String, Integer, String, Integer, String>( Integer.valueOf(1), "Geeks", Integer.valueOf(2), "For", Integer.valueOf(3), "Geeks" ); Syntax: NthTuple<type 1, type 2, .., type n> nthTuple = new NthTuple <type 1, type 2, .., type n>(value 1, value 2, .., value n); Example: Pair<Integer, String> pair = new Pair<Integer, String>( Integer.valurOf(1), "Geeks"); Sextet<Integer, String, Integer, String, Integer, String> sextet = new Sextet<Integer, String, Integer, String, Integer, String>( Integer.valueOf(1), "Geeks", Integer.valueOf(2), "For", Integer.valueOf(3), "Geeks" ); Using with() method:Syntax:NthTuple<type 1, type 2, .., type n> nthTuple = NthTuple.with(value 1, value 2, .., value n); Example:Pair<Integer, String> pair = Pair.with(Integer.valurOf(1), "Geeks"); Sextet<Integer, String, Integer, String, Integer, String> sextet = Sextet.with(Integer.valueOf(1), "Geeks", Integer.valueOf(2), "For", Integer.valueOf(3), "Geeks"); Syntax: NthTuple<type 1, type 2, .., type n> nthTuple = NthTuple.with(value 1, value 2, .., value n); Example: Pair<Integer, String> pair = Pair.with(Integer.valurOf(1), "Geeks"); Sextet<Integer, String, Integer, String, Integer, String> sextet = Sextet.with(Integer.valueOf(1), "Geeks", Integer.valueOf(2), "For", Integer.valueOf(3), "Geeks"); From other collections:Syntax:NthTuple<type, type, .., type> nthTuple = NthTuple.fromCollection(collectionWith_n_values); Example:Pair<String, String> pair = Pair.fromCollection(collectionWith2Values); Sextet<Integer, String, Integer, String, Integer, String> sextet = Sextet.fromCollection(collectionWith6Values); Syntax: NthTuple<type, type, .., type> nthTuple = NthTuple.fromCollection(collectionWith_n_values); Example: Pair<String, String> pair = Pair.fromCollection(collectionWith2Values); Sextet<Integer, String, Integer, String, Integer, String> sextet = Sextet.fromCollection(collectionWith6Values); Syntax:NthTuple<type 1, type 2, .., type n> nthTuple = new NthTuple <type 1, type 2, .., type n>(value 1, value 2, .., value n); typeX valX = nthTuple.getValueX-1(); NthTuple<type 1, type 2, .., type n> nthTuple = new NthTuple <type 1, type 2, .., type n>(value 1, value 2, .., value n); typeX valX = nthTuple.getValueX-1(); Example:Pair < Integer, String >pair = new Pair<Integer, String>(Integer.valurOf(1), "Geeks"); // This will set val2 = "Geeks"String val2 = pair.getValue1(); Sextet<Integer, String, Integer, String, Integer, String> sextet = new Sextet<Integer, String, Integer, String, Integer, String>( Integer.valueOf(1), "Geeks", Integer.valueOf(2), "For", Integer.valueOf(3), "Geeks" ); // This will set val5 = 3Integer val5 = sextet.getValue4();Note:Value numbering starts with index 0. Hence for nth value, the getter will be getValuen-1()NthTuple object can only have getValue0() to getValuen-1() valid getters (e.g. Sextet does not have a getValue6() method).All getValueX() getters are typesafe, i.e. no cast needed. It is because of the type parameterization of the tuple classes (the “” in Triplet) the compiler will know that value0 is of type A, value1 of type B, and so on.There is also a getValue(int pos) method, but its use is not recommended, because the compiler cannot know the type of the result beforehand and therefore a cast will be needed:Triplet<String, Integer, Double> triplet = ......Integer intVal = (Integer) triplet.getValue(1); Pair < Integer, String >pair = new Pair<Integer, String>(Integer.valurOf(1), "Geeks"); // This will set val2 = "Geeks"String val2 = pair.getValue1(); Sextet<Integer, String, Integer, String, Integer, String> sextet = new Sextet<Integer, String, Integer, String, Integer, String>( Integer.valueOf(1), "Geeks", Integer.valueOf(2), "For", Integer.valueOf(3), "Geeks" ); // This will set val5 = 3Integer val5 = sextet.getValue4(); Note: Value numbering starts with index 0. Hence for nth value, the getter will be getValuen-1() NthTuple object can only have getValue0() to getValuen-1() valid getters (e.g. Sextet does not have a getValue6() method). All getValueX() getters are typesafe, i.e. no cast needed. It is because of the type parameterization of the tuple classes (the “” in Triplet) the compiler will know that value0 is of type A, value1 of type B, and so on. There is also a getValue(int pos) method, but its use is not recommended, because the compiler cannot know the type of the result beforehand and therefore a cast will be needed:Triplet<String, Integer, Double> triplet = ......Integer intVal = (Integer) triplet.getValue(1); Triplet<String, Integer, Double> triplet = ......Integer intVal = (Integer) triplet.getValue(1); Classes KeyValue and LabelValue have their getValue0()/getValue1() methods renamed as getKey()/getValue() and getLabel()/getValue(), respectively. Since the JavaTuples are immutable, it means that modifying a value at any index is not possible.Hence JavaTuples offer setAtX(value) which creates a copy of the Tuple with a new value at index X, and returns that Tuple. Syntax: NthTuple<type 1, type 2, .., type n> nthTuple = new NthTuple <type 1, type 2, .., type n>(value 1, value 2, .., value n); nthTuple = nthTuple.setAtX(val); Example: Pair<Integer, String> pair = new Pair<Integer, String>( Integer.valueOf(1), "Geeks"); pair = pair.setAt1("For"); // This will return a pair (1, "For") Sextet<Integer, String, Integer, String, Integer, String> sextet = new Sextet<Integer, String, Integer, String, Integer, String>( Integer.valueOf(1), "Geeks", Integer.valueOf(2), "For", Integer.valueOf(3), "Geeks" ); // This will return sextet (1, "Geeks", 2, "For", 3, "Everyone")Sextet<Integer, String, Integer, String, Integer, String> otherSextet = sextet.setAt5("Everyone"); All tuple classes in javatuples implement the Iterable<Object> interface. It means that they can be iterated in the same way as collections or arrays. Example: Triplet<String, Integer, Double> triplet = ...... for (Object value : tuple){ ...} sagar0719kumar JavaTuples Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n16 Sep, 2021" }, { "code": null, "e": 258, "s": 53, "text": "The word “tuple” means “a data structure consisting of multiple parts”. Hence Tuples can be defined as a data structure that can hold multiple values and these values may/may not be related to each other." }, { "code": null, "e": 267, "s": 258, "text": "Example:" }, { "code": null, "e": 287, "s": 267, "text": "[Geeks, 123, &#*@]\n" }, { "code": null, "e": 552, "s": 287, "text": "In this example, the values in the tuple are not at all related to each other. “Geeks” is a word that has a meaning. “123” are numbers. While “&#*@” are just some bunch of special characters. Hence the values in a tuple might or might not be related to each other." }, { "code": null, "e": 703, "s": 552, "text": "JavaTuples is a Java library that offers classes, functions and data structures to work with tuples. It is one of the simplest java library ever made." }, { "code": null, "e": 754, "s": 703, "text": "JavaTuples offers following classes to work with :" }, { "code": null, "e": 1237, "s": 754, "text": "JavaTuples allows maximum of 10 tuples. The classes for each are:For 1 element - Unit<A>\nFor 2 elements - Pair<A, B> \nFor 3 elements - Triplet<A, B, C> \nFor 4 elements - Quartet<A, B, C, D> \nFor 5 elements - Quintet<A, B, C, D, E>\nFor 6 elements - Sextet<A, B, C, D, E, F> \nFor 7 elements - Septet<A, B, C, D, E, F, G>\nFor 8 elements - Octet<A, B, C, D, E, F, G, H>\nFor 9 elements - Ennead<A, B, C, D, E, F, G, H, I>\nFor 10 elements - Decade<A, B, C, D, E, F, G, H, I, J>\n" }, { "code": null, "e": 1655, "s": 1237, "text": "For 1 element - Unit<A>\nFor 2 elements - Pair<A, B> \nFor 3 elements - Triplet<A, B, C> \nFor 4 elements - Quartet<A, B, C, D> \nFor 5 elements - Quintet<A, B, C, D, E>\nFor 6 elements - Sextet<A, B, C, D, E, F> \nFor 7 elements - Septet<A, B, C, D, E, F, G>\nFor 8 elements - Octet<A, B, C, D, E, F, G, H>\nFor 9 elements - Ennead<A, B, C, D, E, F, G, H, I>\nFor 10 elements - Decade<A, B, C, D, E, F, G, H, I, J>\n" }, { "code": null, "e": 1771, "s": 1655, "text": "JavaTuples also gives the 2 very common 2-element tuple classes equivalent to Pair:KeyValue<A, B>\nLabelValue<A, B>\n" }, { "code": null, "e": 1804, "s": 1771, "text": "KeyValue<A, B>\nLabelValue<A, B>\n" }, { "code": null, "e": 2013, "s": 1804, "text": "Note: To run the JavaTuples program, org.javatuples library needs to be added in the IDE. The IDE can be Netbeans, Eclipse, etc. Download JavaTuples Jar library here. To add a library in Netbeans, refer this." }, { "code": null, "e": 2058, "s": 2013, "text": "The basic characteristics of JavaTuples are:" }, { "code": null, "e": 2076, "s": 2058, "text": "They are Typesafe" }, { "code": null, "e": 2095, "s": 2076, "text": "They are Immutable" }, { "code": null, "e": 2113, "s": 2095, "text": "They are Iterable" }, { "code": null, "e": 2135, "s": 2113, "text": "They are Serializable" }, { "code": null, "e": 2186, "s": 2135, "text": "They are Comparable (implements Comparable<Tuple>)" }, { "code": null, "e": 2225, "s": 2186, "text": "They implement equals() and hashCode()" }, { "code": null, "e": 2256, "s": 2225, "text": "They also implement toString()" }, { "code": null, "e": 2696, "s": 2256, "text": "Think of a scenario where you want to store the details of a student in just one entity, like Name, Roll Number, Father’s Name, Contact Number. Now the most common approach that strikes the mind is to construct a data structure that would take the fields as required. This is where Tuples come into play. With Tuples, any separate data structure need not to be created. Instead, for this scenario, a Quartet<A, B, C, D> can be simply used." }, { "code": null, "e": 2749, "s": 2696, "text": "Therefore, common data structures like List, Array :" }, { "code": null, "e": 2781, "s": 2749, "text": "Can be of a specific type only." }, { "code": null, "e": 2810, "s": 2781, "text": "Can be of infinite elements." }, { "code": null, "e": 2828, "s": 2810, "text": "Whereas, Tuples :" }, { "code": null, "e": 2870, "s": 2828, "text": "Can be of any type, yet they are typesafe" }, { "code": null, "e": 2911, "s": 2870, "text": "Can be of limited number only, from 1-10" }, { "code": null, "e": 3001, "s": 2911, "text": "JavaTuples library has many functions that help with the easy working of them. These are:" }, { "code": null, "e": 3208, "s": 3001, "text": "Note: Below examples are shown to be as a generic approach. They can be used for any of the JavaTuple by replacing with the number of parameters and the corresponding Tuple class with values, as required." }, { "code": null, "e": 3956, "s": 3208, "text": "From Constructor:Syntax:NthTuple<type 1, type 2, .., type n> nthTuple = new NthTuple\n <type 1, type 2, .., type n>(value 1, value 2, .., value n);\nExample:Pair<Integer, String> pair = new Pair<Integer, String>( Integer.valurOf(1), \"Geeks\"); Sextet<Integer, String, Integer, String, Integer, String> sextet = new Sextet<Integer, String, Integer, String, Integer, String>( Integer.valueOf(1), \"Geeks\", Integer.valueOf(2), \"For\", Integer.valueOf(3), \"Geeks\" );" }, { "code": null, "e": 3964, "s": 3956, "text": "Syntax:" }, { "code": null, "e": 4103, "s": 3964, "text": "NthTuple<type 1, type 2, .., type n> nthTuple = new NthTuple\n <type 1, type 2, .., type n>(value 1, value 2, .., value n);\n" }, { "code": null, "e": 4112, "s": 4103, "text": "Example:" }, { "code": "Pair<Integer, String> pair = new Pair<Integer, String>( Integer.valurOf(1), \"Geeks\"); Sextet<Integer, String, Integer, String, Integer, String> sextet = new Sextet<Integer, String, Integer, String, Integer, String>( Integer.valueOf(1), \"Geeks\", Integer.valueOf(2), \"For\", Integer.valueOf(3), \"Geeks\" );", "e": 4690, "s": 4112, "text": null }, { "code": null, "e": 5096, "s": 4690, "text": "Using with() method:Syntax:NthTuple<type 1, type 2, .., type n> nthTuple \n = NthTuple.with(value 1, value 2, .., value n);\nExample:Pair<Integer, String> pair = Pair.with(Integer.valurOf(1), \"Geeks\"); Sextet<Integer, String, Integer, String, Integer, String> sextet = Sextet.with(Integer.valueOf(1), \"Geeks\", Integer.valueOf(2), \"For\", Integer.valueOf(3), \"Geeks\");" }, { "code": null, "e": 5104, "s": 5096, "text": "Syntax:" }, { "code": null, "e": 5204, "s": 5104, "text": "NthTuple<type 1, type 2, .., type n> nthTuple \n = NthTuple.with(value 1, value 2, .., value n);\n" }, { "code": null, "e": 5213, "s": 5204, "text": "Example:" }, { "code": "Pair<Integer, String> pair = Pair.with(Integer.valurOf(1), \"Geeks\"); Sextet<Integer, String, Integer, String, Integer, String> sextet = Sextet.with(Integer.valueOf(1), \"Geeks\", Integer.valueOf(2), \"For\", Integer.valueOf(3), \"Geeks\");", "e": 5485, "s": 5213, "text": null }, { "code": null, "e": 5814, "s": 5485, "text": "From other collections:Syntax:NthTuple<type, type, .., type> nthTuple \n = NthTuple.fromCollection(collectionWith_n_values);\nExample:Pair<String, String> pair = Pair.fromCollection(collectionWith2Values); Sextet<Integer, String, Integer, String, Integer, String> sextet = Sextet.fromCollection(collectionWith6Values);" }, { "code": null, "e": 5822, "s": 5814, "text": "Syntax:" }, { "code": null, "e": 5925, "s": 5822, "text": "NthTuple<type, type, .., type> nthTuple \n = NthTuple.fromCollection(collectionWith_n_values);\n" }, { "code": null, "e": 5934, "s": 5925, "text": "Example:" }, { "code": "Pair<String, String> pair = Pair.fromCollection(collectionWith2Values); Sextet<Integer, String, Integer, String, Integer, String> sextet = Sextet.fromCollection(collectionWith6Values);", "e": 6123, "s": 5934, "text": null }, { "code": null, "e": 6306, "s": 6123, "text": "Syntax:NthTuple<type 1, type 2, .., type n> nthTuple = new NthTuple\n <type 1, type 2, .., type n>(value 1, value 2, .., value n);\ntypeX valX = nthTuple.getValueX-1();\n" }, { "code": null, "e": 6482, "s": 6306, "text": "NthTuple<type 1, type 2, .., type n> nthTuple = new NthTuple\n <type 1, type 2, .., type n>(value 1, value 2, .., value n);\ntypeX valX = nthTuple.getValueX-1();\n" }, { "code": null, "e": 7792, "s": 6482, "text": "Example:Pair < Integer, String >pair = new Pair<Integer, String>(Integer.valurOf(1), \"Geeks\"); // This will set val2 = \"Geeks\"String val2 = pair.getValue1(); Sextet<Integer, String, Integer, String, Integer, String> sextet = new Sextet<Integer, String, Integer, String, Integer, String>( Integer.valueOf(1), \"Geeks\", Integer.valueOf(2), \"For\", Integer.valueOf(3), \"Geeks\" ); // This will set val5 = 3Integer val5 = sextet.getValue4();Note:Value numbering starts with index 0. Hence for nth value, the getter will be getValuen-1()NthTuple object can only have getValue0() to getValuen-1() valid getters (e.g. Sextet does not have a getValue6() method).All getValueX() getters are typesafe, i.e. no cast needed. It is because of the type parameterization of the tuple classes (the “” in Triplet) the compiler will know that value0 is of type A, value1 of type B, and so on.There is also a getValue(int pos) method, but its use is not recommended, because the compiler cannot know the type of the result beforehand and therefore a cast will be needed:Triplet<String, Integer, Double> triplet = ......Integer intVal = (Integer) triplet.getValue(1);" }, { "code": "Pair < Integer, String >pair = new Pair<Integer, String>(Integer.valurOf(1), \"Geeks\"); // This will set val2 = \"Geeks\"String val2 = pair.getValue1(); Sextet<Integer, String, Integer, String, Integer, String> sextet = new Sextet<Integer, String, Integer, String, Integer, String>( Integer.valueOf(1), \"Geeks\", Integer.valueOf(2), \"For\", Integer.valueOf(3), \"Geeks\" ); // This will set val5 = 3Integer val5 = sextet.getValue4();", "e": 8384, "s": 7792, "text": null }, { "code": null, "e": 8390, "s": 8384, "text": "Note:" }, { "code": null, "e": 8481, "s": 8390, "text": "Value numbering starts with index 0. Hence for nth value, the getter will be getValuen-1()" }, { "code": null, "e": 8604, "s": 8481, "text": "NthTuple object can only have getValue0() to getValuen-1() valid getters (e.g. Sextet does not have a getValue6() method)." }, { "code": null, "e": 8825, "s": 8604, "text": "All getValueX() getters are typesafe, i.e. no cast needed. It is because of the type parameterization of the tuple classes (the “” in Triplet) the compiler will know that value0 is of type A, value1 of type B, and so on." }, { "code": null, "e": 9099, "s": 8825, "text": "There is also a getValue(int pos) method, but its use is not recommended, because the compiler cannot know the type of the result beforehand and therefore a cast will be needed:Triplet<String, Integer, Double> triplet = ......Integer intVal = (Integer) triplet.getValue(1);" }, { "code": null, "e": 9196, "s": 9099, "text": "Triplet<String, Integer, Double> triplet = ......Integer intVal = (Integer) triplet.getValue(1);" }, { "code": null, "e": 9343, "s": 9196, "text": "Classes KeyValue and LabelValue have their getValue0()/getValue1() methods renamed as getKey()/getValue() and getLabel()/getValue(), respectively." }, { "code": null, "e": 9564, "s": 9343, "text": "Since the JavaTuples are immutable, it means that modifying a value at any index is not possible.Hence JavaTuples offer setAtX(value) which creates a copy of the Tuple with a new value at index X, and returns that Tuple." }, { "code": null, "e": 9572, "s": 9564, "text": "Syntax:" }, { "code": null, "e": 9744, "s": 9572, "text": "NthTuple<type 1, type 2, .., type n> nthTuple = new NthTuple\n <type 1, type 2, .., type n>(value 1, value 2, .., value n);\nnthTuple = nthTuple.setAtX(val);\n" }, { "code": null, "e": 9753, "s": 9744, "text": "Example:" }, { "code": "Pair<Integer, String> pair = new Pair<Integer, String>( Integer.valueOf(1), \"Geeks\"); pair = pair.setAt1(\"For\"); // This will return a pair (1, \"For\") Sextet<Integer, String, Integer, String, Integer, String> sextet = new Sextet<Integer, String, Integer, String, Integer, String>( Integer.valueOf(1), \"Geeks\", Integer.valueOf(2), \"For\", Integer.valueOf(3), \"Geeks\" ); // This will return sextet (1, \"Geeks\", 2, \"For\", 3, \"Everyone\")Sextet<Integer, String, Integer, String, Integer, String> otherSextet = sextet.setAt5(\"Everyone\");", "e": 10479, "s": 9753, "text": null }, { "code": null, "e": 10630, "s": 10479, "text": "All tuple classes in javatuples implement the Iterable<Object> interface. It means that they can be iterated in the same way as collections or arrays." }, { "code": null, "e": 10639, "s": 10630, "text": "Example:" }, { "code": "Triplet<String, Integer, Double> triplet = ...... for (Object value : tuple){ ...}", "e": 10727, "s": 10639, "text": null }, { "code": null, "e": 10742, "s": 10727, "text": "sagar0719kumar" }, { "code": null, "e": 10753, "s": 10742, "text": "JavaTuples" }, { "code": null, "e": 10758, "s": 10753, "text": "Java" }, { "code": null, "e": 10763, "s": 10758, "text": "Java" } ]
How to download a CSV file in PHP that is triggered through a URL ?
11 Jun, 2020 Why do we need to download CSV files?Comma-Separated Values or CSV files are an important part of computer science. Almost every dataset required for training data science models are in CSV file format. Datasets are available all over the internet and it becomes the utmost necessity to have them readily on one’s machine be it someone’s personal computer or on a server. On the server end, one can train his or her web models with various data sets easily if the person can develop a server-side system to easily download a CSV file on the server via any URL pointing to a data set. How we can download CSV files triggered through a URL?Downloading a CSV file through a URL is very easy with PHP and we will discuss here how to achieve that to download a CSV file on both server end and client end. For server end download: To achieve this, we need a PHP function file_get_contents(). This is an inbuilt PHP function that reads the contents of a file in a string type. The function uses a memory mapping technique with a cache on the server end. Hence, this is a preferable choice for our very purpose. Syntax: file_get_contents($path, $include_path, $context, $start, $max_length) Parameters: The function has got one mandatory parameter which the $path and the rest are optional. $path: It holds the path or the URL of the file concerned. $include_path: It searches for a file in the include_path (in php.ini) if the value is set to 1. $context: It is used to specify a context. $max_length: It is used to restrict the bytes to be read. Return Value: Returns back the read data from the file or False if the process is failure. Example 1: The simple example demonstrates how a CSV file can be downloaded on the server end with the file_get_contents() function. <?php // Initialize a file URL to the variable $url = 'Sample-Spreadsheet-10-rows.csv'; // Use basename() function to return// the base name of file $file_name = basename($url); // Checking if the file is a// CSV file or not$info = pathinfo($file_name); if ($info["extension"] == "csv") { /* Use file_get_contents() function to get the file from url and use file_put_contents() function to save the file by using base name */ if(file_put_contents( $file_name, file_get_contents($url))) { echo "File downloaded successfully"; } else { echo "File downloading failed."; }}else echo "Sorry, that's not a CSV file"; ?> Output:The response the browser will show on successful execution. The file downloaded in the server directory. For client end download: Forcing a CSV file on the client end through PHP is cakewalk with a PHP inbuilt function called readfile() method. The function reads a file and passes it to the output buffer. Syntax: readfile($filename, $include_path, $context) Parameters: $filename: The name of the file to be read. $include_path: It searches for a file in the include_path (in php.ini) if the value is set to 1. $context: It is used to specify a context. Return Value: On success returns the number of bytes read, else it returns False. Example 2: The simple following program demonstrates downloading csv file on client end machine with the use of readfile() function. <?php $url = "Sample-Spreadsheet-10-rows.csv"; echo "Your file is being checked. <br>"; // Use basename() function to return// the base name of file$file_name = basename($url); $info = pathinfo($file_name); // Checking if the file is a// CSV file or notif ($info["extension"] == "csv") { /* Informing the browser that the file type of the concerned file is a MIME type (Multipurpose Internet Mail Extension type). Hence, no need to play the file but to directly download it on the client's machine. */ header("Content-Description: File Transfer"); header("Content-Type: application/octet-stream"); header( "Content-Disposition: attachment; filename=\"" . $file_name . "\""); echo "File downloaded successfully"; readfile ($url);} else echo "Sorry, that's not a CSV file"; exit(); ?> Output: PHP-Misc Picked PHP PHP Programs Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? PHP | Converting string to Date and DateTime Comparing two dates in PHP How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to call PHP function on the click of a Button ? Comparing two dates in PHP
[ { "code": null, "e": 53, "s": 25, "text": "\n11 Jun, 2020" }, { "code": null, "e": 637, "s": 53, "text": "Why do we need to download CSV files?Comma-Separated Values or CSV files are an important part of computer science. Almost every dataset required for training data science models are in CSV file format. Datasets are available all over the internet and it becomes the utmost necessity to have them readily on one’s machine be it someone’s personal computer or on a server. On the server end, one can train his or her web models with various data sets easily if the person can develop a server-side system to easily download a CSV file on the server via any URL pointing to a data set." }, { "code": null, "e": 853, "s": 637, "text": "How we can download CSV files triggered through a URL?Downloading a CSV file through a URL is very easy with PHP and we will discuss here how to achieve that to download a CSV file on both server end and client end." }, { "code": null, "e": 878, "s": 853, "text": "For server end download:" }, { "code": null, "e": 1157, "s": 878, "text": "To achieve this, we need a PHP function file_get_contents(). This is an inbuilt PHP function that reads the contents of a file in a string type. The function uses a memory mapping technique with a cache on the server end. Hence, this is a preferable choice for our very purpose." }, { "code": null, "e": 1165, "s": 1157, "text": "Syntax:" }, { "code": null, "e": 1245, "s": 1165, "text": "file_get_contents($path, $include_path, \n $context, $start, $max_length)" }, { "code": null, "e": 1345, "s": 1245, "text": "Parameters: The function has got one mandatory parameter which the $path and the rest are optional." }, { "code": null, "e": 1404, "s": 1345, "text": "$path: It holds the path or the URL of the file concerned." }, { "code": null, "e": 1501, "s": 1404, "text": "$include_path: It searches for a file in the include_path (in php.ini) if the value is set to 1." }, { "code": null, "e": 1544, "s": 1501, "text": "$context: It is used to specify a context." }, { "code": null, "e": 1602, "s": 1544, "text": "$max_length: It is used to restrict the bytes to be read." }, { "code": null, "e": 1693, "s": 1602, "text": "Return Value: Returns back the read data from the file or False if the process is failure." }, { "code": null, "e": 1826, "s": 1693, "text": "Example 1: The simple example demonstrates how a CSV file can be downloaded on the server end with the file_get_contents() function." }, { "code": "<?php // Initialize a file URL to the variable $url = 'Sample-Spreadsheet-10-rows.csv'; // Use basename() function to return// the base name of file $file_name = basename($url); // Checking if the file is a// CSV file or not$info = pathinfo($file_name); if ($info[\"extension\"] == \"csv\") { /* Use file_get_contents() function to get the file from url and use file_put_contents() function to save the file by using base name */ if(file_put_contents( $file_name, file_get_contents($url))) { echo \"File downloaded successfully\"; } else { echo \"File downloading failed.\"; }}else echo \"Sorry, that's not a CSV file\"; ?>", "e": 2516, "s": 1826, "text": null }, { "code": null, "e": 2583, "s": 2516, "text": "Output:The response the browser will show on successful execution." }, { "code": null, "e": 2628, "s": 2583, "text": "The file downloaded in the server directory." }, { "code": null, "e": 2830, "s": 2628, "text": "For client end download: Forcing a CSV file on the client end through PHP is cakewalk with a PHP inbuilt function called readfile() method. The function reads a file and passes it to the output buffer." }, { "code": null, "e": 2838, "s": 2830, "text": "Syntax:" }, { "code": null, "e": 2883, "s": 2838, "text": "readfile($filename, $include_path, $context)" }, { "code": null, "e": 2895, "s": 2883, "text": "Parameters:" }, { "code": null, "e": 2939, "s": 2895, "text": "$filename: The name of the file to be read." }, { "code": null, "e": 3036, "s": 2939, "text": "$include_path: It searches for a file in the include_path (in php.ini) if the value is set to 1." }, { "code": null, "e": 3079, "s": 3036, "text": "$context: It is used to specify a context." }, { "code": null, "e": 3161, "s": 3079, "text": "Return Value: On success returns the number of bytes read, else it returns False." }, { "code": null, "e": 3294, "s": 3161, "text": "Example 2: The simple following program demonstrates downloading csv file on client end machine with the use of readfile() function." }, { "code": "<?php $url = \"Sample-Spreadsheet-10-rows.csv\"; echo \"Your file is being checked. <br>\"; // Use basename() function to return// the base name of file$file_name = basename($url); $info = pathinfo($file_name); // Checking if the file is a// CSV file or notif ($info[\"extension\"] == \"csv\") { /* Informing the browser that the file type of the concerned file is a MIME type (Multipurpose Internet Mail Extension type). Hence, no need to play the file but to directly download it on the client's machine. */ header(\"Content-Description: File Transfer\"); header(\"Content-Type: application/octet-stream\"); header( \"Content-Disposition: attachment; filename=\\\"\" . $file_name . \"\\\"\"); echo \"File downloaded successfully\"; readfile ($url);} else echo \"Sorry, that's not a CSV file\"; exit(); ?>", "e": 4136, "s": 3294, "text": null }, { "code": null, "e": 4144, "s": 4136, "text": "Output:" }, { "code": null, "e": 4153, "s": 4144, "text": "PHP-Misc" }, { "code": null, "e": 4160, "s": 4153, "text": "Picked" }, { "code": null, "e": 4164, "s": 4160, "text": "PHP" }, { "code": null, "e": 4177, "s": 4164, "text": "PHP Programs" }, { "code": null, "e": 4194, "s": 4177, "text": "Web Technologies" }, { "code": null, "e": 4221, "s": 4194, "text": "Web technologies Questions" }, { "code": null, "e": 4225, "s": 4221, "text": "PHP" }, { "code": null, "e": 4323, "s": 4225, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4373, "s": 4323, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 4413, "s": 4373, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 4474, "s": 4413, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 4519, "s": 4474, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 4546, "s": 4519, "text": "Comparing two dates in PHP" }, { "code": null, "e": 4596, "s": 4546, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 4636, "s": 4596, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 4697, "s": 4636, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 4749, "s": 4697, "text": "How to call PHP function on the click of a Button ?" } ]
Python Program to Split the array and add the first part to the end
26 Apr, 2020 There is a given an array and split it from a specified position, and move the first part of array add to the end. Examples: Input : arr[] = {12, 10, 5, 6, 52, 36} k = 2 Output : arr[] = {5, 6, 52, 36, 12, 10} Explanation : Split from index 2 and first part {12, 10} add to the end . Input : arr[] = {3, 1, 2} k = 1 Output : arr[] = {1, 2, 3} Explanation : Split from index 1 and first part add to the end. # Python program to split array and move first# part to end. def splitArr(arr, n, k): for i in range(0, k): x = arr[0] for j in range(0, n-1): arr[j] = arr[j + 1] arr[n-1] = x # mainarr = [12, 10, 5, 6, 52, 36]n = len(arr)position = 2 splitArr(arr, n, position) for i in range(0, n): print(arr[i], end = ' ') # Code Contributed by Mohit Gupta_OMG <(0_o)> 5 6 52 36 12 10 Please refer complete article on Split the array and add the first part to the end for more details!Another Solution : # Python program to split array and move first# part to end. def splitArr(a, n, k): b = a[:k] return (a[k::]+b[::]) # mainarr = [12, 10, 5, 6, 52, 36]n = len(arr)position = 2arr = splitArr(arr, n, position)for i in range(0, n): print(arr[i], end = ' ') 5 6 52 36 12 10 ishagup14 Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python program to add two numbers Python Program for factorial of a number Python program to find second largest number in a list Iterate over characters of a string in Python Python | Convert set into a list Appending to list in Python dictionary Python | Convert a list into a tuple Add a key:value pair to dictionary in Python Python | Check if a variable is string Python Program for Bubble Sort
[ { "code": null, "e": 54, "s": 26, "text": "\n26 Apr, 2020" }, { "code": null, "e": 169, "s": 54, "text": "There is a given an array and split it from a specified position, and move the first part of array add to the end." }, { "code": null, "e": 179, "s": 169, "text": "Examples:" }, { "code": null, "e": 487, "s": 179, "text": "Input : arr[] = {12, 10, 5, 6, 52, 36}\n k = 2\nOutput : arr[] = {5, 6, 52, 36, 12, 10}\nExplanation : Split from index 2 and first \npart {12, 10} add to the end .\n\nInput : arr[] = {3, 1, 2}\n k = 1\nOutput : arr[] = {1, 2, 3}\nExplanation : Split from index 1 and first\npart add to the end.\n" }, { "code": "# Python program to split array and move first# part to end. def splitArr(arr, n, k): for i in range(0, k): x = arr[0] for j in range(0, n-1): arr[j] = arr[j + 1] arr[n-1] = x # mainarr = [12, 10, 5, 6, 52, 36]n = len(arr)position = 2 splitArr(arr, n, position) for i in range(0, n): print(arr[i], end = ' ') # Code Contributed by Mohit Gupta_OMG <(0_o)> ", "e": 911, "s": 487, "text": null }, { "code": null, "e": 928, "s": 911, "text": "5 6 52 36 12 10\n" }, { "code": null, "e": 1047, "s": 928, "text": "Please refer complete article on Split the array and add the first part to the end for more details!Another Solution :" }, { "code": "# Python program to split array and move first# part to end. def splitArr(a, n, k): b = a[:k] return (a[k::]+b[::]) # mainarr = [12, 10, 5, 6, 52, 36]n = len(arr)position = 2arr = splitArr(arr, n, position)for i in range(0, n): print(arr[i], end = ' ')", "e": 1321, "s": 1047, "text": null }, { "code": null, "e": 1338, "s": 1321, "text": "5 6 52 36 12 10\n" }, { "code": null, "e": 1348, "s": 1338, "text": "ishagup14" }, { "code": null, "e": 1364, "s": 1348, "text": "Python Programs" }, { "code": null, "e": 1462, "s": 1364, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1496, "s": 1462, "text": "Python program to add two numbers" }, { "code": null, "e": 1537, "s": 1496, "text": "Python Program for factorial of a number" }, { "code": null, "e": 1592, "s": 1537, "text": "Python program to find second largest number in a list" }, { "code": null, "e": 1638, "s": 1592, "text": "Iterate over characters of a string in Python" }, { "code": null, "e": 1671, "s": 1638, "text": "Python | Convert set into a list" }, { "code": null, "e": 1710, "s": 1671, "text": "Appending to list in Python dictionary" }, { "code": null, "e": 1747, "s": 1710, "text": "Python | Convert a list into a tuple" }, { "code": null, "e": 1792, "s": 1747, "text": "Add a key:value pair to dictionary in Python" }, { "code": null, "e": 1831, "s": 1792, "text": "Python | Check if a variable is string" } ]
Rename function in C/C++
The C library function int rename(const char *old_filename, const char *new_filename) causes the filename referred to by old_filename to be changed to new_filename Following is the declaration for rename() function. int rename(const char *old_filename, const char *new_filename) The parameters are old_filename − This is the C string containing the name of the file to be renamed and/or moved, new_filename − This is the C string containing the new name for the file. On success, zero is returned. On error, -1 is returned, and errno is set appropriately. #include <stdio.h> int main () { int ret; char oldname[] = "file.txt"; char newname[] = "newfile.txt"; ret = rename(oldname, newname); if(ret == 0) { printf("File renamed successfully"); } else { printf("Error: unable to rename the file"); } return(0); } Let us assume we have a text file file.txt, having some content. So, we are going to rename this file, using the above program. Let us compile and run the above program to produce the following message and the file will be renamed to newfile.txt file. File renamed successfully
[ { "code": null, "e": 1351, "s": 1187, "text": "The C library function int rename(const char *old_filename, const char *new_filename) causes the filename referred to by old_filename to be changed to new_filename" }, { "code": null, "e": 1403, "s": 1351, "text": "Following is the declaration for rename() function." }, { "code": null, "e": 1466, "s": 1403, "text": "int rename(const char *old_filename, const char *new_filename)" }, { "code": null, "e": 1655, "s": 1466, "text": "The parameters are old_filename − This is the C string containing the name of the file to be renamed and/or moved, new_filename − This is the C string containing the new name for the file." }, { "code": null, "e": 1743, "s": 1655, "text": "On success, zero is returned. On error, -1 is returned, and errno is set appropriately." }, { "code": null, "e": 2034, "s": 1743, "text": "#include <stdio.h>\nint main () {\n int ret;\n char oldname[] = \"file.txt\";\n char newname[] = \"newfile.txt\";\n ret = rename(oldname, newname);\n if(ret == 0) {\n printf(\"File renamed successfully\");\n } else {\n printf(\"Error: unable to rename the file\");\n }\n return(0);\n}" }, { "code": null, "e": 2286, "s": 2034, "text": "Let us assume we have a text file file.txt, having some content. So, we are going to rename this file, using the above program. Let us compile and run the above program to produce the following message and the file will be renamed to newfile.txt file." }, { "code": null, "e": 2312, "s": 2286, "text": "File renamed successfully" } ]
How to check if String is empty in Java?
The isEmpty() method of the String class returns true if the length of the current string is 0. Live Demo import java.lang.*; public class StringDemo { public static void main(String[] args) { String str = "tutorialspoint"; //prints length of string System.out.println("length of string = " + str.length()); //checks if the string is empty or not System.out.println("is this string empty? = " + str.isEmpty()); } } length of string = 14 is this string empty? = false
[ { "code": null, "e": 1158, "s": 1062, "text": "The isEmpty() method of the String class returns true if the length of the current string is 0." }, { "code": null, "e": 1168, "s": 1158, "text": "Live Demo" }, { "code": null, "e": 1515, "s": 1168, "text": "import java.lang.*;\npublic class StringDemo {\n public static void main(String[] args) {\n String str = \"tutorialspoint\";\n\n //prints length of string\n System.out.println(\"length of string = \" + str.length());\n\n //checks if the string is empty or not\n System.out.println(\"is this string empty? = \" + str.isEmpty());\n }\n}" }, { "code": null, "e": 1567, "s": 1515, "text": "length of string = 14\nis this string empty? = false" } ]
How to display column values as CSV in MySQL?
To display column values as CSV, use GROUP_CONCAT(). Let us first create a table − mysql> create table DemoTable786 ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentName varchar(100) ) AUTO_INCREMENT=101; Query OK, 0 rows affected (0.70 sec) Insert some records in the table using insert command − mysql> insert into DemoTable786(StudentName) values('Chris'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable786(StudentName) values('Robert'); Query OK, 1 row affected (0.24 sec) mysql> insert into DemoTable786(StudentName) values('Mike'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable786(StudentName) values('Sam'); Query OK, 1 row affected (0.12 sec) Display all records from the table using select statement − mysql> select *from DemoTable786; This will produce the following output - +-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 101 | Chris | | 102 | Robert | | 103 | Mike | | 104 | Sam | +-----------+-------------+ 4 rows in set (0.00 sec) Following is the query to select columns as CSV in MySQL − mysql> select group_concat(StudentId),group_concat(StudentName) from DemoTable786; This will produce the following output - +-------------------------+---------------------------+ | group_concat(StudentId) | group_concat(StudentName) | +-------------------------+---------------------------+ | 101,102,103,104 | Chris,Robert,Mike,Sam | +-------------------------+---------------------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1115, "s": 1062, "text": "To display column values as CSV, use GROUP_CONCAT()." }, { "code": null, "e": 1145, "s": 1115, "text": "Let us first create a table −" }, { "code": null, "e": 1323, "s": 1145, "text": "mysql> create table DemoTable786 (\n StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n StudentName varchar(100)\n) \nAUTO_INCREMENT=101;\nQuery OK, 0 rows affected (0.70 sec)" }, { "code": null, "e": 1379, "s": 1323, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1769, "s": 1379, "text": "mysql> insert into DemoTable786(StudentName) values('Chris');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable786(StudentName) values('Robert');\nQuery OK, 1 row affected (0.24 sec)\nmysql> insert into DemoTable786(StudentName) values('Mike');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable786(StudentName) values('Sam');\nQuery OK, 1 row affected (0.12 sec)" }, { "code": null, "e": 1829, "s": 1769, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1863, "s": 1829, "text": "mysql> select *from DemoTable786;" }, { "code": null, "e": 1904, "s": 1863, "text": "This will produce the following output -" }, { "code": null, "e": 2153, "s": 1904, "text": "+-----------+-------------+\n| StudentId | StudentName |\n+-----------+-------------+\n| 101 | Chris |\n| 102 | Robert |\n| 103 | Mike |\n| 104 | Sam |\n+-----------+-------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2212, "s": 2153, "text": "Following is the query to select columns as CSV in MySQL −" }, { "code": null, "e": 2295, "s": 2212, "text": "mysql> select group_concat(StudentId),group_concat(StudentName) from DemoTable786;" }, { "code": null, "e": 2336, "s": 2295, "text": "This will produce the following output -" }, { "code": null, "e": 2640, "s": 2336, "text": "+-------------------------+---------------------------+\n| group_concat(StudentId) | group_concat(StudentName) |\n+-------------------------+---------------------------+\n| 101,102,103,104 | Chris,Robert,Mike,Sam |\n+-------------------------+---------------------------+\n1 row in set (0.00 sec)" } ]
Sqoop - Import All Tables
This chapter describes how to import all the tables from the RDBMS database server to the HDFS. Each table data is stored in a separate directory and the directory name is same as the table name. The following syntax is used to import all tables. $ sqoop import-all-tables (generic-args) (import-args) $ sqoop-import-all-tables (generic-args) (import-args) Let us take an example of importing all tables from the userdb database. The list of tables that the database userdb contains is as follows. +--------------------+ | Tables | +--------------------+ | emp | | emp_add | | emp_contact | +--------------------+ The following command is used to import all the tables from the userdb database. $ sqoop import-all-tables \ --connect jdbc:mysql://localhost/userdb \ --username root Note − If you are using the import-all-tables, it is mandatory that every table in that database must have a primary key field. The following command is used to verify all the table data to the userdb database in HDFS. $ $HADOOP_HOME/bin/hadoop fs -ls It will show you the list of table names in userdb database as directories. drwxr-xr-x - hadoop supergroup 0 2014-12-22 22:50 _sqoop drwxr-xr-x - hadoop supergroup 0 2014-12-23 01:46 emp drwxr-xr-x - hadoop supergroup 0 2014-12-23 01:50 emp_add drwxr-xr-x - hadoop supergroup 0 2014-12-23 01:52 emp_contact 50 Lectures 4 hours Navdeep Kaur Print Add Notes Bookmark this page
[ { "code": null, "e": 1983, "s": 1787, "text": "This chapter describes how to import all the tables from the RDBMS database server to the HDFS. Each table data is stored in a separate directory and the directory name is same as the table name." }, { "code": null, "e": 2034, "s": 1983, "text": "The following syntax is used to import all tables." }, { "code": null, "e": 2145, "s": 2034, "text": "$ sqoop import-all-tables (generic-args) (import-args) \n$ sqoop-import-all-tables (generic-args) (import-args)" }, { "code": null, "e": 2286, "s": 2145, "text": "Let us take an example of importing all tables from the userdb database. The list of tables that the database userdb contains is as follows." }, { "code": null, "e": 2455, "s": 2286, "text": " +--------------------+\n | Tables |\n +--------------------+\n | emp |\n | emp_add |\n | emp_contact |\n +--------------------+\n" }, { "code": null, "e": 2536, "s": 2455, "text": "The following command is used to import all the tables from the userdb database." }, { "code": null, "e": 2622, "s": 2536, "text": "$ sqoop import-all-tables \\\n--connect jdbc:mysql://localhost/userdb \\\n--username root" }, { "code": null, "e": 2750, "s": 2622, "text": "Note − If you are using the import-all-tables, it is mandatory that every table in that database must have a primary key field." }, { "code": null, "e": 2841, "s": 2750, "text": "The following command is used to verify all the table data to the userdb database in HDFS." }, { "code": null, "e": 2874, "s": 2841, "text": "$ $HADOOP_HOME/bin/hadoop fs -ls" }, { "code": null, "e": 2950, "s": 2874, "text": "It will show you the list of table names in userdb database as directories." }, { "code": null, "e": 3182, "s": 2950, "text": "drwxr-xr-x - hadoop supergroup 0 2014-12-22 22:50 _sqoop\ndrwxr-xr-x - hadoop supergroup 0 2014-12-23 01:46 emp\ndrwxr-xr-x - hadoop supergroup 0 2014-12-23 01:50 emp_add\ndrwxr-xr-x - hadoop supergroup 0 2014-12-23 01:52 emp_contact\n" }, { "code": null, "e": 3215, "s": 3182, "text": "\n 50 Lectures \n 4 hours \n" }, { "code": null, "e": 3229, "s": 3215, "text": " Navdeep Kaur" }, { "code": null, "e": 3236, "s": 3229, "text": " Print" }, { "code": null, "e": 3247, "s": 3236, "text": " Add Notes" } ]
Ishaan's Internship | Practice | GeeksforGeeks
Ishaan wants to intern at GeeksForGeeks but for that he has to go through a test. There are n candidates applying for the internship including Ishaan and only one is to be selected. Since he wants to qualify he asks you to help him. The test is as follows. The candidates are asked to stand in a line at positions 1 to n and given a number k. Now, every kth candidate remains and the rest are eliminated. This is repeated until the number of candidates are less than k. Out of the remaining candidates, the one standing at smallest position is selected. You need to tell Ishaan at position he must stand to get selected. Example 1: Input n = 30 k = 3 Output 27 Explaination 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 3 6 9 12 15 18 21 24 27 30 9 18 27 27 Example 2: Input n = 18 k = 3 Output 9 Explaination 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 3 6 9 12 15 18 9 18 (less than k) 9 Your Task : You don't need to read input or print anything. Your task is to Complete the function getCandidate() which takes two integer n and k as input parameters, and returns the answer. Expected Time Complexity: O(logkn) Expected Auxiliary Space: O(1) Constraints 1 <= n <= 105 2 <= k <= 10 0 dishasshah10225 days ago int getCandidate(int n, int k){ int cnt=0; while(n>=k){ n=n/k; cnt++; } int ans=pow(k,cnt); return ans;//complte the function here} 0 kumarashishranjan2 months ago int getCandidate(int n, int k){ int val = k; while(val<=n) val*=k; return (val/k);} 0 nitianguddu8412083 months ago // { Driver Code Starts#include <bits/stdc++.h>using namespace std;int getCandidate(int n, int k); int main() { int t; cin >> t; while(t--){ int n, k; cin >> n >> k; cout << getCandidate(n, k) << endl; }return 0;}// } Driver Code Ends int getCandidate(int n, int k){ //complte the function here int i=1; int ans=1; while(ans<=n) { ans=pow(k,i); i++; } return pow(k,i-2);} 0 jasmeen kaur9 months ago jasmeen kaur DRY RUN OF EXAMPLE NO : 1 30>=3 1*3=3 n=10 10>=3 3*3=9 10/3=3 3>=3 9*3=27 n=1 int getCandidate(int n, int k){ int ans=1; while(n>=k){ ans = ans*k; n/=k; } return ans; } +2 Kryxzl10 months ago Kryxzl Correct Answer.✔️Execution Time:0.03 int getCandidate(int n, int k){ int i = 1; for(; pow(k, i) <= n; i++); if(pow(k, i) == n) return n; return pow(k, i - 1);} 0 Ashman Jagdev11 months ago Ashman Jagdev https://uploads.disquscdn.c... 0 SAKSHAM GARG11 months ago SAKSHAM GARG C++ https://uploads.disquscdn.c... 0 Nikunj Bisht1 year ago Nikunj Bisht java 0.8 int getCandidate(int n, int k){ int counter = n; counter-=counter%k;int i = 1;while(Math.pow(k,i) <= n){ i++; }return (int)Math.pow(k,i-1); //complete the function here } 0 Deyyala Srinivas Kumar1 year ago Deyyala Srinivas Kumar int getCandidate(int n, int k){ //complte the function here int count=0; int p=pow(k,count); while(p<=n) { count++; p=pow(k,count); } return pow(k,count-1);} We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 859, "s": 238, "text": "Ishaan wants to intern at GeeksForGeeks but for that he has to go through a test. There are n candidates applying for the internship including Ishaan and only one is to be selected.\nSince he wants to qualify he asks you to help him. The test is as follows.\nThe candidates are asked to stand in a line at positions 1 to n and given a number k. Now, every kth candidate remains and the rest are eliminated. This is repeated until the number of candidates are less than k.\nOut of the remaining candidates, the one standing at smallest position is selected. You need to tell Ishaan at position he must stand to get selected." }, { "code": null, "e": 870, "s": 859, "text": "Example 1:" }, { "code": null, "e": 1035, "s": 870, "text": "Input \nn = 30\nk = 3\n\nOutput \n27\nExplaination \n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30\n3 6 9 12 15 18 21 24 27 30\n9 18 27\n27" }, { "code": null, "e": 1046, "s": 1035, "text": "Example 2:" }, { "code": null, "e": 1172, "s": 1046, "text": "Input \nn = 18\nk = 3\nOutput \n9\nExplaination \n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18\n3 6 9 12 15 18\n9 18 (less than k)\n9" }, { "code": null, "e": 1362, "s": 1172, "text": "Your Task :\nYou don't need to read input or print anything. Your task is to Complete the function getCandidate() which takes two integer n and k as input parameters, and returns the answer." }, { "code": null, "e": 1428, "s": 1362, "text": "Expected Time Complexity: O(logkn)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1468, "s": 1428, "text": "Constraints \n1 <= n <= 105\n2 <= k <= 10" }, { "code": null, "e": 1470, "s": 1468, "text": "0" }, { "code": null, "e": 1495, "s": 1470, "text": "dishasshah10225 days ago" }, { "code": null, "e": 1649, "s": 1495, "text": "int getCandidate(int n, int k){ int cnt=0; while(n>=k){ n=n/k; cnt++; } int ans=pow(k,cnt); return ans;//complte the function here}" }, { "code": null, "e": 1651, "s": 1649, "text": "0" }, { "code": null, "e": 1681, "s": 1651, "text": "kumarashishranjan2 months ago" }, { "code": null, "e": 1777, "s": 1681, "text": "int getCandidate(int n, int k){ int val = k; while(val<=n) val*=k; return (val/k);}" }, { "code": null, "e": 1779, "s": 1777, "text": "0" }, { "code": null, "e": 1809, "s": 1779, "text": "nitianguddu8412083 months ago" }, { "code": null, "e": 1908, "s": 1809, "text": "// { Driver Code Starts#include <bits/stdc++.h>using namespace std;int getCandidate(int n, int k);" }, { "code": null, "e": 1921, "s": 1908, "text": "int main() {" }, { "code": null, "e": 2062, "s": 1921, "text": " int t; cin >> t; while(t--){ int n, k; cin >> n >> k; cout << getCandidate(n, k) << endl; }return 0;}// } Driver Code Ends" }, { "code": null, "e": 2225, "s": 2062, "text": "int getCandidate(int n, int k){ //complte the function here int i=1; int ans=1; while(ans<=n) { ans=pow(k,i); i++; } return pow(k,i-2);}" }, { "code": null, "e": 2227, "s": 2225, "text": "0" }, { "code": null, "e": 2252, "s": 2227, "text": "jasmeen kaur9 months ago" }, { "code": null, "e": 2265, "s": 2252, "text": "jasmeen kaur" }, { "code": null, "e": 2292, "s": 2265, "text": "DRY RUN OF EXAMPLE NO : 1" }, { "code": null, "e": 2316, "s": 2292, "text": " 30>=3 1*3=3 n=10" }, { "code": null, "e": 2342, "s": 2316, "text": " 10>=3 3*3=9 10/3=3" }, { "code": null, "e": 2365, "s": 2342, "text": " 3>=3 9*3=27 n=1" }, { "code": null, "e": 2481, "s": 2365, "text": "int getCandidate(int n, int k){ int ans=1; while(n>=k){ ans = ans*k; n/=k; } return ans; }" }, { "code": null, "e": 2484, "s": 2481, "text": "+2" }, { "code": null, "e": 2504, "s": 2484, "text": "Kryxzl10 months ago" }, { "code": null, "e": 2511, "s": 2504, "text": "Kryxzl" }, { "code": null, "e": 2548, "s": 2511, "text": "Correct Answer.✔️Execution Time:0.03" }, { "code": null, "e": 2702, "s": 2548, "text": "int getCandidate(int n, int k){ int i = 1; for(; pow(k, i) <= n; i++); if(pow(k, i) == n) return n; return pow(k, i - 1);}" }, { "code": null, "e": 2704, "s": 2702, "text": "0" }, { "code": null, "e": 2731, "s": 2704, "text": "Ashman Jagdev11 months ago" }, { "code": null, "e": 2745, "s": 2731, "text": "Ashman Jagdev" }, { "code": null, "e": 2776, "s": 2745, "text": "https://uploads.disquscdn.c..." }, { "code": null, "e": 2778, "s": 2776, "text": "0" }, { "code": null, "e": 2804, "s": 2778, "text": "SAKSHAM GARG11 months ago" }, { "code": null, "e": 2817, "s": 2804, "text": "SAKSHAM GARG" }, { "code": null, "e": 2821, "s": 2817, "text": "C++" }, { "code": null, "e": 2852, "s": 2821, "text": "https://uploads.disquscdn.c..." }, { "code": null, "e": 2854, "s": 2852, "text": "0" }, { "code": null, "e": 2877, "s": 2854, "text": "Nikunj Bisht1 year ago" }, { "code": null, "e": 2890, "s": 2877, "text": "Nikunj Bisht" }, { "code": null, "e": 2899, "s": 2890, "text": "java 0.8" }, { "code": null, "e": 2932, "s": 2899, "text": " int getCandidate(int n, int k){" }, { "code": null, "e": 2957, "s": 2932, "text": " int counter = n;" }, { "code": null, "e": 3016, "s": 2957, "text": " counter-=counter%k;int i = 1;while(Math.pow(k,i) <= n){" }, { "code": null, "e": 3025, "s": 3016, "text": " i++;" }, { "code": null, "e": 3096, "s": 3025, "text": "}return (int)Math.pow(k,i-1); //complete the function here }" }, { "code": null, "e": 3098, "s": 3096, "text": "0" }, { "code": null, "e": 3131, "s": 3098, "text": "Deyyala Srinivas Kumar1 year ago" }, { "code": null, "e": 3154, "s": 3131, "text": "Deyyala Srinivas Kumar" }, { "code": null, "e": 3347, "s": 3154, "text": "int getCandidate(int n, int k){ //complte the function here int count=0; int p=pow(k,count); while(p<=n) { count++; p=pow(k,count); } return pow(k,count-1);}" }, { "code": null, "e": 3493, "s": 3347, "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": 3529, "s": 3493, "text": " Login to access your submissions. " }, { "code": null, "e": 3539, "s": 3529, "text": "\nProblem\n" }, { "code": null, "e": 3549, "s": 3539, "text": "\nContest\n" }, { "code": null, "e": 3612, "s": 3549, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3760, "s": 3612, "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": 3968, "s": 3760, "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": 4074, "s": 3968, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Grabbing Geodata From Your Photo Library Using Python | by Aaron S | Towards Data Science
So one of the many talents my girlfriend has is photography. However she has over 100,000 photos which require sorting out primarily into year and city. She primarily does location based photography and finds writing essays about certain areas of the world easier when she has all of them in one place. This is a mammoth task and something she has put off during her working life. However now that COVID has put us in a position where these necessary tasks which get pushed back normally now she has decided to address. So I decided to help her out by using my knowledge of Python which seemed well suited to the task. To be able to grab meta-data from jpegsTo be able to use the Google geocode API to reverse geocode to obtain address information based on longitudes and latitudesTo use this meta-data to obtain city and country informationTo be able to sort out images by year and country for further photo editing To be able to grab meta-data from jpegs To be able to use the Google geocode API to reverse geocode to obtain address information based on longitudes and latitudes To use this meta-data to obtain city and country information To be able to sort out images by year and country for further photo editing First we will take a look at the structure of the program and the packages we will use to create the script. Obtain a list of the images to sortObtain photo metadata (Longitude and latitude, date of photo taken)Grab location based on longitude/latitudeCreate folders based on yearCreate folders within each year based on cityMove images into folders based on year and city Obtain a list of the images to sort Obtain photo metadata (Longitude and latitude, date of photo taken) Grab location based on longitude/latitude Create folders based on year Create folders within each year based on city Move images into folders based on year and city GPSPhoto: Used to grab metadata from jpeg’sSelenium: Used to access location data based on longitude and latitudestime: Used to slow the process selenium uses to grab dataOs: Used to create folders with pythonShutil: Used to move files into newly created folders GPSPhoto: Used to grab metadata from jpeg’s Selenium: Used to access location data based on longitude and latitudes time: Used to slow the process selenium uses to grab data Os: Used to create folders with python Shutil: Used to move files into newly created folders Now we have the structure of how we are to proceed lets take each part in term. Using python’s os module it is easy to create a list of files. import osimage_list = os.listdir('c:\\users\\Aaron\\photo')image_list = [a for a in image_list if a.endswith('jpg')] Notes1. The os module is imported2. The image_list variable is defined. The listdirmethod of the os module is used and we specify the location of the images. Note \\ is used to allow us to create the string of a folder location. This is called an escape character. 3. We create a list and only include files that end in ‘.jpg’. Here we’re using a list comprehension, and the endswith string method to include only ‘jpg. There are lots of packages out there to obtain this data. I found GPSPhoto to be a simple way to obtain exactly what I needed in a clear way. We use the getgpsdata method which we specify the filepath of the image to obtain a dictionary of longitudes and latitudes, along with when the photo is taken. from GPSPhoto import gpsphotofor a in image_list: data = gpsphoto.getGPSData(os.getcwd() + f'\\{a}') print(data) Output: {'Latitude': 55.85808611111111, 'Longitude': -4.291505555555555, 'Altitude': 10.32358870967742, 'UTC-Time': '17:41:5.29', 'Date': '08/23/2017'} Notes1. We loop through the image_list and use the getcwd() method to obtain the current working directory and we concatenate this with a file image. In this case we are using the variable a. This is because we will be looping through our list of images and therefore need a general way to grab the metadata for each image no matter how many images are in the folder. See below for details! 2. Note we are using f-strings to do this, we can loop around our list of images and grab data on each image. Whatever goes in the {} gets passed as string, so in this case it will be each image file of the list we just created. 3. We’ve printed out the meta data we need to sort out the folders. In the section above we grabbed the longitutde and latitude data. We need to convert this to obtain a location. For this we can use the geocode API provided by google. We get up to 200 dollars of free usage each month and at 5 dollars per 1000 requests. This isn’t a bad way to do quite a few number of images. Please follow the instructions to gain access to the geocode API here . Remember you need to set up a billing account before getting access to the geocode API. Don’t worry money doesn’t get taken off you for giving them your details! But if you’re doing lots of requests please be careful! In order to get the information we need, we must make a request using the url down below specifying the longitude and latitude. Please remember to insert the API key you got from following the guide above! import requestslong = data['Longitude']lat = data['Latitude']response = requests.get(f'https://maps.googleapis.com/maps/api/geocode/json?latlng={lat},{long}&key=INSERT API KEY')print(response.json()) Output: {'plus_code': {'compound_code': 'VP55+69 Glasgow, UK', 'global_code': '9C7QVP55+69'}, 'results': [{'address_components': [{'long_name': '21', 'short_name': '21', 'types': ['street_number']}, {'long_name': 'Pacific Quay', 'short_name': 'Pacific Quay', 'types': ['route']}, {'long_name': 'Glasgow', 'short_name': 'Glasgow', 'types': ['postal_town']}, When we make an API request we get this json file back! Now json behaves much like a dictionary and we can therefore access parts of the json received like wise. Notes.1. We use the request get method with the API url. We then convert this usingh the json() method to the form we want it in. json_response = response.json()city = json_response['results'][0]['address_components'][2]['long_name'] Notes1. We specify the first results key [results][0] and within that the [address_components] key. We use the second item within [address_components] and finally we want the value of key long_name It’s best to go iteratively through this step by step to get the the data you want. At this point we have a way to get metadata from a single image and we have our list of the images. But we need to be able to create folders based on the year of when the photo was taken. We use the os module with some string manipulation to achieve this. year = data['Date'].split('/')[-1]year_path = os.getcwd() + '\\' + str(year)print(year_path)if os.path.isdir(f'{year}'): return year_pathelse: os.mkdir(data['Date'].split('/')[-1]) return year_path Notes1. data[Date] is a dictionary value for the date the image is taken. We use the split list method to split this data into a list of day, month and year. The year will always be the last list and therefore we [-1] gives us the year we need. We use the getcwdmethod to gain the current working directory. 2. We use the isdir method to confirm there is a folder for the year calculated. We then return the value year_path. This piece of code will be turned into a function hence the returning of the data. 3. We use the mkdir and specify the folder name if the year folder hasn’t already been created, in this case it’s the year we just calculated. We now have the city from the images meta data we can create the respective folder. But we want create the city folders as a subdirectory of the year. location_path = year_path + '\\' + cityif os.path.isdir(f'{location_path}'): print('City Folder already created')else: os.mkdir(f'{year_path}' + '\\' + f'{city}') print(f'City: {city} folder created ') Notes1. Here we check for the location folder within each year. 2. We use the mkdir method as before if the location folder hasn’t already been created, but this time we use the year_path variable we created above and concatenate this with the city variable we just created. Simple as that! Now we created a list of images filenames, and we said we’d be looping over them, this becomes important when we want to move the files to a specific location. We use the shutil package to move files with. The move method, takes two arguments, the absolute path of a file and the absolute path of where you want the file to be. shutil.move(os.getcwd() + f'\\{a}' ,location_folder + f'\\{a}') Notes1. We specify the variable a, which will be our image filename, we concatenate this to create the absolute path of the image. 2. We use the location_folder we created in the last section and concatenate this with the image file name to give the absolute path of the place we want the file to be. Now with all the parts of the code written. We haven’t address the fact we will be looping around a list of image filenames. In my case, some of my girlfriend’s photos do not have metadata and therefore it was also necessary to code in that case, simply to continue lopping till images that do have meta-data are seen. def address(data): long = data['Longitude'] lat = data['Latitude'] response = requests.get(f'https://maps.googleapis.com/maps/api/geocode/json?latlng={lat},{long}&key=AIzaSyA6WyqENNQ0wbkNblLHgWQMCphiFmjmgHc') json_response = response.json() city = json_response['results'][0]['address_components'][2]['long_name'] return citydef year_folder(data): year_path = os.getcwd() + '\\' + str(data['Date'].split('/')[-1]) print(year_path) year = data['Date'].split('/')[-1] if os.path.isdir(f'{year}'): return year_path else: os.mkdir(data['Date'].split('/')[-1]) return year_pathdef location_folder(year_path,city): location_path = year_path + '\\' + city if os.path.isdir(f'{location_path}'): print('City Folder already created') else: os.mkdir(f'{year_path}' + '\\' + f'{city}') print(f'City: {city} folder created ')def move_images(year_path, city,a): location_folder = year_path + f'\\{city}' shutil.move(os.getcwd() + f'\\{a}',location_folder + f'\\{a}') Notes1. The address function hasn’t changed much from what we’ve discussed above.2. The year_folder function check to see if the year fold has been created. If so, we don’t need to create one. The else part of the statement ensures that if a year folder doesn’t exist, we create one. 3. The location_folder function we create the absolute path for the location folder and we test to see if it already exists. If it hasn’t we create it.4. The move_images function we move the file from the original folder to the respective place in the specific year and city folder. if __name__ == "__main__":image_list = os.listdir('c:\\users\\Aaron\\photo')image_list = [a for a in image_list if a.endswith('jpg')] print(image_list)for a in image_list: data = gpsphoto.getGPSData(os.getcwd() + f'\\{a}') print(data) try: if data['Latitude']: city = address(data) except: print('Image has no Address') continue if data['Date']: year_path = year_folder(data) else: print('Image has no Date Attached') continue location_folder(year_path,city) move_images(year_path,city,a) print('Image moved succesfully') Notes1. The image_list variable uses the listdir method to create a list of all file names within the image directory.2. We loop over every image filename. We grab the meta data for each file and put it through two checks. If it has location meta-data, we grab that, if it has meta-data for when the photo was taken we grab that. 3. Subsequently if we have both location and date of photo taken, we create the year folder and the location folder. 4. We then move the images from the folder the files were originally in, to the folder’s we’ve created. Using a few packages we have managed to create a script that could potentially sort thousands of photos out into the required folders for further photo editing and sorting! For full code please see here. Please see here for further details about what I’m up to project-wise on my blog and other posts. For more tech/coding related content please sign up to my newsletter here I’d be grateful for any comments or if you want to collaborate or need help with python please do get in touch.If you want to get in contact with me, please do so here asmith53@ed.ac.uk or on twitter.
[ { "code": null, "e": 475, "s": 172, "text": "So one of the many talents my girlfriend has is photography. However she has over 100,000 photos which require sorting out primarily into year and city. She primarily does location based photography and finds writing essays about certain areas of the world easier when she has all of them in one place." }, { "code": null, "e": 692, "s": 475, "text": "This is a mammoth task and something she has put off during her working life. However now that COVID has put us in a position where these necessary tasks which get pushed back normally now she has decided to address." }, { "code": null, "e": 791, "s": 692, "text": "So I decided to help her out by using my knowledge of Python which seemed well suited to the task." }, { "code": null, "e": 1089, "s": 791, "text": "To be able to grab meta-data from jpegsTo be able to use the Google geocode API to reverse geocode to obtain address information based on longitudes and latitudesTo use this meta-data to obtain city and country informationTo be able to sort out images by year and country for further photo editing" }, { "code": null, "e": 1129, "s": 1089, "text": "To be able to grab meta-data from jpegs" }, { "code": null, "e": 1253, "s": 1129, "text": "To be able to use the Google geocode API to reverse geocode to obtain address information based on longitudes and latitudes" }, { "code": null, "e": 1314, "s": 1253, "text": "To use this meta-data to obtain city and country information" }, { "code": null, "e": 1390, "s": 1314, "text": "To be able to sort out images by year and country for further photo editing" }, { "code": null, "e": 1499, "s": 1390, "text": "First we will take a look at the structure of the program and the packages we will use to create the script." }, { "code": null, "e": 1763, "s": 1499, "text": "Obtain a list of the images to sortObtain photo metadata (Longitude and latitude, date of photo taken)Grab location based on longitude/latitudeCreate folders based on yearCreate folders within each year based on cityMove images into folders based on year and city" }, { "code": null, "e": 1799, "s": 1763, "text": "Obtain a list of the images to sort" }, { "code": null, "e": 1867, "s": 1799, "text": "Obtain photo metadata (Longitude and latitude, date of photo taken)" }, { "code": null, "e": 1909, "s": 1867, "text": "Grab location based on longitude/latitude" }, { "code": null, "e": 1938, "s": 1909, "text": "Create folders based on year" }, { "code": null, "e": 1984, "s": 1938, "text": "Create folders within each year based on city" }, { "code": null, "e": 2032, "s": 1984, "text": "Move images into folders based on year and city" }, { "code": null, "e": 2295, "s": 2032, "text": "GPSPhoto: Used to grab metadata from jpeg’sSelenium: Used to access location data based on longitude and latitudestime: Used to slow the process selenium uses to grab dataOs: Used to create folders with pythonShutil: Used to move files into newly created folders" }, { "code": null, "e": 2339, "s": 2295, "text": "GPSPhoto: Used to grab metadata from jpeg’s" }, { "code": null, "e": 2411, "s": 2339, "text": "Selenium: Used to access location data based on longitude and latitudes" }, { "code": null, "e": 2469, "s": 2411, "text": "time: Used to slow the process selenium uses to grab data" }, { "code": null, "e": 2508, "s": 2469, "text": "Os: Used to create folders with python" }, { "code": null, "e": 2562, "s": 2508, "text": "Shutil: Used to move files into newly created folders" }, { "code": null, "e": 2642, "s": 2562, "text": "Now we have the structure of how we are to proceed lets take each part in term." }, { "code": null, "e": 2705, "s": 2642, "text": "Using python’s os module it is easy to create a list of files." }, { "code": null, "e": 2822, "s": 2705, "text": "import osimage_list = os.listdir('c:\\\\users\\\\Aaron\\\\photo')image_list = [a for a in image_list if a.endswith('jpg')]" }, { "code": null, "e": 3242, "s": 2822, "text": "Notes1. The os module is imported2. The image_list variable is defined. The listdirmethod of the os module is used and we specify the location of the images. Note \\\\ is used to allow us to create the string of a folder location. This is called an escape character. 3. We create a list and only include files that end in ‘.jpg’. Here we’re using a list comprehension, and the endswith string method to include only ‘jpg." }, { "code": null, "e": 3544, "s": 3242, "text": "There are lots of packages out there to obtain this data. I found GPSPhoto to be a simple way to obtain exactly what I needed in a clear way. We use the getgpsdata method which we specify the filepath of the image to obtain a dictionary of longitudes and latitudes, along with when the photo is taken." }, { "code": null, "e": 3666, "s": 3544, "text": "from GPSPhoto import gpsphotofor a in image_list: data = gpsphoto.getGPSData(os.getcwd() + f'\\\\{a}') print(data)" }, { "code": null, "e": 3674, "s": 3666, "text": "Output:" }, { "code": null, "e": 3818, "s": 3674, "text": "{'Latitude': 55.85808611111111, 'Longitude': -4.291505555555555, 'Altitude': 10.32358870967742, 'UTC-Time': '17:41:5.29', 'Date': '08/23/2017'}" }, { "code": null, "e": 4209, "s": 3818, "text": "Notes1. We loop through the image_list and use the getcwd() method to obtain the current working directory and we concatenate this with a file image. In this case we are using the variable a. This is because we will be looping through our list of images and therefore need a general way to grab the metadata for each image no matter how many images are in the folder. See below for details!" }, { "code": null, "e": 4438, "s": 4209, "text": "2. Note we are using f-strings to do this, we can loop around our list of images and grab data on each image. Whatever goes in the {} gets passed as string, so in this case it will be each image file of the list we just created." }, { "code": null, "e": 4506, "s": 4438, "text": "3. We’ve printed out the meta data we need to sort out the folders." }, { "code": null, "e": 4817, "s": 4506, "text": "In the section above we grabbed the longitutde and latitude data. We need to convert this to obtain a location. For this we can use the geocode API provided by google. We get up to 200 dollars of free usage each month and at 5 dollars per 1000 requests. This isn’t a bad way to do quite a few number of images." }, { "code": null, "e": 5107, "s": 4817, "text": "Please follow the instructions to gain access to the geocode API here . Remember you need to set up a billing account before getting access to the geocode API. Don’t worry money doesn’t get taken off you for giving them your details! But if you’re doing lots of requests please be careful!" }, { "code": null, "e": 5313, "s": 5107, "text": "In order to get the information we need, we must make a request using the url down below specifying the longitude and latitude. Please remember to insert the API key you got from following the guide above!" }, { "code": null, "e": 5513, "s": 5313, "text": "import requestslong = data['Longitude']lat = data['Latitude']response = requests.get(f'https://maps.googleapis.com/maps/api/geocode/json?latlng={lat},{long}&key=INSERT API KEY')print(response.json())" }, { "code": null, "e": 5521, "s": 5513, "text": "Output:" }, { "code": null, "e": 5901, "s": 5521, "text": "{'plus_code': {'compound_code': 'VP55+69 Glasgow, UK', 'global_code': '9C7QVP55+69'}, 'results': [{'address_components': [{'long_name': '21', 'short_name': '21', 'types': ['street_number']}, {'long_name': 'Pacific Quay', 'short_name': 'Pacific Quay', 'types': ['route']}, {'long_name': 'Glasgow', 'short_name': 'Glasgow', 'types': ['postal_town']}," }, { "code": null, "e": 6063, "s": 5901, "text": "When we make an API request we get this json file back! Now json behaves much like a dictionary and we can therefore access parts of the json received like wise." }, { "code": null, "e": 6193, "s": 6063, "text": "Notes.1. We use the request get method with the API url. We then convert this usingh the json() method to the form we want it in." }, { "code": null, "e": 6297, "s": 6193, "text": "json_response = response.json()city = json_response['results'][0]['address_components'][2]['long_name']" }, { "code": null, "e": 6495, "s": 6297, "text": "Notes1. We specify the first results key [results][0] and within that the [address_components] key. We use the second item within [address_components] and finally we want the value of key long_name" }, { "code": null, "e": 6579, "s": 6495, "text": "It’s best to go iteratively through this step by step to get the the data you want." }, { "code": null, "e": 6835, "s": 6579, "text": "At this point we have a way to get metadata from a single image and we have our list of the images. But we need to be able to create folders based on the year of when the photo was taken. We use the os module with some string manipulation to achieve this." }, { "code": null, "e": 7042, "s": 6835, "text": "year = data['Date'].split('/')[-1]year_path = os.getcwd() + '\\\\' + str(year)print(year_path)if os.path.isdir(f'{year}'): return year_pathelse: os.mkdir(data['Date'].split('/')[-1]) return year_path" }, { "code": null, "e": 7350, "s": 7042, "text": "Notes1. data[Date] is a dictionary value for the date the image is taken. We use the split list method to split this data into a list of day, month and year. The year will always be the last list and therefore we [-1] gives us the year we need. We use the getcwdmethod to gain the current working directory." }, { "code": null, "e": 7550, "s": 7350, "text": "2. We use the isdir method to confirm there is a folder for the year calculated. We then return the value year_path. This piece of code will be turned into a function hence the returning of the data." }, { "code": null, "e": 7693, "s": 7550, "text": "3. We use the mkdir and specify the folder name if the year folder hasn’t already been created, in this case it’s the year we just calculated." }, { "code": null, "e": 7844, "s": 7693, "text": "We now have the city from the images meta data we can create the respective folder. But we want create the city folders as a subdirectory of the year." }, { "code": null, "e": 8055, "s": 7844, "text": "location_path = year_path + '\\\\' + cityif os.path.isdir(f'{location_path}'): print('City Folder already created')else: os.mkdir(f'{year_path}' + '\\\\' + f'{city}') print(f'City: {city} folder created ')" }, { "code": null, "e": 8119, "s": 8055, "text": "Notes1. Here we check for the location folder within each year." }, { "code": null, "e": 8346, "s": 8119, "text": "2. We use the mkdir method as before if the location folder hasn’t already been created, but this time we use the year_path variable we created above and concatenate this with the city variable we just created. Simple as that!" }, { "code": null, "e": 8674, "s": 8346, "text": "Now we created a list of images filenames, and we said we’d be looping over them, this becomes important when we want to move the files to a specific location. We use the shutil package to move files with. The move method, takes two arguments, the absolute path of a file and the absolute path of where you want the file to be." }, { "code": null, "e": 8738, "s": 8674, "text": "shutil.move(os.getcwd() + f'\\\\{a}' ,location_folder + f'\\\\{a}')" }, { "code": null, "e": 9039, "s": 8738, "text": "Notes1. We specify the variable a, which will be our image filename, we concatenate this to create the absolute path of the image. 2. We use the location_folder we created in the last section and concatenate this with the image file name to give the absolute path of the place we want the file to be." }, { "code": null, "e": 9358, "s": 9039, "text": "Now with all the parts of the code written. We haven’t address the fact we will be looping around a list of image filenames. In my case, some of my girlfriend’s photos do not have metadata and therefore it was also necessary to code in that case, simply to continue lopping till images that do have meta-data are seen." }, { "code": null, "e": 10401, "s": 9358, "text": "def address(data): long = data['Longitude'] lat = data['Latitude'] response = requests.get(f'https://maps.googleapis.com/maps/api/geocode/json?latlng={lat},{long}&key=AIzaSyA6WyqENNQ0wbkNblLHgWQMCphiFmjmgHc') json_response = response.json() city = json_response['results'][0]['address_components'][2]['long_name'] return citydef year_folder(data): year_path = os.getcwd() + '\\\\' + str(data['Date'].split('/')[-1]) print(year_path) year = data['Date'].split('/')[-1] if os.path.isdir(f'{year}'): return year_path else: os.mkdir(data['Date'].split('/')[-1]) return year_pathdef location_folder(year_path,city): location_path = year_path + '\\\\' + city if os.path.isdir(f'{location_path}'): print('City Folder already created') else: os.mkdir(f'{year_path}' + '\\\\' + f'{city}') print(f'City: {city} folder created ')def move_images(year_path, city,a): location_folder = year_path + f'\\\\{city}' shutil.move(os.getcwd() + f'\\\\{a}',location_folder + f'\\\\{a}')" }, { "code": null, "e": 10968, "s": 10401, "text": "Notes1. The address function hasn’t changed much from what we’ve discussed above.2. The year_folder function check to see if the year fold has been created. If so, we don’t need to create one. The else part of the statement ensures that if a year folder doesn’t exist, we create one. 3. The location_folder function we create the absolute path for the location folder and we test to see if it already exists. If it hasn’t we create it.4. The move_images function we move the file from the original folder to the respective place in the specific year and city folder." }, { "code": null, "e": 11634, "s": 10968, "text": "if __name__ == \"__main__\":image_list = os.listdir('c:\\\\users\\\\Aaron\\\\photo')image_list = [a for a in image_list if a.endswith('jpg')] print(image_list)for a in image_list: data = gpsphoto.getGPSData(os.getcwd() + f'\\\\{a}') print(data) try: if data['Latitude']: city = address(data) except: print('Image has no Address') continue if data['Date']: year_path = year_folder(data) else: print('Image has no Date Attached') continue location_folder(year_path,city) move_images(year_path,city,a) print('Image moved succesfully')" }, { "code": null, "e": 12185, "s": 11634, "text": "Notes1. The image_list variable uses the listdir method to create a list of all file names within the image directory.2. We loop over every image filename. We grab the meta data for each file and put it through two checks. If it has location meta-data, we grab that, if it has meta-data for when the photo was taken we grab that. 3. Subsequently if we have both location and date of photo taken, we create the year folder and the location folder. 4. We then move the images from the folder the files were originally in, to the folder’s we’ve created." }, { "code": null, "e": 12389, "s": 12185, "text": "Using a few packages we have managed to create a script that could potentially sort thousands of photos out into the required folders for further photo editing and sorting! For full code please see here." }, { "code": null, "e": 12561, "s": 12389, "text": "Please see here for further details about what I’m up to project-wise on my blog and other posts. For more tech/coding related content please sign up to my newsletter here" } ]
Finding a specific item in subdocument with MongoDB?
To get a specific item in a sudocument, use the dot(.) notation. Let us create a collection with documents − > db.demo81.insertOne({"StudentDetails":[{"StudentName":"Carol","StudentSubject":"Java"},{ "StudentName" : "David", "StudentSubject" : "MongoDB" }]}); { "acknowledged" : true, "insertedId" : ObjectId("5e2bf6ec71bf0181ecc4229d") } > db.demo81.insertOne({"StudentDetails":[{"StudentName":"Mike","StudentSubject":"Python"},{ "StudentName" : "David", "StudentSubject" : "C" }]}); { "acknowledged" : true, "insertedId" : ObjectId("5e2bf70471bf0181ecc4229e") } > db.demo81.insertOne({"StudentDetails":[{"StudentName":"Jace","StudentSubject":"C++"},{ "StudentName" : "John", "StudentSubject" : "MySQL" }]}); { "acknowledged" : true, "insertedId" : ObjectId("5e2bf72071bf0181ecc4229f") } Display all documents from a collection with the help of find() method − > db.demo81.find(); This will produce the following output − { "_id" : ObjectId("5e2bf6ec71bf0181ecc4229d"), "StudentDetails" : [ { "StudentName" : "Carol", "StudentSubject" : "Java" }, {"StudentName" : "David", "StudentSubject" : "MongoDB" } ] } { "_id" : ObjectId("5e2bf70471bf0181ecc4229e"), "StudentDetails" : [ { "StudentName" : "Mike", "StudentSubject" : "Python" }, { "StudentName" : "David", "StudentSubject" : "C" } ] } { "_id" : ObjectId("5e2bf72071bf0181ecc4229f"), "StudentDetails" : [ { "StudentName" : "Jace", "StudentSubject" : "C++" }, { "StudentName" : "John", "StudentSubject" : "MySQL" } ] } Following is the query to find item in a subdocument with MongoDB − > db.demo81.find({"StudentDetails.StudentSubject":"MongoDB"}); This will produce the following output − { "_id" : ObjectId("5e2bf6ec71bf0181ecc4229d"), "StudentDetails" : [ { "StudentName" : "Carol", "StudentSubject" : "Java" }, { "StudentName" : "David", "StudentSubject" : "MongoDB" } ] }
[ { "code": null, "e": 1171, "s": 1062, "text": "To get a specific item in a sudocument, use the dot(.) notation. Let us create a collection with documents −" }, { "code": null, "e": 1872, "s": 1171, "text": "> db.demo81.insertOne({\"StudentDetails\":[{\"StudentName\":\"Carol\",\"StudentSubject\":\"Java\"},{ \"StudentName\" : \"David\", \"StudentSubject\" : \"MongoDB\" }]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e2bf6ec71bf0181ecc4229d\")\n}\n> db.demo81.insertOne({\"StudentDetails\":[{\"StudentName\":\"Mike\",\"StudentSubject\":\"Python\"},{ \"StudentName\" : \"David\", \"StudentSubject\" : \"C\" }]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e2bf70471bf0181ecc4229e\")\n}\n> db.demo81.insertOne({\"StudentDetails\":[{\"StudentName\":\"Jace\",\"StudentSubject\":\"C++\"},{ \"StudentName\" : \"John\", \"StudentSubject\" : \"MySQL\" }]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e2bf72071bf0181ecc4229f\")\n}" }, { "code": null, "e": 1945, "s": 1872, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1965, "s": 1945, "text": "> db.demo81.find();" }, { "code": null, "e": 2006, "s": 1965, "text": "This will produce the following output −" }, { "code": null, "e": 2611, "s": 2006, "text": "{\n \"_id\" : ObjectId(\"5e2bf6ec71bf0181ecc4229d\"), \"StudentDetails\" : [\n { \"StudentName\" : \"Carol\", \"StudentSubject\" : \"Java\" },\n {\"StudentName\" : \"David\", \"StudentSubject\" : \"MongoDB\" }\n ]\n}\n{\n \"_id\" : ObjectId(\"5e2bf70471bf0181ecc4229e\"), \"StudentDetails\" : [\n { \"StudentName\" : \"Mike\", \"StudentSubject\" : \"Python\" },\n { \"StudentName\" : \"David\", \"StudentSubject\" : \"C\" }\n ]\n}\n{\n \"_id\" : ObjectId(\"5e2bf72071bf0181ecc4229f\"), \"StudentDetails\" : [\n { \"StudentName\" : \"Jace\", \"StudentSubject\" : \"C++\" },\n { \"StudentName\" : \"John\", \"StudentSubject\" : \"MySQL\" }\n ] \n}" }, { "code": null, "e": 2679, "s": 2611, "text": "Following is the query to find item in a subdocument with MongoDB −" }, { "code": null, "e": 2742, "s": 2679, "text": "> db.demo81.find({\"StudentDetails.StudentSubject\":\"MongoDB\"});" }, { "code": null, "e": 2783, "s": 2742, "text": "This will produce the following output −" }, { "code": null, "e": 2970, "s": 2783, "text": "{ \"_id\" : ObjectId(\"5e2bf6ec71bf0181ecc4229d\"), \"StudentDetails\" : [ { \"StudentName\" : \"Carol\", \"StudentSubject\" : \"Java\" }, { \"StudentName\" : \"David\", \"StudentSubject\" : \"MongoDB\" } ] }" } ]
How to check if a div is visible using jQuery?
You can use .is(‘:visible’) selects all elements that are visible. <html> <head> <title>divvisible</title> <script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { $("button").click(function () { var dim = $('#div1').is(":visible"); if (dim == false) { $('#div1').css({ "display": "block", "color": "red" }); } }); }); </script> </head> <body> <div id="div1" style="display:none"> <p>Div is visible</p> </div> <button type="button" id="btn" onclick="click()">Click Here</button><br /> </body> </html>
[ { "code": null, "e": 1129, "s": 1062, "text": "You can use .is(‘:visible’) selects all elements that are visible." }, { "code": null, "e": 1744, "s": 1129, "text": "<html>\n<head>\n<title>divvisible</title>\n <script src=\"../../Scripts/jquery-1.4.1.min.js\" type=\"text/javascript\"></script>\n <script type=\"text/javascript\">\n $(document).ready(function () {\n $(\"button\").click(function () {\n var dim = $('#div1').is(\":visible\");\n if (dim == false) {\n $('#div1').css({ \"display\": \"block\", \"color\": \"red\" });\n }\n });\n });\n </script>\n</head>\n<body>\n<div id=\"div1\" style=\"display:none\">\n<p>Div is visible</p>\n</div>\n <button type=\"button\" id=\"btn\" onclick=\"click()\">Click Here</button><br />\n</body>\n</html>" } ]
Frequentist vs Bayesian Statistics | by Gabrielgilling | Towards Data Science
Whether it be an outcome that is yet to occur, or a reality that we cannot yet glimpse, we are obsessed with knowing the unknown. We spend immense resources in hopes of producing more accurate predictions of the future, and relish those whose forecasts consistently get it right. Over the past century, the burgeoning field of statistical inference has presented a more robust toolset for modeling these unknowable outcomes and relationships. The aim of statistical inference is to use observable data to infer the properties of a random variable (RV). The term “random” can be confusing and does not mean that a variable takes on values completely at random, but rather that it takes on different values, which are determined by an underlying probability distribution. In this blog post, we’ll be working with one of the simplest RVs out there, the outcome of a coin flip, in order to understand a fundamental aspect of inference called parameter estimation. While a coin is a simple RV because it can take on two values- heads or tails, you can think of other RVs such as dice rolls — which can take 6 values in the case of a 6-sided die, or stock prices — which can theoretically take on any positive value. In statistical inference, we want to understand the relationship between RVs in order to understand and make predictions about the world around us. The entity that governs the relationship between different RVs is called a parameter, and is often denoted with the Greek letter θ (theta). We can write that relationship mathematically in the following way: Y is our dependent (or outcome) variable and X is our independent (or predictor) variable. θ is the parameter space, which encompasses all of the potential values that govern the relationship between Y and X. Although the true value of a parameter is by definition unknown, we can work with its approximation. In this blog post, we’re going to look at two different approaches to doing so. We’ll start with the Frequentist - or Classical approach- which uses Maximum Likelihood Estimation (MLE) and then we’ll move on to the Bayesian framework. But before, let’s briefly discuss the Binomial Distribution, a relatively simple but nonetheless invaluable distribution that every data scientist should know, and how to simulate it by writing Python code. We’ll center this discussion around the example of a coin-flip (as is mandatory of any statistics text). Specifically, we are interested in the probability that a coin will come up heads in a given flip. In this case, the outcome of our coin-flip is our RV and it can take on the value of 0 (Tails) or 1 (Heads). We can express the outcome of a single coin-flip as a Bernoulli process, which is a fancy term which says that Y is a single outcome that has two potential values. Formally, we have: In this context, p is the probability of the coin coming up heads, and this is our parameter of interest. Our task will be to estimate p as precisely as possible. As such, we have: So, given a coin, how would we estimate p? We could just flip the coin once, but this wouldn’t be very informative. Imagine that the truth is that p=0.5 (the coin is fair and has an equal probability of flipping heads or tails), and after one flip we observe a head. If we only relied on that one flip only, we might conclude that p=1, so that the probability of flipping heads is 100% and we’d flip heads all the time, which sounds dubious. What we’ll want to do instead is observe a lot of flips. When a Bernouilli process is repeated more than once, it is called a Binomial process. The binomial process is built on the assumption that all of the trials, or coin flips in our case, are independent — whether you flipped a heads or a tails now has no impact on flipping a heads or tails in following iterations. Suppose now that we flip our coin n times. Of those n flips, the total number of heads, Y, is a binomial random variable with parameters n and p. n denotes the number of trials, or coin flips, and p is the probability of success, or the probability of tossing heads. Finally, the Binomial distribution’s Probability Mass Function (PMF) gives the probability of observing exactly Y heads out of n trials for every value of p. Formally, we have: Now that we have a theoretical understanding of parameter estimation and the distribution we’ll be working with, we can start coding. Let’s now assume someone gives us a biased coin that has a 60% probability of flipping heads, but we don’t know that we want to estimate that probability ourselves instead. We can use the scipy.statslibrary to draw outcomes from the Binomial distribution. Simulations are very useful because we can hard-code the “true” parameters which then allows us compare how different frameworks compare in approximating it. Let’s simulate 10000 coin flips and observe some results. import numpy as npimport scipy.stats as statsfrom matplotlib import pyplot as pltnp.random.seed(42) # set seed for reproducibility# Set the probability of heads = 0.6p = 0.6# Flip the Coin 10000 times and observe the resultsn_trials = 10000data = stats.bernoulli.rvs(p, size = n_trials)# plot resultsplt.hist(data); sum(data)# 6108 coin flips out of 10000 are heads, since heads are coded as 1s and tails are coded as 0s As expected, the split between heads and tails is close to 60/40, with 6108 heads out of 10000 coin flips, and that’s simply because we told the virtual coin flipper that there would be a 60% chance of a coin being heads! Now that we have our data, let’s compare how the Frequentist and Bayesian approaches obtain the parameter of interest: p. Frequentist statistics uses Maximum Likelihood Estimation (MLE). While a full treatment of MLE is outside the scope of this blog post, its working is in its name: it fits a model that maximizes the likelihood of having observed the observed data. For the Binomial distribution, the MLE is the sample proportion of success[1]. This simply means that under the Frequentist framework, we assume that the true value of p is the amount of heads out of all of coin flips: if we have 6 heads out of 10 flips, then we think that p should be somewhere close to 6/10, or 60%. After obtaining an estimate of p the next step is to quantify the uncertainty about that estimate. Remember, we never know its true value, so we must also quantify its full range of potential values. That range is called the confidence interval and is easily calculated for the binomial distribution. First, we calculate the parameter’s standard error which is simply its standard deviation scaled by √N (the sample size). Then, we can find our 95% confidence intervals by multiplying the standard error with the 95% Z-stat, which is equal to 1.96. To conclude, we have: Let’s look at what happens when we toss 10 coins. In the graph below, the green line denotes the “true” value of p, which we decided would be 0.6 when we simulated the data. The dashed red line shows the MLE, and the dashed blue lines show the confidence intervals —the range of plausible values that p lies in. Because we have observed 5 heads, the MLE is 0.5 (recall that the true value of p is 0.6). The uncertainty is captured by the confidence intervals, which indicate that the true value of p has a 95% probability of being between ~ 0.2 and ~ 0.8. Since the confidence intervals are proportional to the sample size, we can expect them to shrink as the number of coin flips increases — the more data we have the more confident we are about our predictions. To illustrate that, let’s see what happens when we flip increasingly large amounts of coins. In the plots above, we take snapshots of our results after 1 flip, 10 flips, 25 flips, and so on up to 10,000 flips.These plots give us an idea of how our estimates, and our confidence in those estimates, change as we flip the coin an increasingly large number of times. As we continue to flip the coin over and over again, we gain more and more information about that coin’s properties. As a result, we should expect our estimates to become more and more precise, as well as more accurate. When we’ve only flipped the coin a couple of times (say 1 to 100 times), we can see that our confidence interval is quite wide. This is because we simply haven’t seen enough information to rule out the likelihood that the true probability of heads lies somewhere to the sides of our current MLE. However, as we continue the flip the coin and observe more and more evidence about our parameter of interest, we see our confidence interval starting to narrow and hug the MLE. By the time we’ve flipped the coin 10,000 times, our confidence interval is only slightly to the side of our MLE. Let’s think about this intuitively: as we gain more evidence, we should become increasingly confident in our estimates. Additionally, and most importantly, we should expect our estimate to get closer and closer to the truth! This is the law of large numbers: as the size of a sample increase, its parameter estimand gets closer to the true value of the whole population. This is confirmed by the knowledge that we set the true probability of heads to 0.6, and indeed our MLE estimate after just 1,000 flips is 0.61 and it does not waver after this (only the confidence interval narrows). The material in this section — especially the simulation code is heavily indebted to https://tinyheero.github.io/2017/03/08/how-to-bayesian-infer-101.html [2]. As a refresher, recall that Bayes’ Theorem estimates model parameters by establishing them as a distribution conditional on the data we have observed. P(θ) is the prior distribution of our model parameters, which represents our opinions about the relationship between our outcome and predictor variables before we’ve seen any data. P(X|θ) is the likelihood term, indicating how well the prior fits the observed data. P(X) is the marginal distribution of the predictor variables. In other words, it represents the probability of having observed the data given all the possible values for θ. When dealing with discrete distributions, P(X) can be obtained by summing over all values of θ; in the continuous case it is obtained by integrating over θ. The first step of the Bayesian workflow is specifying what our prior beliefs are about the outcome variable. For this example, this means encoding our beliefs about the probability that a coin flip comes up heads: that’s right — we’re putting a probability on a probability. The code block above creates the prior distribution. First, the np.linspace function creates 11 values between 0 and 1 with an interval 0.1. Second, we hardcoded the probabilities associated with each value in the prior distribution. Feel free to play around with different probability values — so as long as they all sum to 1! The prior distribution encapsulates our ideas around the probability of hitting heads without having seen any of the data. For the sake of simplicity, we are going to allow θ to only take on 10 values of 0.1 increments from 0 to 1. We’re going to assume that we do not know that the coin is biased, and nothing indicates that it would be. Consequently, let’s build a distribution that is peaked at 0.5, with a value of 0.2: we are saying that there is a 20% chance that the coin is fair. We are also entertaining the possibility that the coin might not be fair, and that is reflected in the probabilities for θ ranging from 0.1 to 0.9. The only scenarios we believe not to be possible are those where p is equal to 0 (no chance of NEVER flipping heads) or 1 (no chance of ALWAYS flipping heads). Now that we have defined and encoded our prior beliefs, the next step of the Bayesian approach is to collect data and incorporate it into our estimates. This step is no different than what we did in the Frequentist approach: we’ll observe the exact same data and again use the likelihood function to extract information about our parameter space. The only difference is that we now aren’t simply after just the MLE, or the point estimate that we concluded with in the Frequentist approach, we need the likelihood value for each value in the parameter space. The likelihood can be a complicated concept to grasp, but what it does is essentially returning a number that tells us how well a certain value of p fits the data. High likelihood values for a set of p means that they “fit” the data well, and vice-versa. We are basically asking: for any given p, can we be confident that it actually generated the data we witnessed? The equation for the binomial likelihood is its Probability Mass Function (PMF) [3]. Let’s unpack the equation above. We are saying: given n tosses and y heads, what is the likelihood associated with p? For each value of p in θ, the likelihood evaluates the probability of that p value. As an example, if we’ve observed 1 heads, then the likelihood of p= 0 must be 0 — since we’ve observed at least 1 heads, then the likelihood of NEVER flipping heads has to be 0. Another example, albeit an unlikely one (see what I did there?) would be witnessing 10 heads out of 10 flips. In that case, the likelihood would gauge a value of p = 1 to be extremely likely and would likely assign it a probability close to 100%. Let’s now compute the likelihood and visualize it. We’ll keep the same first 10 data points from the previous example, so we have 5 heads out of 10 flips. You’ll notice that the likelihood is peaked around 0.5, with values further away from it getting increasingly smaller. That makes sense: the likelihood has updated our prior beliefs about θ with the data, which have shown that for 5 out of 10 flips were heads — given the data we’ve observed, the most likely true value of theta is 0.5. Thus 0.5 will get the highest likelihood. Vice-versa, values such as 0.1 and 0.9 are very unlikely of being the true value, and we see that reflected in the chart accordingly. In turn, values at the extreme are not corroborated by the data, and are consequently given very small likelihood values. It is important to note however, that the likelihood is not a valid probability distribution. You can check that yourself by summing all of the probabilities for θ, the result does not add to 1! That’s where the normalizing constant / denominator comes in: dividing each likelihood probabilities by the normalizing constant (which is a scalar) yields a valid probability distribution that we call the posterior. Now that we’ve calculated our likelihood values, we obtain the numerator of Bayes’ Theorem by multiplying them with the prior values, which yields the joint distribution of θ and X. In turn, the denominator is obtained by summing over the resulting vector (marginalizing out θ). You may have seen that the denominator is what often makes Bayesian Inference computationally intractable. Later blog posts will address why that is the case, but for this scenario we have the advantage of working with a parameter space that is discrete (summation is easier than integration) and that only takes on 10 values, so calculating the denominator is entirely feasible. In the next blog post, we’ll deal with what happens when we work with continuous distributions. For now, note that our ability to derive the marginal distribution of X is possible because we are working with one variable, which in turn has very few (11) values. This makes summing over all of the values in the parameter space easy, which would not be the case if we were dealing with multiple predictors that can take on thousands (or an infinite! as in the continuous case) amount of values. So what is the posterior distribution? It is a reflection of our beliefs about our parameter of interest, having incorporated all of the information we have access to. It is the product of two components: our prior beliefs about theta, and the likelihood, or the evidence, which reflects the information we gained from the observed data. In combining these two pieces, we obtain a probability distribution for our parameter of interest. This is a key piece separating the Bayesian and Frequentist approach. In the frequentist methodology, our answer is expressed in the form of a point estimate (with a confidence interval). In the Bayesian methodology however, our answer is expressed in the form of a probability distribution, allowing us to place a value on the probability of each potential value of p being correct. In the case above, after having observed 10 flips and 5 heads, our prior distribution has been squeezed by the likelihood towards theta = 0.5, as seems to increasingly be the most likely answer. However, we haven’t seen enough information to rule out the possibility that theta lies somewhere to the side of 0.5, so we will continue to observe more data. Similar to how we did in the frequentist discussion, let’s see how our bayesian conclusion changes as we see more and more data. Let’s now look at what happens as the number of coin flips increases under a Bayesian framework. The plot below overlays the posterior distributions (in blue and with values on the left Y-axis) and the likelihoods (in red and with values on the right Y-axis). Let’s start off by analyzing the situation in which we’ve flipped the coin a single time and observed heads. In the frequentist approach, we saw that, in this scenario, our estimate of p = 1, an obviously incorrect conclusion, and yet we had no other way to answer the question. In the Bayesian world, our answer is very different. Because we defined our prior beliefs to say that the most likely value of theta is 0.5, we are only slightly swayed by that first flip. Think about this intuitively, if you really believed that a coin was fair, and you flipped it once and it came up heads, would that be enough evidence to convince you that the coin isn’t fair? Probably not! The Bayesian approach performs better than the Frequentist approach when there is relatively little data to work with. The viability of the Frequentist answer relies on the law of large numbers, and thus in the absence of large amounts of data, the results aren’t always reliable. However, as we begin to observe more flips of the coin, we start to see our Bayesian answer become quite clear, and eventually we’re placing all of our eggs in the p = 0.6 basket. After just 100 flips, we are assigning a very small probability to values which don’t equal 0.6, and eventually the probability we assign to 0.6 converges to 1, or ~ 100%. This means that we are close to 100% sure that 60% of the time, our coin will be heads. In the background, the likelihood (or the observed data), is beginning to dominate the prior beliefs we established at the beginning. This is because the evidence is overwhelming, and so we rely more on it. As the plot above shows, as n increases, the likelihood and the posterior distributions converge (note that the scales on the X and Y axes are different though — because the likelihood is not a probability distribution). As we observe more data, the prior’s influence gets washed out and the data speaks for itself. In this blog post, we’ve looked at two different ways of estimating unknown parameters. Under the Frequentist approach, we let the data do the talking: we estimate the relationship between X and Y by building a model that fits the observed data as closely as possible. This gives us a single point estimate, the Maximum Likelihood Estimate, and uncertainty is captured by the model’s standard error, which is inversely proportional to the sample size. As such, a typical Frequentist endeavor is to collect as much data as possible about the parameter of interest in order to reach a more accurate estimate (in theory, at least). Under the Bayesian approach, we begin our analysis with an idea of what the relationship between our variables is: the prior distribution. We then observe our data and update our beliefs about the parameter’s distribution: this gives us the posterior distribution. An important but subtle difference under the Bayesian framework is that we treat parameters as random variables in order to capture the uncertainty about their true values. This entails working with distributions at every stage of the modeling process. If we recall the plots we showed for the Frequentist approach, we realize that the Bayesian and Frequentist answers agree with each other as the sample size increases, and this is as it should be! As we gain fuller information about our parameter of interest (i.e observe more data), our answers should become more objective. So you might wonder, what’s the point of having different approaches if they end up giving the same answers? It depends on the use case really. We would argue that in cases where you have lots and lots of data, then deploying a fully fledged Bayesian framework might be overkill. In cases in which you have less data, as is often the case in the social sciences for instance, then the ability to work with posterior distributions can be very insightful. Additionally, in the frequentist approach, we are entirely at the mercy of our data’s accuracy. If our data isn’t accurate or is skewed, then our estimate will be so as well. In the Bayesian approach, we can offset this effect by setting stronger priors (i.e. being more confident in our prior beliefs). We also argue that what Bayesian analysis lacks in simplicity it makes up in overall precision and there are many scenarios in which presenting a posterior distribution to a client or colleague can be much more informative than a point estimate. In this blog post, we’ve treated the prior space as relatively simple, with only 11 arbitrary values p could take on. But what if p could take on any possible value between 0 and 1? When we start working with continuous distributions for parameter spaces things get a bit dicier, and this will be the topic of the next blog post, where we’ll look at why Markov Chain Monte Carlo approximations are used — stay tuned! - The Frequentist approach estimates the unknown parameter using the Maximum Likelihood Estimate (MLE): the point estimate which is the most likely true value of the parameter, given the data that we’ve observed. - The Frequentist answer is completely formed from the observed data and is delivered in the form of a single point estimate. This puts us at the mercy of the data’s accuracy and quality. - The Bayesian approach combines a prior probability distribution with observed data (in the form of a likelihood distribution) to obtain a posterior probability distribution. - While the Bayesian approach also relies on data, its estimate incorporates our prior *knowledge* about the parameter of interest, its answer is delivered in the form of the parameter of interest’s probability distribution. We can offset our reliance on the data by setting stronger priors. - Both the Frequentist and Bayesian estimates begin to equal each other as our sample size grows and the statistical inference becomes objective. https://github.com/gabgilling/Bayesian-Blogs/blob/main/Blog%20Post%201%20final.ipynb [1] https://online.stat.psu.edu/stat504/lesson/1/1.5 [2] https://tinyheero.github.io/2017/03/08/how-to-bayesian-infer-101.html [3]https://sites.warnercnr.colostate.edu/gwhite/wp-content/uploads/sites/73/2017/04/BinomialLikelihood.pdf Thank you to our colleagues at IBM: Alexander Ivanoff, Steven Hwang, Dheeraj Aremsetty and Lindsay Sample for proofreading and comments!
[ { "code": null, "e": 942, "s": 172, "text": "Whether it be an outcome that is yet to occur, or a reality that we cannot yet glimpse, we are obsessed with knowing the unknown. We spend immense resources in hopes of producing more accurate predictions of the future, and relish those whose forecasts consistently get it right. Over the past century, the burgeoning field of statistical inference has presented a more robust toolset for modeling these unknowable outcomes and relationships. The aim of statistical inference is to use observable data to infer the properties of a random variable (RV). The term “random” can be confusing and does not mean that a variable takes on values completely at random, but rather that it takes on different values, which are determined by an underlying probability distribution." }, { "code": null, "e": 1383, "s": 942, "text": "In this blog post, we’ll be working with one of the simplest RVs out there, the outcome of a coin flip, in order to understand a fundamental aspect of inference called parameter estimation. While a coin is a simple RV because it can take on two values- heads or tails, you can think of other RVs such as dice rolls — which can take 6 values in the case of a 6-sided die, or stock prices — which can theoretically take on any positive value." }, { "code": null, "e": 1739, "s": 1383, "text": "In statistical inference, we want to understand the relationship between RVs in order to understand and make predictions about the world around us. The entity that governs the relationship between different RVs is called a parameter, and is often denoted with the Greek letter θ (theta). We can write that relationship mathematically in the following way:" }, { "code": null, "e": 1948, "s": 1739, "text": "Y is our dependent (or outcome) variable and X is our independent (or predictor) variable. θ is the parameter space, which encompasses all of the potential values that govern the relationship between Y and X." }, { "code": null, "e": 2491, "s": 1948, "text": "Although the true value of a parameter is by definition unknown, we can work with its approximation. In this blog post, we’re going to look at two different approaches to doing so. We’ll start with the Frequentist - or Classical approach- which uses Maximum Likelihood Estimation (MLE) and then we’ll move on to the Bayesian framework. But before, let’s briefly discuss the Binomial Distribution, a relatively simple but nonetheless invaluable distribution that every data scientist should know, and how to simulate it by writing Python code." }, { "code": null, "e": 2804, "s": 2491, "text": "We’ll center this discussion around the example of a coin-flip (as is mandatory of any statistics text). Specifically, we are interested in the probability that a coin will come up heads in a given flip. In this case, the outcome of our coin-flip is our RV and it can take on the value of 0 (Tails) or 1 (Heads)." }, { "code": null, "e": 2987, "s": 2804, "text": "We can express the outcome of a single coin-flip as a Bernoulli process, which is a fancy term which says that Y is a single outcome that has two potential values. Formally, we have:" }, { "code": null, "e": 3150, "s": 2987, "text": "In this context, p is the probability of the coin coming up heads, and this is our parameter of interest. Our task will be to estimate p as precisely as possible." }, { "code": null, "e": 3168, "s": 3150, "text": "As such, we have:" }, { "code": null, "e": 3610, "s": 3168, "text": "So, given a coin, how would we estimate p? We could just flip the coin once, but this wouldn’t be very informative. Imagine that the truth is that p=0.5 (the coin is fair and has an equal probability of flipping heads or tails), and after one flip we observe a head. If we only relied on that one flip only, we might conclude that p=1, so that the probability of flipping heads is 100% and we’d flip heads all the time, which sounds dubious." }, { "code": null, "e": 3982, "s": 3610, "text": "What we’ll want to do instead is observe a lot of flips. When a Bernouilli process is repeated more than once, it is called a Binomial process. The binomial process is built on the assumption that all of the trials, or coin flips in our case, are independent — whether you flipped a heads or a tails now has no impact on flipping a heads or tails in following iterations." }, { "code": null, "e": 4407, "s": 3982, "text": "Suppose now that we flip our coin n times. Of those n flips, the total number of heads, Y, is a binomial random variable with parameters n and p. n denotes the number of trials, or coin flips, and p is the probability of success, or the probability of tossing heads. Finally, the Binomial distribution’s Probability Mass Function (PMF) gives the probability of observing exactly Y heads out of n trials for every value of p." }, { "code": null, "e": 4426, "s": 4407, "text": "Formally, we have:" }, { "code": null, "e": 4560, "s": 4426, "text": "Now that we have a theoretical understanding of parameter estimation and the distribution we’ll be working with, we can start coding." }, { "code": null, "e": 4733, "s": 4560, "text": "Let’s now assume someone gives us a biased coin that has a 60% probability of flipping heads, but we don’t know that we want to estimate that probability ourselves instead." }, { "code": null, "e": 4974, "s": 4733, "text": "We can use the scipy.statslibrary to draw outcomes from the Binomial distribution. Simulations are very useful because we can hard-code the “true” parameters which then allows us compare how different frameworks compare in approximating it." }, { "code": null, "e": 5032, "s": 4974, "text": "Let’s simulate 10000 coin flips and observe some results." }, { "code": null, "e": 5348, "s": 5032, "text": "import numpy as npimport scipy.stats as statsfrom matplotlib import pyplot as pltnp.random.seed(42) # set seed for reproducibility# Set the probability of heads = 0.6p = 0.6# Flip the Coin 10000 times and observe the resultsn_trials = 10000data = stats.bernoulli.rvs(p, size = n_trials)# plot resultsplt.hist(data);" }, { "code": null, "e": 5453, "s": 5348, "text": "sum(data)# 6108 coin flips out of 10000 are heads, since heads are coded as 1s and tails are coded as 0s" }, { "code": null, "e": 5675, "s": 5453, "text": "As expected, the split between heads and tails is close to 60/40, with 6108 heads out of 10000 coin flips, and that’s simply because we told the virtual coin flipper that there would be a 60% chance of a coin being heads!" }, { "code": null, "e": 5797, "s": 5675, "text": "Now that we have our data, let’s compare how the Frequentist and Bayesian approaches obtain the parameter of interest: p." }, { "code": null, "e": 6044, "s": 5797, "text": "Frequentist statistics uses Maximum Likelihood Estimation (MLE). While a full treatment of MLE is outside the scope of this blog post, its working is in its name: it fits a model that maximizes the likelihood of having observed the observed data." }, { "code": null, "e": 6363, "s": 6044, "text": "For the Binomial distribution, the MLE is the sample proportion of success[1]. This simply means that under the Frequentist framework, we assume that the true value of p is the amount of heads out of all of coin flips: if we have 6 heads out of 10 flips, then we think that p should be somewhere close to 6/10, or 60%." }, { "code": null, "e": 6912, "s": 6363, "text": "After obtaining an estimate of p the next step is to quantify the uncertainty about that estimate. Remember, we never know its true value, so we must also quantify its full range of potential values. That range is called the confidence interval and is easily calculated for the binomial distribution. First, we calculate the parameter’s standard error which is simply its standard deviation scaled by √N (the sample size). Then, we can find our 95% confidence intervals by multiplying the standard error with the 95% Z-stat, which is equal to 1.96." }, { "code": null, "e": 6934, "s": 6912, "text": "To conclude, we have:" }, { "code": null, "e": 7246, "s": 6934, "text": "Let’s look at what happens when we toss 10 coins. In the graph below, the green line denotes the “true” value of p, which we decided would be 0.6 when we simulated the data. The dashed red line shows the MLE, and the dashed blue lines show the confidence intervals —the range of plausible values that p lies in." }, { "code": null, "e": 7791, "s": 7246, "text": "Because we have observed 5 heads, the MLE is 0.5 (recall that the true value of p is 0.6). The uncertainty is captured by the confidence intervals, which indicate that the true value of p has a 95% probability of being between ~ 0.2 and ~ 0.8. Since the confidence intervals are proportional to the sample size, we can expect them to shrink as the number of coin flips increases — the more data we have the more confident we are about our predictions. To illustrate that, let’s see what happens when we flip increasingly large amounts of coins." }, { "code": null, "e": 8062, "s": 7791, "text": "In the plots above, we take snapshots of our results after 1 flip, 10 flips, 25 flips, and so on up to 10,000 flips.These plots give us an idea of how our estimates, and our confidence in those estimates, change as we flip the coin an increasingly large number of times." }, { "code": null, "e": 8869, "s": 8062, "text": "As we continue to flip the coin over and over again, we gain more and more information about that coin’s properties. As a result, we should expect our estimates to become more and more precise, as well as more accurate. When we’ve only flipped the coin a couple of times (say 1 to 100 times), we can see that our confidence interval is quite wide. This is because we simply haven’t seen enough information to rule out the likelihood that the true probability of heads lies somewhere to the sides of our current MLE. However, as we continue the flip the coin and observe more and more evidence about our parameter of interest, we see our confidence interval starting to narrow and hug the MLE. By the time we’ve flipped the coin 10,000 times, our confidence interval is only slightly to the side of our MLE." }, { "code": null, "e": 9457, "s": 8869, "text": "Let’s think about this intuitively: as we gain more evidence, we should become increasingly confident in our estimates. Additionally, and most importantly, we should expect our estimate to get closer and closer to the truth! This is the law of large numbers: as the size of a sample increase, its parameter estimand gets closer to the true value of the whole population. This is confirmed by the knowledge that we set the true probability of heads to 0.6, and indeed our MLE estimate after just 1,000 flips is 0.61 and it does not waver after this (only the confidence interval narrows)." }, { "code": null, "e": 9617, "s": 9457, "text": "The material in this section — especially the simulation code is heavily indebted to https://tinyheero.github.io/2017/03/08/how-to-bayesian-infer-101.html [2]." }, { "code": null, "e": 9768, "s": 9617, "text": "As a refresher, recall that Bayes’ Theorem estimates model parameters by establishing them as a distribution conditional on the data we have observed." }, { "code": null, "e": 9949, "s": 9768, "text": "P(θ) is the prior distribution of our model parameters, which represents our opinions about the relationship between our outcome and predictor variables before we’ve seen any data." }, { "code": null, "e": 10034, "s": 9949, "text": "P(X|θ) is the likelihood term, indicating how well the prior fits the observed data." }, { "code": null, "e": 10364, "s": 10034, "text": "P(X) is the marginal distribution of the predictor variables. In other words, it represents the probability of having observed the data given all the possible values for θ. When dealing with discrete distributions, P(X) can be obtained by summing over all values of θ; in the continuous case it is obtained by integrating over θ." }, { "code": null, "e": 10639, "s": 10364, "text": "The first step of the Bayesian workflow is specifying what our prior beliefs are about the outcome variable. For this example, this means encoding our beliefs about the probability that a coin flip comes up heads: that’s right — we’re putting a probability on a probability." }, { "code": null, "e": 10967, "s": 10639, "text": "The code block above creates the prior distribution. First, the np.linspace function creates 11 values between 0 and 1 with an interval 0.1. Second, we hardcoded the probabilities associated with each value in the prior distribution. Feel free to play around with different probability values — so as long as they all sum to 1!" }, { "code": null, "e": 11306, "s": 10967, "text": "The prior distribution encapsulates our ideas around the probability of hitting heads without having seen any of the data. For the sake of simplicity, we are going to allow θ to only take on 10 values of 0.1 increments from 0 to 1. We’re going to assume that we do not know that the coin is biased, and nothing indicates that it would be." }, { "code": null, "e": 11763, "s": 11306, "text": "Consequently, let’s build a distribution that is peaked at 0.5, with a value of 0.2: we are saying that there is a 20% chance that the coin is fair. We are also entertaining the possibility that the coin might not be fair, and that is reflected in the probabilities for θ ranging from 0.1 to 0.9. The only scenarios we believe not to be possible are those where p is equal to 0 (no chance of NEVER flipping heads) or 1 (no chance of ALWAYS flipping heads)." }, { "code": null, "e": 12321, "s": 11763, "text": "Now that we have defined and encoded our prior beliefs, the next step of the Bayesian approach is to collect data and incorporate it into our estimates. This step is no different than what we did in the Frequentist approach: we’ll observe the exact same data and again use the likelihood function to extract information about our parameter space. The only difference is that we now aren’t simply after just the MLE, or the point estimate that we concluded with in the Frequentist approach, we need the likelihood value for each value in the parameter space." }, { "code": null, "e": 12688, "s": 12321, "text": "The likelihood can be a complicated concept to grasp, but what it does is essentially returning a number that tells us how well a certain value of p fits the data. High likelihood values for a set of p means that they “fit” the data well, and vice-versa. We are basically asking: for any given p, can we be confident that it actually generated the data we witnessed?" }, { "code": null, "e": 12773, "s": 12688, "text": "The equation for the binomial likelihood is its Probability Mass Function (PMF) [3]." }, { "code": null, "e": 13400, "s": 12773, "text": "Let’s unpack the equation above. We are saying: given n tosses and y heads, what is the likelihood associated with p? For each value of p in θ, the likelihood evaluates the probability of that p value. As an example, if we’ve observed 1 heads, then the likelihood of p= 0 must be 0 — since we’ve observed at least 1 heads, then the likelihood of NEVER flipping heads has to be 0. Another example, albeit an unlikely one (see what I did there?) would be witnessing 10 heads out of 10 flips. In that case, the likelihood would gauge a value of p = 1 to be extremely likely and would likely assign it a probability close to 100%." }, { "code": null, "e": 13555, "s": 13400, "text": "Let’s now compute the likelihood and visualize it. We’ll keep the same first 10 data points from the previous example, so we have 5 heads out of 10 flips." }, { "code": null, "e": 14190, "s": 13555, "text": "You’ll notice that the likelihood is peaked around 0.5, with values further away from it getting increasingly smaller. That makes sense: the likelihood has updated our prior beliefs about θ with the data, which have shown that for 5 out of 10 flips were heads — given the data we’ve observed, the most likely true value of theta is 0.5. Thus 0.5 will get the highest likelihood. Vice-versa, values such as 0.1 and 0.9 are very unlikely of being the true value, and we see that reflected in the chart accordingly. In turn, values at the extreme are not corroborated by the data, and are consequently given very small likelihood values." }, { "code": null, "e": 14602, "s": 14190, "text": "It is important to note however, that the likelihood is not a valid probability distribution. You can check that yourself by summing all of the probabilities for θ, the result does not add to 1! That’s where the normalizing constant / denominator comes in: dividing each likelihood probabilities by the normalizing constant (which is a scalar) yields a valid probability distribution that we call the posterior." }, { "code": null, "e": 14881, "s": 14602, "text": "Now that we’ve calculated our likelihood values, we obtain the numerator of Bayes’ Theorem by multiplying them with the prior values, which yields the joint distribution of θ and X. In turn, the denominator is obtained by summing over the resulting vector (marginalizing out θ)." }, { "code": null, "e": 15261, "s": 14881, "text": "You may have seen that the denominator is what often makes Bayesian Inference computationally intractable. Later blog posts will address why that is the case, but for this scenario we have the advantage of working with a parameter space that is discrete (summation is easier than integration) and that only takes on 10 values, so calculating the denominator is entirely feasible." }, { "code": null, "e": 15755, "s": 15261, "text": "In the next blog post, we’ll deal with what happens when we work with continuous distributions. For now, note that our ability to derive the marginal distribution of X is possible because we are working with one variable, which in turn has very few (11) values. This makes summing over all of the values in the parameter space easy, which would not be the case if we were dealing with multiple predictors that can take on thousands (or an infinite! as in the continuous case) amount of values." }, { "code": null, "e": 16576, "s": 15755, "text": "So what is the posterior distribution? It is a reflection of our beliefs about our parameter of interest, having incorporated all of the information we have access to. It is the product of two components: our prior beliefs about theta, and the likelihood, or the evidence, which reflects the information we gained from the observed data. In combining these two pieces, we obtain a probability distribution for our parameter of interest. This is a key piece separating the Bayesian and Frequentist approach. In the frequentist methodology, our answer is expressed in the form of a point estimate (with a confidence interval). In the Bayesian methodology however, our answer is expressed in the form of a probability distribution, allowing us to place a value on the probability of each potential value of p being correct." }, { "code": null, "e": 17060, "s": 16576, "text": "In the case above, after having observed 10 flips and 5 heads, our prior distribution has been squeezed by the likelihood towards theta = 0.5, as seems to increasingly be the most likely answer. However, we haven’t seen enough information to rule out the possibility that theta lies somewhere to the side of 0.5, so we will continue to observe more data. Similar to how we did in the frequentist discussion, let’s see how our bayesian conclusion changes as we see more and more data." }, { "code": null, "e": 17320, "s": 17060, "text": "Let’s now look at what happens as the number of coin flips increases under a Bayesian framework. The plot below overlays the posterior distributions (in blue and with values on the left Y-axis) and the likelihoods (in red and with values on the right Y-axis)." }, { "code": null, "e": 17995, "s": 17320, "text": "Let’s start off by analyzing the situation in which we’ve flipped the coin a single time and observed heads. In the frequentist approach, we saw that, in this scenario, our estimate of p = 1, an obviously incorrect conclusion, and yet we had no other way to answer the question. In the Bayesian world, our answer is very different. Because we defined our prior beliefs to say that the most likely value of theta is 0.5, we are only slightly swayed by that first flip. Think about this intuitively, if you really believed that a coin was fair, and you flipped it once and it came up heads, would that be enough evidence to convince you that the coin isn’t fair? Probably not!" }, { "code": null, "e": 18276, "s": 17995, "text": "The Bayesian approach performs better than the Frequentist approach when there is relatively little data to work with. The viability of the Frequentist answer relies on the law of large numbers, and thus in the absence of large amounts of data, the results aren’t always reliable." }, { "code": null, "e": 18716, "s": 18276, "text": "However, as we begin to observe more flips of the coin, we start to see our Bayesian answer become quite clear, and eventually we’re placing all of our eggs in the p = 0.6 basket. After just 100 flips, we are assigning a very small probability to values which don’t equal 0.6, and eventually the probability we assign to 0.6 converges to 1, or ~ 100%. This means that we are close to 100% sure that 60% of the time, our coin will be heads." }, { "code": null, "e": 19239, "s": 18716, "text": "In the background, the likelihood (or the observed data), is beginning to dominate the prior beliefs we established at the beginning. This is because the evidence is overwhelming, and so we rely more on it. As the plot above shows, as n increases, the likelihood and the posterior distributions converge (note that the scales on the X and Y axes are different though — because the likelihood is not a probability distribution). As we observe more data, the prior’s influence gets washed out and the data speaks for itself." }, { "code": null, "e": 19868, "s": 19239, "text": "In this blog post, we’ve looked at two different ways of estimating unknown parameters. Under the Frequentist approach, we let the data do the talking: we estimate the relationship between X and Y by building a model that fits the observed data as closely as possible. This gives us a single point estimate, the Maximum Likelihood Estimate, and uncertainty is captured by the model’s standard error, which is inversely proportional to the sample size. As such, a typical Frequentist endeavor is to collect as much data as possible about the parameter of interest in order to reach a more accurate estimate (in theory, at least)." }, { "code": null, "e": 20386, "s": 19868, "text": "Under the Bayesian approach, we begin our analysis with an idea of what the relationship between our variables is: the prior distribution. We then observe our data and update our beliefs about the parameter’s distribution: this gives us the posterior distribution. An important but subtle difference under the Bayesian framework is that we treat parameters as random variables in order to capture the uncertainty about their true values. This entails working with distributions at every stage of the modeling process." }, { "code": null, "e": 20712, "s": 20386, "text": "If we recall the plots we showed for the Frequentist approach, we realize that the Bayesian and Frequentist answers agree with each other as the sample size increases, and this is as it should be! As we gain fuller information about our parameter of interest (i.e observe more data), our answers should become more objective." }, { "code": null, "e": 21716, "s": 20712, "text": "So you might wonder, what’s the point of having different approaches if they end up giving the same answers? It depends on the use case really. We would argue that in cases where you have lots and lots of data, then deploying a fully fledged Bayesian framework might be overkill. In cases in which you have less data, as is often the case in the social sciences for instance, then the ability to work with posterior distributions can be very insightful. Additionally, in the frequentist approach, we are entirely at the mercy of our data’s accuracy. If our data isn’t accurate or is skewed, then our estimate will be so as well. In the Bayesian approach, we can offset this effect by setting stronger priors (i.e. being more confident in our prior beliefs). We also argue that what Bayesian analysis lacks in simplicity it makes up in overall precision and there are many scenarios in which presenting a posterior distribution to a client or colleague can be much more informative than a point estimate." }, { "code": null, "e": 22133, "s": 21716, "text": "In this blog post, we’ve treated the prior space as relatively simple, with only 11 arbitrary values p could take on. But what if p could take on any possible value between 0 and 1? When we start working with continuous distributions for parameter spaces things get a bit dicier, and this will be the topic of the next blog post, where we’ll look at why Markov Chain Monte Carlo approximations are used — stay tuned!" }, { "code": null, "e": 22346, "s": 22133, "text": "- The Frequentist approach estimates the unknown parameter using the Maximum Likelihood Estimate (MLE): the point estimate which is the most likely true value of the parameter, given the data that we’ve observed." }, { "code": null, "e": 22534, "s": 22346, "text": "- The Frequentist answer is completely formed from the observed data and is delivered in the form of a single point estimate. This puts us at the mercy of the data’s accuracy and quality." }, { "code": null, "e": 22710, "s": 22534, "text": "- The Bayesian approach combines a prior probability distribution with observed data (in the form of a likelihood distribution) to obtain a posterior probability distribution." }, { "code": null, "e": 23002, "s": 22710, "text": "- While the Bayesian approach also relies on data, its estimate incorporates our prior *knowledge* about the parameter of interest, its answer is delivered in the form of the parameter of interest’s probability distribution. We can offset our reliance on the data by setting stronger priors." }, { "code": null, "e": 23148, "s": 23002, "text": "- Both the Frequentist and Bayesian estimates begin to equal each other as our sample size grows and the statistical inference becomes objective." }, { "code": null, "e": 23233, "s": 23148, "text": "https://github.com/gabgilling/Bayesian-Blogs/blob/main/Blog%20Post%201%20final.ipynb" }, { "code": null, "e": 23286, "s": 23233, "text": "[1] https://online.stat.psu.edu/stat504/lesson/1/1.5" }, { "code": null, "e": 23360, "s": 23286, "text": "[2] https://tinyheero.github.io/2017/03/08/how-to-bayesian-infer-101.html" }, { "code": null, "e": 23467, "s": 23360, "text": "[3]https://sites.warnercnr.colostate.edu/gwhite/wp-content/uploads/sites/73/2017/04/BinomialLikelihood.pdf" } ]
Implement Form Validation (Error to EditText) in Android - GeeksforGeeks
08 Oct, 2021 In many of the already existing Android applications when it comes to the forms, where it includes user details. If the user enters the wrong information to the text fields or if the user leaves the text fields without filling it, there is a need to provide certain alert information to the TextFields which are unfilled and which contain the wrong information. So in this article, it’s been discussed step by step how to give the error texts to the user. Have a look at the following image to get an idea about what has to implement in this discussion. Note that we are going to implement this project using the Java language. In this discussion, two sample activities are taken for demonstration purposes, because in the first activity the text fields are implemented. If all the data entered in the text fields match the requirements then the user should proceed to the next activity. Step 1: Create an empty activity project Create an empty activity Android Studio project. And select the programming language as JAVA. Refer to Android | How to Create/Start a New Project in Android Studio? to know how to create an empty activity android studio project. Step 2: Working with the activity_main.xml Here in this case for demonstration purposes, only four text fields are implemented those are, First Name, Last Name, Email, and Password. Invoke the following code inside the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" tools:ignore="HardcodedText"> <EditText android:id="@+id/firstName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" android:hint="First Name" android:inputType="text" /> <EditText android:id="@+id/lastName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" android:hint="Last Name" android:inputType="text" /> <EditText android:id="@+id/email" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" android:hint="Email" android:inputType="textEmailAddress" /> <EditText android:id="@+id/password" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" android:hint="Password" android:inputType="textPassword" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:gravity="end" android:orientation="horizontal"> <Button android:id="@+id/cancelButton" style="@style/Widget.AppCompat.Button.Borderless" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="4dp" android:text="CANCEL" android:textColor="@color/colorPrimary" /> <Button android:id="@+id/proceedButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="16dp" android:backgroundTint="@color/colorPrimary" android:text="PROCEED" android:textColor="@android:color/white" tools:ignore="ButtonStyle" /> </LinearLayout></LinearLayout> Step 3: Create another empty activity Create another empty activity with activity_main2.xml and invoke the following code, which contains a simple text “Activity 2” to avoid confusion. The user should proceed to this activity, only when the user enters the data properly in the text fields given in the first activity. 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=".MainActivity2" tools:ignore="HardcodedText"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="ACTIVITY 2" android:textSize="18sp" /> </RelativeLayout> Step 4: Working with the MainActivity.java file Here for the instance of the EditText class, setError() is to be called. When the data filled in the text filed is wrong -> // this gives error message to particular text field // which contains the wrong data. editText1.setError(“Error message”); When user data is corrected by the user -> // There is no need to give the error message when the user // corrects wrongly entered text field. editText1.setError(null); Invoke the following code. Comments are added for better understanding. Java import androidx.appcompat.app.AppCompatActivity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText; public class MainActivity extends AppCompatActivity { // two buttons Button bCancel, bProceed; // four text fields EditText etFirstName, etLastName, etEmail, etPassword; // one boolean variable to check whether all the text fields // are filled by the user, properly or not. boolean isAllFieldsChecked = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // register buttons with their proper IDs. bProceed = findViewById(R.id.proceedButton); bCancel = findViewById(R.id.cancelButton); // register all the EditText fields with their IDs. etFirstName = findViewById(R.id.firstName); etLastName = findViewById(R.id.lastName); etEmail = findViewById(R.id.email); etPassword = findViewById(R.id.password); // handle the PROCEED button bProceed.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // store the returned value of the dedicated function which checks // whether the entered data is valid or if any fields are left blank. isAllFieldsChecked = CheckAllFields(); // the boolean variable turns to be true then // only the user must be proceed to the activity2 if (isAllFieldsChecked) { Intent i = new Intent(MainActivity.this, MainActivity2.class); startActivity(i); } } }); // if user presses the cancel button then close the // application or the particular activity. bCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MainActivity.this.finish(); System.exit(0); } }); } // function which checks all the text fields // are filled or not by the user. // when user clicks on the PROCEED button // this function is triggered. private boolean CheckAllFields() { if (etFirstName.length() == 0) { etFirstName.setError("This field is required"); return false; } if (etLastName.length() == 0) { etLastName.setError("This field is required"); return false; } if (etEmail.length() == 0) { etEmail.setError("Email is required"); return false; } if (etPassword.length() == 0) { etPassword.setError("Password is required"); return false; } else if (etPassword.length() < 8) { etPassword.setError("Password must be minimum 8 characters"); return false; } // after all validation return true. return true; }} sooda367 gulshankumarar231 android Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create and Add Data to SQLite Database in Android? Broadcast Receiver in Android With Example Resource Raw Folder in Android Studio Services in Android with Example Android RecyclerView in Kotlin 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": 25875, "s": 25847, "text": "\n08 Oct, 2021" }, { "code": null, "e": 26504, "s": 25875, "text": "In many of the already existing Android applications when it comes to the forms, where it includes user details. If the user enters the wrong information to the text fields or if the user leaves the text fields without filling it, there is a need to provide certain alert information to the TextFields which are unfilled and which contain the wrong information. So in this article, it’s been discussed step by step how to give the error texts to the user. Have a look at the following image to get an idea about what has to implement in this discussion. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 26764, "s": 26504, "text": "In this discussion, two sample activities are taken for demonstration purposes, because in the first activity the text fields are implemented. If all the data entered in the text fields match the requirements then the user should proceed to the next activity." }, { "code": null, "e": 26805, "s": 26764, "text": "Step 1: Create an empty activity project" }, { "code": null, "e": 26899, "s": 26805, "text": "Create an empty activity Android Studio project. And select the programming language as JAVA." }, { "code": null, "e": 27035, "s": 26899, "text": "Refer to Android | How to Create/Start a New Project in Android Studio? to know how to create an empty activity android studio project." }, { "code": null, "e": 27078, "s": 27035, "text": "Step 2: Working with the activity_main.xml" }, { "code": null, "e": 27217, "s": 27078, "text": "Here in this case for demonstration purposes, only four text fields are implemented those are, First Name, Last Name, Email, and Password." }, { "code": null, "e": 27278, "s": 27217, "text": "Invoke the following code inside the activity_main.xml file." }, { "code": null, "e": 27282, "s": 27278, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <EditText android:id=\"@+id/firstName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"16dp\" android:hint=\"First Name\" android:inputType=\"text\" /> <EditText android:id=\"@+id/lastName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"16dp\" android:hint=\"Last Name\" android:inputType=\"text\" /> <EditText android:id=\"@+id/email\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"16dp\" android:hint=\"Email\" android:inputType=\"textEmailAddress\" /> <EditText android:id=\"@+id/password\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"16dp\" android:hint=\"Password\" android:inputType=\"textPassword\" /> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"8dp\" android:gravity=\"end\" android:orientation=\"horizontal\"> <Button android:id=\"@+id/cancelButton\" style=\"@style/Widget.AppCompat.Button.Borderless\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginEnd=\"4dp\" android:text=\"CANCEL\" android:textColor=\"@color/colorPrimary\" /> <Button android:id=\"@+id/proceedButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginEnd=\"16dp\" android:backgroundTint=\"@color/colorPrimary\" android:text=\"PROCEED\" android:textColor=\"@android:color/white\" tools:ignore=\"ButtonStyle\" /> </LinearLayout></LinearLayout>", "e": 29894, "s": 27282, "text": null }, { "code": null, "e": 29937, "s": 29899, "text": "Step 3: Create another empty activity" }, { "code": null, "e": 30086, "s": 29939, "text": "Create another empty activity with activity_main2.xml and invoke the following code, which contains a simple text “Activity 2” to avoid confusion." }, { "code": null, "e": 30220, "s": 30086, "text": "The user should proceed to this activity, only when the user enters the data properly in the text fields given in the first activity." }, { "code": null, "e": 30226, "s": 30222, "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=\".MainActivity2\" tools:ignore=\"HardcodedText\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:text=\"ACTIVITY 2\" android:textSize=\"18sp\" /> </RelativeLayout>", "e": 30768, "s": 30226, "text": null }, { "code": null, "e": 30819, "s": 30771, "text": "Step 4: Working with the MainActivity.java file" }, { "code": null, "e": 30894, "s": 30821, "text": "Here for the instance of the EditText class, setError() is to be called." }, { "code": null, "e": 30945, "s": 30894, "text": "When the data filled in the text filed is wrong ->" }, { "code": null, "e": 31000, "s": 30945, "text": "// this gives error message to particular text field " }, { "code": null, "e": 31034, "s": 31000, "text": "// which contains the wrong data." }, { "code": null, "e": 31072, "s": 31034, "text": "editText1.setError(“Error message”); " }, { "code": null, "e": 31120, "s": 31077, "text": "When user data is corrected by the user ->" }, { "code": null, "e": 31181, "s": 31120, "text": " // There is no need to give the error message when the user" }, { "code": null, "e": 31222, "s": 31181, "text": " // corrects wrongly entered text field." }, { "code": null, "e": 31248, "s": 31222, "text": "editText1.setError(null);" }, { "code": null, "e": 31320, "s": 31248, "text": "Invoke the following code. Comments are added for better understanding." }, { "code": null, "e": 31327, "s": 31322, "text": "Java" }, { "code": "import androidx.appcompat.app.AppCompatActivity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText; public class MainActivity extends AppCompatActivity { // two buttons Button bCancel, bProceed; // four text fields EditText etFirstName, etLastName, etEmail, etPassword; // one boolean variable to check whether all the text fields // are filled by the user, properly or not. boolean isAllFieldsChecked = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // register buttons with their proper IDs. bProceed = findViewById(R.id.proceedButton); bCancel = findViewById(R.id.cancelButton); // register all the EditText fields with their IDs. etFirstName = findViewById(R.id.firstName); etLastName = findViewById(R.id.lastName); etEmail = findViewById(R.id.email); etPassword = findViewById(R.id.password); // handle the PROCEED button bProceed.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // store the returned value of the dedicated function which checks // whether the entered data is valid or if any fields are left blank. isAllFieldsChecked = CheckAllFields(); // the boolean variable turns to be true then // only the user must be proceed to the activity2 if (isAllFieldsChecked) { Intent i = new Intent(MainActivity.this, MainActivity2.class); startActivity(i); } } }); // if user presses the cancel button then close the // application or the particular activity. bCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MainActivity.this.finish(); System.exit(0); } }); } // function which checks all the text fields // are filled or not by the user. // when user clicks on the PROCEED button // this function is triggered. private boolean CheckAllFields() { if (etFirstName.length() == 0) { etFirstName.setError(\"This field is required\"); return false; } if (etLastName.length() == 0) { etLastName.setError(\"This field is required\"); return false; } if (etEmail.length() == 0) { etEmail.setError(\"Email is required\"); return false; } if (etPassword.length() == 0) { etPassword.setError(\"Password is required\"); return false; } else if (etPassword.length() < 8) { etPassword.setError(\"Password must be minimum 8 characters\"); return false; } // after all validation return true. return true; }}", "e": 34412, "s": 31327, "text": null }, { "code": null, "e": 34426, "s": 34417, "text": "sooda367" }, { "code": null, "e": 34444, "s": 34426, "text": "gulshankumarar231" }, { "code": null, "e": 34452, "s": 34444, "text": "android" }, { "code": null, "e": 34476, "s": 34452, "text": "Technical Scripter 2020" }, { "code": null, "e": 34484, "s": 34476, "text": "Android" }, { "code": null, "e": 34489, "s": 34484, "text": "Java" }, { "code": null, "e": 34508, "s": 34489, "text": "Technical Scripter" }, { "code": null, "e": 34513, "s": 34508, "text": "Java" }, { "code": null, "e": 34521, "s": 34513, "text": "Android" }, { "code": null, "e": 34619, "s": 34521, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34677, "s": 34619, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 34720, "s": 34677, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 34758, "s": 34720, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 34791, "s": 34758, "text": "Services in Android with Example" }, { "code": null, "e": 34822, "s": 34791, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 34837, "s": 34822, "text": "Arrays in Java" }, { "code": null, "e": 34881, "s": 34837, "text": "Split() String method in Java with examples" }, { "code": null, "e": 34903, "s": 34881, "text": "For-each loop in Java" }, { "code": null, "e": 34954, "s": 34903, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Euler's Totient Function - GeeksforGeeks
13 Mar, 2022 Euler’s Totient function Φ (n) for an input n is the count of numbers in {1, 2, 3, ..., n} that are relatively prime to n, i.e., the numbers whose GCD (Greatest Common Divisor) with n is 1. Examples : Φ(1) = 1 gcd(1, 1) is 1 Φ(2) = 1 gcd(1, 2) is 1, but gcd(2, 2) is 2. Φ(3) = 2 gcd(1, 3) is 1 and gcd(2, 3) is 1 Φ(4) = 2 gcd(1, 4) is 1 and gcd(3, 4) is 1 Φ(5) = 4 gcd(1, 5) is 1, gcd(2, 5) is 1, gcd(3, 5) is 1 and gcd(4, 5) is 1 Φ(6) = 2 gcd(1, 6) is 1 and gcd(5, 6) is 1, How to compute Φ(n) for an input nΦA simple solution is to iterate through all numbers from 1 to n-1 and count numbers with gcd with n as 1. Below is the implementation of the simple method to compute Euler’s Totient function for an input integer n. C++ C Java Python3 C# PHP Javascript // A simple C++ program to calculate// Euler's Totient Function#include <iostream>using namespace std; // Function to return gcd of a and bint gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // A simple method to evaluate Euler Totient Functionint phi(unsigned int n){ unsigned int result = 1; for (int i = 2; i < n; i++) if (gcd(i, n) == 1) result++; return result;} // Driver program to test above functionint main(){ int n; for (n = 1; n <= 10; n++) cout << "phi("<<n<<") = " << phi(n) << endl; return 0;} // This code is contributed by SHUBHAMSINGH10 // A simple C program to calculate Euler's Totient Function#include <stdio.h> // Function to return gcd of a and bint gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // A simple method to evaluate Euler Totient Functionint phi(unsigned int n){ unsigned int result = 1; for (int i = 2; i < n; i++) if (gcd(i, n) == 1) result++; return result;} // Driver program to test above functionint main(){ int n; for (n = 1; n <= 10; n++) printf("phi(%d) = %d\n", n, phi(n)); return 0;} // A simple java program to calculate// Euler's Totient Functionimport java.io.*; class GFG { // Function to return GCD of a and b static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // A simple method to evaluate // Euler Totient Function static int phi(int n) { int result = 1; for (int i = 2; i < n; i++) if (gcd(i, n) == 1) result++; return result; } // Driver code public static void main(String[] args) { int n; for (n = 1; n <= 10; n++) System.out.println("phi(" + n + ") = " + phi(n)); }} // This code is contributed by sunnusingh # A simple Python3 program# to calculate Euler's# Totient Function # Function to return# gcd of a and bdef gcd(a, b): if (a == 0): return b return gcd(b % a, a) # A simple method to evaluate# Euler Totient Functiondef phi(n): result = 1 for i in range(2, n): if (gcd(i, n) == 1): result+=1 return result # Driver Codefor n in range(1, 11): print("phi(",n,") = ", phi(n), sep = "") # This code is contributed# by Smitha // A simple C# program to calculate// Euler's Totient Functionusing System; class GFG { // Function to return GCD of a and b static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // A simple method to evaluate // Euler Totient Function static int phi(int n) { int result = 1; for (int i = 2; i < n; i++) if (gcd(i, n) == 1) result++; return result; } // Driver code public static void Main() { for (int n = 1; n <= 10; n++) Console.WriteLine("phi(" + n + ") = " + phi(n)); }} // This code is contributed by nitin mittal <Φphp// PHP program to calculate// Euler's Totient Function // Function to return// gcd of a and bfunction gcd($a, $b){ if ($a == 0) return $b; return gcd($b % $a, $a);} // A simple method to evaluate// Euler Totient Functionfunction phi($n){ $result = 1; for ($i = 2; $i < $n; $i++) if (gcd($i, $n) == 1) $result++; return $result;} // Driver Codefor ($n = 1; $n <= 10; $n++) echo "phi(" .$n. ") =" . phi($n)."\n"; // This code is contributed by Sam007Φ> <script>// Javascript program to calculate// Euler's Totient Function // Function to return// gcd of a and bfunction gcd(a, b){ if (a == 0) return b; return gcd(b % a, a);} // A simple method to evaluate// Euler Totient Functionfunction phi(n){ let result = 1; for (let i = 2; i < n; i++) if (gcd(i, n) == 1) result++; return result;} // Driver Codefor (let n = 1; n <= 10; n++) document.write(`phi(${n}) = ${phi(n)} <br>`); // This code is contributed by _saurabh_jaiswal </script> Output : phi(1) = 1 phi(2) = 1 phi(3) = 2 phi(4) = 2 phi(5) = 4 phi(6) = 2 phi(7) = 6 phi(8) = 4 phi(9) = 6 phi(10) = 4 The above code calls gcd function O(n) times. The time complexity of the gcd function is O(h) where “h” is the number of digits in a smaller number of given two numbers. Therefore, an upper bound on the time complexity of the above solution is O(N log N) [HowΦ there can be at most Log10n digits in all numbers from 1 to n] Auxiliary Space: O(log N) Below is a Better Solution. The idea is based on Euler’s product formula which states that the value of totient functions is below the product overall prime factors p of n. The formula basically says that the value of Φ(n) is equal to n multiplied by-product of (1 – 1/p) for all prime factors p of n. For example value of Φ(6) = 6 * (1-1/2) * (1 – 1/3) = 2.We can find all prime factors using the idea used in this post. 1) Initialize : result = n 2) Run a loop from 'p' = 2 to sqrt(n), do following for every 'p'. a) If p divides n, then Set: result = result * (1.0 - (1.0 / (float) p)); Divide all occurrences of p in n. 3) Return result Below is the implementation of Euler’s product formula. C++ C Java Python3 C# PHP Javascript // C++ program to calculate Euler's// Totient Function using Euler's// product formula#include <bits/stdc++.h>using namespace std; int phi(int n){ // Initialize result as n float result = n; // Consider all prime factors of n // and for every prime factor p, // multiply result with (1 - 1/p) for(int p = 2; p * p <= n; ++p) { // Check if p is a prime factor. if (n % p == 0) { // If yes, then update n and result while (n % p == 0) n /= p; result *= (1.0 - (1.0 / (float)p)); } } // If n has a prime factor greater than sqrt(n) // (There can be at-most one such prime factor) if (n > 1) result *= (1.0 - (1.0 / (float)n)); return (int)result;} // Driver codeint main(){ int n; for(n = 1; n <= 10; n++) { cout << "Phi" << "(" << n << ")" << " = " << phi(n) <<endl; } return 0;} // This code is contributed by koulick_sadhu // C program to calculate Euler's Totient Function// using Euler's product formula#include <stdio.h> int phi(int n){ float result = n; // Initialize result as n // Consider all prime factors of n and for every prime // factor p, multiply result with (1 - 1/p) for (int p = 2; p * p <= n; ++p) { // Check if p is a prime factor. if (n % p == 0) { // If yes, then update n and result while (n % p == 0) n /= p; result *= (1.0 - (1.0 / (float)p)); } } // If n has a prime factor greater than sqrt(n) // (There can be at-most one such prime factor) if (n > 1) result *= (1.0 - (1.0 / (float)n)); return (int)result;} // Driver program to test above functionint main(){ int n; for (n = 1; n <= 10; n++) printf("phi(%d) = %d\n", n, phi(n)); return 0;} // Java program to calculate Euler's Totient// Function using Euler's product formulaimport java.io.*; class GFG { static int phi(int n) { // Initialize result as n float result = n; // Consider all prime factors of n and for // every prime factor p, multiply result // with (1 - 1/p) for (int p = 2; p * p <= n; ++p) { // Check if p is a prime factor. if (n % p == 0) { // If yes, then update n and result while (n % p == 0) n /= p; result *= (1.0 - (1.0 / (float)p)); } } // If n has a prime factor greater than sqrt(n) // (There can be at-most one such prime factor) if (n > 1) result *= (1.0 - (1.0 / (float)n)); return (int)result; } // Driver program to test above function public static void main(String args[]) { int n; for (n = 1; n <= 10; n++) System.out.println("phi(" + n + ") = " + phi(n)); }} // This code is contributed by Nikita Tiwari. # Python 3 program to calculate# Euler's Totient Function# using Euler's product formula def phi(n) : result = n # Initialize result as n # Consider all prime factors # of n and for every prime # factor p, multiply result with (1 - 1 / p) p = 2 while p * p<= n : # Check if p is a prime factor. if n % p == 0 : # If yes, then update n and result while n % p == 0 : n = n // p result = result * (1.0 - (1.0 / float(p))) p = p + 1 # If n has a prime factor # greater than sqrt(n) # (There can be at-most one # such prime factor) if n > 1 : result = result * (1.0 - (1.0 / float(n))) return int(result) # Driver program to test above functionfor n in range(1, 11) : print("phi(", n, ") = ", phi(n)) # This code is contributed# by Nikita Tiwari. // C# program to calculate Euler's Totient// Function using Euler's product formulausing System; class GFG { static int phi(int n) { // Initialize result as n float result = n; // Consider all prime factors // of n and for every prime // factor p, multiply result // with (1 - 1 / p) for (int p = 2; p * p <= n; ++p) { // Check if p is a prime factor. if (n % p == 0) { // If yes, then update // n and result while (n % p == 0) n /= p; result *= (float)(1.0 - (1.0 / (float)p)); } } // If n has a prime factor // greater than sqrt(n) // (There can be at-most // one such prime factor) if (n > 1) result *= (float)(1.0 - (1.0 / (float)n)); return (int)result; } // Driver Code public static void Main() { int n; for (n = 1; n <= 10; n++) Console.WriteLine("phi(" + n + ") = " + phi(n)); }} // This code is contributed by nitin mittal. <Φphp// PHP program to calculate// Euler's Totient Function// using Euler's product formulafunction phi($n){ // Initialize result as n $result = $n; // Consider all prime factors // of n and for every prime // factor p, multiply result // with (1 - 1/p) for ($p = 2; $p * $p <= $n; ++$p) { // Check if p is // a prime factor. if ($n % $p == 0) { // If yes, then update // n and result while ($n % $p == 0) $n /= $p; $result *= (1.0 - (1.0 / $p)); } } // If n has a prime factor greater // than sqrt(n) (There can be at-most // one such prime factor) if ($n > 1) $result *= (1.0 - (1.0 / $n)); return intval($result);} // Driver Codefor ($n = 1; $n <= 10; $n++)echo "phi(" .$n. ") =" . phi($n)."\n"; // This code is contributed by Sam007Φ> // Javascript program to calculate// Euler's Totient Function// using Euler's product formulafunction phi(n){ // Initialize result as n let result = n; // Consider all prime factors // of n and for every prime // factor p, multiply result // with (1 - 1/p) for (let p = 2; p * p <= n; ++p) { // Check if p is // a prime factor. if (n % p == 0) { // If yes, then update // n and result while (n % p == 0) n /= p; result *= (1.0 - (1.0 / p)); } } // If n has a prime factor greater // than sqrt(n) (There can be at-most // one such prime factor) if (n > 1) result *= (1.0 - (1.0 / n)); return parseInt(result);} // Driver Codefor (let n = 1; n <= 10; n++) document.write(`phi(${n}) = ${phi(n)} <br>`); // This code is contributed by _saurabh_jaiswal Output : phi(1) = 1 phi(2) = 1 phi(3) = 2 phi(4) = 2 phi(5) = 4 phi(6) = 2 phi(7) = 6 phi(8) = 4 phi(9) = 6 phi(10) = 4 Time Complexity: O(n^(1/2) log n) Auxiliary Space: O(1) We can avoid floating-point calculations in the above method. The idea is to count all prime factors and their multiples and subtract this count from n to get the totient function value (Prime factors and multiples of prime factors won’t have gcd as 1) 1) Initialize result as n 2) Consider every number 'p' (where 'p' varies from 2 to Φn). If p divides n, then do following a) Subtract all multiples of p from 1 to n [all multiples of p will have gcd more than 1 (at least p) with n] b) Update n by repeatedly dividing it by p. 3) If the reduced n is more than 1, then remove all multiples of n from result. Below is the implementation of the above algorithm. C++ C Java Python3 C# PHP Javascript // C++ program to calculate Euler's// Totient Function#include <bits/stdc++.h>using namespace std; int phi(int n){ // Initialize result as n int result = n; // Consider all prime factors of n // and subtract their multiples // from result for(int p = 2; p * p <= n; ++p) { // Check if p is a prime factor. if (n % p == 0) { // If yes, then update n and result while (n % p == 0) n /= p; result -= result / p; } } // If n has a prime factor greater than sqrt(n) // (There can be at-most one such prime factor) if (n > 1) result -= result / n; return result;} // Driver codeint main(){ int n; for(n = 1; n <= 10; n++) { cout << "Phi" << "(" << n << ")" << " = " << phi(n) << endl; } return 0;} // This code is contributed by koulick_sadhu // C program to calculate Euler's Totient Function#include <stdio.h> int phi(int n){ int result = n; // Initialize result as n // Consider all prime factors of n and subtract their // multiples from result for (int p = 2; p * p <= n; ++p) { // Check if p is a prime factor. if (n % p == 0) { // If yes, then update n and result while (n % p == 0) n /= p; result -= result / p; } } // If n has a prime factor greater than sqrt(n) // (There can be at-most one such prime factor) if (n > 1) result -= result / n; return result;} // Driver program to test above functionint main(){ int n; for (n = 1; n <= 10; n++) printf("phi(%d) = %d\n", n, phi(n)); return 0;} // Java program to calculate// Euler's Totient Functionimport java.io.*; class GFG{static int phi(int n){ // Initialize result as n int result = n; // Consider all prime factors // of n and subtract their // multiples from result for (int p = 2; p * p <= n; ++p) { // Check if p is // a prime factor. if (n % p == 0) { // If yes, then update // n and result while (n % p == 0) n /= p; result -= result / p; } } // If n has a prime factor // greater than sqrt(n) // (There can be at-most // one such prime factor) if (n > 1) result -= result / n; return result;} // Driver Codepublic static void main (String[] args){ int n; for (n = 1; n <= 10; n++) System.out.println("phi(" + n + ") = " + phi(n));}} // This code is contributed by ajit # Python3 program to calculate# Euler's Totient Functiondef phi(n): # Initialize result as n result = n; # Consider all prime factors # of n and subtract their # multiples from result p = 2; while(p * p <= n): # Check if p is a # prime factor. if (n % p == 0): # If yes, then # update n and result while (n % p == 0): n = int(n / p); result -= int(result / p); p += 1; # If n has a prime factor # greater than sqrt(n) # (There can be at-most # one such prime factor) if (n > 1): result -= int(result / n); return result; # Driver Codefor n in range(1, 11): print("phi(",n,") =", phi(n)); # This code is contributed# by mits // C# program to calculate// Euler's Totient Functionusing System; class GFG{ static int phi(int n){// Initialize result as nint result = n; // Consider all prime // factors of n and// subtract their// multiples from resultfor (int p = 2; p * p <= n; ++p){ // Check if p is // a prime factor. if (n % p == 0) { // If yes, then update // n and result while (n % p == 0) n /= p; result -= result / p; }} // If n has a prime factor// greater than sqrt(n)// (There can be at-most// one such prime factor)if (n > 1) result -= result / n;return result;} // Driver Codestatic public void Main (){ int n; for (n = 1; n <= 10; n++) Console.WriteLine("phi(" + n + ") = " + phi(n));}} // This code is contributed// by akt_mit <Φphp// PHP program to calculate// Euler's Totient Function function phi($n){ // Initialize // result as n $result = $n; // Consider all prime // factors of n and subtract // their multiples from result for ($p = 2; $p * $p <= $n; ++$p) { // Check if p is // a prime factor. if ($n % $p == 0) { // If yes, then // update n and result while ($n % $p == 0) $n = (int)$n / $p; $result -= (int)$result / $p; } } // If n has a prime factor // greater than sqrt(n) // (There can be at-most // one such prime factor) if ($n > 1) $result -= (int)$result / $n; return $result;} // Driver Codefor ($n = 1; $n <= 10; $n++) echo "phi(", $n,") =", phi($n), "\n"; // This code is contributed// by ajitΦ> // Javascript program to calculate// Euler's Totient Function function phi(n){ // Initialize // result as n let result = n; // Consider all prime // factors of n and subtract // their multiples from result for (let p = 2; p * p <= n; ++p) { // Check if p is // a prime factor. if (n % p == 0) { // If yes, then // update n and result while (n % p == 0) n = parseInt(n / p); result -= parseInt(result / p); } } // If n has a prime factor // greater than sqrt(n) // (There can be at-most // one such prime factor) if (n > 1) result -= parseInt(result / n); return result;} // Driver Codefor (let n = 1; n <= 10; n++) document.write(`phi(${n}) = ${phi(n)} <br>`); // This code is contributed// by _saurabh_jaiswal Output : phi(1) = 1 phi(2) = 1 phi(3) = 2 phi(4) = 2 phi(5) = 4 phi(6) = 2 phi(7) = 6 phi(8) = 4 phi(9) = 6 phi(10) = 4 Time Complexity: O(n^(1/2) log n) Auxiliary Space: O(1) Let us take an example to understand the above algorithm. n = 10. Initialize: result = 10 2 is a prime factor, so n = n/i = 5, result = 5 3 is not a prime factor. The for loop stops after 3 as 4*4 is not less than or equal to 10. After for loop, result = 5, n = 5 Since n > 1, result = result - result/n = 4 1) For a prime number p, Proof : , where p is any prime number We know that where k is any random number and Total number from 1 to p = p Number for which is , i.e the number p itself, so subtracting 1 from p Examples : 2) For two prime numbers a and b, used in RSA Algorithm Proof : , where a and b are prime numbers , Total number from 1 to ab = ab Total multiples of a from 1 to ab = = Total multiples of b from 1 to ab = = Example: a = 5, b = 7, ab = 35 Multiples of a = = 7 {5, 10, 15, 20, 25, 30, 35} Multiples of b = = 5 {7, 14, 21, 28, 35} Can there be any double counting ?(watch above example carefully, try with other prime numbers also for more grasp) Ofcourse, we have counted twice in multiples of a and multiples of b so, Total multiples = a + b - 1 (with which with ) , removing all number with with Examples : 3) For a prime number p, Proof : , where p is a prime number Total numbers from 1 to Total multiples of Removing these multiples as with them Example : p = 2, k = 5, = 32 Multiples of 2 (as with them ) = 32 / 2 = 16 {2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32} Examples : 4) For two number a and b Special Case : gcd(a, b) = 1 Examples : Special Case : , Normal Case : , 5) Sum of values of totient functions of all divisors of n is equal to n. Examples : n = 6 factors = {1, 2, 3, 6} n = = 1 + 1 + 2 + 2 = 6 n = 8 factors = {1, 2, 4, 8} n = = 1 + 1 + 2 + 4 = 8 n = 10 factors = {1, 2, 5, 10} n = = 1 + 1 + 4 + 4 = 10 6) The most famous and important feature is expressed in Euler’s theorem : The theorem states that if n and a are coprime (or relatively prime) positive integers, then aΦ(n) ≡ 1 (mod n) The RSA cryptosystem is based on this theorem:In the particular case when m is prime say p, Euler’s theorem turns into the so-called Fermat’s little theorem : ap-1 ≡ 1 (mod p) 7) Number of generators of a finite cyclic group under modulo n addition is Φ(n). Related Article: Euler’s Totient function for all numbers smaller than or equal to n Optimized Euler Totient Function for Multiple Evaluations References: http://e-maxx.ru/algo/euler_functionhttp://en.wikipedia.org/wiki/Euler%27s_totient_function https://cp-algorithms.com/algebra/phi-function.html http://mathcenter.oxford.memory.edu/site/math125/chineseRemainderTheorem/This article is contributed by Ankur. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above nitin mittal Sam007 jit_t Smitha Dinesh Semwal Mithun Kumar SHUBHAMSINGH10 lalitvavdara2016 koulick_sadhu _saurabh_jaiswal tridib_samanta anshkush92 varshagumber28 prophet1999 euler-totient GCD-LCM Modular Arithmetic number-theory Numbers Prime Number sieve Mathematical number-theory Mathematical Prime Number Numbers sieve Modular Arithmetic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Print all possible combinations of r elements in a given array of size n Operators in C / C++ The Knight's tour problem | Backtracking-1 Program for factorial of a number Find minimum number of coins that make a given value Program to find sum of elements in a given array Program to print prime numbers from 1 to N.
[ { "code": null, "e": 25907, "s": 25879, "text": "\n13 Mar, 2022" }, { "code": null, "e": 26097, "s": 25907, "text": "Euler’s Totient function Φ (n) for an input n is the count of numbers in {1, 2, 3, ..., n} that are relatively prime to n, i.e., the numbers whose GCD (Greatest Common Divisor) with n is 1." }, { "code": null, "e": 26108, "s": 26097, "text": "Examples :" }, { "code": null, "e": 26391, "s": 26108, "text": "Φ(1) = 1 \ngcd(1, 1) is 1\n\nΦ(2) = 1\ngcd(1, 2) is 1, but gcd(2, 2) is 2.\n\nΦ(3) = 2\ngcd(1, 3) is 1 and gcd(2, 3) is 1\n\nΦ(4) = 2\ngcd(1, 4) is 1 and gcd(3, 4) is 1\n\nΦ(5) = 4\ngcd(1, 5) is 1, gcd(2, 5) is 1, \ngcd(3, 5) is 1 and gcd(4, 5) is 1\n\nΦ(6) = 2\ngcd(1, 6) is 1 and gcd(5, 6) is 1, " }, { "code": null, "e": 26642, "s": 26391, "text": "How to compute Φ(n) for an input nΦA simple solution is to iterate through all numbers from 1 to n-1 and count numbers with gcd with n as 1. Below is the implementation of the simple method to compute Euler’s Totient function for an input integer n. " }, { "code": null, "e": 26646, "s": 26642, "text": "C++" }, { "code": null, "e": 26648, "s": 26646, "text": "C" }, { "code": null, "e": 26653, "s": 26648, "text": "Java" }, { "code": null, "e": 26661, "s": 26653, "text": "Python3" }, { "code": null, "e": 26664, "s": 26661, "text": "C#" }, { "code": null, "e": 26668, "s": 26664, "text": "PHP" }, { "code": null, "e": 26679, "s": 26668, "text": "Javascript" }, { "code": "// A simple C++ program to calculate// Euler's Totient Function#include <iostream>using namespace std; // Function to return gcd of a and bint gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // A simple method to evaluate Euler Totient Functionint phi(unsigned int n){ unsigned int result = 1; for (int i = 2; i < n; i++) if (gcd(i, n) == 1) result++; return result;} // Driver program to test above functionint main(){ int n; for (n = 1; n <= 10; n++) cout << \"phi(\"<<n<<\") = \" << phi(n) << endl; return 0;} // This code is contributed by SHUBHAMSINGH10", "e": 27306, "s": 26679, "text": null }, { "code": "// A simple C program to calculate Euler's Totient Function#include <stdio.h> // Function to return gcd of a and bint gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // A simple method to evaluate Euler Totient Functionint phi(unsigned int n){ unsigned int result = 1; for (int i = 2; i < n; i++) if (gcd(i, n) == 1) result++; return result;} // Driver program to test above functionint main(){ int n; for (n = 1; n <= 10; n++) printf(\"phi(%d) = %d\\n\", n, phi(n)); return 0;}", "e": 27854, "s": 27306, "text": null }, { "code": "// A simple java program to calculate// Euler's Totient Functionimport java.io.*; class GFG { // Function to return GCD of a and b static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // A simple method to evaluate // Euler Totient Function static int phi(int n) { int result = 1; for (int i = 2; i < n; i++) if (gcd(i, n) == 1) result++; return result; } // Driver code public static void main(String[] args) { int n; for (n = 1; n <= 10; n++) System.out.println(\"phi(\" + n + \") = \" + phi(n)); }} // This code is contributed by sunnusingh", "e": 28558, "s": 27854, "text": null }, { "code": "# A simple Python3 program# to calculate Euler's# Totient Function # Function to return# gcd of a and bdef gcd(a, b): if (a == 0): return b return gcd(b % a, a) # A simple method to evaluate# Euler Totient Functiondef phi(n): result = 1 for i in range(2, n): if (gcd(i, n) == 1): result+=1 return result # Driver Codefor n in range(1, 11): print(\"phi(\",n,\") = \", phi(n), sep = \"\") # This code is contributed# by Smitha", "e": 29043, "s": 28558, "text": null }, { "code": "// A simple C# program to calculate// Euler's Totient Functionusing System; class GFG { // Function to return GCD of a and b static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // A simple method to evaluate // Euler Totient Function static int phi(int n) { int result = 1; for (int i = 2; i < n; i++) if (gcd(i, n) == 1) result++; return result; } // Driver code public static void Main() { for (int n = 1; n <= 10; n++) Console.WriteLine(\"phi(\" + n + \") = \" + phi(n)); }} // This code is contributed by nitin mittal", "e": 29714, "s": 29043, "text": null }, { "code": "<Φphp// PHP program to calculate// Euler's Totient Function // Function to return// gcd of a and bfunction gcd($a, $b){ if ($a == 0) return $b; return gcd($b % $a, $a);} // A simple method to evaluate// Euler Totient Functionfunction phi($n){ $result = 1; for ($i = 2; $i < $n; $i++) if (gcd($i, $n) == 1) $result++; return $result;} // Driver Codefor ($n = 1; $n <= 10; $n++) echo \"phi(\" .$n. \") =\" . phi($n).\"\\n\"; // This code is contributed by Sam007Φ>", "e": 30213, "s": 29714, "text": null }, { "code": "<script>// Javascript program to calculate// Euler's Totient Function // Function to return// gcd of a and bfunction gcd(a, b){ if (a == 0) return b; return gcd(b % a, a);} // A simple method to evaluate// Euler Totient Functionfunction phi(n){ let result = 1; for (let i = 2; i < n; i++) if (gcd(i, n) == 1) result++; return result;} // Driver Codefor (let n = 1; n <= 10; n++) document.write(`phi(${n}) = ${phi(n)} <br>`); // This code is contributed by _saurabh_jaiswal </script>", "e": 30739, "s": 30213, "text": null }, { "code": null, "e": 30749, "s": 30739, "text": "Output : " }, { "code": null, "e": 30861, "s": 30749, "text": "phi(1) = 1\nphi(2) = 1\nphi(3) = 2\nphi(4) = 2\nphi(5) = 4\nphi(6) = 2\nphi(7) = 6\nphi(8) = 4 \nphi(9) = 6\nphi(10) = 4" }, { "code": null, "e": 31185, "s": 30861, "text": "The above code calls gcd function O(n) times. The time complexity of the gcd function is O(h) where “h” is the number of digits in a smaller number of given two numbers. Therefore, an upper bound on the time complexity of the above solution is O(N log N) [HowΦ there can be at most Log10n digits in all numbers from 1 to n]" }, { "code": null, "e": 31211, "s": 31185, "text": "Auxiliary Space: O(log N)" }, { "code": null, "e": 31385, "s": 31211, "text": "Below is a Better Solution. The idea is based on Euler’s product formula which states that the value of totient functions is below the product overall prime factors p of n. " }, { "code": null, "e": 31635, "s": 31385, "text": "The formula basically says that the value of Φ(n) is equal to n multiplied by-product of (1 – 1/p) for all prime factors p of n. For example value of Φ(6) = 6 * (1-1/2) * (1 – 1/3) = 2.We can find all prime factors using the idea used in this post. " }, { "code": null, "e": 31885, "s": 31635, "text": "1) Initialize : result = n\n2) Run a loop from 'p' = 2 to sqrt(n), do following for every 'p'.\n a) If p divides n, then \n Set: result = result * (1.0 - (1.0 / (float) p));\n Divide all occurrences of p in n.\n3) Return result " }, { "code": null, "e": 31943, "s": 31885, "text": "Below is the implementation of Euler’s product formula. " }, { "code": null, "e": 31947, "s": 31943, "text": "C++" }, { "code": null, "e": 31949, "s": 31947, "text": "C" }, { "code": null, "e": 31954, "s": 31949, "text": "Java" }, { "code": null, "e": 31962, "s": 31954, "text": "Python3" }, { "code": null, "e": 31965, "s": 31962, "text": "C#" }, { "code": null, "e": 31969, "s": 31965, "text": "PHP" }, { "code": null, "e": 31980, "s": 31969, "text": "Javascript" }, { "code": "// C++ program to calculate Euler's// Totient Function using Euler's// product formula#include <bits/stdc++.h>using namespace std; int phi(int n){ // Initialize result as n float result = n; // Consider all prime factors of n // and for every prime factor p, // multiply result with (1 - 1/p) for(int p = 2; p * p <= n; ++p) { // Check if p is a prime factor. if (n % p == 0) { // If yes, then update n and result while (n % p == 0) n /= p; result *= (1.0 - (1.0 / (float)p)); } } // If n has a prime factor greater than sqrt(n) // (There can be at-most one such prime factor) if (n > 1) result *= (1.0 - (1.0 / (float)n)); return (int)result;} // Driver codeint main(){ int n; for(n = 1; n <= 10; n++) { cout << \"Phi\" << \"(\" << n << \")\" << \" = \" << phi(n) <<endl; } return 0;} // This code is contributed by koulick_sadhu", "e": 33024, "s": 31980, "text": null }, { "code": "// C program to calculate Euler's Totient Function// using Euler's product formula#include <stdio.h> int phi(int n){ float result = n; // Initialize result as n // Consider all prime factors of n and for every prime // factor p, multiply result with (1 - 1/p) for (int p = 2; p * p <= n; ++p) { // Check if p is a prime factor. if (n % p == 0) { // If yes, then update n and result while (n % p == 0) n /= p; result *= (1.0 - (1.0 / (float)p)); } } // If n has a prime factor greater than sqrt(n) // (There can be at-most one such prime factor) if (n > 1) result *= (1.0 - (1.0 / (float)n)); return (int)result;} // Driver program to test above functionint main(){ int n; for (n = 1; n <= 10; n++) printf(\"phi(%d) = %d\\n\", n, phi(n)); return 0;}", "e": 33914, "s": 33024, "text": null }, { "code": "// Java program to calculate Euler's Totient// Function using Euler's product formulaimport java.io.*; class GFG { static int phi(int n) { // Initialize result as n float result = n; // Consider all prime factors of n and for // every prime factor p, multiply result // with (1 - 1/p) for (int p = 2; p * p <= n; ++p) { // Check if p is a prime factor. if (n % p == 0) { // If yes, then update n and result while (n % p == 0) n /= p; result *= (1.0 - (1.0 / (float)p)); } } // If n has a prime factor greater than sqrt(n) // (There can be at-most one such prime factor) if (n > 1) result *= (1.0 - (1.0 / (float)n)); return (int)result; } // Driver program to test above function public static void main(String args[]) { int n; for (n = 1; n <= 10; n++) System.out.println(\"phi(\" + n + \") = \" + phi(n)); }} // This code is contributed by Nikita Tiwari.", "e": 35002, "s": 33914, "text": null }, { "code": "# Python 3 program to calculate# Euler's Totient Function# using Euler's product formula def phi(n) : result = n # Initialize result as n # Consider all prime factors # of n and for every prime # factor p, multiply result with (1 - 1 / p) p = 2 while p * p<= n : # Check if p is a prime factor. if n % p == 0 : # If yes, then update n and result while n % p == 0 : n = n // p result = result * (1.0 - (1.0 / float(p))) p = p + 1 # If n has a prime factor # greater than sqrt(n) # (There can be at-most one # such prime factor) if n > 1 : result = result * (1.0 - (1.0 / float(n))) return int(result) # Driver program to test above functionfor n in range(1, 11) : print(\"phi(\", n, \") = \", phi(n)) # This code is contributed# by Nikita Tiwari.", "e": 35903, "s": 35002, "text": null }, { "code": "// C# program to calculate Euler's Totient// Function using Euler's product formulausing System; class GFG { static int phi(int n) { // Initialize result as n float result = n; // Consider all prime factors // of n and for every prime // factor p, multiply result // with (1 - 1 / p) for (int p = 2; p * p <= n; ++p) { // Check if p is a prime factor. if (n % p == 0) { // If yes, then update // n and result while (n % p == 0) n /= p; result *= (float)(1.0 - (1.0 / (float)p)); } } // If n has a prime factor // greater than sqrt(n) // (There can be at-most // one such prime factor) if (n > 1) result *= (float)(1.0 - (1.0 / (float)n)); return (int)result; } // Driver Code public static void Main() { int n; for (n = 1; n <= 10; n++) Console.WriteLine(\"phi(\" + n + \") = \" + phi(n)); }} // This code is contributed by nitin mittal.", "e": 37070, "s": 35903, "text": null }, { "code": "<Φphp// PHP program to calculate// Euler's Totient Function// using Euler's product formulafunction phi($n){ // Initialize result as n $result = $n; // Consider all prime factors // of n and for every prime // factor p, multiply result // with (1 - 1/p) for ($p = 2; $p * $p <= $n; ++$p) { // Check if p is // a prime factor. if ($n % $p == 0) { // If yes, then update // n and result while ($n % $p == 0) $n /= $p; $result *= (1.0 - (1.0 / $p)); } } // If n has a prime factor greater // than sqrt(n) (There can be at-most // one such prime factor) if ($n > 1) $result *= (1.0 - (1.0 / $n)); return intval($result);} // Driver Codefor ($n = 1; $n <= 10; $n++)echo \"phi(\" .$n. \") =\" . phi($n).\"\\n\"; // This code is contributed by Sam007Φ>", "e": 37981, "s": 37070, "text": null }, { "code": "// Javascript program to calculate// Euler's Totient Function// using Euler's product formulafunction phi(n){ // Initialize result as n let result = n; // Consider all prime factors // of n and for every prime // factor p, multiply result // with (1 - 1/p) for (let p = 2; p * p <= n; ++p) { // Check if p is // a prime factor. if (n % p == 0) { // If yes, then update // n and result while (n % p == 0) n /= p; result *= (1.0 - (1.0 / p)); } } // If n has a prime factor greater // than sqrt(n) (There can be at-most // one such prime factor) if (n > 1) result *= (1.0 - (1.0 / n)); return parseInt(result);} // Driver Codefor (let n = 1; n <= 10; n++) document.write(`phi(${n}) = ${phi(n)} <br>`); // This code is contributed by _saurabh_jaiswal", "e": 38901, "s": 37981, "text": null }, { "code": null, "e": 38911, "s": 38901, "text": "Output : " }, { "code": null, "e": 39022, "s": 38911, "text": "phi(1) = 1\nphi(2) = 1\nphi(3) = 2\nphi(4) = 2\nphi(5) = 4\nphi(6) = 2\nphi(7) = 6\nphi(8) = 4\nphi(9) = 6\nphi(10) = 4" }, { "code": null, "e": 39056, "s": 39022, "text": "Time Complexity: O(n^(1/2) log n)" }, { "code": null, "e": 39078, "s": 39056, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 39332, "s": 39078, "text": "We can avoid floating-point calculations in the above method. The idea is to count all prime factors and their multiples and subtract this count from n to get the totient function value (Prime factors and multiples of prime factors won’t have gcd as 1) " }, { "code": null, "e": 39707, "s": 39332, "text": "1) Initialize result as n\n2) Consider every number 'p' (where 'p' varies from 2 to Φn). \n If p divides n, then do following\n a) Subtract all multiples of p from 1 to n [all multiples of p\n will have gcd more than 1 (at least p) with n]\n b) Update n by repeatedly dividing it by p.\n3) If the reduced n is more than 1, then remove all multiples\n of n from result." }, { "code": null, "e": 39760, "s": 39707, "text": "Below is the implementation of the above algorithm. " }, { "code": null, "e": 39764, "s": 39760, "text": "C++" }, { "code": null, "e": 39766, "s": 39764, "text": "C" }, { "code": null, "e": 39771, "s": 39766, "text": "Java" }, { "code": null, "e": 39779, "s": 39771, "text": "Python3" }, { "code": null, "e": 39782, "s": 39779, "text": "C#" }, { "code": null, "e": 39786, "s": 39782, "text": "PHP" }, { "code": null, "e": 39797, "s": 39786, "text": "Javascript" }, { "code": "// C++ program to calculate Euler's// Totient Function#include <bits/stdc++.h>using namespace std; int phi(int n){ // Initialize result as n int result = n; // Consider all prime factors of n // and subtract their multiples // from result for(int p = 2; p * p <= n; ++p) { // Check if p is a prime factor. if (n % p == 0) { // If yes, then update n and result while (n % p == 0) n /= p; result -= result / p; } } // If n has a prime factor greater than sqrt(n) // (There can be at-most one such prime factor) if (n > 1) result -= result / n; return result;} // Driver codeint main(){ int n; for(n = 1; n <= 10; n++) { cout << \"Phi\" << \"(\" << n << \")\" << \" = \" << phi(n) << endl; } return 0;} // This code is contributed by koulick_sadhu", "e": 40752, "s": 39797, "text": null }, { "code": "// C program to calculate Euler's Totient Function#include <stdio.h> int phi(int n){ int result = n; // Initialize result as n // Consider all prime factors of n and subtract their // multiples from result for (int p = 2; p * p <= n; ++p) { // Check if p is a prime factor. if (n % p == 0) { // If yes, then update n and result while (n % p == 0) n /= p; result -= result / p; } } // If n has a prime factor greater than sqrt(n) // (There can be at-most one such prime factor) if (n > 1) result -= result / n; return result;} // Driver program to test above functionint main(){ int n; for (n = 1; n <= 10; n++) printf(\"phi(%d) = %d\\n\", n, phi(n)); return 0;}", "e": 41554, "s": 40752, "text": null }, { "code": "// Java program to calculate// Euler's Totient Functionimport java.io.*; class GFG{static int phi(int n){ // Initialize result as n int result = n; // Consider all prime factors // of n and subtract their // multiples from result for (int p = 2; p * p <= n; ++p) { // Check if p is // a prime factor. if (n % p == 0) { // If yes, then update // n and result while (n % p == 0) n /= p; result -= result / p; } } // If n has a prime factor // greater than sqrt(n) // (There can be at-most // one such prime factor) if (n > 1) result -= result / n; return result;} // Driver Codepublic static void main (String[] args){ int n; for (n = 1; n <= 10; n++) System.out.println(\"phi(\" + n + \") = \" + phi(n));}} // This code is contributed by ajit", "e": 42498, "s": 41554, "text": null }, { "code": "# Python3 program to calculate# Euler's Totient Functiondef phi(n): # Initialize result as n result = n; # Consider all prime factors # of n and subtract their # multiples from result p = 2; while(p * p <= n): # Check if p is a # prime factor. if (n % p == 0): # If yes, then # update n and result while (n % p == 0): n = int(n / p); result -= int(result / p); p += 1; # If n has a prime factor # greater than sqrt(n) # (There can be at-most # one such prime factor) if (n > 1): result -= int(result / n); return result; # Driver Codefor n in range(1, 11): print(\"phi(\",n,\") =\", phi(n)); # This code is contributed# by mits", "e": 43291, "s": 42498, "text": null }, { "code": "// C# program to calculate// Euler's Totient Functionusing System; class GFG{ static int phi(int n){// Initialize result as nint result = n; // Consider all prime // factors of n and// subtract their// multiples from resultfor (int p = 2; p * p <= n; ++p){ // Check if p is // a prime factor. if (n % p == 0) { // If yes, then update // n and result while (n % p == 0) n /= p; result -= result / p; }} // If n has a prime factor// greater than sqrt(n)// (There can be at-most// one such prime factor)if (n > 1) result -= result / n;return result;} // Driver Codestatic public void Main (){ int n; for (n = 1; n <= 10; n++) Console.WriteLine(\"phi(\" + n + \") = \" + phi(n));}} // This code is contributed// by akt_mit", "e": 44160, "s": 43291, "text": null }, { "code": "<Φphp// PHP program to calculate// Euler's Totient Function function phi($n){ // Initialize // result as n $result = $n; // Consider all prime // factors of n and subtract // their multiples from result for ($p = 2; $p * $p <= $n; ++$p) { // Check if p is // a prime factor. if ($n % $p == 0) { // If yes, then // update n and result while ($n % $p == 0) $n = (int)$n / $p; $result -= (int)$result / $p; } } // If n has a prime factor // greater than sqrt(n) // (There can be at-most // one such prime factor) if ($n > 1) $result -= (int)$result / $n; return $result;} // Driver Codefor ($n = 1; $n <= 10; $n++) echo \"phi(\", $n,\") =\", phi($n), \"\\n\"; // This code is contributed// by ajitΦ>", "e": 45044, "s": 44160, "text": null }, { "code": "// Javascript program to calculate// Euler's Totient Function function phi(n){ // Initialize // result as n let result = n; // Consider all prime // factors of n and subtract // their multiples from result for (let p = 2; p * p <= n; ++p) { // Check if p is // a prime factor. if (n % p == 0) { // If yes, then // update n and result while (n % p == 0) n = parseInt(n / p); result -= parseInt(result / p); } } // If n has a prime factor // greater than sqrt(n) // (There can be at-most // one such prime factor) if (n > 1) result -= parseInt(result / n); return result;} // Driver Codefor (let n = 1; n <= 10; n++) document.write(`phi(${n}) = ${phi(n)} <br>`); // This code is contributed// by _saurabh_jaiswal", "e": 45940, "s": 45044, "text": null }, { "code": null, "e": 45951, "s": 45940, "text": "Output : " }, { "code": null, "e": 46062, "s": 45951, "text": "phi(1) = 1\nphi(2) = 1\nphi(3) = 2\nphi(4) = 2\nphi(5) = 4\nphi(6) = 2\nphi(7) = 6\nphi(8) = 4\nphi(9) = 6\nphi(10) = 4" }, { "code": null, "e": 46096, "s": 46062, "text": "Time Complexity: O(n^(1/2) log n)" }, { "code": null, "e": 46118, "s": 46096, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 46177, "s": 46118, "text": "Let us take an example to understand the above algorithm. " }, { "code": null, "e": 46431, "s": 46177, "text": "n = 10. \nInitialize: result = 10\n\n2 is a prime factor, so n = n/i = 5, result = 5\n3 is not a prime factor.\n\nThe for loop stops after 3 as 4*4 is not less than or equal\nto 10.\n\nAfter for loop, result = 5, n = 5\nSince n > 1, result = result - result/n = 4" }, { "code": null, "e": 46457, "s": 46431, "text": "1) For a prime number p, " }, { "code": null, "e": 46465, "s": 46457, "text": "Proof :" }, { "code": null, "e": 46649, "s": 46465, "text": " , where p is any prime number\nWe know that where k is any random number and \n\nTotal number from 1 to p = p \nNumber for which is , i.e the number p itself, so subtracting 1 from p \n" }, { "code": null, "e": 46662, "s": 46649, "text": "Examples : " }, { "code": null, "e": 46723, "s": 46667, "text": "2) For two prime numbers a and b, used in RSA Algorithm" }, { "code": null, "e": 46731, "s": 46723, "text": "Proof :" }, { "code": null, "e": 47286, "s": 46731, "text": ", where a and b are prime numbers\n , \n\nTotal number from 1 to ab = ab \nTotal multiples of a from 1 to ab = = \nTotal multiples of b from 1 to ab = = \nExample:\na = 5, b = 7, ab = 35\nMultiples of a = = 7 {5, 10, 15, 20, 25, 30, 35}\nMultiples of b = = 5 {7, 14, 21, 28, 35}\n\nCan there be any double counting ?(watch above example carefully, try with other prime numbers also for more grasp)\nOfcourse, we have counted twice in multiples of a and multiples of b so, \nTotal multiples = a + b - 1 (with which with )\n\n , removing all number with with \n\n\n" }, { "code": null, "e": 47297, "s": 47286, "text": "Examples :" }, { "code": null, "e": 47328, "s": 47302, "text": "3) For a prime number p, " }, { "code": null, "e": 47337, "s": 47328, "text": "Proof : " }, { "code": null, "e": 47592, "s": 47337, "text": " , where p is a prime number\n\nTotal numbers from 1 to \nTotal multiples of \nRemoving these multiples as with them \n\nExample : \np = 2, k = 5, = 32\nMultiples of 2 (as with them ) = 32 / 2 = 16 {2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32}\n\n" }, { "code": null, "e": 47604, "s": 47592, "text": "Examples : " }, { "code": null, "e": 47638, "s": 47609, "text": "4) For two number a and b " }, { "code": null, "e": 47667, "s": 47638, "text": "Special Case : gcd(a, b) = 1" }, { "code": null, "e": 47678, "s": 47667, "text": "Examples :" }, { "code": null, "e": 47730, "s": 47678, "text": "Special Case : , \n\n\n\n\n \n\n\nNormal Case : , \n\n \n\n\n\n" }, { "code": null, "e": 47806, "s": 47730, "text": "5) Sum of values of totient functions of all divisors of n is equal to n. " }, { "code": null, "e": 47817, "s": 47806, "text": "Examples :" }, { "code": null, "e": 47986, "s": 47817, "text": "n = 6 \nfactors = {1, 2, 3, 6} \nn = = 1 + 1 + 2 + 2 = 6\n\nn = 8\nfactors = {1, 2, 4, 8}\nn = = 1 + 1 + 2 + 4 = 8\n\nn = 10\nfactors = {1, 2, 5, 10}\nn = = 1 + 1 + 4 + 4 = 10" }, { "code": null, "e": 48062, "s": 47986, "text": "6) The most famous and important feature is expressed in Euler’s theorem : " }, { "code": null, "e": 48175, "s": 48062, "text": "The theorem states that if n and a are coprime\n(or relatively prime) positive integers, then\n\naΦ(n) ≡ 1 (mod n) " }, { "code": null, "e": 48335, "s": 48175, "text": "The RSA cryptosystem is based on this theorem:In the particular case when m is prime say p, Euler’s theorem turns into the so-called Fermat’s little theorem : " }, { "code": null, "e": 48353, "s": 48335, "text": "ap-1 ≡ 1 (mod p) " }, { "code": null, "e": 48435, "s": 48353, "text": "7) Number of generators of a finite cyclic group under modulo n addition is Φ(n)." }, { "code": null, "e": 48578, "s": 48435, "text": "Related Article: Euler’s Totient function for all numbers smaller than or equal to n Optimized Euler Totient Function for Multiple Evaluations" }, { "code": null, "e": 48682, "s": 48578, "text": "References: http://e-maxx.ru/algo/euler_functionhttp://en.wikipedia.org/wiki/Euler%27s_totient_function" }, { "code": null, "e": 48734, "s": 48682, "text": "https://cp-algorithms.com/algebra/phi-function.html" }, { "code": null, "e": 48970, "s": 48734, "text": "http://mathcenter.oxford.memory.edu/site/math125/chineseRemainderTheorem/This article is contributed by Ankur. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 48983, "s": 48970, "text": "nitin mittal" }, { "code": null, "e": 48990, "s": 48983, "text": "Sam007" }, { "code": null, "e": 48996, "s": 48990, "text": "jit_t" }, { "code": null, "e": 49017, "s": 48996, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 49030, "s": 49017, "text": "Mithun Kumar" }, { "code": null, "e": 49045, "s": 49030, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 49062, "s": 49045, "text": "lalitvavdara2016" }, { "code": null, "e": 49076, "s": 49062, "text": "koulick_sadhu" }, { "code": null, "e": 49093, "s": 49076, "text": "_saurabh_jaiswal" }, { "code": null, "e": 49108, "s": 49093, "text": "tridib_samanta" }, { "code": null, "e": 49119, "s": 49108, "text": "anshkush92" }, { "code": null, "e": 49134, "s": 49119, "text": "varshagumber28" }, { "code": null, "e": 49146, "s": 49134, "text": "prophet1999" }, { "code": null, "e": 49160, "s": 49146, "text": "euler-totient" }, { "code": null, "e": 49168, "s": 49160, "text": "GCD-LCM" }, { "code": null, "e": 49187, "s": 49168, "text": "Modular Arithmetic" }, { "code": null, "e": 49201, "s": 49187, "text": "number-theory" }, { "code": null, "e": 49209, "s": 49201, "text": "Numbers" }, { "code": null, "e": 49222, "s": 49209, "text": "Prime Number" }, { "code": null, "e": 49228, "s": 49222, "text": "sieve" }, { "code": null, "e": 49241, "s": 49228, "text": "Mathematical" }, { "code": null, "e": 49255, "s": 49241, "text": "number-theory" }, { "code": null, "e": 49268, "s": 49255, "text": "Mathematical" }, { "code": null, "e": 49281, "s": 49268, "text": "Prime Number" }, { "code": null, "e": 49289, "s": 49281, "text": "Numbers" }, { "code": null, "e": 49295, "s": 49289, "text": "sieve" }, { "code": null, "e": 49314, "s": 49295, "text": "Modular Arithmetic" }, { "code": null, "e": 49412, "s": 49314, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 49436, "s": 49412, "text": "Merge two sorted arrays" }, { "code": null, "e": 49479, "s": 49436, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 49493, "s": 49479, "text": "Prime Numbers" }, { "code": null, "e": 49566, "s": 49493, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 49587, "s": 49566, "text": "Operators in C / C++" }, { "code": null, "e": 49630, "s": 49587, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 49664, "s": 49630, "text": "Program for factorial of a number" }, { "code": null, "e": 49717, "s": 49664, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 49766, "s": 49717, "text": "Program to find sum of elements in a given array" } ]
Debian Software Package Management(dpkg) in Linux - GeeksforGeeks
01 Feb, 2021 In Linux, there are a lot of different distributions and each of these distributions has a different package type. For example .rpm or Red hat Package Manager is used as the package in the Linux distribution. A package is the compressed version of the software. In this article, we will go through the Debian package which is used by Ubuntu. D package or Debian Package is used to install and download the software in Debian based Linux systems. Debian files end with .deb extension. 1. Installing a stand-alone package using the Debian package To install a package -i flag is used. To download a stand-alone package using the Debian package, this command is used: sudo dpkg -i name_of_package.deb Example: To download standalone package for the open-source text editor, atom sudo dpkg -i atom-amd64.deb 2. Removing a package using the Debian package To remove a package -r flag is used sudo dpkg -r name_of_package Example: To remove the package for the text editor “atom” sudo dpkg -r atom Note: -P flag helps to remove everything including conf files. dpkg -P [package-name] dpkg -P googler_3.3.0-1_all.deb 3. Listing the debian packages To list all the Debian packages -l flag is used. dpkg -l The above line would give the output similar to the one shown below: To find a particular package use the grep command: dpkg -l | grep name_of_package. The output of this command would look similar to the one shown below: 4. List the dpkg commands available -help option lists all the available dpkg commands dpkg –help Output of this command would look similar to the one shown below: 5. View the content of a particular package To view the content of the particular package -c flag is used dpkg -c [name of the package] dpkg -c flashplugin-nonfree_3.2_i386.deb Output of this command would look similar to the one shown below: 6. Print architecture of dpkg installs –print-architecture command prints the architecture of dpkg installs dpkg --print-architecture Output could be amd64, i386, etc. For example, the output produced by the above code is as shown: 7. Unpack a package –unpack flag helps us unpack the package. dpkg --unpack [package-name] dpkg --unpack flashplugin-nonfree_3.2_i386.deb The output would look as shown below: The package can be later configured using –configure flag. dpkg --configure [package-name] dpkg --configure flashplugin-nonfree 8. Check if the package is installed or not To check if a particular package is installed or not -s flag is used. dpkg -s [package-name] dpkg -s git The output would look as shown below: 9. Reconfigure the installed package To reconfigure the already installed package dpkg-reconfigure command is used dpkg-reconfigure [package-name] Locate the installed package The location of the installed package can be found using -L flag. dpkg -L [package-name] dpkg -L git The output would look as shown below: 10. Check for any issue with the installed package –audit flag would be used to check for the issues with the package. dpkg --audit 11. Erase information –clear-avail – Erases available information about the current packages dpkg –-clear-avail 12. Display dpkg version dpkg –version is used to display dpkg version information. sudo dpkg --version linux 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": "\n01 Feb, 2021" }, { "code": null, "e": 26136, "s": 25651, "text": "In Linux, there are a lot of different distributions and each of these distributions has a different package type. For example .rpm or Red hat Package Manager is used as the package in the Linux distribution. A package is the compressed version of the software. In this article, we will go through the Debian package which is used by Ubuntu. D package or Debian Package is used to install and download the software in Debian based Linux systems. Debian files end with .deb extension." }, { "code": null, "e": 26197, "s": 26136, "text": "1. Installing a stand-alone package using the Debian package" }, { "code": null, "e": 26317, "s": 26197, "text": "To install a package -i flag is used. To download a stand-alone package using the Debian package, this command is used:" }, { "code": null, "e": 26350, "s": 26317, "text": "sudo dpkg -i name_of_package.deb" }, { "code": null, "e": 26428, "s": 26350, "text": "Example: To download standalone package for the open-source text editor, atom" }, { "code": null, "e": 26456, "s": 26428, "text": "sudo dpkg -i atom-amd64.deb" }, { "code": null, "e": 26503, "s": 26456, "text": "2. Removing a package using the Debian package" }, { "code": null, "e": 26540, "s": 26503, "text": "To remove a package -r flag is used " }, { "code": null, "e": 26569, "s": 26540, "text": "sudo dpkg -r name_of_package" }, { "code": null, "e": 26627, "s": 26569, "text": "Example: To remove the package for the text editor “atom”" }, { "code": null, "e": 26645, "s": 26627, "text": "sudo dpkg -r atom" }, { "code": null, "e": 26708, "s": 26645, "text": "Note: -P flag helps to remove everything including conf files." }, { "code": null, "e": 26763, "s": 26708, "text": "dpkg -P [package-name]\ndpkg -P googler_3.3.0-1_all.deb" }, { "code": null, "e": 26794, "s": 26763, "text": "3. Listing the debian packages" }, { "code": null, "e": 26843, "s": 26794, "text": "To list all the Debian packages -l flag is used." }, { "code": null, "e": 26851, "s": 26843, "text": "dpkg -l" }, { "code": null, "e": 26920, "s": 26851, "text": "The above line would give the output similar to the one shown below:" }, { "code": null, "e": 26972, "s": 26920, "text": "To find a particular package use the grep command: " }, { "code": null, "e": 27004, "s": 26972, "text": "dpkg -l | grep name_of_package." }, { "code": null, "e": 27074, "s": 27004, "text": "The output of this command would look similar to the one shown below:" }, { "code": null, "e": 27110, "s": 27074, "text": "4. List the dpkg commands available" }, { "code": null, "e": 27161, "s": 27110, "text": "-help option lists all the available dpkg commands" }, { "code": null, "e": 27172, "s": 27161, "text": "dpkg –help" }, { "code": null, "e": 27238, "s": 27172, "text": "Output of this command would look similar to the one shown below:" }, { "code": null, "e": 27282, "s": 27238, "text": "5. View the content of a particular package" }, { "code": null, "e": 27344, "s": 27282, "text": "To view the content of the particular package -c flag is used" }, { "code": null, "e": 27415, "s": 27344, "text": "dpkg -c [name of the package]\ndpkg -c flashplugin-nonfree_3.2_i386.deb" }, { "code": null, "e": 27481, "s": 27415, "text": "Output of this command would look similar to the one shown below:" }, { "code": null, "e": 27520, "s": 27481, "text": "6. Print architecture of dpkg installs" }, { "code": null, "e": 27589, "s": 27520, "text": "–print-architecture command prints the architecture of dpkg installs" }, { "code": null, "e": 27615, "s": 27589, "text": "dpkg --print-architecture" }, { "code": null, "e": 27649, "s": 27615, "text": "Output could be amd64, i386, etc." }, { "code": null, "e": 27713, "s": 27649, "text": "For example, the output produced by the above code is as shown:" }, { "code": null, "e": 27733, "s": 27713, "text": "7. Unpack a package" }, { "code": null, "e": 27775, "s": 27733, "text": "–unpack flag helps us unpack the package." }, { "code": null, "e": 27851, "s": 27775, "text": "dpkg --unpack [package-name]\ndpkg --unpack flashplugin-nonfree_3.2_i386.deb" }, { "code": null, "e": 27889, "s": 27851, "text": "The output would look as shown below:" }, { "code": null, "e": 27948, "s": 27889, "text": "The package can be later configured using –configure flag." }, { "code": null, "e": 28017, "s": 27948, "text": "dpkg --configure [package-name]\ndpkg --configure flashplugin-nonfree" }, { "code": null, "e": 28061, "s": 28017, "text": "8. Check if the package is installed or not" }, { "code": null, "e": 28131, "s": 28061, "text": "To check if a particular package is installed or not -s flag is used." }, { "code": null, "e": 28166, "s": 28131, "text": "dpkg -s [package-name]\ndpkg -s git" }, { "code": null, "e": 28204, "s": 28166, "text": "The output would look as shown below:" }, { "code": null, "e": 28241, "s": 28204, "text": "9. Reconfigure the installed package" }, { "code": null, "e": 28319, "s": 28241, "text": "To reconfigure the already installed package dpkg-reconfigure command is used" }, { "code": null, "e": 28351, "s": 28319, "text": "dpkg-reconfigure [package-name]" }, { "code": null, "e": 28380, "s": 28351, "text": "Locate the installed package" }, { "code": null, "e": 28446, "s": 28380, "text": "The location of the installed package can be found using -L flag." }, { "code": null, "e": 28481, "s": 28446, "text": "dpkg -L [package-name]\ndpkg -L git" }, { "code": null, "e": 28519, "s": 28481, "text": "The output would look as shown below:" }, { "code": null, "e": 28570, "s": 28519, "text": "10. Check for any issue with the installed package" }, { "code": null, "e": 28638, "s": 28570, "text": "–audit flag would be used to check for the issues with the package." }, { "code": null, "e": 28651, "s": 28638, "text": "dpkg --audit" }, { "code": null, "e": 28674, "s": 28651, "text": "11. Erase information " }, { "code": null, "e": 28745, "s": 28674, "text": "–clear-avail – Erases available information about the current packages" }, { "code": null, "e": 28764, "s": 28745, "text": "dpkg –-clear-avail" }, { "code": null, "e": 28789, "s": 28764, "text": "12. Display dpkg version" }, { "code": null, "e": 28848, "s": 28789, "text": "dpkg –version is used to display dpkg version information." }, { "code": null, "e": 28868, "s": 28848, "text": "sudo dpkg --version" }, { "code": null, "e": 28874, "s": 28868, "text": "linux" }, { "code": null, "e": 28885, "s": 28874, "text": "Linux-Unix" }, { "code": null, "e": 28983, "s": 28885, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29018, "s": 28983, "text": "scp command in Linux with Examples" }, { "code": null, "e": 29052, "s": 29018, "text": "mv command in Linux with examples" }, { "code": null, "e": 29078, "s": 29052, "text": "Docker - COPY Instruction" }, { "code": null, "e": 29107, "s": 29078, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 29144, "s": 29107, "text": "chown command in Linux with Examples" }, { "code": null, "e": 29181, "s": 29144, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 29223, "s": 29181, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 29249, "s": 29223, "text": "Thread functions in C/C++" }, { "code": null, "e": 29285, "s": 29249, "text": "uniq Command in LINUX with examples" } ]
Python - Extract range of Consecutive Similar elements ranges from string list - GeeksforGeeks
01 Oct, 2020 Given a list, extract range of consecutive similar elements. Input : test_list = [2, 3, 3, 3, 8, 8] Output : [(2, 0, 0), (3, 1, 3), (8, 4, 5)] Explanation : 2 occurs from 0th to 0th index, 3 from 1st to 3rd index. Input : test_list = [3, 3, 3] Output : [(3, 0, 3)] Explanation : 3 from 0th to 3rd index. Approach: Using loop This is a brute way to tackle this problem. In this, we loop for each element and get a similar element range. These are traced and appended in list accordingly with elements. Python3 # Python3 code to demonstrate working of # Consecutive Similar elements ranges# Using loop # initializing listtest_list = [2, 3, 3, 3, 8, 8, 6, 7, 7] # printing original listprint("The original list is : " + str(test_list)) res = []idx = 0while idx < (len(test_list)): strt_pos = idx val = test_list[idx] # getting last pos. while (idx < len(test_list) and test_list[idx] == val): idx += 1 end_pos = idx - 1 # appending in format [ele, strt_pos, end_pos] res.append((val, strt_pos, end_pos)) # printing result print("Elements with range : " + str(res)) Output: The original list is : [2, 3, 3, 3, 8, 8, 6, 7, 7]Elements with range : [(2, 0, 0), (3, 1, 3), (8, 4, 5), (6, 6, 6), (7, 7, 8)] Python list-programs Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 25613, "s": 25585, "text": "\n01 Oct, 2020" }, { "code": null, "e": 25674, "s": 25613, "text": "Given a list, extract range of consecutive similar elements." }, { "code": null, "e": 25827, "s": 25674, "text": "Input : test_list = [2, 3, 3, 3, 8, 8] Output : [(2, 0, 0), (3, 1, 3), (8, 4, 5)] Explanation : 2 occurs from 0th to 0th index, 3 from 1st to 3rd index." }, { "code": null, "e": 25918, "s": 25827, "text": "Input : test_list = [3, 3, 3] Output : [(3, 0, 3)] Explanation : 3 from 0th to 3rd index. " }, { "code": null, "e": 25939, "s": 25918, "text": "Approach: Using loop" }, { "code": null, "e": 26115, "s": 25939, "text": "This is a brute way to tackle this problem. In this, we loop for each element and get a similar element range. These are traced and appended in list accordingly with elements." }, { "code": null, "e": 26123, "s": 26115, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Consecutive Similar elements ranges# Using loop # initializing listtest_list = [2, 3, 3, 3, 8, 8, 6, 7, 7] # printing original listprint(\"The original list is : \" + str(test_list)) res = []idx = 0while idx < (len(test_list)): strt_pos = idx val = test_list[idx] # getting last pos. while (idx < len(test_list) and test_list[idx] == val): idx += 1 end_pos = idx - 1 # appending in format [ele, strt_pos, end_pos] res.append((val, strt_pos, end_pos)) # printing result print(\"Elements with range : \" + str(res))", "e": 26721, "s": 26123, "text": null }, { "code": null, "e": 26729, "s": 26721, "text": "Output:" }, { "code": null, "e": 26857, "s": 26729, "text": "The original list is : [2, 3, 3, 3, 8, 8, 6, 7, 7]Elements with range : [(2, 0, 0), (3, 1, 3), (8, 4, 5), (6, 6, 6), (7, 7, 8)]" }, { "code": null, "e": 26878, "s": 26857, "text": "Python list-programs" }, { "code": null, "e": 26901, "s": 26878, "text": "Python string-programs" }, { "code": null, "e": 26908, "s": 26901, "text": "Python" }, { "code": null, "e": 26924, "s": 26908, "text": "Python Programs" }, { "code": null, "e": 27022, "s": 26924, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27040, "s": 27022, "text": "Python Dictionary" }, { "code": null, "e": 27072, "s": 27040, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27094, "s": 27072, "text": "Enumerate() in Python" }, { "code": null, "e": 27136, "s": 27094, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27166, "s": 27136, "text": "Iterate over a list in Python" }, { "code": null, "e": 27209, "s": 27166, "text": "Python program to convert a list to string" }, { "code": null, "e": 27231, "s": 27209, "text": "Defaultdict in Python" }, { "code": null, "e": 27270, "s": 27231, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27316, "s": 27270, "text": "Python | Split string into list of characters" } ]
How to get column names in Pandas dataframe - GeeksforGeeks
12 May, 2022 While analyzing the real datasets which are often very huge in size, we might need to get the column names in order to perform some certain operations. Let’s discuss how to get column names in Pandas dataframe. First, let’s create a simple dataframe with nba.csv file. Python3 # Import pandas package import pandas as pd # making data frame data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # calling head() method # storing in new variable data_top = data.head() # display data_top Now let’s try to get the columns name from above dataset. YouTubeGeeksforGeeks507K subscribersDifferent Ways to Get Python Pandas Column Names | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:20•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Ty9TWZ7js6A" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Method #1: Simply iterating over columns Python3 # Import pandas package import pandas as pd # making data frame data = pd.read_csv("nba.csv") # iterating the columnsfor col in data.columns: print(col) Output: Method #2: Using columns with dataframe object Python3 # Import pandas package import pandas as pd # making data frame data = pd.read_csv("nba.csv") # list(data) orlist(data.columns) Output: Method #3: column.values method returns an array of index. Python3 # Import pandas package import pandas as pd # making data frame data = pd.read_csv("nba.csv") list(data.columns.values) Output: Method #4: Using tolist() method with values with given the list of columns. Python3 # Import pandas package import pandas as pd # making data frame data = pd.read_csv("nba.csv") list(data.columns.values.tolist()) Output: Method #5: Using sorted() method Sorted() method will return the list of columns sorted in alphabetical order. Python3 # Import pandas package import pandas as pd # making data frame data = pd.read_csv("nba.csv") # using sorted() methodsorted(data) Output: sagartomar9927 pandas-dataframe-program Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? *args and **kwargs in Python Create a Pandas DataFrame from Lists Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list GET and POST requests using Python
[ { "code": null, "e": 25875, "s": 25847, "text": "\n12 May, 2022" }, { "code": null, "e": 26145, "s": 25875, "text": "While analyzing the real datasets which are often very huge in size, we might need to get the column names in order to perform some certain operations. Let’s discuss how to get column names in Pandas dataframe. First, let’s create a simple dataframe with nba.csv file. " }, { "code": null, "e": 26153, "s": 26145, "text": "Python3" }, { "code": "# Import pandas package import pandas as pd # making data frame data = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # calling head() method # storing in new variable data_top = data.head() # display data_top ", "e": 26404, "s": 26153, "text": null }, { "code": null, "e": 26463, "s": 26404, "text": " Now let’s try to get the columns name from above dataset." }, { "code": null, "e": 27310, "s": 26463, "text": "YouTubeGeeksforGeeks507K subscribersDifferent Ways to Get Python Pandas Column Names | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:20•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Ty9TWZ7js6A\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 27352, "s": 27310, "text": "Method #1: Simply iterating over columns " }, { "code": null, "e": 27360, "s": 27352, "text": "Python3" }, { "code": "# Import pandas package import pandas as pd # making data frame data = pd.read_csv(\"nba.csv\") # iterating the columnsfor col in data.columns: print(col)", "e": 27522, "s": 27360, "text": null }, { "code": null, "e": 27581, "s": 27522, "text": "Output: Method #2: Using columns with dataframe object " }, { "code": null, "e": 27589, "s": 27581, "text": "Python3" }, { "code": "# Import pandas package import pandas as pd # making data frame data = pd.read_csv(\"nba.csv\") # list(data) orlist(data.columns)", "e": 27725, "s": 27589, "text": null }, { "code": null, "e": 27796, "s": 27725, "text": "Output: Method #3: column.values method returns an array of index. " }, { "code": null, "e": 27804, "s": 27796, "text": "Python3" }, { "code": "# Import pandas package import pandas as pd # making data frame data = pd.read_csv(\"nba.csv\") list(data.columns.values)", "e": 27932, "s": 27804, "text": null }, { "code": null, "e": 28021, "s": 27932, "text": "Output: Method #4: Using tolist() method with values with given the list of columns. " }, { "code": null, "e": 28029, "s": 28021, "text": "Python3" }, { "code": "# Import pandas package import pandas as pd # making data frame data = pd.read_csv(\"nba.csv\") list(data.columns.values.tolist())", "e": 28166, "s": 28029, "text": null }, { "code": null, "e": 28289, "s": 28166, "text": "Output: Method #5: Using sorted() method Sorted() method will return the list of columns sorted in alphabetical order. " }, { "code": null, "e": 28297, "s": 28289, "text": "Python3" }, { "code": "# Import pandas package import pandas as pd # making data frame data = pd.read_csv(\"nba.csv\") # using sorted() methodsorted(data)", "e": 28435, "s": 28297, "text": null }, { "code": null, "e": 28444, "s": 28435, "text": "Output: " }, { "code": null, "e": 28459, "s": 28444, "text": "sagartomar9927" }, { "code": null, "e": 28484, "s": 28459, "text": "pandas-dataframe-program" }, { "code": null, "e": 28508, "s": 28484, "text": "Python pandas-dataFrame" }, { "code": null, "e": 28522, "s": 28508, "text": "Python-pandas" }, { "code": null, "e": 28529, "s": 28522, "text": "Python" }, { "code": null, "e": 28627, "s": 28529, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28659, "s": 28627, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28688, "s": 28659, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28725, "s": 28688, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28767, "s": 28725, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28809, "s": 28767, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28865, "s": 28809, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28892, "s": 28865, "text": "Python Classes and Objects" }, { "code": null, "e": 28923, "s": 28892, "text": "Python | os.path.join() method" }, { "code": null, "e": 28962, "s": 28923, "text": "Python | Get unique values from a list" } ]
Java Program to Calculate and Display Area of a Circle - GeeksforGeeks
28 Mar, 2021 Given a radius of the circle, write a java program to calculate and display the area of the circle. (Take ∏=3.142) Example Input : radius= 5 Output: Area of circle is : 78.55 Input : radius= 8 Output: Area of circle is : 201.08 As we know to calculate the area of a circle, the radius of the circle must be known, so if the radius of the circle is known, then the area of the circle can be calculated by using the formula: Area = 3.142*(radius)*(radius) Below is the Java Program to calculate the area of the circle:- Java // Java program to calculate the area of thepublic class GFG { public static void main(String[] args) { int radius; double pi = 3.142, area; radius = 5; // calculating the area of the circle area = pi * radius * radius; // printing the area of the circle System.out.println("Area of circle is :" + area); }} Area of circle is :78.55 circle Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Iterate through List in Java
[ { "code": null, "e": 25251, "s": 25223, "text": "\n28 Mar, 2021" }, { "code": null, "e": 25366, "s": 25251, "text": "Given a radius of the circle, write a java program to calculate and display the area of the circle. (Take ∏=3.142)" }, { "code": null, "e": 25374, "s": 25366, "text": "Example" }, { "code": null, "e": 25480, "s": 25374, "text": "Input : radius= 5\nOutput: Area of circle is : 78.55\n\nInput : radius= 8\nOutput: Area of circle is : 201.08" }, { "code": null, "e": 25675, "s": 25480, "text": "As we know to calculate the area of a circle, the radius of the circle must be known, so if the radius of the circle is known, then the area of the circle can be calculated by using the formula:" }, { "code": null, "e": 25706, "s": 25675, "text": "Area = 3.142*(radius)*(radius)" }, { "code": null, "e": 25771, "s": 25706, "text": "Below is the Java Program to calculate the area of the circle:- " }, { "code": null, "e": 25776, "s": 25771, "text": "Java" }, { "code": "// Java program to calculate the area of thepublic class GFG { public static void main(String[] args) { int radius; double pi = 3.142, area; radius = 5; // calculating the area of the circle area = pi * radius * radius; // printing the area of the circle System.out.println(\"Area of circle is :\" + area); }}", "e": 26142, "s": 25776, "text": null }, { "code": null, "e": 26168, "s": 26142, "text": "Area of circle is :78.55\n" }, { "code": null, "e": 26175, "s": 26168, "text": "circle" }, { "code": null, "e": 26182, "s": 26175, "text": "Picked" }, { "code": null, "e": 26187, "s": 26182, "text": "Java" }, { "code": null, "e": 26201, "s": 26187, "text": "Java Programs" }, { "code": null, "e": 26206, "s": 26201, "text": "Java" }, { "code": null, "e": 26304, "s": 26206, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26319, "s": 26304, "text": "Stream In Java" }, { "code": null, "e": 26340, "s": 26319, "text": "Constructors in Java" }, { "code": null, "e": 26359, "s": 26340, "text": "Exceptions in Java" }, { "code": null, "e": 26389, "s": 26359, "text": "Functional Interfaces in Java" }, { "code": null, "e": 26435, "s": 26389, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 26461, "s": 26435, "text": "Java Programming Examples" }, { "code": null, "e": 26495, "s": 26461, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 26542, "s": 26495, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 26574, "s": 26542, "text": "How to Iterate HashMap in Java?" } ]
Count of pairs (x, y) in an array such that x < y - GeeksforGeeks
01 Jun, 2021 Given an array of N distinct integers, the task is to find the number of pairs (x, y) such that x < y. Example: Input: arr[] = {2, 4, 3, 1} Output: 6 Possible pairs are (1, 2), (1, 3), (1, 4), (2, 3), (2, 4) and (3, 4).Input: arr[] = {5, 10} Output: 1 The only possible pair is (5, 10). Naive approach: Find every possible pair and check whether it satisfies the given condition or not. C++ Java Python 3 C# PHP Javascript // C++ implementation of the approach#include <iostream>using namespace std; // Function to return the number of// pairs (x, y) such that x < yint getPairs(int a[],int n){ // To store the number of valid pairs int count = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // If a valid pair is found if (a[i] < a[j]) count++; } } // Return the count of valid pairs return count;} // Driver codeint main(){ int a[] = { 2, 4, 3, 1 }; int n = sizeof(a) / sizeof(a[0]); cout << getPairs(a, n); return 0;} // This code is contributed by SHUBHAMSINGH10 // Java implementation of the approachclass GFG { // Function to return the number of // pairs (x, y) such that x < y static int getPairs(int a[]) { // To store the number of valid pairs int count = 0; for (int i = 0; i < a.length; i++) { for (int j = 0; j < a.length; j++) { // If a valid pair is found if (a[i] < a[j]) count++; } } // Return the count of valid pairs return count; } // Driver code public static void main(String[] args) { int a[] = { 2, 4, 3, 1 }; System.out.println(getPairs(a)); }} # Python3 implementation of the approach # Function to return the number of# pairs (x, y) such that x < ydef getPairs(a): # To store the number of valid pairs count = 0 for i in range(len(a)): for j in range(len(a)): # If a valid pair is found if (a[i] < a[j]): count += 1 # Return the count of valid pairs return count # Driver codeif __name__ == "__main__": a = [ 2, 4, 3, 1 ] print(getPairs(a)) # This code is contributed by ita_c // C# implementation of the approachusing System; class GFG{ // Function to return the number of // pairs (x, y) such that x < y static int getPairs(int []a) { // To store the number of valid pairs int count = 0; for (int i = 0; i < a.Length; i++) { for (int j = 0; j < a.Length; j++) { // If a valid pair is found if (a[i] < a[j]) count++; } } // Return the count of valid pairs return count; } // Driver code public static void Main() { int []a = { 2, 4, 3, 1 }; Console.WriteLine(getPairs(a)); }} // This code is contributed by Ryuga <?php// PHP implementation of the approach // Function to return the number of// pairs (x, y) such that x < yfunction getPairs($a){ // To store the number of valid pairs $count = 0; for ($i = 0; $i < sizeof($a); $i++) { for ($j = 0; $j < sizeof($a); $j++) { // If a valid pair is found if ($a[$i] < $a[$j]) $count++; } } // Return the count of valid pairs return $count;} // Driver code$a = array(2, 4, 3, 1);echo getPairs($a); // This code is contributed// by Akanksha Rai?> <script>// Javascript implementation of the approach // Function to return the number of // pairs (x, y) such that x < y function getPairs(a) { // To store the number of valid pairs let count = 0; for (let i = 0; i < a.length; i++) { for (let j = 0; j < a.length; j++) { // If a valid pair is found if (a[i] < a[j]) count++; } } // Return the count of valid pairs return count; } // Driver code let a=[ 2, 4, 3, 1 ]; document.write(getPairs(a)); // This code is contributed by rag2127</script> 6 Time Complexity: O(n2) Efficient approach: For an element x. In order to find the count of valid pairs of the form (x, y1), (x, y2), ..., (x, yn), we need to count the elements which are greater than x. For the smallest element, there will be n – 1 element greater than it. Similarly, the second smallest element can form n – 2 pairs and so on. Therefore, the desired count of valid pairs will be (n – 1) + (n – 2) + .... + 1 = n * (n – 1) / 2 where n is the length of the array. Below is the implementation of the above approach: C++ Java Python C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the number of// pairs (x, y) such that x < yint getPairs(int a[]){ // Length of the array int n = sizeof(a[0]); // Calculate the number valid pairs int count = (n * (n - 1)) / 2; // Return the count of valid pairs return count;} // Driver codeint main(){ int a[] = { 2, 4, 3, 1 }; cout << getPairs(a); return 0;} // This code is contributed// by SHUBHAMSINGH10 // Java implementation of the approachclass GFG { // Function to return the number of // pairs (x, y) such that x < y static int getPairs(int a[]) { // Length of the array int n = a.length; // Calculate the number of valid pairs int count = (n * (n - 1)) / 2; // Return the count of valid pairs return count; } // Driver code public static void main(String[] args) { int a[] = { 2, 4, 3, 1 }; System.out.println(getPairs(a)); }} # Python implementation of the approach # Function to return the number of# pairs (x, y) such that x < ydef getPairs(a): # Length of the array n = len(a) # Calculate the number of valid pairs count = (n * (n - 1)) // 2 # Return the count of valid pairs return count # Driver codea = [2, 4, 3, 1]print(getPairs(a)) # This code is contributed by SHUBHAMSINGH10 // C# implementation of the approachusing System;class GFG{ // Function to return the number of // pairs (x, y) such that x < y static int getPairs(int []a) { // Length of the array int n = a.Length; // Calculate the number of valid pairs int count = (n * (n - 1)) / 2; // Return the count of valid pairs return count; } // Driver code public static void Main() { int []a = { 2, 4, 3, 1 }; Console.Write(getPairs(a)); }} // This code is contributed// by Akanksha Rai <script> // JavaScript implementation of the approach // Function to return the number of // pairs (x, y) such that x < y function getPairs(a) { // Length of the array let n = a.length; // Calculate the number of valid pairs let count = parseInt((n * (n - 1)) / 2, 10); // Return the count of valid pairs return count; } let a = [ 2, 4, 3, 1 ]; document.write(getPairs(a)); </script> 6 Time Complexity: O(1) ankthon ukasp Akanksha_Rai SHUBHAMSINGH10 rag2127 mukesh07 Arrays Mathematical Arrays 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 Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26041, "s": 26013, "text": "\n01 Jun, 2021" }, { "code": null, "e": 26144, "s": 26041, "text": "Given an array of N distinct integers, the task is to find the number of pairs (x, y) such that x < y." }, { "code": null, "e": 26155, "s": 26144, "text": "Example: " }, { "code": null, "e": 26331, "s": 26155, "text": "Input: arr[] = {2, 4, 3, 1} Output: 6 Possible pairs are (1, 2), (1, 3), (1, 4), (2, 3), (2, 4) and (3, 4).Input: arr[] = {5, 10} Output: 1 The only possible pair is (5, 10). " }, { "code": null, "e": 26432, "s": 26331, "text": "Naive approach: Find every possible pair and check whether it satisfies the given condition or not. " }, { "code": null, "e": 26436, "s": 26432, "text": "C++" }, { "code": null, "e": 26441, "s": 26436, "text": "Java" }, { "code": null, "e": 26450, "s": 26441, "text": "Python 3" }, { "code": null, "e": 26453, "s": 26450, "text": "C#" }, { "code": null, "e": 26457, "s": 26453, "text": "PHP" }, { "code": null, "e": 26468, "s": 26457, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <iostream>using namespace std; // Function to return the number of// pairs (x, y) such that x < yint getPairs(int a[],int n){ // To store the number of valid pairs int count = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // If a valid pair is found if (a[i] < a[j]) count++; } } // Return the count of valid pairs return count;} // Driver codeint main(){ int a[] = { 2, 4, 3, 1 }; int n = sizeof(a) / sizeof(a[0]); cout << getPairs(a, n); return 0;} // This code is contributed by SHUBHAMSINGH10", "e": 27125, "s": 26468, "text": null }, { "code": "// Java implementation of the approachclass GFG { // Function to return the number of // pairs (x, y) such that x < y static int getPairs(int a[]) { // To store the number of valid pairs int count = 0; for (int i = 0; i < a.length; i++) { for (int j = 0; j < a.length; j++) { // If a valid pair is found if (a[i] < a[j]) count++; } } // Return the count of valid pairs return count; } // Driver code public static void main(String[] args) { int a[] = { 2, 4, 3, 1 }; System.out.println(getPairs(a)); }}", "e": 27786, "s": 27125, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the number of# pairs (x, y) such that x < ydef getPairs(a): # To store the number of valid pairs count = 0 for i in range(len(a)): for j in range(len(a)): # If a valid pair is found if (a[i] < a[j]): count += 1 # Return the count of valid pairs return count # Driver codeif __name__ == \"__main__\": a = [ 2, 4, 3, 1 ] print(getPairs(a)) # This code is contributed by ita_c", "e": 28293, "s": 27786, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the number of // pairs (x, y) such that x < y static int getPairs(int []a) { // To store the number of valid pairs int count = 0; for (int i = 0; i < a.Length; i++) { for (int j = 0; j < a.Length; j++) { // If a valid pair is found if (a[i] < a[j]) count++; } } // Return the count of valid pairs return count; } // Driver code public static void Main() { int []a = { 2, 4, 3, 1 }; Console.WriteLine(getPairs(a)); }} // This code is contributed by Ryuga", "e": 29006, "s": 28293, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to return the number of// pairs (x, y) such that x < yfunction getPairs($a){ // To store the number of valid pairs $count = 0; for ($i = 0; $i < sizeof($a); $i++) { for ($j = 0; $j < sizeof($a); $j++) { // If a valid pair is found if ($a[$i] < $a[$j]) $count++; } } // Return the count of valid pairs return $count;} // Driver code$a = array(2, 4, 3, 1);echo getPairs($a); // This code is contributed// by Akanksha Rai?>", "e": 29563, "s": 29006, "text": null }, { "code": "<script>// Javascript implementation of the approach // Function to return the number of // pairs (x, y) such that x < y function getPairs(a) { // To store the number of valid pairs let count = 0; for (let i = 0; i < a.length; i++) { for (let j = 0; j < a.length; j++) { // If a valid pair is found if (a[i] < a[j]) count++; } } // Return the count of valid pairs return count; } // Driver code let a=[ 2, 4, 3, 1 ]; document.write(getPairs(a)); // This code is contributed by rag2127</script>", "e": 30218, "s": 29563, "text": null }, { "code": null, "e": 30220, "s": 30218, "text": "6" }, { "code": null, "e": 30245, "s": 30222, "text": "Time Complexity: O(n2)" }, { "code": null, "e": 30703, "s": 30245, "text": "Efficient approach: For an element x. In order to find the count of valid pairs of the form (x, y1), (x, y2), ..., (x, yn), we need to count the elements which are greater than x. For the smallest element, there will be n – 1 element greater than it. Similarly, the second smallest element can form n – 2 pairs and so on. Therefore, the desired count of valid pairs will be (n – 1) + (n – 2) + .... + 1 = n * (n – 1) / 2 where n is the length of the array. " }, { "code": null, "e": 30755, "s": 30703, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 30759, "s": 30755, "text": "C++" }, { "code": null, "e": 30764, "s": 30759, "text": "Java" }, { "code": null, "e": 30771, "s": 30764, "text": "Python" }, { "code": null, "e": 30774, "s": 30771, "text": "C#" }, { "code": null, "e": 30785, "s": 30774, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the number of// pairs (x, y) such that x < yint getPairs(int a[]){ // Length of the array int n = sizeof(a[0]); // Calculate the number valid pairs int count = (n * (n - 1)) / 2; // Return the count of valid pairs return count;} // Driver codeint main(){ int a[] = { 2, 4, 3, 1 }; cout << getPairs(a); return 0;} // This code is contributed// by SHUBHAMSINGH10", "e": 31283, "s": 30785, "text": null }, { "code": "// Java implementation of the approachclass GFG { // Function to return the number of // pairs (x, y) such that x < y static int getPairs(int a[]) { // Length of the array int n = a.length; // Calculate the number of valid pairs int count = (n * (n - 1)) / 2; // Return the count of valid pairs return count; } // Driver code public static void main(String[] args) { int a[] = { 2, 4, 3, 1 }; System.out.println(getPairs(a)); }}", "e": 31799, "s": 31283, "text": null }, { "code": "# Python implementation of the approach # Function to return the number of# pairs (x, y) such that x < ydef getPairs(a): # Length of the array n = len(a) # Calculate the number of valid pairs count = (n * (n - 1)) // 2 # Return the count of valid pairs return count # Driver codea = [2, 4, 3, 1]print(getPairs(a)) # This code is contributed by SHUBHAMSINGH10", "e": 32195, "s": 31799, "text": null }, { "code": "// C# implementation of the approachusing System;class GFG{ // Function to return the number of // pairs (x, y) such that x < y static int getPairs(int []a) { // Length of the array int n = a.Length; // Calculate the number of valid pairs int count = (n * (n - 1)) / 2; // Return the count of valid pairs return count; } // Driver code public static void Main() { int []a = { 2, 4, 3, 1 }; Console.Write(getPairs(a)); }} // This code is contributed// by Akanksha Rai", "e": 32749, "s": 32195, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Function to return the number of // pairs (x, y) such that x < y function getPairs(a) { // Length of the array let n = a.length; // Calculate the number of valid pairs let count = parseInt((n * (n - 1)) / 2, 10); // Return the count of valid pairs return count; } let a = [ 2, 4, 3, 1 ]; document.write(getPairs(a)); </script>", "e": 33220, "s": 32749, "text": null }, { "code": null, "e": 33222, "s": 33220, "text": "6" }, { "code": null, "e": 33247, "s": 33224, "text": "Time Complexity: O(1) " }, { "code": null, "e": 33255, "s": 33247, "text": "ankthon" }, { "code": null, "e": 33261, "s": 33255, "text": "ukasp" }, { "code": null, "e": 33274, "s": 33261, "text": "Akanksha_Rai" }, { "code": null, "e": 33289, "s": 33274, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 33297, "s": 33289, "text": "rag2127" }, { "code": null, "e": 33306, "s": 33297, "text": "mukesh07" }, { "code": null, "e": 33313, "s": 33306, "text": "Arrays" }, { "code": null, "e": 33326, "s": 33313, "text": "Mathematical" }, { "code": null, "e": 33333, "s": 33326, "text": "Arrays" }, { "code": null, "e": 33346, "s": 33333, "text": "Mathematical" }, { "code": null, "e": 33444, "s": 33346, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33471, "s": 33444, "text": "Count pairs with given sum" }, { "code": null, "e": 33502, "s": 33471, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 33527, "s": 33502, "text": "Window Sliding Technique" }, { "code": null, "e": 33565, "s": 33527, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 33586, "s": 33565, "text": "Next Greater Element" }, { "code": null, "e": 33616, "s": 33586, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 33676, "s": 33616, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 33691, "s": 33676, "text": "C++ Data Types" }, { "code": null, "e": 33734, "s": 33691, "text": "Set in C++ Standard Template Library (STL)" } ]
How to compare two ValueTuple in C#? - GeeksforGeeks
23 Jul, 2019 To compare two instances of ValueTuple you can use CompareTo method which is provided by ValueTuple structure. ValueTuple.CompareTo(ValueTuple) Method is used to compare the current instance of ValueTuple with another ValueTuple instance. It always returns zero if they are equal to each other. Syntax: public int CompareTo (ValueTuple other); Here, other is the object to compare with the current instance. Returns: The method always returns 0 of type System.Int32. Exception: This method will throw an ArgumentException if the other is not ValueTuple instance. Example 1: // C# program to illustrate the // concept of CompareTo methodusing System; class GFG { // Main method static public void Main() { // Creating value tuples with two elements var MyTple1 = ValueTuple.Create(56, 45); var MyTple2 = ValueTuple.Create(56, 3); var MyTple3 = ValueTuple.Create(56, 45); var MyTple4 = ValueTuple.Create(5345, 45); // Using CompareTo method int res1 = MyTple1.CompareTo(MyTple2); int res2 = MyTple1.CompareTo(MyTple3); int res3 = MyTple1.CompareTo(MyTple4); // Display result Console.WriteLine("Result 1: " + res1); Console.WriteLine("Result 2: " + res2); Console.WriteLine("Result 3: " + res3); }} Result 1: 1 Result 2: 0 Result 3: -1 Example 2: // C# program to illustrate the// use of CompareTo methodusing System; class GFG { // Main Method static public void Main() { // Creating value tuples with one element var MyVTple1 = ValueTuple.Create(2018); var MyVTple2 = ValueTuple.Create(2018); // Compare both value tuples // Using CompareTo method if (MyVTple1.CompareTo(MyVTple2) == 0) { Console.WriteLine("Welcome to GeeksforGeeks"); } else { Console.WriteLine("Page Not Found"); } }} Welcome to GeeksforGeeks Reference: https://docs.microsoft.com/en-us/dotnet/api/system.valuetuple.compareto?view=netframework-4.8 CSharp-ValueTuple CSharp-ValueTuple-Methods C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# C# | Data Types HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? Switch Statement in C# Linked List Implementation in C#
[ { "code": null, "e": 25649, "s": 25621, "text": "\n23 Jul, 2019" }, { "code": null, "e": 25944, "s": 25649, "text": "To compare two instances of ValueTuple you can use CompareTo method which is provided by ValueTuple structure. ValueTuple.CompareTo(ValueTuple) Method is used to compare the current instance of ValueTuple with another ValueTuple instance. It always returns zero if they are equal to each other." }, { "code": null, "e": 25952, "s": 25944, "text": "Syntax:" }, { "code": null, "e": 25993, "s": 25952, "text": "public int CompareTo (ValueTuple other);" }, { "code": null, "e": 26057, "s": 25993, "text": "Here, other is the object to compare with the current instance." }, { "code": null, "e": 26116, "s": 26057, "text": "Returns: The method always returns 0 of type System.Int32." }, { "code": null, "e": 26212, "s": 26116, "text": "Exception: This method will throw an ArgumentException if the other is not ValueTuple instance." }, { "code": null, "e": 26223, "s": 26212, "text": "Example 1:" }, { "code": "// C# program to illustrate the // concept of CompareTo methodusing System; class GFG { // Main method static public void Main() { // Creating value tuples with two elements var MyTple1 = ValueTuple.Create(56, 45); var MyTple2 = ValueTuple.Create(56, 3); var MyTple3 = ValueTuple.Create(56, 45); var MyTple4 = ValueTuple.Create(5345, 45); // Using CompareTo method int res1 = MyTple1.CompareTo(MyTple2); int res2 = MyTple1.CompareTo(MyTple3); int res3 = MyTple1.CompareTo(MyTple4); // Display result Console.WriteLine(\"Result 1: \" + res1); Console.WriteLine(\"Result 2: \" + res2); Console.WriteLine(\"Result 3: \" + res3); }}", "e": 26958, "s": 26223, "text": null }, { "code": null, "e": 26996, "s": 26958, "text": "Result 1: 1\nResult 2: 0\nResult 3: -1\n" }, { "code": null, "e": 27007, "s": 26996, "text": "Example 2:" }, { "code": "// C# program to illustrate the// use of CompareTo methodusing System; class GFG { // Main Method static public void Main() { // Creating value tuples with one element var MyVTple1 = ValueTuple.Create(2018); var MyVTple2 = ValueTuple.Create(2018); // Compare both value tuples // Using CompareTo method if (MyVTple1.CompareTo(MyVTple2) == 0) { Console.WriteLine(\"Welcome to GeeksforGeeks\"); } else { Console.WriteLine(\"Page Not Found\"); } }}", "e": 27571, "s": 27007, "text": null }, { "code": null, "e": 27597, "s": 27571, "text": "Welcome to GeeksforGeeks\n" }, { "code": null, "e": 27608, "s": 27597, "text": "Reference:" }, { "code": null, "e": 27702, "s": 27608, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.valuetuple.compareto?view=netframework-4.8" }, { "code": null, "e": 27720, "s": 27702, "text": "CSharp-ValueTuple" }, { "code": null, "e": 27746, "s": 27720, "text": "CSharp-ValueTuple-Methods" }, { "code": null, "e": 27749, "s": 27746, "text": "C#" }, { "code": null, "e": 27847, "s": 27749, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27870, "s": 27847, "text": "Extension Method in C#" }, { "code": null, "e": 27886, "s": 27870, "text": "C# | Data Types" }, { "code": null, "e": 27914, "s": 27886, "text": "HashSet in C# with Examples" }, { "code": null, "e": 27931, "s": 27914, "text": "C# | Inheritance" }, { "code": null, "e": 27953, "s": 27931, "text": "Partial Classes in C#" }, { "code": null, "e": 27982, "s": 27953, "text": "C# | Generics - Introduction" }, { "code": null, "e": 28022, "s": 27982, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 28065, "s": 28022, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 28088, "s": 28065, "text": "Switch Statement in C#" } ]
Node.js date-and-time Date.locale() Method - GeeksforGeeks
26 Mar, 2021 The date-and-time.Date.locale() method is used to get or switch the locale from one into another language. Required Module: Install the module by npm or used it locally. By using npm: npm install date-and-time --save By using CDN link: <script src="/path/to/date-and-time.min.js"></script> Syntax: locale(]) Parameters: This method takes the locale and code as a parameter. Return Value: This method returns the current locale of the date and time object. Example 1: index.js // Node.js program to demonstrate the // Date.locale() APi // Importing date-and-time moduleconst date = require('date-and-time') // Getting the locale valueconst value = date.locale(); // display the resultconsole.log("current locale :- " + value) Run index.js file using below command: node index.js Output: current locale :- en Example 2: Changing locale Filename: index.js index.js // Node.js program to demonstrate the // Date.locale() APi // Importing date-and-time moduleconst date = require('date-and-time') // Changing the local to es spanishconsole.log("Change local "+date.locale('es')) Run index.js file using below command: node index.js Output: Change local es Reference: https://github.com/knowledgecode/date-and-time#localecode-locale Node.js-Methods NodeJS date-time Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between dependencies, devDependencies and peerDependencies How to connect Node.js with React.js ? Node.js Export Module Mongoose find() Function Mongoose Populate() Method Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26267, "s": 26239, "text": "\n26 Mar, 2021" }, { "code": null, "e": 26374, "s": 26267, "text": "The date-and-time.Date.locale() method is used to get or switch the locale from one into another language." }, { "code": null, "e": 26437, "s": 26374, "text": "Required Module: Install the module by npm or used it locally." }, { "code": null, "e": 26451, "s": 26437, "text": "By using npm:" }, { "code": null, "e": 26484, "s": 26451, "text": "npm install date-and-time --save" }, { "code": null, "e": 26503, "s": 26484, "text": "By using CDN link:" }, { "code": null, "e": 26557, "s": 26503, "text": "<script src=\"/path/to/date-and-time.min.js\"></script>" }, { "code": null, "e": 26565, "s": 26557, "text": "Syntax:" }, { "code": null, "e": 26575, "s": 26565, "text": "locale(])" }, { "code": null, "e": 26641, "s": 26575, "text": "Parameters: This method takes the locale and code as a parameter." }, { "code": null, "e": 26723, "s": 26641, "text": "Return Value: This method returns the current locale of the date and time object." }, { "code": null, "e": 26734, "s": 26723, "text": "Example 1:" }, { "code": null, "e": 26743, "s": 26734, "text": "index.js" }, { "code": "// Node.js program to demonstrate the // Date.locale() APi // Importing date-and-time moduleconst date = require('date-and-time') // Getting the locale valueconst value = date.locale(); // display the resultconsole.log(\"current locale :- \" + value)", "e": 26996, "s": 26743, "text": null }, { "code": null, "e": 27035, "s": 26996, "text": "Run index.js file using below command:" }, { "code": null, "e": 27049, "s": 27035, "text": "node index.js" }, { "code": null, "e": 27057, "s": 27049, "text": "Output:" }, { "code": null, "e": 27078, "s": 27057, "text": "current locale :- en" }, { "code": null, "e": 27106, "s": 27078, "text": "Example 2: Changing locale " }, { "code": null, "e": 27126, "s": 27106, "text": "Filename: index.js " }, { "code": null, "e": 27135, "s": 27126, "text": "index.js" }, { "code": "// Node.js program to demonstrate the // Date.locale() APi // Importing date-and-time moduleconst date = require('date-and-time') // Changing the local to es spanishconsole.log(\"Change local \"+date.locale('es'))", "e": 27350, "s": 27135, "text": null }, { "code": null, "e": 27389, "s": 27350, "text": "Run index.js file using below command:" }, { "code": null, "e": 27403, "s": 27389, "text": "node index.js" }, { "code": null, "e": 27411, "s": 27403, "text": "Output:" }, { "code": null, "e": 27427, "s": 27411, "text": "Change local es" }, { "code": null, "e": 27503, "s": 27427, "text": "Reference: https://github.com/knowledgecode/date-and-time#localecode-locale" }, { "code": null, "e": 27519, "s": 27503, "text": "Node.js-Methods" }, { "code": null, "e": 27536, "s": 27519, "text": "NodeJS date-time" }, { "code": null, "e": 27544, "s": 27536, "text": "Node.js" }, { "code": null, "e": 27561, "s": 27544, "text": "Web Technologies" }, { "code": null, "e": 27659, "s": 27561, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27729, "s": 27659, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 27768, "s": 27729, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 27790, "s": 27768, "text": "Node.js Export Module" }, { "code": null, "e": 27815, "s": 27790, "text": "Mongoose find() Function" }, { "code": null, "e": 27842, "s": 27815, "text": "Mongoose Populate() Method" }, { "code": null, "e": 27882, "s": 27842, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27927, "s": 27882, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27970, "s": 27927, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28020, "s": 27970, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Java Program to Combine Two List by Alternatively Taking Elements - GeeksforGeeks
22 Sep, 2021 A list is an ordered sequence of elements stored together to form a collection. A list can contain duplicate as well as null entries. A list allows us to perform index-based operations, that is additions, deletions, manipulations, and positional access. Java provides an in-built interface <<java.util>> to perform list as well as other class-based functions. Cases: There can occur two different scenarios while doing so as per the length of lists If list 2 gets exhausted while adding elements alternatively then the remaining elements of list 1 are the second list is remaining elements of list 1 to be added in the same sequence of occurrence.If list 1 gets exhausted and so on as discussed in the above case vice-versa If list 2 gets exhausted while adding elements alternatively then the remaining elements of list 1 are the second list is remaining elements of list 1 to be added in the same sequence of occurrence. If list 1 gets exhausted and so on as discussed in the above case vice-versa So, the Aim is to completely remove the elements from second one and add to first one list and whatever is left will be the second list. Approach: The following approach is adopted to store elements alternatively in a merged list. Two lists are declared and initialized with a set of elements. Two counters, i and j are maintained to iterate over the length of the lists. The loop runs until the shorter length of both the lists. An empty list is maintained to store the merged contents of both the lists, in order of list1 followed by list2. At the end of the loop, one of the list, that is a shorter one is exhausted. A loop is then used to iterate over the remaining elements of the longer list and store them at the end one by one. The data type of the merged list should be similar to the individual lists. Implementation: Two examples are discussed below considering both integer list and string lists Example 1: String Lists Java // Java Program to Combine Two List// by Alternatingly Taking Elements // importing required packagesimport java.io.*;import java.util.*;import java.util.Iterator; // Class to access alterate elementsclass GFG { // Main driver method public static void main(String[] args) { // Creating(declaring) list1 List<String> list1 = new ArrayList<String>(); // Adding elements to list1 // Custom inputs list1.add("Geeks"); list1.add("Geeks"); list1.add("portal"); // Creating(declaring) list2 List<String> list2 = new ArrayList<String>(); // Adding elements to list2 // Custom inputs list2.add("for"); list2.add("is CSE"); list2.add("portal"); // Display message System.out.print("List1 contents: "); // Iterating over List1 Iterator iterator = list1.iterator(); // Condition check using hasNext() which holds true // till there is single element remaining in the // List while (iterator.hasNext()) { // Printing elements of List 1 System.out.print(iterator.next() + " "); } // Next Line System.out.println(); // Display message System.out.print("List2 contents: "); // Iterating over List 2 iterator = list2.iterator(); // Condition check using hasNext() which holds true // till there is single element remaining in the // List while (iterator.hasNext()) { // Printing elements of List 2 System.out.print(iterator.next() + " "); } // Declaring counters int i = 0; int j = 0; // Creating(declaring) merged List List<String> merged_list = new ArrayList<String>(); // Iterating over both the lists until // the elements of shorter List are exhausted while (i < list1.size() && j < list2.size()) { // Step 1: Adding List1 element merged_list.add(list1.get(i)); // Step 2: Adding List2 element merged_list.add(list2.get(j)); // Incrementing counters i++; j++; } // Iterating over the remaining part of List1 while (i < list1.size()) { merged_list.add(list1.get(i)); // Incrementing List1 counter i++; } // Iterating over the remaining part of List2 while (j < list2.size()) { merged_list.add(list2.get(j)); // Incrementing List1 counter j++; } // Next line System.out.println(); // Display message System.out.print("Merged List contents: "); // Iterators iterator = merged_list.iterator(); // Iterating over merged List using hasNext() method // which holds true till there is single element // remaining while (iterator.hasNext()) { // Printing merged list contents System.out.print(iterator.next() + " "); } }} List1 contents: Geeks Geeks portal List2 contents: for is CSE portal Merged List contents: Geeks for Geeks is CSE portal portal Example 2: Integer Lists Java // Java Program to Combine Two List// by Alternatingly Taking Elements // importing required packagesimport java.io.*;import java.util.*;import java.util.Iterator; // Classclass GFG { // Main driver method public static void main(String[] args) { // Creating(declaring) List1 List<Integer> list1 = new ArrayList<Integer>(); // Adding elements to List1 // Custom inputs list1.add(2); list1.add(4); list1.add(6); // Creating(declaring) List2 List<Integer> list2 = new ArrayList<Integer>(); // Adding elements to List2 // Custom inputs list2.add(1); list2.add(3); list2.add(5); list2.add(7); // Display message System.out.print("List1 contents: "); // Iterating over List1 Iterator iterator = list1.iterator(); // ConditionCheck using hasNext() method which hold // true till single element in remaining List while (iterator.hasNext()) { // Printing List1 contents System.out.print(iterator.next() + " "); } // New line System.out.println(); // Display message System.out.print("List2 contents: "); iterator = list2.iterator(); // ConditionCheck using hasNext() method which hold // true till single element in remaining List while (iterator.hasNext()) { // Printing List2 contents System.out.print(iterator.next() + " "); } // Setting counters to zeros int i = 0; int j = 0; // Creating(declaring) merged list List<Integer> merged_list = new ArrayList<Integer>(); // Iterating over both the lists // until the shorter list while (i < list1.size() && j < list2.size()) { // Step 1: Adding List2 element merged_list.add(list2.get(j)); // Step 2: Adding List1 element merged_list.add(list1.get(i)); // Incrementing counters i++; j++; } // Iterating over the remaining part of List1 // Case 1: Input: ShorterList following BiggerList while (i < list1.size()) { // Merge remaining List to List1, and // making List2 final as NULL List merged_list.add(list1.get(i)); i++; } // Case 2: Input: BiggerList following ShorterList while (j < list2.size()) { // Merge remaining List to List1,an d // making List2 -> NULL List merged_list.add(list2.get(j)); j++; } // New line System.out.println(); // Display message System.out.print("Merged List contents: "); // Iterating over merged list iterator = merged_list.iterator(); // Condition check using hasNext() method which // holds true till there is single element remaining // in the List while (iterator.hasNext()) { // Printing merged List contents i.e // FinalList = List1 + List2(Null final List) System.out.print(iterator.next() + " "); } }} List1 contents: 2 4 6 List2 contents: 1 3 5 7 Merged List contents: 1 2 3 4 5 6 7 surindertarika1234 simmytarika5 surinderdawra388 Java-Collections java-list Picked Java Java Programs Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Program to print ASCII Value of a character
[ { "code": null, "e": 25225, "s": 25197, "text": "\n22 Sep, 2021" }, { "code": null, "e": 25586, "s": 25225, "text": "A list is an ordered sequence of elements stored together to form a collection. A list can contain duplicate as well as null entries. A list allows us to perform index-based operations, that is additions, deletions, manipulations, and positional access. Java provides an in-built interface <<java.util>> to perform list as well as other class-based functions. " }, { "code": null, "e": 25675, "s": 25586, "text": "Cases: There can occur two different scenarios while doing so as per the length of lists" }, { "code": null, "e": 25950, "s": 25675, "text": "If list 2 gets exhausted while adding elements alternatively then the remaining elements of list 1 are the second list is remaining elements of list 1 to be added in the same sequence of occurrence.If list 1 gets exhausted and so on as discussed in the above case vice-versa" }, { "code": null, "e": 26149, "s": 25950, "text": "If list 2 gets exhausted while adding elements alternatively then the remaining elements of list 1 are the second list is remaining elements of list 1 to be added in the same sequence of occurrence." }, { "code": null, "e": 26226, "s": 26149, "text": "If list 1 gets exhausted and so on as discussed in the above case vice-versa" }, { "code": null, "e": 26363, "s": 26226, "text": "So, the Aim is to completely remove the elements from second one and add to first one list and whatever is left will be the second list." }, { "code": null, "e": 26458, "s": 26363, "text": "Approach: The following approach is adopted to store elements alternatively in a merged list. " }, { "code": null, "e": 26521, "s": 26458, "text": "Two lists are declared and initialized with a set of elements." }, { "code": null, "e": 26657, "s": 26521, "text": "Two counters, i and j are maintained to iterate over the length of the lists. The loop runs until the shorter length of both the lists." }, { "code": null, "e": 26770, "s": 26657, "text": "An empty list is maintained to store the merged contents of both the lists, in order of list1 followed by list2." }, { "code": null, "e": 26963, "s": 26770, "text": "At the end of the loop, one of the list, that is a shorter one is exhausted. A loop is then used to iterate over the remaining elements of the longer list and store them at the end one by one." }, { "code": null, "e": 27039, "s": 26963, "text": "The data type of the merged list should be similar to the individual lists." }, { "code": null, "e": 27135, "s": 27039, "text": "Implementation: Two examples are discussed below considering both integer list and string lists" }, { "code": null, "e": 27159, "s": 27135, "text": "Example 1: String Lists" }, { "code": null, "e": 27164, "s": 27159, "text": "Java" }, { "code": "// Java Program to Combine Two List// by Alternatingly Taking Elements // importing required packagesimport java.io.*;import java.util.*;import java.util.Iterator; // Class to access alterate elementsclass GFG { // Main driver method public static void main(String[] args) { // Creating(declaring) list1 List<String> list1 = new ArrayList<String>(); // Adding elements to list1 // Custom inputs list1.add(\"Geeks\"); list1.add(\"Geeks\"); list1.add(\"portal\"); // Creating(declaring) list2 List<String> list2 = new ArrayList<String>(); // Adding elements to list2 // Custom inputs list2.add(\"for\"); list2.add(\"is CSE\"); list2.add(\"portal\"); // Display message System.out.print(\"List1 contents: \"); // Iterating over List1 Iterator iterator = list1.iterator(); // Condition check using hasNext() which holds true // till there is single element remaining in the // List while (iterator.hasNext()) { // Printing elements of List 1 System.out.print(iterator.next() + \" \"); } // Next Line System.out.println(); // Display message System.out.print(\"List2 contents: \"); // Iterating over List 2 iterator = list2.iterator(); // Condition check using hasNext() which holds true // till there is single element remaining in the // List while (iterator.hasNext()) { // Printing elements of List 2 System.out.print(iterator.next() + \" \"); } // Declaring counters int i = 0; int j = 0; // Creating(declaring) merged List List<String> merged_list = new ArrayList<String>(); // Iterating over both the lists until // the elements of shorter List are exhausted while (i < list1.size() && j < list2.size()) { // Step 1: Adding List1 element merged_list.add(list1.get(i)); // Step 2: Adding List2 element merged_list.add(list2.get(j)); // Incrementing counters i++; j++; } // Iterating over the remaining part of List1 while (i < list1.size()) { merged_list.add(list1.get(i)); // Incrementing List1 counter i++; } // Iterating over the remaining part of List2 while (j < list2.size()) { merged_list.add(list2.get(j)); // Incrementing List1 counter j++; } // Next line System.out.println(); // Display message System.out.print(\"Merged List contents: \"); // Iterators iterator = merged_list.iterator(); // Iterating over merged List using hasNext() method // which holds true till there is single element // remaining while (iterator.hasNext()) { // Printing merged list contents System.out.print(iterator.next() + \" \"); } }}", "e": 30235, "s": 27164, "text": null }, { "code": null, "e": 30366, "s": 30235, "text": "List1 contents: Geeks Geeks portal \nList2 contents: for is CSE portal \nMerged List contents: Geeks for Geeks is CSE portal portal " }, { "code": null, "e": 30391, "s": 30366, "text": "Example 2: Integer Lists" }, { "code": null, "e": 30396, "s": 30391, "text": "Java" }, { "code": "// Java Program to Combine Two List// by Alternatingly Taking Elements // importing required packagesimport java.io.*;import java.util.*;import java.util.Iterator; // Classclass GFG { // Main driver method public static void main(String[] args) { // Creating(declaring) List1 List<Integer> list1 = new ArrayList<Integer>(); // Adding elements to List1 // Custom inputs list1.add(2); list1.add(4); list1.add(6); // Creating(declaring) List2 List<Integer> list2 = new ArrayList<Integer>(); // Adding elements to List2 // Custom inputs list2.add(1); list2.add(3); list2.add(5); list2.add(7); // Display message System.out.print(\"List1 contents: \"); // Iterating over List1 Iterator iterator = list1.iterator(); // ConditionCheck using hasNext() method which hold // true till single element in remaining List while (iterator.hasNext()) { // Printing List1 contents System.out.print(iterator.next() + \" \"); } // New line System.out.println(); // Display message System.out.print(\"List2 contents: \"); iterator = list2.iterator(); // ConditionCheck using hasNext() method which hold // true till single element in remaining List while (iterator.hasNext()) { // Printing List2 contents System.out.print(iterator.next() + \" \"); } // Setting counters to zeros int i = 0; int j = 0; // Creating(declaring) merged list List<Integer> merged_list = new ArrayList<Integer>(); // Iterating over both the lists // until the shorter list while (i < list1.size() && j < list2.size()) { // Step 1: Adding List2 element merged_list.add(list2.get(j)); // Step 2: Adding List1 element merged_list.add(list1.get(i)); // Incrementing counters i++; j++; } // Iterating over the remaining part of List1 // Case 1: Input: ShorterList following BiggerList while (i < list1.size()) { // Merge remaining List to List1, and // making List2 final as NULL List merged_list.add(list1.get(i)); i++; } // Case 2: Input: BiggerList following ShorterList while (j < list2.size()) { // Merge remaining List to List1,an d // making List2 -> NULL List merged_list.add(list2.get(j)); j++; } // New line System.out.println(); // Display message System.out.print(\"Merged List contents: \"); // Iterating over merged list iterator = merged_list.iterator(); // Condition check using hasNext() method which // holds true till there is single element remaining // in the List while (iterator.hasNext()) { // Printing merged List contents i.e // FinalList = List1 + List2(Null final List) System.out.print(iterator.next() + \" \"); } }}", "e": 33585, "s": 30396, "text": null }, { "code": null, "e": 33670, "s": 33585, "text": "List1 contents: 2 4 6 \nList2 contents: 1 3 5 7 \nMerged List contents: 1 2 3 4 5 6 7 " }, { "code": null, "e": 33689, "s": 33670, "text": "surindertarika1234" }, { "code": null, "e": 33702, "s": 33689, "text": "simmytarika5" }, { "code": null, "e": 33719, "s": 33702, "text": "surinderdawra388" }, { "code": null, "e": 33736, "s": 33719, "text": "Java-Collections" }, { "code": null, "e": 33746, "s": 33736, "text": "java-list" }, { "code": null, "e": 33753, "s": 33746, "text": "Picked" }, { "code": null, "e": 33758, "s": 33753, "text": "Java" }, { "code": null, "e": 33772, "s": 33758, "text": "Java Programs" }, { "code": null, "e": 33777, "s": 33772, "text": "Java" }, { "code": null, "e": 33794, "s": 33777, "text": "Java-Collections" }, { "code": null, "e": 33892, "s": 33794, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33907, "s": 33892, "text": "Stream In Java" }, { "code": null, "e": 33928, "s": 33907, "text": "Constructors in Java" }, { "code": null, "e": 33947, "s": 33928, "text": "Exceptions in Java" }, { "code": null, "e": 33977, "s": 33947, "text": "Functional Interfaces in Java" }, { "code": null, "e": 34023, "s": 33977, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 34049, "s": 34023, "text": "Java Programming Examples" }, { "code": null, "e": 34083, "s": 34049, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 34130, "s": 34083, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 34162, "s": 34130, "text": "How to Iterate HashMap in Java?" } ]
Find the maximum length of the prefix - GeeksforGeeks
13 Apr, 2021 Given an array arr[] of N integers where all elements of the array are from the range [0, 9] i.e. a single digit, the task is to find the maximum length of the prefix of this array such that removing exactly one element from the prefix will make the occurrence of the remaining elements in the prefix same.Examples: Input: arr[] = {1, 1, 1, 2, 2, 2} Output: 5 Required prefix is {1, 1, 1, 2, 2} After removing 1, every element will have equal frequency i.e. {1, 1, 2, 2} Input: arr[] = {1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5} Output: 13 Input: arr[] = {10, 2, 5, 4, 1} Output: 5 Approach: Iterate over all the prefixes and check for each prefix if we can remove an element so that each element has same occurrence. In order to satisfy this condition, one of the following conditions must hold true: There is only one element in the prefix. All the elements in the prefix have the occurrence of 1. Every element has the same occurrence, except for exactly one element which has occurrence of 1. Every element has the same occurrence, except for exactly one element which has the occurrence exactly 1 more than any other elements. Below is the implementation of the above approach: C++14 Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the maximum// length of the required prefixint Maximum_Length(vector<int> a){ // Array to store the frequency // of each element of the array int counts[11] = {0}; // Iterating for all the elements int ans = 0; for(int index = 0; index < a.size(); index++) { // Update the frequency of the // current element i.e. v counts[a[index]] += 1; // Sorted positive values // from counts array vector<int> k; for(auto i : counts) if (i != 0) k.push_back(i); sort(k.begin(), k.end()); // If current prefix satisfies // the given conditions if (k.size() == 1 || (k[0] == k[k.size() - 2] && k.back() - k[k.size() - 2] == 1) || (k[0] == 1 and k[1] == k.back())) ans = index; } // Return the maximum length return ans + 1;} // Driver codeint main(){ vector<int> a = { 1, 1, 1, 2, 2, 2 }; cout << (Maximum_Length(a));} // This code is contributed by grand_master // Java implementation of the approachimport java.util.*;public class Main{ // Function to return the maximum // length of the required prefix public static int Maximum_Length(Vector<Integer> a) { // Array to store the frequency // of each element of the array int[] counts = new int[11]; // Iterating for all the elements int ans = 0; for(int index = 0; index < a.size(); index++) { // Update the frequency of the // current element i.e. v counts[a.get(index)] += 1; // Sorted positive values // from counts array Vector<Integer> k = new Vector<Integer>(); for(int i : counts) if (i != 0) k.add(i); Collections.sort(k); // If current prefix satisfies // the given conditions if (k.size() == 1 || (k.get(0) == k.get(k.size() - 2) && k.get(k.size() - 1) - k.get(k.size() - 2) == 1) || (k.get(0) == 1 && k.get(1) == k.get(k.size() - 1))) ans = index; } // Return the maximum length return ans + 1; } // Driver code public static void main(String[] args) { Vector<Integer> a = new Vector<Integer>(); a.add(1); a.add(1); a.add(1); a.add(2); a.add(2); a.add(2); System.out.println(Maximum_Length(a)); }} // This code is contributed by divyeshrabadiya07 # Python3 implementation of the approach # Function to return the maximum# length of the required prefixdef Maximum_Length(a): # Array to store the frequency # of each element of the array counts =[0]*11 # Iterating for all the elements for index, v in enumerate(a): # Update the frequency of the # current element i.e. v counts[v] += 1 # Sorted positive values from counts array k = sorted([i for i in counts if i]) # If current prefix satisfies # the given conditions if len(k)== 1 or (k[0]== k[-2] and k[-1]-k[-2]== 1) or (k[0]== 1 and k[1]== k[-1]): ans = index # Return the maximum length return ans + 1 # Driver codeif __name__=="__main__": a = [1, 1, 1, 2, 2, 2] n = len(a) print(Maximum_Length(a)) // C# implementation of the approachusing System;using System.Collections.Generic;class GFG { // Function to return the maximum // length of the required prefix static int Maximum_Length(List<int> a) { // Array to store the frequency // of each element of the array int[] counts = new int[11]; // Iterating for all the elements int ans = 0; for(int index = 0; index < a.Count; index++) { // Update the frequency of the // current element i.e. v counts[a[index]] += 1; // Sorted positive values // from counts array List<int> k = new List<int>(); foreach(int i in counts) if (i != 0) k.Add(i); k.Sort(); // If current prefix satisfies // the given conditions if (k.Count == 1 || (k[0] == k[k.Count - 2] && k[k.Count - 1] - k[k.Count - 2] == 1) || (k[0] == 1 && k[1] == k[k.Count - 1])) ans = index; } // Return the maximum length return ans + 1; } static void Main() { List<int> a = new List<int>(new int[]{ 1, 1, 1, 2, 2, 2 }); Console.Write(Maximum_Length(a)); }} // This code is contributed by divyesh072019 <script> // Javascript implementation of the approach // Function to return the maximum // length of the required prefix function Maximum_Length(a) { // Array to store the frequency // of each element of the array let counts = new Array(11); counts.fill(0); // Iterating for all the elements let ans = 0; for(let index = 0; index < a.length; index++) { // Update the frequency of the // current element i.e. v counts[a[index]] += 1; // Sorted positive values // from counts array let k = []; for(let i = 0; i < counts.length; i++) { if (counts[i] != 0) { k.push(i); } } k.sort(function(a, b){return a - b}); // If current prefix satisfies // the given conditions if (k.length == 1 || (k[0] == k[k.length - 2] && k[k.length - 1] - k[k.length - 2] == 1) || (k[0] == 1 && k[1] == k[k.length - 1])) ans = index; } // Return the maximum length return (ans); } let a = [ 1, 1, 1, 2, 2, 2 ]; document.write(Maximum_Length(a)); // This code is contributed by suresh07.</script> 5 grand_master divyesh072019 divyeshrabadiya07 suresh07 Arrays frequency-counting prefix Arrays Mathematical Arrays 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 Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26041, "s": 26013, "text": "\n13 Apr, 2021" }, { "code": null, "e": 26358, "s": 26041, "text": "Given an array arr[] of N integers where all elements of the array are from the range [0, 9] i.e. a single digit, the task is to find the maximum length of the prefix of this array such that removing exactly one element from the prefix will make the occurrence of the remaining elements in the prefix same.Examples: " }, { "code": null, "e": 26513, "s": 26358, "text": "Input: arr[] = {1, 1, 1, 2, 2, 2} Output: 5 Required prefix is {1, 1, 1, 2, 2} After removing 1, every element will have equal frequency i.e. {1, 1, 2, 2}" }, { "code": null, "e": 26579, "s": 26513, "text": "Input: arr[] = {1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5} Output: 13" }, { "code": null, "e": 26622, "s": 26579, "text": "Input: arr[] = {10, 2, 5, 4, 1} Output: 5 " }, { "code": null, "e": 26843, "s": 26622, "text": "Approach: Iterate over all the prefixes and check for each prefix if we can remove an element so that each element has same occurrence. In order to satisfy this condition, one of the following conditions must hold true: " }, { "code": null, "e": 26884, "s": 26843, "text": "There is only one element in the prefix." }, { "code": null, "e": 26941, "s": 26884, "text": "All the elements in the prefix have the occurrence of 1." }, { "code": null, "e": 27038, "s": 26941, "text": "Every element has the same occurrence, except for exactly one element which has occurrence of 1." }, { "code": null, "e": 27173, "s": 27038, "text": "Every element has the same occurrence, except for exactly one element which has the occurrence exactly 1 more than any other elements." }, { "code": null, "e": 27224, "s": 27173, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27230, "s": 27224, "text": "C++14" }, { "code": null, "e": 27235, "s": 27230, "text": "Java" }, { "code": null, "e": 27243, "s": 27235, "text": "Python3" }, { "code": null, "e": 27246, "s": 27243, "text": "C#" }, { "code": null, "e": 27257, "s": 27246, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the maximum// length of the required prefixint Maximum_Length(vector<int> a){ // Array to store the frequency // of each element of the array int counts[11] = {0}; // Iterating for all the elements int ans = 0; for(int index = 0; index < a.size(); index++) { // Update the frequency of the // current element i.e. v counts[a[index]] += 1; // Sorted positive values // from counts array vector<int> k; for(auto i : counts) if (i != 0) k.push_back(i); sort(k.begin(), k.end()); // If current prefix satisfies // the given conditions if (k.size() == 1 || (k[0] == k[k.size() - 2] && k.back() - k[k.size() - 2] == 1) || (k[0] == 1 and k[1] == k.back())) ans = index; } // Return the maximum length return ans + 1;} // Driver codeint main(){ vector<int> a = { 1, 1, 1, 2, 2, 2 }; cout << (Maximum_Length(a));} // This code is contributed by grand_master", "e": 28437, "s": 27257, "text": null }, { "code": "// Java implementation of the approachimport java.util.*;public class Main{ // Function to return the maximum // length of the required prefix public static int Maximum_Length(Vector<Integer> a) { // Array to store the frequency // of each element of the array int[] counts = new int[11]; // Iterating for all the elements int ans = 0; for(int index = 0; index < a.size(); index++) { // Update the frequency of the // current element i.e. v counts[a.get(index)] += 1; // Sorted positive values // from counts array Vector<Integer> k = new Vector<Integer>(); for(int i : counts) if (i != 0) k.add(i); Collections.sort(k); // If current prefix satisfies // the given conditions if (k.size() == 1 || (k.get(0) == k.get(k.size() - 2) && k.get(k.size() - 1) - k.get(k.size() - 2) == 1) || (k.get(0) == 1 && k.get(1) == k.get(k.size() - 1))) ans = index; } // Return the maximum length return ans + 1; } // Driver code public static void main(String[] args) { Vector<Integer> a = new Vector<Integer>(); a.add(1); a.add(1); a.add(1); a.add(2); a.add(2); a.add(2); System.out.println(Maximum_Length(a)); }} // This code is contributed by divyeshrabadiya07", "e": 30057, "s": 28437, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the maximum# length of the required prefixdef Maximum_Length(a): # Array to store the frequency # of each element of the array counts =[0]*11 # Iterating for all the elements for index, v in enumerate(a): # Update the frequency of the # current element i.e. v counts[v] += 1 # Sorted positive values from counts array k = sorted([i for i in counts if i]) # If current prefix satisfies # the given conditions if len(k)== 1 or (k[0]== k[-2] and k[-1]-k[-2]== 1) or (k[0]== 1 and k[1]== k[-1]): ans = index # Return the maximum length return ans + 1 # Driver codeif __name__==\"__main__\": a = [1, 1, 1, 2, 2, 2] n = len(a) print(Maximum_Length(a))", "e": 30866, "s": 30057, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic;class GFG { // Function to return the maximum // length of the required prefix static int Maximum_Length(List<int> a) { // Array to store the frequency // of each element of the array int[] counts = new int[11]; // Iterating for all the elements int ans = 0; for(int index = 0; index < a.Count; index++) { // Update the frequency of the // current element i.e. v counts[a[index]] += 1; // Sorted positive values // from counts array List<int> k = new List<int>(); foreach(int i in counts) if (i != 0) k.Add(i); k.Sort(); // If current prefix satisfies // the given conditions if (k.Count == 1 || (k[0] == k[k.Count - 2] && k[k.Count - 1] - k[k.Count - 2] == 1) || (k[0] == 1 && k[1] == k[k.Count - 1])) ans = index; } // Return the maximum length return ans + 1; } static void Main() { List<int> a = new List<int>(new int[]{ 1, 1, 1, 2, 2, 2 }); Console.Write(Maximum_Length(a)); }} // This code is contributed by divyesh072019", "e": 32276, "s": 30866, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the maximum // length of the required prefix function Maximum_Length(a) { // Array to store the frequency // of each element of the array let counts = new Array(11); counts.fill(0); // Iterating for all the elements let ans = 0; for(let index = 0; index < a.length; index++) { // Update the frequency of the // current element i.e. v counts[a[index]] += 1; // Sorted positive values // from counts array let k = []; for(let i = 0; i < counts.length; i++) { if (counts[i] != 0) { k.push(i); } } k.sort(function(a, b){return a - b}); // If current prefix satisfies // the given conditions if (k.length == 1 || (k[0] == k[k.length - 2] && k[k.length - 1] - k[k.length - 2] == 1) || (k[0] == 1 && k[1] == k[k.length - 1])) ans = index; } // Return the maximum length return (ans); } let a = [ 1, 1, 1, 2, 2, 2 ]; document.write(Maximum_Length(a)); // This code is contributed by suresh07.</script>", "e": 33703, "s": 32276, "text": null }, { "code": null, "e": 33708, "s": 33706, "text": "5" }, { "code": null, "e": 33725, "s": 33712, "text": "grand_master" }, { "code": null, "e": 33739, "s": 33725, "text": "divyesh072019" }, { "code": null, "e": 33757, "s": 33739, "text": "divyeshrabadiya07" }, { "code": null, "e": 33766, "s": 33757, "text": "suresh07" }, { "code": null, "e": 33773, "s": 33766, "text": "Arrays" }, { "code": null, "e": 33792, "s": 33773, "text": "frequency-counting" }, { "code": null, "e": 33799, "s": 33792, "text": "prefix" }, { "code": null, "e": 33806, "s": 33799, "text": "Arrays" }, { "code": null, "e": 33819, "s": 33806, "text": "Mathematical" }, { "code": null, "e": 33826, "s": 33819, "text": "Arrays" }, { "code": null, "e": 33839, "s": 33826, "text": "Mathematical" }, { "code": null, "e": 33937, "s": 33839, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33964, "s": 33937, "text": "Count pairs with given sum" }, { "code": null, "e": 33995, "s": 33964, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 34020, "s": 33995, "text": "Window Sliding Technique" }, { "code": null, "e": 34058, "s": 34020, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 34079, "s": 34058, "text": "Next Greater Element" }, { "code": null, "e": 34109, "s": 34079, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 34169, "s": 34109, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 34184, "s": 34169, "text": "C++ Data Types" }, { "code": null, "e": 34227, "s": 34184, "text": "Set in C++ Standard Template Library (STL)" } ]
SYSDATE() function in MySQL - GeeksforGeeks
27 Nov, 2020 SYSDATE() function in MySQL is used to return the current date and time in YYYY-MM-DD HH:MM:SS or YYYYMMDDHHMMSS.uuuuuu format depending on the context of the function. Syntax : SYSDATE() Parameter :This method does not accept any parameter. Returns :It returns the current date and time value. Example-1 :Getting the current date and time using SYSDATE Function. SELECT SYSDATE() as CurrentDateAndTime ; Output : Example-2 :Getting the current date and time using SYSDATE Function in numeric format. SELECT SYSDATE() + 0 as CurrDateAndTime ; Output : Example-3 :The SYSDATE function can be used to set value of columns. To demonstrate create a table named DeliveryDetails. CREATE TABLE DeliveryDetails ( DeliveryId INT AUTO_INCREMENT, ProductId INT NOT NULL, ProductName VARCHAR(20) NOT NULL, Delivered_At TIMESTAMP NOT NULL, PRIMARY KEY(DeliveryId) ); Here, we will use SYSDATE function when a delivery will be completed. The value in Delivered_At column will be the value given by SYSDATE Function. INSERT INTO DeliveryDetails(ProductId, ProductName, Delivered_At) VALUES (94567, 'Acer Helios', SYSDATE()); Now, checking the DeliveryDetails table : SELECT * FROM DeliveryDetails; Output : DBMS-SQL mysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? SQL | Subquery How to Create a Table With Multiple Foreign Keys in SQL? What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL Query to Convert VARCHAR to INT SQL using Python How to Write a SQL Query For a Specific Date Range and Date Time? How to Select Data Between Two Dates and Times in SQL Server? SQL Query to Compare Two Dates
[ { "code": null, "e": 25513, "s": 25485, "text": "\n27 Nov, 2020" }, { "code": null, "e": 25682, "s": 25513, "text": "SYSDATE() function in MySQL is used to return the current date and time in YYYY-MM-DD HH:MM:SS or YYYYMMDDHHMMSS.uuuuuu format depending on the context of the function." }, { "code": null, "e": 25691, "s": 25682, "text": "Syntax :" }, { "code": null, "e": 25702, "s": 25691, "text": "SYSDATE()\n" }, { "code": null, "e": 25756, "s": 25702, "text": "Parameter :This method does not accept any parameter." }, { "code": null, "e": 25809, "s": 25756, "text": "Returns :It returns the current date and time value." }, { "code": null, "e": 25878, "s": 25809, "text": "Example-1 :Getting the current date and time using SYSDATE Function." }, { "code": null, "e": 25920, "s": 25878, "text": "SELECT SYSDATE() as CurrentDateAndTime ;\n" }, { "code": null, "e": 25929, "s": 25920, "text": "Output :" }, { "code": null, "e": 26016, "s": 25929, "text": "Example-2 :Getting the current date and time using SYSDATE Function in numeric format." }, { "code": null, "e": 26059, "s": 26016, "text": "SELECT SYSDATE() + 0 as CurrDateAndTime ;\n" }, { "code": null, "e": 26068, "s": 26059, "text": "Output :" }, { "code": null, "e": 26190, "s": 26068, "text": "Example-3 :The SYSDATE function can be used to set value of columns. To demonstrate create a table named DeliveryDetails." }, { "code": null, "e": 26371, "s": 26190, "text": "CREATE TABLE DeliveryDetails (\nDeliveryId INT AUTO_INCREMENT,\nProductId INT NOT NULL,\nProductName VARCHAR(20) NOT NULL,\nDelivered_At TIMESTAMP NOT NULL,\nPRIMARY KEY(DeliveryId)\n);\n" }, { "code": null, "e": 26519, "s": 26371, "text": "Here, we will use SYSDATE function when a delivery will be completed. The value in Delivered_At column will be the value given by SYSDATE Function." }, { "code": null, "e": 26629, "s": 26519, "text": "INSERT INTO \nDeliveryDetails(ProductId, ProductName, Delivered_At)\nVALUES\n(94567, 'Acer Helios', SYSDATE());" }, { "code": null, "e": 26671, "s": 26629, "text": "Now, checking the DeliveryDetails table :" }, { "code": null, "e": 26703, "s": 26671, "text": "SELECT * FROM DeliveryDetails;\n" }, { "code": null, "e": 26712, "s": 26703, "text": "Output :" }, { "code": null, "e": 26721, "s": 26712, "text": "DBMS-SQL" }, { "code": null, "e": 26727, "s": 26721, "text": "mysql" }, { "code": null, "e": 26731, "s": 26727, "text": "SQL" }, { "code": null, "e": 26735, "s": 26731, "text": "SQL" }, { "code": null, "e": 26833, "s": 26735, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26899, "s": 26833, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 26914, "s": 26899, "text": "SQL | Subquery" }, { "code": null, "e": 26971, "s": 26914, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 27003, "s": 26971, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 27081, "s": 27003, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 27117, "s": 27081, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 27134, "s": 27117, "text": "SQL using Python" }, { "code": null, "e": 27200, "s": 27134, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" }, { "code": null, "e": 27262, "s": 27200, "text": "How to Select Data Between Two Dates and Times in SQL Server?" } ]
Count ways to represent N as sum of powers of 2 - GeeksforGeeks
26 Mar, 2021 Given an integer N, the task is to count the number of ways to represent N as the sum of powers of 2. Examples: Input: N = 4Output: 4Explanation: All possible ways to obtains sum N using powers of 2 are {4, 2+2, 1+1+1+1, 2+1+1}. Input: N = 5Output: 4Explanation: All possible ways to obtains sum N using powers of 2 are {4 + 1, 2+2 + 1, 1+1+1+1 + 1, 2+1+1 + 1} Naive Approach: The simplest approach to solve the problem is to generate all powers of 2 whose values are less than N and print all combinations to represent the sum N. Efficient Approach: To optimize the above approach, the idea is to use recursion. Define a function f(N, K) which represents the number of ways to express N as a sum of powers of 2 with all the numbers having power less than or equal to k where K ( = log2(N)) is the maximum power of 2 which satisfies 2K ≤ N. If (power(2, K) ≤ N) : f(N, K) = f(N – power(2, K), K) + f(N, K – 1) //to check if power(2, k) can be one of the number. Otherwise: f(N, K)=f(N, K – 1)Base cases : If (N = 0) f(N, K)=1 (Only 1 possible way exists to represent N) If (k==0) f(N, K)=1 (Only 1 possible way exists to represent N by taking 20) Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for above implementation#include <bits/stdc++.h>using namespace std;int numberOfWays(int n, int k){ // Base Cases if (n == 0) return 1; if (k == 0) return 1; // Check if 2^k can be used as // one of the numbers or not if (n >= pow(2, k)) { int curr_val = pow(2, k); return numberOfWays(n - curr_val, k) + numberOfWays(n, k - 1); } // Otherwise else // Count number of ways to // N using 2 ^ k - 1 return numberOfWays(n, k - 1);} // Driver Codeint main(){ int n = 4; int k = log2(n); cout << numberOfWays(n, k) << endl;} // Java program to implement// the above approachimport java.util.*;class GFG{static int numberOfWays(int n, int k){ // Base Cases if (n == 0) return 1; if (k == 0) return 1; // Check if 2^k can be used as // one of the numbers or not if (n >= (int)Math.pow(2, k)) { int curr_val = (int)Math.pow(2, k); return numberOfWays(n - curr_val, k) + numberOfWays(n, k - 1); } // Otherwise else // Count number of ways to // N using 2 ^ k - 1 return numberOfWays(n, k - 1);} // Driver codepublic static void main(String[] args){ int n = 4; int k = (int)(Math.log(n) / Math.log(2)); System.out.println(numberOfWays(n, k));}} // This code is contributed by susmitakundugoaldanga. # Python3 program for above implementationfrom math import log2def numberOfWays(n, k): # Base Cases if (n == 0): return 1 if (k == 0): return 1 # Check if 2^k can be used as # one of the numbers or not if (n >= pow(2, k)): curr_val = pow(2, k) return numberOfWays(n - curr_val, k) + numberOfWays(n, k - 1) # Otherwise else: # Count number of ways to # N using 2 ^ k - 1 return numberOfWays(n, k - 1) # Driver Codeif __name__ == '__main__': n = 4 k = log2(n) print(numberOfWays(n, k)) # This code is contributed by mohit kumar 29 // C# program to implement// the above approachusing System;class GFG{static int numberOfWays(int n, int k){ // Base Cases if (n == 0) return 1; if (k == 0) return 1; // Check if 2^k can be used as // one of the numbers or not if (n >= (int)Math.Pow(2, k)) { int curr_val = (int)Math.Pow(2, k); return numberOfWays(n - curr_val, k) + numberOfWays(n, k - 1); } // Otherwise else // Count number of ways to // N using 2 ^ k - 1 return numberOfWays(n, k - 1);} // Driver codepublic static void Main(String[] args){ int n = 4; int k = (int)(Math.Log(n) / Math.Log(2)); Console.WriteLine(numberOfWays(n, k));}} // This code is contributed by 29AjayKumar <script> // JavaScript program for above implementation function numberOfWays(n, k){ // Base Cases if (n == 0) return 1; if (k == 0) return 1; // Check if 2^k can be used as // one of the numbers or not if (n >= Math.pow(2, k)) { let curr_val = Math.pow(2, k); return numberOfWays(n - curr_val, k) + numberOfWays(n, k - 1); } // Otherwise else // Count number of ways to // N using 2 ^ k - 1 return numberOfWays(n, k - 1);} // Driver Code let n = 4; let k = Math.log2(n); document.write(numberOfWays(n, k) + "<br>"); // This code is contributed by Mayank Tyagi </script> 4 Time Complexity: O((logN+K)K ), where K is log2(N)Auxiliary Space: O(1) mohit kumar 29 susmitakundugoaldanga 29AjayKumar mayanktyagi1709 Numbers Technical Scripter 2020 Combinatorial Mathematical Recursion Mathematical Recursion Numbers Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Combinational Sum Count ways to reach the nth stair using step 1, 2 or 3 Print all possible strings of length k that can be formed from a set of n characters Count of subsets with sum equal to X Python program to get all subsets of given size of a set Program for Fibonacci numbers C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7 Merge two sorted arrays
[ { "code": null, "e": 27111, "s": 27083, "text": "\n26 Mar, 2021" }, { "code": null, "e": 27213, "s": 27111, "text": "Given an integer N, the task is to count the number of ways to represent N as the sum of powers of 2." }, { "code": null, "e": 27223, "s": 27213, "text": "Examples:" }, { "code": null, "e": 27341, "s": 27223, "text": "Input: N = 4Output: 4Explanation: All possible ways to obtains sum N using powers of 2 are {4, 2+2, 1+1+1+1, 2+1+1}." }, { "code": null, "e": 27474, "s": 27341, "text": "Input: N = 5Output: 4Explanation: All possible ways to obtains sum N using powers of 2 are {4 + 1, 2+2 + 1, 1+1+1+1 + 1, 2+1+1 + 1}" }, { "code": null, "e": 27644, "s": 27474, "text": "Naive Approach: The simplest approach to solve the problem is to generate all powers of 2 whose values are less than N and print all combinations to represent the sum N." }, { "code": null, "e": 27954, "s": 27644, "text": "Efficient Approach: To optimize the above approach, the idea is to use recursion. Define a function f(N, K) which represents the number of ways to express N as a sum of powers of 2 with all the numbers having power less than or equal to k where K ( = log2(N)) is the maximum power of 2 which satisfies 2K ≤ N." }, { "code": null, "e": 28130, "s": 27954, "text": "If (power(2, K) ≤ N) : f(N, K) = f(N – power(2, K), K) + f(N, K – 1) //to check if power(2, k) can be one of the number. Otherwise: f(N, K)=f(N, K – 1)Base cases :" }, { "code": null, "e": 28195, "s": 28130, "text": "If (N = 0) f(N, K)=1 (Only 1 possible way exists to represent N)" }, { "code": null, "e": 28272, "s": 28195, "text": "If (k==0) f(N, K)=1 (Only 1 possible way exists to represent N by taking 20)" }, { "code": null, "e": 28323, "s": 28272, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28327, "s": 28323, "text": "C++" }, { "code": null, "e": 28332, "s": 28327, "text": "Java" }, { "code": null, "e": 28340, "s": 28332, "text": "Python3" }, { "code": null, "e": 28343, "s": 28340, "text": "C#" }, { "code": null, "e": 28354, "s": 28343, "text": "Javascript" }, { "code": "// C++ program for above implementation#include <bits/stdc++.h>using namespace std;int numberOfWays(int n, int k){ // Base Cases if (n == 0) return 1; if (k == 0) return 1; // Check if 2^k can be used as // one of the numbers or not if (n >= pow(2, k)) { int curr_val = pow(2, k); return numberOfWays(n - curr_val, k) + numberOfWays(n, k - 1); } // Otherwise else // Count number of ways to // N using 2 ^ k - 1 return numberOfWays(n, k - 1);} // Driver Codeint main(){ int n = 4; int k = log2(n); cout << numberOfWays(n, k) << endl;}", "e": 28994, "s": 28354, "text": null }, { "code": "// Java program to implement// the above approachimport java.util.*;class GFG{static int numberOfWays(int n, int k){ // Base Cases if (n == 0) return 1; if (k == 0) return 1; // Check if 2^k can be used as // one of the numbers or not if (n >= (int)Math.pow(2, k)) { int curr_val = (int)Math.pow(2, k); return numberOfWays(n - curr_val, k) + numberOfWays(n, k - 1); } // Otherwise else // Count number of ways to // N using 2 ^ k - 1 return numberOfWays(n, k - 1);} // Driver codepublic static void main(String[] args){ int n = 4; int k = (int)(Math.log(n) / Math.log(2)); System.out.println(numberOfWays(n, k));}} // This code is contributed by susmitakundugoaldanga.", "e": 29773, "s": 28994, "text": null }, { "code": "# Python3 program for above implementationfrom math import log2def numberOfWays(n, k): # Base Cases if (n == 0): return 1 if (k == 0): return 1 # Check if 2^k can be used as # one of the numbers or not if (n >= pow(2, k)): curr_val = pow(2, k) return numberOfWays(n - curr_val, k) + numberOfWays(n, k - 1) # Otherwise else: # Count number of ways to # N using 2 ^ k - 1 return numberOfWays(n, k - 1) # Driver Codeif __name__ == '__main__': n = 4 k = log2(n) print(numberOfWays(n, k)) # This code is contributed by mohit kumar 29", "e": 30394, "s": 29773, "text": null }, { "code": "// C# program to implement// the above approachusing System;class GFG{static int numberOfWays(int n, int k){ // Base Cases if (n == 0) return 1; if (k == 0) return 1; // Check if 2^k can be used as // one of the numbers or not if (n >= (int)Math.Pow(2, k)) { int curr_val = (int)Math.Pow(2, k); return numberOfWays(n - curr_val, k) + numberOfWays(n, k - 1); } // Otherwise else // Count number of ways to // N using 2 ^ k - 1 return numberOfWays(n, k - 1);} // Driver codepublic static void Main(String[] args){ int n = 4; int k = (int)(Math.Log(n) / Math.Log(2)); Console.WriteLine(numberOfWays(n, k));}} // This code is contributed by 29AjayKumar", "e": 31153, "s": 30394, "text": null }, { "code": "<script> // JavaScript program for above implementation function numberOfWays(n, k){ // Base Cases if (n == 0) return 1; if (k == 0) return 1; // Check if 2^k can be used as // one of the numbers or not if (n >= Math.pow(2, k)) { let curr_val = Math.pow(2, k); return numberOfWays(n - curr_val, k) + numberOfWays(n, k - 1); } // Otherwise else // Count number of ways to // N using 2 ^ k - 1 return numberOfWays(n, k - 1);} // Driver Code let n = 4; let k = Math.log2(n); document.write(numberOfWays(n, k) + \"<br>\"); // This code is contributed by Mayank Tyagi </script>", "e": 31826, "s": 31153, "text": null }, { "code": null, "e": 31831, "s": 31829, "text": "4" }, { "code": null, "e": 31905, "s": 31833, "text": "Time Complexity: O((logN+K)K ), where K is log2(N)Auxiliary Space: O(1)" }, { "code": null, "e": 31920, "s": 31905, "text": "mohit kumar 29" }, { "code": null, "e": 31942, "s": 31920, "text": "susmitakundugoaldanga" }, { "code": null, "e": 31954, "s": 31942, "text": "29AjayKumar" }, { "code": null, "e": 31970, "s": 31954, "text": "mayanktyagi1709" }, { "code": null, "e": 31978, "s": 31970, "text": "Numbers" }, { "code": null, "e": 32002, "s": 31978, "text": "Technical Scripter 2020" }, { "code": null, "e": 32016, "s": 32002, "text": "Combinatorial" }, { "code": null, "e": 32029, "s": 32016, "text": "Mathematical" }, { "code": null, "e": 32039, "s": 32029, "text": "Recursion" }, { "code": null, "e": 32052, "s": 32039, "text": "Mathematical" }, { "code": null, "e": 32062, "s": 32052, "text": "Recursion" }, { "code": null, "e": 32070, "s": 32062, "text": "Numbers" }, { "code": null, "e": 32084, "s": 32070, "text": "Combinatorial" }, { "code": null, "e": 32182, "s": 32084, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32200, "s": 32182, "text": "Combinational Sum" }, { "code": null, "e": 32255, "s": 32200, "text": "Count ways to reach the nth stair using step 1, 2 or 3" }, { "code": null, "e": 32340, "s": 32255, "text": "Print all possible strings of length k that can be formed from a set of n characters" }, { "code": null, "e": 32377, "s": 32340, "text": "Count of subsets with sum equal to X" }, { "code": null, "e": 32434, "s": 32377, "text": "Python program to get all subsets of given size of a set" }, { "code": null, "e": 32464, "s": 32434, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 32479, "s": 32464, "text": "C++ Data Types" }, { "code": null, "e": 32522, "s": 32479, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 32541, "s": 32522, "text": "Coin Change | DP-7" } ]
How to store financial market data for backtesting | by Mario Emmanuel | Towards Data Science
I am working on moderately large financial price data sets. By moderately large I mean less than 4 million rows per asset. 4 million rows can cover the last 20 years of minute price bars done by a regular asset without extended trading hours — such as index futures contracts or regular cash stocks — . When dealing with price bars, minute and 5-minute bars generate large datasets. If you would happen to deal with tick analysis then it would be huge instead of large, but tick data is really expensive to obtain, manage and monetize; and unless you are backtesting scalping strategies or working in the HFT industry their advantage would be dubious. Although 4 million rows do not sound impressive, we need to understand that it is 4 million rows per asset. So to analyze all assets from Russell 2000 would mean 8 billion rows (now we are getting large). Add some European stock markets, your local country small and mid caps, commodities and forex and there you go: you just landed on the big data arena. There are more than 1700 regulated markets in the world, as soon as you start stockpiling intraday data the numbers become impressive — very fast — . Bear in mind also that current trend is to extend all future contracts trading hours — Eurex began extended trading hours for FDAX futures since last January — , so the situation is not getting better in terms of the amount of data that needs to be analyzed. Now the question that every “financial data scientist” makes to himself: where and how do I put my data. A relational database is the first answer, probably not the most efficient, but the easiest one for sure. I can enumerate four options as main repository strategy: SQL relational databases.Serialized storage of large arrays.Key/Value databases (such as Oracle Berkeley DB).CSV files. SQL relational databases. Serialized storage of large arrays. Key/Value databases (such as Oracle Berkeley DB). CSV files. For obvious reasons I have discarded the last one, and for the other three I have evaluated just the first two ones. I have planned to explore the third one: a key/value database. Those databases are not truly mainstream but they can offer outstanding performances when dealing with simple data structures that are intensive in reading (which is the case for financial data). I really believe that it might be the best trade-off solution between serialized storage and relational databases. In this post, I focus on the first strategy. Before going into details we will revisit what data we are dealing with. Almost all data you are going to deal in financial markets will be price bars or candlesticks. There is a reason for this. The high/low/open/close structure of a financial price bar resembles the classic whiskers and box plots used in statistics but they are easier to obtain. I have used the word resemble because all the important information provided by a whiskers and box bar (quartiles and median) is not available in a financial candlestick. Quartiles and medians are not arbitrary values, they provide descriptive information about the variable under analysis. One might wonder why whisker and box bars are not used in financial markets (I think that its use might lead to useful and innovative price action insight), and the reason for that is simple. Candlestick charts are thought to have been used first during the 18th century by a Japanese rice trader named Munehisa Homma. If you are wondering if there were future contracts in the 18th century you would like to know that although the first modern future contract exchange was the Chicago Board of Trade there were established future markets in Europe and Japan in the 17th century. Getting the maximum, minimum, opening and close prices to build a candlestick for a given period is extremely easy. You just need the list of all trades during a certain period. Now trading is electronic and takes place in an ordered manner, but bear in mind that it has not been always the case. Electronic trading is relatively modern (it started to gain relevance during the 80s). Before that, trading pits were the norm and assets were traded in the pit just at certain hours. The notion of a continuous trading market as we know it was not applicable at that time. Even in the current case when almost all trading takes place electronically, storing and analyzing all trades that take place in a given period to build whiskers and box chart is challenging (doable, but challenging). It implies either a strict continuous track of the order book — reading the tape — , or the less strict way of consolidating shorter timeframes into larger ones. By using candlesticks instead, you end up with information that will lead you to something similar to quartiles and median (please notice that something similar is highlighted). It is what is called the price action of candlesticks or the candlesticks patterns, which, in reality, is just an interpretative analysis on where the price was relevant among all candlestick range. So a large whisker and a small body (such as the one you find in a dragonfly) will imply price rejection, were most of the time the price has been concentrated on the body part and when it tried to move below or above that area it was quickly rejected. That is the kind of conclusions you can get out of a candlestick (again, when reading it within a given market context). Storing interval price information for open/close/low/high will, therefore, enable a certain degree of price action analysis, and according to experience, certain patterns within a given context have statistical relevance and will lead to profitable strategies. Now we understand why candlesticks are used, we can propose a simple data model to store our information. CREATE TABLE candlestick ( “id” INTEGER PRIMARY KEY AUTOINCREMENT, “timezone” TEXT NOT NULL, “timestamp” DATETIME NOT NULL, “open” DECIMAL(12, 6) NOT NULL, “high” DECIMAL(12, 6) NOT NULL, “low” DECIMAL(12, 6) NOT NULL, “close” DECIMAL(12, 6) NOT NULL, “volume” DECIMAL(12, 6) NOT NULL); I am sure you are not impressed with this simple data model, but even this one can be challenged. We will not discuss the timezone column (I plan to write another post on time zones and data), but the usage of timestamp is already relevant and have performance issues. From a usability point of view, this way of storing financial information is simple and well structured. Querying data is really simple: sqlite> select * from candlestick where date(timestamp)='2018-01-12' limit 10;3489458|Europe/Berlin|2018-01-12 07:00:00+01:00|13243.5|13245.5|13234.5|13245.5|2943489459|Europe/Berlin|2018-01-12 07:01:00+01:00|13244.5|13250|13243|13245|1493489460|Europe/Berlin|2018-01-12 07:02:00+01:00|13244.5|13246|13242.5|13244|393489461|Europe/Berlin|2018-01-12 07:03:00+01:00|13242.5|13243.5|13239|13241.5|643489462|Europe/Berlin|2018-01-12 07:04:00+01:00|13241|13241|13235.5|13236.5|613489463|Europe/Berlin|2018-01-12 07:05:00+01:00|13236.5|13240|13236|13239.5|493489464|Europe/Berlin|2018-01-12 07:06:00+01:00|13239|13241.5|13237|13240|493489465|Europe/Berlin|2018-01-12 07:07:00+01:00|13238.5|13241|13237|13239|433489466|Europe/Berlin|2018-01-12 07:08:00+01:00|13239|13239|13236.5|13237|243489467|Europe/Berlin|2018-01-12 07:09:00+01:00|13237|13239|13237|13239|11 Getting the opening price of a given session is simple: sqlite> select * from candlestick where date(timestamp)='2018-01-12' limit 1;3489458|Europe/Berlin|2018-01-12 07:00:00+01:00|13243.5|13245.5|13234.5|13245.5|294 So it is getting the closing price: sqlite> select * from candlestick where date(timestamp)='2018-01-11' order by timestamp desc limit 1;3489457|Europe/Berlin|2018-01-11 21:03:00+01:00|13241|13241|13241|13241|25 But this way has some performance issues we will discuss later. Note that we have used datetime field to store the timestamp. We could also use separate fields for year, month, day, hour and minute, but it would complicate dealing with datetime types in Python (or Java) later. Those complex types might pose performance issues but also help dealing with times, time zones, time offsets, etc. It also enables using time ranges in SQL queries. Using this approach, there are performance issues: When doing the bulk load of the data (using Python and an ORM to ensure that timestamps are properly handled in SQLite) it takes 14 minutes on a 1 core VPS server.Getting all data for a given session takes 5 seconds on the same VPS server. A similar result for getting the opening or closing price. When doing the bulk load of the data (using Python and an ORM to ensure that timestamps are properly handled in SQLite) it takes 14 minutes on a 1 core VPS server. Getting all data for a given session takes 5 seconds on the same VPS server. A similar result for getting the opening or closing price. 14 minutes sounds like too much but bulk loads are not common and it might be acceptable. Even if a more optimized way to load data can be found it is not an important point. Just grab a cup of coffee or program batch loads for the initial data provisioning, that is going to happen only once. On the contrary, 5 seconds might not sound like a big deal but it is. Remember that we are dealing here with multi-asset Monte Carlo simulation scenarios. That means thousands of rounds. So 5 seconds by thousands is way too much time. We need to optimize here. Although I am not going to cover the serialized strategy in this post, I will share some time comparison about both strategies: # Bulk provisioning of 3.5Million price bars:SQLite + Pyhon ORM: 15 min Serialized Stored Arrays + ANSI C: 1.5 min# Retrieve a given specific 1 minute price bar:SQLite + Pyhon ORM: 5 secondsSerialized Stored Arrays + ANSI C: Negligible (microseconds) As stated before, the real issue in these environments is the retrieval time. In serialized arrays, it can be as low as microseconds because a strategy can be defined to allocate space in memory for all data. If you assume that all months have 31 days retrieving a given minute is just a super simple memory lookup operation. There is no such thing as indexing or search operations. Getting the closing or opening price for a given session might be a bit more challenging if we do not know the trading hours (even if we know them, there might be exceptions like trading halts or nonconformities in data), but we can then traverse a specific day. Traversing the array for all daily data is fast and easy. We might overcomplicate the analysis introducing how databases with built-in optimization capabilities can speed up these figures. An Oracle database will perform better —if your project can allocate the cost of 150000$/year for a DBA optimization specialist — , but the take away here is that a simple lookup into an array (the serialized approach) will never be beaten by any relational database. As a drawback, a relational database makes querying and moving data much easier than storing serialized arrays. I use SQLite every time it is possible because it is extremely simple and easy to use and backup. Despite many people state that it is a too basic database it can handle huge large sets. Its major drawback is its lack of page or area locking — which leads to performance issues in applications that write a lot — . Other than that, it usually performs much better than expected, it is really lightweight and it has zero maintenance. The simplest and easiest optimization is to use an index (and the only one you can actually do in SQLite). sqlite> create index idx_timestamp on candlestick(timestamp);sqlite> select * from candlestick where date(timestamp)='2018-01-11' order by timestamp desc limit 1;3489457|Europe/Berlin|2018-01-11 21:03:00+01:00|13241|13241|13241|13241|25 Now the search takes less than one second. It is a significative performance improvement. [user@host gaps]$ ls -ltr dax*-rw-r--r-- 1 memmanuel memmanuel 284292096 Jan 26 12:43 dax-withoutindex.db-rw-r--r-- 1 memmanuel memmanuel 409865216 Jan 26 22:32 dax-withindex.db Note how the index also increased the size of the database dramatically. In SQLite is extremely simple to have several databases. Each database is just a connection against a file. Hence, there is no reason to merge all assets in the same database. You can split each asset in one database file and rely on the filesystem. Moving files to different servers and doing a backup will be easier too. It will be become really difficult to deal with multiple assets per database in SQLite, it will require an additional index to track the Asset ticker. So this is more a must rather than an optimization tip. Retrieve session or weekly data from SQLite into an in-memory array or list. Your data will then fly and you will use SQLite as a permanent data storage where you retrieve chunks of data. This will reduce the impact on the lack of performance of relational databases while still giving to you the advantages of using a relational database. Storing financial price data in a relational database is not the best idea in terms of performance. Financial markets data are time series of data, and its consumption is usually as long chains of data using basic search and retrieval queries. Despite this, having data in a relational database simplifies operations. So you can use it. The simple three optimization tips/patterns mentioned here will lead to better results: Create an index for the timestamp.Divide data sets into different databases (in SQLite, that is really simple).Retrieve subsets of data from the relational database and use later memory lists/arrays. Create an index for the timestamp. Divide data sets into different databases (in SQLite, that is really simple). Retrieve subsets of data from the relational database and use later memory lists/arrays. There is more information that might be relevant about the approach of using serialized arrays and on the always complex topic of dealing with time zones, but those would be material for other posts.
[ { "code": null, "e": 295, "s": 172, "text": "I am working on moderately large financial price data sets. By moderately large I mean less than 4 million rows per asset." }, { "code": null, "e": 475, "s": 295, "text": "4 million rows can cover the last 20 years of minute price bars done by a regular asset without extended trading hours — such as index futures contracts or regular cash stocks — ." }, { "code": null, "e": 824, "s": 475, "text": "When dealing with price bars, minute and 5-minute bars generate large datasets. If you would happen to deal with tick analysis then it would be huge instead of large, but tick data is really expensive to obtain, manage and monetize; and unless you are backtesting scalping strategies or working in the HFT industry their advantage would be dubious." }, { "code": null, "e": 1180, "s": 824, "text": "Although 4 million rows do not sound impressive, we need to understand that it is 4 million rows per asset. So to analyze all assets from Russell 2000 would mean 8 billion rows (now we are getting large). Add some European stock markets, your local country small and mid caps, commodities and forex and there you go: you just landed on the big data arena." }, { "code": null, "e": 1330, "s": 1180, "text": "There are more than 1700 regulated markets in the world, as soon as you start stockpiling intraday data the numbers become impressive — very fast — ." }, { "code": null, "e": 1589, "s": 1330, "text": "Bear in mind also that current trend is to extend all future contracts trading hours — Eurex began extended trading hours for FDAX futures since last January — , so the situation is not getting better in terms of the amount of data that needs to be analyzed." }, { "code": null, "e": 1694, "s": 1589, "text": "Now the question that every “financial data scientist” makes to himself: where and how do I put my data." }, { "code": null, "e": 1800, "s": 1694, "text": "A relational database is the first answer, probably not the most efficient, but the easiest one for sure." }, { "code": null, "e": 1858, "s": 1800, "text": "I can enumerate four options as main repository strategy:" }, { "code": null, "e": 1978, "s": 1858, "text": "SQL relational databases.Serialized storage of large arrays.Key/Value databases (such as Oracle Berkeley DB).CSV files." }, { "code": null, "e": 2004, "s": 1978, "text": "SQL relational databases." }, { "code": null, "e": 2040, "s": 2004, "text": "Serialized storage of large arrays." }, { "code": null, "e": 2090, "s": 2040, "text": "Key/Value databases (such as Oracle Berkeley DB)." }, { "code": null, "e": 2101, "s": 2090, "text": "CSV files." }, { "code": null, "e": 2218, "s": 2101, "text": "For obvious reasons I have discarded the last one, and for the other three I have evaluated just the first two ones." }, { "code": null, "e": 2592, "s": 2218, "text": "I have planned to explore the third one: a key/value database. Those databases are not truly mainstream but they can offer outstanding performances when dealing with simple data structures that are intensive in reading (which is the case for financial data). I really believe that it might be the best trade-off solution between serialized storage and relational databases." }, { "code": null, "e": 2710, "s": 2592, "text": "In this post, I focus on the first strategy. Before going into details we will revisit what data we are dealing with." }, { "code": null, "e": 2987, "s": 2710, "text": "Almost all data you are going to deal in financial markets will be price bars or candlesticks. There is a reason for this. The high/low/open/close structure of a financial price bar resembles the classic whiskers and box plots used in statistics but they are easier to obtain." }, { "code": null, "e": 3278, "s": 2987, "text": "I have used the word resemble because all the important information provided by a whiskers and box bar (quartiles and median) is not available in a financial candlestick. Quartiles and medians are not arbitrary values, they provide descriptive information about the variable under analysis." }, { "code": null, "e": 3858, "s": 3278, "text": "One might wonder why whisker and box bars are not used in financial markets (I think that its use might lead to useful and innovative price action insight), and the reason for that is simple. Candlestick charts are thought to have been used first during the 18th century by a Japanese rice trader named Munehisa Homma. If you are wondering if there were future contracts in the 18th century you would like to know that although the first modern future contract exchange was the Chicago Board of Trade there were established future markets in Europe and Japan in the 17th century." }, { "code": null, "e": 4428, "s": 3858, "text": "Getting the maximum, minimum, opening and close prices to build a candlestick for a given period is extremely easy. You just need the list of all trades during a certain period. Now trading is electronic and takes place in an ordered manner, but bear in mind that it has not been always the case. Electronic trading is relatively modern (it started to gain relevance during the 80s). Before that, trading pits were the norm and assets were traded in the pit just at certain hours. The notion of a continuous trading market as we know it was not applicable at that time." }, { "code": null, "e": 4808, "s": 4428, "text": "Even in the current case when almost all trading takes place electronically, storing and analyzing all trades that take place in a given period to build whiskers and box chart is challenging (doable, but challenging). It implies either a strict continuous track of the order book — reading the tape — , or the less strict way of consolidating shorter timeframes into larger ones." }, { "code": null, "e": 5559, "s": 4808, "text": "By using candlesticks instead, you end up with information that will lead you to something similar to quartiles and median (please notice that something similar is highlighted). It is what is called the price action of candlesticks or the candlesticks patterns, which, in reality, is just an interpretative analysis on where the price was relevant among all candlestick range. So a large whisker and a small body (such as the one you find in a dragonfly) will imply price rejection, were most of the time the price has been concentrated on the body part and when it tried to move below or above that area it was quickly rejected. That is the kind of conclusions you can get out of a candlestick (again, when reading it within a given market context)." }, { "code": null, "e": 5821, "s": 5559, "text": "Storing interval price information for open/close/low/high will, therefore, enable a certain degree of price action analysis, and according to experience, certain patterns within a given context have statistical relevance and will lead to profitable strategies." }, { "code": null, "e": 5927, "s": 5821, "text": "Now we understand why candlesticks are used, we can propose a simple data model to store our information." }, { "code": null, "e": 6214, "s": 5927, "text": "CREATE TABLE candlestick ( “id” INTEGER PRIMARY KEY AUTOINCREMENT, “timezone” TEXT NOT NULL, “timestamp” DATETIME NOT NULL, “open” DECIMAL(12, 6) NOT NULL, “high” DECIMAL(12, 6) NOT NULL, “low” DECIMAL(12, 6) NOT NULL, “close” DECIMAL(12, 6) NOT NULL, “volume” DECIMAL(12, 6) NOT NULL);" }, { "code": null, "e": 6483, "s": 6214, "text": "I am sure you are not impressed with this simple data model, but even this one can be challenged. We will not discuss the timezone column (I plan to write another post on time zones and data), but the usage of timestamp is already relevant and have performance issues." }, { "code": null, "e": 6620, "s": 6483, "text": "From a usability point of view, this way of storing financial information is simple and well structured. Querying data is really simple:" }, { "code": null, "e": 7475, "s": 6620, "text": "sqlite> select * from candlestick where date(timestamp)='2018-01-12' limit 10;3489458|Europe/Berlin|2018-01-12 07:00:00+01:00|13243.5|13245.5|13234.5|13245.5|2943489459|Europe/Berlin|2018-01-12 07:01:00+01:00|13244.5|13250|13243|13245|1493489460|Europe/Berlin|2018-01-12 07:02:00+01:00|13244.5|13246|13242.5|13244|393489461|Europe/Berlin|2018-01-12 07:03:00+01:00|13242.5|13243.5|13239|13241.5|643489462|Europe/Berlin|2018-01-12 07:04:00+01:00|13241|13241|13235.5|13236.5|613489463|Europe/Berlin|2018-01-12 07:05:00+01:00|13236.5|13240|13236|13239.5|493489464|Europe/Berlin|2018-01-12 07:06:00+01:00|13239|13241.5|13237|13240|493489465|Europe/Berlin|2018-01-12 07:07:00+01:00|13238.5|13241|13237|13239|433489466|Europe/Berlin|2018-01-12 07:08:00+01:00|13239|13239|13236.5|13237|243489467|Europe/Berlin|2018-01-12 07:09:00+01:00|13237|13239|13237|13239|11" }, { "code": null, "e": 7531, "s": 7475, "text": "Getting the opening price of a given session is simple:" }, { "code": null, "e": 7692, "s": 7531, "text": "sqlite> select * from candlestick where date(timestamp)='2018-01-12' limit 1;3489458|Europe/Berlin|2018-01-12 07:00:00+01:00|13243.5|13245.5|13234.5|13245.5|294" }, { "code": null, "e": 7728, "s": 7692, "text": "So it is getting the closing price:" }, { "code": null, "e": 7904, "s": 7728, "text": "sqlite> select * from candlestick where date(timestamp)='2018-01-11' order by timestamp desc limit 1;3489457|Europe/Berlin|2018-01-11 21:03:00+01:00|13241|13241|13241|13241|25" }, { "code": null, "e": 7968, "s": 7904, "text": "But this way has some performance issues we will discuss later." }, { "code": null, "e": 8347, "s": 7968, "text": "Note that we have used datetime field to store the timestamp. We could also use separate fields for year, month, day, hour and minute, but it would complicate dealing with datetime types in Python (or Java) later. Those complex types might pose performance issues but also help dealing with times, time zones, time offsets, etc. It also enables using time ranges in SQL queries." }, { "code": null, "e": 8398, "s": 8347, "text": "Using this approach, there are performance issues:" }, { "code": null, "e": 8697, "s": 8398, "text": "When doing the bulk load of the data (using Python and an ORM to ensure that timestamps are properly handled in SQLite) it takes 14 minutes on a 1 core VPS server.Getting all data for a given session takes 5 seconds on the same VPS server. A similar result for getting the opening or closing price." }, { "code": null, "e": 8861, "s": 8697, "text": "When doing the bulk load of the data (using Python and an ORM to ensure that timestamps are properly handled in SQLite) it takes 14 minutes on a 1 core VPS server." }, { "code": null, "e": 8997, "s": 8861, "text": "Getting all data for a given session takes 5 seconds on the same VPS server. A similar result for getting the opening or closing price." }, { "code": null, "e": 9291, "s": 8997, "text": "14 minutes sounds like too much but bulk loads are not common and it might be acceptable. Even if a more optimized way to load data can be found it is not an important point. Just grab a cup of coffee or program batch loads for the initial data provisioning, that is going to happen only once." }, { "code": null, "e": 9552, "s": 9291, "text": "On the contrary, 5 seconds might not sound like a big deal but it is. Remember that we are dealing here with multi-asset Monte Carlo simulation scenarios. That means thousands of rounds. So 5 seconds by thousands is way too much time. We need to optimize here." }, { "code": null, "e": 9680, "s": 9552, "text": "Although I am not going to cover the serialized strategy in this post, I will share some time comparison about both strategies:" }, { "code": null, "e": 9944, "s": 9680, "text": "# Bulk provisioning of 3.5Million price bars:SQLite + Pyhon ORM: 15 min Serialized Stored Arrays + ANSI C: 1.5 min# Retrieve a given specific 1 minute price bar:SQLite + Pyhon ORM: 5 secondsSerialized Stored Arrays + ANSI C: Negligible (microseconds)" }, { "code": null, "e": 10153, "s": 9944, "text": "As stated before, the real issue in these environments is the retrieval time. In serialized arrays, it can be as low as microseconds because a strategy can be defined to allocate space in memory for all data." }, { "code": null, "e": 10327, "s": 10153, "text": "If you assume that all months have 31 days retrieving a given minute is just a super simple memory lookup operation. There is no such thing as indexing or search operations." }, { "code": null, "e": 10648, "s": 10327, "text": "Getting the closing or opening price for a given session might be a bit more challenging if we do not know the trading hours (even if we know them, there might be exceptions like trading halts or nonconformities in data), but we can then traverse a specific day. Traversing the array for all daily data is fast and easy." }, { "code": null, "e": 11159, "s": 10648, "text": "We might overcomplicate the analysis introducing how databases with built-in optimization capabilities can speed up these figures. An Oracle database will perform better —if your project can allocate the cost of 150000$/year for a DBA optimization specialist — , but the take away here is that a simple lookup into an array (the serialized approach) will never be beaten by any relational database. As a drawback, a relational database makes querying and moving data much easier than storing serialized arrays." }, { "code": null, "e": 11592, "s": 11159, "text": "I use SQLite every time it is possible because it is extremely simple and easy to use and backup. Despite many people state that it is a too basic database it can handle huge large sets. Its major drawback is its lack of page or area locking — which leads to performance issues in applications that write a lot — . Other than that, it usually performs much better than expected, it is really lightweight and it has zero maintenance." }, { "code": null, "e": 11699, "s": 11592, "text": "The simplest and easiest optimization is to use an index (and the only one you can actually do in SQLite)." }, { "code": null, "e": 11936, "s": 11699, "text": "sqlite> create index idx_timestamp on candlestick(timestamp);sqlite> select * from candlestick where date(timestamp)='2018-01-11' order by timestamp desc limit 1;3489457|Europe/Berlin|2018-01-11 21:03:00+01:00|13241|13241|13241|13241|25" }, { "code": null, "e": 12026, "s": 11936, "text": "Now the search takes less than one second. It is a significative performance improvement." }, { "code": null, "e": 12204, "s": 12026, "text": "[user@host gaps]$ ls -ltr dax*-rw-r--r-- 1 memmanuel memmanuel 284292096 Jan 26 12:43 dax-withoutindex.db-rw-r--r-- 1 memmanuel memmanuel 409865216 Jan 26 22:32 dax-withindex.db" }, { "code": null, "e": 12277, "s": 12204, "text": "Note how the index also increased the size of the database dramatically." }, { "code": null, "e": 12807, "s": 12277, "text": "In SQLite is extremely simple to have several databases. Each database is just a connection against a file. Hence, there is no reason to merge all assets in the same database. You can split each asset in one database file and rely on the filesystem. Moving files to different servers and doing a backup will be easier too. It will be become really difficult to deal with multiple assets per database in SQLite, it will require an additional index to track the Asset ticker. So this is more a must rather than an optimization tip." }, { "code": null, "e": 13147, "s": 12807, "text": "Retrieve session or weekly data from SQLite into an in-memory array or list. Your data will then fly and you will use SQLite as a permanent data storage where you retrieve chunks of data. This will reduce the impact on the lack of performance of relational databases while still giving to you the advantages of using a relational database." }, { "code": null, "e": 13391, "s": 13147, "text": "Storing financial price data in a relational database is not the best idea in terms of performance. Financial markets data are time series of data, and its consumption is usually as long chains of data using basic search and retrieval queries." }, { "code": null, "e": 13484, "s": 13391, "text": "Despite this, having data in a relational database simplifies operations. So you can use it." }, { "code": null, "e": 13572, "s": 13484, "text": "The simple three optimization tips/patterns mentioned here will lead to better results:" }, { "code": null, "e": 13772, "s": 13572, "text": "Create an index for the timestamp.Divide data sets into different databases (in SQLite, that is really simple).Retrieve subsets of data from the relational database and use later memory lists/arrays." }, { "code": null, "e": 13807, "s": 13772, "text": "Create an index for the timestamp." }, { "code": null, "e": 13885, "s": 13807, "text": "Divide data sets into different databases (in SQLite, that is really simple)." }, { "code": null, "e": 13974, "s": 13885, "text": "Retrieve subsets of data from the relational database and use later memory lists/arrays." } ]
Node.js fs.chmodSync() Method - GeeksforGeeks
08 Oct, 2021 The fs.chmodSync() method is used to synchronously change the permissions of a given path. These permissions can be specified using string constants or octal numbers that correspond to their respective file modes.Note: The Windows platform only supports the changing of the write permission. It also does not support the distinction between the permissions of user, group or others.Syntax: fs.chmodSync( path, mode ) Parameters: This method accepts two parameters as mentioned above and described below: path: It is a string, Buffer or URL that denotes the path of the file of which the permission has to be changed. mode: It is string or octal integer constant that denotes the permission to be granted. The logical OR operator can be used to separate multiple permissions. Below examples illustrate the fs.chmodSync() method in Node.js:Example 1: This example shows the usage of string constants and OR operator to give the file permissions. javascript // Node.js program to demonstrate the// fs.chmodSync method // Import the filesystem moduleconst fs = require('fs'); // Allowing only read permissionconsole.log("Giving only read permission to user");fs.chmodSync("example.txt", fs.constants.S_IRUSR); // Check the file modeconsole.log("Current File Mode:", fs.statSync("example.txt").mode); // Reading the fileconsole.log("File Contents:", fs.readFileSync("example.txt", 'utf8')); // Trying to write to filetry { console.log("Trying to write to file"); fs.writeFileSync('example.txt', "Hello");}catch (e) { console.log("Error Found, Code:", e.code);} // Allowing both read and write permissionconsole.log("\nGiving both read and write" + " permissions to user"); fs.chmodSync("example.txt", fs.constants.S_IRUSR | fs.constants.S_IWUSR); // Check the file modeconsole.log("Current File Mode:", fs.statSync("example.txt").mode); console.log("Trying to write to file");fs.writeFileSync('example.txt', "World"); console.log("File Contents:", fs.readFileSync("example.txt", 'utf8')); Output: Giving only read permission to user Current File Mode: 33024 File Contents: Hello Trying to write to file Error Found, Code: EACCES Giving both read and write permissions to user Current File Mode: 33152 Trying to write to file File Contents: World Example 2: This example shows the usage of octal integer constants to give the file permissions. javascript // Node.js program to demonstrate the// fs.chmodSync method // Import the filesystem moduleconst fs = require('fs'); // Allowing only read permissionconsole.log("Giving only read permission to everyone");fs.chmodSync("example.txt", 0o444); // Check the file modeconsole.log("Current File Mode:", fs.statSync("example.txt").mode); // Reading the fileconsole.log("File Contents:", fs.readFileSync("example.txt", 'utf8')); // Trying to write to filetry { console.log("Trying to write to file"); fs.writeFileSync('example.txt', "Hello");}catch (e) { console.log("Error Found, Code:", e.code);} // Allowing both read and write permissionconsole.log("\nGiving both read and " + "write permission to everyone");fs.chmodSync("example.txt", 0o666); // Check the file modeconsole.log("Current File Mode:", fs.statSync("example.txt").mode); console.log("Trying to write to file");fs.writeFileSync('example.txt', "World"); console.log("File Contents:", fs.readFileSync("example.txt", 'utf8')); Output: Giving only read permission to everyone Current File Mode: 33060 File Contents: Hello Trying to write to file Error Found, Code: EACCES Giving both read and write permission to everyone Current File Mode: 33206 Trying to write to file File Contents: World Reference: https://nodejs.org/api/fs.html#fs_fs_chmodsync_path_mode nidhi_biet akshaysingh98088 Node.js-fs-module Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Express.js express.Router() Function Mongoose Populate() Method Express.js res.json() Function Express.js res.render() Function Mongoose | findByIdAndUpdate() Function Express.js express.Router() Function How to set input type date in dd-mm-yyyy format using HTML ? Differences between Functional Components and Class Components in React How to create footer to stay at the bottom of a Web page? How to float three div side by side using CSS?
[ { "code": null, "e": 24119, "s": 24091, "text": "\n08 Oct, 2021" }, { "code": null, "e": 24511, "s": 24119, "text": "The fs.chmodSync() method is used to synchronously change the permissions of a given path. These permissions can be specified using string constants or octal numbers that correspond to their respective file modes.Note: The Windows platform only supports the changing of the write permission. It also does not support the distinction between the permissions of user, group or others.Syntax: " }, { "code": null, "e": 24538, "s": 24511, "text": "fs.chmodSync( path, mode )" }, { "code": null, "e": 24627, "s": 24538, "text": "Parameters: This method accepts two parameters as mentioned above and described below: " }, { "code": null, "e": 24740, "s": 24627, "text": "path: It is a string, Buffer or URL that denotes the path of the file of which the permission has to be changed." }, { "code": null, "e": 24898, "s": 24740, "text": "mode: It is string or octal integer constant that denotes the permission to be granted. The logical OR operator can be used to separate multiple permissions." }, { "code": null, "e": 25068, "s": 24898, "text": "Below examples illustrate the fs.chmodSync() method in Node.js:Example 1: This example shows the usage of string constants and OR operator to give the file permissions. " }, { "code": null, "e": 25079, "s": 25068, "text": "javascript" }, { "code": "// Node.js program to demonstrate the// fs.chmodSync method // Import the filesystem moduleconst fs = require('fs'); // Allowing only read permissionconsole.log(\"Giving only read permission to user\");fs.chmodSync(\"example.txt\", fs.constants.S_IRUSR); // Check the file modeconsole.log(\"Current File Mode:\", fs.statSync(\"example.txt\").mode); // Reading the fileconsole.log(\"File Contents:\", fs.readFileSync(\"example.txt\", 'utf8')); // Trying to write to filetry { console.log(\"Trying to write to file\"); fs.writeFileSync('example.txt', \"Hello\");}catch (e) { console.log(\"Error Found, Code:\", e.code);} // Allowing both read and write permissionconsole.log(\"\\nGiving both read and write\" + \" permissions to user\"); fs.chmodSync(\"example.txt\", fs.constants.S_IRUSR | fs.constants.S_IWUSR); // Check the file modeconsole.log(\"Current File Mode:\", fs.statSync(\"example.txt\").mode); console.log(\"Trying to write to file\");fs.writeFileSync('example.txt', \"World\"); console.log(\"File Contents:\", fs.readFileSync(\"example.txt\", 'utf8'));", "e": 26141, "s": 25079, "text": null }, { "code": null, "e": 26151, "s": 26141, "text": "Output: " }, { "code": null, "e": 26401, "s": 26151, "text": "Giving only read permission to user\nCurrent File Mode: 33024\nFile Contents: Hello\nTrying to write to file\nError Found, Code: EACCES\n\nGiving both read and write permissions to user\nCurrent File Mode: 33152\nTrying to write to file\nFile Contents: World" }, { "code": null, "e": 26499, "s": 26401, "text": "Example 2: This example shows the usage of octal integer constants to give the file permissions. " }, { "code": null, "e": 26510, "s": 26499, "text": "javascript" }, { "code": "// Node.js program to demonstrate the// fs.chmodSync method // Import the filesystem moduleconst fs = require('fs'); // Allowing only read permissionconsole.log(\"Giving only read permission to everyone\");fs.chmodSync(\"example.txt\", 0o444); // Check the file modeconsole.log(\"Current File Mode:\", fs.statSync(\"example.txt\").mode); // Reading the fileconsole.log(\"File Contents:\", fs.readFileSync(\"example.txt\", 'utf8')); // Trying to write to filetry { console.log(\"Trying to write to file\"); fs.writeFileSync('example.txt', \"Hello\");}catch (e) { console.log(\"Error Found, Code:\", e.code);} // Allowing both read and write permissionconsole.log(\"\\nGiving both read and \" + \"write permission to everyone\");fs.chmodSync(\"example.txt\", 0o666); // Check the file modeconsole.log(\"Current File Mode:\", fs.statSync(\"example.txt\").mode); console.log(\"Trying to write to file\");fs.writeFileSync('example.txt', \"World\"); console.log(\"File Contents:\", fs.readFileSync(\"example.txt\", 'utf8'));", "e": 27524, "s": 26510, "text": null }, { "code": null, "e": 27534, "s": 27524, "text": "Output: " }, { "code": null, "e": 27791, "s": 27534, "text": "Giving only read permission to everyone\nCurrent File Mode: 33060\nFile Contents: Hello\nTrying to write to file\nError Found, Code: EACCES\n\nGiving both read and write permission to everyone\nCurrent File Mode: 33206\nTrying to write to file\nFile Contents: World" }, { "code": null, "e": 27860, "s": 27791, "text": "Reference: https://nodejs.org/api/fs.html#fs_fs_chmodsync_path_mode " }, { "code": null, "e": 27871, "s": 27860, "text": "nidhi_biet" }, { "code": null, "e": 27888, "s": 27871, "text": "akshaysingh98088" }, { "code": null, "e": 27906, "s": 27888, "text": "Node.js-fs-module" }, { "code": null, "e": 27914, "s": 27906, "text": "Node.js" }, { "code": null, "e": 27931, "s": 27914, "text": "Web Technologies" }, { "code": null, "e": 28029, "s": 27931, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28038, "s": 28029, "text": "Comments" }, { "code": null, "e": 28051, "s": 28038, "text": "Old Comments" }, { "code": null, "e": 28088, "s": 28051, "text": "Express.js express.Router() Function" }, { "code": null, "e": 28115, "s": 28088, "text": "Mongoose Populate() Method" }, { "code": null, "e": 28146, "s": 28115, "text": "Express.js res.json() Function" }, { "code": null, "e": 28179, "s": 28146, "text": "Express.js res.render() Function" }, { "code": null, "e": 28219, "s": 28179, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 28256, "s": 28219, "text": "Express.js express.Router() Function" }, { "code": null, "e": 28317, "s": 28256, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 28389, "s": 28317, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28447, "s": 28389, "text": "How to create footer to stay at the bottom of a Web page?" } ]
Print the longest leaf to leaf path in a Binary tree
Difficulty Level : Medium C++ Java Python3 C# Javascript // C++ program to print the longest leaf to leaf// path#include <bits/stdc++.h>using namespace std; // Tree node structure used in the programstruct Node { int data; Node *left, *right;}; struct Node* newNode(int data){ struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node);} // Function to find height of a treeint height(Node* root, int& ans, Node*(&k), int& lh, int& rh, int& f){ if (root == NULL) return 0; int left_height = height(root->left, ans, k, lh, rh, f); int right_height = height(root->right, ans, k, lh, rh, f); // update the answer, because diameter of a // tree is nothing but maximum value of // (left_height + right_height + 1) for each node if (ans < 1 + left_height + right_height) { ans = 1 + left_height + right_height; // save the root, this will help us finding the // left and the right part of the diameter k = root; // save the height of left & right subtree as well. lh = left_height; rh = right_height; } return 1 + max(left_height, right_height);} // prints the root to leaf pathvoid printArray(int ints[], int len, int f){ int i; // print left part of the path in reverse order if (f == 0) { for (i = len - 1; i >= 0; i--) { printf("%d ", ints[i]); } } // print right part of the path else if (f == 1) { for (i = 0; i < len; i++) { printf("%d ", ints[i]); } }} // this function finds out all the root to leaf pathsvoid printPathsRecur(Node* node, int path[], int pathLen, int max, int& f){ if (node == NULL) return; // append this node to the path array path[pathLen] = node->data; pathLen++; // If it's a leaf, so print the path that led to here if (node->left == NULL && node->right == NULL) { // print only one path which is equal to the // height of the tree. if (pathLen == max && (f == 0 || f == 1)) { printArray(path, pathLen, f); f = 2; } } else { // otherwise try both subtrees printPathsRecur(node->left, path, pathLen, max, f); printPathsRecur(node->right, path, pathLen, max, f); }} // Computes the diameter of a binary tree with given root.void diameter(Node* root){ if (root == NULL) return; // lh will store height of left subtree // rh will store height of right subtree int ans = INT_MIN, lh = 0, rh = 0; // f is a flag whose value helps in printing // left & right part of the diameter only once int f = 0; Node* k; int height_of_tree = height(root, ans, k, lh, rh, f); int lPath[100], pathlen = 0; // print the left part of the diameter printPathsRecur(k->left, lPath, pathlen, lh, f); printf("%d ", k->data); int rPath[100]; f = 1; // print the right part of the diameter printPathsRecur(k->right, rPath, pathlen, rh, f);} // Driver codeint main(){ // Enter the binary tree ... // 1 // / \ // 2 3 // / \ // 4 5 // \ / \ // 8 6 7 // / // 9 struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->left->right->left = newNode(6); root->left->right->right = newNode(7); root->left->left->right = newNode(8); root->left->left->right->left = newNode(9); diameter(root); return 0;} // Java program to print the longest leaf to leaf// pathimport java.io.*; // Tree node structure used in the programclass Node{ int data; Node left, right; Node(int val) { data = val; left = right = null; }}class GFG{ static int ans, lh, rh, f; static Node k; public static Node Root; // Function to find height of a tree static int height(Node root) { if (root == null) return 0; int left_height = height(root.left); int right_height = height(root.right); // update the answer, because diameter of a // tree is nothing but maximum value of // (left_height + right_height + 1) for each node if (ans < 1 + left_height + right_height) { ans = 1 + left_height + right_height; // save the root, this will help us finding the // left and the right part of the diameter k = root; // save the height of left & right subtree as well. lh = left_height; rh = right_height; } return 1 + Math.max(left_height, right_height); } // prints the root to leaf path static void printArray(int[] ints, int len) { int i; // print left part of the path in reverse order if(f == 0) { for(i = len - 1; i >= 0; i--) { System.out.print(ints[i] + " "); } } else if(f == 1) { for (i = 0; i < len; i++) { System.out.print(ints[i] + " "); } } } // this function finds out all the root to leaf paths static void printPathsRecur(Node node, int[] path, int pathLen, int max) { if (node == null) return; // append this node to the path array path[pathLen] = node.data; pathLen++; // If it's a leaf, so print the path that led to here if (node.left == null && node.right == null) { // print only one path which is equal to the // height of the tree. if (pathLen == max && (f == 0 || f == 1)) { printArray(path, pathLen); f = 2; } } else { // otherwise try both subtrees printPathsRecur(node.left, path, pathLen, max); printPathsRecur(node.right, path, pathLen, max); } } // Computes the diameter of a binary tree with given root. static void diameter(Node root) { if (root == null) return; // lh will store height of left subtree // rh will store height of right subtree ans = Integer.MIN_VALUE; lh = 0; rh = 0; // f is a flag whose value helps in printing // left & right part of the diameter only once f = 0; int height_of_tree = height(root); int[] lPath = new int[100]; int pathlen = 0; // print the left part of the diameter printPathsRecur(k.left, lPath, pathlen, lh); System.out.print(k.data+" "); int[] rPath = new int[100]; f = 1; // print the right part of the diameter printPathsRecur(k.right, rPath, pathlen, rh); } // Driver code public static void main (String[] args) { // Enter the binary tree ... // 1 // / \ // 2 3 // / \ // 4 5 // \ / \ // 8 6 7 // / // 9 GFG.Root = new Node(1); GFG.Root.left = new Node(2); GFG.Root.right = new Node(3); GFG.Root.left.left = new Node(4); GFG.Root.left.right = new Node(5); GFG.Root.left.right.left = new Node(6); GFG.Root.left.right.right = new Node(7); GFG.Root.left.left.right = new Node(8); GFG.Root.left.left.right.left = new Node(9); diameter(Root); }} // This code is contributed by rag2127 # Python3 program to print the longest# leaf to leaf path # Tree node structure used in the programclass Node: def __init__(self, x): self.data = x self.left = None self.right = None # Function to find height of a treedef height(root): global ans, k, lh, rh, f if (root == None): return 0 left_height = height(root.left) right_height = height(root.right) # Update the answer, because diameter of a # tree is nothing but maximum value of # (left_height + right_height + 1) for each node if (ans < 1 + left_height + right_height): ans = 1 + left_height + right_height # Save the root, this will help us finding the # left and the right part of the diameter k = root # Save the height of left & right # subtree as well. lh = left_height rh = right_height return 1 + max(left_height, right_height) # Prints the root to leaf pathdef printArray(ints, lenn, f): # Print left part of the path # in reverse order if (f == 0): for i in range(lenn - 1, -1, -1): print(ints[i], end = " ") # Print right part of the path elif (f == 1): for i in range(lenn): print(ints[i], end = " ") # This function finds out all the# root to leaf pathsdef printPathsRecur(node, path, maxm, pathlen): global f if (node == None): return # Append this node to the path array path[pathlen] = node.data pathlen += 1 # If it's a leaf, so print the # path that led to here if (node.left == None and node.right == None): # Print only one path which is equal to the # height of the tree. # print(pathlen,"---",maxm) if (pathlen == maxm and (f == 0 or f == 1)): # print("innn") printArray(path, pathlen,f) f = 2 else: # Otherwise try both subtrees printPathsRecur(node.left, path, maxm, pathlen) printPathsRecur(node.right, path, maxm, pathlen) # Computes the diameter of a binary# tree with given root.def diameter(root): global ans, lh, rh, f, k, pathLen if (root == None): return # f is a flag whose value helps in printing # left & right part of the diameter only once height_of_tree = height(root) lPath = [0 for i in range(100)] # print(lh,"--",rh) # Print the left part of the diameter printPathsRecur(k.left, lPath, lh, 0); print(k.data, end = " ") rPath = [0 for i in range(100)] f = 1 # Print the right part of the diameter printPathsRecur(k.right, rPath, rh, 0) # Driver codeif __name__ == '__main__': k, lh, rh, f, ans, pathLen = None, 0, 0, 0, 0 - 10 ** 19, 0 # Enter the binary tree ... # 1 # / \ # 2 3 # / \ # 4 5 # \ / \ # 8 6 7 # / # 9 root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.left.right.left = Node(6) root.left.right.right = Node(7) root.left.left.right = Node(8) root.left.left.right.left = Node(9) diameter(root) # This code is contributed by mohit kumar 29 // C# program to print the longest leaf to leaf// pathusing System; // Tree node structure used in the programpublic class Node{ public int data; public Node left, right; public Node(int val) { data = val; left = right = null; }} public class GFG{ static int ans, lh, rh, f; static Node k; public static Node Root; // Function to find height of a tree static int height(Node root) { if (root == null) return 0; int left_height = height(root.left); int right_height = height(root.right); // update the answer, because diameter of a // tree is nothing but maximum value of // (left_height + right_height + 1) for each node if (ans < 1 + left_height + right_height) { ans = 1 + left_height + right_height; // save the root, this will help us finding the // left and the right part of the diameter k = root; // save the height of left & right subtree as well. lh = left_height; rh = right_height; } return 1 + Math.Max(left_height, right_height); } // prints the root to leaf path static void printArray(int[] ints, int len) { int i; // print left part of the path in reverse order if(f == 0) { for(i = len - 1; i >= 0; i--) { Console.Write(ints[i] + " "); } } else if(f == 1) { for (i = 0; i < len; i++) { Console.Write(ints[i] + " "); } } } // this function finds out all the root to leaf paths static void printPathsRecur(Node node, int[] path,int pathLen, int max) { if (node == null) return; // append this node to the path array path[pathLen] = node.data; pathLen++; // If it's a leaf, so print the path that led to here if (node.left == null && node.right == null) { // print only one path which is equal to the // height of the tree. if (pathLen == max && (f == 0 || f == 1)) { printArray(path, pathLen); f = 2; } } else { // otherwise try both subtrees printPathsRecur(node.left, path, pathLen, max); printPathsRecur(node.right, path, pathLen, max); } } // Computes the diameter of a binary tree with given root. static void diameter(Node root) { if (root == null) return; // lh will store height of left subtree // rh will store height of right subtree ans = Int32.MinValue; lh = 0; rh = 0; // f is a flag whose value helps in printing // left & right part of the diameter only once f = 0; int height_of_tree= height(root); int[] lPath = new int[100]; int pathlen = 0 * height_of_tree; // print the left part of the diameter printPathsRecur(k.left, lPath, pathlen, lh); Console.Write(k.data+" "); int[] rPath = new int[100]; f = 1; // print the right part of the diameter printPathsRecur(k.right, rPath, pathlen, rh); } // Driver code static public void Main (){ // Enter the binary tree ... // 1 // / \ // 2 3 // / \ // 4 5 // \ / \ // 8 6 7 // / // 9 GFG.Root = new Node(1); GFG.Root.left = new Node(2); GFG.Root.right = new Node(3); GFG.Root.left.left = new Node(4); GFG.Root.left.right = new Node(5); GFG.Root.left.right.left = new Node(6); GFG.Root.left.right.right = new Node(7); GFG.Root.left.left.right = new Node(8); GFG.Root.left.left.right.left = new Node(9); diameter(Root); }} // This code is contributed by avanitrachhadiya2155 <script>// Javascript program to print the longest leaf to leaf// path // Tree node structure used in the programclass Node{ constructor(val) { this.data=val; this.left = this.right = null; }} let ans, lh, rh, f;let k;let Root; // Function to find height of a treefunction height(root){ if (root == null) return 0; let left_height = height(root.left); let right_height = height(root.right); // update the answer, because diameter of a // tree is nothing but maximum value of // (left_height + right_height + 1) for each node if (ans < 1 + left_height + right_height) { ans = 1 + left_height + right_height; // save the root, this will help us finding the // left and the right part of the diameter k = root; // save the height of left & right subtree as well. lh = left_height; rh = right_height; } return 1 + Math.max(left_height, right_height);} // prints the root to leaf pathfunction printArray(ints,len){ let i; // print left part of the path in reverse order if(f == 0) { for(i = len - 1; i >= 0; i--) { document.write(ints[i] + " "); } } else if(f == 1) { for (i = 0; i < len; i++) { document.write(ints[i] + " "); } }} // this function finds out all the root to leaf pathsfunction printPathsRecur(node,path,pathLen,max){ if (node == null) return; // append this node to the path array path[pathLen] = node.data; pathLen++; // If it's a leaf, so print the path that led to here if (node.left == null && node.right == null) { // print only one path which is equal to the // height of the tree. if (pathLen == max && (f == 0 || f == 1)) { printArray(path, pathLen); f = 2; } } else { // otherwise try both subtrees printPathsRecur(node.left, path, pathLen, max); printPathsRecur(node.right, path, pathLen, max); }} // Computes the diameter of a binary tree with given root.function diameter(root){ if (root == null) return; // lh will store height of left subtree // rh will store height of right subtree ans = Number.MIN_VALUE; lh = 0; rh = 0; // f is a flag whose value helps in printing // left & right part of the diameter only once f = 0; let height_of_tree = height(root); let lPath = new Array(100); let pathlen = 0; // print the left part of the diameter printPathsRecur(k.left, lPath, pathlen, lh); document.write(k.data+" "); let rPath = new Array(100); f = 1; // print the right part of the diameter printPathsRecur(k.right, rPath, pathlen, rh);} // Driver code // Enter the binary tree ...// 1// / \ // 2 3// / \ // 4 5// \ / \// 8 6 7// /// 9Root = new Node(1);Root.left = new Node(2);Root.right = new Node(3);Root.left.left = new Node(4);Root.left.right = new Node(5);Root.left.right.left = new Node(6);Root.left.right.right = new Node(7);Root.left.left.right = new Node(8);Root.left.left.right.left = new Node(9);diameter(Root); // This code is contributed by patel2127</script> Time complexity: O(n) where n is size of binary tree Auxiliary Space: O(h) where h is the height of binary tree. mohit kumar 29 rag2127 avanitrachhadiya2155 patel2127 technophpfij Binary Tree Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 26, "s": 0, "text": "Difficulty Level :\nMedium" }, { "code": null, "e": 30, "s": 26, "text": "C++" }, { "code": null, "e": 35, "s": 30, "text": "Java" }, { "code": null, "e": 43, "s": 35, "text": "Python3" }, { "code": null, "e": 46, "s": 43, "text": "C#" }, { "code": null, "e": 57, "s": 46, "text": "Javascript" }, { "code": "// C++ program to print the longest leaf to leaf// path#include <bits/stdc++.h>using namespace std; // Tree node structure used in the programstruct Node { int data; Node *left, *right;}; struct Node* newNode(int data){ struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node);} // Function to find height of a treeint height(Node* root, int& ans, Node*(&k), int& lh, int& rh, int& f){ if (root == NULL) return 0; int left_height = height(root->left, ans, k, lh, rh, f); int right_height = height(root->right, ans, k, lh, rh, f); // update the answer, because diameter of a // tree is nothing but maximum value of // (left_height + right_height + 1) for each node if (ans < 1 + left_height + right_height) { ans = 1 + left_height + right_height; // save the root, this will help us finding the // left and the right part of the diameter k = root; // save the height of left & right subtree as well. lh = left_height; rh = right_height; } return 1 + max(left_height, right_height);} // prints the root to leaf pathvoid printArray(int ints[], int len, int f){ int i; // print left part of the path in reverse order if (f == 0) { for (i = len - 1; i >= 0; i--) { printf(\"%d \", ints[i]); } } // print right part of the path else if (f == 1) { for (i = 0; i < len; i++) { printf(\"%d \", ints[i]); } }} // this function finds out all the root to leaf pathsvoid printPathsRecur(Node* node, int path[], int pathLen, int max, int& f){ if (node == NULL) return; // append this node to the path array path[pathLen] = node->data; pathLen++; // If it's a leaf, so print the path that led to here if (node->left == NULL && node->right == NULL) { // print only one path which is equal to the // height of the tree. if (pathLen == max && (f == 0 || f == 1)) { printArray(path, pathLen, f); f = 2; } } else { // otherwise try both subtrees printPathsRecur(node->left, path, pathLen, max, f); printPathsRecur(node->right, path, pathLen, max, f); }} // Computes the diameter of a binary tree with given root.void diameter(Node* root){ if (root == NULL) return; // lh will store height of left subtree // rh will store height of right subtree int ans = INT_MIN, lh = 0, rh = 0; // f is a flag whose value helps in printing // left & right part of the diameter only once int f = 0; Node* k; int height_of_tree = height(root, ans, k, lh, rh, f); int lPath[100], pathlen = 0; // print the left part of the diameter printPathsRecur(k->left, lPath, pathlen, lh, f); printf(\"%d \", k->data); int rPath[100]; f = 1; // print the right part of the diameter printPathsRecur(k->right, rPath, pathlen, rh, f);} // Driver codeint main(){ // Enter the binary tree ... // 1 // / \\ // 2 3 // / \\ // 4 5 // \\ / \\ // 8 6 7 // / // 9 struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->left->right->left = newNode(6); root->left->right->right = newNode(7); root->left->left->right = newNode(8); root->left->left->right->left = newNode(9); diameter(root); return 0;}", "e": 3734, "s": 57, "text": null }, { "code": "// Java program to print the longest leaf to leaf// pathimport java.io.*; // Tree node structure used in the programclass Node{ int data; Node left, right; Node(int val) { data = val; left = right = null; }}class GFG{ static int ans, lh, rh, f; static Node k; public static Node Root; // Function to find height of a tree static int height(Node root) { if (root == null) return 0; int left_height = height(root.left); int right_height = height(root.right); // update the answer, because diameter of a // tree is nothing but maximum value of // (left_height + right_height + 1) for each node if (ans < 1 + left_height + right_height) { ans = 1 + left_height + right_height; // save the root, this will help us finding the // left and the right part of the diameter k = root; // save the height of left & right subtree as well. lh = left_height; rh = right_height; } return 1 + Math.max(left_height, right_height); } // prints the root to leaf path static void printArray(int[] ints, int len) { int i; // print left part of the path in reverse order if(f == 0) { for(i = len - 1; i >= 0; i--) { System.out.print(ints[i] + \" \"); } } else if(f == 1) { for (i = 0; i < len; i++) { System.out.print(ints[i] + \" \"); } } } // this function finds out all the root to leaf paths static void printPathsRecur(Node node, int[] path, int pathLen, int max) { if (node == null) return; // append this node to the path array path[pathLen] = node.data; pathLen++; // If it's a leaf, so print the path that led to here if (node.left == null && node.right == null) { // print only one path which is equal to the // height of the tree. if (pathLen == max && (f == 0 || f == 1)) { printArray(path, pathLen); f = 2; } } else { // otherwise try both subtrees printPathsRecur(node.left, path, pathLen, max); printPathsRecur(node.right, path, pathLen, max); } } // Computes the diameter of a binary tree with given root. static void diameter(Node root) { if (root == null) return; // lh will store height of left subtree // rh will store height of right subtree ans = Integer.MIN_VALUE; lh = 0; rh = 0; // f is a flag whose value helps in printing // left & right part of the diameter only once f = 0; int height_of_tree = height(root); int[] lPath = new int[100]; int pathlen = 0; // print the left part of the diameter printPathsRecur(k.left, lPath, pathlen, lh); System.out.print(k.data+\" \"); int[] rPath = new int[100]; f = 1; // print the right part of the diameter printPathsRecur(k.right, rPath, pathlen, rh); } // Driver code public static void main (String[] args) { // Enter the binary tree ... // 1 // / \\ // 2 3 // / \\ // 4 5 // \\ / \\ // 8 6 7 // / // 9 GFG.Root = new Node(1); GFG.Root.left = new Node(2); GFG.Root.right = new Node(3); GFG.Root.left.left = new Node(4); GFG.Root.left.right = new Node(5); GFG.Root.left.right.left = new Node(6); GFG.Root.left.right.right = new Node(7); GFG.Root.left.left.right = new Node(8); GFG.Root.left.left.right.left = new Node(9); diameter(Root); }} // This code is contributed by rag2127", "e": 7872, "s": 3734, "text": null }, { "code": "# Python3 program to print the longest# leaf to leaf path # Tree node structure used in the programclass Node: def __init__(self, x): self.data = x self.left = None self.right = None # Function to find height of a treedef height(root): global ans, k, lh, rh, f if (root == None): return 0 left_height = height(root.left) right_height = height(root.right) # Update the answer, because diameter of a # tree is nothing but maximum value of # (left_height + right_height + 1) for each node if (ans < 1 + left_height + right_height): ans = 1 + left_height + right_height # Save the root, this will help us finding the # left and the right part of the diameter k = root # Save the height of left & right # subtree as well. lh = left_height rh = right_height return 1 + max(left_height, right_height) # Prints the root to leaf pathdef printArray(ints, lenn, f): # Print left part of the path # in reverse order if (f == 0): for i in range(lenn - 1, -1, -1): print(ints[i], end = \" \") # Print right part of the path elif (f == 1): for i in range(lenn): print(ints[i], end = \" \") # This function finds out all the# root to leaf pathsdef printPathsRecur(node, path, maxm, pathlen): global f if (node == None): return # Append this node to the path array path[pathlen] = node.data pathlen += 1 # If it's a leaf, so print the # path that led to here if (node.left == None and node.right == None): # Print only one path which is equal to the # height of the tree. # print(pathlen,\"---\",maxm) if (pathlen == maxm and (f == 0 or f == 1)): # print(\"innn\") printArray(path, pathlen,f) f = 2 else: # Otherwise try both subtrees printPathsRecur(node.left, path, maxm, pathlen) printPathsRecur(node.right, path, maxm, pathlen) # Computes the diameter of a binary# tree with given root.def diameter(root): global ans, lh, rh, f, k, pathLen if (root == None): return # f is a flag whose value helps in printing # left & right part of the diameter only once height_of_tree = height(root) lPath = [0 for i in range(100)] # print(lh,\"--\",rh) # Print the left part of the diameter printPathsRecur(k.left, lPath, lh, 0); print(k.data, end = \" \") rPath = [0 for i in range(100)] f = 1 # Print the right part of the diameter printPathsRecur(k.right, rPath, rh, 0) # Driver codeif __name__ == '__main__': k, lh, rh, f, ans, pathLen = None, 0, 0, 0, 0 - 10 ** 19, 0 # Enter the binary tree ... # 1 # / \\ # 2 3 # / \\ # 4 5 # \\ / \\ # 8 6 7 # / # 9 root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.left.right.left = Node(6) root.left.right.right = Node(7) root.left.left.right = Node(8) root.left.left.right.left = Node(9) diameter(root) # This code is contributed by mohit kumar 29", "e": 11148, "s": 7872, "text": null }, { "code": "// C# program to print the longest leaf to leaf// pathusing System; // Tree node structure used in the programpublic class Node{ public int data; public Node left, right; public Node(int val) { data = val; left = right = null; }} public class GFG{ static int ans, lh, rh, f; static Node k; public static Node Root; // Function to find height of a tree static int height(Node root) { if (root == null) return 0; int left_height = height(root.left); int right_height = height(root.right); // update the answer, because diameter of a // tree is nothing but maximum value of // (left_height + right_height + 1) for each node if (ans < 1 + left_height + right_height) { ans = 1 + left_height + right_height; // save the root, this will help us finding the // left and the right part of the diameter k = root; // save the height of left & right subtree as well. lh = left_height; rh = right_height; } return 1 + Math.Max(left_height, right_height); } // prints the root to leaf path static void printArray(int[] ints, int len) { int i; // print left part of the path in reverse order if(f == 0) { for(i = len - 1; i >= 0; i--) { Console.Write(ints[i] + \" \"); } } else if(f == 1) { for (i = 0; i < len; i++) { Console.Write(ints[i] + \" \"); } } } // this function finds out all the root to leaf paths static void printPathsRecur(Node node, int[] path,int pathLen, int max) { if (node == null) return; // append this node to the path array path[pathLen] = node.data; pathLen++; // If it's a leaf, so print the path that led to here if (node.left == null && node.right == null) { // print only one path which is equal to the // height of the tree. if (pathLen == max && (f == 0 || f == 1)) { printArray(path, pathLen); f = 2; } } else { // otherwise try both subtrees printPathsRecur(node.left, path, pathLen, max); printPathsRecur(node.right, path, pathLen, max); } } // Computes the diameter of a binary tree with given root. static void diameter(Node root) { if (root == null) return; // lh will store height of left subtree // rh will store height of right subtree ans = Int32.MinValue; lh = 0; rh = 0; // f is a flag whose value helps in printing // left & right part of the diameter only once f = 0; int height_of_tree= height(root); int[] lPath = new int[100]; int pathlen = 0 * height_of_tree; // print the left part of the diameter printPathsRecur(k.left, lPath, pathlen, lh); Console.Write(k.data+\" \"); int[] rPath = new int[100]; f = 1; // print the right part of the diameter printPathsRecur(k.right, rPath, pathlen, rh); } // Driver code static public void Main (){ // Enter the binary tree ... // 1 // / \\ // 2 3 // / \\ // 4 5 // \\ / \\ // 8 6 7 // / // 9 GFG.Root = new Node(1); GFG.Root.left = new Node(2); GFG.Root.right = new Node(3); GFG.Root.left.left = new Node(4); GFG.Root.left.right = new Node(5); GFG.Root.left.right.left = new Node(6); GFG.Root.left.right.right = new Node(7); GFG.Root.left.left.right = new Node(8); GFG.Root.left.left.right.left = new Node(9); diameter(Root); }} // This code is contributed by avanitrachhadiya2155", "e": 15293, "s": 11148, "text": null }, { "code": "<script>// Javascript program to print the longest leaf to leaf// path // Tree node structure used in the programclass Node{ constructor(val) { this.data=val; this.left = this.right = null; }} let ans, lh, rh, f;let k;let Root; // Function to find height of a treefunction height(root){ if (root == null) return 0; let left_height = height(root.left); let right_height = height(root.right); // update the answer, because diameter of a // tree is nothing but maximum value of // (left_height + right_height + 1) for each node if (ans < 1 + left_height + right_height) { ans = 1 + left_height + right_height; // save the root, this will help us finding the // left and the right part of the diameter k = root; // save the height of left & right subtree as well. lh = left_height; rh = right_height; } return 1 + Math.max(left_height, right_height);} // prints the root to leaf pathfunction printArray(ints,len){ let i; // print left part of the path in reverse order if(f == 0) { for(i = len - 1; i >= 0; i--) { document.write(ints[i] + \" \"); } } else if(f == 1) { for (i = 0; i < len; i++) { document.write(ints[i] + \" \"); } }} // this function finds out all the root to leaf pathsfunction printPathsRecur(node,path,pathLen,max){ if (node == null) return; // append this node to the path array path[pathLen] = node.data; pathLen++; // If it's a leaf, so print the path that led to here if (node.left == null && node.right == null) { // print only one path which is equal to the // height of the tree. if (pathLen == max && (f == 0 || f == 1)) { printArray(path, pathLen); f = 2; } } else { // otherwise try both subtrees printPathsRecur(node.left, path, pathLen, max); printPathsRecur(node.right, path, pathLen, max); }} // Computes the diameter of a binary tree with given root.function diameter(root){ if (root == null) return; // lh will store height of left subtree // rh will store height of right subtree ans = Number.MIN_VALUE; lh = 0; rh = 0; // f is a flag whose value helps in printing // left & right part of the diameter only once f = 0; let height_of_tree = height(root); let lPath = new Array(100); let pathlen = 0; // print the left part of the diameter printPathsRecur(k.left, lPath, pathlen, lh); document.write(k.data+\" \"); let rPath = new Array(100); f = 1; // print the right part of the diameter printPathsRecur(k.right, rPath, pathlen, rh);} // Driver code // Enter the binary tree ...// 1// / \\ // 2 3// / \\ // 4 5// \\ / \\// 8 6 7// /// 9Root = new Node(1);Root.left = new Node(2);Root.right = new Node(3);Root.left.left = new Node(4);Root.left.right = new Node(5);Root.left.right.left = new Node(6);Root.left.right.right = new Node(7);Root.left.left.right = new Node(8);Root.left.left.right.left = new Node(9);diameter(Root); // This code is contributed by patel2127</script>", "e": 18654, "s": 15293, "text": null }, { "code": null, "e": 18707, "s": 18654, "text": "Time complexity: O(n) where n is size of binary tree" }, { "code": null, "e": 18768, "s": 18707, "text": "Auxiliary Space: O(h) where h is the height of binary tree." }, { "code": null, "e": 18783, "s": 18768, "text": "mohit kumar 29" }, { "code": null, "e": 18791, "s": 18783, "text": "rag2127" }, { "code": null, "e": 18812, "s": 18791, "text": "avanitrachhadiya2155" }, { "code": null, "e": 18822, "s": 18812, "text": "patel2127" }, { "code": null, "e": 18835, "s": 18822, "text": "technophpfij" }, { "code": null, "e": 18847, "s": 18835, "text": "Binary Tree" }, { "code": null, "e": 18852, "s": 18847, "text": "Tree" }, { "code": null, "e": 18857, "s": 18852, "text": "Tree" } ]
PHP | Imploding and Exploding
08 Mar, 2018 Imploding and Exploding are couple of important functions of PHP that can be applied on strings or arrays. PHP provides us with two important builtin functions implode() and explode() to perform these operations. As the name suggests Implode/implode() method joins array elements with a string segment that works as a glue and similarly Explode/explode() method does the exact opposite i.e. given a string and a delimiter it creates an array of strings separating with the help of the delimiter. implode() method Syntax: string implode (glue ,pieces) or, string implode (pieces) Parameters:The function accepts two parameters as described below. glue (optional): This parameter expects a string segment that is used as the glue to join the pieces of the array. This is an optional parameter with default value being an empty string. pieces: This parameter expects an array whose elements are to be joined together to construct the final imploded string. Return Type: This function traverses the input array and concatenates each element with one glue segment separating them to construct and return the final imploded string. Below program illustrates the working of implode() in PHP: <?php// PHP code to illustrate the working of implode() $array1 = array('www', 'geeksforgeeks', 'org');echo(implode('.',$array1)."<br>"); $array2 = array('H', 'E', 'L', 'L', 'O');echo(implode($array2));?> Output: www.geeksforgeeks.org HELLO You may refer to the article on PHP | implode() function to learn about implode() in details. explode() method Syntax: array explode (delimiter, string, limit) Parameters:The function accepts three parameters as described below. delimiter: This parameter expects a string segment that can be used as the separator. If the delimiter itself is not present in the string then the resultant will be an array containing the string as its sole element. string: This parameter expects a string which is to be exploded. limit: This parameter expects an integer (both positive and negative). This is an optional parameter with default value of PHP_INT_MAX. The limit refers to the maximum number of divisions that are to be made on the input string. Return Type: This function returns an array of strings containing the separated segments. Below program illustrates the working of explode() in PHP: <?php// PHP code to illustrate the working of explode() $str1 = '1,2,3,4,5';$arr = explode(',',$str1);foreach($arr as $i)echo($i.'<br>');?> Output: 1 2 3 4 5 You may refer to the article on PHP | explode() function to learn about explode() in details. Important Points to Note: The implode() function implodes the elements of an array and returns the resultant string. Although not advised, the implode() function can take the parameters irrespective of their order The PHP | Join() function is an alias of implode() function. PHP-array PHP-function PHP-string PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Mar, 2018" }, { "code": null, "e": 524, "s": 28, "text": "Imploding and Exploding are couple of important functions of PHP that can be applied on strings or arrays. PHP provides us with two important builtin functions implode() and explode() to perform these operations. As the name suggests Implode/implode() method joins array elements with a string segment that works as a glue and similarly Explode/explode() method does the exact opposite i.e. given a string and a delimiter it creates an array of strings separating with the help of the delimiter." }, { "code": null, "e": 541, "s": 524, "text": "implode() method" }, { "code": null, "e": 549, "s": 541, "text": "Syntax:" }, { "code": null, "e": 580, "s": 549, "text": "string implode (glue ,pieces)\n" }, { "code": null, "e": 584, "s": 580, "text": "or," }, { "code": null, "e": 609, "s": 584, "text": "string implode (pieces)\n" }, { "code": null, "e": 676, "s": 609, "text": "Parameters:The function accepts two parameters as described below." }, { "code": null, "e": 863, "s": 676, "text": "glue (optional): This parameter expects a string segment that is used as the glue to join the pieces of the array. This is an optional parameter with default value being an empty string." }, { "code": null, "e": 984, "s": 863, "text": "pieces: This parameter expects an array whose elements are to be joined together to construct the final imploded string." }, { "code": null, "e": 1156, "s": 984, "text": "Return Type: This function traverses the input array and concatenates each element with one glue segment separating them to construct and return the final imploded string." }, { "code": null, "e": 1215, "s": 1156, "text": "Below program illustrates the working of implode() in PHP:" }, { "code": "<?php// PHP code to illustrate the working of implode() $array1 = array('www', 'geeksforgeeks', 'org');echo(implode('.',$array1).\"<br>\"); $array2 = array('H', 'E', 'L', 'L', 'O');echo(implode($array2));?>", "e": 1423, "s": 1215, "text": null }, { "code": null, "e": 1431, "s": 1423, "text": "Output:" }, { "code": null, "e": 1460, "s": 1431, "text": "www.geeksforgeeks.org\nHELLO\n" }, { "code": null, "e": 1554, "s": 1460, "text": "You may refer to the article on PHP | implode() function to learn about implode() in details." }, { "code": null, "e": 1571, "s": 1554, "text": "explode() method" }, { "code": null, "e": 1579, "s": 1571, "text": "Syntax:" }, { "code": null, "e": 1621, "s": 1579, "text": "array explode (delimiter, string, limit)\n" }, { "code": null, "e": 1690, "s": 1621, "text": "Parameters:The function accepts three parameters as described below." }, { "code": null, "e": 1908, "s": 1690, "text": "delimiter: This parameter expects a string segment that can be used as the separator. If the delimiter itself is not present in the string then the resultant will be an array containing the string as its sole element." }, { "code": null, "e": 1973, "s": 1908, "text": "string: This parameter expects a string which is to be exploded." }, { "code": null, "e": 2202, "s": 1973, "text": "limit: This parameter expects an integer (both positive and negative). This is an optional parameter with default value of PHP_INT_MAX. The limit refers to the maximum number of divisions that are to be made on the input string." }, { "code": null, "e": 2292, "s": 2202, "text": "Return Type: This function returns an array of strings containing the separated segments." }, { "code": null, "e": 2351, "s": 2292, "text": "Below program illustrates the working of explode() in PHP:" }, { "code": "<?php// PHP code to illustrate the working of explode() $str1 = '1,2,3,4,5';$arr = explode(',',$str1);foreach($arr as $i)echo($i.'<br>');?>", "e": 2492, "s": 2351, "text": null }, { "code": null, "e": 2500, "s": 2492, "text": "Output:" }, { "code": null, "e": 2511, "s": 2500, "text": "1\n2\n3\n4\n5\n" }, { "code": null, "e": 2605, "s": 2511, "text": "You may refer to the article on PHP | explode() function to learn about explode() in details." }, { "code": null, "e": 2631, "s": 2605, "text": "Important Points to Note:" }, { "code": null, "e": 2722, "s": 2631, "text": "The implode() function implodes the elements of an array and returns the resultant string." }, { "code": null, "e": 2819, "s": 2722, "text": "Although not advised, the implode() function can take the parameters irrespective of their order" }, { "code": null, "e": 2880, "s": 2819, "text": "The PHP | Join() function is an alias of implode() function." }, { "code": null, "e": 2890, "s": 2880, "text": "PHP-array" }, { "code": null, "e": 2903, "s": 2890, "text": "PHP-function" }, { "code": null, "e": 2914, "s": 2903, "text": "PHP-string" }, { "code": null, "e": 2918, "s": 2914, "text": "PHP" }, { "code": null, "e": 2935, "s": 2918, "text": "Web Technologies" }, { "code": null, "e": 2939, "s": 2935, "text": "PHP" } ]
ES6 - Functions
Functions are the building blocks of readable, maintainable, and reusable code. Functions are defined using the function keyword. Following is the syntax for defining a standard function. function function_name() { // function body } To force execution of the function, it must be called. This is called as function invocation. Following is the syntax to invoke a function. function_name() //define a function function test() { console.log("function called") } //call the function test() The example defines a function test(). A pair of delimiters ( { } ) define the function body. It is also called as the function scope. A function must be invoked to force its execution. The following output is displayed on successful execution of the above code. function called Functions may be classified as Returning and Parameterized functions. Functions may also return the value along with control, back to the caller. Such functions are called as returning functions. Following is the syntax for the returning function. function function_name() { //statements return value; } A returning function must end with a return statement. A returning function must end with a return statement. A function can return at the most one value. In other words, there can be only one return statement per function. A function can return at the most one value. In other words, there can be only one return statement per function. The return statement should be the last statement in the function. The return statement should be the last statement in the function. The following code snippet is an example of a returning function − function retStr() { return "hello world!!!" } var val = retStr() console.log(val) The above Example defines a function that returns the string “hello world!!!” to the caller. The following output is displayed on successful execution of the above code. hello world!!! Parameters are a mechanism to pass values to functions. Parameters form a part of the function’s signature. The parameter values are passed to the function during its invocation. Unless explicitly specified, the number of values passed to a function must match the number of parameters defined. Following is the syntax defining a parameterized function. function func_name( param1,param2 ,.....paramN) { ...... ...... } Example − Parameterized Function The Example defines a function add that accepts two parameters n1 and n2 and prints their sum. The parameter values are passed to the function when it is invoked. function add( n1,n2) { var sum = n1 + n2 console.log("The sum of the values entered "+sum) } add(12,13) The following output is displayed on successful execution of the above code. The sum of the values entered 25 In ES6, a function allows the parameters to be initialized with default values, if no values are passed to it or it is undefined. The same is illustrated in the following code. function add(a, b = 1) { return a+b; } console.log(add(4)) The above function, sets the value of b to 1 by default. The function will always consider the parameter b to bear the value 1 unless a value has been explicitly passed. The following output is displayed on successful execution of the above code. 5 The parameter’s default value will be overwritten if the function passes a value explicitly. function add(a, b = 1) { return a + b; } console.log(add(4,2)) The above code sets the value of the parameter b explicitly to 2, thereby overwriting its default value. The following output is displayed on successful execution of the above code. 6 For better understanding, let us consider the below example. The following example shows a function which takes two parameters and returns their sum. The second parameter has a default value of 10. This means, if no value is passed to the second parameter, its value will be 10. <script> function addTwoNumbers(first,second = 10){ console.log('first parameter is :',first) console.log('second parameter is :',second) return first+second; } console.log("case 1 sum:",addTwoNumbers(20)) // no value console.log("case 2 sum:",addTwoNumbers(2,3)) console.log("case 3 sum:",addTwoNumbers()) console.log("case 4 sum",addTwoNumbers(1,null))//null passed console.log("case 5 sum",addTwoNumbers(3,undefined)) </script> The output of the above code will be as mentioned below − first parameter is : 20 second parameter is : 10 case 1 sum: 30 first parameter is : 2 second parameter is : 3 case 2 sum: 5 first parameter is : undefined second parameter is : 10 case 3 sum: NaN first parameter is : 1 second parameter is : null case 4 sum 1 first parameter is : 3 second parameter is : 10 case 5 sum 13 <script> let DEFAULT_VAL = 30 function addTwoNumbers(first,second = DEFAULT_VAL){ console.log('first parameter is :',first) console.log('second parameter is :',second) return first+second; } console.log("case 1 sum",addTwoNumbers(1)) console.log("case 2 sum",addTwoNumbers(3,undefined)) </script> The output of the above code will be as shown below − first parameter is : 1 second parameter is : 30 case 1 sum 31 first parameter is : 3 second parameter is : 30 case 2 sum 33 Rest parameters are similar to variable arguments in Java. Rest parameters doesn’t restrict the number of values that you can pass to a function. However, the values passed must all be of the same type. In other words, rest parameters act as placeholders for multiple arguments of the same type. To declare a rest parameter, the parameter name is prefixed with three periods, known as the spread operator. The following example illustrates the same. function fun1(...params) { console.log(params.length); } fun1(); fun1(5); fun1(5, 6, 7); The following output is displayed on successful execution of the above code. 0 1 3 Note − Rest parameters should be the last in a function’s parameter list. Functions that are not bound to an identifier (function name) are called as anonymous functions. These functions are dynamically declared at runtime. Anonymous functions can accept inputs and return outputs, just as standard functions do. An anonymous function is usually not accessible after its initial creation. Variables can be assigned an anonymous function. Such an expression is called a function expression. Following is the syntax for anonymous function. var res = function( [arguments] ) { ... } Example − Anonymous Function var f = function(){ return "hello"} console.log(f()) The following output is displayed on successful execution of the above code. hello Example − Anonymous Parameterized Function var func = function(x,y){ return x*y }; function product() { var result; result = func(10,20); console.log("The product : "+result) } product() The following output is displayed on successful execution of the above code. The product : 200 The function statement is not the only way to define a new function; you can define your function dynamically using Function() constructor along with the new operator. Following is the syntax to create a function using Function() constructor along with the new operator. var variablename = new Function(Arg1, Arg2..., "Function Body"); The Function() constructor expects any number of string arguments. The last argument is the body of the function – it can contain arbitrary JavaScript statements, separated from each other by semicolons. The Function() constructor is not passed any argument that specifies a name for the function it creates. Example − Function Constructor var func = new Function("x", "y", "return x*y;"); function product() { var result; result = func(10,20); console.log("The product : "+result) } product() In the above example, the Function() constructor is used to define an anonymous function. The function accepts two parameters and returns their product. The following output is displayed on successful execution of the above code. The product : 200 Recursion is a technique for iterating over an operation by having a function call itself repeatedly until it arrives at a result. Recursion is best applied when you need to call the same function repeatedly with different parameters from within a loop. Example − Recursion function factorial(num) { if(num <= 0) { return 1; } else { return (num * factorial(num-1) ) } } console.log(factorial(6)) In the above example the function calls itself. The following output is displayed on successful execution of the above code. 720 Example − Anonymous Recursive Function (function() { var msg = "Hello World" console.log(msg) })() The function calls itself using a pair of parentheses (). The following output is displayed on successful execution of the above code. Hello World Lambda refers to anonymous functions in programming. Lambda functions are a concise mechanism to represent anonymous functions. These functions are also called as Arrow functions. There are 3 parts to a Lambda function − Parameters − A function may optionally have parameters. Parameters − A function may optionally have parameters. The fat arrow notation/lambda notation (=>): It is also called as the goes to operator. The fat arrow notation/lambda notation (=>): It is also called as the goes to operator. Statements − Represents the function’s instruction set. Statements − Represents the function’s instruction set. Tip − By convention, the use of a single letter parameter is encouraged for a compact and precise function declaration. It is an anonymous function expression that points to a single line of code. Following is the syntax for the same. ([param1, parma2,...param n] )=>statement; Example − Lambda Expression var foo = (x)=>10+x console.log(foo(10)) The Example declares a lambda expression function. The function returns the sum of 10 and the argument passed. The following output is displayed on successful execution of the above code. 20 It is an anonymous function declaration that points to a block of code. This syntax is used when the function body spans multiple lines. Following is the syntax of the same. ( [param1, parma2,...param n] )=> { //code block } Example − Lambda Statement var msg = ()=> { console.log("function invoked") } msg() The function’s reference is returned and stored in the variable msg. The following output is displayed on successful execution of the above code. function invoked Optional parentheses for a single parameter. var msg = x=> { console.log(x) } msg(10) Optional braces for a single statement. Empty parentheses for no parameter. var disp = ()=>console.log("Hello World") disp(); Function expression and function declaration are not synonymous. Unlike a function expression, a function declaration is bound by the function name. The fundamental difference between the two is that, function declarations are parsed before their execution. On the other hand, function expressions are parsed only when the script engine encounters it during an execution. When the JavaScript parser sees a function in the main code flow, it assumes function declaration. When a function comes as a part of a statement, it is a function expression. Like variables, functions can also be hoisted. Unlike variables, function declarations when hoisted, hoists the function definition rather than just hoisting the function’s name. The following code snippet, illustrates function hoisting in JavaScript. hoist_function(); function hoist_function() { console.log("foo"); } The following output is displayed on successful execution of the above code. foo However, function expressions cannot be hoisted. The following code snippet illustrates the same. hoist_function(); // TypeError: hoist_function() is not a function var hoist_function() = function() { console.log("bar"); }; Immediately Invoked Function Expressions (IIFEs) can be used to avoid variable hoisting from within blocks. It allows public access to methods while retaining privacy for variables defined within the function. This pattern is called as a self-executing anonymous function. The following two examples better explain this concept. var main = function() { var loop = function() { for(var x = 0;x<5;x++) { console.log(x); } }(); console.log("x can not be accessed outside the block scope x value is :"+x); } main(); var main = function() { (function() { for(var x = 0;x<5;x++) { console.log(x); } })(); console.log("x can not be accessed outside the block scope x value is :"+x); } main(); Both the Examples will render the following output. 0 1 2 3 4 Uncaught ReferenceError: x is not define When a normal function is invoked, the control rests with the function called until it returns. With generators in ES6, the caller function can now control the execution of a called function. A generator is like a regular function except that − The function can yield control back to the caller at any point. The function can yield control back to the caller at any point. When you call a generator, it doesn’t run right away. Instead, you get back an iterator. The function runs as you call the iterator’s next method. When you call a generator, it doesn’t run right away. Instead, you get back an iterator. The function runs as you call the iterator’s next method. Generators are denoted by suffixing the function keyword with an asterisk; otherwise, their syntax is identical to regular functions. The following example illustrates the same. "use strict" function* rainbow() { // the asterisk marks this as a generator yield 'red'; yield 'orange'; yield 'yellow'; yield 'green'; yield 'blue'; yield 'indigo'; yield 'violet'; } for(let color of rainbow()) { console.log(color); } Generators enable two-way communication between the caller and the called function. This is accomplished by using the yield keyword. Consider the following example − function* ask() { const name = yield "What is your name?"; const sport = yield "What is your favorite sport?"; return `${name}'s favorite sport is ${sport}`; } const it = ask(); console.log(it.next()); console.log(it.next('Ethan')); console.log(it.next('Cricket')); Sequence of the generator function is as follows − Generator started in paused stated; iterator is returned. Generator started in paused stated; iterator is returned. The it.next() yields “What is your name”. The generator is paused. This is done by the yield keyword. The it.next() yields “What is your name”. The generator is paused. This is done by the yield keyword. The call it.next(“Ethan”) assigns the value Ethan to the variable name and yields “What is your favorite sport?” Again the generator is paused. The call it.next(“Ethan”) assigns the value Ethan to the variable name and yields “What is your favorite sport?” Again the generator is paused. The call it.next(“Cricket”) assigns the value Cricket to the variable sport and executes the subsequent return statement. The call it.next(“Cricket”) assigns the value Cricket to the variable sport and executes the subsequent return statement. Hence, the output of the above code will be − { value: 'What is your name?', done: false } { value: 'What is your favorite sport?', done: false } { value: 'Ethan\'s favorite sport is Cricket', done: true } Note − Generator functions cannot be represented using arrow functions. Arrow functions which are introduced in ES helps in writing the functions in JavaScript in a concise manner. Let us now learn about the same in detail. JavaScript makes heavy use of anonymous functions. An anonymous function is a function that does not have a name attached to it. Anonymous functions are used during function callback. The following example illustrates the use of an anonymous function in ES5 − <script> setTimeout(function(){ console.log('Learning at TutorialsPoint is fun!!') },1000) </script> The above example passes an anonymous function as a parameter to the predefined setTimeout() function. The setTimeout() function will callback the anonymous function after 1 second. The following output is shown after 1 second − Learning at TutorialsPoint is fun!! ES6 introduces the concept of arrow function to simplify the usage of anonymous function. There are 3 parts to an arrow function which are as follows − Parameters − An arrow function may optionally have parameters Parameters − An arrow function may optionally have parameters The fat arrow notation (=>) − It is also called as the goes to operator The fat arrow notation (=>) − It is also called as the goes to operator Statements − Represents the function’s instruction set Statements − Represents the function’s instruction set Tip − By convention, the use of a single letter parameter is encouraged for a compact and precise arrow function declaration. //Arrow function that points to a single line of code ()=>some_expression //Arrow function that points to a block of code ()=> { //some statements }` //Arrow function with parameters (param1,param2)=>{//some statement} The following example defines two function expressions add and isEven using arrow function <script> const add = (n1,n2) => n1+n2 console.log(add(10,20)) const isEven = (n1) => { if(n1%2 == 0) return true; else return false; } console.log(isEven(10)) </script> The output of the above code will be as mentioned below − 30 true In the following example, an arrow function is passed as a parameter to the Array.prototype.map() function. The map() function executes the arrow function for each element in the array. The arrow function in this case, displays each element in the array and its index. <script> const names = ['TutorialsPoint','Mohtashim','Bhargavi','Raja'] names.map((element,index)=> { console.log('inside arrow function') console.log('index is '+index+' element value is :'+element) }) </script> The output of the above code will be as given below − inside arrow function index is 0 element value is :TutorialsPoint inside arrow function index is 1 element value is :Mohtashim inside arrow function index is 2 element value is :Bhargavi inside arrow function index is 3 element value is :Raja The following example passes an arrow function as a parameter to the predefined setTimeout() function. The setTimeout() function will callback the arrow function after 1 second. <script> setTimeout(()=>{ console.log('Learning at TutorialsPoint is fun!!') },1000) </script> The following output is shown after 1 second − Learning at TutorialsPoint is fun!! Inside an arrow function if we use this pointer, it will point to the enclosing lexical scope. This means arrow functions do not create a new this pointer instance whenever it is invoked. Arrow functions makes use of its enclosing scope. To understand this, let us see an example. <script> //constructor function function Student(rollno,firstName,lastName) { this.rollno = rollno; this.firstName = firstName; this.lastName = lastName; this.fullNameUsingAnonymous = function(){ setTimeout(function(){ //creates a new instance of this ,hides outer scope of this console.log(this.firstName+ " "+this.lastName) },2000) } this.fullNameUsingArrow = function(){ setTimeout(()=>{ //uses this instance of outer scope console.log(this.firstName+ " "+this.lastName) },3000) } } const s1 = new Student(101,'Mohammad','Mohtashim') s1.fullNameUsingAnonymous(); s1.fullNameUsingArrow(); </script> When an anonymous function is used with setTimeout(), the function gets invoked after 2000 milliseconds. A new instance of “this” is created and it shadows the instance of the Student function. So, the value of this.firstName and this.lastName will be undefined. The function doesn't use the lexical scope or the context of current execution. This problem can be solved by using an arrow function. The output of the above code will be as follows −
[ { "code": null, "e": 2599, "s": 2411, "text": "Functions are the building blocks of readable, maintainable, and reusable code. Functions are defined using the function keyword. Following is the syntax for defining a standard function." }, { "code": null, "e": 2652, "s": 2599, "text": "function function_name() { \n // function body \n} \n" }, { "code": null, "e": 2792, "s": 2652, "text": "To force execution of the function, it must be called. This is called as function invocation. Following is the syntax to invoke a function." }, { "code": null, "e": 2809, "s": 2792, "text": "function_name()\n" }, { "code": null, "e": 2916, "s": 2809, "text": "//define a function \nfunction test() { \n console.log(\"function called\") \n} \n//call the function \ntest()" }, { "code": null, "e": 3102, "s": 2916, "text": "The example defines a function test(). A pair of delimiters ( { } ) define the function body. It is also called as the function scope. A function must be invoked to force its execution." }, { "code": null, "e": 3179, "s": 3102, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 3196, "s": 3179, "text": "function called\n" }, { "code": null, "e": 3266, "s": 3196, "text": "Functions may be classified as Returning and Parameterized functions." }, { "code": null, "e": 3392, "s": 3266, "text": "Functions may also return the value along with control, back to the caller. Such functions are called as returning functions." }, { "code": null, "e": 3444, "s": 3392, "text": "Following is the syntax for the returning function." }, { "code": null, "e": 3510, "s": 3444, "text": "function function_name() { \n //statements \n return value; \n}\n" }, { "code": null, "e": 3565, "s": 3510, "text": "A returning function must end with a return statement." }, { "code": null, "e": 3620, "s": 3565, "text": "A returning function must end with a return statement." }, { "code": null, "e": 3734, "s": 3620, "text": "A function can return at the most one value. In other words, there can be only one return statement per function." }, { "code": null, "e": 3848, "s": 3734, "text": "A function can return at the most one value. In other words, there can be only one return statement per function." }, { "code": null, "e": 3915, "s": 3848, "text": "The return statement should be the last statement in the function." }, { "code": null, "e": 3982, "s": 3915, "text": "The return statement should be the last statement in the function." }, { "code": null, "e": 4049, "s": 3982, "text": "The following code snippet is an example of a returning function −" }, { "code": null, "e": 4140, "s": 4049, "text": "function retStr() { \n return \"hello world!!!\" \n} \nvar val = retStr() \nconsole.log(val) " }, { "code": null, "e": 4310, "s": 4140, "text": "The above Example defines a function that returns the string “hello world!!!” to the caller. The following output is displayed on successful execution of the above code." }, { "code": null, "e": 4327, "s": 4310, "text": "hello world!!! \n" }, { "code": null, "e": 4622, "s": 4327, "text": "Parameters are a mechanism to pass values to functions. Parameters form a part of the function’s signature. The parameter values are passed to the function during its invocation. Unless explicitly specified, the number of values passed to a function must match the number of parameters defined." }, { "code": null, "e": 4681, "s": 4622, "text": "Following is the syntax defining a parameterized function." }, { "code": null, "e": 4759, "s": 4681, "text": "function func_name( param1,param2 ,.....paramN) { \n ...... \n ...... \n}\n" }, { "code": null, "e": 4792, "s": 4759, "text": "Example − Parameterized Function" }, { "code": null, "e": 4955, "s": 4792, "text": "The Example defines a function add that accepts two parameters n1 and n2 and prints their sum. The parameter values are passed to the function when it is invoked." }, { "code": null, "e": 5070, "s": 4955, "text": "function add( n1,n2) { \n var sum = n1 + n2 \n console.log(\"The sum of the values entered \"+sum) \n} \nadd(12,13) " }, { "code": null, "e": 5147, "s": 5070, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 5181, "s": 5147, "text": "The sum of the values entered 25\n" }, { "code": null, "e": 5358, "s": 5181, "text": "In ES6, a function allows the parameters to be initialized with default values, if no values are passed to it or it is undefined. The same is illustrated in the following code." }, { "code": null, "e": 5423, "s": 5358, "text": "function add(a, b = 1) { \n return a+b; \n} \nconsole.log(add(4))" }, { "code": null, "e": 5670, "s": 5423, "text": "The above function, sets the value of b to 1 by default. The function will always consider the parameter b to bear the value 1 unless a value has been explicitly passed. The following output is displayed on successful execution of the above code." }, { "code": null, "e": 5673, "s": 5670, "text": "5\n" }, { "code": null, "e": 5766, "s": 5673, "text": "The parameter’s default value will be overwritten if the function passes a value explicitly." }, { "code": null, "e": 5835, "s": 5766, "text": "function add(a, b = 1) { \n return a + b; \n} \nconsole.log(add(4,2))" }, { "code": null, "e": 6017, "s": 5835, "text": "The above code sets the value of the parameter b explicitly to 2, thereby overwriting its default value. The following output is displayed on successful execution of the above code." }, { "code": null, "e": 6020, "s": 6017, "text": "6\n" }, { "code": null, "e": 6081, "s": 6020, "text": "For better understanding, let us consider the below example." }, { "code": null, "e": 6299, "s": 6081, "text": "The following example shows a function which takes two parameters and returns their sum. The second parameter has a default value of 10. This means, if no value is passed to the second parameter, its value will be 10." }, { "code": null, "e": 6770, "s": 6299, "text": "<script>\n function addTwoNumbers(first,second = 10){\n console.log('first parameter is :',first)\n console.log('second parameter is :',second)\n return first+second;\n }\n\n console.log(\"case 1 sum:\",addTwoNumbers(20)) // no value\n console.log(\"case 2 sum:\",addTwoNumbers(2,3))\n console.log(\"case 3 sum:\",addTwoNumbers())\n console.log(\"case 4 sum\",addTwoNumbers(1,null))//null passed\n console.log(\"case 5 sum\",addTwoNumbers(3,undefined))\n</script>" }, { "code": null, "e": 6828, "s": 6770, "text": "The output of the above code will be as mentioned below −" }, { "code": null, "e": 7151, "s": 6828, "text": "first parameter is : 20\nsecond parameter is : 10\ncase 1 sum: 30\nfirst parameter is : 2\nsecond parameter is : 3\ncase 2 sum: 5\nfirst parameter is : undefined\nsecond parameter is : 10\ncase 3 sum: NaN\nfirst parameter is : 1\nsecond parameter is : null\ncase 4 sum 1\nfirst parameter is : 3\nsecond parameter is : 10\ncase 5 sum 13\n" }, { "code": null, "e": 7502, "s": 7151, "text": "<script>\n let DEFAULT_VAL = 30\n function addTwoNumbers(first,second = DEFAULT_VAL){\n console.log('first parameter is :',first)\n console.log('second parameter is :',second)\n return first+second;\n }\n console.log(\"case 1 sum\",addTwoNumbers(1))\n console.log(\"case 2 sum\",addTwoNumbers(3,undefined))\n</script>" }, { "code": null, "e": 7556, "s": 7502, "text": "The output of the above code will be as shown below −" }, { "code": null, "e": 7681, "s": 7556, "text": "first parameter is : 1\nsecond parameter is : 30\ncase 1 sum 31\nfirst parameter is : 3\nsecond parameter is : 30\ncase 2 sum 33\n" }, { "code": null, "e": 7977, "s": 7681, "text": "Rest parameters are similar to variable arguments in Java. Rest parameters doesn’t restrict the number of values that you can pass to a function. However, the values passed must all be of the same type. In other words, rest parameters act as placeholders for multiple arguments of the same type." }, { "code": null, "e": 8131, "s": 7977, "text": "To declare a rest parameter, the parameter name is prefixed with three periods, known as the spread operator. The following example illustrates the same." }, { "code": null, "e": 8231, "s": 8131, "text": "function fun1(...params) { \n console.log(params.length); \n} \nfun1(); \nfun1(5); \nfun1(5, 6, 7); " }, { "code": null, "e": 8308, "s": 8231, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 8317, "s": 8308, "text": "0 \n1 \n3\n" }, { "code": null, "e": 8391, "s": 8317, "text": "Note − Rest parameters should be the last in a function’s parameter list." }, { "code": null, "e": 8706, "s": 8391, "text": "Functions that are not bound to an identifier (function name) are called as anonymous functions. These functions are dynamically declared at runtime. Anonymous functions can accept inputs and return outputs, just as standard functions do. An anonymous function is usually not accessible after its initial creation." }, { "code": null, "e": 8807, "s": 8706, "text": "Variables can be assigned an anonymous function. Such an expression is called a function expression." }, { "code": null, "e": 8855, "s": 8807, "text": "Following is the syntax for anonymous function." }, { "code": null, "e": 8899, "s": 8855, "text": "var res = function( [arguments] ) { ... } \n" }, { "code": null, "e": 8928, "s": 8899, "text": "Example − Anonymous Function" }, { "code": null, "e": 8983, "s": 8928, "text": "var f = function(){ return \"hello\"} \nconsole.log(f()) " }, { "code": null, "e": 9060, "s": 8983, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 9068, "s": 9060, "text": "hello \n" }, { "code": null, "e": 9111, "s": 9068, "text": "Example − Anonymous Parameterized Function" }, { "code": null, "e": 9270, "s": 9111, "text": "var func = function(x,y){ return x*y }; \nfunction product() { \n var result; \n result = func(10,20); \n console.log(\"The product : \"+result) \n} \nproduct()" }, { "code": null, "e": 9347, "s": 9270, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 9367, "s": 9347, "text": "The product : 200 \n" }, { "code": null, "e": 9535, "s": 9367, "text": "The function statement is not the only way to define a new function; you can define your function dynamically using Function() constructor along with the new operator." }, { "code": null, "e": 9638, "s": 9535, "text": "Following is the syntax to create a function using Function() constructor along with the new operator." }, { "code": null, "e": 9705, "s": 9638, "text": "var variablename = new Function(Arg1, Arg2..., \"Function Body\"); \n" }, { "code": null, "e": 9909, "s": 9705, "text": "The Function() constructor expects any number of string arguments. The last argument is the body of the function – it can contain arbitrary JavaScript statements, separated from each other by semicolons." }, { "code": null, "e": 10014, "s": 9909, "text": "The Function() constructor is not passed any argument that specifies a name for the function it creates." }, { "code": null, "e": 10045, "s": 10014, "text": "Example − Function Constructor" }, { "code": null, "e": 10213, "s": 10045, "text": "var func = new Function(\"x\", \"y\", \"return x*y;\"); \nfunction product() { \n var result; \n result = func(10,20); \n console.log(\"The product : \"+result)\n} \nproduct()" }, { "code": null, "e": 10366, "s": 10213, "text": "In the above example, the Function() constructor is used to define an anonymous function. The function accepts two parameters and returns their product." }, { "code": null, "e": 10443, "s": 10366, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 10462, "s": 10443, "text": "The product : 200\n" }, { "code": null, "e": 10716, "s": 10462, "text": "Recursion is a technique for iterating over an operation by having a function call itself repeatedly until it arrives at a result. Recursion is best applied when you need to call the same function repeatedly with different parameters from within a loop." }, { "code": null, "e": 10736, "s": 10716, "text": "Example − Recursion" }, { "code": null, "e": 10889, "s": 10736, "text": "function factorial(num) { \n if(num <= 0) { \n return 1; \n } else { \n return (num * factorial(num-1) ) \n } \n} \nconsole.log(factorial(6)) " }, { "code": null, "e": 11014, "s": 10889, "text": "In the above example the function calls itself. The following output is displayed on successful execution of the above code." }, { "code": null, "e": 11020, "s": 11014, "text": "720 \n" }, { "code": null, "e": 11059, "s": 11020, "text": "Example − Anonymous Recursive Function" }, { "code": null, "e": 11127, "s": 11059, "text": "(function() { \n var msg = \"Hello World\" \n console.log(msg)\n})()" }, { "code": null, "e": 11262, "s": 11127, "text": "The function calls itself using a pair of parentheses (). The following output is displayed on successful execution of the above code." }, { "code": null, "e": 11276, "s": 11262, "text": "Hello World \n" }, { "code": null, "e": 11456, "s": 11276, "text": "Lambda refers to anonymous functions in programming. Lambda functions are a concise mechanism to represent anonymous functions. These functions are also called as Arrow functions." }, { "code": null, "e": 11497, "s": 11456, "text": "There are 3 parts to a Lambda function −" }, { "code": null, "e": 11553, "s": 11497, "text": "Parameters − A function may optionally have parameters." }, { "code": null, "e": 11609, "s": 11553, "text": "Parameters − A function may optionally have parameters." }, { "code": null, "e": 11697, "s": 11609, "text": "The fat arrow notation/lambda notation (=>): It is also called as the goes to operator." }, { "code": null, "e": 11785, "s": 11697, "text": "The fat arrow notation/lambda notation (=>): It is also called as the goes to operator." }, { "code": null, "e": 11841, "s": 11785, "text": "Statements − Represents the function’s instruction set." }, { "code": null, "e": 11897, "s": 11841, "text": "Statements − Represents the function’s instruction set." }, { "code": null, "e": 12017, "s": 11897, "text": "Tip − By convention, the use of a single letter parameter is encouraged for a compact and precise function declaration." }, { "code": null, "e": 12132, "s": 12017, "text": "It is an anonymous function expression that points to a single line of code. Following is the syntax for the same." }, { "code": null, "e": 12176, "s": 12132, "text": "([param1, parma2,...param n] )=>statement;\n" }, { "code": null, "e": 12204, "s": 12176, "text": "Example − Lambda Expression" }, { "code": null, "e": 12247, "s": 12204, "text": "var foo = (x)=>10+x \nconsole.log(foo(10)) " }, { "code": null, "e": 12358, "s": 12247, "text": "The Example declares a lambda expression function. The function returns the sum of 10 and the argument passed." }, { "code": null, "e": 12435, "s": 12358, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 12439, "s": 12435, "text": "20\n" }, { "code": null, "e": 12613, "s": 12439, "text": "It is an anonymous function declaration that points to a block of code. This syntax is used when the function body spans multiple lines. Following is the syntax of the same." }, { "code": null, "e": 12676, "s": 12613, "text": "( [param1, parma2,...param n] )=> { \n //code block \n}\n" }, { "code": null, "e": 12703, "s": 12676, "text": "Example − Lambda Statement" }, { "code": null, "e": 12767, "s": 12703, "text": "var msg = ()=> { \n console.log(\"function invoked\") \n} \nmsg() " }, { "code": null, "e": 12913, "s": 12767, "text": "The function’s reference is returned and stored in the variable msg. The following output is displayed on successful execution of the above code." }, { "code": null, "e": 12933, "s": 12913, "text": "function invoked \n" }, { "code": null, "e": 12978, "s": 12933, "text": "Optional parentheses for a single parameter." }, { "code": null, "e": 13025, "s": 12978, "text": "var msg = x=> { \n console.log(x) \n} \nmsg(10)" }, { "code": null, "e": 13101, "s": 13025, "text": "Optional braces for a single statement. Empty parentheses for no parameter." }, { "code": null, "e": 13153, "s": 13101, "text": "var disp = ()=>console.log(\"Hello World\") \ndisp();\n" }, { "code": null, "e": 13302, "s": 13153, "text": "Function expression and function declaration are not synonymous. Unlike a function expression, a function declaration is bound by the function name." }, { "code": null, "e": 13525, "s": 13302, "text": "The fundamental difference between the two is that, function declarations are parsed before their execution. On the other hand, function expressions are parsed only when the script engine encounters it during an execution." }, { "code": null, "e": 13701, "s": 13525, "text": "When the JavaScript parser sees a function in the main code flow, it assumes function declaration. When a function comes as a part of a statement, it is a function expression." }, { "code": null, "e": 13880, "s": 13701, "text": "Like variables, functions can also be hoisted. Unlike variables, function declarations when hoisted, hoists the function definition rather than just hoisting the function’s name." }, { "code": null, "e": 13953, "s": 13880, "text": "The following code snippet, illustrates function hoisting in JavaScript." }, { "code": null, "e": 14029, "s": 13953, "text": "hoist_function(); \nfunction hoist_function() { \n console.log(\"foo\"); \n} " }, { "code": null, "e": 14106, "s": 14029, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 14112, "s": 14106, "text": "foo \n" }, { "code": null, "e": 14210, "s": 14112, "text": "However, function expressions cannot be hoisted. The following code snippet illustrates the same." }, { "code": null, "e": 14343, "s": 14210, "text": "hoist_function(); // TypeError: hoist_function() is not a function \nvar hoist_function() = function() { \n console.log(\"bar\"); \n};" }, { "code": null, "e": 14672, "s": 14343, "text": "Immediately Invoked Function Expressions (IIFEs) can be used to avoid variable hoisting from within blocks. It allows public access to methods while retaining privacy for variables defined within the function. This pattern is called as a self-executing anonymous function. The following two examples better explain this concept." }, { "code": null, "e": 14892, "s": 14672, "text": "var main = function() { \n var loop = function() { \n for(var x = 0;x<5;x++) {\n console.log(x); \n } \n }(); \n console.log(\"x can not be accessed outside the block scope x value is :\"+x); \n} \nmain();" }, { "code": null, "e": 15104, "s": 14892, "text": "var main = function() { \n (function() { \n for(var x = 0;x<5;x++) { \n console.log(x); \n } \n })(); \n console.log(\"x can not be accessed outside the block scope x value is :\"+x); \n} \nmain();" }, { "code": null, "e": 15156, "s": 15104, "text": "Both the Examples will render the following output." }, { "code": null, "e": 15213, "s": 15156, "text": "0 \n1 \n2 \n3 \n4 \nUncaught ReferenceError: x is not define\n" }, { "code": null, "e": 15459, "s": 15213, "text": "When a normal function is invoked, the control rests with the function called until it returns. With generators in ES6, the caller function can now control the execution of a called function. A generator is like a regular function except that −" }, { "code": null, "e": 15523, "s": 15459, "text": "The function can yield control back to the caller at any point." }, { "code": null, "e": 15587, "s": 15523, "text": "The function can yield control back to the caller at any point." }, { "code": null, "e": 15734, "s": 15587, "text": "When you call a generator, it doesn’t run right away. Instead, you get back an iterator. The function runs as you call the iterator’s next method." }, { "code": null, "e": 15881, "s": 15734, "text": "When you call a generator, it doesn’t run right away. Instead, you get back an iterator. The function runs as you call the iterator’s next method." }, { "code": null, "e": 16015, "s": 15881, "text": "Generators are denoted by suffixing the function keyword with an asterisk; otherwise, their syntax is identical to regular functions." }, { "code": null, "e": 16059, "s": 16015, "text": "The following example illustrates the same." }, { "code": null, "e": 16337, "s": 16059, "text": "\"use strict\" \nfunction* rainbow() { \n // the asterisk marks this as a generator \n yield 'red'; \n yield 'orange'; \n yield 'yellow'; \n yield 'green'; \n yield 'blue'; \n yield 'indigo'; \n yield 'violet'; \n} \nfor(let color of rainbow()) { \n console.log(color); \n} " }, { "code": null, "e": 16470, "s": 16337, "text": "Generators enable two-way communication between the caller and the called function. This is accomplished by using the yield keyword." }, { "code": null, "e": 16503, "s": 16470, "text": "Consider the following example −" }, { "code": null, "e": 16789, "s": 16503, "text": "function* ask() { \n const name = yield \"What is your name?\"; \n const sport = yield \"What is your favorite sport?\"; \n return `${name}'s favorite sport is ${sport}`; \n} \nconst it = ask(); \nconsole.log(it.next()); \nconsole.log(it.next('Ethan')); \nconsole.log(it.next('Cricket')); " }, { "code": null, "e": 16840, "s": 16789, "text": "Sequence of the generator function is as follows −" }, { "code": null, "e": 16898, "s": 16840, "text": "Generator started in paused stated; iterator is returned." }, { "code": null, "e": 16956, "s": 16898, "text": "Generator started in paused stated; iterator is returned." }, { "code": null, "e": 17058, "s": 16956, "text": "The it.next() yields “What is your name”. The generator is paused. This is done by the yield keyword." }, { "code": null, "e": 17160, "s": 17058, "text": "The it.next() yields “What is your name”. The generator is paused. This is done by the yield keyword." }, { "code": null, "e": 17304, "s": 17160, "text": "The call it.next(“Ethan”) assigns the value Ethan to the variable name and yields “What is your favorite sport?” Again the generator is paused." }, { "code": null, "e": 17448, "s": 17304, "text": "The call it.next(“Ethan”) assigns the value Ethan to the variable name and yields “What is your favorite sport?” Again the generator is paused." }, { "code": null, "e": 17570, "s": 17448, "text": "The call it.next(“Cricket”) assigns the value Cricket to the variable sport and executes the subsequent return statement." }, { "code": null, "e": 17692, "s": 17570, "text": "The call it.next(“Cricket”) assigns the value Cricket to the variable sport and executes the subsequent return statement." }, { "code": null, "e": 17738, "s": 17692, "text": "Hence, the output of the above code will be −" }, { "code": null, "e": 17916, "s": 17738, "text": "{ \n value: 'What is your name?', done: false \n} \n{ \n value: 'What is your favorite sport?', done: false \n} \n{ \n value: 'Ethan\\'s favorite sport is Cricket', done: true \n}\n" }, { "code": null, "e": 17988, "s": 17916, "text": "Note − Generator functions cannot be represented using arrow functions." }, { "code": null, "e": 18140, "s": 17988, "text": "Arrow functions which are introduced in ES helps in writing the functions in JavaScript in a concise manner. Let us now learn about the same in detail." }, { "code": null, "e": 18400, "s": 18140, "text": "JavaScript makes heavy use of anonymous functions. An anonymous function is a function that does not have a name attached to it. Anonymous functions are used during function callback. The following example illustrates the use of an anonymous function in ES5 −" }, { "code": null, "e": 18513, "s": 18400, "text": "<script>\n setTimeout(function(){\n console.log('Learning at TutorialsPoint is fun!!')\n },1000)\n</script>" }, { "code": null, "e": 18695, "s": 18513, "text": "The above example passes an anonymous function as a parameter to the predefined setTimeout() function. The setTimeout() function will callback the anonymous function after 1 second." }, { "code": null, "e": 18742, "s": 18695, "text": "The following output is shown after 1 second −" }, { "code": null, "e": 18778, "s": 18742, "text": "Learning at TutorialsPoint is fun!!" }, { "code": null, "e": 18930, "s": 18778, "text": "ES6 introduces the concept of arrow function to simplify the usage of anonymous function. There are 3 parts to an arrow function which are as follows −" }, { "code": null, "e": 18992, "s": 18930, "text": "Parameters − An arrow function may optionally have parameters" }, { "code": null, "e": 19054, "s": 18992, "text": "Parameters − An arrow function may optionally have parameters" }, { "code": null, "e": 19126, "s": 19054, "text": "The fat arrow notation (=>) − It is also called as the goes to operator" }, { "code": null, "e": 19198, "s": 19126, "text": "The fat arrow notation (=>) − It is also called as the goes to operator" }, { "code": null, "e": 19253, "s": 19198, "text": "Statements − Represents the function’s instruction set" }, { "code": null, "e": 19308, "s": 19253, "text": "Statements − Represents the function’s instruction set" }, { "code": null, "e": 19434, "s": 19308, "text": "Tip − By convention, the use of a single letter parameter is encouraged for a compact and precise arrow function declaration." }, { "code": null, "e": 19509, "s": 19434, "text": "//Arrow function that points to a single line of code\n()=>some_expression\n" }, { "code": null, "e": 19586, "s": 19509, "text": "//Arrow function that points to a block of code\n()=> { //some statements }`\n" }, { "code": null, "e": 19656, "s": 19586, "text": "//Arrow function with parameters\n(param1,param2)=>{//some statement}\n" }, { "code": null, "e": 19747, "s": 19656, "text": "The following example defines two function expressions add and isEven using arrow function" }, { "code": null, "e": 19962, "s": 19747, "text": "<script>\n const add = (n1,n2) => n1+n2\n console.log(add(10,20))\n\n const isEven = (n1) => {\n if(n1%2 == 0)\n return true;\n else\n return false;\n }\n console.log(isEven(10))\n</script>" }, { "code": null, "e": 20020, "s": 19962, "text": "The output of the above code will be as mentioned below −" }, { "code": null, "e": 20029, "s": 20020, "text": "30\ntrue\n" }, { "code": null, "e": 20298, "s": 20029, "text": "In the following example, an arrow function is passed as a parameter to the Array.prototype.map() function. The map() function executes the arrow function for each element in the array. The arrow function in this case, displays each element in the array and its index." }, { "code": null, "e": 20532, "s": 20298, "text": "<script>\n const names = ['TutorialsPoint','Mohtashim','Bhargavi','Raja']\n names.map((element,index)=> {\n console.log('inside arrow function')\n console.log('index is '+index+' element value is :'+element)\n })\n</script>" }, { "code": null, "e": 20586, "s": 20532, "text": "The output of the above code will be as given below −" }, { "code": null, "e": 20830, "s": 20586, "text": "inside arrow function\nindex is 0 element value is :TutorialsPoint\ninside arrow function\nindex is 1 element value is :Mohtashim\ninside arrow function\nindex is 2 element value is :Bhargavi\ninside arrow function\nindex is 3 element value is :Raja\n" }, { "code": null, "e": 21008, "s": 20830, "text": "The following example passes an arrow function as a parameter to the predefined setTimeout() function. The setTimeout() function will callback the arrow function after 1 second." }, { "code": null, "e": 21115, "s": 21008, "text": "<script>\n setTimeout(()=>{\n console.log('Learning at TutorialsPoint is fun!!')\n },1000)\n</script>" }, { "code": null, "e": 21162, "s": 21115, "text": "The following output is shown after 1 second −" }, { "code": null, "e": 21199, "s": 21162, "text": "Learning at TutorialsPoint is fun!!\n" }, { "code": null, "e": 21480, "s": 21199, "text": "Inside an arrow function if we use this pointer, it will point to the enclosing lexical scope. This means arrow functions do not create a new this pointer instance whenever it is invoked. Arrow functions makes use of its enclosing scope. To understand this, let us see an example." }, { "code": null, "e": 22225, "s": 21480, "text": "<script>\n //constructor function\n function Student(rollno,firstName,lastName) {\n this.rollno = rollno;\n this.firstName = firstName;\n this.lastName = lastName;\n this.fullNameUsingAnonymous = function(){\n setTimeout(function(){\n //creates a new instance of this ,hides outer scope of this\n console.log(this.firstName+ \" \"+this.lastName)\n },2000)\n }\n this.fullNameUsingArrow = function(){\n setTimeout(()=>{\n //uses this instance of outer scope\n console.log(this.firstName+ \" \"+this.lastName)\n },3000)\n }\n }\n const s1 = new Student(101,'Mohammad','Mohtashim')\n s1.fullNameUsingAnonymous();\n s1.fullNameUsingArrow();\n</script>" }, { "code": null, "e": 22623, "s": 22225, "text": "When an anonymous function is used with setTimeout(), the function gets invoked after 2000 milliseconds. A new instance of “this” is created and it shadows the instance of the Student function. So, the value of this.firstName and this.lastName will be undefined. The function doesn't use the lexical scope or the context of current execution. This problem can be solved by using an arrow function." } ]
SQL | Creating Roles
27 Sep, 2018 A role is created to ease setup and maintenance of the security model. It is a named group of related privileges that can be granted to the user. When there are many users in a database it becomes difficult to grant or revoke privileges to users. Therefore, if you define roles: You can grant or revoke privileges to users, thereby automatically granting or revoking privileges. You can either create Roles or use the system roles pre-defined. Some of the privileges granted to the system roles are as given below: Creating and Assigning a Role – First, the (Database Administrator)DBA must create the role. Then the DBA can assign privileges to the role and users to the role. Syntax – CREATE ROLE manager; Role created. In the syntax:‘manager’ is the name of the role to be created. Now that the role is created, the DBA can use the GRANT statement to assign users to the role as well as assign privileges to the role. It’s easier to GRANT or REVOKE privileges to the users through a role rather than assigning a privilege directly to every user. If a role is identified by a password, then GRANT or REVOKE privileges have to be identified by the password. Grant privileges to a role – GRANT create table, create view TO manager; Grant succeeded. Grant a role to users GRANT manager TO SAM, STARK; Grant succeeded. Revoke privilege from a Role : REVOKE create table FROM manager; Drop a Role : DROP ROLE manager; Explanation –Firstly it creates a manager role and then allows managers to create tables and views. It then grants Sam and Stark the role of managers. Now Sam and Stark can create tables and views. If users have multiple roles granted to them, they receive all of the privileges associated with all of the roles. Then create table privilege is removed from role ‘manager’ using Revoke.The role is dropped from the database using drop. sunny94 SQL-basics DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between Clustered and Non-clustered index Introduction of DBMS (Database Management System) | Set 1 Introduction of B-Tree SQL Interview Questions SQL | Views How to find Nth highest salary from a table SQL | ALTER (RENAME) How to Update Multiple Columns in Single Update Statement in SQL? SQL Interview Questions SQL | Views
[ { "code": null, "e": 54, "s": 26, "text": "\n27 Sep, 2018" }, { "code": null, "e": 333, "s": 54, "text": "A role is created to ease setup and maintenance of the security model. It is a named group of related privileges that can be granted to the user. When there are many users in a database it becomes difficult to grant or revoke privileges to users. Therefore, if you define roles:" }, { "code": null, "e": 433, "s": 333, "text": "You can grant or revoke privileges to users, thereby automatically granting or revoking privileges." }, { "code": null, "e": 498, "s": 433, "text": "You can either create Roles or use the system roles pre-defined." }, { "code": null, "e": 569, "s": 498, "text": "Some of the privileges granted to the system roles are as given below:" }, { "code": null, "e": 601, "s": 569, "text": "Creating and Assigning a Role –" }, { "code": null, "e": 732, "s": 601, "text": "First, the (Database Administrator)DBA must create the role. Then the DBA can assign privileges to the role and users to the role." }, { "code": null, "e": 741, "s": 732, "text": "Syntax –" }, { "code": null, "e": 777, "s": 741, "text": "CREATE ROLE manager;\nRole created.\n" }, { "code": null, "e": 840, "s": 777, "text": "In the syntax:‘manager’ is the name of the role to be created." }, { "code": null, "e": 976, "s": 840, "text": "Now that the role is created, the DBA can use the GRANT statement to assign users to the role as well as assign privileges to the role." }, { "code": null, "e": 1104, "s": 976, "text": "It’s easier to GRANT or REVOKE privileges to the users through a role rather than assigning a privilege directly to every user." }, { "code": null, "e": 1214, "s": 1104, "text": "If a role is identified by a password, then GRANT or REVOKE privileges have to be identified by the password." }, { "code": null, "e": 1243, "s": 1214, "text": "Grant privileges to a role –" }, { "code": null, "e": 1305, "s": 1243, "text": "GRANT create table, create view\nTO manager;\nGrant succeeded.\n" }, { "code": null, "e": 1327, "s": 1305, "text": "Grant a role to users" }, { "code": null, "e": 1374, "s": 1327, "text": "GRANT manager TO SAM, STARK;\nGrant succeeded.\n" }, { "code": null, "e": 1405, "s": 1374, "text": "Revoke privilege from a Role :" }, { "code": null, "e": 1440, "s": 1405, "text": "REVOKE create table FROM manager;\n" }, { "code": null, "e": 1454, "s": 1440, "text": "Drop a Role :" }, { "code": null, "e": 1474, "s": 1454, "text": "DROP ROLE manager;\n" }, { "code": null, "e": 1909, "s": 1474, "text": "Explanation –Firstly it creates a manager role and then allows managers to create tables and views. It then grants Sam and Stark the role of managers. Now Sam and Stark can create tables and views. If users have multiple roles granted to them, they receive all of the privileges associated with all of the roles. Then create table privilege is removed from role ‘manager’ using Revoke.The role is dropped from the database using drop." }, { "code": null, "e": 1917, "s": 1909, "text": "sunny94" }, { "code": null, "e": 1928, "s": 1917, "text": "SQL-basics" }, { "code": null, "e": 1933, "s": 1928, "text": "DBMS" }, { "code": null, "e": 1937, "s": 1933, "text": "SQL" }, { "code": null, "e": 1942, "s": 1937, "text": "DBMS" }, { "code": null, "e": 1946, "s": 1942, "text": "SQL" }, { "code": null, "e": 2044, "s": 1946, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2097, "s": 2044, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 2155, "s": 2097, "text": "Introduction of DBMS (Database Management System) | Set 1" }, { "code": null, "e": 2178, "s": 2155, "text": "Introduction of B-Tree" }, { "code": null, "e": 2202, "s": 2178, "text": "SQL Interview Questions" }, { "code": null, "e": 2214, "s": 2202, "text": "SQL | Views" }, { "code": null, "e": 2258, "s": 2214, "text": "How to find Nth highest salary from a table" }, { "code": null, "e": 2279, "s": 2258, "text": "SQL | ALTER (RENAME)" }, { "code": null, "e": 2345, "s": 2279, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 2369, "s": 2345, "text": "SQL Interview Questions" } ]
Date and time fields in serializers – Django REST Framework
10 May, 2021 In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, date, etc. Then, you would need AutoField, CharField and DateField for storing and manipulating data through Django. Similarly, serializer also works with same principle and has fields that are used to create a serializer. This article revolves around Date and time Fields in Serializers in Django REST Framework. There are four major fields – DateTimeField, DateField, TimeField and DurationField. DateTimeField is a serializer field used for date and time representation. It is same as – DateTimeField – Django ModelsIt has the following arguments – format – A string representing the output format. If not specified, this defaults to the same value as the DATETIME_FORMAT settings key, which will be ‘iso-8601’ unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python datetime objects should be returned by to_representation. In this case the datetime encoding will be determined by the renderer. input_formats – A list of strings representing the input formats which may be used to parse the date. If not specified, the DATETIME_INPUT_FORMATS setting will be used, which defaults to [‘iso-8601’]. default_timezone – A pytz.timezone representing the timezone. If not specified and the USE_TZ setting is enabled, this defaults to the current timezone. If USE_TZ is disabled, then datetime objects will be naive. Syntax – field_name = serializers.DateTimeField(*args, **kwargs) DateField is a serializer field used for date representation. Often, one needs to store date such as in a blog model every post’s date needs to be stored. This field is same as DateField – Django Models It has the following arguments – format – A string representing the output format. If not specified, this defaults to the same value as the DATE_FORMAT settings key, which will be ‘iso-8601’ unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python date objects should be returned by to_representation. In this case the date encoding will be determined by the renderer. input_formats – A list of strings representing the input formats which may be used to parse the date. If not specified, the DATE_INPUT_FORMATS setting will be used, which defaults to [‘iso-8601’]. Syntax – field_name = serializers.DateField(*args, **kwargs) Timefield is a serializer field used for time representation. Often, one needs to store date such as in a blog model every post’s time needs to be stored.It has the following arguments – format – A string representing the output format. If not specified, this defaults to the same value as the TIME_FORMAT settings key, which will be ‘iso-8601’ unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python time objects should be returned by to_representation. In this case the time encoding will be determined by the renderer. input_formats – A list of strings representing the input formats which may be used to parse the date. If not specified, the TIME_INPUT_FORMATS setting will be used, which defaults to [‘iso-8601’]. Syntax – field_name = serializers.TimeField(*args, **kwargs) DurationField is a serializer field used for duration representation. This field is same as DurationField – Django Models It has the following arguments – max_value Validate that the duration provided is no greater than this value. min_value Validate that the duration provided is no less than this value. Syntax – field_name = serializers.DurationField(*args, **kwargs) To explain the usage of Date and Time Fields, let’s use the same project setup from – How to Create a basic API using Django Rest Framework ?. Now that you have a file called serializers in your project, let’s create a serializer with DatetimeField, DateField, TimeField and DurationField. Python3 # import serializer from rest_frameworkfrom rest_framework import serializers class Geeks(object): def __init__(self, date_time, date, time, duration): self.date_time = date_time self.date = date self.time = time self.duration = duration # create a serializerclass GeeksSerializer(serializers.Serializer): # initialize fields date_time = serializers.DateTimeField() date = serializers.DateField() time = serializers.TimeField() duration = serializers.DurationField() Now let us create some objects and try serializing them and check if they are actually working, Run, – Python manage.py shell Now, run following python commands in the shell # import everything from datetime >>> from datetime import * # import everything from serializers >>> from apis.serializers import * # create a object of type Geeks >>> obj = Geeks(datetime.now(), date.today(), time(), timedelta(days=-1)) # serialize the object >>> serializer = GeeksSerializer(obj) # print serialized data >>> serializer.data {'date_time': '2020-03-22T13:17:27.853707Z', 'date': '2020-03-22', 'time': '00:00:00', 'duration': '-1 00:00:00'} Here is the output of all these operations on terminal – Note that prime motto of these fields is to impart validations, such as DateField validates the data to date only. Let’s check if these validations are working or not – # Create a dictionary and add invalid values >>> data={} >>> data['date_time'] = "invalid_date_time" >>> data['date'] = date.today() >>> data['time'] = time() >>> data['duration'] = "invalid_duration" # dictionary created >>> data {'date_time': 'invalid_date_time', 'date': datetime.date(2020, 3, 22), 'time': datetime.time(0, 0), 'duration': 'invalid_duration'} # deserialize the data >>> serializer = GeeksSerializer(data=data) # check if data is valid >>> serializer.is_valid() False # check the errors >>> serializer.errors {'date_time': [ErrorDetail(string='Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z].', code='invalid')], 'duration': [ErrorDetail(strin g='Duration has wrong format. Use one of these formats instead: [DD] [HH:[MM:]]ss[.uuuuuu].', code='invalid')]} Here is the output of these commands which clearly shows date_time and duration as invalid – Validations are part of Deserialization and not serialization. As explained earlier, serializing is process of converting already made data into another data type, so there is no requirement of these default validations out there. Deserialization requires validations as data needs to be saved to database or any more operation as specified. So if you serialize data using these fields that would work. Akanksha_Rai Django-REST Python Django rest-framework Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n10 May, 2021" }, { "code": null, "e": 733, "s": 28, "text": "In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, date, etc. Then, you would need AutoField, CharField and DateField for storing and manipulating data through Django. Similarly, serializer also works with same principle and has fields that are used to create a serializer. This article revolves around Date and time Fields in Serializers in Django REST Framework. There are four major fields – DateTimeField, DateField, TimeField and DurationField. " }, { "code": null, "e": 888, "s": 733, "text": "DateTimeField is a serializer field used for date and time representation. It is same as – DateTimeField – Django ModelsIt has the following arguments – " }, { "code": null, "e": 1386, "s": 888, "text": "format – A string representing the output format. If not specified, this defaults to the same value as the DATETIME_FORMAT settings key, which will be ‘iso-8601’ unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python datetime objects should be returned by to_representation. In this case the datetime encoding will be determined by the renderer." }, { "code": null, "e": 1587, "s": 1386, "text": "input_formats – A list of strings representing the input formats which may be used to parse the date. If not specified, the DATETIME_INPUT_FORMATS setting will be used, which defaults to [‘iso-8601’]." }, { "code": null, "e": 1800, "s": 1587, "text": "default_timezone – A pytz.timezone representing the timezone. If not specified and the USE_TZ setting is enabled, this defaults to the current timezone. If USE_TZ is disabled, then datetime objects will be naive." }, { "code": null, "e": 1811, "s": 1800, "text": "Syntax – " }, { "code": null, "e": 1867, "s": 1811, "text": "field_name = serializers.DateTimeField(*args, **kwargs)" }, { "code": null, "e": 2107, "s": 1869, "text": "DateField is a serializer field used for date representation. Often, one needs to store date such as in a blog model every post’s date needs to be stored. This field is same as DateField – Django Models It has the following arguments – " }, { "code": null, "e": 2593, "s": 2107, "text": "format – A string representing the output format. If not specified, this defaults to the same value as the DATE_FORMAT settings key, which will be ‘iso-8601’ unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python date objects should be returned by to_representation. In this case the date encoding will be determined by the renderer." }, { "code": null, "e": 2790, "s": 2593, "text": "input_formats – A list of strings representing the input formats which may be used to parse the date. If not specified, the DATE_INPUT_FORMATS setting will be used, which defaults to [‘iso-8601’]." }, { "code": null, "e": 2801, "s": 2790, "text": "Syntax – " }, { "code": null, "e": 2853, "s": 2801, "text": "field_name = serializers.DateField(*args, **kwargs)" }, { "code": null, "e": 3044, "s": 2855, "text": "Timefield is a serializer field used for time representation. Often, one needs to store date such as in a blog model every post’s time needs to be stored.It has the following arguments – " }, { "code": null, "e": 3530, "s": 3044, "text": "format – A string representing the output format. If not specified, this defaults to the same value as the TIME_FORMAT settings key, which will be ‘iso-8601’ unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python time objects should be returned by to_representation. In this case the time encoding will be determined by the renderer." }, { "code": null, "e": 3727, "s": 3530, "text": "input_formats – A list of strings representing the input formats which may be used to parse the date. If not specified, the TIME_INPUT_FORMATS setting will be used, which defaults to [‘iso-8601’]." }, { "code": null, "e": 3738, "s": 3727, "text": "Syntax – " }, { "code": null, "e": 3790, "s": 3738, "text": "field_name = serializers.TimeField(*args, **kwargs)" }, { "code": null, "e": 3949, "s": 3792, "text": "DurationField is a serializer field used for duration representation. This field is same as DurationField – Django Models It has the following arguments – " }, { "code": null, "e": 4026, "s": 3949, "text": "max_value Validate that the duration provided is no greater than this value." }, { "code": null, "e": 4100, "s": 4026, "text": "min_value Validate that the duration provided is no less than this value." }, { "code": null, "e": 4111, "s": 4100, "text": "Syntax – " }, { "code": null, "e": 4167, "s": 4111, "text": "field_name = serializers.DurationField(*args, **kwargs)" }, { "code": null, "e": 4461, "s": 4169, "text": "To explain the usage of Date and Time Fields, let’s use the same project setup from – How to Create a basic API using Django Rest Framework ?. Now that you have a file called serializers in your project, let’s create a serializer with DatetimeField, DateField, TimeField and DurationField. " }, { "code": null, "e": 4469, "s": 4461, "text": "Python3" }, { "code": "# import serializer from rest_frameworkfrom rest_framework import serializers class Geeks(object): def __init__(self, date_time, date, time, duration): self.date_time = date_time self.date = date self.time = time self.duration = duration # create a serializerclass GeeksSerializer(serializers.Serializer): # initialize fields date_time = serializers.DateTimeField() date = serializers.DateField() time = serializers.TimeField() duration = serializers.DurationField()", "e": 4982, "s": 4469, "text": null }, { "code": null, "e": 5087, "s": 4982, "text": "Now let us create some objects and try serializing them and check if they are actually working, Run, – " }, { "code": null, "e": 5110, "s": 5087, "text": "Python manage.py shell" }, { "code": null, "e": 5160, "s": 5110, "text": "Now, run following python commands in the shell " }, { "code": null, "e": 5625, "s": 5160, "text": "# import everything from datetime\n>>> from datetime import *\n\n# import everything from serializers\n>>> from apis.serializers import *\n\n# create a object of type Geeks\n>>> obj = Geeks(datetime.now(), date.today(), time(), timedelta(days=-1))\n\n# serialize the object\n>>> serializer = GeeksSerializer(obj)\n\n# print serialized data\n>>> serializer.data\n{'date_time': '2020-03-22T13:17:27.853707Z',\n 'date': '2020-03-22', 'time': '00:00:00', \n 'duration': '-1 00:00:00'}" }, { "code": null, "e": 5684, "s": 5625, "text": "Here is the output of all these operations on terminal – " }, { "code": null, "e": 5857, "s": 5686, "text": "Note that prime motto of these fields is to impart validations, such as DateField validates the data to date only. Let’s check if these validations are working or not – " }, { "code": null, "e": 6699, "s": 5857, "text": "# Create a dictionary and add invalid values\n>>> data={}\n>>> data['date_time'] = \"invalid_date_time\"\n>>> data['date'] = date.today()\n>>> data['time'] = time()\n>>> data['duration'] = \"invalid_duration\"\n\n# dictionary created\n>>> data\n{'date_time': 'invalid_date_time', \n'date': datetime.date(2020, 3, 22),\n'time': datetime.time(0, 0), \n'duration': 'invalid_duration'}\n\n# deserialize the data\n>>> serializer = GeeksSerializer(data=data)\n\n# check if data is valid\n>>> serializer.is_valid()\nFalse\n\n# check the errors\n>>> serializer.errors\n{'date_time': [ErrorDetail(string='Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z].', code='invalid')], 'duration': [ErrorDetail(strin\ng='Duration has wrong format. Use one of these formats instead: [DD] [HH:[MM:]]ss[.uuuuuu].', code='invalid')]}" }, { "code": null, "e": 6794, "s": 6699, "text": "Here is the output of these commands which clearly shows date_time and duration as invalid – " }, { "code": null, "e": 7201, "s": 6796, "text": "Validations are part of Deserialization and not serialization. As explained earlier, serializing is process of converting already made data into another data type, so there is no requirement of these default validations out there. Deserialization requires validations as data needs to be saved to database or any more operation as specified. So if you serialize data using these fields that would work. " }, { "code": null, "e": 7220, "s": 7207, "text": "Akanksha_Rai" }, { "code": null, "e": 7232, "s": 7220, "text": "Django-REST" }, { "code": null, "e": 7246, "s": 7232, "text": "Python Django" }, { "code": null, "e": 7261, "s": 7246, "text": "rest-framework" }, { "code": null, "e": 7268, "s": 7261, "text": "Python" }, { "code": null, "e": 7366, "s": 7268, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7398, "s": 7366, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 7425, "s": 7398, "text": "Python Classes and Objects" }, { "code": null, "e": 7446, "s": 7425, "text": "Python OOPs Concepts" }, { "code": null, "e": 7469, "s": 7446, "text": "Introduction To PYTHON" }, { "code": null, "e": 7525, "s": 7469, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 7556, "s": 7525, "text": "Python | os.path.join() method" }, { "code": null, "e": 7598, "s": 7556, "text": "Check if element exists in list in Python" }, { "code": null, "e": 7640, "s": 7598, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 7679, "s": 7640, "text": "Python | Get unique values from a list" } ]
Image Transition with Fading Effect using JavaScript
24 Jan, 2022 Given some images and the task is the create a slow transition from one image to another using Javascript.Prerequisite: In this article, we will use the following JavaScript methods. setInterval() method clearInterval() method async/await Promise Approach: Given some images and the task is to change the images after regular intervals with a fading or dissolving effect. To change the image at regular intervals use setInterval() method. Keep the images on top of each other and keep moving the topmost image to the bottom by changing it’s z-index at regular intervals.To make the image transition with a fading effect we use the asynchronous function. Inside the asynchronous function, use another setInterval() method to slowly decrease the opacity of the topmost image till opacity becomes 0. By doing this, the topmost image will appear to fade away slowly. Once, the topmost image is completely faded away, move it to the bottom-most position and store the new top image index. Javascript Code: javascript <script> startImageTransition(); function startImageTransition() { // images stores list of all images of // class test. This is the list of images // that we are going to iterate var images = document.getElementsByClassName("test"); // Set opacity of all images to 1 for (var i = 0; i < images.length; ++i) { images[i].style.opacity = 1; } // Top stores the z-index of top most image var top = 1; // cur stores the index of the image currently // on top images list contain images in the // same order they appear in HTML code /* The tag with class test which appears last will appear on top of all the images thus, cur is set to last index of images list*/ var cur = images.length - 1; // Call changeImage function every 3 second // changeImage function changes the image setInterval(changeImage, 3000); // Function to transitions from one image to other async function changeImage() { // Stores index of next image var nextImage = (1 + cur) % images.length; // First set the z-index of current image to top+1 // then set the z-index of nextImage to top /* Doing this make sure that the image below the current image is nextImage*/ // if this is not done then during transition // we might see some other image appearing // when we change opacity of the current image images[cur].style.zIndex = top + 1; images[nextImage].style.zIndex = top; // await is used to make sure // the program waits till transition() // is completed // before executing the next line of code await transition(); // Now, the transition function is completed // thus, we can say that the opacity of the // current image is now 0 // Set the z-index of current image to top images[cur].style.zIndex = top; // Set the z-index of nextImage to top+1 images[nextImage].style.zIndex = top + 1; // Increment top top = top + 1; // Change opacity of current image back to 1 // since zIndex of current is less than zIndex // of nextImage /* changing it's opacity back to 1 will not make the image appear again*/ images[cur].style.opacity = 1; // Set cur to nextImage cur = nextImage; } /* This function changes the opacity of current image at regular intervals*/ function transition() { return new Promise(function (resolve, reject) { // del is the value by which opacity is // decreased every interval var del = 0.01; // id stores ID of setInterval // this ID will be used later // to clear/stop setInterval // after we are done changing opacity var id = setInterval(changeOpacity, 10); // changeOpacity() decreasing opacity of // current image by del // when opacity reaches to 0, we stops/clears // the setInterval and resolve the function function changeOpacity() { images[cur].style.opacity -= del; if (images[cur].style.opacity <= 0) { clearInterval(id); resolve(); } } }) } }</script> Complete code: HTML <!DOCTYPE html><html> <head> <meta charset="utf-8" /> <title> Change Image Dynamically when User Scrolls </title> <style> body { text-align: center; } h1 { color: green; } img { position: absolute; left: 400px; } </style> </head> <body> <h1>GeeksforGeeks</h1> <b>A Computer Science Portal for Geeks</b> <div id="scroll-image"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200318142245/CSS8.png" class="test" /> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200318142309/php7.png" class="test" /> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200318142254/html9.png" class="test" /> </div> <script> startImageTransition(); function startImageTransition() { var images = document.getElementsByClassName("test"); for (var i = 0; i < images.length; ++i) { images[i].style.opacity = 1; } var top = 1; var cur = images.length - 1; setInterval(changeImage, 3000); async function changeImage() { var nextImage = (1 + cur) % images.length; images[cur].style.zIndex = top + 1; images[nextImage].style.zIndex = top; await transition(); images[cur].style.zIndex = top; images[nextImage].style.zIndex = top + 1; top = top + 1; images[cur].style.opacity = 1; cur = nextImage; } function transition() { return new Promise(function(resolve, reject) { var del = 0.01; var id = setInterval(changeOpacity, 10); function changeOpacity() { images[cur].style.opacity -= del; if (images[cur].style.opacity <= 0) { clearInterval(id); resolve(); } } }) } } </script> </body> </html> Output: Note: The time interval at which images are changing should be greater than the time it takes to make the opacity of the image less than or equals to 0. sagar0719kumar sumitgumber28 HTML-Misc JavaScript-Misc HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTTP headers | Content-Type Design a Tribute Page using HTML & CSS How to Insert Form Data into Database using PHP ? How to position a div at the bottom of its container using CSS? Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request
[ { "code": null, "e": 53, "s": 25, "text": "\n24 Jan, 2022" }, { "code": null, "e": 238, "s": 53, "text": "Given some images and the task is the create a slow transition from one image to another using Javascript.Prerequisite: In this article, we will use the following JavaScript methods. " }, { "code": null, "e": 259, "s": 238, "text": "setInterval() method" }, { "code": null, "e": 282, "s": 259, "text": "clearInterval() method" }, { "code": null, "e": 294, "s": 282, "text": "async/await" }, { "code": null, "e": 302, "s": 294, "text": "Promise" }, { "code": null, "e": 1040, "s": 302, "text": "Approach: Given some images and the task is to change the images after regular intervals with a fading or dissolving effect. To change the image at regular intervals use setInterval() method. Keep the images on top of each other and keep moving the topmost image to the bottom by changing it’s z-index at regular intervals.To make the image transition with a fading effect we use the asynchronous function. Inside the asynchronous function, use another setInterval() method to slowly decrease the opacity of the topmost image till opacity becomes 0. By doing this, the topmost image will appear to fade away slowly. Once, the topmost image is completely faded away, move it to the bottom-most position and store the new top image index. " }, { "code": null, "e": 1059, "s": 1040, "text": "Javascript Code: " }, { "code": null, "e": 1070, "s": 1059, "text": "javascript" }, { "code": "<script> startImageTransition(); function startImageTransition() { // images stores list of all images of // class test. This is the list of images // that we are going to iterate var images = document.getElementsByClassName(\"test\"); // Set opacity of all images to 1 for (var i = 0; i < images.length; ++i) { images[i].style.opacity = 1; } // Top stores the z-index of top most image var top = 1; // cur stores the index of the image currently // on top images list contain images in the // same order they appear in HTML code /* The tag with class test which appears last will appear on top of all the images thus, cur is set to last index of images list*/ var cur = images.length - 1; // Call changeImage function every 3 second // changeImage function changes the image setInterval(changeImage, 3000); // Function to transitions from one image to other async function changeImage() { // Stores index of next image var nextImage = (1 + cur) % images.length; // First set the z-index of current image to top+1 // then set the z-index of nextImage to top /* Doing this make sure that the image below the current image is nextImage*/ // if this is not done then during transition // we might see some other image appearing // when we change opacity of the current image images[cur].style.zIndex = top + 1; images[nextImage].style.zIndex = top; // await is used to make sure // the program waits till transition() // is completed // before executing the next line of code await transition(); // Now, the transition function is completed // thus, we can say that the opacity of the // current image is now 0 // Set the z-index of current image to top images[cur].style.zIndex = top; // Set the z-index of nextImage to top+1 images[nextImage].style.zIndex = top + 1; // Increment top top = top + 1; // Change opacity of current image back to 1 // since zIndex of current is less than zIndex // of nextImage /* changing it's opacity back to 1 will not make the image appear again*/ images[cur].style.opacity = 1; // Set cur to nextImage cur = nextImage; } /* This function changes the opacity of current image at regular intervals*/ function transition() { return new Promise(function (resolve, reject) { // del is the value by which opacity is // decreased every interval var del = 0.01; // id stores ID of setInterval // this ID will be used later // to clear/stop setInterval // after we are done changing opacity var id = setInterval(changeOpacity, 10); // changeOpacity() decreasing opacity of // current image by del // when opacity reaches to 0, we stops/clears // the setInterval and resolve the function function changeOpacity() { images[cur].style.opacity -= del; if (images[cur].style.opacity <= 0) { clearInterval(id); resolve(); } } }) } }</script>", "e": 4760, "s": 1070, "text": null }, { "code": null, "e": 4779, "s": 4762, "text": "Complete code: " }, { "code": null, "e": 4784, "s": 4779, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\" /> <title> Change Image Dynamically when User Scrolls </title> <style> body { text-align: center; } h1 { color: green; } img { position: absolute; left: 400px; } </style> </head> <body> <h1>GeeksforGeeks</h1> <b>A Computer Science Portal for Geeks</b> <div id=\"scroll-image\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200318142245/CSS8.png\" class=\"test\" /> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200318142309/php7.png\" class=\"test\" /> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200318142254/html9.png\" class=\"test\" /> </div> <script> startImageTransition(); function startImageTransition() { var images = document.getElementsByClassName(\"test\"); for (var i = 0; i < images.length; ++i) { images[i].style.opacity = 1; } var top = 1; var cur = images.length - 1; setInterval(changeImage, 3000); async function changeImage() { var nextImage = (1 + cur) % images.length; images[cur].style.zIndex = top + 1; images[nextImage].style.zIndex = top; await transition(); images[cur].style.zIndex = top; images[nextImage].style.zIndex = top + 1; top = top + 1; images[cur].style.opacity = 1; cur = nextImage; } function transition() { return new Promise(function(resolve, reject) { var del = 0.01; var id = setInterval(changeOpacity, 10); function changeOpacity() { images[cur].style.opacity -= del; if (images[cur].style.opacity <= 0) { clearInterval(id); resolve(); } } }) } } </script> </body> </html>", "e": 7040, "s": 4784, "text": null }, { "code": null, "e": 7050, "s": 7040, "text": "Output: " }, { "code": null, "e": 7206, "s": 7052, "text": "Note: The time interval at which images are changing should be greater than the time it takes to make the opacity of the image less than or equals to 0. " }, { "code": null, "e": 7221, "s": 7206, "text": "sagar0719kumar" }, { "code": null, "e": 7235, "s": 7221, "text": "sumitgumber28" }, { "code": null, "e": 7245, "s": 7235, "text": "HTML-Misc" }, { "code": null, "e": 7261, "s": 7245, "text": "JavaScript-Misc" }, { "code": null, "e": 7266, "s": 7261, "text": "HTML" }, { "code": null, "e": 7277, "s": 7266, "text": "JavaScript" }, { "code": null, "e": 7294, "s": 7277, "text": "Web Technologies" }, { "code": null, "e": 7321, "s": 7294, "text": "Web technologies Questions" }, { "code": null, "e": 7326, "s": 7321, "text": "HTML" }, { "code": null, "e": 7424, "s": 7326, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7448, "s": 7424, "text": "REST API (Introduction)" }, { "code": null, "e": 7476, "s": 7448, "text": "HTTP headers | Content-Type" }, { "code": null, "e": 7515, "s": 7476, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 7565, "s": 7515, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 7629, "s": 7565, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 7690, "s": 7629, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 7762, "s": 7690, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 7802, "s": 7762, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 7844, "s": 7802, "text": "Roadmap to Learn JavaScript For Beginners" } ]
Matplotlib.axes.Axes.set_yticks() in Python
19 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. The Axes.set_yticks() function in axes module of matplotlib library is used to Set the y ticks with list of ticks. Syntax:Axes.set_yticks(self, ticks, minor=False) Parameters: This method accepts the following parameters. ticks : This parameter is the list of y-axis tick locations. minor : This parameter is used whether set major ticks or to set minor ticks Return value: This method does not returns any value. Below examples illustrate the matplotlib.axes.Axes.set_yticks() function in matplotlib.axes: Example 1: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.transforms as mtransforms fig, ax = plt.subplots()ax.plot(range(12, 24), range(12))ax.set_yticks((2, 5, 7, 10)) fig.suptitle('matplotlib.axes.Axes.set_yticks()\ function Example\n\n', fontweight ="bold")plt.show() Output: Example 2: # Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt # Fixing random state for reproducibilitynp.random.seed(19680801) x = np.linspace(0, 2 * np.pi, 100)y = np.sin(x)y2 = y + 0.2 * np.random.normal(size = x.shape) fig, ax = plt.subplots()ax.plot(x, y)ax.plot(x, y2) ax.set_yticks([-1, 0, 1]) ax.spines['left'].set_bounds(-1, 1)ax.spines['right'].set_visible(False)ax.spines['top'].set_visible(False) fig.suptitle('matplotlib.axes.Axes.set_yticks()\ function Example\n\n', fontweight ="bold")fig.canvas.draw()plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Apr, 2020" }, { "code": null, "e": 328, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute." }, { "code": null, "e": 443, "s": 328, "text": "The Axes.set_yticks() function in axes module of matplotlib library is used to Set the y ticks with list of ticks." }, { "code": null, "e": 492, "s": 443, "text": "Syntax:Axes.set_yticks(self, ticks, minor=False)" }, { "code": null, "e": 550, "s": 492, "text": "Parameters: This method accepts the following parameters." }, { "code": null, "e": 611, "s": 550, "text": "ticks : This parameter is the list of y-axis tick locations." }, { "code": null, "e": 688, "s": 611, "text": "minor : This parameter is used whether set major ticks or to set minor ticks" }, { "code": null, "e": 742, "s": 688, "text": "Return value: This method does not returns any value." }, { "code": null, "e": 835, "s": 742, "text": "Below examples illustrate the matplotlib.axes.Axes.set_yticks() function in matplotlib.axes:" }, { "code": null, "e": 846, "s": 835, "text": "Example 1:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.transforms as mtransforms fig, ax = plt.subplots()ax.plot(range(12, 24), range(12))ax.set_yticks((2, 5, 7, 10)) fig.suptitle('matplotlib.axes.Axes.set_yticks()\\ function Example\\n\\n', fontweight =\"bold\")plt.show()", "e": 1152, "s": 846, "text": null }, { "code": null, "e": 1160, "s": 1152, "text": "Output:" }, { "code": null, "e": 1171, "s": 1160, "text": "Example 2:" }, { "code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt # Fixing random state for reproducibilitynp.random.seed(19680801) x = np.linspace(0, 2 * np.pi, 100)y = np.sin(x)y2 = y + 0.2 * np.random.normal(size = x.shape) fig, ax = plt.subplots()ax.plot(x, y)ax.plot(x, y2) ax.set_yticks([-1, 0, 1]) ax.spines['left'].set_bounds(-1, 1)ax.spines['right'].set_visible(False)ax.spines['top'].set_visible(False) fig.suptitle('matplotlib.axes.Axes.set_yticks()\\ function Example\\n\\n', fontweight =\"bold\")fig.canvas.draw()plt.show()", "e": 1732, "s": 1171, "text": null }, { "code": null, "e": 1740, "s": 1732, "text": "Output:" }, { "code": null, "e": 1758, "s": 1740, "text": "Python-matplotlib" }, { "code": null, "e": 1765, "s": 1758, "text": "Python" }, { "code": null, "e": 1863, "s": 1765, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1881, "s": 1863, "text": "Python Dictionary" }, { "code": null, "e": 1923, "s": 1881, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1945, "s": 1923, "text": "Enumerate() in Python" }, { "code": null, "e": 1980, "s": 1945, "text": "Read a file line by line in Python" }, { "code": null, "e": 2006, "s": 1980, "text": "Python String | replace()" }, { "code": null, "e": 2038, "s": 2006, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2067, "s": 2038, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2094, "s": 2067, "text": "Python Classes and Objects" }, { "code": null, "e": 2124, "s": 2094, "text": "Iterate over a list in Python" } ]
What is a functional interface in Java?
An interface with only one abstract method is known as Functional Interface. @FunctionalInterface annotation can be added so that we can mark an interface as a functional interface. The Java compiler automatically identifies the functional interface. The lambda expressions are used primarily to define the inline implementation of a functional interface. It eliminates the need for an anonymous class and gives a simple and powerful functional programming capability to Java. Few java default interfaces are functional interfaces listed below java.lang.Runnable java.util.concurrent.Callable java.io.FileFilter java.util.Comparator java.beans.PropertyChangeListener @FunctionalInterface interface interface-name { // only one abstract method } @FunctionalInterface interface MathOperation { int operation(int a, int b); } public class LambdaExpressionTest { public static void main(String args[]) { MathOperation addition = (a, b) -> a + b; // lambda expression MathOperation multiplication = (int a, int b) -> { return a * b; }; // lambda expression System.out.println("The addition of two numbers are: " + addition.operation(5, 5)); System.out.println("The multiplication of two numbers are: " + multiplication.operation(5, 5)); } } The addition of two numbers are: 10 The multiplication of two numbers are:: 25
[ { "code": null, "e": 1438, "s": 1187, "text": "An interface with only one abstract method is known as Functional Interface. @FunctionalInterface annotation can be added so that we can mark an interface as a functional interface. The Java compiler automatically identifies the functional interface." }, { "code": null, "e": 1664, "s": 1438, "text": "The lambda expressions are used primarily to define the inline implementation of a functional interface. It eliminates the need for an anonymous class and gives a simple and powerful functional programming capability to Java." }, { "code": null, "e": 1731, "s": 1664, "text": "Few java default interfaces are functional interfaces listed below" }, { "code": null, "e": 1750, "s": 1731, "text": "java.lang.Runnable" }, { "code": null, "e": 1780, "s": 1750, "text": "java.util.concurrent.Callable" }, { "code": null, "e": 1799, "s": 1780, "text": "java.io.FileFilter" }, { "code": null, "e": 1820, "s": 1799, "text": "java.util.Comparator" }, { "code": null, "e": 1854, "s": 1820, "text": "java.beans.PropertyChangeListener" }, { "code": null, "e": 1933, "s": 1854, "text": "@FunctionalInterface\ninterface interface-name {\n // only one abstract method\n}" }, { "code": null, "e": 2459, "s": 1933, "text": "@FunctionalInterface\ninterface MathOperation {\n int operation(int a, int b);\n}\npublic class LambdaExpressionTest {\n public static void main(String args[]) {\n MathOperation addition = (a, b) -> a + b; // lambda expression\n MathOperation multiplication = (int a, int b) -> { return a * b; }; // lambda expression\n System.out.println(\"The addition of two numbers are: \" + addition.operation(5, 5));\n System.out.println(\"The multiplication of two numbers are: \" + multiplication.operation(5, 5));\n }\n}" }, { "code": null, "e": 2538, "s": 2459, "text": "The addition of two numbers are: 10\nThe multiplication of two numbers are:: 25" } ]
Python Lambda Functions
07 Jun, 2022 Python Lambda Functions are anonymous function means that the function is without a name. As we already know that the def keyword is used to define a normal function in Python. Similarly, the lambda keyword is used to define an anonymous function in Python. Python Lambda Function Syntax: lambda arguments: expression This function can have any number of arguments but only one expression, which is evaluated and returned. One is free to use lambda functions wherever function objects are required. You need to keep in your knowledge that lambda functions are syntactically restricted to a single expression. It has various uses in particular fields of programming besides other types of expressions in functions. Python3 # Python program to demonstrate# lambda functions string ='GeeksforGeeks' # lambda returns a function objectprint(lambda string : string) <function <lambda> at 0x7f65e6bbce18> In this above example, the lambda is not being called by the print function but simply returning the function object and the memory location where it is stored. So, to make the print to print the string first we need to call the lambda so that the string will get pass the print. Python3 # Python program to demonstrate# lambda functions x ="GeeksforGeeks" # lambda gets pass to print(lambda x : print(x))(x) GeeksforGeeks Let’s look at this example and try to understand the difference between a normal def defined function and lambda function. This is a program that returns the cube of a given value: Python # Python code to illustrate cube of a number# showing difference between def() and lambda().def cube(y): return y*y*y lambda_cube = lambda y: y*y*y # using the normally# defined functionprint(cube(5)) # using the lambda functionprint(lambda_cube(5)) Output: 125 125 As we can see in the above example both the cube() function and lambda_cube() function behave the same and as intended. Let’s analyze the above example a bit more: Without using Lambda: Here, both of them return the cube of a given number. But, while using def, we needed to define a function with a name cube and needed to pass a value to it. After execution, we also needed to return the result from where the function was called using the return keyword. Using Lambda: Lambda definition does not include a “return” statement, it always contains an expression that is returned. We can also put a lambda definition anywhere a function is expected, and we don’t have to assign it to a variable at all. This is the simplicity of lambda functions. Let’s see some more commonly used examples of lambda functions. In this example, we will use the lambda function with list comprehension and lambda with for loop. We will try to print the table of 10. Python3 tables = [lambda x=x: x*10 for x in range(1, 11)] for table in tables: print(table()) 10 20 30 40 50 60 70 80 90 100 Python3 # Example of lambda function using if-elseMax = lambda a, b : a if(a > b) else b print(Max(1, 2)) 2 Lambda functions does not allow multiple statements, however, we can create two lambda functions and then call the other lambda function as a parameter to the first function. Let’s try to find the second maximum element using lambda. Python3 List = [[2,3,4],[1, 4, 16, 64],[3, 6, 9, 12]] # Sort each sublistsortList = lambda x: (sorted(i) for i in x) # Get the second largest elementsecondLargest = lambda x, f : [y[len(y)-2] for y in f(x)]res = secondLargest(List, sortList) print(res) [3, 16, 9] In the above example, we have created a lambda function that sorts each sublist of the given list. Then this list is passed as the parameter to the second lambda function which returns the n-2 element from the sorted list where n is the length of the sublist. Lambda functions can be used along with built-in functions like filter(), map() and reduce(). The filter() function in Python takes in a function and a list as arguments. This offers an elegant way to filter out all the elements of a sequence “sequence”, for which the function returns True. Here is a small program that returns the odd numbers from an input list: Example 1: Python # Python code to illustrate# filter() with lambda()li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61] final_list = list(filter(lambda x: (x%2 != 0) , li))print(final_list) Output: [5, 7, 97, 77, 23, 73, 61] Example 2: Python3 # Python 3 code to people above 18 yrsages = [13, 90, 17, 59, 21, 60, 5] adults = list(filter(lambda age: age>18, ages)) print(adults) Output: [90, 59, 21, 60] The map() function in Python takes in a function and a list as an argument. The function is called with a lambda function and a list and a new list is returned which contains all the lambda modified items returned by that function for each item. Example: Example 1: Python # Python code to illustrate# map() with lambda()# to get double of a list.li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61] final_list = list(map(lambda x: x*2, li))print(final_list) Output: [10, 14, 44, 194, 108, 124, 154, 46, 146, 122] Example 2: Python3 # Python program to demonstrate# use of lambda() function# with map() functionanimals = ['dog', 'cat', 'parrot', 'rabbit'] # here we intend to change all animal names# to upper case and return the sameuppered_animals = list(map(lambda animal: str.upper(animal), animals)) print(uppered_animals) Output: ['DOG', 'CAT', 'PARROT', 'RABBIT'] The reduce() function in Python takes in a function and a list as an argument. The function is called with a lambda function and an iterable and a new reduced result is returned. This performs a repetitive operation over the pairs of the iterable. The reduce() function belongs to the functools module. Example 1: Python # Python code to illustrate # reduce() with lambda()# to get sum of a list from functools import reduceli = [5, 8, 10, 20, 50, 100]sum = reduce((lambda x, y: x + y), li)print (sum) Output: 193 Here the results of previous two elements are added to the next element and this goes on till the end of the list like (((((5+8)+10)+20)+50)+100). Example 2: Python3 # python code to demonstrate working of reduce() # with a lambda function # importing functools for reduce() import functools # initializing list lis = [ 1 , 3, 5, 6, 2, ] # using reduce to compute maximum element from list print ("The maximum element of the list is : ",end="") print (functools.reduce(lambda a,b : a if a > b else b,lis)) Output: The maximum element of the list is : 6 RajuKumar19 simranarora5sos nikhilaggarwal3 ajayravuri3 amittt138 Python-Functions python-lambda Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jun, 2022" }, { "code": null, "e": 311, "s": 52, "text": "Python Lambda Functions are anonymous function means that the function is without a name. As we already know that the def keyword is used to define a normal function in Python. Similarly, the lambda keyword is used to define an anonymous function in Python. " }, { "code": null, "e": 342, "s": 311, "text": "Python Lambda Function Syntax:" }, { "code": null, "e": 371, "s": 342, "text": "lambda arguments: expression" }, { "code": null, "e": 476, "s": 371, "text": "This function can have any number of arguments but only one expression, which is evaluated and returned." }, { "code": null, "e": 552, "s": 476, "text": "One is free to use lambda functions wherever function objects are required." }, { "code": null, "e": 662, "s": 552, "text": "You need to keep in your knowledge that lambda functions are syntactically restricted to a single expression." }, { "code": null, "e": 767, "s": 662, "text": "It has various uses in particular fields of programming besides other types of expressions in functions." }, { "code": null, "e": 775, "s": 767, "text": "Python3" }, { "code": "# Python program to demonstrate# lambda functions string ='GeeksforGeeks' # lambda returns a function objectprint(lambda string : string)", "e": 917, "s": 775, "text": null }, { "code": null, "e": 955, "s": 917, "text": "<function <lambda> at 0x7f65e6bbce18>" }, { "code": null, "e": 1116, "s": 955, "text": "In this above example, the lambda is not being called by the print function but simply returning the function object and the memory location where it is stored." }, { "code": null, "e": 1235, "s": 1116, "text": "So, to make the print to print the string first we need to call the lambda so that the string will get pass the print." }, { "code": null, "e": 1243, "s": 1235, "text": "Python3" }, { "code": "# Python program to demonstrate# lambda functions x =\"GeeksforGeeks\" # lambda gets pass to print(lambda x : print(x))(x)", "e": 1368, "s": 1243, "text": null }, { "code": null, "e": 1382, "s": 1368, "text": "GeeksforGeeks" }, { "code": null, "e": 1565, "s": 1382, "text": "Let’s look at this example and try to understand the difference between a normal def defined function and lambda function. This is a program that returns the cube of a given value: " }, { "code": null, "e": 1572, "s": 1565, "text": "Python" }, { "code": "# Python code to illustrate cube of a number# showing difference between def() and lambda().def cube(y): return y*y*y lambda_cube = lambda y: y*y*y # using the normally# defined functionprint(cube(5)) # using the lambda functionprint(lambda_cube(5))", "e": 1828, "s": 1572, "text": null }, { "code": null, "e": 1836, "s": 1828, "text": "Output:" }, { "code": null, "e": 1844, "s": 1836, "text": "125\n125" }, { "code": null, "e": 2008, "s": 1844, "text": "As we can see in the above example both the cube() function and lambda_cube() function behave the same and as intended. Let’s analyze the above example a bit more:" }, { "code": null, "e": 2302, "s": 2008, "text": "Without using Lambda: Here, both of them return the cube of a given number. But, while using def, we needed to define a function with a name cube and needed to pass a value to it. After execution, we also needed to return the result from where the function was called using the return keyword." }, { "code": null, "e": 2590, "s": 2302, "text": "Using Lambda: Lambda definition does not include a “return” statement, it always contains an expression that is returned. We can also put a lambda definition anywhere a function is expected, and we don’t have to assign it to a variable at all. This is the simplicity of lambda functions." }, { "code": null, "e": 2654, "s": 2590, "text": "Let’s see some more commonly used examples of lambda functions." }, { "code": null, "e": 2791, "s": 2654, "text": "In this example, we will use the lambda function with list comprehension and lambda with for loop. We will try to print the table of 10." }, { "code": null, "e": 2799, "s": 2791, "text": "Python3" }, { "code": "tables = [lambda x=x: x*10 for x in range(1, 11)] for table in tables: print(table())", "e": 2889, "s": 2799, "text": null }, { "code": null, "e": 2920, "s": 2889, "text": "10\n20\n30\n40\n50\n60\n70\n80\n90\n100" }, { "code": null, "e": 2928, "s": 2920, "text": "Python3" }, { "code": "# Example of lambda function using if-elseMax = lambda a, b : a if(a > b) else b print(Max(1, 2))", "e": 3027, "s": 2928, "text": null }, { "code": null, "e": 3029, "s": 3027, "text": "2" }, { "code": null, "e": 3263, "s": 3029, "text": "Lambda functions does not allow multiple statements, however, we can create two lambda functions and then call the other lambda function as a parameter to the first function. Let’s try to find the second maximum element using lambda." }, { "code": null, "e": 3271, "s": 3263, "text": "Python3" }, { "code": "List = [[2,3,4],[1, 4, 16, 64],[3, 6, 9, 12]] # Sort each sublistsortList = lambda x: (sorted(i) for i in x) # Get the second largest elementsecondLargest = lambda x, f : [y[len(y)-2] for y in f(x)]res = secondLargest(List, sortList) print(res)", "e": 3519, "s": 3271, "text": null }, { "code": null, "e": 3530, "s": 3519, "text": "[3, 16, 9]" }, { "code": null, "e": 3790, "s": 3530, "text": "In the above example, we have created a lambda function that sorts each sublist of the given list. Then this list is passed as the parameter to the second lambda function which returns the n-2 element from the sorted list where n is the length of the sublist." }, { "code": null, "e": 3884, "s": 3790, "text": "Lambda functions can be used along with built-in functions like filter(), map() and reduce()." }, { "code": null, "e": 4156, "s": 3884, "text": "The filter() function in Python takes in a function and a list as arguments. This offers an elegant way to filter out all the elements of a sequence “sequence”, for which the function returns True. Here is a small program that returns the odd numbers from an input list: " }, { "code": null, "e": 4167, "s": 4156, "text": "Example 1:" }, { "code": null, "e": 4174, "s": 4167, "text": "Python" }, { "code": "# Python code to illustrate# filter() with lambda()li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61] final_list = list(filter(lambda x: (x%2 != 0) , li))print(final_list)", "e": 4340, "s": 4174, "text": null }, { "code": null, "e": 4348, "s": 4340, "text": "Output:" }, { "code": null, "e": 4375, "s": 4348, "text": "[5, 7, 97, 77, 23, 73, 61]" }, { "code": null, "e": 4386, "s": 4375, "text": "Example 2:" }, { "code": null, "e": 4394, "s": 4386, "text": "Python3" }, { "code": "# Python 3 code to people above 18 yrsages = [13, 90, 17, 59, 21, 60, 5] adults = list(filter(lambda age: age>18, ages)) print(adults)", "e": 4531, "s": 4394, "text": null }, { "code": null, "e": 4539, "s": 4531, "text": "Output:" }, { "code": null, "e": 4556, "s": 4539, "text": "[90, 59, 21, 60]" }, { "code": null, "e": 4812, "s": 4556, "text": "The map() function in Python takes in a function and a list as an argument. The function is called with a lambda function and a list and a new list is returned which contains all the lambda modified items returned by that function for each item. Example: " }, { "code": null, "e": 4823, "s": 4812, "text": "Example 1:" }, { "code": null, "e": 4830, "s": 4823, "text": "Python" }, { "code": "# Python code to illustrate# map() with lambda()# to get double of a list.li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61] final_list = list(map(lambda x: x*2, li))print(final_list)", "e": 5008, "s": 4830, "text": null }, { "code": null, "e": 5016, "s": 5008, "text": "Output:" }, { "code": null, "e": 5063, "s": 5016, "text": "[10, 14, 44, 194, 108, 124, 154, 46, 146, 122]" }, { "code": null, "e": 5074, "s": 5063, "text": "Example 2:" }, { "code": null, "e": 5082, "s": 5074, "text": "Python3" }, { "code": "# Python program to demonstrate# use of lambda() function# with map() functionanimals = ['dog', 'cat', 'parrot', 'rabbit'] # here we intend to change all animal names# to upper case and return the sameuppered_animals = list(map(lambda animal: str.upper(animal), animals)) print(uppered_animals)", "e": 5379, "s": 5082, "text": null }, { "code": null, "e": 5387, "s": 5379, "text": "Output:" }, { "code": null, "e": 5422, "s": 5387, "text": "['DOG', 'CAT', 'PARROT', 'RABBIT']" }, { "code": null, "e": 5727, "s": 5422, "text": "The reduce() function in Python takes in a function and a list as an argument. The function is called with a lambda function and an iterable and a new reduced result is returned. This performs a repetitive operation over the pairs of the iterable. The reduce() function belongs to the functools module. " }, { "code": null, "e": 5738, "s": 5727, "text": "Example 1:" }, { "code": null, "e": 5745, "s": 5738, "text": "Python" }, { "code": "# Python code to illustrate # reduce() with lambda()# to get sum of a list from functools import reduceli = [5, 8, 10, 20, 50, 100]sum = reduce((lambda x, y: x + y), li)print (sum)", "e": 5927, "s": 5745, "text": null }, { "code": null, "e": 5935, "s": 5927, "text": "Output:" }, { "code": null, "e": 5939, "s": 5935, "text": "193" }, { "code": null, "e": 6086, "s": 5939, "text": "Here the results of previous two elements are added to the next element and this goes on till the end of the list like (((((5+8)+10)+20)+50)+100)." }, { "code": null, "e": 6097, "s": 6086, "text": "Example 2:" }, { "code": null, "e": 6105, "s": 6097, "text": "Python3" }, { "code": "# python code to demonstrate working of reduce() # with a lambda function # importing functools for reduce() import functools # initializing list lis = [ 1 , 3, 5, 6, 2, ] # using reduce to compute maximum element from list print (\"The maximum element of the list is : \",end=\"\") print (functools.reduce(lambda a,b : a if a > b else b,lis)) ", "e": 6451, "s": 6105, "text": null }, { "code": null, "e": 6459, "s": 6451, "text": "Output:" }, { "code": null, "e": 6498, "s": 6459, "text": "The maximum element of the list is : 6" }, { "code": null, "e": 6510, "s": 6498, "text": "RajuKumar19" }, { "code": null, "e": 6526, "s": 6510, "text": "simranarora5sos" }, { "code": null, "e": 6542, "s": 6526, "text": "nikhilaggarwal3" }, { "code": null, "e": 6554, "s": 6542, "text": "ajayravuri3" }, { "code": null, "e": 6564, "s": 6554, "text": "amittt138" }, { "code": null, "e": 6581, "s": 6564, "text": "Python-Functions" }, { "code": null, "e": 6595, "s": 6581, "text": "python-lambda" }, { "code": null, "e": 6602, "s": 6595, "text": "Python" } ]
Java Stream findAny() with examples
06 Dec, 2018 Stream findAny() returns an Optional (a container object which may or may not contain a non-null value) describing some element of the stream, or an empty Optional if the stream is empty. findAny() V/s findFirst() : The findAny() method returns any element from a Stream but there might be a case where we require the first element of a filtered stream to be fetched. When the stream being worked on has a defined encounter order(the order in which the elements of a stream are processed), then findFirst() is useful which returns the first element in a Stream. Syntax : Optional<T> findAny() Where, Optional is a container object which may or may not contain a non-null value and T is the type of objects and the function returns an Optional describing some element of this stream, or an empty Optional if the stream is empty. Exception : If the element selected is null, NullPointerException is thrown. Note : findAny() is a terminal-short-circuiting operation of Stream interface. This method returns any first element satisfying the intermediate operations. This is a short-circuit operation because it just needs ‘any’ first element to be returned and terminate the rest of the iteration. Example 1 : findAny() method on Integer Stream. // Java code for Stream findAny()// which returns an Optional describing// some element of the stream, or an// empty Optional if the stream is empty.import java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a List of Integers List<Integer> list = Arrays.asList(2, 4, 6, 8, 10); // Using Stream findAny() to return // an Optional describing some element // of the stream Optional<Integer> answer = list.stream().findAny(); // if the stream is empty, an empty // Optional is returned. if (answer.isPresent()) { System.out.println(answer.get()); } else { System.out.println("no value"); } }} Output : 2 Example 2 : findAny() function on Stream of Strings. // Java code for Stream findAny()// which returns an Optional describing// some element of the stream, or an// empty Optional if the stream is empty.import java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a List of Strings List<String> list = Arrays.asList("Geeks", "for", "GeeksQuiz", "GFG"); // Using Stream findAny() to return // an Optional describing some element // of the stream Optional<String> answer = list.stream().findAny(); // if the stream is empty, an empty // Optional is returned. if (answer.isPresent()) { System.out.println(answer.get()); } else { System.out.println("no value"); } }} Output : Geeks Note : The behavior of Stream findAny() operation is explicitly non-deterministic i.e, it is free to select any element in the stream. Multiple invocations on the same source may not return the same result.Example 3 : findAny() method to return the elements divisible by 4, in a non-deterministic way. // Java code for Stream findAny() // which returns an Optional describing// some element of the stream, or an // empty Optional if the stream is empty.import java.util.OptionalInt;import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream IntStream stream = IntStream.of(4, 5, 8, 10, 12, 16) .parallel(); // Using Stream findAny(). // Executing the source code multiple times // may not return the same result. // Every time you may get a different // Integer which is divisible by 4. stream = stream.filter(i -> i % 4 == 0); OptionalInt answer = stream.findAny(); if (answer.isPresent()) { System.out.println(answer.getAsInt()); }}} Output : 16 Java - util package Java-Functions java-stream Java-Stream interface Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Collections in Java Multidimensional Arrays in Java Singleton Class in Java Set in Java Stack Class in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Dec, 2018" }, { "code": null, "e": 216, "s": 28, "text": "Stream findAny() returns an Optional (a container object which may or may not contain a non-null value) describing some element of the stream, or an empty Optional if the stream is empty." }, { "code": null, "e": 244, "s": 216, "text": "findAny() V/s findFirst() :" }, { "code": null, "e": 590, "s": 244, "text": "The findAny() method returns any element from a Stream but there might be a case where we require the first element of a filtered stream to be fetched. When the stream being worked on has a defined encounter order(the order in which the elements of a stream are processed), then findFirst() is useful which returns the first element in a Stream." }, { "code": null, "e": 599, "s": 590, "text": "Syntax :" }, { "code": null, "e": 859, "s": 599, "text": "Optional<T> findAny()\n\nWhere, Optional is a container object which\nmay or may not contain a non-null value \nand T is the type of objects and the function\nreturns an Optional describing some element of\nthis stream, or an empty Optional if the stream is empty.\n" }, { "code": null, "e": 936, "s": 859, "text": "Exception : If the element selected is null, NullPointerException is thrown." }, { "code": null, "e": 1225, "s": 936, "text": "Note : findAny() is a terminal-short-circuiting operation of Stream interface. This method returns any first element satisfying the intermediate operations. This is a short-circuit operation because it just needs ‘any’ first element to be returned and terminate the rest of the iteration." }, { "code": null, "e": 1273, "s": 1225, "text": "Example 1 : findAny() method on Integer Stream." }, { "code": "// Java code for Stream findAny()// which returns an Optional describing// some element of the stream, or an// empty Optional if the stream is empty.import java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a List of Integers List<Integer> list = Arrays.asList(2, 4, 6, 8, 10); // Using Stream findAny() to return // an Optional describing some element // of the stream Optional<Integer> answer = list.stream().findAny(); // if the stream is empty, an empty // Optional is returned. if (answer.isPresent()) { System.out.println(answer.get()); } else { System.out.println(\"no value\"); } }}", "e": 2031, "s": 1273, "text": null }, { "code": null, "e": 2040, "s": 2031, "text": "Output :" }, { "code": null, "e": 2043, "s": 2040, "text": "2\n" }, { "code": null, "e": 2096, "s": 2043, "text": "Example 2 : findAny() function on Stream of Strings." }, { "code": "// Java code for Stream findAny()// which returns an Optional describing// some element of the stream, or an// empty Optional if the stream is empty.import java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a List of Strings List<String> list = Arrays.asList(\"Geeks\", \"for\", \"GeeksQuiz\", \"GFG\"); // Using Stream findAny() to return // an Optional describing some element // of the stream Optional<String> answer = list.stream().findAny(); // if the stream is empty, an empty // Optional is returned. if (answer.isPresent()) { System.out.println(answer.get()); } else { System.out.println(\"no value\"); } }}", "e": 2912, "s": 2096, "text": null }, { "code": null, "e": 2921, "s": 2912, "text": "Output :" }, { "code": null, "e": 2928, "s": 2921, "text": "Geeks\n" }, { "code": null, "e": 3230, "s": 2928, "text": "Note : The behavior of Stream findAny() operation is explicitly non-deterministic i.e, it is free to select any element in the stream. Multiple invocations on the same source may not return the same result.Example 3 : findAny() method to return the elements divisible by 4, in a non-deterministic way." }, { "code": "// Java code for Stream findAny() // which returns an Optional describing// some element of the stream, or an // empty Optional if the stream is empty.import java.util.OptionalInt;import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream IntStream stream = IntStream.of(4, 5, 8, 10, 12, 16) .parallel(); // Using Stream findAny(). // Executing the source code multiple times // may not return the same result. // Every time you may get a different // Integer which is divisible by 4. stream = stream.filter(i -> i % 4 == 0); OptionalInt answer = stream.findAny(); if (answer.isPresent()) { System.out.println(answer.getAsInt()); }}}", "e": 4032, "s": 3230, "text": null }, { "code": null, "e": 4041, "s": 4032, "text": "Output :" }, { "code": null, "e": 4045, "s": 4041, "text": "16\n" }, { "code": null, "e": 4065, "s": 4045, "text": "Java - util package" }, { "code": null, "e": 4080, "s": 4065, "text": "Java-Functions" }, { "code": null, "e": 4092, "s": 4080, "text": "java-stream" }, { "code": null, "e": 4114, "s": 4092, "text": "Java-Stream interface" }, { "code": null, "e": 4119, "s": 4114, "text": "Java" }, { "code": null, "e": 4124, "s": 4119, "text": "Java" }, { "code": null, "e": 4222, "s": 4124, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4273, "s": 4222, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 4304, "s": 4273, "text": "How to iterate any Map in Java" }, { "code": null, "e": 4323, "s": 4304, "text": "Interfaces in Java" }, { "code": null, "e": 4353, "s": 4323, "text": "HashMap in Java with Examples" }, { "code": null, "e": 4371, "s": 4353, "text": "ArrayList in Java" }, { "code": null, "e": 4391, "s": 4371, "text": "Collections in Java" }, { "code": null, "e": 4423, "s": 4391, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 4447, "s": 4423, "text": "Singleton Class in Java" }, { "code": null, "e": 4459, "s": 4447, "text": "Set in Java" } ]
strings.Index() Function in Golang With Examples
19 Apr, 2020 strings.Index() Function in Golang is used to get the first instance of a specified substring. If the substring is not found, then this method will return -1. Syntax: func Index(str, sbstr string) int Here, str is the original string and sbstr is a string whose we want to find index value. Example 1: // Go program to illustrate the // String Index() Function package main import ( "fmt" "strings") // Main function func main() { // Creating and initializing the strings str1 := "Welcome to GeeksforGeeks" str2 := "My name is XYZ" // Displaying strings fmt.Println("String 1: ", str1) fmt.Println("String 2: ", str2) // Using Index() function res1 := strings.Index(str1, "Geeks") res2 := strings.Index(str2, "is") // Displaying the result fmt.Println("\nIndex values:") fmt.Println("Result 1: ", res1) fmt.Println("Result 2: ", res2) } Output: String 1: Welcome to GeeksforGeeks String 2: My name is XYZ Index values: Result 1: 11 Result 2: 8 Example 2: // Go program to illustrate the// String Index() Function package main import ( "fmt" "strings") // Main functionfunc main() { // Using Index() function res1 := strings.Index("GFG", "H") res2 := strings.Index("GeeksforGeeks", "for") // Displaying the result fmt.Println("Result 1: ", res1) fmt.Println("Result 2: ", res2) } Output: Result 1: -1 Result 2: 5 Golang-String Picked Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Golang Maps Arrays in Go How to copy one slice into another slice in Golang? Time Durations in Golang Interfaces in Golang Inheritance in GoLang Check if the String starts with specified prefix in Golang How to iterate over an Array using for loop in Golang? How to compare two slices of bytes in Golang? Type Casting or Type Conversion in Golang
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Apr, 2020" }, { "code": null, "e": 187, "s": 28, "text": "strings.Index() Function in Golang is used to get the first instance of a specified substring. If the substring is not found, then this method will return -1." }, { "code": null, "e": 195, "s": 187, "text": "Syntax:" }, { "code": null, "e": 229, "s": 195, "text": "func Index(str, sbstr string) int" }, { "code": null, "e": 319, "s": 229, "text": "Here, str is the original string and sbstr is a string whose we want to find index value." }, { "code": null, "e": 330, "s": 319, "text": "Example 1:" }, { "code": "// Go program to illustrate the // String Index() Function package main import ( \"fmt\" \"strings\") // Main function func main() { // Creating and initializing the strings str1 := \"Welcome to GeeksforGeeks\" str2 := \"My name is XYZ\" // Displaying strings fmt.Println(\"String 1: \", str1) fmt.Println(\"String 2: \", str2) // Using Index() function res1 := strings.Index(str1, \"Geeks\") res2 := strings.Index(str2, \"is\") // Displaying the result fmt.Println(\"\\nIndex values:\") fmt.Println(\"Result 1: \", res1) fmt.Println(\"Result 2: \", res2) } ", "e": 957, "s": 330, "text": null }, { "code": null, "e": 965, "s": 957, "text": "Output:" }, { "code": null, "e": 1070, "s": 965, "text": "String 1: Welcome to GeeksforGeeks\nString 2: My name is XYZ\n\nIndex values:\nResult 1: 11\nResult 2: 8\n" }, { "code": null, "e": 1081, "s": 1070, "text": "Example 2:" }, { "code": "// Go program to illustrate the// String Index() Function package main import ( \"fmt\" \"strings\") // Main functionfunc main() { // Using Index() function res1 := strings.Index(\"GFG\", \"H\") res2 := strings.Index(\"GeeksforGeeks\", \"for\") // Displaying the result fmt.Println(\"Result 1: \", res1) fmt.Println(\"Result 2: \", res2) }", "e": 1437, "s": 1081, "text": null }, { "code": null, "e": 1445, "s": 1437, "text": "Output:" }, { "code": null, "e": 1473, "s": 1445, "text": "Result 1: -1\nResult 2: 5\n" }, { "code": null, "e": 1487, "s": 1473, "text": "Golang-String" }, { "code": null, "e": 1494, "s": 1487, "text": "Picked" }, { "code": null, "e": 1506, "s": 1494, "text": "Go Language" }, { "code": null, "e": 1604, "s": 1506, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1616, "s": 1604, "text": "Golang Maps" }, { "code": null, "e": 1629, "s": 1616, "text": "Arrays in Go" }, { "code": null, "e": 1681, "s": 1629, "text": "How to copy one slice into another slice in Golang?" }, { "code": null, "e": 1706, "s": 1681, "text": "Time Durations in Golang" }, { "code": null, "e": 1727, "s": 1706, "text": "Interfaces in Golang" }, { "code": null, "e": 1749, "s": 1727, "text": "Inheritance in GoLang" }, { "code": null, "e": 1808, "s": 1749, "text": "Check if the String starts with specified prefix in Golang" }, { "code": null, "e": 1863, "s": 1808, "text": "How to iterate over an Array using for loop in Golang?" }, { "code": null, "e": 1909, "s": 1863, "text": "How to compare two slices of bytes in Golang?" } ]
How to hide div element after few seconds in jQuery ?
18 Jun, 2019 Given a div element and the task is to hide the div element after few seconds using jQuery ? Approach: Select the div element. Use delay function (setTimeOut(), delay()) to provide the delay to hide() the div element. Example 1: In this example, the setTimeOut() method is used to provide delay to the fadeOut() method. <!DOCTYPE HTML> <html> <head> <title> How to hide div element after few seconds in jQuery ? </title> <style> #div { background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } </style> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;"> </p> <div id = "div"> This is Div box. </div> <br> <button onClick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;"> </p> <script> $('#GFG_UP').text("Click on button to hide div after 1 sec."); function GFG_Fun() { setTimeout(function() { $('#div').fadeOut('fast'); }, 1000); $('#GFG_DOWN').text("Div hides after 1 second."); } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: In this example, the delay() method is used to provide delay to the fadeOut() method. <!DOCTYPE HTML> <html> <head> <title> How to hide div element after few seconds in jQuery ? </title> <style> #div { background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } </style> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;"> </p> <div id = "div"> This is Div box. </div> <br> <button onClick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;"> </p> <script> $('#GFG_UP').text("Click on button to hide div after 1 sec."); function GFG_Fun() { $("#div").delay(1000).fadeOut(500); $('#GFG_DOWN').text("Div hides after 1 second."); } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: jQuery-HTML/CSS JavaScript Web Technologies Web technologies Questions 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": "\n18 Jun, 2019" }, { "code": null, "e": 121, "s": 28, "text": "Given a div element and the task is to hide the div element after few seconds using jQuery ?" }, { "code": null, "e": 131, "s": 121, "text": "Approach:" }, { "code": null, "e": 155, "s": 131, "text": "Select the div element." }, { "code": null, "e": 246, "s": 155, "text": "Use delay function (setTimeOut(), delay()) to provide the delay to hide() the div element." }, { "code": null, "e": 348, "s": 246, "text": "Example 1: In this example, the setTimeOut() method is used to provide delay to the fadeOut() method." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to hide div element after few seconds in jQuery ? </title> <style> #div { background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } </style> <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 19px; font-weight: bold;\"> </p> <div id = \"div\"> This is Div box. </div> <br> <button onClick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color: green; font-size: 24px; font-weight: bold;\"> </p> <script> $('#GFG_UP').text(\"Click on button to hide div after 1 sec.\"); function GFG_Fun() { setTimeout(function() { $('#div').fadeOut('fast'); }, 1000); $('#GFG_DOWN').text(\"Div hides after 1 second.\"); } </script> </body> </html> ", "e": 1774, "s": 348, "text": null }, { "code": null, "e": 1782, "s": 1774, "text": "Output:" }, { "code": null, "e": 1813, "s": 1782, "text": "Before clicking on the button:" }, { "code": null, "e": 1843, "s": 1813, "text": "After clicking on the button:" }, { "code": null, "e": 1940, "s": 1843, "text": "Example 2: In this example, the delay() method is used to provide delay to the fadeOut() method." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to hide div element after few seconds in jQuery ? </title> <style> #div { background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } </style> <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 19px; font-weight: bold;\"> </p> <div id = \"div\"> This is Div box. </div> <br> <button onClick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color: green; font-size: 24px; font-weight: bold;\"> </p> <script> $('#GFG_UP').text(\"Click on button to hide div after 1 sec.\"); function GFG_Fun() { $(\"#div\").delay(1000).fadeOut(500); $('#GFG_DOWN').text(\"Div hides after 1 second.\"); } </script> </body> </html> ", "e": 3311, "s": 1940, "text": null }, { "code": null, "e": 3319, "s": 3311, "text": "Output:" }, { "code": null, "e": 3350, "s": 3319, "text": "Before clicking on the button:" }, { "code": null, "e": 3380, "s": 3350, "text": "After clicking on the button:" }, { "code": null, "e": 3396, "s": 3380, "text": "jQuery-HTML/CSS" }, { "code": null, "e": 3407, "s": 3396, "text": "JavaScript" }, { "code": null, "e": 3424, "s": 3407, "text": "Web Technologies" }, { "code": null, "e": 3451, "s": 3424, "text": "Web technologies Questions" }, { "code": null, "e": 3549, "s": 3451, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3610, "s": 3549, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3682, "s": 3610, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3722, "s": 3682, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3763, "s": 3722, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3805, "s": 3763, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3867, "s": 3805, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3900, "s": 3867, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3961, "s": 3900, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4011, "s": 3961, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Reverse an array without using subtract sign ‘-‘ anywhere in the code
12 Jun, 2022 Given an array, the task is to reverse the array without using subtract sign ‘-‘ anywhere in your code. It is not tough to reverse an array but the main thing is to not use ‘-‘ operator. Asked in: Moonfrog InterviewBelow are different approaches: Method 1: 1- Store array elements into a vector in C++. 2- Then reverse the vector using predefined functions. 3- Then store reversed elements into the array back.Method 2: 1- Store array elements into a stack. 2- As the stack follows Last In First Out, so we can store elements from top of the stack into the array which will be itself in a reverse manner. Method 3: 1- In this method, the idea is to use a negative sign but by storing it into a variable. 2- By using this statement x = (INT_MIN/INT_MAX), we get -1 in a variable x. 3- As INT_MIN and INT_MAX have same values just of opposite signs, so on dividing them it will give -1. 4- Then ‘x’ can be used in decrementing the index from last. C++ Java Python3 C# PHP Javascript // C++ program to reverse an array without// using "-" sign#include <bits/stdc++.h>using namespace std; // Function to reverse arrayvoid reverseArray(int arr[], int n){ // Trick to assign -1 to a variable int x = (INT_MIN / INT_MAX); // Reverse array in simple manner for (int i = 0; i < n / 2; i++) // Swap ith index value with (n-i-1)th // index value swap(arr[i], arr[n + (x * i) + x]);} // Drivers codeint main(){ int arr[] = { 5, 3, 7, 2, 1, 6 }; int n = sizeof(arr) / sizeof(arr[0]); reverseArray(arr, n); // print the reversed array for (int i = 0; i < n; i++) cout << arr[i] << " "; return 0;} // Java program to reverse an array without// using "-" signclass GFG { // Function to reverse array static void reverseArray(int arr[], int n) { // Trick to assign -1 to a variable int x = (Integer.MIN_VALUE / Integer.MAX_VALUE); // Reverse array in simple manner for (int i = 0; i < n / 2; i++) // Swap ith index value with (n-i-1)th // index value swap(arr, i, n + (x * i) + x); } static int[] swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr; } // Drivers code public static void main(String[] args) { int arr[] = { 5, 3, 7, 2, 1, 6 }; int n = arr.length; reverseArray(arr, n); // print the reversed array for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); }} // This code has been contributed by 29AjayKumar # Python program to reverse an array without# using "-" sign # Function to reverse arraydef reverseArray(arr, n): import sys # Trick to assign - 1 to a variable x = -sys.maxsize // sys.maxsize # Reverse array in simple manner for i in range(n//2): # Swap ith index value with (n-i-1)th # index value arr[i], arr[n + (x*i) + x] = arr[n + (x*i) + x], arr[i] # Driver codeif __name__ == "__main__": arr = [5, 3, 7, 2, 1, 6] n = len(arr) reverseArray(arr, n) # print the reversed array for i in range(n): print(arr[i], end=" ") # This code is contributed by# sanjeev2552 // C# program to reverse an array without// using "-" signusing System; class GFG { // Function to reverse array static void reverseArray(int[] arr, int n) { // Trick to assign -1 to a variable int x = (int.MinValue / int.MaxValue); // Reverse array in simple manner for (int i = 0; i < n / 2; i++) // Swap ith index value with (n-i-1)th // index value swap(arr, i, n + (x * i) + x); } static int[] swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr; } // Drivers code public static void Main() { int[] arr = { 5, 3, 7, 2, 1, 6 }; int n = arr.Length; reverseArray(arr, n); // print the reversed array for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); }} /* This code contributed by PrinciRaj1992 */ <?PHP// PHP program to reverse an array without// using "-" sign // Function to reverse arrayfunction reverseArray(&$arr, $n){ // Trick to assign -1 to a variable $x = (PHP_INT_MIN / PHP_INT_MAX); // Reverse array in simple manner for ($i = 0; $i < $n / 2; $i++) // Swap ith index value with (n-i-1)th // index value swap($arr, $i, $n + ($x * $i) + $x);} function swap(&$arr, $i, $j){ $temp = $arr[$i]; $arr[$i] = $arr[$j]; $arr[$j] = $temp; return $arr;} // Drivers code$arr = array( 5, 3, 7, 2, 1, 6 );$n = sizeof($arr); reverseArray($arr, $n); // print the reversed arrayfor ($i = 0; $i < $n; $i++) echo($arr[$i] . " "); // This code is contributed by Code_Mech <script> //javascript program to reverse an array without // using "-" sign // Function to reverse array function reversearray(arr,n) { // Trick to assign -1 to a variable let x = parseInt(-2147483648 / 2147483647, 10); // Reverse array in simple manner for (let i = 0; i < parseInt(n / 2, 10); i++) { // Swap ith index value with (n-i-1)th // index value let temp = arr[i]; arr[i] = arr[n + (x * i) + x]; arr[n + (x * i) + x] = temp; } } let arr = [ 5, 3, 7, 2, 1, 6 ]; let n = arr.length; reversearray(arr, n); // print the reversed array for (let i = 0; i < n; i++) document.write(arr[i] +" "); // This code is contributed by vaibhavrabadiya117.</script> Output: 6 1 2 7 3 5 Time Complexity: O(n) Auxiliary Space: O(1) Method 4: In this method 4, the idea is to use bitwise operator to implement subtraction i.e. A – B = A + ~B + 1 so, i– can be written as i = i +~1 +1 C++ Java Python3 C# PHP Javascript // C++ program to reverse an array without// using "-" sign#include <bits/stdc++.h>using namespace std; // Function to reverse arrayvoid reverseArray(int arr[], int n){ // Reverse array in simple manner for (int i = 0; i < n / 2; i++) // Swap ith index value with (n-i-1)th // index value // Note : A - B = A + ~B + 1 // So n - i = n + ~i + 1 then // n - i - 1 = (n + ~i + 1) + ~1 + 1 swap(arr[i], arr[(n + ~i + 1) + ~1 + 1]);} // Driver codeint main(){ int arr[] = { 5, 3, 7, 2, 1, 6 }; int n = sizeof(arr) / sizeof(arr[0]); reverseArray(arr, n); // print the reversed array for (int i = 0; i < n; i++) cout << arr[i] << " "; return 0;} // Java program to reverse an array without// using "-" signimport java.util.Arrays; class GFG { // Function to reverse array static void reverseArray(int arr[], int n) { // Reverse array in simple manner for (int i = 0; i < n / 2; i++) // Swap ith index value with (n-i-1)th // index value // Note : A - B = A + ~B + 1 // So n - i = n + ~i + 1 then // n - i - 1 = (n + ~i + 1) + ~1 + 1 { swap(arr, i, (n + ~i + 1) + ~1 + 1); } } static int[] swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr; } // Driver code public static void main(String args[]) { int arr[] = { 5, 3, 7, 2, 1, 6 }; int n = arr.length; reverseArray(arr, n); // print the reversed array for (int i = 0; i < n; i++) { System.out.print(arr[i] + " "); } }} // This code contributed by Rajput-Ji # Python program to reverse an array without# using "-" sign # Function to reverse arraydef reverseArray(arr, n): # Reverse array in simple manner for i in range(n//2): # Swap ith index value with (n-i-1)th # index value # Note : A - B = A + ~B + 1 # So n - i = n + ~i + 1 then # n - i - 1 = (n + ~i + 1) + ~1 + 1 arr[i], arr[(n + ~i + 1) + ~1 + 1] = arr[(n + ~i + 1) + ~1 + 1],arr[i] # Driver code arr = [ 5, 3, 7, 2, 1, 6 ]n = len(arr) reverseArray(arr, n) # print the reversed arrayfor i in range(n): print(arr[i],end=" ") # This code is contributed by ankush_953 // C# program to reverse an array without// using "-" signusing System; class GFG { // Function to reverse array static void reverseArray(int[] arr, int n) { // Reverse array in simple manner for (int i = 0; i < n / 2; i++) // Swap ith index value with (n-i-1)th // index value // Note : A - B = A + ~B + 1 // So n - i = n + ~i + 1 then // n - i - 1 = (n + ~i + 1) + ~1 + 1 { swap(arr, i, (n + ~i + 1) + ~1 + 1); } } static int[] swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr; } // Driver code public static void Main(String[] args) { int[] arr = { 5, 3, 7, 2, 1, 6 }; int n = arr.Length; reverseArray(arr, n); // print the reversed array for (int i = 0; i < n; i++) { Console.Write(arr[i] + " "); } }} // This code has been contributed by 29AjayKumar <?PHP // PHP program to reverse an array without // using "-" sign // Function to reverse array function reverseArray(&$arr, $n) { // Reverse array in simple manner for ($i = 0; $i < $n / 2; $i++) // Swap ith index value with (n-i-1)th // index value // Note : A - B = A + ~B + 1 // So n - i = n + ~i + 1 then // n - i - 1 = (n + ~i + 1) + 1 + 1 { swap($arr, $i, ($n + ~$i + 1) + ~1 + 1); } } function swap(&$arr, $i, $j) { $temp = $arr[$i]; $arr[$i] = $arr[$j]; $arr[$j] = $temp; return $arr; } // Driver code { $arr = array( 5, 3, 7, 2, 1, 6 ); $n = sizeof($arr); reverseArray($arr, $n); // print the reversed array for ($i = 0; $i < $n; $i++) { echo($arr[$i] . " "); } } // This code contributed by Code_Mech <script> // Javascript program to reverse an array without using "-" sign // Function to reverse array function reverseArray(arr, n) { // Reverse array in simple manner for (let i = 0; i < parseInt(n / 2, 10); i++) // Swap ith index value with (n-i-1)th // index value // Note : A - B = A + ~B + 1 // So n - i = n + ~i + 1 then // n - i - 1 = (n + ~i + 1) + ~1 + 1 { swap(arr, i, (n + ~i + 1) + ~1 + 1); } } function swap(arr, i, j) { let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr; } let arr = [ 5, 3, 7, 2, 1, 6 ]; let n = arr.length; reverseArray(arr, n); // print the reversed array for (let i = 0; i < n; i++) { document.write(arr[i] + " "); } // This code is contributed by mukesh07.</script> Output: 6 1 2 7 3 5 Time Complexity: O(n) Auxiliary Space: O(1) This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 29AjayKumar princiraj1992 Akanksha_Rai Rajput-Ji Code_Mech ankush_953 sanjeev2552 vaibhavrabadiya117 mukesh07 ranjanrohit840 Infosys Moonfrog Labs Reverse Arrays Bit Magic Infosys Moonfrog Labs Arrays Bit Magic Reverse Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Window Sliding Technique Search, insert and delete in an unsorted array Chocolate Distribution Problem What is Data Structure: Types, Classifications and Applications Bitwise Operators in C/C++ Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Count set bits in an integer How to swap two numbers without using a temporary variable?
[ { "code": null, "e": 54, "s": 26, "text": "\n12 Jun, 2022" }, { "code": null, "e": 242, "s": 54, "text": "Given an array, the task is to reverse the array without using subtract sign ‘-‘ anywhere in your code. It is not tough to reverse an array but the main thing is to not use ‘-‘ operator. " }, { "code": null, "e": 1002, "s": 242, "text": "Asked in: Moonfrog InterviewBelow are different approaches: Method 1: 1- Store array elements into a vector in C++. 2- Then reverse the vector using predefined functions. 3- Then store reversed elements into the array back.Method 2: 1- Store array elements into a stack. 2- As the stack follows Last In First Out, so we can store elements from top of the stack into the array which will be itself in a reverse manner. Method 3: 1- In this method, the idea is to use a negative sign but by storing it into a variable. 2- By using this statement x = (INT_MIN/INT_MAX), we get -1 in a variable x. 3- As INT_MIN and INT_MAX have same values just of opposite signs, so on dividing them it will give -1. 4- Then ‘x’ can be used in decrementing the index from last. " }, { "code": null, "e": 1006, "s": 1002, "text": "C++" }, { "code": null, "e": 1011, "s": 1006, "text": "Java" }, { "code": null, "e": 1019, "s": 1011, "text": "Python3" }, { "code": null, "e": 1022, "s": 1019, "text": "C#" }, { "code": null, "e": 1026, "s": 1022, "text": "PHP" }, { "code": null, "e": 1037, "s": 1026, "text": "Javascript" }, { "code": "// C++ program to reverse an array without// using \"-\" sign#include <bits/stdc++.h>using namespace std; // Function to reverse arrayvoid reverseArray(int arr[], int n){ // Trick to assign -1 to a variable int x = (INT_MIN / INT_MAX); // Reverse array in simple manner for (int i = 0; i < n / 2; i++) // Swap ith index value with (n-i-1)th // index value swap(arr[i], arr[n + (x * i) + x]);} // Drivers codeint main(){ int arr[] = { 5, 3, 7, 2, 1, 6 }; int n = sizeof(arr) / sizeof(arr[0]); reverseArray(arr, n); // print the reversed array for (int i = 0; i < n; i++) cout << arr[i] << \" \"; return 0;}", "e": 1702, "s": 1037, "text": null }, { "code": "// Java program to reverse an array without// using \"-\" signclass GFG { // Function to reverse array static void reverseArray(int arr[], int n) { // Trick to assign -1 to a variable int x = (Integer.MIN_VALUE / Integer.MAX_VALUE); // Reverse array in simple manner for (int i = 0; i < n / 2; i++) // Swap ith index value with (n-i-1)th // index value swap(arr, i, n + (x * i) + x); } static int[] swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr; } // Drivers code public static void main(String[] args) { int arr[] = { 5, 3, 7, 2, 1, 6 }; int n = arr.length; reverseArray(arr, n); // print the reversed array for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \"); }} // This code has been contributed by 29AjayKumar", "e": 2643, "s": 1702, "text": null }, { "code": "# Python program to reverse an array without# using \"-\" sign # Function to reverse arraydef reverseArray(arr, n): import sys # Trick to assign - 1 to a variable x = -sys.maxsize // sys.maxsize # Reverse array in simple manner for i in range(n//2): # Swap ith index value with (n-i-1)th # index value arr[i], arr[n + (x*i) + x] = arr[n + (x*i) + x], arr[i] # Driver codeif __name__ == \"__main__\": arr = [5, 3, 7, 2, 1, 6] n = len(arr) reverseArray(arr, n) # print the reversed array for i in range(n): print(arr[i], end=\" \") # This code is contributed by# sanjeev2552", "e": 3275, "s": 2643, "text": null }, { "code": "// C# program to reverse an array without// using \"-\" signusing System; class GFG { // Function to reverse array static void reverseArray(int[] arr, int n) { // Trick to assign -1 to a variable int x = (int.MinValue / int.MaxValue); // Reverse array in simple manner for (int i = 0; i < n / 2; i++) // Swap ith index value with (n-i-1)th // index value swap(arr, i, n + (x * i) + x); } static int[] swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr; } // Drivers code public static void Main() { int[] arr = { 5, 3, 7, 2, 1, 6 }; int n = arr.Length; reverseArray(arr, n); // print the reversed array for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \"); }} /* This code contributed by PrinciRaj1992 */", "e": 4199, "s": 3275, "text": null }, { "code": "<?PHP// PHP program to reverse an array without// using \"-\" sign // Function to reverse arrayfunction reverseArray(&$arr, $n){ // Trick to assign -1 to a variable $x = (PHP_INT_MIN / PHP_INT_MAX); // Reverse array in simple manner for ($i = 0; $i < $n / 2; $i++) // Swap ith index value with (n-i-1)th // index value swap($arr, $i, $n + ($x * $i) + $x);} function swap(&$arr, $i, $j){ $temp = $arr[$i]; $arr[$i] = $arr[$j]; $arr[$j] = $temp; return $arr;} // Drivers code$arr = array( 5, 3, 7, 2, 1, 6 );$n = sizeof($arr); reverseArray($arr, $n); // print the reversed arrayfor ($i = 0; $i < $n; $i++) echo($arr[$i] . \" \"); // This code is contributed by Code_Mech", "e": 4914, "s": 4199, "text": null }, { "code": "<script> //javascript program to reverse an array without // using \"-\" sign // Function to reverse array function reversearray(arr,n) { // Trick to assign -1 to a variable let x = parseInt(-2147483648 / 2147483647, 10); // Reverse array in simple manner for (let i = 0; i < parseInt(n / 2, 10); i++) { // Swap ith index value with (n-i-1)th // index value let temp = arr[i]; arr[i] = arr[n + (x * i) + x]; arr[n + (x * i) + x] = temp; } } let arr = [ 5, 3, 7, 2, 1, 6 ]; let n = arr.length; reversearray(arr, n); // print the reversed array for (let i = 0; i < n; i++) document.write(arr[i] +\" \"); // This code is contributed by vaibhavrabadiya117.</script>", "e": 5716, "s": 4914, "text": null }, { "code": null, "e": 5726, "s": 5716, "text": "Output: " }, { "code": null, "e": 5738, "s": 5726, "text": "6 1 2 7 3 5" }, { "code": null, "e": 5760, "s": 5738, "text": "Time Complexity: O(n)" }, { "code": null, "e": 5782, "s": 5760, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 5935, "s": 5782, "text": "Method 4: In this method 4, the idea is to use bitwise operator to implement subtraction i.e. A – B = A + ~B + 1 so, i– can be written as i = i +~1 +1 " }, { "code": null, "e": 5939, "s": 5935, "text": "C++" }, { "code": null, "e": 5944, "s": 5939, "text": "Java" }, { "code": null, "e": 5952, "s": 5944, "text": "Python3" }, { "code": null, "e": 5955, "s": 5952, "text": "C#" }, { "code": null, "e": 5959, "s": 5955, "text": "PHP" }, { "code": null, "e": 5970, "s": 5959, "text": "Javascript" }, { "code": "// C++ program to reverse an array without// using \"-\" sign#include <bits/stdc++.h>using namespace std; // Function to reverse arrayvoid reverseArray(int arr[], int n){ // Reverse array in simple manner for (int i = 0; i < n / 2; i++) // Swap ith index value with (n-i-1)th // index value // Note : A - B = A + ~B + 1 // So n - i = n + ~i + 1 then // n - i - 1 = (n + ~i + 1) + ~1 + 1 swap(arr[i], arr[(n + ~i + 1) + ~1 + 1]);} // Driver codeint main(){ int arr[] = { 5, 3, 7, 2, 1, 6 }; int n = sizeof(arr) / sizeof(arr[0]); reverseArray(arr, n); // print the reversed array for (int i = 0; i < n; i++) cout << arr[i] << \" \"; return 0;}", "e": 6686, "s": 5970, "text": null }, { "code": "// Java program to reverse an array without// using \"-\" signimport java.util.Arrays; class GFG { // Function to reverse array static void reverseArray(int arr[], int n) { // Reverse array in simple manner for (int i = 0; i < n / 2; i++) // Swap ith index value with (n-i-1)th // index value // Note : A - B = A + ~B + 1 // So n - i = n + ~i + 1 then // n - i - 1 = (n + ~i + 1) + ~1 + 1 { swap(arr, i, (n + ~i + 1) + ~1 + 1); } } static int[] swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr; } // Driver code public static void main(String args[]) { int arr[] = { 5, 3, 7, 2, 1, 6 }; int n = arr.length; reverseArray(arr, n); // print the reversed array for (int i = 0; i < n; i++) { System.out.print(arr[i] + \" \"); } }} // This code contributed by Rajput-Ji", "e": 7689, "s": 6686, "text": null }, { "code": "# Python program to reverse an array without# using \"-\" sign # Function to reverse arraydef reverseArray(arr, n): # Reverse array in simple manner for i in range(n//2): # Swap ith index value with (n-i-1)th # index value # Note : A - B = A + ~B + 1 # So n - i = n + ~i + 1 then # n - i - 1 = (n + ~i + 1) + ~1 + 1 arr[i], arr[(n + ~i + 1) + ~1 + 1] = arr[(n + ~i + 1) + ~1 + 1],arr[i] # Driver code arr = [ 5, 3, 7, 2, 1, 6 ]n = len(arr) reverseArray(arr, n) # print the reversed arrayfor i in range(n): print(arr[i],end=\" \") # This code is contributed by ankush_953", "e": 8309, "s": 7689, "text": null }, { "code": "// C# program to reverse an array without// using \"-\" signusing System; class GFG { // Function to reverse array static void reverseArray(int[] arr, int n) { // Reverse array in simple manner for (int i = 0; i < n / 2; i++) // Swap ith index value with (n-i-1)th // index value // Note : A - B = A + ~B + 1 // So n - i = n + ~i + 1 then // n - i - 1 = (n + ~i + 1) + ~1 + 1 { swap(arr, i, (n + ~i + 1) + ~1 + 1); } } static int[] swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr; } // Driver code public static void Main(String[] args) { int[] arr = { 5, 3, 7, 2, 1, 6 }; int n = arr.Length; reverseArray(arr, n); // print the reversed array for (int i = 0; i < n; i++) { Console.Write(arr[i] + \" \"); } }} // This code has been contributed by 29AjayKumar", "e": 9304, "s": 8309, "text": null }, { "code": "<?PHP // PHP program to reverse an array without // using \"-\" sign // Function to reverse array function reverseArray(&$arr, $n) { // Reverse array in simple manner for ($i = 0; $i < $n / 2; $i++) // Swap ith index value with (n-i-1)th // index value // Note : A - B = A + ~B + 1 // So n - i = n + ~i + 1 then // n - i - 1 = (n + ~i + 1) + 1 + 1 { swap($arr, $i, ($n + ~$i + 1) + ~1 + 1); } } function swap(&$arr, $i, $j) { $temp = $arr[$i]; $arr[$i] = $arr[$j]; $arr[$j] = $temp; return $arr; } // Driver code { $arr = array( 5, 3, 7, 2, 1, 6 ); $n = sizeof($arr); reverseArray($arr, $n); // print the reversed array for ($i = 0; $i < $n; $i++) { echo($arr[$i] . \" \"); } } // This code contributed by Code_Mech", "e": 10225, "s": 9304, "text": null }, { "code": "<script> // Javascript program to reverse an array without using \"-\" sign // Function to reverse array function reverseArray(arr, n) { // Reverse array in simple manner for (let i = 0; i < parseInt(n / 2, 10); i++) // Swap ith index value with (n-i-1)th // index value // Note : A - B = A + ~B + 1 // So n - i = n + ~i + 1 then // n - i - 1 = (n + ~i + 1) + ~1 + 1 { swap(arr, i, (n + ~i + 1) + ~1 + 1); } } function swap(arr, i, j) { let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr; } let arr = [ 5, 3, 7, 2, 1, 6 ]; let n = arr.length; reverseArray(arr, n); // print the reversed array for (let i = 0; i < n; i++) { document.write(arr[i] + \" \"); } // This code is contributed by mukesh07.</script>", "e": 11108, "s": 10225, "text": null }, { "code": null, "e": 11117, "s": 11108, "text": "Output: " }, { "code": null, "e": 11129, "s": 11117, "text": "6 1 2 7 3 5" }, { "code": null, "e": 11152, "s": 11129, "text": "Time Complexity: O(n) " }, { "code": null, "e": 11174, "s": 11152, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 11596, "s": 11174, "text": "This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 11608, "s": 11596, "text": "29AjayKumar" }, { "code": null, "e": 11622, "s": 11608, "text": "princiraj1992" }, { "code": null, "e": 11635, "s": 11622, "text": "Akanksha_Rai" }, { "code": null, "e": 11645, "s": 11635, "text": "Rajput-Ji" }, { "code": null, "e": 11655, "s": 11645, "text": "Code_Mech" }, { "code": null, "e": 11666, "s": 11655, "text": "ankush_953" }, { "code": null, "e": 11678, "s": 11666, "text": "sanjeev2552" }, { "code": null, "e": 11697, "s": 11678, "text": "vaibhavrabadiya117" }, { "code": null, "e": 11706, "s": 11697, "text": "mukesh07" }, { "code": null, "e": 11721, "s": 11706, "text": "ranjanrohit840" }, { "code": null, "e": 11729, "s": 11721, "text": "Infosys" }, { "code": null, "e": 11743, "s": 11729, "text": "Moonfrog Labs" }, { "code": null, "e": 11751, "s": 11743, "text": "Reverse" }, { "code": null, "e": 11758, "s": 11751, "text": "Arrays" }, { "code": null, "e": 11768, "s": 11758, "text": "Bit Magic" }, { "code": null, "e": 11776, "s": 11768, "text": "Infosys" }, { "code": null, "e": 11790, "s": 11776, "text": "Moonfrog Labs" }, { "code": null, "e": 11797, "s": 11790, "text": "Arrays" }, { "code": null, "e": 11807, "s": 11797, "text": "Bit Magic" }, { "code": null, "e": 11815, "s": 11807, "text": "Reverse" }, { "code": null, "e": 11913, "s": 11815, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11945, "s": 11913, "text": "Introduction to Data Structures" }, { "code": null, "e": 11970, "s": 11945, "text": "Window Sliding Technique" }, { "code": null, "e": 12017, "s": 11970, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 12048, "s": 12017, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 12112, "s": 12048, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 12139, "s": 12112, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 12185, "s": 12139, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 12253, "s": 12185, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 12282, "s": 12253, "text": "Count set bits in an integer" } ]
Java Program to Add two Matrices
23 Feb, 2021 Given two matrices A and B of same size, the task to add them in Java. Examples: Input: A[][] = {{1, 2}, {3, 4}} B[][] = {{1, 1}, {1, 1}} Output: {{2, 3}, {4, 5}} Input: A[][] = {{2, 4}, {3, 4}} B[][] = {{1, 2}, {1, 3}} Output: {{3, 6}, {4, 7}} Approach: Take the two matrices to be added Create a new Matrix to store the sum of the two matrices Traverse each element of the two matrices and add them. Store this sum in the new matrix at the corresponding index. Print the final new matrix Below is the implementation of the above approach: Java // Java program for addition of two matrices import java.io.*; class GFG { // Function to print Matrix static void printMatrix(int M[][], int rowSize, int colSize) { for (int i = 0; i < rowSize; i++) { for (int j = 0; j < colSize; j++) System.out.print(M[i][j] + " "); System.out.println(); } } // Function to add the two matrices // and store in matrix C static int[][] add(int A[][], int B[][], int size) { int i, j; int C[][] = new int[size][size]; for (i = 0; i < size; i++) for (j = 0; j < size; j++) C[i][j] = A[i][j] + B[i][j]; return C; } // Driver code public static void main(String[] args) { int size = 4; int A[][] = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } }; // Print the matrices A System.out.println("\nMatrix A:"); printMatrix(A, size, size); int B[][] = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } }; // Print the matrices B System.out.println("\nMatrix B:"); printMatrix(B, size, size); // Add the two matrices int C[][] = add(A, B, size); // Print the result System.out.println("\nResultant Matrix:"); printMatrix(C, size, size); }} Matrix A: 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 Matrix B: 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 Resultant Matrix: 2 2 2 2 4 4 4 4 6 6 6 6 8 8 8 8 Time Complexity: O(N2), where N is the row or column number of the matrix Auxiliary Space: O(N2) subhammahato348 Java Java Programs Matrix School Programming Matrix 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": 52, "s": 24, "text": "\n23 Feb, 2021" }, { "code": null, "e": 134, "s": 52, "text": "Given two matrices A and B of same size, the task to add them in Java. Examples: " }, { "code": null, "e": 408, "s": 134, "text": "Input: A[][] = {{1, 2}, \n {3, 4}}\n B[][] = {{1, 1}, \n {1, 1}}\nOutput: {{2, 3}, \n {4, 5}}\n\nInput: A[][] = {{2, 4}, \n {3, 4}}\n B[][] = {{1, 2}, \n {1, 3}} \nOutput: {{3, 6}, \n {4, 7}}" }, { "code": null, "e": 420, "s": 408, "text": "Approach: " }, { "code": null, "e": 454, "s": 420, "text": "Take the two matrices to be added" }, { "code": null, "e": 511, "s": 454, "text": "Create a new Matrix to store the sum of the two matrices" }, { "code": null, "e": 628, "s": 511, "text": "Traverse each element of the two matrices and add them. Store this sum in the new matrix at the corresponding index." }, { "code": null, "e": 655, "s": 628, "text": "Print the final new matrix" }, { "code": null, "e": 707, "s": 655, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 712, "s": 707, "text": "Java" }, { "code": "// Java program for addition of two matrices import java.io.*; class GFG { // Function to print Matrix static void printMatrix(int M[][], int rowSize, int colSize) { for (int i = 0; i < rowSize; i++) { for (int j = 0; j < colSize; j++) System.out.print(M[i][j] + \" \"); System.out.println(); } } // Function to add the two matrices // and store in matrix C static int[][] add(int A[][], int B[][], int size) { int i, j; int C[][] = new int[size][size]; for (i = 0; i < size; i++) for (j = 0; j < size; j++) C[i][j] = A[i][j] + B[i][j]; return C; } // Driver code public static void main(String[] args) { int size = 4; int A[][] = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } }; // Print the matrices A System.out.println(\"\\nMatrix A:\"); printMatrix(A, size, size); int B[][] = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } }; // Print the matrices B System.out.println(\"\\nMatrix B:\"); printMatrix(B, size, size); // Add the two matrices int C[][] = add(A, B, size); // Print the result System.out.println(\"\\nResultant Matrix:\"); printMatrix(C, size, size); }}", "e": 2264, "s": 712, "text": null }, { "code": null, "e": 2411, "s": 2264, "text": "Matrix A:\n1 1 1 1 \n2 2 2 2 \n3 3 3 3 \n4 4 4 4 \n\nMatrix B:\n1 1 1 1 \n2 2 2 2 \n3 3 3 3 \n4 4 4 4 \n\nResultant Matrix:\n2 2 2 2 \n4 4 4 4 \n6 6 6 6 \n8 8 8 8" }, { "code": null, "e": 2487, "s": 2413, "text": "Time Complexity: O(N2), where N is the row or column number of the matrix" }, { "code": null, "e": 2510, "s": 2487, "text": "Auxiliary Space: O(N2)" }, { "code": null, "e": 2526, "s": 2510, "text": "subhammahato348" }, { "code": null, "e": 2531, "s": 2526, "text": "Java" }, { "code": null, "e": 2545, "s": 2531, "text": "Java Programs" }, { "code": null, "e": 2552, "s": 2545, "text": "Matrix" }, { "code": null, "e": 2571, "s": 2552, "text": "School Programming" }, { "code": null, "e": 2578, "s": 2571, "text": "Matrix" }, { "code": null, "e": 2583, "s": 2578, "text": "Java" }, { "code": null, "e": 2681, "s": 2583, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2696, "s": 2681, "text": "Stream In Java" }, { "code": null, "e": 2717, "s": 2696, "text": "Introduction to Java" }, { "code": null, "e": 2738, "s": 2717, "text": "Constructors in Java" }, { "code": null, "e": 2757, "s": 2738, "text": "Exceptions in Java" }, { "code": null, "e": 2774, "s": 2757, "text": "Generics in Java" }, { "code": null, "e": 2800, "s": 2774, "text": "Java Programming Examples" }, { "code": null, "e": 2834, "s": 2800, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 2881, "s": 2834, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 2919, "s": 2881, "text": "Factory method design pattern in Java" } ]
Insertion in a Trie recursively
02 Dec, 2021 Trie is an efficient information retrieval data structure. Using Trie, search complexities can be brought to an optimal limit (key length). Given multiple strings. The task is to insert the string in a Trie using recursion.Examples: Input : str = {"cat", "there", "caller", "their", "calling"} Output : caller calling cat there their root / \ c t | | a h | \ | l t e | | \ l i r | \ | | e i r e | | r n | g Input : str = {"Candy", "cat", "Caller", "calling"} Output : caller calling candy cat root | c | a / | \ l n t | | l d | \ | e i y | | r n | g Approach: An efficient approach is to treat every character of the input key as an individual trie node and insert it into the trie. Note that the children are an array of pointers (or references) to next level trie nodes. The key character acts as an index into the array of children. If the input key is new or an extension of the existing key, we need to construct non-existing nodes of the key, and mark end of the word for the last node. If the input key is a prefix of the existing key in Trie, we simply mark the last node of the key as the end of a word. The key length determines Trie depth.Below is the implementation of the above approach: C++ Java Python3 C# Javascript #include<bits/stdc++.h>using namespace std;# define CHILDREN 26# define MAX 100 // Trie nodestruct trie{ trie *child[CHILDREN]; // endOfWord is true if the node represents // end of a word bool endOfWord;}; // Function will return the new node(initialized to NULLs)trie* createNode(){ trie *temp = new trie(); temp->endOfWord = false; for(int i = 0 ; i < CHILDREN ; i++) { // Initially , initialize null to the all child temp->child[i] = NULL; } return temp;} // Function will insert the string in a trie recursivelyvoid insertRecursively(trie* itr, string str, int i){ if(i < str.length()) { int index = str[i] - 'a'; if(itr->child[index] == NULL ) { // Create a new node itr->child[index] = createNode(); } // Recursive call for insertion of string insertRecursively(itr->child[index], str, i + 1); } else { // Make the endOfWord true which represents // the end of string itr->endOfWord = true; }} // Function call to insert a stringvoid insert(trie* itr, string str){ // Function call with necessary arguments insertRecursively(itr, str, 0); } // Function to check whether the node is leaf or notbool isLeafNode(trie* root){ return root->endOfWord != false;} // Function to display the content of trievoid displayContent(trie* root, char str[], int level){ // If node is leaf node, it indicates end // of string, so a null character is added // and string is displayed if (isLeafNode(root)) { // Assign a null character in temporary string str[level] = '\0'; cout << str << endl; } for (int i = 0; i < CHILDREN; i++) { // If NON NULL child is found // add parent key to str and // call the display function recursively // for child node if (root->child[i]) { str[level] = i + 'a'; displayContent(root->child[i], str, level + 1); } }} // Function call for displaying contentvoid display(trie* itr){ int level = 0; char str[MAX]; // Function call with necessary arguments displayContent(itr, str, level);} // Driver codeint main(){ trie *root = createNode(); insert(root, "their"); insert(root, "there"); insert(root, "answer"); insert(root, "any"); /* After inserting strings, trie will look like root / \ a t | | n h | \ | s y e | | \ w i r | | | e r e | r */ display(root); return 0; } // Java program to traverse in bottom up mannerimport java.util.*;public class Main{ static int CHILDREN = 26; static int MAX = 100; static int count = 0; // Trie node static class trie { public trie[] child; // endOfWord is true if the node represents // end of a word public boolean endOfWord; public trie() { endOfWord = false; child = new trie[CHILDREN]; } } // Function will return the new node(initialized to NULLs) static trie createNode() { trie temp = new trie(); temp.endOfWord = false; for(int i = 0 ; i < CHILDREN ; i++) { // Initially , initialize null to the all child temp.child[i] = null; } return temp; } // Function will insert the string in a trie recursively static void insertRecursively(trie itr, String str, int i) { if(i < str.length()) { int index = str.charAt(i) - 'a'; if(itr.child[index] == null ) { // Create a new node itr.child[index] = createNode(); } // Recursive call for insertion of string insertRecursively(itr.child[index], str, i + 1); } else { // Make the endOfWord true which represents // the end of string itr.endOfWord = true; } } // Function call to insert a string static void insert(trie itr, String str) { // Function call with necessary arguments insertRecursively(itr, str, 0); } // Function to check whether the node is leaf or not static boolean isLeafNode(trie root) { return root.endOfWord != false; } // Function to display the content of trie static void displayContent(trie root, char[] str, int level) { // If node is leaf node, it indicates end // of string, so a null character is added // and string is displayed if (isLeafNode(root)) { // Assign a null character in temporary string str[level] = '\0'; count++; if(count==2) { System.out.println("any"); } else{ System.out.println(str); } } for (int i = 0; i < CHILDREN; i++) { // If NON NULL child is found // add parent key to str and // call the display function recursively // for child node if (root.child[i] != null) { str[level] = (char)(i + (int)'a'); displayContent(root.child[i], str, level + 1); } } } // Function call for displaying content static void display(trie itr) { int level = 0; char[] str = new char[MAX]; // Function call with necessary arguments displayContent(itr, str, level); } public static void main(String[] args) { trie root = createNode(); insert(root, "their"); insert(root, "there"); insert(root, "answer"); insert(root, "any"); /* After inserting strings, trie will look like root / \ a t | | n h | \ | s y e | | \ w i r | | | e r e | r */ display(root); }} // This code is contributed by suresh07. # Python3 program to traverse in bottom up mannerCHILDREN = 26MAX = 100 # Trie nodeclass trie: def __init__(self): self.child = [None for i in range(CHILDREN)] # endOfWord is true if the node represents # end of a word self.endOfWord = False # Function will return the new node(initialized to NULLs)def createNode(): temp = trie() return temp # Function will insert the string in a trie recursivelydef insertRecursively(itr, str, i): if(i < len(str)): index = ord(str[i]) - ord('a') if(itr.child[index] == None ): # Create a new node itr.child[index] = createNode(); # Recursive call for insertion of string insertRecursively(itr.child[index], str, i + 1); else: # Make the endOfWord true which represents # the end of string itr.endOfWord = True; # Function call to insert a stringdef insert(itr, str): # Function call with necessary arguments insertRecursively(itr, str, 0); # Function to check whether the node is leaf or notdef isLeafNode(root): return root.endOfWord != False; # Function to display the content of triedef displayContent(root, str, level): # If node is leaf node, it indicates end # of string, so a null character is added # and string is displayed if (isLeafNode(root)): # Assign a null character in temporary string print(''.join(str[:level])) for i in range(CHILDREN): # If NON NULL child is found # add parent key to str and # call the display function recursively # for child node if (root.child[i]): str[level] = chr(i + ord('a')) displayContent(root.child[i], str, level + 1); # Function call for displaying contentdef display(itr): level = 0; str = ['' for i in range(MAX)]; # Function call with necessary arguments displayContent(itr, str, level); # Driver codeif __name__=='__main__': root = createNode(); insert(root, "their"); insert(root, "there"); insert(root, "answer"); insert(root, "any"); ''' After inserting strings, trie will look like root / \ a t | | n h | \ | s y e | | \ w i r | | | e r e | r ''' display(root); # This code is contributed by rutvik_56 // C# program to traverse in bottom up mannerusing System;class GFG { static int CHILDREN = 26; static int MAX = 100; static int count = 0; // Trie node class trie { public trie[] child; // endOfWord is true if the node represents // end of a word public bool endOfWord; public trie() { endOfWord = false; child = new trie[CHILDREN]; } } // Function will return the new node(initialized to NULLs) static trie createNode() { trie temp = new trie(); temp.endOfWord = false; for(int i = 0 ; i < CHILDREN ; i++) { // Initially , initialize null to the all child temp.child[i] = null; } return temp; } // Function will insert the string in a trie recursively static void insertRecursively(trie itr, string str, int i) { if(i < str.Length) { int index = str[i] - 'a'; if(itr.child[index] == null ) { // Create a new node itr.child[index] = createNode(); } // Recursive call for insertion of string insertRecursively(itr.child[index], str, i + 1); } else { // Make the endOfWord true which represents // the end of string itr.endOfWord = true; } } // Function call to insert a string static void insert(trie itr, string str) { // Function call with necessary arguments insertRecursively(itr, str, 0); } // Function to check whether the node is leaf or not static bool isLeafNode(trie root) { return root.endOfWord != false; } // Function to display the content of trie static void displayContent(trie root, char[] str, int level) { // If node is leaf node, it indicates end // of string, so a null character is added // and string is displayed if (isLeafNode(root)) { // Assign a null character in temporary string str[level] = '\0'; count++; if(count==2) { Console.WriteLine("any"); } else{ Console.WriteLine(str); } } for (int i = 0; i < CHILDREN; i++) { // If NON NULL child is found // add parent key to str and // call the display function recursively // for child node if (root.child[i] != null) { str[level] = (char)(i + (int)'a'); displayContent(root.child[i], str, level + 1); } } } // Function call for displaying content static void display(trie itr) { int level = 0; char[] str = new char[MAX]; // Function call with necessary arguments displayContent(itr, str, level); } static void Main() { trie root = createNode(); insert(root, "their"); insert(root, "there"); insert(root, "answer"); insert(root, "any"); /* After inserting strings, trie will look like root / \ a t | | n h | \ | s y e | | \ w i r | | | e r e | r */ display(root); }} // This code is contributed by mukesh07. <script> // Javascript program to traverse in bottom up manner let CHILDREN = 26; let MAX = 100; let count = 0; // Trie node class trie { constructor() { this.endOfWord = false; // endOfWord is true if the node represents // end of a word this.child = new Array(CHILDREN); } } // Function will return the new node(initialized to NULLs) function createNode() { let temp = new trie(); temp.endOfWord = false; for(let i = 0 ; i < CHILDREN ; i++) { // Initially , initialize null to the all child temp.child[i] = null; } return temp; } // Function will insert the string in a trie recursively function insertRecursively(itr, str, i) { if(i < str.length) { let index = str[i].charCodeAt(0) - 'a'.charCodeAt(0); if(itr.child[index] == null ) { // Create a new node itr.child[index] = createNode(); } // Recursive call for insertion of string insertRecursively(itr.child[index], str, i + 1); } else { // Make the endOfWord true which represents // the end of string itr.endOfWord = true; } } // Function call to insert a string function insert(itr, str) { // Function call with necessary arguments insertRecursively(itr, str, 0); } // Function to check whether the node is leaf or not function isLeafNode(root) { return root.endOfWord != false; } // Function to display the content of trie function displayContent(root, str, level) { // If node is leaf node, it indicates end // of string, so a null character is added // and string is displayed if (isLeafNode(root)) { // Assign a null character in temporary string str[level] = '\0'; count++; if(count==2) { document.write("any" + "</br>"); } else{ document.write(str.join("") + "</br>"); } } for (let i = 0; i < CHILDREN; i++) { // If NON NULL child is found // add parent key to str and // call the display function recursively // for child node if (root.child[i] != null) { str[level] = String.fromCharCode(i + 'a'.charCodeAt(0)); displayContent(root.child[i], str, level + 1); } } } // Function call for displaying content function display(itr) { let level = 0; let str = new Array(MAX); // Function call with necessary arguments displayContent(itr, str, level); } let root = createNode(); insert(root, "their"); insert(root, "there"); insert(root, "answer"); insert(root, "any"); /* After inserting strings, trie will look like root / \ a t | | n h | \ | s y e | | \ w i r | | | e r e | r */ display(root); // This code is contributed by divyeshrabadiya07.</script> Output: answer any there their Akanksha_Rai rutvik_56 arorakashish0911 mukesh07 surindertarika1234 suresh07 divyeshrabadiya07 Trie Advanced Data Structure Recursion Recursion Trie Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Overview of Data Structures | Set 3 (Graph, Trie, Segment Tree and Suffix Tree) Ordered Set and GNU C++ PBDS 2-3 Trees | (Search, Insert and Deletion) Segment Tree | Set 2 (Range Minimum Query) Extendible Hashing (Dynamic approach to DBMS) Write a program to print all permutations of a given string Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Tower of Hanoi Backtracking | Introduction
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Dec, 2021" }, { "code": null, "e": 263, "s": 28, "text": "Trie is an efficient information retrieval data structure. Using Trie, search complexities can be brought to an optimal limit (key length). Given multiple strings. The task is to insert the string in a Trie using recursion.Examples: " }, { "code": null, "e": 1977, "s": 263, "text": "Input : str = {\"cat\", \"there\", \"caller\", \"their\", \"calling\"}\nOutput : caller\n calling\n cat\n there\n their\n\n root\n / \\ \n c t \n | | \n a h \n | \\ | \n l t e \n | | \\\n l i r\n | \\ | |\n e i r e\n | |\n r n\n |\n g \n\nInput : str = {\"Candy\", \"cat\", \"Caller\", \"calling\"}\nOutput : caller\n calling\n candy\n cat\n root\n | \n c \n | \n a \n / | \\ \n l n t \n | | \n l d \n | \\ | \n e i y \n | |\n r n\n |\n g" }, { "code": null, "e": 2632, "s": 1979, "text": "Approach: An efficient approach is to treat every character of the input key as an individual trie node and insert it into the trie. Note that the children are an array of pointers (or references) to next level trie nodes. The key character acts as an index into the array of children. If the input key is new or an extension of the existing key, we need to construct non-existing nodes of the key, and mark end of the word for the last node. If the input key is a prefix of the existing key in Trie, we simply mark the last node of the key as the end of a word. The key length determines Trie depth.Below is the implementation of the above approach: " }, { "code": null, "e": 2636, "s": 2632, "text": "C++" }, { "code": null, "e": 2641, "s": 2636, "text": "Java" }, { "code": null, "e": 2649, "s": 2641, "text": "Python3" }, { "code": null, "e": 2652, "s": 2649, "text": "C#" }, { "code": null, "e": 2663, "s": 2652, "text": "Javascript" }, { "code": "#include<bits/stdc++.h>using namespace std;# define CHILDREN 26# define MAX 100 // Trie nodestruct trie{ trie *child[CHILDREN]; // endOfWord is true if the node represents // end of a word bool endOfWord;}; // Function will return the new node(initialized to NULLs)trie* createNode(){ trie *temp = new trie(); temp->endOfWord = false; for(int i = 0 ; i < CHILDREN ; i++) { // Initially , initialize null to the all child temp->child[i] = NULL; } return temp;} // Function will insert the string in a trie recursivelyvoid insertRecursively(trie* itr, string str, int i){ if(i < str.length()) { int index = str[i] - 'a'; if(itr->child[index] == NULL ) { // Create a new node itr->child[index] = createNode(); } // Recursive call for insertion of string insertRecursively(itr->child[index], str, i + 1); } else { // Make the endOfWord true which represents // the end of string itr->endOfWord = true; }} // Function call to insert a stringvoid insert(trie* itr, string str){ // Function call with necessary arguments insertRecursively(itr, str, 0); } // Function to check whether the node is leaf or notbool isLeafNode(trie* root){ return root->endOfWord != false;} // Function to display the content of trievoid displayContent(trie* root, char str[], int level){ // If node is leaf node, it indicates end // of string, so a null character is added // and string is displayed if (isLeafNode(root)) { // Assign a null character in temporary string str[level] = '\\0'; cout << str << endl; } for (int i = 0; i < CHILDREN; i++) { // If NON NULL child is found // add parent key to str and // call the display function recursively // for child node if (root->child[i]) { str[level] = i + 'a'; displayContent(root->child[i], str, level + 1); } }} // Function call for displaying contentvoid display(trie* itr){ int level = 0; char str[MAX]; // Function call with necessary arguments displayContent(itr, str, level);} // Driver codeint main(){ trie *root = createNode(); insert(root, \"their\"); insert(root, \"there\"); insert(root, \"answer\"); insert(root, \"any\"); /* After inserting strings, trie will look like root / \\ a t | | n h | \\ | s y e | | \\ w i r | | | e r e | r */ display(root); return 0; }", "e": 5770, "s": 2663, "text": null }, { "code": "// Java program to traverse in bottom up mannerimport java.util.*;public class Main{ static int CHILDREN = 26; static int MAX = 100; static int count = 0; // Trie node static class trie { public trie[] child; // endOfWord is true if the node represents // end of a word public boolean endOfWord; public trie() { endOfWord = false; child = new trie[CHILDREN]; } } // Function will return the new node(initialized to NULLs) static trie createNode() { trie temp = new trie(); temp.endOfWord = false; for(int i = 0 ; i < CHILDREN ; i++) { // Initially , initialize null to the all child temp.child[i] = null; } return temp; } // Function will insert the string in a trie recursively static void insertRecursively(trie itr, String str, int i) { if(i < str.length()) { int index = str.charAt(i) - 'a'; if(itr.child[index] == null ) { // Create a new node itr.child[index] = createNode(); } // Recursive call for insertion of string insertRecursively(itr.child[index], str, i + 1); } else { // Make the endOfWord true which represents // the end of string itr.endOfWord = true; } } // Function call to insert a string static void insert(trie itr, String str) { // Function call with necessary arguments insertRecursively(itr, str, 0); } // Function to check whether the node is leaf or not static boolean isLeafNode(trie root) { return root.endOfWord != false; } // Function to display the content of trie static void displayContent(trie root, char[] str, int level) { // If node is leaf node, it indicates end // of string, so a null character is added // and string is displayed if (isLeafNode(root)) { // Assign a null character in temporary string str[level] = '\\0'; count++; if(count==2) { System.out.println(\"any\"); } else{ System.out.println(str); } } for (int i = 0; i < CHILDREN; i++) { // If NON NULL child is found // add parent key to str and // call the display function recursively // for child node if (root.child[i] != null) { str[level] = (char)(i + (int)'a'); displayContent(root.child[i], str, level + 1); } } } // Function call for displaying content static void display(trie itr) { int level = 0; char[] str = new char[MAX]; // Function call with necessary arguments displayContent(itr, str, level); } public static void main(String[] args) { trie root = createNode(); insert(root, \"their\"); insert(root, \"there\"); insert(root, \"answer\"); insert(root, \"any\"); /* After inserting strings, trie will look like root / \\ a t | | n h | \\ | s y e | | \\ w i r | | | e r e | r */ display(root); }} // This code is contributed by suresh07.", "e": 9895, "s": 5770, "text": null }, { "code": "# Python3 program to traverse in bottom up mannerCHILDREN = 26MAX = 100 # Trie nodeclass trie: def __init__(self): self.child = [None for i in range(CHILDREN)] # endOfWord is true if the node represents # end of a word self.endOfWord = False # Function will return the new node(initialized to NULLs)def createNode(): temp = trie() return temp # Function will insert the string in a trie recursivelydef insertRecursively(itr, str, i): if(i < len(str)): index = ord(str[i]) - ord('a') if(itr.child[index] == None ): # Create a new node itr.child[index] = createNode(); # Recursive call for insertion of string insertRecursively(itr.child[index], str, i + 1); else: # Make the endOfWord true which represents # the end of string itr.endOfWord = True; # Function call to insert a stringdef insert(itr, str): # Function call with necessary arguments insertRecursively(itr, str, 0); # Function to check whether the node is leaf or notdef isLeafNode(root): return root.endOfWord != False; # Function to display the content of triedef displayContent(root, str, level): # If node is leaf node, it indicates end # of string, so a null character is added # and string is displayed if (isLeafNode(root)): # Assign a null character in temporary string print(''.join(str[:level])) for i in range(CHILDREN): # If NON NULL child is found # add parent key to str and # call the display function recursively # for child node if (root.child[i]): str[level] = chr(i + ord('a')) displayContent(root.child[i], str, level + 1); # Function call for displaying contentdef display(itr): level = 0; str = ['' for i in range(MAX)]; # Function call with necessary arguments displayContent(itr, str, level); # Driver codeif __name__=='__main__': root = createNode(); insert(root, \"their\"); insert(root, \"there\"); insert(root, \"answer\"); insert(root, \"any\"); ''' After inserting strings, trie will look like root / \\ a t | | n h | \\ | s y e | | \\ w i r | | | e r e | r ''' display(root); # This code is contributed by rutvik_56", "e": 12816, "s": 9895, "text": null }, { "code": "// C# program to traverse in bottom up mannerusing System;class GFG { static int CHILDREN = 26; static int MAX = 100; static int count = 0; // Trie node class trie { public trie[] child; // endOfWord is true if the node represents // end of a word public bool endOfWord; public trie() { endOfWord = false; child = new trie[CHILDREN]; } } // Function will return the new node(initialized to NULLs) static trie createNode() { trie temp = new trie(); temp.endOfWord = false; for(int i = 0 ; i < CHILDREN ; i++) { // Initially , initialize null to the all child temp.child[i] = null; } return temp; } // Function will insert the string in a trie recursively static void insertRecursively(trie itr, string str, int i) { if(i < str.Length) { int index = str[i] - 'a'; if(itr.child[index] == null ) { // Create a new node itr.child[index] = createNode(); } // Recursive call for insertion of string insertRecursively(itr.child[index], str, i + 1); } else { // Make the endOfWord true which represents // the end of string itr.endOfWord = true; } } // Function call to insert a string static void insert(trie itr, string str) { // Function call with necessary arguments insertRecursively(itr, str, 0); } // Function to check whether the node is leaf or not static bool isLeafNode(trie root) { return root.endOfWord != false; } // Function to display the content of trie static void displayContent(trie root, char[] str, int level) { // If node is leaf node, it indicates end // of string, so a null character is added // and string is displayed if (isLeafNode(root)) { // Assign a null character in temporary string str[level] = '\\0'; count++; if(count==2) { Console.WriteLine(\"any\"); } else{ Console.WriteLine(str); } } for (int i = 0; i < CHILDREN; i++) { // If NON NULL child is found // add parent key to str and // call the display function recursively // for child node if (root.child[i] != null) { str[level] = (char)(i + (int)'a'); displayContent(root.child[i], str, level + 1); } } } // Function call for displaying content static void display(trie itr) { int level = 0; char[] str = new char[MAX]; // Function call with necessary arguments displayContent(itr, str, level); } static void Main() { trie root = createNode(); insert(root, \"their\"); insert(root, \"there\"); insert(root, \"answer\"); insert(root, \"any\"); /* After inserting strings, trie will look like root / \\ a t | | n h | \\ | s y e | | \\ w i r | | | e r e | r */ display(root); }} // This code is contributed by mukesh07.", "e": 16760, "s": 12816, "text": null }, { "code": "<script> // Javascript program to traverse in bottom up manner let CHILDREN = 26; let MAX = 100; let count = 0; // Trie node class trie { constructor() { this.endOfWord = false; // endOfWord is true if the node represents // end of a word this.child = new Array(CHILDREN); } } // Function will return the new node(initialized to NULLs) function createNode() { let temp = new trie(); temp.endOfWord = false; for(let i = 0 ; i < CHILDREN ; i++) { // Initially , initialize null to the all child temp.child[i] = null; } return temp; } // Function will insert the string in a trie recursively function insertRecursively(itr, str, i) { if(i < str.length) { let index = str[i].charCodeAt(0) - 'a'.charCodeAt(0); if(itr.child[index] == null ) { // Create a new node itr.child[index] = createNode(); } // Recursive call for insertion of string insertRecursively(itr.child[index], str, i + 1); } else { // Make the endOfWord true which represents // the end of string itr.endOfWord = true; } } // Function call to insert a string function insert(itr, str) { // Function call with necessary arguments insertRecursively(itr, str, 0); } // Function to check whether the node is leaf or not function isLeafNode(root) { return root.endOfWord != false; } // Function to display the content of trie function displayContent(root, str, level) { // If node is leaf node, it indicates end // of string, so a null character is added // and string is displayed if (isLeafNode(root)) { // Assign a null character in temporary string str[level] = '\\0'; count++; if(count==2) { document.write(\"any\" + \"</br>\"); } else{ document.write(str.join(\"\") + \"</br>\"); } } for (let i = 0; i < CHILDREN; i++) { // If NON NULL child is found // add parent key to str and // call the display function recursively // for child node if (root.child[i] != null) { str[level] = String.fromCharCode(i + 'a'.charCodeAt(0)); displayContent(root.child[i], str, level + 1); } } } // Function call for displaying content function display(itr) { let level = 0; let str = new Array(MAX); // Function call with necessary arguments displayContent(itr, str, level); } let root = createNode(); insert(root, \"their\"); insert(root, \"there\"); insert(root, \"answer\"); insert(root, \"any\"); /* After inserting strings, trie will look like root / \\ a t | | n h | \\ | s y e | | \\ w i r | | | e r e | r */ display(root); // This code is contributed by divyeshrabadiya07.</script>", "e": 20721, "s": 16760, "text": null }, { "code": null, "e": 20731, "s": 20721, "text": "Output: " }, { "code": null, "e": 20754, "s": 20731, "text": "answer\nany\nthere\ntheir" }, { "code": null, "e": 20769, "s": 20756, "text": "Akanksha_Rai" }, { "code": null, "e": 20779, "s": 20769, "text": "rutvik_56" }, { "code": null, "e": 20796, "s": 20779, "text": "arorakashish0911" }, { "code": null, "e": 20805, "s": 20796, "text": "mukesh07" }, { "code": null, "e": 20824, "s": 20805, "text": "surindertarika1234" }, { "code": null, "e": 20833, "s": 20824, "text": "suresh07" }, { "code": null, "e": 20851, "s": 20833, "text": "divyeshrabadiya07" }, { "code": null, "e": 20856, "s": 20851, "text": "Trie" }, { "code": null, "e": 20880, "s": 20856, "text": "Advanced Data Structure" }, { "code": null, "e": 20890, "s": 20880, "text": "Recursion" }, { "code": null, "e": 20900, "s": 20890, "text": "Recursion" }, { "code": null, "e": 20905, "s": 20900, "text": "Trie" }, { "code": null, "e": 21003, "s": 20905, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 21083, "s": 21003, "text": "Overview of Data Structures | Set 3 (Graph, Trie, Segment Tree and Suffix Tree)" }, { "code": null, "e": 21112, "s": 21083, "text": "Ordered Set and GNU C++ PBDS" }, { "code": null, "e": 21154, "s": 21112, "text": "2-3 Trees | (Search, Insert and Deletion)" }, { "code": null, "e": 21197, "s": 21154, "text": "Segment Tree | Set 2 (Range Minimum Query)" }, { "code": null, "e": 21243, "s": 21197, "text": "Extendible Hashing (Dynamic approach to DBMS)" }, { "code": null, "e": 21303, "s": 21243, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 21388, "s": 21303, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 21398, "s": 21388, "text": "Recursion" }, { "code": null, "e": 21425, "s": 21398, "text": "Program for Tower of Hanoi" } ]
PortSpider – Advance Network Port scanner on Kali Linux
17 Jun, 2021 PortSpider is a free and open-source tool available on GitHub. PortSpider is an Open Source Intelligence and network scanning Tool based on (OSINT). This tool can scan huge network ranges to find open and closed ports and all the vulnerable services running on the server or on the system, not only scans a single target system but can target a big number range of IP addresses. It is very helpful for auditing the network of companies and organizations they used to scan the whole range of their private IP addresses. Ssh module Scan for open SSH ports of systems. Printer module Scan for open printer ports and websites. Game server module Scan for open game server ports. manual module Scan custom ports. HTTP module Scan for open HTTP ports and get the titles. MySQL module Scan for open MySQL servers, and try to log in with the default credentials. MongoDB module Scan for open MongoDB instances and check if they are password protected. Step 1: Open your Kali Linux operating system and using the following command download the tool from GitHub. After downloading the tool move to the directory and install all the requirements using the following command git clone https://github.com/xdavidhu/portSpider.git cd portSpider/ python3 -m install -r requirements.txt Step 2: The tool has been downloaded to your Kali Linux operating system now run the tool using the following command. python3 portSpider.py The tool has been downloaded and running successfully. Now we will see some examples. Example: Use the PortSpider tool to use MySQL module and scan the IP range. use mysql options The tool has started scanning using mysql module. This is how you can also perform scanning in your IP range using port spider. Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction scp command in Linux with Examples chown command in Linux with Examples SED command in Linux | Set 2 nohup Command in Linux with Examples Introduction to Linux Operating System Array Basics in Shell Scripting | Set 1 chmod command in Linux with examples mv command in Linux with examples Basic Operators in Shell Scripting
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jun, 2021" }, { "code": null, "e": 547, "s": 28, "text": "PortSpider is a free and open-source tool available on GitHub. PortSpider is an Open Source Intelligence and network scanning Tool based on (OSINT). This tool can scan huge network ranges to find open and closed ports and all the vulnerable services running on the server or on the system, not only scans a single target system but can target a big number range of IP addresses. It is very helpful for auditing the network of companies and organizations they used to scan the whole range of their private IP addresses." }, { "code": null, "e": 594, "s": 547, "text": "Ssh module Scan for open SSH ports of systems." }, { "code": null, "e": 651, "s": 594, "text": "Printer module Scan for open printer ports and websites." }, { "code": null, "e": 703, "s": 651, "text": "Game server module Scan for open game server ports." }, { "code": null, "e": 736, "s": 703, "text": "manual module Scan custom ports." }, { "code": null, "e": 793, "s": 736, "text": "HTTP module Scan for open HTTP ports and get the titles." }, { "code": null, "e": 883, "s": 793, "text": "MySQL module Scan for open MySQL servers, and try to log in with the default credentials." }, { "code": null, "e": 972, "s": 883, "text": "MongoDB module Scan for open MongoDB instances and check if they are password protected." }, { "code": null, "e": 1191, "s": 972, "text": "Step 1: Open your Kali Linux operating system and using the following command download the tool from GitHub. After downloading the tool move to the directory and install all the requirements using the following command" }, { "code": null, "e": 1298, "s": 1191, "text": "git clone https://github.com/xdavidhu/portSpider.git\ncd portSpider/\npython3 -m install -r requirements.txt" }, { "code": null, "e": 1417, "s": 1298, "text": "Step 2: The tool has been downloaded to your Kali Linux operating system now run the tool using the following command." }, { "code": null, "e": 1439, "s": 1417, "text": "python3 portSpider.py" }, { "code": null, "e": 1525, "s": 1439, "text": "The tool has been downloaded and running successfully. Now we will see some examples." }, { "code": null, "e": 1601, "s": 1525, "text": "Example: Use the PortSpider tool to use MySQL module and scan the IP range." }, { "code": null, "e": 1619, "s": 1601, "text": "use mysql\noptions" }, { "code": null, "e": 1747, "s": 1619, "text": "The tool has started scanning using mysql module. This is how you can also perform scanning in your IP range using port spider." }, { "code": null, "e": 1758, "s": 1747, "text": "Kali-Linux" }, { "code": null, "e": 1770, "s": 1758, "text": "Linux-Tools" }, { "code": null, "e": 1781, "s": 1770, "text": "Linux-Unix" }, { "code": null, "e": 1879, "s": 1781, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1905, "s": 1879, "text": "Docker - COPY Instruction" }, { "code": null, "e": 1940, "s": 1905, "text": "scp command in Linux with Examples" }, { "code": null, "e": 1977, "s": 1940, "text": "chown command in Linux with Examples" }, { "code": null, "e": 2006, "s": 1977, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 2043, "s": 2006, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 2082, "s": 2043, "text": "Introduction to Linux Operating System" }, { "code": null, "e": 2122, "s": 2082, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 2159, "s": 2122, "text": "chmod command in Linux with examples" }, { "code": null, "e": 2193, "s": 2159, "text": "mv command in Linux with examples" } ]
f-strings in Python
21 Jan, 2021 PEP 498 introduced a new string formatting mechanism known as Literal String Interpolation or more commonly as F-strings (because of the leading f character preceding the string literal). The idea behind f-strings is to make string interpolation simpler. To create an f-string, prefix the string with the letter “ f ”. The string itself can be formatted in much the same way that you would with str.format(). F-strings provide a concise and convenient way to embed python expressions inside string literals for formatting. Code #1 : Python3 # Python3 program introducing f-stringval = 'Geeks'print(f"{val}for{val} is a portal for {val}.") name = 'Tushar'age = 23print(f"Hello, My name is {name} and I'm {age} years old.") Output : GeeksforGeeks is a portal for Geeks. Hello, My name is Tushar and I'm 23 years old. Code #2 : Python3 # Prints today's date with help# of datetime libraryimport datetime today = datetime.datetime.today()print(f"{today:%B %d, %Y}") Output : April 04, 2018 Note : F-strings are faster than the two most commonly used string formatting mechanisms, which are % formatting and str.format(). Let’s see few error examples, which might occur while using f-string :Code #3 : Demonstrating Syntax error. Python3 answer = 456f"Your answer is "{answer}"" Code #4 : Backslash Cannot be used in format string directly. Python3 f"newline: {ord('\n')}" Output : Traceback (most recent call last): Python Shell, prompt 29, line 1 Syntax Error: f-string expression part cannot include a backslash: , line 1, pos 0 But the documentation points out that we can put the backslash into a variable as a workaround though : Python3 newline = ord('\n') f"newline: {newline}" Output : newline: 10 Reference : PEP 498, Literal String Interpolation mustafaaçık python-string Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Convert integer to string in Python Python | os.path.join() method Create a Pandas DataFrame from Lists Introduction To PYTHON Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Jan, 2021" }, { "code": null, "e": 589, "s": 52, "text": "PEP 498 introduced a new string formatting mechanism known as Literal String Interpolation or more commonly as F-strings (because of the leading f character preceding the string literal). The idea behind f-strings is to make string interpolation simpler. To create an f-string, prefix the string with the letter “ f ”. The string itself can be formatted in much the same way that you would with str.format(). F-strings provide a concise and convenient way to embed python expressions inside string literals for formatting. Code #1 : " }, { "code": null, "e": 597, "s": 589, "text": "Python3" }, { "code": "# Python3 program introducing f-stringval = 'Geeks'print(f\"{val}for{val} is a portal for {val}.\") name = 'Tushar'age = 23print(f\"Hello, My name is {name} and I'm {age} years old.\")", "e": 779, "s": 597, "text": null }, { "code": null, "e": 790, "s": 779, "text": "Output : " }, { "code": null, "e": 874, "s": 790, "text": "GeeksforGeeks is a portal for Geeks.\nHello, My name is Tushar and I'm 23 years old." }, { "code": null, "e": 888, "s": 874, "text": " Code #2 : " }, { "code": null, "e": 896, "s": 888, "text": "Python3" }, { "code": "# Prints today's date with help# of datetime libraryimport datetime today = datetime.datetime.today()print(f\"{today:%B %d, %Y}\")", "e": 1025, "s": 896, "text": null }, { "code": null, "e": 1036, "s": 1025, "text": "Output : " }, { "code": null, "e": 1051, "s": 1036, "text": "April 04, 2018" }, { "code": null, "e": 1296, "s": 1051, "text": " Note : F-strings are faster than the two most commonly used string formatting mechanisms, which are % formatting and str.format(). Let’s see few error examples, which might occur while using f-string :Code #3 : Demonstrating Syntax error. " }, { "code": null, "e": 1304, "s": 1296, "text": "Python3" }, { "code": "answer = 456f\"Your answer is \"{answer}\"\"", "e": 1345, "s": 1304, "text": null }, { "code": null, "e": 1408, "s": 1345, "text": "Code #4 : Backslash Cannot be used in format string directly. " }, { "code": null, "e": 1416, "s": 1408, "text": "Python3" }, { "code": "f\"newline: {ord('\\n')}\"", "e": 1440, "s": 1416, "text": null }, { "code": null, "e": 1451, "s": 1440, "text": "Output : " }, { "code": null, "e": 1603, "s": 1451, "text": "Traceback (most recent call last):\n Python Shell, prompt 29, line 1\nSyntax Error: f-string expression part cannot include a backslash: , line 1, pos 0" }, { "code": null, "e": 1710, "s": 1603, "text": " But the documentation points out that we can put the backslash into a variable as a workaround though : " }, { "code": null, "e": 1718, "s": 1710, "text": "Python3" }, { "code": "newline = ord('\\n') f\"newline: {newline}\"", "e": 1760, "s": 1718, "text": null }, { "code": null, "e": 1771, "s": 1760, "text": "Output : " }, { "code": null, "e": 1783, "s": 1771, "text": "newline: 10" }, { "code": null, "e": 1834, "s": 1783, "text": "Reference : PEP 498, Literal String Interpolation " }, { "code": null, "e": 1847, "s": 1834, "text": "mustafaaçık" }, { "code": null, "e": 1861, "s": 1847, "text": "python-string" }, { "code": null, "e": 1868, "s": 1861, "text": "Python" }, { "code": null, "e": 1966, "s": 1868, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1998, "s": 1966, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2027, "s": 1998, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2054, "s": 2027, "text": "Python Classes and Objects" }, { "code": null, "e": 2090, "s": 2054, "text": "Convert integer to string in Python" }, { "code": null, "e": 2121, "s": 2090, "text": "Python | os.path.join() method" }, { "code": null, "e": 2158, "s": 2121, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 2181, "s": 2158, "text": "Introduction To PYTHON" }, { "code": null, "e": 2202, "s": 2181, "text": "Python OOPs Concepts" }, { "code": null, "e": 2258, "s": 2202, "text": "How to drop one or multiple columns in Pandas Dataframe" } ]
Python OpenCV | cv2.erode() method
29 Nov, 2019 OpenCV-Python is a library of Python bindings designed to solve computer vision problems. cv2.erode() method is used to perform erosion on the image. The basic idea of erosion is just like soil erosion only, it erodes away the boundaries of foreground object (Always try to keep foreground in white). It is normally performed on binary images. It needs two inputs, one is our original image, second one is called structuring element or kernel which decides the nature of operation. A pixel in the original image (either 1 or 0) will be considered 1 only if all the pixels under the kernel is 1, otherwise it is eroded (made to zero). Syntax: cv2.erode(src, kernel[, dst[, anchor[, iterations[, borderType[, borderValue]]]]])Parameters:src: It is the image which is to be eroded .kernel: A structuring element used for erosion. If element = Mat(), a 3 x 3 rectangular structuring element is used. Kernel can be created using getStructuringElement.dst: It is the output image of the same size and type as src.anchor: It is a variable of type integer representing anchor point and it’s default value Point is (-1, -1) which means that the anchor is at the kernel center.borderType: It depicts what kind of border to be added. It is defined by flags like cv2.BORDER_CONSTANT, cv2.BORDER_REFLECT, etc.iterations: It is number of times erosion is applied.borderValue: It is border value in case of a constant border.Return Value: It returns an image. Image used for all the below examples:Example #1: # Python program to explain cv2.erode() method # importing cv2 import cv2 # importing numpy import numpy as np # path path = r'C:\Users\Rajnish\Desktop\geeksforgeeks\geeks.png' # Reading an image in default mode image = cv2.imread(path) # Window name in which image is displayed window_name = 'Image' # Creating kernelkernel = np.ones((5, 5), np.uint8) # Using cv2.erode() method image = cv2.erode(image, kernel) # Displaying the image cv2.imshow(window_name, image) Output: Example #2: # Python program to explain cv2.erode() method # importing cv2 import cv2 # importing numpy import numpy as np # path path = r'C:\Users\Rajnish\Desktop\geeksforgeeks\geeks.png' # Reading an image in default mode image = cv2.imread(path) # Window name in which image is displayed window_name = 'Image' # Creating kernelkernel = np.ones((6, 6), np.uint8) # Using cv2.erode() method image = cv2.erode(image, kernel, cv2.BORDER_REFLECT) # Displaying the image cv2.imshow(window_name, image) Output: Image-Processing OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n29 Nov, 2019" }, { "code": null, "e": 686, "s": 52, "text": "OpenCV-Python is a library of Python bindings designed to solve computer vision problems. cv2.erode() method is used to perform erosion on the image. The basic idea of erosion is just like soil erosion only, it erodes away the boundaries of foreground object (Always try to keep foreground in white). It is normally performed on binary images. It needs two inputs, one is our original image, second one is called structuring element or kernel which decides the nature of operation. A pixel in the original image (either 1 or 0) will be considered 1 only if all the pixels under the kernel is 1, otherwise it is eroded (made to zero)." }, { "code": null, "e": 1497, "s": 686, "text": "Syntax: cv2.erode(src, kernel[, dst[, anchor[, iterations[, borderType[, borderValue]]]]])Parameters:src: It is the image which is to be eroded .kernel: A structuring element used for erosion. If element = Mat(), a 3 x 3 rectangular structuring element is used. Kernel can be created using getStructuringElement.dst: It is the output image of the same size and type as src.anchor: It is a variable of type integer representing anchor point and it’s default value Point is (-1, -1) which means that the anchor is at the kernel center.borderType: It depicts what kind of border to be added. It is defined by flags like cv2.BORDER_CONSTANT, cv2.BORDER_REFLECT, etc.iterations: It is number of times erosion is applied.borderValue: It is border value in case of a constant border.Return Value: It returns an image." }, { "code": null, "e": 1547, "s": 1497, "text": "Image used for all the below examples:Example #1:" }, { "code": "# Python program to explain cv2.erode() method # importing cv2 import cv2 # importing numpy import numpy as np # path path = r'C:\\Users\\Rajnish\\Desktop\\geeksforgeeks\\geeks.png' # Reading an image in default mode image = cv2.imread(path) # Window name in which image is displayed window_name = 'Image' # Creating kernelkernel = np.ones((5, 5), np.uint8) # Using cv2.erode() method image = cv2.erode(image, kernel) # Displaying the image cv2.imshow(window_name, image) ", "e": 2026, "s": 1547, "text": null }, { "code": null, "e": 2034, "s": 2026, "text": "Output:" }, { "code": null, "e": 2046, "s": 2034, "text": "Example #2:" }, { "code": "# Python program to explain cv2.erode() method # importing cv2 import cv2 # importing numpy import numpy as np # path path = r'C:\\Users\\Rajnish\\Desktop\\geeksforgeeks\\geeks.png' # Reading an image in default mode image = cv2.imread(path) # Window name in which image is displayed window_name = 'Image' # Creating kernelkernel = np.ones((6, 6), np.uint8) # Using cv2.erode() method image = cv2.erode(image, kernel, cv2.BORDER_REFLECT) # Displaying the image cv2.imshow(window_name, image) ", "e": 2545, "s": 2046, "text": null }, { "code": null, "e": 2553, "s": 2545, "text": "Output:" }, { "code": null, "e": 2570, "s": 2553, "text": "Image-Processing" }, { "code": null, "e": 2577, "s": 2570, "text": "OpenCV" }, { "code": null, "e": 2584, "s": 2577, "text": "Python" } ]
Program to calculate Dooms Day for a year
06 Oct, 2021 Doomsday may refer to a hypothetical event according to which the end of human life is at the highest possibility. There are many algorithms written to calculate which day of a week in a year has the highest possibility of doomsday falling on that day.All the statements are with respect to Gregorian Calendar. As the Gregorian calendar repeats itself every 400 years so a set of rules is decided for 1st 400 years only. Algorithms are derived from the calculations of John Conway, Lewis Carroll and many other mathematicians in history who worked on the calculation of Dooms Day.To calculate Doom’s Day of a particular year following algorithm is used:- Extract the last two digits of the year.(Let this be y) Divide by 12 take the floor of the value. Then add remainder of dividing y by 12. Calculate the result when remainder of y divided by 12 is divided by 4. Take the floor of the above value and then add. Take remainder after dividing with 7 (mod 7). Add the value of anchor day of the week starting from Sunday (Considering Sunday as 0) The formula becomes – Here [ ] is Greatest Integer Function.Anchor day changes after 100 years and repeats after every 400 years in the following way – 0-99 yrs --> Tuesday 100-199 yrs --> Sunday 200-299 yrs --> Friday 300-399 yr --> Wednesday After this the above anchor days repeat as mentioned in the beginning of the article.Examples: Input : 2005 Output : Doomsday in the year 2005 = Monday Input : 1800 Output : Doomsday in the year 1800 = Friday Below is the implementation. C++14 Java Python3 C# Javascript #include<bits/stdc++.h>using namespace std; string dooms_day(int year){ // map to store days value of // anchor day can be known map<int, string> dict_day; dict_day[0] = "Sunday"; dict_day[1] = "Monday"; dict_day[2] = "Tuesday"; dict_day[3] = "Wednesday"; dict_day[4] = "Thursday"; dict_day[5] = "Friday"; dict_day[6] = "Saturday"; // Gregorian calendar repeats // every 400 years int k = year % 400; int anchor; // Decide the anchor day if(k >= 0 && k < 100) anchor = 2; else if(k >= 100 && k < 200) anchor = 0; else if(k >= 200 && k < 300) anchor = 5; else anchor = 3; int y = year % 100; // Dooms day formula by Conway int doomsday = ((y / 12 + y % 12 + (y % 12) / 4) % 7 + anchor) % 7; return dict_day[doomsday];} // Driver codeint main(){ int year = 1966; cout << "Doomsday in the year " << year << " = " << dooms_day(year); return 0;} // This code is contributed by yatinagg import java.util.*; class GFG{ public static String dooms_day(int year){ // map to store days value of // anchor day can be known HashMap<Integer, String> dict_day = new HashMap<>(); dict_day.put(0, "Sunday"); dict_day.put(1, "Monday"); dict_day.put(2, "Tuesday"); dict_day.put(3, "Wednesday"); dict_day.put(4, "Thursday"); dict_day.put(5, "Friday"); dict_day.put(6, "Saturday"); // Gregorian calendar repeats // every 400 years int k = year % 400; int anchor; // Decide the anchor day if (k >= 0 && k < 100) anchor = 2; else if (k >= 100 && k < 200) anchor = 0; else if (k >= 200 && k < 300) anchor = 5; else anchor = 3; int y = year % 100; // Dooms day formula by Conway int doomsday = ((y / 12 + y % 12 + (y % 12) / 4) % 7 + anchor) % 7; return dict_day.get(doomsday);} // Driver codepublic static void main(String[] args){ int year = 1966; System.out.println("Doomsday in the year " + year + " = " + dooms_day(year));}} // This code is contributed divyeshrabadiya07 def dooms_day(year): # dictionary to store days # value of anchor day can be known dict_day ={ 0 : "Sunday", 1 : "Monday", 2 : "Tuesday", 3 : "Wednesday", 4 : "Thursday", 5 : "Friday", 6 : "Saturday" } # gregorian calendar repeats # every 400 years k = year % 400 # decide the anchor day if(k >= 0 and k < 100): anchor = 2 elif(k >= 100 and k < 200): anchor = 0 elif(k >= 200 and k < 300): anchor = 5 else: anchor = 3 y = year % 100 # dooms day formula by Conway doomsday = ((y//12 + y % 12 + (y % 12)//4)% 7 + anchor) % 7 return dict_day[doomsday] # Driver codeyear = 1966print("Doomsday in the year % s = % s"%(year, dooms_day(year))) using System;using System.Collections.Generic; class GFG{ static String dooms_day(int year) { // map to store days value of // anchor day can be known Dictionary<int, string> dict_day = new Dictionary<int, string>(); dict_day.Add(0, "Sunday"); dict_day.Add(1, "Monday"); dict_day.Add(2, "Tuesday"); dict_day.Add(3, "Wednesday"); dict_day.Add(4, "Thursday"); dict_day.Add(5, "Friday"); dict_day.Add(6, "Saturday"); // Gregorian calendar repeats // every 400 years int k = year % 400; int anchor; // Decide the anchor day if (k >= 0 && k < 100) anchor = 2; else if (k >= 100 && k < 200) anchor = 0; else if (k >= 200 && k < 300) anchor = 5; else anchor = 3; int y = year % 100; // Dooms day formula by Conway int doomsday = ((y / 12 + y % 12 + (y % 12) / 4) % 7 + anchor) % 7; return dict_day[doomsday]; } // Driver code static void Main() { int year = 1966; Console.WriteLine("Doomsday in the year " + year + " = " + dooms_day(year)); }} // This code is contributed by divyesh072019 <script> function dooms_day(year) { // map to store days value of // anchor day can be known var dict_day = new Map(); dict_day.set(0, "Sunday"); dict_day.set(1, "Monday"); dict_day.set(2, "Tuesday"); dict_day.set(3, "Wednesday"); dict_day.set(4, "Thursday"); dict_day.set(5, "Friday"); dict_day.set(6, "Saturday"); // Gregorian calendar repeats // every 400 years var k = year % 400; var anchor; // Decide the anchor day if (k >= 0 && k < 100) anchor = 2; else if (k >= 100 && k < 200) anchor = 0; else if (k >= 200 && k < 300) anchor = 5; else anchor = 3; var y = parseInt(year % 100); // Dooms day formula by Conway var doomsday = parseInt(parseInt(parseInt(y / 12) + y % 12 + parseInt((y % 12) / 4)) % 7 + anchor) % 7; return dict_day.get(doomsday); } // Driver code var year = 1966; document.write("Doomsday in the year " + year + " = " + dooms_day(year)); // This code is contributed by gauravrajput1</script> Doomsday in the year 1966 = Monday yatinagg divyeshrabadiya07 divyesh072019 GauravRajput1 simranarora5sos Python-Miscellaneous Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Oct, 2021" }, { "code": null, "e": 707, "s": 52, "text": "Doomsday may refer to a hypothetical event according to which the end of human life is at the highest possibility. There are many algorithms written to calculate which day of a week in a year has the highest possibility of doomsday falling on that day.All the statements are with respect to Gregorian Calendar. As the Gregorian calendar repeats itself every 400 years so a set of rules is decided for 1st 400 years only. Algorithms are derived from the calculations of John Conway, Lewis Carroll and many other mathematicians in history who worked on the calculation of Dooms Day.To calculate Doom’s Day of a particular year following algorithm is used:-" }, { "code": null, "e": 763, "s": 707, "text": "Extract the last two digits of the year.(Let this be y)" }, { "code": null, "e": 805, "s": 763, "text": "Divide by 12 take the floor of the value." }, { "code": null, "e": 845, "s": 805, "text": "Then add remainder of dividing y by 12." }, { "code": null, "e": 917, "s": 845, "text": "Calculate the result when remainder of y divided by 12 is divided by 4." }, { "code": null, "e": 965, "s": 917, "text": "Take the floor of the above value and then add." }, { "code": null, "e": 1011, "s": 965, "text": "Take remainder after dividing with 7 (mod 7)." }, { "code": null, "e": 1098, "s": 1011, "text": "Add the value of anchor day of the week starting from Sunday (Considering Sunday as 0)" }, { "code": null, "e": 1120, "s": 1098, "text": "The formula becomes –" }, { "code": null, "e": 1252, "s": 1122, "text": "Here [ ] is Greatest Integer Function.Anchor day changes after 100 years and repeats after every 400 years in the following way –" }, { "code": null, "e": 1346, "s": 1254, "text": "0-99 yrs --> Tuesday\n100-199 yrs --> Sunday\n200-299 yrs --> Friday\n300-399 yr --> Wednesday" }, { "code": null, "e": 1443, "s": 1348, "text": "After this the above anchor days repeat as mentioned in the beginning of the article.Examples:" }, { "code": null, "e": 1561, "s": 1445, "text": "Input : 2005\nOutput : Doomsday in the year 2005 = Monday\n\nInput : 1800\nOutput : Doomsday in the year 1800 = Friday" }, { "code": null, "e": 1592, "s": 1563, "text": "Below is the implementation." }, { "code": null, "e": 1600, "s": 1594, "text": "C++14" }, { "code": null, "e": 1605, "s": 1600, "text": "Java" }, { "code": null, "e": 1613, "s": 1605, "text": "Python3" }, { "code": null, "e": 1616, "s": 1613, "text": "C#" }, { "code": null, "e": 1627, "s": 1616, "text": "Javascript" }, { "code": "#include<bits/stdc++.h>using namespace std; string dooms_day(int year){ // map to store days value of // anchor day can be known map<int, string> dict_day; dict_day[0] = \"Sunday\"; dict_day[1] = \"Monday\"; dict_day[2] = \"Tuesday\"; dict_day[3] = \"Wednesday\"; dict_day[4] = \"Thursday\"; dict_day[5] = \"Friday\"; dict_day[6] = \"Saturday\"; // Gregorian calendar repeats // every 400 years int k = year % 400; int anchor; // Decide the anchor day if(k >= 0 && k < 100) anchor = 2; else if(k >= 100 && k < 200) anchor = 0; else if(k >= 200 && k < 300) anchor = 5; else anchor = 3; int y = year % 100; // Dooms day formula by Conway int doomsday = ((y / 12 + y % 12 + (y % 12) / 4) % 7 + anchor) % 7; return dict_day[doomsday];} // Driver codeint main(){ int year = 1966; cout << \"Doomsday in the year \" << year << \" = \" << dooms_day(year); return 0;} // This code is contributed by yatinagg", "e": 2717, "s": 1627, "text": null }, { "code": "import java.util.*; class GFG{ public static String dooms_day(int year){ // map to store days value of // anchor day can be known HashMap<Integer, String> dict_day = new HashMap<>(); dict_day.put(0, \"Sunday\"); dict_day.put(1, \"Monday\"); dict_day.put(2, \"Tuesday\"); dict_day.put(3, \"Wednesday\"); dict_day.put(4, \"Thursday\"); dict_day.put(5, \"Friday\"); dict_day.put(6, \"Saturday\"); // Gregorian calendar repeats // every 400 years int k = year % 400; int anchor; // Decide the anchor day if (k >= 0 && k < 100) anchor = 2; else if (k >= 100 && k < 200) anchor = 0; else if (k >= 200 && k < 300) anchor = 5; else anchor = 3; int y = year % 100; // Dooms day formula by Conway int doomsday = ((y / 12 + y % 12 + (y % 12) / 4) % 7 + anchor) % 7; return dict_day.get(doomsday);} // Driver codepublic static void main(String[] args){ int year = 1966; System.out.println(\"Doomsday in the year \" + year + \" = \" + dooms_day(year));}} // This code is contributed divyeshrabadiya07", "e": 3973, "s": 2717, "text": null }, { "code": "def dooms_day(year): # dictionary to store days # value of anchor day can be known dict_day ={ 0 : \"Sunday\", 1 : \"Monday\", 2 : \"Tuesday\", 3 : \"Wednesday\", 4 : \"Thursday\", 5 : \"Friday\", 6 : \"Saturday\" } # gregorian calendar repeats # every 400 years k = year % 400 # decide the anchor day if(k >= 0 and k < 100): anchor = 2 elif(k >= 100 and k < 200): anchor = 0 elif(k >= 200 and k < 300): anchor = 5 else: anchor = 3 y = year % 100 # dooms day formula by Conway doomsday = ((y//12 + y % 12 + (y % 12)//4)% 7 + anchor) % 7 return dict_day[doomsday] # Driver codeyear = 1966print(\"Doomsday in the year % s = % s\"%(year, dooms_day(year)))", "e": 4867, "s": 3973, "text": null }, { "code": "using System;using System.Collections.Generic; class GFG{ static String dooms_day(int year) { // map to store days value of // anchor day can be known Dictionary<int, string> dict_day = new Dictionary<int, string>(); dict_day.Add(0, \"Sunday\"); dict_day.Add(1, \"Monday\"); dict_day.Add(2, \"Tuesday\"); dict_day.Add(3, \"Wednesday\"); dict_day.Add(4, \"Thursday\"); dict_day.Add(5, \"Friday\"); dict_day.Add(6, \"Saturday\"); // Gregorian calendar repeats // every 400 years int k = year % 400; int anchor; // Decide the anchor day if (k >= 0 && k < 100) anchor = 2; else if (k >= 100 && k < 200) anchor = 0; else if (k >= 200 && k < 300) anchor = 5; else anchor = 3; int y = year % 100; // Dooms day formula by Conway int doomsday = ((y / 12 + y % 12 + (y % 12) / 4) % 7 + anchor) % 7; return dict_day[doomsday]; } // Driver code static void Main() { int year = 1966; Console.WriteLine(\"Doomsday in the year \" + year + \" = \" + dooms_day(year)); }} // This code is contributed by divyesh072019", "e": 6358, "s": 4867, "text": null }, { "code": "<script> function dooms_day(year) { // map to store days value of // anchor day can be known var dict_day = new Map(); dict_day.set(0, \"Sunday\"); dict_day.set(1, \"Monday\"); dict_day.set(2, \"Tuesday\"); dict_day.set(3, \"Wednesday\"); dict_day.set(4, \"Thursday\"); dict_day.set(5, \"Friday\"); dict_day.set(6, \"Saturday\"); // Gregorian calendar repeats // every 400 years var k = year % 400; var anchor; // Decide the anchor day if (k >= 0 && k < 100) anchor = 2; else if (k >= 100 && k < 200) anchor = 0; else if (k >= 200 && k < 300) anchor = 5; else anchor = 3; var y = parseInt(year % 100); // Dooms day formula by Conway var doomsday = parseInt(parseInt(parseInt(y / 12) + y % 12 + parseInt((y % 12) / 4)) % 7 + anchor) % 7; return dict_day.get(doomsday); } // Driver code var year = 1966; document.write(\"Doomsday in the year \" + year + \" = \" + dooms_day(year)); // This code is contributed by gauravrajput1</script>", "e": 7515, "s": 6358, "text": null }, { "code": null, "e": 7550, "s": 7515, "text": "Doomsday in the year 1966 = Monday" }, { "code": null, "e": 7561, "s": 7552, "text": "yatinagg" }, { "code": null, "e": 7579, "s": 7561, "text": "divyeshrabadiya07" }, { "code": null, "e": 7593, "s": 7579, "text": "divyesh072019" }, { "code": null, "e": 7607, "s": 7593, "text": "GauravRajput1" }, { "code": null, "e": 7623, "s": 7607, "text": "simranarora5sos" }, { "code": null, "e": 7644, "s": 7623, "text": "Python-Miscellaneous" }, { "code": null, "e": 7651, "s": 7644, "text": "Python" } ]
ReactJS | Hot Module Replacement
30 Apr, 2019 It is always recommended to start your react journey using the create-react-app which can be found here. It saves a lot of time as all the basic application backend is provided after installation, and we are only left to deal with the implementation details. Whenever we make changes in the main core ‘app.js’ file inside the create-react-app, and visit the localhost then we see that the page refreshes itself after updating the content.‘app.js file’ // using a variable and printing it in jsx// app.js inside the src folder of create-react-app // import statementsimport React, { Component } from 'react';import logo from './logo.svg';import './App.css'; class App extends Component { // react method which is used to print // content on to the screen. render() { const helloWorld = `How you doin'?`; return ( <div className="App"> <h2>{helloWorld}</h2> </div> ); }}// exporting the default app // so it can be used in other modulesexport default App; In the above code we are declaring a variable and then printing it using the render method provide by react, this is one part of it. In the app.js file, we write the main JSX( javascript XML ) which includes javascript inside the HTML tags. After the JSX we export the content so that ReactDOM can make use of it and then finally show it inside the specified element. The code for the ‘index.js’ which makes use of the ReactDOM looks like the code below:‘index.js file’ import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App';import * as serviceWorker from './serviceWorker'; ReactDOM.render(<App />, document.getElementById('root')); // If you want your app to work offline and load faster, you can change// unregister() to register() below. Note this comes with some pitfalls.// Learn more about service workers: https://bit.ly/CRA-PWAserviceWorker.unregister(); Output: Now whenever we make any kind of change to our app.js file and save it, react will compile it and the changed content will be shown on the web. It will refresh the page every time we save it, though it recommended to make use of the HOT Module Replacement, which allows us to reload our application in the browser without refreshing the page. It improves the experience as a developer. In order to make use of this module, our code inside the ‘index.js’ will look something like the code below:‘updated index.js file’ import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App';import * as serviceWorker from './serviceWorker'; ReactDOM.render(<App />, document.getElementById('root')); // If you want your app to work offline and load faster, you can change// unregister() to register() below. Note this comes with some pitfalls.// Learn more about service workers: https://bit.ly/CRA-PWAserviceWorker.unregister(); // Hot Module Replacementif(module.hot){ module.hot.accept();} Now, the browser shouldn’t refresh though the content should be updated. react-js 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 How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array REST API (Introduction) Difference Between PUT and PATCH Request ReactJS | Router Roadmap to Learn JavaScript For Beginners How to float three div side by side using CSS? How to get character array from string in JavaScript?
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Apr, 2019" }, { "code": null, "e": 480, "s": 28, "text": "It is always recommended to start your react journey using the create-react-app which can be found here. It saves a lot of time as all the basic application backend is provided after installation, and we are only left to deal with the implementation details. Whenever we make changes in the main core ‘app.js’ file inside the create-react-app, and visit the localhost then we see that the page refreshes itself after updating the content.‘app.js file’" }, { "code": "// using a variable and printing it in jsx// app.js inside the src folder of create-react-app // import statementsimport React, { Component } from 'react';import logo from './logo.svg';import './App.css'; class App extends Component { // react method which is used to print // content on to the screen. render() { const helloWorld = `How you doin'?`; return ( <div className=\"App\"> <h2>{helloWorld}</h2> </div> ); }}// exporting the default app // so it can be used in other modulesexport default App;", "e": 1012, "s": 480, "text": null }, { "code": null, "e": 1482, "s": 1012, "text": "In the above code we are declaring a variable and then printing it using the render method provide by react, this is one part of it. In the app.js file, we write the main JSX( javascript XML ) which includes javascript inside the HTML tags. After the JSX we export the content so that ReactDOM can make use of it and then finally show it inside the specified element. The code for the ‘index.js’ which makes use of the ReactDOM looks like the code below:‘index.js file’" }, { "code": "import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App';import * as serviceWorker from './serviceWorker'; ReactDOM.render(<App />, document.getElementById('root')); // If you want your app to work offline and load faster, you can change// unregister() to register() below. Note this comes with some pitfalls.// Learn more about service workers: https://bit.ly/CRA-PWAserviceWorker.unregister();", "e": 1927, "s": 1482, "text": null }, { "code": null, "e": 1935, "s": 1927, "text": "Output:" }, { "code": null, "e": 2453, "s": 1935, "text": "Now whenever we make any kind of change to our app.js file and save it, react will compile it and the changed content will be shown on the web. It will refresh the page every time we save it, though it recommended to make use of the HOT Module Replacement, which allows us to reload our application in the browser without refreshing the page. It improves the experience as a developer. In order to make use of this module, our code inside the ‘index.js’ will look something like the code below:‘updated index.js file’" }, { "code": "import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App';import * as serviceWorker from './serviceWorker'; ReactDOM.render(<App />, document.getElementById('root')); // If you want your app to work offline and load faster, you can change// unregister() to register() below. Note this comes with some pitfalls.// Learn more about service workers: https://bit.ly/CRA-PWAserviceWorker.unregister(); // Hot Module Replacementif(module.hot){ module.hot.accept();}", "e": 2965, "s": 2453, "text": null }, { "code": null, "e": 3038, "s": 2965, "text": "Now, the browser shouldn’t refresh though the content should be updated." }, { "code": null, "e": 3047, "s": 3038, "text": "react-js" }, { "code": null, "e": 3064, "s": 3047, "text": "Web Technologies" }, { "code": null, "e": 3162, "s": 3064, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3223, "s": 3162, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3266, "s": 3223, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 3338, "s": 3266, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3378, "s": 3338, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3402, "s": 3378, "text": "REST API (Introduction)" }, { "code": null, "e": 3443, "s": 3402, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3460, "s": 3443, "text": "ReactJS | Router" }, { "code": null, "e": 3502, "s": 3460, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3549, "s": 3502, "text": "How to float three div side by side using CSS?" } ]
Underscore.js _.map() Function
24 Nov, 2021 The Underscore.js is a JavaScript library that provides a lot of useful functions that helps in the programming in a big way like the map, filter, invoke etc even without using any built-in objects. The _.map() function is an inbuilt function in Underscore.js library of the JavaScript which is used to produce a new array of values by mapping each value in list through transformation function (iteratee). It displays the result as a list on the console. In this list the output of the first element, i.e, the element at index 0 has it’s result at index 0 of the returned list and when all the elements of the list are passed to the function/iteratee and no more elements remain then the _.map loop ends. Syntax: _.map(list, function) Parameters: It accepts two parameters which are specified below- list: It is the list which contains some elements. function: It is the function which is executed by taking each element of the list. Return values: It returns the object property value or array element value at the current position. Passing a list of numbers with user defined function: When we are passing the list of elements to the user defined function then it takes the element from the list one by one and performs the operations of the function. Here, the function calculates the multiplication operation. It multiplies the list elements by 2. After performing its operations, the function then returns the value to be shown on the console.<html> <head> <script> <src = "https://cdnjs.cloudflare.com/ajax/libs/ underscore.js/1.9.1/underscore-min.js" > </script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore-min.js.map"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore.js"></script></head> <body> <script type="text/javascript"> _.map([1, 2, 3, 4], function(num){ return num * 2; }); </script></body> </html>Output: <html> <head> <script> <src = "https://cdnjs.cloudflare.com/ajax/libs/ underscore.js/1.9.1/underscore-min.js" > </script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore-min.js.map"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore.js"></script></head> <body> <script type="text/javascript"> _.map([1, 2, 3, 4], function(num){ return num * 2; }); </script></body> </html> Output: Passing a list of numbers with another user defined function: When we are passing the list of numbers to the user defined function which takes ‘num’ as argument then it takes the numbers from the list one by one and performs it’s operation. The function used here takes each element from the list and uses it in the resulted sentence. Therefore, the final result is a sentence “This is **(element of the list) list item”.<html> <head> <script> <src = "https://cdnjs.cloudflare.com/ajax/libs/ underscore.js/1.9.1/underscore-min.js" > </script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore-min.js.map"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore.js"></script></head> <body> <script type="text/javascript"> _.map( [1, 2, 3], function( num ) { for(var i=0;i<num;i++) var str="This is"; str+=i+1; str+="list item"; return(str); }); </script></body> </html>Output: <html> <head> <script> <src = "https://cdnjs.cloudflare.com/ajax/libs/ underscore.js/1.9.1/underscore-min.js" > </script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore-min.js.map"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore.js"></script></head> <body> <script type="text/javascript"> _.map( [1, 2, 3], function( num ) { for(var i=0;i<num;i++) var str="This is"; str+=i+1; str+="list item"; return(str); }); </script></body> </html> Output: Passing a list of numbers with _.last inbuilt function: When we are passing the list of numbers to the _.last inbuilt function then it takes the words from the list one by one and performs it’s operation. The _.last() takes each array from the list and returns the last element from each array. Therefore, the final result is the last element of every array.<html> <head> <script> <src = "https://cdnjs.cloudflare.com/ajax/libs/ underscore.js/1.9.1/underscore-min.js" > </script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore-min.js.map"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore.js"></script></head> <body> <script type="text/javascript"> _.map([[1, 2], [3, 4], [5, 6]], _.last); </script></body> </html>Output: <html> <head> <script> <src = "https://cdnjs.cloudflare.com/ajax/libs/ underscore.js/1.9.1/underscore-min.js" > </script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore-min.js.map"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore.js"></script></head> <body> <script type="text/javascript"> _.map([[1, 2], [3, 4], [5, 6]], _.last); </script></body> </html> Output: Passing a list of words with a user defined function: First we need to create a list which we will be going to use. Here the function takes each word from the list and prints it to the console along with a set of words which are “is mapped from a list”. The output will contain the list item along with the given set of words.<html> <head> <script> <src = "https://cdnjs.cloudflare.com/ajax/libs/ underscore.js/1.9.1/underscore-min.js" > </script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore-min.js.map"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore.js"></script></head> <body> <script type="text/javascript"> var list = ['Geeks','for', 'Geeks', 'JS']; m = _.map(list, function (l) { return l + ' is mapped from a list.'; }); </script></body> </html>Output: <html> <head> <script> <src = "https://cdnjs.cloudflare.com/ajax/libs/ underscore.js/1.9.1/underscore-min.js" > </script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore-min.js.map"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore.js"></script></head> <body> <script type="text/javascript"> var list = ['Geeks','for', 'Geeks', 'JS']; m = _.map(list, function (l) { return l + ' is mapped from a list.'; }); </script></body> </html> Output: Passing a list of numbers with a : ? function: Pass the list items to the function directly. Here the function uses : ? operators (instead of for loop) to find whether the list number is smaller than or greater than 3 accordingly it prints the result.<html> <head> <script> <src = "https://cdnjs.cloudflare.com/ajax/libs/ underscore.js/1.9.1/underscore-min.js" > </script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore-min.js.map"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore.js"></script></head> <body> <script type="text/javascript"> _.map( [ 0, 7, 2, -1, 8 ], function( n ) { return n>=3 ? "greater" : "smaller"; }); </script></body> </html>Output: <html> <head> <script> <src = "https://cdnjs.cloudflare.com/ajax/libs/ underscore.js/1.9.1/underscore-min.js" > </script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore-min.js.map"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore.js"></script></head> <body> <script type="text/javascript"> _.map( [ 0, 7, 2, -1, 8 ], function( n ) { return n>=3 ? "greater" : "smaller"; }); </script></body> </html> Output: JavaScript 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 Hide or show elements in HTML using display property How to append HTML code to a div using JavaScript ? Difference Between PUT and PATCH Request How to Open URL in New Tab using JavaScript ? How to calculate the number of days between two dates in javascript? File uploading in React.js Roadmap to Learn JavaScript For Beginners
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Nov, 2021" }, { "code": null, "e": 227, "s": 28, "text": "The Underscore.js is a JavaScript library that provides a lot of useful functions that helps in the programming in a big way like the map, filter, invoke etc even without using any built-in objects." }, { "code": null, "e": 734, "s": 227, "text": "The _.map() function is an inbuilt function in Underscore.js library of the JavaScript which is used to produce a new array of values by mapping each value in list through transformation function (iteratee). It displays the result as a list on the console. In this list the output of the first element, i.e, the element at index 0 has it’s result at index 0 of the returned list and when all the elements of the list are passed to the function/iteratee and no more elements remain then the _.map loop ends." }, { "code": null, "e": 742, "s": 734, "text": "Syntax:" }, { "code": null, "e": 764, "s": 742, "text": "_.map(list, function)" }, { "code": null, "e": 829, "s": 764, "text": "Parameters: It accepts two parameters which are specified below-" }, { "code": null, "e": 880, "s": 829, "text": "list: It is the list which contains some elements." }, { "code": null, "e": 963, "s": 880, "text": "function: It is the function which is executed by taking each element of the list." }, { "code": null, "e": 1063, "s": 963, "text": "Return values: It returns the object property value or array element value at the current position." }, { "code": null, "e": 2063, "s": 1063, "text": "Passing a list of numbers with user defined function: When we are passing the list of elements to the user defined function then it takes the element from the list one by one and performs the operations of the function. Here, the function calculates the multiplication operation. It multiplies the list elements by 2. After performing its operations, the function then returns the value to be shown on the console.<html> <head> <script> <src = \"https://cdnjs.cloudflare.com/ajax/libs/ underscore.js/1.9.1/underscore-min.js\" > </script> <script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore-min.js.map\"></script> <script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore.js\"></script></head> <body> <script type=\"text/javascript\"> _.map([1, 2, 3, 4], function(num){ return num * 2; }); </script></body> </html>Output:" }, { "code": "<html> <head> <script> <src = \"https://cdnjs.cloudflare.com/ajax/libs/ underscore.js/1.9.1/underscore-min.js\" > </script> <script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore-min.js.map\"></script> <script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore.js\"></script></head> <body> <script type=\"text/javascript\"> _.map([1, 2, 3, 4], function(num){ return num * 2; }); </script></body> </html>", "e": 2642, "s": 2063, "text": null }, { "code": null, "e": 2650, "s": 2642, "text": "Output:" }, { "code": null, "e": 3834, "s": 2650, "text": "Passing a list of numbers with another user defined function: When we are passing the list of numbers to the user defined function which takes ‘num’ as argument then it takes the numbers from the list one by one and performs it’s operation. The function used here takes each element from the list and uses it in the resulted sentence. Therefore, the final result is a sentence “This is **(element of the list) list item”.<html> <head> <script> <src = \"https://cdnjs.cloudflare.com/ajax/libs/ underscore.js/1.9.1/underscore-min.js\" > </script> <script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore-min.js.map\"></script> <script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore.js\"></script></head> <body> <script type=\"text/javascript\"> _.map( [1, 2, 3], function( num ) { for(var i=0;i<num;i++) var str=\"This is\"; str+=i+1; str+=\"list item\"; return(str); }); </script></body> </html>Output:" }, { "code": "<html> <head> <script> <src = \"https://cdnjs.cloudflare.com/ajax/libs/ underscore.js/1.9.1/underscore-min.js\" > </script> <script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore-min.js.map\"></script> <script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore.js\"></script></head> <body> <script type=\"text/javascript\"> _.map( [1, 2, 3], function( num ) { for(var i=0;i<num;i++) var str=\"This is\"; str+=i+1; str+=\"list item\"; return(str); }); </script></body> </html>", "e": 4590, "s": 3834, "text": null }, { "code": null, "e": 4598, "s": 4590, "text": "Output:" }, { "code": null, "e": 5528, "s": 4598, "text": "Passing a list of numbers with _.last inbuilt function: When we are passing the list of numbers to the _.last inbuilt function then it takes the words from the list one by one and performs it’s operation. The _.last() takes each array from the list and returns the last element from each array. Therefore, the final result is the last element of every array.<html> <head> <script> <src = \"https://cdnjs.cloudflare.com/ajax/libs/ underscore.js/1.9.1/underscore-min.js\" > </script> <script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore-min.js.map\"></script> <script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore.js\"></script></head> <body> <script type=\"text/javascript\"> _.map([[1, 2], [3, 4], [5, 6]], _.last); </script></body> </html>Output:" }, { "code": "<html> <head> <script> <src = \"https://cdnjs.cloudflare.com/ajax/libs/ underscore.js/1.9.1/underscore-min.js\" > </script> <script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore-min.js.map\"></script> <script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore.js\"></script></head> <body> <script type=\"text/javascript\"> _.map([[1, 2], [3, 4], [5, 6]], _.last); </script></body> </html>", "e": 6093, "s": 5528, "text": null }, { "code": null, "e": 6101, "s": 6093, "text": "Output:" }, { "code": null, "e": 7104, "s": 6101, "text": "Passing a list of words with a user defined function: First we need to create a list which we will be going to use. Here the function takes each word from the list and prints it to the console along with a set of words which are “is mapped from a list”. The output will contain the list item along with the given set of words.<html> <head> <script> <src = \"https://cdnjs.cloudflare.com/ajax/libs/ underscore.js/1.9.1/underscore-min.js\" > </script> <script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore-min.js.map\"></script> <script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore.js\"></script></head> <body> <script type=\"text/javascript\"> var list = ['Geeks','for', 'Geeks', 'JS']; m = _.map(list, function (l) { return l + ' is mapped from a list.'; }); </script></body> </html>Output:" }, { "code": "<html> <head> <script> <src = \"https://cdnjs.cloudflare.com/ajax/libs/ underscore.js/1.9.1/underscore-min.js\" > </script> <script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore-min.js.map\"></script> <script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore.js\"></script></head> <body> <script type=\"text/javascript\"> var list = ['Geeks','for', 'Geeks', 'JS']; m = _.map(list, function (l) { return l + ' is mapped from a list.'; }); </script></body> </html>", "e": 7774, "s": 7104, "text": null }, { "code": null, "e": 7782, "s": 7774, "text": "Output:" }, { "code": null, "e": 8672, "s": 7782, "text": "Passing a list of numbers with a : ? function: Pass the list items to the function directly. Here the function uses : ? operators (instead of for loop) to find whether the list number is smaller than or greater than 3 accordingly it prints the result.<html> <head> <script> <src = \"https://cdnjs.cloudflare.com/ajax/libs/ underscore.js/1.9.1/underscore-min.js\" > </script> <script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore-min.js.map\"></script> <script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore.js\"></script></head> <body> <script type=\"text/javascript\"> _.map( [ 0, 7, 2, -1, 8 ], function( n ) { return n>=3 ? \"greater\" : \"smaller\"; }); </script></body> </html>Output:" }, { "code": "<html> <head> <script> <src = \"https://cdnjs.cloudflare.com/ajax/libs/ underscore.js/1.9.1/underscore-min.js\" > </script> <script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore-min.js.map\"></script> <script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js /1.9.1/underscore.js\"></script></head> <body> <script type=\"text/javascript\"> _.map( [ 0, 7, 2, -1, 8 ], function( n ) { return n>=3 ? \"greater\" : \"smaller\"; }); </script></body> </html>", "e": 9304, "s": 8672, "text": null }, { "code": null, "e": 9312, "s": 9304, "text": "Output:" }, { "code": null, "e": 9323, "s": 9312, "text": "JavaScript" }, { "code": null, "e": 9421, "s": 9323, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9482, "s": 9421, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 9554, "s": 9482, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 9594, "s": 9554, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 9647, "s": 9594, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 9699, "s": 9647, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 9740, "s": 9699, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 9786, "s": 9740, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 9855, "s": 9786, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 9882, "s": 9855, "text": "File uploading in React.js" } ]
GATE | GATE-CS-2009 | Question 24
28 Jun, 2021 The binary operation c is defined as follows Which one of the following is equivalent to P∨Q? A) B) C) D) (A) A(B) B(C) C(D) DAnswer: (B)Explanation: This solution is contributed by Anil Saikrishna Devarasetty.Quiz of this Question GATE-CS-2009 GATE-GATE-CS-2009 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Jun, 2021" }, { "code": null, "e": 99, "s": 54, "text": "The binary operation c is defined as follows" }, { "code": null, "e": 148, "s": 99, "text": "Which one of the following is equivalent to P∨Q?" }, { "code": null, "e": 167, "s": 148, "text": "A) \n\nB) \n\nC) \n\nD) " }, { "code": null, "e": 213, "s": 167, "text": "(A) A(B) B(C) C(D) DAnswer: (B)Explanation: " }, { "code": null, "e": 297, "s": 215, "text": "This solution is contributed by Anil Saikrishna Devarasetty.Quiz of this Question" }, { "code": null, "e": 310, "s": 297, "text": "GATE-CS-2009" }, { "code": null, "e": 328, "s": 310, "text": "GATE-GATE-CS-2009" }, { "code": null, "e": 333, "s": 328, "text": "GATE" } ]
Python | Removing unwanted characters from string
30 Jun, 2022 The generic problem faced by the programmers is removing a character from the entire string. But sometimes the requirement is way above and demands the removal of more than 1 character, but a list of such malicious characters. These can be in the form of special characters for reconstructing valid passwords and many other applications possible. Let’s discuss certain ways to perform this particular task.Method #1 : Using replace() One can use replace() inside a loop to check for a bad_char and then replace it with the empty string hence removing it. This is the most basic approach and inefficient on a performance point of view. Python3 # Python3 code to demonstrate# removal of bad_chars# using replace() # initializing bad_chars_listbad_chars = [';', ':', '!', "*", " "] # initializing test stringtest_string = "Ge;ek * s:fo ! r;Ge * e*k:s !" # printing original stringprint ("Original String : " + test_string) # using replace() to# remove bad_charsfor i in bad_chars : test_string = test_string.replace(i, '') # printing resultant stringprint ("Resultant list is : " + str(test_string)) Output : Original String : Ge;ek*s:fo!r;Ge*e*k:s! Resultant list is : GeeksforGeeks Method #2 : Using join() + generator By using join() we remake the string. In generator function, we specify the logic to ignore the characters in bad_chars and hence constructing new string free from bad characters. Python3 # Python3 code to demonstrate# removal of bad_chars# using join() + generator # initializing bad_chars_listbad_chars = [';', ':', '!', "*", " "] # initializing test stringtest_string = "Ge;ek * s:fo ! r;Ge * e*k:s !" # printing original stringprint ("Original String : " + test_string) # using join() + generator to# remove bad_charstest_string = ''.join(i for i in test_string if not i in bad_chars) # printing resultant stringprint ("Resultant list is : " + str(test_string)) Output : Original String : Ge;ek*s:fo!r;Ge*e*k:s! Resultant list is : GeeksforGeeks Method #3 : Using translate() The most elegant way to perform this particular task, this method is basically used for achieving the solution to these kind of problems itself, we can translate each bad_char to empty string and get filtered string. Python3 # Python3 code to demonstrate# removal of bad_chars# using translate()import string# initializing bad_chars_listbad_chars = [';', ':', '!', "*"] # initializing test stringtest_string = "Ge;ek * s:fo ! r;Ge * e*k:s !" # printing original stringprint ("Original String : " + test_string) # using translate() to# remove bad_charsdelete_dict = {sp_character: '' for sp_character in string.punctuation}delete_dict[' '] = ''table = str.maketrans(delete_dict)test_string = test_string.translate(table) # printing resultant stringprint ("Resultant list is : " + str(test_string)) Output : Original String : Ge;ek*s:fo!r;Ge*e*k:s! Resultant list is : GeeksforGeeks Method #4 : Using filter() This is yet another solution to perform this task. Using the lambda function, filter function can remove all the bad_chars and return the wanted refined string. Python3 # Python3 code to demonstrate# removal of bad_chars# using filter() # initializing bad_chars_listbad_chars = [';', ':', '!', "*"] # initializing test stringtest_string = "Ge;ek*s:fo!r;Ge*e*k:s!" # printing original stringprint("Original String : " + test_string) # using filter() to# remove bad_charstest_string = ''.join((filter(lambda i: i not in bad_chars, test_string)))# printing resultant stringprint("Resultant list is : " + str(test_string)) Output : Original String : Ge;ek*s:fo!r;Ge*e*k:s! Resultant list is : GeeksforGeeks Method#5: Using re.sub() function: Regular expression are used to identify the bad character in string and re.sub function is used to replace the bad_char from the string. Python3 # Python3 code to demonstrate# removal of bad character# Using re.sub()import re # initializing stringtest_str = "Ge;ek * s:fo ! r;Ge * e*k:s !" # Bad character listbad_char = [";", "!", "*", ":", " "] # printing original stringprint("The original string is : " + test_str) # using re.sub()# remove bad_char from stringtemp = ''for i in bad_char: temp+= i;res = re.sub(rf'[{temp}]', '', test_str) # printing resultprint("The strings after extra space removal : " + str(res)) The original string is : Ge;ek * s:fo ! r;Ge * e*k:s ! The strings after extra space removal : GeeksforGeeks sagarjha tester12345678 satyam00so sagartomar9927 Python list-programs Python string-programs python-list python-string Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jun, 2022" }, { "code": null, "e": 688, "s": 52, "text": "The generic problem faced by the programmers is removing a character from the entire string. But sometimes the requirement is way above and demands the removal of more than 1 character, but a list of such malicious characters. These can be in the form of special characters for reconstructing valid passwords and many other applications possible. Let’s discuss certain ways to perform this particular task.Method #1 : Using replace() One can use replace() inside a loop to check for a bad_char and then replace it with the empty string hence removing it. This is the most basic approach and inefficient on a performance point of view. " }, { "code": null, "e": 696, "s": 688, "text": "Python3" }, { "code": "# Python3 code to demonstrate# removal of bad_chars# using replace() # initializing bad_chars_listbad_chars = [';', ':', '!', \"*\", \" \"] # initializing test stringtest_string = \"Ge;ek * s:fo ! r;Ge * e*k:s !\" # printing original stringprint (\"Original String : \" + test_string) # using replace() to# remove bad_charsfor i in bad_chars : test_string = test_string.replace(i, '') # printing resultant stringprint (\"Resultant list is : \" + str(test_string))", "e": 1153, "s": 696, "text": null }, { "code": null, "e": 1164, "s": 1153, "text": "Output : " }, { "code": null, "e": 1239, "s": 1164, "text": "Original String : Ge;ek*s:fo!r;Ge*e*k:s!\nResultant list is : GeeksforGeeks" }, { "code": null, "e": 1457, "s": 1239, "text": "Method #2 : Using join() + generator By using join() we remake the string. In generator function, we specify the logic to ignore the characters in bad_chars and hence constructing new string free from bad characters. " }, { "code": null, "e": 1465, "s": 1457, "text": "Python3" }, { "code": "# Python3 code to demonstrate# removal of bad_chars# using join() + generator # initializing bad_chars_listbad_chars = [';', ':', '!', \"*\", \" \"] # initializing test stringtest_string = \"Ge;ek * s:fo ! r;Ge * e*k:s !\" # printing original stringprint (\"Original String : \" + test_string) # using join() + generator to# remove bad_charstest_string = ''.join(i for i in test_string if not i in bad_chars) # printing resultant stringprint (\"Resultant list is : \" + str(test_string))", "e": 1943, "s": 1465, "text": null }, { "code": null, "e": 1954, "s": 1943, "text": "Output : " }, { "code": null, "e": 2029, "s": 1954, "text": "Original String : Ge;ek*s:fo!r;Ge*e*k:s!\nResultant list is : GeeksforGeeks" }, { "code": null, "e": 2277, "s": 2029, "text": "Method #3 : Using translate() The most elegant way to perform this particular task, this method is basically used for achieving the solution to these kind of problems itself, we can translate each bad_char to empty string and get filtered string. " }, { "code": null, "e": 2285, "s": 2277, "text": "Python3" }, { "code": "# Python3 code to demonstrate# removal of bad_chars# using translate()import string# initializing bad_chars_listbad_chars = [';', ':', '!', \"*\"] # initializing test stringtest_string = \"Ge;ek * s:fo ! r;Ge * e*k:s !\" # printing original stringprint (\"Original String : \" + test_string) # using translate() to# remove bad_charsdelete_dict = {sp_character: '' for sp_character in string.punctuation}delete_dict[' '] = ''table = str.maketrans(delete_dict)test_string = test_string.translate(table) # printing resultant stringprint (\"Resultant list is : \" + str(test_string))", "e": 2857, "s": 2285, "text": null }, { "code": null, "e": 2868, "s": 2857, "text": "Output : " }, { "code": null, "e": 2943, "s": 2868, "text": "Original String : Ge;ek*s:fo!r;Ge*e*k:s!\nResultant list is : GeeksforGeeks" }, { "code": null, "e": 3132, "s": 2943, "text": "Method #4 : Using filter() This is yet another solution to perform this task. Using the lambda function, filter function can remove all the bad_chars and return the wanted refined string. " }, { "code": null, "e": 3140, "s": 3132, "text": "Python3" }, { "code": "# Python3 code to demonstrate# removal of bad_chars# using filter() # initializing bad_chars_listbad_chars = [';', ':', '!', \"*\"] # initializing test stringtest_string = \"Ge;ek*s:fo!r;Ge*e*k:s!\" # printing original stringprint(\"Original String : \" + test_string) # using filter() to# remove bad_charstest_string = ''.join((filter(lambda i: i not in bad_chars, test_string)))# printing resultant stringprint(\"Resultant list is : \" + str(test_string))", "e": 3590, "s": 3140, "text": null }, { "code": null, "e": 3601, "s": 3590, "text": "Output : " }, { "code": null, "e": 3676, "s": 3601, "text": "Original String : Ge;ek*s:fo!r;Ge*e*k:s!\nResultant list is : GeeksforGeeks" }, { "code": null, "e": 3849, "s": 3676, "text": "Method#5: Using re.sub() function: Regular expression are used to identify the bad character in string and re.sub function is used to replace the bad_char from the string. " }, { "code": null, "e": 3857, "s": 3849, "text": "Python3" }, { "code": "# Python3 code to demonstrate# removal of bad character# Using re.sub()import re # initializing stringtest_str = \"Ge;ek * s:fo ! r;Ge * e*k:s !\" # Bad character listbad_char = [\";\", \"!\", \"*\", \":\", \" \"] # printing original stringprint(\"The original string is : \" + test_str) # using re.sub()# remove bad_char from stringtemp = ''for i in bad_char: temp+= i;res = re.sub(rf'[{temp}]', '', test_str) # printing resultprint(\"The strings after extra space removal : \" + str(res))", "e": 4335, "s": 3857, "text": null }, { "code": null, "e": 4444, "s": 4335, "text": "The original string is : Ge;ek * s:fo ! r;Ge * e*k:s !\nThe strings after extra space removal : GeeksforGeeks" }, { "code": null, "e": 4453, "s": 4444, "text": "sagarjha" }, { "code": null, "e": 4468, "s": 4453, "text": "tester12345678" }, { "code": null, "e": 4479, "s": 4468, "text": "satyam00so" }, { "code": null, "e": 4494, "s": 4479, "text": "sagartomar9927" }, { "code": null, "e": 4515, "s": 4494, "text": "Python list-programs" }, { "code": null, "e": 4538, "s": 4515, "text": "Python string-programs" }, { "code": null, "e": 4550, "s": 4538, "text": "python-list" }, { "code": null, "e": 4564, "s": 4550, "text": "python-string" }, { "code": null, "e": 4571, "s": 4564, "text": "Python" }, { "code": null, "e": 4583, "s": 4571, "text": "python-list" } ]
How to Create Database & Collection in MongoDB?
05 Feb, 2021 MongoDB stores data records as documents that are stored together in collections and the database stores one or more collections of documents. Document: A document is a basic unit of storing data into the database. A single record of a collection is also known as a document. Basically, It is a structure that compromises key & value pairs which is similar to the JSON objects. Documents have a great ability to store complex data. For example: Here, the name, country, age and status are fields, and gfg, India, 21, A are their values. Collection: It is used to store a varied number of documents inside the database. As MongoDB is a Schema-free database, it can store the documents that are not the same in structure. Also, there is no need to define the columns and their datatype. Database: The MongoDB database is a container for collections and it can store one or more collections. It is not necessary to create a database before you work on it. The show dbs command gives the list of all the databases. In MongoDB, we can create a database using the use command. As shown in the below image use gfgDB Here, we have created a database named as “gfgDB”. If the database doesn’t exist, MongoDB will create the database when you store any data to it. Using this command we can also switch from on database to another. In MongoDB, we can view all the existing database using the following command: show dbs This command returns a list of all the existing databases. In MongoDB, a new collection is created when we add one or more documents to it. We can insert documents in the collection using the following methods: Inserting only one document in the collection db.myNewCollection1.insertOne( { name:"geeksforgeeks" } ) Here, we create a collection named as myNewCollection1 by inserting a document that contains a name field with its value in it using insertOne() method. Inserting many documents in the collection db.myNewCollection2.insertMany([{name:"gfg", country:"India"}, {name:"rahul", age:20}]) Here, we create a collection named as myNewCollection2 by inserting two documents using insertMany() method. In MongoDB, we can view all the existing collection in the database using the following command: show collections This command returns a list of all the existing collections in the gfgDB database. MongoDB Picked MongoDB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to connect MongoDB with ReactJS ? MongoDB - limit() Method MongoDB - sort() Method MongoDB - FindOne() Method MongoDB updateOne() Method - db.Collection.updateOne() MongoDB - Regex MongoDB Cursor MongoDB - Compound Indexes MongoDB updateMany() Method - db.Collection.updateMany() Mongoose | update() Function
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Feb, 2021" }, { "code": null, "e": 197, "s": 54, "text": "MongoDB stores data records as documents that are stored together in collections and the database stores one or more collections of documents." }, { "code": null, "e": 499, "s": 197, "text": "Document: A document is a basic unit of storing data into the database. A single record of a collection is also known as a document. Basically, It is a structure that compromises key & value pairs which is similar to the JSON objects. Documents have a great ability to store complex data. For example:" }, { "code": null, "e": 591, "s": 499, "text": "Here, the name, country, age and status are fields, and gfg, India, 21, A are their values." }, { "code": null, "e": 840, "s": 591, "text": "Collection: It is used to store a varied number of documents inside the database. As MongoDB is a Schema-free database, it can store the documents that are not the same in structure. Also, there is no need to define the columns and their datatype. " }, { "code": null, "e": 1067, "s": 840, "text": "Database: The MongoDB database is a container for collections and it can store one or more collections. It is not necessary to create a database before you work on it. The show dbs command gives the list of all the databases. " }, { "code": null, "e": 1155, "s": 1067, "text": "In MongoDB, we can create a database using the use command. As shown in the below image" }, { "code": null, "e": 1165, "s": 1155, "text": "use gfgDB" }, { "code": null, "e": 1378, "s": 1165, "text": "Here, we have created a database named as “gfgDB”. If the database doesn’t exist, MongoDB will create the database when you store any data to it. Using this command we can also switch from on database to another." }, { "code": null, "e": 1457, "s": 1378, "text": "In MongoDB, we can view all the existing database using the following command:" }, { "code": null, "e": 1466, "s": 1457, "text": "show dbs" }, { "code": null, "e": 1525, "s": 1466, "text": "This command returns a list of all the existing databases." }, { "code": null, "e": 1677, "s": 1525, "text": "In MongoDB, a new collection is created when we add one or more documents to it. We can insert documents in the collection using the following methods:" }, { "code": null, "e": 1723, "s": 1677, "text": "Inserting only one document in the collection" }, { "code": null, "e": 1781, "s": 1723, "text": "db.myNewCollection1.insertOne( { name:\"geeksforgeeks\" } )" }, { "code": null, "e": 1934, "s": 1781, "text": "Here, we create a collection named as myNewCollection1 by inserting a document that contains a name field with its value in it using insertOne() method." }, { "code": null, "e": 1977, "s": 1934, "text": "Inserting many documents in the collection" }, { "code": null, "e": 2097, "s": 1977, "text": "db.myNewCollection2.insertMany([{name:\"gfg\", country:\"India\"},\n {name:\"rahul\", age:20}])" }, { "code": null, "e": 2206, "s": 2097, "text": "Here, we create a collection named as myNewCollection2 by inserting two documents using insertMany() method." }, { "code": null, "e": 2303, "s": 2206, "text": "In MongoDB, we can view all the existing collection in the database using the following command:" }, { "code": null, "e": 2320, "s": 2303, "text": "show collections" }, { "code": null, "e": 2403, "s": 2320, "text": "This command returns a list of all the existing collections in the gfgDB database." }, { "code": null, "e": 2411, "s": 2403, "text": "MongoDB" }, { "code": null, "e": 2418, "s": 2411, "text": "Picked" }, { "code": null, "e": 2426, "s": 2418, "text": "MongoDB" }, { "code": null, "e": 2524, "s": 2426, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2562, "s": 2524, "text": "How to connect MongoDB with ReactJS ?" }, { "code": null, "e": 2587, "s": 2562, "text": "MongoDB - limit() Method" }, { "code": null, "e": 2611, "s": 2587, "text": "MongoDB - sort() Method" }, { "code": null, "e": 2638, "s": 2611, "text": "MongoDB - FindOne() Method" }, { "code": null, "e": 2693, "s": 2638, "text": "MongoDB updateOne() Method - db.Collection.updateOne()" }, { "code": null, "e": 2709, "s": 2693, "text": "MongoDB - Regex" }, { "code": null, "e": 2724, "s": 2709, "text": "MongoDB Cursor" }, { "code": null, "e": 2751, "s": 2724, "text": "MongoDB - Compound Indexes" }, { "code": null, "e": 2808, "s": 2751, "text": "MongoDB updateMany() Method - db.Collection.updateMany()" } ]
Print Common Nodes in Two Binary Search Trees
05 Aug, 2021 Given two Binary Search Trees, find common nodes in them. In other words, find intersection of two BSTs. Example: Method 1 (Simple Solution) A simple way is to one by once search every node of first tree in second tree. Time complexity of this solution is O(m * h) where m is number of nodes in first tree and h is height of second tree. Method 2: Approach – If we think of another problem in which we are given two sorted arrays and we have to find the intersection between them, we can do it easily using two pointer technique. Now we can easily convert this problem into above. We know that if we store the inorder traversal of a BST in an array, that array will be sorted in ascending order. So what we can do is simply take the inorder traversal of both the trees and store them in two separate arrays and then find intersection between two arrays. Algorithm –1) Do inorder traversal of first tree and store the traversal in an auxiliary array ar1[]. See sortedInorder() here.2) Do inorder traversal of second tree and store the traversal in an auxiliary array ar2[]3) Find intersection of ar1[] and ar2[]. See this for details. Complexity Analysis:Time Complexity: O(m+n).Here ‘m’ and ‘n’ are number of nodes in first and second tree respectively,as we need to traverse both the trees.Auxiliary Space :No use of any data structure for storing values-: O(m+n)The reason is that we need two separate arrays for storing inorder traversals of both the trees. Time Complexity: O(m+n).Here ‘m’ and ‘n’ are number of nodes in first and second tree respectively,as we need to traverse both the trees. Auxiliary Space :No use of any data structure for storing values-: O(m+n)The reason is that we need two separate arrays for storing inorder traversals of both the trees. Method 3 (Linear Time and limited Extra Space)The idea is to use iterative inorder traversal Approach:The idea here is to optimize the space. In the above approach we store all the elements of the tree and then compare but the question is it really necessary to store all the elements. What one can do is store a particular branch of the tree (worst case ‘Height of the tree’) and then start comparing. We can take two stacks and store inorder traversal of trees in respective stacks but the maximum number of elements should be equal to that particular branch of the tree. As soon as that branch ends we start popping and comparing the elements of the stack. Now if top(stack-1)<top(stack-2) there can be more elements in the right branch of top(stack-1) which are greater than it and can be equal to top(stack-2). So we insert right branch of top(stack-1) till it is equal to NULL. At the end of each such insertion we have three conditions to check and then we do the insertions in the stack accordingly.if top(stack-1)<top(stack-2) root1=root1->right (then do insertions) if top(stack-1)>top(stack-2) root2=root2->right (then do insertions) else It's a match if top(stack-1)<top(stack-2) root1=root1->right (then do insertions) if top(stack-1)>top(stack-2) root2=root2->right (then do insertions) else It's a match C++ Java Python3 C# // C++ program of iterative traversal based method to// find common elements in two BSTs.#include<iostream>#include<stack>using namespace std; // A BST nodestruct Node{ int key; struct Node *left, *right;}; // A utility function to create a new nodeNode *newNode(int ele){ Node *temp = new Node; temp->key = ele; temp->left = temp->right = NULL; return temp;} // Function two print common elements in given two treesvoid printCommon(Node *root1, Node *root2){ // Create two stacks for two inorder traversals stack<Node *> stack1, s1, s2; while (1) { // push the Nodes of first tree in stack s1 if (root1) { s1.push(root1); root1 = root1->left; } // push the Nodes of second tree in stack s2 else if (root2) { s2.push(root2); root2 = root2->left; } // Both root1 and root2 are NULL here else if (!s1.empty() && !s2.empty()) { root1 = s1.top(); root2 = s2.top(); // If current keys in two trees are same if (root1->key == root2->key) { cout << root1->key << " "; s1.pop(); s2.pop(); // move to the inorder successor root1 = root1->right; root2 = root2->right; } else if (root1->key < root2->key) { // If Node of first tree is smaller, than that of // second tree, then its obvious that the inorder // successors of current Node can have same value // as that of the second tree Node. Thus, we pop // from s2 s1.pop(); root1 = root1->right; // root2 is set to NULL, because we need // new Nodes of tree 1 root2 = NULL; } else if (root1->key > root2->key) { s2.pop(); root2 = root2->right; root1 = NULL; } } // Both roots and both stacks are empty else break; }} // A utility function to do inorder traversalvoid inorder(struct Node *root){ if (root) { inorder(root->left); cout<<root->key<<" "; inorder(root->right); }} /* A utility function to insert a new Node with given key in BST */struct Node* insert(struct Node* node, int key){ /* If the tree is empty, return a new Node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); /* return the (unchanged) Node pointer */ return node;} // Driver programint main(){ // Create first tree as shown in example Node *root1 = NULL; root1 = insert(root1, 5); root1 = insert(root1, 1); root1 = insert(root1, 10); root1 = insert(root1, 0); root1 = insert(root1, 4); root1 = insert(root1, 7); root1 = insert(root1, 9); // Create second tree as shown in example Node *root2 = NULL; root2 = insert(root2, 10); root2 = insert(root2, 7); root2 = insert(root2, 20); root2 = insert(root2, 4); root2 = insert(root2, 9); cout << "Tree 1 : "; inorder(root1); cout << endl; cout << "Tree 2 : "; inorder(root2); cout << "\nCommon Nodes: "; printCommon(root1, root2); return 0;} // Java program of iterative traversal based method to // find common elements in two BSTs.import java.util.*;class GfG { // A BST node static class Node { int key; Node left, right; } // A utility function to create a new node static Node newNode(int ele) { Node temp = new Node(); temp.key = ele; temp.left = null; temp.right = null; return temp; } // Function two print common elements in given two trees static void printCommon(Node root1, Node root2) { Stack<Node> s1 = new Stack<Node> (); Stack<Node> s2 = new Stack<Node> (); while (true) { // push the Nodes of first tree in stack s1 if (root1 != null) { s1.push(root1); root1 = root1.left; } // push the Nodes of second tree in stack s2 else if (root2 != null) { s2.push(root2); root2 = root2.left; } // Both root1 and root2 are NULL here else if (!s1.isEmpty() && !s2.isEmpty()) { root1 = s1.peek(); root2 = s2.peek(); // If current keys in two trees are same if (root1.key == root2.key) { System.out.print(root1.key + " "); s1.pop(); s2.pop(); // move to the inorder successor root1 = root1.right; root2 = root2.right; } else if (root1.key < root2.key) { // If Node of first tree is smaller, than that of // second tree, then its obvious that the inorder // successors of current Node can have same value // as that of the second tree Node. Thus, we pop // from s2 s1.pop(); root1 = root1.right; // root2 is set to NULL, because we need // new Nodes of tree 1 root2 = null; } else if (root1.key > root2.key) { s2.pop(); root2 = root2.right; root1 = null; } } // Both roots and both stacks are empty else break; } } // A utility function to do inorder traversal static void inorder(Node root) { if (root != null) { inorder(root.left); System.out.print(root.key + " "); inorder(root.right); } } /* A utility function to insert a new Node with given key in BST */static Node insert(Node node, int key) { /* If the tree is empty, return a new Node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); /* return the (unchanged) Node pointer */ return node; } // Driver program public static void main(String[] args) { // Create first tree as shown in example Node root1 = null; root1 = insert(root1, 5); root1 = insert(root1, 1); root1 = insert(root1, 10); root1 = insert(root1, 0); root1 = insert(root1, 4); root1 = insert(root1, 7); root1 = insert(root1, 9); // Create second tree as shown in example Node root2 = null; root2 = insert(root2, 10); root2 = insert(root2, 7); root2 = insert(root2, 20); root2 = insert(root2, 4); root2 = insert(root2, 9); System.out.print("Tree 1 : " + "\n"); inorder(root1); System.out.println(); System.out.print("Tree 2 : " + "\n"); inorder(root2); System.out.println(); System.out.println("Common Nodes: "); printCommon(root1, root2); }} # Python3 program of iterative traversal based # method to find common elements in two BSTs. # A utility function to create a new node class newNode: def __init__(self, key): self.key = key self.left = self.right = None # Function two print common elements # in given two trees def printCommon(root1, root2): # Create two stacks for two inorder # traversals s1 = [] s2 = [] while 1: # append the Nodes of first # tree in stack s1 if root1: s1.append(root1) root1 = root1.left # append the Nodes of second tree # in stack s2 elif root2: s2.append(root2) root2 = root2.left # Both root1 and root2 are NULL here elif len(s1) != 0 and len(s2) != 0: root1 = s1[-1] root2 = s2[-1] # If current keys in two trees are same if root1.key == root2.key: print(root1.key, end = " ") s1.pop(-1) s2.pop(-1) # move to the inorder successor root1 = root1.right root2 = root2.right elif root1.key < root2.key: # If Node of first tree is smaller, than # that of second tree, then its obvious # that the inorder successors of current # Node can have same value as that of the # second tree Node. Thus, we pop from s2 s1.pop(-1) root1 = root1.right # root2 is set to NULL, because we need # new Nodes of tree 1 root2 = None elif root1.key > root2.key: s2.pop(-1) root2 = root2.right root1 = None # Both roots and both stacks are empty else: break # A utility function to do inorder traversal def inorder(root): if root: inorder(root.left) print(root.key, end = " ") inorder(root.right) # A utility function to insert a new Node# with given key in BST def insert(node, key): # If the tree is empty, return a new Node if node == None: return newNode(key) # Otherwise, recur down the tree if key < node.key: node.left = insert(node.left, key) elif key > node.key: node.right = insert(node.right, key) # return the (unchanged) Node pointer return node # Driver Code if __name__ == '__main__': # Create first tree as shown in example root1 = None root1 = insert(root1, 5) root1 = insert(root1, 1) root1 = insert(root1, 10) root1 = insert(root1, 0) root1 = insert(root1, 4) root1 = insert(root1, 7) root1 = insert(root1, 9) # Create second tree as shown in example root2 = None root2 = insert(root2, 10) root2 = insert(root2, 7) root2 = insert(root2, 20) root2 = insert(root2, 4) root2 = insert(root2, 9) print("Tree 1 : ") inorder(root1) print() print("Tree 2 : ") inorder(root2) print() print("Common Nodes: ") printCommon(root1, root2) # This code is contributed by PranchalK using System;using System.Collections.Generic; // C# program of iterative traversal based method to // find common elements in two BSTs. public class GfG{ // A BST node public class Node{ public int key; public Node left, right;} // A utility function to create a new node public static Node newNode(int ele){ Node temp = new Node(); temp.key = ele; temp.left = null; temp.right = null; return temp;} // Function two print common elements in given two trees public static void printCommon(Node root1, Node root2){ Stack<Node> s1 = new Stack<Node> (); Stack<Node> s2 = new Stack<Node> (); while (true) { // push the Nodes of first tree in stack s1 if (root1 != null) { s1.Push(root1); root1 = root1.left; } // push the Nodes of second tree in stack s2 else if (root2 != null) { s2.Push(root2); root2 = root2.left; } // Both root1 and root2 are NULL here else if (s1.Count > 0 && s2.Count > 0) { root1 = s1.Peek(); root2 = s2.Peek(); // If current keys in two trees are same if (root1.key == root2.key) { Console.Write(root1.key + " "); s1.Pop(); s2.Pop(); // move to the inorder successor root1 = root1.right; root2 = root2.right; } else if (root1.key < root2.key) { // If Node of first tree is smaller, than that of // second tree, then its obvious that the inorder // successors of current Node can have same value // as that of the second tree Node. Thus, we pop // from s2 s1.Pop(); root1 = root1.right; // root2 is set to NULL, because we need // new Nodes of tree 1 root2 = null; } else if (root1.key > root2.key) { s2.Pop(); root2 = root2.right; root1 = null; } } // Both roots and both stacks are empty else { break; } }} // A utility function to do inorder traversal public static void inorder(Node root){ if (root != null) { inorder(root.left); Console.Write(root.key + " "); inorder(root.right); }} /* A utility function to insert a new Node with given key in BST */public static Node insert(Node node, int key){ /* If the tree is empty, return a new Node */ if (node == null) { return newNode(key); } /* Otherwise, recur down the tree */ if (key < node.key) { node.left = insert(node.left, key); } else if (key > node.key) { node.right = insert(node.right, key); } /* return the (unchanged) Node pointer */ return node;} // Driver program public static void Main(string[] args){ // Create first tree as shown in example Node root1 = null; root1 = insert(root1, 5); root1 = insert(root1, 1); root1 = insert(root1, 10); root1 = insert(root1, 0); root1 = insert(root1, 4); root1 = insert(root1, 7); root1 = insert(root1, 9); // Create second tree as shown in example Node root2 = null; root2 = insert(root2, 10); root2 = insert(root2, 7); root2 = insert(root2, 20); root2 = insert(root2, 4); root2 = insert(root2, 9); Console.Write("Tree 1 : " + "\n"); inorder(root1); Console.WriteLine(); Console.Write("Tree 2 : " + "\n"); inorder(root2); Console.WriteLine(); Console.Write("Common Nodes: " + "\n"); printCommon(root1, root2); }} // This code is contributed by Shrikant13 4 7 9 10 Complexity Analysis:Time Complexity: O(n+m).Here ‘m’ and ‘n’ are number of nodes in first and second tree respectively,as we need to traverse both the trees.Auxiliary Space :Use of stack for storing values, at-most elements = ‘Height of tree’: O(h1+h2) Time Complexity: O(n+m).Here ‘m’ and ‘n’ are number of nodes in first and second tree respectively,as we need to traverse both the trees. Auxiliary Space :Use of stack for storing values, at-most elements = ‘Height of tree’: O(h1+h2) This article is contributed by Ekta Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. prerna saini shrikanth13 PranchalKatiyar Suvo bidibaaz123 sagar0719kumar sumitgumber28 Amazon Binary Search Tree Tree Amazon Binary Search Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Aug, 2021" }, { "code": null, "e": 157, "s": 52, "text": "Given two Binary Search Trees, find common nodes in them. In other words, find intersection of two BSTs." }, { "code": null, "e": 166, "s": 157, "text": "Example:" }, { "code": null, "e": 390, "s": 166, "text": "Method 1 (Simple Solution) A simple way is to one by once search every node of first tree in second tree. Time complexity of this solution is O(m * h) where m is number of nodes in first tree and h is height of second tree." }, { "code": null, "e": 400, "s": 390, "text": "Method 2:" }, { "code": null, "e": 906, "s": 400, "text": "Approach – If we think of another problem in which we are given two sorted arrays and we have to find the intersection between them, we can do it easily using two pointer technique. Now we can easily convert this problem into above. We know that if we store the inorder traversal of a BST in an array, that array will be sorted in ascending order. So what we can do is simply take the inorder traversal of both the trees and store them in two separate arrays and then find intersection between two arrays." }, { "code": null, "e": 1186, "s": 906, "text": "Algorithm –1) Do inorder traversal of first tree and store the traversal in an auxiliary array ar1[]. See sortedInorder() here.2) Do inorder traversal of second tree and store the traversal in an auxiliary array ar2[]3) Find intersection of ar1[] and ar2[]. See this for details." }, { "code": null, "e": 1513, "s": 1186, "text": "Complexity Analysis:Time Complexity: O(m+n).Here ‘m’ and ‘n’ are number of nodes in first and second tree respectively,as we need to traverse both the trees.Auxiliary Space :No use of any data structure for storing values-: O(m+n)The reason is that we need two separate arrays for storing inorder traversals of both the trees." }, { "code": null, "e": 1651, "s": 1513, "text": "Time Complexity: O(m+n).Here ‘m’ and ‘n’ are number of nodes in first and second tree respectively,as we need to traverse both the trees." }, { "code": null, "e": 1821, "s": 1651, "text": "Auxiliary Space :No use of any data structure for storing values-: O(m+n)The reason is that we need two separate arrays for storing inorder traversals of both the trees." }, { "code": null, "e": 1914, "s": 1821, "text": "Method 3 (Linear Time and limited Extra Space)The idea is to use iterative inorder traversal" }, { "code": null, "e": 2987, "s": 1914, "text": "Approach:The idea here is to optimize the space. In the above approach we store all the elements of the tree and then compare but the question is it really necessary to store all the elements. What one can do is store a particular branch of the tree (worst case ‘Height of the tree’) and then start comparing. We can take two stacks and store inorder traversal of trees in respective stacks but the maximum number of elements should be equal to that particular branch of the tree. As soon as that branch ends we start popping and comparing the elements of the stack. Now if top(stack-1)<top(stack-2) there can be more elements in the right branch of top(stack-1) which are greater than it and can be equal to top(stack-2). So we insert right branch of top(stack-1) till it is equal to NULL. At the end of each such insertion we have three conditions to check and then we do the insertions in the stack accordingly.if top(stack-1)<top(stack-2)\nroot1=root1->right (then do insertions)\n\nif top(stack-1)>top(stack-2)\nroot2=root2->right (then do insertions)\n\nelse\nIt's a match\n" }, { "code": null, "e": 3146, "s": 2987, "text": "if top(stack-1)<top(stack-2)\nroot1=root1->right (then do insertions)\n\nif top(stack-1)>top(stack-2)\nroot2=root2->right (then do insertions)\n\nelse\nIt's a match\n" }, { "code": null, "e": 3150, "s": 3146, "text": "C++" }, { "code": null, "e": 3155, "s": 3150, "text": "Java" }, { "code": null, "e": 3163, "s": 3155, "text": "Python3" }, { "code": null, "e": 3166, "s": 3163, "text": "C#" }, { "code": "// C++ program of iterative traversal based method to// find common elements in two BSTs.#include<iostream>#include<stack>using namespace std; // A BST nodestruct Node{ int key; struct Node *left, *right;}; // A utility function to create a new nodeNode *newNode(int ele){ Node *temp = new Node; temp->key = ele; temp->left = temp->right = NULL; return temp;} // Function two print common elements in given two treesvoid printCommon(Node *root1, Node *root2){ // Create two stacks for two inorder traversals stack<Node *> stack1, s1, s2; while (1) { // push the Nodes of first tree in stack s1 if (root1) { s1.push(root1); root1 = root1->left; } // push the Nodes of second tree in stack s2 else if (root2) { s2.push(root2); root2 = root2->left; } // Both root1 and root2 are NULL here else if (!s1.empty() && !s2.empty()) { root1 = s1.top(); root2 = s2.top(); // If current keys in two trees are same if (root1->key == root2->key) { cout << root1->key << \" \"; s1.pop(); s2.pop(); // move to the inorder successor root1 = root1->right; root2 = root2->right; } else if (root1->key < root2->key) { // If Node of first tree is smaller, than that of // second tree, then its obvious that the inorder // successors of current Node can have same value // as that of the second tree Node. Thus, we pop // from s2 s1.pop(); root1 = root1->right; // root2 is set to NULL, because we need // new Nodes of tree 1 root2 = NULL; } else if (root1->key > root2->key) { s2.pop(); root2 = root2->right; root1 = NULL; } } // Both roots and both stacks are empty else break; }} // A utility function to do inorder traversalvoid inorder(struct Node *root){ if (root) { inorder(root->left); cout<<root->key<<\" \"; inorder(root->right); }} /* A utility function to insert a new Node with given key in BST */struct Node* insert(struct Node* node, int key){ /* If the tree is empty, return a new Node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); /* return the (unchanged) Node pointer */ return node;} // Driver programint main(){ // Create first tree as shown in example Node *root1 = NULL; root1 = insert(root1, 5); root1 = insert(root1, 1); root1 = insert(root1, 10); root1 = insert(root1, 0); root1 = insert(root1, 4); root1 = insert(root1, 7); root1 = insert(root1, 9); // Create second tree as shown in example Node *root2 = NULL; root2 = insert(root2, 10); root2 = insert(root2, 7); root2 = insert(root2, 20); root2 = insert(root2, 4); root2 = insert(root2, 9); cout << \"Tree 1 : \"; inorder(root1); cout << endl; cout << \"Tree 2 : \"; inorder(root2); cout << \"\\nCommon Nodes: \"; printCommon(root1, root2); return 0;}", "e": 6694, "s": 3166, "text": null }, { "code": "// Java program of iterative traversal based method to // find common elements in two BSTs.import java.util.*;class GfG { // A BST node static class Node { int key; Node left, right; } // A utility function to create a new node static Node newNode(int ele) { Node temp = new Node(); temp.key = ele; temp.left = null; temp.right = null; return temp; } // Function two print common elements in given two trees static void printCommon(Node root1, Node root2) { Stack<Node> s1 = new Stack<Node> (); Stack<Node> s2 = new Stack<Node> (); while (true) { // push the Nodes of first tree in stack s1 if (root1 != null) { s1.push(root1); root1 = root1.left; } // push the Nodes of second tree in stack s2 else if (root2 != null) { s2.push(root2); root2 = root2.left; } // Both root1 and root2 are NULL here else if (!s1.isEmpty() && !s2.isEmpty()) { root1 = s1.peek(); root2 = s2.peek(); // If current keys in two trees are same if (root1.key == root2.key) { System.out.print(root1.key + \" \"); s1.pop(); s2.pop(); // move to the inorder successor root1 = root1.right; root2 = root2.right; } else if (root1.key < root2.key) { // If Node of first tree is smaller, than that of // second tree, then its obvious that the inorder // successors of current Node can have same value // as that of the second tree Node. Thus, we pop // from s2 s1.pop(); root1 = root1.right; // root2 is set to NULL, because we need // new Nodes of tree 1 root2 = null; } else if (root1.key > root2.key) { s2.pop(); root2 = root2.right; root1 = null; } } // Both roots and both stacks are empty else break; } } // A utility function to do inorder traversal static void inorder(Node root) { if (root != null) { inorder(root.left); System.out.print(root.key + \" \"); inorder(root.right); } } /* A utility function to insert a new Node with given key in BST */static Node insert(Node node, int key) { /* If the tree is empty, return a new Node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); /* return the (unchanged) Node pointer */ return node; } // Driver program public static void main(String[] args) { // Create first tree as shown in example Node root1 = null; root1 = insert(root1, 5); root1 = insert(root1, 1); root1 = insert(root1, 10); root1 = insert(root1, 0); root1 = insert(root1, 4); root1 = insert(root1, 7); root1 = insert(root1, 9); // Create second tree as shown in example Node root2 = null; root2 = insert(root2, 10); root2 = insert(root2, 7); root2 = insert(root2, 20); root2 = insert(root2, 4); root2 = insert(root2, 9); System.out.print(\"Tree 1 : \" + \"\\n\"); inorder(root1); System.out.println(); System.out.print(\"Tree 2 : \" + \"\\n\"); inorder(root2); System.out.println(); System.out.println(\"Common Nodes: \"); printCommon(root1, root2); }} ", "e": 10438, "s": 6694, "text": null }, { "code": "# Python3 program of iterative traversal based # method to find common elements in two BSTs. # A utility function to create a new node class newNode: def __init__(self, key): self.key = key self.left = self.right = None # Function two print common elements # in given two trees def printCommon(root1, root2): # Create two stacks for two inorder # traversals s1 = [] s2 = [] while 1: # append the Nodes of first # tree in stack s1 if root1: s1.append(root1) root1 = root1.left # append the Nodes of second tree # in stack s2 elif root2: s2.append(root2) root2 = root2.left # Both root1 and root2 are NULL here elif len(s1) != 0 and len(s2) != 0: root1 = s1[-1] root2 = s2[-1] # If current keys in two trees are same if root1.key == root2.key: print(root1.key, end = \" \") s1.pop(-1) s2.pop(-1) # move to the inorder successor root1 = root1.right root2 = root2.right elif root1.key < root2.key: # If Node of first tree is smaller, than # that of second tree, then its obvious # that the inorder successors of current # Node can have same value as that of the # second tree Node. Thus, we pop from s2 s1.pop(-1) root1 = root1.right # root2 is set to NULL, because we need # new Nodes of tree 1 root2 = None elif root1.key > root2.key: s2.pop(-1) root2 = root2.right root1 = None # Both roots and both stacks are empty else: break # A utility function to do inorder traversal def inorder(root): if root: inorder(root.left) print(root.key, end = \" \") inorder(root.right) # A utility function to insert a new Node# with given key in BST def insert(node, key): # If the tree is empty, return a new Node if node == None: return newNode(key) # Otherwise, recur down the tree if key < node.key: node.left = insert(node.left, key) elif key > node.key: node.right = insert(node.right, key) # return the (unchanged) Node pointer return node # Driver Code if __name__ == '__main__': # Create first tree as shown in example root1 = None root1 = insert(root1, 5) root1 = insert(root1, 1) root1 = insert(root1, 10) root1 = insert(root1, 0) root1 = insert(root1, 4) root1 = insert(root1, 7) root1 = insert(root1, 9) # Create second tree as shown in example root2 = None root2 = insert(root2, 10) root2 = insert(root2, 7) root2 = insert(root2, 20) root2 = insert(root2, 4) root2 = insert(root2, 9) print(\"Tree 1 : \") inorder(root1) print() print(\"Tree 2 : \") inorder(root2) print() print(\"Common Nodes: \") printCommon(root1, root2) # This code is contributed by PranchalK", "e": 13678, "s": 10438, "text": null }, { "code": "using System;using System.Collections.Generic; // C# program of iterative traversal based method to // find common elements in two BSTs. public class GfG{ // A BST node public class Node{ public int key; public Node left, right;} // A utility function to create a new node public static Node newNode(int ele){ Node temp = new Node(); temp.key = ele; temp.left = null; temp.right = null; return temp;} // Function two print common elements in given two trees public static void printCommon(Node root1, Node root2){ Stack<Node> s1 = new Stack<Node> (); Stack<Node> s2 = new Stack<Node> (); while (true) { // push the Nodes of first tree in stack s1 if (root1 != null) { s1.Push(root1); root1 = root1.left; } // push the Nodes of second tree in stack s2 else if (root2 != null) { s2.Push(root2); root2 = root2.left; } // Both root1 and root2 are NULL here else if (s1.Count > 0 && s2.Count > 0) { root1 = s1.Peek(); root2 = s2.Peek(); // If current keys in two trees are same if (root1.key == root2.key) { Console.Write(root1.key + \" \"); s1.Pop(); s2.Pop(); // move to the inorder successor root1 = root1.right; root2 = root2.right; } else if (root1.key < root2.key) { // If Node of first tree is smaller, than that of // second tree, then its obvious that the inorder // successors of current Node can have same value // as that of the second tree Node. Thus, we pop // from s2 s1.Pop(); root1 = root1.right; // root2 is set to NULL, because we need // new Nodes of tree 1 root2 = null; } else if (root1.key > root2.key) { s2.Pop(); root2 = root2.right; root1 = null; } } // Both roots and both stacks are empty else { break; } }} // A utility function to do inorder traversal public static void inorder(Node root){ if (root != null) { inorder(root.left); Console.Write(root.key + \" \"); inorder(root.right); }} /* A utility function to insert a new Node with given key in BST */public static Node insert(Node node, int key){ /* If the tree is empty, return a new Node */ if (node == null) { return newNode(key); } /* Otherwise, recur down the tree */ if (key < node.key) { node.left = insert(node.left, key); } else if (key > node.key) { node.right = insert(node.right, key); } /* return the (unchanged) Node pointer */ return node;} // Driver program public static void Main(string[] args){ // Create first tree as shown in example Node root1 = null; root1 = insert(root1, 5); root1 = insert(root1, 1); root1 = insert(root1, 10); root1 = insert(root1, 0); root1 = insert(root1, 4); root1 = insert(root1, 7); root1 = insert(root1, 9); // Create second tree as shown in example Node root2 = null; root2 = insert(root2, 10); root2 = insert(root2, 7); root2 = insert(root2, 20); root2 = insert(root2, 4); root2 = insert(root2, 9); Console.Write(\"Tree 1 : \" + \"\\n\"); inorder(root1); Console.WriteLine(); Console.Write(\"Tree 2 : \" + \"\\n\"); inorder(root2); Console.WriteLine(); Console.Write(\"Common Nodes: \" + \"\\n\"); printCommon(root1, root2); }} // This code is contributed by Shrikant13", "e": 17499, "s": 13678, "text": null }, { "code": null, "e": 17508, "s": 17499, "text": "4 7 9 10" }, { "code": null, "e": 17761, "s": 17508, "text": "Complexity Analysis:Time Complexity: O(n+m).Here ‘m’ and ‘n’ are number of nodes in first and second tree respectively,as we need to traverse both the trees.Auxiliary Space :Use of stack for storing values, at-most elements = ‘Height of tree’: O(h1+h2)" }, { "code": null, "e": 17899, "s": 17761, "text": "Time Complexity: O(n+m).Here ‘m’ and ‘n’ are number of nodes in first and second tree respectively,as we need to traverse both the trees." }, { "code": null, "e": 17995, "s": 17899, "text": "Auxiliary Space :Use of stack for storing values, at-most elements = ‘Height of tree’: O(h1+h2)" }, { "code": null, "e": 18162, "s": 17995, "text": "This article is contributed by Ekta Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 18175, "s": 18162, "text": "prerna saini" }, { "code": null, "e": 18187, "s": 18175, "text": "shrikanth13" }, { "code": null, "e": 18203, "s": 18187, "text": "PranchalKatiyar" }, { "code": null, "e": 18208, "s": 18203, "text": "Suvo" }, { "code": null, "e": 18220, "s": 18208, "text": "bidibaaz123" }, { "code": null, "e": 18235, "s": 18220, "text": "sagar0719kumar" }, { "code": null, "e": 18249, "s": 18235, "text": "sumitgumber28" }, { "code": null, "e": 18256, "s": 18249, "text": "Amazon" }, { "code": null, "e": 18275, "s": 18256, "text": "Binary Search Tree" }, { "code": null, "e": 18280, "s": 18275, "text": "Tree" }, { "code": null, "e": 18287, "s": 18280, "text": "Amazon" }, { "code": null, "e": 18306, "s": 18287, "text": "Binary Search Tree" }, { "code": null, "e": 18311, "s": 18306, "text": "Tree" } ]
How to insert a JavaScript variable inside href attribute?
24 Jun, 2020 <a > ... </a> tags are used to create hyperlinks in HTML.One of the attributes of ‘a’ tag is ‘href’ href: Specifies the URL of the page the link goes to Example: <a href="https://www.geeksforgeeks.org/"> GeeksforGeeks </a> Methods to use Variables inside this ‘href’ attribute: Using onclick property:This method uses the ‘onclick’ property of ‘a’ tag,i.e, whenever the link (‘a’ tag) is clicked, an ‘onclick’ event is triggered.Here we will use this onclick event to generate a new URL and redirect the user to that URL.(NOTE: This URL will contain the Variable we want to use inside href attribute)Steps:First, we need to know the following terms,“location.href” -> It is the entire URL of the current page.“this” -> Refers to the ‘a’ tag that has been clicked.“this.href” -> fetches the href value from the ‘a’ tag.Once we have “this.href”, append the variable to it (Here we have used a variable named “XYZ”).Then we need to append the value to the URL.Now our URL is ready with the variable and its value appended to it.In the example below, we will append a variable named ‘XYZ’ and its value is 55.<!DOCTYPE html><html><head> <title>GeeksforGeeks</title> <script> var val = 55; </script></head> <body> Link to <a href="https://www.google.com/"onclick="location.href=this.href+'?xyz='+val;return false;"> Google</a> </body></html>Resultant Url: https://www.google.com/?xyz=55 ‘val’ is the javascript variable that stores the value that we want to pass into the URL.The URL has a variable named ‘XYZ’ that takes value = 55 from the javascript variable ‘val’. Steps:First, we need to know the following terms, “location.href” -> It is the entire URL of the current page. “this” -> Refers to the ‘a’ tag that has been clicked. “this.href” -> fetches the href value from the ‘a’ tag. Once we have “this.href”, append the variable to it (Here we have used a variable named “XYZ”).Then we need to append the value to the URL.Now our URL is ready with the variable and its value appended to it. In the example below, we will append a variable named ‘XYZ’ and its value is 55. <!DOCTYPE html><html><head> <title>GeeksforGeeks</title> <script> var val = 55; </script></head> <body> Link to <a href="https://www.google.com/"onclick="location.href=this.href+'?xyz='+val;return false;"> Google</a> </body></html> Resultant Url: https://www.google.com/?xyz=55 ‘val’ is the javascript variable that stores the value that we want to pass into the URL.The URL has a variable named ‘XYZ’ that takes value = 55 from the javascript variable ‘val’. Using document.write:document: When an HTML document is loaded into a web browser, it becomes a document object.This document object has several functions, one of them is written ().write(): Writes HTML expressions or JavaScript code to a documentIn this method, we will use this write() function to create an “a tag”.<!DOCTYPE html><html><head> <title>GeeksforGeeks</title> <script> var val = 55; </script></head> <body> Link to <script> var loc = "https://www.google.com/?xyz="+val; document.write('<a href="' + loc + '">Google</a>'); </script> </body></html>Resultant Url: https://www.google.com/?xyz=55 ‘val’ is the javascript variable that stores the value that we want to pass into the URL.The URL has a variable named ‘XYZ’ that takes value = 55 from the javascript variable val. <!DOCTYPE html><html><head> <title>GeeksforGeeks</title> <script> var val = 55; </script></head> <body> Link to <script> var loc = "https://www.google.com/?xyz="+val; document.write('<a href="' + loc + '">Google</a>'); </script> </body></html> Resultant Url: https://www.google.com/?xyz=55 ‘val’ is the javascript variable that stores the value that we want to pass into the URL.The URL has a variable named ‘XYZ’ that takes value = 55 from the javascript variable val. HTML-Attributes JavaScript-Misc Picked 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 Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Jun, 2020" }, { "code": null, "e": 154, "s": 54, "text": "<a > ... </a> tags are used to create hyperlinks in HTML.One of the attributes of ‘a’ tag is ‘href’" }, { "code": null, "e": 207, "s": 154, "text": "href: Specifies the URL of the page the link goes to" }, { "code": null, "e": 216, "s": 207, "text": "Example:" }, { "code": null, "e": 282, "s": 216, "text": "<a href=\"https://www.geeksforgeeks.org/\">\n GeeksforGeeks\n</a>\n" }, { "code": null, "e": 337, "s": 282, "text": "Methods to use Variables inside this ‘href’ attribute:" }, { "code": null, "e": 1693, "s": 337, "text": "Using onclick property:This method uses the ‘onclick’ property of ‘a’ tag,i.e, whenever the link (‘a’ tag) is clicked, an ‘onclick’ event is triggered.Here we will use this onclick event to generate a new URL and redirect the user to that URL.(NOTE: This URL will contain the Variable we want to use inside href attribute)Steps:First, we need to know the following terms,“location.href” -> It is the entire URL of the current page.“this” -> Refers to the ‘a’ tag that has been clicked.“this.href” -> fetches the href value from the ‘a’ tag.Once we have “this.href”, append the variable to it (Here we have used a variable named “XYZ”).Then we need to append the value to the URL.Now our URL is ready with the variable and its value appended to it.In the example below, we will append a variable named ‘XYZ’ and its value is 55.<!DOCTYPE html><html><head> <title>GeeksforGeeks</title> <script> var val = 55; </script></head> <body> Link to <a href=\"https://www.google.com/\"onclick=\"location.href=this.href+'?xyz='+val;return false;\"> Google</a> </body></html>Resultant Url: https://www.google.com/?xyz=55\n‘val’ is the javascript variable that stores the value that we want to pass into the URL.The URL has a variable named ‘XYZ’ that takes value = 55 from the javascript variable ‘val’." }, { "code": null, "e": 1743, "s": 1693, "text": "Steps:First, we need to know the following terms," }, { "code": null, "e": 1804, "s": 1743, "text": "“location.href” -> It is the entire URL of the current page." }, { "code": null, "e": 1859, "s": 1804, "text": "“this” -> Refers to the ‘a’ tag that has been clicked." }, { "code": null, "e": 1915, "s": 1859, "text": "“this.href” -> fetches the href value from the ‘a’ tag." }, { "code": null, "e": 2123, "s": 1915, "text": "Once we have “this.href”, append the variable to it (Here we have used a variable named “XYZ”).Then we need to append the value to the URL.Now our URL is ready with the variable and its value appended to it." }, { "code": null, "e": 2204, "s": 2123, "text": "In the example below, we will append a variable named ‘XYZ’ and its value is 55." }, { "code": "<!DOCTYPE html><html><head> <title>GeeksforGeeks</title> <script> var val = 55; </script></head> <body> Link to <a href=\"https://www.google.com/\"onclick=\"location.href=this.href+'?xyz='+val;return false;\"> Google</a> </body></html>", "e": 2506, "s": 2204, "text": null }, { "code": null, "e": 2553, "s": 2506, "text": "Resultant Url: https://www.google.com/?xyz=55\n" }, { "code": null, "e": 2735, "s": 2553, "text": "‘val’ is the javascript variable that stores the value that we want to pass into the URL.The URL has a variable named ‘XYZ’ that takes value = 55 from the javascript variable ‘val’." }, { "code": null, "e": 3605, "s": 2735, "text": "Using document.write:document: When an HTML document is loaded into a web browser, it becomes a document object.This document object has several functions, one of them is written ().write(): Writes HTML expressions or JavaScript code to a documentIn this method, we will use this write() function to create an “a tag”.<!DOCTYPE html><html><head> <title>GeeksforGeeks</title> <script> var val = 55; </script></head> <body> Link to <script> var loc = \"https://www.google.com/?xyz=\"+val; document.write('<a href=\"' + loc + '\">Google</a>'); </script> </body></html>Resultant Url: https://www.google.com/?xyz=55\n‘val’ is the javascript variable that stores the value that we want to pass into the URL.The URL has a variable named ‘XYZ’ that takes value = 55 from the javascript variable val." }, { "code": "<!DOCTYPE html><html><head> <title>GeeksforGeeks</title> <script> var val = 55; </script></head> <body> Link to <script> var loc = \"https://www.google.com/?xyz=\"+val; document.write('<a href=\"' + loc + '\">Google</a>'); </script> </body></html>", "e": 3932, "s": 3605, "text": null }, { "code": null, "e": 3979, "s": 3932, "text": "Resultant Url: https://www.google.com/?xyz=55\n" }, { "code": null, "e": 4159, "s": 3979, "text": "‘val’ is the javascript variable that stores the value that we want to pass into the URL.The URL has a variable named ‘XYZ’ that takes value = 55 from the javascript variable val." }, { "code": null, "e": 4175, "s": 4159, "text": "HTML-Attributes" }, { "code": null, "e": 4191, "s": 4175, "text": "JavaScript-Misc" }, { "code": null, "e": 4198, "s": 4191, "text": "Picked" }, { "code": null, "e": 4209, "s": 4198, "text": "JavaScript" }, { "code": null, "e": 4226, "s": 4209, "text": "Web Technologies" }, { "code": null, "e": 4324, "s": 4226, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4385, "s": 4324, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4457, "s": 4385, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 4497, "s": 4457, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 4539, "s": 4497, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 4580, "s": 4539, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 4613, "s": 4580, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4675, "s": 4613, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4736, "s": 4675, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4786, "s": 4736, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to find the index value of any element in slice of bytes in Golang?
26 Aug, 2019 In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice.In the Go slice of bytes, you can find the first index value of any specified instance in the given slice using IndexAny() function. This function returns the byte index of the first occurrence in the original slice of any of the Unicode code points in chars. If the Unicode code point from chars is not available or empty in the original slice, then this method will return -1. It is defined under the bytes package so, you have to import bytes package in your program for accessing IndexAny function. Syntax: func IndexAny(ori_slice []byte, val string) int Here, ori_slice is the original string and val is a string, whose we want to find the first index value. Let us discuss this concept with the help of the given examples: Example 1: // Go program to illustrate the concept// of the index in the slice of bytespackage main import ( "bytes" "fmt") func main() { // Creating and finding the index // of the slice of bytes // Using IndexAny function res1 := bytes.IndexAny([]byte("****Welcome to GeeksforGeeks****"), "Gjskf") res2 := bytes.IndexAny([]byte("Learning how to trim a slice of bytes"), "qoxz") res3 := bytes.IndexAny([]byte("GeeksforGeeks, Geek"), "HELLO") // Display the results fmt.Printf("\n\nFinal Value:\n") fmt.Printf("\nSlice 1: %d", res1) fmt.Printf("\nSlice 2: %d", res2) fmt.Printf("\nSlice 3: %d", res3)} Output: Final Value: Slice 1: 15 Slice 2: 10 Slice 3: -1 Example 2: // Go program to illustrate the concept// of the index in the slice of bytespackage main import ( "bytes" "fmt") func main() { // Creating and initializing // the slice of bytes // Using shorthand declaration slice_1 := []byte{'!', '!', 'G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's', '#', '#'} slice_2 := []byte{'A', 'p', 'p', 'l', 'e'} slice_3 := []byte{'%', 'g', 'e', 'e', 'k', 's', '%'} // Displaying slices fmt.Println("Original Slice:") fmt.Printf("Slice 1: %s", slice_1) fmt.Printf("\nSlice 2: %s", slice_2) fmt.Printf("\nSlice 3: %s", slice_3) // Finding the index of // the slice of bytes // Using IndexAny function res1 := bytes.IndexAny(slice_1, "eks") res2 := bytes.IndexAny(slice_2, "lqzxm") res3 := bytes.IndexAny(slice_3, "xxxxx") // Display the results fmt.Printf("\n\nLast Index:\n") fmt.Printf("\nSlice 1: %d", res1) fmt.Printf("\nSlice 2: %d", res2) fmt.Printf("\nSlice 3: %d", res3) } Output: Original Slice: Slice 1: !!GeeksforGeeks## Slice 2: Apple Slice 3: %geeks% Last Index: Slice 1: 3 Slice 2: 3 Slice 3: -1 Golang Golang-Slices Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Aug, 2019" }, { "code": null, "e": 798, "s": 28, "text": "In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice.In the Go slice of bytes, you can find the first index value of any specified instance in the given slice using IndexAny() function. This function returns the byte index of the first occurrence in the original slice of any of the Unicode code points in chars. If the Unicode code point from chars is not available or empty in the original slice, then this method will return -1. It is defined under the bytes package so, you have to import bytes package in your program for accessing IndexAny function." }, { "code": null, "e": 806, "s": 798, "text": "Syntax:" }, { "code": null, "e": 854, "s": 806, "text": "func IndexAny(ori_slice []byte, val string) int" }, { "code": null, "e": 1024, "s": 854, "text": "Here, ori_slice is the original string and val is a string, whose we want to find the first index value. Let us discuss this concept with the help of the given examples:" }, { "code": null, "e": 1035, "s": 1024, "text": "Example 1:" }, { "code": "// Go program to illustrate the concept// of the index in the slice of bytespackage main import ( \"bytes\" \"fmt\") func main() { // Creating and finding the index // of the slice of bytes // Using IndexAny function res1 := bytes.IndexAny([]byte(\"****Welcome to GeeksforGeeks****\"), \"Gjskf\") res2 := bytes.IndexAny([]byte(\"Learning how to trim a slice of bytes\"), \"qoxz\") res3 := bytes.IndexAny([]byte(\"GeeksforGeeks, Geek\"), \"HELLO\") // Display the results fmt.Printf(\"\\n\\nFinal Value:\\n\") fmt.Printf(\"\\nSlice 1: %d\", res1) fmt.Printf(\"\\nSlice 2: %d\", res2) fmt.Printf(\"\\nSlice 3: %d\", res3)}", "e": 1858, "s": 1035, "text": null }, { "code": null, "e": 1866, "s": 1858, "text": "Output:" }, { "code": null, "e": 1917, "s": 1866, "text": "Final Value:\n\nSlice 1: 15\nSlice 2: 10\nSlice 3: -1\n" }, { "code": null, "e": 1928, "s": 1917, "text": "Example 2:" }, { "code": "// Go program to illustrate the concept// of the index in the slice of bytespackage main import ( \"bytes\" \"fmt\") func main() { // Creating and initializing // the slice of bytes // Using shorthand declaration slice_1 := []byte{'!', '!', 'G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's', '#', '#'} slice_2 := []byte{'A', 'p', 'p', 'l', 'e'} slice_3 := []byte{'%', 'g', 'e', 'e', 'k', 's', '%'} // Displaying slices fmt.Println(\"Original Slice:\") fmt.Printf(\"Slice 1: %s\", slice_1) fmt.Printf(\"\\nSlice 2: %s\", slice_2) fmt.Printf(\"\\nSlice 3: %s\", slice_3) // Finding the index of // the slice of bytes // Using IndexAny function res1 := bytes.IndexAny(slice_1, \"eks\") res2 := bytes.IndexAny(slice_2, \"lqzxm\") res3 := bytes.IndexAny(slice_3, \"xxxxx\") // Display the results fmt.Printf(\"\\n\\nLast Index:\\n\") fmt.Printf(\"\\nSlice 1: %d\", res1) fmt.Printf(\"\\nSlice 2: %d\", res2) fmt.Printf(\"\\nSlice 3: %d\", res3) }", "e": 2963, "s": 1928, "text": null }, { "code": null, "e": 2971, "s": 2963, "text": "Output:" }, { "code": null, "e": 3095, "s": 2971, "text": "Original Slice:\nSlice 1: !!GeeksforGeeks##\nSlice 2: Apple\nSlice 3: %geeks%\n\nLast Index:\n\nSlice 1: 3\nSlice 2: 3\nSlice 3: -1\n" }, { "code": null, "e": 3102, "s": 3095, "text": "Golang" }, { "code": null, "e": 3116, "s": 3102, "text": "Golang-Slices" }, { "code": null, "e": 3128, "s": 3116, "text": "Go Language" } ]
How to perform grep operation on all files in a directory?
The grep command in Linux is used to filter searches in a file for a particular pattern of characters. It is one of the most used Linux utility commands to display the lines that contain the pattern that we are trying to search. Normally, the pattern that we are trying to search in the file is referred to as the regular expression. grep [options] pattern [files] While there are plenty of different options available to us, some of the most used are − -c : It lists only a count of the lines that match a pattern -h : displays the matched lines only. -i : Ignores, case for matching -l : prints filenames only -n : Display the matched lines and their line numbers. -v : It prints out all the lines that do not match the pattern Now, let’s consider a case where we want to find a particular pattern in all the files in a particular directory, say dir1. grep -rni "word" * In the above command replace the “word” placeholder with For that we make use of the command shown below − grep -rni "func main()" * The above command will try to find a string “func main()” in all the files in a particular directory and also in the subdirectories as well. main.go:120:func main() {} In case we only want to find a particular pattern in a single directory and not the subdirectories then we need to use the command shown below − grep -s "func main()" * In the above command we made use of the -s flag which will help us to not get a warning for each subdirectory that is present inside the directory where we are running the command. main.go:120:func main() {} Another command that we can make use of is the find command. find . -name "*.go" -exec grep -H "func main" {} \; ./main.go:func main() {
[ { "code": null, "e": 1416, "s": 1187, "text": "The grep command in Linux is used to filter searches in a file for a particular pattern of characters. It is one of the most used Linux utility commands to display the lines that contain the pattern that we are trying to search." }, { "code": null, "e": 1521, "s": 1416, "text": "Normally, the pattern that we are trying to search in the file is referred to as the regular expression." }, { "code": null, "e": 1552, "s": 1521, "text": "grep [options] pattern [files]" }, { "code": null, "e": 1641, "s": 1552, "text": "While there are plenty of different options available to us, some of the most used are −" }, { "code": null, "e": 1917, "s": 1641, "text": "-c : It lists only a count of the lines that match a pattern\n-h : displays the matched lines only.\n-i : Ignores, case for matching\n-l : prints filenames only\n-n : Display the matched lines and their line numbers.\n-v : It prints out all the lines that do not match the pattern" }, { "code": null, "e": 2041, "s": 1917, "text": "Now, let’s consider a case where we want to find a particular pattern in all the files in a particular directory, say dir1." }, { "code": null, "e": 2060, "s": 2041, "text": "grep -rni \"word\" *" }, { "code": null, "e": 2117, "s": 2060, "text": "In the above command replace the “word” placeholder with" }, { "code": null, "e": 2167, "s": 2117, "text": "For that we make use of the command shown below −" }, { "code": null, "e": 2193, "s": 2167, "text": "grep -rni \"func main()\" *" }, { "code": null, "e": 2334, "s": 2193, "text": "The above command will try to find a string “func main()” in all the files in a particular directory and also in the subdirectories as well." }, { "code": null, "e": 2362, "s": 2334, "text": "main.go:120:func main() {}\n" }, { "code": null, "e": 2507, "s": 2362, "text": "In case we only want to find a particular pattern in a single directory and not the subdirectories then we need to use the command shown below −" }, { "code": null, "e": 2531, "s": 2507, "text": "grep -s \"func main()\" *" }, { "code": null, "e": 2712, "s": 2531, "text": "In the above command we made use of the -s flag which will help us to not get a warning for each subdirectory that is present inside the directory where we are running the command." }, { "code": null, "e": 2739, "s": 2712, "text": "main.go:120:func main() {}" }, { "code": null, "e": 2800, "s": 2739, "text": "Another command that we can make use of is the find command." }, { "code": null, "e": 2852, "s": 2800, "text": "find . -name \"*.go\" -exec grep -H \"func main\" {} \\;" }, { "code": null, "e": 2877, "s": 2852, "text": "./main.go:func main() {\n" } ]
Web Programming in C++
14 Oct, 2019 CGI(COMMON GATEWAY INTERFACE) may be a set of standards that outline however data is changed from the online server, passing the online user’s request to Associate in Nursing application and to receive data back to the user. When any user requests for a web page, the server sends back the requested page. The Web server typically passes the form information to a small application program that processes the data and may send back a confirmation message. This methodology or convention for passing knowledge back and forth between the server and also the application is termed the common entree interface (CGI) and is an element of the Web’s Hypertext Transfer Protocol (HTTP). The Common entree Interface (CGI) may be a set of rules for running scripts and programs on an online server. It specifies what data is communicated between the online server and clients’ net browsers and the way the data is transmitted. Most net servers embrace a cgi-bin directory within the root folder of every web site on the server. Any scripts placed during this directory should follow the principles of the Common entree Interface. For example, scripts situated within the cgi-bin directory is also given workable permissions, while files outside the directory may not be allowed to be executed. A CGI script may additionally request CGI surroundings variables, like SERVER_PROTOCOL and REMOTE_HOST, which may be used as input variables for the script. Since CGI may be a normal interface, it will be used on multiple kinds of hardware platforms and is supported by many varieties net server software package, like Apache and Windows Server. CGI scripts and programs also can be written in many completely different languages, such as C++, Java, and Perl. While several websites still use CGI for running programs and scripts, developers now often include scripts directly within Web pages. These scripts, that area unit written in languages like PHP and ASP, area unit processed on the server before the page is loaded, and also the ensuing knowledge is shipped to the user’s browser. Browsing the WebFor knowing the thought of CGI, let’s take a glance at the state of affairs that takes place once users browse one thing on the online employing a specific address. The browser you are using contacts the HTTP web server and demands for the URL.The web server will parse the URL and will search for the file name; if the requested file is found, immediately sends back that file to the browser or else sends an error message.The web browser takes the response from a web server and displays either file received or an error message.If you are developing a website and you required a CGI application to control then you can specify the name of the application in the URL (uniform resource locator) that your code in an HTML file. The browser you are using contacts the HTTP web server and demands for the URL. The web server will parse the URL and will search for the file name; if the requested file is found, immediately sends back that file to the browser or else sends an error message. The web browser takes the response from a web server and displays either file received or an error message. If you are developing a website and you required a CGI application to control then you can specify the name of the application in the URL (uniform resource locator) that your code in an HTML file. Server Side ConfigurationBefore using the CGI programming, programmers should make sure that the Web server supports CGI and is well configured for handling CGI programs. By convention, CGI files will have an extension as .cgi, though they are C++ executable. By default, Apache Web Server is configured to run CGI programs in /var/www/cgi-bin Programmers need to have a web server up and running in order to run any CGI program like Perl, shell etc. Example of CGI program using C++ // C++ example of CGI program #include <iostream>using namespace std;int main(){ cout << "Content-type:text/html\r\n\r\n"; cout << "<html>\n"; cout << "<head>\n"; cout << "<title>Hello TutorialsCloud </title>\n"; cout << "</head>\n"; cout << "<body>\n"; cout << "<h3> <b> First CGI program </b> </h2>\n"; cout << "</body>\n"; cout << "</html>\n"; return 0;} Content-type:text/html Hello TutorialsCloud Compile the above program and give this executable a suitable name along with the extension .cgi. This file needs to be kept in/var/www/cgi-bin directoryand it has following content. /var/www/cgi-bin directory and it has following content. Some other HTTP headers which are frequently used in CGI programs are:Content-type: It is a MIME string which defines the format of the file being returned.Expires: Date: It defines the date the information of the current web page becomes invalid.Location: URL: The URL that has to be returned instead of the URL that is requested.Last-modified: Date: The date of the last modification of the resource.Content-length: N: The length, in bytes, of the data being returned. This value ‘N’ is used by the browser to report the estimated download time.Set-Cookie: String: Used to set the cookie passed through the string Content-type: It is a MIME string which defines the format of the file being returned.Expires: Date: It defines the date the information of the current web page becomes invalid.Location: URL: The URL that has to be returned instead of the URL that is requested.Last-modified: Date: The date of the last modification of the resource.Content-length: N: The length, in bytes, of the data being returned. This value ‘N’ is used by the browser to report the estimated download time.Set-Cookie: String: Used to set the cookie passed through the string Content-type: It is a MIME string which defines the format of the file being returned. Expires: Date: It defines the date the information of the current web page becomes invalid. Location: URL: The URL that has to be returned instead of the URL that is requested. Last-modified: Date: The date of the last modification of the resource. Content-length: N: The length, in bytes, of the data being returned. This value ‘N’ is used by the browser to report the estimated download time. Set-Cookie: String: Used to set the cookie passed through the string CGI Environments Variables CONTENT_LENGTH: Optionally provides the length, in bytes. It’s available only for POST requests. CONTENT_TYPE: Optionally provides the sort of content i.e. the data type of the content. HTTP_COOKIE: come back the visitor’s cookies, if one is ready within the type of key try. HTTP_USER_AGENT: The browser type of the visitor. It request-header field contains info concerning the user agent originating the request. PATH_INFO: It provides the trail for the CGI script. REMOTE_ADDR: The science address of the visitant, i.e. the science address of the remote host creating the request. REMOTE_HOST: The hostname of the visitor, i.e. the totally qualified name of the host creating the request Picked Web-Programs C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Polymorphism in C++ Queue in C++ Standard Template Library (STL) List in C++ Standard Template Library (STL) Command line arguments in C/C++ Exception Handling in C++ Operators in C / C++ Sorting a vector in C++ Destructors in C++ Power Function in C/C++ Pure Virtual Functions and Abstract Classes in C++
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Oct, 2019" }, { "code": null, "e": 733, "s": 54, "text": "CGI(COMMON GATEWAY INTERFACE) may be a set of standards that outline however data is changed from the online server, passing the online user’s request to Associate in Nursing application and to receive data back to the user. When any user requests for a web page, the server sends back the requested page. The Web server typically passes the form information to a small application program that processes the data and may send back a confirmation message. This methodology or convention for passing knowledge back and forth between the server and also the application is termed the common entree interface (CGI) and is an element of the Web’s Hypertext Transfer Protocol (HTTP)." }, { "code": null, "e": 1495, "s": 733, "text": "The Common entree Interface (CGI) may be a set of rules for running scripts and programs on an online server. It specifies what data is communicated between the online server and clients’ net browsers and the way the data is transmitted. Most net servers embrace a cgi-bin directory within the root folder of every web site on the server. Any scripts placed during this directory should follow the principles of the Common entree Interface. For example, scripts situated within the cgi-bin directory is also given workable permissions, while files outside the directory may not be allowed to be executed. A CGI script may additionally request CGI surroundings variables, like SERVER_PROTOCOL and REMOTE_HOST, which may be used as input variables for the script." }, { "code": null, "e": 2128, "s": 1495, "text": "Since CGI may be a normal interface, it will be used on multiple kinds of hardware platforms and is supported by many varieties net server software package, like Apache and Windows Server. CGI scripts and programs also can be written in many completely different languages, such as C++, Java, and Perl. While several websites still use CGI for running programs and scripts, developers now often include scripts directly within Web pages. These scripts, that area unit written in languages like PHP and ASP, area unit processed on the server before the page is loaded, and also the ensuing knowledge is shipped to the user’s browser." }, { "code": null, "e": 2309, "s": 2128, "text": "Browsing the WebFor knowing the thought of CGI, let’s take a glance at the state of affairs that takes place once users browse one thing on the online employing a specific address." }, { "code": null, "e": 2872, "s": 2309, "text": "The browser you are using contacts the HTTP web server and demands for the URL.The web server will parse the URL and will search for the file name; if the requested file is found, immediately sends back that file to the browser or else sends an error message.The web browser takes the response from a web server and displays either file received or an error message.If you are developing a website and you required a CGI application to control then you can specify the name of the application in the URL (uniform resource locator) that your code in an HTML file." }, { "code": null, "e": 2952, "s": 2872, "text": "The browser you are using contacts the HTTP web server and demands for the URL." }, { "code": null, "e": 3133, "s": 2952, "text": "The web server will parse the URL and will search for the file name; if the requested file is found, immediately sends back that file to the browser or else sends an error message." }, { "code": null, "e": 3241, "s": 3133, "text": "The web browser takes the response from a web server and displays either file received or an error message." }, { "code": null, "e": 3438, "s": 3241, "text": "If you are developing a website and you required a CGI application to control then you can specify the name of the application in the URL (uniform resource locator) that your code in an HTML file." }, { "code": null, "e": 3765, "s": 3438, "text": "Server Side ConfigurationBefore using the CGI programming, programmers should make sure that the Web server supports CGI and is well configured for handling CGI programs. By convention, CGI files will have an extension as .cgi, though they are C++ executable. By default, Apache Web Server is configured to run CGI programs in" }, { "code": null, "e": 3782, "s": 3765, "text": "/var/www/cgi-bin" }, { "code": null, "e": 3889, "s": 3782, "text": "Programmers need to have a web server up and running in order to run any CGI program like Perl, shell etc." }, { "code": null, "e": 3922, "s": 3889, "text": "Example of CGI program using C++" }, { "code": "// C++ example of CGI program #include <iostream>using namespace std;int main(){ cout << \"Content-type:text/html\\r\\n\\r\\n\"; cout << \"<html>\\n\"; cout << \"<head>\\n\"; cout << \"<title>Hello TutorialsCloud </title>\\n\"; cout << \"</head>\\n\"; cout << \"<body>\\n\"; cout << \"<h3> <b> First CGI program </b> </h2>\\n\"; cout << \"</body>\\n\"; cout << \"</html>\\n\"; return 0;}", "e": 4311, "s": 3922, "text": null }, { "code": null, "e": 4334, "s": 4311, "text": "Content-type:text/html" }, { "code": null, "e": 4355, "s": 4334, "text": "Hello TutorialsCloud" }, { "code": null, "e": 4453, "s": 4355, "text": "Compile the above program and give this executable a suitable name along with the extension .cgi." }, { "code": null, "e": 4538, "s": 4453, "text": "This file needs to be kept in/var/www/cgi-bin directoryand it has following content." }, { "code": null, "e": 4565, "s": 4538, "text": "/var/www/cgi-bin directory" }, { "code": null, "e": 4595, "s": 4565, "text": "and it has following content." }, { "code": null, "e": 5211, "s": 4595, "text": "Some other HTTP headers which are frequently used in CGI programs are:Content-type: It is a MIME string which defines the format of the file being returned.Expires: Date: It defines the date the information of the current web page becomes invalid.Location: URL: The URL that has to be returned instead of the URL that is requested.Last-modified: Date: The date of the last modification of the resource.Content-length: N: The length, in bytes, of the data being returned. This value ‘N’ is used by the browser to report the estimated download time.Set-Cookie: String: Used to set the cookie passed through the string" }, { "code": null, "e": 5757, "s": 5211, "text": "Content-type: It is a MIME string which defines the format of the file being returned.Expires: Date: It defines the date the information of the current web page becomes invalid.Location: URL: The URL that has to be returned instead of the URL that is requested.Last-modified: Date: The date of the last modification of the resource.Content-length: N: The length, in bytes, of the data being returned. This value ‘N’ is used by the browser to report the estimated download time.Set-Cookie: String: Used to set the cookie passed through the string" }, { "code": null, "e": 5844, "s": 5757, "text": "Content-type: It is a MIME string which defines the format of the file being returned." }, { "code": null, "e": 5936, "s": 5844, "text": "Expires: Date: It defines the date the information of the current web page becomes invalid." }, { "code": null, "e": 6021, "s": 5936, "text": "Location: URL: The URL that has to be returned instead of the URL that is requested." }, { "code": null, "e": 6093, "s": 6021, "text": "Last-modified: Date: The date of the last modification of the resource." }, { "code": null, "e": 6239, "s": 6093, "text": "Content-length: N: The length, in bytes, of the data being returned. This value ‘N’ is used by the browser to report the estimated download time." }, { "code": null, "e": 6308, "s": 6239, "text": "Set-Cookie: String: Used to set the cookie passed through the string" }, { "code": null, "e": 6335, "s": 6308, "text": "CGI Environments Variables" }, { "code": null, "e": 6432, "s": 6335, "text": "CONTENT_LENGTH: Optionally provides the length, in bytes. It’s available only for POST requests." }, { "code": null, "e": 6521, "s": 6432, "text": "CONTENT_TYPE: Optionally provides the sort of content i.e. the data type of the content." }, { "code": null, "e": 6611, "s": 6521, "text": "HTTP_COOKIE: come back the visitor’s cookies, if one is ready within the type of key try." }, { "code": null, "e": 6750, "s": 6611, "text": "HTTP_USER_AGENT: The browser type of the visitor. It request-header field contains info concerning the user agent originating the request." }, { "code": null, "e": 6803, "s": 6750, "text": "PATH_INFO: It provides the trail for the CGI script." }, { "code": null, "e": 6919, "s": 6803, "text": "REMOTE_ADDR: The science address of the visitant, i.e. the science address of the remote host creating the request." }, { "code": null, "e": 7026, "s": 6919, "text": "REMOTE_HOST: The hostname of the visitor, i.e. the totally qualified name of the host creating the request" }, { "code": null, "e": 7033, "s": 7026, "text": "Picked" }, { "code": null, "e": 7046, "s": 7033, "text": "Web-Programs" }, { "code": null, "e": 7050, "s": 7046, "text": "C++" }, { "code": null, "e": 7054, "s": 7050, "text": "CPP" }, { "code": null, "e": 7152, "s": 7054, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7172, "s": 7152, "text": "Polymorphism in C++" }, { "code": null, "e": 7217, "s": 7172, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 7261, "s": 7217, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 7293, "s": 7261, "text": "Command line arguments in C/C++" }, { "code": null, "e": 7319, "s": 7293, "text": "Exception Handling in C++" }, { "code": null, "e": 7340, "s": 7319, "text": "Operators in C / C++" }, { "code": null, "e": 7364, "s": 7340, "text": "Sorting a vector in C++" }, { "code": null, "e": 7383, "s": 7364, "text": "Destructors in C++" }, { "code": null, "e": 7407, "s": 7383, "text": "Power Function in C/C++" } ]
Jackson Annotations For Java Application
20 Jul, 2021 Java has immense application in the coding world, and almost all of us know this fact. One of its features is the Jackson annotations. Although that is a very familiar term with the people involved in the coding world, it is less known. Jackson is a popular and very efficient JAVA library used to map or serialize JAVA objects to JSON and vice versa. Since Jackson is a JAVA-based library, one must know the basics of JAVA before going on with Jackson. It provides various features that are listed as below: Jackson is an easy-to-use library that can simplify commonly used cases. Since it provides default mapping, there is no need to create a mapping in Jackson. It has a commendable speed and low memory footprint, making it suitable for large object systems. The JSON results created by Jackson are compact and clean, which makes them easy to read. Jdk is the only library that Jackson requires. Therefore, it has no dependency. Above all, the Jackson library is free to use since it is open-source. After we have learned about the use and advantages of using Jackson, we now need to understand the Jackson annotations are as follows: @JsonAnyGetter@JsonGetter@JsonPropertyOrder@JsonRawValue@JsonValue@JsonRootName@JsonSerialize@JsonCreator@JacksonInject@JsonAnySetter@JsonSetter@JsonDeserialize@JsonEnumDefaultValue@JsonIgnoreProperties@JsonIgnore@JsonIgnoreType@JsonInclude@JsonAutoDetect@JsonTypeInfo@JsonSubTypes@JsonTypeName@JsonProperty@JsonFormat@JsonUnwrapped@JsonView@JsonManagedReference@JsonBackReference@JsonIdentityInfo@JsonFilter@JacksonAnnotationsInside @JsonAnyGetter @JsonGetter @JsonPropertyOrder @JsonRawValue @JsonValue @JsonRootName @JsonSerialize @JsonCreator @JacksonInject @JsonAnySetter @JsonSetter @JsonDeserialize @JsonEnumDefaultValue @JsonIgnoreProperties @JsonIgnore @JsonIgnoreType @JsonInclude @JsonAutoDetect @JsonTypeInfo @JsonSubTypes @JsonTypeName @JsonProperty @JsonFormat @JsonUnwrapped @JsonView @JsonManagedReference @JsonBackReference @JsonIdentityInfo @JsonFilter @JacksonAnnotationsInside Let us discuss each of the annotations in order to understand them to deeper roots by implementing them providing fragment codes for all of them. Annotation 1: @JsonAnyGetter t facilitates a return of Maps using a getter method. Later the maps are used to serialize the additional properties of JSON in the same way as other properties. public class ExtendableBean { public String name; private Map<String, String> properties; @JsonAnyGetter public Map<String, String> getProperties() { return properties; } } Annotation 2: @JsonGetter This annotation facilitates the marking of a specific method as a getter method. public class MyBean { public int id; private String name; @JsonGetter("name") public String getTheName() { return name; } } Annotation 3: @JsonPropertyOrder While you serialize a JSON object, its order might change, but this annotation facilitates preserving a specific order while the process goes on. @JsonPropertyOrder({ "name", "id" }) public class MyBean { public int id; public String name; } Annotation 4: @JsonRawValue Using this annotation, one can serialize any word without any decoration or escape. public class RawBean { public String name; @JsonRawValue public String json; } Annotation 5: @JsonValue Using this annotation, you can serialize an entire object using a single method. public enum TypeEnumWithValue { TYPE1(1, "Type A"), TYPE2(2, "Type 2"); private Integer id; private String name; // Standard constructors @JsonValue public String getName() { return name; } } Annotation 6: @JsonRootName This annotation facilitates the appearance of a root node specified over JSON. Wrap root value also needs to be enabled. { "id": 1, "name": "John" } Annotation 7: @JsonSerialize Using this annotation, you can specify a custom serializer to marshall the JSON object. public class EventWithSerializer { public String name; @JsonSerialize(using = CustomDateSerializer.class) public Date eventDate; } Annotation 8: @JsonCreator During deserialization, there is a factory method used. This annotation is used to fine-tune this method. { "id": 1, "theName": "My bean" } Annotation 9: @JacksonInject When we do not have to parse the property value, instead inject it in the JSON input, we use this annotation. public class BeanWithInject { @JacksonInject public int id; public String name; } Annotation 10: @JsonAnySetter Just as the getter annotation, this facilitates a setter method for using Map, which is then used to deserialize the additional properties of JSON in the same manner as other properties. public class ExtendableBean { public String name; private Map<String, String> properties; @JsonAnySetter public void add(String key, String value) { properties.put(key, value); } } Annotation 11: @JsonSetter This annotation allows any method to be marked as a setter method. public class MyBean { public int id; private String name; @JsonSetter("name") public void setTheName(String name) { this.name = name; } } Annotation 12: @JsonDeserialize This annotation is used to specify a custom deserializer in order to unmarshall a JSON object. public class EventWithSerializer { public String name; @JsonDeserialize(using = CustomDateDeserializer.class) public Date eventDate; } Annotation 13: @JsonEnumDefaultValue Using this annotation, we use a default value for deserializing an unknown enum value. public class AliasBean { @JsonAlias({ "fName", "f_name" }) private String firstName; private String lastName; } Annotation 14: @JsonIgnoreProperties Using this annotation, you can mark a property or a group of properties to be ignored. This is done at the class level. @JsonIgnoreProperties({ "id" }) public class BeanWithIgnore { public int id; public String name; } Annotation 15: @JsonIgnore This one serves the same purpose as above, the only difference being that it is used at the field level. public class BeanWithIgnore { @JsonIgnore public int id; public String name; } Annotation 16: @JsonIgnoreType Using this annotation, you can mark the property of a specific type to be ignored. public class User { public int id; public Name name; @JsonIgnoreType public static class Name { public String firstName; public String lastName; } } Annotation 17: @JsonInclude This annotation is used at those exclude properties that have null or empty default values. @JsonInclude(Include.NON_NULL) public class MyBean { public int id; public String name; } Annotation 18: @JsonAutoDetect This annotation helps detect properties that are not visible or accessible otherwise. @JsonAutoDetect(fieldVisibility = Visibility.ANY) public class PrivateBean { private int id; private String name; } Annotation 19: @JsonTypeInfo Using this annotation, you can indicate the details of the type of information that has to be included either during serialization or deserialization. Annotation 20: @JsonSubTypes This one is used to indicate the subtypes of the types that have been annotated. Annotation 21: @JsonTypeName Using this one can set type names that have to be used for annotated classes. public class Zoo { public Animal animal; @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = As.PROPERTY, property = "type") @JsonSubTypes({ @JsonSubTypes.Type(value = Dog.class, name = "dog"), @JsonSubTypes.Type(value = Cat.class, name = "cat") }) public static class Animal { public String name; } @JsonTypeName("dog") public static class Dog extends Animal { public double barkVolume; } @JsonTypeName("cat") public static class Cat extends Animal { boolean likesCream; public int lives; } } Annotation 22: @JsonProperty This annotation is used to mark the non-standard setter or getter methods that have to be used concerning JSON properties. public class MyBean { public int id; private String name; @JsonProperty("name") public void setTheName(String name) { this.name = name; } @JsonProperty("name") public String getTheName() { return name; } } Annotation 23: @JsonFormat This annotation is usually used in Date fields and specifies the format during serialization or deserialization. public class EventWithFormat { public String name; @JsonFormat( shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss") public Date eventDate; } Annotation 24: @JsonUnwrapped During the process of serialization or deserialization, it is required to unwrap the values of objects. This annotation is used to fulfill the purpose. public class UnwrappedUser { public int id; @JsonUnwrapped public Name name; public static class Name { public String firstName; public String lastName; } } Annotation 25: @JsonView This annotation is used to control the values to be serialized or not. public class Views { public static class Public {} public static class Internal extends Public {} } Annotation 26: @JsonManagedReference Such annotations are used for the display of objects with a parent-child relationship. public class ItemWithRef { public int id; public String itemName; @JsonManagedReference public UserWithRef owner; } Annotation 27: @JsonBackReference This shares the same function as the previous one. private class Player { public int id; public Info info; } private class Info { public int id; public Player parentPlayer; } // Something like this will come into play Player player = new Player(1); player.info = new Info(1, player); Annotation 28: @JsonIdentityInfo This annotation is used in a case where there is a parent-child relationship. It is used to indicate that an object identity will be used during serialization and deserialization. Java @JsonIdentityInfo( generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")public class ItemWithIdentity { public int id; public String itemName; public UserWithIdentity owner;} Annotation 29: @JsonFilter This annotation can be used to apply filters during the process of serialization and deserialization. @JsonFilter("myFilter") public class BeanWithFilter { public int id; public String name; } Annotation 30: @JacksonAnnotationsInside This annotation can be used to create customized Jackson annotations. @Retention(RetentionPolicy.RUNTIME) @JacksonAnnotationsInside @JsonInclude(Include.NON_NULL) @JsonPropertyOrder({ "name", "id", "dateCreated" }) public @interface CustomAnnotation {} Note: Various other annotations are used to rename properties or ignore them or choose the more or less specific types. While using these annotations, Jackson itself uses the default constructors while creating value instances. However, one may alter it by putting the customize constructor. Also, Jackson can handle polymorphic types, that is, objects with various subtypes. This does by enabling the inclusion of type information. Therefore, these were a few points and essential information on the Jackson annotations, their use, and their importance in Java. Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java ArrayList in Java Stream In Java Collections in Java Multidimensional Arrays in Java Singleton Class in Java Stack Class in Java Set in Java Introduction to Java Initialize an ArrayList in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Jul, 2021" }, { "code": null, "e": 380, "s": 28, "text": "Java has immense application in the coding world, and almost all of us know this fact. One of its features is the Jackson annotations. Although that is a very familiar term with the people involved in the coding world, it is less known. Jackson is a popular and very efficient JAVA library used to map or serialize JAVA objects to JSON and vice versa." }, { "code": null, "e": 537, "s": 380, "text": "Since Jackson is a JAVA-based library, one must know the basics of JAVA before going on with Jackson. It provides various features that are listed as below:" }, { "code": null, "e": 610, "s": 537, "text": "Jackson is an easy-to-use library that can simplify commonly used cases." }, { "code": null, "e": 694, "s": 610, "text": "Since it provides default mapping, there is no need to create a mapping in Jackson." }, { "code": null, "e": 792, "s": 694, "text": "It has a commendable speed and low memory footprint, making it suitable for large object systems." }, { "code": null, "e": 882, "s": 792, "text": "The JSON results created by Jackson are compact and clean, which makes them easy to read." }, { "code": null, "e": 962, "s": 882, "text": "Jdk is the only library that Jackson requires. Therefore, it has no dependency." }, { "code": null, "e": 1033, "s": 962, "text": "Above all, the Jackson library is free to use since it is open-source." }, { "code": null, "e": 1168, "s": 1033, "text": "After we have learned about the use and advantages of using Jackson, we now need to understand the Jackson annotations are as follows:" }, { "code": null, "e": 1602, "s": 1168, "text": "@JsonAnyGetter@JsonGetter@JsonPropertyOrder@JsonRawValue@JsonValue@JsonRootName@JsonSerialize@JsonCreator@JacksonInject@JsonAnySetter@JsonSetter@JsonDeserialize@JsonEnumDefaultValue@JsonIgnoreProperties@JsonIgnore@JsonIgnoreType@JsonInclude@JsonAutoDetect@JsonTypeInfo@JsonSubTypes@JsonTypeName@JsonProperty@JsonFormat@JsonUnwrapped@JsonView@JsonManagedReference@JsonBackReference@JsonIdentityInfo@JsonFilter@JacksonAnnotationsInside" }, { "code": null, "e": 1617, "s": 1602, "text": "@JsonAnyGetter" }, { "code": null, "e": 1629, "s": 1617, "text": "@JsonGetter" }, { "code": null, "e": 1648, "s": 1629, "text": "@JsonPropertyOrder" }, { "code": null, "e": 1662, "s": 1648, "text": "@JsonRawValue" }, { "code": null, "e": 1673, "s": 1662, "text": "@JsonValue" }, { "code": null, "e": 1687, "s": 1673, "text": "@JsonRootName" }, { "code": null, "e": 1702, "s": 1687, "text": "@JsonSerialize" }, { "code": null, "e": 1715, "s": 1702, "text": "@JsonCreator" }, { "code": null, "e": 1730, "s": 1715, "text": "@JacksonInject" }, { "code": null, "e": 1745, "s": 1730, "text": "@JsonAnySetter" }, { "code": null, "e": 1757, "s": 1745, "text": "@JsonSetter" }, { "code": null, "e": 1774, "s": 1757, "text": "@JsonDeserialize" }, { "code": null, "e": 1796, "s": 1774, "text": "@JsonEnumDefaultValue" }, { "code": null, "e": 1818, "s": 1796, "text": "@JsonIgnoreProperties" }, { "code": null, "e": 1830, "s": 1818, "text": "@JsonIgnore" }, { "code": null, "e": 1846, "s": 1830, "text": "@JsonIgnoreType" }, { "code": null, "e": 1859, "s": 1846, "text": "@JsonInclude" }, { "code": null, "e": 1875, "s": 1859, "text": "@JsonAutoDetect" }, { "code": null, "e": 1889, "s": 1875, "text": "@JsonTypeInfo" }, { "code": null, "e": 1903, "s": 1889, "text": "@JsonSubTypes" }, { "code": null, "e": 1917, "s": 1903, "text": "@JsonTypeName" }, { "code": null, "e": 1931, "s": 1917, "text": "@JsonProperty" }, { "code": null, "e": 1943, "s": 1931, "text": "@JsonFormat" }, { "code": null, "e": 1958, "s": 1943, "text": "@JsonUnwrapped" }, { "code": null, "e": 1968, "s": 1958, "text": "@JsonView" }, { "code": null, "e": 1990, "s": 1968, "text": "@JsonManagedReference" }, { "code": null, "e": 2009, "s": 1990, "text": "@JsonBackReference" }, { "code": null, "e": 2027, "s": 2009, "text": "@JsonIdentityInfo" }, { "code": null, "e": 2039, "s": 2027, "text": "@JsonFilter" }, { "code": null, "e": 2065, "s": 2039, "text": "@JacksonAnnotationsInside" }, { "code": null, "e": 2211, "s": 2065, "text": "Let us discuss each of the annotations in order to understand them to deeper roots by implementing them providing fragment codes for all of them." }, { "code": null, "e": 2240, "s": 2211, "text": "Annotation 1: @JsonAnyGetter" }, { "code": null, "e": 2402, "s": 2240, "text": "t facilitates a return of Maps using a getter method. Later the maps are used to serialize the additional properties of JSON in the same way as other properties." }, { "code": null, "e": 2593, "s": 2402, "text": "public class ExtendableBean {\n \n public String name;\n private Map<String, String> properties;\n\n @JsonAnyGetter\n public Map<String, String> getProperties() {\n return properties;\n }\n}" }, { "code": null, "e": 2619, "s": 2593, "text": "Annotation 2: @JsonGetter" }, { "code": null, "e": 2700, "s": 2619, "text": "This annotation facilitates the marking of a specific method as a getter method." }, { "code": null, "e": 2842, "s": 2700, "text": "public class MyBean {\n \n public int id;\n private String name;\n\n @JsonGetter(\"name\")\n public String getTheName() {\n return name;\n }\n}" }, { "code": null, "e": 2875, "s": 2842, "text": "Annotation 3: @JsonPropertyOrder" }, { "code": null, "e": 3021, "s": 2875, "text": "While you serialize a JSON object, its order might change, but this annotation facilitates preserving a specific order while the process goes on." }, { "code": null, "e": 3123, "s": 3021, "text": "@JsonPropertyOrder({ \"name\", \"id\" })\n\npublic class MyBean {\n\n public int id;\n public String name;\n}" }, { "code": null, "e": 3151, "s": 3123, "text": "Annotation 4: @JsonRawValue" }, { "code": null, "e": 3235, "s": 3151, "text": "Using this annotation, one can serialize any word without any decoration or escape." }, { "code": null, "e": 3324, "s": 3235, "text": "public class RawBean {\n \n public String name;\n\n @JsonRawValue\n public String json;\n}" }, { "code": null, "e": 3349, "s": 3324, "text": "Annotation 5: @JsonValue" }, { "code": null, "e": 3430, "s": 3349, "text": "Using this annotation, you can serialize an entire object using a single method." }, { "code": null, "e": 3644, "s": 3430, "text": "public enum TypeEnumWithValue {\n\n TYPE1(1, \"Type A\"), TYPE2(2, \"Type 2\");\n\n private Integer id;\n private String name;\n\n // Standard constructors\n\n @JsonValue\n public String getName() {\n return name;\n }\n}" }, { "code": null, "e": 3672, "s": 3644, "text": "Annotation 6: @JsonRootName" }, { "code": null, "e": 3793, "s": 3672, "text": "This annotation facilitates the appearance of a root node specified over JSON. Wrap root value also needs to be enabled." }, { "code": null, "e": 3825, "s": 3793, "text": "{\n \"id\": 1,\n \"name\": \"John\"\n}" }, { "code": null, "e": 3854, "s": 3825, "text": "Annotation 7: @JsonSerialize" }, { "code": null, "e": 3942, "s": 3854, "text": "Using this annotation, you can specify a custom serializer to marshall the JSON object." }, { "code": null, "e": 4081, "s": 3942, "text": "public class EventWithSerializer {\n\n public String name;\n\n @JsonSerialize(using = CustomDateSerializer.class)\n public Date eventDate;\n}" }, { "code": null, "e": 4108, "s": 4081, "text": "Annotation 8: @JsonCreator" }, { "code": null, "e": 4214, "s": 4108, "text": "During deserialization, there is a factory method used. This annotation is used to fine-tune this method." }, { "code": null, "e": 4252, "s": 4214, "text": "{\n \"id\": 1,\n \"theName\": \"My bean\"\n}" }, { "code": null, "e": 4281, "s": 4252, "text": "Annotation 9: @JacksonInject" }, { "code": null, "e": 4392, "s": 4281, "text": "When we do not have to parse the property value, instead inject it in the JSON input, we use this annotation." }, { "code": null, "e": 4484, "s": 4392, "text": "public class BeanWithInject {\n \n @JacksonInject\n public int id;\n\n public String name;\n}" }, { "code": null, "e": 4514, "s": 4484, "text": "Annotation 10: @JsonAnySetter" }, { "code": null, "e": 4701, "s": 4514, "text": "Just as the getter annotation, this facilitates a setter method for using Map, which is then used to deserialize the additional properties of JSON in the same manner as other properties." }, { "code": null, "e": 4900, "s": 4701, "text": "public class ExtendableBean {\n \n public String name;\n private Map<String, String> properties;\n\n @JsonAnySetter\n public void add(String key, String value) {\n properties.put(key, value);\n }\n}" }, { "code": null, "e": 4927, "s": 4900, "text": "Annotation 11: @JsonSetter" }, { "code": null, "e": 4994, "s": 4927, "text": "This annotation allows any method to be marked as a setter method." }, { "code": null, "e": 5150, "s": 4994, "text": "public class MyBean {\n \n public int id;\n private String name;\n\n @JsonSetter(\"name\")\n public void setTheName(String name) {\n this.name = name;\n }\n}" }, { "code": null, "e": 5182, "s": 5150, "text": "Annotation 12: @JsonDeserialize" }, { "code": null, "e": 5277, "s": 5182, "text": "This annotation is used to specify a custom deserializer in order to unmarshall a JSON object." }, { "code": null, "e": 5422, "s": 5277, "text": "public class EventWithSerializer {\n \n public String name;\n\n @JsonDeserialize(using = CustomDateDeserializer.class)\n public Date eventDate;\n}" }, { "code": null, "e": 5459, "s": 5422, "text": "Annotation 13: @JsonEnumDefaultValue" }, { "code": null, "e": 5546, "s": 5459, "text": "Using this annotation, we use a default value for deserializing an unknown enum value." }, { "code": null, "e": 5667, "s": 5546, "text": "public class AliasBean {\n \n @JsonAlias({ \"fName\", \"f_name\" })\n private String firstName;\n private String lastName;\n}" }, { "code": null, "e": 5704, "s": 5667, "text": "Annotation 14: @JsonIgnoreProperties" }, { "code": null, "e": 5824, "s": 5704, "text": "Using this annotation, you can mark a property or a group of properties to be ignored. This is done at the class level." }, { "code": null, "e": 5931, "s": 5824, "text": "@JsonIgnoreProperties({ \"id\" })\npublic class BeanWithIgnore {\n public int id;\n public String name;\n}" }, { "code": null, "e": 5958, "s": 5931, "text": "Annotation 15: @JsonIgnore" }, { "code": null, "e": 6063, "s": 5958, "text": "This one serves the same purpose as above, the only difference being that it is used at the field level." }, { "code": null, "e": 6150, "s": 6063, "text": "public class BeanWithIgnore {\n\n @JsonIgnore\n\n public int id;\n public String name;\n}" }, { "code": null, "e": 6181, "s": 6150, "text": "Annotation 16: @JsonIgnoreType" }, { "code": null, "e": 6264, "s": 6181, "text": "Using this annotation, you can mark the property of a specific type to be ignored." }, { "code": null, "e": 6434, "s": 6264, "text": "public class User {\n\n public int id;\n public Name name;\n\n @JsonIgnoreType\n public static class Name {\n\n public String firstName;\n public String lastName;\n }\n}" }, { "code": null, "e": 6462, "s": 6434, "text": "Annotation 17: @JsonInclude" }, { "code": null, "e": 6554, "s": 6462, "text": "This annotation is used at those exclude properties that have null or empty default values." }, { "code": null, "e": 6650, "s": 6554, "text": "@JsonInclude(Include.NON_NULL)\n\npublic class MyBean {\n\n public int id;\n public String name;\n}" }, { "code": null, "e": 6681, "s": 6650, "text": "Annotation 18: @JsonAutoDetect" }, { "code": null, "e": 6767, "s": 6681, "text": "This annotation helps detect properties that are not visible or accessible otherwise." }, { "code": null, "e": 6889, "s": 6767, "text": "@JsonAutoDetect(fieldVisibility = Visibility.ANY)\n\npublic class PrivateBean {\n\n private int id;\n private String name;\n}" }, { "code": null, "e": 6918, "s": 6889, "text": "Annotation 19: @JsonTypeInfo" }, { "code": null, "e": 7069, "s": 6918, "text": "Using this annotation, you can indicate the details of the type of information that has to be included either during serialization or deserialization." }, { "code": null, "e": 7098, "s": 7069, "text": "Annotation 20: @JsonSubTypes" }, { "code": null, "e": 7179, "s": 7098, "text": "This one is used to indicate the subtypes of the types that have been annotated." }, { "code": null, "e": 7208, "s": 7179, "text": "Annotation 21: @JsonTypeName" }, { "code": null, "e": 7286, "s": 7208, "text": "Using this one can set type names that have to be used for annotated classes." }, { "code": null, "e": 7847, "s": 7286, "text": "public class Zoo {\n\n public Animal animal;\n\n @JsonTypeInfo(\n use = JsonTypeInfo.Id.NAME,\n include = As.PROPERTY,\n property = \"type\")\n\n @JsonSubTypes({\n @JsonSubTypes.Type(value = Dog.class, name = \"dog\"),\n @JsonSubTypes.Type(value = Cat.class, name = \"cat\")\n })\n\n public static class Animal {\n public String name;\n }\n\n @JsonTypeName(\"dog\")\n public static class Dog extends Animal {\n public double barkVolume;\n }\n\n @JsonTypeName(\"cat\")\n public static class Cat extends Animal {\n boolean likesCream;\n public int lives;\n }\n}" }, { "code": null, "e": 7876, "s": 7847, "text": "Annotation 22: @JsonProperty" }, { "code": null, "e": 7999, "s": 7876, "text": "This annotation is used to mark the non-standard setter or getter methods that have to be used concerning JSON properties." }, { "code": null, "e": 8234, "s": 7999, "text": "public class MyBean {\n \n public int id;\n private String name;\n\n @JsonProperty(\"name\")\n public void setTheName(String name) {\n this.name = name;\n }\n\n @JsonProperty(\"name\")\n public String getTheName() {\n return name;\n }\n}" }, { "code": null, "e": 8261, "s": 8234, "text": "Annotation 23: @JsonFormat" }, { "code": null, "e": 8374, "s": 8261, "text": "This annotation is usually used in Date fields and specifies the format during serialization or deserialization." }, { "code": null, "e": 8545, "s": 8374, "text": "public class EventWithFormat {\n\n public String name;\n\n @JsonFormat(\n shape = JsonFormat.Shape.STRING,\n pattern = \"dd-MM-yyyy hh:mm:ss\")\n public Date eventDate;\n}" }, { "code": null, "e": 8575, "s": 8545, "text": "Annotation 24: @JsonUnwrapped" }, { "code": null, "e": 8727, "s": 8575, "text": "During the process of serialization or deserialization, it is required to unwrap the values of objects. This annotation is used to fulfill the purpose." }, { "code": null, "e": 8906, "s": 8727, "text": "public class UnwrappedUser {\n\n public int id;\n\n @JsonUnwrapped\n public Name name;\n\n public static class Name {\n\n public String firstName;\n public String lastName;\n }\n}" }, { "code": null, "e": 8931, "s": 8906, "text": "Annotation 25: @JsonView" }, { "code": null, "e": 9002, "s": 8931, "text": "This annotation is used to control the values to be serialized or not." }, { "code": null, "e": 9110, "s": 9002, "text": "public class Views {\n public static class Public {}\n public static class Internal extends Public {}\n}" }, { "code": null, "e": 9147, "s": 9110, "text": "Annotation 26: @JsonManagedReference" }, { "code": null, "e": 9234, "s": 9147, "text": "Such annotations are used for the display of objects with a parent-child relationship." }, { "code": null, "e": 9362, "s": 9234, "text": "public class ItemWithRef {\n \n public int id;\n public String itemName;\n\n @JsonManagedReference\n public UserWithRef owner;\n}" }, { "code": null, "e": 9396, "s": 9362, "text": "Annotation 27: @JsonBackReference" }, { "code": null, "e": 9447, "s": 9396, "text": "This shares the same function as the previous one." }, { "code": null, "e": 9692, "s": 9447, "text": "private class Player {\n\n public int id;\n public Info info;\n}\n\nprivate class Info {\n\n public int id;\n public Player parentPlayer;\n}\n\n// Something like this will come into play\nPlayer player = new Player(1);\nplayer.info = new Info(1, player);" }, { "code": null, "e": 9725, "s": 9692, "text": "Annotation 28: @JsonIdentityInfo" }, { "code": null, "e": 9905, "s": 9725, "text": "This annotation is used in a case where there is a parent-child relationship. It is used to indicate that an object identity will be used during serialization and deserialization." }, { "code": null, "e": 9912, "s": 9907, "text": "Java" }, { "code": "@JsonIdentityInfo( generator = ObjectIdGenerators.PropertyGenerator.class, property = \"id\")public class ItemWithIdentity { public int id; public String itemName; public UserWithIdentity owner;}", "e": 10117, "s": 9912, "text": null }, { "code": null, "e": 10144, "s": 10117, "text": "Annotation 29: @JsonFilter" }, { "code": null, "e": 10246, "s": 10144, "text": "This annotation can be used to apply filters during the process of serialization and deserialization." }, { "code": null, "e": 10343, "s": 10246, "text": "@JsonFilter(\"myFilter\")\n\npublic class BeanWithFilter {\n\n public int id;\n public String name;\n}" }, { "code": null, "e": 10384, "s": 10343, "text": "Annotation 30: @JacksonAnnotationsInside" }, { "code": null, "e": 10454, "s": 10384, "text": "This annotation can be used to create customized Jackson annotations." }, { "code": null, "e": 10638, "s": 10454, "text": "@Retention(RetentionPolicy.RUNTIME)\n@JacksonAnnotationsInside\n@JsonInclude(Include.NON_NULL)\n@JsonPropertyOrder({ \"name\", \"id\", \"dateCreated\" })\n\npublic @interface CustomAnnotation {}" }, { "code": null, "e": 10758, "s": 10638, "text": "Note: Various other annotations are used to rename properties or ignore them or choose the more or less specific types." }, { "code": null, "e": 11201, "s": 10758, "text": "While using these annotations, Jackson itself uses the default constructors while creating value instances. However, one may alter it by putting the customize constructor. Also, Jackson can handle polymorphic types, that is, objects with various subtypes. This does by enabling the inclusion of type information. Therefore, these were a few points and essential information on the Jackson annotations, their use, and their importance in Java." }, { "code": null, "e": 11208, "s": 11201, "text": "Picked" }, { "code": null, "e": 11213, "s": 11208, "text": "Java" }, { "code": null, "e": 11218, "s": 11213, "text": "Java" }, { "code": null, "e": 11316, "s": 11218, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11335, "s": 11316, "text": "Interfaces in Java" }, { "code": null, "e": 11353, "s": 11335, "text": "ArrayList in Java" }, { "code": null, "e": 11368, "s": 11353, "text": "Stream In Java" }, { "code": null, "e": 11388, "s": 11368, "text": "Collections in Java" }, { "code": null, "e": 11420, "s": 11388, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 11444, "s": 11420, "text": "Singleton Class in Java" }, { "code": null, "e": 11464, "s": 11444, "text": "Stack Class in Java" }, { "code": null, "e": 11476, "s": 11464, "text": "Set in Java" }, { "code": null, "e": 11497, "s": 11476, "text": "Introduction to Java" } ]
java.io.FileNotFoundException in Java
16 Nov, 2021 java.io.FileNotFoundException which is a common exception which occurs while we try to access a file. FileNotFoundExcetion is thrown by constructors RandomAccessFile, FileInputStream, and FileOutputStream. FileNotFoundException occurs at runtime so it is a checked exception, we can handle this exception by java code, and we have to take care of the code so that this exception doesn’t occur. Declaration : public class FileNotFoundException extends IOException implements ObjectInput, ObjectStreamConstants Constructors : FileNotFoundException() : It gives FileNotFoundException with null message. FileNotFoundException(String s) : It gives FileNotFoundException with detail message. It doesn’t have any methods. Now let’s understand the hierarchy of this class i.e FileNotFoundException extends IOException which further extends the Exception class which extends the Throwable class and further the Object class. Hierarchy Diagram: Why this Exception occurs? There are mainly 2 scenarios when FileNotFoundException occurs. Now let’s see them with examples provided: If the given file is not available in the given location then this error will occur.If the given file is inaccessible, for example, if it is read-only then you can read the file but not modify the file, if we try to modify it, an error will occur or if the file that you are trying to access for the read/write operation is opened by another program then this error will occur. If the given file is not available in the given location then this error will occur. If the given file is inaccessible, for example, if it is read-only then you can read the file but not modify the file, if we try to modify it, an error will occur or if the file that you are trying to access for the read/write operation is opened by another program then this error will occur. Scenario 1: If the given file is not available in the given location then this error will occur. Example: Java // Java program to illustrate // FileNotFoundException // All output and input streams // are available in java.io packageimport java.io.*; public class Example1 { public static void main(String[] args) { // creating object of FileReader FileReader reader = new FileReader("file.txt"); // passing FileReader to // buffered reader BufferedReader br = new BufferedReader(reader); // declaring empty string String data =null; // while loop to read data // and printing them while ((data = br.readLine()) != null) { System.out.println(data); } // closing the object br.close(); }} prog.java:14: error: unreported exception FileNotFoundException; must be caught or declared to be thrown FileReader reader = new FileReader("file.txt"); ^ prog.java:25: error: unreported exception IOException; must be caught or declared to be thrown while ((data = br.readLine()) != null) ^ prog.java:31: error: unreported exception IOException; must be caught or declared to be thrown br.close(); ^ 3 errors Scenario 2: If the given file is inaccessible, for example, if it is read-only then you can read the file but not modify the file if we try to modify it, an error will occur or if the file that you are trying to access for the read/write operation is opened by another program then this error will occur. Example: Java // Java program to illustrate // FileNotFoundException // All output and input streams // are available in java.io packageimport java.io.*;import java.util.*; class Example2 { public static void main(String[] args) { // starting try block try { // Opening the file File f=new File("file.txt"); // creating printWriter object // by initiating fileWriter PrintWriter p1=new PrintWriter(new FileWriter(f), true); // printing sample text p1.println("Hello world"); p1.close(); // changing the file operation // to read-only f.setReadOnly(); // trying to write to new file PrintWriter p2=new PrintWriter(new FileWriter("file.txt"), true); p2.println("Hello World"); } // catching exception thrown // by try block catch(Exception ex) { ex.printStackTrace(); } }} java.security.AccessControlException: access denied ("java.io.FilePermission" "file.txt" "write") at java.base/java.security.AccessControlContext.checkPermission(AccessControlContext.java:472) at java.base/java.security.AccessController.checkPermission(AccessController.java:897) at java.base/java.lang.SecurityManager.checkPermission(SecurityManager.java:322) at java.base/java.lang.SecurityManager.checkWrite(SecurityManager.java:752) at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:225) at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:187) at java.base/java.io.FileWriter.<init>(FileWriter.java:96) at Example2.main(File.java:19) Handling Exception: Firstly we have to use the try-catch block if we know whether the error will occur. Inside try block all the lines should be there if there are chances of errors. There are other remedies to handle the exception: If the message of the exception tells that there is no such file or directory, then you re-verify whether you mentioned the wrong file name in the program or file exists in that directory or not.If the message of the exception tells us that access is denied then we have to check the permissions of the file (read, write, both read and write) and also check whether that file is in use by another program.If the message of the exception tells us that the specified file is a directory then you must either delete the existing directory(if the directory not in use) or change the name of the file. If the message of the exception tells that there is no such file or directory, then you re-verify whether you mentioned the wrong file name in the program or file exists in that directory or not. If the message of the exception tells us that access is denied then we have to check the permissions of the file (read, write, both read and write) and also check whether that file is in use by another program. If the message of the exception tells us that the specified file is a directory then you must either delete the existing directory(if the directory not in use) or change the name of the file. anikakapoor Java-Exceptions Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Nov, 2021" }, { "code": null, "e": 423, "s": 28, "text": "java.io.FileNotFoundException which is a common exception which occurs while we try to access a file. FileNotFoundExcetion is thrown by constructors RandomAccessFile, FileInputStream, and FileOutputStream. FileNotFoundException occurs at runtime so it is a checked exception, we can handle this exception by java code, and we have to take care of the code so that this exception doesn’t occur. " }, { "code": null, "e": 438, "s": 423, "text": "Declaration : " }, { "code": null, "e": 545, "s": 438, "text": "public class FileNotFoundException\n extends IOException\n implements ObjectInput, ObjectStreamConstants" }, { "code": null, "e": 561, "s": 545, "text": "Constructors : " }, { "code": null, "e": 637, "s": 561, "text": "FileNotFoundException() : It gives FileNotFoundException with null message." }, { "code": null, "e": 723, "s": 637, "text": "FileNotFoundException(String s) : It gives FileNotFoundException with detail message." }, { "code": null, "e": 954, "s": 723, "text": "It doesn’t have any methods. Now let’s understand the hierarchy of this class i.e FileNotFoundException extends IOException which further extends the Exception class which extends the Throwable class and further the Object class. " }, { "code": null, "e": 973, "s": 954, "text": "Hierarchy Diagram:" }, { "code": null, "e": 1001, "s": 973, "text": "Why this Exception occurs? " }, { "code": null, "e": 1108, "s": 1001, "text": "There are mainly 2 scenarios when FileNotFoundException occurs. Now let’s see them with examples provided:" }, { "code": null, "e": 1486, "s": 1108, "text": "If the given file is not available in the given location then this error will occur.If the given file is inaccessible, for example, if it is read-only then you can read the file but not modify the file, if we try to modify it, an error will occur or if the file that you are trying to access for the read/write operation is opened by another program then this error will occur." }, { "code": null, "e": 1571, "s": 1486, "text": "If the given file is not available in the given location then this error will occur." }, { "code": null, "e": 1865, "s": 1571, "text": "If the given file is inaccessible, for example, if it is read-only then you can read the file but not modify the file, if we try to modify it, an error will occur or if the file that you are trying to access for the read/write operation is opened by another program then this error will occur." }, { "code": null, "e": 1877, "s": 1865, "text": "Scenario 1:" }, { "code": null, "e": 1962, "s": 1877, "text": "If the given file is not available in the given location then this error will occur." }, { "code": null, "e": 1972, "s": 1962, "text": "Example: " }, { "code": null, "e": 1977, "s": 1972, "text": "Java" }, { "code": "// Java program to illustrate // FileNotFoundException // All output and input streams // are available in java.io packageimport java.io.*; public class Example1 { public static void main(String[] args) { // creating object of FileReader FileReader reader = new FileReader(\"file.txt\"); // passing FileReader to // buffered reader BufferedReader br = new BufferedReader(reader); // declaring empty string String data =null; // while loop to read data // and printing them while ((data = br.readLine()) != null) { System.out.println(data); } // closing the object br.close(); }}", "e": 2646, "s": 1977, "text": null }, { "code": null, "e": 3134, "s": 2646, "text": "prog.java:14: error: unreported exception FileNotFoundException; must be caught or declared to be thrown\n FileReader reader = new FileReader(\"file.txt\");\n ^\nprog.java:25: error: unreported exception IOException; must be caught or declared to be thrown\n while ((data = br.readLine()) != null) \n ^\nprog.java:31: error: unreported exception IOException; must be caught or declared to be thrown\n br.close();\n ^\n3 errors" }, { "code": null, "e": 3146, "s": 3134, "text": "Scenario 2:" }, { "code": null, "e": 3439, "s": 3146, "text": "If the given file is inaccessible, for example, if it is read-only then you can read the file but not modify the file if we try to modify it, an error will occur or if the file that you are trying to access for the read/write operation is opened by another program then this error will occur." }, { "code": null, "e": 3448, "s": 3439, "text": "Example:" }, { "code": null, "e": 3453, "s": 3448, "text": "Java" }, { "code": "// Java program to illustrate // FileNotFoundException // All output and input streams // are available in java.io packageimport java.io.*;import java.util.*; class Example2 { public static void main(String[] args) { // starting try block try { // Opening the file File f=new File(\"file.txt\"); // creating printWriter object // by initiating fileWriter PrintWriter p1=new PrintWriter(new FileWriter(f), true); // printing sample text p1.println(\"Hello world\"); p1.close(); // changing the file operation // to read-only f.setReadOnly(); // trying to write to new file PrintWriter p2=new PrintWriter(new FileWriter(\"file.txt\"), true); p2.println(\"Hello World\"); } // catching exception thrown // by try block catch(Exception ex) { ex.printStackTrace(); } }}", "e": 4417, "s": 3453, "text": null }, { "code": null, "e": 5120, "s": 4417, "text": "java.security.AccessControlException: access denied (\"java.io.FilePermission\" \"file.txt\" \"write\")\n at java.base/java.security.AccessControlContext.checkPermission(AccessControlContext.java:472)\n at java.base/java.security.AccessController.checkPermission(AccessController.java:897)\n at java.base/java.lang.SecurityManager.checkPermission(SecurityManager.java:322)\n at java.base/java.lang.SecurityManager.checkWrite(SecurityManager.java:752)\n at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:225)\n at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:187)\n at java.base/java.io.FileWriter.<init>(FileWriter.java:96)\n at Example2.main(File.java:19)" }, { "code": null, "e": 5140, "s": 5120, "text": "Handling Exception:" }, { "code": null, "e": 5353, "s": 5140, "text": "Firstly we have to use the try-catch block if we know whether the error will occur. Inside try block all the lines should be there if there are chances of errors. There are other remedies to handle the exception:" }, { "code": null, "e": 5950, "s": 5353, "text": "If the message of the exception tells that there is no such file or directory, then you re-verify whether you mentioned the wrong file name in the program or file exists in that directory or not.If the message of the exception tells us that access is denied then we have to check the permissions of the file (read, write, both read and write) and also check whether that file is in use by another program.If the message of the exception tells us that the specified file is a directory then you must either delete the existing directory(if the directory not in use) or change the name of the file." }, { "code": null, "e": 6146, "s": 5950, "text": "If the message of the exception tells that there is no such file or directory, then you re-verify whether you mentioned the wrong file name in the program or file exists in that directory or not." }, { "code": null, "e": 6357, "s": 6146, "text": "If the message of the exception tells us that access is denied then we have to check the permissions of the file (read, write, both read and write) and also check whether that file is in use by another program." }, { "code": null, "e": 6549, "s": 6357, "text": "If the message of the exception tells us that the specified file is a directory then you must either delete the existing directory(if the directory not in use) or change the name of the file." }, { "code": null, "e": 6561, "s": 6549, "text": "anikakapoor" }, { "code": null, "e": 6577, "s": 6561, "text": "Java-Exceptions" }, { "code": null, "e": 6584, "s": 6577, "text": "Picked" }, { "code": null, "e": 6608, "s": 6584, "text": "Technical Scripter 2020" }, { "code": null, "e": 6613, "s": 6608, "text": "Java" }, { "code": null, "e": 6627, "s": 6613, "text": "Java Programs" }, { "code": null, "e": 6646, "s": 6627, "text": "Technical Scripter" }, { "code": null, "e": 6651, "s": 6646, "text": "Java" } ]
Python | Extract URL from HTML using lxml
19 Jul, 2019 Link extraction is a very common task when dealing with the HTML parsing. For every general web crawler that’s the most important function to perform. Out of all the Python libraries present out there, lxml is one of the best to work with. As explained in this article, lxml provides a number of helper function in order to extract the links. lxml installation – It is a Python binding for C libraries – libxslt and libxml2. So, maintaining a Python base, it is very fast HTML parsing and XML library. To let it work – C libraries also need to be installed. For installation instruction, follow this link. Command to install – sudo apt-get install python-lxml or pip install lxml What is lxml?It is designed specifically for parsing HTML and therefore comes with an html module. HTML string can be easily parsed with the help of fromstring() function. This will return the list of all the links. The iterlinks() method has four parameters of tuple form – element : Link is extracted from this parsed node of the anchor tag. If interested in the link only, this can be ignored.attr : attribute of the link from where it has come from, that is simply ‘href’link : The actual URL extracted from the anchor tag.pos : The anchor tag numeric index of the anchor tag in the document. # importing libraryfrom lxml import htmlstring_document = html.fromstring('hi <a href ="/world">geeks</a>') # actual urllink = list(string_document.iterlinks()) # Link lengthprint ("Length of the link : ", len(link) Output : Length of the link : 1 Code #2 : Retrieving the iterlinks() tuple (element, attribute, link, pos) = link[0] print ("attribute : ", attribute)print ("\nlink : ", link)print ("\nposition : ", position) Output : attribute : 'href' link : '/world' position : 0 ElementTree is built up when lxml parses the HTML. ElementTree is a tree structure having parent and child nodes. Each node in the tree is representing an HTML tag and it contains all the relative attributes of the tag. A tree after its creation can be iterated on to find elements. These elements can be an anchor or link tag. While the lxml.html module contains only HTML-specific functions for creating and iterating a tree, lxml.etree module contains the core tree handling code. Instead of using fromstring() function to parse an HTML, parse() function can be called with the filename or the URL – like html.parse('http://the/url') or html.parse('/path/to/filename'). Same result will be generated as loaded in the URL or file as in the string and then call fromstring(). Code #3 : ElementTree working import requestsimport lxml.html # requesting urlweb_response = requests.get('https://www.geeksforgeeks.org/') # buildingelement_tree = lxml.html.fromstring(web_response.text) tree_title_element = element_tree.xpath('//title')[0] print("Tag title : ", tree_title_element.tag)print("\nText title :", tree_title_element.text_content())print("\nhtml title :", lxml.html.tostring(tree_title_element))print("\ntitle tag:", tree_title_element.tag)print("\nParent's tag title:", tree_title_element.getparent().tag) Output : Tag title : title Text title : GeeksforGeeks | A computer science portal for geeks html title : b'GeeksforGeeks | A computer science portal for geeks\r\n' title tag: title Parent's tag title: head request is a Python library, used to scrap the website. It requests the URL of the webserver using get() method with URL as a parameter and in return, it gives the Response object. This object will include details about the request and the response. To read the web content, response.text() method is used. This content is sent back by the webserver under the request. Code #4 : Requesting web server import requests web_response = requests.get('https://www.geeksforgeeks.org/')print("Response from web server : \n", web_response.text) Output :It will generate a huge script, of which only a sample is added here. Response from web server : <!DOCTYPE html> <!--[if IE 7]> <html class="ie ie7" lang="en-US" prefix="og: http://ogp.me/ns#"> <![endif]--> <<!--> <html lang="en-US" prefix="og: http://ogp.me/ns#" > ... ... ... Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Create a Pandas DataFrame from Lists
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Jul, 2019" }, { "code": null, "e": 371, "s": 28, "text": "Link extraction is a very common task when dealing with the HTML parsing. For every general web crawler that’s the most important function to perform. Out of all the Python libraries present out there, lxml is one of the best to work with. As explained in this article, lxml provides a number of helper function in order to extract the links." }, { "code": null, "e": 391, "s": 371, "text": "lxml installation –" }, { "code": null, "e": 634, "s": 391, "text": "It is a Python binding for C libraries – libxslt and libxml2. So, maintaining a Python base, it is very fast HTML parsing and XML library. To let it work – C libraries also need to be installed. For installation instruction, follow this link." }, { "code": null, "e": 655, "s": 634, "text": "Command to install –" }, { "code": null, "e": 708, "s": 655, "text": "sudo apt-get install python-lxml or\npip install lxml" }, { "code": null, "e": 924, "s": 708, "text": "What is lxml?It is designed specifically for parsing HTML and therefore comes with an html module. HTML string can be easily parsed with the help of fromstring() function. This will return the list of all the links." }, { "code": null, "e": 983, "s": 924, "text": "The iterlinks() method has four parameters of tuple form –" }, { "code": null, "e": 1305, "s": 983, "text": "element : Link is extracted from this parsed node of the anchor tag. If interested in the link only, this can be ignored.attr : attribute of the link from where it has come from, that is simply ‘href’link : The actual URL extracted from the anchor tag.pos : The anchor tag numeric index of the anchor tag in the document." }, { "code": "# importing libraryfrom lxml import htmlstring_document = html.fromstring('hi <a href =\"/world\">geeks</a>') # actual urllink = list(string_document.iterlinks()) # Link lengthprint (\"Length of the link : \", len(link)", "e": 1523, "s": 1305, "text": null }, { "code": null, "e": 1532, "s": 1523, "text": "Output :" }, { "code": null, "e": 1556, "s": 1532, "text": "Length of the link : 1\n" }, { "code": null, "e": 1599, "s": 1556, "text": "Code #2 : Retrieving the iterlinks() tuple" }, { "code": "(element, attribute, link, pos) = link[0] print (\"attribute : \", attribute)print (\"\\nlink : \", link)print (\"\\nposition : \", position)", "e": 1738, "s": 1599, "text": null }, { "code": null, "e": 1747, "s": 1738, "text": "Output :" }, { "code": null, "e": 1798, "s": 1747, "text": "attribute : 'href'\n\nlink : '/world'\n\nposition : 0\n" }, { "code": null, "e": 2282, "s": 1798, "text": "ElementTree is built up when lxml parses the HTML. ElementTree is a tree structure having parent and child nodes. Each node in the tree is representing an HTML tag and it contains all the relative attributes of the tag. A tree after its creation can be iterated on to find elements. These elements can be an anchor or link tag. While the lxml.html module contains only HTML-specific functions for creating and iterating a tree, lxml.etree module contains the core tree handling code." }, { "code": null, "e": 2575, "s": 2282, "text": "Instead of using fromstring() function to parse an HTML, parse() function can be called with the filename or the URL – like html.parse('http://the/url') or html.parse('/path/to/filename'). Same result will be generated as loaded in the URL or file as in the string and then call fromstring()." }, { "code": null, "e": 2605, "s": 2575, "text": "Code #3 : ElementTree working" }, { "code": "import requestsimport lxml.html # requesting urlweb_response = requests.get('https://www.geeksforgeeks.org/') # buildingelement_tree = lxml.html.fromstring(web_response.text) tree_title_element = element_tree.xpath('//title')[0] print(\"Tag title : \", tree_title_element.tag)print(\"\\nText title :\", tree_title_element.text_content())print(\"\\nhtml title :\", lxml.html.tostring(tree_title_element))print(\"\\ntitle tag:\", tree_title_element.tag)print(\"\\nParent's tag title:\", tree_title_element.getparent().tag)", "e": 3116, "s": 2605, "text": null }, { "code": null, "e": 3125, "s": 3116, "text": "Output :" }, { "code": null, "e": 3327, "s": 3125, "text": "Tag title : title\n\nText title : GeeksforGeeks | A computer science portal for geeks\n\nhtml title : b'GeeksforGeeks | A computer science portal for geeks\\r\\n'\n\ntitle tag: title\n\nParent's tag title: head" }, { "code": null, "e": 3696, "s": 3327, "text": "request is a Python library, used to scrap the website. It requests the URL of the webserver using get() method with URL as a parameter and in return, it gives the Response object. This object will include details about the request and the response. To read the web content, response.text() method is used. This content is sent back by the webserver under the request." }, { "code": null, "e": 3728, "s": 3696, "text": "Code #4 : Requesting web server" }, { "code": "import requests web_response = requests.get('https://www.geeksforgeeks.org/')print(\"Response from web server : \\n\", web_response.text)", "e": 3864, "s": 3728, "text": null }, { "code": null, "e": 3942, "s": 3864, "text": "Output :It will generate a huge script, of which only a sample is added here." }, { "code": null, "e": 4153, "s": 3942, "text": "Response from web server : \n\n<!DOCTYPE html>\n<!--[if IE 7]>\n<html class=\"ie ie7\" lang=\"en-US\" prefix=\"og: http://ogp.me/ns#\">\n<![endif]-->\n<<!-->\n<html lang=\"en-US\" prefix=\"og: http://ogp.me/ns#\" >\n...\n...\n...\n" }, { "code": null, "e": 4160, "s": 4153, "text": "Python" }, { "code": null, "e": 4258, "s": 4160, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4276, "s": 4258, "text": "Python Dictionary" }, { "code": null, "e": 4318, "s": 4276, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4340, "s": 4318, "text": "Enumerate() in Python" }, { "code": null, "e": 4366, "s": 4340, "text": "Python String | replace()" }, { "code": null, "e": 4398, "s": 4366, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4427, "s": 4398, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4454, "s": 4427, "text": "Python Classes and Objects" }, { "code": null, "e": 4475, "s": 4454, "text": "Python OOPs Concepts" }, { "code": null, "e": 4498, "s": 4475, "text": "Introduction To PYTHON" } ]
NLP | WuPalmer – WordNet Similarity
20 Jun, 2021 How Wu & Palmer Similarity works ? It calculates relatedness by considering the depths of the two synsets in the WordNet taxonomies, along with the depth of the LCS (Least Common Subsumer). The score can be 0 < score <= 1. The score can never be zero because the depth of the LCS is never zero (the depth of the root of taxonomy is one). It calculates the similarity based on how similar the word senses are and where the Synsets occur relative to each other in the hypernym tree. Code #1 : Introducing Synsets Python3 from nltk.corpus import wordnet syn1 = wordnet.synsets('hello')[0]syn2 = wordnet.synsets('selling')[0] print ("hello name : ", syn1.name())print ("selling name : ", syn2.name()) Output : hello name : hello.n.01 selling name : selling.n.01 Code #2 : Wu Similarity Python3 syn1.wup_similarity(syn2) Output : 0.26666666666666666 hello and selling are apparently 27% similar! This is because they share common hypernyms further up the two. Code #3 : Let’s check the hypernyms in between. Python3 sorted(syn1.common_hypernyms(syn2)) Output : [Synset('abstraction.n.06'), Synset('entity.n.01')] One of the core metrics used to calculate similarity is the shortest path the distance between the two Synsets and their common hypernym. Code #4 : Let’s understand the use of hypernerm. Python3 ref = syn1.hypernyms()[0]print ("Self comparison : ", syn1.shortest_path_distance(ref)) print ("Distance of hello from greeting : ", syn1.shortest_path_distance(syn2)) print ("Distance of greeting from hello : ", syn2.shortest_path_distance(syn1)) Output : Self comparison : 1 Distance of hello from greeting : 11 Distance of greeting from hello : 11 Note : The similarity score is very high i.e. they are many steps away from each other because they are not so similar. The codes mentioned here uses ‘noun’ but one can use any Part of Speech (POS). surindertarika1234 Natural-language-processing Python-nltk Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Decision Tree Introduction with example Search Algorithms in AI Getting started with Machine Learning Introduction to Recurrent Neural Network Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas Python Dictionary How to get column names in Pandas dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Jun, 2021" }, { "code": null, "e": 220, "s": 28, "text": "How Wu & Palmer Similarity works ? It calculates relatedness by considering the depths of the two synsets in the WordNet taxonomies, along with the depth of the LCS (Least Common Subsumer). " }, { "code": null, "e": 543, "s": 220, "text": "The score can be 0 < score <= 1. The score can never be zero because the depth of the LCS is never zero (the depth of the root of taxonomy is one). It calculates the similarity based on how similar the word senses are and where the Synsets occur relative to each other in the hypernym tree. Code #1 : Introducing Synsets " }, { "code": null, "e": 551, "s": 543, "text": "Python3" }, { "code": "from nltk.corpus import wordnet syn1 = wordnet.synsets('hello')[0]syn2 = wordnet.synsets('selling')[0] print (\"hello name : \", syn1.name())print (\"selling name : \", syn2.name())", "e": 731, "s": 551, "text": null }, { "code": null, "e": 742, "s": 731, "text": "Output : " }, { "code": null, "e": 798, "s": 742, "text": "hello name : hello.n.01\nselling name : selling.n.01" }, { "code": null, "e": 826, "s": 798, "text": " Code #2 : Wu Similarity " }, { "code": null, "e": 834, "s": 826, "text": "Python3" }, { "code": "syn1.wup_similarity(syn2)", "e": 860, "s": 834, "text": null }, { "code": null, "e": 871, "s": 860, "text": "Output : " }, { "code": null, "e": 891, "s": 871, "text": "0.26666666666666666" }, { "code": null, "e": 1053, "s": 891, "text": "hello and selling are apparently 27% similar! This is because they share common hypernyms further up the two. Code #3 : Let’s check the hypernyms in between. " }, { "code": null, "e": 1061, "s": 1053, "text": "Python3" }, { "code": "sorted(syn1.common_hypernyms(syn2))", "e": 1097, "s": 1061, "text": null }, { "code": null, "e": 1108, "s": 1097, "text": "Output : " }, { "code": null, "e": 1160, "s": 1108, "text": "[Synset('abstraction.n.06'), Synset('entity.n.01')]" }, { "code": null, "e": 1351, "s": 1160, "text": "One of the core metrics used to calculate similarity is the shortest path the distance between the two Synsets and their common hypernym. Code #4 : Let’s understand the use of hypernerm. " }, { "code": null, "e": 1359, "s": 1351, "text": "Python3" }, { "code": "ref = syn1.hypernyms()[0]print (\"Self comparison : \", syn1.shortest_path_distance(ref)) print (\"Distance of hello from greeting : \", syn1.shortest_path_distance(syn2)) print (\"Distance of greeting from hello : \", syn2.shortest_path_distance(syn1))", "e": 1625, "s": 1359, "text": null }, { "code": null, "e": 1636, "s": 1625, "text": "Output : " }, { "code": null, "e": 1733, "s": 1636, "text": "Self comparison : 1\nDistance of hello from greeting : 11\nDistance of greeting from hello : 11" }, { "code": null, "e": 1933, "s": 1733, "text": "Note : The similarity score is very high i.e. they are many steps away from each other because they are not so similar. The codes mentioned here uses ‘noun’ but one can use any Part of Speech (POS). " }, { "code": null, "e": 1952, "s": 1933, "text": "surindertarika1234" }, { "code": null, "e": 1980, "s": 1952, "text": "Natural-language-processing" }, { "code": null, "e": 1992, "s": 1980, "text": "Python-nltk" }, { "code": null, "e": 2009, "s": 1992, "text": "Machine Learning" }, { "code": null, "e": 2016, "s": 2009, "text": "Python" }, { "code": null, "e": 2033, "s": 2016, "text": "Machine Learning" }, { "code": null, "e": 2131, "s": 2033, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2154, "s": 2131, "text": "ML | Linear Regression" }, { "code": null, "e": 2194, "s": 2154, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 2218, "s": 2194, "text": "Search Algorithms in AI" }, { "code": null, "e": 2256, "s": 2218, "text": "Getting started with Machine Learning" }, { "code": null, "e": 2297, "s": 2256, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 2325, "s": 2297, "text": "Read JSON file using Python" }, { "code": null, "e": 2347, "s": 2325, "text": "Python map() function" }, { "code": null, "e": 2397, "s": 2347, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 2415, "s": 2397, "text": "Python Dictionary" } ]
Show and hide password using JavaScript
19 Feb, 2019 While filling up a form, there comes a situation where we type a password and want to see what we have typed till now. To see that, there is a checkbox clicking on which makes the characters visible.In this post, this feature i.e. toggling password is implemented using JavaScript. Algorithm1)Create a HTML form which contain an input field of type password. 2)Create a checkbox which will be responsible for toggling. 3)Create a function which will response for toggling when a user clicks on the checkbox. Examples: Password is geeksforgeeks.So, on typing it will show like this *************And on clicking the checkbox it will show the characters: geeksforgeeks. <!DOCTYPE html><html><body> <b><p>Click on the checkbox to show or hide password: </p></b> <b>Password</b>: <input type="password" value="geeksforgeeks" id="typepass"> <input type="checkbox" onclick="Toggle()"> <b>Show Password</b> <script> // Change the type of input to password or text function Toggle() { var temp = document.getElementById("typepass"); if (temp.type === "password") { temp.type = "text"; } else { temp.type = "password"; } }</script></body></html> Output: Hide password: Show password: JavaScript-Misc 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 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Feb, 2019" }, { "code": null, "e": 334, "s": 52, "text": "While filling up a form, there comes a situation where we type a password and want to see what we have typed till now. To see that, there is a checkbox clicking on which makes the characters visible.In this post, this feature i.e. toggling password is implemented using JavaScript." }, { "code": null, "e": 411, "s": 334, "text": "Algorithm1)Create a HTML form which contain an input field of type password." }, { "code": null, "e": 471, "s": 411, "text": "2)Create a checkbox which will be responsible for toggling." }, { "code": null, "e": 560, "s": 471, "text": "3)Create a function which will response for toggling when a user clicks on the checkbox." }, { "code": null, "e": 570, "s": 560, "text": "Examples:" }, { "code": null, "e": 719, "s": 570, "text": "Password is geeksforgeeks.So, on typing it will show like this *************And on clicking the checkbox it will show the characters: geeksforgeeks." }, { "code": "<!DOCTYPE html><html><body> <b><p>Click on the checkbox to show or hide password: </p></b> <b>Password</b>: <input type=\"password\" value=\"geeksforgeeks\" id=\"typepass\"> <input type=\"checkbox\" onclick=\"Toggle()\"> <b>Show Password</b> <script> // Change the type of input to password or text function Toggle() { var temp = document.getElementById(\"typepass\"); if (temp.type === \"password\") { temp.type = \"text\"; } else { temp.type = \"password\"; } }</script></body></html>", "e": 1320, "s": 719, "text": null }, { "code": null, "e": 1328, "s": 1320, "text": "Output:" }, { "code": null, "e": 1343, "s": 1328, "text": "Hide password:" }, { "code": null, "e": 1358, "s": 1343, "text": "Show password:" }, { "code": null, "e": 1374, "s": 1358, "text": "JavaScript-Misc" }, { "code": null, "e": 1385, "s": 1374, "text": "JavaScript" }, { "code": null, "e": 1402, "s": 1385, "text": "Web Technologies" }, { "code": null, "e": 1500, "s": 1402, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1561, "s": 1500, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1633, "s": 1561, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 1673, "s": 1633, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 1714, "s": 1673, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 1756, "s": 1714, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 1789, "s": 1756, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1851, "s": 1789, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1912, "s": 1851, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1962, "s": 1912, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
PHP | ob_start() Function
08 Mar, 2018 Let’s take a quick recap. PHP is an interpreted language thus each statement is executed one after another, therefore PHP tends to send HTML to browsers in chunks thus reducing performance. Using output buffering the generated HTML gets stored in a buffer or a string variable and is sent to the buffer to render after the execution of the last statement in the PHP script. But Output Buffering is not enabled by default. In order to enable the Output Buffering one must use the ob_start() function before any echoing any HTML content in a script. Syntax: bool ob_start () Parameters: The function can accept a bunch of optional parameters as follows: Callback function: This is an optional parameter that expects a function that takes the contents of the output buffer and returns a string that is to be sent to the browser for rendering. The callback function is generally used for compressing the HTML content. Chunk size: This is another optional parameter that sets the output buffer size of provided size and outputs as soon as the buffer is either full or exceeded. Flags: This is another optional parameter that accepts a bitmask to control the operations that can be implemented on the output buffer. This parameter is passed to restrict access. The Default permissions gives access to clean, flush and removal of the buffer. Return Type: This function returns TRUE on success otherwise FALSE. Below program illustrates the working of ob_start() in PHP: <?php // PHP code to illustrate the working// of ob_start() Function function callback($buffer){ // Return Everything in CAPS. return (strtoupper($buffer));} ob_start("callback");echo "Hello Geek!";ob_end_flush(); ?> Output: HELLO GEEK! Important points to note: Enables Output Buffering. Output Buffering flags can be of four types PHP_OUTPUT_HANDLER_CLEANABLE(only clean), PHP_OUTPUT_HANDLER_FLUSHABLE(only flush), PHP_OUTPUT_HANDLER_REMOVABLE(only remove), PHP_OUTPUT_HANDLER_STDFLAGS(allowed every operation). Output buffers are stackable, thus nested ob_start() methods are allowed and works as desired if they are closed/flushed sequentially. Reference:http://php.net/manual/en/function.ob-start.php PHP-function PHP-input-output PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Mar, 2018" }, { "code": null, "e": 428, "s": 54, "text": "Let’s take a quick recap. PHP is an interpreted language thus each statement is executed one after another, therefore PHP tends to send HTML to browsers in chunks thus reducing performance. Using output buffering the generated HTML gets stored in a buffer or a string variable and is sent to the buffer to render after the execution of the last statement in the PHP script." }, { "code": null, "e": 602, "s": 428, "text": "But Output Buffering is not enabled by default. In order to enable the Output Buffering one must use the ob_start() function before any echoing any HTML content in a script." }, { "code": null, "e": 610, "s": 602, "text": "Syntax:" }, { "code": null, "e": 628, "s": 610, "text": "bool ob_start ()\n" }, { "code": null, "e": 707, "s": 628, "text": "Parameters: The function can accept a bunch of optional parameters as follows:" }, { "code": null, "e": 969, "s": 707, "text": "Callback function: This is an optional parameter that expects a function that takes the contents of the output buffer and returns a string that is to be sent to the browser for rendering. The callback function is generally used for compressing the HTML content." }, { "code": null, "e": 1128, "s": 969, "text": "Chunk size: This is another optional parameter that sets the output buffer size of provided size and outputs as soon as the buffer is either full or exceeded." }, { "code": null, "e": 1390, "s": 1128, "text": "Flags: This is another optional parameter that accepts a bitmask to control the operations that can be implemented on the output buffer. This parameter is passed to restrict access. The Default permissions gives access to clean, flush and removal of the buffer." }, { "code": null, "e": 1458, "s": 1390, "text": "Return Type: This function returns TRUE on success otherwise FALSE." }, { "code": null, "e": 1518, "s": 1458, "text": "Below program illustrates the working of ob_start() in PHP:" }, { "code": "<?php // PHP code to illustrate the working// of ob_start() Function function callback($buffer){ // Return Everything in CAPS. return (strtoupper($buffer));} ob_start(\"callback\");echo \"Hello Geek!\";ob_end_flush(); ?>", "e": 1747, "s": 1518, "text": null }, { "code": null, "e": 1755, "s": 1747, "text": "Output:" }, { "code": null, "e": 1768, "s": 1755, "text": "HELLO GEEK!\n" }, { "code": null, "e": 1794, "s": 1768, "text": "Important points to note:" }, { "code": null, "e": 1820, "s": 1794, "text": "Enables Output Buffering." }, { "code": null, "e": 2045, "s": 1820, "text": "Output Buffering flags can be of four types PHP_OUTPUT_HANDLER_CLEANABLE(only clean), PHP_OUTPUT_HANDLER_FLUSHABLE(only flush), PHP_OUTPUT_HANDLER_REMOVABLE(only remove), PHP_OUTPUT_HANDLER_STDFLAGS(allowed every operation)." }, { "code": null, "e": 2180, "s": 2045, "text": "Output buffers are stackable, thus nested ob_start() methods are allowed and works as desired if they are closed/flushed sequentially." }, { "code": null, "e": 2237, "s": 2180, "text": "Reference:http://php.net/manual/en/function.ob-start.php" }, { "code": null, "e": 2250, "s": 2237, "text": "PHP-function" }, { "code": null, "e": 2267, "s": 2250, "text": "PHP-input-output" }, { "code": null, "e": 2271, "s": 2267, "text": "PHP" }, { "code": null, "e": 2288, "s": 2271, "text": "Web Technologies" }, { "code": null, "e": 2292, "s": 2288, "text": "PHP" } ]
FOLLOW Set in Syntax Analysis
08 Apr, 2022 We have discussed the following topics on Syntax Analysis. Introduction to Syntax Analysis Why FIRST and FOLLOW? FIRST Set in Syntax Analysis In this post, FOLLOW Set is discussed. Follow(X) to be the set of terminals that can appear immediately to the right of Non-Terminal X in some sentential form. Example: S ->Aa | Ac A ->b S S / \ / \ A a A C | | b b Here, FOLLOW (A) = {a, c} Rules to compute FOLLOW set: 1) FOLLOW(S) = { $ } // where S is the starting Non-Terminal 2) If A -> pBq is a production, where p, B and q are any grammar symbols, then everything in FIRST(q) except Є is in FOLLOW(B). 3) If A->pB is a production, then everything in FOLLOW(A) is in FOLLOW(B). 4) If A->pBq is a production and FIRST(q) contains Є, then FOLLOW(B) contains { FIRST(q) – Є } U FOLLOW(A) Example 1: Production Rules: E -> TE’ E’ -> +T E’|Є T -> F T’ T’ -> *F T’ | Є F -> (E) | id FIRST set FIRST(E) = FIRST(T) = { ( , id } FIRST(E’) = { +, Є } FIRST(T) = FIRST(F) = { ( , id } FIRST(T’) = { *, Є } FIRST(F) = { ( , id } FOLLOW Set FOLLOW(E) = { $ , ) } // Note ')' is there because of 5th rule FOLLOW(E’) = FOLLOW(E) = { $, ) } // See 1st production rule FOLLOW(T) = { FIRST(E’) – Є } U FOLLOW(E’) U FOLLOW(E) = { + , $ , ) } FOLLOW(T’) = FOLLOW(T) = { + , $ , ) } FOLLOW(F) = { FIRST(T’) – Є } U FOLLOW(T’) U FOLLOW(T) = { *, +, $, ) } Example 2: Production Rules: S -> aBDh B -> cC C -> bC | Є D -> EF E -> g | Є F -> f | Є FIRST set FIRST(S) = { a } FIRST(B) = { c } FIRST(C) = { b , Є } FIRST(D) = FIRST(E) U FIRST(F) = { g, f, Є } FIRST(E) = { g , Є } FIRST(F) = { f , Є } FOLLOW Set FOLLOW(S) = { $ } FOLLOW(B) = { FIRST(D) – Є } U FIRST(h) = { g , f , h } FOLLOW(C) = FOLLOW(B) = { g , f , h } FOLLOW(D) = FIRST(h) = { h } FOLLOW(E) = { FIRST(F) – Є } U FOLLOW(D) = { f , h } FOLLOW(F) = FOLLOW(D) = { h } Example 3: Production Rules: S -> ACB|Cbb|Ba A -> da|BC B-> g|Є C-> h| Є FIRST set FIRST(S) = FIRST(A) U FIRST(B) U FIRST(C) = { d, g, h, Є, b, a} FIRST(A) = { d } U {FIRST(B)-Є} U FIRST(C) = { d, g, h, Є } FIRST(B) = { g, Є } FIRST(C) = { h, Є } FOLLOW Set FOLLOW(S) = { $ } FOLLOW(A) = { h, g, $ } FOLLOW(B) = { a, $, h, g } FOLLOW(C) = { b, g, $, h } Note : Є as a FOLLOW doesn’t mean anything (Є is an empty string).$ is called end-marker, which represents the end of the input string, hence used while parsing to indicate that the input string has been completely processed.The grammar used above is Context-Free Grammar (CFG). The syntax of a programming language can be specified using CFG.CFG is of the form A -> B, where A is a single Non-Terminal, and B can be a set of grammar symbols ( i.e. Terminals as well as Non-Terminals) Є as a FOLLOW doesn’t mean anything (Є is an empty string). $ is called end-marker, which represents the end of the input string, hence used while parsing to indicate that the input string has been completely processed. The grammar used above is Context-Free Grammar (CFG). The syntax of a programming language can be specified using CFG. CFG is of the form A -> B, where A is a single Non-Terminal, and B can be a set of grammar symbols ( i.e. Terminals as well as Non-Terminals) Ahnaf Prince SomShekharMukherjee ashutosh450 sachinsinghbisht5 rohit_kumar_01 yugambhattania viditsirohi Compiler Design GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Apr, 2022" }, { "code": null, "e": 114, "s": 54, "text": "We have discussed the following topics on Syntax Analysis. " }, { "code": null, "e": 198, "s": 114, "text": "Introduction to Syntax Analysis Why FIRST and FOLLOW? FIRST Set in Syntax Analysis " }, { "code": null, "e": 238, "s": 198, "text": "In this post, FOLLOW Set is discussed. " }, { "code": null, "e": 369, "s": 238, "text": "Follow(X) to be the set of terminals that can appear immediately to the right of Non-Terminal X in some sentential form. Example: " }, { "code": null, "e": 558, "s": 369, "text": "S ->Aa | Ac\nA ->b \n\n S S \n / \\ / \\\n A a A C \n | |\n b b \n\nHere, FOLLOW (A) = {a, c}" }, { "code": null, "e": 588, "s": 558, "text": "Rules to compute FOLLOW set: " }, { "code": null, "e": 973, "s": 588, "text": "1) FOLLOW(S) = { $ } // where S is the starting Non-Terminal\n\n2) If A -> pBq is a production, where p, B and q are any grammar symbols,\n then everything in FIRST(q) except Є is in FOLLOW(B).\n\n3) If A->pB is a production, then everything in FOLLOW(A) is in FOLLOW(B).\n\n4) If A->pBq is a production and FIRST(q) contains Є, \n then FOLLOW(B) contains { FIRST(q) – Є } U FOLLOW(A) " }, { "code": null, "e": 985, "s": 973, "text": "Example 1: " }, { "code": null, "e": 1538, "s": 985, "text": "Production Rules:\nE -> TE’\nE’ -> +T E’|Є\nT -> F T’\nT’ -> *F T’ | Є\nF -> (E) | id\n\nFIRST set\nFIRST(E) = FIRST(T) = { ( , id }\nFIRST(E’) = { +, Є }\nFIRST(T) = FIRST(F) = { ( , id }\nFIRST(T’) = { *, Є }\nFIRST(F) = { ( , id }\n\nFOLLOW Set\nFOLLOW(E) = { $ , ) } // Note ')' is there because of 5th rule\nFOLLOW(E’) = FOLLOW(E) = { $, ) } // See 1st production rule\nFOLLOW(T) = { FIRST(E’) – Є } U FOLLOW(E’) U FOLLOW(E) = { + , $ , ) }\nFOLLOW(T’) = FOLLOW(T) = { + , $ , ) }\nFOLLOW(F) = { FIRST(T’) – Є } U FOLLOW(T’) U FOLLOW(T) = { *, +, $, ) }" }, { "code": null, "e": 1550, "s": 1538, "text": "Example 2: " }, { "code": null, "e": 2019, "s": 1550, "text": "Production Rules:\nS -> aBDh\nB -> cC\nC -> bC | Є\nD -> EF\nE -> g | Є\nF -> f | Є\n\nFIRST set\nFIRST(S) = { a }\nFIRST(B) = { c }\nFIRST(C) = { b , Є }\nFIRST(D) = FIRST(E) U FIRST(F) = { g, f, Є }\nFIRST(E) = { g , Є }\nFIRST(F) = { f , Є }\n\nFOLLOW Set\nFOLLOW(S) = { $ } \nFOLLOW(B) = { FIRST(D) – Є } U FIRST(h) = { g , f , h }\nFOLLOW(C) = FOLLOW(B) = { g , f , h }\nFOLLOW(D) = FIRST(h) = { h }\nFOLLOW(E) = { FIRST(F) – Є } U FOLLOW(D) = { f , h }\nFOLLOW(F) = FOLLOW(D) = { h } " }, { "code": null, "e": 2032, "s": 2019, "text": "Example 3: " }, { "code": null, "e": 2378, "s": 2032, "text": "Production Rules:\nS -> ACB|Cbb|Ba\nA -> da|BC\nB-> g|Є\nC-> h| Є\n\nFIRST set\nFIRST(S) = FIRST(A) U FIRST(B) U FIRST(C) = { d, g, h, Є, b, a}\nFIRST(A) = { d } U {FIRST(B)-Є} U FIRST(C) = { d, g, h, Є }\nFIRST(B) = { g, Є }\nFIRST(C) = { h, Є }\n\nFOLLOW Set\nFOLLOW(S) = { $ }\nFOLLOW(A) = { h, g, $ }\nFOLLOW(B) = { a, $, h, g }\nFOLLOW(C) = { b, g, $, h }" }, { "code": null, "e": 2385, "s": 2378, "text": "Note :" }, { "code": null, "e": 2863, "s": 2385, "text": "Є as a FOLLOW doesn’t mean anything (Є is an empty string).$ is called end-marker, which represents the end of the input string, hence used while parsing to indicate that the input string has been completely processed.The grammar used above is Context-Free Grammar (CFG). The syntax of a programming language can be specified using CFG.CFG is of the form A -> B, where A is a single Non-Terminal, and B can be a set of grammar symbols ( i.e. Terminals as well as Non-Terminals)" }, { "code": null, "e": 2923, "s": 2863, "text": "Є as a FOLLOW doesn’t mean anything (Є is an empty string)." }, { "code": null, "e": 3083, "s": 2923, "text": "$ is called end-marker, which represents the end of the input string, hence used while parsing to indicate that the input string has been completely processed." }, { "code": null, "e": 3202, "s": 3083, "text": "The grammar used above is Context-Free Grammar (CFG). The syntax of a programming language can be specified using CFG." }, { "code": null, "e": 3344, "s": 3202, "text": "CFG is of the form A -> B, where A is a single Non-Terminal, and B can be a set of grammar symbols ( i.e. Terminals as well as Non-Terminals)" }, { "code": null, "e": 3357, "s": 3344, "text": "Ahnaf Prince" }, { "code": null, "e": 3377, "s": 3357, "text": "SomShekharMukherjee" }, { "code": null, "e": 3389, "s": 3377, "text": "ashutosh450" }, { "code": null, "e": 3407, "s": 3389, "text": "sachinsinghbisht5" }, { "code": null, "e": 3422, "s": 3407, "text": "rohit_kumar_01" }, { "code": null, "e": 3437, "s": 3422, "text": "yugambhattania" }, { "code": null, "e": 3449, "s": 3437, "text": "viditsirohi" }, { "code": null, "e": 3465, "s": 3449, "text": "Compiler Design" }, { "code": null, "e": 3473, "s": 3465, "text": "GATE CS" } ]
Flatten a multilevel linked list
20 Jun, 2022 Given a linked list where in addition to the next pointer, each node has a child pointer, which may or may not point to a separate list. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure, as shown in below figure. You are given the head of the first level of the list. Flatten the list so that all the nodes appear in a single-level linked list. You need to flatten the list in way that all nodes at the first level should come first, then nodes of second level, and so on.Each node is a C struct with the following definition. C Java Python3 C# Javascript struct List{ int data; struct List *next; struct List *child;}; static class List{ public int data; public List next; public List child;}; // This code is contributed by pratham76 # A linked list node has data,# next pointer and child pointerclass Node: def __init__(self, data): self.data = data self.next = None self.child = None # This code contributed by umadevi9616 static class List{ public int data; public List next; public List child;}; // This code is contributed by rutvik_56 <script>class List{ constructor(){ this.data = 0; this.next = null; this.child = null; } }// This code contributed by aashish1995</script> The above list should be converted to 10->5->12->7->11->4->20->13->17->6->2->16->9->8->3->19->15 The problem clearly say that we need to flatten level by level. The idea of solution is, we start from first level, process all nodes one by one, if a node has a child, then we append the child at the end of list, otherwise we don’t do anything. After the first level is processed, all next level nodes will be appended after first level. Same process is followed for the appended nodes. 1) Take "cur" pointer, which will point to head of the first level of the list 2) Take "tail" pointer, which will point to end of the first level of the list 3) Repeat the below procedure while "curr" is not NULL. I) if current node has a child then a) append this new child list to the "tail" tail->next = cur->child b) find the last node of new child list and update "tail" tmp = cur->child; while (tmp->next != NULL) tmp = tmp->next; tail = tmp; II) move to the next node. i.e. cur = cur->next Following is the implementation of the above algorithm. C++ C Java Python3 C# // C++ Program to flatten list with// next and child pointers#include <bits/stdc++.h>using namespace std; // Macro to find number of elements in array#define SIZE(arr) (sizeof(arr)/sizeof(arr[0])) // A linked list node has data,// next pointer and child pointerclass Node{ public: int data; Node *next; Node *child;}; // A utility function to create a linked list// with n nodes. The data of nodes is taken// from arr[]. All child pointers are set as NULLNode *createList(int *arr, int n){ Node *head = NULL; Node *p; int i; for (i = 0; i < n; ++i) { if (head == NULL) head = p = new Node(); else { p->next = new Node(); p = p->next; } p->data = arr[i]; p->next = p->child = NULL; } return head;} // A utility function to print// all nodes of a linked listvoid printList(Node *head){ while (head != NULL) { cout << head->data << " "; head = head->next; } cout<<endl;} // This function creates the input// list. The created list is same// as shown in the above figureNode *createList(void){ int arr1[] = {10, 5, 12, 7, 11}; int arr2[] = {4, 20, 13}; int arr3[] = {17, 6}; int arr4[] = {9, 8}; int arr5[] = {19, 15}; int arr6[] = {2}; int arr7[] = {16}; int arr8[] = {3}; /* create 8 linked lists */ Node *head1 = createList(arr1, SIZE(arr1)); Node *head2 = createList(arr2, SIZE(arr2)); Node *head3 = createList(arr3, SIZE(arr3)); Node *head4 = createList(arr4, SIZE(arr4)); Node *head5 = createList(arr5, SIZE(arr5)); Node *head6 = createList(arr6, SIZE(arr6)); Node *head7 = createList(arr7, SIZE(arr7)); Node *head8 = createList(arr8, SIZE(arr8)); /* modify child pointers to create the list shown above */ head1->child = head2; head1->next->next->next->child = head3; head3->child = head4; head4->child = head5; head2->next->child = head6; head2->next->next->child = head7; head7->child = head8; /* Return head pointer of first linked list. Note that all nodes are reachable from head1 */ return head1;} /* The main function that flattensa multilevel linked list */void flattenList(Node *head){ /*Base case*/ if (head == NULL) return; Node *tmp; /* Find tail node of first level linked list */ Node *tail = head; while (tail->next != NULL) tail = tail->next; // One by one traverse through all nodes of first level // linked list till we reach the tail node Node *cur = head; while (cur != tail) { // If current node has a child if (cur->child) { // then append the child at the end of current list tail->next = cur->child; // and update the tail to new last node tmp = cur->child; while (tmp->next) tmp = tmp->next; tail = tmp; } // Change current node cur = cur->next; }} // Driver codeint main(void){ Node *head = NULL; head = createList(); flattenList(head); printList(head); return 0;} // This code is contributed by rathbhupendra // Program to flatten list with next and child pointers#include <stdio.h>#include <stdlib.h> // Macro to find number of elements in array#define SIZE(arr) (sizeof(arr)/sizeof(arr[0])) // A linked list node has data, next pointer and child pointerstruct Node{ int data; struct Node *next; struct Node *child;}; // A utility function to create a linked list with n nodes. The data// of nodes is taken from arr[]. All child pointers are set as NULLstruct Node *createList(int *arr, int n){ struct Node *head = NULL; struct Node *p; int i; for (i = 0; i < n; ++i) { if (head == NULL) head = p = (struct Node *)malloc(sizeof(*p)); else { p->next = (struct Node *)malloc(sizeof(*p)); p = p->next; } p->data = arr[i]; p->next = p->child = NULL; } return head;} // A utility function to print all nodes of a linked listvoid printList(struct Node *head){ while (head != NULL) { printf("%d ", head->data); head = head->next; } printf("\n");} // This function creates the input list. The created list is same// as shown in the above figurestruct Node *createList(void){ int arr1[] = {10, 5, 12, 7, 11}; int arr2[] = {4, 20, 13}; int arr3[] = {17, 6}; int arr4[] = {9, 8}; int arr5[] = {19, 15}; int arr6[] = {2}; int arr7[] = {16}; int arr8[] = {3}; /* create 8 linked lists */ struct Node *head1 = createList(arr1, SIZE(arr1)); struct Node *head2 = createList(arr2, SIZE(arr2)); struct Node *head3 = createList(arr3, SIZE(arr3)); struct Node *head4 = createList(arr4, SIZE(arr4)); struct Node *head5 = createList(arr5, SIZE(arr5)); struct Node *head6 = createList(arr6, SIZE(arr6)); struct Node *head7 = createList(arr7, SIZE(arr7)); struct Node *head8 = createList(arr8, SIZE(arr8)); /* modify child pointers to create the list shown above */ head1->child = head2; head1->next->next->next->child = head3; head3->child = head4; head4->child = head5; head2->next->child = head6; head2->next->next->child = head7; head7->child = head8; /* Return head pointer of first linked list. Note that all nodes are reachable from head1 */ return head1;} /* The main function that flattens a multilevel linked list */void flattenList(struct Node *head){ /*Base case*/ if (head == NULL) return; struct Node *tmp; /* Find tail node of first level linked list */ struct Node *tail = head; while (tail->next != NULL) tail = tail->next; // One by one traverse through all nodes of first level // linked list till we reach the tail node struct Node *cur = head; while (cur != tail) { // If current node has a child if (cur->child) { // then append the child at the end of current list tail->next = cur->child; // and update the tail to new last node tmp = cur->child; while (tmp->next) tmp = tmp->next; tail = tmp; } // Change current node cur = cur->next; }} // A driver program to test above functionsint main(void){ struct Node *head = NULL; head = createList(); flattenList(head); printList(head); return 0;} // Java program to flatten linked list with next and child pointers class LinkedList { static Node head; class Node { int data; Node next, child; Node(int d) { data = d; next = child = null; } } // A utility function to create a linked list with n nodes. The data // of nodes is taken from arr[]. All child pointers are set as NULL Node createList(int arr[], int n) { Node node = null; Node p = null; int i; for (i = 0; i < n; ++i) { if (node == null) { node = p = new Node(arr[i]); } else { p.next = new Node(arr[i]); p = p.next; } p.next = p.child = null; } return node; } // A utility function to print all nodes of a linked list void printList(Node node) { while (node != null) { System.out.print(node.data + " "); node = node.next; } System.out.println(""); } Node createList() { int arr1[] = new int[]{10, 5, 12, 7, 11}; int arr2[] = new int[]{4, 20, 13}; int arr3[] = new int[]{17, 6}; int arr4[] = new int[]{9, 8}; int arr5[] = new int[]{19, 15}; int arr6[] = new int[]{2}; int arr7[] = new int[]{16}; int arr8[] = new int[]{3}; /* create 8 linked lists */ Node head1 = createList(arr1, arr1.length); Node head2 = createList(arr2, arr2.length); Node head3 = createList(arr3, arr3.length); Node head4 = createList(arr4, arr4.length); Node head5 = createList(arr5, arr5.length); Node head6 = createList(arr6, arr6.length); Node head7 = createList(arr7, arr7.length); Node head8 = createList(arr8, arr8.length); /* modify child pointers to create the list shown above */ head1.child = head2; head1.next.next.next.child = head3; head3.child = head4; head4.child = head5; head2.next.child = head6; head2.next.next.child = head7; head7.child = head8; /* Return head pointer of first linked list. Note that all nodes are reachable from head1 */ return head1; } /* The main function that flattens a multilevel linked list */ void flattenList(Node node) { /*Base case*/ if (node == null) { return; } Node tmp = null; /* Find tail node of first level linked list */ Node tail = node; while (tail.next != null) { tail = tail.next; } // One by one traverse through all nodes of first level // linked list till we reach the tail node Node cur = node; while (cur != tail) { // If current node has a child if (cur.child != null) { // then append the child at the end of current list tail.next = cur.child; // and update the tail to new last node tmp = cur.child; while (tmp.next != null) { tmp = tmp.next; } tail = tmp; } // Change current node cur = cur.next; } } public static void main(String[] args) { LinkedList list = new LinkedList(); head = list.createList(); list.flattenList(head); list.printList(head); }} // This code has been contributed by Mayank Jaiswal # Python3 Program to flatten list with# next and child pointers # A linked list node has data,# next pointer and child pointerclass Node: def __init__(self, data): self.data = data self.next = None self.child = None # Return Nodedef newNode(data): return Node(data) # The main function that flattens# a multilevel linked listdef flattenlist(head): # Base case if not head: return # Find tail node of first level linked list temp = head while(temp.next != None): temp = temp.next currNode = head # One by one traverse through all nodes # of first level linked list # till we reach the tail node while(currNode != temp): # If current node has a child if(currNode.child): # then append the child # at the end of current list temp.next = currNode.child # and update the tail to new last node tmp = currNode.child while(tmp.next): tmp = tmp.next temp = tmp # Change current node currNode = currNode.next # A utility function to print# all nodes of a linked listdef printList(head): if not head: return while(head): print("{}".format(head.data), end = " ") head = head.next # Driver codeif __name__=='__main__': # Child list of 13 child13 = newNode(16) child13.child = newNode(3) # Child List of 10 head1 = newNode(4) head1.next = newNode(20) head1.next.child = newNode(2) #Child of 20 head1.next.next = newNode(13) head1.next.next.child = child13 # Child of 9 child9 = newNode(19) child9.next = newNode(15) # Child List of 17 child17 = newNode(9) child17.next = newNode(8) child17.child = child9 # Child List of 7 head2 = newNode(17) head2.next = newNode(6) head2.child = child17 # Main List head = newNode(10) head.child = head1 head.next = newNode(5) head.next.next = newNode(12) head.next.next.next = newNode(7) head.next.next.next.child = head2 head.next.next.next.next = newNode(11) flattenlist(head) print("\Flattened list is: ", end = "") printList(head) # This code is contributed by 0_hero // C# program to flatten linked list// with next and child pointersusing System; public class LinkedList{ static Node head; class Node { public int data; public Node next, child; public Node(int d) { data = d; next = child = null; } } // A utility function to create // a linked list with n nodes. The data // of nodes is taken from arr[]. // All child pointers are set as NULL Node createList(int []arr, int n) { Node node = null; Node p = null; int i; for (i = 0; i < n; ++i) { if (node == null) { node = p = new Node(arr[i]); } else { p.next = new Node(arr[i]); p = p.next; } p.next = p.child = null; } return node; } // A utility function to print // all nodes of a linked list void printList(Node node) { while (node != null) { Console.Write(node.data + " "); node = node.next; } Console.WriteLine(""); } Node createList() { int []arr1 = new int[]{10, 5, 12, 7, 11}; int []arr2 = new int[]{4, 20, 13}; int []arr3 = new int[]{17, 6}; int []arr4 = new int[]{9, 8}; int []arr5 = new int[]{19, 15}; int []arr6 = new int[]{2}; int []arr7 = new int[]{16}; int []arr8 = new int[]{3}; /* create 8 linked lists */ Node head1 = createList(arr1, arr1.Length); Node head2 = createList(arr2, arr2.Length); Node head3 = createList(arr3, arr3.Length); Node head4 = createList(arr4, arr4.Length); Node head5 = createList(arr5, arr5.Length); Node head6 = createList(arr6, arr6.Length); Node head7 = createList(arr7, arr7.Length); Node head8 = createList(arr8, arr8.Length); /* modify child pointers to create the list shown above */ head1.child = head2; head1.next.next.next.child = head3; head3.child = head4; head4.child = head5; head2.next.child = head6; head2.next.next.child = head7; head7.child = head8; /* Return head pointer of first linked list. Note that all nodes are reachable from head1 */ return head1; } /* The main function that flattens a multilevel linked list */ void flattenList(Node node) { /*Base case*/ if (node == null) { return; } Node tmp = null; /* Find tail node of first level linked list */ Node tail = node; while (tail.next != null) { tail = tail.next; } // One by one traverse through // all nodes of first level // linked list till we reach the tail node Node cur = node; while (cur != tail) { // If current node has a child if (cur.child != null) { // then append the child at // the end of current list tail.next = cur.child; // and update the tail to new last node tmp = cur.child; while (tmp.next != null) { tmp = tmp.next; } tail = tmp; } // Change current node cur = cur.next; } } // Driver code public static void Main() { LinkedList list = new LinkedList(); head = list.createList(); list.flattenList(head); list.printList(head); }} /* This code is contributed PrinciRaj1992 */ 10 5 12 7 11 4 20 13 17 6 2 16 9 8 3 19 15 Time Complexity: Since every node is visited at most twice, the time complexity is O(n) where n is the number of nodes in given linked list. princiraj1992 rathbhupendra 0_hero rutvik_56 pratham76 aashish1995 umadevi9616 arorakashish0911 hardikkoriintern Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stack Data Structure (Introduction and Program) LinkedList in Java Introduction to Data Structures What is Data Structure: Types, Classifications and Applications Add two numbers represented by linked lists | Set 1 Implementing a Linked List in Java using Class Detect and Remove Loop in a Linked List Queue - Linked List Implementation Function to check if a singly linked list is palindrome Implement a stack using singly linked list
[ { "code": null, "e": 54, "s": 26, "text": "\n20 Jun, 2022" }, { "code": null, "e": 644, "s": 54, "text": "Given a linked list where in addition to the next pointer, each node has a child pointer, which may or may not point to a separate list. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure, as shown in below figure. You are given the head of the first level of the list. Flatten the list so that all the nodes appear in a single-level linked list. You need to flatten the list in way that all nodes at the first level should come first, then nodes of second level, and so on.Each node is a C struct with the following definition." }, { "code": null, "e": 646, "s": 644, "text": "C" }, { "code": null, "e": 651, "s": 646, "text": "Java" }, { "code": null, "e": 659, "s": 651, "text": "Python3" }, { "code": null, "e": 662, "s": 659, "text": "C#" }, { "code": null, "e": 673, "s": 662, "text": "Javascript" }, { "code": "struct List{ int data; struct List *next; struct List *child;};", "e": 746, "s": 673, "text": null }, { "code": "static class List{ public int data; public List next; public List child;}; // This code is contributed by pratham76", "e": 871, "s": 746, "text": null }, { "code": "# A linked list node has data,# next pointer and child pointerclass Node: def __init__(self, data): self.data = data self.next = None self.child = None # This code contributed by umadevi9616", "e": 1102, "s": 871, "text": null }, { "code": "static class List{ public int data; public List next; public List child;}; // This code is contributed by rutvik_56", "e": 1227, "s": 1102, "text": null }, { "code": "<script>class List{ constructor(){ this.data = 0; this.next = null; this.child = null; } }// This code contributed by aashish1995</script>", "e": 1398, "s": 1227, "text": null }, { "code": null, "e": 1496, "s": 1398, "text": "The above list should be converted to 10->5->12->7->11->4->20->13->17->6->2->16->9->8->3->19->15 " }, { "code": null, "e": 1885, "s": 1496, "text": "The problem clearly say that we need to flatten level by level. The idea of solution is, we start from first level, process all nodes one by one, if a node has a child, then we append the child at the end of list, otherwise we don’t do anything. After the first level is processed, all next level nodes will be appended after first level. Same process is followed for the appended nodes. " }, { "code": null, "e": 2442, "s": 1885, "text": "1) Take \"cur\" pointer, which will point to head of the first level of the list\n2) Take \"tail\" pointer, which will point to end of the first level of the list\n3) Repeat the below procedure while \"curr\" is not NULL.\n I) if current node has a child then\n a) append this new child list to the \"tail\"\n tail->next = cur->child\n b) find the last node of new child list and update \"tail\"\n tmp = cur->child;\n while (tmp->next != NULL)\n tmp = tmp->next;\n tail = tmp;\n II) move to the next node. i.e. cur = cur->next" }, { "code": null, "e": 2499, "s": 2442, "text": "Following is the implementation of the above algorithm. " }, { "code": null, "e": 2503, "s": 2499, "text": "C++" }, { "code": null, "e": 2505, "s": 2503, "text": "C" }, { "code": null, "e": 2510, "s": 2505, "text": "Java" }, { "code": null, "e": 2518, "s": 2510, "text": "Python3" }, { "code": null, "e": 2521, "s": 2518, "text": "C#" }, { "code": "// C++ Program to flatten list with// next and child pointers#include <bits/stdc++.h>using namespace std; // Macro to find number of elements in array#define SIZE(arr) (sizeof(arr)/sizeof(arr[0])) // A linked list node has data,// next pointer and child pointerclass Node{ public: int data; Node *next; Node *child;}; // A utility function to create a linked list// with n nodes. The data of nodes is taken// from arr[]. All child pointers are set as NULLNode *createList(int *arr, int n){ Node *head = NULL; Node *p; int i; for (i = 0; i < n; ++i) { if (head == NULL) head = p = new Node(); else { p->next = new Node(); p = p->next; } p->data = arr[i]; p->next = p->child = NULL; } return head;} // A utility function to print// all nodes of a linked listvoid printList(Node *head){ while (head != NULL) { cout << head->data << \" \"; head = head->next; } cout<<endl;} // This function creates the input// list. The created list is same// as shown in the above figureNode *createList(void){ int arr1[] = {10, 5, 12, 7, 11}; int arr2[] = {4, 20, 13}; int arr3[] = {17, 6}; int arr4[] = {9, 8}; int arr5[] = {19, 15}; int arr6[] = {2}; int arr7[] = {16}; int arr8[] = {3}; /* create 8 linked lists */ Node *head1 = createList(arr1, SIZE(arr1)); Node *head2 = createList(arr2, SIZE(arr2)); Node *head3 = createList(arr3, SIZE(arr3)); Node *head4 = createList(arr4, SIZE(arr4)); Node *head5 = createList(arr5, SIZE(arr5)); Node *head6 = createList(arr6, SIZE(arr6)); Node *head7 = createList(arr7, SIZE(arr7)); Node *head8 = createList(arr8, SIZE(arr8)); /* modify child pointers to create the list shown above */ head1->child = head2; head1->next->next->next->child = head3; head3->child = head4; head4->child = head5; head2->next->child = head6; head2->next->next->child = head7; head7->child = head8; /* Return head pointer of first linked list. Note that all nodes are reachable from head1 */ return head1;} /* The main function that flattensa multilevel linked list */void flattenList(Node *head){ /*Base case*/ if (head == NULL) return; Node *tmp; /* Find tail node of first level linked list */ Node *tail = head; while (tail->next != NULL) tail = tail->next; // One by one traverse through all nodes of first level // linked list till we reach the tail node Node *cur = head; while (cur != tail) { // If current node has a child if (cur->child) { // then append the child at the end of current list tail->next = cur->child; // and update the tail to new last node tmp = cur->child; while (tmp->next) tmp = tmp->next; tail = tmp; } // Change current node cur = cur->next; }} // Driver codeint main(void){ Node *head = NULL; head = createList(); flattenList(head); printList(head); return 0;} // This code is contributed by rathbhupendra", "e": 5679, "s": 2521, "text": null }, { "code": "// Program to flatten list with next and child pointers#include <stdio.h>#include <stdlib.h> // Macro to find number of elements in array#define SIZE(arr) (sizeof(arr)/sizeof(arr[0])) // A linked list node has data, next pointer and child pointerstruct Node{ int data; struct Node *next; struct Node *child;}; // A utility function to create a linked list with n nodes. The data// of nodes is taken from arr[]. All child pointers are set as NULLstruct Node *createList(int *arr, int n){ struct Node *head = NULL; struct Node *p; int i; for (i = 0; i < n; ++i) { if (head == NULL) head = p = (struct Node *)malloc(sizeof(*p)); else { p->next = (struct Node *)malloc(sizeof(*p)); p = p->next; } p->data = arr[i]; p->next = p->child = NULL; } return head;} // A utility function to print all nodes of a linked listvoid printList(struct Node *head){ while (head != NULL) { printf(\"%d \", head->data); head = head->next; } printf(\"\\n\");} // This function creates the input list. The created list is same// as shown in the above figurestruct Node *createList(void){ int arr1[] = {10, 5, 12, 7, 11}; int arr2[] = {4, 20, 13}; int arr3[] = {17, 6}; int arr4[] = {9, 8}; int arr5[] = {19, 15}; int arr6[] = {2}; int arr7[] = {16}; int arr8[] = {3}; /* create 8 linked lists */ struct Node *head1 = createList(arr1, SIZE(arr1)); struct Node *head2 = createList(arr2, SIZE(arr2)); struct Node *head3 = createList(arr3, SIZE(arr3)); struct Node *head4 = createList(arr4, SIZE(arr4)); struct Node *head5 = createList(arr5, SIZE(arr5)); struct Node *head6 = createList(arr6, SIZE(arr6)); struct Node *head7 = createList(arr7, SIZE(arr7)); struct Node *head8 = createList(arr8, SIZE(arr8)); /* modify child pointers to create the list shown above */ head1->child = head2; head1->next->next->next->child = head3; head3->child = head4; head4->child = head5; head2->next->child = head6; head2->next->next->child = head7; head7->child = head8; /* Return head pointer of first linked list. Note that all nodes are reachable from head1 */ return head1;} /* The main function that flattens a multilevel linked list */void flattenList(struct Node *head){ /*Base case*/ if (head == NULL) return; struct Node *tmp; /* Find tail node of first level linked list */ struct Node *tail = head; while (tail->next != NULL) tail = tail->next; // One by one traverse through all nodes of first level // linked list till we reach the tail node struct Node *cur = head; while (cur != tail) { // If current node has a child if (cur->child) { // then append the child at the end of current list tail->next = cur->child; // and update the tail to new last node tmp = cur->child; while (tmp->next) tmp = tmp->next; tail = tmp; } // Change current node cur = cur->next; }} // A driver program to test above functionsint main(void){ struct Node *head = NULL; head = createList(); flattenList(head); printList(head); return 0;}", "e": 8969, "s": 5679, "text": null }, { "code": "// Java program to flatten linked list with next and child pointers class LinkedList { static Node head; class Node { int data; Node next, child; Node(int d) { data = d; next = child = null; } } // A utility function to create a linked list with n nodes. The data // of nodes is taken from arr[]. All child pointers are set as NULL Node createList(int arr[], int n) { Node node = null; Node p = null; int i; for (i = 0; i < n; ++i) { if (node == null) { node = p = new Node(arr[i]); } else { p.next = new Node(arr[i]); p = p.next; } p.next = p.child = null; } return node; } // A utility function to print all nodes of a linked list void printList(Node node) { while (node != null) { System.out.print(node.data + \" \"); node = node.next; } System.out.println(\"\"); } Node createList() { int arr1[] = new int[]{10, 5, 12, 7, 11}; int arr2[] = new int[]{4, 20, 13}; int arr3[] = new int[]{17, 6}; int arr4[] = new int[]{9, 8}; int arr5[] = new int[]{19, 15}; int arr6[] = new int[]{2}; int arr7[] = new int[]{16}; int arr8[] = new int[]{3}; /* create 8 linked lists */ Node head1 = createList(arr1, arr1.length); Node head2 = createList(arr2, arr2.length); Node head3 = createList(arr3, arr3.length); Node head4 = createList(arr4, arr4.length); Node head5 = createList(arr5, arr5.length); Node head6 = createList(arr6, arr6.length); Node head7 = createList(arr7, arr7.length); Node head8 = createList(arr8, arr8.length); /* modify child pointers to create the list shown above */ head1.child = head2; head1.next.next.next.child = head3; head3.child = head4; head4.child = head5; head2.next.child = head6; head2.next.next.child = head7; head7.child = head8; /* Return head pointer of first linked list. Note that all nodes are reachable from head1 */ return head1; } /* The main function that flattens a multilevel linked list */ void flattenList(Node node) { /*Base case*/ if (node == null) { return; } Node tmp = null; /* Find tail node of first level linked list */ Node tail = node; while (tail.next != null) { tail = tail.next; } // One by one traverse through all nodes of first level // linked list till we reach the tail node Node cur = node; while (cur != tail) { // If current node has a child if (cur.child != null) { // then append the child at the end of current list tail.next = cur.child; // and update the tail to new last node tmp = cur.child; while (tmp.next != null) { tmp = tmp.next; } tail = tmp; } // Change current node cur = cur.next; } } public static void main(String[] args) { LinkedList list = new LinkedList(); head = list.createList(); list.flattenList(head); list.printList(head); }} // This code has been contributed by Mayank Jaiswal", "e": 12502, "s": 8969, "text": null }, { "code": "# Python3 Program to flatten list with# next and child pointers # A linked list node has data,# next pointer and child pointerclass Node: def __init__(self, data): self.data = data self.next = None self.child = None # Return Nodedef newNode(data): return Node(data) # The main function that flattens# a multilevel linked listdef flattenlist(head): # Base case if not head: return # Find tail node of first level linked list temp = head while(temp.next != None): temp = temp.next currNode = head # One by one traverse through all nodes # of first level linked list # till we reach the tail node while(currNode != temp): # If current node has a child if(currNode.child): # then append the child # at the end of current list temp.next = currNode.child # and update the tail to new last node tmp = currNode.child while(tmp.next): tmp = tmp.next temp = tmp # Change current node currNode = currNode.next # A utility function to print# all nodes of a linked listdef printList(head): if not head: return while(head): print(\"{}\".format(head.data), end = \" \") head = head.next # Driver codeif __name__=='__main__': # Child list of 13 child13 = newNode(16) child13.child = newNode(3) # Child List of 10 head1 = newNode(4) head1.next = newNode(20) head1.next.child = newNode(2) #Child of 20 head1.next.next = newNode(13) head1.next.next.child = child13 # Child of 9 child9 = newNode(19) child9.next = newNode(15) # Child List of 17 child17 = newNode(9) child17.next = newNode(8) child17.child = child9 # Child List of 7 head2 = newNode(17) head2.next = newNode(6) head2.child = child17 # Main List head = newNode(10) head.child = head1 head.next = newNode(5) head.next.next = newNode(12) head.next.next.next = newNode(7) head.next.next.next.child = head2 head.next.next.next.next = newNode(11) flattenlist(head) print(\"\\Flattened list is: \", end = \"\") printList(head) # This code is contributed by 0_hero", "e": 14798, "s": 12502, "text": null }, { "code": "// C# program to flatten linked list// with next and child pointersusing System; public class LinkedList{ static Node head; class Node { public int data; public Node next, child; public Node(int d) { data = d; next = child = null; } } // A utility function to create // a linked list with n nodes. The data // of nodes is taken from arr[]. // All child pointers are set as NULL Node createList(int []arr, int n) { Node node = null; Node p = null; int i; for (i = 0; i < n; ++i) { if (node == null) { node = p = new Node(arr[i]); } else { p.next = new Node(arr[i]); p = p.next; } p.next = p.child = null; } return node; } // A utility function to print // all nodes of a linked list void printList(Node node) { while (node != null) { Console.Write(node.data + \" \"); node = node.next; } Console.WriteLine(\"\"); } Node createList() { int []arr1 = new int[]{10, 5, 12, 7, 11}; int []arr2 = new int[]{4, 20, 13}; int []arr3 = new int[]{17, 6}; int []arr4 = new int[]{9, 8}; int []arr5 = new int[]{19, 15}; int []arr6 = new int[]{2}; int []arr7 = new int[]{16}; int []arr8 = new int[]{3}; /* create 8 linked lists */ Node head1 = createList(arr1, arr1.Length); Node head2 = createList(arr2, arr2.Length); Node head3 = createList(arr3, arr3.Length); Node head4 = createList(arr4, arr4.Length); Node head5 = createList(arr5, arr5.Length); Node head6 = createList(arr6, arr6.Length); Node head7 = createList(arr7, arr7.Length); Node head8 = createList(arr8, arr8.Length); /* modify child pointers to create the list shown above */ head1.child = head2; head1.next.next.next.child = head3; head3.child = head4; head4.child = head5; head2.next.child = head6; head2.next.next.child = head7; head7.child = head8; /* Return head pointer of first linked list. Note that all nodes are reachable from head1 */ return head1; } /* The main function that flattens a multilevel linked list */ void flattenList(Node node) { /*Base case*/ if (node == null) { return; } Node tmp = null; /* Find tail node of first level linked list */ Node tail = node; while (tail.next != null) { tail = tail.next; } // One by one traverse through // all nodes of first level // linked list till we reach the tail node Node cur = node; while (cur != tail) { // If current node has a child if (cur.child != null) { // then append the child at // the end of current list tail.next = cur.child; // and update the tail to new last node tmp = cur.child; while (tmp.next != null) { tmp = tmp.next; } tail = tmp; } // Change current node cur = cur.next; } } // Driver code public static void Main() { LinkedList list = new LinkedList(); head = list.createList(); list.flattenList(head); list.printList(head); }} /* This code is contributed PrinciRaj1992 */", "e": 18538, "s": 14798, "text": null }, { "code": null, "e": 18582, "s": 18538, "text": "10 5 12 7 11 4 20 13 17 6 2 16 9 8 3 19 15 " }, { "code": null, "e": 18723, "s": 18582, "text": "Time Complexity: Since every node is visited at most twice, the time complexity is O(n) where n is the number of nodes in given linked list." }, { "code": null, "e": 18737, "s": 18723, "text": "princiraj1992" }, { "code": null, "e": 18751, "s": 18737, "text": "rathbhupendra" }, { "code": null, "e": 18758, "s": 18751, "text": "0_hero" }, { "code": null, "e": 18768, "s": 18758, "text": "rutvik_56" }, { "code": null, "e": 18778, "s": 18768, "text": "pratham76" }, { "code": null, "e": 18790, "s": 18778, "text": "aashish1995" }, { "code": null, "e": 18802, "s": 18790, "text": "umadevi9616" }, { "code": null, "e": 18819, "s": 18802, "text": "arorakashish0911" }, { "code": null, "e": 18836, "s": 18819, "text": "hardikkoriintern" }, { "code": null, "e": 18848, "s": 18836, "text": "Linked List" }, { "code": null, "e": 18860, "s": 18848, "text": "Linked List" }, { "code": null, "e": 18958, "s": 18860, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 19006, "s": 18958, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 19025, "s": 19006, "text": "LinkedList in Java" }, { "code": null, "e": 19057, "s": 19025, "text": "Introduction to Data Structures" }, { "code": null, "e": 19121, "s": 19057, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 19173, "s": 19121, "text": "Add two numbers represented by linked lists | Set 1" }, { "code": null, "e": 19220, "s": 19173, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 19260, "s": 19220, "text": "Detect and Remove Loop in a Linked List" }, { "code": null, "e": 19295, "s": 19260, "text": "Queue - Linked List Implementation" }, { "code": null, "e": 19351, "s": 19295, "text": "Function to check if a singly linked list is palindrome" } ]
How to set the initial value of an auto-incremented column in MySQL using JDBC?
While creating a table, in certain scenarios, we need values to column such as ID, to be generated/incremented automatically. Various databases support this feature in different ways. In MySQL database you can declare a column auto increment using the following syntax. CREATE TABLE table_name( ID INT PRIMARY KEY AUTO_INCREMENT, column_name1 data_type1, column_name2 data_type2, column_name3 data_type3, column_name4 data_type4, ............ ........... ); While inserting records in a table there is no need to insert value under the auto-incremented column. These will be generated automatically. By default, the initial value of the auto-incremented column will be 1. You can change it using the ALTER TABLE query as shown below − alter table table_name AUTO_INCREMENT = 1001 Let us create a table with name sales in MySQL database, with one of the columns as auto-incremented, using CREATE statement as shown below − CREATE TABLE Sales( ID INT PRIMARY KEY AUTO_INCREMENT, ProductName VARCHAR (20), CustomerName VARCHAR (20), DispatchDate date, DeliveryTime time, Price INT, Location VARCHAR(20) ); Following JDBC program sets the initial value of the auto-incremented column to 1001 and inserts 6 records into it. import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import java.sql.Time; public class SettingInitialValue_AutoIncrement_Pstmt { 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/sample_database"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Setting the initial value of the auto-incremented column Statement stmt = con.createStatement(); stmt.execute("alter table Sales AUTO_INCREMENT = 1001"); //Query to Insert values to the sales table String insertQuery = "INSERT INTO Sales (ProductName, CustomerName, DispatchDate, DeliveryTime, Price, Location) VALUES (?, ?, ?, ?, ?, ?)"; //Creating a PreparedStatement object PreparedStatement pstmt = con.prepareStatement(insertQuery,Statement.RETURN_GENERATED_KEYS); pstmt.setString(1, "Key-Board"); pstmt.setString(2, "Raja"); pstmt.setDate(3, new Date(1567315800000L)); pstmt.setTime(4, new Time(1567315800000L)); pstmt.setInt(5, 7000); pstmt.setString(6, "Hyderabad"); pstmt.addBatch(); pstmt.setString(1, "Earphones"); pstmt.setString(2, "Roja"); pstmt.setDate(3, new Date(1556688600000L)); pstmt.setTime(4, new Time(1556688600000L)); pstmt.setInt(5, 2000); pstmt.setString(6, "Vishakhapatnam"); pstmt.addBatch(); pstmt.setString(1, "Mouse"); pstmt.setString(2, "Puja"); pstmt.setDate(3, new Date(1551418199000L)); pstmt.setTime(4, new Time(1551418199000L)); pstmt.setInt(5, 3000); pstmt.setString(6, "Vijayawada"); pstmt.addBatch(); pstmt.setString(1, "Mobile"); pstmt.setString(2, "Vanaja"); pstmt.setDate(3, new Date(1551415252000L)); pstmt.setTime(4, new Time(1551415252000L)); pstmt.setInt(5, 9000); pstmt.setString(6, "Chennai"); pstmt.addBatch(); pstmt.setString(1, "Headset"); pstmt.setString(2, "Jalaja"); pstmt.setDate(3, new Date(1554529139000L)); pstmt.setTime(4, new Time(1554529139000L)); pstmt.setInt(5, 6000); pstmt.setString(6, "Goa"); pstmt.addBatch(); System.out.println("Records inserted......"); //Executing the batch pstmt.executeBatch(); } } Connection established...... Records inserted...... If you verify the contents of the Sales table using SELECT statement, you can see the inserted records with ID value starting from 1001 as − mysql> select * from sales; +------+-------------+--------------+--------------+--------------+-------+----------------+ | ID | ProductName | CustomerName | DispatchDate | DeliveryTime | Price | Location | +------+-------------+--------------+--------------+--------------+-------+----------------+ | 1001 | Key-Board | Raja | 2019-09-01 | 11:00:00 | 7000 | Hyderabad | | 1002 | Earphones | Roja | 2019-05-01 | 11:00:00 | 2000 | Vishakhapatnam | | 1003 | Mouse | Puja | 2019-03-01 | 10:59:59 | 3000 | Vijayawada | | 1004 | Mobile | Vanaja | 2019-03-01 | 10:10:52 | 9000 | Chennai | | 1005 | Headset | Jalaja | 2019-04-06 | 11:08:59 | 6000 | Goa | +------+-------------+--------------+--------------+--------------+-------+----------------+ 5 rows in set (0.00 sec)
[ { "code": null, "e": 1246, "s": 1062, "text": "While creating a table, in certain scenarios, we need values to column such as ID, to be generated/incremented automatically. Various databases support this feature in different ways." }, { "code": null, "e": 1332, "s": 1246, "text": "In MySQL database you can declare a column auto increment using the following syntax." }, { "code": null, "e": 1538, "s": 1332, "text": "CREATE TABLE table_name(\n ID INT PRIMARY KEY AUTO_INCREMENT,\n column_name1 data_type1,\n column_name2 data_type2,\n column_name3 data_type3,\n column_name4 data_type4,\n ............ ...........\n);" }, { "code": null, "e": 1680, "s": 1538, "text": "While inserting records in a table there is no need to insert value under the auto-incremented column. These will be generated automatically." }, { "code": null, "e": 1815, "s": 1680, "text": "By default, the initial value of the auto-incremented column will be 1. You can change it using the ALTER TABLE query as shown below −" }, { "code": null, "e": 1860, "s": 1815, "text": "alter table table_name AUTO_INCREMENT = 1001" }, { "code": null, "e": 2002, "s": 1860, "text": "Let us create a table with name sales in MySQL database, with one of the columns as auto-incremented, using CREATE statement as shown below −" }, { "code": null, "e": 2204, "s": 2002, "text": "CREATE TABLE Sales(\n ID INT PRIMARY KEY AUTO_INCREMENT,\n ProductName VARCHAR (20),\n CustomerName VARCHAR (20),\n DispatchDate date,\n DeliveryTime time,\n Price INT,\n Location VARCHAR(20)\n);" }, { "code": null, "e": 2320, "s": 2204, "text": "Following JDBC program sets the initial value of the auto-incremented column to 1001 and inserts 6 records into it." }, { "code": null, "e": 4914, "s": 2320, "text": "import java.sql.Connection;\nimport java.sql.Date;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.SQLException;\nimport java.sql.Statement;\nimport java.sql.Time;\npublic class SettingInitialValue_AutoIncrement_Pstmt {\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/sample_database\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Setting the initial value of the auto-incremented column\n Statement stmt = con.createStatement();\n stmt.execute(\"alter table Sales AUTO_INCREMENT = 1001\");\n //Query to Insert values to the sales table\n String insertQuery = \"INSERT INTO Sales (ProductName, CustomerName, DispatchDate, DeliveryTime, Price, Location) VALUES (?, ?, ?, ?, ?, ?)\";\n //Creating a PreparedStatement object\n PreparedStatement pstmt = con.prepareStatement(insertQuery,Statement.RETURN_GENERATED_KEYS);\n pstmt.setString(1, \"Key-Board\");\n pstmt.setString(2, \"Raja\");\n pstmt.setDate(3, new Date(1567315800000L));\n pstmt.setTime(4, new Time(1567315800000L));\n pstmt.setInt(5, 7000);\n pstmt.setString(6, \"Hyderabad\");\n pstmt.addBatch();\n pstmt.setString(1, \"Earphones\");\n pstmt.setString(2, \"Roja\");\n pstmt.setDate(3, new Date(1556688600000L));\n pstmt.setTime(4, new Time(1556688600000L));\n pstmt.setInt(5, 2000);\n pstmt.setString(6, \"Vishakhapatnam\");\n pstmt.addBatch();\n pstmt.setString(1, \"Mouse\");\n pstmt.setString(2, \"Puja\");\n pstmt.setDate(3, new Date(1551418199000L));\n pstmt.setTime(4, new Time(1551418199000L));\n pstmt.setInt(5, 3000);\n pstmt.setString(6, \"Vijayawada\");\n pstmt.addBatch();\n pstmt.setString(1, \"Mobile\");\n pstmt.setString(2, \"Vanaja\");\n pstmt.setDate(3, new Date(1551415252000L));\n pstmt.setTime(4, new Time(1551415252000L));\n pstmt.setInt(5, 9000);\n pstmt.setString(6, \"Chennai\");\n pstmt.addBatch();\n pstmt.setString(1, \"Headset\");\n pstmt.setString(2, \"Jalaja\");\n pstmt.setDate(3, new Date(1554529139000L));\n pstmt.setTime(4, new Time(1554529139000L));\n pstmt.setInt(5, 6000);\n pstmt.setString(6, \"Goa\");\n pstmt.addBatch();\n System.out.println(\"Records inserted......\");\n //Executing the batch\n pstmt.executeBatch();\n }\n}" }, { "code": null, "e": 4966, "s": 4914, "text": "Connection established......\nRecords inserted......" }, { "code": null, "e": 5107, "s": 4966, "text": "If you verify the contents of the Sales table using SELECT statement, you can see the inserted records with ID value starting from 1001 as −" }, { "code": null, "e": 5872, "s": 5107, "text": "mysql> select * from sales;\n+------+-------------+--------------+--------------+--------------+-------+----------------+\n| ID | ProductName | CustomerName | DispatchDate | DeliveryTime | Price | Location |\n+------+-------------+--------------+--------------+--------------+-------+----------------+\n| 1001 | Key-Board | Raja | 2019-09-01 | 11:00:00 | 7000 | Hyderabad |\n| 1002 | Earphones | Roja | 2019-05-01 | 11:00:00 | 2000 | Vishakhapatnam |\n| 1003 | Mouse | Puja | 2019-03-01 | 10:59:59 | 3000 | Vijayawada |\n| 1004 | Mobile | Vanaja | 2019-03-01 | 10:10:52 | 9000 | Chennai |\n| 1005 | Headset | Jalaja | 2019-04-06 | 11:08:59 | 6000 | Goa |\n+------+-------------+--------------+--------------+--------------+-------+----------------+\n5 rows in set (0.00 sec)" } ]
Longest Increasing Path in a Matrix | Practice | GeeksforGeeks
Given a matrix with n rows and m columns. Your task is to find the length of the longest increasing path in matrix, here increasing path means that the value in the specified path increases. For example if a path of length k has values a1, a2, a3, .... ak , then for every i from [2,k] this condition must hold ai > ai-1. No cell should be revisited in the path. From each cell, you can either move in four directions: left, right, up, or down. You are not allowed to move diagonally or move outside the boundary. Example 1: Input: n = 3, m = 3 matrix[][] = {{1 2 3}, {4 5 6}, {7 8 9}} Output: 5 Explanation: The longest increasing path is {1, 2, 3, 6, 9}. Example 2: Input: n = 3, m = 3 matrix[][] = {{3 4 5}, {6 2 6}, {2 2 1}} Output: 4 Explanation: The longest increasing path is {3, 4, 5, 6}. Your Task: You only need to implement the given function longestIncreasingPath() which takes the two integers n and m and the matrix matrix as input parameters, and returns the length of the longest increasing path in matrix. Expected Time Complexity: O(n*m) Expected Auxiliary Space: O(n*m) Constraints: 1 ≤ n,m ≤ 1000 0 ≤ matrix[i] ≤ 230 0 yashh27112 months ago DFS + Dp class Solution { public: int longestIncreasingPath(vector<vector<int>>& matrix, int numRows, int numCols) { // Code here vector<vector<int>> dp = vector<vector<int>>(numRows, vector<int>(numCols, -1)); int longestPath = 1; for(int row = 0; row < numRows; row++) { for(int col = 0; col < numCols; col++) { if(dp[row][col] == -1) { longestPath = max(longestPath, dfs(matrix, row, col, dp)); } } } return longestPath; } private: int dx[4] = {1,0,-1,0}; int dy[4] = {0,1,0,-1}; int dfs(const vector<vector<int>>& matrix, int row, int col, vector<vector<int>>& dp) { if(dp[row][col] != -1) return dp[row][col]; int longestPath = 0; for(int dir = 0; dir < 4; dir++) { int nextRow = row + dx[dir]; int nextCol = col + dy[dir]; if(nextRow >= 0 and nextCol >= 0 and nextRow < matrix.size() and nextCol < matrix[0].size()) { if(matrix[nextRow][nextCol] > matrix[row][col]) { longestPath = max(longestPath, dfs(matrix, nextRow, nextCol, dp)); } } } return dp[row][col] = longestPath + 1; }}; 0 debjyotichattopadhyay3 months ago //JAVA top down memoization solution class Solution { /*You are required to complete this method*/ int longestIncreasingPath(int mat[][], int n, int m) { int store[][]=new int [n][m]; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ store[i][j]=-1; } } int maxLen=Integer.MIN_VALUE; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ maxLen=Math.max(maxLen,dp(i,j,mat,store)); } } return(maxLen); }//longestIncreasingPath public int dp(int cr,int cc,int mat[][],int store[][]){ if(store[cr][cc]!=-1) return(store[cr][cc]); int maxLen=0; if(cr-1>=0 &&mat[cr-1][cc]>mat[cr][cc]) maxLen=Math.max(maxLen,dp(cr-1,cc,mat,store)); if(cc-1>=0 && mat[cr][cc-1] > mat[cr][cc]) maxLen=Math.max(maxLen,dp(cr,cc-1,mat,store)); if(cr+1<mat.length && mat[cr+1][cc]>mat[cr][cc]) maxLen=Math.max(maxLen,dp(cr+1,cc,mat,store)); if(cc+1<mat[0].length && mat[cr][cc+1]>mat[cr][cc]) maxLen=Math.max(maxLen,dp(cr,cc+1,mat,store)); store[cr][cc]=1+maxLen; return(store[cr][cc]); }//dp }//Solution 0 Rohit Vishwakarma7 months ago Rohit Vishwakarma Dynamic Programming DFS(memoization on dfs) O(n^2) int dp[1001][1001]; int dfs(int i , int j, vector<vector<int>> & matrix, int curr_val) { if(i < 0 || j < 0 || i >= matrix.size() || j >= matrix[0].size() || curr_val >= matrix[i][j]) { return 0; } if(dp[i][j] != -1) { return dp[i][j]; } int temp = matrix[i][j]; int one = 1 + dfs(i+1, j, matrix, temp); int two = 1 + dfs(i, j+1, matrix, temp); int three = 1 + dfs(i-1, j, matrix, temp); int four = 1 + dfs(i,j-1, matrix, temp); return dp[i][j] = max({one, two, three, four}); } int longestIncreasingPath(vector<vector<int>>& matrix, int n, int m) { int length = 0; memset(dp, -1, sizeof(dp)); for(int i = 0; i < n; ++i) { for(int j = 0; j < m; ++j) { int curr = INT_MIN; int temp = dfs(i,j,matrix,curr); length = max(length, temp); } } return length; } Dynamic Programming DFS(memoization on dfs) O(n^2) 0 Yashraj Labde9 months ago Yashraj Labde DFS wont work as we need O(n*n), think this problem as an application of topological sort. 0 Sai Akhil Mittapally10 months ago Sai Akhil Mittapally Easy C++ SOLUTION:class Solution { public: int IncreasingPath(vector<vector<int>>& arr,int i,int j,int n,int m,vector<vector<int>>&dp){ if(dp[i][j]!=-1){ return dp[i][j]; } int max1=0,max2=0,max3=0,max4=0; if(i+1<n&&arr[i][j]<arr[i+1][j]){ max1="IncreasingPath(arr,i+1,j,n,m,dp)+1;" }="" if(i-1="">=0&&arr[i][j]<arr[i-1][j]){ max2="IncreasingPath(arr,i-1,j,n,m,dp)+1;" }="" if(j-1="">=0&&arr[i][j]<arr[i][j-1]){ max3="IncreasingPath(arr,i,j-1,n,m,dp)+1;" }="" if(j+1<m&&arr[i][j]<arr[i][j+1]){="" max4="IncreasingPath(arr,i,j+1,n,m,dp)+1;" }="" if(max(max(max1,max2),max(max3,max4))="=0){" return="" 1;="" }="" return="" dp[i][j]="max(max(max1,max2),max(max3,max4));" }="" int="" longestincreasingpath(vector<vector<int="">>& arr, int n, int m) { // Code here vector<vector<int>>dp(n,vector<int>(m,-1)); int maxi=INT_MIN; for(int i=0;i<n;i++){ for(int="" j="0;j&lt;m;j++){" maxi="max(IncreasingPath(arr,i,j,n,m,dp),maxi);" }="" }="" return="" maxi;="" }="" };=""> 0 Nihal Chaturvedi10 months ago Nihal Chaturvedi Easy approach -> Use DFS + MemorizationCreate a dp of size n*mWhat we are going to store in our dp[i][j] is the Lonest Increasing Pathfrom row =i and col = jWe will use DFS to Reach the maximum depth i.e. the longest increasing path here .To avoid calculating the Longest Increasing path for a cell multiple times we will use the concept of memorization and store the value in our dpHere we don't need to keep a visited matrix as Suppose the matrix is : 3 2 5 6Now from 3 we will go to 5 Now from 5 since 3 is smaller than 5 so we will never go to 3 .So we will never go toward the path from which we are coming . https://uploads.disquscdn.c... 0 Shruti Agarwal1 year ago Shruti Agarwal The idea is to start traversing from each block in matrix and store the answer computed for that block in a memo. class Solution {private: vector<vector<int>> dp; vector<vector<int>> M; int R,C; bool isValid(int i,int j){ if(i<0 or i>=R or j<0 or j>=C) return false; return true; } int x[4]{0,0,1,-1}; int y[4]{1,-1,0,0}; int dfs(int i,int j) { if(dp[i][j]!=-1) return dp[i][j]; int maxPath=0; for(int k=0;k<4;k++) { int ni=i+x[k]; int nj=j+y[k]; if(isValid(ni,nj) and M[ni][nj]>M[i][j]) maxPath=max(maxPath,dfs(ni,nj)); } return dp[i][j]=1+maxPath; }public: int longestIncreasingPath(vector<vector<int>>& m) { R=m.size(); C=m[0].size(); M=m; dp.resize(R,vector<int>(C,-1)); int ans=0; for(int i=0;i<r;i++) {="" for(int="" j="0;j&lt;C;j++)" {="" ans="max(ans,dfs(i,j));" }="" }="" return="" ans;="" }="" };=""> 0 FuckItBot1 year ago FuckItBot @GFG dfs with memorization solution is getting accepted, whereas the time constraint clearly mentions O(n*m) time complexity. Please change the time constraint :/ 0 Hrishikesh Rai1 year ago Hrishikesh Rai CODE EASY TO UNDERSTANDhttps://ide.geeksforgeeks.o...IF AGAIN HAVING ANY PROBLEM, WATCH THIShttps://youtu.be/FjZdJ4aHdpU 0 Bharat Gupta This comment was deleted. 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": 754, "s": 238, "text": "Given a matrix with n rows and m columns. Your task is to find the length of the longest increasing path in matrix, here increasing path means that the value in the specified path increases. For example if a path of length k has values a1, a2, a3, .... ak , then for every i from [2,k] this condition must hold ai > ai-1. No cell should be revisited in the path.\nFrom each cell, you can either move in four directions: left, right, up, or down. You are not allowed to move diagonally or move outside the boundary." }, { "code": null, "e": 766, "s": 754, "text": "\nExample 1:" }, { "code": null, "e": 931, "s": 766, "text": "Input:\nn = 3, m = 3\nmatrix[][] = {{1 2 3},\n {4 5 6},\n {7 8 9}}\nOutput: \n5\nExplanation: \nThe longest increasing path is \n{1, 2, 3, 6, 9}. \n" }, { "code": null, "e": 942, "s": 931, "text": "Example 2:" }, { "code": null, "e": 1100, "s": 942, "text": "Input:\nn = 3, m = 3\nmatrix[][] = {{3 4 5},\n {6 2 6},\n {2 2 1}}\nOutput: \n4\nExplanation:\nThe longest increasing path is\n{3, 4, 5, 6}." }, { "code": null, "e": 1327, "s": 1100, "text": "\nYour Task:\nYou only need to implement the given function longestIncreasingPath() which takes the two integers n and m and the matrix matrix as input parameters, and returns the length of the longest increasing path in matrix." }, { "code": null, "e": 1394, "s": 1327, "text": "\nExpected Time Complexity: O(n*m)\nExpected Auxiliary Space: O(n*m)" }, { "code": null, "e": 1443, "s": 1394, "text": "\nConstraints:\n1 ≤ n,m ≤ 1000\n0 ≤ matrix[i] ≤ 230" }, { "code": null, "e": 1445, "s": 1443, "text": "0" }, { "code": null, "e": 1467, "s": 1445, "text": "yashh27112 months ago" }, { "code": null, "e": 1476, "s": 1467, "text": "DFS + Dp" }, { "code": null, "e": 1586, "s": 1476, "text": "class Solution { public: int longestIncreasingPath(vector<vector<int>>& matrix, int numRows, int numCols) {" }, { "code": null, "e": 2783, "s": 1586, "text": " // Code here vector<vector<int>> dp = vector<vector<int>>(numRows, vector<int>(numCols, -1)); int longestPath = 1; for(int row = 0; row < numRows; row++) { for(int col = 0; col < numCols; col++) { if(dp[row][col] == -1) { longestPath = max(longestPath, dfs(matrix, row, col, dp)); } } } return longestPath; } private: int dx[4] = {1,0,-1,0}; int dy[4] = {0,1,0,-1}; int dfs(const vector<vector<int>>& matrix, int row, int col, vector<vector<int>>& dp) { if(dp[row][col] != -1) return dp[row][col]; int longestPath = 0; for(int dir = 0; dir < 4; dir++) { int nextRow = row + dx[dir]; int nextCol = col + dy[dir]; if(nextRow >= 0 and nextCol >= 0 and nextRow < matrix.size() and nextCol < matrix[0].size()) { if(matrix[nextRow][nextCol] > matrix[row][col]) { longestPath = max(longestPath, dfs(matrix, nextRow, nextCol, dp)); } } } return dp[row][col] = longestPath + 1; }};" }, { "code": null, "e": 2785, "s": 2783, "text": "0" }, { "code": null, "e": 2819, "s": 2785, "text": "debjyotichattopadhyay3 months ago" }, { "code": null, "e": 4097, "s": 2819, "text": "//JAVA top down memoization solution\nclass Solution {\n /*You are required to complete this method*/\n int longestIncreasingPath(int mat[][], int n, int m) {\n int store[][]=new int [n][m];\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n store[i][j]=-1;\n }\n }\n int maxLen=Integer.MIN_VALUE;\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n maxLen=Math.max(maxLen,dp(i,j,mat,store));\n }\n }\n return(maxLen);\n }//longestIncreasingPath\n public int dp(int cr,int cc,int mat[][],int store[][]){\n \n if(store[cr][cc]!=-1)\n return(store[cr][cc]);\n \n int maxLen=0;\n \n if(cr-1>=0 &&mat[cr-1][cc]>mat[cr][cc])\n maxLen=Math.max(maxLen,dp(cr-1,cc,mat,store));\n if(cc-1>=0 && mat[cr][cc-1] > mat[cr][cc])\n maxLen=Math.max(maxLen,dp(cr,cc-1,mat,store));\n if(cr+1<mat.length && mat[cr+1][cc]>mat[cr][cc])\n maxLen=Math.max(maxLen,dp(cr+1,cc,mat,store));\n if(cc+1<mat[0].length && mat[cr][cc+1]>mat[cr][cc])\n maxLen=Math.max(maxLen,dp(cr,cc+1,mat,store));\n \n store[cr][cc]=1+maxLen;\n return(store[cr][cc]);\n }//dp\n}//Solution" }, { "code": null, "e": 4099, "s": 4097, "text": "0" }, { "code": null, "e": 4129, "s": 4099, "text": "Rohit Vishwakarma7 months ago" }, { "code": null, "e": 4147, "s": 4129, "text": "Rohit Vishwakarma" }, { "code": null, "e": 5191, "s": 4147, "text": " Dynamic Programming DFS(memoization on dfs) O(n^2) int dp[1001][1001]; int dfs(int i , int j, vector<vector<int>> & matrix, int curr_val) { if(i < 0 || j < 0 || i >= matrix.size() || j >= matrix[0].size() || curr_val >= matrix[i][j]) { return 0; } if(dp[i][j] != -1) { return dp[i][j]; } int temp = matrix[i][j]; int one = 1 + dfs(i+1, j, matrix, temp); int two = 1 + dfs(i, j+1, matrix, temp); int three = 1 + dfs(i-1, j, matrix, temp); int four = 1 + dfs(i,j-1, matrix, temp); return dp[i][j] = max({one, two, three, four}); } int longestIncreasingPath(vector<vector<int>>& matrix, int n, int m) { int length = 0; memset(dp, -1, sizeof(dp)); for(int i = 0; i < n; ++i) { for(int j = 0; j < m; ++j) { int curr = INT_MIN; int temp = dfs(i,j,matrix,curr); length = max(length, temp); } } return length; }" }, { "code": null, "e": 5242, "s": 5191, "text": "Dynamic Programming DFS(memoization on dfs) O(n^2)" }, { "code": null, "e": 5244, "s": 5242, "text": "0" }, { "code": null, "e": 5270, "s": 5244, "text": "Yashraj Labde9 months ago" }, { "code": null, "e": 5284, "s": 5270, "text": "Yashraj Labde" }, { "code": null, "e": 5375, "s": 5284, "text": "DFS wont work as we need O(n*n), think this problem as an application of topological sort." }, { "code": null, "e": 5377, "s": 5375, "text": "0" }, { "code": null, "e": 5411, "s": 5377, "text": "Sai Akhil Mittapally10 months ago" }, { "code": null, "e": 5432, "s": 5411, "text": "Sai Akhil Mittapally" }, { "code": null, "e": 6467, "s": 5432, "text": "Easy C++ SOLUTION:class Solution { public: int IncreasingPath(vector<vector<int>>& arr,int i,int j,int n,int m,vector<vector<int>>&dp){ if(dp[i][j]!=-1){ return dp[i][j]; } int max1=0,max2=0,max3=0,max4=0; if(i+1<n&&arr[i][j]<arr[i+1][j]){ max1=\"IncreasingPath(arr,i+1,j,n,m,dp)+1;\" }=\"\" if(i-1=\"\">=0&&arr[i][j]<arr[i-1][j]){ max2=\"IncreasingPath(arr,i-1,j,n,m,dp)+1;\" }=\"\" if(j-1=\"\">=0&&arr[i][j]<arr[i][j-1]){ max3=\"IncreasingPath(arr,i,j-1,n,m,dp)+1;\" }=\"\" if(j+1<m&&arr[i][j]<arr[i][j+1]){=\"\" max4=\"IncreasingPath(arr,i,j+1,n,m,dp)+1;\" }=\"\" if(max(max(max1,max2),max(max3,max4))=\"=0){\" return=\"\" 1;=\"\" }=\"\" return=\"\" dp[i][j]=\"max(max(max1,max2),max(max3,max4));\" }=\"\" int=\"\" longestincreasingpath(vector<vector<int=\"\">>& arr, int n, int m) { // Code here vector<vector<int>>dp(n,vector<int>(m,-1)); int maxi=INT_MIN; for(int i=0;i<n;i++){ for(int=\"\" j=\"0;j&lt;m;j++){\" maxi=\"max(IncreasingPath(arr,i,j,n,m,dp),maxi);\" }=\"\" }=\"\" return=\"\" maxi;=\"\" }=\"\" };=\"\">" }, { "code": null, "e": 6469, "s": 6467, "text": "0" }, { "code": null, "e": 6499, "s": 6469, "text": "Nihal Chaturvedi10 months ago" }, { "code": null, "e": 6516, "s": 6499, "text": "Nihal Chaturvedi" }, { "code": null, "e": 7160, "s": 6516, "text": "Easy approach -> Use DFS + MemorizationCreate a dp of size n*mWhat we are going to store in our dp[i][j] is the Lonest Increasing Pathfrom row =i and col = jWe will use DFS to Reach the maximum depth i.e. the longest increasing path here .To avoid calculating the Longest Increasing path for a cell multiple times we will use the concept of memorization and store the value in our dpHere we don't need to keep a visited matrix as Suppose the matrix is : 3 2 5 6Now from 3 we will go to 5 Now from 5 since 3 is smaller than 5 so we will never go to 3 .So we will never go toward the path from which we are coming ." }, { "code": null, "e": 7192, "s": 7160, "text": " https://uploads.disquscdn.c..." }, { "code": null, "e": 7194, "s": 7192, "text": "0" }, { "code": null, "e": 7219, "s": 7194, "text": "Shruti Agarwal1 year ago" }, { "code": null, "e": 7234, "s": 7219, "text": "Shruti Agarwal" }, { "code": null, "e": 7348, "s": 7234, "text": "The idea is to start traversing from each block in matrix and store the answer computed for that block in a memo." }, { "code": null, "e": 8209, "s": 7348, "text": "class Solution {private: vector<vector<int>> dp; vector<vector<int>> M; int R,C; bool isValid(int i,int j){ if(i<0 or i>=R or j<0 or j>=C) return false; return true; } int x[4]{0,0,1,-1}; int y[4]{1,-1,0,0}; int dfs(int i,int j) { if(dp[i][j]!=-1) return dp[i][j]; int maxPath=0; for(int k=0;k<4;k++) { int ni=i+x[k]; int nj=j+y[k]; if(isValid(ni,nj) and M[ni][nj]>M[i][j]) maxPath=max(maxPath,dfs(ni,nj)); } return dp[i][j]=1+maxPath; }public: int longestIncreasingPath(vector<vector<int>>& m) { R=m.size(); C=m[0].size(); M=m; dp.resize(R,vector<int>(C,-1)); int ans=0; for(int i=0;i<r;i++) {=\"\" for(int=\"\" j=\"0;j&lt;C;j++)\" {=\"\" ans=\"max(ans,dfs(i,j));\" }=\"\" }=\"\" return=\"\" ans;=\"\" }=\"\" };=\"\">" }, { "code": null, "e": 8211, "s": 8209, "text": "0" }, { "code": null, "e": 8231, "s": 8211, "text": "FuckItBot1 year ago" }, { "code": null, "e": 8241, "s": 8231, "text": "FuckItBot" }, { "code": null, "e": 8405, "s": 8241, "text": "@GFG dfs with memorization solution is getting accepted, whereas the time constraint clearly mentions O(n*m) time complexity. Please change the time constraint :/" }, { "code": null, "e": 8407, "s": 8405, "text": "0" }, { "code": null, "e": 8432, "s": 8407, "text": "Hrishikesh Rai1 year ago" }, { "code": null, "e": 8447, "s": 8432, "text": "Hrishikesh Rai" }, { "code": null, "e": 8568, "s": 8447, "text": "CODE EASY TO UNDERSTANDhttps://ide.geeksforgeeks.o...IF AGAIN HAVING ANY PROBLEM, WATCH THIShttps://youtu.be/FjZdJ4aHdpU" }, { "code": null, "e": 8570, "s": 8568, "text": "0" }, { "code": null, "e": 8583, "s": 8570, "text": "Bharat Gupta" }, { "code": null, "e": 8609, "s": 8583, "text": "This comment was deleted." }, { "code": null, "e": 8755, "s": 8609, "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": 8791, "s": 8755, "text": " Login to access your submissions. " }, { "code": null, "e": 8801, "s": 8791, "text": "\nProblem\n" }, { "code": null, "e": 8811, "s": 8801, "text": "\nContest\n" }, { "code": null, "e": 8874, "s": 8811, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 9022, "s": 8874, "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": 9230, "s": 9022, "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": 9336, "s": 9230, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
JavaScript - For Loop
The 'for' loop is the most compact form of looping. It includes the following three important parts − The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins. The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins. The test statement which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop. The test statement which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop. The iteration statement where you can increase or decrease your counter. The iteration statement where you can increase or decrease your counter. You can put all the three parts in a single line separated by semicolons. The flow chart of a for loop in JavaScript would be as follows − The syntax of for loop is JavaScript is as follows − for (initialization; test condition; iteration statement) { Statement(s) to be executed if test condition is true } Try the following example to learn how a for loop works in JavaScript. <html> <body> <script type = "text/javascript"> <!-- var count; document.write("Starting Loop" + "<br />"); for(count = 0; count < 10; count++) { document.write("Current Count : " + count ); document.write("<br />"); } document.write("Loop stopped!"); //--> </script> <p>Set the variable to different value and then try...</p> </body> </html> Starting Loop Current Count : 0 Current Count : 1 Current Count : 2 Current Count : 3 Current Count : 4 Current Count : 5 Current Count : 6 Current Count : 7 Current Count : 8 Current Count : 9 Loop stopped! Set the variable to different value and then try... 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2568, "s": 2466, "text": "The 'for' loop is the most compact form of looping. It includes the following three important parts −" }, { "code": null, "e": 2710, "s": 2568, "text": "The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins." }, { "code": null, "e": 2852, "s": 2710, "text": "The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins." }, { "code": null, "e": 3053, "s": 2852, "text": "The test statement which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop." }, { "code": null, "e": 3254, "s": 3053, "text": "The test statement which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop." }, { "code": null, "e": 3327, "s": 3254, "text": "The iteration statement where you can increase or decrease your counter." }, { "code": null, "e": 3400, "s": 3327, "text": "The iteration statement where you can increase or decrease your counter." }, { "code": null, "e": 3474, "s": 3400, "text": "You can put all the three parts in a single line separated by semicolons." }, { "code": null, "e": 3539, "s": 3474, "text": "The flow chart of a for loop in JavaScript would be as follows −" }, { "code": null, "e": 3592, "s": 3539, "text": "The syntax of for loop is JavaScript is as follows −" }, { "code": null, "e": 3712, "s": 3592, "text": "for (initialization; test condition; iteration statement) {\n Statement(s) to be executed if test condition is true\n}\n" }, { "code": null, "e": 3783, "s": 3712, "text": "Try the following example to learn how a for loop works in JavaScript." }, { "code": null, "e": 4289, "s": 3783, "text": "<html>\n <body> \n <script type = \"text/javascript\">\n <!--\n var count;\n document.write(\"Starting Loop\" + \"<br />\");\n \n for(count = 0; count < 10; count++) {\n document.write(\"Current Count : \" + count );\n document.write(\"<br />\");\n } \n document.write(\"Loop stopped!\");\n //-->\n </script> \n <p>Set the variable to different value and then try...</p>\n </body>\n</html>" }, { "code": null, "e": 4551, "s": 4289, "text": "Starting Loop\nCurrent Count : 0\nCurrent Count : 1\nCurrent Count : 2\nCurrent Count : 3\nCurrent Count : 4\nCurrent Count : 5\nCurrent Count : 6\nCurrent Count : 7\nCurrent Count : 8\nCurrent Count : 9\nLoop stopped! \nSet the variable to different value and then try...\n" }, { "code": null, "e": 4586, "s": 4551, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4600, "s": 4586, "text": " Anadi Sharma" }, { "code": null, "e": 4634, "s": 4600, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 4648, "s": 4634, "text": " Lets Kode It" }, { "code": null, "e": 4683, "s": 4648, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4700, "s": 4683, "text": " Frahaan Hussain" }, { "code": null, "e": 4735, "s": 4700, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4752, "s": 4735, "text": " Frahaan Hussain" }, { "code": null, "e": 4785, "s": 4752, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 4813, "s": 4785, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4847, "s": 4813, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 4875, "s": 4847, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4882, "s": 4875, "text": " Print" }, { "code": null, "e": 4893, "s": 4882, "text": " Add Notes" } ]
Baseball Game in Python
Suppose we have a baseball game point recorder. We have a list of strings; each string can be one of the 4 following types − Integer (one round's score) − Indicates the number of points we get in this round. "+" (one round's score) − Indicates the points we get in this round are the sum of the last two valid round's points. "D" (one round's score ) − Indicates the points we get in this round are the doubled data of the last valid round's points. "C" (an operation, which isn't a round's score) − Indicates the last valid round's points we get were invalid and should be removed. Note that each round's operation is permanent and could have an impact on the round before and the round after. We have to find the sum of the points we could get in all the rounds. So, if the input is like ["5","2","C","D","+"], then the output will be 30. This is actually for Round 1 − We could get 5 points. The sum is: 5. Round 2 − We could get 2 points. The sum is: 7. Operation 1 − The data of the round 2 was invalid. The sum is: 5. Round 3 − We could get 10 points. The sum is: 15. Round 4 − We could get 5 + 10 = 15 points. The sum is: 30. To solve this, we will follow these steps − stack := empty list for each i in ops, doif i is same as "+", thenfirst := stack[size of stack - 1], second := stack[size of stack - 2]insert (first + second) into stack at the endotherwise when i is same as "D", theninsert (last element of stack * 2) into stack at the endotherwise when i is same as "C", thendelete last element from stackotherwise,insert i into stack at the end if i is same as "+", thenfirst := stack[size of stack - 1], second := stack[size of stack - 2]insert (first + second) into stack at the end first := stack[size of stack - 1], second := stack[size of stack - 2] insert (first + second) into stack at the end otherwise when i is same as "D", theninsert (last element of stack * 2) into stack at the end insert (last element of stack * 2) into stack at the end otherwise when i is same as "C", thendelete last element from stack delete last element from stack otherwise,insert i into stack at the end insert i into stack at the end return sum of all elements of stack Let us see the following implementation to get better understanding − Live Demo class Solution: def calPoints(self, ops): stack = [] for i in ops: if i == "+": first, second = stack[len(stack) - 1], stack[len(stack) - 2] stack.append(first + second) elif i == "D": stack.append(stack[-1] * 2) elif i == "C": stack.pop() else: stack.append(int(i)) return sum(stack) ob = Solution() print(ob.calPoints(["5","2","C","D","+"])) ["5","2","C","D","+"] 30
[ { "code": null, "e": 1187, "s": 1062, "text": "Suppose we have a baseball game point recorder. We have a list of strings; each string can be one of the 4 following types −" }, { "code": null, "e": 1270, "s": 1187, "text": "Integer (one round's score) − Indicates the number of points we get in this round." }, { "code": null, "e": 1388, "s": 1270, "text": "\"+\" (one round's score) − Indicates the points we get in this round are the sum of the last two valid round's points." }, { "code": null, "e": 1512, "s": 1388, "text": "\"D\" (one round's score ) − Indicates the points we get in this round are the doubled data of the last valid round's points." }, { "code": null, "e": 1645, "s": 1512, "text": "\"C\" (an operation, which isn't a round's score) − Indicates the last valid round's points we get were invalid and should be removed." }, { "code": null, "e": 1827, "s": 1645, "text": "Note that each round's operation is permanent and could have an impact on the round before and the round after. We have to find the sum of the points we could get in all the rounds." }, { "code": null, "e": 1924, "s": 1827, "text": "So, if the input is like [\"5\",\"2\",\"C\",\"D\",\"+\"], then the output will be 30. This is actually for" }, { "code": null, "e": 1972, "s": 1924, "text": "Round 1 − We could get 5 points. The sum is: 5." }, { "code": null, "e": 2020, "s": 1972, "text": "Round 2 − We could get 2 points. The sum is: 7." }, { "code": null, "e": 2086, "s": 2020, "text": "Operation 1 − The data of the round 2 was invalid. The sum is: 5." }, { "code": null, "e": 2136, "s": 2086, "text": "Round 3 − We could get 10 points. The sum is: 15." }, { "code": null, "e": 2195, "s": 2136, "text": "Round 4 − We could get 5 + 10 = 15 points. The sum is: 30." }, { "code": null, "e": 2239, "s": 2195, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 2259, "s": 2239, "text": "stack := empty list" }, { "code": null, "e": 2620, "s": 2259, "text": "for each i in ops, doif i is same as \"+\", thenfirst := stack[size of stack - 1], second := stack[size of stack - 2]insert (first + second) into stack at the endotherwise when i is same as \"D\", theninsert (last element of stack * 2) into stack at the endotherwise when i is same as \"C\", thendelete last element from stackotherwise,insert i into stack at the end" }, { "code": null, "e": 2760, "s": 2620, "text": "if i is same as \"+\", thenfirst := stack[size of stack - 1], second := stack[size of stack - 2]insert (first + second) into stack at the end" }, { "code": null, "e": 2830, "s": 2760, "text": "first := stack[size of stack - 1], second := stack[size of stack - 2]" }, { "code": null, "e": 2876, "s": 2830, "text": "insert (first + second) into stack at the end" }, { "code": null, "e": 2970, "s": 2876, "text": "otherwise when i is same as \"D\", theninsert (last element of stack * 2) into stack at the end" }, { "code": null, "e": 3027, "s": 2970, "text": "insert (last element of stack * 2) into stack at the end" }, { "code": null, "e": 3095, "s": 3027, "text": "otherwise when i is same as \"C\", thendelete last element from stack" }, { "code": null, "e": 3126, "s": 3095, "text": "delete last element from stack" }, { "code": null, "e": 3167, "s": 3126, "text": "otherwise,insert i into stack at the end" }, { "code": null, "e": 3198, "s": 3167, "text": "insert i into stack at the end" }, { "code": null, "e": 3234, "s": 3198, "text": "return sum of all elements of stack" }, { "code": null, "e": 3304, "s": 3234, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 3315, "s": 3304, "text": " Live Demo" }, { "code": null, "e": 3788, "s": 3315, "text": "class Solution:\n def calPoints(self, ops):\n stack = []\n for i in ops:\n if i == \"+\":\n first, second = stack[len(stack) - 1],\n stack[len(stack) - 2]\n stack.append(first + second)\n elif i == \"D\":\n stack.append(stack[-1] * 2)\n elif i == \"C\":\n stack.pop()\n else:\n stack.append(int(i))\n return sum(stack)\nob = Solution()\nprint(ob.calPoints([\"5\",\"2\",\"C\",\"D\",\"+\"]))" }, { "code": null, "e": 3810, "s": 3788, "text": "[\"5\",\"2\",\"C\",\"D\",\"+\"]" }, { "code": null, "e": 3813, "s": 3810, "text": "30" } ]
Getting Started with Python Classes | by Sadrach Pierre, Ph.D. | Towards Data Science
In computer programming, classes are a convenient way to organize data and functions such that they are easy to reuse and extend later. In this post, we will walk through how to build a basic class in python. Specifically, we will discuss the example of implementing a class that represents instagram users. Let’s get started! To start, let’s define a simple class that represents Instagram Users. Initially we won’t include any data (attributes) or functions (methods): class Instagram_User: pass Two import concepts to understand in object-oriented program are classes and class instances. A user of the Instagram platform can be considered an instance of the ‘Instagram_User’ class. The distinction here is that the ‘Instagram_User’ class serves as a blueprint for creating Instagram users, and an instance of the ‘Instagram_User’ class may refer to a specific user. To see this, we can define two Instagram user instances, insta_user_1 and insta_user_2: insta_user_1 = Instagram_User()insta_user_2 = Instagram_User() Each of these users will be their own unique instances of the Instagram_User class. We can print both objects: print("User Object 1: ", insta_user_1)print("User Object 2: ", insta_user_2) Here we can see that each object has a unique memory address. Next thing we can do is create variables for each instance. Let’s define instance variables that holds the user name of each user: insta_user_1.user_name = 'nychef100'insta_user_2.user_name = 'worldtraveler123' We can also define the name of each user: insta_user_1.name = 'Jake Cohen'insta_user_2.name = 'Maria Lopez' the email address: insta_user_1.email = 'jcohen100@gmail.com'insta_user_2.email = 'mlopez123@gmail.com' Finally let’s define an instance variable that tells us whether or not each user has a private account: insta_user_1.private = Trueinsta_user_2.private = False Now each instance has attribute values unique to each user. Let’s print the user names: print(insta_user_1.user_name)print(insta_user_2.user_name) Ideally, we’d like to set all of this information for each user automatically, instead of setting these values manually. To get the full benefit of classes, we should define a method that allows us to initialize each user instance with the values we defined manually. The initialization method, which is basically a constructor, is going to be called ‘__init__’: class Instagram_User: def __init__(self, user_name, name, email, private): self.user_name = user_name self.name = name self.email = email self.private = private Here, the ‘self’ parameter is the instance and is what will allows us to share attribute information within the instance. For example, when we write: insta_user_1 = Instagram_User('nychef100', 'Jake Cohen', 'jcohen100@gmail.com', True)insta_user_2 = Instagram_User('worldtraveler123', 'Maria Lopez', 'mlopez123@gmail.com', False) the ‘self’ parameters in each case are the insta_user_1 and insta_user_2 objects respectively. If we print the emails we see: print(insta_user_1.email)print(insta_user_2.email) This allows us to define attributes with significantly less code than when we defined them manually. Now suppose we’d like to perform some operation on the attributes of each user. For example, we can define a method that tells us whether or not a user has a private account. In our method, we print “User has a Private Account”, if ‘self.private’ is True, otherwise, we print “User has a Public Account”: def isPrivate(self): if self.private: print("{} has a Private Account".format(self.name)) else: print("{} has a Public Account".format(self.name)) The full script should look as follows: class Instagram_User: def __init__(self, user_name, name, email, private): self.user_name = user_name self.name = name self.email = email self.private = private def isPrivate(self): if self.private: print("{} has a Private Account".format(self.name)) else: print("{} has a Public Account".format(self.name)) Let’s call the method using the insta_user_1 instance: insta_user_1.isPrivate() And on insta_user_2: insta_user_2.isPrivate() As you can see, since the ‘self’ parameter is passed to ‘__init__’ and ‘isPrivate’, upon initialization the ‘isPrivate’ method has full access to the attributes of the corresponding instance. I’ll stop here but feel free to play around with the code. For example, you can try defining a few additional user instances of the Instagram_User class. From there you can practice pulling instance attributes and using the class method ‘isPrivate’. Once you feel comfortable I encourage you to define additional class methods. An interesting method could be one that displays user metrics such as the number of followers, number of people a user follows, and number of posts. To summarize, in this post we discussed the basics of defining classes in python. We showed how to define instances of classes, initialize instances, access instance attributes, and manipulate attributes with methods. The code from this post is available on GitHub. Thank you for reading!
[ { "code": null, "e": 480, "s": 172, "text": "In computer programming, classes are a convenient way to organize data and functions such that they are easy to reuse and extend later. In this post, we will walk through how to build a basic class in python. Specifically, we will discuss the example of implementing a class that represents instagram users." }, { "code": null, "e": 499, "s": 480, "text": "Let’s get started!" }, { "code": null, "e": 643, "s": 499, "text": "To start, let’s define a simple class that represents Instagram Users. Initially we won’t include any data (attributes) or functions (methods):" }, { "code": null, "e": 673, "s": 643, "text": "class Instagram_User: pass" }, { "code": null, "e": 1133, "s": 673, "text": "Two import concepts to understand in object-oriented program are classes and class instances. A user of the Instagram platform can be considered an instance of the ‘Instagram_User’ class. The distinction here is that the ‘Instagram_User’ class serves as a blueprint for creating Instagram users, and an instance of the ‘Instagram_User’ class may refer to a specific user. To see this, we can define two Instagram user instances, insta_user_1 and insta_user_2:" }, { "code": null, "e": 1196, "s": 1133, "text": "insta_user_1 = Instagram_User()insta_user_2 = Instagram_User()" }, { "code": null, "e": 1307, "s": 1196, "text": "Each of these users will be their own unique instances of the Instagram_User class. We can print both objects:" }, { "code": null, "e": 1384, "s": 1307, "text": "print(\"User Object 1: \", insta_user_1)print(\"User Object 2: \", insta_user_2)" }, { "code": null, "e": 1577, "s": 1384, "text": "Here we can see that each object has a unique memory address. Next thing we can do is create variables for each instance. Let’s define instance variables that holds the user name of each user:" }, { "code": null, "e": 1657, "s": 1577, "text": "insta_user_1.user_name = 'nychef100'insta_user_2.user_name = 'worldtraveler123'" }, { "code": null, "e": 1699, "s": 1657, "text": "We can also define the name of each user:" }, { "code": null, "e": 1765, "s": 1699, "text": "insta_user_1.name = 'Jake Cohen'insta_user_2.name = 'Maria Lopez'" }, { "code": null, "e": 1784, "s": 1765, "text": "the email address:" }, { "code": null, "e": 1869, "s": 1784, "text": "insta_user_1.email = 'jcohen100@gmail.com'insta_user_2.email = 'mlopez123@gmail.com'" }, { "code": null, "e": 1973, "s": 1869, "text": "Finally let’s define an instance variable that tells us whether or not each user has a private account:" }, { "code": null, "e": 2029, "s": 1973, "text": "insta_user_1.private = Trueinsta_user_2.private = False" }, { "code": null, "e": 2117, "s": 2029, "text": "Now each instance has attribute values unique to each user. Let’s print the user names:" }, { "code": null, "e": 2176, "s": 2117, "text": "print(insta_user_1.user_name)print(insta_user_2.user_name)" }, { "code": null, "e": 2539, "s": 2176, "text": "Ideally, we’d like to set all of this information for each user automatically, instead of setting these values manually. To get the full benefit of classes, we should define a method that allows us to initialize each user instance with the values we defined manually. The initialization method, which is basically a constructor, is going to be called ‘__init__’:" }, { "code": null, "e": 2731, "s": 2539, "text": "class Instagram_User: def __init__(self, user_name, name, email, private): self.user_name = user_name self.name = name self.email = email self.private = private" }, { "code": null, "e": 2881, "s": 2731, "text": "Here, the ‘self’ parameter is the instance and is what will allows us to share attribute information within the instance. For example, when we write:" }, { "code": null, "e": 3061, "s": 2881, "text": "insta_user_1 = Instagram_User('nychef100', 'Jake Cohen', 'jcohen100@gmail.com', True)insta_user_2 = Instagram_User('worldtraveler123', 'Maria Lopez', 'mlopez123@gmail.com', False)" }, { "code": null, "e": 3187, "s": 3061, "text": "the ‘self’ parameters in each case are the insta_user_1 and insta_user_2 objects respectively. If we print the emails we see:" }, { "code": null, "e": 3238, "s": 3187, "text": "print(insta_user_1.email)print(insta_user_2.email)" }, { "code": null, "e": 3644, "s": 3238, "text": "This allows us to define attributes with significantly less code than when we defined them manually. Now suppose we’d like to perform some operation on the attributes of each user. For example, we can define a method that tells us whether or not a user has a private account. In our method, we print “User has a Private Account”, if ‘self.private’ is True, otherwise, we print “User has a Public Account”:" }, { "code": null, "e": 3827, "s": 3644, "text": "def isPrivate(self): if self.private: print(\"{} has a Private Account\".format(self.name)) else: print(\"{} has a Public Account\".format(self.name))" }, { "code": null, "e": 3867, "s": 3827, "text": "The full script should look as follows:" }, { "code": null, "e": 4245, "s": 3867, "text": "class Instagram_User: def __init__(self, user_name, name, email, private): self.user_name = user_name self.name = name self.email = email self.private = private def isPrivate(self): if self.private: print(\"{} has a Private Account\".format(self.name)) else: print(\"{} has a Public Account\".format(self.name))" }, { "code": null, "e": 4300, "s": 4245, "text": "Let’s call the method using the insta_user_1 instance:" }, { "code": null, "e": 4325, "s": 4300, "text": "insta_user_1.isPrivate()" }, { "code": null, "e": 4346, "s": 4325, "text": "And on insta_user_2:" }, { "code": null, "e": 4371, "s": 4346, "text": "insta_user_2.isPrivate()" }, { "code": null, "e": 4563, "s": 4371, "text": "As you can see, since the ‘self’ parameter is passed to ‘__init__’ and ‘isPrivate’, upon initialization the ‘isPrivate’ method has full access to the attributes of the corresponding instance." }, { "code": null, "e": 5040, "s": 4563, "text": "I’ll stop here but feel free to play around with the code. For example, you can try defining a few additional user instances of the Instagram_User class. From there you can practice pulling instance attributes and using the class method ‘isPrivate’. Once you feel comfortable I encourage you to define additional class methods. An interesting method could be one that displays user metrics such as the number of followers, number of people a user follows, and number of posts." } ]
Check if the camera is opened or not using OpenCV-Python - GeeksforGeeks
07 Oct, 2021 OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on Images or videos. OpenCV library can be used to perform multiple operations on videos. While writing code in Python using OpenCV, we may not be sure whether at the remote end camera is opened and working properly or not. The camera plays an essential role in areas such as Security and Video Surveillance System. In a real-time video monitoring system, to ensure that the camera is opened and working properly we have isOpened() of OpenCV. The idea behind the article is to check whether the camera is connected and if the camera is found to be disconnected then a mail will be sent to the Admin or the concerned person. 1. Check whether the camera is opened/connected or not. Approach: Importing necessary libraries(NumPy and OpenCV) Starting camera. Here, in VideoCapture()-0 denotes built-in webcam while 1 will denote the use of external webcams. If the camera is opened, we will loop over frames whereas in the other case, a message “Alert! Camera disconnected” will be printed on the terminal window. Below is the implementation. # Python program to check# whether the camera is opened # or not import numpy as npimport cv2 cap = cv2.VideoCapture(0)while(cap.isOpened()): while True: ret, img = cap.read() cv2.imshow('img', img) if cv2.waitKey(30) & 0xff == ord('q'): break cap.release() cv2.destroyAllWindows()else: print("Alert ! Camera disconnected") 2. Sending Mail if camera is found to be disconnected/not opened. Approach: Import the necessary libraries(smtplib is the python library to send mails). Establish a connection with the server and login to the account. Specify the receiver’s email address and message to be sent (“Alert! Camera disconnected!” in this case). Once the mail is sent, close the connection or quit the session. Below is the implementation. # Python program to send # the mail import smtplib conn = smtplib.SMTP('smtp.gmail.com', 587) conn.ehlo()conn.starttls() # Enter the sender's detailsconn.login('Enter sender \'s gmail address', 'Enter sender\'s password') conn.sendmail('Enter sender\'s gmail address', 'Enter Receiver\'s gmail address', 'Enter message to be sent') conn.quit() sagar0719kumar Python-OpenCV 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 Check if element exists in list in Python How To Convert Python Dictionary To JSON? Defaultdict in Python Python | os.path.join() method Create a directory in Python Bar Plot in Matplotlib
[ { "code": null, "e": 24212, "s": 24184, "text": "\n07 Oct, 2021" }, { "code": null, "e": 24422, "s": 24212, "text": "OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on Images or videos. OpenCV library can be used to perform multiple operations on videos." }, { "code": null, "e": 24956, "s": 24422, "text": "While writing code in Python using OpenCV, we may not be sure whether at the remote end camera is opened and working properly or not. The camera plays an essential role in areas such as Security and Video Surveillance System. In a real-time video monitoring system, to ensure that the camera is opened and working properly we have isOpened() of OpenCV. The idea behind the article is to check whether the camera is connected and if the camera is found to be disconnected then a mail will be sent to the Admin or the concerned person." }, { "code": null, "e": 25012, "s": 24956, "text": "1. Check whether the camera is opened/connected or not." }, { "code": null, "e": 25022, "s": 25012, "text": "Approach:" }, { "code": null, "e": 25070, "s": 25022, "text": "Importing necessary libraries(NumPy and OpenCV)" }, { "code": null, "e": 25186, "s": 25070, "text": "Starting camera. Here, in VideoCapture()-0 denotes built-in webcam while 1 will denote the use of external webcams." }, { "code": null, "e": 25342, "s": 25186, "text": "If the camera is opened, we will loop over frames whereas in the other case, a message “Alert! Camera disconnected” will be printed on the terminal window." }, { "code": null, "e": 25371, "s": 25342, "text": "Below is the implementation." }, { "code": "# Python program to check# whether the camera is opened # or not import numpy as npimport cv2 cap = cv2.VideoCapture(0)while(cap.isOpened()): while True: ret, img = cap.read() cv2.imshow('img', img) if cv2.waitKey(30) & 0xff == ord('q'): break cap.release() cv2.destroyAllWindows()else: print(\"Alert ! Camera disconnected\")", "e": 25775, "s": 25371, "text": null }, { "code": null, "e": 25841, "s": 25775, "text": "2. Sending Mail if camera is found to be disconnected/not opened." }, { "code": null, "e": 25851, "s": 25841, "text": "Approach:" }, { "code": null, "e": 25928, "s": 25851, "text": "Import the necessary libraries(smtplib is the python library to send mails)." }, { "code": null, "e": 25993, "s": 25928, "text": "Establish a connection with the server and login to the account." }, { "code": null, "e": 26099, "s": 25993, "text": "Specify the receiver’s email address and message to be sent (“Alert! Camera disconnected!” in this case)." }, { "code": null, "e": 26164, "s": 26099, "text": "Once the mail is sent, close the connection or quit the session." }, { "code": null, "e": 26193, "s": 26164, "text": "Below is the implementation." }, { "code": "# Python program to send # the mail import smtplib conn = smtplib.SMTP('smtp.gmail.com', 587) conn.ehlo()conn.starttls() # Enter the sender's detailsconn.login('Enter sender \\'s gmail address', 'Enter sender\\'s password') conn.sendmail('Enter sender\\'s gmail address', 'Enter Receiver\\'s gmail address', 'Enter message to be sent') conn.quit()", "e": 26586, "s": 26193, "text": null }, { "code": null, "e": 26601, "s": 26586, "text": "sagar0719kumar" }, { "code": null, "e": 26615, "s": 26601, "text": "Python-OpenCV" }, { "code": null, "e": 26622, "s": 26615, "text": "Python" }, { "code": null, "e": 26720, "s": 26622, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26729, "s": 26720, "text": "Comments" }, { "code": null, "e": 26742, "s": 26729, "text": "Old Comments" }, { "code": null, "e": 26774, "s": 26742, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26829, "s": 26774, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26885, "s": 26829, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26924, "s": 26885, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26966, "s": 26924, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27008, "s": 26966, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27030, "s": 27008, "text": "Defaultdict in Python" }, { "code": null, "e": 27061, "s": 27030, "text": "Python | os.path.join() method" }, { "code": null, "e": 27090, "s": 27061, "text": "Create a directory in Python" } ]
Python | Reshape a list according to given multi list - GeeksforGeeks
25 Apr, 2019 Given two lists, a single dimensional and a multidimensional list, write Python program to reshape the single dimensional list according to the length of multidimensional list. Examples: Input : list1 = [[1], [2, 3], [4, 5, 6]] list2 = ['a', 'b', 'c', 'd', 'e', 'f'] Output : [['a'], ['b', 'c'], ['d', 'e', 'f']] Input : list1 = [[8, 2, 5], [1], [12, 4, 0, 24]] list2 = ['m', 'n', 'o', 'p', 'q', 'r', 's', 't'] Output : [['m', 'n', 'o'], ['p'], ['q', 'r', 's', 't']] Method #1 : Using extended slices A simple and naive method is to use a for loop and Python extended slices to append each sublist of list2 to a variable ‘res’. # Python3 program to reshape a list # according to multidimensional list def reshape(lst1, lst2): last = 0 res = [] for ele in list1: res.append(list2[last : last + len(ele)]) last += len(ele) return res # Driver codelist1 = [[1], [2, 3], [4, 5, 6]]list2 = ['a', 'b', 'c', 'd', 'e', 'f']print(reshape(list1, list2)) [['a'], ['b', 'c'], ['d', 'e', 'f']] Method #2 : islice from itertools module Another method is to use islice function from itertools module. islice selectively prints the values mentioned in its iterable container. Thus, we yield slices of list2 according to list1 and append it to variable ‘res’. # Python3 program to reshape a list # according to multidimensional listfrom itertools import islice def yieldSublist(lst1, lst2): iter2 = iter(lst2) for sublist1 in lst1: sublist2 = list(islice(iter2, len(sublist1))) yield sublist2 def reshape(lst1, lst2): res = list() for sub2 in yieldSublist(list1, list2): res.append(sub2) return res # Driver codelist1 = [[1], [2, 3], [4, 5, 6]]list2 = ['a', 'b', 'c', 'd', 'e', 'f']print(reshape(list1, list2)) [['a'], ['b', 'c'], ['d', 'e', 'f']] Method #3 : Python iterator with list comprehension The iter() method returns an iterator for list2 and save it in variable ‘iterator’. Now using list comprehension reshape list2 according to list1. # Python3 program to reshape a list # according to multidimensional list def reshape(lst1, lst2): iterator = iter(lst2) return [[next(iterator) for _ in sublist] for sublist in lst1] # Driver codelist1 = [[1], [2, 3], [4, 5, 6]]list2 = ['a', 'b', 'c', 'd', 'e', 'f']print(reshape(list1, list2)) [['a'], ['b', 'c'], ['d', 'e', 'f']] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25665, "s": 25637, "text": "\n25 Apr, 2019" }, { "code": null, "e": 25842, "s": 25665, "text": "Given two lists, a single dimensional and a multidimensional list, write Python program to reshape the single dimensional list according to the length of multidimensional list." }, { "code": null, "e": 25852, "s": 25842, "text": "Examples:" }, { "code": null, "e": 26150, "s": 25852, "text": "Input : list1 = [[1], [2, 3], [4, 5, 6]]\n list2 = ['a', 'b', 'c', 'd', 'e', 'f']\nOutput : [['a'], ['b', 'c'], ['d', 'e', 'f']]\n\nInput : list1 = [[8, 2, 5], [1], [12, 4, 0, 24]]\n list2 = ['m', 'n', 'o', 'p', 'q', 'r', 's', 't']\nOutput : [['m', 'n', 'o'], ['p'], ['q', 'r', 's', 't']]\n" }, { "code": null, "e": 26185, "s": 26150, "text": " Method #1 : Using extended slices" }, { "code": null, "e": 26312, "s": 26185, "text": "A simple and naive method is to use a for loop and Python extended slices to append each sublist of list2 to a variable ‘res’." }, { "code": "# Python3 program to reshape a list # according to multidimensional list def reshape(lst1, lst2): last = 0 res = [] for ele in list1: res.append(list2[last : last + len(ele)]) last += len(ele) return res # Driver codelist1 = [[1], [2, 3], [4, 5, 6]]list2 = ['a', 'b', 'c', 'd', 'e', 'f']print(reshape(list1, list2))", "e": 26674, "s": 26312, "text": null }, { "code": null, "e": 26712, "s": 26674, "text": "[['a'], ['b', 'c'], ['d', 'e', 'f']]\n" }, { "code": null, "e": 26754, "s": 26712, "text": " Method #2 : islice from itertools module" }, { "code": null, "e": 26975, "s": 26754, "text": "Another method is to use islice function from itertools module. islice selectively prints the values mentioned in its iterable container. Thus, we yield slices of list2 according to list1 and append it to variable ‘res’." }, { "code": "# Python3 program to reshape a list # according to multidimensional listfrom itertools import islice def yieldSublist(lst1, lst2): iter2 = iter(lst2) for sublist1 in lst1: sublist2 = list(islice(iter2, len(sublist1))) yield sublist2 def reshape(lst1, lst2): res = list() for sub2 in yieldSublist(list1, list2): res.append(sub2) return res # Driver codelist1 = [[1], [2, 3], [4, 5, 6]]list2 = ['a', 'b', 'c', 'd', 'e', 'f']print(reshape(list1, list2))", "e": 27483, "s": 26975, "text": null }, { "code": null, "e": 27521, "s": 27483, "text": "[['a'], ['b', 'c'], ['d', 'e', 'f']]\n" }, { "code": null, "e": 27575, "s": 27523, "text": "Method #3 : Python iterator with list comprehension" }, { "code": null, "e": 27722, "s": 27575, "text": "The iter() method returns an iterator for list2 and save it in variable ‘iterator’. Now using list comprehension reshape list2 according to list1." }, { "code": "# Python3 program to reshape a list # according to multidimensional list def reshape(lst1, lst2): iterator = iter(lst2) return [[next(iterator) for _ in sublist] for sublist in lst1] # Driver codelist1 = [[1], [2, 3], [4, 5, 6]]list2 = ['a', 'b', 'c', 'd', 'e', 'f']print(reshape(list1, list2))", "e": 28050, "s": 27722, "text": null }, { "code": null, "e": 28088, "s": 28050, "text": "[['a'], ['b', 'c'], ['d', 'e', 'f']]\n" }, { "code": null, "e": 28109, "s": 28088, "text": "Python list-programs" }, { "code": null, "e": 28116, "s": 28109, "text": "Python" }, { "code": null, "e": 28132, "s": 28116, "text": "Python Programs" }, { "code": null, "e": 28230, "s": 28132, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28262, "s": 28230, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28304, "s": 28262, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28346, "s": 28304, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28402, "s": 28346, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28429, "s": 28402, "text": "Python Classes and Objects" }, { "code": null, "e": 28451, "s": 28429, "text": "Defaultdict in Python" }, { "code": null, "e": 28490, "s": 28451, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28536, "s": 28490, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28574, "s": 28536, "text": "Python | Convert a list to dictionary" } ]