title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Count of n digit numbers whose sum of digits equals to given sum | Practice | GeeksforGeeks
Given two integers ‘n’ and ‘sum’, find the count of all n digit numbers whose sum of digits is ‘sum’. Leading 0’s are not counted as digits. Example 1: Input: n = 2, sum = 2 Output: 2 Explaination: The 2 digit numbers are 11 and 20. Example 2: Input: n = 1, sum = 10 Output: -1 Explaination: We cannot get sum as 10 from a single digit. Your Task: You do not need to read input or print anything. Your task is to complete the function countWays() which takes the value n and sum as input parameters and returns the number of possible ways modulo 109+7. If there is no possible way then it returns -1. Expected Time Complexity: O(n*sum) Expected Auxiliary Space: O(n*sum) Constraints: 1 ≤ n ≤ 102 1 ≤ sum ≤ 103 0 imranwahid6 days ago Easy C++ solution using memoization 0 ankitpodder3 months ago Total Time Taken: 0.2/1.2 long int countWays(int N, int Sum){ lli ans = 0; vvlli dp(N+1 , vector<lli>(Sum+1 , 0)); dp[0][0] = 1; for(int n = 1 ; n <= N ; n++){ for(int s = 1 ; s <= Sum ; s++){ for(int d = 0 ; d < min(10 , s+1) ; d++ ){ if(d == 0 && n == 1) continue; lli r = (dp[n-1][s-d] % di); dp[n][s] += r; dp[n][s] %= di; } } } return dp[N][Sum]==0 ? -1 : dp[N][Sum]; } 0 VickySam19019 months ago VickySam1901 class Solution{public: long int count(int n,int sum,vector<vector<int>> &vec){ if(n==0){ return sum==0; } if(vec[n][sum]!=-1){ return vec[n][sum]; } long int ans=0; for(int i=0;i<=9;i++){ if(sum-i>=0){ ans+=count(n-1,sum-i,vec); ans=ans%1000000007; } } return vec[n][sum]=ans; } long int countWays(int n, int Sum){ vector<vector<int>> vec(n+1,vector<int>(Sum+1,-1)); long int ans=0; for(int i=1;i<=9;i++){ if(Sum-i>=0){ ans+=count(n-1,Sum-i,vec); ans=ans%1000000007; } } return ans?ans:-1; }}; 0 VickySam1901 This comment was deleted. 0 Debjyoti Chattopadhyay10 months ago Debjyoti Chattopadhyay class Solution{ static long countWays(int n, int Sum) { long store[][]=new long[n+1][Sum+1]; for(int i=0;i<=n;i++){ for(int j=0;j<=Sum;j++) store[i][j]=-1; } long val=dp(n,Sum,store); if(val==0) return(-1); return(val); }//countWays public static long dp(int i,int sum,long store[][]){ if(sum<=0 && i!=0) return(0); if(i==1){ if(sum<10) return(1); return(0); } if(store[i][sum]!=-1) return(store[i][sum]); long ans=0; for(int j=0;j<=9;j++){ long v=dp(i-1,sum-j,store); ans=(ans+v)%1000000007; } store[i][sum]=ans%1000000007; return(ans); }//dp}//SolutionJAVA soln 0 HUNTER10 months ago HUNTER long int countWays(int n, int Sum){ // code here if(n==1&&Sum<10) return 1; long int dp[n+1][Sum+1]; memset(dp,0,sizeof dp); dp[0][0]=1; for(int i=1;i<=n;i++) for(int j=1;j<=Sum;j++) for(int k=0;k<10&&k<=j;k++) dp[i][j]=(dp[i][j]+dp[i-1][j-k])%1000000007; return dp[n][Sum]?dp[n][Sum]:-1; } 0 Jdragon jds2 years ago Jdragon jds dude n*sum complexity thats the first thing came to my mind ,without dp 0 Archit2 years ago Archit Python Simple DP Solutionhttps://ide.geeksforgeeks.o... 0 Akshay Solanki2 years ago Akshay Solanki JAVA simple DP solution.https://ide.geeksforgeeks.o... 0 Sachin Negi2 years ago Sachin Negi python memoization https://ide.geeksforgeeks.o... We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 380, "s": 238, "text": "Given two integers ‘n’ and ‘sum’, find the count of all n digit numbers whose sum of digits is ‘sum’. Leading 0’s are not counted as digits. " }, { "code": null, "e": 392, "s": 380, "text": "\nExample 1:" }, { "code": null, "e": 474, "s": 392, "text": "Input: n = 2, sum = 2\nOutput: 2\nExplaination: \nThe 2 digit numbers are 11 and 20." }, { "code": null, "e": 486, "s": 474, "text": "\nExample 2:" }, { "code": null, "e": 580, "s": 486, "text": "Input: n = 1, sum = 10\nOutput: -1\nExplaination: \nWe cannot get sum as 10 from a single digit." }, { "code": null, "e": 845, "s": 580, "text": "\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function countWays() which takes the value n and sum as input parameters and returns the number of possible ways modulo 109+7. If there is no possible way then it returns -1." }, { "code": null, "e": 916, "s": 845, "text": "\nExpected Time Complexity: O(n*sum)\nExpected Auxiliary Space: O(n*sum)" }, { "code": null, "e": 956, "s": 916, "text": "\nConstraints:\n1 ≤ n ≤ 102\n1 ≤ sum ≤ 103" }, { "code": null, "e": 958, "s": 956, "text": "0" }, { "code": null, "e": 979, "s": 958, "text": "imranwahid6 days ago" }, { "code": null, "e": 1015, "s": 979, "text": "Easy C++ solution using memoization" }, { "code": null, "e": 1017, "s": 1015, "text": "0" }, { "code": null, "e": 1041, "s": 1017, "text": "ankitpodder3 months ago" }, { "code": null, "e": 1059, "s": 1041, "text": "Total Time Taken:" }, { "code": null, "e": 1067, "s": 1059, "text": "0.2/1.2" }, { "code": null, "e": 1640, "s": 1069, "text": "long int countWays(int N, int Sum){\n lli ans = 0;\n vvlli dp(N+1 , vector<lli>(Sum+1 , 0));\n dp[0][0] = 1;\n for(int n = 1 ; n <= N ; n++){\n for(int s = 1 ; s <= Sum ; s++){\n for(int d = 0 ; d < \n \tmin(10 , s+1) ; d++\n ){\n if(d == 0 && n == 1) continue;\n lli r = (dp[n-1][s-d] % di);\n dp[n][s] += r;\n dp[n][s] %= di;\n }\n }\n }\n return dp[N][Sum]==0 ? -1 : dp[N][Sum];\n }" }, { "code": null, "e": 1642, "s": 1640, "text": "0" }, { "code": null, "e": 1667, "s": 1642, "text": "VickySam19019 months ago" }, { "code": null, "e": 1680, "s": 1667, "text": "VickySam1901" }, { "code": null, "e": 2403, "s": 1680, "text": "class Solution{public: long int count(int n,int sum,vector<vector<int>> &vec){ if(n==0){ return sum==0; } if(vec[n][sum]!=-1){ return vec[n][sum]; } long int ans=0; for(int i=0;i<=9;i++){ if(sum-i>=0){ ans+=count(n-1,sum-i,vec); ans=ans%1000000007; } } return vec[n][sum]=ans; } long int countWays(int n, int Sum){ vector<vector<int>> vec(n+1,vector<int>(Sum+1,-1)); long int ans=0; for(int i=1;i<=9;i++){ if(Sum-i>=0){ ans+=count(n-1,Sum-i,vec); ans=ans%1000000007; } } return ans?ans:-1; }};" }, { "code": null, "e": 2405, "s": 2403, "text": "0" }, { "code": null, "e": 2418, "s": 2405, "text": "VickySam1901" }, { "code": null, "e": 2444, "s": 2418, "text": "This comment was deleted." }, { "code": null, "e": 2446, "s": 2444, "text": "0" }, { "code": null, "e": 2482, "s": 2446, "text": "Debjyoti Chattopadhyay10 months ago" }, { "code": null, "e": 2505, "s": 2482, "text": "Debjyoti Chattopadhyay" }, { "code": null, "e": 3307, "s": 2505, "text": "class Solution{ static long countWays(int n, int Sum) { long store[][]=new long[n+1][Sum+1]; for(int i=0;i<=n;i++){ for(int j=0;j<=Sum;j++) store[i][j]=-1; } long val=dp(n,Sum,store); if(val==0) return(-1); return(val); }//countWays public static long dp(int i,int sum,long store[][]){ if(sum<=0 && i!=0) return(0); if(i==1){ if(sum<10) return(1); return(0); } if(store[i][sum]!=-1) return(store[i][sum]); long ans=0; for(int j=0;j<=9;j++){ long v=dp(i-1,sum-j,store); ans=(ans+v)%1000000007; } store[i][sum]=ans%1000000007; return(ans); }//dp}//SolutionJAVA soln" }, { "code": null, "e": 3309, "s": 3307, "text": "0" }, { "code": null, "e": 3329, "s": 3309, "text": "HUNTER10 months ago" }, { "code": null, "e": 3336, "s": 3329, "text": "HUNTER" }, { "code": null, "e": 3701, "s": 3336, "text": "long int countWays(int n, int Sum){ // code here if(n==1&&Sum<10) return 1; long int dp[n+1][Sum+1]; memset(dp,0,sizeof dp); dp[0][0]=1; for(int i=1;i<=n;i++) for(int j=1;j<=Sum;j++) for(int k=0;k<10&&k<=j;k++) dp[i][j]=(dp[i][j]+dp[i-1][j-k])%1000000007; return dp[n][Sum]?dp[n][Sum]:-1; }" }, { "code": null, "e": 3703, "s": 3701, "text": "0" }, { "code": null, "e": 3726, "s": 3703, "text": "Jdragon jds2 years ago" }, { "code": null, "e": 3738, "s": 3726, "text": "Jdragon jds" }, { "code": null, "e": 3810, "s": 3738, "text": "dude n*sum complexity thats the first thing came to my mind ,without dp" }, { "code": null, "e": 3812, "s": 3810, "text": "0" }, { "code": null, "e": 3830, "s": 3812, "text": "Archit2 years ago" }, { "code": null, "e": 3837, "s": 3830, "text": "Archit" }, { "code": null, "e": 3893, "s": 3837, "text": "Python Simple DP Solutionhttps://ide.geeksforgeeks.o..." }, { "code": null, "e": 3895, "s": 3893, "text": "0" }, { "code": null, "e": 3921, "s": 3895, "text": "Akshay Solanki2 years ago" }, { "code": null, "e": 3936, "s": 3921, "text": "Akshay Solanki" }, { "code": null, "e": 3991, "s": 3936, "text": "JAVA simple DP solution.https://ide.geeksforgeeks.o..." }, { "code": null, "e": 3993, "s": 3991, "text": "0" }, { "code": null, "e": 4016, "s": 3993, "text": "Sachin Negi2 years ago" }, { "code": null, "e": 4028, "s": 4016, "text": "Sachin Negi" }, { "code": null, "e": 4079, "s": 4028, "text": "python memoization https://ide.geeksforgeeks.o..." }, { "code": null, "e": 4225, "s": 4079, "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": 4261, "s": 4225, "text": " Login to access your submissions. " }, { "code": null, "e": 4271, "s": 4261, "text": "\nProblem\n" }, { "code": null, "e": 4281, "s": 4271, "text": "\nContest\n" }, { "code": null, "e": 4344, "s": 4281, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4492, "s": 4344, "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": 4700, "s": 4492, "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": 4806, "s": 4700, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Maximum number of pieces in N cuts - GeeksforGeeks
20 Apr, 2021 Given a square piece and a total number of cuts available n, Find out the maximum number of rectangular or square pieces of equal size that can be obtained with n cuts. The allowed cuts are horizontal and vertical cut. Note: Stacking and folding is not allowed.Examples: Input : n = 1 Output : 2 Explanation : Input : n = 2 Output : 4 Explanation : Input : n = 3 Output : 6 Explanation : Given is n which is the number of allowed cuts. As it is required to maximize number of pieces after n cuts, So number of horizontal cuts will be equal to number of vertical cuts. This can be prove using differentiation. So number of horizontal cut will be n/2. and vertical cuts will be n-n/2.So number of pieces = (horizontal cut + 1) * (vertical cut + 1).Program: C++ Java Python 3 C# PHP Javascript // C++ program to find maximum no of pieces// by given number of cuts#include <bits/stdc++.h>using namespace std; // Function for finding maximum pieces// with n cuts.int findMaximumPieces(int n){ // to maximize number of pieces // x is the horizontal cuts int x = n / 2; // Now (x) is the horizontal cuts // and (n-x) is vertical cuts, then // maximum number of pieces = (x+1)*(n-x+1) return ((x + 1) * (n - x + 1));} // Driver codeint main(){ // Taking the maximum number of cuts allowed as 3 int n = 3; // Finding and printing the max number of pieces cout << "Max number of pieces for n = " << n << " is " << findMaximumPieces(3); return 0;} // Java program to find maximum// no of pieces by given number// of cutsimport java.util.*; class GFG{// Function for finding maximum// pieces with n cuts.public static int findMaximumPieces(int n){ // to maximize number of pieces // x is the horizontal cuts int x = n / 2; // Now (x) is the horizontal cuts // and (n-x) is vertical cuts, then // maximum number of pieces = (x+1)*(n-x+1) return ((x + 1) * (n - x + 1));} // Driver codepublic static void main (String[] args){ // Taking the maximum number // of cuts allowed as 3 int n = 3; // Finding and printing the // max number of pieces System.out.print("Max number of pieces for n = " + n + " is " + findMaximumPieces(3)); }} // This code is contributed by Kirti_Mangal # Python 3 program to find maximum no of pieces# by given number of cuts # Function for finding maximum pieces# with n cuts.def findMaximumPieces(n): # to maximize number of pieces # x is the horizontal cuts x = n // 2 # Now (x) is the horizontal cuts # and (n-x) is vertical cuts, then # maximum number of pieces = (x+1)*(n-x+1) return ((x + 1) * (n - x + 1)) # Driver codeif __name__ == "__main__": #Taking the maximum number of cuts allowed as 3 n = 3 # Finding and printing the max number of pieces print("Max number of pieces for n = " +str( n) +" is " + str(findMaximumPieces(3))) # This code is contributed by ChitraNayal // C# program to find maximum// no of pieces by given number// of cutsusing System; class GFG{ // Function for finding maximum// pieces with n cuts.public static int findMaximumPieces(int n){ // to maximize number of pieces // x is the horizontal cuts int x = n / 2; // Now (x) is the horizontal // cuts and (n-x) is vertical // cuts, then maximum number // of pieces = (x+1)*(n-x+1) return ((x + 1) * (n - x + 1));} // Driver codestatic public void Main (){ // Taking the maximum number // of cuts allowed as 3 int n = 3; // Finding and printing the // max number of pieces Console.Write("Max number of pieces for n = " + n + " is " + findMaximumPieces(3));}} // This code is contributed by Mahadev <?php// PHP program to find maximum no// of pieces by given number of cuts // Function for finding maximum// pieces with n cuts.function findMaximumPieces($n){ // to maximize number of pieces // x is the horizontal cuts $x = (int)($n / 2); // Now (x) is the horizontal cuts // and (n-x) is vertical cuts, then // maximum number of pieces = (x+1)*(n-x+1) return (($x + 1) * ($n - $x + 1));} // Driver code // Taking the maximum number// of cuts allowed as 3$n = 3; // Finding and printing the// max number of piecesecho "Max number of pieces for n = " . $n . " is " . findMaximumPieces(3); // This code is contributed// by Akanksha Rai(Abby_akku)?> <script> // Javascript program to find maximum no of pieces// by given number of cuts // Function for finding maximum pieces// with n cuts.function findMaximumPieces(n){ // to maximize number of pieces // x is the horizontal cuts var x = parseInt(n / 2); // Now (x) is the horizontal cuts // and (n-x) is vertical cuts, then // maximum number of pieces = (x+1)*(n-x+1) return ((x + 1) * (n - x + 1));} // Driver code// Taking the maximum number of cuts allowed as 3var n = 3; // Finding and printing the max number of piecesdocument.write("Max number of pieces for n = " + n + " is " + findMaximumPieces(3)); // This code is contributed by noob2000.</script> Max number of pieces for n = 3 is 6 Kirti_Mangal Mahadev99 Akanksha_Rai ukasp noob2000 math school-programming Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Circle and Lattice Points Program for distance between two points on earth Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping) Convex Hull | Set 2 (Graham Scan) Given n line segments, find if any two segments intersect 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": 24789, "s": 24761, "text": "\n20 Apr, 2021" }, { "code": null, "e": 25062, "s": 24789, "text": "Given a square piece and a total number of cuts available n, Find out the maximum number of rectangular or square pieces of equal size that can be obtained with n cuts. The allowed cuts are horizontal and vertical cut. Note: Stacking and folding is not allowed.Examples: " }, { "code": null, "e": 25102, "s": 25062, "text": "Input : n = 1\nOutput : 2\nExplanation : " }, { "code": null, "e": 25142, "s": 25102, "text": "Input : n = 2\nOutput : 4\nExplanation : " }, { "code": null, "e": 25182, "s": 25142, "text": "Input : n = 3\nOutput : 6\nExplanation : " }, { "code": null, "e": 25553, "s": 25184, "text": "Given is n which is the number of allowed cuts. As it is required to maximize number of pieces after n cuts, So number of horizontal cuts will be equal to number of vertical cuts. This can be prove using differentiation. So number of horizontal cut will be n/2. and vertical cuts will be n-n/2.So number of pieces = (horizontal cut + 1) * (vertical cut + 1).Program: " }, { "code": null, "e": 25557, "s": 25553, "text": "C++" }, { "code": null, "e": 25562, "s": 25557, "text": "Java" }, { "code": null, "e": 25571, "s": 25562, "text": "Python 3" }, { "code": null, "e": 25574, "s": 25571, "text": "C#" }, { "code": null, "e": 25578, "s": 25574, "text": "PHP" }, { "code": null, "e": 25589, "s": 25578, "text": "Javascript" }, { "code": "// C++ program to find maximum no of pieces// by given number of cuts#include <bits/stdc++.h>using namespace std; // Function for finding maximum pieces// with n cuts.int findMaximumPieces(int n){ // to maximize number of pieces // x is the horizontal cuts int x = n / 2; // Now (x) is the horizontal cuts // and (n-x) is vertical cuts, then // maximum number of pieces = (x+1)*(n-x+1) return ((x + 1) * (n - x + 1));} // Driver codeint main(){ // Taking the maximum number of cuts allowed as 3 int n = 3; // Finding and printing the max number of pieces cout << \"Max number of pieces for n = \" << n << \" is \" << findMaximumPieces(3); return 0;}", "e": 26283, "s": 25589, "text": null }, { "code": "// Java program to find maximum// no of pieces by given number// of cutsimport java.util.*; class GFG{// Function for finding maximum// pieces with n cuts.public static int findMaximumPieces(int n){ // to maximize number of pieces // x is the horizontal cuts int x = n / 2; // Now (x) is the horizontal cuts // and (n-x) is vertical cuts, then // maximum number of pieces = (x+1)*(n-x+1) return ((x + 1) * (n - x + 1));} // Driver codepublic static void main (String[] args){ // Taking the maximum number // of cuts allowed as 3 int n = 3; // Finding and printing the // max number of pieces System.out.print(\"Max number of pieces for n = \" + n + \" is \" + findMaximumPieces(3)); }} // This code is contributed by Kirti_Mangal", "e": 27080, "s": 26283, "text": null }, { "code": "# Python 3 program to find maximum no of pieces# by given number of cuts # Function for finding maximum pieces# with n cuts.def findMaximumPieces(n): # to maximize number of pieces # x is the horizontal cuts x = n // 2 # Now (x) is the horizontal cuts # and (n-x) is vertical cuts, then # maximum number of pieces = (x+1)*(n-x+1) return ((x + 1) * (n - x + 1)) # Driver codeif __name__ == \"__main__\": #Taking the maximum number of cuts allowed as 3 n = 3 # Finding and printing the max number of pieces print(\"Max number of pieces for n = \" +str( n) +\" is \" + str(findMaximumPieces(3))) # This code is contributed by ChitraNayal", "e": 27759, "s": 27080, "text": null }, { "code": "// C# program to find maximum// no of pieces by given number// of cutsusing System; class GFG{ // Function for finding maximum// pieces with n cuts.public static int findMaximumPieces(int n){ // to maximize number of pieces // x is the horizontal cuts int x = n / 2; // Now (x) is the horizontal // cuts and (n-x) is vertical // cuts, then maximum number // of pieces = (x+1)*(n-x+1) return ((x + 1) * (n - x + 1));} // Driver codestatic public void Main (){ // Taking the maximum number // of cuts allowed as 3 int n = 3; // Finding and printing the // max number of pieces Console.Write(\"Max number of pieces for n = \" + n + \" is \" + findMaximumPieces(3));}} // This code is contributed by Mahadev", "e": 28523, "s": 27759, "text": null }, { "code": "<?php// PHP program to find maximum no// of pieces by given number of cuts // Function for finding maximum// pieces with n cuts.function findMaximumPieces($n){ // to maximize number of pieces // x is the horizontal cuts $x = (int)($n / 2); // Now (x) is the horizontal cuts // and (n-x) is vertical cuts, then // maximum number of pieces = (x+1)*(n-x+1) return (($x + 1) * ($n - $x + 1));} // Driver code // Taking the maximum number// of cuts allowed as 3$n = 3; // Finding and printing the// max number of piecesecho \"Max number of pieces for n = \" . $n . \" is \" . findMaximumPieces(3); // This code is contributed// by Akanksha Rai(Abby_akku)?>", "e": 29196, "s": 28523, "text": null }, { "code": "<script> // Javascript program to find maximum no of pieces// by given number of cuts // Function for finding maximum pieces// with n cuts.function findMaximumPieces(n){ // to maximize number of pieces // x is the horizontal cuts var x = parseInt(n / 2); // Now (x) is the horizontal cuts // and (n-x) is vertical cuts, then // maximum number of pieces = (x+1)*(n-x+1) return ((x + 1) * (n - x + 1));} // Driver code// Taking the maximum number of cuts allowed as 3var n = 3; // Finding and printing the max number of piecesdocument.write(\"Max number of pieces for n = \" + n + \" is \" + findMaximumPieces(3)); // This code is contributed by noob2000.</script>", "e": 29881, "s": 29196, "text": null }, { "code": null, "e": 29917, "s": 29881, "text": "Max number of pieces for n = 3 is 6" }, { "code": null, "e": 29932, "s": 29919, "text": "Kirti_Mangal" }, { "code": null, "e": 29942, "s": 29932, "text": "Mahadev99" }, { "code": null, "e": 29955, "s": 29942, "text": "Akanksha_Rai" }, { "code": null, "e": 29961, "s": 29955, "text": "ukasp" }, { "code": null, "e": 29970, "s": 29961, "text": "noob2000" }, { "code": null, "e": 29975, "s": 29970, "text": "math" }, { "code": null, "e": 29994, "s": 29975, "text": "school-programming" }, { "code": null, "e": 30004, "s": 29994, "text": "Geometric" }, { "code": null, "e": 30017, "s": 30004, "text": "Mathematical" }, { "code": null, "e": 30030, "s": 30017, "text": "Mathematical" }, { "code": null, "e": 30040, "s": 30030, "text": "Geometric" }, { "code": null, "e": 30138, "s": 30040, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30147, "s": 30138, "text": "Comments" }, { "code": null, "e": 30160, "s": 30147, "text": "Old Comments" }, { "code": null, "e": 30186, "s": 30160, "text": "Circle and Lattice Points" }, { "code": null, "e": 30235, "s": 30186, "text": "Program for distance between two points on earth" }, { "code": null, "e": 30288, "s": 30235, "text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)" }, { "code": null, "e": 30322, "s": 30288, "text": "Convex Hull | Set 2 (Graham Scan)" }, { "code": null, "e": 30380, "s": 30322, "text": "Given n line segments, find if any two segments intersect" }, { "code": null, "e": 30410, "s": 30380, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 30470, "s": 30410, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 30485, "s": 30470, "text": "C++ Data Types" }, { "code": null, "e": 30528, "s": 30485, "text": "Set in C++ Standard Template Library (STL)" } ]
K-NN Classifier in R Programming - GeeksforGeeks
22 Jun, 2020 K-Nearest Neighbor or K-NN is a Supervised Non-linear classification algorithm. K-NN is a Non-parametric algorithm i.e it doesn’t make any assumption about underlying data or its distribution. It is one of the simplest and widely used algorithm which depends on it’s k value(Neighbors) and finds it’s applications in many industries like finance industry, healthcare industry etc. In the KNN algorithm, K specifies the number of neighbors and its algorithm is as follows: Choose the number K of neighbor. Take the K Nearest Neighbor of unknown data point according to distance. Among the K-neighbors, Count the number of data points in each category. Assign the new data point to a category, where you counted the most neighbors. For the Nearest Neighbor classifier, the distance between two points is expressed in the form of Euclidean Distance. Example:Consider a dataset containing two features Red and Blue and we classify them. Here K is 5 i.e we are considering 5 neighbors according to Euclidean distance. So, when a new data point enters, out of 5 neighbors, 3 are Blue and 2 are Red. We assign the new data point to the category with most neighbors i.e Blue. Iris dataset consists of 50 samples from each of 3 species of Iris(Iris setosa, Iris virginica, Iris versicolor) and a multivariate dataset introduced by British statistician and biologist Ronald Fisher in his 1936 paper The use of multiple measurements in taxonomic problems. Four features were measured from each sample i.e length and width of the sepals and petals and based on the combination of these four features, Fisher developed a linear discriminant model to distinguish the species from each other. # Loading datadata(iris) # Structure str(iris) Using the K-Nearest Neighbor algorithm on the dataset which includes 11 persons and 6 variables or attributes. # Installing Packagesinstall.packages("e1071")install.packages("caTools")install.packages("class") # Loading packagelibrary(e1071)library(caTools)library(class) # Loading datadata(iris)head(iris) # Splitting data into train# and test datasplit <- sample.split(iris, SplitRatio = 0.7)train_cl <- subset(iris, split == "TRUE")test_cl <- subset(iris, split == "FALSE") # Feature Scalingtrain_scale <- scale(train_cl[, 1:4])test_scale <- scale(test_cl[, 1:4]) # Fitting KNN Model # to training datasetclassifier_knn <- knn(train = train_scale, test = test_scale, cl = train_cl$Species, k = 1)classifier_knn # Confusiin Matrixcm <- table(test_cl$Species, classifier_knn)cm # Model Evaluation - Choosing K# Calculate out of Sample errormisClassError <- mean(classifier_knn != test_cl$Species)print(paste('Accuracy =', 1-misClassError)) # K = 3classifier_knn <- knn(train = train_scale, test = test_scale, cl = train_cl$Species, k = 3)misClassError <- mean(classifier_knn != test_cl$Species)print(paste('Accuracy =', 1-misClassError)) # K = 5classifier_knn <- knn(train = train_scale, test = test_scale, cl = train_cl$Species, k = 5)misClassError <- mean(classifier_knn != test_cl$Species)print(paste('Accuracy =', 1-misClassError)) # K = 7classifier_knn <- knn(train = train_scale, test = test_scale, cl = train_cl$Species, k = 7)misClassError <- mean(classifier_knn != test_cl$Species)print(paste('Accuracy =', 1-misClassError)) # K = 15classifier_knn <- knn(train = train_scale, test = test_scale, cl = train_cl$Species, k = 15)misClassError <- mean(classifier_knn != test_cl$Species)print(paste('Accuracy =', 1-misClassError)) # K = 19classifier_knn <- knn(train = train_scale, test = test_scale, cl = train_cl$Species, k = 19)misClassError <- mean(classifier_knn != test_cl$Species)print(paste('Accuracy =', 1-misClassError)) Output: Model classifier_knn(k=1):The KNN model is fitted with a train, test, and k value. Also, the Classifier Species feature is fitted in the model. The KNN model is fitted with a train, test, and k value. Also, the Classifier Species feature is fitted in the model. Confusion Matrix:So, 20 Setosa are correctly classified as Setosa. Out of 20 Versicolor, 17 Versicolor are correctly classified as Versicolor and 3 are classified as virginica. Out of 20 virginica, 17 virginica are correctly classified as virginica and 3 are classified as Versicolor. So, 20 Setosa are correctly classified as Setosa. Out of 20 Versicolor, 17 Versicolor are correctly classified as Versicolor and 3 are classified as virginica. Out of 20 virginica, 17 virginica are correctly classified as virginica and 3 are classified as Versicolor. Model Evaluation:(k=1)The model achieved 90% accuracy with k is 1.(K=3)The model achieved 88.33% accuracy with k is 3 which is lower than when k was 1.(K=5)The model achieved 91.66% accuracy with k is 5 which is more than when k was 1 and 3.(K=7)The model achieved 93.33% accuracy with k is 7 which is more than when k was 1, 3, and 5.(K=15)The model achieved 95% accuracy with k is 15 which is more than when k was 1, 3, 5, and 7.(K=19)The model achieved 95% accuracy with k is 19 which is more than when k was 1, 3, 5, and 7. Its same accuracy when k was 15 which means now increasing k values doesn’t affect the accuracy.So, K Nearest Neighbor is widely used in the industry. The model achieved 90% accuracy with k is 1. (K=3) The model achieved 88.33% accuracy with k is 3 which is lower than when k was 1. (K=5) The model achieved 91.66% accuracy with k is 5 which is more than when k was 1 and 3. (K=7) The model achieved 93.33% accuracy with k is 7 which is more than when k was 1, 3, and 5. (K=15) The model achieved 95% accuracy with k is 15 which is more than when k was 1, 3, 5, and 7. (K=19) The model achieved 95% accuracy with k is 19 which is more than when k was 1, 3, 5, and 7. Its same accuracy when k was 15 which means now increasing k values doesn’t affect the accuracy. So, K Nearest Neighbor is widely used in the industry. R-Mathematics R-Statistics R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change column name of a given DataFrame in R How to Replace specific values in column in R DataFrame ? Adding elements in a vector in R programming - append() method How to change Row Names of DataFrame in R ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Change Color of Bars in Barchart using ggplot2 in R Convert Factor to Numeric and Numeric to Factor in R Programming How to Change Axis Scales in R Plots? Group by function in R using Dplyr
[ { "code": null, "e": 28677, "s": 28649, "text": "\n22 Jun, 2020" }, { "code": null, "e": 29058, "s": 28677, "text": "K-Nearest Neighbor or K-NN is a Supervised Non-linear classification algorithm. K-NN is a Non-parametric algorithm i.e it doesn’t make any assumption about underlying data or its distribution. It is one of the simplest and widely used algorithm which depends on it’s k value(Neighbors) and finds it’s applications in many industries like finance industry, healthcare industry etc." }, { "code": null, "e": 29149, "s": 29058, "text": "In the KNN algorithm, K specifies the number of neighbors and its algorithm is as follows:" }, { "code": null, "e": 29182, "s": 29149, "text": "Choose the number K of neighbor." }, { "code": null, "e": 29255, "s": 29182, "text": "Take the K Nearest Neighbor of unknown data point according to distance." }, { "code": null, "e": 29328, "s": 29255, "text": "Among the K-neighbors, Count the number of data points in each category." }, { "code": null, "e": 29407, "s": 29328, "text": "Assign the new data point to a category, where you counted the most neighbors." }, { "code": null, "e": 29524, "s": 29407, "text": "For the Nearest Neighbor classifier, the distance between two points is expressed in the form of Euclidean Distance." }, { "code": null, "e": 29690, "s": 29524, "text": "Example:Consider a dataset containing two features Red and Blue and we classify them. Here K is 5 i.e we are considering 5 neighbors according to Euclidean distance." }, { "code": null, "e": 29845, "s": 29690, "text": "So, when a new data point enters, out of 5 neighbors, 3 are Blue and 2 are Red. We assign the new data point to the category with most neighbors i.e Blue." }, { "code": null, "e": 30355, "s": 29845, "text": "Iris dataset consists of 50 samples from each of 3 species of Iris(Iris setosa, Iris virginica, Iris versicolor) and a multivariate dataset introduced by British statistician and biologist Ronald Fisher in his 1936 paper The use of multiple measurements in taxonomic problems. Four features were measured from each sample i.e length and width of the sepals and petals and based on the combination of these four features, Fisher developed a linear discriminant model to distinguish the species from each other." }, { "code": "# Loading datadata(iris) # Structure str(iris)", "e": 30404, "s": 30355, "text": null }, { "code": null, "e": 30515, "s": 30404, "text": "Using the K-Nearest Neighbor algorithm on the dataset which includes 11 persons and 6 variables or attributes." }, { "code": "# Installing Packagesinstall.packages(\"e1071\")install.packages(\"caTools\")install.packages(\"class\") # Loading packagelibrary(e1071)library(caTools)library(class) # Loading datadata(iris)head(iris) # Splitting data into train# and test datasplit <- sample.split(iris, SplitRatio = 0.7)train_cl <- subset(iris, split == \"TRUE\")test_cl <- subset(iris, split == \"FALSE\") # Feature Scalingtrain_scale <- scale(train_cl[, 1:4])test_scale <- scale(test_cl[, 1:4]) # Fitting KNN Model # to training datasetclassifier_knn <- knn(train = train_scale, test = test_scale, cl = train_cl$Species, k = 1)classifier_knn # Confusiin Matrixcm <- table(test_cl$Species, classifier_knn)cm # Model Evaluation - Choosing K# Calculate out of Sample errormisClassError <- mean(classifier_knn != test_cl$Species)print(paste('Accuracy =', 1-misClassError)) # K = 3classifier_knn <- knn(train = train_scale, test = test_scale, cl = train_cl$Species, k = 3)misClassError <- mean(classifier_knn != test_cl$Species)print(paste('Accuracy =', 1-misClassError)) # K = 5classifier_knn <- knn(train = train_scale, test = test_scale, cl = train_cl$Species, k = 5)misClassError <- mean(classifier_knn != test_cl$Species)print(paste('Accuracy =', 1-misClassError)) # K = 7classifier_knn <- knn(train = train_scale, test = test_scale, cl = train_cl$Species, k = 7)misClassError <- mean(classifier_knn != test_cl$Species)print(paste('Accuracy =', 1-misClassError)) # K = 15classifier_knn <- knn(train = train_scale, test = test_scale, cl = train_cl$Species, k = 15)misClassError <- mean(classifier_knn != test_cl$Species)print(paste('Accuracy =', 1-misClassError)) # K = 19classifier_knn <- knn(train = train_scale, test = test_scale, cl = train_cl$Species, k = 19)misClassError <- mean(classifier_knn != test_cl$Species)print(paste('Accuracy =', 1-misClassError))", "e": 32729, "s": 30515, "text": null }, { "code": null, "e": 32737, "s": 32729, "text": "Output:" }, { "code": null, "e": 32881, "s": 32737, "text": "Model classifier_knn(k=1):The KNN model is fitted with a train, test, and k value. Also, the Classifier Species feature is fitted in the model." }, { "code": null, "e": 32999, "s": 32881, "text": "The KNN model is fitted with a train, test, and k value. Also, the Classifier Species feature is fitted in the model." }, { "code": null, "e": 33284, "s": 32999, "text": "Confusion Matrix:So, 20 Setosa are correctly classified as Setosa. Out of 20 Versicolor, 17 Versicolor are correctly classified as Versicolor and 3 are classified as virginica. Out of 20 virginica, 17 virginica are correctly classified as virginica and 3 are classified as Versicolor." }, { "code": null, "e": 33552, "s": 33284, "text": "So, 20 Setosa are correctly classified as Setosa. Out of 20 Versicolor, 17 Versicolor are correctly classified as Versicolor and 3 are classified as virginica. Out of 20 virginica, 17 virginica are correctly classified as virginica and 3 are classified as Versicolor." }, { "code": null, "e": 34231, "s": 33552, "text": "Model Evaluation:(k=1)The model achieved 90% accuracy with k is 1.(K=3)The model achieved 88.33% accuracy with k is 3 which is lower than when k was 1.(K=5)The model achieved 91.66% accuracy with k is 5 which is more than when k was 1 and 3.(K=7)The model achieved 93.33% accuracy with k is 7 which is more than when k was 1, 3, and 5.(K=15)The model achieved 95% accuracy with k is 15 which is more than when k was 1, 3, 5, and 7.(K=19)The model achieved 95% accuracy with k is 19 which is more than when k was 1, 3, 5, and 7. Its same accuracy when k was 15 which means now increasing k values doesn’t affect the accuracy.So, K Nearest Neighbor is widely used in the industry." }, { "code": null, "e": 34276, "s": 34231, "text": "The model achieved 90% accuracy with k is 1." }, { "code": null, "e": 34282, "s": 34276, "text": "(K=3)" }, { "code": null, "e": 34363, "s": 34282, "text": "The model achieved 88.33% accuracy with k is 3 which is lower than when k was 1." }, { "code": null, "e": 34369, "s": 34363, "text": "(K=5)" }, { "code": null, "e": 34455, "s": 34369, "text": "The model achieved 91.66% accuracy with k is 5 which is more than when k was 1 and 3." }, { "code": null, "e": 34461, "s": 34455, "text": "(K=7)" }, { "code": null, "e": 34551, "s": 34461, "text": "The model achieved 93.33% accuracy with k is 7 which is more than when k was 1, 3, and 5." }, { "code": null, "e": 34558, "s": 34551, "text": "(K=15)" }, { "code": null, "e": 34649, "s": 34558, "text": "The model achieved 95% accuracy with k is 15 which is more than when k was 1, 3, 5, and 7." }, { "code": null, "e": 34656, "s": 34649, "text": "(K=19)" }, { "code": null, "e": 34844, "s": 34656, "text": "The model achieved 95% accuracy with k is 19 which is more than when k was 1, 3, 5, and 7. Its same accuracy when k was 15 which means now increasing k values doesn’t affect the accuracy." }, { "code": null, "e": 34899, "s": 34844, "text": "So, K Nearest Neighbor is widely used in the industry." }, { "code": null, "e": 34913, "s": 34899, "text": "R-Mathematics" }, { "code": null, "e": 34926, "s": 34913, "text": "R-Statistics" }, { "code": null, "e": 34937, "s": 34926, "text": "R Language" }, { "code": null, "e": 35035, "s": 34937, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35044, "s": 35035, "text": "Comments" }, { "code": null, "e": 35057, "s": 35044, "text": "Old Comments" }, { "code": null, "e": 35102, "s": 35057, "text": "Change column name of a given DataFrame in R" }, { "code": null, "e": 35160, "s": 35102, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 35223, "s": 35160, "text": "Adding elements in a vector in R programming - append() method" }, { "code": null, "e": 35267, "s": 35223, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 35319, "s": 35267, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 35351, "s": 35319, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 35403, "s": 35351, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 35468, "s": 35403, "text": "Convert Factor to Numeric and Numeric to Factor in R Programming" }, { "code": null, "e": 35506, "s": 35468, "text": "How to Change Axis Scales in R Plots?" } ]
Pandas | Basic of Time Series Manipulation - GeeksforGeeks
22 Mar, 2022 Although time series is also available in scikit-learn but Pandas has some sort of compiled more features. In this module of Pandas, we can include the date and time for every record and can fetch the records of dataframe. We can find out the data within a certain range of date and time by using pandas module named Time series. Let’s discuss some major objectives to introduce the pandas time series analysis.Objectives of time series analysis Create the series of date Work with data timestamp Convert string data to timestamp Slicing of data using timestamp Resample your time series for different time period aggregates/summary statistics Working with missing data Now, let’s do some practical analysis on some data to demonstrate the use of pandas time series.Code #1: Python3 import pandas as pdfrom datetime import datetimeimport numpy as np range_date = pd.date_range(start ='1/1/2019', end ='1/08/2019', freq ='Min')print(range_date) DatetimeIndex(['2019-01-01 00:00:00', '2019-01-01 00:01:00', '2019-01-01 00:02:00', '2019-01-01 00:03:00', '2019-01-01 00:04:00', '2019-01-01 00:05:00', '2019-01-01 00:06:00', '2019-01-01 00:07:00', '2019-01-01 00:08:00', '2019-01-01 00:09:00', ... '2019-01-07 23:51:00', '2019-01-07 23:52:00', '2019-01-07 23:53:00', '2019-01-07 23:54:00', '2019-01-07 23:55:00', '2019-01-07 23:56:00', '2019-01-07 23:57:00', '2019-01-07 23:58:00', '2019-01-07 23:59:00', '2019-01-08 00:00:00'], dtype='datetime64[ns]', length=10081, freq='T') Explanation: Here in this code, we have created the timestamp on the bases of minutes for date ranges from 1/1/2019 – 8/1/2019. We can vary the frequency by hours to minutes or seconds. This function will help you to track the record of data stored per minute. As we can see in the output the length of the datetime stamp is 10081. Remember pandas use data type as datetime64[ns].Code #2: Python3 import pandas as pdfrom datetime import datetimeimport numpy as np range_date = pd.date_range(start ='1/1/2019', end ='1/08/2019', freq ='Min')print(type(range_date[110])) <class 'pandas._libs.tslibs.timestamps.Timestamp'> Explanation: We are checking the type of our object named range_date. Code #3: Python3 import pandas as pdfrom datetime import datetimeimport numpy as np range_date = pd.date_range(start ='1/1/2019', end ='1/08/2019', freq ='Min') df = pd.DataFrame(range_date, columns =['date'])df['data'] = np.random.randint(0, 100, size =(len(range_date))) print(df.head(10)) date data 0 2019-01-01 00:00:00 49 1 2019-01-01 00:01:00 58 2 2019-01-01 00:02:00 48 3 2019-01-01 00:03:00 96 4 2019-01-01 00:04:00 42 5 2019-01-01 00:05:00 8 6 2019-01-01 00:06:00 20 7 2019-01-01 00:07:00 96 8 2019-01-01 00:08:00 48 9 2019-01-01 00:09:00 78 Explanation:We have first created a time series then converted this data into dataframe and use random function to generate the random data and map over the dataframe. Then to check the result we use print function. In order to do time series manipulation, we need to have a datetime index so that dataframe is indexed on the timestamp. Here, we are adding one more new column in pandas dataframe.Code #4: Python3 import pandas as pdfrom datetime import datetimeimport numpy as np range_date = pd.date_range(start ='1/1/2019', end ='1/08/2019', freq ='Min') df = pd.DataFrame(range_date, columns =['date'])df['data'] = np.random.randint(0, 100, size =(len(range_date))) string_data = [str(x) for x in range_date]print(string_data[1:11]) Explanation: This code just use the elements of data_rng and converted to string and due to lot of data we slice the data and print first ten values list string_data. By using the for each loop in list, we got all the values that are in the series range_date. When we are using date_range we always have to specify the start and end date.Example: Python3 import pandas as pdfrom datetime import datetimeimport numpy as np range_data = pd.date_range(start ='1/1/2019', end ='1/08/2019', freq ='Min') df = pd.DataFrame(range_data, columns =['date'])df['data'] = np.random.randint(0, 100, size =(len(range_data))) df['datetime'] = pd.to_datetime(df['date'])df = df.set_index('datetime')df.drop(['date'], axis = 1, inplace = True) print(df['2019-01-05'][1:11]) data datetime 2019-01-05 00:01:00 99 2019-01-05 00:02:00 21 2019-01-05 00:03:00 29 2019-01-05 00:04:00 98 2019-01-05 00:05:00 0 2019-01-05 00:06:00 72 2019-01-05 00:07:00 69 2019-01-05 00:08:00 53 2019-01-05 00:09:00 3 2019-01-05 00:10:00 37 varshagumber28 simmytarika5 pandas-dataframe-program Python pandas-datetime Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Create a Pandas DataFrame from Lists Box Plot in Python using Matplotlib Python Dictionary Bar Plot in Matplotlib Enumerate() in Python Python | Get dictionary keys as a list Python | Convert set into a list Ways to filter Pandas DataFrame by column values Graph Plotting in Python | Set 1 Python - Call function from another file
[ { "code": null, "e": 24539, "s": 24511, "text": "\n22 Mar, 2022" }, { "code": null, "e": 24986, "s": 24539, "text": "Although time series is also available in scikit-learn but Pandas has some sort of compiled more features. In this module of Pandas, we can include the date and time for every record and can fetch the records of dataframe. We can find out the data within a certain range of date and time by using pandas module named Time series. Let’s discuss some major objectives to introduce the pandas time series analysis.Objectives of time series analysis " }, { "code": null, "e": 25012, "s": 24986, "text": "Create the series of date" }, { "code": null, "e": 25037, "s": 25012, "text": "Work with data timestamp" }, { "code": null, "e": 25070, "s": 25037, "text": "Convert string data to timestamp" }, { "code": null, "e": 25102, "s": 25070, "text": "Slicing of data using timestamp" }, { "code": null, "e": 25184, "s": 25102, "text": "Resample your time series for different time period aggregates/summary statistics" }, { "code": null, "e": 25210, "s": 25184, "text": "Working with missing data" }, { "code": null, "e": 25316, "s": 25210, "text": "Now, let’s do some practical analysis on some data to demonstrate the use of pandas time series.Code #1: " }, { "code": null, "e": 25324, "s": 25316, "text": "Python3" }, { "code": "import pandas as pdfrom datetime import datetimeimport numpy as np range_date = pd.date_range(start ='1/1/2019', end ='1/08/2019', freq ='Min')print(range_date)", "e": 25535, "s": 25324, "text": null }, { "code": null, "e": 26227, "s": 25535, "text": "DatetimeIndex(['2019-01-01 00:00:00', '2019-01-01 00:01:00',\n '2019-01-01 00:02:00', '2019-01-01 00:03:00',\n '2019-01-01 00:04:00', '2019-01-01 00:05:00',\n '2019-01-01 00:06:00', '2019-01-01 00:07:00',\n '2019-01-01 00:08:00', '2019-01-01 00:09:00',\n ...\n '2019-01-07 23:51:00', '2019-01-07 23:52:00',\n '2019-01-07 23:53:00', '2019-01-07 23:54:00',\n '2019-01-07 23:55:00', '2019-01-07 23:56:00',\n '2019-01-07 23:57:00', '2019-01-07 23:58:00',\n '2019-01-07 23:59:00', '2019-01-08 00:00:00'],\n dtype='datetime64[ns]', length=10081, freq='T')" }, { "code": null, "e": 26619, "s": 26229, "text": "Explanation: Here in this code, we have created the timestamp on the bases of minutes for date ranges from 1/1/2019 – 8/1/2019. We can vary the frequency by hours to minutes or seconds. This function will help you to track the record of data stored per minute. As we can see in the output the length of the datetime stamp is 10081. Remember pandas use data type as datetime64[ns].Code #2: " }, { "code": null, "e": 26627, "s": 26619, "text": "Python3" }, { "code": "import pandas as pdfrom datetime import datetimeimport numpy as np range_date = pd.date_range(start ='1/1/2019', end ='1/08/2019', freq ='Min')print(type(range_date[110]))", "e": 26849, "s": 26627, "text": null }, { "code": null, "e": 26900, "s": 26849, "text": "<class 'pandas._libs.tslibs.timestamps.Timestamp'>" }, { "code": null, "e": 26982, "s": 26902, "text": "Explanation: We are checking the type of our object named range_date. Code #3: " }, { "code": null, "e": 26990, "s": 26982, "text": "Python3" }, { "code": "import pandas as pdfrom datetime import datetimeimport numpy as np range_date = pd.date_range(start ='1/1/2019', end ='1/08/2019', freq ='Min') df = pd.DataFrame(range_date, columns =['date'])df['data'] = np.random.randint(0, 100, size =(len(range_date))) print(df.head(10))", "e": 27315, "s": 26990, "text": null }, { "code": null, "e": 27624, "s": 27315, "text": " date data\n0 2019-01-01 00:00:00 49\n1 2019-01-01 00:01:00 58\n2 2019-01-01 00:02:00 48\n3 2019-01-01 00:03:00 96\n4 2019-01-01 00:04:00 42\n5 2019-01-01 00:05:00 8\n6 2019-01-01 00:06:00 20\n7 2019-01-01 00:07:00 96\n8 2019-01-01 00:08:00 48\n9 2019-01-01 00:09:00 78" }, { "code": null, "e": 28033, "s": 27626, "text": "Explanation:We have first created a time series then converted this data into dataframe and use random function to generate the random data and map over the dataframe. Then to check the result we use print function. In order to do time series manipulation, we need to have a datetime index so that dataframe is indexed on the timestamp. Here, we are adding one more new column in pandas dataframe.Code #4: " }, { "code": null, "e": 28041, "s": 28033, "text": "Python3" }, { "code": "import pandas as pdfrom datetime import datetimeimport numpy as np range_date = pd.date_range(start ='1/1/2019', end ='1/08/2019', freq ='Min') df = pd.DataFrame(range_date, columns =['date'])df['data'] = np.random.randint(0, 100, size =(len(range_date))) string_data = [str(x) for x in range_date]print(string_data[1:11])", "e": 28413, "s": 28041, "text": null }, { "code": null, "e": 28761, "s": 28413, "text": "Explanation: This code just use the elements of data_rng and converted to string and due to lot of data we slice the data and print first ten values list string_data. By using the for each loop in list, we got all the values that are in the series range_date. When we are using date_range we always have to specify the start and end date.Example: " }, { "code": null, "e": 28769, "s": 28761, "text": "Python3" }, { "code": "import pandas as pdfrom datetime import datetimeimport numpy as np range_data = pd.date_range(start ='1/1/2019', end ='1/08/2019', freq ='Min') df = pd.DataFrame(range_data, columns =['date'])df['data'] = np.random.randint(0, 100, size =(len(range_data))) df['datetime'] = pd.to_datetime(df['date'])df = df.set_index('datetime')df.drop(['date'], axis = 1, inplace = True) print(df['2019-01-05'][1:11])", "e": 29220, "s": 28769, "text": null }, { "code": null, "e": 29532, "s": 29220, "text": " data\ndatetime \n2019-01-05 00:01:00 99\n2019-01-05 00:02:00 21\n2019-01-05 00:03:00 29\n2019-01-05 00:04:00 98\n2019-01-05 00:05:00 0\n2019-01-05 00:06:00 72\n2019-01-05 00:07:00 69\n2019-01-05 00:08:00 53\n2019-01-05 00:09:00 3\n2019-01-05 00:10:00 37" }, { "code": null, "e": 29549, "s": 29534, "text": "varshagumber28" }, { "code": null, "e": 29562, "s": 29549, "text": "simmytarika5" }, { "code": null, "e": 29587, "s": 29562, "text": "pandas-dataframe-program" }, { "code": null, "e": 29610, "s": 29587, "text": "Python pandas-datetime" }, { "code": null, "e": 29624, "s": 29610, "text": "Python-pandas" }, { "code": null, "e": 29631, "s": 29624, "text": "Python" }, { "code": null, "e": 29729, "s": 29631, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29738, "s": 29729, "text": "Comments" }, { "code": null, "e": 29751, "s": 29738, "text": "Old Comments" }, { "code": null, "e": 29788, "s": 29751, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 29824, "s": 29788, "text": "Box Plot in Python using Matplotlib" }, { "code": null, "e": 29842, "s": 29824, "text": "Python Dictionary" }, { "code": null, "e": 29865, "s": 29842, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 29887, "s": 29865, "text": "Enumerate() in Python" }, { "code": null, "e": 29926, "s": 29887, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 29959, "s": 29926, "text": "Python | Convert set into a list" }, { "code": null, "e": 30008, "s": 29959, "text": "Ways to filter Pandas DataFrame by column values" }, { "code": null, "e": 30041, "s": 30008, "text": "Graph Plotting in Python | Set 1" } ]
Bash Script - Arithmetic Operators - GeeksforGeeks
04 Jan, 2022 In this article, we will see arithmetic operators in bash script. Arithmetic operators is used to perform arithmetic operations. Bash script supports 11 arithmetic operators. All the operators with their uses is given below: 16/3 result = 5 16/ 3 result = 1 x= 13 x+=3 result = 16 x= 13 x -= 3 result = 10 x= 10 x*=3 result = 30 x = 31 x/=3 result = 10 x= 31 x%=3 result = 1 3**2 result = 9 Let’s see the examples for the uses of arithmetic operators: Code: Sum=$((10+3)) echo "Sum = $Sum" Output: Code: Difference=$((10-3)) echo "Difference = $Difference" Output: Code: Product=$((10*3)) echo "Product = $Product" Output: Code: Division=$((10/3)) echo "Division = $Division" Output: Code: Modulo=$((10%3)) echo "Modulo = $Modulo" Output: Code: Exponent=$((10**2)) echo "Exponent = $Exponent" Output: Example to show use of all the operators in a single code Code: x=10 y=20 echo "x=10, y=5" echo "Addition of x and y" echo $(( $x + $y )) echo "Subtraction of x and y" echo $(( $x - $y )) echo "Multiplication of x and y" echo $(( $x * $y )) echo "Division of x by y" echo $(( $x / $y )) echo "Exponentiation of x,y" echo $(( $x ** $y )) echo "Modular Division of x,y" echo $(( $x % $y )) echo "Incrementing x by 10, then x= " (( x += 10 )) echo $x echo "Decrementing x by 15, then x= " (( x -= 15 )) echo $x echo "Multiply of x by 2, then x=" (( x *= 2 )) echo $x echo "Dividing x by 5, x= " (( x /= 5 )) echo $x echo "Remainder of Dividing x by 5, x=" (( x %= 5 )) echo $x Output: There are some of the different ways to perform Arithmetic Operations. This could be used for arithmetic expansion. Let’s see an example to see the use of double quotes. Code: #!/bin/bash first=10 second=3 echo $(( first + second )) # addition echo $(( $first + $second )) # this is also valid echo $(( first - second )) # subtraction echo $(( $first - $second )) # this is also valid Output: 13 13 7 7 let command is used to perform arithmetic operations. Example code: #!/bin/bash x=10 y=3 let "z = $(( x * y ))" # multiplication echo $z let z=$((x*y)) echo $z let "z = $(( x / y ))" # division echo $z let z=$((x/y)) echo $z Output: 30 30 3 3 Arithmetic expansion could be done using backticks and expr. Code: a=10 b=3 # there must be spaces before/after the operator sum=`expr $a + $b` echo $sum sub=`expr $a - $b` echo $sub mul=`expr $a \* $b` echo $mul div=`expr $a / $b` echo $div Output: 13 7 30 3 Bash-Script Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Thread functions in C/C++ nohup Command in Linux with Examples mv command in Linux with examples scp command in Linux with Examples Docker - COPY Instruction chown command in Linux with Examples nslookup command in Linux with Examples SED command in Linux | Set 2 Named Pipe or FIFO with example C program uniq Command in LINUX with examples
[ { "code": null, "e": 24015, "s": 23987, "text": "\n04 Jan, 2022" }, { "code": null, "e": 24144, "s": 24015, "text": "In this article, we will see arithmetic operators in bash script. Arithmetic operators is used to perform arithmetic operations." }, { "code": null, "e": 24240, "s": 24144, "text": "Bash script supports 11 arithmetic operators. All the operators with their uses is given below:" }, { "code": null, "e": 24245, "s": 24240, "text": "16/3" }, { "code": null, "e": 24256, "s": 24245, "text": "result = 5" }, { "code": null, "e": 24262, "s": 24256, "text": "16/ 3" }, { "code": null, "e": 24273, "s": 24262, "text": "result = 1" }, { "code": null, "e": 24279, "s": 24273, "text": "x= 13" }, { "code": null, "e": 24284, "s": 24279, "text": "x+=3" }, { "code": null, "e": 24296, "s": 24284, "text": "result = 16" }, { "code": null, "e": 24302, "s": 24296, "text": "x= 13" }, { "code": null, "e": 24309, "s": 24302, "text": "x -= 3" }, { "code": null, "e": 24321, "s": 24309, "text": "result = 10" }, { "code": null, "e": 24327, "s": 24321, "text": "x= 10" }, { "code": null, "e": 24332, "s": 24327, "text": "x*=3" }, { "code": null, "e": 24344, "s": 24332, "text": "result = 30" }, { "code": null, "e": 24351, "s": 24344, "text": "x = 31" }, { "code": null, "e": 24356, "s": 24351, "text": "x/=3" }, { "code": null, "e": 24368, "s": 24356, "text": "result = 10" }, { "code": null, "e": 24374, "s": 24368, "text": "x= 31" }, { "code": null, "e": 24379, "s": 24374, "text": "x%=3" }, { "code": null, "e": 24390, "s": 24379, "text": "result = 1" }, { "code": null, "e": 24395, "s": 24390, "text": "3**2" }, { "code": null, "e": 24406, "s": 24395, "text": "result = 9" }, { "code": null, "e": 24467, "s": 24406, "text": "Let’s see the examples for the uses of arithmetic operators:" }, { "code": null, "e": 24473, "s": 24467, "text": "Code:" }, { "code": null, "e": 24509, "s": 24473, "text": "Sum=$((10+3)) \necho \"Sum = $Sum\" " }, { "code": null, "e": 24517, "s": 24509, "text": "Output:" }, { "code": null, "e": 24523, "s": 24517, "text": "Code:" }, { "code": null, "e": 24580, "s": 24523, "text": "Difference=$((10-3)) \necho \"Difference = $Difference\" " }, { "code": null, "e": 24588, "s": 24580, "text": "Output:" }, { "code": null, "e": 24594, "s": 24588, "text": "Code:" }, { "code": null, "e": 24642, "s": 24594, "text": "Product=$((10*3)) \necho \"Product = $Product\" " }, { "code": null, "e": 24650, "s": 24642, "text": "Output:" }, { "code": null, "e": 24656, "s": 24650, "text": "Code:" }, { "code": null, "e": 24707, "s": 24656, "text": "Division=$((10/3)) \necho \"Division = $Division\" " }, { "code": null, "e": 24715, "s": 24707, "text": "Output:" }, { "code": null, "e": 24721, "s": 24715, "text": "Code:" }, { "code": null, "e": 24766, "s": 24721, "text": "Modulo=$((10%3)) \necho \"Modulo = $Modulo\" " }, { "code": null, "e": 24774, "s": 24766, "text": "Output:" }, { "code": null, "e": 24780, "s": 24774, "text": "Code:" }, { "code": null, "e": 24832, "s": 24780, "text": "Exponent=$((10**2)) \necho \"Exponent = $Exponent\" " }, { "code": null, "e": 24840, "s": 24832, "text": "Output:" }, { "code": null, "e": 24898, "s": 24840, "text": "Example to show use of all the operators in a single code" }, { "code": null, "e": 24904, "s": 24898, "text": "Code:" }, { "code": null, "e": 25572, "s": 24904, "text": "x=10\ny=20\necho \"x=10, y=5\" \necho \"Addition of x and y\" \necho $(( $x + $y )) \necho \"Subtraction of x and y\" \necho $(( $x - $y )) \necho \"Multiplication of x and y\" \necho $(( $x * $y )) \necho \"Division of x by y\" \necho $(( $x / $y )) \necho \"Exponentiation of x,y\" \necho $(( $x ** $y )) \necho \"Modular Division of x,y\" \necho $(( $x % $y )) \necho \"Incrementing x by 10, then x= \" \n(( x += 10 )) \necho $x \necho \"Decrementing x by 15, then x= \" \n(( x -= 15 )) \necho $x \necho \"Multiply of x by 2, then x=\" \n(( x *= 2 )) \necho $x \necho \"Dividing x by 5, x= \" \n(( x /= 5 )) \necho $x \necho \"Remainder of Dividing x by 5, x=\" \n(( x %= 5 )) \necho $x " }, { "code": null, "e": 25580, "s": 25572, "text": "Output:" }, { "code": null, "e": 25651, "s": 25580, "text": "There are some of the different ways to perform Arithmetic Operations." }, { "code": null, "e": 25750, "s": 25651, "text": "This could be used for arithmetic expansion. Let’s see an example to see the use of double quotes." }, { "code": null, "e": 25756, "s": 25750, "text": "Code:" }, { "code": null, "e": 25977, "s": 25756, "text": "#!/bin/bash\n \nfirst=10\nsecond=3\n \necho $(( first + second )) # addition\necho $(( $first + $second )) # this is also valid\n \necho $(( first - second )) # subtraction\necho $(( $first - $second )) # this is also valid\n " }, { "code": null, "e": 25986, "s": 25977, "text": " Output:" }, { "code": null, "e": 25996, "s": 25986, "text": "13\n13\n7\n7" }, { "code": null, "e": 26051, "s": 25996, "text": "let command is used to perform arithmetic operations. " }, { "code": null, "e": 26059, "s": 26051, "text": "Example" }, { "code": null, "e": 26065, "s": 26059, "text": "code:" }, { "code": null, "e": 26230, "s": 26065, "text": "#!/bin/bash\n \nx=10\ny=3\n \nlet \"z = $(( x * y ))\" # multiplication\necho $z\nlet z=$((x*y))\necho $z\n \nlet \"z = $(( x / y ))\" # division\necho $z\nlet z=$((x/y))\necho $z" }, { "code": null, "e": 26238, "s": 26230, "text": "Output:" }, { "code": null, "e": 26248, "s": 26238, "text": "30\n30\n3\n3" }, { "code": null, "e": 26309, "s": 26248, "text": "Arithmetic expansion could be done using backticks and expr." }, { "code": null, "e": 26315, "s": 26309, "text": "Code:" }, { "code": null, "e": 26495, "s": 26315, "text": "a=10\nb=3\n\n# there must be spaces before/after the operator\n\nsum=`expr $a + $b`\necho $sum\n\nsub=`expr $a - $b`\necho $sub\n\nmul=`expr $a \\* $b`\necho $mul\n\ndiv=`expr $a / $b`\necho $div" }, { "code": null, "e": 26503, "s": 26495, "text": "Output:" }, { "code": null, "e": 26513, "s": 26503, "text": "13\n7\n30\n3" }, { "code": null, "e": 26525, "s": 26513, "text": "Bash-Script" }, { "code": null, "e": 26532, "s": 26525, "text": "Picked" }, { "code": null, "e": 26543, "s": 26532, "text": "Linux-Unix" }, { "code": null, "e": 26641, "s": 26543, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26650, "s": 26641, "text": "Comments" }, { "code": null, "e": 26663, "s": 26650, "text": "Old Comments" }, { "code": null, "e": 26689, "s": 26663, "text": "Thread functions in C/C++" }, { "code": null, "e": 26726, "s": 26689, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 26760, "s": 26726, "text": "mv command in Linux with examples" }, { "code": null, "e": 26795, "s": 26760, "text": "scp command in Linux with Examples" }, { "code": null, "e": 26821, "s": 26795, "text": "Docker - COPY Instruction" }, { "code": null, "e": 26858, "s": 26821, "text": "chown command in Linux with Examples" }, { "code": null, "e": 26898, "s": 26858, "text": "nslookup command in Linux with Examples" }, { "code": null, "e": 26927, "s": 26898, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 26969, "s": 26927, "text": "Named Pipe or FIFO with example C program" } ]
How to find the cumulative sum for factor levels in an R data frame?
Cumulative sums are mostly used in descriptive analysis of data but sometimes we might want to calculate them in understanding the time series analysis for moving sums but it is very rare. If we have a factor column in an R data frame then it would not make sense to find the cumulative sum for all factor levels together, we must find the cumulative sums for each level. This can be easily done by using ave function. Consider the below data frame − Live Demo set.seed(15) x1<-as.factor(sample(LETTERS[1:3],20,replace=TRUE)) x2<-rpois(20,5) df1<-data.frame(x1,x2) df1 x1 x2 1 A 5 2 C 6 3 B 2 4 B 3 5 A 8 6 B 5 7 A 5 8 A 3 9 C 5 10 A 2 11 C 5 12 B 6 13 A 2 14 A 5 15 A 4 16 C 6 17 B 8 18 A 5 19 B 8 20 B 3 Finding cumulative sum of x2 values for different values of x1 − df1$CumSum_x2_based_on_x1<-ave(x2,x1,FUN=cumsum) df1 x1 x2 CumSum_x2_based_on_x1 1 A 5 5 2 C 6 6 3 B 2 2 4 B 3 5 5 A 8 13 6 B 5 10 7 A 5 18 8 A 3 21 9 C 5 11 10 A 2 23 11 C 5 16 12 B 6 16 13 A 2 25 14 A 5 30 15 A 4 34 16 C 6 22 17 B 8 24 18 A 5 39 19 B 8 32 20 B 3 35 Let’s have a look at another example − Live Demo Group<-sample(c("GRP1","GRP2","GRP3","GRP4"),20,replace=TRUE) Response<-sample(1:10,20,replace=TRUE) df2<-data.frame(Group,Response) df2 Group Response 1 GRP2 1 2 GRP3 1 3 GRP2 8 4 GRP2 1 5 GRP2 4 6 GRP1 7 7 GRP1 8 8 GRP1 2 9 GRP1 1 10 GRP1 1 11 GRP4 3 12 GRP3 9 13 GRP4 4 14 GRP1 9 15 GRP4 5 16 GRP2 8 17 GRP2 10 18 GRP3 5 19 GRP3 8 20 GRP3 8 Finding cumulative sum of Response values for different values of Group df2$CumSum_of_GroupLevels<-ave(Response,Group,FUN=cumsum) df2 Group Response CumSum_of_GroupLevels 1 GRP2 1 1 2 GRP3 1 1 3 GRP2 8 9 4 GRP2 1 10 5 GRP2 4 14 6 GRP1 7 7 7 GRP1 8 15 8 GRP1 2 17 9 GRP1 1 18 10 GRP1 1 19 11 GRP4 3 3 12 GRP3 9 10 13 GRP4 4 7 14 GRP1 9 28 15 GRP4 5 12 16 GRP2 8 22 17 GRP2 10 32 18 GRP3 5 15 19 GRP3 8 23 20 GRP3 8 31
[ { "code": null, "e": 1481, "s": 1062, "text": "Cumulative sums are mostly used in descriptive analysis of data but sometimes we might want to calculate them in understanding the time series analysis for moving sums but it is very rare. If we have a factor column in an R data frame then it would not make sense to find the cumulative sum for all factor levels together, we must find the cumulative sums for each level. This can be easily done by using ave function." }, { "code": null, "e": 1513, "s": 1481, "text": "Consider the below data frame −" }, { "code": null, "e": 1524, "s": 1513, "text": " Live Demo" }, { "code": null, "e": 1632, "s": 1524, "text": "set.seed(15)\nx1<-as.factor(sample(LETTERS[1:3],20,replace=TRUE))\nx2<-rpois(20,5)\ndf1<-data.frame(x1,x2)\ndf1" }, { "code": null, "e": 1780, "s": 1632, "text": " x1 x2\n1 A 5\n2 C 6\n3 B 2\n4 B 3\n5 A 8\n6 B 5\n7 A 5\n8 A 3\n9 C 5\n10 A 2\n11 C 5\n12 B 6\n13 A 2\n14 A 5\n15 A 4\n16 C 6\n17 B 8\n18 A 5\n19 B 8\n20 B 3" }, { "code": null, "e": 1845, "s": 1780, "text": "Finding cumulative sum of x2 values for different values of x1 −" }, { "code": null, "e": 1898, "s": 1845, "text": "df1$CumSum_x2_based_on_x1<-ave(x2,x1,FUN=cumsum)\ndf1" }, { "code": null, "e": 2184, "s": 1898, "text": " x1 x2 CumSum_x2_based_on_x1\n1 A 5 5\n2 C 6 6\n3 B 2 2\n4 B 3 5\n5 A 8 13\n6 B 5 10\n7 A 5 18\n8 A 3 21\n9 C 5 11\n10 A 2 23\n11 C 5 16\n12 B 6 16\n13 A 2 25\n14 A 5 30\n15 A 4 34\n16 C 6 22\n17 B 8 24\n18 A 5 39\n19 B 8 32\n20 B 3 35" }, { "code": null, "e": 2223, "s": 2184, "text": "Let’s have a look at another example −" }, { "code": null, "e": 2234, "s": 2223, "text": " Live Demo" }, { "code": null, "e": 2371, "s": 2234, "text": "Group<-sample(c(\"GRP1\",\"GRP2\",\"GRP3\",\"GRP4\"),20,replace=TRUE)\nResponse<-sample(1:10,20,replace=TRUE)\ndf2<-data.frame(Group,Response)\ndf2" }, { "code": null, "e": 2648, "s": 2371, "text": " Group Response\n1 GRP2 1\n2 GRP3 1\n3 GRP2 8\n4 GRP2 1\n5 GRP2 4\n6 GRP1 7\n7 GRP1 8\n8 GRP1 2\n9 GRP1 1\n10 GRP1 1\n11 GRP4 3\n12 GRP3 9\n13 GRP4 4\n14 GRP1 9\n15 GRP4 5\n16 GRP2 8\n17 GRP2 10\n18 GRP3 5\n19 GRP3 8\n20 GRP3 8" }, { "code": null, "e": 2720, "s": 2648, "text": "Finding cumulative sum of Response values for different values of Group" }, { "code": null, "e": 2782, "s": 2720, "text": "df2$CumSum_of_GroupLevels<-ave(Response,Group,FUN=cumsum)\ndf2" }, { "code": null, "e": 3256, "s": 2782, "text": " Group Response CumSum_of_GroupLevels\n1 GRP2 1 1\n2 GRP3 1 1\n3 GRP2 8 9\n4 GRP2 1 10\n5 GRP2 4 14\n6 GRP1 7 7\n7 GRP1 8 15\n8 GRP1 2 17\n9 GRP1 1 18\n10 GRP1 1 19\n11 GRP4 3 3\n12 GRP3 9 10\n13 GRP4 4 7\n14 GRP1 9 28\n15 GRP4 5 12\n16 GRP2 8 22\n17 GRP2 10 32\n18 GRP3 5 15\n19 GRP3 8 23\n20 GRP3 8 31" } ]
Heart Disease UCI-Diagnosis & Prediction | by Hardik Deshmukh | Towards Data Science
Every day, the average human heart beats around 100,000 times, pumping 2,000 gallons of blood through the body. Inside your body there are 60,000 miles of blood vessels. The signs of a woman having a heart attack are much less noticeable than the signs of a male. In women, heart attacks may feel uncomfortable squeezing, pressure, fullness, or pain in the center of the chest. It may also cause pain in one or both arms, the back, neck, jaw or stomach, shortness of breath, nausea and other symptoms. Men experience typical symptoms of heart attack, such as chest pain , discomfort, and stress. They may also experience pain in other areas, such as arms, neck , back, and jaw, and shortness of breath, sweating, and discomfort that mimics heartburn. It’s a lot of work for an organ which is just like a large fist and weighs between 8 and 12 ounces. source: healthblog.uofmhealth Code by Hardik: Link to the Google colab notebook: https://colab.research.google.com/drive/16iFRPq0vx_CZypo4ZyJ_qTLrvds3FlDb?usp=sharing GitHub: https://github.com/smarthardik10/Heart-Disease-UCI-Diagnosis-Prediction Dataset by Heart Disease UCI: Dataset source: https://archive.ics.uci.edu/ml/datasets/Heart+Disease Dataset columns: age: The person’s age in years sex: The person’s sex (1 = male, 0 = female) cp: chest pain type — Value 0: asymptomatic — Value 1: atypical angina — Value 2: non-anginal pain — Value 3: typical angina trestbps: The person’s resting blood pressure (mm Hg on admission to the hospital) chol: The person’s cholesterol measurement in mg/dl fbs: The person’s fasting blood sugar (> 120 mg/dl, 1 = true; 0 = false) restecg: resting electrocardiographic results — Value 0: showing probable or definite left ventricular hypertrophy by Estes’ criteria — Value 1: normal — Value 2: having ST-T wave abnormality (T wave inversions and/or ST elevation or depression of > 0.05 mV) thalach: The person’s maximum heart rate achieved exang: Exercise induced angina (1 = yes; 0 = no) oldpeak: ST depression induced by exercise relative to rest (‘ST’ relates to positions on the ECG plot. See more here) slope: the slope of the peak exercise ST segment — 0: downsloping; 1: flat; 2: upsloping0: downsloping; 1: flat; 2: upsloping ca: The number of major vessels (0–3) thal: A blood disorder called thalassemia Value 0: NULL (dropped from the dataset previouslyValue 1: fixed defect (no blood flow in some part of the heart)Value 2: normal blood flowValue 3: reversible defect (a blood flow is observed but it is not normal) target: Heart disease (1 = no, 0= yes) Context: This is multivariate type of dataset which means providing or involving a variety of separate mathematical or statistical variables, multivariate numerical data analysis. It is composed of 14 attributes which are age, sex, chest pain type, resting blood pressure, serum cholesterol, fasting blood sugar, resting electrocardiographic results, maximum heart rate achieved, exercise induced angina, oldpeak — ST depression induced by exercise relative to rest, the slope of the peak exercise ST segment, number of major vessels and Thalassemia. This database includes 76 attributes, but all published studies relate to the use of a subset of 14 of them. The Cleveland database is the only one used by ML researchers to date. One of the major tasks on this dataset is to predict based on the given attributes of a patient that whether that particular person has a heart disease or not and other is the experimental task to diagnose and find out various insights from this dataset which could help in understanding the problem more. The dataset was created by: - 1. Hungarian Institute of Cardiology. Budapest: Andras Janosi, M.D. 2. University Hospital, Zurich, Switzerland: William Steinbrunn, M.D. 3. University Hospital, Basel, Switzerland: Matthias Pfisterer, M.D. 4. V.A. Medical Center, Long Beach and Cleveland Clinic Foundation: Robert Detrano, M.D., Ph.D. Imports and Reading DatasetData Description Imports and Reading Dataset Data Description Describe Null 3. Data Analysis 1) Univariate Selection 2) Feature Selection 3) Correlation Matrix with Heatmap 4. Data Visualization 1)Countplot 2)Distplot 3)Jointplot 4)Boxplot/violinplot 5)Cluster map 6)Pairplot Classification Tree 5. Data Pre-processing 1)Pre-processing 2)One Hot Encoding 6. Logistic Regression 1)Gather columns 2)Splitting Data 3)Normalization 4)Fitting into the model 5)Prediction 6)Model Evaluation 7. Conclusion 1)Coefficients 2)Analysis 3)Conclusion import numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inlinedf = pd.read_csv('/content/drive/My Drive/dataset/heart.csv')df.head() There has been lot of confusion about the meta data, as there are various different meta data available out there. Over here below I have got the two most used meta data description from kaggle. So we are going to follow the second description(2 — description). 1 — description • age: The person's age in years• sex: The person's sex (1 = male, 0 = female)• cp: The chest pain experienced (Value 1: typical angina, Value 2: atypical angina, Value 3: non-anginal pain, Value 4: asymptomatic)• trestbps: The person's resting blood pressure (mm Hg on admission to the hospital)• chol: The person's cholesterol measurement in mg/dl• fbs: The person's fasting blood sugar (> 120 mg/dl, 1 = true; 0 = false)• restecg: Resting electrocardiographic measurement (0 = normal, 1 = having ST-T wave abnormality, 2 = showing probable or definite left ventricular hypertrophy by Estes' criteria)• thalach: The person's maximum heart rate achieved• exang: Exercise induced angina (1 = yes; 0 = no)• oldpeak: ST depression induced by exercise relative to rest ('ST' relates to positions on the ECG plot. See more here)• slope: the slope of the peak exercise ST segment (Value 1: upsloping, Value 2: flat, Value 3: downsloping)• ca: The number of major vessels (0-3)• thal: A blood disorder called thalassemia (3 = normal; 6 = fixed defect; 7 = reversable defect)• target: Heart disease (0 = no, 1 = yes) 2 — description cp: chest pain type-- Value 0: asymptomatic-- Value 1: atypical angina-- Value 2: non-anginal pain-- Value 3: typical angina restecg: resting electrocardiographic results-- Value 0: showing probable or definite left ventricular hypertrophy by Estes' criteria-- Value 1: normal-- Value 2: having ST-T wave abnormality (T wave inversions and/or ST elevation or depression of > 0.05 mV) slope: the slope of the peak exercise ST segment0: downsloping; 1: flat; 2: upsloping thalResults of the blood flow observed via the radioactive dye. Value 0: NULL (dropped from the dataset previously)Value 1: fixed defect (no blood flow in some part of the heart)Value 2: normal blood flowValue 3: reversible defect (a blood flow is observed but it is not normal)This feature and the next one are obtained through a very invasive process for the patients. But, by themselves, they give a very good indication of the presence of a heart disease or not. target : 0 = disease, 1 = no diseasedf.info() df.describe() Checking for null values df.isnull().sum() #visualizing Null values if it exists plt.figure(figsize=(22,10))plt.xticks(size=20,color='grey')plt.tick_params(size=12,color='grey')plt.title('Finding Null Values Using Heatmap\n',color='grey',size=30)sns.heatmap(df.isnull(), yticklabels=False, cbar=False, cmap='PuBu_r', ) Dataset has no null values !pip install https://github.com/pandas-profiling/pandas-profiling/archive/master.zipimport pandas_profiling as pppp.ProfileReport(df) For detailed view: https://colab.research.google.com/drive/16iFRPq0vx_CZypo4ZyJ_qTLrvds3FlDb#scrollTo=5crIBqgn9FiI&line=1&uniqifier=1 Feature Selection Univariate Selction — Statistical tests may be used to pick certain features that have the best relationship to the performance variable.The scikit-learn library provides the SelectKBest class that can be used to select a specific number of features in a suite of different statistical tests.The following example uses the chi-squared (chi2) statistical test for non-negative features to select 13 of the best features from the Dataset. Univariate Selction — Statistical tests may be used to pick certain features that have the best relationship to the performance variable.The scikit-learn library provides the SelectKBest class that can be used to select a specific number of features in a suite of different statistical tests.The following example uses the chi-squared (chi2) statistical test for non-negative features to select 13 of the best features from the Dataset. from sklearn.feature_selection import SelectKBestfrom sklearn.feature_selection import chi2data = df.copy()X = data.iloc[:,0:13] #independent columnsy = data.iloc[:,-1] #target column #apply SelectKBest class to extract top best featuresbestfeatures = SelectKBest(score_func=chi2, k=10)fit = bestfeatures.fit(X,y)dfscores = pd.DataFrame(fit.scores_)dfcolumns = pd.DataFrame(X.columns)#concat two dataframes for better visualization featureScores = pd.concat([dfcolumns,dfscores],axis=1)featureScores.columns = ['Specs','Score'] #naming the dataframe columnsprint(featureScores.nlargest(12,'Score')) #print best features 2. Feature Importance — You can gain the significance of each feature of your dataset by using the Model Characteristics property.Feature value gives you a score for every function of your results, the higher the score the more significant or appropriate the performance variable is.Feature importance is the built-in class that comes with Tree Based Classifiers, we will use the Extra Tree Classifier to extract the top features for the dataset. from sklearn.ensemble import ExtraTreesClassifiermodel = ExtraTreesClassifier()model.fit(X,y)print(model.feature_importances_) #use inbuilt class feature_importances of tree based classifiers#plot graph of feature importances for better visualizationfeat_importances = pd.Series(model.feature_importances_, index=X.columns)feat_importances.nlargest(13).plot(kind='barh')plt.show() 3. Correlation Matrix with Heatmap — Correlation indicates how the features are related to each other or to the target variable.The correlation may be positive (increase in one value of the feature increases the value of the target variable) or negative (increase in one value of the feature decreases the value of the target variable)Heatmap makes it easy to classify the features are most relevant to the target variable, and we will plot the associated features of the heatmap using the seaborn library. Correlation shows whether the characteristics are related to each other or to the target variable. Correlation can be positive (increase in one value, the value of the objective variable increases) or negative (increase in one value, the value of the target variable decreased). From this heatmap we can observe that the ‘cp’ chest pain is highly related to the target variable. Compared to relation between other two variables we can say that chest pain contributes the most in prediction of presences of a heart disease. Medical emergency is a heart attack. A cardiac occurs usually when blood clot blocks blood flow to the cardiac. Tissue loses oxygen without blood and dies causing chest pain. plt.figure(figsize=(12,10))sns.heatmap(df.corr(),annot=True,cmap="magma",fmt='.2f') for i in df.columns: print(i,len(df[i].unique())) Seaborn sns.set_style('darkgrid')sns.set_palette('Set2') Preparing Data df2 = df.copy()def chng(sex): if sex == 0: return 'female' else: return 'male'df2['sex'] = df2['sex'].apply(chng)def chng2(prob): if prob == 0: return ‘Heart Disease’ else: return ‘No Heart Disease’df2['target'] = df2['target'].apply(chng2) df2['target'] = df2['target'].apply(chng2)sns.countplot(data= df2, x='sex',hue='target')plt.title('Gender v/s target\n') According to this Cleveland dataset males are more susceptible to get Heart Disease than females. Men experience heart attacks more than women. Sudden Heart Attacks are experienced by men between 70% — 89%. Woman may experience a heart attack with no chest pressure at all, they usually experience nausea or vomiting which are often confused with acid reflux or the flu. sns.countplot(data= df2, x='cp',hue='target')plt.title('Chest Pain Type v/s target\n') There are four types of chest pain, asymptomatic, atypical angina, non-anginal pain and typical angina. Most of the Heart Disease patients are found to have asymptomatic chest pain. These group of people might show atypical symptoms like indigestion, flu or a strained chest muscle. A asymptomatic attack, like any heart attack, involves, blockage of blood flow to your heart and possible damage to the heart muscle. The risk factors for asymptomatic heart attacks are same as those with heart symptoms. These factors include: · Age · Diabetes · Excess weight · Family History of Heart Disease · High Blood Pressure · High cholesterol · Lack of exercise · Prior Heart attack · Tobacco use Asymptomatic Heart attack puts you at a greater risk of having another heart attack which could be d deadly. Having another heart attack also increases your risk of complications, such as heart failure. There are no test to determine your potential for asymptomatic heart attack. The only way to tell If you had asymptomatic attack is by an electrocardiogram or echocardiogram. These tests can reveal changes that signal a heart attack. sns.countplot(data= df2, x='sex',hue='thal')plt.title('Gender v/s Thalassemia\n')print('Thalassemia (thal-uh-SEE-me-uh) is an inherited blood disorder that causes your body to have less hemoglobin than normal. Hemoglobin enables red blood cells to carry oxygen') The Beta thalassemia cardiomyopathy is mainly characterized by two distinct pheno types , dilated type, with left ventricular dilatation and impaired contractility and a restrictive pheno type, with restrictive left ventricular feeling , pulmonary hyper tension and right heart failure. Heart problems, congestive heart failures and abnormal heart rhythms can be associated with severe thalassemia. sns.countplot(data= df2, x='slope',hue='target')plt.title('Slope v/s Target\n') sns.countplot(data= df2, x='exang',hue='thal')plt.title('exang v/s Thalassemia\n') plt.figure(figsize=(16,7))sns.distplot(df[df['target']==0]['age'],kde=False,bins=50)plt.title('Age of Heart Diseased Patients\n') Heart Disease is very common in the seniors which is composed of age group 60 and above and common among adults which belong to the age group of 41 to 60. But it’s rare among the age group of 19 to 40 and very rare among the age group of 0 to 18. plt.figure(figsize=(16,7))sns.distplot(df[df['target']==0]['chol'],kde=False,bins=40)plt.title('Chol of Heart Diseased Patients\n') Total cholesterol LDL — ‘bad cholesterol” HDL — ‘good cholesterol” In adults, the total cholesterol levels are considered desirable less than 200 milligram per decilitre ( mg / dL). Borderlines are considered to be high between 200 to 239 mg / dL and 240 mg / dL and above. LDL should contain less than 100 mg / dL of cholesterol. 100 mg / dl rates for individuals without any health issue are appropriate but may be more relevant for those with cardiac problems or risk factors for heart disease. The levels are borderline moderate between 130 and 159 mg / dL and moderate between 160 and 189 mg / dL. The reading is very high at or above 190 mg / dL. Levels of HDL are to be maintained higher. The risk factor for cardiovascular diseases is called a reading less than 40 mg / dL. Borderline low is considered to be between 41 mg / dL and 59 mg / dL. The HDL level can be measured with a maximum of 60 mg / dL. plt.figure(figsize=(16,7))sns.distplot(df[df['target']==0]['thalach'],kde=False,bins=40)plt.title('thalach of Heart Diseased Patients\n') Preparing data df3 = df[df['target'] == 0 ][['age', 'sex', 'cp', 'trestbps', 'chol', 'fbs', 'restecg', 'thalach', 'exang', 'oldpeak', 'slope', 'ca', 'thal', 'target']] #target 0 - people with heart diseasepal = sns.light_palette("blue", as_cmap=True)print('Age vs trestbps(Heart Diseased Patinets)')sns.jointplot(data=df3, x='age', y='trestbps', kind='hex', cmap='Reds' ) sns.jointplot(data=df3, x='chol', y='age', kind='kde', cmap='PuBu' ) Joint plots in seaborn helps us to understand the trend seen among two features. As observed from the above plot we can see that most of the Heart diseased patients in their age of upper 50s or lower 60s tend to have Cholesterol between 200mg/dl to 300mg/dl. sns.jointplot(data=df3, x='chol', y='trestbps', kind='resid', ) sns.boxplot(data=df2,x='target',y='age') plt.figure(figsize=(14,8))sns.violinplot(data=df2,x='ca',y='age',hue='target') sns.boxplot(data=df2,x='cp',y='thalach',hue='target') plt.figure(figsize=(10,7))sns.boxplot(data=df2,x='fbs',y='trestbps',hue='target') plt.figure(figsize=(10,7))sns.violinplot(data=df2,x='exang',y='oldpeak',hue='target') plt.figure(figsize=(10,7))sns.boxplot(data=df2,x='slope',y='thalach',hue='target') sns.violinplot(data=df2,x='thal',y='oldpeak',hue='target') sns.violinplot(data=df2,x='target',y='thalach') sns.clustermap(df.corr(),annot=True) sns.pairplot(df,hue='cp') from sklearn.tree import DecisionTreeClassifier # Import Decision Tree Classifierfrom sklearn.model_selection import train_test_split # Import train_test_split functionfrom sklearn import metrics #Import scikit-learn metrics module for accuracy calculationX = df.iloc[:,0:13] # Featuresy = df.iloc[:,13] # Target variableX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1) # 70% training and 30% test# Create Decision Tree classifer objectclf = DecisionTreeClassifier()# Train Decision Tree Classiferclf = clf.fit(X_train,y_train)#Predict the response for test datasety_pred = clf.predict(X_test)print("Accuracy:",metrics.accuracy_score(y_test, y_pred)) Accuracy: 0.7142857142857143 feature_cols = ['age', 'sex', 'cp', 'trestbps','chol', 'fbs', 'restecg', 'thalach','exang', 'oldpeak', 'slope', 'ca', 'thal']from sklearn.tree import export_graphvizfrom sklearn.externals.six import StringIO from IPython.display import Image import pydotplusdot_data = StringIO()export_graphviz(clf, out_file=dot_data, filled=True, rounded=True, special_characters=True,feature_names = feature_cols ,class_names=['0','1'])graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) graph.write_png('diabetes.png')Image(graph.create_png()) # Create Decision Tree classifer objectclf = DecisionTreeClassifier(criterion="entropy", max_depth=3)# Train Decision Tree Classiferclf = clf.fit(X_train,y_train)#Predict the response for test datasety_pred = clf.predict(X_test)# Model Accuracy, how often is the classifier correct?print("Accuracy:",metrics.accuracy_score(y_test, y_pred)) Accuracy: 0.7362637362637363 from sklearn.externals.six import StringIO from IPython.display import Image from sklearn.tree import export_graphvizimport pydotplusdot_data = StringIO()export_graphviz(clf, out_file=dot_data, filled=True, rounded=True, special_characters=True, feature_names = feature_cols,class_names=['0','1'])graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) graph.write_png('diabetes.png')Image(graph.create_png()) Change Name of the column df.columns = ['age', 'sex', 'chest_pain_type', 'resting_blood_pressure', 'cholesterol', 'fasting_blood_sugar', 'rest_ecg_type', 'max_heart_rate_achieved', 'exercise_induced_angina', 'st_depression', 'st_slope_type', 'num_major_vessels', 'thalassemia_type', 'target']df.columns Index([‘age’, ‘sex’, ‘chest_pain_type’, ‘resting_blood_pressure’, ‘cholesterol’, ‘fasting_blood_sugar’, ‘rest_ecg_type’, ‘max_heart_rate_achieved’, ‘exercise_induced_angina’, ‘st_depression’, ‘st_slope_type’, ‘num_major_vessels’, ‘thalassemia_type’, ‘target’], dtype=’object’) We have 4 Categorical columns as seen in Data Description using pandas profiling: cp — chest_pain_type restecg — rest_ecg_type slope — st_slope_type thal — thalassemia_type Generating categorical columns values #cp - chest_pain_typedf.loc[df['chest_pain_type'] == 0, 'chest_pain_type'] = 'asymptomatic'df.loc[df['chest_pain_type'] == 1, 'chest_pain_type'] = 'atypical angina'df.loc[df['chest_pain_type'] == 2, 'chest_pain_type'] = 'non-anginal pain'df.loc[df['chest_pain_type'] == 3, 'chest_pain_type'] = 'typical angina'#restecg - rest_ecg_typedf.loc[df['rest_ecg_type'] == 0, 'rest_ecg_type'] = 'left ventricular hypertrophy'df.loc[df['rest_ecg_type'] == 1, 'rest_ecg_type'] = 'normal'df.loc[df['rest_ecg_type'] == 2, 'rest_ecg_type'] = 'ST-T wave abnormality'#slope - st_slope_typedf.loc[df['st_slope_type'] == 0, 'st_slope_type'] = 'downsloping'df.loc[df['st_slope_type'] == 1, 'st_slope_type'] = 'flat'df.loc[df['st_slope_type'] == 2, 'st_slope_type'] = 'upsloping'#thal - thalassemia_typedf.loc[df['thalassemia_type'] == 0, 'thalassemia_type'] = 'nothing'df.loc[df['thalassemia_type'] == 1, 'thalassemia_type'] = 'fixed defect'df.loc[df['thalassemia_type'] == 2, 'thalassemia_type'] = 'normal'df.loc[df['thalassemia_type'] == 3, 'thalassemia_type'] = 'reversable defect' data = pd.get_dummies(df, drop_first=False)data.columns Index([‘age’, ‘sex’, ‘resting_blood_pressure’, ‘cholesterol’, ‘fasting_blood_sugar’, ‘max_heart_rate_achieved’, ‘exercise_induced_angina’, ‘st_depression’, ‘num_major_vessels’, ‘target’, ‘chest_pain_type_asymptomatic’, ‘chest_pain_type_atypical angina’, ‘chest_pain_type_non-anginal pain’, ‘chest_pain_type_typical angina’, ‘rest_ecg_type_ST-T wave abnormality’, ‘rest_ecg_type_left ventricular hypertrophy’, ‘rest_ecg_type_normal’, ‘st_slope_type_downsloping’, ‘st_slope_type_flat’, ‘st_slope_type_upsloping’, ‘thalassemia_type_fixed defect’, ‘thalassemia_type_normal’, ‘thalassemia_type_nothing’, ‘thalassemia_type_reversable defect’], dtype=’object’) df_temp = data['thalassemia_type_fixed defect']data = pd.get_dummies(df, drop_first=True)data.head() Since one hot encoding dropped “thalassemia_type_fixed defect” column which was a useful column compared to ‘thalassemia_type_nothing’ which is a null column, we dropped ‘thalassemia_type_nothing’ and concatinated ‘thalassemia_type_fixed defect’ frames = [data, df_temp]result = pd.concat(frames,axis=1)result.drop('thalassemia_type_nothing',axis=1,inplace=True)resultc = result.copy()# making a copy for further analysis in conclusion section X = result.drop('target', axis = 1)y = result['target'] from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) Min-Max Normalization method is used to Normalize the data. This method scales the data range to [0,1]. Standardization is also used on a feature-wise basis in most cases. X_train=(X_train-np.min(X_train))/(np.max(X_train)-np.min(X_train)).valuesX_test=(X_test-np.min(X_test))/(np.max(X_test)-np.min(X_test)).values from sklearn.linear_model import LogisticRegressionlogre = LogisticRegression()logre.fit(X_train,y_train) LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True, intercept_scaling=1, l1_ratio=None, max_iter=100, multi_class=’auto’, n_jobs=None, penalty=’l2', random_state=None, solver=’lbfgs’, tol=0.0001, verbose=0, warm_start=False) y_pred = logre.predict(X_test)actual = []predcition = []for i,j in zip(y_test,y_pred): actual.append(i) predcition.append(j)dic = {'Actual':actual, 'Prediction':predcition }result = pd.DataFrame(dic)import plotly.graph_objects as go fig = go.Figure() fig.add_trace(go.Scatter(x=np.arange(0,len(y_test)), y=y_test, mode='markers+lines', name='Test'))fig.add_trace(go.Scatter(x=np.arange(0,len(y_test)), y=y_pred, mode='markers', name='Pred')) The red dots represent the predicted values that is either 0 or 1 and the blue line & and dot represents the actual value of that particular patient. In the places where the red dot and blue dot do not overlap are the wrong predictions and where the both dots overlap those are the right predicted values. from sklearn.metrics import accuracy_scoreprint(accuracy_score(y_test,y_pred)) 0.8688524590163934 from sklearn.metrics import classification_reportprint(classification_report(y_test,y_pred)) The classification report of the model shows that 91% prediction of absence of heart disease was predicted correct and 83% of presence of heart disease was predicted correct. from sklearn.metrics import confusion_matrixprint(confusion_matrix(y_test,y_pred))sns.heatmap(confusion_matrix(y_test,y_pred),annot=True) The confusion Matrix The Confusion Matrix True Positive value is 24 and true Negative was 29. And the False Positive came out to be 3 and False Negative is 5. ROC Curve ROC Curves summarizes the trade-off between the true positive rate and the false positive rate for the predictive model using different probability thresholds. The accuracy of the ROC curve came out to be 87.09%. from sklearn.metrics import roc_curvefpr, tpr, thresholds = roc_curve(y_test, y_pred)plt.plot(fpr,tpr)plt.xlim([0.0, 1.0])plt.ylim([0.0, 1.0])plt.title('ROC curve for Heart disease classifier')plt.xlabel('False positive rate (1-Specificity)')plt.ylabel('True positive rate (Sensitivity)')plt.grid(True) import sklearnsklearn.metrics.roc_auc_score(y_test,y_pred) 0.8709150326797386 print(logre.intercept_)plt.figure(figsize=(10,12))coeffecients = pd.DataFrame(logre.coef_.ravel(),X.columns)coeffecients.columns = ['Coeffecient']coeffecients.sort_values(by=['Coeffecient'],inplace=True,ascending=False)coeffecientsts Preparing data for analysis df4 = df[df['target'] == 0 ][['age', 'sex', 'chest_pain_type', 'resting_blood_pressure','cholesterol', 'fasting_blood_sugar', 'rest_ecg_type', 'max_heart_rate_achieved', 'exercise_induced_angina', 'st_depression','st_slope_type', 'num_major_vessels', 'thalassemia_type', 'target']] #target 0 - people with heart disease Heart Diseased Patient’s visualization plt.figure(figsize=(16,6))sns.distplot(df4['max_heart_rate_achieved']) Normal Heart rate is found to be between 60 and 100 bpm. Some areas of cardiac muscles will start to die during a Heart Attack because of Lack of Blood. A person’s pulse may become slower (bradycardia) or faster (tachycardiac) depending on the type of Heart Attack they are experiencing. plt.figure(figsize=(20,6))sns.boxenplot(data=df4,x='rest_ecg_type',y='cholesterol',hue='st_slope_type') In normal type of rest ECG proves to be important for the prediction model along with the down sloping ST slope. The patient composed of these two features usually has cholesterol level between 170 to 225 mg/dl. The other types of slops with the rest ECG seems to be more spread out and less concise. plt.figure(figsize=(20,6))sns.boxenplot(data=df4,x='chest_pain_type',y='max_heart_rate_achieved',hue='thalassemia_type') Shap Values !pip install shap import shapexplainer = shap.TreeExplainer(model)shap_values = explainer.shap_values(X_test,check_additivity=False)shap.summary_plot(shap_values[1], X_test, plot_type="bar") Shap value for Model Explaination shap.summary_plot(shap_values[1], X_test) def patient_analysis(model, patient): explainer = shap.TreeExplainer(model) shap_values = explainer.shap_values(patient) shap.initjs() return shap.force_plot(explainer.expected_value[1], shap_values[1], patient) Reports for two Patients patients = X_test.iloc[3,:].astype(float)patients_target = y_test.iloc[3:4]print('Target : ',int(patients_target))patient_analysis(model, patients) Target : 0 patients = X_test.iloc[33,:].astype(float)patients_target = y_test.iloc[33:34]print('Target : ',int(patients_target))patient_analysis(model, patients) Target : 1 # dependence plotshap.dependence_plot('num_major_vessels', shap_values[1], X_test, interaction_index = "st_depression") shap_values = explainer.shap_values(X_train.iloc[:50],check_additivity=False)shap.initjs()shap.force_plot(explainer.expected_value[1], shap_values[1], X_test.iloc[:50]) The Area under the ROC curve is 87.09% which is somewhat satisfactory. The model predicted with 86.88% accuracy. The model is more specific than sensitive. According to this model the major features contributing in precision of predicting model are shown in the heatmap in Ascending order. plt.figure(figsize=(10,12))coeffecients = pd.DataFrame(logre.coef_.ravel(),X.columns)coeffecients.columns = ['Coeffecient']coeffecients.sort_values(by=['Coeffecient'],inplace=True,ascending=False)sns.heatmap(coeffecients,annot=True,fmt='.2f',cmap='Set2',linewidths=0.5) The important features contributing to the accuracy of the prediction are shown through the Heatmap in descending order. In silver color code, the most contributing feature, the chest pain types and maximum heart rate achieved proved to be more valuable by 1.28 to 1.03 units.
[ { "code": null, "e": 342, "s": 172, "text": "Every day, the average human heart beats around 100,000 times, pumping 2,000 gallons of blood through the body. Inside your body there are 60,000 miles of blood vessels." }, { "code": null, "e": 923, "s": 342, "text": "The signs of a woman having a heart attack are much less noticeable than the signs of a male. In women, heart attacks may feel uncomfortable squeezing, pressure, fullness, or pain in the center of the chest. It may also cause pain in one or both arms, the back, neck, jaw or stomach, shortness of breath, nausea and other symptoms. Men experience typical symptoms of heart attack, such as chest pain , discomfort, and stress. They may also experience pain in other areas, such as arms, neck , back, and jaw, and shortness of breath, sweating, and discomfort that mimics heartburn." }, { "code": null, "e": 1023, "s": 923, "text": "It’s a lot of work for an organ which is just like a large fist and weighs between 8 and 12 ounces." }, { "code": null, "e": 1053, "s": 1023, "text": "source: healthblog.uofmhealth" }, { "code": null, "e": 1069, "s": 1053, "text": "Code by Hardik:" }, { "code": null, "e": 1190, "s": 1069, "text": "Link to the Google colab notebook: https://colab.research.google.com/drive/16iFRPq0vx_CZypo4ZyJ_qTLrvds3FlDb?usp=sharing" }, { "code": null, "e": 1270, "s": 1190, "text": "GitHub: https://github.com/smarthardik10/Heart-Disease-UCI-Diagnosis-Prediction" }, { "code": null, "e": 1300, "s": 1270, "text": "Dataset by Heart Disease UCI:" }, { "code": null, "e": 1370, "s": 1300, "text": "Dataset source: https://archive.ics.uci.edu/ml/datasets/Heart+Disease" }, { "code": null, "e": 1387, "s": 1370, "text": "Dataset columns:" }, { "code": null, "e": 1418, "s": 1387, "text": "age: The person’s age in years" }, { "code": null, "e": 1463, "s": 1418, "text": "sex: The person’s sex (1 = male, 0 = female)" }, { "code": null, "e": 1588, "s": 1463, "text": "cp: chest pain type — Value 0: asymptomatic — Value 1: atypical angina — Value 2: non-anginal pain — Value 3: typical angina" }, { "code": null, "e": 1671, "s": 1588, "text": "trestbps: The person’s resting blood pressure (mm Hg on admission to the hospital)" }, { "code": null, "e": 1723, "s": 1671, "text": "chol: The person’s cholesterol measurement in mg/dl" }, { "code": null, "e": 1796, "s": 1723, "text": "fbs: The person’s fasting blood sugar (> 120 mg/dl, 1 = true; 0 = false)" }, { "code": null, "e": 2055, "s": 1796, "text": "restecg: resting electrocardiographic results — Value 0: showing probable or definite left ventricular hypertrophy by Estes’ criteria — Value 1: normal — Value 2: having ST-T wave abnormality (T wave inversions and/or ST elevation or depression of > 0.05 mV)" }, { "code": null, "e": 2105, "s": 2055, "text": "thalach: The person’s maximum heart rate achieved" }, { "code": null, "e": 2154, "s": 2105, "text": "exang: Exercise induced angina (1 = yes; 0 = no)" }, { "code": null, "e": 2273, "s": 2154, "text": "oldpeak: ST depression induced by exercise relative to rest (‘ST’ relates to positions on the ECG plot. See more here)" }, { "code": null, "e": 2399, "s": 2273, "text": "slope: the slope of the peak exercise ST segment — 0: downsloping; 1: flat; 2: upsloping0: downsloping; 1: flat; 2: upsloping" }, { "code": null, "e": 2437, "s": 2399, "text": "ca: The number of major vessels (0–3)" }, { "code": null, "e": 2693, "s": 2437, "text": "thal: A blood disorder called thalassemia Value 0: NULL (dropped from the dataset previouslyValue 1: fixed defect (no blood flow in some part of the heart)Value 2: normal blood flowValue 3: reversible defect (a blood flow is observed but it is not normal)" }, { "code": null, "e": 2732, "s": 2693, "text": "target: Heart disease (1 = no, 0= yes)" }, { "code": null, "e": 2741, "s": 2732, "text": "Context:" }, { "code": null, "e": 3769, "s": 2741, "text": "This is multivariate type of dataset which means providing or involving a variety of separate mathematical or statistical variables, multivariate numerical data analysis. It is composed of 14 attributes which are age, sex, chest pain type, resting blood pressure, serum cholesterol, fasting blood sugar, resting electrocardiographic results, maximum heart rate achieved, exercise induced angina, oldpeak — ST depression induced by exercise relative to rest, the slope of the peak exercise ST segment, number of major vessels and Thalassemia. This database includes 76 attributes, but all published studies relate to the use of a subset of 14 of them. The Cleveland database is the only one used by ML researchers to date. One of the major tasks on this dataset is to predict based on the given attributes of a patient that whether that particular person has a heart disease or not and other is the experimental task to diagnose and find out various insights from this dataset which could help in understanding the problem more." }, { "code": null, "e": 3799, "s": 3769, "text": "The dataset was created by: -" }, { "code": null, "e": 4102, "s": 3799, "text": "1. Hungarian Institute of Cardiology. Budapest: Andras Janosi, M.D. 2. University Hospital, Zurich, Switzerland: William Steinbrunn, M.D. 3. University Hospital, Basel, Switzerland: Matthias Pfisterer, M.D. 4. V.A. Medical Center, Long Beach and Cleveland Clinic Foundation: Robert Detrano, M.D., Ph.D." }, { "code": null, "e": 4146, "s": 4102, "text": "Imports and Reading DatasetData Description" }, { "code": null, "e": 4174, "s": 4146, "text": "Imports and Reading Dataset" }, { "code": null, "e": 4191, "s": 4174, "text": "Data Description" }, { "code": null, "e": 4200, "s": 4191, "text": "Describe" }, { "code": null, "e": 4205, "s": 4200, "text": "Null" }, { "code": null, "e": 4222, "s": 4205, "text": "3. Data Analysis" }, { "code": null, "e": 4246, "s": 4222, "text": "1) Univariate Selection" }, { "code": null, "e": 4267, "s": 4246, "text": "2) Feature Selection" }, { "code": null, "e": 4302, "s": 4267, "text": "3) Correlation Matrix with Heatmap" }, { "code": null, "e": 4324, "s": 4302, "text": "4. Data Visualization" }, { "code": null, "e": 4336, "s": 4324, "text": "1)Countplot" }, { "code": null, "e": 4347, "s": 4336, "text": "2)Distplot" }, { "code": null, "e": 4359, "s": 4347, "text": "3)Jointplot" }, { "code": null, "e": 4380, "s": 4359, "text": "4)Boxplot/violinplot" }, { "code": null, "e": 4394, "s": 4380, "text": "5)Cluster map" }, { "code": null, "e": 4405, "s": 4394, "text": "6)Pairplot" }, { "code": null, "e": 4425, "s": 4405, "text": "Classification Tree" }, { "code": null, "e": 4448, "s": 4425, "text": "5. Data Pre-processing" }, { "code": null, "e": 4465, "s": 4448, "text": "1)Pre-processing" }, { "code": null, "e": 4484, "s": 4465, "text": "2)One Hot Encoding" }, { "code": null, "e": 4507, "s": 4484, "text": "6. Logistic Regression" }, { "code": null, "e": 4524, "s": 4507, "text": "1)Gather columns" }, { "code": null, "e": 4541, "s": 4524, "text": "2)Splitting Data" }, { "code": null, "e": 4557, "s": 4541, "text": "3)Normalization" }, { "code": null, "e": 4582, "s": 4557, "text": "4)Fitting into the model" }, { "code": null, "e": 4595, "s": 4582, "text": "5)Prediction" }, { "code": null, "e": 4614, "s": 4595, "text": "6)Model Evaluation" }, { "code": null, "e": 4628, "s": 4614, "text": "7. Conclusion" }, { "code": null, "e": 4643, "s": 4628, "text": "1)Coefficients" }, { "code": null, "e": 4654, "s": 4643, "text": "2)Analysis" }, { "code": null, "e": 4667, "s": 4654, "text": "3)Conclusion" }, { "code": null, "e": 4845, "s": 4667, "text": "import numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inlinedf = pd.read_csv('/content/drive/My Drive/dataset/heart.csv')df.head()" }, { "code": null, "e": 5107, "s": 4845, "text": "There has been lot of confusion about the meta data, as there are various different meta data available out there. Over here below I have got the two most used meta data description from kaggle. So we are going to follow the second description(2 — description)." }, { "code": null, "e": 5123, "s": 5107, "text": "1 — description" }, { "code": null, "e": 6275, "s": 5123, "text": "• age: The person's age in years• sex: The person's sex (1 = male, 0 = female)• cp: The chest pain experienced (Value 1: typical angina, Value 2: atypical angina, Value 3: non-anginal pain, Value 4: asymptomatic)• trestbps: The person's resting blood pressure (mm Hg on admission to the hospital)• chol: The person's cholesterol measurement in mg/dl• fbs: The person's fasting blood sugar (> 120 mg/dl, 1 = true; 0 = false)• restecg: Resting electrocardiographic measurement (0 = normal, 1 = having ST-T wave abnormality, 2 = showing probable or definite left ventricular hypertrophy by Estes' criteria)• thalach: The person's maximum heart rate achieved• exang: Exercise induced angina (1 = yes; 0 = no)• oldpeak: ST depression induced by exercise relative to rest ('ST' relates to positions on the ECG plot. See more here)• slope: the slope of the peak exercise ST segment (Value 1: upsloping, Value 2: flat, Value 3: downsloping)• ca: The number of major vessels (0-3)• thal: A blood disorder called thalassemia (3 = normal; 6 = fixed defect; 7 = reversable defect)• target: Heart disease (0 = no, 1 = yes)" }, { "code": null, "e": 6291, "s": 6275, "text": "2 — description" }, { "code": null, "e": 7274, "s": 6291, "text": "cp: chest pain type-- Value 0: asymptomatic-- Value 1: atypical angina-- Value 2: non-anginal pain-- Value 3: typical angina restecg: resting electrocardiographic results-- Value 0: showing probable or definite left ventricular hypertrophy by Estes' criteria-- Value 1: normal-- Value 2: having ST-T wave abnormality (T wave inversions and/or ST elevation or depression of > 0.05 mV) slope: the slope of the peak exercise ST segment0: downsloping; 1: flat; 2: upsloping thalResults of the blood flow observed via the radioactive dye. Value 0: NULL (dropped from the dataset previously)Value 1: fixed defect (no blood flow in some part of the heart)Value 2: normal blood flowValue 3: reversible defect (a blood flow is observed but it is not normal)This feature and the next one are obtained through a very invasive process for the patients. But, by themselves, they give a very good indication of the presence of a heart disease or not. target : 0 = disease, 1 = no diseasedf.info()" }, { "code": null, "e": 7288, "s": 7274, "text": "df.describe()" }, { "code": null, "e": 7313, "s": 7288, "text": "Checking for null values" }, { "code": null, "e": 7331, "s": 7313, "text": "df.isnull().sum()" }, { "code": null, "e": 7651, "s": 7331, "text": "#visualizing Null values if it exists plt.figure(figsize=(22,10))plt.xticks(size=20,color='grey')plt.tick_params(size=12,color='grey')plt.title('Finding Null Values Using Heatmap\\n',color='grey',size=30)sns.heatmap(df.isnull(), yticklabels=False, cbar=False, cmap='PuBu_r', )" }, { "code": null, "e": 7678, "s": 7651, "text": "Dataset has no null values" }, { "code": null, "e": 7812, "s": 7678, "text": "!pip install https://github.com/pandas-profiling/pandas-profiling/archive/master.zipimport pandas_profiling as pppp.ProfileReport(df)" }, { "code": null, "e": 7946, "s": 7812, "text": "For detailed view: https://colab.research.google.com/drive/16iFRPq0vx_CZypo4ZyJ_qTLrvds3FlDb#scrollTo=5crIBqgn9FiI&line=1&uniqifier=1" }, { "code": null, "e": 7964, "s": 7946, "text": "Feature Selection" }, { "code": null, "e": 8401, "s": 7964, "text": "Univariate Selction — Statistical tests may be used to pick certain features that have the best relationship to the performance variable.The scikit-learn library provides the SelectKBest class that can be used to select a specific number of features in a suite of different statistical tests.The following example uses the chi-squared (chi2) statistical test for non-negative features to select 13 of the best features from the Dataset." }, { "code": null, "e": 8838, "s": 8401, "text": "Univariate Selction — Statistical tests may be used to pick certain features that have the best relationship to the performance variable.The scikit-learn library provides the SelectKBest class that can be used to select a specific number of features in a suite of different statistical tests.The following example uses the chi-squared (chi2) statistical test for non-negative features to select 13 of the best features from the Dataset." }, { "code": null, "e": 9464, "s": 8838, "text": "from sklearn.feature_selection import SelectKBestfrom sklearn.feature_selection import chi2data = df.copy()X = data.iloc[:,0:13] #independent columnsy = data.iloc[:,-1] #target column #apply SelectKBest class to extract top best featuresbestfeatures = SelectKBest(score_func=chi2, k=10)fit = bestfeatures.fit(X,y)dfscores = pd.DataFrame(fit.scores_)dfcolumns = pd.DataFrame(X.columns)#concat two dataframes for better visualization featureScores = pd.concat([dfcolumns,dfscores],axis=1)featureScores.columns = ['Specs','Score'] #naming the dataframe columnsprint(featureScores.nlargest(12,'Score')) #print best features" }, { "code": null, "e": 9911, "s": 9464, "text": "2. Feature Importance — You can gain the significance of each feature of your dataset by using the Model Characteristics property.Feature value gives you a score for every function of your results, the higher the score the more significant or appropriate the performance variable is.Feature importance is the built-in class that comes with Tree Based Classifiers, we will use the Extra Tree Classifier to extract the top features for the dataset." }, { "code": null, "e": 10292, "s": 9911, "text": "from sklearn.ensemble import ExtraTreesClassifiermodel = ExtraTreesClassifier()model.fit(X,y)print(model.feature_importances_) #use inbuilt class feature_importances of tree based classifiers#plot graph of feature importances for better visualizationfeat_importances = pd.Series(model.feature_importances_, index=X.columns)feat_importances.nlargest(13).plot(kind='barh')plt.show()" }, { "code": null, "e": 10799, "s": 10292, "text": "3. Correlation Matrix with Heatmap — Correlation indicates how the features are related to each other or to the target variable.The correlation may be positive (increase in one value of the feature increases the value of the target variable) or negative (increase in one value of the feature decreases the value of the target variable)Heatmap makes it easy to classify the features are most relevant to the target variable, and we will plot the associated features of the heatmap using the seaborn library." }, { "code": null, "e": 11497, "s": 10799, "text": "Correlation shows whether the characteristics are related to each other or to the target variable. Correlation can be positive (increase in one value, the value of the objective variable increases) or negative (increase in one value, the value of the target variable decreased). From this heatmap we can observe that the ‘cp’ chest pain is highly related to the target variable. Compared to relation between other two variables we can say that chest pain contributes the most in prediction of presences of a heart disease. Medical emergency is a heart attack. A cardiac occurs usually when blood clot blocks blood flow to the cardiac. Tissue loses oxygen without blood and dies causing chest pain." }, { "code": null, "e": 11581, "s": 11497, "text": "plt.figure(figsize=(12,10))sns.heatmap(df.corr(),annot=True,cmap=\"magma\",fmt='.2f')" }, { "code": null, "e": 11634, "s": 11581, "text": "for i in df.columns: print(i,len(df[i].unique()))" }, { "code": null, "e": 11642, "s": 11634, "text": "Seaborn" }, { "code": null, "e": 11691, "s": 11642, "text": "sns.set_style('darkgrid')sns.set_palette('Set2')" }, { "code": null, "e": 11706, "s": 11691, "text": "Preparing Data" }, { "code": null, "e": 11987, "s": 11706, "text": "df2 = df.copy()def chng(sex): if sex == 0: return 'female' else: return 'male'df2['sex'] = df2['sex'].apply(chng)def chng2(prob): if prob == 0: return ‘Heart Disease’ else: return ‘No Heart Disease’df2['target'] = df2['target'].apply(chng2)" }, { "code": null, "e": 12108, "s": 11987, "text": "df2['target'] = df2['target'].apply(chng2)sns.countplot(data= df2, x='sex',hue='target')plt.title('Gender v/s target\\n')" }, { "code": null, "e": 12479, "s": 12108, "text": "According to this Cleveland dataset males are more susceptible to get Heart Disease than females. Men experience heart attacks more than women. Sudden Heart Attacks are experienced by men between 70% — 89%. Woman may experience a heart attack with no chest pressure at all, they usually experience nausea or vomiting which are often confused with acid reflux or the flu." }, { "code": null, "e": 12566, "s": 12479, "text": "sns.countplot(data= df2, x='cp',hue='target')plt.title('Chest Pain Type v/s target\\n')" }, { "code": null, "e": 13093, "s": 12566, "text": "There are four types of chest pain, asymptomatic, atypical angina, non-anginal pain and typical angina. Most of the Heart Disease patients are found to have asymptomatic chest pain. These group of people might show atypical symptoms like indigestion, flu or a strained chest muscle. A asymptomatic attack, like any heart attack, involves, blockage of blood flow to your heart and possible damage to the heart muscle. The risk factors for asymptomatic heart attacks are same as those with heart symptoms. These factors include:" }, { "code": null, "e": 13099, "s": 13093, "text": "· Age" }, { "code": null, "e": 13110, "s": 13099, "text": "· Diabetes" }, { "code": null, "e": 13126, "s": 13110, "text": "· Excess weight" }, { "code": null, "e": 13160, "s": 13126, "text": "· Family History of Heart Disease" }, { "code": null, "e": 13182, "s": 13160, "text": "· High Blood Pressure" }, { "code": null, "e": 13201, "s": 13182, "text": "· High cholesterol" }, { "code": null, "e": 13220, "s": 13201, "text": "· Lack of exercise" }, { "code": null, "e": 13241, "s": 13220, "text": "· Prior Heart attack" }, { "code": null, "e": 13255, "s": 13241, "text": "· Tobacco use" }, { "code": null, "e": 13692, "s": 13255, "text": "Asymptomatic Heart attack puts you at a greater risk of having another heart attack which could be d deadly. Having another heart attack also increases your risk of complications, such as heart failure. There are no test to determine your potential for asymptomatic heart attack. The only way to tell If you had asymptomatic attack is by an electrocardiogram or echocardiogram. These tests can reveal changes that signal a heart attack." }, { "code": null, "e": 13955, "s": 13692, "text": "sns.countplot(data= df2, x='sex',hue='thal')plt.title('Gender v/s Thalassemia\\n')print('Thalassemia (thal-uh-SEE-me-uh) is an inherited blood disorder that causes your body to have less hemoglobin than normal. Hemoglobin enables red blood cells to carry oxygen')" }, { "code": null, "e": 14354, "s": 13955, "text": "The Beta thalassemia cardiomyopathy is mainly characterized by two distinct pheno types , dilated type, with left ventricular dilatation and impaired contractility and a restrictive pheno type, with restrictive left ventricular feeling , pulmonary hyper tension and right heart failure. Heart problems, congestive heart failures and abnormal heart rhythms can be associated with severe thalassemia." }, { "code": null, "e": 14434, "s": 14354, "text": "sns.countplot(data= df2, x='slope',hue='target')plt.title('Slope v/s Target\\n')" }, { "code": null, "e": 14517, "s": 14434, "text": "sns.countplot(data= df2, x='exang',hue='thal')plt.title('exang v/s Thalassemia\\n')" }, { "code": null, "e": 14647, "s": 14517, "text": "plt.figure(figsize=(16,7))sns.distplot(df[df['target']==0]['age'],kde=False,bins=50)plt.title('Age of Heart Diseased Patients\\n')" }, { "code": null, "e": 14894, "s": 14647, "text": "Heart Disease is very common in the seniors which is composed of age group 60 and above and common among adults which belong to the age group of 41 to 60. But it’s rare among the age group of 19 to 40 and very rare among the age group of 0 to 18." }, { "code": null, "e": 15026, "s": 14894, "text": "plt.figure(figsize=(16,7))sns.distplot(df[df['target']==0]['chol'],kde=False,bins=40)plt.title('Chol of Heart Diseased Patients\\n')" }, { "code": null, "e": 15044, "s": 15026, "text": "Total cholesterol" }, { "code": null, "e": 15068, "s": 15044, "text": "LDL — ‘bad cholesterol”" }, { "code": null, "e": 15093, "s": 15068, "text": "HDL — ‘good cholesterol”" }, { "code": null, "e": 15938, "s": 15093, "text": "In adults, the total cholesterol levels are considered desirable less than 200 milligram per decilitre ( mg / dL). Borderlines are considered to be high between 200 to 239 mg / dL and 240 mg / dL and above. LDL should contain less than 100 mg / dL of cholesterol. 100 mg / dl rates for individuals without any health issue are appropriate but may be more relevant for those with cardiac problems or risk factors for heart disease. The levels are borderline moderate between 130 and 159 mg / dL and moderate between 160 and 189 mg / dL. The reading is very high at or above 190 mg / dL. Levels of HDL are to be maintained higher. The risk factor for cardiovascular diseases is called a reading less than 40 mg / dL. Borderline low is considered to be between 41 mg / dL and 59 mg / dL. The HDL level can be measured with a maximum of 60 mg / dL." }, { "code": null, "e": 16076, "s": 15938, "text": "plt.figure(figsize=(16,7))sns.distplot(df[df['target']==0]['thalach'],kde=False,bins=40)plt.title('thalach of Heart Diseased Patients\\n')" }, { "code": null, "e": 16091, "s": 16076, "text": "Preparing data" }, { "code": null, "e": 16530, "s": 16091, "text": "df3 = df[df['target'] == 0 ][['age', 'sex', 'cp', 'trestbps', 'chol', 'fbs', 'restecg', 'thalach', 'exang', 'oldpeak', 'slope', 'ca', 'thal', 'target']] #target 0 - people with heart diseasepal = sns.light_palette(\"blue\", as_cmap=True)print('Age vs trestbps(Heart Diseased Patinets)')sns.jointplot(data=df3, x='age', y='trestbps', kind='hex', cmap='Reds' )" }, { "code": null, "e": 16664, "s": 16530, "text": "sns.jointplot(data=df3, x='chol', y='age', kind='kde', cmap='PuBu' )" }, { "code": null, "e": 16923, "s": 16664, "text": "Joint plots in seaborn helps us to understand the trend seen among two features. As observed from the above plot we can see that most of the Heart diseased patients in their age of upper 50s or lower 60s tend to have Cholesterol between 200mg/dl to 300mg/dl." }, { "code": null, "e": 17052, "s": 16923, "text": "sns.jointplot(data=df3, x='chol', y='trestbps', kind='resid', )" }, { "code": null, "e": 17093, "s": 17052, "text": "sns.boxplot(data=df2,x='target',y='age')" }, { "code": null, "e": 17172, "s": 17093, "text": "plt.figure(figsize=(14,8))sns.violinplot(data=df2,x='ca',y='age',hue='target')" }, { "code": null, "e": 17226, "s": 17172, "text": "sns.boxplot(data=df2,x='cp',y='thalach',hue='target')" }, { "code": null, "e": 17308, "s": 17226, "text": "plt.figure(figsize=(10,7))sns.boxplot(data=df2,x='fbs',y='trestbps',hue='target')" }, { "code": null, "e": 17394, "s": 17308, "text": "plt.figure(figsize=(10,7))sns.violinplot(data=df2,x='exang',y='oldpeak',hue='target')" }, { "code": null, "e": 17477, "s": 17394, "text": "plt.figure(figsize=(10,7))sns.boxplot(data=df2,x='slope',y='thalach',hue='target')" }, { "code": null, "e": 17536, "s": 17477, "text": "sns.violinplot(data=df2,x='thal',y='oldpeak',hue='target')" }, { "code": null, "e": 17584, "s": 17536, "text": "sns.violinplot(data=df2,x='target',y='thalach')" }, { "code": null, "e": 17621, "s": 17584, "text": "sns.clustermap(df.corr(),annot=True)" }, { "code": null, "e": 17647, "s": 17621, "text": "sns.pairplot(df,hue='cp')" }, { "code": null, "e": 18338, "s": 17647, "text": "from sklearn.tree import DecisionTreeClassifier # Import Decision Tree Classifierfrom sklearn.model_selection import train_test_split # Import train_test_split functionfrom sklearn import metrics #Import scikit-learn metrics module for accuracy calculationX = df.iloc[:,0:13] # Featuresy = df.iloc[:,13] # Target variableX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1) # 70% training and 30% test# Create Decision Tree classifer objectclf = DecisionTreeClassifier()# Train Decision Tree Classiferclf = clf.fit(X_train,y_train)#Predict the response for test datasety_pred = clf.predict(X_test)print(\"Accuracy:\",metrics.accuracy_score(y_test, y_pred))" }, { "code": null, "e": 18367, "s": 18338, "text": "Accuracy: 0.7142857142857143" }, { "code": null, "e": 18941, "s": 18367, "text": "feature_cols = ['age', 'sex', 'cp', 'trestbps','chol', 'fbs', 'restecg', 'thalach','exang', 'oldpeak', 'slope', 'ca', 'thal']from sklearn.tree import export_graphvizfrom sklearn.externals.six import StringIO from IPython.display import Image import pydotplusdot_data = StringIO()export_graphviz(clf, out_file=dot_data, filled=True, rounded=True, special_characters=True,feature_names = feature_cols ,class_names=['0','1'])graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) graph.write_png('diabetes.png')Image(graph.create_png())" }, { "code": null, "e": 19281, "s": 18941, "text": "# Create Decision Tree classifer objectclf = DecisionTreeClassifier(criterion=\"entropy\", max_depth=3)# Train Decision Tree Classiferclf = clf.fit(X_train,y_train)#Predict the response for test datasety_pred = clf.predict(X_test)# Model Accuracy, how often is the classifier correct?print(\"Accuracy:\",metrics.accuracy_score(y_test, y_pred))" }, { "code": null, "e": 19310, "s": 19281, "text": "Accuracy: 0.7362637362637363" }, { "code": null, "e": 19758, "s": 19310, "text": "from sklearn.externals.six import StringIO from IPython.display import Image from sklearn.tree import export_graphvizimport pydotplusdot_data = StringIO()export_graphviz(clf, out_file=dot_data, filled=True, rounded=True, special_characters=True, feature_names = feature_cols,class_names=['0','1'])graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) graph.write_png('diabetes.png')Image(graph.create_png())" }, { "code": null, "e": 19784, "s": 19758, "text": "Change Name of the column" }, { "code": null, "e": 20067, "s": 19784, "text": "df.columns = ['age', 'sex', 'chest_pain_type', 'resting_blood_pressure', 'cholesterol', 'fasting_blood_sugar', 'rest_ecg_type', 'max_heart_rate_achieved', 'exercise_induced_angina', 'st_depression', 'st_slope_type', 'num_major_vessels', 'thalassemia_type', 'target']df.columns" }, { "code": null, "e": 20344, "s": 20067, "text": "Index([‘age’, ‘sex’, ‘chest_pain_type’, ‘resting_blood_pressure’, ‘cholesterol’, ‘fasting_blood_sugar’, ‘rest_ecg_type’, ‘max_heart_rate_achieved’, ‘exercise_induced_angina’, ‘st_depression’, ‘st_slope_type’, ‘num_major_vessels’, ‘thalassemia_type’, ‘target’], dtype=’object’)" }, { "code": null, "e": 20426, "s": 20344, "text": "We have 4 Categorical columns as seen in Data Description using pandas profiling:" }, { "code": null, "e": 20447, "s": 20426, "text": "cp — chest_pain_type" }, { "code": null, "e": 20471, "s": 20447, "text": "restecg — rest_ecg_type" }, { "code": null, "e": 20493, "s": 20471, "text": "slope — st_slope_type" }, { "code": null, "e": 20517, "s": 20493, "text": "thal — thalassemia_type" }, { "code": null, "e": 20555, "s": 20517, "text": "Generating categorical columns values" }, { "code": null, "e": 21621, "s": 20555, "text": "#cp - chest_pain_typedf.loc[df['chest_pain_type'] == 0, 'chest_pain_type'] = 'asymptomatic'df.loc[df['chest_pain_type'] == 1, 'chest_pain_type'] = 'atypical angina'df.loc[df['chest_pain_type'] == 2, 'chest_pain_type'] = 'non-anginal pain'df.loc[df['chest_pain_type'] == 3, 'chest_pain_type'] = 'typical angina'#restecg - rest_ecg_typedf.loc[df['rest_ecg_type'] == 0, 'rest_ecg_type'] = 'left ventricular hypertrophy'df.loc[df['rest_ecg_type'] == 1, 'rest_ecg_type'] = 'normal'df.loc[df['rest_ecg_type'] == 2, 'rest_ecg_type'] = 'ST-T wave abnormality'#slope - st_slope_typedf.loc[df['st_slope_type'] == 0, 'st_slope_type'] = 'downsloping'df.loc[df['st_slope_type'] == 1, 'st_slope_type'] = 'flat'df.loc[df['st_slope_type'] == 2, 'st_slope_type'] = 'upsloping'#thal - thalassemia_typedf.loc[df['thalassemia_type'] == 0, 'thalassemia_type'] = 'nothing'df.loc[df['thalassemia_type'] == 1, 'thalassemia_type'] = 'fixed defect'df.loc[df['thalassemia_type'] == 2, 'thalassemia_type'] = 'normal'df.loc[df['thalassemia_type'] == 3, 'thalassemia_type'] = 'reversable defect'" }, { "code": null, "e": 21677, "s": 21621, "text": "data = pd.get_dummies(df, drop_first=False)data.columns" }, { "code": null, "e": 22331, "s": 21677, "text": "Index([‘age’, ‘sex’, ‘resting_blood_pressure’, ‘cholesterol’, ‘fasting_blood_sugar’, ‘max_heart_rate_achieved’, ‘exercise_induced_angina’, ‘st_depression’, ‘num_major_vessels’, ‘target’, ‘chest_pain_type_asymptomatic’, ‘chest_pain_type_atypical angina’, ‘chest_pain_type_non-anginal pain’, ‘chest_pain_type_typical angina’, ‘rest_ecg_type_ST-T wave abnormality’, ‘rest_ecg_type_left ventricular hypertrophy’, ‘rest_ecg_type_normal’, ‘st_slope_type_downsloping’, ‘st_slope_type_flat’, ‘st_slope_type_upsloping’, ‘thalassemia_type_fixed defect’, ‘thalassemia_type_normal’, ‘thalassemia_type_nothing’, ‘thalassemia_type_reversable defect’], dtype=’object’)" }, { "code": null, "e": 22432, "s": 22331, "text": "df_temp = data['thalassemia_type_fixed defect']data = pd.get_dummies(df, drop_first=True)data.head()" }, { "code": null, "e": 22678, "s": 22432, "text": "Since one hot encoding dropped “thalassemia_type_fixed defect” column which was a useful column compared to ‘thalassemia_type_nothing’ which is a null column, we dropped ‘thalassemia_type_nothing’ and concatinated ‘thalassemia_type_fixed defect’" }, { "code": null, "e": 22876, "s": 22678, "text": "frames = [data, df_temp]result = pd.concat(frames,axis=1)result.drop('thalassemia_type_nothing',axis=1,inplace=True)resultc = result.copy()# making a copy for further analysis in conclusion section" }, { "code": null, "e": 22932, "s": 22876, "text": "X = result.drop('target', axis = 1)y = result['target']" }, { "code": null, "e": 23073, "s": 22932, "text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)" }, { "code": null, "e": 23245, "s": 23073, "text": "Min-Max Normalization method is used to Normalize the data. This method scales the data range to [0,1]. Standardization is also used on a feature-wise basis in most cases." }, { "code": null, "e": 23389, "s": 23245, "text": "X_train=(X_train-np.min(X_train))/(np.max(X_train)-np.min(X_train)).valuesX_test=(X_test-np.min(X_test))/(np.max(X_test)-np.min(X_test)).values" }, { "code": null, "e": 23495, "s": 23389, "text": "from sklearn.linear_model import LogisticRegressionlogre = LogisticRegression()logre.fit(X_train,y_train)" }, { "code": null, "e": 23745, "s": 23495, "text": "LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True, intercept_scaling=1, l1_ratio=None, max_iter=100, multi_class=’auto’, n_jobs=None, penalty=’l2', random_state=None, solver=’lbfgs’, tol=0.0001, verbose=0, warm_start=False)" }, { "code": null, "e": 24279, "s": 23745, "text": "y_pred = logre.predict(X_test)actual = []predcition = []for i,j in zip(y_test,y_pred): actual.append(i) predcition.append(j)dic = {'Actual':actual, 'Prediction':predcition }result = pd.DataFrame(dic)import plotly.graph_objects as go fig = go.Figure() fig.add_trace(go.Scatter(x=np.arange(0,len(y_test)), y=y_test, mode='markers+lines', name='Test'))fig.add_trace(go.Scatter(x=np.arange(0,len(y_test)), y=y_pred, mode='markers', name='Pred'))" }, { "code": null, "e": 24585, "s": 24279, "text": "The red dots represent the predicted values that is either 0 or 1 and the blue line & and dot represents the actual value of that particular patient. In the places where the red dot and blue dot do not overlap are the wrong predictions and where the both dots overlap those are the right predicted values." }, { "code": null, "e": 24664, "s": 24585, "text": "from sklearn.metrics import accuracy_scoreprint(accuracy_score(y_test,y_pred))" }, { "code": null, "e": 24683, "s": 24664, "text": "0.8688524590163934" }, { "code": null, "e": 24776, "s": 24683, "text": "from sklearn.metrics import classification_reportprint(classification_report(y_test,y_pred))" }, { "code": null, "e": 24951, "s": 24776, "text": "The classification report of the model shows that 91% prediction of absence of heart disease was predicted correct and 83% of presence of heart disease was predicted correct." }, { "code": null, "e": 25089, "s": 24951, "text": "from sklearn.metrics import confusion_matrixprint(confusion_matrix(y_test,y_pred))sns.heatmap(confusion_matrix(y_test,y_pred),annot=True)" }, { "code": null, "e": 25110, "s": 25089, "text": "The confusion Matrix" }, { "code": null, "e": 25248, "s": 25110, "text": "The Confusion Matrix True Positive value is 24 and true Negative was 29. And the False Positive came out to be 3 and False Negative is 5." }, { "code": null, "e": 25258, "s": 25248, "text": "ROC Curve" }, { "code": null, "e": 25418, "s": 25258, "text": "ROC Curves summarizes the trade-off between the true positive rate and the false positive rate for the predictive model using different probability thresholds." }, { "code": null, "e": 25471, "s": 25418, "text": "The accuracy of the ROC curve came out to be 87.09%." }, { "code": null, "e": 25774, "s": 25471, "text": "from sklearn.metrics import roc_curvefpr, tpr, thresholds = roc_curve(y_test, y_pred)plt.plot(fpr,tpr)plt.xlim([0.0, 1.0])plt.ylim([0.0, 1.0])plt.title('ROC curve for Heart disease classifier')plt.xlabel('False positive rate (1-Specificity)')plt.ylabel('True positive rate (Sensitivity)')plt.grid(True)" }, { "code": null, "e": 25833, "s": 25774, "text": "import sklearnsklearn.metrics.roc_auc_score(y_test,y_pred)" }, { "code": null, "e": 25852, "s": 25833, "text": "0.8709150326797386" }, { "code": null, "e": 26086, "s": 25852, "text": "print(logre.intercept_)plt.figure(figsize=(10,12))coeffecients = pd.DataFrame(logre.coef_.ravel(),X.columns)coeffecients.columns = ['Coeffecient']coeffecients.sort_values(by=['Coeffecient'],inplace=True,ascending=False)coeffecientsts" }, { "code": null, "e": 26114, "s": 26086, "text": "Preparing data for analysis" }, { "code": null, "e": 26434, "s": 26114, "text": "df4 = df[df['target'] == 0 ][['age', 'sex', 'chest_pain_type', 'resting_blood_pressure','cholesterol', 'fasting_blood_sugar', 'rest_ecg_type', 'max_heart_rate_achieved', 'exercise_induced_angina', 'st_depression','st_slope_type', 'num_major_vessels', 'thalassemia_type', 'target']] #target 0 - people with heart disease" }, { "code": null, "e": 26473, "s": 26434, "text": "Heart Diseased Patient’s visualization" }, { "code": null, "e": 26544, "s": 26473, "text": "plt.figure(figsize=(16,6))sns.distplot(df4['max_heart_rate_achieved'])" }, { "code": null, "e": 26832, "s": 26544, "text": "Normal Heart rate is found to be between 60 and 100 bpm. Some areas of cardiac muscles will start to die during a Heart Attack because of Lack of Blood. A person’s pulse may become slower (bradycardia) or faster (tachycardiac) depending on the type of Heart Attack they are experiencing." }, { "code": null, "e": 26936, "s": 26832, "text": "plt.figure(figsize=(20,6))sns.boxenplot(data=df4,x='rest_ecg_type',y='cholesterol',hue='st_slope_type')" }, { "code": null, "e": 27237, "s": 26936, "text": "In normal type of rest ECG proves to be important for the prediction model along with the down sloping ST slope. The patient composed of these two features usually has cholesterol level between 170 to 225 mg/dl. The other types of slops with the rest ECG seems to be more spread out and less concise." }, { "code": null, "e": 27358, "s": 27237, "text": "plt.figure(figsize=(20,6))sns.boxenplot(data=df4,x='chest_pain_type',y='max_heart_rate_achieved',hue='thalassemia_type')" }, { "code": null, "e": 27370, "s": 27358, "text": "Shap Values" }, { "code": null, "e": 27561, "s": 27370, "text": "!pip install shap import shapexplainer = shap.TreeExplainer(model)shap_values = explainer.shap_values(X_test,check_additivity=False)shap.summary_plot(shap_values[1], X_test, plot_type=\"bar\")" }, { "code": null, "e": 27595, "s": 27561, "text": "Shap value for Model Explaination" }, { "code": null, "e": 27637, "s": 27595, "text": "shap.summary_plot(shap_values[1], X_test)" }, { "code": null, "e": 27853, "s": 27637, "text": "def patient_analysis(model, patient): explainer = shap.TreeExplainer(model) shap_values = explainer.shap_values(patient) shap.initjs() return shap.force_plot(explainer.expected_value[1], shap_values[1], patient)" }, { "code": null, "e": 27878, "s": 27853, "text": "Reports for two Patients" }, { "code": null, "e": 28026, "s": 27878, "text": "patients = X_test.iloc[3,:].astype(float)patients_target = y_test.iloc[3:4]print('Target : ',int(patients_target))patient_analysis(model, patients)" }, { "code": null, "e": 28037, "s": 28026, "text": "Target : 0" }, { "code": null, "e": 28188, "s": 28037, "text": "patients = X_test.iloc[33,:].astype(float)patients_target = y_test.iloc[33:34]print('Target : ',int(patients_target))patient_analysis(model, patients)" }, { "code": null, "e": 28199, "s": 28188, "text": "Target : 1" }, { "code": null, "e": 28319, "s": 28199, "text": "# dependence plotshap.dependence_plot('num_major_vessels', shap_values[1], X_test, interaction_index = \"st_depression\")" }, { "code": null, "e": 28488, "s": 28319, "text": "shap_values = explainer.shap_values(X_train.iloc[:50],check_additivity=False)shap.initjs()shap.force_plot(explainer.expected_value[1], shap_values[1], X_test.iloc[:50])" }, { "code": null, "e": 28559, "s": 28488, "text": "The Area under the ROC curve is 87.09% which is somewhat satisfactory." }, { "code": null, "e": 28644, "s": 28559, "text": "The model predicted with 86.88% accuracy. The model is more specific than sensitive." }, { "code": null, "e": 28778, "s": 28644, "text": "According to this model the major features contributing in precision of predicting model are shown in the heatmap in Ascending order." }, { "code": null, "e": 29048, "s": 28778, "text": "plt.figure(figsize=(10,12))coeffecients = pd.DataFrame(logre.coef_.ravel(),X.columns)coeffecients.columns = ['Coeffecient']coeffecients.sort_values(by=['Coeffecient'],inplace=True,ascending=False)sns.heatmap(coeffecients,annot=True,fmt='.2f',cmap='Set2',linewidths=0.5)" } ]
C++ Program for QuickSort - GeeksforGeeks
06 Feb, 2022 Similar to the Merge Sort algorithm, the Quick Sort algorithm is a Divide and Conquer algorithm. It initially selects an element as a pivot element and partitions the given array around the picked pivot. There are many different versions of quickSort that pick pivot in different ways. Always pick the first element as a pivot (implemented below).Always pick the last element as the pivot.Pick a random element as a pivot.Pick median as a pivot. Always pick the first element as a pivot (implemented below). Always pick the last element as the pivot. Pick a random element as a pivot. Pick median as a pivot. The key process in quickSort is the partition() process. The aim of the partition() function is to receive an array and an element x of the array as a pivot, put x at its correct position in a sorted array and then put all smaller elements (smaller than x) before x, and put all greater elements (greater than x) after x. All this should be done in linear time i.e. Big O(n) .Pseudo Code for recursive QuickSort function : /* low --> Starting index, high --> Ending index */ quickSort(arr[], low, high) { if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ pi = partition(arr, low, high); quickSort(arr, low, pi - 1); // Before pi quickSort(arr, pi + 1, high); // After pi } } CPP // C++ Implementation of the Quick Sort Algorithm.#include <iostream>using namespace std; int partition(int arr[], int start, int end){ int pivot = arr[start]; int count = 0; for (int i = start + 1; i <= end; i++) { if (arr[i] <= pivot) count++; } // Giving pivot element its correct position int pivotIndex = start + count; swap(arr[pivotIndex], arr[start]); // Sorting left and right parts of the pivot element int i = start, j = end; while (i < pivotIndex && j > pivotIndex) { while (arr[i] <= pivot) { i++; } while (arr[j] > pivot) { j--; } if (i < pivotIndex && j > pivotIndex) { swap(arr[i++], arr[j--]); } } return pivotIndex;} void quickSort(int arr[], int start, int end){ // base case if (start >= end) return; // partitioning the array int p = partition(arr, start, end); // Sorting the left part quickSort(arr, start, p - 1); // Sorting the right part quickSort(arr, p + 1, end);} int main(){ int arr[] = { 9, 3, 4, 2, 1, 8 }; int n = 6; quickSort(arr, 0, n - 1); for (int i = 0; i < n; i++) { cout << arr[i] << " "; } return 0;} 1 2 3 4 8 9 Please refer complete article on QuickSort for more details! hitesh_tripathi shreyasnaphad Quick Sort C++ Programs Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Passing a function as a parameter in C++ Program to implement Singly Linked List in C++ using class cout in C++ Pi(π) in C++ with Examples Const keyword in C++
[ { "code": null, "e": 24187, "s": 24159, "text": "\n06 Feb, 2022" }, { "code": null, "e": 24474, "s": 24187, "text": "Similar to the Merge Sort algorithm, the Quick Sort algorithm is a Divide and Conquer algorithm. It initially selects an element as a pivot element and partitions the given array around the picked pivot. There are many different versions of quickSort that pick pivot in different ways. " }, { "code": null, "e": 24634, "s": 24474, "text": "Always pick the first element as a pivot (implemented below).Always pick the last element as the pivot.Pick a random element as a pivot.Pick median as a pivot." }, { "code": null, "e": 24696, "s": 24634, "text": "Always pick the first element as a pivot (implemented below)." }, { "code": null, "e": 24739, "s": 24696, "text": "Always pick the last element as the pivot." }, { "code": null, "e": 24773, "s": 24739, "text": "Pick a random element as a pivot." }, { "code": null, "e": 24797, "s": 24773, "text": "Pick median as a pivot." }, { "code": null, "e": 25222, "s": 24797, "text": "The key process in quickSort is the partition() process. The aim of the partition() function is to receive an array and an element x of the array as a pivot, put x at its correct position in a sorted array and then put all smaller elements (smaller than x) before x, and put all greater elements (greater than x) after x. All this should be done in linear time i.e. Big O(n) .Pseudo Code for recursive QuickSort function : " }, { "code": null, "e": 25563, "s": 25222, "text": "/* low --> Starting index, high --> Ending index */\nquickSort(arr[], low, high)\n{\n if (low < high)\n {\n /* pi is partitioning index, arr[p] is now\n at right place */\n pi = partition(arr, low, high);\n\n quickSort(arr, low, pi - 1); // Before pi\n quickSort(arr, pi + 1, high); // After pi\n }\n}" }, { "code": null, "e": 25567, "s": 25563, "text": "CPP" }, { "code": "// C++ Implementation of the Quick Sort Algorithm.#include <iostream>using namespace std; int partition(int arr[], int start, int end){ int pivot = arr[start]; int count = 0; for (int i = start + 1; i <= end; i++) { if (arr[i] <= pivot) count++; } // Giving pivot element its correct position int pivotIndex = start + count; swap(arr[pivotIndex], arr[start]); // Sorting left and right parts of the pivot element int i = start, j = end; while (i < pivotIndex && j > pivotIndex) { while (arr[i] <= pivot) { i++; } while (arr[j] > pivot) { j--; } if (i < pivotIndex && j > pivotIndex) { swap(arr[i++], arr[j--]); } } return pivotIndex;} void quickSort(int arr[], int start, int end){ // base case if (start >= end) return; // partitioning the array int p = partition(arr, start, end); // Sorting the left part quickSort(arr, start, p - 1); // Sorting the right part quickSort(arr, p + 1, end);} int main(){ int arr[] = { 9, 3, 4, 2, 1, 8 }; int n = 6; quickSort(arr, 0, n - 1); for (int i = 0; i < n; i++) { cout << arr[i] << \" \"; } return 0;}", "e": 26811, "s": 25567, "text": null }, { "code": null, "e": 26824, "s": 26811, "text": "1 2 3 4 8 9 " }, { "code": null, "e": 26885, "s": 26824, "text": "Please refer complete article on QuickSort for more details!" }, { "code": null, "e": 26901, "s": 26885, "text": "hitesh_tripathi" }, { "code": null, "e": 26915, "s": 26901, "text": "shreyasnaphad" }, { "code": null, "e": 26926, "s": 26915, "text": "Quick Sort" }, { "code": null, "e": 26939, "s": 26926, "text": "C++ Programs" }, { "code": null, "e": 26947, "s": 26939, "text": "Sorting" }, { "code": null, "e": 26955, "s": 26947, "text": "Sorting" }, { "code": null, "e": 27053, "s": 26955, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27062, "s": 27053, "text": "Comments" }, { "code": null, "e": 27075, "s": 27062, "text": "Old Comments" }, { "code": null, "e": 27116, "s": 27075, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 27175, "s": 27116, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 27187, "s": 27175, "text": "cout in C++" }, { "code": null, "e": 27214, "s": 27187, "text": "Pi(π) in C++ with Examples" } ]
C library function - tolower()
The C library function int tolower(int c) converts a given letter to lowercase. Following is the declaration for tolower() function. int tolower(int c); c − This is the letter to be converted to lowercase. c − This is the letter to be converted to lowercase. This function returns lowercase equivalent to c, if such value exists, else c remains unchanged. The value is returned as an int value that can be implicitly casted to char. The following example shows the usage of tolower() function. #include <stdio.h> #include <ctype.h> int main () { int i = 0; char c; char str[] = "TUTORIALS POINT"; while( str[i] ) { putchar(tolower(str[i])); i++; } return(0); } Let us compile and run the above program to produce the following result − tutorials point 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2087, "s": 2007, "text": "The C library function int tolower(int c) converts a given letter to lowercase." }, { "code": null, "e": 2140, "s": 2087, "text": "Following is the declaration for tolower() function." }, { "code": null, "e": 2160, "s": 2140, "text": "int tolower(int c);" }, { "code": null, "e": 2213, "s": 2160, "text": "c − This is the letter to be converted to lowercase." }, { "code": null, "e": 2266, "s": 2213, "text": "c − This is the letter to be converted to lowercase." }, { "code": null, "e": 2440, "s": 2266, "text": "This function returns lowercase equivalent to c, if such value exists, else c remains unchanged. The value is returned as an int value that can be implicitly casted to char." }, { "code": null, "e": 2501, "s": 2440, "text": "The following example shows the usage of tolower() function." }, { "code": null, "e": 2705, "s": 2501, "text": "#include <stdio.h>\n#include <ctype.h>\n\nint main () {\n int i = 0;\n char c;\n char str[] = \"TUTORIALS POINT\";\n\t\n while( str[i] ) {\n putchar(tolower(str[i]));\n i++;\n }\n \n return(0);\n}" }, { "code": null, "e": 2780, "s": 2705, "text": "Let us compile and run the above program to produce the following result −" }, { "code": null, "e": 2797, "s": 2780, "text": "tutorials point\n" }, { "code": null, "e": 2830, "s": 2797, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 2845, "s": 2830, "text": " Nishant Malik" }, { "code": null, "e": 2880, "s": 2845, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2895, "s": 2880, "text": " Nishant Malik" }, { "code": null, "e": 2930, "s": 2895, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 2944, "s": 2930, "text": " Asif Hussain" }, { "code": null, "e": 2977, "s": 2944, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 2995, "s": 2977, "text": " Richa Maheshwari" }, { "code": null, "e": 3030, "s": 2995, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3049, "s": 3030, "text": " Vandana Annavaram" }, { "code": null, "e": 3082, "s": 3049, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 3094, "s": 3082, "text": " Amit Diwan" }, { "code": null, "e": 3101, "s": 3094, "text": " Print" }, { "code": null, "e": 3112, "s": 3101, "text": " Add Notes" } ]
Facial expression detection using Deepface module in Python - GeeksforGeeks
28 Jul, 2021 In this article, we are going to detect the facial expression of an already existing image using OpenCV, Deepface, and matplotlib modules in python. OpenCV: OpenCV is an open-source library in python which is used for computer vision, machine learning, and image processing. Matplotlib: Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. Deepface: Deepface was built by an artificial intelligence researchers group at Facebook. It is a framework in python for facial recognition and attributes analysis. Deepface’s core library components are used in Keras and TensorFlow. pip install deepface This is the most basic expression detection technique and there are several ways in which we can detect facial expression. Step 1: Importing the required module. Python3 #import the required modulesimport cv2import matplotlib.pyplot as pltfrom deepface import DeepFace Step 2: Copy the path of the picture of which expression detection is to be done, read the image using “imread()” method in cv2 providing the path within the bracket. imread() reads the image from the file and stores it in an array. Then use imshow() method of matplotlib. imshow() method converts data into image. Now plot the image using show method in order to ensure that the image has been correctly imported. Python3 # read imageimg = cv2.imread('img1.jpg') # call imshow() using plt objectplt.imshow(img[:, :, : : -1]) # display that imageplt.show() Output: Output image Step 3: Create a result variable that will store the result. Use Deepface analyze() method, Deepface analyze() method contains strong facial attribute analysis features such as age, gender, facial expressions. Facial expressions include anger, fear, neutral, sad, disgust, happy, and surprise. Print the result. The result shows the facial expressions percentage of the person. Python3 # storing the resultresult = DeepFace.analyze(img, actions = ['emotion']) # print resultprint(result) Output: The result shows that person is 96% happy. Below is the complete implementation: Python3 # import the required modulesimport cv2import matplotlib.pyplot as pltfrom deepface import DeepFace # read imageimg = cv2.imread('img.jpg') # call imshow() using plt objectplt.imshow(img[:,:,::-1]) # display that imageplt.show() # storing the resultresult = DeepFace.analyze(img,actions=['emotion']) # print resultprint(result) Output: Picked python-modules 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 ? How to drop one or multiple columns in Pandas Dataframe Python OOPs Concepts Python | Get unique values from a list Check if element exists in list in Python Python Classes and Objects Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Pandas dataframe.groupby() Create a directory in Python
[ { "code": null, "e": 24238, "s": 24210, "text": "\n28 Jul, 2021" }, { "code": null, "e": 24387, "s": 24238, "text": "In this article, we are going to detect the facial expression of an already existing image using OpenCV, Deepface, and matplotlib modules in python." }, { "code": null, "e": 24513, "s": 24387, "text": "OpenCV: OpenCV is an open-source library in python which is used for computer vision, machine learning, and image processing." }, { "code": null, "e": 24636, "s": 24513, "text": "Matplotlib: Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python." }, { "code": null, "e": 24871, "s": 24636, "text": "Deepface: Deepface was built by an artificial intelligence researchers group at Facebook. It is a framework in python for facial recognition and attributes analysis. Deepface’s core library components are used in Keras and TensorFlow." }, { "code": null, "e": 24892, "s": 24871, "text": "pip install deepface" }, { "code": null, "e": 25016, "s": 24892, "text": "This is the most basic expression detection technique and there are several ways in which we can detect facial expression. " }, { "code": null, "e": 25055, "s": 25016, "text": "Step 1: Importing the required module." }, { "code": null, "e": 25063, "s": 25055, "text": "Python3" }, { "code": "#import the required modulesimport cv2import matplotlib.pyplot as pltfrom deepface import DeepFace", "e": 25162, "s": 25063, "text": null }, { "code": null, "e": 25577, "s": 25162, "text": "Step 2: Copy the path of the picture of which expression detection is to be done, read the image using “imread()” method in cv2 providing the path within the bracket. imread() reads the image from the file and stores it in an array. Then use imshow() method of matplotlib. imshow() method converts data into image. Now plot the image using show method in order to ensure that the image has been correctly imported." }, { "code": null, "e": 25585, "s": 25577, "text": "Python3" }, { "code": "# read imageimg = cv2.imread('img1.jpg') # call imshow() using plt objectplt.imshow(img[:, :, : : -1]) # display that imageplt.show()", "e": 25721, "s": 25585, "text": null }, { "code": null, "e": 25729, "s": 25721, "text": "Output:" }, { "code": null, "e": 25742, "s": 25729, "text": "Output image" }, { "code": null, "e": 26120, "s": 25742, "text": "Step 3: Create a result variable that will store the result. Use Deepface analyze() method, Deepface analyze() method contains strong facial attribute analysis features such as age, gender, facial expressions. Facial expressions include anger, fear, neutral, sad, disgust, happy, and surprise. Print the result. The result shows the facial expressions percentage of the person." }, { "code": null, "e": 26128, "s": 26120, "text": "Python3" }, { "code": "# storing the resultresult = DeepFace.analyze(img, actions = ['emotion']) # print resultprint(result)", "e": 26256, "s": 26128, "text": null }, { "code": null, "e": 26264, "s": 26256, "text": "Output:" }, { "code": null, "e": 26307, "s": 26264, "text": "The result shows that person is 96% happy." }, { "code": null, "e": 26345, "s": 26307, "text": "Below is the complete implementation:" }, { "code": null, "e": 26353, "s": 26345, "text": "Python3" }, { "code": "# import the required modulesimport cv2import matplotlib.pyplot as pltfrom deepface import DeepFace # read imageimg = cv2.imread('img.jpg') # call imshow() using plt objectplt.imshow(img[:,:,::-1]) # display that imageplt.show() # storing the resultresult = DeepFace.analyze(img,actions=['emotion']) # print resultprint(result)", "e": 26686, "s": 26353, "text": null }, { "code": null, "e": 26694, "s": 26686, "text": "Output:" }, { "code": null, "e": 26701, "s": 26694, "text": "Picked" }, { "code": null, "e": 26716, "s": 26701, "text": "python-modules" }, { "code": null, "e": 26730, "s": 26716, "text": "Python-OpenCV" }, { "code": null, "e": 26737, "s": 26730, "text": "Python" }, { "code": null, "e": 26835, "s": 26737, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26844, "s": 26835, "text": "Comments" }, { "code": null, "e": 26857, "s": 26844, "text": "Old Comments" }, { "code": null, "e": 26889, "s": 26857, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26945, "s": 26889, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26966, "s": 26945, "text": "Python OOPs Concepts" }, { "code": null, "e": 27005, "s": 26966, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27047, "s": 27005, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27074, "s": 27047, "text": "Python Classes and Objects" }, { "code": null, "e": 27105, "s": 27074, "text": "Python | os.path.join() method" }, { "code": null, "e": 27147, "s": 27105, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27183, "s": 27147, "text": "Python | Pandas dataframe.groupby()" } ]
F# - Lists
In F#, a list is an ordered, immutable series of elements of the same type. It is to some extent equivalent to a linked list data structure. The F# module, Microsoft.FSharp.Collections.List, has the common operations on lists. However F# imports this module automatically and makes it accessible to every F# application. Following are the various ways of creating lists − Using list literals. Using list literals. Using cons (::) operator. Using cons (::) operator. Using the List.init method of List module. Using the List.init method of List module. Using some syntactic constructs called List Comprehensions. Using some syntactic constructs called List Comprehensions. In this method, you just specify a semicolon-delimited sequence of values in square brackets. For example − let list1 = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10] With this method, you can add some values by prepending or cons-ing it to an existing list using the :: operator. For example − let list2 = 1::2::3::4::5::6::7::8::9::10::[];; [] denotes an empty list. The List.init method of the List module is often used for creating lists. This method has the type − val init : int -> (int -> 'T) -> 'T list The first argument is the desired length of the new list, and the second argument is an initializer function, which generates items in the list. For example, let list5 = List.init 5 (fun index -> (index, index * index, index * index * index)) Here, the index function generates the list. List comprehensions are special syntactic constructs used for generating lists. F# list comprehension syntax comes in two forms − ranges and generators. Ranges have the constructs − [start .. end] and [start .. step .. end] For example, let list3 = [1 .. 10] Generators have the construct − [for x in collection do ... yield expr] For example, let list6 = [ for a in 1 .. 10 do yield (a * a) ] As the yield keyword pushes a single value into a list, the keyword, yield!, pushes a collection of values into the list. The following function demonstrates the above methods − (* using list literals *) let list1 = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10] printfn "The list: %A" list1 (*using cons operator *) let list2 = 1 :: 2 :: 3 :: [] printfn "The list: %A" list2 (* using range constructs*) let list3 = [1 .. 10] printfn "The list: %A" list3 (* using range constructs *) let list4 = ['a' .. 'm'] printfn "The list: %A" list4 (* using init method *) let list5 = List.init 5 (fun index -> (index, index * index, index * index * index)) printfn "The list: %A" list5 (* using yield operator *) let list6 = [ for a in 1 .. 10 do yield (a * a) ] printfn "The list: %A" list6 (* using yield operator *) let list7 = [ for a in 1 .. 100 do if a % 3 = 0 && a % 5 = 0 then yield a] printfn "The list: %A" list7 (* using yield! operator *) let list8 = [for a in 1 .. 3 do yield! [ a .. a + 3 ] ] printfn "The list: %A" list8 When you compile and execute the program, it yields the following output − The list: [1; 2; 3; 4; 5; 6; 7; 8; 9; 10] The list: [1; 2; 3] The list: [1; 2; 3; 4; 5; 6; 7; 8; 9; 10] The list: ['a'; 'b'; 'c'; 'd'; 'e'; 'f'; 'g'; 'h'; 'i'; 'j'; 'k'; 'l'; 'm'] The list: [(0, 0, 0); (1, 1, 1); (2, 4, 8); (3, 9, 27); (4, 16, 64)] The list: [1; 4; 9; 16; 25; 36; 49; 64; 81; 100] The list: [15; 30; 45; 60; 75; 90] The list: [1; 2; 3; 4; 2; 3; 4; 5; 3; 4; 5; 6] The following table shows various properties of list data type − The following example shows the use of these properties − let list1 = [ 2; 4; 6; 8; 10; 12; 14; 16 ] // Use of Properties printfn "list1.IsEmpty is %b" (list1.IsEmpty) printfn "list1.Length is %d" (list1.Length) printfn "list1.Head is %d" (list1.Head) printfn "list1.Tail.Head is %d" (list1.Tail.Head) printfn "list1.Tail.Tail.Head is %d" (list1.Tail.Tail.Head) printfn "list1.Item(1) is %d" (list1.Item(1)) When you compile and execute the program, it yields the following output − list1.IsEmpty is false list1.Length is 8 list1.Head is 2 list1.Tail.Head is 4 list1.Tail.Tail.Head is 6 list1.Item(1) is 4 The following table shows the basic operations on list data type − The following examples demonstrate the uses of the above functionalities − This program shows reversing a list recursively − let list1 = [ 2; 4; 6; 8; 10; 12; 14; 16 ] printfn "The original list: %A" list1 let reverse lt = let rec loop acc = function | [] -> acc | hd :: tl -> loop (hd :: acc) tl loop [] lt printfn "The reversed list: %A" (reverse list1) When you compile and execute the program, it yields the following output − The original list: [2; 4; 6; 8; 10; 12; 14; 16] The reversed list: [16; 14; 12; 10; 8; 6; 4; 2] However, you can use the rev function of the module for the same purpose − let list1 = [ 2; 4; 6; 8; 10; 12; 14; 16 ] printfn "The original list: %A" list1 printfn "The reversed list: %A" (List.rev list1) When you compile and execute the program, it yields the following output − The original list: [2; 4; 6; 8; 10; 12; 14; 16] The reversed list: [16; 14; 12; 10; 8; 6; 4; 2] This program shows filtering a list using the List.filter method − let list1 = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10] printfn "The list: %A" list1 let list2 = list1 |> List.filter (fun x -> x % 2 = 0);; printfn "The Filtered list: %A" list2 When you compile and execute the program, it yields the following output − The list: [1; 2; 3; 4; 5; 6; 7; 8; 9; 10] The Filtered list: [2; 4; 6; 8; 10] The List.map method maps a list from one type to another − let list1 = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10] printfn "The list: %A" list1 let list2 = list1 |> List.map (fun x -> (x * x).ToString());; printfn "The Mapped list: %A" list2 When you compile and execute the program, it yields the following output − The list: [1; 2; 3; 4; 5; 6; 7; 8; 9; 10] The Mapped list: ["1"; "4"; "9"; "16"; "25"; "36"; "49"; "64"; "81"; "100"] The List.append method and the @ operator appends one list to another − let list1 = [1; 2; 3; 4; 5 ] let list2 = [6; 7; 8; 9; 10] let list3 = List.append list1 list2 printfn "The first list: %A" list1 printfn "The second list: %A" list2 printfn "The appened list: %A" list3 let lt1 = ['a'; 'b';'c' ] let lt2 = ['e'; 'f';'g' ] let lt3 = lt1 @ lt2 printfn "The first list: %A" lt1 printfn "The second list: %A" lt2 printfn "The appened list: %A" lt3 When you compile and execute the program, it yields the following output − The first list: [1; 2; 3; 4; 5] The second list: [6; 7; 8; 9; 10] The appened list: [1; 2; 3; 4; 5; 6; 7; 8; 9; 10] The first list: ['a'; 'b'; 'c'] The second list: ['e'; 'f'; 'g'] The appened list: ['a'; 'b'; 'c'; 'e'; 'f'; 'g'] The List.sort method sorts a list. The List.sum method gives the sum of elements in the list and the List.average method gives the average of elements in the list − let list1 = [9.0; 0.0; 2.0; -4.5; 11.2; 8.0; -10.0] printfn "The list: %A" list1 let list2 = List.sort list1 printfn "The sorted list: %A" list2 let s = List.sum list1 let avg = List.average list1 printfn "The sum: %f" s printfn "The average: %f" avg When you compile and execute the program, it yields the following output − The list: [9.0; 0.0; 2.0; -4.5; 11.2; 8.0; -10.0] The sorted list: [-10.0; -4.5; 0.0; 2.0; 8.0; 9.0; 11.2] The sum: 15.700000 The average: 2.242857 A "fold" operation applies a function to each element in a list, aggregates the result of the function in an accumulator variable, and returns the accumulator as the result of the fold operation. The List.fold method applies a function to each element from left to right, while List.foldBack applies a function to each element from right to left. let sumList list = List.fold (fun acc elem -> acc + elem) 0 list printfn "Sum of the elements of list %A is %d." [ 1 .. 10 ] (sumList [ 1 .. 10 ]) When you compile and execute the program, it yields the following output − Sum of the elements of list [1; 2; 3; 4; 5; 6; 7; 8; 9; 10] is 55. Print Add Notes Bookmark this page
[ { "code": null, "e": 2302, "s": 2161, "text": "In F#, a list is an ordered, immutable series of elements of the same type. It is to some extent equivalent to a linked list data structure." }, { "code": null, "e": 2482, "s": 2302, "text": "The F# module, Microsoft.FSharp.Collections.List, has the common operations on lists. However F# imports this module automatically and makes it accessible to every F# application." }, { "code": null, "e": 2533, "s": 2482, "text": "Following are the various ways of creating lists −" }, { "code": null, "e": 2554, "s": 2533, "text": "Using list literals." }, { "code": null, "e": 2575, "s": 2554, "text": "Using list literals." }, { "code": null, "e": 2601, "s": 2575, "text": "Using cons (::) operator." }, { "code": null, "e": 2627, "s": 2601, "text": "Using cons (::) operator." }, { "code": null, "e": 2670, "s": 2627, "text": "Using the List.init method of List module." }, { "code": null, "e": 2713, "s": 2670, "text": "Using the List.init method of List module." }, { "code": null, "e": 2773, "s": 2713, "text": "Using some syntactic constructs called List Comprehensions." }, { "code": null, "e": 2833, "s": 2773, "text": "Using some syntactic constructs called List Comprehensions." }, { "code": null, "e": 2941, "s": 2833, "text": "In this method, you just specify a semicolon-delimited sequence of values in square brackets. For example −" }, { "code": null, "e": 2986, "s": 2941, "text": "let list1 = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]\n" }, { "code": null, "e": 3114, "s": 2986, "text": "With this method, you can add some values by prepending or cons-ing it to an existing list using the :: operator. For example −" }, { "code": null, "e": 3163, "s": 3114, "text": "let list2 = 1::2::3::4::5::6::7::8::9::10::[];;\n" }, { "code": null, "e": 3189, "s": 3163, "text": "[] denotes an empty list." }, { "code": null, "e": 3290, "s": 3189, "text": "The List.init method of the List module is often used for creating lists. This method has the type −" }, { "code": null, "e": 3332, "s": 3290, "text": "val init : int -> (int -> 'T) -> 'T list\n" }, { "code": null, "e": 3477, "s": 3332, "text": "The first argument is the desired length of the new list, and the second argument is an initializer function, which generates items in the list." }, { "code": null, "e": 3490, "s": 3477, "text": "For example," }, { "code": null, "e": 3576, "s": 3490, "text": "let list5 = List.init 5 (fun index -> (index, index * index, index * index * index))\n" }, { "code": null, "e": 3621, "s": 3576, "text": "Here, the index function generates the list." }, { "code": null, "e": 3701, "s": 3621, "text": "List comprehensions are special syntactic constructs used for generating lists." }, { "code": null, "e": 3774, "s": 3701, "text": "F# list comprehension syntax comes in two forms − ranges and generators." }, { "code": null, "e": 3845, "s": 3774, "text": "Ranges have the constructs − [start .. end] and [start .. step .. end]" }, { "code": null, "e": 3858, "s": 3845, "text": "For example," }, { "code": null, "e": 3881, "s": 3858, "text": "let list3 = [1 .. 10]\n" }, { "code": null, "e": 3953, "s": 3881, "text": "Generators have the construct − [for x in collection do ... yield expr]" }, { "code": null, "e": 3966, "s": 3953, "text": "For example," }, { "code": null, "e": 4017, "s": 3966, "text": "let list6 = [ for a in 1 .. 10 do yield (a * a) ]\n" }, { "code": null, "e": 4139, "s": 4017, "text": "As the yield keyword pushes a single value into a list, the keyword, yield!, pushes a collection of values into the list." }, { "code": null, "e": 4195, "s": 4139, "text": "The following function demonstrates the above methods −" }, { "code": null, "e": 5035, "s": 4195, "text": "(* using list literals *)\nlet list1 = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]\nprintfn \"The list: %A\" list1\n\n(*using cons operator *)\nlet list2 = 1 :: 2 :: 3 :: []\nprintfn \"The list: %A\" list2\n\n(* using range constructs*)\nlet list3 = [1 .. 10]\nprintfn \"The list: %A\" list3\n\n(* using range constructs *)\nlet list4 = ['a' .. 'm']\nprintfn \"The list: %A\" list4\n\n(* using init method *)\nlet list5 = List.init 5 (fun index -> (index, index * index, index * index * index))\nprintfn \"The list: %A\" list5\n\n(* using yield operator *)\nlet list6 = [ for a in 1 .. 10 do yield (a * a) ]\nprintfn \"The list: %A\" list6\n\n(* using yield operator *)\nlet list7 = [ for a in 1 .. 100 do if a % 3 = 0 && a % 5 = 0 then yield a]\nprintfn \"The list: %A\" list7\n\n(* using yield! operator *)\nlet list8 = [for a in 1 .. 3 do yield! [ a .. a + 3 ] ]\nprintfn \"The list: %A\" list8" }, { "code": null, "e": 5110, "s": 5035, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 5491, "s": 5110, "text": "The list: [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]\nThe list: [1; 2; 3]\nThe list: [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]\nThe list: ['a'; 'b'; 'c'; 'd'; 'e'; 'f'; 'g'; 'h'; 'i'; 'j'; 'k'; 'l'; 'm']\nThe list: [(0, 0, 0); (1, 1, 1); (2, 4, 8); (3, 9, 27); (4, 16, 64)]\nThe list: [1; 4; 9; 16; 25; 36; 49; 64; 81; 100]\nThe list: [15; 30; 45; 60; 75; 90]\nThe list: [1; 2; 3; 4; 2; 3; 4; 5; 3; 4; 5; 6]\n" }, { "code": null, "e": 5556, "s": 5491, "text": "The following table shows various properties of list data type −" }, { "code": null, "e": 5614, "s": 5556, "text": "The following example shows the use of these properties −" }, { "code": null, "e": 5965, "s": 5614, "text": "let list1 = [ 2; 4; 6; 8; 10; 12; 14; 16 ]\n\n// Use of Properties\nprintfn \"list1.IsEmpty is %b\" (list1.IsEmpty)\nprintfn \"list1.Length is %d\" (list1.Length)\nprintfn \"list1.Head is %d\" (list1.Head)\nprintfn \"list1.Tail.Head is %d\" (list1.Tail.Head)\nprintfn \"list1.Tail.Tail.Head is %d\" (list1.Tail.Tail.Head)\nprintfn \"list1.Item(1) is %d\" (list1.Item(1))" }, { "code": null, "e": 6040, "s": 5965, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 6164, "s": 6040, "text": "list1.IsEmpty is false\nlist1.Length is 8\nlist1.Head is 2\nlist1.Tail.Head is 4\nlist1.Tail.Tail.Head is 6\nlist1.Item(1) is 4\n" }, { "code": null, "e": 6231, "s": 6164, "text": "The following table shows the basic operations on list data type −" }, { "code": null, "e": 6306, "s": 6231, "text": "The following examples demonstrate the uses of the above functionalities −" }, { "code": null, "e": 6356, "s": 6306, "text": "This program shows reversing a list recursively −" }, { "code": null, "e": 6607, "s": 6356, "text": "let list1 = [ 2; 4; 6; 8; 10; 12; 14; 16 ]\nprintfn \"The original list: %A\" list1\n\nlet reverse lt =\n let rec loop acc = function\n | [] -> acc\n | hd :: tl -> loop (hd :: acc) tl\n loop [] lt\n\nprintfn \"The reversed list: %A\" (reverse list1)" }, { "code": null, "e": 6682, "s": 6607, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 6779, "s": 6682, "text": "The original list: [2; 4; 6; 8; 10; 12; 14; 16]\nThe reversed list: [16; 14; 12; 10; 8; 6; 4; 2]\n" }, { "code": null, "e": 6854, "s": 6779, "text": "However, you can use the rev function of the module for the same purpose −" }, { "code": null, "e": 6984, "s": 6854, "text": "let list1 = [ 2; 4; 6; 8; 10; 12; 14; 16 ]\nprintfn \"The original list: %A\" list1\nprintfn \"The reversed list: %A\" (List.rev list1)" }, { "code": null, "e": 7059, "s": 6984, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 7156, "s": 7059, "text": "The original list: [2; 4; 6; 8; 10; 12; 14; 16]\nThe reversed list: [16; 14; 12; 10; 8; 6; 4; 2]\n" }, { "code": null, "e": 7223, "s": 7156, "text": "This program shows filtering a list using the List.filter method −" }, { "code": null, "e": 7390, "s": 7223, "text": "let list1 = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]\nprintfn \"The list: %A\" list1\nlet list2 = list1 |> List.filter (fun x -> x % 2 = 0);;\nprintfn \"The Filtered list: %A\" list2" }, { "code": null, "e": 7465, "s": 7390, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 7544, "s": 7465, "text": "The list: [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]\nThe Filtered list: [2; 4; 6; 8; 10]\n" }, { "code": null, "e": 7603, "s": 7544, "text": "The List.map method maps a list from one type to another −" }, { "code": null, "e": 7774, "s": 7603, "text": "let list1 = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]\nprintfn \"The list: %A\" list1\nlet list2 = list1 |> List.map (fun x -> (x * x).ToString());;\nprintfn \"The Mapped list: %A\" list2" }, { "code": null, "e": 7849, "s": 7774, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 7968, "s": 7849, "text": "The list: [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]\nThe Mapped list: [\"1\"; \"4\"; \"9\"; \"16\"; \"25\"; \"36\"; \"49\"; \"64\"; \"81\"; \"100\"]\n" }, { "code": null, "e": 8040, "s": 7968, "text": "The List.append method and the @ operator appends one list to another −" }, { "code": null, "e": 8419, "s": 8040, "text": "let list1 = [1; 2; 3; 4; 5 ]\nlet list2 = [6; 7; 8; 9; 10]\nlet list3 = List.append list1 list2\n\nprintfn \"The first list: %A\" list1\nprintfn \"The second list: %A\" list2\nprintfn \"The appened list: %A\" list3\n\nlet lt1 = ['a'; 'b';'c' ]\nlet lt2 = ['e'; 'f';'g' ]\nlet lt3 = lt1 @ lt2\n\nprintfn \"The first list: %A\" lt1\nprintfn \"The second list: %A\" lt2\nprintfn \"The appened list: %A\" lt3" }, { "code": null, "e": 8494, "s": 8419, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 8725, "s": 8494, "text": "The first list: [1; 2; 3; 4; 5]\nThe second list: [6; 7; 8; 9; 10]\nThe appened list: [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]\nThe first list: ['a'; 'b'; 'c']\nThe second list: ['e'; 'f'; 'g']\nThe appened list: ['a'; 'b'; 'c'; 'e'; 'f'; 'g']\n" }, { "code": null, "e": 8890, "s": 8725, "text": "The List.sort method sorts a list. The List.sum method gives the sum of elements in the list and the List.average method gives the average of elements in the list −" }, { "code": null, "e": 9143, "s": 8890, "text": "let list1 = [9.0; 0.0; 2.0; -4.5; 11.2; 8.0; -10.0]\nprintfn \"The list: %A\" list1\n\nlet list2 = List.sort list1\nprintfn \"The sorted list: %A\" list2\n\nlet s = List.sum list1\nlet avg = List.average list1\nprintfn \"The sum: %f\" s\nprintfn \"The average: %f\" avg" }, { "code": null, "e": 9218, "s": 9143, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 9367, "s": 9218, "text": "The list: [9.0; 0.0; 2.0; -4.5; 11.2; 8.0; -10.0]\nThe sorted list: [-10.0; -4.5; 0.0; 2.0; 8.0; 9.0; 11.2]\nThe sum: 15.700000\nThe average: 2.242857\n" }, { "code": null, "e": 9563, "s": 9367, "text": "A \"fold\" operation applies a function to each element in a list, aggregates the result of the function in an accumulator variable, and returns the accumulator as the result of the fold operation." }, { "code": null, "e": 9714, "s": 9563, "text": "The List.fold method applies a function to each element from left to right, while List.foldBack applies a function to each element from right to left." }, { "code": null, "e": 9861, "s": 9714, "text": "let sumList list = List.fold (fun acc elem -> acc + elem) 0 list\nprintfn \"Sum of the elements of list %A is %d.\" [ 1 .. 10 ] (sumList [ 1 .. 10 ])" }, { "code": null, "e": 9936, "s": 9861, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 10004, "s": 9936, "text": "Sum of the elements of list [1; 2; 3; 4; 5; 6; 7; 8; 9; 10] is 55.\n" }, { "code": null, "e": 10011, "s": 10004, "text": " Print" }, { "code": null, "e": 10022, "s": 10011, "text": " Add Notes" } ]
HTML | <col> align Attribute
18 Feb, 2022 The HTML <col> align Attribute is used to set the horizontal alignment of text content inside the col element. It is not supported by HTML 5. Syntax: <col align="left | right | center | justify | char"> Attribute Values: left: It sets the text left-align. right: It sets the text right-align. center: It sets the text center-align. justify: It stretches the text of paragraph to set the width of all lines equal. char: It sets the text-align to a specific character. Example: <!DOCTYPE html><html> <head> <title> HTML col align Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2> HTML col align Attribute </h2> <table width="500" border="1"> <col align="center"> <tr> <th>Name</th> <th>Expenses</th> </tr> <tr> <td>BITTU</td> <td>2500.00</td> </tr> <tr> <td>RAKESH</td> <td>1400.00</td> </tr> </table></body> </html> Output: Supported Browsers: The browser supported by HTML <col> align attribute are listed below: Google Chrome: Not Supported Internet Explorer: Not Supported Firefox: Not Supported Safari: Not Supported Opera: Not Supported chhabradhanvi HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) CSS to put icon inside an input element in a form Design a Tribute Page using HTML & CSS Types of CSS (Cascading Style Sheet) How to Insert Form Data into Database using PHP ? Installation of Node.js on Linux 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
[ { "code": null, "e": 53, "s": 25, "text": "\n18 Feb, 2022" }, { "code": null, "e": 195, "s": 53, "text": "The HTML <col> align Attribute is used to set the horizontal alignment of text content inside the col element. It is not supported by HTML 5." }, { "code": null, "e": 203, "s": 195, "text": "Syntax:" }, { "code": null, "e": 256, "s": 203, "text": "<col align=\"left | right | center | justify | char\">" }, { "code": null, "e": 274, "s": 256, "text": "Attribute Values:" }, { "code": null, "e": 309, "s": 274, "text": "left: It sets the text left-align." }, { "code": null, "e": 346, "s": 309, "text": "right: It sets the text right-align." }, { "code": null, "e": 385, "s": 346, "text": "center: It sets the text center-align." }, { "code": null, "e": 466, "s": 385, "text": "justify: It stretches the text of paragraph to set the width of all lines equal." }, { "code": null, "e": 520, "s": 466, "text": "char: It sets the text-align to a specific character." }, { "code": null, "e": 529, "s": 520, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML col align Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2> HTML col align Attribute </h2> <table width=\"500\" border=\"1\"> <col align=\"center\"> <tr> <th>Name</th> <th>Expenses</th> </tr> <tr> <td>BITTU</td> <td>2500.00</td> </tr> <tr> <td>RAKESH</td> <td>1400.00</td> </tr> </table></body> </html>", "e": 1130, "s": 529, "text": null }, { "code": null, "e": 1138, "s": 1130, "text": "Output:" }, { "code": null, "e": 1228, "s": 1138, "text": "Supported Browsers: The browser supported by HTML <col> align attribute are listed below:" }, { "code": null, "e": 1257, "s": 1228, "text": "Google Chrome: Not Supported" }, { "code": null, "e": 1290, "s": 1257, "text": "Internet Explorer: Not Supported" }, { "code": null, "e": 1313, "s": 1290, "text": "Firefox: Not Supported" }, { "code": null, "e": 1335, "s": 1313, "text": "Safari: Not Supported" }, { "code": null, "e": 1356, "s": 1335, "text": "Opera: Not Supported" }, { "code": null, "e": 1370, "s": 1356, "text": "chhabradhanvi" }, { "code": null, "e": 1386, "s": 1370, "text": "HTML-Attributes" }, { "code": null, "e": 1391, "s": 1386, "text": "HTML" }, { "code": null, "e": 1408, "s": 1391, "text": "Web Technologies" }, { "code": null, "e": 1413, "s": 1408, "text": "HTML" }, { "code": null, "e": 1511, "s": 1413, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1535, "s": 1511, "text": "REST API (Introduction)" }, { "code": null, "e": 1585, "s": 1535, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 1624, "s": 1585, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 1661, "s": 1624, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 1711, "s": 1661, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 1744, "s": 1711, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1805, "s": 1744, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1848, "s": 1805, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 1920, "s": 1848, "text": "Differences between Functional Components and Class Components in React" } ]
How to change the permission of a file using Python?
To change the permission of a file, you can use the os.chmod(file, mode) call. Note that the mode should be specified in octal representation and therefore must begin with a 0o. For example, to make a file readonly, you can set the permission to 0o777, you can use: >>> import os >>> os.chmod('my_file', 0o777) You can also use flags from the stat module. You can read more about these flags here: http://docs.python.org/2/library/stat.html Another way to acheive it is using a subprocess call: >>> import subprocess >>> subprocess.call(['chmod', '0444', 'my_file'])
[ { "code": null, "e": 1453, "s": 1187, "text": "To change the permission of a file, you can use the os.chmod(file, mode) call. Note that the mode should be specified in octal representation and therefore must begin with a 0o. For example, to make a file readonly, you can set the permission to 0o777, you can use:" }, { "code": null, "e": 1498, "s": 1453, "text": ">>> import os\n>>> os.chmod('my_file', 0o777)" }, { "code": null, "e": 1628, "s": 1498, "text": "You can also use flags from the stat module. You can read more about these flags here: http://docs.python.org/2/library/stat.html" }, { "code": null, "e": 1682, "s": 1628, "text": "Another way to acheive it is using a subprocess call:" }, { "code": null, "e": 1754, "s": 1682, "text": ">>> import subprocess\n>>> subprocess.call(['chmod', '0444', 'my_file'])" } ]
How To Customize Border in facet plot in ggplot2 in R
05 Nov, 2021 In this article, we will discuss how to customize the border in the facet plot in ggplot2 in R Programming language. Facet plots, where one subsets the data based on a categorical variable and makes a series of similar plots with the same scale. Facetting helps us to show the relationship between more than two categories of data. When we have multiple variables, with faceting it can be plotted in a single plot into smaller plots. We can easily plot a facetted plot using the facet_wrap() function of the ggplot2 package. When we use facet_wrap() in ggplot2, by default it gives a title in a grey box. Syntax: plot + facet_wrap( ~facet-variable) Where: facet-variable: determines the variable around which plots have to be divided. Here, is a basic facet plot made using the diamonds data frame which is provided by R Language natively. We have used the facet_wrap() function with ~cut to divide the plot into facets according to their clarity. R # load library tidyverselibrary(tidyverse) # set theme_bw()theme_set(theme_bw(18)) # Basic facet plot divided according to category # clarity diamonds data frame is used in plot which# is provided natively by R Language# ggplot() function is used to plot the chartggplot(diamonds, aes(x="price")) + # geom_bar function is used to create bar plot geom_bar()+ # facet_wrap() function divides the plot in# facets according to category of clarity facet_wrap(~clarity) Output: To remove the space between panels we use panel.spacing.x / panel.spacing.y argument of theme() function. We can even manually specify the amount of space needed between the panels using this method. Syntax: plot + theme( panel.spacing.x / panel.spacing.y ) Example: Here, we have used the diamonds dataset to create a faceted bar plot and removed space between panels by using panel.spacing.x and panel.spacing.y argument of theme() function. R # load library tidyverselibrary(tidyverse) # set theme_bw()theme_set(theme_bw(18)) # Basic facet plot divided according to category clarity# diamonds data frame is used in plot which# is provided natively by R Language# ggplot() function is used to plot the chartggplot(diamonds, aes(x="price")) + # geom_bar function is used to create bar plot geom_bar()+ # facet_wrap() function divides the plot in# facets according to category of clarity facet_wrap(~clarity)+ # theme function with panel.spacing argument# is used to modify space between panelstheme( panel.spacing.x = unit(0,"line"), panel.spacing.y = unit(0,"line")) Output: To remove the Panel Border Lines, we use panel.border argument of theme() function. we use element.blank() function as parameter for panel.border argument to remove the border. Syntax: plot + theme( panel.border = element_blank() ) Example: Here, we have used the diamonds dataset to create a faceted bar plot and removed panel borders by using panel.border aselement_blank() in theme() function. R # load library tidyverselibrary(tidyverse) # set theme_bw()theme_set(theme_bw(18)) # Basic facet plot divided according to category clarity# diamonds data frame is used in plot which# is provided natively by R Language# ggplot() function is used to plot the chartggplot(diamonds, aes(x="price")) + # geom_bar function is used to create bar plot geom_bar()+ # facet_wrap() function divides the plot in# facets according to category of clarity facet_wrap(~clarity)+ # theme function with panel.border is# used to remove border of facet panelstheme( panel.border = element_blank() ) Output: Picked R-ggplot R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? R - if statement Logistic Regression in R Programming Replace Specific Characters in String in R How to import an Excel File into R ? Joining of Dataframes in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Nov, 2021" }, { "code": null, "e": 145, "s": 28, "text": "In this article, we will discuss how to customize the border in the facet plot in ggplot2 in R Programming language." }, { "code": null, "e": 462, "s": 145, "text": "Facet plots, where one subsets the data based on a categorical variable and makes a series of similar plots with the same scale. Facetting helps us to show the relationship between more than two categories of data. When we have multiple variables, with faceting it can be plotted in a single plot into smaller plots." }, { "code": null, "e": 633, "s": 462, "text": "We can easily plot a facetted plot using the facet_wrap() function of the ggplot2 package. When we use facet_wrap() in ggplot2, by default it gives a title in a grey box." }, { "code": null, "e": 677, "s": 633, "text": "Syntax: plot + facet_wrap( ~facet-variable)" }, { "code": null, "e": 684, "s": 677, "text": "Where:" }, { "code": null, "e": 763, "s": 684, "text": "facet-variable: determines the variable around which plots have to be divided." }, { "code": null, "e": 976, "s": 763, "text": "Here, is a basic facet plot made using the diamonds data frame which is provided by R Language natively. We have used the facet_wrap() function with ~cut to divide the plot into facets according to their clarity." }, { "code": null, "e": 978, "s": 976, "text": "R" }, { "code": "# load library tidyverselibrary(tidyverse) # set theme_bw()theme_set(theme_bw(18)) # Basic facet plot divided according to category # clarity diamonds data frame is used in plot which# is provided natively by R Language# ggplot() function is used to plot the chartggplot(diamonds, aes(x=\"price\")) + # geom_bar function is used to create bar plot geom_bar()+ # facet_wrap() function divides the plot in# facets according to category of clarity facet_wrap(~clarity)", "e": 1448, "s": 978, "text": null }, { "code": null, "e": 1456, "s": 1448, "text": "Output:" }, { "code": null, "e": 1656, "s": 1456, "text": "To remove the space between panels we use panel.spacing.x / panel.spacing.y argument of theme() function. We can even manually specify the amount of space needed between the panels using this method." }, { "code": null, "e": 1714, "s": 1656, "text": "Syntax: plot + theme( panel.spacing.x / panel.spacing.y )" }, { "code": null, "e": 1723, "s": 1714, "text": "Example:" }, { "code": null, "e": 1900, "s": 1723, "text": "Here, we have used the diamonds dataset to create a faceted bar plot and removed space between panels by using panel.spacing.x and panel.spacing.y argument of theme() function." }, { "code": null, "e": 1902, "s": 1900, "text": "R" }, { "code": "# load library tidyverselibrary(tidyverse) # set theme_bw()theme_set(theme_bw(18)) # Basic facet plot divided according to category clarity# diamonds data frame is used in plot which# is provided natively by R Language# ggplot() function is used to plot the chartggplot(diamonds, aes(x=\"price\")) + # geom_bar function is used to create bar plot geom_bar()+ # facet_wrap() function divides the plot in# facets according to category of clarity facet_wrap(~clarity)+ # theme function with panel.spacing argument# is used to modify space between panelstheme( panel.spacing.x = unit(0,\"line\"), panel.spacing.y = unit(0,\"line\"))", "e": 2539, "s": 1902, "text": null }, { "code": null, "e": 2547, "s": 2539, "text": "Output:" }, { "code": null, "e": 2724, "s": 2547, "text": "To remove the Panel Border Lines, we use panel.border argument of theme() function. we use element.blank() function as parameter for panel.border argument to remove the border." }, { "code": null, "e": 2779, "s": 2724, "text": "Syntax: plot + theme( panel.border = element_blank() )" }, { "code": null, "e": 2788, "s": 2779, "text": "Example:" }, { "code": null, "e": 2944, "s": 2788, "text": "Here, we have used the diamonds dataset to create a faceted bar plot and removed panel borders by using panel.border aselement_blank() in theme() function." }, { "code": null, "e": 2946, "s": 2944, "text": "R" }, { "code": "# load library tidyverselibrary(tidyverse) # set theme_bw()theme_set(theme_bw(18)) # Basic facet plot divided according to category clarity# diamonds data frame is used in plot which# is provided natively by R Language# ggplot() function is used to plot the chartggplot(diamonds, aes(x=\"price\")) + # geom_bar function is used to create bar plot geom_bar()+ # facet_wrap() function divides the plot in# facets according to category of clarity facet_wrap(~clarity)+ # theme function with panel.border is# used to remove border of facet panelstheme( panel.border = element_blank() )", "e": 3533, "s": 2946, "text": null }, { "code": null, "e": 3541, "s": 3533, "text": "Output:" }, { "code": null, "e": 3548, "s": 3541, "text": "Picked" }, { "code": null, "e": 3557, "s": 3548, "text": "R-ggplot" }, { "code": null, "e": 3568, "s": 3557, "text": "R Language" }, { "code": null, "e": 3666, "s": 3568, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3718, "s": 3666, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 3776, "s": 3718, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 3811, "s": 3776, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 3849, "s": 3811, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 3898, "s": 3849, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 3915, "s": 3898, "text": "R - if statement" }, { "code": null, "e": 3952, "s": 3915, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 3995, "s": 3952, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 4032, "s": 3995, "text": "How to import an Excel File into R ?" } ]
Create a matrix with alternating rectangles of O and X
23 Jun, 2022 Write a code which inputs two numbers m and n and creates a matrix of size m x n (m rows and n columns) in which every elements is either X or 0. The Xs and 0s must be filled alternatively, the matrix should have outermost rectangle of Xs, then a rectangle of 0s, then a rectangle of Xs, and so on. Examples: Input: m = 3, n = 3 Output: Following matrix X X X X 0 X X X X Input: m = 4, n = 5 Output: Following matrix X X X X X X 0 0 0 X X 0 0 0 X X X X X X Input: m = 5, n = 5 Output: Following matrix X X X X X X 0 0 0 X X 0 X 0 X X 0 0 0 X X X X X X Input: m = 6, n = 7 Output: Following matrix X X X X X X X X 0 0 0 0 0 X X 0 X X X 0 X X 0 X X X 0 X X 0 0 0 0 0 X X X X X X X X We strongly recommend to minimize the browser and try this yourself first. This question was asked in campus recruitment of Shreepartners Gurgaon. I followed the following approach. Use the code for Printing Matrix in Spiral form. Instead of printing the array, inserted the element ‘X’ or ‘0’ alternatively in the array. Use the code for Printing Matrix in Spiral form. Instead of printing the array, inserted the element ‘X’ or ‘0’ alternatively in the array. Following is implementation of the above approach. C++ C Java Python3 C# PHP Javascript #include <bits/stdc++.h>using namespace std; // Function to print alternating rectangles of 0 and Xvoid fill0X(int m, int n){ /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ int i, k = 0, l = 0; // Store given number of rows and columns for later use int r = m, c = n; // A 2D array to store the output to be printed char a[m][n]; char x = 'X'; // Initialize the character to be stored in a[][] // Fill characters in a[][] in spiral form. Every iteration fills // one rectangle of either Xs or Os while (k < m && l < n) { /* Fill the first row from the remaining rows */ for (i = l; i < n; ++i) a[k][i] = x; k++; /* Fill the last column from the remaining columns */ for (i = k; i < m; ++i) a[i][n-1] = x; n--; /* Fill the last row from the remaining rows */ if (k < m) { for (i = n-1; i >= l; --i) a[m-1][i] = x; m--; } /* Print the first column from the remaining columns */ if (l < n) { for (i = m-1; i >= k; --i) a[i][l] = x; l++; } // Flip character for next iteration x = (x == '0')? 'X': '0'; } // Print the filled matrix for (i = 0; i < r; i++) { for (int j = 0; j < c; j++) cout <<" "<< a[i][j]; cout <<"\n"; }} /* Driver program to test above functions */int main(){ puts("Output for m = 5, n = 6"); fill0X(5, 6); puts("\nOutput for m = 4, n = 4"); fill0X(4, 4); puts("\nOutput for m = 3, n = 4"); fill0X(3, 4); return 0;} // This code is contributed by shivanisinghss2110 #include <stdio.h> // Function to print alternating rectangles of 0 and Xvoid fill0X(int m, int n){ /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ int i, k = 0, l = 0; // Store given number of rows and columns for later use int r = m, c = n; // A 2D array to store the output to be printed char a[m][n]; char x = 'X'; // Initialize the character to be stored in a[][] // Fill characters in a[][] in spiral form. Every iteration fills // one rectangle of either Xs or Os while (k < m && l < n) { /* Fill the first row from the remaining rows */ for (i = l; i < n; ++i) a[k][i] = x; k++; /* Fill the last column from the remaining columns */ for (i = k; i < m; ++i) a[i][n-1] = x; n--; /* Fill the last row from the remaining rows */ if (k < m) { for (i = n-1; i >= l; --i) a[m-1][i] = x; m--; } /* Print the first column from the remaining columns */ if (l < n) { for (i = m-1; i >= k; --i) a[i][l] = x; l++; } // Flip character for next iteration x = (x == '0')? 'X': '0'; } // Print the filled matrix for (i = 0; i < r; i++) { for (int j = 0; j < c; j++) printf("%c ", a[i][j]); printf("\n"); }} /* Driver program to test above functions */int main(){ puts("Output for m = 5, n = 6"); fill0X(5, 6); puts("\nOutput for m = 4, n = 4"); fill0X(4, 4); puts("\nOutput for m = 3, n = 4"); fill0X(3, 4); return 0;} // Java code to demonstrate the working. import java.io.*; class GFG { // Function to print alternating// rectangles of 0 and X static void fill0X(int m, int n){ /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ int i, k = 0, l = 0; // Store given number of rows // and columns for later use int r = m, c = n; // A 2D array to store // the output to be printed char a[][] = new char[m][n]; // Initialize the character // to be stored in a[][] char x = 'X'; // Fill characters in a[][] in spiral // form. Every iteration fills // one rectangle of either Xs or Os while (k < m && l < n) { /* Fill the first row from the remaining rows */ for (i = l; i < n; ++i) a[k][i] = x; k++; /* Fill the last column from the remaining columns */ for (i = k; i < m; ++i) a[i][n-1] = x; n--; /* Fill the last row from the remaining rows */ if (k < m) { for (i = n-1; i >= l; --i) a[m-1][i] = x; m--; } /* Print the first column // from the remaining columns */ if (l < n) { for (i = m-1; i >= k; --i) a[i][l] = x; l++; } // Flip character for next iteration x = (x == '0')? 'X': '0'; } // Print the filled matrix for (i = 0; i < r; i++) { for (int j = 0; j < c; j++) System.out.print(a[i][j] + " "); System.out.println(); }} /* Driver program to test above functions */public static void main (String[] args) { System.out.println("Output for m = 5, n = 6"); fill0X(5, 6); System.out.println("Output for m = 4, n = 4"); fill0X(4, 4); System.out.println("Output for m = 3, n = 4"); fill0X(3, 4); }} // This code is contributed by vt_m # Python3 program to Create a matrix with# alternating rectangles of O and X # Function to print alternating rectangles# of 0 and Xdef fill0X(m, n): # k - starting row index # m - ending row index # l - starting column index # n - ending column index # i - iterator i, k, l = 0, 0, 0 # Store given number of rows and # columns for later use r = m c = n # A 2D array to store the output # to be printed a = [[None] * n for i in range(m)] x = 'X' # Initialize the character to # be stored in a[][] # Fill characters in a[][] in spiral form. # Every iteration fills one rectangle of # either Xs or Os while k < m and l < n: # Fill the first row from the # remaining rows for i in range(l, n): a[k][i] = x k += 1 # Fill the last column from # the remaining columns for i in range(k, m): a[i][n - 1] = x n -= 1 # Fill the last row from the # remaining rows if k < m: for i in range(n - 1, l - 1, -1): a[m - 1][i] = x m -= 1 # Print the first column from # the remaining columns if l < n: for i in range(m - 1, k - 1, -1): a[i][l] = x l += 1 # Flip character for next iteration x = 'X' if x == '0' else '0' # Print the filled matrix for i in range(r): for j in range(c): print(a[i][j], end = " ") print() # Driver Codeif __name__ == '__main__': print("Output for m = 5, n = 6") fill0X(5, 6) print("Output for m = 4, n = 4") fill0X(4, 4) print("Output for m = 3, n = 4") fill0X(3, 4) # This code is contributed by pranchalK // C# code to demonstrate the working.using System; class GFG { // Function to print alternating // rectangles of 0 and X static void fill0X(int m, int n) { /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ int i, k = 0, l = 0; // Store given number of rows // and columns for later use int r = m, c = n; // A 2D array to store // the output to be printed char [,]a = new char[m,n]; // Initialize the character // to be stored in a[][] char x = 'X'; // Fill characters in a[][] in spiral // form. Every iteration fills // one rectangle of either Xs or Os while (k < m && l < n) { /* Fill the first row from the remaining rows */ for (i = l; i < n; ++i) a[k,i] = x; k++; /* Fill the last column from the remaining columns */ for (i = k; i < m; ++i) a[i,n-1] = x; n--; /* Fill the last row from the remaining rows */ if (k < m) { for (i = n-1; i >= l; --i) a[m-1,i] = x; m--; } /* Print the first column from the remaining columns */ if (l < n) { for (i = m-1; i >= k; --i) a[i,l] = x; l++; } // Flip character for next // iteration x = (x == '0')? 'X': '0'; } // Print the filled matrix for (i = 0; i < r; i++) { for (int j = 0; j < c; j++) Console.Write(a[i,j] + " "); Console.WriteLine(); } } /* Driver program to test above functions */ public static void Main () { Console.WriteLine("Output for" + " m = 5, n = 6"); fill0X(5, 6); Console.WriteLine("Output for" + " m = 4, n = 4"); fill0X(4, 4); Console.WriteLine("Output for" + " m = 3, n = 4"); fill0X(3, 4); }} // This code is contributed by Sam007. <?php// PHP program to Create a matrix with// alternating rectangles of O and X // Function to print alternating// rectangles of 0 and Xfunction fill0X($m, $n){ /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ $k = 0; $l = 0; // Store given number of rows // and columns for later use $r = $m; $c = $n; // A 2D array to store the // output to be printed // Initialize the character // to be stored in a[][] $x = 'X'; // Fill characters in a[][] in // spiral form. Every iteration fills // one rectangle of either Xs or Os while ($k < $m && $l < $n) { /* Fill the first row from the remaining rows */ for ($i = $l; $i < $n; ++$i) $a[$k][$i] = $x; $k++; /* Fill the last column from the remaining columns */ for ($i = $k; $i < $m; ++$i) $a[$i][$n - 1] = $x; $n--; /* Fill the last row from the remaining rows */ if ($k < $m) { for ($i = $n - 1; $i >= $l; --$i) $a[$m - 1][$i] = $x; $m--; } /* Print the first column from the remaining columns */ if ($l < $n) { for ($i = $m - 1; $i >= $k; --$i) $a[$i][$l] = $x; $l++; } // Flip character for // next iteration $x = ($x == '0')? 'X': '0'; } // Print the filled matrix for ($i = 0; $i < $r; $i++) { for ($j = 0; $j < $c; $j++) echo($a[$i][$j]." "); echo "\n"; }} // Driver Codeecho "Output for m = 5, n = 6\n";fill0X(5, 6); echo "\nOutput for m = 4, n = 4\n";fill0X(4, 4); echo "\nOutput for m = 3, n = 4\n";fill0X(3, 4); // This code is contributed by ChitraNayal.?> <script> // JavaScript code to demonstrate the working. // Function to print alternating// rectangles of 0 and Xfunction fill0X(m, n){ /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ let i, k = 0, l = 0; // Store given number of rows // and columns for later use let r = m, c = n; // A 2D array to store // the output to be printed let a = new Array(m); for(let i = 0; i < m; i++) { a[i] = new Array(n); } // Initialize the character // to be stored in a[][] let x = 'X'; // Fill characters in a[][] in spiral // form. Every iteration fills // one rectangle of either Xs or Os while (k < m && l < n) { // Fill the first row from the // remaining rows for(i = l; i < n; ++i) { a[k][i] = x; } k++; // Fill the last column from the // remaining columns for(i = k; i < m; ++i) { a[i][n - 1] = x; } n--; // Fill the last row from the // remaining rows if (k < m) { for(i = n - 1; i >= l; --i) a[m - 1][i] = x; m--; } // Print the first column // from the remaining columns if (l < n) { for(i = m - 1; i >= k; --i) { a[i][l] = x; } l++; } // Flip character for next iteration x = (x == '0') ? 'X' : '0'; } // Print the filled matrix for(i = 0; i < r; i++) { for(let j = 0; j < c; j++) { document.write(a[i][j] + " "); } document.write("<br>"); }} // Driver Codedocument.write("Output for m = 5, n = 6 <br>");fill0X(5, 6); document.write("Output for m = 4, n = 4<br>");fill0X(4, 4); document.write("Output for m = 3, n = 4<br>");fill0X(3, 4); // This code is contributed by rag2127 </script> Output for m = 5, n = 6 X X X X X X X 0 0 0 0 X X 0 X X 0 X X 0 0 0 0 X X X X X X X Output for m = 4, n = 4 X X X X X 0 0 X X 0 0 X X X X X Output for m = 3, n = 4 X X X X X 0 0 X X X X X Time Complexity: O(mn) Auxiliary Space: O(mn) Sam007 ukasp PranchalKatiyar rag2127 simranarora5sos shivanisinghss2110 hardikkoriintern square-rectangle Matrix Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Unique paths in a Grid with Obstacles Traverse a given Matrix using Recursion Find median in row wise sorted matrix Zigzag (or diagonal) traversal of Matrix A Boolean Matrix Question Python program to add two Matrices Find a specific pair in Matrix Common elements in all rows of a given matrix Find shortest safe route in a path with landmines Flood fill Algorithm - how to implement fill() in paint?
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Jun, 2022" }, { "code": null, "e": 353, "s": 54, "text": "Write a code which inputs two numbers m and n and creates a matrix of size m x n (m rows and n columns) in which every elements is either X or 0. The Xs and 0s must be filled alternatively, the matrix should have outermost rectangle of Xs, then a rectangle of 0s, then a rectangle of Xs, and so on." }, { "code": null, "e": 365, "s": 353, "text": "Examples: " }, { "code": null, "e": 744, "s": 365, "text": "Input: m = 3, n = 3\nOutput: Following matrix \nX X X\nX 0 X\nX X X\n\nInput: m = 4, n = 5\nOutput: Following matrix\nX X X X X\nX 0 0 0 X\nX 0 0 0 X\nX X X X X\n\nInput: m = 5, n = 5\nOutput: Following matrix\nX X X X X\nX 0 0 0 X\nX 0 X 0 X\nX 0 0 0 X\nX X X X X\n\nInput: m = 6, n = 7\nOutput: Following matrix\nX X X X X X X\nX 0 0 0 0 0 X\nX 0 X X X 0 X\nX 0 X X X 0 X\nX 0 0 0 0 0 X\nX X X X X X X " }, { "code": null, "e": 819, "s": 744, "text": "We strongly recommend to minimize the browser and try this yourself first." }, { "code": null, "e": 926, "s": 819, "text": "This question was asked in campus recruitment of Shreepartners Gurgaon. I followed the following approach." }, { "code": null, "e": 1066, "s": 926, "text": "Use the code for Printing Matrix in Spiral form. Instead of printing the array, inserted the element ‘X’ or ‘0’ alternatively in the array." }, { "code": null, "e": 1116, "s": 1066, "text": "Use the code for Printing Matrix in Spiral form. " }, { "code": null, "e": 1207, "s": 1116, "text": "Instead of printing the array, inserted the element ‘X’ or ‘0’ alternatively in the array." }, { "code": null, "e": 1260, "s": 1207, "text": "Following is implementation of the above approach. " }, { "code": null, "e": 1264, "s": 1260, "text": "C++" }, { "code": null, "e": 1266, "s": 1264, "text": "C" }, { "code": null, "e": 1271, "s": 1266, "text": "Java" }, { "code": null, "e": 1279, "s": 1271, "text": "Python3" }, { "code": null, "e": 1282, "s": 1279, "text": "C#" }, { "code": null, "e": 1286, "s": 1282, "text": "PHP" }, { "code": null, "e": 1297, "s": 1286, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; // Function to print alternating rectangles of 0 and Xvoid fill0X(int m, int n){ /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ int i, k = 0, l = 0; // Store given number of rows and columns for later use int r = m, c = n; // A 2D array to store the output to be printed char a[m][n]; char x = 'X'; // Initialize the character to be stored in a[][] // Fill characters in a[][] in spiral form. Every iteration fills // one rectangle of either Xs or Os while (k < m && l < n) { /* Fill the first row from the remaining rows */ for (i = l; i < n; ++i) a[k][i] = x; k++; /* Fill the last column from the remaining columns */ for (i = k; i < m; ++i) a[i][n-1] = x; n--; /* Fill the last row from the remaining rows */ if (k < m) { for (i = n-1; i >= l; --i) a[m-1][i] = x; m--; } /* Print the first column from the remaining columns */ if (l < n) { for (i = m-1; i >= k; --i) a[i][l] = x; l++; } // Flip character for next iteration x = (x == '0')? 'X': '0'; } // Print the filled matrix for (i = 0; i < r; i++) { for (int j = 0; j < c; j++) cout <<\" \"<< a[i][j]; cout <<\"\\n\"; }} /* Driver program to test above functions */int main(){ puts(\"Output for m = 5, n = 6\"); fill0X(5, 6); puts(\"\\nOutput for m = 4, n = 4\"); fill0X(4, 4); puts(\"\\nOutput for m = 3, n = 4\"); fill0X(3, 4); return 0;} // This code is contributed by shivanisinghss2110", "e": 3090, "s": 1297, "text": null }, { "code": "#include <stdio.h> // Function to print alternating rectangles of 0 and Xvoid fill0X(int m, int n){ /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ int i, k = 0, l = 0; // Store given number of rows and columns for later use int r = m, c = n; // A 2D array to store the output to be printed char a[m][n]; char x = 'X'; // Initialize the character to be stored in a[][] // Fill characters in a[][] in spiral form. Every iteration fills // one rectangle of either Xs or Os while (k < m && l < n) { /* Fill the first row from the remaining rows */ for (i = l; i < n; ++i) a[k][i] = x; k++; /* Fill the last column from the remaining columns */ for (i = k; i < m; ++i) a[i][n-1] = x; n--; /* Fill the last row from the remaining rows */ if (k < m) { for (i = n-1; i >= l; --i) a[m-1][i] = x; m--; } /* Print the first column from the remaining columns */ if (l < n) { for (i = m-1; i >= k; --i) a[i][l] = x; l++; } // Flip character for next iteration x = (x == '0')? 'X': '0'; } // Print the filled matrix for (i = 0; i < r; i++) { for (int j = 0; j < c; j++) printf(\"%c \", a[i][j]); printf(\"\\n\"); }} /* Driver program to test above functions */int main(){ puts(\"Output for m = 5, n = 6\"); fill0X(5, 6); puts(\"\\nOutput for m = 4, n = 4\"); fill0X(4, 4); puts(\"\\nOutput for m = 3, n = 4\"); fill0X(3, 4); return 0;}", "e": 4810, "s": 3090, "text": null }, { "code": "// Java code to demonstrate the working. import java.io.*; class GFG { // Function to print alternating// rectangles of 0 and X static void fill0X(int m, int n){ /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ int i, k = 0, l = 0; // Store given number of rows // and columns for later use int r = m, c = n; // A 2D array to store // the output to be printed char a[][] = new char[m][n]; // Initialize the character // to be stored in a[][] char x = 'X'; // Fill characters in a[][] in spiral // form. Every iteration fills // one rectangle of either Xs or Os while (k < m && l < n) { /* Fill the first row from the remaining rows */ for (i = l; i < n; ++i) a[k][i] = x; k++; /* Fill the last column from the remaining columns */ for (i = k; i < m; ++i) a[i][n-1] = x; n--; /* Fill the last row from the remaining rows */ if (k < m) { for (i = n-1; i >= l; --i) a[m-1][i] = x; m--; } /* Print the first column // from the remaining columns */ if (l < n) { for (i = m-1; i >= k; --i) a[i][l] = x; l++; } // Flip character for next iteration x = (x == '0')? 'X': '0'; } // Print the filled matrix for (i = 0; i < r; i++) { for (int j = 0; j < c; j++) System.out.print(a[i][j] + \" \"); System.out.println(); }} /* Driver program to test above functions */public static void main (String[] args) { System.out.println(\"Output for m = 5, n = 6\"); fill0X(5, 6); System.out.println(\"Output for m = 4, n = 4\"); fill0X(4, 4); System.out.println(\"Output for m = 3, n = 4\"); fill0X(3, 4); }} // This code is contributed by vt_m", "e": 6792, "s": 4810, "text": null }, { "code": "# Python3 program to Create a matrix with# alternating rectangles of O and X # Function to print alternating rectangles# of 0 and Xdef fill0X(m, n): # k - starting row index # m - ending row index # l - starting column index # n - ending column index # i - iterator i, k, l = 0, 0, 0 # Store given number of rows and # columns for later use r = m c = n # A 2D array to store the output # to be printed a = [[None] * n for i in range(m)] x = 'X' # Initialize the character to # be stored in a[][] # Fill characters in a[][] in spiral form. # Every iteration fills one rectangle of # either Xs or Os while k < m and l < n: # Fill the first row from the # remaining rows for i in range(l, n): a[k][i] = x k += 1 # Fill the last column from # the remaining columns for i in range(k, m): a[i][n - 1] = x n -= 1 # Fill the last row from the # remaining rows if k < m: for i in range(n - 1, l - 1, -1): a[m - 1][i] = x m -= 1 # Print the first column from # the remaining columns if l < n: for i in range(m - 1, k - 1, -1): a[i][l] = x l += 1 # Flip character for next iteration x = 'X' if x == '0' else '0' # Print the filled matrix for i in range(r): for j in range(c): print(a[i][j], end = \" \") print() # Driver Codeif __name__ == '__main__': print(\"Output for m = 5, n = 6\") fill0X(5, 6) print(\"Output for m = 4, n = 4\") fill0X(4, 4) print(\"Output for m = 3, n = 4\") fill0X(3, 4) # This code is contributed by pranchalK", "e": 8564, "s": 6792, "text": null }, { "code": "// C# code to demonstrate the working.using System; class GFG { // Function to print alternating // rectangles of 0 and X static void fill0X(int m, int n) { /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ int i, k = 0, l = 0; // Store given number of rows // and columns for later use int r = m, c = n; // A 2D array to store // the output to be printed char [,]a = new char[m,n]; // Initialize the character // to be stored in a[][] char x = 'X'; // Fill characters in a[][] in spiral // form. Every iteration fills // one rectangle of either Xs or Os while (k < m && l < n) { /* Fill the first row from the remaining rows */ for (i = l; i < n; ++i) a[k,i] = x; k++; /* Fill the last column from the remaining columns */ for (i = k; i < m; ++i) a[i,n-1] = x; n--; /* Fill the last row from the remaining rows */ if (k < m) { for (i = n-1; i >= l; --i) a[m-1,i] = x; m--; } /* Print the first column from the remaining columns */ if (l < n) { for (i = m-1; i >= k; --i) a[i,l] = x; l++; } // Flip character for next // iteration x = (x == '0')? 'X': '0'; } // Print the filled matrix for (i = 0; i < r; i++) { for (int j = 0; j < c; j++) Console.Write(a[i,j] + \" \"); Console.WriteLine(); } } /* Driver program to test above functions */ public static void Main () { Console.WriteLine(\"Output for\" + \" m = 5, n = 6\"); fill0X(5, 6); Console.WriteLine(\"Output for\" + \" m = 4, n = 4\"); fill0X(4, 4); Console.WriteLine(\"Output for\" + \" m = 3, n = 4\"); fill0X(3, 4); }} // This code is contributed by Sam007.", "e": 10915, "s": 8564, "text": null }, { "code": "<?php// PHP program to Create a matrix with// alternating rectangles of O and X // Function to print alternating// rectangles of 0 and Xfunction fill0X($m, $n){ /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ $k = 0; $l = 0; // Store given number of rows // and columns for later use $r = $m; $c = $n; // A 2D array to store the // output to be printed // Initialize the character // to be stored in a[][] $x = 'X'; // Fill characters in a[][] in // spiral form. Every iteration fills // one rectangle of either Xs or Os while ($k < $m && $l < $n) { /* Fill the first row from the remaining rows */ for ($i = $l; $i < $n; ++$i) $a[$k][$i] = $x; $k++; /* Fill the last column from the remaining columns */ for ($i = $k; $i < $m; ++$i) $a[$i][$n - 1] = $x; $n--; /* Fill the last row from the remaining rows */ if ($k < $m) { for ($i = $n - 1; $i >= $l; --$i) $a[$m - 1][$i] = $x; $m--; } /* Print the first column from the remaining columns */ if ($l < $n) { for ($i = $m - 1; $i >= $k; --$i) $a[$i][$l] = $x; $l++; } // Flip character for // next iteration $x = ($x == '0')? 'X': '0'; } // Print the filled matrix for ($i = 0; $i < $r; $i++) { for ($j = 0; $j < $c; $j++) echo($a[$i][$j].\" \"); echo \"\\n\"; }} // Driver Codeecho \"Output for m = 5, n = 6\\n\";fill0X(5, 6); echo \"\\nOutput for m = 4, n = 4\\n\";fill0X(4, 4); echo \"\\nOutput for m = 3, n = 4\\n\";fill0X(3, 4); // This code is contributed by ChitraNayal.?>", "e": 12789, "s": 10915, "text": null }, { "code": "<script> // JavaScript code to demonstrate the working. // Function to print alternating// rectangles of 0 and Xfunction fill0X(m, n){ /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ let i, k = 0, l = 0; // Store given number of rows // and columns for later use let r = m, c = n; // A 2D array to store // the output to be printed let a = new Array(m); for(let i = 0; i < m; i++) { a[i] = new Array(n); } // Initialize the character // to be stored in a[][] let x = 'X'; // Fill characters in a[][] in spiral // form. Every iteration fills // one rectangle of either Xs or Os while (k < m && l < n) { // Fill the first row from the // remaining rows for(i = l; i < n; ++i) { a[k][i] = x; } k++; // Fill the last column from the // remaining columns for(i = k; i < m; ++i) { a[i][n - 1] = x; } n--; // Fill the last row from the // remaining rows if (k < m) { for(i = n - 1; i >= l; --i) a[m - 1][i] = x; m--; } // Print the first column // from the remaining columns if (l < n) { for(i = m - 1; i >= k; --i) { a[i][l] = x; } l++; } // Flip character for next iteration x = (x == '0') ? 'X' : '0'; } // Print the filled matrix for(i = 0; i < r; i++) { for(let j = 0; j < c; j++) { document.write(a[i][j] + \" \"); } document.write(\"<br>\"); }} // Driver Codedocument.write(\"Output for m = 5, n = 6 <br>\");fill0X(5, 6); document.write(\"Output for m = 4, n = 4<br>\");fill0X(4, 4); document.write(\"Output for m = 3, n = 4<br>\");fill0X(3, 4); // This code is contributed by rag2127 </script>", "e": 14843, "s": 12789, "text": null }, { "code": null, "e": 15045, "s": 14843, "text": "Output for m = 5, n = 6\n X X X X X X\n X 0 0 0 0 X\n X 0 X X 0 X\n X 0 0 0 0 X\n X X X X X X\n\nOutput for m = 4, n = 4\n X X X X\n X 0 0 X\n X 0 0 X\n X X X X\n\nOutput for m = 3, n = 4\n X X X X\n X 0 0 X\n X X X X" }, { "code": null, "e": 15091, "s": 15045, "text": "Time Complexity: O(mn) Auxiliary Space: O(mn)" }, { "code": null, "e": 15098, "s": 15091, "text": "Sam007" }, { "code": null, "e": 15104, "s": 15098, "text": "ukasp" }, { "code": null, "e": 15120, "s": 15104, "text": "PranchalKatiyar" }, { "code": null, "e": 15128, "s": 15120, "text": "rag2127" }, { "code": null, "e": 15144, "s": 15128, "text": "simranarora5sos" }, { "code": null, "e": 15163, "s": 15144, "text": "shivanisinghss2110" }, { "code": null, "e": 15180, "s": 15163, "text": "hardikkoriintern" }, { "code": null, "e": 15197, "s": 15180, "text": "square-rectangle" }, { "code": null, "e": 15204, "s": 15197, "text": "Matrix" }, { "code": null, "e": 15211, "s": 15204, "text": "Matrix" }, { "code": null, "e": 15309, "s": 15211, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 15347, "s": 15309, "text": "Unique paths in a Grid with Obstacles" }, { "code": null, "e": 15387, "s": 15347, "text": "Traverse a given Matrix using Recursion" }, { "code": null, "e": 15425, "s": 15387, "text": "Find median in row wise sorted matrix" }, { "code": null, "e": 15466, "s": 15425, "text": "Zigzag (or diagonal) traversal of Matrix" }, { "code": null, "e": 15492, "s": 15466, "text": "A Boolean Matrix Question" }, { "code": null, "e": 15527, "s": 15492, "text": "Python program to add two Matrices" }, { "code": null, "e": 15558, "s": 15527, "text": "Find a specific pair in Matrix" }, { "code": null, "e": 15604, "s": 15558, "text": "Common elements in all rows of a given matrix" }, { "code": null, "e": 15654, "s": 15604, "text": "Find shortest safe route in a path with landmines" } ]
Java program to count the characters in each word in a given sentence
19 May, 2021 Write a Java program to count the characters in each word in a given sentence?Examples: Input : geeks for geeks Output : geeks->5 for->3 geeks->5 Here first we create an equivalent char array of given String. Now we iterate the char array using for loop. Inside for loop we declare a String with empty implementation. Whenever we found an alphabet we will perform concatenation of that alphabet with the String variable and increment the value of i. Now when i reaches to a space it will come out from the while loop and now String variable has the word which is previous of space. Now we will print the String variable with the length of the String. JAVA class CountCharacterInEachWords { static void count(String str) { // Create an char array of given String char[] ch = str.toCharArray(); for (int i = 0; i < ch.length; i++) { // Declare an String with empty initialization String s = ""; // When the character is not space while (i < ch.length && ch[i] != ' ') { // concat with the declared String s = s + ch[i]; i++; } if (s.length() > 0) System.out.println(s + "->" + s.length()); } } public static void main(String[] args) { String str = "geeks for geeks"; count(str); }} Output: Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. geeks->5 for->3 geeks->5 YouTube<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=2Y5vWkeNjcg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> gabaa406 Java-Strings Java Programs Strings Java-Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Iterate Over the Characters of a String in Java How to Convert Char to String in Java? How to Get Elements By Index from HashSet in Java? Java Program to Write into a File How to Write Data into Excel Sheet using Java? Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 52, "s": 24, "text": "\n19 May, 2021" }, { "code": null, "e": 142, "s": 52, "text": "Write a Java program to count the characters in each word in a given sentence?Examples: " }, { "code": null, "e": 200, "s": 142, "text": "Input : geeks for geeks\nOutput :\ngeeks->5\nfor->3\ngeeks->5" }, { "code": null, "e": 265, "s": 202, "text": "Here first we create an equivalent char array of given String." }, { "code": null, "e": 374, "s": 265, "text": "Now we iterate the char array using for loop. Inside for loop we declare a String with empty implementation." }, { "code": null, "e": 506, "s": 374, "text": "Whenever we found an alphabet we will perform concatenation of that alphabet with the String variable and increment the value of i." }, { "code": null, "e": 638, "s": 506, "text": "Now when i reaches to a space it will come out from the while loop and now String variable has the word which is previous of space." }, { "code": null, "e": 707, "s": 638, "text": "Now we will print the String variable with the length of the String." }, { "code": null, "e": 714, "s": 709, "text": "JAVA" }, { "code": "class CountCharacterInEachWords { static void count(String str) { // Create an char array of given String char[] ch = str.toCharArray(); for (int i = 0; i < ch.length; i++) { // Declare an String with empty initialization String s = \"\"; // When the character is not space while (i < ch.length && ch[i] != ' ') { // concat with the declared String s = s + ch[i]; i++; } if (s.length() > 0) System.out.println(s + \"->\" + s.length()); } } public static void main(String[] args) { String str = \"geeks for geeks\"; count(str); }}", "e": 1439, "s": 714, "text": null }, { "code": null, "e": 1449, "s": 1439, "text": "Output: " }, { "code": null, "e": 1458, "s": 1449, "text": "Chapters" }, { "code": null, "e": 1485, "s": 1458, "text": "descriptions off, selected" }, { "code": null, "e": 1535, "s": 1485, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1558, "s": 1535, "text": "captions off, selected" }, { "code": null, "e": 1566, "s": 1558, "text": "English" }, { "code": null, "e": 1590, "s": 1566, "text": "This is a modal window." }, { "code": null, "e": 1659, "s": 1590, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1681, "s": 1659, "text": "End of dialog window." }, { "code": null, "e": 1706, "s": 1681, "text": "geeks->5\nfor->3\ngeeks->5" }, { "code": null, "e": 2000, "s": 1708, "text": "YouTube<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=2Y5vWkeNjcg\" 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": 2011, "s": 2002, "text": "gabaa406" }, { "code": null, "e": 2024, "s": 2011, "text": "Java-Strings" }, { "code": null, "e": 2038, "s": 2024, "text": "Java Programs" }, { "code": null, "e": 2046, "s": 2038, "text": "Strings" }, { "code": null, "e": 2059, "s": 2046, "text": "Java-Strings" }, { "code": null, "e": 2067, "s": 2059, "text": "Strings" }, { "code": null, "e": 2165, "s": 2067, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2213, "s": 2165, "text": "Iterate Over the Characters of a String in Java" }, { "code": null, "e": 2252, "s": 2213, "text": "How to Convert Char to String in Java?" }, { "code": null, "e": 2303, "s": 2252, "text": "How to Get Elements By Index from HashSet in Java?" }, { "code": null, "e": 2337, "s": 2303, "text": "Java Program to Write into a File" }, { "code": null, "e": 2384, "s": 2337, "text": "How to Write Data into Excel Sheet using Java?" }, { "code": null, "e": 2430, "s": 2384, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 2455, "s": 2430, "text": "Reverse a string in Java" }, { "code": null, "e": 2515, "s": 2455, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 2530, "s": 2515, "text": "C++ Data Types" } ]
Node.js Open Weather Map API for Weather Forecasts
08 Oct, 2021 The Open Weather Map API is very popular as it allows you to request weather forecasts and historical weather data programmatically.Feature of Open Weather Map API: It is easy to get started and easy to use.It is widely used and popular API for Weather Forecasts. It is easy to get started and easy to use. It is widely used and popular API for Weather Forecasts. Installation of request module: You can visit the link to Install Request module. You can install this package by using this command. npm install requestAfter installing request module you can check your request version in command prompt using the command. npm version requestNow go to Open Weather Map website and create an account and get your API KEY.After that, you can create a folder and add a file, for example index.js. To run this file you need to run the following command. You can visit the link to Install Request module. You can install this package by using this command. npm install request After installing request module you can check your request version in command prompt using the command. npm version request Now go to Open Weather Map website and create an account and get your API KEY. After that, you can create a folder and add a file, for example index.js. To run this file you need to run the following command. node index.js Filename: index.js index.js const request = require('request'); var API_KEY = 'your_api_key'; const forecast = function (latitude, longitude) { var url = `http://api.openweathermap.org/data/2.5/weather?` +`lat=${latitude}&lon=${longitude}&appid=${API_KEY}` request({ url: url, json: true }, function (error, response) { if (error) { console.log('Unable to connect to Forecast API'); } else { console.log('It is currently ' + response.body.main.temp + ' degrees out.' ); console.log('The high today is ' + response.body.main.temp_max + ' with a low of ' + response.body.main.temp_min ); console.log('Humidity today is ' + response.body.main.humidity ); } }) } var latitude = 22.7196; // Indore latitude var longitude = 75.8577; // Indore longitude // Function call forecast(latitude, longitude); Steps to run the program: The project structure will look like this: Make sure you have installed request module using following command: npm install requestRun index.js file using below command: node index.js The project structure will look like this: Make sure you have installed request module using following command: npm install request Run index.js file using below command: node index.js So this is how you can use the Open Weather Map API which allows you to request weather forecasts and historical weather data programmatically. mridulmanochagfg Node.js-Misc Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js fs.writeFile() Method How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js Mongoose | findByIdAndUpdate() Function Installation of Node.js on Windows Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Oct, 2021" }, { "code": null, "e": 195, "s": 28, "text": "The Open Weather Map API is very popular as it allows you to request weather forecasts and historical weather data programmatically.Feature of Open Weather Map API: " }, { "code": null, "e": 294, "s": 195, "text": "It is easy to get started and easy to use.It is widely used and popular API for Weather Forecasts." }, { "code": null, "e": 337, "s": 294, "text": "It is easy to get started and easy to use." }, { "code": null, "e": 394, "s": 337, "text": "It is widely used and popular API for Weather Forecasts." }, { "code": null, "e": 428, "s": 394, "text": "Installation of request module: " }, { "code": null, "e": 884, "s": 428, "text": "You can visit the link to Install Request module. You can install this package by using this command. npm install requestAfter installing request module you can check your request version in command prompt using the command. npm version requestNow go to Open Weather Map website and create an account and get your API KEY.After that, you can create a folder and add a file, for example index.js. To run this file you need to run the following command. " }, { "code": null, "e": 988, "s": 884, "text": "You can visit the link to Install Request module. You can install this package by using this command. " }, { "code": null, "e": 1008, "s": 988, "text": "npm install request" }, { "code": null, "e": 1114, "s": 1008, "text": "After installing request module you can check your request version in command prompt using the command. " }, { "code": null, "e": 1134, "s": 1114, "text": "npm version request" }, { "code": null, "e": 1213, "s": 1134, "text": "Now go to Open Weather Map website and create an account and get your API KEY." }, { "code": null, "e": 1345, "s": 1213, "text": "After that, you can create a folder and add a file, for example index.js. To run this file you need to run the following command. " }, { "code": null, "e": 1359, "s": 1345, "text": "node index.js" }, { "code": null, "e": 1380, "s": 1359, "text": "Filename: index.js " }, { "code": null, "e": 1389, "s": 1380, "text": "index.js" }, { "code": "const request = require('request'); var API_KEY = 'your_api_key'; const forecast = function (latitude, longitude) { var url = `http://api.openweathermap.org/data/2.5/weather?` +`lat=${latitude}&lon=${longitude}&appid=${API_KEY}` request({ url: url, json: true }, function (error, response) { if (error) { console.log('Unable to connect to Forecast API'); } else { console.log('It is currently ' + response.body.main.temp + ' degrees out.' ); console.log('The high today is ' + response.body.main.temp_max + ' with a low of ' + response.body.main.temp_min ); console.log('Humidity today is ' + response.body.main.humidity ); } }) } var latitude = 22.7196; // Indore latitude var longitude = 75.8577; // Indore longitude // Function call forecast(latitude, longitude); ", "e": 2397, "s": 1389, "text": null }, { "code": null, "e": 2425, "s": 2397, "text": "Steps to run the program: " }, { "code": null, "e": 2612, "s": 2425, "text": "The project structure will look like this: Make sure you have installed request module using following command: npm install requestRun index.js file using below command: node index.js" }, { "code": null, "e": 2657, "s": 2612, "text": "The project structure will look like this: " }, { "code": null, "e": 2728, "s": 2657, "text": "Make sure you have installed request module using following command: " }, { "code": null, "e": 2748, "s": 2728, "text": "npm install request" }, { "code": null, "e": 2789, "s": 2748, "text": "Run index.js file using below command: " }, { "code": null, "e": 2803, "s": 2789, "text": "node index.js" }, { "code": null, "e": 2948, "s": 2803, "text": "So this is how you can use the Open Weather Map API which allows you to request weather forecasts and historical weather data programmatically. " }, { "code": null, "e": 2965, "s": 2948, "text": "mridulmanochagfg" }, { "code": null, "e": 2978, "s": 2965, "text": "Node.js-Misc" }, { "code": null, "e": 2986, "s": 2978, "text": "Node.js" }, { "code": null, "e": 3003, "s": 2986, "text": "Web Technologies" }, { "code": null, "e": 3101, "s": 3003, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3131, "s": 3101, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 3188, "s": 3131, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 3242, "s": 3188, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 3282, "s": 3242, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 3317, "s": 3282, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 3378, "s": 3317, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3428, "s": 3378, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3471, "s": 3428, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 3543, "s": 3471, "text": "Differences between Functional Components and Class Components in React" } ]
How to measure execution time for a Java method?
In general, the elapsed time is the time from the starting point to ending point of an event. Following are various ways to find elapsed time in Java − The currentTimeMillis() method returns the current time in milliseconds. To find the elapsed time for a method you can get the difference between time values before and after the execution of the desired method. The nanoTime() method returns the current time in nano seconds. To find the elapsed time for a method you can get the difference between time values before and after the execution of the desired method. The now() method of the Instant class returns the current time and the Duration.between() methods returns the difference between the given two time values to get the elapsed time retrieve the time values before and after the execution of the desired method and retrieve the duration using the Duration.between() method. The Apache commons library provides a class known as Stopwatch to it provides the start() stop() and getTime() methods to find the time taken for the execution of a method. Following example demonstrates how to find the execution time of a method using the above mentioned methods − Live Demo import java.time.Duration; import java.time.Instant; import org.apache.commons.lang3.time.StopWatch; public class Example { public void test(){ int num = 0; for(int i=0; i<=50; i++){ num =num+i; System.out.print(num+", "); } } public static void main(String args[]){ Example obj = new Example(); long start1 = System.nanoTime(); obj.test(); long end1 = System.nanoTime(); System.out.println("Elapsed Time in nano seconds: "+ (end1-start1)); long start2 = System.currentTimeMillis(); obj.test(); long end2 = System.currentTimeMillis(); System.out.println("Elapsed Time in milli seconds: "+ (end2-start2)); Instant inst1 = Instant.now(); obj.test(); Instant inst2 = Instant.now(); System.out.println("Elapsed Time: "+ Duration.between(inst1, inst2).toString()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); obj.test(); stopWatch.stop(); System.out.println("Elapsed Time in minutes: "+ stopWatch.getTime()); } } 0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990, 1035, 1081, 1128, 1176, 1225, 1275, Elapsed Time in nano seconds: 1882300 0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990, 1035, 1081, 1128, 1176, 1225, 1275, Elapsed Time in milli seconds: 1 0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990, 1035, 1081, 1128, 1176, 1225, 1275, Elapsed Time: PT0.001S 0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990, 1035, 1081, 1128, 1176, 1225, 1275, Elapsed Time in minutes: 1
[ { "code": null, "e": 1339, "s": 1187, "text": "In general, the elapsed time is the time from the starting point to ending point of an event. Following are various ways to find elapsed time in Java −" }, { "code": null, "e": 1551, "s": 1339, "text": "The currentTimeMillis() method returns the current time in milliseconds. To find the elapsed time for a method you can get the difference between time values before and after the execution of the desired method." }, { "code": null, "e": 1754, "s": 1551, "text": "The nanoTime() method returns the current time in nano seconds. To find the elapsed time for a method you can get the difference between time values before and after the execution of the desired method." }, { "code": null, "e": 2074, "s": 1754, "text": "The now() method of the Instant class returns the current time and the Duration.between() methods returns the difference between the given two time values to get the elapsed time retrieve the time values before and after the execution of the desired method and retrieve the duration using the Duration.between() method." }, { "code": null, "e": 2247, "s": 2074, "text": "The Apache commons library provides a class known as Stopwatch to it provides the start() stop() and getTime() methods to find the time taken for the execution of a method." }, { "code": null, "e": 2357, "s": 2247, "text": "Following example demonstrates how to find the execution time of a method using the above mentioned methods −" }, { "code": null, "e": 2367, "s": 2357, "text": "Live Demo" }, { "code": null, "e": 3479, "s": 2367, "text": "import java.time.Duration;\nimport java.time.Instant;\nimport org.apache.commons.lang3.time.StopWatch;\npublic class Example {\n public void test(){\n int num = 0;\n for(int i=0; i<=50; i++){ \n num =num+i;\n System.out.print(num+\", \");\n } \n }\n public static void main(String args[]){\n Example obj = new Example();\n long start1 = System.nanoTime();\n obj.test();\n long end1 = System.nanoTime(); \n System.out.println(\"Elapsed Time in nano seconds: \"+ (end1-start1)); \n long start2 = System.currentTimeMillis();\n obj.test();\n long end2 = System.currentTimeMillis(); \n System.out.println(\"Elapsed Time in milli seconds: \"+ (end2-start2));\n Instant inst1 = Instant.now();\n obj.test();\n Instant inst2 = Instant.now(); \n System.out.println(\"Elapsed Time: \"+ Duration.between(inst1, inst2).toString());\n StopWatch stopWatch = new StopWatch();\n stopWatch.start();\n obj.test();\n stopWatch.stop(); \n System.out.println(\"Elapsed Time in minutes: \"+ stopWatch.getTime());\n }\n}" }, { "code": null, "e": 4572, "s": 3479, "text": "0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990, 1035, 1081, 1128, 1176, 1225, 1275, Elapsed Time in nano seconds: 1882300\n0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990, 1035, 1081, 1128, 1176, 1225, 1275, Elapsed Time in milli seconds: 1\n0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990, 1035, 1081, 1128, 1176, 1225, 1275, Elapsed Time: PT0.001S\n0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990, 1035, 1081, 1128, 1176, 1225, 1275, Elapsed Time in minutes: 1" } ]
Int32.CompareTo Method in C# with Examples
04 Apr, 2019 Int32.CompareTo Method is used to compare the current instance to a specified object or Int32 and returns a sign of their relative values. There are 2 methods in the overload list of this method as follows: CompareTo(Int32) Method CompareTo(Object) Method This method is used to compare the current instance to a specified 32-bit signed integer and returns a sign of their relative values. Syntax: public int CompareTo (int value); Here, it takes integer to compare. Return Value: It returns a 32-bit signed number indicating the relative values of current instance and value parameter as follows: Less than Zero: if Current Instance < value Zero: if Current Instance = value Greater than Zero: if Current Instance > value Below programs illustrate the use of the above-discussed method: Example 1: // C# program to demonstrate the// Int32.CompareTo(Int32) Methodusing System; class GFG { // Main Method public static void Main() { // Declaring and initializing value1 int value1 = 10; // Declaring and initializing value2 int value2 = 20; // using CompareTo() method int status = value1.CompareTo(value2); // checking the status if (status > 0) Console.WriteLine("{0} is greater than {1}", value1, value2); else if (status < 0) Console.WriteLine("{0} is less than {1}", value1, value2); else Console.WriteLine("{0} is equal to {1}", value1, value2); }} 10 is less than 20 Example 2: // C# program to demonstrate the// Int32.CompareTo(Int32) Methodusing System; class GFG { // Main Method public static void Main() { // calling get() method get(5, 7); get(3025, 3025); get(10, 20); get(7, -12); } // defining get() method public static void get(int value1, int value2) { // using the method int status = value1.CompareTo(value2); // checking the status if (status > 0) Console.WriteLine("{0} is greater than {1}", value1, value2); else if (status < 0) Console.WriteLine("{0} is less than {1}", value1, value2); else Console.WriteLine("{0} is equal to {1}", value1, value2); }} 5 is less than 7 3025 is equal to 3025 10 is less than 20 7 is greater than -12 This method is used to compare the current instance to a specified object and returns a sign of their relative values. Syntax: public int CompareTo (object value); Here, it takes an object to compare, or null. Return Value: It returns a 32-bit signed number indicating the relative values of current instance and value parameter as follows: Less than Zero: if Current Instance < value Zero: if Current Instance = value Greater than Zero: if Current Instance > value or value is null. Exception: It throws ArgumentException if value is not an Int32. Below programs illustrate the use of the above-discussed method: Example 1: // C# program to demonstrate the// Int32.CompareTo(Object) Methodusing System; class GFG { // Main Method public static void Main() { try { // Declaring and initializing value1 int value1 = 10; // Declaring and initializing value2 object value2 = 562587; // using CompareTo() method int status = value1.CompareTo(value2); // checking the status if (status > 0) Console.WriteLine("{0} is greater than {1}", value1, value2); else if (status < 0) Console.WriteLine("{0} is less than {1}", value1, value2); else Console.WriteLine("{0} is equal to {1}", value1, value2); } catch (ArgumentException e) { Console.WriteLine("value2 must be Int32"); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }} 10 is less than 562587 Example 2: For ArgumentException // C# program to demonstrate the// Int32.CompareTo(object) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // Declaring and initializing value1 int value1 = 10; // Declaring and initializing value2 object value2 = 9856745963; // using CompareTo() method int status = value1.CompareTo(value2); // checking the status if (status > 0) Console.WriteLine("{0} is greater than {1}", value1, value2); else if (status < 0) Console.WriteLine("{0} is less than {1}", value1, value2); else Console.WriteLine("{0} is equal to {1}", value1, value2); } catch (ArgumentException e) { Console.WriteLine("value2 must be Int32"); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }} value2 must be Int32 Exception Thrown: System.ArgumentException Reference: https://docs.microsoft.com/en-us/dotnet/api/system.int32.compareto?view=netframework-4.7.2 CSharp-Int32-Struct CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework Extension Method in C# C# | List Class HashSet in C# with Examples C# | .NET Framework (Basic Architecture and Component Stack) Switch Statement in C# Partial Classes in C# Lambda Expressions in C# Hello World in C#
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Apr, 2019" }, { "code": null, "e": 235, "s": 28, "text": "Int32.CompareTo Method is used to compare the current instance to a specified object or Int32 and returns a sign of their relative values. There are 2 methods in the overload list of this method as follows:" }, { "code": null, "e": 259, "s": 235, "text": "CompareTo(Int32) Method" }, { "code": null, "e": 284, "s": 259, "text": "CompareTo(Object) Method" }, { "code": null, "e": 418, "s": 284, "text": "This method is used to compare the current instance to a specified 32-bit signed integer and returns a sign of their relative values." }, { "code": null, "e": 426, "s": 418, "text": "Syntax:" }, { "code": null, "e": 460, "s": 426, "text": "public int CompareTo (int value);" }, { "code": null, "e": 495, "s": 460, "text": "Here, it takes integer to compare." }, { "code": null, "e": 626, "s": 495, "text": "Return Value: It returns a 32-bit signed number indicating the relative values of current instance and value parameter as follows:" }, { "code": null, "e": 670, "s": 626, "text": "Less than Zero: if Current Instance < value" }, { "code": null, "e": 704, "s": 670, "text": "Zero: if Current Instance = value" }, { "code": null, "e": 751, "s": 704, "text": "Greater than Zero: if Current Instance > value" }, { "code": null, "e": 816, "s": 751, "text": "Below programs illustrate the use of the above-discussed method:" }, { "code": null, "e": 827, "s": 816, "text": "Example 1:" }, { "code": "// C# program to demonstrate the// Int32.CompareTo(Int32) Methodusing System; class GFG { // Main Method public static void Main() { // Declaring and initializing value1 int value1 = 10; // Declaring and initializing value2 int value2 = 20; // using CompareTo() method int status = value1.CompareTo(value2); // checking the status if (status > 0) Console.WriteLine(\"{0} is greater than {1}\", value1, value2); else if (status < 0) Console.WriteLine(\"{0} is less than {1}\", value1, value2); else Console.WriteLine(\"{0} is equal to {1}\", value1, value2); }}", "e": 1618, "s": 827, "text": null }, { "code": null, "e": 1638, "s": 1618, "text": "10 is less than 20\n" }, { "code": null, "e": 1649, "s": 1638, "text": "Example 2:" }, { "code": "// C# program to demonstrate the// Int32.CompareTo(Int32) Methodusing System; class GFG { // Main Method public static void Main() { // calling get() method get(5, 7); get(3025, 3025); get(10, 20); get(7, -12); } // defining get() method public static void get(int value1, int value2) { // using the method int status = value1.CompareTo(value2); // checking the status if (status > 0) Console.WriteLine(\"{0} is greater than {1}\", value1, value2); else if (status < 0) Console.WriteLine(\"{0} is less than {1}\", value1, value2); else Console.WriteLine(\"{0} is equal to {1}\", value1, value2); }}", "e": 2520, "s": 1649, "text": null }, { "code": null, "e": 2601, "s": 2520, "text": "5 is less than 7\n3025 is equal to 3025\n10 is less than 20\n7 is greater than -12\n" }, { "code": null, "e": 2720, "s": 2601, "text": "This method is used to compare the current instance to a specified object and returns a sign of their relative values." }, { "code": null, "e": 2728, "s": 2720, "text": "Syntax:" }, { "code": null, "e": 2765, "s": 2728, "text": "public int CompareTo (object value);" }, { "code": null, "e": 2811, "s": 2765, "text": "Here, it takes an object to compare, or null." }, { "code": null, "e": 2942, "s": 2811, "text": "Return Value: It returns a 32-bit signed number indicating the relative values of current instance and value parameter as follows:" }, { "code": null, "e": 2986, "s": 2942, "text": "Less than Zero: if Current Instance < value" }, { "code": null, "e": 3020, "s": 2986, "text": "Zero: if Current Instance = value" }, { "code": null, "e": 3085, "s": 3020, "text": "Greater than Zero: if Current Instance > value or value is null." }, { "code": null, "e": 3150, "s": 3085, "text": "Exception: It throws ArgumentException if value is not an Int32." }, { "code": null, "e": 3215, "s": 3150, "text": "Below programs illustrate the use of the above-discussed method:" }, { "code": null, "e": 3226, "s": 3215, "text": "Example 1:" }, { "code": "// C# program to demonstrate the// Int32.CompareTo(Object) Methodusing System; class GFG { // Main Method public static void Main() { try { // Declaring and initializing value1 int value1 = 10; // Declaring and initializing value2 object value2 = 562587; // using CompareTo() method int status = value1.CompareTo(value2); // checking the status if (status > 0) Console.WriteLine(\"{0} is greater than {1}\", value1, value2); else if (status < 0) Console.WriteLine(\"{0} is less than {1}\", value1, value2); else Console.WriteLine(\"{0} is equal to {1}\", value1, value2); } catch (ArgumentException e) { Console.WriteLine(\"value2 must be Int32\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}", "e": 4327, "s": 3226, "text": null }, { "code": null, "e": 4351, "s": 4327, "text": "10 is less than 562587\n" }, { "code": null, "e": 4384, "s": 4351, "text": "Example 2: For ArgumentException" }, { "code": "// C# program to demonstrate the// Int32.CompareTo(object) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // Declaring and initializing value1 int value1 = 10; // Declaring and initializing value2 object value2 = 9856745963; // using CompareTo() method int status = value1.CompareTo(value2); // checking the status if (status > 0) Console.WriteLine(\"{0} is greater than {1}\", value1, value2); else if (status < 0) Console.WriteLine(\"{0} is less than {1}\", value1, value2); else Console.WriteLine(\"{0} is equal to {1}\", value1, value2); } catch (ArgumentException e) { Console.WriteLine(\"value2 must be Int32\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}", "e": 5516, "s": 4384, "text": null }, { "code": null, "e": 5581, "s": 5516, "text": "value2 must be Int32\nException Thrown: System.ArgumentException\n" }, { "code": null, "e": 5592, "s": 5581, "text": "Reference:" }, { "code": null, "e": 5683, "s": 5592, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.int32.compareto?view=netframework-4.7.2" }, { "code": null, "e": 5703, "s": 5683, "text": "CSharp-Int32-Struct" }, { "code": null, "e": 5717, "s": 5703, "text": "CSharp-method" }, { "code": null, "e": 5720, "s": 5717, "text": "C#" }, { "code": null, "e": 5818, "s": 5720, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5861, "s": 5818, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 5910, "s": 5861, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 5933, "s": 5910, "text": "Extension Method in C#" }, { "code": null, "e": 5949, "s": 5933, "text": "C# | List Class" }, { "code": null, "e": 5977, "s": 5949, "text": "HashSet in C# with Examples" }, { "code": null, "e": 6038, "s": 5977, "text": "C# | .NET Framework (Basic Architecture and Component Stack)" }, { "code": null, "e": 6061, "s": 6038, "text": "Switch Statement in C#" }, { "code": null, "e": 6083, "s": 6061, "text": "Partial Classes in C#" }, { "code": null, "e": 6108, "s": 6083, "text": "Lambda Expressions in C#" } ]
Check if a string can be obtained by rotating another string 2 places
08 Jul, 2022 Given two strings, the task is to find if a string can be obtained by rotating another string two places. Examples: Input: string1 = “amazon”, string2 = “azonam” Output: Yes // rotated anti-clockwiseInput: string1 = “amazon”, string2 = “onamaz” Output: Yes // rotated clockwise Asked in: Amazon Interview Clockwise rotated Anti-clockwise rotated Clockwise rotated Anti-clockwise rotated If clockwise rotated that means elements are shifted in right. So, check if a substring[2.... len-1] of string2 when concatenated with substring[0,1] of string2 is equal to string1. Then, return true. Else, check if it is rotated anti-clockwise that means elements are shifted to left. So, check if concatenation of substring[len-2, len-1] with substring[0....len-3] makes it equals to string1. Then return true. Else, return false. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ program to check if a string is two time// rotation of another string.#include<bits/stdc++.h>using namespace std; // Function to check if string2 is obtained by// string 1bool isRotated(string str1, string str2){ if (str1.length() != str2.length()) return false; if(str1.length()<2){ return str1.compare(str2) == 0; } string clock_rot = ""; string anticlock_rot = ""; int len = str2.length(); // Initialize string as anti-clockwise rotation anticlock_rot = anticlock_rot + str2.substr(len-2, 2) + str2.substr(0, len-2) ; // Initialize string as clock wise rotation clock_rot = clock_rot + str2.substr(2) + str2.substr(0, 2) ; // check if any of them is equal to string1 return (str1.compare(clock_rot) == 0 || str1.compare(anticlock_rot) == 0);} // Driver codeint main(){ string str1 = "geeks"; string str2 = "eksge"; isRotated(str1, str2) ? cout << "Yes" : cout << "No"; return 0;} // Java program to check if a string is two time// rotation of another string. class Test{ // Method to check if string2 is obtained by // string 1 static boolean isRotated(String str1, String str2) { if (str1.length() != str2.length()) return false; if(str1.length() < 2) { return str1.equals(str2); } String clock_rot = ""; String anticlock_rot = ""; int len = str2.length(); // Initialize string as anti-clockwise rotation anticlock_rot = anticlock_rot + str2.substring(len-2, len) + str2.substring(0, len-2) ; // Initialize string as clock wise rotation clock_rot = clock_rot + str2.substring(2) + str2.substring(0, 2) ; // check if any of them is equal to string1 return (str1.equals(clock_rot) || str1.equals(anticlock_rot)); } // Driver method public static void main(String[] args) { String str1 = "geeks"; String str2 = "eksge"; System.out.println(isRotated(str1, str2) ? "Yes" : "No"); }} # Python 3 program to check if a string# is two time rotation of another string. # Function to check if string2 is# obtained by string 1def isRotated(str1, str2): if (len(str1) != len(str2)): return False if(len(str1) < 2): return str1 == str2 clock_rot = "" anticlock_rot = "" l = len(str2) # Initialize string as anti-clockwise rotation anticlock_rot = (anticlock_rot + str2[l - 2:] + str2[0: l - 2]) # Initialize string as clock wise rotation clock_rot = clock_rot + str2[2:] + str2[0:2] # check if any of them is equal to string1 return (str1 == clock_rot or str1 == anticlock_rot) # Driver codeif __name__ == "__main__": str1 = "geeks" str2 = "eksge"if isRotated(str1, str2): print("Yes") else: print("No") # This code is contributed by ita_c using System; // C# program to check if a string is two time// rotation of another string. public class Test { // Method to check if string2 is obtained by // string 1 public static bool isRotated(string str1, string str2) { if (str1.Length != str2.Length) { return false; } if (str1.Length < 2) { return str1.Equals(str2); } string clock_rot = ""; string anticlock_rot = ""; int len = str2.Length; // Initialize string as anti-clockwise rotation anticlock_rot = anticlock_rot + str2.Substring(len - 2, len - (len - 2)) + str2.Substring(0, len - 2); // Initialize string as clock wise rotation clock_rot = clock_rot + str2.Substring(2) + str2.Substring(0, 2); // check if any of them is equal to string1 return (str1.Equals(clock_rot) || str1.Equals(anticlock_rot)); } // Driver code public static void Main(string[] args) { string str1 = "geeks"; string str2 = "eksge"; Console.WriteLine(isRotated(str1, str2) ? "Yes" : "No"); }} // This code is contributed by Shrikant13 <script> // Javascript program to check if a// string is two time rotation of// another string. // Method to check if string2 is// obtained by string 1function isRotated(str1, str2){ if (str1.length != str2.length) return false; if (str1.length < 2) { return str1.localeCompare(str2); } let clock_rot = ""; let anticlock_rot = ""; let len = str2.length; // Initialize string as anti-clockwise rotation anticlock_rot = anticlock_rot + str2.substring(len - 2, len + 1) + str2.substring(0, len - 1) ; // Initialize string as clock wise rotation clock_rot = clock_rot + str2.substring(2, str2.length - 2 + 1) + str2.substring(0, 2 + 1); // Check if any of them is equal to string1 return (str1.localeCompare(clock_rot) || str1.localeCompare(anticlock_rot));} // Driver codelet str1 = "geeks";let str2 = "eksge"; document.write(isRotated(str1, str2) ? "Yes" : "No"); // This code is contributed by rag2127 </script> Yes Time Complexity : O(n) Auxiliary Space: O(n) Exercise : Check if string2 is obtained by rotating string1 by k places Method 2 – Without using any extra space: We could check directly if the string is rotated or not by comparing the two strings. Steps – Check if the string is rotated in clockwise manner.Check if the string is rotated in anticlockwise manner. Return true if any one of the above is true Check if the string is rotated in clockwise manner. Check if the string is rotated in anticlockwise manner. Return true if any one of the above is true We compare for clockwise and anticlockwise by using for loops and the modulo operator- Note that – For clockwise – str1[i] == str2[(i + 2) % n] For anticlockwise – str1[(i + 2) % n] == str2[i] Here n is length of string Check using the above two conditions and the problem will be solved! See the code for better understanding. C++ // C++ code to find if string is rotated by 2 positions #include <iostream>using namespace std; bool isRotated(string str1, string str2){ // Your code here // clockwise direction check int n = str1.length(); bool clockwise = true, anticlockwise = true; for (int i = 0; i < n; i++) { if (str1[i] != str2[(i + 2) % n]) { clockwise = false; // not rotated clockwise break; } } for (int i = 0; i < n; i++) { if (str1[(i + 2) % n] != str2[i]) { anticlockwise = false; // not rotated anticlockwise break; } } return clockwise or anticlockwise; // if any of both is true, return true}int main(){ string str1 = "geeks"; string str2 = "eksge"; isRotated(str1, str2) ? cout << "Yes" : cout << "No"; return 0;} //code contributed by Anshit Bansal Yes Time Complexity – O(n)Space Complexity – 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. shrikanth13 ukasp piyush_1301 rajatmiglani1 rag2127 hasani anshitbansal hardikkoriintern Accolite Amazon rotation Strings Accolite Amazon Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. What is Data Structure: Types, Classifications and Applications Top 50 String Coding Problems for Interviews Length of the longest substring without repeating characters Convert string to char array in C++ Reverse words in a given string Check whether two strings are anagram of each other Print all the duplicates in the input string Reverse string in Python (6 different ways) Remove duplicates from a given string Array of Strings in C++ - 5 Different Ways to Create
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Jul, 2022" }, { "code": null, "e": 159, "s": 52, "text": "Given two strings, the task is to find if a string can be obtained by rotating another string two places. " }, { "code": null, "e": 170, "s": 159, "text": "Examples: " }, { "code": null, "e": 332, "s": 170, "text": "Input: string1 = “amazon”, string2 = “azonam” Output: Yes // rotated anti-clockwiseInput: string1 = “amazon”, string2 = “onamaz” Output: Yes // rotated clockwise" }, { "code": null, "e": 359, "s": 332, "text": "Asked in: Amazon Interview" }, { "code": null, "e": 400, "s": 359, "text": "Clockwise rotated Anti-clockwise rotated" }, { "code": null, "e": 419, "s": 400, "text": "Clockwise rotated " }, { "code": null, "e": 442, "s": 419, "text": "Anti-clockwise rotated" }, { "code": null, "e": 643, "s": 442, "text": "If clockwise rotated that means elements are shifted in right. So, check if a substring[2.... len-1] of string2 when concatenated with substring[0,1] of string2 is equal to string1. Then, return true." }, { "code": null, "e": 856, "s": 643, "text": "Else, check if it is rotated anti-clockwise that means elements are shifted to left. So, check if concatenation of substring[len-2, len-1] with substring[0....len-3] makes it equals to string1. Then return true." }, { "code": null, "e": 876, "s": 856, "text": "Else, return false." }, { "code": null, "e": 927, "s": 876, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 931, "s": 927, "text": "C++" }, { "code": null, "e": 936, "s": 931, "text": "Java" }, { "code": null, "e": 944, "s": 936, "text": "Python3" }, { "code": null, "e": 947, "s": 944, "text": "C#" }, { "code": null, "e": 958, "s": 947, "text": "Javascript" }, { "code": "// C++ program to check if a string is two time// rotation of another string.#include<bits/stdc++.h>using namespace std; // Function to check if string2 is obtained by// string 1bool isRotated(string str1, string str2){ if (str1.length() != str2.length()) return false; if(str1.length()<2){ return str1.compare(str2) == 0; } string clock_rot = \"\"; string anticlock_rot = \"\"; int len = str2.length(); // Initialize string as anti-clockwise rotation anticlock_rot = anticlock_rot + str2.substr(len-2, 2) + str2.substr(0, len-2) ; // Initialize string as clock wise rotation clock_rot = clock_rot + str2.substr(2) + str2.substr(0, 2) ; // check if any of them is equal to string1 return (str1.compare(clock_rot) == 0 || str1.compare(anticlock_rot) == 0);} // Driver codeint main(){ string str1 = \"geeks\"; string str2 = \"eksge\"; isRotated(str1, str2) ? cout << \"Yes\" : cout << \"No\"; return 0;}", "e": 2016, "s": 958, "text": null }, { "code": "// Java program to check if a string is two time// rotation of another string. class Test{ // Method to check if string2 is obtained by // string 1 static boolean isRotated(String str1, String str2) { if (str1.length() != str2.length()) return false; if(str1.length() < 2) { return str1.equals(str2); } String clock_rot = \"\"; String anticlock_rot = \"\"; int len = str2.length(); // Initialize string as anti-clockwise rotation anticlock_rot = anticlock_rot + str2.substring(len-2, len) + str2.substring(0, len-2) ; // Initialize string as clock wise rotation clock_rot = clock_rot + str2.substring(2) + str2.substring(0, 2) ; // check if any of them is equal to string1 return (str1.equals(clock_rot) || str1.equals(anticlock_rot)); } // Driver method public static void main(String[] args) { String str1 = \"geeks\"; String str2 = \"eksge\"; System.out.println(isRotated(str1, str2) ? \"Yes\" : \"No\"); }}", "e": 3240, "s": 2016, "text": null }, { "code": "# Python 3 program to check if a string# is two time rotation of another string. # Function to check if string2 is# obtained by string 1def isRotated(str1, str2): if (len(str1) != len(str2)): return False if(len(str1) < 2): return str1 == str2 clock_rot = \"\" anticlock_rot = \"\" l = len(str2) # Initialize string as anti-clockwise rotation anticlock_rot = (anticlock_rot + str2[l - 2:] + str2[0: l - 2]) # Initialize string as clock wise rotation clock_rot = clock_rot + str2[2:] + str2[0:2] # check if any of them is equal to string1 return (str1 == clock_rot or str1 == anticlock_rot) # Driver codeif __name__ == \"__main__\": str1 = \"geeks\" str2 = \"eksge\"if isRotated(str1, str2): print(\"Yes\") else: print(\"No\") # This code is contributed by ita_c", "e": 4112, "s": 3240, "text": null }, { "code": "using System; // C# program to check if a string is two time// rotation of another string. public class Test { // Method to check if string2 is obtained by // string 1 public static bool isRotated(string str1, string str2) { if (str1.Length != str2.Length) { return false; } if (str1.Length < 2) { return str1.Equals(str2); } string clock_rot = \"\"; string anticlock_rot = \"\"; int len = str2.Length; // Initialize string as anti-clockwise rotation anticlock_rot = anticlock_rot + str2.Substring(len - 2, len - (len - 2)) + str2.Substring(0, len - 2); // Initialize string as clock wise rotation clock_rot = clock_rot + str2.Substring(2) + str2.Substring(0, 2); // check if any of them is equal to string1 return (str1.Equals(clock_rot) || str1.Equals(anticlock_rot)); } // Driver code public static void Main(string[] args) { string str1 = \"geeks\"; string str2 = \"eksge\"; Console.WriteLine(isRotated(str1, str2) ? \"Yes\" : \"No\"); }} // This code is contributed by Shrikant13", "e": 5371, "s": 4112, "text": null }, { "code": "<script> // Javascript program to check if a// string is two time rotation of// another string. // Method to check if string2 is// obtained by string 1function isRotated(str1, str2){ if (str1.length != str2.length) return false; if (str1.length < 2) { return str1.localeCompare(str2); } let clock_rot = \"\"; let anticlock_rot = \"\"; let len = str2.length; // Initialize string as anti-clockwise rotation anticlock_rot = anticlock_rot + str2.substring(len - 2, len + 1) + str2.substring(0, len - 1) ; // Initialize string as clock wise rotation clock_rot = clock_rot + str2.substring(2, str2.length - 2 + 1) + str2.substring(0, 2 + 1); // Check if any of them is equal to string1 return (str1.localeCompare(clock_rot) || str1.localeCompare(anticlock_rot));} // Driver codelet str1 = \"geeks\";let str2 = \"eksge\"; document.write(isRotated(str1, str2) ? \"Yes\" : \"No\"); // This code is contributed by rag2127 </script>", "e": 6454, "s": 5371, "text": null }, { "code": null, "e": 6458, "s": 6454, "text": "Yes" }, { "code": null, "e": 6503, "s": 6458, "text": "Time Complexity : O(n) Auxiliary Space: O(n)" }, { "code": null, "e": 6575, "s": 6503, "text": "Exercise : Check if string2 is obtained by rotating string1 by k places" }, { "code": null, "e": 6618, "s": 6575, "text": "Method 2 – Without using any extra space: " }, { "code": null, "e": 6705, "s": 6618, "text": "We could check directly if the string is rotated or not by comparing the two strings. " }, { "code": null, "e": 6713, "s": 6705, "text": "Steps –" }, { "code": null, "e": 6864, "s": 6713, "text": "Check if the string is rotated in clockwise manner.Check if the string is rotated in anticlockwise manner. Return true if any one of the above is true" }, { "code": null, "e": 6916, "s": 6864, "text": "Check if the string is rotated in clockwise manner." }, { "code": null, "e": 6973, "s": 6916, "text": "Check if the string is rotated in anticlockwise manner. " }, { "code": null, "e": 7017, "s": 6973, "text": "Return true if any one of the above is true" }, { "code": null, "e": 7104, "s": 7017, "text": "We compare for clockwise and anticlockwise by using for loops and the modulo operator-" }, { "code": null, "e": 7117, "s": 7104, "text": "Note that – " }, { "code": null, "e": 7162, "s": 7117, "text": "For clockwise – str1[i] == str2[(i + 2) % n]" }, { "code": null, "e": 7211, "s": 7162, "text": "For anticlockwise – str1[(i + 2) % n] == str2[i]" }, { "code": null, "e": 7239, "s": 7211, "text": "Here n is length of string " }, { "code": null, "e": 7308, "s": 7239, "text": "Check using the above two conditions and the problem will be solved!" }, { "code": null, "e": 7347, "s": 7308, "text": "See the code for better understanding." }, { "code": null, "e": 7351, "s": 7347, "text": "C++" }, { "code": "// C++ code to find if string is rotated by 2 positions #include <iostream>using namespace std; bool isRotated(string str1, string str2){ // Your code here // clockwise direction check int n = str1.length(); bool clockwise = true, anticlockwise = true; for (int i = 0; i < n; i++) { if (str1[i] != str2[(i + 2) % n]) { clockwise = false; // not rotated clockwise break; } } for (int i = 0; i < n; i++) { if (str1[(i + 2) % n] != str2[i]) { anticlockwise = false; // not rotated anticlockwise break; } } return clockwise or anticlockwise; // if any of both is true, return true}int main(){ string str1 = \"geeks\"; string str2 = \"eksge\"; isRotated(str1, str2) ? cout << \"Yes\" : cout << \"No\"; return 0;} //code contributed by Anshit Bansal", "e": 8246, "s": 7351, "text": null }, { "code": null, "e": 8250, "s": 8246, "text": "Yes" }, { "code": null, "e": 8296, "s": 8250, "text": "Time Complexity – O(n)Space Complexity – O(1)" }, { "code": null, "e": 8594, "s": 8296, "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. " }, { "code": null, "e": 8606, "s": 8594, "text": "shrikanth13" }, { "code": null, "e": 8612, "s": 8606, "text": "ukasp" }, { "code": null, "e": 8624, "s": 8612, "text": "piyush_1301" }, { "code": null, "e": 8638, "s": 8624, "text": "rajatmiglani1" }, { "code": null, "e": 8646, "s": 8638, "text": "rag2127" }, { "code": null, "e": 8653, "s": 8646, "text": "hasani" }, { "code": null, "e": 8666, "s": 8653, "text": "anshitbansal" }, { "code": null, "e": 8683, "s": 8666, "text": "hardikkoriintern" }, { "code": null, "e": 8692, "s": 8683, "text": "Accolite" }, { "code": null, "e": 8699, "s": 8692, "text": "Amazon" }, { "code": null, "e": 8708, "s": 8699, "text": "rotation" }, { "code": null, "e": 8716, "s": 8708, "text": "Strings" }, { "code": null, "e": 8725, "s": 8716, "text": "Accolite" }, { "code": null, "e": 8732, "s": 8725, "text": "Amazon" }, { "code": null, "e": 8740, "s": 8732, "text": "Strings" }, { "code": null, "e": 8838, "s": 8740, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8902, "s": 8838, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 8947, "s": 8902, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 9008, "s": 8947, "text": "Length of the longest substring without repeating characters" }, { "code": null, "e": 9044, "s": 9008, "text": "Convert string to char array in C++" }, { "code": null, "e": 9076, "s": 9044, "text": "Reverse words in a given string" }, { "code": null, "e": 9128, "s": 9076, "text": "Check whether two strings are anagram of each other" }, { "code": null, "e": 9173, "s": 9128, "text": "Print all the duplicates in the input string" }, { "code": null, "e": 9217, "s": 9173, "text": "Reverse string in Python (6 different ways)" }, { "code": null, "e": 9255, "s": 9217, "text": "Remove duplicates from a given string" } ]
How to Make a Scientific Calculator Android App using Android Studio?
11 Jun, 2021 The calculator is the app that is present on every android device. This app comes pre-installed or we can also install another application from Play Store. It is one of the most used applications for college students for making any calculations. In this article, we will take a look at building a simple scientific calculator app in Android using Kotlin. Note: To build a simple calculator app please refer to this article How to build a simple Calculator app using Android Studio? We will be building a scientific calculator in which we will be performing several mathematical operations such as addition, subtraction, square root, factorial, and many more. A sample video is given below to get an idea about what we are going to do in this article. How to Make a Scientific Calculator Android App? | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersHow to Make a Scientific Calculator Android App? | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:10:36•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=gwOL-4V_sNw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Adding new colors to the colors.xml file Navigate to the app > res > values > colors.xml file and add the below code to it for different colors. Comments are added in the code to get to know in more detail. XML <?xml version="1.0" encoding="utf-8"?><resources> <color name="purple_200">#0F9D58</color> <color name="purple_500">#0F9D58</color> <color name="purple_700">#0F9D58</color> <color name="teal_200">#FF03DAC5</color> <color name="teal_700">#FF018786</color> <color name="black">#FF000000</color> <color name="white">#FFFFFFFF</color> <!--three different shades of black color--> <color name="blac_shade_1">#292D36</color> <color name="black_shade_2">#272B33</color> <color name="black_shade_3">#22252D</color> <color name="yellow">#ffa500</color> </resources> Step 3: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/black_shade_3" tools:context=".MainActivity"> <TextView android:id="@+id/idTVSecondary" android:layout_width="match_parent" android:layout_height="70dp" android:background="@color/black_shade_3" android:gravity="bottom" android:maxLines="1" android:padding="10dp" android:paddingTop="30dp" android:text="" android:textAlignment="viewEnd" android:textColor="@color/white" android:textSize="15sp" tools:ignore="RtlCompat" /> <TextView android:id="@+id/idTVprimary" android:layout_width="match_parent" android:layout_height="100dp" android:layout_below="@id/idTVSecondary" android:background="@color/black_shade_3" android:gravity="bottom" android:maxLines="1" android:padding="10dp" android:text="" android:textAlignment="viewEnd" android:textColor="#fff" android:textSize="50sp" tools:ignore="RtlCompat" /> <androidx.cardview.widget.CardView android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/idTVprimary" android:background="@color/blac_shade_1" app:cardCornerRadius="4dp" app:cardElevation="2dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="7" android:background="@color/blac_shade_1" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:weightSum="7"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:orientation="horizontal"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:weightSum="4"> <Button android:id="@+id/bac" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="AC" android:textColor="@color/yellow" android:textSize="15sp" tools:targetApi="lollipop" /> <Button android:id="@+id/bc" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="C" android:textColor="@color/yellow" android:textSize="15sp" /> <Button android:id="@+id/bbrac1" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="(" android:textColor="#ffa500" android:textSize="15sp" /> <Button android:id="@+id/bbrac2" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text=")" android:textColor="#ffa500" android:textSize="15sp" /> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:orientation="horizontal"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:weightSum="5"> <Button android:id="@+id/bsin" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="sin" android:textAllCaps="false" android:textColor="#ffa500" android:textSize="15sp" /> <Button android:id="@+id/bcos" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="cos" android:textAllCaps="false" android:textColor="#ffa500" android:textSize="15sp" /> <Button android:id="@+id/btan" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="tan" android:textAllCaps="false" android:textColor="#ffa500" android:textSize="15sp" /> <Button android:id="@+id/blog" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="log" android:textAllCaps="false" android:textColor="#ffa500" android:textSize="15sp" /> <Button android:id="@+id/bln" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="ln" android:textAllCaps="false" android:textColor="#ffa500" android:textSize="15sp" /> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:orientation="horizontal"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:weightSum="5"> <Button android:id="@+id/bfact" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="x!" android:textAllCaps="false" android:textColor="#ffa500" android:textSize="15sp" /> <Button android:id="@+id/bsquare" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="x2" android:textAllCaps="false" android:textColor="#ffa500" android:textSize="15sp" /> <Button android:id="@+id/bsqrt" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="√" android:textColor="#ffa500" android:textSize="15sp" /> <Button android:id="@+id/binv" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="1/x" android:textAllCaps="false" android:textColor="#ffa500" android:textSize="15sp" /> <Button android:id="@+id/bdiv" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="÷" android:textColor="#ffa500" android:textSize="15sp" /> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:orientation="horizontal"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:weightSum="4"> <Button android:id="@+id/b7" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="7" android:textColor="#fff" android:textSize="15sp" /> <Button android:id="@+id/b8" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="8" android:textColor="#fff" android:textSize="15sp" /> <Button android:id="@+id/b9" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="9" android:textColor="#fff" android:textSize="15sp" /> <Button android:id="@+id/bmul" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="×" android:textColor="#ffa500" android:textSize="15sp" /> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:orientation="horizontal"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:weightSum="4"> <Button android:id="@+id/b4" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="4" android:textColor="#fff" android:textSize="15sp" /> <Button android:id="@+id/b5" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="5" android:textColor="#fff" android:textSize="15sp" /> <Button android:id="@+id/b6" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="6" android:textColor="#fff" android:textSize="15sp" /> <Button android:id="@+id/bminus" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="-" android:textColor="#ffa500" android:textSize="15sp" /> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:orientation="horizontal"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:weightSum="4"> <Button android:id="@+id/b1" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="1" android:textColor="#fff" android:textSize="15sp" /> <Button android:id="@+id/b2" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="2" android:textColor="#fff" android:textSize="15sp" /> <Button android:id="@+id/b3" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="3" android:textColor="#fff" android:textSize="15sp" /> <Button android:id="@+id/bplus" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="+" android:textColor="#ffa500" android:textSize="15sp" /> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:orientation="horizontal"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:weightSum="4"> <Button android:id="@+id/bpi" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="π" android:textColor="#fff" android:textSize="15sp" /> <Button android:id="@+id/b0" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="0" android:textColor="#fff" android:textSize="15sp" /> <Button android:id="@+id/bdot" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="." android:textColor="#fff" android:textSize="15sp" /> <Button android:id="@+id/bequal" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="=" android:textColor="#ffa500" android:textSize="15sp" /> </LinearLayout> </LinearLayout> </LinearLayout> </LinearLayout> </androidx.cardview.widget.CardView> </RelativeLayout> Step 4: Working with the MainActivity.kt file Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. Kotlin import android.os.Bundleimport android.widget.Buttonimport android.widget.TextViewimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { // creating variables for our text view and button lateinit var tvsec: TextView lateinit var tvMain: TextView lateinit var bac: Button lateinit var bc: Button lateinit var bbrac1: Button lateinit var bbrac2: Button lateinit var bsin: Button lateinit var bcos: Button lateinit var btan: Button lateinit var blog: Button lateinit var bln: Button lateinit var bfact: Button lateinit var bsquare: Button lateinit var bsqrt: Button lateinit var binv: Button lateinit var b0: Button lateinit var b9: Button lateinit var b8: Button lateinit var b7: Button lateinit var b6: Button lateinit var b5: Button lateinit var b4: Button lateinit var b3: Button lateinit var b2: Button lateinit var b1: Button lateinit var bpi: Button lateinit var bmul: Button lateinit var bminus: Button lateinit var bplus: Button lateinit var bequal: Button lateinit var bdot: Button lateinit var bdiv: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // initializing all our variables. tvsec = findViewById(R.id.idTVSecondary) tvMain = findViewById(R.id.idTVprimary) bac = findViewById(R.id.bac) bc = findViewById(R.id.bc) bbrac1 = findViewById(R.id.bbrac1) bbrac2 = findViewById(R.id.bbrac2) bsin = findViewById(R.id.bsin) bcos = findViewById(R.id.bcos) btan = findViewById(R.id.btan) blog = findViewById(R.id.blog) bln = findViewById(R.id.bln) bfact = findViewById(R.id.bfact) bsquare = findViewById(R.id.bsquare) bsqrt = findViewById(R.id.bsqrt) binv = findViewById(R.id.binv) b0 = findViewById(R.id.b0) b9 = findViewById(R.id.b9) b8 = findViewById(R.id.b8) b7 = findViewById(R.id.b7) b6 = findViewById(R.id.b6) b5 = findViewById(R.id.b5) b4 = findViewById(R.id.b4) b3 = findViewById(R.id.b3) b2 = findViewById(R.id.b2) b1 = findViewById(R.id.b1) bpi = findViewById(R.id.bpi) bmul = findViewById(R.id.bmul) bminus = findViewById(R.id.bminus) bplus = findViewById(R.id.bplus) bequal = findViewById(R.id.bequal) bdot = findViewById(R.id.bdot) bdiv = findViewById(R.id.bdiv) // adding on click listener to our all buttons. b1.setOnClickListener { // on below line we are appending // the expression to our text view. tvMain.text = (tvMain.text.toString() + "1") } b2.setOnClickListener { // on below line we are appending // the expression to our text view. tvMain.text = (tvMain.text.toString() + "2") } b3.setOnClickListener { // on below line we are appending // the expression to our text view. tvMain.text = (tvMain.text.toString() + "3") } b4.setOnClickListener { tvMain.text = (tvMain.text.toString() + "4") } b5.setOnClickListener { tvMain.text = (tvMain.text.toString() + "5") } b6.setOnClickListener { tvMain.text = (tvMain.text.toString() + "6") } b7.setOnClickListener { tvMain.text = (tvMain.text.toString() + "7") } b8.setOnClickListener { tvMain.text = (tvMain.text.toString() + "8") } b9.setOnClickListener { tvMain.text = (tvMain.text.toString() + "9") } b0.setOnClickListener { tvMain.text = (tvMain.text.toString() + "0") } bdot.setOnClickListener { tvMain.text = (tvMain.text.toString() + ".") } bplus.setOnClickListener { tvMain.text = (tvMain.text.toString() + "+") } bdiv.setOnClickListener { tvMain.text = (tvMain.text.toString() + "/") } bbrac1.setOnClickListener { tvMain.text = (tvMain.text.toString() + "(") } bbrac2.setOnClickListener { tvMain.text = (tvMain.text.toString() + ")") } bpi.setOnClickListener { // on clicking on pi button we are adding // pi value as 3.142 to our current value. tvMain.text = (tvMain.text.toString() + "3.142") tvsec.text = (bpi.text.toString()) } bsin.setOnClickListener { tvMain.text = (tvMain.text.toString() + "sin") } bcos.setOnClickListener { tvMain.text = (tvMain.text.toString() + "cos") } btan.setOnClickListener { tvMain.text = (tvMain.text.toString() + "tan") } binv.setOnClickListener { tvMain.text = (tvMain.text.toString() + "^" + "(-1)") } bln.setOnClickListener { tvMain.text = (tvMain.text.toString() + "ln") } blog.setOnClickListener { tvMain.text = (tvMain.text.toString() + "log") } bminus.setOnClickListener { // on clicking on minus we are checking if // the user has already a minus operation on screen. // if minus operation is already present // then we will not do anything. val str: String = tvMain.text.toString() if (!str.get(index = str.length - 1).equals("-")) { tvMain.text = (tvMain.text.toString() + "-") } } bmul.setOnClickListener { // if mul sign is not present in our // text view then only we are adding // the multiplication operator to it. val str: String = tvMain.text.toString() if (!str.get(index = str.length - 1).equals("*")) { tvMain.text = (tvMain.text.toString() + "*") } } bsqrt.setOnClickListener { if (tvMain.text.toString().isEmpty()) { // if the entered number is empty we are displaying an error message. Toast.makeText(this, "Please enter a valid number..", Toast.LENGTH_SHORT).show() } else { val str: String = tvMain.text.toString() // on below line we are calculation // square root of the given number. val r = Math.sqrt(str.toDouble()) // on below line we are converting our double // to string and then setting it to text view. val result = r.toString() tvMain.setText(result) } } bequal.setOnClickListener { val str: String = tvMain.text.toString() // on below line we are calling an evaluate // method to calculate the value of expressions. val result: Double = evaluate(str) // on below line we are getting result // and setting it to text view. val r = result.toString() tvMain.setText(r) tvsec.text = str } bac.setOnClickListener { // on clicking on ac button we are clearing // our primary and secondary text view. tvMain.setText("") tvsec.setText("") } bc.setOnClickListener { // on clicking on c button we are clearing // the last character by checking the length. var str: String = tvMain.text.toString() if (!str.equals("")) { str = str.substring(0, str.length - 1) tvMain.text = str } } bsquare.setOnClickListener { if (tvMain.text.toString().isEmpty()) { // if the entered number is empty we are displaying an error message. Toast.makeText(this, "Please enter a valid number..", Toast.LENGTH_SHORT).show() } else { // on below line we are getting the expression and then calculating the square of the number val d: Double = tvMain.getText().toString().toDouble() // on below line we are calculating the square. val square = d * d // after calculating the square we // are setting it to text view. tvMain.setText(square.toString()) // on below line we are setting // the d to secondary text view. tvsec.text = "$d2" } } bfact.setOnClickListener { if (tvMain.text.toString().isEmpty()) { // if the entered number is empty we are displaying an error message. Toast.makeText(this, "Please enter a valid number..", Toast.LENGTH_SHORT).show() } else { // on below line we are getting int value // and calculating the factorial value of the entered number. val value: Int = tvMain.text.toString().toInt() val fact: Int = factorial(value) tvMain.setText(fact.toString()) tvsec.text = "$value`!" } } } fun factorial(n: Int): Int { // this method is use to find factorial return if (n == 1 || n == 0) 1 else n * factorial(n - 1) } fun evaluate(str: String): Double { return object : Any() { // on below line we ar creating variable // for tracking the position and char pos. var pos = -1 var ch = 0 // below method is for moving to next character. fun nextChar() { // on below line we are incrementing our position // and moving it to next position. ch = if (++pos < str.length) str[pos].toInt() else -1 } // this method is use to check the extra space // present int the expression and removing it. fun eat(charToEat: Int): Boolean { while (ch == ' '.toInt()) nextChar() // on below line we are checking the char pos // if both is equal then we are returning it to true. if (ch == charToEat) { nextChar() return true } return false } // below method is to parse our // expression and to get the ans // in this we are calling a parse // expression method to calculate the value. fun parse(): Double { nextChar() val x = parseExpression() if (pos < str.length) throw RuntimeException("Unexpected: " + ch.toChar()) return x } // in this method we will only perform addition and // subtraction operation on the expression. fun parseExpression(): Double { var x = parseTerm() while (true) { if (eat('+'.toInt())) x += parseTerm() // addition else if (eat('-'.toInt())) x -= parseTerm() // subtraction else return x } } // in below method we will perform // only multiplication and division operation. fun parseTerm(): Double { var x = parseFactor() while (true) { if (eat('*'.toInt())) x *= parseFactor() // multiplication else if (eat('/'.toInt())) x /= parseFactor() // division else return x } } // below method is use to parse the factor fun parseFactor(): Double { //on below line we are checking for addition // and subtraction and performing unary operations. if (eat('+'.toInt())) return parseFactor() // unary plus if (eat('-'.toInt())) return -parseFactor() // unary minus // creating a double variable for ans. var x: Double // on below line we are creating // a variable for position. val startPos = pos // on below line we are checking // for opening and closing parenthesis. if (eat('('.toInt())) { // parentheses x = parseExpression() eat(')'.toInt()) } else if (ch >= '0'.toInt() && ch <= '9'.toInt() || ch == '.'.toInt()) { // numbers while (ch >= '0'.toInt() && ch <= '9'.toInt() || ch == '.'.toInt()) nextChar() // on below line we are getting sub string from our string using start and pos. x = str.substring(startPos, pos).toDouble() } else if (ch >= 'a'.toInt() && ch <= 'z'.toInt()) { // on below function we are checking for the operator in our expression. while (ch >= 'a'.toInt() && ch <= 'z'.toInt()) nextChar() val func = str.substring(startPos, pos) // calling a method to parse our factor. x = parseFactor() // on below line we are checking for square root. x = if (func == "sqrt") Math.sqrt(x) // on below line we are checking for sin function // and calculating sin function using Math class. else if (func == "sin") Math.sin( Math.toRadians(x) // on below line we are calculating the cos value ) else if (func == "cos") Math.cos( Math.toRadians(x) // on below line we are calculating // the tan value of our expression. ) else if (func == "tan") Math.tan(Math.toRadians(x)) // on below line we are calculating // log value of the expression. else if (func == "log") Math.log10(x) // on below line we are calculating // ln value of expression. else if (func == "ln") Math.log(x) // f we get any error then // we simply return the exception. else throw RuntimeException( "Unknown function: $func" ) } else { // if the condition not satisfy then we are returning the exception throw RuntimeException("Unexpected: " + ch.toChar()) } // on below line we are calculating the power of the expression. if (eat('^'.toInt())) x = Math.pow(x, parseFactor()) // exponentiation return x } // at last calling a parse for our expression. }.parse() }} Now run your app to see the output of the app. Output: Android-Studio ProGeek 2021 Android Kotlin ProGeek Project Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Jun, 2021" }, { "code": null, "e": 410, "s": 54, "text": "The calculator is the app that is present on every android device. This app comes pre-installed or we can also install another application from Play Store. It is one of the most used applications for college students for making any calculations. In this article, we will take a look at building a simple scientific calculator app in Android using Kotlin. " }, { "code": null, "e": 537, "s": 410, "text": "Note: To build a simple calculator app please refer to this article How to build a simple Calculator app using Android Studio?" }, { "code": null, "e": 806, "s": 537, "text": "We will be building a scientific calculator in which we will be performing several mathematical operations such as addition, subtraction, square root, factorial, and many more. A sample video is given below to get an idea about what we are going to do in this article." }, { "code": null, "e": 1723, "s": 806, "text": "How to Make a Scientific Calculator Android App? | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersHow to Make a Scientific Calculator Android App? | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:10:36•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=gwOL-4V_sNw\" 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": 1752, "s": 1723, "text": "Step 1: Create a New Project" }, { "code": null, "e": 1914, "s": 1752, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 1964, "s": 1914, "text": "Step 2: Adding new colors to the colors.xml file " }, { "code": null, "e": 2131, "s": 1964, "text": "Navigate to the app > res > values > colors.xml file and add the below code to it for different colors. Comments are added in the code to get to know in more detail. " }, { "code": null, "e": 2135, "s": 2131, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><resources> <color name=\"purple_200\">#0F9D58</color> <color name=\"purple_500\">#0F9D58</color> <color name=\"purple_700\">#0F9D58</color> <color name=\"teal_200\">#FF03DAC5</color> <color name=\"teal_700\">#FF018786</color> <color name=\"black\">#FF000000</color> <color name=\"white\">#FFFFFFFF</color> <!--three different shades of black color--> <color name=\"blac_shade_1\">#292D36</color> <color name=\"black_shade_2\">#272B33</color> <color name=\"black_shade_3\">#22252D</color> <color name=\"yellow\">#ffa500</color> </resources>", "e": 2739, "s": 2135, "text": null }, { "code": null, "e": 2787, "s": 2739, "text": "Step 3: Working with the activity_main.xml file" }, { "code": null, "e": 2930, "s": 2787, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 2934, "s": 2930, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"@color/black_shade_3\" tools:context=\".MainActivity\"> <TextView android:id=\"@+id/idTVSecondary\" android:layout_width=\"match_parent\" android:layout_height=\"70dp\" android:background=\"@color/black_shade_3\" android:gravity=\"bottom\" android:maxLines=\"1\" android:padding=\"10dp\" android:paddingTop=\"30dp\" android:text=\"\" android:textAlignment=\"viewEnd\" android:textColor=\"@color/white\" android:textSize=\"15sp\" tools:ignore=\"RtlCompat\" /> <TextView android:id=\"@+id/idTVprimary\" android:layout_width=\"match_parent\" android:layout_height=\"100dp\" android:layout_below=\"@id/idTVSecondary\" android:background=\"@color/black_shade_3\" android:gravity=\"bottom\" android:maxLines=\"1\" android:padding=\"10dp\" android:text=\"\" android:textAlignment=\"viewEnd\" android:textColor=\"#fff\" android:textSize=\"50sp\" tools:ignore=\"RtlCompat\" /> <androidx.cardview.widget.CardView android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_below=\"@id/idTVprimary\" android:background=\"@color/blac_shade_1\" app:cardCornerRadius=\"4dp\" app:cardElevation=\"2dp\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_weight=\"7\" android:background=\"@color/blac_shade_1\" android:orientation=\"vertical\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" android:weightSum=\"7\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_weight=\"1\" android:orientation=\"horizontal\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"horizontal\" android:weightSum=\"4\"> <Button android:id=\"@+id/bac\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"AC\" android:textColor=\"@color/yellow\" android:textSize=\"15sp\" tools:targetApi=\"lollipop\" /> <Button android:id=\"@+id/bc\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"C\" android:textColor=\"@color/yellow\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/bbrac1\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"(\" android:textColor=\"#ffa500\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/bbrac2\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\")\" android:textColor=\"#ffa500\" android:textSize=\"15sp\" /> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_weight=\"1\" android:orientation=\"horizontal\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"horizontal\" android:weightSum=\"5\"> <Button android:id=\"@+id/bsin\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"sin\" android:textAllCaps=\"false\" android:textColor=\"#ffa500\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/bcos\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"cos\" android:textAllCaps=\"false\" android:textColor=\"#ffa500\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/btan\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"tan\" android:textAllCaps=\"false\" android:textColor=\"#ffa500\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/blog\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"log\" android:textAllCaps=\"false\" android:textColor=\"#ffa500\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/bln\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"ln\" android:textAllCaps=\"false\" android:textColor=\"#ffa500\" android:textSize=\"15sp\" /> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_weight=\"1\" android:orientation=\"horizontal\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"horizontal\" android:weightSum=\"5\"> <Button android:id=\"@+id/bfact\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"x!\" android:textAllCaps=\"false\" android:textColor=\"#ffa500\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/bsquare\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"x2\" android:textAllCaps=\"false\" android:textColor=\"#ffa500\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/bsqrt\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"√\" android:textColor=\"#ffa500\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/binv\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"1/x\" android:textAllCaps=\"false\" android:textColor=\"#ffa500\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/bdiv\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"÷\" android:textColor=\"#ffa500\" android:textSize=\"15sp\" /> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_weight=\"1\" android:orientation=\"horizontal\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"horizontal\" android:weightSum=\"4\"> <Button android:id=\"@+id/b7\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"7\" android:textColor=\"#fff\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/b8\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"8\" android:textColor=\"#fff\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/b9\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"9\" android:textColor=\"#fff\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/bmul\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"×\" android:textColor=\"#ffa500\" android:textSize=\"15sp\" /> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_weight=\"1\" android:orientation=\"horizontal\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"horizontal\" android:weightSum=\"4\"> <Button android:id=\"@+id/b4\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"4\" android:textColor=\"#fff\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/b5\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"5\" android:textColor=\"#fff\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/b6\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"6\" android:textColor=\"#fff\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/bminus\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"-\" android:textColor=\"#ffa500\" android:textSize=\"15sp\" /> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_weight=\"1\" android:orientation=\"horizontal\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"horizontal\" android:weightSum=\"4\"> <Button android:id=\"@+id/b1\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"1\" android:textColor=\"#fff\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/b2\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"2\" android:textColor=\"#fff\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/b3\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"3\" android:textColor=\"#fff\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/bplus\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"+\" android:textColor=\"#ffa500\" android:textSize=\"15sp\" /> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_weight=\"1\" android:orientation=\"horizontal\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"horizontal\" android:weightSum=\"4\"> <Button android:id=\"@+id/bpi\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"π\" android:textColor=\"#fff\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/b0\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"0\" android:textColor=\"#fff\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/bdot\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\".\" android:textColor=\"#fff\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/bequal\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"=\" android:textColor=\"#ffa500\" android:textSize=\"15sp\" /> </LinearLayout> </LinearLayout> </LinearLayout> </LinearLayout> </androidx.cardview.widget.CardView> </RelativeLayout>", "e": 27722, "s": 2934, "text": null }, { "code": null, "e": 27768, "s": 27722, "text": "Step 4: Working with the MainActivity.kt file" }, { "code": null, "e": 27954, "s": 27768, "text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 27961, "s": 27954, "text": "Kotlin" }, { "code": "import android.os.Bundleimport android.widget.Buttonimport android.widget.TextViewimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { // creating variables for our text view and button lateinit var tvsec: TextView lateinit var tvMain: TextView lateinit var bac: Button lateinit var bc: Button lateinit var bbrac1: Button lateinit var bbrac2: Button lateinit var bsin: Button lateinit var bcos: Button lateinit var btan: Button lateinit var blog: Button lateinit var bln: Button lateinit var bfact: Button lateinit var bsquare: Button lateinit var bsqrt: Button lateinit var binv: Button lateinit var b0: Button lateinit var b9: Button lateinit var b8: Button lateinit var b7: Button lateinit var b6: Button lateinit var b5: Button lateinit var b4: Button lateinit var b3: Button lateinit var b2: Button lateinit var b1: Button lateinit var bpi: Button lateinit var bmul: Button lateinit var bminus: Button lateinit var bplus: Button lateinit var bequal: Button lateinit var bdot: Button lateinit var bdiv: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // initializing all our variables. tvsec = findViewById(R.id.idTVSecondary) tvMain = findViewById(R.id.idTVprimary) bac = findViewById(R.id.bac) bc = findViewById(R.id.bc) bbrac1 = findViewById(R.id.bbrac1) bbrac2 = findViewById(R.id.bbrac2) bsin = findViewById(R.id.bsin) bcos = findViewById(R.id.bcos) btan = findViewById(R.id.btan) blog = findViewById(R.id.blog) bln = findViewById(R.id.bln) bfact = findViewById(R.id.bfact) bsquare = findViewById(R.id.bsquare) bsqrt = findViewById(R.id.bsqrt) binv = findViewById(R.id.binv) b0 = findViewById(R.id.b0) b9 = findViewById(R.id.b9) b8 = findViewById(R.id.b8) b7 = findViewById(R.id.b7) b6 = findViewById(R.id.b6) b5 = findViewById(R.id.b5) b4 = findViewById(R.id.b4) b3 = findViewById(R.id.b3) b2 = findViewById(R.id.b2) b1 = findViewById(R.id.b1) bpi = findViewById(R.id.bpi) bmul = findViewById(R.id.bmul) bminus = findViewById(R.id.bminus) bplus = findViewById(R.id.bplus) bequal = findViewById(R.id.bequal) bdot = findViewById(R.id.bdot) bdiv = findViewById(R.id.bdiv) // adding on click listener to our all buttons. b1.setOnClickListener { // on below line we are appending // the expression to our text view. tvMain.text = (tvMain.text.toString() + \"1\") } b2.setOnClickListener { // on below line we are appending // the expression to our text view. tvMain.text = (tvMain.text.toString() + \"2\") } b3.setOnClickListener { // on below line we are appending // the expression to our text view. tvMain.text = (tvMain.text.toString() + \"3\") } b4.setOnClickListener { tvMain.text = (tvMain.text.toString() + \"4\") } b5.setOnClickListener { tvMain.text = (tvMain.text.toString() + \"5\") } b6.setOnClickListener { tvMain.text = (tvMain.text.toString() + \"6\") } b7.setOnClickListener { tvMain.text = (tvMain.text.toString() + \"7\") } b8.setOnClickListener { tvMain.text = (tvMain.text.toString() + \"8\") } b9.setOnClickListener { tvMain.text = (tvMain.text.toString() + \"9\") } b0.setOnClickListener { tvMain.text = (tvMain.text.toString() + \"0\") } bdot.setOnClickListener { tvMain.text = (tvMain.text.toString() + \".\") } bplus.setOnClickListener { tvMain.text = (tvMain.text.toString() + \"+\") } bdiv.setOnClickListener { tvMain.text = (tvMain.text.toString() + \"/\") } bbrac1.setOnClickListener { tvMain.text = (tvMain.text.toString() + \"(\") } bbrac2.setOnClickListener { tvMain.text = (tvMain.text.toString() + \")\") } bpi.setOnClickListener { // on clicking on pi button we are adding // pi value as 3.142 to our current value. tvMain.text = (tvMain.text.toString() + \"3.142\") tvsec.text = (bpi.text.toString()) } bsin.setOnClickListener { tvMain.text = (tvMain.text.toString() + \"sin\") } bcos.setOnClickListener { tvMain.text = (tvMain.text.toString() + \"cos\") } btan.setOnClickListener { tvMain.text = (tvMain.text.toString() + \"tan\") } binv.setOnClickListener { tvMain.text = (tvMain.text.toString() + \"^\" + \"(-1)\") } bln.setOnClickListener { tvMain.text = (tvMain.text.toString() + \"ln\") } blog.setOnClickListener { tvMain.text = (tvMain.text.toString() + \"log\") } bminus.setOnClickListener { // on clicking on minus we are checking if // the user has already a minus operation on screen. // if minus operation is already present // then we will not do anything. val str: String = tvMain.text.toString() if (!str.get(index = str.length - 1).equals(\"-\")) { tvMain.text = (tvMain.text.toString() + \"-\") } } bmul.setOnClickListener { // if mul sign is not present in our // text view then only we are adding // the multiplication operator to it. val str: String = tvMain.text.toString() if (!str.get(index = str.length - 1).equals(\"*\")) { tvMain.text = (tvMain.text.toString() + \"*\") } } bsqrt.setOnClickListener { if (tvMain.text.toString().isEmpty()) { // if the entered number is empty we are displaying an error message. Toast.makeText(this, \"Please enter a valid number..\", Toast.LENGTH_SHORT).show() } else { val str: String = tvMain.text.toString() // on below line we are calculation // square root of the given number. val r = Math.sqrt(str.toDouble()) // on below line we are converting our double // to string and then setting it to text view. val result = r.toString() tvMain.setText(result) } } bequal.setOnClickListener { val str: String = tvMain.text.toString() // on below line we are calling an evaluate // method to calculate the value of expressions. val result: Double = evaluate(str) // on below line we are getting result // and setting it to text view. val r = result.toString() tvMain.setText(r) tvsec.text = str } bac.setOnClickListener { // on clicking on ac button we are clearing // our primary and secondary text view. tvMain.setText(\"\") tvsec.setText(\"\") } bc.setOnClickListener { // on clicking on c button we are clearing // the last character by checking the length. var str: String = tvMain.text.toString() if (!str.equals(\"\")) { str = str.substring(0, str.length - 1) tvMain.text = str } } bsquare.setOnClickListener { if (tvMain.text.toString().isEmpty()) { // if the entered number is empty we are displaying an error message. Toast.makeText(this, \"Please enter a valid number..\", Toast.LENGTH_SHORT).show() } else { // on below line we are getting the expression and then calculating the square of the number val d: Double = tvMain.getText().toString().toDouble() // on below line we are calculating the square. val square = d * d // after calculating the square we // are setting it to text view. tvMain.setText(square.toString()) // on below line we are setting // the d to secondary text view. tvsec.text = \"$d2\" } } bfact.setOnClickListener { if (tvMain.text.toString().isEmpty()) { // if the entered number is empty we are displaying an error message. Toast.makeText(this, \"Please enter a valid number..\", Toast.LENGTH_SHORT).show() } else { // on below line we are getting int value // and calculating the factorial value of the entered number. val value: Int = tvMain.text.toString().toInt() val fact: Int = factorial(value) tvMain.setText(fact.toString()) tvsec.text = \"$value`!\" } } } fun factorial(n: Int): Int { // this method is use to find factorial return if (n == 1 || n == 0) 1 else n * factorial(n - 1) } fun evaluate(str: String): Double { return object : Any() { // on below line we ar creating variable // for tracking the position and char pos. var pos = -1 var ch = 0 // below method is for moving to next character. fun nextChar() { // on below line we are incrementing our position // and moving it to next position. ch = if (++pos < str.length) str[pos].toInt() else -1 } // this method is use to check the extra space // present int the expression and removing it. fun eat(charToEat: Int): Boolean { while (ch == ' '.toInt()) nextChar() // on below line we are checking the char pos // if both is equal then we are returning it to true. if (ch == charToEat) { nextChar() return true } return false } // below method is to parse our // expression and to get the ans // in this we are calling a parse // expression method to calculate the value. fun parse(): Double { nextChar() val x = parseExpression() if (pos < str.length) throw RuntimeException(\"Unexpected: \" + ch.toChar()) return x } // in this method we will only perform addition and // subtraction operation on the expression. fun parseExpression(): Double { var x = parseTerm() while (true) { if (eat('+'.toInt())) x += parseTerm() // addition else if (eat('-'.toInt())) x -= parseTerm() // subtraction else return x } } // in below method we will perform // only multiplication and division operation. fun parseTerm(): Double { var x = parseFactor() while (true) { if (eat('*'.toInt())) x *= parseFactor() // multiplication else if (eat('/'.toInt())) x /= parseFactor() // division else return x } } // below method is use to parse the factor fun parseFactor(): Double { //on below line we are checking for addition // and subtraction and performing unary operations. if (eat('+'.toInt())) return parseFactor() // unary plus if (eat('-'.toInt())) return -parseFactor() // unary minus // creating a double variable for ans. var x: Double // on below line we are creating // a variable for position. val startPos = pos // on below line we are checking // for opening and closing parenthesis. if (eat('('.toInt())) { // parentheses x = parseExpression() eat(')'.toInt()) } else if (ch >= '0'.toInt() && ch <= '9'.toInt() || ch == '.'.toInt()) { // numbers while (ch >= '0'.toInt() && ch <= '9'.toInt() || ch == '.'.toInt()) nextChar() // on below line we are getting sub string from our string using start and pos. x = str.substring(startPos, pos).toDouble() } else if (ch >= 'a'.toInt() && ch <= 'z'.toInt()) { // on below function we are checking for the operator in our expression. while (ch >= 'a'.toInt() && ch <= 'z'.toInt()) nextChar() val func = str.substring(startPos, pos) // calling a method to parse our factor. x = parseFactor() // on below line we are checking for square root. x = if (func == \"sqrt\") Math.sqrt(x) // on below line we are checking for sin function // and calculating sin function using Math class. else if (func == \"sin\") Math.sin( Math.toRadians(x) // on below line we are calculating the cos value ) else if (func == \"cos\") Math.cos( Math.toRadians(x) // on below line we are calculating // the tan value of our expression. ) else if (func == \"tan\") Math.tan(Math.toRadians(x)) // on below line we are calculating // log value of the expression. else if (func == \"log\") Math.log10(x) // on below line we are calculating // ln value of expression. else if (func == \"ln\") Math.log(x) // f we get any error then // we simply return the exception. else throw RuntimeException( \"Unknown function: $func\" ) } else { // if the condition not satisfy then we are returning the exception throw RuntimeException(\"Unexpected: \" + ch.toChar()) } // on below line we are calculating the power of the expression. if (eat('^'.toInt())) x = Math.pow(x, parseFactor()) // exponentiation return x } // at last calling a parse for our expression. }.parse() }}", "e": 43191, "s": 27961, "text": null }, { "code": null, "e": 43239, "s": 43191, "text": "Now run your app to see the output of the app. " }, { "code": null, "e": 43247, "s": 43239, "text": "Output:" }, { "code": null, "e": 43262, "s": 43247, "text": "Android-Studio" }, { "code": null, "e": 43275, "s": 43262, "text": "ProGeek 2021" }, { "code": null, "e": 43283, "s": 43275, "text": "Android" }, { "code": null, "e": 43290, "s": 43283, "text": "Kotlin" }, { "code": null, "e": 43298, "s": 43290, "text": "ProGeek" }, { "code": null, "e": 43306, "s": 43298, "text": "Project" }, { "code": null, "e": 43314, "s": 43306, "text": "Android" } ]
man command in Linux with Examples
18 Feb, 2021 man command in Linux is used to display the user manual of any command that we can run on the terminal. It provides a detailed view of the command which includes NAME, SYNOPSIS, DESCRIPTION, OPTIONS, EXIT STATUS, RETURN VALUES, ERRORS, FILES, VERSIONS, EXAMPLES, AUTHORS and SEE ALSO. Every manual is divided into the following sections: Executable programs or shell commands System calls (functions provided by the kernel) Library calls (functions within program libraries Games Special files (usually found in /dev) File formats and conventions eg /etc/passwd Miscellaneous (including macro packages and conventions), e.g. groff(7) System administration commands (usually only for root) Kernel routines [Non standard] Syntax : $man [OPTION]... [COMMAND NAME]... 1. No Option: It displays the whole manual of the command. Syntax : $ man [COMMAND NAME] Example: $ man printf Output: In this example, manual pages of the command ‘printf‘ are simply returned. 2. Section-num: Since a manual is divided into multiple sections so this option is used to display only a specific section of a manual. Syntax : $ man [SECTION-NUM] [COMMAND NAME] Example: $ man 2 intro Output: In this example, the manual pages of command ‘intro‘ are returned which lies in the section 2. 3. -f option: One may not be able to remember the sections in which a command is present. So this option gives the section in which the given command is present. Syntax: $ man -f [COMMAND NAME] Example: $ man -f ls Output: In this example, the command ‘ls‘ is returned with its section number. 4. -a option: This option helps us to display all the available intro manual pages in succession. Syntax: $ man -a [COMMAND NAME] Example: $ man -a intro Output: In this example you can move through the manual pages(sections) i.e either reading(by pressing Enter) or skipping(by pressing ctrl+D) or exiting(by pressing ctrl+C). 5. -k option: This option searches the given command as a regular expression in all the manuals and it returns the manual pages with the section number in which it is found. Syntax: $ man -k [COMMAND NAME] Example: $ man -k cd Output: The command ‘cd‘ is searched in all the manual pages by considering it as a regular expression. 6. -w option: This option returns the location in which the manual page of a given command is present. Syntax: $ man -w [COMMAND NAME] Example: $ man -w ls Output: The location of command ‘ls‘ is returned. 7. -I option: It considers the command as case sensitive. Syntax: $ man -I [COMMAND NAME] Example: $ man -I printf Output: The command ‘printf‘ is taken as case-sensitive i.e ‘printf‘ returns the manual pages but ‘Printf‘ gives error.Linux Tutorials | Getting Help and Escaping | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersLinux Tutorials | Getting Help and Escaping | GeeksforGeeksWatch laterShareCopy link8/36InfoShoppingTap 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 / 3:39•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=USMVhdydb4Y" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> linux-command Linux-misc-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. tar command in Linux with examples curl command in Linux with Examples Tail command in Linux with examples Conditional Statements | Shell Script Docker - COPY Instruction scp command in Linux with Examples UDP Server-Client implementation in C echo command in Linux with Examples Cat command in Linux with examples touch command in Linux with Examples
[ { "code": null, "e": 53, "s": 25, "text": "\n18 Feb, 2021" }, { "code": null, "e": 338, "s": 53, "text": "man command in Linux is used to display the user manual of any command that we can run on the terminal. It provides a detailed view of the command which includes NAME, SYNOPSIS, DESCRIPTION, OPTIONS, EXIT STATUS, RETURN VALUES, ERRORS, FILES, VERSIONS, EXAMPLES, AUTHORS and SEE ALSO." }, { "code": null, "e": 391, "s": 338, "text": "Every manual is divided into the following sections:" }, { "code": null, "e": 429, "s": 391, "text": "Executable programs or shell commands" }, { "code": null, "e": 477, "s": 429, "text": "System calls (functions provided by the kernel)" }, { "code": null, "e": 527, "s": 477, "text": "Library calls (functions within program libraries" }, { "code": null, "e": 533, "s": 527, "text": "Games" }, { "code": null, "e": 571, "s": 533, "text": "Special files (usually found in /dev)" }, { "code": null, "e": 615, "s": 571, "text": "File formats and conventions eg /etc/passwd" }, { "code": null, "e": 687, "s": 615, "text": "Miscellaneous (including macro packages and conventions), e.g. groff(7)" }, { "code": null, "e": 742, "s": 687, "text": "System administration commands (usually only for root)" }, { "code": null, "e": 773, "s": 742, "text": "Kernel routines [Non standard]" }, { "code": null, "e": 782, "s": 773, "text": "Syntax :" }, { "code": null, "e": 818, "s": 782, "text": "$man [OPTION]... [COMMAND NAME]...\n" }, { "code": null, "e": 877, "s": 818, "text": "1. No Option: It displays the whole manual of the command." }, { "code": null, "e": 886, "s": 877, "text": "Syntax :" }, { "code": null, "e": 908, "s": 886, "text": "$ man [COMMAND NAME]\n" }, { "code": null, "e": 917, "s": 908, "text": "Example:" }, { "code": null, "e": 930, "s": 917, "text": "$ man printf" }, { "code": null, "e": 938, "s": 930, "text": "Output:" }, { "code": null, "e": 1013, "s": 938, "text": "In this example, manual pages of the command ‘printf‘ are simply returned." }, { "code": null, "e": 1149, "s": 1013, "text": "2. Section-num: Since a manual is divided into multiple sections so this option is used to display only a specific section of a manual." }, { "code": null, "e": 1158, "s": 1149, "text": "Syntax :" }, { "code": null, "e": 1194, "s": 1158, "text": "$ man [SECTION-NUM] [COMMAND NAME]\n" }, { "code": null, "e": 1203, "s": 1194, "text": "Example:" }, { "code": null, "e": 1217, "s": 1203, "text": "$ man 2 intro" }, { "code": null, "e": 1225, "s": 1217, "text": "Output:" }, { "code": null, "e": 1320, "s": 1225, "text": "In this example, the manual pages of command ‘intro‘ are returned which lies in the section 2." }, { "code": null, "e": 1482, "s": 1320, "text": "3. -f option: One may not be able to remember the sections in which a command is present. So this option gives the section in which the given command is present." }, { "code": null, "e": 1490, "s": 1482, "text": "Syntax:" }, { "code": null, "e": 1515, "s": 1490, "text": "$ man -f [COMMAND NAME]\n" }, { "code": null, "e": 1524, "s": 1515, "text": "Example:" }, { "code": null, "e": 1536, "s": 1524, "text": "$ man -f ls" }, { "code": null, "e": 1544, "s": 1536, "text": "Output:" }, { "code": null, "e": 1615, "s": 1544, "text": "In this example, the command ‘ls‘ is returned with its section number." }, { "code": null, "e": 1713, "s": 1615, "text": "4. -a option: This option helps us to display all the available intro manual pages in succession." }, { "code": null, "e": 1721, "s": 1713, "text": "Syntax:" }, { "code": null, "e": 1746, "s": 1721, "text": "$ man -a [COMMAND NAME]\n" }, { "code": null, "e": 1755, "s": 1746, "text": "Example:" }, { "code": null, "e": 1770, "s": 1755, "text": "$ man -a intro" }, { "code": null, "e": 1778, "s": 1770, "text": "Output:" }, { "code": null, "e": 1944, "s": 1778, "text": "In this example you can move through the manual pages(sections) i.e either reading(by pressing Enter) or skipping(by pressing ctrl+D) or exiting(by pressing ctrl+C)." }, { "code": null, "e": 2118, "s": 1944, "text": "5. -k option: This option searches the given command as a regular expression in all the manuals and it returns the manual pages with the section number in which it is found." }, { "code": null, "e": 2126, "s": 2118, "text": "Syntax:" }, { "code": null, "e": 2151, "s": 2126, "text": "$ man -k [COMMAND NAME]\n" }, { "code": null, "e": 2160, "s": 2151, "text": "Example:" }, { "code": null, "e": 2172, "s": 2160, "text": "$ man -k cd" }, { "code": null, "e": 2180, "s": 2172, "text": "Output:" }, { "code": null, "e": 2276, "s": 2180, "text": "The command ‘cd‘ is searched in all the manual pages by considering it as a regular expression." }, { "code": null, "e": 2379, "s": 2276, "text": "6. -w option: This option returns the location in which the manual page of a given command is present." }, { "code": null, "e": 2387, "s": 2379, "text": "Syntax:" }, { "code": null, "e": 2412, "s": 2387, "text": "$ man -w [COMMAND NAME]\n" }, { "code": null, "e": 2421, "s": 2412, "text": "Example:" }, { "code": null, "e": 2433, "s": 2421, "text": "$ man -w ls" }, { "code": null, "e": 2441, "s": 2433, "text": "Output:" }, { "code": null, "e": 2483, "s": 2441, "text": "The location of command ‘ls‘ is returned." }, { "code": null, "e": 2541, "s": 2483, "text": "7. -I option: It considers the command as case sensitive." }, { "code": null, "e": 2549, "s": 2541, "text": "Syntax:" }, { "code": null, "e": 2574, "s": 2549, "text": "$ man -I [COMMAND NAME]\n" }, { "code": null, "e": 2583, "s": 2574, "text": "Example:" }, { "code": null, "e": 2599, "s": 2583, "text": "$ man -I printf" }, { "code": null, "e": 2607, "s": 2599, "text": "Output:" }, { "code": null, "e": 3626, "s": 2607, "text": "The command ‘printf‘ is taken as case-sensitive i.e ‘printf‘ returns the manual pages but ‘Printf‘ gives error.Linux Tutorials | Getting Help and Escaping | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersLinux Tutorials | Getting Help and Escaping | GeeksforGeeksWatch laterShareCopy link8/36InfoShoppingTap 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 / 3:39•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=USMVhdydb4Y\" 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": 3640, "s": 3626, "text": "linux-command" }, { "code": null, "e": 3660, "s": 3640, "text": "Linux-misc-commands" }, { "code": null, "e": 3667, "s": 3660, "text": "Picked" }, { "code": null, "e": 3678, "s": 3667, "text": "Linux-Unix" }, { "code": null, "e": 3776, "s": 3678, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3811, "s": 3776, "text": "tar command in Linux with examples" }, { "code": null, "e": 3847, "s": 3811, "text": "curl command in Linux with Examples" }, { "code": null, "e": 3883, "s": 3847, "text": "Tail command in Linux with examples" }, { "code": null, "e": 3921, "s": 3883, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 3947, "s": 3921, "text": "Docker - COPY Instruction" }, { "code": null, "e": 3982, "s": 3947, "text": "scp command in Linux with Examples" }, { "code": null, "e": 4020, "s": 3982, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 4056, "s": 4020, "text": "echo command in Linux with Examples" }, { "code": null, "e": 4091, "s": 4056, "text": "Cat command in Linux with examples" } ]
set add() in python
04 Sep, 2018 The set add() method adds a given element to a set if the element is not present in the set. Syntax: set.add(elem) The add() method doesn't add an element to the set if it's already present in it otherwise it will get added to the set. Parameters: add() takes single parameter(elem) which needs to be added in the set. Returns: The add() method doesn't return any value. # set of lettersGEEK = {'g', 'e', 'k'} # adding 's'GEEK.add('s')print('Letters are:', GEEK) # adding 's' againGEEK.add('s')print('Letters are:', GEEK) Output: ('Letters are:', set(['k', 'e', 's', 'g'])) ('Letters are:', set(['k', 'e', 's', 'g']) Application: It is used to add a new element to the set. # set of lettersGEEK = {6, 0, 4} # adding 1GEEK.add(1)print('Letters are:', GEEK) # adding 0 GEEK.add(0)print('Letters are:', GEEK) Output: ('Letters are:', set([0, 1, 4, 6])) ('Letters are:', set([0, 1, 4, 6])) Adding tuple to a set: # Python code to demonstrate addition of tuple to a set.s = {'g', 'e', 'e', 'k', 's'}t = ('f', 'o') # adding tuple t to set s.s.add(t) print(s) Output : {'k', 's', 'e', 'g', ('f', 'o')} python-set Python python-set Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function Python Dictionary How to get column names in Pandas dataframe Taking input in Python Enumerate() in Python Different ways to create Pandas Dataframe Read a file line by line in Python How to Install PIP on Windows ?
[ { "code": null, "e": 54, "s": 26, "text": "\n04 Sep, 2018" }, { "code": null, "e": 147, "s": 54, "text": "The set add() method adds a given element to a set if the element is not present in the set." }, { "code": null, "e": 155, "s": 147, "text": "Syntax:" }, { "code": null, "e": 428, "s": 155, "text": "set.add(elem)\nThe add() method doesn't add an element to the\nset if it's already present in it otherwise it \nwill get added to the set.\nParameters:\nadd() takes single parameter(elem) which needs to \nbe added in the set.\nReturns:\nThe add() method doesn't return any value.\n" }, { "code": "# set of lettersGEEK = {'g', 'e', 'k'} # adding 's'GEEK.add('s')print('Letters are:', GEEK) # adding 's' againGEEK.add('s')print('Letters are:', GEEK)", "e": 581, "s": 428, "text": null }, { "code": null, "e": 589, "s": 581, "text": "Output:" }, { "code": null, "e": 677, "s": 589, "text": "('Letters are:', set(['k', 'e', 's', 'g']))\n('Letters are:', set(['k', 'e', 's', 'g'])\n" }, { "code": null, "e": 690, "s": 677, "text": "Application:" }, { "code": null, "e": 736, "s": 690, "text": "It is used to add a new element to the set. \n" }, { "code": "# set of lettersGEEK = {6, 0, 4} # adding 1GEEK.add(1)print('Letters are:', GEEK) # adding 0 GEEK.add(0)print('Letters are:', GEEK)", "e": 870, "s": 736, "text": null }, { "code": null, "e": 878, "s": 870, "text": "Output:" }, { "code": null, "e": 951, "s": 878, "text": "('Letters are:', set([0, 1, 4, 6]))\n('Letters are:', set([0, 1, 4, 6]))\n" }, { "code": null, "e": 974, "s": 951, "text": "Adding tuple to a set:" }, { "code": "# Python code to demonstrate addition of tuple to a set.s = {'g', 'e', 'e', 'k', 's'}t = ('f', 'o') # adding tuple t to set s.s.add(t) print(s)", "e": 1120, "s": 974, "text": null }, { "code": null, "e": 1129, "s": 1120, "text": "Output :" }, { "code": null, "e": 1163, "s": 1129, "text": "{'k', 's', 'e', 'g', ('f', 'o')}\n" }, { "code": null, "e": 1174, "s": 1163, "text": "python-set" }, { "code": null, "e": 1181, "s": 1174, "text": "Python" }, { "code": null, "e": 1192, "s": 1181, "text": "python-set" }, { "code": null, "e": 1290, "s": 1192, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1318, "s": 1290, "text": "Read JSON file using Python" }, { "code": null, "e": 1368, "s": 1318, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 1390, "s": 1368, "text": "Python map() function" }, { "code": null, "e": 1408, "s": 1390, "text": "Python Dictionary" }, { "code": null, "e": 1452, "s": 1408, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 1475, "s": 1452, "text": "Taking input in Python" }, { "code": null, "e": 1497, "s": 1475, "text": "Enumerate() in Python" }, { "code": null, "e": 1539, "s": 1497, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1574, "s": 1539, "text": "Read a file line by line in Python" } ]
std::nth_element in C++
26 Jul, 2017 std::nth_element() is an STL algorithm which rearranges the list in such a way such that the element at the nth position is the one which should be at that position if we sort the list. It does not sort the list, just that all the elements, which precede the nth element are not greater than it, and all the elements which succeed it are not less than it.It has two versions, which are defined below: Comparing elements using “<":Syntax:template void nth_element (RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last); first: Random-access iterator to the first element in the list. last: Random-access iterator to the last element in the list. nth: Random-access iterator pointing to the position in the list, which should be sorted. If it points to end, then this function will do nothing. Return Value: Since, return type is void, so it doesnot return any value. // C++ program to demonstrate the use of std::nth_element#include <iostream>#include <algorithm>using namespace std;int main(){ int v[] = { 3, 2, 10, 45, 33, 56, 23, 47 }, i; // Using std::nth_element with n as 5 std::nth_element(v, v + 4, v + 8); // Since, n is 5 so 5th element should be sorted for (i = 0; i < 8; ++i) { cout << v[i] << " "; } return 0;}Output:3 2 10 23 33 56 45 47 Here, the fifth element is 33, and all elements to its left are smaller than it and all elements to its right are greater than it.By comparing using a pre-defined function:Syntax:template void nth_element (RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last, Compare comp); Here, first, last and nth arguments are the same as previous case. comp: Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines. The function shall not modify any of its arguments. This can either be a function pointer or a function object. Return Value: Since, its return type is void, so it doesnot return any value. // C++ program to demonstrate the use of std::nth_element#include <iostream>#include <algorithm>using namespace std; // Defining the BinaryFunctionbool comp(int a, int b){ return (a < b);}int main(){ int v[] = { 3, 2, 10, 45, 33, 56, 23, 47 }, i; // Using std::nth_element with n as 6 std::nth_element(v, v + 5, v + 8, comp); // Since, n is 6 so 6th element should be the same // as the sixth element present if we sort this array // Sorted Array /* 2 3 10 23 33 45 47 56 */ for (i = 0; i < 8; ++i) { cout << v[i] << " "; } return 0;}Output:33 2 10 23 3 45 47 56 In this code, since the nth element as pointed by the second argument in std::nth_element is the sixth element of the array v, so this means that the sixth element in the array after application of std::nth_element should be the one that would have been there if the whole array was sorted, i.e., 45.And also all the element to its left are either less than it or equal to it and elements on its right are greater than it.Purpose of Binary Function comp: std::nth_element partially sorts the range [first, last) in ascending order so that the condition, *i < *j, (for version 1 ), or comp(*i, *j) == true (for version 2) is met for any i in the range [first, nth) and for any j in the range [nth, last). So, comp() is used to ensure that all the elements before the nth_element are less than elements after the nth_element. Comparing elements using “<":Syntax:template void nth_element (RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last); first: Random-access iterator to the first element in the list. last: Random-access iterator to the last element in the list. nth: Random-access iterator pointing to the position in the list, which should be sorted. If it points to end, then this function will do nothing. Return Value: Since, return type is void, so it doesnot return any value. // C++ program to demonstrate the use of std::nth_element#include <iostream>#include <algorithm>using namespace std;int main(){ int v[] = { 3, 2, 10, 45, 33, 56, 23, 47 }, i; // Using std::nth_element with n as 5 std::nth_element(v, v + 4, v + 8); // Since, n is 5 so 5th element should be sorted for (i = 0; i < 8; ++i) { cout << v[i] << " "; } return 0;}Output:3 2 10 23 33 56 45 47 Here, the fifth element is 33, and all elements to its left are smaller than it and all elements to its right are greater than it. template void nth_element (RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last); first: Random-access iterator to the first element in the list. last: Random-access iterator to the last element in the list. nth: Random-access iterator pointing to the position in the list, which should be sorted. If it points to end, then this function will do nothing. Return Value: Since, return type is void, so it doesnot return any value. // C++ program to demonstrate the use of std::nth_element#include <iostream>#include <algorithm>using namespace std;int main(){ int v[] = { 3, 2, 10, 45, 33, 56, 23, 47 }, i; // Using std::nth_element with n as 5 std::nth_element(v, v + 4, v + 8); // Since, n is 5 so 5th element should be sorted for (i = 0; i < 8; ++i) { cout << v[i] << " "; } return 0;} Output: 3 2 10 23 33 56 45 47 Here, the fifth element is 33, and all elements to its left are smaller than it and all elements to its right are greater than it. By comparing using a pre-defined function:Syntax:template void nth_element (RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last, Compare comp); Here, first, last and nth arguments are the same as previous case. comp: Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines. The function shall not modify any of its arguments. This can either be a function pointer or a function object. Return Value: Since, its return type is void, so it doesnot return any value. // C++ program to demonstrate the use of std::nth_element#include <iostream>#include <algorithm>using namespace std; // Defining the BinaryFunctionbool comp(int a, int b){ return (a < b);}int main(){ int v[] = { 3, 2, 10, 45, 33, 56, 23, 47 }, i; // Using std::nth_element with n as 6 std::nth_element(v, v + 5, v + 8, comp); // Since, n is 6 so 6th element should be the same // as the sixth element present if we sort this array // Sorted Array /* 2 3 10 23 33 45 47 56 */ for (i = 0; i < 8; ++i) { cout << v[i] << " "; } return 0;}Output:33 2 10 23 3 45 47 56 In this code, since the nth element as pointed by the second argument in std::nth_element is the sixth element of the array v, so this means that the sixth element in the array after application of std::nth_element should be the one that would have been there if the whole array was sorted, i.e., 45.And also all the element to its left are either less than it or equal to it and elements on its right are greater than it.Purpose of Binary Function comp: std::nth_element partially sorts the range [first, last) in ascending order so that the condition, *i < *j, (for version 1 ), or comp(*i, *j) == true (for version 2) is met for any i in the range [first, nth) and for any j in the range [nth, last). So, comp() is used to ensure that all the elements before the nth_element are less than elements after the nth_element. Syntax: template void nth_element (RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last, Compare comp); Here, first, last and nth arguments are the same as previous case. comp: Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines. The function shall not modify any of its arguments. This can either be a function pointer or a function object. Return Value: Since, its return type is void, so it doesnot return any value. // C++ program to demonstrate the use of std::nth_element#include <iostream>#include <algorithm>using namespace std; // Defining the BinaryFunctionbool comp(int a, int b){ return (a < b);}int main(){ int v[] = { 3, 2, 10, 45, 33, 56, 23, 47 }, i; // Using std::nth_element with n as 6 std::nth_element(v, v + 5, v + 8, comp); // Since, n is 6 so 6th element should be the same // as the sixth element present if we sort this array // Sorted Array /* 2 3 10 23 33 45 47 56 */ for (i = 0; i < 8; ++i) { cout << v[i] << " "; } return 0;} Output: 33 2 10 23 3 45 47 56 In this code, since the nth element as pointed by the second argument in std::nth_element is the sixth element of the array v, so this means that the sixth element in the array after application of std::nth_element should be the one that would have been there if the whole array was sorted, i.e., 45. And also all the element to its left are either less than it or equal to it and elements on its right are greater than it. Purpose of Binary Function comp: std::nth_element partially sorts the range [first, last) in ascending order so that the condition, *i < *j, (for version 1 ), or comp(*i, *j) == true (for version 2) is met for any i in the range [first, nth) and for any j in the range [nth, last). So, comp() is used to ensure that all the elements before the nth_element are less than elements after the nth_element. Where can we apply std::nth_element() ? It can be used if we want to find the first n smallest numbers, but they may or maynot be ordered.// C++ program to find first n smallest numbers#include <iostream>#include <algorithm>using namespace std;int main(){ int v[] = { 30, 20, 10, 40, 60, 50, 70, 80 }, i; // Using std::nth_element with n as 3 std::nth_element(v, v + 2, v + 8); // Since, n is 3 so now first three numbers will be the // three smallest numbers in the whole array // Displaying first three smallest number for (i = 0; i < 3; ++i) { cout << v[i] << " "; } return 0;}Output:20 10 30 Just like first n smallest number, we can also find first n largest numbers, by just changing the Binary Function passed as argument in std::nth_element.// C++ program to find first n largest numbers#include <iostream>#include <algorithm>using namespace std;int main(){ int v[] = { 30, 20, 50, 60, 70, 10, 80, 40 }, i; // Using std::nth_element with n as 2 std::nth_element(v, v + 1, v + 8, std::greater<int>()); // Since, n is 2 so first 2 elements will be the largest // among all the array elements // Displaying First 2 elements for (i = 0; i < 2; ++i) { cout << v[i] << " "; } return 0;}Output:80 70 Here, we have passed greater() as binary function, so now nth element will be the one which should be at the nth place if we sort the given array in descending order, so first n elements will be the first n largest elements.It can be used to find the median of the elements given.// C++ program to find the median of the vector#include <iostream>#include <algorithm>#include <vector>using namespace std;int main(){ vector<int> v = { 3, 2, 10, 45, 33, 56, 23, 47, 60 }, i; // Using std::nth_element with n as v.size()/2 + 1 std::nth_element(v.begin(), v.begin() + v.size() / 2, v.end()); cout << "The median of the array is " << v[v.size() / 2]; return 0;}Output:The median of the array is 33 Here the sorted array will be 2 3 10 23 33 45 47 56 60, so there are 9 elements and the median will be the middle element, i.e., 5th element : 33. It can be used if we want to find the first n smallest numbers, but they may or maynot be ordered.// C++ program to find first n smallest numbers#include <iostream>#include <algorithm>using namespace std;int main(){ int v[] = { 30, 20, 10, 40, 60, 50, 70, 80 }, i; // Using std::nth_element with n as 3 std::nth_element(v, v + 2, v + 8); // Since, n is 3 so now first three numbers will be the // three smallest numbers in the whole array // Displaying first three smallest number for (i = 0; i < 3; ++i) { cout << v[i] << " "; } return 0;}Output:20 10 30 // C++ program to find first n smallest numbers#include <iostream>#include <algorithm>using namespace std;int main(){ int v[] = { 30, 20, 10, 40, 60, 50, 70, 80 }, i; // Using std::nth_element with n as 3 std::nth_element(v, v + 2, v + 8); // Since, n is 3 so now first three numbers will be the // three smallest numbers in the whole array // Displaying first three smallest number for (i = 0; i < 3; ++i) { cout << v[i] << " "; } return 0;} Output: 20 10 30 Just like first n smallest number, we can also find first n largest numbers, by just changing the Binary Function passed as argument in std::nth_element.// C++ program to find first n largest numbers#include <iostream>#include <algorithm>using namespace std;int main(){ int v[] = { 30, 20, 50, 60, 70, 10, 80, 40 }, i; // Using std::nth_element with n as 2 std::nth_element(v, v + 1, v + 8, std::greater<int>()); // Since, n is 2 so first 2 elements will be the largest // among all the array elements // Displaying First 2 elements for (i = 0; i < 2; ++i) { cout << v[i] << " "; } return 0;}Output:80 70 Here, we have passed greater() as binary function, so now nth element will be the one which should be at the nth place if we sort the given array in descending order, so first n elements will be the first n largest elements. // C++ program to find first n largest numbers#include <iostream>#include <algorithm>using namespace std;int main(){ int v[] = { 30, 20, 50, 60, 70, 10, 80, 40 }, i; // Using std::nth_element with n as 2 std::nth_element(v, v + 1, v + 8, std::greater<int>()); // Since, n is 2 so first 2 elements will be the largest // among all the array elements // Displaying First 2 elements for (i = 0; i < 2; ++i) { cout << v[i] << " "; } return 0;} Output: 80 70 Here, we have passed greater() as binary function, so now nth element will be the one which should be at the nth place if we sort the given array in descending order, so first n elements will be the first n largest elements. It can be used to find the median of the elements given.// C++ program to find the median of the vector#include <iostream>#include <algorithm>#include <vector>using namespace std;int main(){ vector<int> v = { 3, 2, 10, 45, 33, 56, 23, 47, 60 }, i; // Using std::nth_element with n as v.size()/2 + 1 std::nth_element(v.begin(), v.begin() + v.size() / 2, v.end()); cout << "The median of the array is " << v[v.size() / 2]; return 0;}Output:The median of the array is 33 Here the sorted array will be 2 3 10 23 33 45 47 56 60, so there are 9 elements and the median will be the middle element, i.e., 5th element : 33. // C++ program to find the median of the vector#include <iostream>#include <algorithm>#include <vector>using namespace std;int main(){ vector<int> v = { 3, 2, 10, 45, 33, 56, 23, 47, 60 }, i; // Using std::nth_element with n as v.size()/2 + 1 std::nth_element(v.begin(), v.begin() + v.size() / 2, v.end()); cout << "The median of the array is " << v[v.size() / 2]; return 0;} Output: The median of the array is 33 Here the sorted array will be 2 3 10 23 33 45 47 56 60, so there are 9 elements and the median will be the middle element, i.e., 5th element : 33. Time Complexity of std::nth_element(): O(n), with n being the distance between first and the last.Related Articles: std::search std::find std::find_if, std::find_if_not std::find_end std::sort This article is contributed by Mrigendra Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. cpp-algorithm-library STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n26 Jul, 2017" }, { "code": null, "e": 240, "s": 54, "text": "std::nth_element() is an STL algorithm which rearranges the list in such a way such that the element at the nth position is the one which should be at that position if we sort the list." }, { "code": null, "e": 455, "s": 240, "text": "It does not sort the list, just that all the elements, which precede the nth element are not greater than it, and all the elements which succeed it are not less than it.It has two versions, which are defined below:" }, { "code": null, "e": 3680, "s": 455, "text": "Comparing elements using “<\":Syntax:template \nvoid nth_element (RandomAccessIterator first, RandomAccessIterator nth,\n RandomAccessIterator last);\n\nfirst: Random-access iterator to the first element in the list.\nlast: Random-access iterator to the last element in the list.\nnth: Random-access iterator pointing to the position in the list, \nwhich should be sorted.\nIf it points to end, then this function will do nothing.\n\nReturn Value: Since, return type is void, so it doesnot return any value.\n// C++ program to demonstrate the use of std::nth_element#include <iostream>#include <algorithm>using namespace std;int main(){ int v[] = { 3, 2, 10, 45, 33, 56, 23, 47 }, i; // Using std::nth_element with n as 5 std::nth_element(v, v + 4, v + 8); // Since, n is 5 so 5th element should be sorted for (i = 0; i < 8; ++i) { cout << v[i] << \" \"; } return 0;}Output:3 2 10 23 33 56 45 47 \nHere, the fifth element is 33, and all elements to its left are smaller than it and all elements to its right are greater than it.By comparing using a pre-defined function:Syntax:template \nvoid nth_element (RandomAccessIterator first, RandomAccessIterator nth,\n RandomAccessIterator last, Compare comp);\n\nHere, first, last and nth arguments are the same as previous case.\n\ncomp: Binary function that accepts two elements in the range \nas arguments, and returns a value convertible to bool.\nThe value returned indicates whether the element passed as first argument is \nconsidered to go before the second in the specific strict weak ordering it defines.\nThe function shall not modify any of its arguments.\nThis can either be a function pointer or a function object.\n\nReturn Value: Since, its return type is void, so it doesnot return any value.\n// C++ program to demonstrate the use of std::nth_element#include <iostream>#include <algorithm>using namespace std; // Defining the BinaryFunctionbool comp(int a, int b){ return (a < b);}int main(){ int v[] = { 3, 2, 10, 45, 33, 56, 23, 47 }, i; // Using std::nth_element with n as 6 std::nth_element(v, v + 5, v + 8, comp); // Since, n is 6 so 6th element should be the same // as the sixth element present if we sort this array // Sorted Array /* 2 3 10 23 33 45 47 56 */ for (i = 0; i < 8; ++i) { cout << v[i] << \" \"; } return 0;}Output:33 2 10 23 3 45 47 56 \nIn this code, since the nth element as pointed by the second argument in std::nth_element is the sixth element of the array v, so this means that the sixth element in the array after application of std::nth_element should be the one that would have been there if the whole array was sorted, i.e., 45.And also all the element to its left are either less than it or equal to it and elements on its right are greater than it.Purpose of Binary Function comp: std::nth_element partially sorts the range [first, last) in ascending order so that the condition, *i < *j, (for version 1 ), or comp(*i, *j) == true (for version 2) is met for any i in the range [first, nth) and for any j in the range [nth, last). So, comp() is used to ensure that all the elements before the nth_element are less than elements after the nth_element." }, { "code": null, "e": 4743, "s": 3680, "text": "Comparing elements using “<\":Syntax:template \nvoid nth_element (RandomAccessIterator first, RandomAccessIterator nth,\n RandomAccessIterator last);\n\nfirst: Random-access iterator to the first element in the list.\nlast: Random-access iterator to the last element in the list.\nnth: Random-access iterator pointing to the position in the list, \nwhich should be sorted.\nIf it points to end, then this function will do nothing.\n\nReturn Value: Since, return type is void, so it doesnot return any value.\n// C++ program to demonstrate the use of std::nth_element#include <iostream>#include <algorithm>using namespace std;int main(){ int v[] = { 3, 2, 10, 45, 33, 56, 23, 47 }, i; // Using std::nth_element with n as 5 std::nth_element(v, v + 4, v + 8); // Since, n is 5 so 5th element should be sorted for (i = 0; i < 8; ++i) { cout << v[i] << \" \"; } return 0;}Output:3 2 10 23 33 56 45 47 \nHere, the fifth element is 33, and all elements to its left are smaller than it and all elements to its right are greater than it." }, { "code": null, "e": 5222, "s": 4743, "text": "template \nvoid nth_element (RandomAccessIterator first, RandomAccessIterator nth,\n RandomAccessIterator last);\n\nfirst: Random-access iterator to the first element in the list.\nlast: Random-access iterator to the last element in the list.\nnth: Random-access iterator pointing to the position in the list, \nwhich should be sorted.\nIf it points to end, then this function will do nothing.\n\nReturn Value: Since, return type is void, so it doesnot return any value.\n" }, { "code": "// C++ program to demonstrate the use of std::nth_element#include <iostream>#include <algorithm>using namespace std;int main(){ int v[] = { 3, 2, 10, 45, 33, 56, 23, 47 }, i; // Using std::nth_element with n as 5 std::nth_element(v, v + 4, v + 8); // Since, n is 5 so 5th element should be sorted for (i = 0; i < 8; ++i) { cout << v[i] << \" \"; } return 0;}", "e": 5611, "s": 5222, "text": null }, { "code": null, "e": 5619, "s": 5611, "text": "Output:" }, { "code": null, "e": 5643, "s": 5619, "text": "3 2 10 23 33 56 45 47 \n" }, { "code": null, "e": 5774, "s": 5643, "text": "Here, the fifth element is 33, and all elements to its left are smaller than it and all elements to its right are greater than it." }, { "code": null, "e": 7937, "s": 5774, "text": "By comparing using a pre-defined function:Syntax:template \nvoid nth_element (RandomAccessIterator first, RandomAccessIterator nth,\n RandomAccessIterator last, Compare comp);\n\nHere, first, last and nth arguments are the same as previous case.\n\ncomp: Binary function that accepts two elements in the range \nas arguments, and returns a value convertible to bool.\nThe value returned indicates whether the element passed as first argument is \nconsidered to go before the second in the specific strict weak ordering it defines.\nThe function shall not modify any of its arguments.\nThis can either be a function pointer or a function object.\n\nReturn Value: Since, its return type is void, so it doesnot return any value.\n// C++ program to demonstrate the use of std::nth_element#include <iostream>#include <algorithm>using namespace std; // Defining the BinaryFunctionbool comp(int a, int b){ return (a < b);}int main(){ int v[] = { 3, 2, 10, 45, 33, 56, 23, 47 }, i; // Using std::nth_element with n as 6 std::nth_element(v, v + 5, v + 8, comp); // Since, n is 6 so 6th element should be the same // as the sixth element present if we sort this array // Sorted Array /* 2 3 10 23 33 45 47 56 */ for (i = 0; i < 8; ++i) { cout << v[i] << \" \"; } return 0;}Output:33 2 10 23 3 45 47 56 \nIn this code, since the nth element as pointed by the second argument in std::nth_element is the sixth element of the array v, so this means that the sixth element in the array after application of std::nth_element should be the one that would have been there if the whole array was sorted, i.e., 45.And also all the element to its left are either less than it or equal to it and elements on its right are greater than it.Purpose of Binary Function comp: std::nth_element partially sorts the range [first, last) in ascending order so that the condition, *i < *j, (for version 1 ), or comp(*i, *j) == true (for version 2) is met for any i in the range [first, nth) and for any j in the range [nth, last). So, comp() is used to ensure that all the elements before the nth_element are less than elements after the nth_element." }, { "code": null, "e": 7945, "s": 7937, "text": "Syntax:" }, { "code": null, "e": 8627, "s": 7945, "text": "template \nvoid nth_element (RandomAccessIterator first, RandomAccessIterator nth,\n RandomAccessIterator last, Compare comp);\n\nHere, first, last and nth arguments are the same as previous case.\n\ncomp: Binary function that accepts two elements in the range \nas arguments, and returns a value convertible to bool.\nThe value returned indicates whether the element passed as first argument is \nconsidered to go before the second in the specific strict weak ordering it defines.\nThe function shall not modify any of its arguments.\nThis can either be a function pointer or a function object.\n\nReturn Value: Since, its return type is void, so it doesnot return any value.\n" }, { "code": "// C++ program to demonstrate the use of std::nth_element#include <iostream>#include <algorithm>using namespace std; // Defining the BinaryFunctionbool comp(int a, int b){ return (a < b);}int main(){ int v[] = { 3, 2, 10, 45, 33, 56, 23, 47 }, i; // Using std::nth_element with n as 6 std::nth_element(v, v + 5, v + 8, comp); // Since, n is 6 so 6th element should be the same // as the sixth element present if we sort this array // Sorted Array /* 2 3 10 23 33 45 47 56 */ for (i = 0; i < 8; ++i) { cout << v[i] << \" \"; } return 0;}", "e": 9207, "s": 8627, "text": null }, { "code": null, "e": 9215, "s": 9207, "text": "Output:" }, { "code": null, "e": 9239, "s": 9215, "text": "33 2 10 23 3 45 47 56 \n" }, { "code": null, "e": 9540, "s": 9239, "text": "In this code, since the nth element as pointed by the second argument in std::nth_element is the sixth element of the array v, so this means that the sixth element in the array after application of std::nth_element should be the one that would have been there if the whole array was sorted, i.e., 45." }, { "code": null, "e": 9663, "s": 9540, "text": "And also all the element to its left are either less than it or equal to it and elements on its right are greater than it." }, { "code": null, "e": 10065, "s": 9663, "text": "Purpose of Binary Function comp: std::nth_element partially sorts the range [first, last) in ascending order so that the condition, *i < *j, (for version 1 ), or comp(*i, *j) == true (for version 2) is met for any i in the range [first, nth) and for any j in the range [nth, last). So, comp() is used to ensure that all the elements before the nth_element are less than elements after the nth_element." }, { "code": null, "e": 10105, "s": 10065, "text": "Where can we apply std::nth_element() ?" }, { "code": null, "e": 12210, "s": 10105, "text": "It can be used if we want to find the first n smallest numbers, but they may or maynot be ordered.// C++ program to find first n smallest numbers#include <iostream>#include <algorithm>using namespace std;int main(){ int v[] = { 30, 20, 10, 40, 60, 50, 70, 80 }, i; // Using std::nth_element with n as 3 std::nth_element(v, v + 2, v + 8); // Since, n is 3 so now first three numbers will be the // three smallest numbers in the whole array // Displaying first three smallest number for (i = 0; i < 3; ++i) { cout << v[i] << \" \"; } return 0;}Output:20 10 30\nJust like first n smallest number, we can also find first n largest numbers, by just changing the Binary Function passed as argument in std::nth_element.// C++ program to find first n largest numbers#include <iostream>#include <algorithm>using namespace std;int main(){ int v[] = { 30, 20, 50, 60, 70, 10, 80, 40 }, i; // Using std::nth_element with n as 2 std::nth_element(v, v + 1, v + 8, std::greater<int>()); // Since, n is 2 so first 2 elements will be the largest // among all the array elements // Displaying First 2 elements for (i = 0; i < 2; ++i) { cout << v[i] << \" \"; } return 0;}Output:80 70\nHere, we have passed greater() as binary function, so now nth element will be the one which should be at the nth place if we sort the given array in descending order, so first n elements will be the first n largest elements.It can be used to find the median of the elements given.// C++ program to find the median of the vector#include <iostream>#include <algorithm>#include <vector>using namespace std;int main(){ vector<int> v = { 3, 2, 10, 45, 33, 56, 23, 47, 60 }, i; // Using std::nth_element with n as v.size()/2 + 1 std::nth_element(v.begin(), v.begin() + v.size() / 2, v.end()); cout << \"The median of the array is \" << v[v.size() / 2]; return 0;}Output:The median of the array is 33\nHere the sorted array will be 2 3 10 23 33 45 47 56 60, so there are 9 elements and the median will be the middle element, i.e., 5th element : 33." }, { "code": null, "e": 12809, "s": 12210, "text": "It can be used if we want to find the first n smallest numbers, but they may or maynot be ordered.// C++ program to find first n smallest numbers#include <iostream>#include <algorithm>using namespace std;int main(){ int v[] = { 30, 20, 10, 40, 60, 50, 70, 80 }, i; // Using std::nth_element with n as 3 std::nth_element(v, v + 2, v + 8); // Since, n is 3 so now first three numbers will be the // three smallest numbers in the whole array // Displaying first three smallest number for (i = 0; i < 3; ++i) { cout << v[i] << \" \"; } return 0;}Output:20 10 30\n" }, { "code": "// C++ program to find first n smallest numbers#include <iostream>#include <algorithm>using namespace std;int main(){ int v[] = { 30, 20, 10, 40, 60, 50, 70, 80 }, i; // Using std::nth_element with n as 3 std::nth_element(v, v + 2, v + 8); // Since, n is 3 so now first three numbers will be the // three smallest numbers in the whole array // Displaying first three smallest number for (i = 0; i < 3; ++i) { cout << v[i] << \" \"; } return 0;}", "e": 13294, "s": 12809, "text": null }, { "code": null, "e": 13302, "s": 13294, "text": "Output:" }, { "code": null, "e": 13312, "s": 13302, "text": "20 10 30\n" }, { "code": null, "e": 14184, "s": 13312, "text": "Just like first n smallest number, we can also find first n largest numbers, by just changing the Binary Function passed as argument in std::nth_element.// C++ program to find first n largest numbers#include <iostream>#include <algorithm>using namespace std;int main(){ int v[] = { 30, 20, 50, 60, 70, 10, 80, 40 }, i; // Using std::nth_element with n as 2 std::nth_element(v, v + 1, v + 8, std::greater<int>()); // Since, n is 2 so first 2 elements will be the largest // among all the array elements // Displaying First 2 elements for (i = 0; i < 2; ++i) { cout << v[i] << \" \"; } return 0;}Output:80 70\nHere, we have passed greater() as binary function, so now nth element will be the one which should be at the nth place if we sort the given array in descending order, so first n elements will be the first n largest elements." }, { "code": "// C++ program to find first n largest numbers#include <iostream>#include <algorithm>using namespace std;int main(){ int v[] = { 30, 20, 50, 60, 70, 10, 80, 40 }, i; // Using std::nth_element with n as 2 std::nth_element(v, v + 1, v + 8, std::greater<int>()); // Since, n is 2 so first 2 elements will be the largest // among all the array elements // Displaying First 2 elements for (i = 0; i < 2; ++i) { cout << v[i] << \" \"; } return 0;}", "e": 14666, "s": 14184, "text": null }, { "code": null, "e": 14674, "s": 14666, "text": "Output:" }, { "code": null, "e": 14681, "s": 14674, "text": "80 70\n" }, { "code": null, "e": 14906, "s": 14681, "text": "Here, we have passed greater() as binary function, so now nth element will be the one which should be at the nth place if we sort the given array in descending order, so first n elements will be the first n largest elements." }, { "code": null, "e": 15542, "s": 14906, "text": "It can be used to find the median of the elements given.// C++ program to find the median of the vector#include <iostream>#include <algorithm>#include <vector>using namespace std;int main(){ vector<int> v = { 3, 2, 10, 45, 33, 56, 23, 47, 60 }, i; // Using std::nth_element with n as v.size()/2 + 1 std::nth_element(v.begin(), v.begin() + v.size() / 2, v.end()); cout << \"The median of the array is \" << v[v.size() / 2]; return 0;}Output:The median of the array is 33\nHere the sorted array will be 2 3 10 23 33 45 47 56 60, so there are 9 elements and the median will be the middle element, i.e., 5th element : 33." }, { "code": "// C++ program to find the median of the vector#include <iostream>#include <algorithm>#include <vector>using namespace std;int main(){ vector<int> v = { 3, 2, 10, 45, 33, 56, 23, 47, 60 }, i; // Using std::nth_element with n as v.size()/2 + 1 std::nth_element(v.begin(), v.begin() + v.size() / 2, v.end()); cout << \"The median of the array is \" << v[v.size() / 2]; return 0;}", "e": 15939, "s": 15542, "text": null }, { "code": null, "e": 15947, "s": 15939, "text": "Output:" }, { "code": null, "e": 15978, "s": 15947, "text": "The median of the array is 33\n" }, { "code": null, "e": 16125, "s": 15978, "text": "Here the sorted array will be 2 3 10 23 33 45 47 56 60, so there are 9 elements and the median will be the middle element, i.e., 5th element : 33." }, { "code": null, "e": 16241, "s": 16125, "text": "Time Complexity of std::nth_element(): O(n), with n being the distance between first and the last.Related Articles:" }, { "code": null, "e": 16253, "s": 16241, "text": "std::search" }, { "code": null, "e": 16263, "s": 16253, "text": "std::find" }, { "code": null, "e": 16294, "s": 16263, "text": "std::find_if, std::find_if_not" }, { "code": null, "e": 16308, "s": 16294, "text": "std::find_end" }, { "code": null, "e": 16318, "s": 16308, "text": "std::sort" }, { "code": null, "e": 16621, "s": 16318, "text": "This article is contributed by Mrigendra Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 16746, "s": 16621, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 16768, "s": 16746, "text": "cpp-algorithm-library" }, { "code": null, "e": 16772, "s": 16768, "text": "STL" }, { "code": null, "e": 16776, "s": 16772, "text": "C++" }, { "code": null, "e": 16780, "s": 16776, "text": "STL" }, { "code": null, "e": 16784, "s": 16780, "text": "CPP" } ]
How to Create Dynamic GridView in Android using Firebase Firestore?
17 Jan, 2021 GridView is also one of the most used UI components which is used to display items in the Grid format inside our app. By using this type of view we can display the items in the grid format. We have seen this type of GridView in most of the apps. We have also seen the implementation of GridView in our app. In this article, we will take a look at the implementation of GridView using Firebase Firestore in Android. We will be building a simple application in which we will be displaying the data in the grid format and we will load this data from Firebase Firestore inside our GridView. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Step 1: Create a new Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Connect your app to Firebase After creating a new project navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot. Inside that column Navigate to Firebase Cloud Firestore. Click on that option and you will get to see two options on Connect app to Firebase and Add Cloud Firestore to your app. Click on Connect now option and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase. After connecting your app to Firebase you will get to see the below screen. After that verify that dependency for the Firebase Firestore database has been added to our Gradle file. Navigate to the app > Gradle Scripts inside that file to check whether the below dependency is added or not. If the below dependency is not present in your build.gradle file. Add the below dependency in the dependencies section. implementation ‘com.google.firebase:firebase-firestore:22.0.1’ After adding this dependency sync your project and now we are ready for creating our app. If you want to know more about connecting your app to Firebase. Refer to this article to get in detail about How to add Firebase to Android App. Step 3: Working with the AndroidManifest.xml file For adding data to Firebase we should have to give permissions for accessing the internet. For adding these permissions navigate to the app > AndroidManifest.xml and Inside that file add the below permissions to it. XML <!--Permissions for internet--><uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> Step 4: Working with the activity_main.xml file Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <!--Grid View for displaying our data from Firebase--> <GridView android:id="@+id/idGVCourses" android:layout_width="match_parent" android:layout_height="match_parent" android:numColumns="2" /> </RelativeLayout> Step 5: Now we will create a new Java class for storing our data For reading data from the Firebase Firestore database, we have to create an Object class and we will read data inside this class. For creating an object class, navigate to the app > java > your app’s package name > Right-click on it and click on New > Java Class > Give a name to your class. Here we have given the name as DataModal and add the below code to it. Java public class DataModal { // variables for storing our image and name. private String name; private String imgUrl; public DataModal() { // empty constructor required for firebase. } // constructor for our object class. public DataModal(String name, String imgUrl) { this.name = name; this.imgUrl = imgUrl; } // getter and setter methods public String getName() { return name; } public void setName(String name) { this.name = name; } public String getImgUrl() { return imgUrl; } public void setImgUrl(String imgUrl) { this.imgUrl = imgUrl; }} Step 6: Create a layout file for our item of GridView Navigate to the app > res > layout > Right-click on it and click on New > Layout Resource File and give a name to that file. After creating that file add the below code to it. Here we have given the name as image_gv_item and add the below code to it. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" android:orientation="vertical" android:padding="4dp"> <!--Image view for displaying our image--> <ImageView android:id="@+id/idIVimage" android:layout_width="100dp" android:layout_height="100dp" android:layout_margin="4dp" android:background="@color/white" android:backgroundTint="@color/white" android:padding="3dp" /> <!--Text view for displaying our text --> <TextView android:id="@+id/idTVtext" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="2dp" android:padding="3dp" android:text="Category Text" android:textAlignment="center" android:textColor="@color/black" /> </LinearLayout> Step 7: Now create an Adapter class for our GridView For creating a new Adapter class navigate to the app > java > your app’s package name > Right-click on it and Click on New > Java class and name your java class as CoursesGVAdapter and add the below code to it. Comments are added inside the code to understand the code in more detail. Java import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.ImageView;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.annotation.Nullable; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class CoursesGVAdapter extends ArrayAdapter<DataModal> { // constructor for our list view adapter. public CoursesGVAdapter(@NonNull Context context, ArrayList<DataModal> dataModalArrayList) { super(context, 0, dataModalArrayList); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { // below line is use to inflate the // layout for our item of list view. View listitemView = convertView; if (listitemView == null) { listitemView = LayoutInflater.from(getContext()).inflate(R.layout.image_gv_item, parent, false); } // after inflating an item of listview item // we are getting data from array list inside // our modal class. DataModal dataModal = getItem(position); // initializing our UI components of list view item. TextView nameTV = listitemView.findViewById(R.id.idTVtext); ImageView courseIV = listitemView.findViewById(R.id.idIVimage); // after initializing our items we are // setting data to our view. // below line is use to set data to our text view. nameTV.setText(dataModal.getName()); // in below line we are using Picasso to load image // from URL in our Image VIew. Picasso.get().load(dataModal.getImgUrl()).into(courseIV); // below line is use to add item // click listener for our item of list view. listitemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on the item click on our list view. // we are displaying a toast message. Toast.makeText(getContext(), "Item clicked is : " + dataModal.getName(), Toast.LENGTH_SHORT).show(); } }); return listitemView; }} Step 8: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.widget.GridView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.OnFailureListener;import com.google.android.gms.tasks.OnSuccessListener;import com.google.firebase.firestore.DocumentSnapshot;import com.google.firebase.firestore.FirebaseFirestore;import com.google.firebase.firestore.QuerySnapshot; import java.util.ArrayList;import java.util.List; public class MainActivity extends AppCompatActivity { // creating a variable for our // grid view, arraylist and // firebase Firestore. GridView coursesGV; ArrayList<DataModal> dataModalArrayList; FirebaseFirestore db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // below line is use to initialize our variables. coursesGV = findViewById(R.id.idGVCourses); dataModalArrayList = new ArrayList<>(); // initializing our variable for firebase // firestore and getting its instance. db = FirebaseFirestore.getInstance(); // here we are calling a method // to load data in our list view. loadDatainGridView(); } private void loadDatainGridView() { // below line is use to get data from Firebase // firestore using collection in android. db.collection("Data").get() .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() { @Override public void onSuccess(QuerySnapshot queryDocumentSnapshots) { // after getting the data we are calling on success method // and inside this method we are checking if the received // query snapshot is empty or not. if (!queryDocumentSnapshots.isEmpty()) { // if the snapshot is not empty we are hiding our // progress bar and adding our data in a list. List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments(); for (DocumentSnapshot d : list) { // after getting this list we are passing // that list to our object class. DataModal dataModal = d.toObject(DataModal.class); // after getting data from Firebase // we are storing that data in our array list dataModalArrayList.add(dataModal); } // after that we are passing our array list to our adapter class. CoursesGVAdapter adapter = new CoursesGVAdapter(MainActivity.this, dataModalArrayList); // after passing this array list // to our adapter class we are setting // our adapter to our list view. coursesGV.setAdapter(adapter); } else { // if the snapshot is empty we are displaying a toast message. Toast.makeText(MainActivity.this, "No data found in Database", Toast.LENGTH_SHORT).show(); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // we are displaying a toast message // when we get any error from Firebase. Toast.makeText(MainActivity.this, "Fail to load data..", Toast.LENGTH_SHORT).show(); } }); }} After adding the above code add the data to Firebase Firestore in Android. Step 9: Adding the data to Firebase Firestore in Android Search for Firebase in your browser and go to that website and you will get to see the below screen. After clicking on Go to Console option. Click on your project which is shown below. After clicking on your project you will get to see the below screen. After clicking on this project you will get to see the below screen. After clicking on the Create Database option you will get to see the below screen. Inside this screen, we have to select the Start in test mode option. We are using test mode because we are not setting authentication inside our app. So we are selecting Start in test mode. After selecting test mode click on the Next option and you will get to see the below screen. Inside this screen, we just have to click on the Enable button to enable our Firebase Firestore database. After completing this process we have to add the data inside our Firebase Console. For adding data to our Firebase Console. You have to click on Start Collection Option and give the collection name as Data. After creating a collection you have to click on Autoid option for creating the first document. Then create two fields, one filed for “name” and one filed for “imgUrl” and enter the corresponding values for them. Note that specify the image URL link in the value for the imgUrl filed. And click on the Save button. Your first image to the Data has been added. Similarly, add more images by clicking on the “Add document” button. After adding these images run your app and you will get to see the output on the below screen. android Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jan, 2021" }, { "code": null, "e": 444, "s": 28, "text": "GridView is also one of the most used UI components which is used to display items in the Grid format inside our app. By using this type of view we can display the items in the grid format. We have seen this type of GridView in most of the apps. We have also seen the implementation of GridView in our app. In this article, we will take a look at the implementation of GridView using Firebase Firestore in Android. " }, { "code": null, "e": 781, "s": 444, "text": "We will be building a simple application in which we will be displaying the data in the grid format and we will load this data from Firebase Firestore inside our GridView. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 810, "s": 781, "text": "Step 1: Create a new Project" }, { "code": null, "e": 974, "s": 810, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. " }, { "code": null, "e": 1012, "s": 974, "text": "Step 2: Connect your app to Firebase " }, { "code": null, "e": 1216, "s": 1012, "text": "After creating a new project navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot." }, { "code": null, "e": 1625, "s": 1216, "text": "Inside that column Navigate to Firebase Cloud Firestore. Click on that option and you will get to see two options on Connect app to Firebase and Add Cloud Firestore to your app. Click on Connect now option and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase. After connecting your app to Firebase you will get to see the below screen. " }, { "code": null, "e": 1959, "s": 1625, "text": "After that verify that dependency for the Firebase Firestore database has been added to our Gradle file. Navigate to the app > Gradle Scripts inside that file to check whether the below dependency is added or not. If the below dependency is not present in your build.gradle file. Add the below dependency in the dependencies section." }, { "code": null, "e": 2022, "s": 1959, "text": "implementation ‘com.google.firebase:firebase-firestore:22.0.1’" }, { "code": null, "e": 2259, "s": 2022, "text": "After adding this dependency sync your project and now we are ready for creating our app. If you want to know more about connecting your app to Firebase. Refer to this article to get in detail about How to add Firebase to Android App. " }, { "code": null, "e": 2309, "s": 2259, "text": "Step 3: Working with the AndroidManifest.xml file" }, { "code": null, "e": 2527, "s": 2309, "text": "For adding data to Firebase we should have to give permissions for accessing the internet. For adding these permissions navigate to the app > AndroidManifest.xml and Inside that file add the below permissions to it. " }, { "code": null, "e": 2531, "s": 2527, "text": "XML" }, { "code": "<!--Permissions for internet--><uses-permission android:name=\"android.permission.INTERNET\" /><uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\" />", "e": 2699, "s": 2531, "text": null }, { "code": null, "e": 2747, "s": 2699, "text": "Step 4: Working with the activity_main.xml file" }, { "code": null, "e": 2863, "s": 2747, "text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file." }, { "code": null, "e": 2867, "s": 2863, "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\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <!--Grid View for displaying our data from Firebase--> <GridView android:id=\"@+id/idGVCourses\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:numColumns=\"2\" /> </RelativeLayout>", "e": 3430, "s": 2867, "text": null }, { "code": null, "e": 3495, "s": 3430, "text": "Step 5: Now we will create a new Java class for storing our data" }, { "code": null, "e": 3860, "s": 3495, "text": "For reading data from the Firebase Firestore database, we have to create an Object class and we will read data inside this class. For creating an object class, navigate to the app > java > your app’s package name > Right-click on it and click on New > Java Class > Give a name to your class. Here we have given the name as DataModal and add the below code to it. " }, { "code": null, "e": 3865, "s": 3860, "text": "Java" }, { "code": "public class DataModal { // variables for storing our image and name. private String name; private String imgUrl; public DataModal() { // empty constructor required for firebase. } // constructor for our object class. public DataModal(String name, String imgUrl) { this.name = name; this.imgUrl = imgUrl; } // getter and setter methods public String getName() { return name; } public void setName(String name) { this.name = name; } public String getImgUrl() { return imgUrl; } public void setImgUrl(String imgUrl) { this.imgUrl = imgUrl; }}", "e": 4520, "s": 3865, "text": null }, { "code": null, "e": 4574, "s": 4520, "text": "Step 6: Create a layout file for our item of GridView" }, { "code": null, "e": 4829, "s": 4574, "text": "Navigate to the app > res > layout > Right-click on it and click on New > Layout Resource File and give a name to that file. After creating that file add the below code to it. Here we have given the name as image_gv_item and add the below code to it. " }, { "code": null, "e": 4833, "s": 4829, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:gravity=\"center\" android:orientation=\"vertical\" android:padding=\"4dp\"> <!--Image view for displaying our image--> <ImageView android:id=\"@+id/idIVimage\" android:layout_width=\"100dp\" android:layout_height=\"100dp\" android:layout_margin=\"4dp\" android:background=\"@color/white\" android:backgroundTint=\"@color/white\" android:padding=\"3dp\" /> <!--Text view for displaying our text --> <TextView android:id=\"@+id/idTVtext\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_margin=\"2dp\" android:padding=\"3dp\" android:text=\"Category Text\" android:textAlignment=\"center\" android:textColor=\"@color/black\" /> </LinearLayout>", "e": 5852, "s": 4833, "text": null }, { "code": null, "e": 5905, "s": 5852, "text": "Step 7: Now create an Adapter class for our GridView" }, { "code": null, "e": 6190, "s": 5905, "text": "For creating a new Adapter class navigate to the app > java > your app’s package name > Right-click on it and Click on New > Java class and name your java class as CoursesGVAdapter and add the below code to it. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 6195, "s": 6190, "text": "Java" }, { "code": "import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.ImageView;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.annotation.Nullable; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class CoursesGVAdapter extends ArrayAdapter<DataModal> { // constructor for our list view adapter. public CoursesGVAdapter(@NonNull Context context, ArrayList<DataModal> dataModalArrayList) { super(context, 0, dataModalArrayList); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { // below line is use to inflate the // layout for our item of list view. View listitemView = convertView; if (listitemView == null) { listitemView = LayoutInflater.from(getContext()).inflate(R.layout.image_gv_item, parent, false); } // after inflating an item of listview item // we are getting data from array list inside // our modal class. DataModal dataModal = getItem(position); // initializing our UI components of list view item. TextView nameTV = listitemView.findViewById(R.id.idTVtext); ImageView courseIV = listitemView.findViewById(R.id.idIVimage); // after initializing our items we are // setting data to our view. // below line is use to set data to our text view. nameTV.setText(dataModal.getName()); // in below line we are using Picasso to load image // from URL in our Image VIew. Picasso.get().load(dataModal.getImgUrl()).into(courseIV); // below line is use to add item // click listener for our item of list view. listitemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on the item click on our list view. // we are displaying a toast message. Toast.makeText(getContext(), \"Item clicked is : \" + dataModal.getName(), Toast.LENGTH_SHORT).show(); } }); return listitemView; }}", "e": 8515, "s": 6195, "text": null }, { "code": null, "e": 8563, "s": 8515, "text": "Step 8: Working with the MainActivity.java file" }, { "code": null, "e": 8753, "s": 8563, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 8758, "s": 8753, "text": "Java" }, { "code": "import android.os.Bundle;import android.widget.GridView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.OnFailureListener;import com.google.android.gms.tasks.OnSuccessListener;import com.google.firebase.firestore.DocumentSnapshot;import com.google.firebase.firestore.FirebaseFirestore;import com.google.firebase.firestore.QuerySnapshot; import java.util.ArrayList;import java.util.List; public class MainActivity extends AppCompatActivity { // creating a variable for our // grid view, arraylist and // firebase Firestore. GridView coursesGV; ArrayList<DataModal> dataModalArrayList; FirebaseFirestore db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // below line is use to initialize our variables. coursesGV = findViewById(R.id.idGVCourses); dataModalArrayList = new ArrayList<>(); // initializing our variable for firebase // firestore and getting its instance. db = FirebaseFirestore.getInstance(); // here we are calling a method // to load data in our list view. loadDatainGridView(); } private void loadDatainGridView() { // below line is use to get data from Firebase // firestore using collection in android. db.collection(\"Data\").get() .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() { @Override public void onSuccess(QuerySnapshot queryDocumentSnapshots) { // after getting the data we are calling on success method // and inside this method we are checking if the received // query snapshot is empty or not. if (!queryDocumentSnapshots.isEmpty()) { // if the snapshot is not empty we are hiding our // progress bar and adding our data in a list. List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments(); for (DocumentSnapshot d : list) { // after getting this list we are passing // that list to our object class. DataModal dataModal = d.toObject(DataModal.class); // after getting data from Firebase // we are storing that data in our array list dataModalArrayList.add(dataModal); } // after that we are passing our array list to our adapter class. CoursesGVAdapter adapter = new CoursesGVAdapter(MainActivity.this, dataModalArrayList); // after passing this array list // to our adapter class we are setting // our adapter to our list view. coursesGV.setAdapter(adapter); } else { // if the snapshot is empty we are displaying a toast message. Toast.makeText(MainActivity.this, \"No data found in Database\", Toast.LENGTH_SHORT).show(); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // we are displaying a toast message // when we get any error from Firebase. Toast.makeText(MainActivity.this, \"Fail to load data..\", Toast.LENGTH_SHORT).show(); } }); }}", "e": 12722, "s": 8758, "text": null }, { "code": null, "e": 12799, "s": 12722, "text": "After adding the above code add the data to Firebase Firestore in Android. " }, { "code": null, "e": 12856, "s": 12799, "text": "Step 9: Adding the data to Firebase Firestore in Android" }, { "code": null, "e": 12959, "s": 12856, "text": "Search for Firebase in your browser and go to that website and you will get to see the below screen. " }, { "code": null, "e": 13043, "s": 12959, "text": "After clicking on Go to Console option. Click on your project which is shown below." }, { "code": null, "e": 13183, "s": 13043, "text": "After clicking on your project you will get to see the below screen. After clicking on this project you will get to see the below screen. " }, { "code": null, "e": 13268, "s": 13183, "text": "After clicking on the Create Database option you will get to see the below screen. " }, { "code": null, "e": 13553, "s": 13268, "text": "Inside this screen, we have to select the Start in test mode option. We are using test mode because we are not setting authentication inside our app. So we are selecting Start in test mode. After selecting test mode click on the Next option and you will get to see the below screen. " }, { "code": null, "e": 13784, "s": 13553, "text": "Inside this screen, we just have to click on the Enable button to enable our Firebase Firestore database. After completing this process we have to add the data inside our Firebase Console. For adding data to our Firebase Console. " }, { "code": null, "e": 14228, "s": 13784, "text": "You have to click on Start Collection Option and give the collection name as Data. After creating a collection you have to click on Autoid option for creating the first document. Then create two fields, one filed for “name” and one filed for “imgUrl” and enter the corresponding values for them. Note that specify the image URL link in the value for the imgUrl filed. And click on the Save button. Your first image to the Data has been added. " }, { "code": null, "e": 14298, "s": 14228, "text": "Similarly, add more images by clicking on the “Add document” button. " }, { "code": null, "e": 14394, "s": 14298, "text": "After adding these images run your app and you will get to see the output on the below screen. " }, { "code": null, "e": 14402, "s": 14394, "text": "android" }, { "code": null, "e": 14426, "s": 14402, "text": "Technical Scripter 2020" }, { "code": null, "e": 14434, "s": 14426, "text": "Android" }, { "code": null, "e": 14439, "s": 14434, "text": "Java" }, { "code": null, "e": 14458, "s": 14439, "text": "Technical Scripter" }, { "code": null, "e": 14463, "s": 14458, "text": "Java" }, { "code": null, "e": 14471, "s": 14463, "text": "Android" } ]
Python | datetime.timedelta() function
09 Jun, 2022 Python timedelta() function is present under datetime library which is generally used for calculating differences in dates and also can be used for date manipulations in Python. It is one of the easiest ways to perform date manipulations. Syntax : datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) Returns : Date Code #1: Python3 # Timedelta function demonstration from datetime import datetime, timedelta # Using current timeini_time_for_now = datetime.now() # printing initial_dateprint ("initial_date", str(ini_time_for_now)) # Calculating future dates# for two yearsfuture_date_after_2yrs = ini_time_for_now + \ timedelta(days = 730) future_date_after_2days = ini_time_for_now + \ timedelta(days = 2) # printing calculated future_datesprint('future_date_after_2yrs:', str(future_date_after_2yrs))print('future_date_after_2days:', str(future_date_after_2days)) initial_date 2019-02-27 12:41:45.018389 future_date_after_2yrs: 2021-02-26 12:41:45.018389 future_date_after_2days: 2019-03-01 12:41:45.018389 Code #2: Python3 # Timedelta function demonstrationfrom datetime import datetime, timedelta # Using current timeini_time_for_now = datetime.now() # printing initial_dateprint ('initial_date:', str(ini_time_for_now)) # Calculating past dates# for two yearspast_date_before_2yrs = ini_time_for_now - \ timedelta(days = 730) # for two hourspast_date_before_2hours = ini_time_for_now - \ timedelta(hours = 2) # printing calculated past_datesprint('past_date_before_2yrs:', str(past_date_before_2yrs))print('past_date_before_2hours:', str(past_date_before_2hours)) initial_date 2019-02-27 12:41:46.104662 past_date_before_2yrs: 2017-02-27 12:41:46.104662 past_date_after_2days: 2019-02-27 10:41:46.104662 Code #3: Python3 # Timedelta function demonstrationfrom datetime import datetime, timedelta # Using current timeini_time_for_now = datetime.now() # printing initial_dateprint ("initial_date", str(ini_time_for_now)) # Some another datetimenew_final_time = ini_time_for_now + \ timedelta(days = 2) # printing new final_dateprint ("new_final_time", str(new_final_time)) # printing calculated past_datesprint('Time difference:', str(new_final_time - \ ini_time_for_now)) initial_date 2019-02-27 12:41:47.386595 new_final_time 2019-03-01 12:41:47.386595 Time difference: 2 days, 0:00:00 abelbraaksma Python-Functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python 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
[ { "code": null, "e": 52, "s": 24, "text": "\n09 Jun, 2022" }, { "code": null, "e": 292, "s": 52, "text": "Python timedelta() function is present under datetime library which is generally used for calculating differences in dates and also can be used for date manipulations in Python. It is one of the easiest ways to perform date manipulations. " }, { "code": null, "e": 415, "s": 292, "text": "Syntax : datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) Returns : Date" }, { "code": null, "e": 425, "s": 415, "text": "Code #1: " }, { "code": null, "e": 433, "s": 425, "text": "Python3" }, { "code": "# Timedelta function demonstration from datetime import datetime, timedelta # Using current timeini_time_for_now = datetime.now() # printing initial_dateprint (\"initial_date\", str(ini_time_for_now)) # Calculating future dates# for two yearsfuture_date_after_2yrs = ini_time_for_now + \\ timedelta(days = 730) future_date_after_2days = ini_time_for_now + \\ timedelta(days = 2) # printing calculated future_datesprint('future_date_after_2yrs:', str(future_date_after_2yrs))print('future_date_after_2days:', str(future_date_after_2days))", "e": 1015, "s": 433, "text": null }, { "code": null, "e": 1158, "s": 1015, "text": "initial_date 2019-02-27 12:41:45.018389\nfuture_date_after_2yrs: 2021-02-26 12:41:45.018389\nfuture_date_after_2days: 2019-03-01 12:41:45.018389" }, { "code": null, "e": 1168, "s": 1158, "text": "Code #2: " }, { "code": null, "e": 1176, "s": 1168, "text": "Python3" }, { "code": "# Timedelta function demonstrationfrom datetime import datetime, timedelta # Using current timeini_time_for_now = datetime.now() # printing initial_dateprint ('initial_date:', str(ini_time_for_now)) # Calculating past dates# for two yearspast_date_before_2yrs = ini_time_for_now - \\ timedelta(days = 730) # for two hourspast_date_before_2hours = ini_time_for_now - \\ timedelta(hours = 2) # printing calculated past_datesprint('past_date_before_2yrs:', str(past_date_before_2yrs))print('past_date_before_2hours:', str(past_date_before_2hours))", "e": 1766, "s": 1176, "text": null }, { "code": null, "e": 1906, "s": 1766, "text": "initial_date 2019-02-27 12:41:46.104662\npast_date_before_2yrs: 2017-02-27 12:41:46.104662\npast_date_after_2days: 2019-02-27 10:41:46.104662" }, { "code": null, "e": 1916, "s": 1906, "text": "Code #3: " }, { "code": null, "e": 1924, "s": 1916, "text": "Python3" }, { "code": "# Timedelta function demonstrationfrom datetime import datetime, timedelta # Using current timeini_time_for_now = datetime.now() # printing initial_dateprint (\"initial_date\", str(ini_time_for_now)) # Some another datetimenew_final_time = ini_time_for_now + \\ timedelta(days = 2) # printing new final_dateprint (\"new_final_time\", str(new_final_time)) # printing calculated past_datesprint('Time difference:', str(new_final_time - \\ ini_time_for_now))", "e": 2419, "s": 1924, "text": null }, { "code": null, "e": 2534, "s": 2419, "text": "initial_date 2019-02-27 12:41:47.386595\nnew_final_time 2019-03-01 12:41:47.386595\nTime difference: 2 days, 0:00:00" }, { "code": null, "e": 2547, "s": 2534, "text": "abelbraaksma" }, { "code": null, "e": 2564, "s": 2547, "text": "Python-Functions" }, { "code": null, "e": 2571, "s": 2564, "text": "Python" }, { "code": null, "e": 2669, "s": 2571, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2711, "s": 2669, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2733, "s": 2711, "text": "Enumerate() in Python" }, { "code": null, "e": 2765, "s": 2733, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2794, "s": 2765, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2821, "s": 2794, "text": "Python Classes and Objects" }, { "code": null, "e": 2857, "s": 2821, "text": "Convert integer to string in Python" }, { "code": null, "e": 2888, "s": 2857, "text": "Python | os.path.join() method" }, { "code": null, "e": 2925, "s": 2888, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 2948, "s": 2925, "text": "Introduction To PYTHON" } ]
Dart – Type System
24 Mar, 2022 The Dart programming language is considered type safe, meaning it ensures that the variable’s value always matches the variable’s static type through a combination of static type checking and runtime checking. It is also known as Sound Typing. It comes in handy while debugging the code at compile time. All forms of static errors can be resolved by adding type annotations to generic classes.Some frequently used generic collection classes are listed below: List Map Example 1: The below code will throw an error on listwhen a call to the printInts(list) is made. Dart void printInts(List<int> x) => print(x); void main() { var list = []; list.add(1000); list.add(2000); printInts(list);}} Output: error - The argument type 'List' can't be assigned to the parameter type 'List' at lib/strong_analysis.dart:27:17 - (argument_type_not_assignable) The above error occurred due to an unsound implicit cast from a dynamic type List to an integer type , meaning declaring var List = [] doesn’t provide sufficient information to the dart analyzer about the typing of the list items. To resolve this issue we pass the type annotation to the list variable as shown below: Dart // Using num data type in Dartvoid printInts(List<int> a) => print(a); void main() { var list = <int>[]; list.add(1000); list.add(2000); printInts(list);}} Output: [1000, 2000] Soundness is the process of making sure that the code doesn’t run into an invalid state. For instance, if a variable’s static type is boolean, it is not possible to run into a state where the variable evaluates to a non-string value during runtime. Benefits of having Soundness: Debug type related bugs at compile time. Makes code easier to read and debug. Get alters when changing code picese that breaks other dependent part of the code. One of its key features is Ahead Of Time (AOT) compilation, which significantly reduces the compile time of the code and increases efficiency. varshagumber28 kothavvsaakash Dart Data-types Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - DropDownButton Widget Flutter - Checkbox Widget Flutter - Custom Bottom Navigation Bar Flutter - AppBar Widget ListView Class in Flutter Flutter - Stack Widget Flutter - Search Bar How to Append or Concatenate Strings in Dart? Dart Tutorial Flutter - Row and Column Widgets
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Mar, 2022" }, { "code": null, "e": 332, "s": 28, "text": "The Dart programming language is considered type safe, meaning it ensures that the variable’s value always matches the variable’s static type through a combination of static type checking and runtime checking. It is also known as Sound Typing. It comes in handy while debugging the code at compile time." }, { "code": null, "e": 487, "s": 332, "text": "All forms of static errors can be resolved by adding type annotations to generic classes.Some frequently used generic collection classes are listed below:" }, { "code": null, "e": 492, "s": 487, "text": "List" }, { "code": null, "e": 496, "s": 492, "text": "Map" }, { "code": null, "e": 593, "s": 496, "text": "Example 1: The below code will throw an error on listwhen a call to the printInts(list) is made." }, { "code": null, "e": 598, "s": 593, "text": "Dart" }, { "code": "void printInts(List<int> x) => print(x); void main() { var list = []; list.add(1000); list.add(2000); printInts(list);}}", "e": 723, "s": 598, "text": null }, { "code": null, "e": 731, "s": 723, "text": "Output:" }, { "code": null, "e": 878, "s": 731, "text": "error - The argument type 'List' can't be assigned to the parameter type 'List' at lib/strong_analysis.dart:27:17 - (argument_type_not_assignable)" }, { "code": null, "e": 1196, "s": 878, "text": "The above error occurred due to an unsound implicit cast from a dynamic type List to an integer type , meaning declaring var List = [] doesn’t provide sufficient information to the dart analyzer about the typing of the list items. To resolve this issue we pass the type annotation to the list variable as shown below:" }, { "code": null, "e": 1201, "s": 1196, "text": "Dart" }, { "code": "// Using num data type in Dartvoid printInts(List<int> a) => print(a); void main() { var list = <int>[]; list.add(1000); list.add(2000); printInts(list);}}", "e": 1361, "s": 1201, "text": null }, { "code": null, "e": 1369, "s": 1361, "text": "Output:" }, { "code": null, "e": 1383, "s": 1369, "text": "[1000, 2000] " }, { "code": null, "e": 1633, "s": 1383, "text": "Soundness is the process of making sure that the code doesn’t run into an invalid state. For instance, if a variable’s static type is boolean, it is not possible to run into a state where the variable evaluates to a non-string value during runtime. " }, { "code": null, "e": 1663, "s": 1633, "text": "Benefits of having Soundness:" }, { "code": null, "e": 1704, "s": 1663, "text": "Debug type related bugs at compile time." }, { "code": null, "e": 1741, "s": 1704, "text": "Makes code easier to read and debug." }, { "code": null, "e": 1824, "s": 1741, "text": "Get alters when changing code picese that breaks other dependent part of the code." }, { "code": null, "e": 1969, "s": 1824, "text": "One of its key features is Ahead Of Time (AOT) compilation, which significantly reduces the compile time of the code and increases efficiency. " }, { "code": null, "e": 1984, "s": 1969, "text": "varshagumber28" }, { "code": null, "e": 1999, "s": 1984, "text": "kothavvsaakash" }, { "code": null, "e": 2015, "s": 1999, "text": "Dart Data-types" }, { "code": null, "e": 2020, "s": 2015, "text": "Dart" }, { "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": 2150, "s": 2118, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 2176, "s": 2150, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 2215, "s": 2176, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 2239, "s": 2215, "text": "Flutter - AppBar Widget" }, { "code": null, "e": 2265, "s": 2239, "text": "ListView Class in Flutter" }, { "code": null, "e": 2288, "s": 2265, "text": "Flutter - Stack Widget" }, { "code": null, "e": 2309, "s": 2288, "text": "Flutter - Search Bar" }, { "code": null, "e": 2355, "s": 2309, "text": "How to Append or Concatenate Strings in Dart?" }, { "code": null, "e": 2369, "s": 2355, "text": "Dart Tutorial" } ]
C# | Action Delegate
07 Aug, 2019 Action delegate is an in-built generic type delegate. This delegate saves you from defining a custom delegate as shown in the below examples and make your program more readable and optimized. It is defined under System namespace. It can contain minimum 1 and maximum of 16 input parameters and does not contain any output parameter. The Action delegate is generally used for those methods which do not contain any return value, or in other words, Action delegate is used with those methods whose return type is void. It can also contain parameters of the same type or of different types. Syntax: // One input parameter public delegate void Action < in P > (P obj); // Two input parameters public delegate void Action < in P1, in P2 >(P1 arg1, P2 arg2); Here, P, P1, and P2 are the type of the input parameters & arg1 and agr2 are the parameters of the method that Action delegate encapsulates. Example: Below program illustrate how we create a custom delegate. // C# program to illustrate delegatesusing System; class GFG { // Declaring the delegate public delegate void my_delegate(int p, int q); // Method public static void myfun(int p, int q) { Console.WriteLine(p - q); } // Main method static public void Main() { // Creating object of my_delegate my_delegate obj = myfun; obj(10, 5); }} 5 Example: It demonstrates the use of Action delegate. // C# program to illustrate Action delegatesusing System; class GFG { // Method public static void myfun(int p, int q) { Console.WriteLine(p - q); } // Main method static public void Main() { // Using Action delegate // Here, Action delegate // contains two input parameters Action<int, int> val = myfun; val(20, 5); }} 15 Explanation: In the above example, using Action delegate reduce the size of the code and make the program more readable. Here action delegate contains two input parameters. And we directly assign the myfun method to the Action delegate. Important Points: The only difference between Action Delegates and Function Delegates is that Action Delegates does not return anything i.e. having void return type. An Action Delegate can also be initialized using the new keyword.Action<int> val = new Action<int>(myfun); Action<int> val = new Action<int>(myfun); An Action Delegate can also be initialized by directly assigning to a method.Action<int> val = myfun; Action<int> val = myfun; You can also use an Action delegate with an anonymous method as shown in the below example:Example:Action<string> val = delegate(string str){ Console.WriteLine(str);};val("GeeksforGeeks"); Example: Action<string> val = delegate(string str){ Console.WriteLine(str);};val("GeeksforGeeks"); You can also use a Action delegate with the lambda expressions as shown in the below example:Example:Action<string> val = str = > Console.WriteLine(str);val("GeeksforGeeks"); Example: Action<string> val = str = > Console.WriteLine(str);val("GeeksforGeeks"); DivyaPahuja CSharp-Delegates C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Multiple inheritance using interfaces Introduction to .NET Framework Differences Between .NET Core and .NET Framework C# | String.IndexOf( ) Method | Set - 1 C# | Constructors C# | Class and Object C# | Replace() Method C# | Arrays C# | List Class Difference between Ref and Out keywords in C#
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Aug, 2019" }, { "code": null, "e": 642, "s": 54, "text": "Action delegate is an in-built generic type delegate. This delegate saves you from defining a custom delegate as shown in the below examples and make your program more readable and optimized. It is defined under System namespace. It can contain minimum 1 and maximum of 16 input parameters and does not contain any output parameter. The Action delegate is generally used for those methods which do not contain any return value, or in other words, Action delegate is used with those methods whose return type is void. It can also contain parameters of the same type or of different types." }, { "code": null, "e": 650, "s": 642, "text": "Syntax:" }, { "code": null, "e": 809, "s": 650, "text": "// One input parameter\npublic delegate void Action < in P > (P obj);\n\n// Two input parameters\npublic delegate void Action < in P1, in P2 >(P1 arg1, P2 arg2);\n" }, { "code": null, "e": 950, "s": 809, "text": "Here, P, P1, and P2 are the type of the input parameters & arg1 and agr2 are the parameters of the method that Action delegate encapsulates." }, { "code": null, "e": 1017, "s": 950, "text": "Example: Below program illustrate how we create a custom delegate." }, { "code": "// C# program to illustrate delegatesusing System; class GFG { // Declaring the delegate public delegate void my_delegate(int p, int q); // Method public static void myfun(int p, int q) { Console.WriteLine(p - q); } // Main method static public void Main() { // Creating object of my_delegate my_delegate obj = myfun; obj(10, 5); }}", "e": 1417, "s": 1017, "text": null }, { "code": null, "e": 1420, "s": 1417, "text": "5\n" }, { "code": null, "e": 1473, "s": 1420, "text": "Example: It demonstrates the use of Action delegate." }, { "code": "// C# program to illustrate Action delegatesusing System; class GFG { // Method public static void myfun(int p, int q) { Console.WriteLine(p - q); } // Main method static public void Main() { // Using Action delegate // Here, Action delegate // contains two input parameters Action<int, int> val = myfun; val(20, 5); }}", "e": 1867, "s": 1473, "text": null }, { "code": null, "e": 1871, "s": 1867, "text": "15\n" }, { "code": null, "e": 2108, "s": 1871, "text": "Explanation: In the above example, using Action delegate reduce the size of the code and make the program more readable. Here action delegate contains two input parameters. And we directly assign the myfun method to the Action delegate." }, { "code": null, "e": 2126, "s": 2108, "text": "Important Points:" }, { "code": null, "e": 2274, "s": 2126, "text": "The only difference between Action Delegates and Function Delegates is that Action Delegates does not return anything i.e. having void return type." }, { "code": null, "e": 2381, "s": 2274, "text": "An Action Delegate can also be initialized using the new keyword.Action<int> val = new Action<int>(myfun);" }, { "code": null, "e": 2423, "s": 2381, "text": "Action<int> val = new Action<int>(myfun);" }, { "code": null, "e": 2525, "s": 2423, "text": "An Action Delegate can also be initialized by directly assigning to a method.Action<int> val = myfun;" }, { "code": null, "e": 2550, "s": 2525, "text": "Action<int> val = myfun;" }, { "code": null, "e": 2742, "s": 2550, "text": "You can also use an Action delegate with an anonymous method as shown in the below example:Example:Action<string> val = delegate(string str){ Console.WriteLine(str);};val(\"GeeksforGeeks\");" }, { "code": null, "e": 2751, "s": 2742, "text": "Example:" }, { "code": "Action<string> val = delegate(string str){ Console.WriteLine(str);};val(\"GeeksforGeeks\");", "e": 2844, "s": 2751, "text": null }, { "code": null, "e": 3019, "s": 2844, "text": "You can also use a Action delegate with the lambda expressions as shown in the below example:Example:Action<string> val = str = > Console.WriteLine(str);val(\"GeeksforGeeks\");" }, { "code": null, "e": 3028, "s": 3019, "text": "Example:" }, { "code": "Action<string> val = str = > Console.WriteLine(str);val(\"GeeksforGeeks\");", "e": 3102, "s": 3028, "text": null }, { "code": null, "e": 3114, "s": 3102, "text": "DivyaPahuja" }, { "code": null, "e": 3131, "s": 3114, "text": "CSharp-Delegates" }, { "code": null, "e": 3134, "s": 3131, "text": "C#" }, { "code": null, "e": 3232, "s": 3134, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3275, "s": 3232, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 3306, "s": 3275, "text": "Introduction to .NET Framework" }, { "code": null, "e": 3355, "s": 3306, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 3395, "s": 3355, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 3413, "s": 3395, "text": "C# | Constructors" }, { "code": null, "e": 3435, "s": 3413, "text": "C# | Class and Object" }, { "code": null, "e": 3457, "s": 3435, "text": "C# | Replace() Method" }, { "code": null, "e": 3469, "s": 3457, "text": "C# | Arrays" }, { "code": null, "e": 3485, "s": 3469, "text": "C# | List Class" } ]
PostgreSQL Python – Querying Data
31 Aug, 2021 In this article, we are going to see how to use PostSQL using pyscopg2 in Python for executing query data. In order to establish a connection to the PostgreSQL server, we will make use of the pscopg2 library in python. You can install psycopg2 using the following command: pip install psycopg2 If the above command causes an error then use the command: pip uninstall psycopg2 pip install psycopg2-binary After installing the library, the following code can be used to create a connection to the database server: Python import psycopg2 def get_connection(): try: return psycopg2.connect( database="postgres", user="postgres", password="password", host="127.0.0.1", port=5432, ) except: return False conn = get_connection() if conn: print("Connection to the PostgreSQL established successfully.")else: print("Connection to the PostgreSQL encountered and error.") Output: Connection to the PostgreSQL established successfully. Running the above code will produce the following result if the database credentials provided is correct and the connection is successfully established: Let us look at how can we query data using the psycopg2 library. Execute the below SQL query to get the data ready in our table in order to query data from: In the above output, we can see that there are 5 records present in the students table. We will make use of these records to see how can we query data from a database table. Python # This program uses fetchall()# to query all the records from a table # GET THE CONNECTION OBJECTconn = get_connection() # CREATE A CURSOR USING THE CONNECTION OBJECTcurr = conn.cursor() # EXECUTE THE SQL QUERYcurr.execute("SELECT * FROM students;") # FETCH ALL THE ROWS FROM THE CURSORdata = curr.fetchall() # PRINT THE RECORDSfor row in data: print(row) # CLOSE THE CONNECTIONconn.close() Output: Output for fetchall() In the above code, we create a connection and query using SELECT * FROM students which fetches the entire dump of the students table. In order to query data in the python code, we can make use of fetchall(). The fetchall() method fetches all the records that we got from our SQL query (the SELECT query in this case) and provides them in a list. The list consists of tuples where each tuple consists of all the column values present in the particular record or row. Python # This program uses fetchone() to# query one by one record from a table # GET THE CONNECTION OBJECTconn = get_connection() # CREATE A CURSOR USING THE CONNECTION OBJECTcurr = conn.cursor() # EXECUTE THE SQL QUERYcurr.execute("SELECT * FROM students;") # FETCH THE FIRST ROW FROM THE CURSORdata1 = curr.fetchone()print(data1) # FETCH THE SECOND ROW FROM THE CURSORdata2 = curr.fetchone()print(data2) # CLOSE THE CONNECTIONconn.close() Output: Output for fetchone() The fetchone() method is not to be confused with the idea that it queries the first row only. The fetchone() method returns the first record from the dump that we got from the SQL query present in curr.execute() method. It behaves like a queue where we query the first record and then it gets deleted from the cursor object. Now, if we try to use the fetchone() method again, it will return the next record. The above code demonstrates the same where we fetched the first record and then used the fetchone() method again to fetch the next record in the queue. We can keep doing this until we reach the last record in the cursor object. Python # This program uses fetchmany() # to query specified number of records from a table # GET THE CONNECTION OBJECTconn = get_connection() # CREATE A CURSOR USING THE CONNECTION OBJECTcurr = conn.cursor() # EXECUTE THE SQL QUERYcurr.execute("SELECT * FROM students;") print("First two records:") # GET FIRST TWO RECORDS FROM DATABASE TABLEdata1 = curr.fetchmany(2)for row in data1: print(row) print("Next three records:") # GET NEXT THREE RECORDS FROM DATABASE TABLEdata2 = curr.fetchmany(3)for row in data2: print(row) # CLOSE THE CONNECTIONconn.close() Output: Output for fetchmany() We have seen how to query all the records and to query one-by-one records. The fetchmany() method takes in the no. of records that we want to fetch from the entire dump. It also behaves like a queue as we saw in the fetchone() method, except for the fact that it can fetch more than one record at a time. However, using fetchmany(1) is equivalent to using fetchone() method. In the above code, we used the fetchmany(2) to query the first two records and then used the fetchmany(3) to query the next 3 records. The same can be noticed in the below output. Picked Python PostgreSQL Python Pyscopg2 Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Aug, 2021" }, { "code": null, "e": 135, "s": 28, "text": "In this article, we are going to see how to use PostSQL using pyscopg2 in Python for executing query data." }, { "code": null, "e": 301, "s": 135, "text": "In order to establish a connection to the PostgreSQL server, we will make use of the pscopg2 library in python. You can install psycopg2 using the following command:" }, { "code": null, "e": 322, "s": 301, "text": "pip install psycopg2" }, { "code": null, "e": 381, "s": 322, "text": "If the above command causes an error then use the command:" }, { "code": null, "e": 432, "s": 381, "text": "pip uninstall psycopg2\npip install psycopg2-binary" }, { "code": null, "e": 540, "s": 432, "text": "After installing the library, the following code can be used to create a connection to the database server:" }, { "code": null, "e": 547, "s": 540, "text": "Python" }, { "code": "import psycopg2 def get_connection(): try: return psycopg2.connect( database=\"postgres\", user=\"postgres\", password=\"password\", host=\"127.0.0.1\", port=5432, ) except: return False conn = get_connection() if conn: print(\"Connection to the PostgreSQL established successfully.\")else: print(\"Connection to the PostgreSQL encountered and error.\")", "e": 980, "s": 547, "text": null }, { "code": null, "e": 988, "s": 980, "text": "Output:" }, { "code": null, "e": 1043, "s": 988, "text": "Connection to the PostgreSQL established successfully." }, { "code": null, "e": 1196, "s": 1043, "text": "Running the above code will produce the following result if the database credentials provided is correct and the connection is successfully established:" }, { "code": null, "e": 1261, "s": 1196, "text": "Let us look at how can we query data using the psycopg2 library." }, { "code": null, "e": 1353, "s": 1261, "text": "Execute the below SQL query to get the data ready in our table in order to query data from:" }, { "code": null, "e": 1527, "s": 1353, "text": "In the above output, we can see that there are 5 records present in the students table. We will make use of these records to see how can we query data from a database table." }, { "code": null, "e": 1534, "s": 1527, "text": "Python" }, { "code": "# This program uses fetchall()# to query all the records from a table # GET THE CONNECTION OBJECTconn = get_connection() # CREATE A CURSOR USING THE CONNECTION OBJECTcurr = conn.cursor() # EXECUTE THE SQL QUERYcurr.execute(\"SELECT * FROM students;\") # FETCH ALL THE ROWS FROM THE CURSORdata = curr.fetchall() # PRINT THE RECORDSfor row in data: print(row) # CLOSE THE CONNECTIONconn.close()", "e": 1934, "s": 1534, "text": null }, { "code": null, "e": 1942, "s": 1934, "text": "Output:" }, { "code": null, "e": 1964, "s": 1942, "text": "Output for fetchall()" }, { "code": null, "e": 2430, "s": 1964, "text": "In the above code, we create a connection and query using SELECT * FROM students which fetches the entire dump of the students table. In order to query data in the python code, we can make use of fetchall(). The fetchall() method fetches all the records that we got from our SQL query (the SELECT query in this case) and provides them in a list. The list consists of tuples where each tuple consists of all the column values present in the particular record or row." }, { "code": null, "e": 2437, "s": 2430, "text": "Python" }, { "code": "# This program uses fetchone() to# query one by one record from a table # GET THE CONNECTION OBJECTconn = get_connection() # CREATE A CURSOR USING THE CONNECTION OBJECTcurr = conn.cursor() # EXECUTE THE SQL QUERYcurr.execute(\"SELECT * FROM students;\") # FETCH THE FIRST ROW FROM THE CURSORdata1 = curr.fetchone()print(data1) # FETCH THE SECOND ROW FROM THE CURSORdata2 = curr.fetchone()print(data2) # CLOSE THE CONNECTIONconn.close()", "e": 2877, "s": 2437, "text": null }, { "code": null, "e": 2885, "s": 2877, "text": "Output:" }, { "code": null, "e": 2907, "s": 2885, "text": "Output for fetchone()" }, { "code": null, "e": 3543, "s": 2907, "text": "The fetchone() method is not to be confused with the idea that it queries the first row only. The fetchone() method returns the first record from the dump that we got from the SQL query present in curr.execute() method. It behaves like a queue where we query the first record and then it gets deleted from the cursor object. Now, if we try to use the fetchone() method again, it will return the next record. The above code demonstrates the same where we fetched the first record and then used the fetchone() method again to fetch the next record in the queue. We can keep doing this until we reach the last record in the cursor object." }, { "code": null, "e": 3550, "s": 3543, "text": "Python" }, { "code": "# This program uses fetchmany() # to query specified number of records from a table # GET THE CONNECTION OBJECTconn = get_connection() # CREATE A CURSOR USING THE CONNECTION OBJECTcurr = conn.cursor() # EXECUTE THE SQL QUERYcurr.execute(\"SELECT * FROM students;\") print(\"First two records:\") # GET FIRST TWO RECORDS FROM DATABASE TABLEdata1 = curr.fetchmany(2)for row in data1: print(row) print(\"Next three records:\") # GET NEXT THREE RECORDS FROM DATABASE TABLEdata2 = curr.fetchmany(3)for row in data2: print(row) # CLOSE THE CONNECTIONconn.close()", "e": 4115, "s": 3550, "text": null }, { "code": null, "e": 4123, "s": 4115, "text": "Output:" }, { "code": null, "e": 4146, "s": 4123, "text": "Output for fetchmany()" }, { "code": null, "e": 4701, "s": 4146, "text": "We have seen how to query all the records and to query one-by-one records. The fetchmany() method takes in the no. of records that we want to fetch from the entire dump. It also behaves like a queue as we saw in the fetchone() method, except for the fact that it can fetch more than one record at a time. However, using fetchmany(1) is equivalent to using fetchone() method. In the above code, we used the fetchmany(2) to query the first two records and then used the fetchmany(3) to query the next 3 records. The same can be noticed in the below output." }, { "code": null, "e": 4708, "s": 4701, "text": "Picked" }, { "code": null, "e": 4726, "s": 4708, "text": "Python PostgreSQL" }, { "code": null, "e": 4742, "s": 4726, "text": "Python Pyscopg2" }, { "code": null, "e": 4749, "s": 4742, "text": "Python" } ]
Create a Website Alarm Using Python
19 Nov, 2020 We use Bookmarks to remember the important websites which we think we will use them very often in future.Here’s a simple python code which takes the URL of the website as its first input and the time you want to open it as the second input. As the time reaches your given value of the time, it’ll open the URL that you requested in the web browser automatically.In this code, we’ll import two python modules – Time and Webbrowser. # Import the time module, it provides various time-related # functions. import time # Import the webbrowser module, it is used to # display various HTML documents to the user. import webbrowser # First Input: It is the time of the form # 'Hours:Minutes:Seconds' that you'll # use to set the alarm. Set_Alarm = input("Set the website alarm as H:M:S:") # Second Input: It is the URL that you want # to open on the given time. url = input("Enter the website you want to open:") # This is the actual time that we will use to print. Actual_Time = time.strftime("%I:%M:%S") # This is the while loop that'll print the time # until it's value will be equal to the alarm time while (Actual_Time != Set_Alarm): print ("The time is " + Actual_Time) Actual_Time = time.strftime("%I:%M:%S") time.sleep(1) # This if statement plays the role when its the # alarm time and executes the code within it. if (Actual_Time == Set_Alarm): print ("You should see your webpage now :-)") # We are calling the open() # function from the webrowser module. webbrowser.open(url) You can contribute to the code by going here. This article is contributed by Shivam Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. You can contribute to the code by going here. Python Web Technologies 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() 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": "\n19 Nov, 2020" }, { "code": null, "e": 295, "s": 54, "text": "We use Bookmarks to remember the important websites which we think we will use them very often in future.Here’s a simple python code which takes the URL of the website as its first input and the time you want to open it as the second input." }, { "code": null, "e": 485, "s": 295, "text": "As the time reaches your given value of the time, it’ll open the URL that you requested in the web browser automatically.In this code, we’ll import two python modules – Time and Webbrowser." }, { "code": "# Import the time module, it provides various time-related # functions. import time # Import the webbrowser module, it is used to # display various HTML documents to the user. import webbrowser # First Input: It is the time of the form # 'Hours:Minutes:Seconds' that you'll # use to set the alarm. Set_Alarm = input(\"Set the website alarm as H:M:S:\") # Second Input: It is the URL that you want # to open on the given time. url = input(\"Enter the website you want to open:\") # This is the actual time that we will use to print. Actual_Time = time.strftime(\"%I:%M:%S\") # This is the while loop that'll print the time # until it's value will be equal to the alarm time while (Actual_Time != Set_Alarm): print (\"The time is \" + Actual_Time) Actual_Time = time.strftime(\"%I:%M:%S\") time.sleep(1) # This if statement plays the role when its the # alarm time and executes the code within it. if (Actual_Time == Set_Alarm): print (\"You should see your webpage now :-)\") # We are calling the open() # function from the webrowser module. webbrowser.open(url) ", "e": 1579, "s": 485, "text": null }, { "code": null, "e": 1625, "s": 1579, "text": "You can contribute to the code by going here." }, { "code": null, "e": 1926, "s": 1625, "text": "This article is contributed by Shivam Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 1972, "s": 1926, "text": "You can contribute to the code by going here." }, { "code": null, "e": 1979, "s": 1972, "text": "Python" }, { "code": null, "e": 1996, "s": 1979, "text": "Web Technologies" }, { "code": null, "e": 2094, "s": 1996, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2112, "s": 2094, "text": "Python Dictionary" }, { "code": null, "e": 2154, "s": 2112, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2176, "s": 2154, "text": "Enumerate() in Python" }, { "code": null, "e": 2211, "s": 2176, "text": "Read a file line by line in Python" }, { "code": null, "e": 2237, "s": 2211, "text": "Python String | replace()" }, { "code": null, "e": 2270, "s": 2237, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2332, "s": 2270, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2393, "s": 2332, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2443, "s": 2393, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python3 Program to Find all triplets with zero sum
06 Jan, 2022 Given an array of distinct elements. The task is to find triplets in the array whose sum is zero. Examples : Input : arr[] = {0, -1, 2, -3, 1} Output : (0 -1 1), (2 -3 1) Explanation : The triplets with zero sum are 0 + -1 + 1 = 0 and 2 + -3 + 1 = 0 Input : arr[] = {1, -2, 1, 0, 5} Output : 1 -2 1 Explanation : The triplets with zero sum is 1 + -2 + 1 = 0 Method 1: This is a simple method that takes O(n3) time to arrive at the result. Approach: The naive approach runs three loops and check one by one that sum of three elements is zero or not. If the sum of three elements is zero then print elements otherwise print not found. Algorithm: Run three nested loops with loop counter i, j, kThe first loops will run from 0 to n-3 and second loop from i+1 to n-2 and the third loop from j+1 to n-1. The loop counter represents the three elements of the triplet.Check if the sum of elements at i’th, j’th, k’th is equal to zero or not. If yes print the sum else continue. Run three nested loops with loop counter i, j, kThe first loops will run from 0 to n-3 and second loop from i+1 to n-2 and the third loop from j+1 to n-1. The loop counter represents the three elements of the triplet.Check if the sum of elements at i’th, j’th, k’th is equal to zero or not. If yes print the sum else continue. Run three nested loops with loop counter i, j, k The first loops will run from 0 to n-3 and second loop from i+1 to n-2 and the third loop from j+1 to n-1. The loop counter represents the three elements of the triplet. Check if the sum of elements at i’th, j’th, k’th is equal to zero or not. If yes print the sum else continue. Below is the implementation of the above approach: Python3 # A simple Python 3 program # to find three elements whose # sum is equal to zero # Prints all triplets in # arr[] with 0 sumdef findTriplets(arr, n): found = False for i in range(0, n-2): for j in range(i+1, n-1): for k in range(j+1, n): if (arr[i] + arr[j] + arr[k] == 0): print(arr[i], arr[j], arr[k]) found = True # If no triplet with 0 sum # found in array if (found == False): print(" not exist ") # Driver codearr = [0, -1, 2, -3, 1]n = len(arr)findTriplets(arr, n) # This code is contributed by Smitha Dinesh Semwal 0 -1 1 2 -3 1 Complexity Analysis: Time Complexity: O(n3). As three nested loops are required, so the time complexity is O(n3). Auxiliary Space: O(1). Since no extra space is required, so the space complexity is constant. Method 2: The second method uses the process of Hashing to arrive at the result and is solved at a lesser time of O(n2). Approach: This involves traversing through the array. For every element arr[i], find a pair with sum “-arr[i]”. This problem reduces to pair sum and can be solved in O(n) time using hashing. Algorithm: Create a hashmap to store a key-value pair.Run a nested loop with two loops, the outer loop from 0 to n-2 and the inner loop from i+1 to n-1Check if the sum of ith and jth element multiplied with -1 is present in the hashmap or notIf the element is present in the hashmap, print the triplet else insert the j’th element in the hashmap. Create a hashmap to store a key-value pair. Run a nested loop with two loops, the outer loop from 0 to n-2 and the inner loop from i+1 to n-1 Check if the sum of ith and jth element multiplied with -1 is present in the hashmap or not If the element is present in the hashmap, print the triplet else insert the j’th element in the hashmap. Below is the implementation of the above approach: Python3 # Python3 program to find triplets # in a given array whose sum is zero # function to print triplets with 0 sum def findTriplets(arr, n): found = False for i in range(n - 1): # Find all pairs with sum # equals to "-arr[i]" s = set() for j in range(i + 1, n): x = -(arr[i] + arr[j]) if x in s: print(x, arr[i], arr[j]) found = True else: s.add(arr[j]) if found == False: print("No Triplet Found") # Driver Codearr = [0, -1, 2, -3, 1]n = len(arr)findTriplets(arr, n) # This code is contributed by Shrikant13 -1 0 1 -3 2 1 Complexity Analysis: Time Complexity: O(n2). Since two nested loops are required, so the time complexity is O(n2). Auxiliary Space: O(n). Since a hashmap is required, so the space complexity is linear. Method 3: This method uses Sorting to arrive at the correct result and is solved in O(n2) time. Approach: The above method requires extra space. The idea is based on method 2 of this post. For every element check that there is a pair whose sum is equal to the negative value of that element. Algorithm: Sort the array in ascending order.Traverse the array from start to end.For every index i, create two variables l = i + 1 and r = n – 1Run a loop until l is less than r if the sum of array[i], array[l] and array[r] is equal to zero then print the triplet and break the loopIf the sum is less than zero then increment the value of l, by increasing the value of l the sum will increase as the array is sorted, so array[l+1] > array [l]If the sum is greater than zero then decrement the value of r, by increasing the value of l the sum will decrease as the array is sorted, so array[r-1] < array [r]. Sort the array in ascending order. Traverse the array from start to end. For every index i, create two variables l = i + 1 and r = n – 1 Run a loop until l is less than r if the sum of array[i], array[l] and array[r] is equal to zero then print the triplet and break the loop If the sum is less than zero then increment the value of l, by increasing the value of l the sum will increase as the array is sorted, so array[l+1] > array [l] If the sum is greater than zero then decrement the value of r, by increasing the value of l the sum will decrease as the array is sorted, so array[r-1] < array [r]. Below is the implementation of the above approach: Python3 # python program to find triplets in a given# array whose sum is zero # function to print triplets with 0 sumdef findTriplets(arr, n): found = False # sort array elements arr.sort() for i in range(0, n-1): # initialize left and right l = i + 1 r = n - 1 x = arr[i] while (l < r): if (x + arr[l] + arr[r] == 0): # print elements if it's sum is zero print(x, arr[l], arr[r]) l+=1 r-=1 found = True # If sum of three elements is less # than zero then increment in left elif (x + arr[l] + arr[r] < 0): l+=1 # if sum is greater than zero than # decrement in right side else: r-=1 if (found == False): print(" No Triplet Found") # Driven sourcearr = [0, -1, 2, -3, 1]n = len(arr)findTriplets(arr, n) # This code is contributed by Smitha Dinesh Semwal -3 1 2 -1 0 1 Complexity Analysis: Time Complexity : O(n2). Only two nested loops are required, so the time complexity is O(n2). Auxiliary Space : O(1), no extra space is required, so the time complexity is constant. Please refer complete article on Find all triplets with zero sum for more details! Facebook Google two-pointer-algorithm Arrays Hash Python Searching Sorting Google Facebook two-pointer-algorithm Arrays Searching Hash Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) What is Hashing | A Complete Tutorial Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Count pairs with given sum
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jan, 2022" }, { "code": null, "e": 126, "s": 28, "text": "Given an array of distinct elements. The task is to find triplets in the array whose sum is zero." }, { "code": null, "e": 138, "s": 126, "text": "Examples : " }, { "code": null, "e": 395, "s": 138, "text": "Input : arr[] = {0, -1, 2, -3, 1}\nOutput : (0 -1 1), (2 -3 1)\n\nExplanation : The triplets with zero sum are\n0 + -1 + 1 = 0 and 2 + -3 + 1 = 0 \n\nInput : arr[] = {1, -2, 1, 0, 5}\nOutput : 1 -2 1\nExplanation : The triplets with zero sum is\n1 + -2 + 1 = 0 " }, { "code": null, "e": 476, "s": 395, "text": "Method 1: This is a simple method that takes O(n3) time to arrive at the result." }, { "code": null, "e": 670, "s": 476, "text": "Approach: The naive approach runs three loops and check one by one that sum of three elements is zero or not. If the sum of three elements is zero then print elements otherwise print not found." }, { "code": null, "e": 1008, "s": 670, "text": "Algorithm: Run three nested loops with loop counter i, j, kThe first loops will run from 0 to n-3 and second loop from i+1 to n-2 and the third loop from j+1 to n-1. The loop counter represents the three elements of the triplet.Check if the sum of elements at i’th, j’th, k’th is equal to zero or not. If yes print the sum else continue." }, { "code": null, "e": 1335, "s": 1008, "text": "Run three nested loops with loop counter i, j, kThe first loops will run from 0 to n-3 and second loop from i+1 to n-2 and the third loop from j+1 to n-1. The loop counter represents the three elements of the triplet.Check if the sum of elements at i’th, j’th, k’th is equal to zero or not. If yes print the sum else continue." }, { "code": null, "e": 1384, "s": 1335, "text": "Run three nested loops with loop counter i, j, k" }, { "code": null, "e": 1554, "s": 1384, "text": "The first loops will run from 0 to n-3 and second loop from i+1 to n-2 and the third loop from j+1 to n-1. The loop counter represents the three elements of the triplet." }, { "code": null, "e": 1664, "s": 1554, "text": "Check if the sum of elements at i’th, j’th, k’th is equal to zero or not. If yes print the sum else continue." }, { "code": null, "e": 1716, "s": 1664, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1724, "s": 1716, "text": "Python3" }, { "code": "# A simple Python 3 program # to find three elements whose # sum is equal to zero # Prints all triplets in # arr[] with 0 sumdef findTriplets(arr, n): found = False for i in range(0, n-2): for j in range(i+1, n-1): for k in range(j+1, n): if (arr[i] + arr[j] + arr[k] == 0): print(arr[i], arr[j], arr[k]) found = True # If no triplet with 0 sum # found in array if (found == False): print(\" not exist \") # Driver codearr = [0, -1, 2, -3, 1]n = len(arr)findTriplets(arr, n) # This code is contributed by Smitha Dinesh Semwal ", "e": 2401, "s": 1724, "text": null }, { "code": null, "e": 2415, "s": 2401, "text": "0 -1 1\n2 -3 1" }, { "code": null, "e": 2437, "s": 2415, "text": "Complexity Analysis: " }, { "code": null, "e": 2530, "s": 2437, "text": "Time Complexity: O(n3). As three nested loops are required, so the time complexity is O(n3)." }, { "code": null, "e": 2624, "s": 2530, "text": "Auxiliary Space: O(1). Since no extra space is required, so the space complexity is constant." }, { "code": null, "e": 2747, "s": 2624, "text": " Method 2: The second method uses the process of Hashing to arrive at the result and is solved at a lesser time of O(n2). " }, { "code": null, "e": 2938, "s": 2747, "text": "Approach: This involves traversing through the array. For every element arr[i], find a pair with sum “-arr[i]”. This problem reduces to pair sum and can be solved in O(n) time using hashing." }, { "code": null, "e": 2950, "s": 2938, "text": "Algorithm: " }, { "code": null, "e": 3286, "s": 2950, "text": "Create a hashmap to store a key-value pair.Run a nested loop with two loops, the outer loop from 0 to n-2 and the inner loop from i+1 to n-1Check if the sum of ith and jth element multiplied with -1 is present in the hashmap or notIf the element is present in the hashmap, print the triplet else insert the j’th element in the hashmap." }, { "code": null, "e": 3330, "s": 3286, "text": "Create a hashmap to store a key-value pair." }, { "code": null, "e": 3428, "s": 3330, "text": "Run a nested loop with two loops, the outer loop from 0 to n-2 and the inner loop from i+1 to n-1" }, { "code": null, "e": 3520, "s": 3428, "text": "Check if the sum of ith and jth element multiplied with -1 is present in the hashmap or not" }, { "code": null, "e": 3625, "s": 3520, "text": "If the element is present in the hashmap, print the triplet else insert the j’th element in the hashmap." }, { "code": null, "e": 3677, "s": 3625, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 3685, "s": 3677, "text": "Python3" }, { "code": "# Python3 program to find triplets # in a given array whose sum is zero # function to print triplets with 0 sum def findTriplets(arr, n): found = False for i in range(n - 1): # Find all pairs with sum # equals to \"-arr[i]\" s = set() for j in range(i + 1, n): x = -(arr[i] + arr[j]) if x in s: print(x, arr[i], arr[j]) found = True else: s.add(arr[j]) if found == False: print(\"No Triplet Found\") # Driver Codearr = [0, -1, 2, -3, 1]n = len(arr)findTriplets(arr, n) # This code is contributed by Shrikant13", "e": 4321, "s": 3685, "text": null }, { "code": null, "e": 4335, "s": 4321, "text": "-1 0 1\n-3 2 1" }, { "code": null, "e": 4357, "s": 4335, "text": "Complexity Analysis: " }, { "code": null, "e": 4451, "s": 4357, "text": "Time Complexity: O(n2). Since two nested loops are required, so the time complexity is O(n2)." }, { "code": null, "e": 4538, "s": 4451, "text": "Auxiliary Space: O(n). Since a hashmap is required, so the space complexity is linear." }, { "code": null, "e": 4637, "s": 4538, "text": " Method 3: This method uses Sorting to arrive at the correct result and is solved in O(n2) time. " }, { "code": null, "e": 4833, "s": 4637, "text": "Approach: The above method requires extra space. The idea is based on method 2 of this post. For every element check that there is a pair whose sum is equal to the negative value of that element." }, { "code": null, "e": 4845, "s": 4833, "text": "Algorithm: " }, { "code": null, "e": 5442, "s": 4845, "text": "Sort the array in ascending order.Traverse the array from start to end.For every index i, create two variables l = i + 1 and r = n – 1Run a loop until l is less than r if the sum of array[i], array[l] and array[r] is equal to zero then print the triplet and break the loopIf the sum is less than zero then increment the value of l, by increasing the value of l the sum will increase as the array is sorted, so array[l+1] > array [l]If the sum is greater than zero then decrement the value of r, by increasing the value of l the sum will decrease as the array is sorted, so array[r-1] < array [r]." }, { "code": null, "e": 5477, "s": 5442, "text": "Sort the array in ascending order." }, { "code": null, "e": 5515, "s": 5477, "text": "Traverse the array from start to end." }, { "code": null, "e": 5579, "s": 5515, "text": "For every index i, create two variables l = i + 1 and r = n – 1" }, { "code": null, "e": 5718, "s": 5579, "text": "Run a loop until l is less than r if the sum of array[i], array[l] and array[r] is equal to zero then print the triplet and break the loop" }, { "code": null, "e": 5879, "s": 5718, "text": "If the sum is less than zero then increment the value of l, by increasing the value of l the sum will increase as the array is sorted, so array[l+1] > array [l]" }, { "code": null, "e": 6044, "s": 5879, "text": "If the sum is greater than zero then decrement the value of r, by increasing the value of l the sum will decrease as the array is sorted, so array[r-1] < array [r]." }, { "code": null, "e": 6096, "s": 6044, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 6104, "s": 6096, "text": "Python3" }, { "code": "# python program to find triplets in a given# array whose sum is zero # function to print triplets with 0 sumdef findTriplets(arr, n): found = False # sort array elements arr.sort() for i in range(0, n-1): # initialize left and right l = i + 1 r = n - 1 x = arr[i] while (l < r): if (x + arr[l] + arr[r] == 0): # print elements if it's sum is zero print(x, arr[l], arr[r]) l+=1 r-=1 found = True # If sum of three elements is less # than zero then increment in left elif (x + arr[l] + arr[r] < 0): l+=1 # if sum is greater than zero than # decrement in right side else: r-=1 if (found == False): print(\" No Triplet Found\") # Driven sourcearr = [0, -1, 2, -3, 1]n = len(arr)findTriplets(arr, n) # This code is contributed by Smitha Dinesh Semwal", "e": 7143, "s": 6104, "text": null }, { "code": null, "e": 7157, "s": 7143, "text": "-3 1 2\n-1 0 1" }, { "code": null, "e": 7179, "s": 7157, "text": "Complexity Analysis: " }, { "code": null, "e": 7273, "s": 7179, "text": "Time Complexity : O(n2). Only two nested loops are required, so the time complexity is O(n2)." }, { "code": null, "e": 7361, "s": 7273, "text": "Auxiliary Space : O(1), no extra space is required, so the time complexity is constant." }, { "code": null, "e": 7444, "s": 7361, "text": "Please refer complete article on Find all triplets with zero sum for more details!" }, { "code": null, "e": 7453, "s": 7444, "text": "Facebook" }, { "code": null, "e": 7460, "s": 7453, "text": "Google" }, { "code": null, "e": 7482, "s": 7460, "text": "two-pointer-algorithm" }, { "code": null, "e": 7489, "s": 7482, "text": "Arrays" }, { "code": null, "e": 7494, "s": 7489, "text": "Hash" }, { "code": null, "e": 7501, "s": 7494, "text": "Python" }, { "code": null, "e": 7511, "s": 7501, "text": "Searching" }, { "code": null, "e": 7519, "s": 7511, "text": "Sorting" }, { "code": null, "e": 7526, "s": 7519, "text": "Google" }, { "code": null, "e": 7535, "s": 7526, "text": "Facebook" }, { "code": null, "e": 7557, "s": 7535, "text": "two-pointer-algorithm" }, { "code": null, "e": 7564, "s": 7557, "text": "Arrays" }, { "code": null, "e": 7574, "s": 7564, "text": "Searching" }, { "code": null, "e": 7579, "s": 7574, "text": "Hash" }, { "code": null, "e": 7587, "s": 7579, "text": "Sorting" }, { "code": null, "e": 7685, "s": 7587, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7753, "s": 7685, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 7797, "s": 7753, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 7829, "s": 7797, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 7877, "s": 7829, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 7891, "s": 7877, "text": "Linear Search" }, { "code": null, "e": 7976, "s": 7891, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 8014, "s": 7976, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 8050, "s": 8014, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 8081, "s": 8050, "text": "Hashing | Set 1 (Introduction)" } ]
Difference between try-catch and if-else statements in PHP
12 Dec, 2021 The try and catch are used in PHP for handling exceptions like other languages such as C++, Java, etc. An exception is unexpected result or unexpected state of a program that can be handled by the program itself. To handle this kind of unexpected results in PHP, try and catch are used. For more details, visit Exception Handling in PHP. Similarly, PHP also executes conditional statements using if and else to handle decision making scenarios. For more details, visit PHP | Decision Making Differences between ‘try-catch’ and ‘if-else’ in PHP: What are ‘if’ and ‘else’? if: It checks if any condition is “true” or not, if it is true then it executes the code inside the if block. else: If the condition is “false” which is checked by the if block, then else block executes the other code within it. if(condition) {......} else {......} or if(condition) {......} else if(condition) {......} else {......} What are ‘try’ and ‘catch’? try: It is a section where a block of code is defined for tested whether the code generates an unexpected result while executing. catch: It is a section where another block of code is defined, which is executed if any unexpected result generates in the try block. Actually this block of code handles the exceptions. try {...condition...; ...condition..; .....; .....; .....; } catch (Exception) {...handling exception...;} Error Handling: Mainly if-else block is used to handle errors using condition checking. if-else catch errors as a conditional statement. In many cases there are many corner cases which must be checking during a execution but “if-else” can only handle the defined conditions. In if-else, conditions are manually generated based on the task. php <?php $g = "GeeksforGeeks"; // Checks for a condition if// 'g'is null or notif ($g != "") { echo $g;} else { echo "This is not the string";}?> Output: GeeksforGeeks In case of try-catch block, it will check the system generated errors or exception during an executing process or a task. These errors or exceptions are not manually generated. try-catch handles the exceptions that are easily readable. php <?php // Exception handling functionfunction tryCatchException($b, $var) { try { echo "\nDivision is ", $b/$var; throw new Exception('denominator is 0'); // If 'var' is zero then exception // is thrown } // Catch block will be executed if // any Exception has been thrown // by try block catch(Exception $e) { echo "\nException: ", $e->getMessage(); // Print the Message passed // by the thrown statement }} // Exception will happenedtryCatchException(6, 0); ?> Output: Runtime Errors : PHP Warning: Division by zero in /home/1027ff9c161eb6503f545005908318fc.php on line 8 Division is INF Exception: denominator is 0 Use one block to handle errors or exception: In case of if-else we have one else block corresponding to one if block, so we have to define each if block with a else block to handle “false” conditions. Also there may not be any else statement after if. php <?php function rngeLaptop($a) { // Each 'if' with one 'else' if ($a == "Gaming") { echo "Range stated from 50000rs\n"; } else if($a == "Education") { echo "Range stated from 25000rs\n"; } else if($a == "Graphics works") { echo "Range stated from 55000rs\n"; } else if($a == "Entertainment") { echo "Range stated from 18000rs\n"; } else { echo "Not listed\n"; }} rngeLaptop("Gaming");rngeLaptop("Education");rngeLaptop("Movie"); // Not listedrngeLaptop("Entertainment");rngeLaptop("Graphics works"); ?> Output: Range stated from 50000rs Range stated from 25000rs Not listed Range stated from 18000rs Range stated from 55000rs In case of try-catch, we don’t have to define each try with a catch. There can be multiple exceptions defines inside one try and to catch the exceptions thrown by the try block, there can be one catch block. php <?php // Exception handling functionfunction tryCatchException($b, $var) { try { // Checking 2 condition and throwing // all exceptions in one catch block if($var == 0) { throw new Exception('denominator is 0'); } if($var < 0) { throw new Exception('denominator is a negative'); } echo "\nDivision is ", $b/$var; } // Catch block will be executed if any // Exception has been thrown by try block catch(Exception $e) { // Print the Message passed by // the thrown statement echo "\nException: ", $e->getMessage(); }} // Exception will happenedtryCatchException(6, -3);tryCatchException(12, 0);tryCatchException(15, 3); ?> Output: Exception: denominator is a string Exception: denominator is 0 Division is 5 Brief discussion about the differences of ‘try-catch’ and ‘if-else’ in PHP: sweetyty PHP-Misc 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 ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime 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 check whether an array is empty using PHP? How to call PHP function on the click of a Button ?
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Dec, 2021" }, { "code": null, "e": 390, "s": 52, "text": "The try and catch are used in PHP for handling exceptions like other languages such as C++, Java, etc. An exception is unexpected result or unexpected state of a program that can be handled by the program itself. To handle this kind of unexpected results in PHP, try and catch are used. For more details, visit Exception Handling in PHP." }, { "code": null, "e": 543, "s": 390, "text": "Similarly, PHP also executes conditional statements using if and else to handle decision making scenarios. For more details, visit PHP | Decision Making" }, { "code": null, "e": 597, "s": 543, "text": "Differences between ‘try-catch’ and ‘if-else’ in PHP:" }, { "code": null, "e": 624, "s": 597, "text": "What are ‘if’ and ‘else’? " }, { "code": null, "e": 734, "s": 624, "text": "if: It checks if any condition is “true” or not, if it is true then it executes the code inside the if block." }, { "code": null, "e": 853, "s": 734, "text": "else: If the condition is “false” which is checked by the if block, then else block executes the other code within it." }, { "code": null, "e": 891, "s": 853, "text": "if(condition)\n{......}\nelse\n{......} " }, { "code": null, "e": 894, "s": 891, "text": "or" }, { "code": null, "e": 959, "s": 894, "text": "if(condition)\n{......}\nelse if(condition)\n{......}\nelse\n{......}" }, { "code": null, "e": 988, "s": 959, "text": "What are ‘try’ and ‘catch’? " }, { "code": null, "e": 1118, "s": 988, "text": "try: It is a section where a block of code is defined for tested whether the code generates an unexpected result while executing." }, { "code": null, "e": 1306, "s": 1118, "text": "catch: It is a section where another block of code is defined, which is executed if any unexpected result generates in the try block. Actually this block of code handles the exceptions. " }, { "code": null, "e": 1417, "s": 1306, "text": "try\n{...condition...;\n ...condition..;\n .....;\n .....;\n .....;\n}\ncatch (Exception)\n{...handling exception...;}" }, { "code": null, "e": 1758, "s": 1417, "text": "Error Handling: Mainly if-else block is used to handle errors using condition checking. if-else catch errors as a conditional statement. In many cases there are many corner cases which must be checking during a execution but “if-else” can only handle the defined conditions. In if-else, conditions are manually generated based on the task. " }, { "code": null, "e": 1762, "s": 1758, "text": "php" }, { "code": "<?php $g = \"GeeksforGeeks\"; // Checks for a condition if// 'g'is null or notif ($g != \"\") { echo $g;} else { echo \"This is not the string\";}?>", "e": 1911, "s": 1762, "text": null }, { "code": null, "e": 1920, "s": 1911, "text": "Output: " }, { "code": null, "e": 1934, "s": 1920, "text": "GeeksforGeeks" }, { "code": null, "e": 2170, "s": 1934, "text": "In case of try-catch block, it will check the system generated errors or exception during an executing process or a task. These errors or exceptions are not manually generated. try-catch handles the exceptions that are easily readable." }, { "code": null, "e": 2174, "s": 2170, "text": "php" }, { "code": "<?php // Exception handling functionfunction tryCatchException($b, $var) { try { echo \"\\nDivision is \", $b/$var; throw new Exception('denominator is 0'); // If 'var' is zero then exception // is thrown } // Catch block will be executed if // any Exception has been thrown // by try block catch(Exception $e) { echo \"\\nException: \", $e->getMessage(); // Print the Message passed // by the thrown statement }} // Exception will happenedtryCatchException(6, 0); ?>", "e": 2714, "s": 2174, "text": null }, { "code": null, "e": 2724, "s": 2714, "text": "Output: " }, { "code": null, "e": 2875, "s": 2724, "text": "Runtime Errors : \nPHP Warning: Division by zero in \n/home/1027ff9c161eb6503f545005908318fc.php on line 8\nDivision is INF\nException: denominator is 0 " }, { "code": null, "e": 3127, "s": 2875, "text": "Use one block to handle errors or exception: In case of if-else we have one else block corresponding to one if block, so we have to define each if block with a else block to handle “false” conditions. Also there may not be any else statement after if." }, { "code": null, "e": 3131, "s": 3127, "text": "php" }, { "code": "<?php function rngeLaptop($a) { // Each 'if' with one 'else' if ($a == \"Gaming\") { echo \"Range stated from 50000rs\\n\"; } else if($a == \"Education\") { echo \"Range stated from 25000rs\\n\"; } else if($a == \"Graphics works\") { echo \"Range stated from 55000rs\\n\"; } else if($a == \"Entertainment\") { echo \"Range stated from 18000rs\\n\"; } else { echo \"Not listed\\n\"; }} rngeLaptop(\"Gaming\");rngeLaptop(\"Education\");rngeLaptop(\"Movie\"); // Not listedrngeLaptop(\"Entertainment\");rngeLaptop(\"Graphics works\"); ?>", "e": 3717, "s": 3131, "text": null }, { "code": null, "e": 3726, "s": 3717, "text": "Output: " }, { "code": null, "e": 3841, "s": 3726, "text": "Range stated from 50000rs\nRange stated from 25000rs\nNot listed\nRange stated from 18000rs\nRange stated from 55000rs" }, { "code": null, "e": 4049, "s": 3841, "text": "In case of try-catch, we don’t have to define each try with a catch. There can be multiple exceptions defines inside one try and to catch the exceptions thrown by the try block, there can be one catch block." }, { "code": null, "e": 4053, "s": 4049, "text": "php" }, { "code": "<?php // Exception handling functionfunction tryCatchException($b, $var) { try { // Checking 2 condition and throwing // all exceptions in one catch block if($var == 0) { throw new Exception('denominator is 0'); } if($var < 0) { throw new Exception('denominator is a negative'); } echo \"\\nDivision is \", $b/$var; } // Catch block will be executed if any // Exception has been thrown by try block catch(Exception $e) { // Print the Message passed by // the thrown statement echo \"\\nException: \", $e->getMessage(); }} // Exception will happenedtryCatchException(6, -3);tryCatchException(12, 0);tryCatchException(15, 3); ?>", "e": 4821, "s": 4053, "text": null }, { "code": null, "e": 4830, "s": 4821, "text": "Output: " }, { "code": null, "e": 4908, "s": 4830, "text": "Exception: denominator is a string\nException: denominator is 0\nDivision is 5 " }, { "code": null, "e": 4985, "s": 4908, "text": "Brief discussion about the differences of ‘try-catch’ and ‘if-else’ in PHP: " }, { "code": null, "e": 4994, "s": 4985, "text": "sweetyty" }, { "code": null, "e": 5003, "s": 4994, "text": "PHP-Misc" }, { "code": null, "e": 5007, "s": 5003, "text": "PHP" }, { "code": null, "e": 5020, "s": 5007, "text": "PHP Programs" }, { "code": null, "e": 5037, "s": 5020, "text": "Web Technologies" }, { "code": null, "e": 5064, "s": 5037, "text": "Web technologies Questions" }, { "code": null, "e": 5068, "s": 5064, "text": "PHP" }, { "code": null, "e": 5166, "s": 5068, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5216, "s": 5166, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 5256, "s": 5216, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 5317, "s": 5256, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 5367, "s": 5317, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 5412, "s": 5367, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 5462, "s": 5412, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 5502, "s": 5462, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 5563, "s": 5502, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 5613, "s": 5563, "text": "How to check whether an array is empty using PHP?" } ]
Print all possible strings that can be made by placing spaces
24 Jun, 2022 Given a string you need to print all possible strings that can be made by placing spaces (zero or one) in between them. Input: str[] = "ABC" Output: ABC AB C A BC A B C Source: Amazon Interview Experience | Set 158, Round 1, Q 1. The idea is to use recursion and create a buffer that one by one contains all output strings having spaces. We keep updating the buffer in every recursive call. If the length of the given string is ‘n’ our updated string can have a maximum length of n + (n-1) i.e. 2n-1. So we create a buffer size of 2n (one extra character for string termination). We leave 1st character as it is, starting from the 2nd character, we can either fill a space or a character. Thus, one can write a recursive function like below. Below is the implementation of the above approach: C++ Java Python C# PHP Javascript // C++ program to print permutations// of a given string with spaces.#include <cstring>#include <iostream>using namespace std; /* Function recursively prints the strings having space pattern. i and j are indices in 'str[]' and 'buff[]' respectively */void printPatternUtil(const char str[], char buff[], int i, int j, int n){ if (i == n) { buff[j] = '\0'; cout << buff << endl; return; } // Either put the character buff[j] = str[i]; printPatternUtil(str, buff, i + 1, j + 1, n); // Or put a space followed by next character buff[j] = ' '; buff[j + 1] = str[i]; printPatternUtil(str, buff, i + 1, j + 2, n);} // This function creates buf[] to// store individual output string and uses// printPatternUtil() to print all permutations.void printPattern(const char* str){ int n = strlen(str); // Buffer to hold the string // containing spaces // 2n - 1 characters and 1 string terminator char buf[2 * n]; // Copy the first character as // it is, since it will be always // at first position buf[0] = str[0]; printPatternUtil(str, buf, 1, 1, n);} // Driver program to test above functionsint main(){ const char* str = "ABCD"; printPattern(str); return 0;} // Java program to print permutations// of a given string with// spacesimport java.io.*; class Permutation{ // Function recursively prints // the strings having space // pattern i and j are indices in 'String str' and // 'buf[]' respectively static void printPatternUtil(String str, char buf[], int i, int j, int n) { if (i == n) { buf[j] = '\0'; System.out.println(buf); return; } // Either put the character buf[j] = str.charAt(i); printPatternUtil(str, buf, i + 1, j + 1, n); // Or put a space followed // by next character buf[j] = ' '; buf[j + 1] = str.charAt(i); printPatternUtil(str, buf, i + 1, j + 2, n); } // Function creates buf[] to // store individual output // string and uses printPatternUtil() // to print all // permutations static void printPattern(String str) { int len = str.length(); // Buffer to hold the string // containing spaces // 2n-1 characters and 1 // string terminator char[] buf = new char[2 * len]; // Copy the first character as it is, since it will // be always at first position buf[0] = str.charAt(0); printPatternUtil(str, buf, 1, 1, len); } // Driver program public static void main(String[] args) { String str = "ABCD"; printPattern(str); }} # Python program to print permutations# of a given string with# spaces. # Utility functiondef toString(List): s = "" for x in List: if x == '&# 092;&# 048;': break s += x return s # Function recursively prints the# strings having space pattern.# i and j are indices in 'str[]'# and 'buff[]' respectivelydef printPatternUtil(string, buff, i, j, n): if i == n: buff[j] = '&# 092;&# 048;' print toString(buff) return # Either put the character buff[j] = string[i] printPatternUtil(string, buff, i + 1, j + 1, n) # Or put a space followed by next character buff[j] = ' ' buff[j + 1] = string[i] printPatternUtil(string, buff, i + 1, j + 2, n) # This function creates buf[] to# store individual output string# and uses printPatternUtil() to# print all permutations.def printPattern(string): n = len(string) # Buffer to hold the string # containing spaces # 2n - 1 characters and 1 string terminator buff = [0] * (2 * n) # Copy the first character as it is, # since it will be always # at first position buff[0] = string[0] printPatternUtil(string, buff, 1, 1, n) # Driver programstring = "ABCD"printPattern(string) # This code is contributed by BHAVYA JAIN // C# program to print permutations of a// given string with spacesusing System; class GFG{ // Function recursively prints the // strings having space pattern // i and j are indices in 'String // str' and 'buf[]' respectively static void printPatternUtil(string str, char[] buf, int i, int j, int n) { if (i == n) { buf[j] = '\0'; Console.WriteLine(buf); return; } // Either put the character buf[j] = str[i]; printPatternUtil(str, buf, i + 1, j + 1, n); // Or put a space followed by next // character buf[j] = ' '; buf[j + 1] = str[i]; printPatternUtil(str, buf, i + 1, j + 2, n); } // Function creates buf[] to store // individual output string and uses // printPatternUtil() to print all // permutations static void printPattern(string str) { int len = str.Length; // Buffer to hold the string containing // spaces 2n-1 characters and 1 string // terminator char[] buf = new char[2 * len]; // Copy the first character as it is, // since it will be always at first // position buf[0] = str[0]; printPatternUtil(str, buf, 1, 1, len); } // Driver program public static void Main() { string str = "ABCD"; printPattern(str); }} // This code is contributed by nitin mittal. <?php// PHP program to print permutations// of a given string with spaces. /* Function recursively prints the stringshaving space pattern. i and j are indicesin 'str[]' and 'buff[]' respectively */function printPatternUtil($str, $buff, $i, $j, $n){ if ($i == $n) { $buff[$j] = ''; echo str_replace(', ', '', implode(', ', $buff))."\n"; return; } // Either put the character $buff[$j] = $str[$i]; printPatternUtil($str, $buff, $i + 1, $j + 1, $n); // Or put a space followed by next character $buff[$j] = ' '; $buff[$j+1] = $str[$i]; printPatternUtil($str, $buff, $i +1, $j + 2, $n);} // This function creates buf[] to store// individual output string and uses// printPatternUtil() to print all permutations.function printPattern($str){ $n = strlen($str); // Buffer to hold the string containing spaces // 2n-1 characters and 1 string terminator $buf = array_fill(0, 2 * $n, null); // Copy the first character as it is, // since it will be always // at first position $buf[0] = $str[0]; printPatternUtil($str, $buf, 1, 1, $n);} // Driver code$str = "ABCD";printPattern($str); // This code is contributed by chandan_jnu?> <script> // JavaScript program to print permutations of a // given string with spaces // Function recursively prints the // strings having space pattern // i and j are indices in 'String // str' and 'buf[]' respectively function printPatternUtil(str, buf, i, j, n) { if (i === n) { buf[j] = "\0"; document.write(buf.join("") + "<br>"); return; } // Either put the character buf[j] = str[i]; printPatternUtil(str, buf, i + 1, j + 1, n); // Or put a space followed by next // character buf[j] = " "; buf[j + 1] = str[i]; printPatternUtil(str, buf, i + 1, j + 2, n); } // Function creates buf[] to store // individual output string and uses // printPatternUtil() to print all // permutations function printPattern(str) { var len = str.length; // Buffer to hold the string containing // spaces 2n-1 characters and 1 string // terminator var buf = new Array(2 * len); // Copy the first character as it is, // since it will be always at first // position buf[0] = str[0]; printPatternUtil(str, buf, 1, 1, len); } // Driver program var str = "ABCD"; printPattern(str); </script> ABCD ABC D AB CD AB C D A BCD A BC D A B CD A B C D Time Complexity: Since the number of Gaps is n-1, there are total 2^(n-1) patterns each having length ranging from n to 2n-1. Thus overall complexity would be O(n*(2^n)). Recursive Java Solution: Steps: Take the first character, and append space up the rest of the string; First character+”space”+Rest of the spaced up string;First character+Rest of the spaced up string; Take the first character, and append space up the rest of the string; First character+”space”+Rest of the spaced up string; First character+Rest of the spaced up string; Implementation: C++ Java Python3 C# Javascript // C++ program for above approach#include <bits/stdc++.h>using namespace std; vector<string> spaceString(string str){ vector<string> strs; vector<string> ans = {"ABCD", "A BCD", "AB CD", "A B CD", "ABC D", "A BC D", "AB C D", "A B C D"}; // Check if str.Length is 1 if (str.length() == 1) { strs.push_back(str); return strs; } // Return strs return ans;} int main(){ vector<string> patterns = spaceString("ABCD"); // Print patterns for(string s : patterns) { cout << s << endl; } return 0;} // This code is contributed by divyesh072019. // Java program for above approachimport java.util.*; public class GFG{ private static ArrayList<String> spaceString(String str) { ArrayList<String> strs = new ArrayList<String>(); // Check if str.length() is 1 if (str.length() == 1) { strs.add(str); return strs; } ArrayList<String> strsTemp = spaceString(str.substring(1, str.length())); // Iterate over strsTemp for (int i = 0; i < strsTemp.size(); i++) { strs.add(str.charAt(0) + strsTemp.get(i)); strs.add(str.charAt(0) + " " + strsTemp.get(i)); } // Return strs return strs; } // Driver Code public static void main(String args[]) { ArrayList<String> patterns = new ArrayList<String>(); // Function Call patterns = spaceString("ABCD"); // Print patterns for (String s : patterns) { System.out.println(s); } }} # Python program for above approachdef spaceString(str): strs = []; # Check if str.length() is 1 if(len(str) == 1): strs.append(str) return strs strsTemp=spaceString(str[1:]) # Iterate over strsTemp for i in range(len(strsTemp)): strs.append(str[0] + strsTemp[i]) strs.append(str[0] + " " + strsTemp[i]) # Return strs return strs # Driver Codepatterns=[] # Function Callpatterns = spaceString("ABCD") # Print patternsfor s in patterns: print(s) # This code is contributed by rag2127 // C# program for above approachusing System;using System.Collections.Generic; public class GFG{ private static List<String> spaceString(String str) { List<String> strs = new List<String>(); // Check if str.Length is 1 if (str.Length == 1) { strs.Add(str); return strs; } List<String> strsTemp = spaceString(str.Substring(1, str.Length-1)); // Iterate over strsTemp for (int i = 0; i < strsTemp.Count; i++) { strs.Add(str[0] + strsTemp[i]); strs.Add(str[0] + " " + strsTemp[i]); } // Return strs return strs; } // Driver Code public static void Main(String []args) { List<String> patterns = new List<String>(); // Function Call patterns = spaceString("ABCD"); // Print patterns foreach (String s in patterns) { Console.WriteLine(s); } }} // This code is contributed by gauravrajput1 <script>// Javascript program for above approach function spaceString(str){ let strs = []; // Check if str.length() is 1 if (str.length == 1) { strs.push(str); return strs; } let strsTemp = spaceString(str.substring(1, str.length)); // Iterate over strsTemp for (let i = 0; i < strsTemp.length; i++) { strs.push(str[0] + strsTemp[i]); strs.push(str[0] + " " + strsTemp[i]); } // Return strs return strs;} // Driver Codelet patterns = spaceString("ABCD"); // Print patternsfor (let s of patterns.values()){ document.write(s+"<br>");} // This code is contributed by avanitrachhadiya2155</script> ABCD A BCD AB CD A B CD ABC D A BC D AB C D A B C D nitin mittal Chandan_Kumar sinhasiddharth1998 m0hitv rdtank avanitrachhadiya2155 rag2127 sweetyty GauravRajput1 divyesh072019 hardikkoriintern Amazon Backtracking Recursion Strings Amazon Strings Recursion Backtracking Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Print all paths from a given source to a destination Generate all the binary strings of N bits Print all permutations of a string in Java Find if there is a path of more than k length from a source 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 Print all subsequences of a string Recursive Practice Problems with Solutions
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Jun, 2022" }, { "code": null, "e": 175, "s": 54, "text": "Given a string you need to print all possible strings that can be made by placing spaces (zero or one) in between them. " }, { "code": null, "e": 249, "s": 175, "text": "Input: str[] = \"ABC\"\nOutput: ABC\n AB C\n A BC\n A B C" }, { "code": null, "e": 311, "s": 249, "text": "Source: Amazon Interview Experience | Set 158, Round 1, Q 1. " }, { "code": null, "e": 823, "s": 311, "text": "The idea is to use recursion and create a buffer that one by one contains all output strings having spaces. We keep updating the buffer in every recursive call. If the length of the given string is ‘n’ our updated string can have a maximum length of n + (n-1) i.e. 2n-1. So we create a buffer size of 2n (one extra character for string termination). We leave 1st character as it is, starting from the 2nd character, we can either fill a space or a character. Thus, one can write a recursive function like below." }, { "code": null, "e": 875, "s": 823, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 879, "s": 875, "text": "C++" }, { "code": null, "e": 884, "s": 879, "text": "Java" }, { "code": null, "e": 891, "s": 884, "text": "Python" }, { "code": null, "e": 894, "s": 891, "text": "C#" }, { "code": null, "e": 898, "s": 894, "text": "PHP" }, { "code": null, "e": 909, "s": 898, "text": "Javascript" }, { "code": "// C++ program to print permutations// of a given string with spaces.#include <cstring>#include <iostream>using namespace std; /* Function recursively prints the strings having space pattern. i and j are indices in 'str[]' and 'buff[]' respectively */void printPatternUtil(const char str[], char buff[], int i, int j, int n){ if (i == n) { buff[j] = '\\0'; cout << buff << endl; return; } // Either put the character buff[j] = str[i]; printPatternUtil(str, buff, i + 1, j + 1, n); // Or put a space followed by next character buff[j] = ' '; buff[j + 1] = str[i]; printPatternUtil(str, buff, i + 1, j + 2, n);} // This function creates buf[] to// store individual output string and uses// printPatternUtil() to print all permutations.void printPattern(const char* str){ int n = strlen(str); // Buffer to hold the string // containing spaces // 2n - 1 characters and 1 string terminator char buf[2 * n]; // Copy the first character as // it is, since it will be always // at first position buf[0] = str[0]; printPatternUtil(str, buf, 1, 1, n);} // Driver program to test above functionsint main(){ const char* str = \"ABCD\"; printPattern(str); return 0;}", "e": 2210, "s": 909, "text": null }, { "code": "// Java program to print permutations// of a given string with// spacesimport java.io.*; class Permutation{ // Function recursively prints // the strings having space // pattern i and j are indices in 'String str' and // 'buf[]' respectively static void printPatternUtil(String str, char buf[], int i, int j, int n) { if (i == n) { buf[j] = '\\0'; System.out.println(buf); return; } // Either put the character buf[j] = str.charAt(i); printPatternUtil(str, buf, i + 1, j + 1, n); // Or put a space followed // by next character buf[j] = ' '; buf[j + 1] = str.charAt(i); printPatternUtil(str, buf, i + 1, j + 2, n); } // Function creates buf[] to // store individual output // string and uses printPatternUtil() // to print all // permutations static void printPattern(String str) { int len = str.length(); // Buffer to hold the string // containing spaces // 2n-1 characters and 1 // string terminator char[] buf = new char[2 * len]; // Copy the first character as it is, since it will // be always at first position buf[0] = str.charAt(0); printPatternUtil(str, buf, 1, 1, len); } // Driver program public static void main(String[] args) { String str = \"ABCD\"; printPattern(str); }}", "e": 3747, "s": 2210, "text": null }, { "code": "# Python program to print permutations# of a given string with# spaces. # Utility functiondef toString(List): s = \"\" for x in List: if x == '&# 092;&# 048;': break s += x return s # Function recursively prints the# strings having space pattern.# i and j are indices in 'str[]'# and 'buff[]' respectivelydef printPatternUtil(string, buff, i, j, n): if i == n: buff[j] = '&# 092;&# 048;' print toString(buff) return # Either put the character buff[j] = string[i] printPatternUtil(string, buff, i + 1, j + 1, n) # Or put a space followed by next character buff[j] = ' ' buff[j + 1] = string[i] printPatternUtil(string, buff, i + 1, j + 2, n) # This function creates buf[] to# store individual output string# and uses printPatternUtil() to# print all permutations.def printPattern(string): n = len(string) # Buffer to hold the string # containing spaces # 2n - 1 characters and 1 string terminator buff = [0] * (2 * n) # Copy the first character as it is, # since it will be always # at first position buff[0] = string[0] printPatternUtil(string, buff, 1, 1, n) # Driver programstring = \"ABCD\"printPattern(string) # This code is contributed by BHAVYA JAIN", "e": 5088, "s": 3747, "text": null }, { "code": "// C# program to print permutations of a// given string with spacesusing System; class GFG{ // Function recursively prints the // strings having space pattern // i and j are indices in 'String // str' and 'buf[]' respectively static void printPatternUtil(string str, char[] buf, int i, int j, int n) { if (i == n) { buf[j] = '\\0'; Console.WriteLine(buf); return; } // Either put the character buf[j] = str[i]; printPatternUtil(str, buf, i + 1, j + 1, n); // Or put a space followed by next // character buf[j] = ' '; buf[j + 1] = str[i]; printPatternUtil(str, buf, i + 1, j + 2, n); } // Function creates buf[] to store // individual output string and uses // printPatternUtil() to print all // permutations static void printPattern(string str) { int len = str.Length; // Buffer to hold the string containing // spaces 2n-1 characters and 1 string // terminator char[] buf = new char[2 * len]; // Copy the first character as it is, // since it will be always at first // position buf[0] = str[0]; printPatternUtil(str, buf, 1, 1, len); } // Driver program public static void Main() { string str = \"ABCD\"; printPattern(str); }} // This code is contributed by nitin mittal.", "e": 6640, "s": 5088, "text": null }, { "code": "<?php// PHP program to print permutations// of a given string with spaces. /* Function recursively prints the stringshaving space pattern. i and j are indicesin 'str[]' and 'buff[]' respectively */function printPatternUtil($str, $buff, $i, $j, $n){ if ($i == $n) { $buff[$j] = ''; echo str_replace(', ', '', implode(', ', $buff)).\"\\n\"; return; } // Either put the character $buff[$j] = $str[$i]; printPatternUtil($str, $buff, $i + 1, $j + 1, $n); // Or put a space followed by next character $buff[$j] = ' '; $buff[$j+1] = $str[$i]; printPatternUtil($str, $buff, $i +1, $j + 2, $n);} // This function creates buf[] to store// individual output string and uses// printPatternUtil() to print all permutations.function printPattern($str){ $n = strlen($str); // Buffer to hold the string containing spaces // 2n-1 characters and 1 string terminator $buf = array_fill(0, 2 * $n, null); // Copy the first character as it is, // since it will be always // at first position $buf[0] = $str[0]; printPatternUtil($str, $buf, 1, 1, $n);} // Driver code$str = \"ABCD\";printPattern($str); // This code is contributed by chandan_jnu?>", "e": 7944, "s": 6640, "text": null }, { "code": "<script> // JavaScript program to print permutations of a // given string with spaces // Function recursively prints the // strings having space pattern // i and j are indices in 'String // str' and 'buf[]' respectively function printPatternUtil(str, buf, i, j, n) { if (i === n) { buf[j] = \"\\0\"; document.write(buf.join(\"\") + \"<br>\"); return; } // Either put the character buf[j] = str[i]; printPatternUtil(str, buf, i + 1, j + 1, n); // Or put a space followed by next // character buf[j] = \" \"; buf[j + 1] = str[i]; printPatternUtil(str, buf, i + 1, j + 2, n); } // Function creates buf[] to store // individual output string and uses // printPatternUtil() to print all // permutations function printPattern(str) { var len = str.length; // Buffer to hold the string containing // spaces 2n-1 characters and 1 string // terminator var buf = new Array(2 * len); // Copy the first character as it is, // since it will be always at first // position buf[0] = str[0]; printPatternUtil(str, buf, 1, 1, len); } // Driver program var str = \"ABCD\"; printPattern(str); </script>", "e": 9289, "s": 7944, "text": null }, { "code": null, "e": 9341, "s": 9289, "text": "ABCD\nABC D\nAB CD\nAB C D\nA BCD\nA BC D\nA B CD\nA B C D" }, { "code": null, "e": 9512, "s": 9341, "text": "Time Complexity: Since the number of Gaps is n-1, there are total 2^(n-1) patterns each having length ranging from n to 2n-1. Thus overall complexity would be O(n*(2^n))." }, { "code": null, "e": 9537, "s": 9512, "text": "Recursive Java Solution:" }, { "code": null, "e": 9544, "s": 9537, "text": "Steps:" }, { "code": null, "e": 9713, "s": 9544, "text": "Take the first character, and append space up the rest of the string; First character+”space”+Rest of the spaced up string;First character+Rest of the spaced up string;" }, { "code": null, "e": 9784, "s": 9713, "text": "Take the first character, and append space up the rest of the string; " }, { "code": null, "e": 9838, "s": 9784, "text": "First character+”space”+Rest of the spaced up string;" }, { "code": null, "e": 9884, "s": 9838, "text": "First character+Rest of the spaced up string;" }, { "code": null, "e": 9900, "s": 9884, "text": "Implementation:" }, { "code": null, "e": 9904, "s": 9900, "text": "C++" }, { "code": null, "e": 9909, "s": 9904, "text": "Java" }, { "code": null, "e": 9917, "s": 9909, "text": "Python3" }, { "code": null, "e": 9920, "s": 9917, "text": "C#" }, { "code": null, "e": 9931, "s": 9920, "text": "Javascript" }, { "code": "// C++ program for above approach#include <bits/stdc++.h>using namespace std; vector<string> spaceString(string str){ vector<string> strs; vector<string> ans = {\"ABCD\", \"A BCD\", \"AB CD\", \"A B CD\", \"ABC D\", \"A BC D\", \"AB C D\", \"A B C D\"}; // Check if str.Length is 1 if (str.length() == 1) { strs.push_back(str); return strs; } // Return strs return ans;} int main(){ vector<string> patterns = spaceString(\"ABCD\"); // Print patterns for(string s : patterns) { cout << s << endl; } return 0;} // This code is contributed by divyesh072019.", "e": 10549, "s": 9931, "text": null }, { "code": "// Java program for above approachimport java.util.*; public class GFG{ private static ArrayList<String> spaceString(String str) { ArrayList<String> strs = new ArrayList<String>(); // Check if str.length() is 1 if (str.length() == 1) { strs.add(str); return strs; } ArrayList<String> strsTemp = spaceString(str.substring(1, str.length())); // Iterate over strsTemp for (int i = 0; i < strsTemp.size(); i++) { strs.add(str.charAt(0) + strsTemp.get(i)); strs.add(str.charAt(0) + \" \" + strsTemp.get(i)); } // Return strs return strs; } // Driver Code public static void main(String args[]) { ArrayList<String> patterns = new ArrayList<String>(); // Function Call patterns = spaceString(\"ABCD\"); // Print patterns for (String s : patterns) { System.out.println(s); } }}", "e": 11690, "s": 10549, "text": null }, { "code": "# Python program for above approachdef spaceString(str): strs = []; # Check if str.length() is 1 if(len(str) == 1): strs.append(str) return strs strsTemp=spaceString(str[1:]) # Iterate over strsTemp for i in range(len(strsTemp)): strs.append(str[0] + strsTemp[i]) strs.append(str[0] + \" \" + strsTemp[i]) # Return strs return strs # Driver Codepatterns=[] # Function Callpatterns = spaceString(\"ABCD\") # Print patternsfor s in patterns: print(s) # This code is contributed by rag2127", "e": 12252, "s": 11690, "text": null }, { "code": "// C# program for above approachusing System;using System.Collections.Generic; public class GFG{ private static List<String> spaceString(String str) { List<String> strs = new List<String>(); // Check if str.Length is 1 if (str.Length == 1) { strs.Add(str); return strs; } List<String> strsTemp = spaceString(str.Substring(1, str.Length-1)); // Iterate over strsTemp for (int i = 0; i < strsTemp.Count; i++) { strs.Add(str[0] + strsTemp[i]); strs.Add(str[0] + \" \" + strsTemp[i]); } // Return strs return strs; } // Driver Code public static void Main(String []args) { List<String> patterns = new List<String>(); // Function Call patterns = spaceString(\"ABCD\"); // Print patterns foreach (String s in patterns) { Console.WriteLine(s); } }} // This code is contributed by gauravrajput1", "e": 13410, "s": 12252, "text": null }, { "code": "<script>// Javascript program for above approach function spaceString(str){ let strs = []; // Check if str.length() is 1 if (str.length == 1) { strs.push(str); return strs; } let strsTemp = spaceString(str.substring(1, str.length)); // Iterate over strsTemp for (let i = 0; i < strsTemp.length; i++) { strs.push(str[0] + strsTemp[i]); strs.push(str[0] + \" \" + strsTemp[i]); } // Return strs return strs;} // Driver Codelet patterns = spaceString(\"ABCD\"); // Print patternsfor (let s of patterns.values()){ document.write(s+\"<br>\");} // This code is contributed by avanitrachhadiya2155</script>", "e": 14230, "s": 13410, "text": null }, { "code": null, "e": 14282, "s": 14230, "text": "ABCD\nA BCD\nAB CD\nA B CD\nABC D\nA BC D\nAB C D\nA B C D" }, { "code": null, "e": 14295, "s": 14282, "text": "nitin mittal" }, { "code": null, "e": 14309, "s": 14295, "text": "Chandan_Kumar" }, { "code": null, "e": 14328, "s": 14309, "text": "sinhasiddharth1998" }, { "code": null, "e": 14335, "s": 14328, "text": "m0hitv" }, { "code": null, "e": 14342, "s": 14335, "text": "rdtank" }, { "code": null, "e": 14363, "s": 14342, "text": "avanitrachhadiya2155" }, { "code": null, "e": 14371, "s": 14363, "text": "rag2127" }, { "code": null, "e": 14380, "s": 14371, "text": "sweetyty" }, { "code": null, "e": 14394, "s": 14380, "text": "GauravRajput1" }, { "code": null, "e": 14408, "s": 14394, "text": "divyesh072019" }, { "code": null, "e": 14425, "s": 14408, "text": "hardikkoriintern" }, { "code": null, "e": 14432, "s": 14425, "text": "Amazon" }, { "code": null, "e": 14445, "s": 14432, "text": "Backtracking" }, { "code": null, "e": 14455, "s": 14445, "text": "Recursion" }, { "code": null, "e": 14463, "s": 14455, "text": "Strings" }, { "code": null, "e": 14470, "s": 14463, "text": "Amazon" }, { "code": null, "e": 14478, "s": 14470, "text": "Strings" }, { "code": null, "e": 14488, "s": 14478, "text": "Recursion" }, { "code": null, "e": 14501, "s": 14488, "text": "Backtracking" }, { "code": null, "e": 14599, "s": 14501, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14684, "s": 14599, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 14737, "s": 14684, "text": "Print all paths from a given source to a destination" }, { "code": null, "e": 14779, "s": 14737, "text": "Generate all the binary strings of N bits" }, { "code": null, "e": 14822, "s": 14779, "text": "Print all permutations of a string in Java" }, { "code": null, "e": 14882, "s": 14822, "text": "Find if there is a path of more than k length from a source" }, { "code": null, "e": 14967, "s": 14882, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 14977, "s": 14967, "text": "Recursion" }, { "code": null, "e": 15004, "s": 14977, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 15039, "s": 15004, "text": "Print all subsequences of a string" } ]
Java Program to Create a Matrix and Fill it with Prime Numbers
13 Jan, 2021 Prime Numbers are the number which can be divisible by only 1 and itself, it cannot be divisible by any other number. The task here is to find the prime numbers and store them in the form of a matrix. Example: Prime numbers are: 2, 3, 5, 7 Output: 2 3 5 7 Prime numbers : 2, 3, 5, 7, 9, 11, 13, 17, 19 Output: 2 3 5 7 9 11 13 17 19 Approach: First, the class should be created and inside the class a method is created to check the prime number. This method will take the number as input and then check whether it is prime or not. If it is prime then it will return true and if not then return false. Now, the main method will be created, inside the main method the object of Matrix class is made so that the isPrime() method can be accessed from the main. The number of rows and number of columns will be taken from the user and then using this, the another array will be created which is of size rows * columns. The prime numbers will be stored in this array. Now, by iterating through result[] array, the prime numbers will gets stored into the Matrix[] array. After that the result will gets printed. Java // Java Program to Create a Matrix and Fill// it with Prime Numbers import java.util.Scanner; public class MatrixWithPrimeNumbers { // Function to check a number is prime or not boolean isPrime(int num) { int counter = 0; for (int i = 1; i <= num; i++) { if (num % i == 0) counter = counter + 1; } if (counter == 2) return true; else return false; } public static void main(String args[]) { // creating object of Matrix With Prime Numbers // class MatrixWithPrimeNumbers mwp = new MatrixWithPrimeNumbers(); // Enter the number of rows and column. int row = 4; int col = 4; // 2D array for storing prime numbers int Matrix[][] = new int[row][col]; // size of resultant matrix int res = row * col; // 1D array for storing prime numbers int Result[] = new int[res]; int i = 0, j; int k = 1; // Calling the method to check prime and // then result will be stored into the array while (i < res) { if (mwp.isPrime(k) == true) { Result[i] = k; i++; } k++; } // the result is now stored into the form // of matrix (in 2D array) int x = 0; for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { Matrix[i][j] = Result[x]; x++; } } // printing the result in 2D Array. System.out.println("The Resultant Matrix is : "); for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { System.out.print(Matrix[i][j] + " "); } System.out.println(); } }} The Resultant Matrix is : 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Jan, 2021" }, { "code": null, "e": 229, "s": 28, "text": "Prime Numbers are the number which can be divisible by only 1 and itself, it cannot be divisible by any other number. The task here is to find the prime numbers and store them in the form of a matrix." }, { "code": null, "e": 393, "s": 229, "text": "Example: \n\nPrime numbers are: 2, 3, 5, 7\n\nOutput:\n2 3\n5 7\n\nPrime numbers : 2, 3, 5, 7, 9, 11, 13, 17, 19\n\nOutput:\n2 3 5\n7 9 11\n13 17 19\n" }, { "code": null, "e": 404, "s": 393, "text": "Approach: " }, { "code": null, "e": 507, "s": 404, "text": "First, the class should be created and inside the class a method is created to check the prime number." }, { "code": null, "e": 662, "s": 507, "text": "This method will take the number as input and then check whether it is prime or not. If it is prime then it will return true and if not then return false." }, { "code": null, "e": 818, "s": 662, "text": "Now, the main method will be created, inside the main method the object of Matrix class is made so that the isPrime() method can be accessed from the main." }, { "code": null, "e": 975, "s": 818, "text": "The number of rows and number of columns will be taken from the user and then using this, the another array will be created which is of size rows * columns." }, { "code": null, "e": 1023, "s": 975, "text": "The prime numbers will be stored in this array." }, { "code": null, "e": 1166, "s": 1023, "text": "Now, by iterating through result[] array, the prime numbers will gets stored into the Matrix[] array. After that the result will gets printed." }, { "code": null, "e": 1171, "s": 1166, "text": "Java" }, { "code": "// Java Program to Create a Matrix and Fill// it with Prime Numbers import java.util.Scanner; public class MatrixWithPrimeNumbers { // Function to check a number is prime or not boolean isPrime(int num) { int counter = 0; for (int i = 1; i <= num; i++) { if (num % i == 0) counter = counter + 1; } if (counter == 2) return true; else return false; } public static void main(String args[]) { // creating object of Matrix With Prime Numbers // class MatrixWithPrimeNumbers mwp = new MatrixWithPrimeNumbers(); // Enter the number of rows and column. int row = 4; int col = 4; // 2D array for storing prime numbers int Matrix[][] = new int[row][col]; // size of resultant matrix int res = row * col; // 1D array for storing prime numbers int Result[] = new int[res]; int i = 0, j; int k = 1; // Calling the method to check prime and // then result will be stored into the array while (i < res) { if (mwp.isPrime(k) == true) { Result[i] = k; i++; } k++; } // the result is now stored into the form // of matrix (in 2D array) int x = 0; for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { Matrix[i][j] = Result[x]; x++; } } // printing the result in 2D Array. System.out.println(\"The Resultant Matrix is : \"); for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { System.out.print(Matrix[i][j] + \" \"); } System.out.println(); } }}", "e": 3066, "s": 1171, "text": null }, { "code": null, "e": 3142, "s": 3066, "text": "The Resultant Matrix is : \n2 3 5 7 \n11 13 17 19 \n23 29 31 37 \n41 43 47 53 \n" }, { "code": null, "e": 3149, "s": 3142, "text": "Picked" }, { "code": null, "e": 3154, "s": 3149, "text": "Java" }, { "code": null, "e": 3168, "s": 3154, "text": "Java Programs" }, { "code": null, "e": 3173, "s": 3168, "text": "Java" }, { "code": null, "e": 3271, "s": 3173, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3286, "s": 3271, "text": "Stream In Java" }, { "code": null, "e": 3307, "s": 3286, "text": "Introduction to Java" }, { "code": null, "e": 3328, "s": 3307, "text": "Constructors in Java" }, { "code": null, "e": 3347, "s": 3328, "text": "Exceptions in Java" }, { "code": null, "e": 3364, "s": 3347, "text": "Generics in Java" }, { "code": null, "e": 3390, "s": 3364, "text": "Java Programming Examples" }, { "code": null, "e": 3424, "s": 3390, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 3471, "s": 3424, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 3509, "s": 3471, "text": "Factory method design pattern in Java" } ]
Message Boxes using PyAutoGUI
26 May, 2020 PyAutoGUI is a Python module which can automate your GUI and programmatically control your keyboard and mouse. This article illustrates the GUI functions to create display boxes.If you want to know more about PyAutoGUI and its ability to automate your keyboard and mouse, follow this article : Mouse and Keyboard Automation using PyAutoGUI PyAutoGUI does not come with python, so go to command prompt and type the following : pip3 install PyAutoGUI alert() : Displays a simple message box with text and a single OK button. Returns the text of the button clicked on. # Python Program to show alert() functionimport pyautogui pyautogui.alert('GeekforGeeks alert box') Output : It will display the alert box with the given text and when clicked OK it will return ‘OK’ confirm() : Displays a message box with OK and Cancel buttons. Number and text of buttons can be customized. Returns the text of the button clicked on. # Python Program to show confirm() functionimport pyautoguipyautogui.confirm('Geek Shall I proceed?') Output : It will display the alert box with the given text and on clicking the button it will return the text on the button. In this case its ‘OK’ To have multiple select options – # Python Program to show confirm() function# with multiple optionsimport pyautoguipyautogui.confirm('Enter option Gfg', buttons =['A', 'B', 'C']) Output : On clicking A, it will return ‘A’ as output. prompt() : Displays a message box with text input, and OK & Cancel buttons. Returns the text entered, or None if Cancel was clicked. # Python Program to show prompt() functionimport pyautoguipyautogui.prompt('What is your name?') Output : It will return the text entered, in this case ‘GeekForGeeks’ or None if cancelled was clicked. password() : Displays a message box with text input, and OK & Cancel buttons. Typed characters appear as *. Returns the text entered, or None if Cancel was clicked # Python Program to show password() functionimport pyautoguipyautogui.password('Enter password (text will be hidden)') Output : It will return the text/password entered, in this case ‘GeekForGeeks’ or None if cancelled was clicked. Python-gui Python-PyAutoGUI 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 Python OOPs Concepts Introduction To PYTHON
[ { "code": null, "e": 54, "s": 26, "text": "\n26 May, 2020" }, { "code": null, "e": 394, "s": 54, "text": "PyAutoGUI is a Python module which can automate your GUI and programmatically control your keyboard and mouse. This article illustrates the GUI functions to create display boxes.If you want to know more about PyAutoGUI and its ability to automate your keyboard and mouse, follow this article : Mouse and Keyboard Automation using PyAutoGUI" }, { "code": null, "e": 480, "s": 394, "text": "PyAutoGUI does not come with python, so go to command prompt and type the following :" }, { "code": null, "e": 504, "s": 480, "text": " pip3 install PyAutoGUI" }, { "code": null, "e": 621, "s": 504, "text": "alert() : Displays a simple message box with text and a single OK button. Returns the text of the button clicked on." }, { "code": "# Python Program to show alert() functionimport pyautogui pyautogui.alert('GeekforGeeks alert box')", "e": 722, "s": 621, "text": null }, { "code": null, "e": 821, "s": 722, "text": "Output : It will display the alert box with the given text and when clicked OK it will return ‘OK’" }, { "code": null, "e": 974, "s": 821, "text": " confirm() : Displays a message box with OK and Cancel buttons. Number and text of buttons can be customized. Returns the text of the button clicked on." }, { "code": "# Python Program to show confirm() functionimport pyautoguipyautogui.confirm('Geek Shall I proceed?')", "e": 1076, "s": 974, "text": null }, { "code": null, "e": 1223, "s": 1076, "text": "Output : It will display the alert box with the given text and on clicking the button it will return the text on the button. In this case its ‘OK’" }, { "code": null, "e": 1257, "s": 1223, "text": "To have multiple select options –" }, { "code": "# Python Program to show confirm() function# with multiple optionsimport pyautoguipyautogui.confirm('Enter option Gfg', buttons =['A', 'B', 'C'])", "e": 1403, "s": 1257, "text": null }, { "code": null, "e": 1457, "s": 1403, "text": "Output : On clicking A, it will return ‘A’ as output." }, { "code": null, "e": 1591, "s": 1457, "text": " prompt() : Displays a message box with text input, and OK & Cancel buttons. Returns the text entered, or None if Cancel was clicked." }, { "code": "# Python Program to show prompt() functionimport pyautoguipyautogui.prompt('What is your name?')", "e": 1688, "s": 1591, "text": null }, { "code": null, "e": 1793, "s": 1688, "text": "Output : It will return the text entered, in this case ‘GeekForGeeks’ or None if cancelled was clicked. " }, { "code": null, "e": 1957, "s": 1793, "text": "password() : Displays a message box with text input, and OK & Cancel buttons. Typed characters appear as *. Returns the text entered, or None if Cancel was clicked" }, { "code": "# Python Program to show password() functionimport pyautoguipyautogui.password('Enter password (text will be hidden)')", "e": 2076, "s": 1957, "text": null }, { "code": null, "e": 2189, "s": 2076, "text": "Output : It will return the text/password entered, in this case ‘GeekForGeeks’ or None if cancelled was clicked." }, { "code": null, "e": 2200, "s": 2189, "text": "Python-gui" }, { "code": null, "e": 2217, "s": 2200, "text": "Python-PyAutoGUI" }, { "code": null, "e": 2224, "s": 2217, "text": "Python" }, { "code": null, "e": 2322, "s": 2224, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2340, "s": 2322, "text": "Python Dictionary" }, { "code": null, "e": 2382, "s": 2340, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2404, "s": 2382, "text": "Enumerate() in Python" }, { "code": null, "e": 2439, "s": 2404, "text": "Read a file line by line in Python" }, { "code": null, "e": 2465, "s": 2439, "text": "Python String | replace()" }, { "code": null, "e": 2497, "s": 2465, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2526, "s": 2497, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2553, "s": 2526, "text": "Python Classes and Objects" }, { "code": null, "e": 2574, "s": 2553, "text": "Python OOPs Concepts" } ]
Scala | Literals
01 Apr, 2019 Any constant value which can be assigned to the variable is called as literal/constant. The literals are a series of symbols utilized for describing a constant value in the code. There are many types of literals in Scala namely Character literals, String literals, Multi-Line String literals, Boolean literals, Integer literals, and Floating point literals. Integer Literals:The Integer literals are generally of type Int or of type Long when a suffix L or l is added at the end of the Integers. The type Int as well as type Long are all Integer numerals.Note:The range of the type Int is from (-231 to 230).The range of the type Long is from (-263 to 262).When an Integer literal has a number which falls out of this range then a compile time error arises. The Integers literals are specified in two ways:Decimal literals:Here, the allowed digits are from 0 to 9.val x = 37Hexa-decimal literals:Here, the allowed digits are from 0 to 9 and characters used are from a to f. We can use uppercase as well as lowercase characters.// The hexa-decimal number should be prefix // with 0X or 0x. val x = 0xFFFExample:// Scala program of integer// literals // Creating objectobject integer{ // Main method def main(args: Array[String]) { // decimal-form literal val a = 46 // Hexa-decimal form literal val b = 0xfF // Displays results in // integer form println(a) println(b) }}Output:46 255 Note: The Octal form of the literal is obsolete.Floating Point Literals :This type of literals are of type Double as well as type Float when a suffix F or f is added at the end and we can even specify Double type by suffixed with d or D.val x = 3.14159Example:// Scala program of floating// point literals // Creating objectobject double{ // Main method def main(args: Array[String]) { // decimal-form literal val a = 3.156 // It is also a decimal // form of the literal val b = 0123.34 // Displays results println(a) println(b) }}Output:3.156 123.34 Here, we can’t specify literals in Octal or Hexadecimal form.Character Literals :character literals are either uni-code character which are printable or are represented by escape sequences.val x = 'b' //character literal in a single quote.val x = '\u0051' //uni-code representation of character literal, //This uni-code represents Q.val x = '\n' //Escape sequence in character literalsExample:// Scala program of character// literal // Creating objectobject literal{ // Main method def main(args: Array[String]) { // Creating a character literal // in single quote val x = 'b' // uni-code representation of // character literal val y = '\u0051' // Escape sequence in character // literals val z = '\n' // Displays results println(x) println(y) println(z) }}Output:b Q The character literals are enclosed in a single quote.String literals :The String literals are series of characters, which are available in double quotes. The String literals can be handled smoothly by utilizing String Interpolation.val x = "GfG"Example:// Scala program of literals // Creating objectobject literal{ // Main method def main(args: Array[String]) { // Creating a string // literal val x = "GeeksforGeeks" // Displays string // literals println(x) }}Output:GeeksforGeeks A single line string literals are enclosed in a quotation marks.Multi-Line String Literals :The multi-line string literals are also series of characters but it has multiple lines.val x = """GfG"""Example:// Scala program of multi-line// string literals // Creating objectobject literal{ // Main method def main(args: Array[String]) { // Creating a multiple // line string literal val x ="""GeeksforGeeks is a computer science portal""" // Displays multiple // lines println(x) }}Output:GeeksforGeeks is a computer science portal The multi-line string literals are enclosed in triple quotes.Boolean Literals :Boolean literals allow only two values i.e. true and false, which are members of type Boolean.val x = trueExample:// Scala program of Boolean// literals // Creating objectobject GfG{ // Main method def main(args: Array[String]) { // Assigning true val a = true // Assigning false val b = false // Displays results println(a) println(b) }}Output:true false Integer Literals:The Integer literals are generally of type Int or of type Long when a suffix L or l is added at the end of the Integers. The type Int as well as type Long are all Integer numerals.Note:The range of the type Int is from (-231 to 230).The range of the type Long is from (-263 to 262).When an Integer literal has a number which falls out of this range then a compile time error arises. The Integers literals are specified in two ways:Decimal literals:Here, the allowed digits are from 0 to 9.val x = 37Hexa-decimal literals:Here, the allowed digits are from 0 to 9 and characters used are from a to f. We can use uppercase as well as lowercase characters.// The hexa-decimal number should be prefix // with 0X or 0x. val x = 0xFFFExample:// Scala program of integer// literals // Creating objectobject integer{ // Main method def main(args: Array[String]) { // decimal-form literal val a = 46 // Hexa-decimal form literal val b = 0xfF // Displays results in // integer form println(a) println(b) }}Output:46 255 Note: The Octal form of the literal is obsolete. The range of the type Int is from (-231 to 230). The range of the type Long is from (-263 to 262). When an Integer literal has a number which falls out of this range then a compile time error arises. Decimal literals:Here, the allowed digits are from 0 to 9.val x = 37 val x = 37 Hexa-decimal literals:Here, the allowed digits are from 0 to 9 and characters used are from a to f. We can use uppercase as well as lowercase characters.// The hexa-decimal number should be prefix // with 0X or 0x. val x = 0xFFF // The hexa-decimal number should be prefix // with 0X or 0x. val x = 0xFFF Example: // Scala program of integer// literals // Creating objectobject integer{ // Main method def main(args: Array[String]) { // decimal-form literal val a = 46 // Hexa-decimal form literal val b = 0xfF // Displays results in // integer form println(a) println(b) }} 46 255 Note: The Octal form of the literal is obsolete. Floating Point Literals :This type of literals are of type Double as well as type Float when a suffix F or f is added at the end and we can even specify Double type by suffixed with d or D.val x = 3.14159Example:// Scala program of floating// point literals // Creating objectobject double{ // Main method def main(args: Array[String]) { // decimal-form literal val a = 3.156 // It is also a decimal // form of the literal val b = 0123.34 // Displays results println(a) println(b) }}Output:3.156 123.34 Here, we can’t specify literals in Octal or Hexadecimal form. val x = 3.14159 Example: // Scala program of floating// point literals // Creating objectobject double{ // Main method def main(args: Array[String]) { // decimal-form literal val a = 3.156 // It is also a decimal // form of the literal val b = 0123.34 // Displays results println(a) println(b) }} 3.156 123.34 Here, we can’t specify literals in Octal or Hexadecimal form. Character Literals :character literals are either uni-code character which are printable or are represented by escape sequences.val x = 'b' //character literal in a single quote.val x = '\u0051' //uni-code representation of character literal, //This uni-code represents Q.val x = '\n' //Escape sequence in character literalsExample:// Scala program of character// literal // Creating objectobject literal{ // Main method def main(args: Array[String]) { // Creating a character literal // in single quote val x = 'b' // uni-code representation of // character literal val y = '\u0051' // Escape sequence in character // literals val z = '\n' // Displays results println(x) println(y) println(z) }}Output:b Q The character literals are enclosed in a single quote. val x = 'b' //character literal in a single quote. val x = '\u0051' //uni-code representation of character literal, //This uni-code represents Q. val x = '\n' //Escape sequence in character literals Example: // Scala program of character// literal // Creating objectobject literal{ // Main method def main(args: Array[String]) { // Creating a character literal // in single quote val x = 'b' // uni-code representation of // character literal val y = '\u0051' // Escape sequence in character // literals val z = '\n' // Displays results println(x) println(y) println(z) }} b Q The character literals are enclosed in a single quote. String literals :The String literals are series of characters, which are available in double quotes. The String literals can be handled smoothly by utilizing String Interpolation.val x = "GfG"Example:// Scala program of literals // Creating objectobject literal{ // Main method def main(args: Array[String]) { // Creating a string // literal val x = "GeeksforGeeks" // Displays string // literals println(x) }}Output:GeeksforGeeks A single line string literals are enclosed in a quotation marks. val x = "GfG" Example: // Scala program of literals // Creating objectobject literal{ // Main method def main(args: Array[String]) { // Creating a string // literal val x = "GeeksforGeeks" // Displays string // literals println(x) }} GeeksforGeeks A single line string literals are enclosed in a quotation marks. Multi-Line String Literals :The multi-line string literals are also series of characters but it has multiple lines.val x = """GfG"""Example:// Scala program of multi-line// string literals // Creating objectobject literal{ // Main method def main(args: Array[String]) { // Creating a multiple // line string literal val x ="""GeeksforGeeks is a computer science portal""" // Displays multiple // lines println(x) }}Output:GeeksforGeeks is a computer science portal The multi-line string literals are enclosed in triple quotes. val x = """GfG""" Example: // Scala program of multi-line// string literals // Creating objectobject literal{ // Main method def main(args: Array[String]) { // Creating a multiple // line string literal val x ="""GeeksforGeeks is a computer science portal""" // Displays multiple // lines println(x) }} GeeksforGeeks is a computer science portal The multi-line string literals are enclosed in triple quotes. Boolean Literals :Boolean literals allow only two values i.e. true and false, which are members of type Boolean.val x = trueExample:// Scala program of Boolean// literals // Creating objectobject GfG{ // Main method def main(args: Array[String]) { // Assigning true val a = true // Assigning false val b = false // Displays results println(a) println(b) }}Output:true false val x = true Example: // Scala program of Boolean// literals // Creating objectobject GfG{ // Main method def main(args: Array[String]) { // Assigning true val a = true // Assigning false val b = false // Displays results println(a) println(b) }} true false Scala Scala-Basics Scala-Data Type Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Scala | flatMap Method Type Casting in Scala Scala | yield Keyword Throw Keyword in Scala Currying Functions in Scala with Examples Scala List max() method with example Scala | Final Scala List mkString() method with a separator with example For Loop in Scala Scala Iterator drop() method with example
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Apr, 2019" }, { "code": null, "e": 386, "s": 28, "text": "Any constant value which can be assigned to the variable is called as literal/constant. The literals are a series of symbols utilized for describing a constant value in the code. There are many types of literals in Scala namely Character literals, String literals, Multi-Line String literals, Boolean literals, Integer literals, and Floating point literals." }, { "code": null, "e": 4666, "s": 386, "text": "Integer Literals:The Integer literals are generally of type Int or of type Long when a suffix L or l is added at the end of the Integers. The type Int as well as type Long are all Integer numerals.Note:The range of the type Int is from (-231 to 230).The range of the type Long is from (-263 to 262).When an Integer literal has a number which falls out of this range then a compile time error arises. The Integers literals are specified in two ways:Decimal literals:Here, the allowed digits are from 0 to 9.val x = 37Hexa-decimal literals:Here, the allowed digits are from 0 to 9 and characters used are from a to f. We can use uppercase as well as lowercase characters.// The hexa-decimal number should be prefix\n// with 0X or 0x.\nval x = 0xFFFExample:// Scala program of integer// literals // Creating objectobject integer{ // Main method def main(args: Array[String]) { // decimal-form literal val a = 46 // Hexa-decimal form literal val b = 0xfF // Displays results in // integer form println(a) println(b) }}Output:46\n255\nNote: The Octal form of the literal is obsolete.Floating Point Literals :This type of literals are of type Double as well as type Float when a suffix F or f is added at the end and we can even specify Double type by suffixed with d or D.val x = 3.14159Example:// Scala program of floating// point literals // Creating objectobject double{ // Main method def main(args: Array[String]) { // decimal-form literal val a = 3.156 // It is also a decimal // form of the literal val b = 0123.34 // Displays results println(a) println(b) }}Output:3.156\n123.34\nHere, we can’t specify literals in Octal or Hexadecimal form.Character Literals :character literals are either uni-code character which are printable or are represented by escape sequences.val x = 'b' \n//character literal in a single quote.val x = '\\u0051' \n//uni-code representation of character literal,\n//This uni-code represents Q.val x = '\\n' \n//Escape sequence in character literalsExample:// Scala program of character// literal // Creating objectobject literal{ // Main method def main(args: Array[String]) { // Creating a character literal // in single quote val x = 'b' // uni-code representation of // character literal val y = '\\u0051' // Escape sequence in character // literals val z = '\\n' // Displays results println(x) println(y) println(z) }}Output:b\nQ\nThe character literals are enclosed in a single quote.String literals :The String literals are series of characters, which are available in double quotes. The String literals can be handled smoothly by utilizing String Interpolation.val x = \"GfG\"Example:// Scala program of literals // Creating objectobject literal{ // Main method def main(args: Array[String]) { // Creating a string // literal val x = \"GeeksforGeeks\" // Displays string // literals println(x) }}Output:GeeksforGeeks\nA single line string literals are enclosed in a quotation marks.Multi-Line String Literals :The multi-line string literals are also series of characters but it has multiple lines.val x = \"\"\"GfG\"\"\"Example:// Scala program of multi-line// string literals // Creating objectobject literal{ // Main method def main(args: Array[String]) { // Creating a multiple // line string literal val x =\"\"\"GeeksforGeeks is a computer science portal\"\"\" // Displays multiple // lines println(x) }}Output:GeeksforGeeks\nis a\ncomputer science\nportal\nThe multi-line string literals are enclosed in triple quotes.Boolean Literals :Boolean literals allow only two values i.e. true and false, which are members of type Boolean.val x = trueExample:// Scala program of Boolean// literals // Creating objectobject GfG{ // Main method def main(args: Array[String]) { // Assigning true val a = true // Assigning false val b = false // Displays results println(a) println(b) }}Output:true\nfalse\n" }, { "code": null, "e": 5818, "s": 4666, "text": "Integer Literals:The Integer literals are generally of type Int or of type Long when a suffix L or l is added at the end of the Integers. The type Int as well as type Long are all Integer numerals.Note:The range of the type Int is from (-231 to 230).The range of the type Long is from (-263 to 262).When an Integer literal has a number which falls out of this range then a compile time error arises. The Integers literals are specified in two ways:Decimal literals:Here, the allowed digits are from 0 to 9.val x = 37Hexa-decimal literals:Here, the allowed digits are from 0 to 9 and characters used are from a to f. We can use uppercase as well as lowercase characters.// The hexa-decimal number should be prefix\n// with 0X or 0x.\nval x = 0xFFFExample:// Scala program of integer// literals // Creating objectobject integer{ // Main method def main(args: Array[String]) { // decimal-form literal val a = 46 // Hexa-decimal form literal val b = 0xfF // Displays results in // integer form println(a) println(b) }}Output:46\n255\nNote: The Octal form of the literal is obsolete." }, { "code": null, "e": 5867, "s": 5818, "text": "The range of the type Int is from (-231 to 230)." }, { "code": null, "e": 5917, "s": 5867, "text": "The range of the type Long is from (-263 to 262)." }, { "code": null, "e": 6018, "s": 5917, "text": "When an Integer literal has a number which falls out of this range then a compile time error arises." }, { "code": null, "e": 6087, "s": 6018, "text": "Decimal literals:Here, the allowed digits are from 0 to 9.val x = 37" }, { "code": null, "e": 6098, "s": 6087, "text": "val x = 37" }, { "code": null, "e": 6327, "s": 6098, "text": "Hexa-decimal literals:Here, the allowed digits are from 0 to 9 and characters used are from a to f. We can use uppercase as well as lowercase characters.// The hexa-decimal number should be prefix\n// with 0X or 0x.\nval x = 0xFFF" }, { "code": null, "e": 6403, "s": 6327, "text": "// The hexa-decimal number should be prefix\n// with 0X or 0x.\nval x = 0xFFF" }, { "code": null, "e": 6412, "s": 6403, "text": "Example:" }, { "code": "// Scala program of integer// literals // Creating objectobject integer{ // Main method def main(args: Array[String]) { // decimal-form literal val a = 46 // Hexa-decimal form literal val b = 0xfF // Displays results in // integer form println(a) println(b) }}", "e": 6750, "s": 6412, "text": null }, { "code": null, "e": 6758, "s": 6750, "text": "46\n255\n" }, { "code": null, "e": 6807, "s": 6758, "text": "Note: The Octal form of the literal is obsolete." }, { "code": null, "e": 7450, "s": 6807, "text": "Floating Point Literals :This type of literals are of type Double as well as type Float when a suffix F or f is added at the end and we can even specify Double type by suffixed with d or D.val x = 3.14159Example:// Scala program of floating// point literals // Creating objectobject double{ // Main method def main(args: Array[String]) { // decimal-form literal val a = 3.156 // It is also a decimal // form of the literal val b = 0123.34 // Displays results println(a) println(b) }}Output:3.156\n123.34\nHere, we can’t specify literals in Octal or Hexadecimal form." }, { "code": null, "e": 7466, "s": 7450, "text": "val x = 3.14159" }, { "code": null, "e": 7475, "s": 7466, "text": "Example:" }, { "code": "// Scala program of floating// point literals // Creating objectobject double{ // Main method def main(args: Array[String]) { // decimal-form literal val a = 3.156 // It is also a decimal // form of the literal val b = 0123.34 // Displays results println(a) println(b) }}", "e": 7825, "s": 7475, "text": null }, { "code": null, "e": 7839, "s": 7825, "text": "3.156\n123.34\n" }, { "code": null, "e": 7901, "s": 7839, "text": "Here, we can’t specify literals in Octal or Hexadecimal form." }, { "code": null, "e": 8778, "s": 7901, "text": "Character Literals :character literals are either uni-code character which are printable or are represented by escape sequences.val x = 'b' \n//character literal in a single quote.val x = '\\u0051' \n//uni-code representation of character literal,\n//This uni-code represents Q.val x = '\\n' \n//Escape sequence in character literalsExample:// Scala program of character// literal // Creating objectobject literal{ // Main method def main(args: Array[String]) { // Creating a character literal // in single quote val x = 'b' // uni-code representation of // character literal val y = '\\u0051' // Escape sequence in character // literals val z = '\\n' // Displays results println(x) println(y) println(z) }}Output:b\nQ\nThe character literals are enclosed in a single quote." }, { "code": null, "e": 8830, "s": 8778, "text": "val x = 'b' \n//character literal in a single quote." }, { "code": null, "e": 8926, "s": 8830, "text": "val x = '\\u0051' \n//uni-code representation of character literal,\n//This uni-code represents Q." }, { "code": null, "e": 8980, "s": 8926, "text": "val x = '\\n' \n//Escape sequence in character literals" }, { "code": null, "e": 8989, "s": 8980, "text": "Example:" }, { "code": "// Scala program of character// literal // Creating objectobject literal{ // Main method def main(args: Array[String]) { // Creating a character literal // in single quote val x = 'b' // uni-code representation of // character literal val y = '\\u0051' // Escape sequence in character // literals val z = '\\n' // Displays results println(x) println(y) println(z) }}", "e": 9466, "s": 8989, "text": null }, { "code": null, "e": 9471, "s": 9466, "text": "b\nQ\n" }, { "code": null, "e": 9526, "s": 9471, "text": "The character literals are enclosed in a single quote." }, { "code": null, "e": 10083, "s": 9526, "text": "String literals :The String literals are series of characters, which are available in double quotes. The String literals can be handled smoothly by utilizing String Interpolation.val x = \"GfG\"Example:// Scala program of literals // Creating objectobject literal{ // Main method def main(args: Array[String]) { // Creating a string // literal val x = \"GeeksforGeeks\" // Displays string // literals println(x) }}Output:GeeksforGeeks\nA single line string literals are enclosed in a quotation marks." }, { "code": null, "e": 10097, "s": 10083, "text": "val x = \"GfG\"" }, { "code": null, "e": 10106, "s": 10097, "text": "Example:" }, { "code": "// Scala program of literals // Creating objectobject literal{ // Main method def main(args: Array[String]) { // Creating a string // literal val x = \"GeeksforGeeks\" // Displays string // literals println(x) }}", "e": 10378, "s": 10106, "text": null }, { "code": null, "e": 10393, "s": 10378, "text": "GeeksforGeeks\n" }, { "code": null, "e": 10458, "s": 10393, "text": "A single line string literals are enclosed in a quotation marks." }, { "code": null, "e": 11069, "s": 10458, "text": "Multi-Line String Literals :The multi-line string literals are also series of characters but it has multiple lines.val x = \"\"\"GfG\"\"\"Example:// Scala program of multi-line// string literals // Creating objectobject literal{ // Main method def main(args: Array[String]) { // Creating a multiple // line string literal val x =\"\"\"GeeksforGeeks is a computer science portal\"\"\" // Displays multiple // lines println(x) }}Output:GeeksforGeeks\nis a\ncomputer science\nportal\nThe multi-line string literals are enclosed in triple quotes." }, { "code": null, "e": 11087, "s": 11069, "text": "val x = \"\"\"GfG\"\"\"" }, { "code": null, "e": 11096, "s": 11087, "text": "Example:" }, { "code": "// Scala program of multi-line// string literals // Creating objectobject literal{ // Main method def main(args: Array[String]) { // Creating a multiple // line string literal val x =\"\"\"GeeksforGeeks is a computer science portal\"\"\" // Displays multiple // lines println(x) }}", "e": 11456, "s": 11096, "text": null }, { "code": null, "e": 11500, "s": 11456, "text": "GeeksforGeeks\nis a\ncomputer science\nportal\n" }, { "code": null, "e": 11562, "s": 11500, "text": "The multi-line string literals are enclosed in triple quotes." }, { "code": null, "e": 12007, "s": 11562, "text": "Boolean Literals :Boolean literals allow only two values i.e. true and false, which are members of type Boolean.val x = trueExample:// Scala program of Boolean// literals // Creating objectobject GfG{ // Main method def main(args: Array[String]) { // Assigning true val a = true // Assigning false val b = false // Displays results println(a) println(b) }}Output:true\nfalse\n" }, { "code": null, "e": 12020, "s": 12007, "text": "val x = true" }, { "code": null, "e": 12029, "s": 12020, "text": "Example:" }, { "code": "// Scala program of Boolean// literals // Creating objectobject GfG{ // Main method def main(args: Array[String]) { // Assigning true val a = true // Assigning false val b = false // Displays results println(a) println(b) }}", "e": 12324, "s": 12029, "text": null }, { "code": null, "e": 12336, "s": 12324, "text": "true\nfalse\n" }, { "code": null, "e": 12342, "s": 12336, "text": "Scala" }, { "code": null, "e": 12355, "s": 12342, "text": "Scala-Basics" }, { "code": null, "e": 12371, "s": 12355, "text": "Scala-Data Type" }, { "code": null, "e": 12377, "s": 12371, "text": "Scala" }, { "code": null, "e": 12475, "s": 12377, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12498, "s": 12475, "text": "Scala | flatMap Method" }, { "code": null, "e": 12520, "s": 12498, "text": "Type Casting in Scala" }, { "code": null, "e": 12542, "s": 12520, "text": "Scala | yield Keyword" }, { "code": null, "e": 12565, "s": 12542, "text": "Throw Keyword in Scala" }, { "code": null, "e": 12607, "s": 12565, "text": "Currying Functions in Scala with Examples" }, { "code": null, "e": 12644, "s": 12607, "text": "Scala List max() method with example" }, { "code": null, "e": 12658, "s": 12644, "text": "Scala | Final" }, { "code": null, "e": 12717, "s": 12658, "text": "Scala List mkString() method with a separator with example" }, { "code": null, "e": 12735, "s": 12717, "text": "For Loop in Scala" } ]
Lamport’s logical clock
24 Nov, 2021 Lamport’s Logical Clock was created by Leslie Lamport. It is a procedure to determine the order of events occurring. It provides a basis for the more advanced Vector Clock Algorithm. Due to the absence of a Global Clock in a Distributed Operating System Lamport Logical Clock is needed. Algorithm: Happened before relation(->): a -> b, means ‘a’ happened before ‘b’. Logical Clock: The criteria for the logical clocks are:[C1]: Ci (a) < Ci(b), [ Ci -> Logical Clock, If ‘a’ happened before ‘b’, then time of ‘a’ will be less than ‘b’ in a particular process. ][C2]: Ci(a) < Cj(b), [ Clock value of Ci(a) is less than Cj(b) ] [C1]: Ci (a) < Ci(b), [ Ci -> Logical Clock, If ‘a’ happened before ‘b’, then time of ‘a’ will be less than ‘b’ in a particular process. ] [C2]: Ci(a) < Cj(b), [ Clock value of Ci(a) is less than Cj(b) ] Reference: Process: Pi Event: Eij, where i is the process in number and j: jth event in the ith process. tm: vector time span for message m. Ci vector clock associated with process Pi, the jth element is Ci[j] and contains Pi‘s latest value for the current time in process Pj. d: drift time, generally d is 1. Implementation Rules[IR]: [IR1]: If a -> b [‘a’ happened before ‘b’ within the same process] then, Ci(b) =Ci(a) + d [IR2]: Cj = max(Cj, tm + d) [If there’s more number of processes, then tm = value of Ci(a), Cj = max value between Cj and tm + d] For Example: Take the starting value as 1, since it is the 1st event and there is no incoming value at the starting point:e11 = 1e21 = 1 e11 = 1 e21 = 1 The value of the next point will go on increasing by d (d = 1), if there is no incoming value i.e., to follow [IR1].e12 = e11 + d = 1 + 1 = 2e13 = e12 + d = 2 + 1 = 3e14 = e13 + d = 3 + 1 = 4e15 = e14 + d = 4 + 1 = 5e16 = e15 + d = 5 + 1 = 6e22 = e21 + d = 1 + 1 = 2e24 = e23 + d = 3 + 1 = 4e26 = e25 + d = 6 + 1 = 7 e12 = e11 + d = 1 + 1 = 2 e13 = e12 + d = 2 + 1 = 3 e14 = e13 + d = 3 + 1 = 4 e15 = e14 + d = 4 + 1 = 5 e16 = e15 + d = 5 + 1 = 6 e22 = e21 + d = 1 + 1 = 2 e24 = e23 + d = 3 + 1 = 4 e26 = e25 + d = 6 + 1 = 7 When there will be incoming value, then follow [IR2] i.e., take the maximum value between Cj and Tm + d.e17 = max(7, 5) = 7, [e16 + d = 6 + 1 = 7, e24 + d = 4 + 1 = 5, maximum among 7 and 5 is 7]e23 = max(3, 3) = 3, [e22 + d = 2 + 1 = 3, e12 + d = 2 + 1 = 3, maximum among 3 and 3 is 3]e25 = max(5, 6) = 6, [e24 + 1 = 4 + 1 = 5, e15 + d = 5 + 1 = 6, maximum among 5 and 6 is 6] e17 = max(7, 5) = 7, [e16 + d = 6 + 1 = 7, e24 + d = 4 + 1 = 5, maximum among 7 and 5 is 7] e23 = max(3, 3) = 3, [e22 + d = 2 + 1 = 3, e12 + d = 2 + 1 = 3, maximum among 3 and 3 is 3] e25 = max(5, 6) = 6, [e24 + 1 = 4 + 1 = 5, e15 + d = 5 + 1 = 6, maximum among 5 and 6 is 6] Limitation: In case of [IR1], if a -> b, then C(a) < C(b) -> true. In case of [IR2], if a -> b, then C(a) < C(b) -> May be true or may not be true. Below is the C program to implement Lamport’s Logical Clock: C++ C Python3 Javascript // C++ program to illustrate the Lamport's// Logical Clock #include <bits/stdc++.h>using namespace std; // Function to find the maximum timestamp// between 2 eventsint max1(int a, int b){ // Return the greatest of th two if (a > b) return a; else return b;} // Function to display the logical timestampvoid display(int e1, int e2, int p1[5], int p2[3]){ int i; cout << "\nThe time stamps of " "events in P1:\n"; for (i = 0; i < e1; i++) { cout << p1[i] << " "; } cout << "\nThe time stamps of " "events in P2:\n"; // Print the array p2[] for (i = 0; i < e2; i++) cout << p2[i] << " ";} // Function to find the timestamp of eventsvoid lamportLogicalClock(int e1, int e2, int m[5][3]){ int i, j, k, p1[e1], p2[e2]; // Initialize p1[] and p2[] for (i = 0; i < e1; i++) p1[i] = i + 1; for (i = 0; i < e2; i++) p2[i] = i + 1; cout << "\t"; for (i = 0; i < e2; i++) cout << "\te2" << i + 1; for (i = 0; i < e1; i++) { cout << "\n e1" << i + 1 << "\t"; for (j = 0; j < e2; j++) cout << m[i][j] << "\t"; } for (i = 0; i < e1; i++) { for (j = 0; j < e2; j++) { // Change the timestamp if the // message is sent if (m[i][j] == 1) { p2[j] = max1(p2[j], p1[i] + 1); for (k = j + 1; k < e2; k++) p2[k] = p2[k - 1] + 1; } // Change the timestamp if the // message is received if (m[i][j] == -1) { p1[i] = max1(p1[i], p2[j] + 1); for (k = i + 1; k < e1; k++) p1[k] = p1[k - 1] + 1; } } } // Function Call display(e1, e2, p1, p2);} // Driver Codeint main(){ int e1 = 5, e2 = 3, m[5][3]; // message is sent and received // between two process /*dep[i][j] = 1, if message is sent from ei to ej dep[i][j] = -1, if message is received by ei from ej dep[i][j] = 0, otherwise*/ m[0][0] = 0; m[0][1] = 0; m[0][2] = 0; m[1][0] = 0; m[1][1] = 0; m[1][2] = 1; m[2][0] = 0; m[2][1] = 0; m[2][2] = 0; m[3][0] = 0; m[3][1] = 0; m[3][2] = 0; m[4][0] = 0; m[4][1] = -1; m[4][2] = 0; // Function Call lamportLogicalClock(e1, e2, m); return 0;} // C program to illustrate the Lamport's// Logical Clock#include <stdio.h> // Function to find the maximum timestamp// between 2 eventsint max1(int a, int b){ // Return the greatest of th two if (a > b) return a; else return b;} // Function to display the logical timestampvoid display(int e1, int e2, int p1[5], int p2[3]){ int i; printf("\nThe time stamps of " "events in P1:\n"); for (i = 0; i < e1; i++) { printf("%d ", p1[i]); } printf("\nThe time stamps of " "events in P2:\n"); // Print the array p2[] for (i = 0; i < e2; i++) printf("%d ", p2[i]);} // Function to find the timestamp of eventsvoid lamportLogicalClock(int e1, int e2, int m[5][3]){ int i, j, k, p1[e1], p2[e2]; // Initialize p1[] and p2[] for (i = 0; i < e1; i++) p1[i] = i + 1; for (i = 0; i < e2; i++) p2[i] = i + 1; for (i = 0; i < e2; i++) printf("\te2%d", i + 1); for (i = 0; i < e1; i++) { printf("\n e1%d \t", i + 1); for (j = 0; j < e2; j++) printf("%d\t", m[i][j]); } for (i = 0; i < e1; i++) { for (j = 0; j < e2; j++) { // Change the timestamp if the // message is sent if (m[i][j] == 1) { p2[j] = max1(p2[j], p1[i] + 1); for (k = j + 1; k < e2; k++) p2[k] = p2[k - 1] + 1; } // Change the timestamp if the // message is received if (m[i][j] == -1) { p1[i] = max1(p1[i], p2[j] + 1); for (k = i + 1; k < e1; k++) p1[k] = p1[k - 1] + 1; } } } // Function Call display(e1, e2, p1, p2);} // Driver Codeint main(){ int e1 = 5, e2 = 3, m[5][3]; // message is sent and received // between two process /*dep[i][j] = 1, if message is sent from ei to ej dep[i][j] = -1, if message is received by ei from ej dep[i][j] = 0, otherwise*/ m[0][0] = 0; m[0][1] = 0; m[0][2] = 0; m[1][0] = 0; m[1][1] = 0; m[1][2] = 1; m[2][0] = 0; m[2][1] = 0; m[2][2] = 0; m[3][0] = 0; m[3][1] = 0; m[3][2] = 0; m[4][0] = 0; m[4][1] = -1; m[4][2] = 0; // Function Call lamportLogicalClock(e1, e2, m); return 0;} # Python program to illustrate the Lamport's# Logical Clock # Function to find the maximum timestamp# between 2 eventsdef max1(a, b) : # Return the greatest of th two if a > b : return a else : return b # Function to display the logical timestampdef display(e1, e2, p1, p2) : print() print("The time stamps of events in P1:") for i in range(0, e1) : print(p1[i], end = " ") print() print("The time stamps of events in P2:") # Print the array p2[] for i in range(0, e2) : print(p2[i], end = " ") # Function to find the timestamp of eventsdef lamportLogicalClock(e1, e2, m) : p1 = [0]*e1 p2 = [0]*e2 # Initialize p1[] and p2[] for i in range (0, e1) : p1[i] = i + 1 for i in range(0, e2) : p2[i] = i + 1 for i in range(0, e2) : print(end = '\t') print("e2", end = "") print(i + 1, end = "") for i in range(0, e1) : print() print("e1", end = "") print(i + 1, end = "\t") for j in range(0, e2) : print(m[i][j], end = "\t") for i in range(0, e1) : for j in range(0, e2) : # Change the timestamp if the # message is sent if(m[i][j] == 1) : p2[j] = max1(p2[j], p1[i] + 1) for i in range(j + 1, e2) : p2[k] = p2[k - 1] + 1 # Change the timestamp if the # message is received if(m[i][j] == -1) : p1[i] = max1(p1[i], p2[j] + 1) for k in range(i + 1, e1) : p1[k] = p1[k - 1] + 1 # Function Call display(e1, e2, p1, p2) # Driver Code if __name__ == "__main__" : e1 = 5 e2 = 3 m = [[0]*3 for i in range(0,5)] # dep[i][j] = 1, if message is sent # from ei to ej # dep[i][j] = -1, if message is received # by ei from ej # dep[i][j] = 0, otherwise m[0][0] = 0 m[0][1] = 0 m[0][2] = 0 m[1][0] = 0 m[1][1] = 0 m[1][2] = 1 m[2][0] = 0 m[2][1] = 0 m[2][2] = 0 m[3][0] = 0 m[3][1] = 0 m[3][2] = 0 m[4][0] = 0 m[4][1] = -1 m[4][2] = 0 # Function Call lamportLogicalClock(e1, e2, m) # This code is contributed by rakeshsahni <script> // JavaScript program to illustrate the Lamport's // Logical Clock // Function to find the maximum timestamp // between 2 events const max1 = (a, b) => { // Return the greatest of th two if (a > b) return a; else return b; } // Function to display the logical timestamp const display = (e1, e2, p1, p2) => { let i; document.write(`<br/>The time stamps of events in P1:<br/>`); for (i = 0; i < e1; i++) { document.write(`${p1[i]} `); } document.write(`<br/>The time stamps of events in P2:<br/>`); // Print the array p2[] for (i = 0; i < e2; i++) document.write(`${p2[i]} `); } // Function to find the timestamp of events const lamportLogicalClock = (e1, e2, m) => { let i, j, k, p1 = [], p2 = []; // Initialize p1[] and p2[] for (i = 0; i < e1; i++) p1[i] = i + 1; for (i = 0; i < e2; i++) p2[i] = i + 1; for (i = 0; i < e2; i++) document.write(`\te2${i + 1}`) for (i = 0; i < e1; i++) { document.write(`<br/>e1${i + 1} `) for (j = 0; j < e2; j++) document.write(`${m[i][j]}\t`); } for (i = 0; i < e1; i++) { for (j = 0; j < e2; j++) { // Change the timestamp if the // message is sent if (m[i][j] == 1) { p2[j] = max1(p2[j], p1[i] + 1); for (k = j + 1; k < e2; k++) p2[k] = p2[k - 1] + 1; } // Change the timestamp if the // message is received if (m[i][j] == -1) { p1[i] = max1(p1[i], p2[j] + 1); for (k = i + 1; k < e1; k++) p1[k] = p1[k - 1] + 1; } } } // Function Call display(e1, e2, p1, p2); } // Driver Code let e1 = 5, e2 = 3; // message is sent and received // between two process /*dep[i][j] = 1, if message is sent from ei to ej dep[i][j] = -1, if message is received by ei from ej dep[i][j] = 0, otherwise*/ const m = [ [0, 0, 0], [0, 0, 1], [0, 0, 0], [0, 0, 0], [0, -1, 0] ] // Function Call lamportLogicalClock(e1, e2, m); // This code is contributed by rakeshsahni </script> e21 e22 e23 e11 0 0 0 e12 0 0 1 e13 0 0 0 e14 0 0 0 e15 0 -1 0 The time stamps of events in P1: 1 2 3 4 5 The time stamps of events in P2: 1 2 3 Time Complexity: O(e1 * e2 * (e1 + e2))Auxiliary Space: O(e1 + e2) counsellinghelp76 rakeshsahni surinderdawra388 ashutoshsinghgeeksforgeeks Clocks Algorithms Articles C Language C Programs Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Nov, 2021" }, { "code": null, "e": 339, "s": 52, "text": "Lamport’s Logical Clock was created by Leslie Lamport. It is a procedure to determine the order of events occurring. It provides a basis for the more advanced Vector Clock Algorithm. Due to the absence of a Global Clock in a Distributed Operating System Lamport Logical Clock is needed." }, { "code": null, "e": 350, "s": 339, "text": "Algorithm:" }, { "code": null, "e": 419, "s": 350, "text": "Happened before relation(->): a -> b, means ‘a’ happened before ‘b’." }, { "code": null, "e": 677, "s": 419, "text": "Logical Clock: The criteria for the logical clocks are:[C1]: Ci (a) < Ci(b), [ Ci -> Logical Clock, If ‘a’ happened before ‘b’, then time of ‘a’ will be less than ‘b’ in a particular process. ][C2]: Ci(a) < Cj(b), [ Clock value of Ci(a) is less than Cj(b) ]" }, { "code": null, "e": 816, "s": 677, "text": "[C1]: Ci (a) < Ci(b), [ Ci -> Logical Clock, If ‘a’ happened before ‘b’, then time of ‘a’ will be less than ‘b’ in a particular process. ]" }, { "code": null, "e": 881, "s": 816, "text": "[C2]: Ci(a) < Cj(b), [ Clock value of Ci(a) is less than Cj(b) ]" }, { "code": null, "e": 892, "s": 881, "text": "Reference:" }, { "code": null, "e": 904, "s": 892, "text": "Process: Pi" }, { "code": null, "e": 986, "s": 904, "text": "Event: Eij, where i is the process in number and j: jth event in the ith process." }, { "code": null, "e": 1022, "s": 986, "text": "tm: vector time span for message m." }, { "code": null, "e": 1158, "s": 1022, "text": "Ci vector clock associated with process Pi, the jth element is Ci[j] and contains Pi‘s latest value for the current time in process Pj." }, { "code": null, "e": 1191, "s": 1158, "text": "d: drift time, generally d is 1." }, { "code": null, "e": 1217, "s": 1191, "text": "Implementation Rules[IR]:" }, { "code": null, "e": 1308, "s": 1217, "text": "[IR1]: If a -> b [‘a’ happened before ‘b’ within the same process] then, Ci(b) =Ci(a) + d" }, { "code": null, "e": 1438, "s": 1308, "text": "[IR2]: Cj = max(Cj, tm + d) [If there’s more number of processes, then tm = value of Ci(a), Cj = max value between Cj and tm + d]" }, { "code": null, "e": 1451, "s": 1438, "text": "For Example:" }, { "code": null, "e": 1575, "s": 1451, "text": "Take the starting value as 1, since it is the 1st event and there is no incoming value at the starting point:e11 = 1e21 = 1" }, { "code": null, "e": 1583, "s": 1575, "text": "e11 = 1" }, { "code": null, "e": 1591, "s": 1583, "text": "e21 = 1" }, { "code": null, "e": 1908, "s": 1591, "text": "The value of the next point will go on increasing by d (d = 1), if there is no incoming value i.e., to follow [IR1].e12 = e11 + d = 1 + 1 = 2e13 = e12 + d = 2 + 1 = 3e14 = e13 + d = 3 + 1 = 4e15 = e14 + d = 4 + 1 = 5e16 = e15 + d = 5 + 1 = 6e22 = e21 + d = 1 + 1 = 2e24 = e23 + d = 3 + 1 = 4e26 = e25 + d = 6 + 1 = 7" }, { "code": null, "e": 1934, "s": 1908, "text": "e12 = e11 + d = 1 + 1 = 2" }, { "code": null, "e": 1960, "s": 1934, "text": "e13 = e12 + d = 2 + 1 = 3" }, { "code": null, "e": 1986, "s": 1960, "text": "e14 = e13 + d = 3 + 1 = 4" }, { "code": null, "e": 2012, "s": 1986, "text": "e15 = e14 + d = 4 + 1 = 5" }, { "code": null, "e": 2038, "s": 2012, "text": "e16 = e15 + d = 5 + 1 = 6" }, { "code": null, "e": 2064, "s": 2038, "text": "e22 = e21 + d = 1 + 1 = 2" }, { "code": null, "e": 2090, "s": 2064, "text": "e24 = e23 + d = 3 + 1 = 4" }, { "code": null, "e": 2116, "s": 2090, "text": "e26 = e25 + d = 6 + 1 = 7" }, { "code": null, "e": 2494, "s": 2116, "text": "When there will be incoming value, then follow [IR2] i.e., take the maximum value between Cj and Tm + d.e17 = max(7, 5) = 7, [e16 + d = 6 + 1 = 7, e24 + d = 4 + 1 = 5, maximum among 7 and 5 is 7]e23 = max(3, 3) = 3, [e22 + d = 2 + 1 = 3, e12 + d = 2 + 1 = 3, maximum among 3 and 3 is 3]e25 = max(5, 6) = 6, [e24 + 1 = 4 + 1 = 5, e15 + d = 5 + 1 = 6, maximum among 5 and 6 is 6]" }, { "code": null, "e": 2586, "s": 2494, "text": "e17 = max(7, 5) = 7, [e16 + d = 6 + 1 = 7, e24 + d = 4 + 1 = 5, maximum among 7 and 5 is 7]" }, { "code": null, "e": 2678, "s": 2586, "text": "e23 = max(3, 3) = 3, [e22 + d = 2 + 1 = 3, e12 + d = 2 + 1 = 3, maximum among 3 and 3 is 3]" }, { "code": null, "e": 2770, "s": 2678, "text": "e25 = max(5, 6) = 6, [e24 + 1 = 4 + 1 = 5, e15 + d = 5 + 1 = 6, maximum among 5 and 6 is 6]" }, { "code": null, "e": 2782, "s": 2770, "text": "Limitation:" }, { "code": null, "e": 2837, "s": 2782, "text": "In case of [IR1], if a -> b, then C(a) < C(b) -> true." }, { "code": null, "e": 2919, "s": 2837, "text": "In case of [IR2], if a -> b, then C(a) < C(b) -> May be true or may not be true." }, { "code": null, "e": 2980, "s": 2919, "text": "Below is the C program to implement Lamport’s Logical Clock:" }, { "code": null, "e": 2984, "s": 2980, "text": "C++" }, { "code": null, "e": 2986, "s": 2984, "text": "C" }, { "code": null, "e": 2994, "s": 2986, "text": "Python3" }, { "code": null, "e": 3005, "s": 2994, "text": "Javascript" }, { "code": "// C++ program to illustrate the Lamport's// Logical Clock #include <bits/stdc++.h>using namespace std; // Function to find the maximum timestamp// between 2 eventsint max1(int a, int b){ // Return the greatest of th two if (a > b) return a; else return b;} // Function to display the logical timestampvoid display(int e1, int e2, int p1[5], int p2[3]){ int i; cout << \"\\nThe time stamps of \" \"events in P1:\\n\"; for (i = 0; i < e1; i++) { cout << p1[i] << \" \"; } cout << \"\\nThe time stamps of \" \"events in P2:\\n\"; // Print the array p2[] for (i = 0; i < e2; i++) cout << p2[i] << \" \";} // Function to find the timestamp of eventsvoid lamportLogicalClock(int e1, int e2, int m[5][3]){ int i, j, k, p1[e1], p2[e2]; // Initialize p1[] and p2[] for (i = 0; i < e1; i++) p1[i] = i + 1; for (i = 0; i < e2; i++) p2[i] = i + 1; cout << \"\\t\"; for (i = 0; i < e2; i++) cout << \"\\te2\" << i + 1; for (i = 0; i < e1; i++) { cout << \"\\n e1\" << i + 1 << \"\\t\"; for (j = 0; j < e2; j++) cout << m[i][j] << \"\\t\"; } for (i = 0; i < e1; i++) { for (j = 0; j < e2; j++) { // Change the timestamp if the // message is sent if (m[i][j] == 1) { p2[j] = max1(p2[j], p1[i] + 1); for (k = j + 1; k < e2; k++) p2[k] = p2[k - 1] + 1; } // Change the timestamp if the // message is received if (m[i][j] == -1) { p1[i] = max1(p1[i], p2[j] + 1); for (k = i + 1; k < e1; k++) p1[k] = p1[k - 1] + 1; } } } // Function Call display(e1, e2, p1, p2);} // Driver Codeint main(){ int e1 = 5, e2 = 3, m[5][3]; // message is sent and received // between two process /*dep[i][j] = 1, if message is sent from ei to ej dep[i][j] = -1, if message is received by ei from ej dep[i][j] = 0, otherwise*/ m[0][0] = 0; m[0][1] = 0; m[0][2] = 0; m[1][0] = 0; m[1][1] = 0; m[1][2] = 1; m[2][0] = 0; m[2][1] = 0; m[2][2] = 0; m[3][0] = 0; m[3][1] = 0; m[3][2] = 0; m[4][0] = 0; m[4][1] = -1; m[4][2] = 0; // Function Call lamportLogicalClock(e1, e2, m); return 0;}", "e": 5435, "s": 3005, "text": null }, { "code": "// C program to illustrate the Lamport's// Logical Clock#include <stdio.h> // Function to find the maximum timestamp// between 2 eventsint max1(int a, int b){ // Return the greatest of th two if (a > b) return a; else return b;} // Function to display the logical timestampvoid display(int e1, int e2, int p1[5], int p2[3]){ int i; printf(\"\\nThe time stamps of \" \"events in P1:\\n\"); for (i = 0; i < e1; i++) { printf(\"%d \", p1[i]); } printf(\"\\nThe time stamps of \" \"events in P2:\\n\"); // Print the array p2[] for (i = 0; i < e2; i++) printf(\"%d \", p2[i]);} // Function to find the timestamp of eventsvoid lamportLogicalClock(int e1, int e2, int m[5][3]){ int i, j, k, p1[e1], p2[e2]; // Initialize p1[] and p2[] for (i = 0; i < e1; i++) p1[i] = i + 1; for (i = 0; i < e2; i++) p2[i] = i + 1; for (i = 0; i < e2; i++) printf(\"\\te2%d\", i + 1); for (i = 0; i < e1; i++) { printf(\"\\n e1%d \\t\", i + 1); for (j = 0; j < e2; j++) printf(\"%d\\t\", m[i][j]); } for (i = 0; i < e1; i++) { for (j = 0; j < e2; j++) { // Change the timestamp if the // message is sent if (m[i][j] == 1) { p2[j] = max1(p2[j], p1[i] + 1); for (k = j + 1; k < e2; k++) p2[k] = p2[k - 1] + 1; } // Change the timestamp if the // message is received if (m[i][j] == -1) { p1[i] = max1(p1[i], p2[j] + 1); for (k = i + 1; k < e1; k++) p1[k] = p1[k - 1] + 1; } } } // Function Call display(e1, e2, p1, p2);} // Driver Codeint main(){ int e1 = 5, e2 = 3, m[5][3]; // message is sent and received // between two process /*dep[i][j] = 1, if message is sent from ei to ej dep[i][j] = -1, if message is received by ei from ej dep[i][j] = 0, otherwise*/ m[0][0] = 0; m[0][1] = 0; m[0][2] = 0; m[1][0] = 0; m[1][1] = 0; m[1][2] = 1; m[2][0] = 0; m[2][1] = 0; m[2][2] = 0; m[3][0] = 0; m[3][1] = 0; m[3][2] = 0; m[4][0] = 0; m[4][1] = -1; m[4][2] = 0; // Function Call lamportLogicalClock(e1, e2, m); return 0;}", "e": 7819, "s": 5435, "text": null }, { "code": "# Python program to illustrate the Lamport's# Logical Clock # Function to find the maximum timestamp# between 2 eventsdef max1(a, b) : # Return the greatest of th two if a > b : return a else : return b # Function to display the logical timestampdef display(e1, e2, p1, p2) : print() print(\"The time stamps of events in P1:\") for i in range(0, e1) : print(p1[i], end = \" \") print() print(\"The time stamps of events in P2:\") # Print the array p2[] for i in range(0, e2) : print(p2[i], end = \" \") # Function to find the timestamp of eventsdef lamportLogicalClock(e1, e2, m) : p1 = [0]*e1 p2 = [0]*e2 # Initialize p1[] and p2[] for i in range (0, e1) : p1[i] = i + 1 for i in range(0, e2) : p2[i] = i + 1 for i in range(0, e2) : print(end = '\\t') print(\"e2\", end = \"\") print(i + 1, end = \"\") for i in range(0, e1) : print() print(\"e1\", end = \"\") print(i + 1, end = \"\\t\") for j in range(0, e2) : print(m[i][j], end = \"\\t\") for i in range(0, e1) : for j in range(0, e2) : # Change the timestamp if the # message is sent if(m[i][j] == 1) : p2[j] = max1(p2[j], p1[i] + 1) for i in range(j + 1, e2) : p2[k] = p2[k - 1] + 1 # Change the timestamp if the # message is received if(m[i][j] == -1) : p1[i] = max1(p1[i], p2[j] + 1) for k in range(i + 1, e1) : p1[k] = p1[k - 1] + 1 # Function Call display(e1, e2, p1, p2) # Driver Code if __name__ == \"__main__\" : e1 = 5 e2 = 3 m = [[0]*3 for i in range(0,5)] # dep[i][j] = 1, if message is sent # from ei to ej # dep[i][j] = -1, if message is received # by ei from ej # dep[i][j] = 0, otherwise m[0][0] = 0 m[0][1] = 0 m[0][2] = 0 m[1][0] = 0 m[1][1] = 0 m[1][2] = 1 m[2][0] = 0 m[2][1] = 0 m[2][2] = 0 m[3][0] = 0 m[3][1] = 0 m[3][2] = 0 m[4][0] = 0 m[4][1] = -1 m[4][2] = 0 # Function Call lamportLogicalClock(e1, e2, m) # This code is contributed by rakeshsahni", "e": 10091, "s": 7819, "text": null }, { "code": "<script> // JavaScript program to illustrate the Lamport's // Logical Clock // Function to find the maximum timestamp // between 2 events const max1 = (a, b) => { // Return the greatest of th two if (a > b) return a; else return b; } // Function to display the logical timestamp const display = (e1, e2, p1, p2) => { let i; document.write(`<br/>The time stamps of events in P1:<br/>`); for (i = 0; i < e1; i++) { document.write(`${p1[i]} `); } document.write(`<br/>The time stamps of events in P2:<br/>`); // Print the array p2[] for (i = 0; i < e2; i++) document.write(`${p2[i]} `); } // Function to find the timestamp of events const lamportLogicalClock = (e1, e2, m) => { let i, j, k, p1 = [], p2 = []; // Initialize p1[] and p2[] for (i = 0; i < e1; i++) p1[i] = i + 1; for (i = 0; i < e2; i++) p2[i] = i + 1; for (i = 0; i < e2; i++) document.write(`\\te2${i + 1}`) for (i = 0; i < e1; i++) { document.write(`<br/>e1${i + 1} `) for (j = 0; j < e2; j++) document.write(`${m[i][j]}\\t`); } for (i = 0; i < e1; i++) { for (j = 0; j < e2; j++) { // Change the timestamp if the // message is sent if (m[i][j] == 1) { p2[j] = max1(p2[j], p1[i] + 1); for (k = j + 1; k < e2; k++) p2[k] = p2[k - 1] + 1; } // Change the timestamp if the // message is received if (m[i][j] == -1) { p1[i] = max1(p1[i], p2[j] + 1); for (k = i + 1; k < e1; k++) p1[k] = p1[k - 1] + 1; } } } // Function Call display(e1, e2, p1, p2); } // Driver Code let e1 = 5, e2 = 3; // message is sent and received // between two process /*dep[i][j] = 1, if message is sent from ei to ej dep[i][j] = -1, if message is received by ei from ej dep[i][j] = 0, otherwise*/ const m = [ [0, 0, 0], [0, 0, 1], [0, 0, 0], [0, 0, 0], [0, -1, 0] ] // Function Call lamportLogicalClock(e1, e2, m); // This code is contributed by rakeshsahni </script>", "e": 12580, "s": 10091, "text": null }, { "code": null, "e": 12811, "s": 12580, "text": " e21 e22 e23\n e11 0 0 0 \n e12 0 0 1 \n e13 0 0 0 \n e14 0 0 0 \n e15 0 -1 0 \nThe time stamps of events in P1:\n1 2 3 4 5 \nThe time stamps of events in P2:\n1 2 3 " }, { "code": null, "e": 12878, "s": 12811, "text": "Time Complexity: O(e1 * e2 * (e1 + e2))Auxiliary Space: O(e1 + e2)" }, { "code": null, "e": 12896, "s": 12878, "text": "counsellinghelp76" }, { "code": null, "e": 12908, "s": 12896, "text": "rakeshsahni" }, { "code": null, "e": 12925, "s": 12908, "text": "surinderdawra388" }, { "code": null, "e": 12952, "s": 12925, "text": "ashutoshsinghgeeksforgeeks" }, { "code": null, "e": 12959, "s": 12952, "text": "Clocks" }, { "code": null, "e": 12970, "s": 12959, "text": "Algorithms" }, { "code": null, "e": 12979, "s": 12970, "text": "Articles" }, { "code": null, "e": 12990, "s": 12979, "text": "C Language" }, { "code": null, "e": 13001, "s": 12990, "text": "C Programs" }, { "code": null, "e": 13012, "s": 13001, "text": "Algorithms" } ]
How to use stopwatch in PowerShell?
To use the stopwatch in PowerShell, we need to use [System.Diagnostics.Stopwatch] class. We will create a new object for this class, $stopwatch = [System.Diagnostics.Stopwatch]::new() Below are the members of the above stopwatch mentioned class. PS C:\> $Stopwatch | gm TypeName: System.Diagnostics.Stopwatch Name MemberType Definition ---- ---------- ---------- Equals Method bool Equals(System.Object obj) GetHashCode Method int GetHashCode() GetType Method type GetType() Reset Method void Reset() Restart Method void Restart() Start Method void Start() Stop Method void Stop() ToString Method string ToString() Elapsed Property timespan Elapsed {get;} ElapsedMilliseconds Property long ElapsedMilliseconds {get;} ElapsedTicks Property long ElapsedTicks {get;} IsRunning Property bool IsRunning {get;} You can see above that you can Start, Stop, Restart, and Reset the stopwatch and before starting all values should be 0. PS C:\> $Stopwatch.Elapsed Days : 0 Hours : 0 Minutes : 0 Seconds : 0 Milliseconds : 0 Ticks : 0 TotalDays : 0 TotalHours : 0 TotalMinutes : 0 TotalSeconds : 0 TotalMilliseconds : 0 Now, we will start the timer using the Start() method. $Stopwatch.Start() You can check the elapsed time using the Elapsed property. PS C:\> $Stopwatch.Elapsed Days : 0 Hours : 0 Minutes : 1 Seconds : 42 Milliseconds : 284 Ticks : 1022842838 TotalDays : 0.00118384587731481 TotalHours : 0.0284123010555556 TotalMinutes : 1.70473806333333 TotalSeconds : 102.2842838 TotalMilliseconds : 102284.2838 To retrieve any of the above property, use the property name. For example, PS C:\> $Stopwatch.Elapsed.Minutes 4 To stop the stopwatch use Stop(), to Reset the Stopwatch use Reset() methods, and to restart the stopwatch use Restart() method. PS C:\> $Stopwatch.Reset() PS C:\> $Stopwatch.Elapsed Days : 0 Hours : 0 Minutes : 0 Seconds : 0 Milliseconds : 0 Ticks : 0 TotalDays : 0 TotalHours : 0 TotalMinutes : 0 TotalSeconds : 0 TotalMilliseconds : 0 PS C:\> $Stopwatch.Restart() PS C:\> $Stopwatch.Elapsed Days : 0 Hours : 0 Minutes : 0 Seconds : 1 Milliseconds : 757 Ticks : 17570261 TotalDays : 2.03359502314815E-05 TotalHours : 0.000488062805555556 TotalMinutes : 0.0292837683333333 TotalSeconds : 1.7570261 TotalMilliseconds : 1757.0261 PS C:\> $Stopwatch.Stop() PS C:\> $Stopwatch.Elapsed Days : 0 Hours : 0 Minutes : 6 Seconds : 36 Milliseconds : 121 Ticks : 3961214918 TotalDays : 0.00458473948842593 TotalHours : 0.110033747722222 TotalMinutes : 6.60202486333333 TotalSeconds : 396.1214918 TotalMilliseconds : 396121.4918
[ { "code": null, "e": 1276, "s": 1187, "text": "To use the stopwatch in PowerShell, we need to use [System.Diagnostics.Stopwatch] class." }, { "code": null, "e": 1320, "s": 1276, "text": "We will create a new object for this class," }, { "code": null, "e": 1371, "s": 1320, "text": "$stopwatch = [System.Diagnostics.Stopwatch]::new()" }, { "code": null, "e": 1433, "s": 1371, "text": "Below are the members of the above stopwatch mentioned class." }, { "code": null, "e": 1995, "s": 1433, "text": "PS C:\\> $Stopwatch | gm\n\n\nTypeName: System.Diagnostics.Stopwatch\n\nName MemberType Definition\n---- ---------- ----------\nEquals Method bool Equals(System.Object obj)\nGetHashCode Method int GetHashCode()\nGetType Method type GetType()\nReset Method void Reset()\nRestart Method void Restart()\nStart Method void Start()\nStop Method void Stop()\nToString Method string ToString()\nElapsed Property timespan Elapsed {get;}\nElapsedMilliseconds Property long ElapsedMilliseconds {get;}\nElapsedTicks Property long ElapsedTicks {get;}\nIsRunning Property bool IsRunning {get;}" }, { "code": null, "e": 2116, "s": 1995, "text": "You can see above that you can Start, Stop, Restart, and Reset the stopwatch and before starting all values should be 0." }, { "code": null, "e": 2299, "s": 2116, "text": "PS C:\\> $Stopwatch.Elapsed\n\nDays : 0\nHours : 0\nMinutes : 0\nSeconds : 0\nMilliseconds : 0\nTicks : 0\nTotalDays : 0\nTotalHours : 0\nTotalMinutes : 0\nTotalSeconds : 0\nTotalMilliseconds : 0" }, { "code": null, "e": 2354, "s": 2299, "text": "Now, we will start the timer using the Start() method." }, { "code": null, "e": 2374, "s": 2354, "text": "$Stopwatch.Start()\n" }, { "code": null, "e": 2433, "s": 2374, "text": "You can check the elapsed time using the Elapsed property." }, { "code": null, "e": 2698, "s": 2433, "text": "PS C:\\> $Stopwatch.Elapsed\n\nDays : 0\nHours : 0\nMinutes : 1\nSeconds : 42\nMilliseconds : 284\nTicks : 1022842838\nTotalDays : 0.00118384587731481\nTotalHours : 0.0284123010555556\nTotalMinutes : 1.70473806333333\nTotalSeconds : 102.2842838\nTotalMilliseconds : 102284.2838" }, { "code": null, "e": 2773, "s": 2698, "text": "To retrieve any of the above property, use the property name. For example," }, { "code": null, "e": 2810, "s": 2773, "text": "PS C:\\> $Stopwatch.Elapsed.Minutes\n4" }, { "code": null, "e": 2939, "s": 2810, "text": "To stop the stopwatch use Stop(), to Reset the Stopwatch use Reset() methods, and to restart the stopwatch use Restart() method." }, { "code": null, "e": 3733, "s": 2939, "text": "PS C:\\> $Stopwatch.Reset()\nPS C:\\> $Stopwatch.Elapsed\n\nDays : 0\nHours : 0\nMinutes : 0\nSeconds : 0\nMilliseconds : 0\nTicks : 0\nTotalDays : 0\nTotalHours : 0\nTotalMinutes : 0\nTotalSeconds : 0\nTotalMilliseconds : 0\n\nPS C:\\> $Stopwatch.Restart()\nPS C:\\> $Stopwatch.Elapsed\n\nDays : 0\nHours : 0\nMinutes : 0\nSeconds : 1\nMilliseconds : 757\nTicks : 17570261\nTotalDays : 2.03359502314815E-05\nTotalHours : 0.000488062805555556\nTotalMinutes : 0.0292837683333333\nTotalSeconds : 1.7570261\nTotalMilliseconds : 1757.0261\n\nPS C:\\> $Stopwatch.Stop()\nPS C:\\> $Stopwatch.Elapsed\n\nDays : 0\nHours : 0\nMinutes : 6\nSeconds : 36\nMilliseconds : 121\nTicks : 3961214918\nTotalDays : 0.00458473948842593\nTotalHours : 0.110033747722222\nTotalMinutes : 6.60202486333333\nTotalSeconds : 396.1214918\nTotalMilliseconds : 396121.4918" } ]
Select Rows with Partial String Match in R DataFrame
17 Dec, 2021 In this article, we’ll discuss how to select rows with a partial string match in the R programming language. The stringr package in R language is used mainly for character manipulations, locale-sensitive operations, altering whitespace, and Pattern-matching. Here we will use its pattern matching functionality to filter data according to partial string match. Syntax: df[str_detect(df$column-name, “Pattern”), ] Parameters: df: determines the dataframe that is being used. column-name: determines the column in which strings have to be filtered. Pattern: determines the string pattern that has to be matched. Example: This example explains how to extract rows with a partial match using the stringr package. R # Load library stringrlibrary("stringr") # sample dataframedata<- data.frame(names=c('Hello','this','Hell','Geeks', 'Geek', 'Geeksforgeeks')) # Filter data with str_detect for strings# containing "Gee"result1<-data[str_detect(data$name, "Gee"), ] # print result dataresult1 # Filter data with str_detect for strings# containing "Hel"result2<-data[str_detect(data$name, "Hel"), ] # print result dataresult2 Output: [1] “Geeks” “Geek” “Geeksforgeeks” [1] “Hello” “Hell” Data.table is an extension of data.frame package in R. It is widely used for fast aggregation of large datasets, low latency add/update/remove of columns, quicker ordered joins, and a fast file reader. Here we will use its data update of the column functionality to filter data according to partial string match. We will use %like%-operator to select the string match data and will filter data from the dataframe accordingly. Syntax: df[df$column-name %like% “Pattern”, ] Parameter: df: determines the dataframe that is being used. column-name: determines the column in which strings have to be filtered. Pattern: determines the string pattern that has to be matched. Example: This example explains how to extract rows with a partial match using the data.table package. R # load data.table packagelibrary("data.table") # sample dataframedata<- data.frame(names=c('Hello','this','Hell','Geeks', 'Geek', 'Geeksforgeeks')) # Filter data with %like% all strings having "Gee"result1<-data[data$name %like% "Gee", ] # print result dataresult1 # Filter data with %like% all strings having "Hel"result2<-data[data$name %like% "Hel", ] # print result dataresult2 Output: [1] “Geeks” “Geek” “Geeksforgeeks” [1] “Hello” “Hell” rajeev0719singh Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R Merge DataFrames by Column Names in R How to Sort a DataFrame in R ?
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Dec, 2021" }, { "code": null, "e": 137, "s": 28, "text": "In this article, we’ll discuss how to select rows with a partial string match in the R programming language." }, { "code": null, "e": 389, "s": 137, "text": "The stringr package in R language is used mainly for character manipulations, locale-sensitive operations, altering whitespace, and Pattern-matching. Here we will use its pattern matching functionality to filter data according to partial string match." }, { "code": null, "e": 397, "s": 389, "text": "Syntax:" }, { "code": null, "e": 441, "s": 397, "text": "df[str_detect(df$column-name, “Pattern”), ]" }, { "code": null, "e": 453, "s": 441, "text": "Parameters:" }, { "code": null, "e": 502, "s": 453, "text": "df: determines the dataframe that is being used." }, { "code": null, "e": 575, "s": 502, "text": "column-name: determines the column in which strings have to be filtered." }, { "code": null, "e": 638, "s": 575, "text": "Pattern: determines the string pattern that has to be matched." }, { "code": null, "e": 738, "s": 638, "text": "Example: This example explains how to extract rows with a partial match using the stringr package. " }, { "code": null, "e": 740, "s": 738, "text": "R" }, { "code": "# Load library stringrlibrary(\"stringr\") # sample dataframedata<- data.frame(names=c('Hello','this','Hell','Geeks', 'Geek', 'Geeksforgeeks')) # Filter data with str_detect for strings# containing \"Gee\"result1<-data[str_detect(data$name, \"Gee\"), ] # print result dataresult1 # Filter data with str_detect for strings# containing \"Hel\"result2<-data[str_detect(data$name, \"Hel\"), ] # print result dataresult2", "e": 1188, "s": 740, "text": null }, { "code": null, "e": 1197, "s": 1188, "text": "Output: " }, { "code": null, "e": 1249, "s": 1197, "text": "[1] “Geeks” “Geek” “Geeksforgeeks”" }, { "code": null, "e": 1269, "s": 1249, "text": "[1] “Hello” “Hell” " }, { "code": null, "e": 1696, "s": 1269, "text": "Data.table is an extension of data.frame package in R. It is widely used for fast aggregation of large datasets, low latency add/update/remove of columns, quicker ordered joins, and a fast file reader. Here we will use its data update of the column functionality to filter data according to partial string match. We will use %like%-operator to select the string match data and will filter data from the dataframe accordingly. " }, { "code": null, "e": 1704, "s": 1696, "text": "Syntax:" }, { "code": null, "e": 1742, "s": 1704, "text": "df[df$column-name %like% “Pattern”, ]" }, { "code": null, "e": 1753, "s": 1742, "text": "Parameter:" }, { "code": null, "e": 1802, "s": 1753, "text": "df: determines the dataframe that is being used." }, { "code": null, "e": 1875, "s": 1802, "text": "column-name: determines the column in which strings have to be filtered." }, { "code": null, "e": 1938, "s": 1875, "text": "Pattern: determines the string pattern that has to be matched." }, { "code": null, "e": 2042, "s": 1938, "text": "Example: This example explains how to extract rows with a partial match using the data.table package. " }, { "code": null, "e": 2044, "s": 2042, "text": "R" }, { "code": "# load data.table packagelibrary(\"data.table\") # sample dataframedata<- data.frame(names=c('Hello','this','Hell','Geeks', 'Geek', 'Geeksforgeeks')) # Filter data with %like% all strings having \"Gee\"result1<-data[data$name %like% \"Gee\", ] # print result dataresult1 # Filter data with %like% all strings having \"Hel\"result2<-data[data$name %like% \"Hel\", ] # print result dataresult2", "e": 2453, "s": 2044, "text": null }, { "code": null, "e": 2461, "s": 2453, "text": "Output:" }, { "code": null, "e": 2513, "s": 2461, "text": "[1] “Geeks” “Geek” “Geeksforgeeks”" }, { "code": null, "e": 2533, "s": 2513, "text": "[1] “Hello” “Hell” " }, { "code": null, "e": 2549, "s": 2533, "text": "rajeev0719singh" }, { "code": null, "e": 2556, "s": 2549, "text": "Picked" }, { "code": null, "e": 2577, "s": 2556, "text": "R DataFrame-Programs" }, { "code": null, "e": 2589, "s": 2577, "text": "R-DataFrame" }, { "code": null, "e": 2600, "s": 2589, "text": "R Language" }, { "code": null, "e": 2611, "s": 2600, "text": "R Programs" }, { "code": null, "e": 2709, "s": 2611, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2761, "s": 2709, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 2819, "s": 2761, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 2854, "s": 2819, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 2892, "s": 2854, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 2941, "s": 2892, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 2999, "s": 2941, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 3048, "s": 2999, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 3091, "s": 3048, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 3129, "s": 3091, "text": "Merge DataFrames by Column Names in R" } ]
Stack isEmpty() method in Java with Example
24 Dec, 2018 The Java.util.Stack.isEmpty() method in Java is used to check and verify if a Stack is empty or not. It returns True if the Stack is empty else it returns False. Syntax: Stack.isEmpty() Parameters: This method does not take any parameter. Return Value: This function returns True if the Stackis empty else it returns False. Below programs illustrate the Java.util.Stack.isEmpty() method: Program 1: // Java code to illustrate isEmpty()import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<String> stack = new Stack<String>(); // Use add() method to add elements into the Stack stack.add("Welcome"); stack.add("To"); stack.add("Geeks"); stack.add("4"); stack.add("Geeks"); // Displaying the Stack System.out.println("Stack: " + stack); // Verifying if the Stack is empty or not System.out.println("Is the Stack empty? " + stack.isEmpty()); // Clearing the Stack stack.clear(); // Displaying the Stack System.out.println("Stack after clear(): " + stack); // Verifying if the Stack is empty or not System.out.println("Is the Stack empty? " + stack.isEmpty()); }} Stack: [Welcome, To, Geeks, 4, Geeks] Is the Stack empty? false Stack after clear(): [] Is the Stack empty? true Program 2: // Java code to illustrate isEmpty()import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<Integer> stack = new Stack<Integer>(); // Displaying the Stack System.out.println("Stack: " + stack); // Verifying if the Stack is empty or not System.out.println("Is the Stack empty? " + stack.isEmpty()); }} Stack: [] Is the Stack empty? true Java - util package Java-Collections Java-Functions Java-Stack Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Object Oriented Programming (OOPs) Concept in Java Reverse a string in Java For-each loop in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Dec, 2018" }, { "code": null, "e": 190, "s": 28, "text": "The Java.util.Stack.isEmpty() method in Java is used to check and verify if a Stack is empty or not. It returns True if the Stack is empty else it returns False." }, { "code": null, "e": 198, "s": 190, "text": "Syntax:" }, { "code": null, "e": 214, "s": 198, "text": "Stack.isEmpty()" }, { "code": null, "e": 267, "s": 214, "text": "Parameters: This method does not take any parameter." }, { "code": null, "e": 352, "s": 267, "text": "Return Value: This function returns True if the Stackis empty else it returns False." }, { "code": null, "e": 416, "s": 352, "text": "Below programs illustrate the Java.util.Stack.isEmpty() method:" }, { "code": null, "e": 427, "s": 416, "text": "Program 1:" }, { "code": "// Java code to illustrate isEmpty()import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<String> stack = new Stack<String>(); // Use add() method to add elements into the Stack stack.add(\"Welcome\"); stack.add(\"To\"); stack.add(\"Geeks\"); stack.add(\"4\"); stack.add(\"Geeks\"); // Displaying the Stack System.out.println(\"Stack: \" + stack); // Verifying if the Stack is empty or not System.out.println(\"Is the Stack empty? \" + stack.isEmpty()); // Clearing the Stack stack.clear(); // Displaying the Stack System.out.println(\"Stack after clear(): \" + stack); // Verifying if the Stack is empty or not System.out.println(\"Is the Stack empty? \" + stack.isEmpty()); }}", "e": 1380, "s": 427, "text": null }, { "code": null, "e": 1495, "s": 1380, "text": "Stack: [Welcome, To, Geeks, 4, Geeks]\nIs the Stack empty? false\nStack after clear(): []\nIs the Stack empty? true\n" }, { "code": null, "e": 1506, "s": 1495, "text": "Program 2:" }, { "code": "// Java code to illustrate isEmpty()import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<Integer> stack = new Stack<Integer>(); // Displaying the Stack System.out.println(\"Stack: \" + stack); // Verifying if the Stack is empty or not System.out.println(\"Is the Stack empty? \" + stack.isEmpty()); }}", "e": 1953, "s": 1506, "text": null }, { "code": null, "e": 1990, "s": 1953, "text": "Stack: []\nIs the Stack empty? true\n" }, { "code": null, "e": 2010, "s": 1990, "text": "Java - util package" }, { "code": null, "e": 2027, "s": 2010, "text": "Java-Collections" }, { "code": null, "e": 2042, "s": 2027, "text": "Java-Functions" }, { "code": null, "e": 2053, "s": 2042, "text": "Java-Stack" }, { "code": null, "e": 2058, "s": 2053, "text": "Java" }, { "code": null, "e": 2063, "s": 2058, "text": "Java" }, { "code": null, "e": 2080, "s": 2063, "text": "Java-Collections" }, { "code": null, "e": 2178, "s": 2080, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2193, "s": 2178, "text": "Arrays in Java" }, { "code": null, "e": 2237, "s": 2193, "text": "Split() String method in Java with examples" }, { "code": null, "e": 2273, "s": 2237, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 2324, "s": 2273, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 2349, "s": 2324, "text": "Reverse a string in Java" }, { "code": null, "e": 2371, "s": 2349, "text": "For-each loop in Java" }, { "code": null, "e": 2402, "s": 2371, "text": "How to iterate any Map in Java" }, { "code": null, "e": 2421, "s": 2402, "text": "Interfaces in Java" }, { "code": null, "e": 2451, "s": 2421, "text": "HashMap in Java with Examples" } ]
Python | Unit Test Objects Patching | Set-1
12 Jun, 2019 The problem is writing unit tests and need to apply patches to selected objects in order to make assertions about how they were used in the test (e.g., assertions about being called with certain parameters, access to selected attributes, etc.). To do so, the unittest.mock.patch() function can be used to help with this problem. It’s a little unusual, but patch() can be used as a decorator, a context manager, or stand-alone. from unittest.mock import patchimport example@patch('example.func') def test1(x, mock_func): # Uses patched example.func example.func(x) mock_func.assert_called_with(x) Code #2: Using unittest.mock.patch as a decorator with patch('example.func') as mock_func: example.func(x) mock_func.assert_called_with(x) Code #3: Using unittest.mock.patch to patch things manually. p = patch('example.func')mock_func = p.start()example.func(x)mock_func.assert_called_with(x)p.stop() Code #4: Stacking decorators and context managers to patch multiple objects @patch('example.func1')@patch('example.func2')@patch('example.func3') def test1(mock1, mock2, mock3): ...def test2(): with patch('example.patch1') as mock1, \ patch('example.patch2') as mock2, \ patch('example.patch3') as mock3: ... patch() works by taking an existing object with the fully qualified name that you provide and replacing it with a new value. The original value is then restored after the completion of the decorated function or context manager. By default, values are replaced with MagicMock instances. Code #5 : Example x = 42with patch('__main__.x'): print(x) print (x) Output : <MagicMock name='x' id='4314230032'> 42 Python-ctype 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": "\n12 Jun, 2019" }, { "code": null, "e": 273, "s": 28, "text": "The problem is writing unit tests and need to apply patches to selected objects in order to make assertions about how they were used in the test (e.g., assertions about being called with certain parameters, access to selected attributes, etc.)." }, { "code": null, "e": 455, "s": 273, "text": "To do so, the unittest.mock.patch() function can be used to help with this problem. It’s a little unusual, but patch() can be used as a decorator, a context manager, or stand-alone." }, { "code": "from unittest.mock import patchimport example@patch('example.func') def test1(x, mock_func): # Uses patched example.func example.func(x) mock_func.assert_called_with(x)", "e": 635, "s": 455, "text": null }, { "code": null, "e": 686, "s": 635, "text": " Code #2: Using unittest.mock.patch as a decorator" }, { "code": "with patch('example.func') as mock_func: example.func(x) mock_func.assert_called_with(x)", "e": 782, "s": 686, "text": null }, { "code": null, "e": 844, "s": 782, "text": " Code #3: Using unittest.mock.patch to patch things manually." }, { "code": "p = patch('example.func')mock_func = p.start()example.func(x)mock_func.assert_called_with(x)p.stop()", "e": 945, "s": 844, "text": null }, { "code": null, "e": 1022, "s": 945, "text": " Code #4: Stacking decorators and context managers to patch multiple objects" }, { "code": "@patch('example.func1')@patch('example.func2')@patch('example.func3') def test1(mock1, mock2, mock3): ...def test2(): with patch('example.patch1') as mock1, \\ patch('example.patch2') as mock2, \\ patch('example.patch3') as mock3: ...", "e": 1271, "s": 1022, "text": null }, { "code": null, "e": 1575, "s": 1271, "text": "patch() works by taking an existing object with the fully qualified name that you provide and replacing it with a new value. The original value is then restored after the completion of the decorated function or context manager. By default, values are replaced with MagicMock instances. Code #5 : Example" }, { "code": "x = 42with patch('__main__.x'): print(x) print (x)", "e": 1630, "s": 1575, "text": null }, { "code": null, "e": 1639, "s": 1630, "text": "Output :" }, { "code": null, "e": 1679, "s": 1639, "text": "<MagicMock name='x' id='4314230032'>\n42" }, { "code": null, "e": 1692, "s": 1679, "text": "Python-ctype" }, { "code": null, "e": 1699, "s": 1692, "text": "Python" }, { "code": null, "e": 1797, "s": 1699, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1815, "s": 1797, "text": "Python Dictionary" }, { "code": null, "e": 1857, "s": 1815, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1879, "s": 1857, "text": "Enumerate() in Python" }, { "code": null, "e": 1914, "s": 1879, "text": "Read a file line by line in Python" }, { "code": null, "e": 1940, "s": 1914, "text": "Python String | replace()" }, { "code": null, "e": 1972, "s": 1940, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2001, "s": 1972, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2028, "s": 2001, "text": "Python Classes and Objects" }, { "code": null, "e": 2058, "s": 2028, "text": "Iterate over a list in Python" } ]
Maximum number of region in which N non-parallel lines can divide a plane
05 May, 2021 Given N‘, the number of non-parallel lines. The task is to find the maximum number of regions in which these lines can divide a plane.Examples: Input : N = 3 Output : 7Input : N = 2 Output : 4 Maximum number of regions on a plane formed due to non-parallel lines Approach: The above image shows the maximum number of regions a line can divide a plane. One line can divide a plane into two regions, two non-parallel lines can divide a plane into 4 regions and three non-parallel lines can divide into 7 regions, and so on. When the nth line is added to a cluster of (n-1) lines then the maximum number of extra regions formed is equal to n.Now solve the recursion as follows: L(2) – L(1) = 2 ... (i) L(3) – L(2) = 3 ... (ii) L(4) – L(3) = 4 ... (iii) . . . . . . L(n) – L(n-1) = n ; ... (n) Adding all the above equation we get,L(n) – L(1) = 2 + 3 + 4 + 5 + 6 + 7 + ...... + n ; L(n) = L(1) + 2 + 3 + 4 + 5 + 6 + 7 + ...... + n ; L(n) = 2 + 2 + 3 + 4 + 5 + 6 + 7 + ...... + n ; L(n) = 1 + 2 + 3 + 4 + 5 + 6 + 7 + ...... + n + 1 ; L(n) = n ( n + 1 ) / 2 + 1 ; The number of region in which N non-parallel lines can divide a plane is equal to N*( N + 1 )/2 + 1.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to implement the above problem #include <bits/stdc++.h>using namespace std; // Function to find the maximum// number of regions on a planevoid maxRegions(int n){ int num; num = n * (n + 1) / 2 + 1; // print the maximum number of regions cout << num;} // Driver codeint main(){ int n = 10; maxRegions(n); return 0;} // Java program to implement the above problemclass GFG{ // Function to find the maximum // number of regions on a plane static void maxRegions(int n) { int num; num = n * (n + 1) / 2 + 1; // print the maximum number of regions System.out.println(num);; } // Driver code public static void main(String[] args) { int n = 10; maxRegions(n); }} // This code is contributed by 29AjayKumar # Python3 program to implement# the above problem # Function to find the maximum# number of regions on a planedef maxRegions(n): num = n * (n + 1) // 2 + 1 # print the maximum number # of regions print(num) # Driver coden = 10 maxRegions(n) # This code is contributed# by Mohit Kumar // C# program to implement the above problemusing System; class GFG{ // Function to find the maximum // number of regions on a plane static void maxRegions(int n) { int num; num = n * (n + 1) / 2 + 1; // print the maximum number of regions Console.WriteLine(num); } // Driver code public static void Main(String[] args) { int n = 10; maxRegions(n); }} // This code is contributed by 29AjayKumar <script> // Javascript program to implement the above problem // Function to find the maximum// number of regions on a planefunction maxRegions(n){ let num; num = parseInt( n * (n + 1) / 2) + 1; // print the maximum number of regions document.write(num);} // Driver code let n = 10; maxRegions(n); </script> 56 Time Complexity : O(1) mohit kumar 29 29AjayKumar rishavmahato348 Numbers Geometric Mathematical Mathematical Numbers Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n05 May, 2021" }, { "code": null, "e": 200, "s": 54, "text": "Given N‘, the number of non-parallel lines. The task is to find the maximum number of regions in which these lines can divide a plane.Examples: " }, { "code": null, "e": 251, "s": 200, "text": "Input : N = 3 Output : 7Input : N = 2 Output : 4 " }, { "code": null, "e": 325, "s": 255, "text": "Maximum number of regions on a plane formed due to non-parallel lines" }, { "code": null, "e": 739, "s": 325, "text": "Approach: The above image shows the maximum number of regions a line can divide a plane. One line can divide a plane into two regions, two non-parallel lines can divide a plane into 4 regions and three non-parallel lines can divide into 7 regions, and so on. When the nth line is added to a cluster of (n-1) lines then the maximum number of extra regions formed is equal to n.Now solve the recursion as follows: " }, { "code": null, "e": 1123, "s": 739, "text": "L(2) – L(1) = 2 ... (i) L(3) – L(2) = 3 ... (ii) L(4) – L(3) = 4 ... (iii) . . . . . . L(n) – L(n-1) = n ; ... (n) Adding all the above equation we get,L(n) – L(1) = 2 + 3 + 4 + 5 + 6 + 7 + ...... + n ; L(n) = L(1) + 2 + 3 + 4 + 5 + 6 + 7 + ...... + n ; L(n) = 2 + 2 + 3 + 4 + 5 + 6 + 7 + ...... + n ; L(n) = 1 + 2 + 3 + 4 + 5 + 6 + 7 + ...... + n + 1 ; L(n) = n ( n + 1 ) / 2 + 1 ; " }, { "code": null, "e": 1276, "s": 1123, "text": "The number of region in which N non-parallel lines can divide a plane is equal to N*( N + 1 )/2 + 1.Below is the implementation of the above approach: " }, { "code": null, "e": 1280, "s": 1276, "text": "C++" }, { "code": null, "e": 1285, "s": 1280, "text": "Java" }, { "code": null, "e": 1293, "s": 1285, "text": "Python3" }, { "code": null, "e": 1296, "s": 1293, "text": "C#" }, { "code": null, "e": 1307, "s": 1296, "text": "Javascript" }, { "code": "// C++ program to implement the above problem #include <bits/stdc++.h>using namespace std; // Function to find the maximum// number of regions on a planevoid maxRegions(int n){ int num; num = n * (n + 1) / 2 + 1; // print the maximum number of regions cout << num;} // Driver codeint main(){ int n = 10; maxRegions(n); return 0;}", "e": 1661, "s": 1307, "text": null }, { "code": "// Java program to implement the above problemclass GFG{ // Function to find the maximum // number of regions on a plane static void maxRegions(int n) { int num; num = n * (n + 1) / 2 + 1; // print the maximum number of regions System.out.println(num);; } // Driver code public static void main(String[] args) { int n = 10; maxRegions(n); }} // This code is contributed by 29AjayKumar", "e": 2118, "s": 1661, "text": null }, { "code": "# Python3 program to implement# the above problem # Function to find the maximum# number of regions on a planedef maxRegions(n): num = n * (n + 1) // 2 + 1 # print the maximum number # of regions print(num) # Driver coden = 10 maxRegions(n) # This code is contributed# by Mohit Kumar", "e": 2415, "s": 2118, "text": null }, { "code": "// C# program to implement the above problemusing System; class GFG{ // Function to find the maximum // number of regions on a plane static void maxRegions(int n) { int num; num = n * (n + 1) / 2 + 1; // print the maximum number of regions Console.WriteLine(num); } // Driver code public static void Main(String[] args) { int n = 10; maxRegions(n); }} // This code is contributed by 29AjayKumar", "e": 2886, "s": 2415, "text": null }, { "code": "<script> // Javascript program to implement the above problem // Function to find the maximum// number of regions on a planefunction maxRegions(n){ let num; num = parseInt( n * (n + 1) / 2) + 1; // print the maximum number of regions document.write(num);} // Driver code let n = 10; maxRegions(n); </script>", "e": 3214, "s": 2886, "text": null }, { "code": null, "e": 3217, "s": 3214, "text": "56" }, { "code": null, "e": 3243, "s": 3219, "text": "Time Complexity : O(1) " }, { "code": null, "e": 3258, "s": 3243, "text": "mohit kumar 29" }, { "code": null, "e": 3270, "s": 3258, "text": "29AjayKumar" }, { "code": null, "e": 3286, "s": 3270, "text": "rishavmahato348" }, { "code": null, "e": 3294, "s": 3286, "text": "Numbers" }, { "code": null, "e": 3304, "s": 3294, "text": "Geometric" }, { "code": null, "e": 3317, "s": 3304, "text": "Mathematical" }, { "code": null, "e": 3330, "s": 3317, "text": "Mathematical" }, { "code": null, "e": 3338, "s": 3330, "text": "Numbers" }, { "code": null, "e": 3348, "s": 3338, "text": "Geometric" } ]
Operating Systems | Set 12
31 Aug, 2021 Following questions have been asked in GATE CS 2007 exam. 1) Consider a disk pack with 16 surfaces, 128 tracks per surface and 256 sectors per track. 512 bytes of data are stored in a bit serial manner in a sector. The capacity of the disk pack and the number of bits required to specify a particular sector in the disk are respectively: (A) 256 Mbyte, 19 bits (B) 256 Mbyte, 28 bits (C) 512 Mbyte, 20 bits (D) 64 Gbyte, 28 bits Answer (A) Capacity of the disk = 16 surfaces X 128 tracks X 256 sectors X 512 bytes = 256 Mbytes. To calculate number of bits required to access a sector, we need to know total number of sectors. Total number of sectors = 16 surfaces X 128 tracks X 256 sectors = 2^19 So the number of bits required to access a sector is 19. 2) Group 1 contains some CPU scheduling algorithms and Group 2 contains some applications. Match entries in Group 1 to entries in Group 2. Group I Group II (P) Gang Scheduling (1) Guaranteed Scheduling (Q) Rate Monotonic Scheduling (2) Real-time Scheduling (R) Fair Share Scheduling (3) Thread Scheduling (A) P – 3 Q – 2 R – 1 (B) P – 1 Q – 2 R – 3 (C) P – 2 Q – 3 R – 1 (D) P – 1 Q – 3 R – 2 Answer (A) Gang scheduling for parallel systems that schedules related threads or processes to run simultaneously on different processors. Rate monotonic scheduling is used in real-time operating systems with a static-priority scheduling class. The static priorities are assigned on the basis of the cycle duration of the job: the shorter the cycle duration is, the higher is the job’s priority. Fair Share Scheduling is a scheduling strategy in which the CPU usage is equally distributed among system users or groups, as opposed to equal distribution among processes. It is also known as Guaranteed scheduling. 3) An operating system uses Shortest Remaining Time first (SRT) process scheduling algorithm. Consider the arrival times and execution times for the following processes: Process Execution time Arrival time P1 20 0 P2 25 15 P3 10 30 P4 15 45 What is the total waiting time for process P2? (A) 5 (B) 15 (C) 40 (D) 55 Answer (B) At time 0, P1 is the only process, P1 runs for 15 time units. At time 15, P2 arrives, but P1 has the shortest remaining time. So P1 continues for 5 more time units. At time 20, P2 is the only process. So it runs for 10 time units At time 30, P3 is the shortest remaining time process. So it runs for 10 time units At time 40, P2 runs as it is the only process. P2 runs for 5 time units. At time 45, P3 arrives, but P2 has the shortest remaining time. So P2 continues for 10 more time units. P2 completes its execution at time 55 Total waiting time for P2 = Complition time - (Arrival time + Execution time) = 55 - (15 + 25) = 15 Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc. Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above adnanirshad158 GATE-CS-2007 GATE CS MCQ Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Page Replacement Algorithms in Operating Systems Introduction of Operating System - Set 1 Inter Process Communication (IPC) Differences between TCP and UDP Semaphores in Process Synchronization Operating Systems | Set 1 Data Structures and Algorithms | Set 22 Practice questions on Height balanced/AVL Tree Data Structures and Algorithms | Set 11 Computer Networks | Set 1
[ { "code": null, "e": 52, "s": 24, "text": "\n31 Aug, 2021" }, { "code": null, "e": 111, "s": 52, "text": "Following questions have been asked in GATE CS 2007 exam. " }, { "code": null, "e": 483, "s": 111, "text": "1) Consider a disk pack with 16 surfaces, 128 tracks per surface and 256 sectors per track. 512 bytes of data are stored in a bit serial manner in a sector. The capacity of the disk pack and the number of bits required to specify a particular sector in the disk are respectively: (A) 256 Mbyte, 19 bits (B) 256 Mbyte, 28 bits (C) 512 Mbyte, 20 bits (D) 64 Gbyte, 28 bits " }, { "code": null, "e": 810, "s": 483, "text": "Answer (A) Capacity of the disk = 16 surfaces X 128 tracks X 256 sectors X 512 bytes = 256 Mbytes. To calculate number of bits required to access a sector, we need to know total number of sectors. Total number of sectors = 16 surfaces X 128 tracks X 256 sectors = 2^19 So the number of bits required to access a sector is 19. " }, { "code": null, "e": 951, "s": 810, "text": "2) Group 1 contains some CPU scheduling algorithms and Group 2 contains some applications. Match entries in Group 1 to entries in Group 2. " }, { "code": null, "e": 1170, "s": 951, "text": " Group I Group II\n(P) Gang Scheduling (1) Guaranteed Scheduling\n(Q) Rate Monotonic Scheduling (2) Real-time Scheduling\n(R) Fair Share Scheduling (3) Thread Scheduling" }, { "code": null, "e": 1259, "s": 1170, "text": "(A) P – 3 Q – 2 R – 1 (B) P – 1 Q – 2 R – 3 (C) P – 2 Q – 3 R – 1 (D) P – 1 Q – 3 R – 2 " }, { "code": null, "e": 1872, "s": 1259, "text": "Answer (A) Gang scheduling for parallel systems that schedules related threads or processes to run simultaneously on different processors. Rate monotonic scheduling is used in real-time operating systems with a static-priority scheduling class. The static priorities are assigned on the basis of the cycle duration of the job: the shorter the cycle duration is, the higher is the job’s priority. Fair Share Scheduling is a scheduling strategy in which the CPU usage is equally distributed among system users or groups, as opposed to equal distribution among processes. It is also known as Guaranteed scheduling. " }, { "code": null, "e": 2044, "s": 1872, "text": "3) An operating system uses Shortest Remaining Time first (SRT) process scheduling algorithm. Consider the arrival times and execution times for the following processes: " }, { "code": null, "e": 2209, "s": 2044, "text": "Process Execution time Arrival time\nP1 20 0\nP2 25 15\nP3 10 30\nP4 15 45" }, { "code": null, "e": 2284, "s": 2209, "text": "What is the total waiting time for process P2? (A) 5 (B) 15 (C) 40 (D) 55 " }, { "code": null, "e": 2826, "s": 2284, "text": "Answer (B) At time 0, P1 is the only process, P1 runs for 15 time units. At time 15, P2 arrives, but P1 has the shortest remaining time. So P1 continues for 5 more time units. At time 20, P2 is the only process. So it runs for 10 time units At time 30, P3 is the shortest remaining time process. So it runs for 10 time units At time 40, P2 runs as it is the only process. P2 runs for 5 time units. At time 45, P3 arrives, but P2 has the shortest remaining time. So P2 continues for 10 more time units. P2 completes its execution at time 55 " }, { "code": null, "e": 2979, "s": 2826, "text": "Total waiting time for P2 = Complition time - (Arrival time + Execution time)\n = 55 - (15 + 25)\n = 15 " }, { "code": null, "e": 3094, "s": 2979, "text": "Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc. " }, { "code": null, "e": 3242, "s": 3094, "text": "Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above" }, { "code": null, "e": 3257, "s": 3242, "text": "adnanirshad158" }, { "code": null, "e": 3270, "s": 3257, "text": "GATE-CS-2007" }, { "code": null, "e": 3278, "s": 3270, "text": "GATE CS" }, { "code": null, "e": 3282, "s": 3278, "text": "MCQ" }, { "code": null, "e": 3300, "s": 3282, "text": "Operating Systems" }, { "code": null, "e": 3318, "s": 3300, "text": "Operating Systems" }, { "code": null, "e": 3416, "s": 3318, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3465, "s": 3416, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 3506, "s": 3465, "text": "Introduction of Operating System - Set 1" }, { "code": null, "e": 3540, "s": 3506, "text": "Inter Process Communication (IPC)" }, { "code": null, "e": 3572, "s": 3540, "text": "Differences between TCP and UDP" }, { "code": null, "e": 3610, "s": 3572, "text": "Semaphores in Process Synchronization" }, { "code": null, "e": 3636, "s": 3610, "text": "Operating Systems | Set 1" }, { "code": null, "e": 3676, "s": 3636, "text": "Data Structures and Algorithms | Set 22" }, { "code": null, "e": 3723, "s": 3676, "text": "Practice questions on Height balanced/AVL Tree" }, { "code": null, "e": 3763, "s": 3723, "text": "Data Structures and Algorithms | Set 11" } ]
LENGTH() Function in MySQL
15 Feb, 2021 LENGTH() : This function in MySQL is used to find the string length which is of type bytes. Features : This function is used to find the string length which is of type bytes. This function comes under String Functions. This function accepts only one parameter namely string. This function returns the length in bytes only. Syntax : LENGTH(string) Parameters : This method accepts only one parameter. string – A specified string whose length is to be counted. Returns : It returns the string length which is of type bytes. Example-1 : Using LENGTH() function and getting the output. SELECT LENGTH("GEEKSFORGEEKS"); Output : 13 Example-2 : Using LENGTH() function and finding the length of all the float values. CREATE TABLE float061 ( user_id int NOT NULL AUTO_INCREMENT, float_val float, PRIMARY KEY(user_id) ); INSERT float061(float_val) VALUES (1.9); INSERT float061(float_val) VALUES (1.1); INSERT float061(float_val) VALUES (3.9); INSERT float061(float_val) VALUES (10.2); INSERT float061(float_val) VALUES (7.9); SELECT LENGTH(float_val) FROM float061; Output : | LENGTH(float_val)| ----------------------------- | 3 | ----------------------------- | 3 | ----------------------------- | 3 | ----------------------------- | 4 | ----------------------------- | 3 | Example-3 : Using LENGTH() function and getting the length of the item given. CREATE TABLE package099 ( user_id int NOT NULL AUTO_INCREMENT, item VARCHAR(10), mrp int, PRIMARY KEY(user_id) ); INSERT package099(item, mrp) VALUES ('books', 350); SELECT LENGTH(item) FROM package099; Output : 5 Example-4 : Using LENGTH() function and getting the length of all the (MRP+sales price) values. CREATE TABLE package72 ( user_id int NOT NULL AUTO_INCREMENT, item VARCHAR(10), mrp int, sp int, PRIMARY KEY(user_id) ); INSERT package72(item, mrp, sp) VALUES ('book1', 250, 245); INSERT package72(item, mrp, sp) VALUES ('book2', 350, 345); INSERT package72(item, mrp, sp) VALUES ('book3', 400, 350); SELECT LENGTH(mrp+sp) FROM package72; Output : | LENGTH(mrp+sp) | ----------------------------- | 3 | ----------------------------- | 3 | ----------------------------- | 3 | Application : This function is used to find the string length which is of type bytes. DBMS-SQL mysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Window functions in SQL How to Update Multiple Columns in Single Update Statement in SQL? RANK() Function in SQL Server What is Temporary Table in SQL? SQL | DROP, TRUNCATE SQL indexes SQL using Python SQL | MINUS Operator Union and Union All in MS SQL Server SQL | Query Processing
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Feb, 2021" }, { "code": null, "e": 39, "s": 28, "text": "LENGTH() :" }, { "code": null, "e": 120, "s": 39, "text": "This function in MySQL is used to find the string length which is of type bytes." }, { "code": null, "e": 131, "s": 120, "text": "Features :" }, { "code": null, "e": 203, "s": 131, "text": "This function is used to find the string length which is of type bytes." }, { "code": null, "e": 247, "s": 203, "text": "This function comes under String Functions." }, { "code": null, "e": 303, "s": 247, "text": "This function accepts only one parameter namely string." }, { "code": null, "e": 351, "s": 303, "text": "This function returns the length in bytes only." }, { "code": null, "e": 360, "s": 351, "text": "Syntax :" }, { "code": null, "e": 375, "s": 360, "text": "LENGTH(string)" }, { "code": null, "e": 388, "s": 375, "text": "Parameters :" }, { "code": null, "e": 428, "s": 388, "text": "This method accepts only one parameter." }, { "code": null, "e": 487, "s": 428, "text": "string – A specified string whose length is to be counted." }, { "code": null, "e": 497, "s": 487, "text": "Returns :" }, { "code": null, "e": 550, "s": 497, "text": "It returns the string length which is of type bytes." }, { "code": null, "e": 562, "s": 550, "text": "Example-1 :" }, { "code": null, "e": 610, "s": 562, "text": "Using LENGTH() function and getting the output." }, { "code": null, "e": 642, "s": 610, "text": "SELECT LENGTH(\"GEEKSFORGEEKS\");" }, { "code": null, "e": 651, "s": 642, "text": "Output :" }, { "code": null, "e": 654, "s": 651, "text": "13" }, { "code": null, "e": 666, "s": 654, "text": "Example-2 :" }, { "code": null, "e": 738, "s": 666, "text": "Using LENGTH() function and finding the length of all the float values." }, { "code": null, "e": 1103, "s": 738, "text": "CREATE TABLE float061\n( \nuser_id int NOT NULL AUTO_INCREMENT,\nfloat_val float,\nPRIMARY KEY(user_id)\n);\nINSERT float061(float_val) \nVALUES (1.9);\n\nINSERT float061(float_val) \nVALUES (1.1);\n\nINSERT float061(float_val) \nVALUES (3.9);\n\nINSERT float061(float_val) \nVALUES (10.2);\n\nINSERT float061(float_val) \nVALUES (7.9);\n\nSELECT LENGTH(float_val) FROM float061;" }, { "code": null, "e": 1112, "s": 1103, "text": "Output :" }, { "code": null, "e": 1419, "s": 1112, "text": " | LENGTH(float_val)| \n-----------------------------\n | 3 | \n-----------------------------\n | 3 | \n-----------------------------\n | 3 |\n-----------------------------\n | 4 |\n-----------------------------\n | 3 |" }, { "code": null, "e": 1431, "s": 1419, "text": "Example-3 :" }, { "code": null, "e": 1497, "s": 1431, "text": "Using LENGTH() function and getting the length of the item given." }, { "code": null, "e": 1705, "s": 1497, "text": "CREATE TABLE package099\n( \nuser_id int NOT NULL AUTO_INCREMENT,\nitem VARCHAR(10),\nmrp int,\nPRIMARY KEY(user_id)\n);\nINSERT package099(item, mrp) \nVALUES ('books', 350);\n\nSELECT LENGTH(item) FROM package099;" }, { "code": null, "e": 1714, "s": 1705, "text": "Output :" }, { "code": null, "e": 1716, "s": 1714, "text": "5" }, { "code": null, "e": 1728, "s": 1716, "text": "Example-4 :" }, { "code": null, "e": 1812, "s": 1728, "text": "Using LENGTH() function and getting the length of all the (MRP+sales price) values." }, { "code": null, "e": 2164, "s": 1812, "text": "CREATE TABLE package72\n( \nuser_id int NOT NULL AUTO_INCREMENT, \nitem VARCHAR(10),\nmrp int,\nsp int,\nPRIMARY KEY(user_id)\n);\nINSERT package72(item, mrp, sp) \nVALUES ('book1', 250, 245);\n\nINSERT package72(item, mrp, sp) \nVALUES ('book2', 350, 345);\n\nINSERT package72(item, mrp, sp) \nVALUES ('book3', 400, 350);\n\nSELECT LENGTH(mrp+sp) FROM package72;" }, { "code": null, "e": 2173, "s": 2164, "text": "Output :" }, { "code": null, "e": 2367, "s": 2173, "text": " | LENGTH(mrp+sp) | \n-----------------------------\n | 3 | \n-----------------------------\n | 3 | \n-----------------------------\n | 3 |" }, { "code": null, "e": 2381, "s": 2367, "text": "Application :" }, { "code": null, "e": 2453, "s": 2381, "text": "This function is used to find the string length which is of type bytes." }, { "code": null, "e": 2462, "s": 2453, "text": "DBMS-SQL" }, { "code": null, "e": 2468, "s": 2462, "text": "mysql" }, { "code": null, "e": 2472, "s": 2468, "text": "SQL" }, { "code": null, "e": 2476, "s": 2472, "text": "SQL" }, { "code": null, "e": 2574, "s": 2476, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2598, "s": 2574, "text": "Window functions in SQL" }, { "code": null, "e": 2664, "s": 2598, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 2694, "s": 2664, "text": "RANK() Function in SQL Server" }, { "code": null, "e": 2726, "s": 2694, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 2747, "s": 2726, "text": "SQL | DROP, TRUNCATE" }, { "code": null, "e": 2759, "s": 2747, "text": "SQL indexes" }, { "code": null, "e": 2776, "s": 2759, "text": "SQL using Python" }, { "code": null, "e": 2797, "s": 2776, "text": "SQL | MINUS Operator" }, { "code": null, "e": 2834, "s": 2797, "text": "Union and Union All in MS SQL Server" } ]
How to remove column names from an R data frame?
There are situations when we might want to remove column names such as we want to manually replace the existing column names by new names or we simply don’t want to use them if we are very much familiar with the column characteristics. To remove the columns names we can simply set them to NULL as shown in the below examples. Consider the below data frame − Live Demo set.seed(357) x1<−LETTERS[1:20] x2<−rnorm(20) x3<−rpois(20,5) df1<−data.frame(x1,x2,x3) df1 x1 x2 x3 1 A −1.24111731 3 2 B −0.58320499 1 3 C 0.39474705 6 4 D 1.50421107 4 5 E 0.76679974 5 6 F 0.31746044 4 7 G −0.09997594 5 8 H 0.22703071 9 9 I −0.46901506 2 10 J 0.47652129 5 11 K −0.91164798 7 12 L −0.34177516 4 13 M 0.54674134 4 14 N −0.32720797 4 15 O 0.04108975 3 16 P −0.27603366 2 17 Q −0.59349654 2 18 R 0.17646182 6 19 S 0.50575975 4 20 T 1.00851578 3 Removing column names from df1 − names(df1)<−NULL df1 1 A −1.24111731 3 2 B −0.58320499 1 3 C 0.39474705 6 4 D 1.50421107 4 5 E 0.76679974 5 6 F 0.31746044 4 7 G −0.09997594 5 8 H 0.22703071 9 9 I −0.46901506 2 10 J 0.47652129 5 11 K −0.91164798 7 12 L −0.34177516 4 13 M 0.54674134 4 14 N −0.32720797 4 15 O 0.04108975 3 16 P −0.27603366 2 17 Q −0.59349654 2 18 R 0.17646182 6 19 S 0.50575975 4 20 T 1.00851578 3 Live Demo y1<−rexp(20,2.24) y2<−runif(20,2,10) y3<−rpois(20,2) df2<−data.frame(y1,y2,y3) df2 y1 y2 y3 1 0.407887709 2.213538 1 2 1.740076315 8.314833 3 3 0.192889321 2.085092 1 4 0.166686518 2.295179 3 5 0.057761320 3.117768 5 6 0.001199064 8.917747 3 7 0.212810013 5.560138 1 8 0.295809473 6.418326 0 9 0.198128409 6.662312 3 10 0.711248734 4.899675 2 11 0.228512534 5.439995 1 12 0.614415810 7.231990 2 13 0.552638453 6.999130 3 14 1.181955638 2.650087 3 15 0.094478314 4.154438 4 16 0.114416419 2.687630 3 17 0.521020383 4.552469 2 18 0.145134708 3.100630 1 19 0.189475950 3.741155 1 20 0.055434073 7.268179 3 Removing column names from df2 − names(df2)<−NULL df2 1 0.407887709 2.213538 1 2 1.740076315 8.314833 3 3 0.192889321 2.085092 1 4 0.166686518 2.295179 3 5 0.057761320 3.117768 5 6 0.001199064 8.917747 3 7 0.212810013 5.560138 1 8 0.295809473 6.418326 0 9 0.198128409 6.662312 3 10 0.711248734 4.899675 2 11 0.228512534 5.439995 1 12 0.614415810 7.231990 2 13 0.552638453 6.999130 3 14 1.181955638 2.650087 3 15 0.094478314 4.154438 4 16 0.114416419 2.687630 3 17 0.521020383 4.552469 2 18 0.145134708 3.100630 1 19 0.189475950 3.741155 1 20 0.055434073 7.268179 3
[ { "code": null, "e": 1514, "s": 1187, "text": "There are situations when we might want to remove column names such as we want to manually replace the existing column names by new names or we simply don’t want to use them if we are very much familiar with the column characteristics. To remove the columns names we can simply set them to NULL as shown in the below examples." }, { "code": null, "e": 1546, "s": 1514, "text": "Consider the below data frame −" }, { "code": null, "e": 1557, "s": 1546, "text": " Live Demo" }, { "code": null, "e": 1649, "s": 1557, "text": "set.seed(357)\nx1<−LETTERS[1:20]\nx2<−rnorm(20)\nx3<−rpois(20,5)\ndf1<−data.frame(x1,x2,x3)\ndf1" }, { "code": null, "e": 2048, "s": 1649, "text": " x1 x2 x3\n1 A −1.24111731 3\n2 B −0.58320499 1\n3 C 0.39474705 6\n4 D 1.50421107 4\n5 E 0.76679974 5\n6 F 0.31746044 4\n7 G −0.09997594 5\n8 H 0.22703071 9\n9 I −0.46901506 2\n10 J 0.47652129 5\n11 K −0.91164798 7\n12 L −0.34177516 4\n13 M 0.54674134 4\n14 N −0.32720797 4\n15 O 0.04108975 3\n16 P −0.27603366 2\n17 Q −0.59349654 2\n18 R 0.17646182 6\n19 S 0.50575975 4\n20 T 1.00851578 3" }, { "code": null, "e": 2081, "s": 2048, "text": "Removing column names from df1 −" }, { "code": null, "e": 2102, "s": 2081, "text": "names(df1)<−NULL\ndf1" }, { "code": null, "e": 2482, "s": 2102, "text": "1 A −1.24111731 3\n2 B −0.58320499 1\n3 C 0.39474705 6\n4 D 1.50421107 4\n5 E 0.76679974 5\n6 F 0.31746044 4\n7 G −0.09997594 5\n8 H 0.22703071 9\n9 I −0.46901506 2\n10 J 0.47652129 5\n11 K −0.91164798 7\n12 L −0.34177516 4\n13 M 0.54674134 4\n14 N −0.32720797 4\n15 O 0.04108975 3\n16 P −0.27603366 2\n17 Q −0.59349654 2\n18 R 0.17646182 6\n19 S 0.50575975 4\n20 T 1.00851578 3" }, { "code": null, "e": 2493, "s": 2482, "text": " Live Demo" }, { "code": null, "e": 2576, "s": 2493, "text": "y1<−rexp(20,2.24)\ny2<−runif(20,2,10)\ny3<−rpois(20,2)\ndf2<−data.frame(y1,y2,y3)\ndf2" }, { "code": null, "e": 3141, "s": 2576, "text": " y1 y2 y3\n1 0.407887709 2.213538 1\n2 1.740076315 8.314833 3\n3 0.192889321 2.085092 1\n4 0.166686518 2.295179 3\n5 0.057761320 3.117768 5\n6 0.001199064 8.917747 3\n7 0.212810013 5.560138 1\n8 0.295809473 6.418326 0\n9 0.198128409 6.662312 3\n10 0.711248734 4.899675 2\n11 0.228512534 5.439995 1\n12 0.614415810 7.231990 2\n13 0.552638453 6.999130 3\n14 1.181955638 2.650087 3\n15 0.094478314 4.154438 4\n16 0.114416419 2.687630 3\n17 0.521020383 4.552469 2\n18 0.145134708 3.100630 1\n19 0.189475950 3.741155 1\n20 0.055434073 7.268179 3" }, { "code": null, "e": 3174, "s": 3141, "text": "Removing column names from df2 −" }, { "code": null, "e": 3195, "s": 3174, "text": "names(df2)<−NULL\ndf2" }, { "code": null, "e": 3706, "s": 3195, "text": "1 0.407887709 2.213538 1\n2 1.740076315 8.314833 3\n3 0.192889321 2.085092 1\n4 0.166686518 2.295179 3\n5 0.057761320 3.117768 5\n6 0.001199064 8.917747 3\n7 0.212810013 5.560138 1\n8 0.295809473 6.418326 0\n9 0.198128409 6.662312 3\n10 0.711248734 4.899675 2\n11 0.228512534 5.439995 1\n12 0.614415810 7.231990 2\n13 0.552638453 6.999130 3\n14 1.181955638 2.650087 3\n15 0.094478314 4.154438 4\n16 0.114416419 2.687630 3\n17 0.521020383 4.552469 2\n18 0.145134708 3.100630 1\n19 0.189475950 3.741155 1\n20 0.055434073 7.268179 3" } ]
Create pandas dataframe from lists using zip
13 Nov, 2018 One of the way to create Pandas DataFrame is by using zip() function. You can use the lists to create lists of tuples and create a dictionary from it. Then, this dictionary can be used to construct a dataframe. zip() function creates the objects and that can be used to produce single item at a time. This function can create pandans DataFrames by merging two lists. Suppose there are two lists of student data, first list holds the name of student and second list holds the age of student. Then we can have, # List1Name = ['tom', 'krish', 'nick', 'juli'] # List2Age = [25, 30, 26, 22] Above two lists can be merged by using list(zip()) function. Now, create the pandas DataFrame by calling pd.DataFrame() function. # Python program to demonstrate creating# pandas Datadaframe from lists using zip. import pandas as pd # List1Name = ['tom', 'krish', 'nick', 'juli'] # List2Age = [25, 30, 26, 22] # get the list of tuples from two lists.# and merge them by using zip().list_of_tuples = list(zip(Name, Age)) # Assign data to tuples.list_of_tuples Output: # Converting lists of tuples into# pandas Dataframe.df = pd.DataFrame(list_of_tuples, columns = ['Name', 'Age']) # Print data.df Output: Picked Python pandas-dataFrame Python-pandas 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 How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Convert integer to string in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Nov, 2018" }, { "code": null, "e": 98, "s": 28, "text": "One of the way to create Pandas DataFrame is by using zip() function." }, { "code": null, "e": 239, "s": 98, "text": "You can use the lists to create lists of tuples and create a dictionary from it. Then, this dictionary can be used to construct a dataframe." }, { "code": null, "e": 395, "s": 239, "text": "zip() function creates the objects and that can be used to produce single item at a time. This function can create pandans DataFrames by merging two lists." }, { "code": null, "e": 537, "s": 395, "text": "Suppose there are two lists of student data, first list holds the name of student and second list holds the age of student. Then we can have," }, { "code": "# List1Name = ['tom', 'krish', 'nick', 'juli'] # List2Age = [25, 30, 26, 22]", "e": 615, "s": 537, "text": null }, { "code": null, "e": 745, "s": 615, "text": "Above two lists can be merged by using list(zip()) function. Now, create the pandas DataFrame by calling pd.DataFrame() function." }, { "code": "# Python program to demonstrate creating# pandas Datadaframe from lists using zip. import pandas as pd # List1Name = ['tom', 'krish', 'nick', 'juli'] # List2Age = [25, 30, 26, 22] # get the list of tuples from two lists.# and merge them by using zip().list_of_tuples = list(zip(Name, Age)) # Assign data to tuples.list_of_tuples ", "e": 1080, "s": 745, "text": null }, { "code": null, "e": 1089, "s": 1080, "text": "Output: " }, { "code": "# Converting lists of tuples into# pandas Dataframe.df = pd.DataFrame(list_of_tuples, columns = ['Name', 'Age']) # Print data.df", "e": 1220, "s": 1089, "text": null }, { "code": null, "e": 1228, "s": 1220, "text": "Output:" }, { "code": null, "e": 1235, "s": 1228, "text": "Picked" }, { "code": null, "e": 1259, "s": 1235, "text": "Python pandas-dataFrame" }, { "code": null, "e": 1273, "s": 1259, "text": "Python-pandas" }, { "code": null, "e": 1280, "s": 1273, "text": "Python" }, { "code": null, "e": 1378, "s": 1280, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1396, "s": 1378, "text": "Python Dictionary" }, { "code": null, "e": 1438, "s": 1396, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1460, "s": 1438, "text": "Enumerate() in Python" }, { "code": null, "e": 1495, "s": 1460, "text": "Read a file line by line in Python" }, { "code": null, "e": 1527, "s": 1495, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1556, "s": 1527, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1583, "s": 1556, "text": "Python Classes and Objects" }, { "code": null, "e": 1613, "s": 1583, "text": "Iterate over a list in Python" }, { "code": null, "e": 1649, "s": 1613, "text": "Convert integer to string in Python" } ]
JSON Parsing in Android using Volley Library
28 Jan, 2021 JSON is also known as (JavaScript Object Notation) is a format to exchange the data from the server. The data stored in JSON format is lightweight and easy to handle. With the help of JSON, we can access the data in the form of JsonArray, JsonObject, and JsonStringer. In this article, we will specifically take a look at the implementation of JsonObject using Volley in Android. JSON Object: Json Object can be easily identified with “{” braces opening and “}” braces closing. We can fetch data from JSON objects with their key value. From that key, we can access the value of that key. We will be building a simple application in which we will be displaying a simple CardView in which we will display a single course that is available on Geeks for Geeks. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Below is the JSON object from which we will be displaying the data in our Android App. { “courseName”:”Fork CPP”, “courseimg”:”https://media.geeksforgeeks.org/img-practice/banner/fork-cpp-thumbnail.png”, “courseMode”:”Online Batch”, “courseTracks”:”6 Tracks” } Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Add the below dependency in your build.gradle file Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section. We have used the Picasso dependency for image loading from the URL. // below line is used for volley library implementation ‘com.android.volley:volley:1.1.1’ // below line is used for image loading library implementation ‘com.squareup.picasso:picasso:2.71828’ After adding this dependency sync your project and now move towards the AndroidManifest.xml part. Step 3: Adding permissions to the internet in the AndroidManifest.xml file Navigate to the app > AndroidManifest.xml and add the below code to it. XML <!--permissions for INTERNET--><uses-permission android:name="android.permission.INTERNET"/> Step 4: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <androidx.cardview.widget.CardView android:id="@+id/idCVCourse" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:elevation="10dp" android:visibility="gone" app:cardCornerRadius="8dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <ImageView android:id="@+id/idIVCourse" android:layout_width="match_parent" android:layout_height="300dp" android:layout_margin="5dp" /> <TextView android:id="@+id/idTVCourseName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:padding="5dp" android:text="Course Name " android:textColor="@color/black" android:textSize="18sp" android:textStyle="bold" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:orientation="horizontal" android:weightSum="2"> <TextView android:id="@+id/idTVBatch" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:padding="5dp" android:text="Batch" android:textColor="@color/black" /> <TextView android:id="@+id/idTVTracks" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:padding="5dp" android:text="Tracks" android:textColor="@color/black" /> </LinearLayout> </LinearLayout> </androidx.cardview.widget.CardView> <ProgressBar android:id="@+id/idLoadingPB" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:visibility="visible" /> </RelativeLayout> Step 5: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.view.View;import android.widget.ImageView;import android.widget.ProgressBar;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity;import androidx.cardview.widget.CardView; import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.JsonObjectRequest;import com.android.volley.toolbox.Volley;import com.squareup.picasso.Picasso; import org.json.JSONException;import org.json.JSONObject; public class MainActivity extends AppCompatActivity { // creating variables for our textview, // imageview,cardview and progressbar. private TextView courseNameTV, courseTracksTV, courseBatchTV; private ImageView courseIV; private ProgressBar loadingPB; private CardView courseCV; // below line is the variable for url from // where we will be querying our data. String url = "https://jsonkeeper.com/b/63OH"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // in below line we are initializing our all views. loadingPB = findViewById(R.id.idLoadingPB); courseCV = findViewById(R.id.idCVCourse); courseNameTV = findViewById(R.id.idTVCourseName); courseTracksTV = findViewById(R.id.idTVTracks); courseBatchTV = findViewById(R.id.idTVBatch); courseIV = findViewById(R.id.idIVCourse); // creating a new variable for our request queue RequestQueue queue = Volley.newRequestQueue(MainActivity.this); // as our data is in json object format so we are using // json object request to make data request from our url. // in below line we are making a json object // request and creating a new json object request. // inside our json object request we are calling a // method to get the data, "url" from where we are // calling our data,"null" as we are not passing any data. // later on we are calling response listener method // to get the response from our API. JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { // inside the on response method. // we are hiding our progress bar. loadingPB.setVisibility(View.GONE); // in below line we are making our card // view visible after we get all the data. courseCV.setVisibility(View.VISIBLE); try { // now we get our response from API in json object format. // in below line we are extracting a string with its key // value from our json object. // similarly we are extracting all the strings from our json object. String courseName = response.getString("courseName"); String courseTracks = response.getString("courseTracks"); String courseMode = response.getString("courseMode"); String courseImageURL = response.getString("courseimg"); // after extracting all the data we are // setting that data to all our views. courseNameTV.setText(courseName); courseTracksTV.setText(courseTracks); courseBatchTV.setText(courseMode); // we are using picasso to load the image from url. Picasso.get().load(courseImageURL).into(courseIV); } catch (JSONException e) { // if we do not extract data from json object properly. // below line of code is use to handle json exception e.printStackTrace(); } } }, new Response.ErrorListener() { // this is the error listener method which // we will call if we get any error from API. @Override public void onErrorResponse(VolleyError error) { // below line is use to display a toast message along with our error. Toast.makeText(MainActivity.this, "Fail to get data..", Toast.LENGTH_SHORT).show(); } }); // at last we are adding our json // object request to our request // queue to fetch all the json data. queue.add(jsonObjectRequest); }} Now run your app and see the output of the app. android Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jan, 2021" }, { "code": null, "e": 409, "s": 28, "text": "JSON is also known as (JavaScript Object Notation) is a format to exchange the data from the server. The data stored in JSON format is lightweight and easy to handle. With the help of JSON, we can access the data in the form of JsonArray, JsonObject, and JsonStringer. In this article, we will specifically take a look at the implementation of JsonObject using Volley in Android. " }, { "code": null, "e": 619, "s": 409, "text": "JSON Object: Json Object can be easily identified with “{” braces opening and “}” braces closing. We can fetch data from JSON objects with their key value. From that key, we can access the value of that key. " }, { "code": null, "e": 955, "s": 619, "text": "We will be building a simple application in which we will be displaying a simple CardView in which we will display a single course that is available on Geeks for Geeks. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 1043, "s": 955, "text": "Below is the JSON object from which we will be displaying the data in our Android App. " }, { "code": null, "e": 1045, "s": 1043, "text": "{" }, { "code": null, "e": 1072, "s": 1045, "text": " “courseName”:”Fork CPP”," }, { "code": null, "e": 1164, "s": 1072, "text": " “courseimg”:”https://media.geeksforgeeks.org/img-practice/banner/fork-cpp-thumbnail.png”," }, { "code": null, "e": 1195, "s": 1164, "text": " “courseMode”:”Online Batch”," }, { "code": null, "e": 1223, "s": 1195, "text": " “courseTracks”:”6 Tracks”" }, { "code": null, "e": 1225, "s": 1223, "text": "}" }, { "code": null, "e": 1254, "s": 1225, "text": "Step 1: Create a New Project" }, { "code": null, "e": 1416, "s": 1254, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 1475, "s": 1416, "text": "Step 2: Add the below dependency in your build.gradle file" }, { "code": null, "e": 1772, "s": 1475, "text": "Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section. We have used the Picasso dependency for image loading from the URL. " }, { "code": null, "e": 1813, "s": 1772, "text": "// below line is used for volley library" }, { "code": null, "e": 1862, "s": 1813, "text": "implementation ‘com.android.volley:volley:1.1.1’" }, { "code": null, "e": 1910, "s": 1862, "text": "// below line is used for image loading library" }, { "code": null, "e": 1964, "s": 1910, "text": "implementation ‘com.squareup.picasso:picasso:2.71828’" }, { "code": null, "e": 2064, "s": 1964, "text": "After adding this dependency sync your project and now move towards the AndroidManifest.xml part. " }, { "code": null, "e": 2139, "s": 2064, "text": "Step 3: Adding permissions to the internet in the AndroidManifest.xml file" }, { "code": null, "e": 2212, "s": 2139, "text": "Navigate to the app > AndroidManifest.xml and add the below code to it. " }, { "code": null, "e": 2216, "s": 2212, "text": "XML" }, { "code": "<!--permissions for INTERNET--><uses-permission android:name=\"android.permission.INTERNET\"/>", "e": 2309, "s": 2216, "text": null }, { "code": null, "e": 2357, "s": 2309, "text": "Step 4: Working with the activity_main.xml file" }, { "code": null, "e": 2500, "s": 2357, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 2504, "s": 2500, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <androidx.cardview.widget.CardView android:id=\"@+id/idCVCourse\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:elevation=\"10dp\" android:visibility=\"gone\" app:cardCornerRadius=\"8dp\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\"> <ImageView android:id=\"@+id/idIVCourse\" android:layout_width=\"match_parent\" android:layout_height=\"300dp\" android:layout_margin=\"5dp\" /> <TextView android:id=\"@+id/idTVCourseName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"5dp\" android:padding=\"5dp\" android:text=\"Course Name \" android:textColor=\"@color/black\" android:textSize=\"18sp\" android:textStyle=\"bold\" /> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"5dp\" android:orientation=\"horizontal\" android:weightSum=\"2\"> <TextView android:id=\"@+id/idTVBatch\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:padding=\"5dp\" android:text=\"Batch\" android:textColor=\"@color/black\" /> <TextView android:id=\"@+id/idTVTracks\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:padding=\"5dp\" android:text=\"Tracks\" android:textColor=\"@color/black\" /> </LinearLayout> </LinearLayout> </androidx.cardview.widget.CardView> <ProgressBar android:id=\"@+id/idLoadingPB\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:visibility=\"visible\" /> </RelativeLayout>", "e": 5285, "s": 2504, "text": null }, { "code": null, "e": 5333, "s": 5285, "text": "Step 5: Working with the MainActivity.java file" }, { "code": null, "e": 5523, "s": 5333, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 5528, "s": 5523, "text": "Java" }, { "code": "import android.os.Bundle;import android.view.View;import android.widget.ImageView;import android.widget.ProgressBar;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity;import androidx.cardview.widget.CardView; import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.JsonObjectRequest;import com.android.volley.toolbox.Volley;import com.squareup.picasso.Picasso; import org.json.JSONException;import org.json.JSONObject; public class MainActivity extends AppCompatActivity { // creating variables for our textview, // imageview,cardview and progressbar. private TextView courseNameTV, courseTracksTV, courseBatchTV; private ImageView courseIV; private ProgressBar loadingPB; private CardView courseCV; // below line is the variable for url from // where we will be querying our data. String url = \"https://jsonkeeper.com/b/63OH\"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // in below line we are initializing our all views. loadingPB = findViewById(R.id.idLoadingPB); courseCV = findViewById(R.id.idCVCourse); courseNameTV = findViewById(R.id.idTVCourseName); courseTracksTV = findViewById(R.id.idTVTracks); courseBatchTV = findViewById(R.id.idTVBatch); courseIV = findViewById(R.id.idIVCourse); // creating a new variable for our request queue RequestQueue queue = Volley.newRequestQueue(MainActivity.this); // as our data is in json object format so we are using // json object request to make data request from our url. // in below line we are making a json object // request and creating a new json object request. // inside our json object request we are calling a // method to get the data, \"url\" from where we are // calling our data,\"null\" as we are not passing any data. // later on we are calling response listener method // to get the response from our API. JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { // inside the on response method. // we are hiding our progress bar. loadingPB.setVisibility(View.GONE); // in below line we are making our card // view visible after we get all the data. courseCV.setVisibility(View.VISIBLE); try { // now we get our response from API in json object format. // in below line we are extracting a string with its key // value from our json object. // similarly we are extracting all the strings from our json object. String courseName = response.getString(\"courseName\"); String courseTracks = response.getString(\"courseTracks\"); String courseMode = response.getString(\"courseMode\"); String courseImageURL = response.getString(\"courseimg\"); // after extracting all the data we are // setting that data to all our views. courseNameTV.setText(courseName); courseTracksTV.setText(courseTracks); courseBatchTV.setText(courseMode); // we are using picasso to load the image from url. Picasso.get().load(courseImageURL).into(courseIV); } catch (JSONException e) { // if we do not extract data from json object properly. // below line of code is use to handle json exception e.printStackTrace(); } } }, new Response.ErrorListener() { // this is the error listener method which // we will call if we get any error from API. @Override public void onErrorResponse(VolleyError error) { // below line is use to display a toast message along with our error. Toast.makeText(MainActivity.this, \"Fail to get data..\", Toast.LENGTH_SHORT).show(); } }); // at last we are adding our json // object request to our request // queue to fetch all the json data. queue.add(jsonObjectRequest); }}", "e": 10296, "s": 5528, "text": null }, { "code": null, "e": 10345, "s": 10296, "text": "Now run your app and see the output of the app. " }, { "code": null, "e": 10353, "s": 10345, "text": "android" }, { "code": null, "e": 10377, "s": 10353, "text": "Technical Scripter 2020" }, { "code": null, "e": 10385, "s": 10377, "text": "Android" }, { "code": null, "e": 10390, "s": 10385, "text": "Java" }, { "code": null, "e": 10409, "s": 10390, "text": "Technical Scripter" }, { "code": null, "e": 10414, "s": 10409, "text": "Java" }, { "code": null, "e": 10422, "s": 10414, "text": "Android" } ]
Swap all occurrences of two characters to get lexicographically smallest string
06 Jul, 2022 Given string str of lower case English alphabets. One can choose any two characters in the string and replace all the occurrences of the first character with the second character and replace all the occurrences of the second character with the first character. Find the lexicographically smallest string that can be obtained by doing this operation at most once. Examples: Input: str = “ccad” Output: aacd Swap all the occurrences of ‘c’ with ‘a’ and all the occurrences of ‘a’ with ‘c’ to get “aacd” which is the lexicographically smallest string that we can get. Input: str = “abba” Output: abba The only possible operation will convert the given string to “baab” which is not lexicographically smallest. Approach: First, we store the first appearance of every character in a string in a hash array chk[]. In order to find the lexicographically smaller string, the leftmost character must be replaced with some character which is smaller than it. This will only happen if the smaller character appears after it in the array. So, start traversing the string from the left and for every character, find the smallest character (even smaller than the current character) that appears after swapping all of their occurrences to get the required string. If no such character pair is found in the previous string then print the given string as it is the smallest string possible. Below is the implementation of the above approach: C++ Java Python C# Javascript // C++ implementation of the approach#include <iostream>using namespace std; #define MAX 26 // Function to return the lexicographically// smallest string after swapping all the// occurrences of any two charactersstring smallestStr(string str, int n){ int i, j; // To store the first index of // every character of str int chk[MAX]; for (i = 0; i < MAX; i++) chk[i] = -1; // Store the first occurring // index every character for (i = 0; i < n; i++) { // If current character is appearing // for the first time in str if (chk[str[i] - 'a'] == -1) chk[str[i] - 'a'] = i; } // Starting from the leftmost character for (i = 0; i < n; i++) { bool flag = false; // For every character smaller than str[i] for (j = 0; j < str[i] - 'a'; j++) { // If there is a character in str which is // smaller than str[i] and appears after it if (chk[j] > chk[str[i] - 'a']) { flag = true; break; } } // If the required character pair is found if (flag) break; } // If swapping is possible if (i < n-1) { // Characters to be swapped char ch1 = str[i]; char ch2 = char(j + 'a'); // For every character for (i = 0; i < n; i++) { // Replace every ch1 with ch2 // and every ch2 with ch1 if (str[i] == ch1) str[i] = ch2; else if (str[i] == ch2) str[i] = ch1; } } return str;} // Driver codeint main(){ string str = "ccad"; int n = str.length(); cout << smallestStr(str, n); return 0;} // Java implementation of the approachimport java.util.*; class GFG{static int MAX = 26; // Function to return the lexicographically// smallest string after swapping all the// occurrences of any two charactersstatic String smallestStr(char []str, int n){ int i, j = 0; // To store the first index of // every character of str int []chk = new int[MAX]; for (i = 0; i < MAX; i++) chk[i] = -1; // Store the first occurring // index every character for (i = 0; i < n; i++) { // If current character is appearing // for the first time in str if (chk[str[i] - 'a'] == -1) chk[str[i] - 'a'] = i; } // Starting from the leftmost character for (i = 0; i < n; i++) { boolean flag = false; // For every character smaller than str[i] for (j = 0; j < str[i] - 'a'; j++) { // If there is a character in str which is // smaller than str[i] and appears after it if (chk[j] > chk[str[i] - 'a']) { flag = true; break; } } // If the required character pair is found if (flag) break; } // If swapping is possible if (i < n-1) { // Characters to be swapped char ch1 = str[i]; char ch2 = (char) (j + 'a'); // For every character for (i = 0; i < n; i++) { // Replace every ch1 with ch2 // and every ch2 with ch1 if (str[i] == ch1) str[i] = ch2; else if (str[i] == ch2) str[i] = ch1; } } return String.valueOf(str);} // Driver codepublic static void main(String[] args){ String str = "ccad"; int n = str.length(); System.out.println(smallestStr( str.toCharArray(), n));}} # python3 implementation of the approachMAX=256 # Function to return the lexicographically# smallest after swapping all the# occurrences of any two charactersdef smallestStr(str, n): i, j=0,0 # To store the first index of # every character of str chk=[0 for i in range(MAX)] for i in range(MAX): chk[i] = -1 # Store the first occurring # index every character for i in range(n): # If current character is appearing # for the first time in str if (chk[ord(str[i])] == -1): chk[ord(str[i])] = i # Starting from the leftmost character for i in range(n): flag = False # For every character smaller than ord(str[i]) for j in range(ord(str[i])): # If there is a character in str which is # smaller than ord(str[i]) and appears after it if (chk[j] > chk[ord(str[i])]): flag = True break # If the required character pair is found if (flag): break # If swapping is possible if (i < n-1): # Characters to be swapped ch1 = (str[i]) ch2 = chr(j) # For every character for i in range(n): # Replace every ch1 with ch2 # and every ch2 with ch1 if (str[i] == ch1): str[i] = ch2 elif (str[i] == ch2): str[i] = ch1 return "".join(str) # Driver code st = "ccad"str=[i for i in st]n = len(str) print(smallestStr(str, n)) // C# implementation of the approachusing System; class GFG{static int MAX = 26; // Function to return the lexicographically// smallest string after swapping all the// occurrences of any two charactersstatic String smallestStr(char []str, int n){ int i, j = 0; // To store the first index of // every character of str int []chk = new int[MAX]; for (i = 0; i < MAX; i++) chk[i] = -1; // Store the first occurring // index every character for (i = 0; i < n; i++) { // If current character is appearing // for the first time in str if (chk[str[i] - 'a'] == -1) chk[str[i] - 'a'] = i; } // Starting from the leftmost character for (i = 0; i < n; i++) { Boolean flag = false; // For every character smaller than str[i] for (j = 0; j < str[i] - 'a'; j++) { // If there is a character in str which is // smaller than str[i] and appears after it if (chk[j] > chk[str[i] - 'a']) { flag = true; break; } } // If the required character pair is found if (flag) break; } // If swapping is possible if (i < n-1) { // Characters to be swapped char ch1 = str[i]; char ch2 = (char) (j + 'a'); // For every character for (i = 0; i < n; i++) { // Replace every ch1 with ch2 // and every ch2 with ch1 if (str[i] == ch1) str[i] = ch2; else if (str[i] == ch2) str[i] = ch1; } } return String.Join("", str);} // Driver codepublic static void Main(String[] args){ String str = "ccad"; int n = str.Length; Console.WriteLine(smallestStr( str.ToCharArray(), n));}} <script>// JavaScript Implementation of the above approachvar MAX = 26; // utility function to replace a char at particular string positionString.prototype.replaceAt = function(index, replacement) { return this.substring(0, index) + replacement + this.substring(index + replacement.length);} function smallestStr(str, n){ let i, j; // To store the first index of // every character of str const chk=[]; for (i = 0; i < MAX; i++) chk[i] = -1; // Store the first occurring // index every character for (i = 0; i < n; i++) { // If current character is appearing // for the first time in str if (chk[str[i].charCodeAt(0) - 'a'.charCodeAt(0)] == -1) chk[str[i].charCodeAt(0) - 'a'.charCodeAt(0)] = i; } // Starting from the leftmost character for (i = 0; i < n; i++) { let flag = false; // For every character smaller than str[i] for (j = 0; j < str[i].charCodeAt(0) - 'a'.charCodeAt(0); j++) { // If there is a character in str which is // smaller than str[i] and appears after it if (chk[j] > chk[str[i].charCodeAt(0) - 'a'.charCodeAt(0)]) { flag = true; break; } } // If the required character pair is found if (flag) break; } // If swapping is possible if (i < n-1) { // Characters to be swapped let ch1 = str[i]; let ch2 = String.fromCharCode(j + 'a'.charCodeAt(0)); // For every character for (i = 0; i < n; i++) { // Replace every ch1 with ch2 // and every ch2 with ch1 if (str[i] == ch1) str=str.replaceAt(i,ch2); else if (str[i] == ch2) str=str.replaceAt(i,ch1); } } return str;} // Driver Codelet str = "ccad"; let n = str.length; document.write(smallestStr(str, n)); // This code is contributed by Ishan Khandelwal </script> aacd mohit kumar 29 princi singh nidhi_biet ishankhandelwals mananpandey1 frequency-counting lexicographic-ordering Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Jul, 2022" }, { "code": null, "e": 427, "s": 54, "text": "Given string str of lower case English alphabets. One can choose any two characters in the string and replace all the occurrences of the first character with the second character and replace all the occurrences of the second character with the first character. Find the lexicographically smallest string that can be obtained by doing this operation at most once. Examples:" }, { "code": null, "e": 620, "s": 427, "text": "Input: str = “ccad” Output: aacd Swap all the occurrences of ‘c’ with ‘a’ and all the occurrences of ‘a’ with ‘c’ to get “aacd” which is the lexicographically smallest string that we can get. " }, { "code": null, "e": 762, "s": 620, "text": "Input: str = “abba” Output: abba The only possible operation will convert the given string to “baab” which is not lexicographically smallest." }, { "code": null, "e": 772, "s": 762, "text": "Approach:" }, { "code": null, "e": 863, "s": 772, "text": "First, we store the first appearance of every character in a string in a hash array chk[]." }, { "code": null, "e": 1082, "s": 863, "text": "In order to find the lexicographically smaller string, the leftmost character must be replaced with some character which is smaller than it. This will only happen if the smaller character appears after it in the array." }, { "code": null, "e": 1304, "s": 1082, "text": "So, start traversing the string from the left and for every character, find the smallest character (even smaller than the current character) that appears after swapping all of their occurrences to get the required string." }, { "code": null, "e": 1429, "s": 1304, "text": "If no such character pair is found in the previous string then print the given string as it is the smallest string possible." }, { "code": null, "e": 1480, "s": 1429, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1484, "s": 1480, "text": "C++" }, { "code": null, "e": 1489, "s": 1484, "text": "Java" }, { "code": null, "e": 1496, "s": 1489, "text": "Python" }, { "code": null, "e": 1499, "s": 1496, "text": "C#" }, { "code": null, "e": 1510, "s": 1499, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <iostream>using namespace std; #define MAX 26 // Function to return the lexicographically// smallest string after swapping all the// occurrences of any two charactersstring smallestStr(string str, int n){ int i, j; // To store the first index of // every character of str int chk[MAX]; for (i = 0; i < MAX; i++) chk[i] = -1; // Store the first occurring // index every character for (i = 0; i < n; i++) { // If current character is appearing // for the first time in str if (chk[str[i] - 'a'] == -1) chk[str[i] - 'a'] = i; } // Starting from the leftmost character for (i = 0; i < n; i++) { bool flag = false; // For every character smaller than str[i] for (j = 0; j < str[i] - 'a'; j++) { // If there is a character in str which is // smaller than str[i] and appears after it if (chk[j] > chk[str[i] - 'a']) { flag = true; break; } } // If the required character pair is found if (flag) break; } // If swapping is possible if (i < n-1) { // Characters to be swapped char ch1 = str[i]; char ch2 = char(j + 'a'); // For every character for (i = 0; i < n; i++) { // Replace every ch1 with ch2 // and every ch2 with ch1 if (str[i] == ch1) str[i] = ch2; else if (str[i] == ch2) str[i] = ch1; } } return str;} // Driver codeint main(){ string str = \"ccad\"; int n = str.length(); cout << smallestStr(str, n); return 0;}", "e": 3263, "s": 1510, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{static int MAX = 26; // Function to return the lexicographically// smallest string after swapping all the// occurrences of any two charactersstatic String smallestStr(char []str, int n){ int i, j = 0; // To store the first index of // every character of str int []chk = new int[MAX]; for (i = 0; i < MAX; i++) chk[i] = -1; // Store the first occurring // index every character for (i = 0; i < n; i++) { // If current character is appearing // for the first time in str if (chk[str[i] - 'a'] == -1) chk[str[i] - 'a'] = i; } // Starting from the leftmost character for (i = 0; i < n; i++) { boolean flag = false; // For every character smaller than str[i] for (j = 0; j < str[i] - 'a'; j++) { // If there is a character in str which is // smaller than str[i] and appears after it if (chk[j] > chk[str[i] - 'a']) { flag = true; break; } } // If the required character pair is found if (flag) break; } // If swapping is possible if (i < n-1) { // Characters to be swapped char ch1 = str[i]; char ch2 = (char) (j + 'a'); // For every character for (i = 0; i < n; i++) { // Replace every ch1 with ch2 // and every ch2 with ch1 if (str[i] == ch1) str[i] = ch2; else if (str[i] == ch2) str[i] = ch1; } } return String.valueOf(str);} // Driver codepublic static void main(String[] args){ String str = \"ccad\"; int n = str.length(); System.out.println(smallestStr( str.toCharArray(), n));}}", "e": 5158, "s": 3263, "text": null }, { "code": "# python3 implementation of the approachMAX=256 # Function to return the lexicographically# smallest after swapping all the# occurrences of any two charactersdef smallestStr(str, n): i, j=0,0 # To store the first index of # every character of str chk=[0 for i in range(MAX)] for i in range(MAX): chk[i] = -1 # Store the first occurring # index every character for i in range(n): # If current character is appearing # for the first time in str if (chk[ord(str[i])] == -1): chk[ord(str[i])] = i # Starting from the leftmost character for i in range(n): flag = False # For every character smaller than ord(str[i]) for j in range(ord(str[i])): # If there is a character in str which is # smaller than ord(str[i]) and appears after it if (chk[j] > chk[ord(str[i])]): flag = True break # If the required character pair is found if (flag): break # If swapping is possible if (i < n-1): # Characters to be swapped ch1 = (str[i]) ch2 = chr(j) # For every character for i in range(n): # Replace every ch1 with ch2 # and every ch2 with ch1 if (str[i] == ch1): str[i] = ch2 elif (str[i] == ch2): str[i] = ch1 return \"\".join(str) # Driver code st = \"ccad\"str=[i for i in st]n = len(str) print(smallestStr(str, n))", "e": 6706, "s": 5158, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{static int MAX = 26; // Function to return the lexicographically// smallest string after swapping all the// occurrences of any two charactersstatic String smallestStr(char []str, int n){ int i, j = 0; // To store the first index of // every character of str int []chk = new int[MAX]; for (i = 0; i < MAX; i++) chk[i] = -1; // Store the first occurring // index every character for (i = 0; i < n; i++) { // If current character is appearing // for the first time in str if (chk[str[i] - 'a'] == -1) chk[str[i] - 'a'] = i; } // Starting from the leftmost character for (i = 0; i < n; i++) { Boolean flag = false; // For every character smaller than str[i] for (j = 0; j < str[i] - 'a'; j++) { // If there is a character in str which is // smaller than str[i] and appears after it if (chk[j] > chk[str[i] - 'a']) { flag = true; break; } } // If the required character pair is found if (flag) break; } // If swapping is possible if (i < n-1) { // Characters to be swapped char ch1 = str[i]; char ch2 = (char) (j + 'a'); // For every character for (i = 0; i < n; i++) { // Replace every ch1 with ch2 // and every ch2 with ch1 if (str[i] == ch1) str[i] = ch2; else if (str[i] == ch2) str[i] = ch1; } } return String.Join(\"\", str);} // Driver codepublic static void Main(String[] args){ String str = \"ccad\"; int n = str.Length; Console.WriteLine(smallestStr( str.ToCharArray(), n));}}", "e": 8594, "s": 6706, "text": null }, { "code": "<script>// JavaScript Implementation of the above approachvar MAX = 26; // utility function to replace a char at particular string positionString.prototype.replaceAt = function(index, replacement) { return this.substring(0, index) + replacement + this.substring(index + replacement.length);} function smallestStr(str, n){ let i, j; // To store the first index of // every character of str const chk=[]; for (i = 0; i < MAX; i++) chk[i] = -1; // Store the first occurring // index every character for (i = 0; i < n; i++) { // If current character is appearing // for the first time in str if (chk[str[i].charCodeAt(0) - 'a'.charCodeAt(0)] == -1) chk[str[i].charCodeAt(0) - 'a'.charCodeAt(0)] = i; } // Starting from the leftmost character for (i = 0; i < n; i++) { let flag = false; // For every character smaller than str[i] for (j = 0; j < str[i].charCodeAt(0) - 'a'.charCodeAt(0); j++) { // If there is a character in str which is // smaller than str[i] and appears after it if (chk[j] > chk[str[i].charCodeAt(0) - 'a'.charCodeAt(0)]) { flag = true; break; } } // If the required character pair is found if (flag) break; } // If swapping is possible if (i < n-1) { // Characters to be swapped let ch1 = str[i]; let ch2 = String.fromCharCode(j + 'a'.charCodeAt(0)); // For every character for (i = 0; i < n; i++) { // Replace every ch1 with ch2 // and every ch2 with ch1 if (str[i] == ch1) str=str.replaceAt(i,ch2); else if (str[i] == ch2) str=str.replaceAt(i,ch1); } } return str;} // Driver Codelet str = \"ccad\"; let n = str.length; document.write(smallestStr(str, n)); // This code is contributed by Ishan Khandelwal </script>", "e": 10629, "s": 8594, "text": null }, { "code": null, "e": 10634, "s": 10629, "text": "aacd" }, { "code": null, "e": 10649, "s": 10634, "text": "mohit kumar 29" }, { "code": null, "e": 10662, "s": 10649, "text": "princi singh" }, { "code": null, "e": 10673, "s": 10662, "text": "nidhi_biet" }, { "code": null, "e": 10690, "s": 10673, "text": "ishankhandelwals" }, { "code": null, "e": 10703, "s": 10690, "text": "mananpandey1" }, { "code": null, "e": 10722, "s": 10703, "text": "frequency-counting" }, { "code": null, "e": 10745, "s": 10722, "text": "lexicographic-ordering" }, { "code": null, "e": 10753, "s": 10745, "text": "Strings" }, { "code": null, "e": 10761, "s": 10753, "text": "Strings" } ]
Yii - RESTful APIs
Yii provides the following useful features for implementing RESTful APIs − Quick prototyping Customizable object serialization Response format (supporting JSON and XML by default) Formatting of collection data and validation errors Efficient routing Support for HATEOAS Built-in support for the OPTIONS and HEAD verbs Data caching and HTTP caching Authentication and authorization Rate limiting To show RESTful APIs in action, we need data. Step 1 − Create a new database. Database can be prepared in the following two ways. In the terminal run mysql -u root –p. In the terminal run mysql -u root –p. Create a new database via CREATE DATABASE helloworld CHARACTER SET utf8 COLLATE utf8_general_ci; Create a new database via CREATE DATABASE helloworld CHARACTER SET utf8 COLLATE utf8_general_ci; Step 2 − Configure the database connection in the config/db.php file. The following configuration is for the system used currently. <?php return [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host = localhost;dbname = helloworld', 'username' => 'vladimir', 'password' => '12345', 'charset' => 'utf8', ]; ?> Step 3 − Inside the root folder run ./yii migrate/create test_table. This command will create a database migration for managing our DB. The migration file should appear in the migrations folder of the project root. Step 4 − Modify the migration file (m160106_163154_test_table.php in this case) this way. <?php use yii\db\Schema; use yii\db\Migration; class m160106_163154_test_table extends Migration { public function safeUp() { $this->createTable("user", [ "id" => Schema::TYPE_PK, "name" => Schema::TYPE_STRING, "email" => Schema::TYPE_STRING, ]); $this->batchInsert("user", ["name", "email"], [ ["User1", "user1@gmail.com"], ["User2", "user2@gmail.com"], ["User3", "user3@gmail.com"], ["User4", "user4@gmail.com"], ["User5", "user5@gmail.com"], ["User6", "user6@gmail.com"], ["User7", "user7@gmail.com"], ["User8", "user8@gmail.com"], ["User9", "user9@gmail.com"], ["User10", "user10@gmail.com"], ["User11", "user11@gmail.com"], ]); } public function safeDown() { $this->dropTable('user'); } } ?> The above migration creates a user table with these fields: id, name, and email. It also adds a few demo users. Step 5 − Inside the project root run ./yii migrate to apply the migration to the database. Step 6 − Now, we need to create a model for our user table. For the sake of simplicity, we are going to use the Gii code generation tool. Open up this url: http://localhost:8080/index.php?r=gii. Then, click the “Start” button under the “Model generator” header. Fill in the Table Name (“user”) and the Model Class (“MyUser”), click the “Preview” button and finally, click the “Generate” button. The MyUser model should appear in the models directory. Postman is a handy tool when developing a RESTful service. It provides a useful interface for constructing requests. You can find this tool at https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en . To install it, press the “Add to Chrome” button. Print Add Notes Bookmark this page
[ { "code": null, "e": 2908, "s": 2833, "text": "Yii provides the following useful features for implementing RESTful APIs −" }, { "code": null, "e": 2926, "s": 2908, "text": "Quick prototyping" }, { "code": null, "e": 2960, "s": 2926, "text": "Customizable object serialization" }, { "code": null, "e": 3013, "s": 2960, "text": "Response format (supporting JSON and XML by default)" }, { "code": null, "e": 3065, "s": 3013, "text": "Formatting of collection data and validation errors" }, { "code": null, "e": 3083, "s": 3065, "text": "Efficient routing" }, { "code": null, "e": 3103, "s": 3083, "text": "Support for HATEOAS" }, { "code": null, "e": 3151, "s": 3103, "text": "Built-in support for the OPTIONS and HEAD verbs" }, { "code": null, "e": 3181, "s": 3151, "text": "Data caching and HTTP caching" }, { "code": null, "e": 3214, "s": 3181, "text": "Authentication and authorization" }, { "code": null, "e": 3228, "s": 3214, "text": "Rate limiting" }, { "code": null, "e": 3274, "s": 3228, "text": "To show RESTful APIs in action, we need data." }, { "code": null, "e": 3358, "s": 3274, "text": "Step 1 − Create a new database. Database can be prepared in the following two ways." }, { "code": null, "e": 3396, "s": 3358, "text": "In the terminal run mysql -u root –p." }, { "code": null, "e": 3434, "s": 3396, "text": "In the terminal run mysql -u root –p." }, { "code": null, "e": 3531, "s": 3434, "text": "Create a new database via CREATE DATABASE helloworld CHARACTER SET utf8 COLLATE utf8_general_ci;" }, { "code": null, "e": 3628, "s": 3531, "text": "Create a new database via CREATE DATABASE helloworld CHARACTER SET utf8 COLLATE utf8_general_ci;" }, { "code": null, "e": 3760, "s": 3628, "text": "Step 2 − Configure the database connection in the config/db.php file. The following configuration is for the system used currently." }, { "code": null, "e": 3974, "s": 3760, "text": "<?php\n return [\n 'class' => 'yii\\db\\Connection',\n 'dsn' => 'mysql:host = localhost;dbname = helloworld',\n 'username' => 'vladimir',\n 'password' => '12345',\n 'charset' => 'utf8',\n ];\n?>" }, { "code": null, "e": 4189, "s": 3974, "text": "Step 3 − Inside the root folder run ./yii migrate/create test_table. This command will create a database migration for managing our DB. The migration file should appear in the migrations folder of the project root." }, { "code": null, "e": 4279, "s": 4189, "text": "Step 4 − Modify the migration file (m160106_163154_test_table.php in this case) this way." }, { "code": null, "e": 5230, "s": 4279, "text": "<?php\n use yii\\db\\Schema;\n \n use yii\\db\\Migration;\n class m160106_163154_test_table extends Migration {\n public function safeUp() {\n $this->createTable(\"user\", [\n \"id\" => Schema::TYPE_PK,\n \"name\" => Schema::TYPE_STRING,\n \"email\" => Schema::TYPE_STRING,\n ]);\n $this->batchInsert(\"user\", [\"name\", \"email\"], [\n [\"User1\", \"user1@gmail.com\"],\n [\"User2\", \"user2@gmail.com\"],\n [\"User3\", \"user3@gmail.com\"],\n [\"User4\", \"user4@gmail.com\"],\n [\"User5\", \"user5@gmail.com\"], \n [\"User6\", \"user6@gmail.com\"],\n [\"User7\", \"user7@gmail.com\"],\n [\"User8\", \"user8@gmail.com\"],\n [\"User9\", \"user9@gmail.com\"],\n [\"User10\", \"user10@gmail.com\"],\n [\"User11\", \"user11@gmail.com\"],\n ]);\n }\n public function safeDown() {\n $this->dropTable('user');\n }\n }\n?>" }, { "code": null, "e": 5342, "s": 5230, "text": "The above migration creates a user table with these fields: id, name, and email. It also adds a few demo users." }, { "code": null, "e": 5433, "s": 5342, "text": "Step 5 − Inside the project root run ./yii migrate to apply the migration to the database." }, { "code": null, "e": 5828, "s": 5433, "text": "Step 6 − Now, we need to create a model for our user table. For the sake of simplicity, we are going to use the Gii code generation tool. Open up this url: http://localhost:8080/index.php?r=gii. Then, click the “Start” button under the “Model generator” header. Fill in the Table Name (“user”) and the Model Class (“MyUser”), click the “Preview” button and finally, click the “Generate” button." }, { "code": null, "e": 5884, "s": 5828, "text": "The MyUser model should appear in the models directory." }, { "code": null, "e": 6001, "s": 5884, "text": "Postman is a handy tool when developing a RESTful service. It provides a useful interface for constructing requests." }, { "code": null, "e": 6118, "s": 6001, "text": "You can find this tool at https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en ." }, { "code": null, "e": 6167, "s": 6118, "text": "To install it, press the “Add to Chrome” button." }, { "code": null, "e": 6174, "s": 6167, "text": " Print" }, { "code": null, "e": 6185, "s": 6174, "text": " Add Notes" } ]
Drawing a line between two mouse clicks using tkinter
Consider a case for creating a GUI application such that when we click on the window with a mouse button, it stores the coordinates and creates a line between two given points. Tkinter provides events that allow the user to bind the keys or buttons with the functions. To draw a line between two points, we can follow these general steps, Create a canvas widget and pack it to display in the window. Create a canvas widget and pack it to display in the window. Define a function draw_line() that works as the event when the user does the click event. Define a function draw_line() that works as the event when the user does the click event. Create a global variable that counts the number of clicks in the canvas. Create a global variable that counts the number of clicks in the canvas. If the count becomes two, then draw a line between the first and second coordinates. If the count becomes two, then draw a line between the first and second coordinates. Bind the Mouse button with the callback function to get full control over the function. Bind the Mouse button with the callback function to get full control over the function. # Import the required libraries from tkinter import * from tkinter import ttk # Create an instance of tkinter frame or window win=Tk() # Set the size of the window win.geometry("700x350") # Define a function to draw the line between two points def draw_line(event): global click_num global x1,y1 if click_num==0: x1=event.x y1=event.y click_num=1 else: x2=event.x y2=event.y # Draw the line in the given co-ordinates canvas.create_line(x1,y1,x2,y2, fill="green", width=10) # Create a canvas widget canvas=Canvas(win, width=700, height=350, background="white") canvas.grid(row=0, column=0) canvas.bind('<Button-1>', draw_line) click_num=0 win.mainloop() Run the above code to display a window. If we click on the canvas widget twice anywhere, it will draw a line in the canvas.
[ { "code": null, "e": 1331, "s": 1062, "text": "Consider a case for creating a GUI application such that when we click on the window with a mouse button, it stores the coordinates and creates a line between two given points. Tkinter provides events that allow the user to bind the keys or buttons with the functions." }, { "code": null, "e": 1401, "s": 1331, "text": "To draw a line between two points, we can follow these general steps," }, { "code": null, "e": 1462, "s": 1401, "text": "Create a canvas widget and pack it to display in the window." }, { "code": null, "e": 1523, "s": 1462, "text": "Create a canvas widget and pack it to display in the window." }, { "code": null, "e": 1613, "s": 1523, "text": "Define a function draw_line() that works as the event when the user does the click event." }, { "code": null, "e": 1703, "s": 1613, "text": "Define a function draw_line() that works as the event when the user does the click event." }, { "code": null, "e": 1776, "s": 1703, "text": "Create a global variable that counts the number of clicks in the canvas." }, { "code": null, "e": 1849, "s": 1776, "text": "Create a global variable that counts the number of clicks in the canvas." }, { "code": null, "e": 1934, "s": 1849, "text": "If the count becomes two, then draw a line between the first and second coordinates." }, { "code": null, "e": 2019, "s": 1934, "text": "If the count becomes two, then draw a line between the first and second coordinates." }, { "code": null, "e": 2107, "s": 2019, "text": "Bind the Mouse button with the callback function to get full control over the function." }, { "code": null, "e": 2195, "s": 2107, "text": "Bind the Mouse button with the callback function to get full control over the function." }, { "code": null, "e": 2901, "s": 2195, "text": "# Import the required libraries\nfrom tkinter import *\nfrom tkinter import ttk\n\n# Create an instance of tkinter frame or window\nwin=Tk()\n\n# Set the size of the window\nwin.geometry(\"700x350\")\n\n# Define a function to draw the line between two points\ndef draw_line(event):\n global click_num\n global x1,y1\n if click_num==0:\n x1=event.x\n y1=event.y\n click_num=1\n else:\n x2=event.x\n y2=event.y\n # Draw the line in the given co-ordinates\n canvas.create_line(x1,y1,x2,y2, fill=\"green\", width=10)\n\n# Create a canvas widget\ncanvas=Canvas(win, width=700, height=350, background=\"white\")\ncanvas.grid(row=0, column=0)\ncanvas.bind('<Button-1>', draw_line)\nclick_num=0\n\nwin.mainloop()" }, { "code": null, "e": 3025, "s": 2901, "text": "Run the above code to display a window. If we click on the canvas widget twice anywhere, it will draw a line in the canvas." } ]
Deadlock in Java Multithreading
Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. Deadlock occurs when multiple threads need the same locks but obtain them in a different order. A Java multithreaded program may suffer from the deadlock condition because the synchronized keyword causes the executing thread to block while waiting for the lock, or monitor, associated with the specified object. Here is an example. Live Demo public class TestThread { public static Object Lock1 = new Object(); public static Object Lock2 = new Object(); public static void main(String args[]) { ThreadDemo1 T1 = new ThreadDemo1(); ThreadDemo2 T2 = new ThreadDemo2(); T1.start(); T2.start(); } private static class ThreadDemo1 extends Thread { public void run() { synchronized (Lock1) { System.out.println("Thread 1: Holding lock 1..."); try { Thread.sleep(10); } catch (InterruptedException e) {} System.out.println("Thread 1: Waiting for lock 2..."); synchronized (Lock2) { System.out.println("Thread 1: Holding lock 1 &amp; 2..."); } } } } private static class ThreadDemo2 extends Thread { public void run() { synchronized (Lock2) { System.out.println("Thread 2: Holding lock 2..."); try { Thread.sleep(10); } catch (InterruptedException e) {} System.out.println("Thread 2: Waiting for lock 1..."); synchronized (Lock1) { System.out.println("Thread 2: Holding lock 1 &amp; 2..."); } } } } } When you compile and execute the above program, you find a deadlock situation and following is the output produced by the program − Thread 1: Holding lock 1... Thread 2: Holding lock 2... Thread 1: Waiting for lock 2... Thread 2: Waiting for lock 1... The above program will hang forever because neither of the threads in position to proceed and waiting for each other to release the lock, so you can come out of the program by pressing CTRL+C. Let's change the order of the lock and run of the same program to see if both the threads still wait for each other − Live Demo public class TestThread { public static Object Lock1 = new Object(); public static Object Lock2 = new Object(); public static void main(String args[]) { ThreadDemo1 T1 = new ThreadDemo1(); ThreadDemo2 T2 = new ThreadDemo2(); T1.start(); T2.start(); } private static class ThreadDemo1 extends Thread { public void run() { synchronized (Lock1) { System.out.println("Thread 1: Holding lock 1..."); try { Thread.sleep(10); } catch (InterruptedException e) {} System.out.println("Thread 1: Waiting for lock 2..."); synchronized (Lock2) { System.out.println("Thread 1: Holding lock 1 &amp; 2..."); } } } } private static class ThreadDemo2 extends Thread { public void run() { synchronized (Lock1) { System.out.println("Thread 2: Holding lock 1..."); try { Thread.sleep(10); } catch (InterruptedException e) {} System.out.println("Thread 2: Waiting for lock 2..."); synchronized (Lock2) { System.out.println("Thread 2: Holding lock 1 &amp; 2..."); } } } } } So just changing the order of the locks prevent the program in going into a deadlock situation and completes with the following result − Thread 1: Holding lock 1... Thread 1: Waiting for lock 2... Thread 1: Holding lock 1 &amp; 2... Thread 2: Holding lock 1... Thread 2: Waiting for lock 2... Thread 2: Holding lock 1 &amp; 2...
[ { "code": null, "e": 1496, "s": 1062, "text": "Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. Deadlock occurs when multiple threads need the same locks but obtain them in a different order. A Java multithreaded program may suffer from the deadlock condition because the synchronized keyword causes the executing thread to block while waiting for the lock, or monitor, associated with the specified object. Here is an example." }, { "code": null, "e": 1506, "s": 1496, "text": "Live Demo" }, { "code": null, "e": 2746, "s": 1506, "text": "public class TestThread {\n public static Object Lock1 = new Object();\n public static Object Lock2 = new Object();\n\n public static void main(String args[]) {\n ThreadDemo1 T1 = new ThreadDemo1();\n ThreadDemo2 T2 = new ThreadDemo2();\n T1.start();\n T2.start();\n }\n\n private static class ThreadDemo1 extends Thread {\n public void run() {\n synchronized (Lock1) {\n System.out.println(\"Thread 1: Holding lock 1...\");\n\n try { Thread.sleep(10); }\n catch (InterruptedException e) {}\n System.out.println(\"Thread 1: Waiting for lock 2...\");\n\n synchronized (Lock2) {\n System.out.println(\"Thread 1: Holding lock 1 &amp; 2...\");\n }\n }\n }\n }\n\n private static class ThreadDemo2 extends Thread {\n public void run() {\n synchronized (Lock2) {\n System.out.println(\"Thread 2: Holding lock 2...\");\n\n try { Thread.sleep(10); }\n catch (InterruptedException e) {}\n System.out.println(\"Thread 2: Waiting for lock 1...\");\n\n synchronized (Lock1) {\n System.out.println(\"Thread 2: Holding lock 1 &amp; 2...\");\n }\n }\n }\n }\n}" }, { "code": null, "e": 2878, "s": 2746, "text": "When you compile and execute the above program, you find a deadlock situation and following is the output produced by the program −" }, { "code": null, "e": 2998, "s": 2878, "text": "Thread 1: Holding lock 1...\nThread 2: Holding lock 2...\nThread 1: Waiting for lock 2...\nThread 2: Waiting for lock 1..." }, { "code": null, "e": 3191, "s": 2998, "text": "The above program will hang forever because neither of the threads in position to proceed and waiting for each other to release the lock, so you can come out of the program by pressing CTRL+C." }, { "code": null, "e": 3309, "s": 3191, "text": "Let's change the order of the lock and run of the same program to see if both the threads still wait for each other −" }, { "code": null, "e": 3319, "s": 3309, "text": "Live Demo" }, { "code": null, "e": 4589, "s": 3319, "text": "public class TestThread {\n public static Object Lock1 = new Object();\n public static Object Lock2 = new Object();\n\n public static void main(String args[]) {\n ThreadDemo1 T1 = new ThreadDemo1();\n ThreadDemo2 T2 = new ThreadDemo2();\n T1.start();\n T2.start();\n }\n\n private static class ThreadDemo1 extends Thread {\n public void run() {\n synchronized (Lock1) {\n System.out.println(\"Thread 1: Holding lock 1...\");\n\n try {\n Thread.sleep(10);\n } catch (InterruptedException e) {}\n System.out.println(\"Thread 1: Waiting for lock 2...\");\n\n synchronized (Lock2) {\n System.out.println(\"Thread 1: Holding lock 1 &amp; 2...\");\n }\n }\n }\n }\n\n private static class ThreadDemo2 extends Thread {\n public void run() {\n synchronized (Lock1) {\n System.out.println(\"Thread 2: Holding lock 1...\");\n\n try {\n Thread.sleep(10);\n } catch (InterruptedException e) {}\n System.out.println(\"Thread 2: Waiting for lock 2...\");\n\n synchronized (Lock2) {\n System.out.println(\"Thread 2: Holding lock 1 &amp; 2...\");\n }\n }\n }\n }\n}" }, { "code": null, "e": 4726, "s": 4589, "text": "So just changing the order of the locks prevent the program in going into a deadlock situation and completes with the following result −" }, { "code": null, "e": 4918, "s": 4726, "text": "Thread 1: Holding lock 1...\nThread 1: Waiting for lock 2...\nThread 1: Holding lock 1 &amp; 2...\nThread 2: Holding lock 1...\nThread 2: Waiting for lock 2...\nThread 2: Holding lock 1 &amp; 2..." } ]
.NET Core - Running Tests in Visual Studio
In this chapter, we will discuss how to run tests in Visual Studio. The .NET Core has been designed with testability in mind, so that creating unit tests for your applications is easier than ever before. In this chapter, we will run and execute our test project in Visual Studio. Let us open the FirstApp solution in Visual Studio. You can see that it has only two projects and you will not be able to see the test project because we haven’t added that project in our solution. Let us add a folder first and call it test. Right-click on the test folder. Select project.json file and click Open. The following screenshot shows the code in Tests.cs file as output. It is the default implementation and it is just testing that True is equal to true. It is the xUnit testing framework and you will see the Fact attribute that annotates and denotes the test method. using System; using Xunit; namespace Tests { public class Tests { [Fact] public void Test1() { Assert.True(true); } } } Following is the implementation of project.json file. { "version": "1.0.0-*", "buildOptions": { "debugType": "portable" }, "dependencies": { "System.Runtime.Serialization.Primitives": "4.1.1", "xunit": "2.1.0", "dotnet-test-xunit": "1.0.0-rc2-192208-24" }, "testRunner": "xunit", "frameworks": { "netcoreapp1.0": { "dependencies": { "Microsoft.NETCore.App": { "type": "platform", "version": "1.0.1" } }, "imports": [ "dotnet5.4", "portable-net451+win8" ] } } } In project.json file, the most important dependency to the testing framework is the xunit, which brings in the Fact attribute. It brings in the testing framework and APIs for testing with xunit. We also have the dotnet-test-xunit, this is an adopter so that xunit can work with .NET Core, specifically with dotnet test command line utility. Then you will see the testRunner which will run xunit and you can also see the netcoreapp1.0 framework. You will see the .NETCore.App dependeny below. To run test in Visual Studio, let us open Test Explorer from the Test → Window → Test Explorer menu option. And you can see that Visual Studio automatically detects the test. The name of the test consists of namespace.className.TestMethodName. Let us now click on Run All button in Test Explorer. It will first build the code and the run the test and you will see the total time taken by the test. Let us change the test method so that we can see the output when the test fails. using System; using Xunit; namespace Tests { public class Tests { [Fact] public void Test1() { Assert.True(false); } } } Let us execute the test again by clicking on the Run All button link. You can now see the test failure. Print Add Notes Bookmark this page
[ { "code": null, "e": 2666, "s": 2386, "text": "In this chapter, we will discuss how to run tests in Visual Studio. The .NET Core has been designed with testability in mind, so that creating unit tests for your applications is easier than ever before. In this chapter, we will run and execute our test project in Visual Studio." }, { "code": null, "e": 2718, "s": 2666, "text": "Let us open the FirstApp solution in Visual Studio." }, { "code": null, "e": 2864, "s": 2718, "text": "You can see that it has only two projects and you will not be able to see the test project because we haven’t added that project in our solution." }, { "code": null, "e": 2908, "s": 2864, "text": "Let us add a folder first and call it test." }, { "code": null, "e": 2940, "s": 2908, "text": "Right-click on the test folder." }, { "code": null, "e": 2981, "s": 2940, "text": "Select project.json file and click Open." }, { "code": null, "e": 3049, "s": 2981, "text": "The following screenshot shows the code in Tests.cs file as output." }, { "code": null, "e": 3247, "s": 3049, "text": "It is the default implementation and it is just testing that True is equal to true. It is the xUnit testing framework and you will see the Fact attribute that annotates and denotes the test method." }, { "code": null, "e": 3413, "s": 3247, "text": "using System; \nusing Xunit; \n \nnamespace Tests { \n public class Tests { \n [Fact] \n public void Test1() { \n Assert.True(true); \n } \n } \n} " }, { "code": null, "e": 3467, "s": 3413, "text": "Following is the implementation of project.json file." }, { "code": null, "e": 4072, "s": 3467, "text": "{ \n \"version\": \"1.0.0-*\", \n \"buildOptions\": { \n \"debugType\": \"portable\" \n }, \n \"dependencies\": { \n \"System.Runtime.Serialization.Primitives\": \"4.1.1\", \n \"xunit\": \"2.1.0\", \n \"dotnet-test-xunit\": \"1.0.0-rc2-192208-24\" \n }, \n \"testRunner\": \"xunit\", \n \"frameworks\": { \n \"netcoreapp1.0\": { \n \"dependencies\": { \n \"Microsoft.NETCore.App\": { \n \"type\": \"platform\", \n \"version\": \"1.0.1\" \n }\n }, \n \"imports\": [ \n \"dotnet5.4\", \n \"portable-net451+win8\" \n ] \n } \n } \n}" }, { "code": null, "e": 4267, "s": 4072, "text": "In project.json file, the most important dependency to the testing framework is the xunit, which brings in the Fact attribute. It brings in the testing framework and APIs for testing with xunit." }, { "code": null, "e": 4517, "s": 4267, "text": "We also have the dotnet-test-xunit, this is an adopter so that xunit can work with .NET Core, specifically with dotnet test command line utility. Then you will see the testRunner which will run xunit and you can also see the netcoreapp1.0 framework." }, { "code": null, "e": 4564, "s": 4517, "text": "You will see the .NETCore.App dependeny below." }, { "code": null, "e": 4672, "s": 4564, "text": "To run test in Visual Studio, let us open Test Explorer from the Test → Window → Test Explorer menu option." }, { "code": null, "e": 4861, "s": 4672, "text": "And you can see that Visual Studio automatically detects the test. The name of the test consists of namespace.className.TestMethodName. Let us now click on Run All button in Test Explorer." }, { "code": null, "e": 5043, "s": 4861, "text": "It will first build the code and the run the test and you will see the total time taken by the test. Let us change the test method so that we can see the output when the test fails." }, { "code": null, "e": 5210, "s": 5043, "text": "using System; \nusing Xunit; \n \nnamespace Tests { \n public class Tests { \n [Fact] \n public void Test1() { \n Assert.True(false); \n } \n } \n} " }, { "code": null, "e": 5280, "s": 5210, "text": "Let us execute the test again by clicking on the Run All button link." }, { "code": null, "e": 5314, "s": 5280, "text": "You can now see the test failure." }, { "code": null, "e": 5321, "s": 5314, "text": " Print" }, { "code": null, "e": 5332, "s": 5321, "text": " Add Notes" } ]
Tryit Editor v3.7 - Show Java
public class Main { public static void main(String[] args) {
[]
Foundation - Centered Pagination
Including the class .text-center or text-align: center in CSS, you can make the pagination list at the center of the page. The following example demonstrates the use of pagination in Foundation − <!doctype html> <head> <meta charset = "utf-8" /> <meta http-equiv = "x-ua-compatible" content = "ie = edge" /> <meta name = "viewport" content = "width = device-width, initial-scale = 1.0" /> <title>Pagination</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/foundation-sites@6.5.1/dist/css/foundation.min.css" integrity="sha256-1mcRjtAxlSjp6XJBgrBeeCORfBp/ppyX4tsvpQVCcpA= sha384-b5S5X654rX3Wo6z5/hnQ4GBmKuIJKMPwrJXn52ypjztlnDK2w9+9hSMBz/asy9Gw sha512-M1VveR2JGzpgWHb0elGqPTltHK3xbvu3Brgjfg4cg5ZNtyyApxw/45yHYsZ/rCVbfoO5MSZxB241wWq642jLtA==" crossorigin="anonymous"> <!-- Compressed JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.0.1/js/vendor/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/foundation-sites@6.5.1/dist/js/foundation.min.js" integrity="sha256-WUKHnLrIrx8dew//IpSEmPN/NT3DGAEmIePQYIEJLLs= sha384-53StQWuVbn6figscdDC3xV00aYCPEz3srBdV/QGSXw3f19og3Tq2wTRe0vJqRTEO sha512-X9O+2f1ty1rzBJOC8AXBnuNUdyJg0m8xMKmbt9I3Vu/UOWmSg5zG+dtnje4wAZrKtkopz/PEDClHZ1LXx5IeOw==" crossorigin="anonymous"></script> </head> <body> <h3>Pagination Centered Example</h3> <ul class = "pagination text-center"> <li class = "disabled">Previous</li> <li class = "current">1</li> <li><a href = "#">2</a></li> <li><a href = "#">3</a></li> <li><a href = "#">4</a></li> <li class = "ellipsis"></li> <li><a href = "#">12</a></li> <li><a href = "#">13</a></li> <li><a href = "#">Next</a></li> </ul> </body> </html> Let us carry out the following steps to see how the above given code works − Save the above given html code pagination_centered.html file. Save the above given html code pagination_centered.html file. Open this HTML file in a browser, an output is displayed as shown below. Open this HTML file in a browser, an output is displayed as shown below. Previous 1 2 3 4 12 13 Next 117 Lectures 5.5 hours Shakthi Swaroop 61 Lectures 1.5 hours Hans Weemaes 17 Lectures 4 hours Stephen Kahuria 8 Lectures 50 mins Zenva 28 Lectures 2 hours Sandra L 16 Lectures 2.5 hours GreyCampus Inc. Print Add Notes Bookmark this page
[ { "code": null, "e": 2361, "s": 2238, "text": "Including the class .text-center or text-align: center in CSS, you can make the pagination list at the center of the page." }, { "code": null, "e": 2434, "s": 2361, "text": "The following example demonstrates the use of pagination in Foundation −" }, { "code": null, "e": 4061, "s": 2434, "text": "<!doctype html>\n <head>\n <meta charset = \"utf-8\" />\n <meta http-equiv = \"x-ua-compatible\" content = \"ie = edge\" />\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1.0\" />\n\n <title>Pagination</title>\n <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/foundation-sites@6.5.1/dist/css/foundation.min.css\" integrity=\"sha256-1mcRjtAxlSjp6XJBgrBeeCORfBp/ppyX4tsvpQVCcpA= sha384-b5S5X654rX3Wo6z5/hnQ4GBmKuIJKMPwrJXn52ypjztlnDK2w9+9hSMBz/asy9Gw sha512-M1VveR2JGzpgWHb0elGqPTltHK3xbvu3Brgjfg4cg5ZNtyyApxw/45yHYsZ/rCVbfoO5MSZxB241wWq642jLtA==\" crossorigin=\"anonymous\">\n\n <!-- Compressed JavaScript -->\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/foundation/6.0.1/js/vendor/jquery.min.js\"></script>\n <script src=\"https://cdn.jsdelivr.net/npm/foundation-sites@6.5.1/dist/js/foundation.min.js\" integrity=\"sha256-WUKHnLrIrx8dew//IpSEmPN/NT3DGAEmIePQYIEJLLs= sha384-53StQWuVbn6figscdDC3xV00aYCPEz3srBdV/QGSXw3f19og3Tq2wTRe0vJqRTEO sha512-X9O+2f1ty1rzBJOC8AXBnuNUdyJg0m8xMKmbt9I3Vu/UOWmSg5zG+dtnje4wAZrKtkopz/PEDClHZ1LXx5IeOw==\" crossorigin=\"anonymous\"></script>\n </head>\n\n <body>\n <h3>Pagination Centered Example</h3>\n <ul class = \"pagination text-center\">\n <li class = \"disabled\">Previous</li>\n <li class = \"current\">1</li>\n <li><a href = \"#\">2</a></li>\n <li><a href = \"#\">3</a></li>\n <li><a href = \"#\">4</a></li>\n <li class = \"ellipsis\"></li>\n <li><a href = \"#\">12</a></li>\n <li><a href = \"#\">13</a></li>\n <li><a href = \"#\">Next</a></li>\n </ul>\n </body>\n</html>" }, { "code": null, "e": 4138, "s": 4061, "text": "Let us carry out the following steps to see how the above given code works −" }, { "code": null, "e": 4200, "s": 4138, "text": "Save the above given html code pagination_centered.html file." }, { "code": null, "e": 4262, "s": 4200, "text": "Save the above given html code pagination_centered.html file." }, { "code": null, "e": 4335, "s": 4262, "text": "Open this HTML file in a browser, an output is displayed as shown below." }, { "code": null, "e": 4408, "s": 4335, "text": "Open this HTML file in a browser, an output is displayed as shown below." }, { "code": null, "e": 4417, "s": 4408, "text": "Previous" }, { "code": null, "e": 4419, "s": 4417, "text": "1" }, { "code": null, "e": 4421, "s": 4419, "text": "2" }, { "code": null, "e": 4423, "s": 4421, "text": "3" }, { "code": null, "e": 4425, "s": 4423, "text": "4" }, { "code": null, "e": 4428, "s": 4425, "text": "12" }, { "code": null, "e": 4431, "s": 4428, "text": "13" }, { "code": null, "e": 4436, "s": 4431, "text": "Next" }, { "code": null, "e": 4472, "s": 4436, "text": "\n 117 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4489, "s": 4472, "text": " Shakthi Swaroop" }, { "code": null, "e": 4524, "s": 4489, "text": "\n 61 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4538, "s": 4524, "text": " Hans Weemaes" }, { "code": null, "e": 4571, "s": 4538, "text": "\n 17 Lectures \n 4 hours \n" }, { "code": null, "e": 4588, "s": 4571, "text": " Stephen Kahuria" }, { "code": null, "e": 4619, "s": 4588, "text": "\n 8 Lectures \n 50 mins\n" }, { "code": null, "e": 4626, "s": 4619, "text": " Zenva" }, { "code": null, "e": 4659, "s": 4626, "text": "\n 28 Lectures \n 2 hours \n" }, { "code": null, "e": 4669, "s": 4659, "text": " Sandra L" }, { "code": null, "e": 4704, "s": 4669, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4721, "s": 4704, "text": " GreyCampus Inc." }, { "code": null, "e": 4728, "s": 4721, "text": " Print" }, { "code": null, "e": 4739, "s": 4728, "text": " Add Notes" } ]
Gaussian Mixture Modelling (GMM). Making Sense of Text Data using... | by Daniel Foley | Towards Data Science
In a previous post, I discussed k-means clustering as a way of summarising text data. I also talked about some of the limitations of k-means and in what situations it may not be the most appropriate solution. Probably the biggest limitation is that each cluster has the same diagonal covariance matrix. This produces spherical clusters that are quite inflexible in terms of the types of distributions they can model. In this post, I wanted to address some of those limitations and talk about one method in particular that can avoid these issues, Gaussian Mixture Modelling (GMM). The format of this post will be very similar to the last one where I explain the theory behind GMM and how it works. I then want to dive into coding the algorithm in Python and we can see how the results differ from k-means and why using GMM may be a good alternative. At its simplest, GMM is also a type of clustering algorithm. As its name implies, each cluster is modelled according to a different Gaussian distribution. This flexible and probabilistic approach to modelling the data means that rather than having hard assignments into clusters like k-means, we have soft assignments. This means that each data point could have been generated by any of the distributions with a corresponding probability. In effect, each distribution has some ‘responsibility’ for generating a particular data point. How can we estimate this type of model? Well, one thing we could do is to introduce a latent variable γ (gamma) for each data point. This assumes that each data point was generated by using some information about the latent variable γ. In other words, it tells us which Gaussian generated a particular data point. In practice, however, we do not observe these latent variables so we need to estimate them. How do we do this? Well, luckily for us there is already an algorithm to use in cases like these, the Expectation Maximisation (EM) Algorithm and this is what we will discuss next. The EM algorithm consists of two steps, an E-step or Expectation step and M-step or Maximisation step. Let’s say we have some latent variables γ (which are unobserved and denoted by the vector Z below) and our data points X. Our goal is to maximise the marginal likelihood of X given our parameters (denoted by the vector θ). Essentially we can find the marginal distribution as the joint of X and Z and sum over all Z’s (sum rule of probability). The above equation often results in a complicated function that is hard to maximise. What we can do in this case is to use Jensens Inequality to construct a lower bound function which is much easier to optimise. If we optimise this by minimising the KL divergence (gap) between the two distributions we can approximate the original function. This process is illustrated in Figure 1 below. I have also provided a video link above which shows a derivation of KL divergence for those of you who want a more rigorous mathematical explanation. To estimate our model essentially we only need to carry out two steps. In the first step (E-step) we want to estimate the posterior distribution of our latent variables γ conditional on our weights (π) means (μ)and covariance (Σ) of our Gaussians. The vector of parameters is denoted as θ in Figure 1. Estimating the E-step requires initialising these values first and we can do this with k-means which is usually a good starting point (more on this in the code below). We can then move to the second step (M-step) and use γ to maximise the likelihood with respect to our parameters θ. This process is repeated until the algorithm converges (loss function doesn't change). Why don't we try and visualise this process using Figure 1? We calculate the posterior distribution of γ in the first step which as it turns out is equivalent to the value we would get by minimising the KL divergence between the two distributions. We then set the posterior equal to q (confusing notation I know but this is just γ) and maximise this function with respect to the parameters θ. We can see from the graph as we iterate and perform these calculations we move towards the optimum (or at least a local optimum). Ok, now that we have visualised what the EM algorithm is doing I want to outline and explain the equations we need to calculate in the E-step and the M-step. These will be really important when it comes time to write our code. We can write the Gaussian Mixture distribution as a combination of Gaussians with weights equal to π as below. Where K is the number of Gaussians we want to model. Taking the above results we can calculate the posterior distribution of the responsibilities that each Gaussian has for each data point using the formula below. This equation is just Bayes rule where π is the prior weights and the likelihood is normal. After calculating our posterior all we need to do is get an estimate of the parameters of each Gaussian defined by the equations below and then evaluate the log-likelihood. These two steps are then repeated until convergence. Remember though, we have set the problem up in such a way that we can instead maximise a lower bound (or minimise the distance between the distributions) which will approximate equation 8 above. We can write our lower bound as follows where z is our latent variable. Notice our summation now appears outside the logarithm instead of inside it resulting in a much simpler expression than equation 8. Now that we have explained the theory behind the modelling I want to code up this algorithm using Python. Like my previous post, I am going to be using the same data set so we can compare the results between k-means and GMM. The preprocessing steps are exactly the same as those in the previous post and I provide a link to the full code at the end of this post. As I mentioned before, in order to start the algorithm (perform 1st E-step) we need initial values for our parameters. Rather than just randomly setting these values it is usually a good idea to estimate them using k-means. This will usually give us a good starting point and can help our model converge faster. Before we estimate GMM let’s have a quick look at what kind of clusters k-means gives us. Using our estimates from sklearn we can create a nice visualisation of our clusters (Figure 2). Notice the clusters are all spherical in shape and are the same size. The spherical clusters do not seem to model the spread of the data very well indicating that k-means in this particular case may not be the best approach. This illustrates one of the limitations of k-means as all covariance matrices are diagonal with unit variance. This limitation means that the model is not particularly flexible. With that in mind, let’s try out GMM and see what kind of results that gives us. Figure 3 below illustrates what GMM is doing. It clearly shows three clusters modelled by three different Gaussian distributions. I have used a toy data set here just to illustrate this clearly as it is less clear with the Enron data set. As you can see, compared to Figure 2 modelled using spherical clusters, GMM is much more flexible allowing us to generate much better fitting distributions. Ok, now we are going to get straight into coding our GMM class in Python. As always, we start off with an init method. The only things I am initialising here are the number of times we want to run our algorithm and the number of clusters we want to model. The most interesting method in this code snippet is calculate_mean_covariance. This helps us calculate values for our initial parameters. It takes in our data as well as our predictions from k-means and calculates the weights, means and covariance matrices of each cluster. The next bit of code implements our initialise_parameters method which uses k-means from the sklearn library to calculate our clusters. Notice that this function actually calls our calculate_mean_covariance method defined above. We could have probably used one method to calculate our clusters and initial parameters but it is usually much easier to debug and avoid errors if each method only carries out one specific task. It’s time to get right into the most important methods in our class. The E-step of the algorithm is defined below and takes in our parameters and data which makes perfect sense given the equations we defined above. Remember, the purpose of this step is to calculate the posterior distribution of our responsibilities (γ). The main thing to note here is that we loop through each of the C Gaussian’s (3 in our case) and calculate the posterior using a function from scipy to calculate the multivariate normal pdf. from scipy.stats import multivariate_normal as mvn After we have calculated this value for each Gaussian we just need to normalise the gamma (γ), corresponding to the denominator in equation 3. This is to ensure our gammas are valid probabilities. If we sum the values across clusters for each data point they should equal 1. After we calculate the values for the responsibilities (γ) we can feed these into the M-step. Again the purpose of the M-step is to calculate our new parameter values using the results from the E-step corresponding to equations 4, 5 and 6. To make debugging easier I have separated the m_step method and the compute_loss_function method in my code below. The compute_loss_function does exactly what its name implies. It takes in the responsibilities and parameters returned by the E-step and M-step and uses these to calculate our lower bound loss function defined in equation 9. All of our most important methods have now been coded up. Keeping consistent with sklearn I am going to define a fit method which will call the methods we just defined. In particular, we start by initialising our parameter values. After this, we perform the steps outlined in the EM-algorithm for our chosen number of iterations. Note that it doesn't actually take a large number of iterations to converge particularly when you use k-means to get values of the initial parameters (I think my algorithm converged in about 30 iterations). Since we are probably also interested in using this model to predict what Gaussian new data might belong to we can implement a predict and predict_proba method. The predict_proba method will take in new data points and predict the responsibilities for each Gaussian. In other words, the probability that this data point came from each distribution. This is the essence of the soft assignment that I mentioned at the start of the post. The predict method does essentially the same but assigns the cluster which has the highest probability using np.argmax. After that explanation, I think it’s about time we estimate our model and see what we get. Hopefully, the GMM visualisation above provided a good intuition about what the model is doing. We are going to be doing the exact same thing for our Enron data set. The code below just estimates our GMM model on our dataset using 3 different Gaussians. For plotting purposes, I also calculate the point of highest density of each distribution, corresponding to the centre which is helpful as a visualisation aid. Finally, we also use the model parameters to draw the shape of each distribution in Figure 4. The main takeaway in this figure is that the distributions are clearly no longer spherical. GMM has allowed us the relax our restrictions on the covariance matrix allowing the distribution to have a much better fit to the data. This is particularly useful given that the shape of our data was clearly not spherical. Now, this is probably not a perfect solution and there are some data points which do not fit any distribution very well but it is an improvement over k-means. Now, just to make sure we haven't done anything completely crazy in our code I am going to redo this estimation using sklearn and see if my solution is the same. The code below is pretty much the exact same as the code above so I won't go through it in detail. It looks like we have very similar result compared to sklearn. The one difference is that one of our cluster centres appears to be different. In the sklearn implementation, the centre is closer to 0.4 while in our implementation it is closer to 0.6. Perhaps this is due to a slightly different initialization in sklearn? Alright, guys, that’s it for this post. I hope that was a useful and pretty intuitive explanation of Gaussian Mixture Modelling. If any of you want to get a deeper understanding of the material I recommend the Coursera course Bayesian Methods for Machine Learning. I sourced a lot of the material from this course and I think it gives really nice and in-depth explanations of the concepts I presented here. I would also recommend the book, Pattern Recognition and Machine Learning by Bishop. This book is a great reference for most of the classic algorithms you will come across in machine learning. Below I provide the full code for the GMM class outlined in the post as well as a link to the Kaggle kernel where I did all the analysis. As always, feedback is welcome. Link to full code: https://www.kaggle.com/dfoly1/gaussian-mixture-model Source: Christopher M. Bishop 2006, Pattern Recognition and Machine Learning Source: Bayesian Methods for Machine Learning: Coursera course Source: Python for Data Science Handbook Note some of the links above are affiliate links.
[ { "code": null, "e": 895, "s": 46, "text": "In a previous post, I discussed k-means clustering as a way of summarising text data. I also talked about some of the limitations of k-means and in what situations it may not be the most appropriate solution. Probably the biggest limitation is that each cluster has the same diagonal covariance matrix. This produces spherical clusters that are quite inflexible in terms of the types of distributions they can model. In this post, I wanted to address some of those limitations and talk about one method in particular that can avoid these issues, Gaussian Mixture Modelling (GMM). The format of this post will be very similar to the last one where I explain the theory behind GMM and how it works. I then want to dive into coding the algorithm in Python and we can see how the results differ from k-means and why using GMM may be a good alternative." }, { "code": null, "e": 1429, "s": 895, "text": "At its simplest, GMM is also a type of clustering algorithm. As its name implies, each cluster is modelled according to a different Gaussian distribution. This flexible and probabilistic approach to modelling the data means that rather than having hard assignments into clusters like k-means, we have soft assignments. This means that each data point could have been generated by any of the distributions with a corresponding probability. In effect, each distribution has some ‘responsibility’ for generating a particular data point." }, { "code": null, "e": 2016, "s": 1429, "text": "How can we estimate this type of model? Well, one thing we could do is to introduce a latent variable γ (gamma) for each data point. This assumes that each data point was generated by using some information about the latent variable γ. In other words, it tells us which Gaussian generated a particular data point. In practice, however, we do not observe these latent variables so we need to estimate them. How do we do this? Well, luckily for us there is already an algorithm to use in cases like these, the Expectation Maximisation (EM) Algorithm and this is what we will discuss next." }, { "code": null, "e": 2464, "s": 2016, "text": "The EM algorithm consists of two steps, an E-step or Expectation step and M-step or Maximisation step. Let’s say we have some latent variables γ (which are unobserved and denoted by the vector Z below) and our data points X. Our goal is to maximise the marginal likelihood of X given our parameters (denoted by the vector θ). Essentially we can find the marginal distribution as the joint of X and Z and sum over all Z’s (sum rule of probability)." }, { "code": null, "e": 3003, "s": 2464, "text": "The above equation often results in a complicated function that is hard to maximise. What we can do in this case is to use Jensens Inequality to construct a lower bound function which is much easier to optimise. If we optimise this by minimising the KL divergence (gap) between the two distributions we can approximate the original function. This process is illustrated in Figure 1 below. I have also provided a video link above which shows a derivation of KL divergence for those of you who want a more rigorous mathematical explanation." }, { "code": null, "e": 3676, "s": 3003, "text": "To estimate our model essentially we only need to carry out two steps. In the first step (E-step) we want to estimate the posterior distribution of our latent variables γ conditional on our weights (π) means (μ)and covariance (Σ) of our Gaussians. The vector of parameters is denoted as θ in Figure 1. Estimating the E-step requires initialising these values first and we can do this with k-means which is usually a good starting point (more on this in the code below). We can then move to the second step (M-step) and use γ to maximise the likelihood with respect to our parameters θ. This process is repeated until the algorithm converges (loss function doesn't change)." }, { "code": null, "e": 4199, "s": 3676, "text": "Why don't we try and visualise this process using Figure 1? We calculate the posterior distribution of γ in the first step which as it turns out is equivalent to the value we would get by minimising the KL divergence between the two distributions. We then set the posterior equal to q (confusing notation I know but this is just γ) and maximise this function with respect to the parameters θ. We can see from the graph as we iterate and perform these calculations we move towards the optimum (or at least a local optimum)." }, { "code": null, "e": 4590, "s": 4199, "text": "Ok, now that we have visualised what the EM algorithm is doing I want to outline and explain the equations we need to calculate in the E-step and the M-step. These will be really important when it comes time to write our code. We can write the Gaussian Mixture distribution as a combination of Gaussians with weights equal to π as below. Where K is the number of Gaussians we want to model." }, { "code": null, "e": 4843, "s": 4590, "text": "Taking the above results we can calculate the posterior distribution of the responsibilities that each Gaussian has for each data point using the formula below. This equation is just Bayes rule where π is the prior weights and the likelihood is normal." }, { "code": null, "e": 5069, "s": 4843, "text": "After calculating our posterior all we need to do is get an estimate of the parameters of each Gaussian defined by the equations below and then evaluate the log-likelihood. These two steps are then repeated until convergence." }, { "code": null, "e": 5468, "s": 5069, "text": "Remember though, we have set the problem up in such a way that we can instead maximise a lower bound (or minimise the distance between the distributions) which will approximate equation 8 above. We can write our lower bound as follows where z is our latent variable. Notice our summation now appears outside the logarithm instead of inside it resulting in a much simpler expression than equation 8." }, { "code": null, "e": 5831, "s": 5468, "text": "Now that we have explained the theory behind the modelling I want to code up this algorithm using Python. Like my previous post, I am going to be using the same data set so we can compare the results between k-means and GMM. The preprocessing steps are exactly the same as those in the previous post and I provide a link to the full code at the end of this post." }, { "code": null, "e": 6233, "s": 5831, "text": "As I mentioned before, in order to start the algorithm (perform 1st E-step) we need initial values for our parameters. Rather than just randomly setting these values it is usually a good idea to estimate them using k-means. This will usually give us a good starting point and can help our model converge faster. Before we estimate GMM let’s have a quick look at what kind of clusters k-means gives us." }, { "code": null, "e": 6813, "s": 6233, "text": "Using our estimates from sklearn we can create a nice visualisation of our clusters (Figure 2). Notice the clusters are all spherical in shape and are the same size. The spherical clusters do not seem to model the spread of the data very well indicating that k-means in this particular case may not be the best approach. This illustrates one of the limitations of k-means as all covariance matrices are diagonal with unit variance. This limitation means that the model is not particularly flexible. With that in mind, let’s try out GMM and see what kind of results that gives us." }, { "code": null, "e": 7209, "s": 6813, "text": "Figure 3 below illustrates what GMM is doing. It clearly shows three clusters modelled by three different Gaussian distributions. I have used a toy data set here just to illustrate this clearly as it is less clear with the Enron data set. As you can see, compared to Figure 2 modelled using spherical clusters, GMM is much more flexible allowing us to generate much better fitting distributions." }, { "code": null, "e": 7739, "s": 7209, "text": "Ok, now we are going to get straight into coding our GMM class in Python. As always, we start off with an init method. The only things I am initialising here are the number of times we want to run our algorithm and the number of clusters we want to model. The most interesting method in this code snippet is calculate_mean_covariance. This helps us calculate values for our initial parameters. It takes in our data as well as our predictions from k-means and calculates the weights, means and covariance matrices of each cluster." }, { "code": null, "e": 8163, "s": 7739, "text": "The next bit of code implements our initialise_parameters method which uses k-means from the sklearn library to calculate our clusters. Notice that this function actually calls our calculate_mean_covariance method defined above. We could have probably used one method to calculate our clusters and initial parameters but it is usually much easier to debug and avoid errors if each method only carries out one specific task." }, { "code": null, "e": 8676, "s": 8163, "text": "It’s time to get right into the most important methods in our class. The E-step of the algorithm is defined below and takes in our parameters and data which makes perfect sense given the equations we defined above. Remember, the purpose of this step is to calculate the posterior distribution of our responsibilities (γ). The main thing to note here is that we loop through each of the C Gaussian’s (3 in our case) and calculate the posterior using a function from scipy to calculate the multivariate normal pdf." }, { "code": null, "e": 8727, "s": 8676, "text": "from scipy.stats import multivariate_normal as mvn" }, { "code": null, "e": 9002, "s": 8727, "text": "After we have calculated this value for each Gaussian we just need to normalise the gamma (γ), corresponding to the denominator in equation 3. This is to ensure our gammas are valid probabilities. If we sum the values across clusters for each data point they should equal 1." }, { "code": null, "e": 9582, "s": 9002, "text": "After we calculate the values for the responsibilities (γ) we can feed these into the M-step. Again the purpose of the M-step is to calculate our new parameter values using the results from the E-step corresponding to equations 4, 5 and 6. To make debugging easier I have separated the m_step method and the compute_loss_function method in my code below. The compute_loss_function does exactly what its name implies. It takes in the responsibilities and parameters returned by the E-step and M-step and uses these to calculate our lower bound loss function defined in equation 9." }, { "code": null, "e": 10119, "s": 9582, "text": "All of our most important methods have now been coded up. Keeping consistent with sklearn I am going to define a fit method which will call the methods we just defined. In particular, we start by initialising our parameter values. After this, we perform the steps outlined in the EM-algorithm for our chosen number of iterations. Note that it doesn't actually take a large number of iterations to converge particularly when you use k-means to get values of the initial parameters (I think my algorithm converged in about 30 iterations)." }, { "code": null, "e": 10674, "s": 10119, "text": "Since we are probably also interested in using this model to predict what Gaussian new data might belong to we can implement a predict and predict_proba method. The predict_proba method will take in new data points and predict the responsibilities for each Gaussian. In other words, the probability that this data point came from each distribution. This is the essence of the soft assignment that I mentioned at the start of the post. The predict method does essentially the same but assigns the cluster which has the highest probability using np.argmax." }, { "code": null, "e": 11273, "s": 10674, "text": "After that explanation, I think it’s about time we estimate our model and see what we get. Hopefully, the GMM visualisation above provided a good intuition about what the model is doing. We are going to be doing the exact same thing for our Enron data set. The code below just estimates our GMM model on our dataset using 3 different Gaussians. For plotting purposes, I also calculate the point of highest density of each distribution, corresponding to the centre which is helpful as a visualisation aid. Finally, we also use the model parameters to draw the shape of each distribution in Figure 4." }, { "code": null, "e": 11748, "s": 11273, "text": "The main takeaway in this figure is that the distributions are clearly no longer spherical. GMM has allowed us the relax our restrictions on the covariance matrix allowing the distribution to have a much better fit to the data. This is particularly useful given that the shape of our data was clearly not spherical. Now, this is probably not a perfect solution and there are some data points which do not fit any distribution very well but it is an improvement over k-means." }, { "code": null, "e": 12330, "s": 11748, "text": "Now, just to make sure we haven't done anything completely crazy in our code I am going to redo this estimation using sklearn and see if my solution is the same. The code below is pretty much the exact same as the code above so I won't go through it in detail. It looks like we have very similar result compared to sklearn. The one difference is that one of our cluster centres appears to be different. In the sklearn implementation, the centre is closer to 0.4 while in our implementation it is closer to 0.6. Perhaps this is due to a slightly different initialization in sklearn?" }, { "code": null, "e": 13100, "s": 12330, "text": "Alright, guys, that’s it for this post. I hope that was a useful and pretty intuitive explanation of Gaussian Mixture Modelling. If any of you want to get a deeper understanding of the material I recommend the Coursera course Bayesian Methods for Machine Learning. I sourced a lot of the material from this course and I think it gives really nice and in-depth explanations of the concepts I presented here. I would also recommend the book, Pattern Recognition and Machine Learning by Bishop. This book is a great reference for most of the classic algorithms you will come across in machine learning. Below I provide the full code for the GMM class outlined in the post as well as a link to the Kaggle kernel where I did all the analysis. As always, feedback is welcome." }, { "code": null, "e": 13172, "s": 13100, "text": "Link to full code: https://www.kaggle.com/dfoly1/gaussian-mixture-model" }, { "code": null, "e": 13249, "s": 13172, "text": "Source: Christopher M. Bishop 2006, Pattern Recognition and Machine Learning" }, { "code": null, "e": 13312, "s": 13249, "text": "Source: Bayesian Methods for Machine Learning: Coursera course" }, { "code": null, "e": 13353, "s": 13312, "text": "Source: Python for Data Science Handbook" } ]
A Simplex Stop-and-Wait Protocol for an Error-Free Channel
Stop – and – Wait protocol is data link layer protocol for transmission of frames over noiseless channels. It provides unidirectional data transmission with flow control facilities but without error control facilities. This protocol takes into account the fact that the receiver has a finite processing speed. If data frames arrive at the receiver’s end at a rate which is greater than its rate of processing, frames be dropped out. In order to avoid this, the receiver sends an acknowledgement for each frame upon its arrival. The sender sends the next frame only when it has received a positive acknowledgement from the receiver that it is available for further data processing. Sender Site: The data link layer in the sender site waits for the network layer for a data packet. It then checks whether it can send the frame. If it receives a positive notification from the physical layer, it makes frames out of the data and sends it. It then waits for an acknowledgement before sending the next frame. Sender Site: The data link layer in the sender site waits for the network layer for a data packet. It then checks whether it can send the frame. If it receives a positive notification from the physical layer, it makes frames out of the data and sends it. It then waits for an acknowledgement before sending the next frame. Receiver Site: The data link layer in the receiver site waits for a frame to arrive. When it arrives, the receiver processes it and delivers it to the network layer. It then sends an acknowledgement back to the sender. Receiver Site: The data link layer in the receiver site waits for a frame to arrive. When it arrives, the receiver processes it and delivers it to the network layer. It then sends an acknowledgement back to the sender. begin canSend = True; //Allow the first frame to be sent while (true) //check repeatedly do Wait_For_Event(); //wait for availability of packet if ( Event(Request_For_Transfer) AND canSend) then Get_Data_From_Network_Layer(); Make_Frame(); Send_Frame_To_Physical_Layer(); canSend = False; else if ( Event(Acknowledgement_Arrival)) then Receive_ACK(); canSend = True; end if end while end begin while (true) //check repeatedly do Wait_For_Event(); //wait for arrival of frame if ( Event(Frame_Arrival) then Receive_Frame_From_Physical_Layer(); Extract_Data(); Deliver_Data_To_Network_Layer(); Send_ACK(); end if end while end The following flow diagram depicts communication via simplex stop – and – wait protocol for noiseless channel:
[ { "code": null, "e": 1281, "s": 1062, "text": "Stop – and – Wait protocol is data link layer protocol for transmission of frames over noiseless channels. It provides unidirectional data transmission with flow control facilities but without error control facilities." }, { "code": null, "e": 1743, "s": 1281, "text": "This protocol takes into account the fact that the receiver has a finite processing speed. If data frames arrive at the receiver’s end at a rate which is greater than its rate of processing, frames be dropped out. In order to avoid this, the receiver sends an acknowledgement for each frame upon its arrival. The sender sends the next frame only when it has received a positive acknowledgement from the receiver that it is available for further data processing." }, { "code": null, "e": 2066, "s": 1743, "text": "Sender Site: The data link layer in the sender site waits for the network layer for a data packet. It then checks whether it can send the frame. If it receives a positive notification from the physical layer, it makes frames out of the data and sends it. It then waits for an acknowledgement before sending the next frame." }, { "code": null, "e": 2389, "s": 2066, "text": "Sender Site: The data link layer in the sender site waits for the network layer for a data packet. It then checks whether it can send the frame. If it receives a positive notification from the physical layer, it makes frames out of the data and sends it. It then waits for an acknowledgement before sending the next frame." }, { "code": null, "e": 2608, "s": 2389, "text": "Receiver Site: The data link layer in the receiver site waits for a frame to arrive. When it arrives, the receiver processes it and delivers it to the network layer. It then sends an acknowledgement back to the sender." }, { "code": null, "e": 2827, "s": 2608, "text": "Receiver Site: The data link layer in the receiver site waits for a frame to arrive. When it arrives, the receiver processes it and delivers it to the network layer. It then sends an acknowledgement back to the sender." }, { "code": null, "e": 3324, "s": 2827, "text": "begin\n canSend = True; //Allow the first frame to be sent\n while (true) //check repeatedly\n do\n Wait_For_Event(); //wait for availability of packet\n if ( Event(Request_For_Transfer) AND canSend) then\n Get_Data_From_Network_Layer();\n Make_Frame();\n Send_Frame_To_Physical_Layer();\n canSend = False;\n else if ( Event(Acknowledgement_Arrival)) then\n Receive_ACK();\n canSend = True;\n end if\n end while\nend" }, { "code": null, "e": 3633, "s": 3324, "text": "begin\n while (true) //check repeatedly\n do\n Wait_For_Event(); //wait for arrival of frame\n if ( Event(Frame_Arrival) then\n Receive_Frame_From_Physical_Layer();\n Extract_Data();\n Deliver_Data_To_Network_Layer();\n Send_ACK();\n end if\n end while\nend" }, { "code": null, "e": 3744, "s": 3633, "text": "The following flow diagram depicts communication via simplex stop – and – wait protocol for noiseless channel:" } ]
How to Use View Binding in RecyclerView Adapter Class in Android?
30 Nov, 2021 View Binding is a part of Android Jetpack which provides the views to bind with the classes by replacing the findViewById() method in a null safe way. In this article, we will see its implementations in the Adapter class of RecyclerView. Note that we are going to implement this project using the Kotlin language. Step 1: Create a new project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language Step 2: Add view binding dependency Go to build.gradle(app) and the following dependency inside the android tag and click sync now. buildFeatures { viewBinding true } Step 3: Working with the activity_main.xml file Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. It has only a single Recycler view which we will use to show our data. 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:background="#F5F8FD" android:layout_height="match_parent" tools:context=".MainActivity"> <!--Add recycler view to main activity--> <androidx.recyclerview.widget.RecyclerView android:id="@+id/rv_list" android:layout_width="match_parent" android:layout_height="match_parent" tools:listitem="@layout/single_item" app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" /> </androidx.constraintlayout.widget.ConstraintLayout> Step 4: Create a new layout file and name it as single_item.xml file Go to the single_item.xml file and refer to the following code. Below is the code for the single_item.xml file. It is the single item layout that we will use in RecyclerView. XML <?xml version="1.0" encoding="utf-8"?><com.google.android.material.card.MaterialCardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_marginBottom="10dp" android:layout_marginStart="5dp" android:layout_marginEnd="5dp" android:layout_height="110dp"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent"> <!--Add image view, We will not set any data here.--> <ImageView android:id="@+id/iv_language" android:layout_width="80dp" android:layout_height="90dp" android:layout_marginStart="20dp" android:layout_marginTop="10dp" android:scaleType="fitCenter" android:src="@mipmap/ic_launcher" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintTop_toTopOf="parent" /> <!--Text view for showing the language name--> <TextView android:id="@+id/tv_lang_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="30dp" android:layout_marginTop="30dp" android:text="Language" android:textSize="16sp" android:textStyle="bold" app:layout_constraintLeft_toRightOf="@id/iv_language" app:layout_constraintTop_toTopOf="parent" /> <!--Text View for showing the exp--> <TextView android:id="@+id/tv_exp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="Exp : 3 years" app:layout_constraintLeft_toLeftOf="@id/tv_lang_name" app:layout_constraintTop_toBottomOf="@id/tv_lang_name" /> </androidx.constraintlayout.widget.ConstraintLayout> </com.google.android.material.card.MaterialCardView> Step 5: Create a new Model class Create a new class Language.kt we will use data of custom generic “Language” to pass in the list that will be shown in RecyclerView. Kotlin // this is the Language model classclass Language( val name : String ="", val exp : String ="") Step 6: Working with the Adapter class Create a new class RvAdapter.kt this will act as an Adapter class for the recycler view. Using View binding we use the generated class of the layout single_item.xml ie SingleItemBinding to add data and view in the recycler view of MainActivity.kt in our case. Comments are added before the code for better understanding. Kotlin import android.view.LayoutInflaterimport android.view.ViewGroupimport androidx.recyclerview.widget.RecyclerViewimport com.geeksforgeeks.rvadapterviewbinding.databinding.SingleItemBinding class RvAdapter( var languageList: List<Language>,) : RecyclerView.Adapter<RvAdapter.ViewHolder>() { // create an inner class with name ViewHolder // It takes a view argument, in which pass the generated class of single_item.xml // ie SingleItemBinding and in the RecyclerView.ViewHolder(binding.root) pass it like this inner class ViewHolder(val binding: SingleItemBinding) : RecyclerView.ViewHolder(binding.root) // inside the onCreateViewHolder inflate the view of SingleItemBinding // and return new ViewHolder object containing this layout override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = SingleItemBinding.inflate(LayoutInflater.from(parent.context), parent, false) return ViewHolder(binding) } // bind the items with each item // of the list languageList // which than will be // shown in recycler view // to keep it simple we are // not setting any image data to view override fun onBindViewHolder(holder: ViewHolder, position: Int) { with(holder){ with(languageList[position]){ binding.tvLangName.text = this.name binding.tvExp.text = this.exp } } } // return the size of languageList override fun getItemCount(): Int { return languageList.size }} Step 7: Working with the MainActivity.kt file Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. Kotlin import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport com.geeksforgeeks.rvadapterviewbinding.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { // view binding for the activity private var _binding : ActivityMainBinding? = null private val binding get() = _binding!! // create reference to the adapter and the list // in the list pass the model of Language private lateinit var rvAdapter: RvAdapter private lateinit var languageList : List<Language> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) _binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) // load data to language list loadLanguage() // create layoutManager val layoutManager: RecyclerView.LayoutManager = LinearLayoutManager(this) // pass it to rvLists layoutManager binding.rvList.setLayoutManager(layoutManager) // initialize the adapter, // and pass the required argument rvAdapter = RvAdapter(languageList) // attach adapter to the recycler view binding.rvList.adapter = rvAdapter } // add items to the list manually in our case private fun loadLanguage() { languageList = listOf( Language("Java" , "Exp : 3 years"), Language("Kotlin" , "Exp : 2 years"), Language("Python" , "Exp : 4 years"), Language("JavaScript" , "Exp : 6 years"), Language("PHP" , "Exp : 1 years"), Language("CPP" , "Exp : 8 years"), ) } // on destroy of view make // the binding reference to null override fun onDestroy() { super.onDestroy() _binding = null }} Output: introidx skillz_06 Android-Jetpack 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 How to Communicate Between Fragments in Android? Flutter - Custom Bottom Navigation Bar 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": 52, "s": 24, "text": "\n30 Nov, 2021" }, { "code": null, "e": 367, "s": 52, "text": "View Binding is a part of Android Jetpack which provides the views to bind with the classes by replacing the findViewById() method in a null safe way. In this article, we will see its implementations in the Adapter class of RecyclerView. Note that we are going to implement this project using the Kotlin language. " }, { "code": null, "e": 396, "s": 367, "text": "Step 1: Create a new project" }, { "code": null, "e": 559, "s": 396, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language" }, { "code": null, "e": 595, "s": 559, "text": "Step 2: Add view binding dependency" }, { "code": null, "e": 691, "s": 595, "text": "Go to build.gradle(app) and the following dependency inside the android tag and click sync now." }, { "code": null, "e": 708, "s": 691, "text": " buildFeatures {" }, { "code": null, "e": 732, "s": 708, "text": " viewBinding true" }, { "code": null, "e": 737, "s": 732, "text": " }" }, { "code": null, "e": 785, "s": 737, "text": "Step 3: Working with the activity_main.xml file" }, { "code": null, "e": 972, "s": 785, "text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. It has only a single Recycler view which we will use to show our data." }, { "code": null, "e": 976, "s": 972, "text": "XML" }, { "code": "<?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:background=\"#F5F8FD\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--Add recycler view to main activity--> <androidx.recyclerview.widget.RecyclerView android:id=\"@+id/rv_list\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:listitem=\"@layout/single_item\" app:layoutManager=\"androidx.recyclerview.widget.LinearLayoutManager\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 1769, "s": 976, "text": null }, { "code": null, "e": 1838, "s": 1769, "text": "Step 4: Create a new layout file and name it as single_item.xml file" }, { "code": null, "e": 2014, "s": 1838, "text": "Go to the single_item.xml file and refer to the following code. Below is the code for the single_item.xml file. It is the single item layout that we will use in RecyclerView. " }, { "code": null, "e": 2018, "s": 2014, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><com.google.android.material.card.MaterialCardView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_marginBottom=\"10dp\" android:layout_marginStart=\"5dp\" android:layout_marginEnd=\"5dp\" android:layout_height=\"110dp\"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <!--Add image view, We will not set any data here.--> <ImageView android:id=\"@+id/iv_language\" android:layout_width=\"80dp\" android:layout_height=\"90dp\" android:layout_marginStart=\"20dp\" android:layout_marginTop=\"10dp\" android:scaleType=\"fitCenter\" android:src=\"@mipmap/ic_launcher\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <!--Text view for showing the language name--> <TextView android:id=\"@+id/tv_lang_name\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"30dp\" android:layout_marginTop=\"30dp\" android:text=\"Language\" android:textSize=\"16sp\" android:textStyle=\"bold\" app:layout_constraintLeft_toRightOf=\"@id/iv_language\" app:layout_constraintTop_toTopOf=\"parent\" /> <!--Text View for showing the exp--> <TextView android:id=\"@+id/tv_exp\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"10dp\" android:text=\"Exp : 3 years\" app:layout_constraintLeft_toLeftOf=\"@id/tv_lang_name\" app:layout_constraintTop_toBottomOf=\"@id/tv_lang_name\" /> </androidx.constraintlayout.widget.ConstraintLayout> </com.google.android.material.card.MaterialCardView>", "e": 4107, "s": 2018, "text": null }, { "code": null, "e": 4141, "s": 4107, "text": "Step 5: Create a new Model class " }, { "code": null, "e": 4275, "s": 4141, "text": "Create a new class Language.kt we will use data of custom generic “Language” to pass in the list that will be shown in RecyclerView. " }, { "code": null, "e": 4282, "s": 4275, "text": "Kotlin" }, { "code": "// this is the Language model classclass Language( val name : String =\"\", val exp : String =\"\")", "e": 4384, "s": 4282, "text": null }, { "code": null, "e": 4423, "s": 4384, "text": "Step 6: Working with the Adapter class" }, { "code": null, "e": 4745, "s": 4423, "text": "Create a new class RvAdapter.kt this will act as an Adapter class for the recycler view. Using View binding we use the generated class of the layout single_item.xml ie SingleItemBinding to add data and view in the recycler view of MainActivity.kt in our case. Comments are added before the code for better understanding. " }, { "code": null, "e": 4752, "s": 4745, "text": "Kotlin" }, { "code": "import android.view.LayoutInflaterimport android.view.ViewGroupimport androidx.recyclerview.widget.RecyclerViewimport com.geeksforgeeks.rvadapterviewbinding.databinding.SingleItemBinding class RvAdapter( var languageList: List<Language>,) : RecyclerView.Adapter<RvAdapter.ViewHolder>() { // create an inner class with name ViewHolder // It takes a view argument, in which pass the generated class of single_item.xml // ie SingleItemBinding and in the RecyclerView.ViewHolder(binding.root) pass it like this inner class ViewHolder(val binding: SingleItemBinding) : RecyclerView.ViewHolder(binding.root) // inside the onCreateViewHolder inflate the view of SingleItemBinding // and return new ViewHolder object containing this layout override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = SingleItemBinding.inflate(LayoutInflater.from(parent.context), parent, false) return ViewHolder(binding) } // bind the items with each item // of the list languageList // which than will be // shown in recycler view // to keep it simple we are // not setting any image data to view override fun onBindViewHolder(holder: ViewHolder, position: Int) { with(holder){ with(languageList[position]){ binding.tvLangName.text = this.name binding.tvExp.text = this.exp } } } // return the size of languageList override fun getItemCount(): Int { return languageList.size }}", "e": 6299, "s": 4752, "text": null }, { "code": null, "e": 6346, "s": 6299, "text": "Step 7: Working with the MainActivity.kt file " }, { "code": null, "e": 6533, "s": 6346, "text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. " }, { "code": null, "e": 6540, "s": 6533, "text": "Kotlin" }, { "code": "import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport com.geeksforgeeks.rvadapterviewbinding.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { // view binding for the activity private var _binding : ActivityMainBinding? = null private val binding get() = _binding!! // create reference to the adapter and the list // in the list pass the model of Language private lateinit var rvAdapter: RvAdapter private lateinit var languageList : List<Language> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) _binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) // load data to language list loadLanguage() // create layoutManager val layoutManager: RecyclerView.LayoutManager = LinearLayoutManager(this) // pass it to rvLists layoutManager binding.rvList.setLayoutManager(layoutManager) // initialize the adapter, // and pass the required argument rvAdapter = RvAdapter(languageList) // attach adapter to the recycler view binding.rvList.adapter = rvAdapter } // add items to the list manually in our case private fun loadLanguage() { languageList = listOf( Language(\"Java\" , \"Exp : 3 years\"), Language(\"Kotlin\" , \"Exp : 2 years\"), Language(\"Python\" , \"Exp : 4 years\"), Language(\"JavaScript\" , \"Exp : 6 years\"), Language(\"PHP\" , \"Exp : 1 years\"), Language(\"CPP\" , \"Exp : 8 years\"), ) } // on destroy of view make // the binding reference to null override fun onDestroy() { super.onDestroy() _binding = null }}", "e": 8345, "s": 6540, "text": null }, { "code": null, "e": 8353, "s": 8345, "text": "Output:" }, { "code": null, "e": 8362, "s": 8353, "text": "introidx" }, { "code": null, "e": 8372, "s": 8362, "text": "skillz_06" }, { "code": null, "e": 8388, "s": 8372, "text": "Android-Jetpack" }, { "code": null, "e": 8396, "s": 8388, "text": "Android" }, { "code": null, "e": 8403, "s": 8396, "text": "Kotlin" }, { "code": null, "e": 8411, "s": 8403, "text": "Android" }, { "code": null, "e": 8509, "s": 8411, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8578, "s": 8509, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 8610, "s": 8578, "text": "Android SDK and it's Components" }, { "code": null, "e": 8659, "s": 8610, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 8698, "s": 8659, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 8740, "s": 8698, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 8809, "s": 8740, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 8828, "s": 8809, "text": "Android UI Layouts" }, { "code": null, "e": 8841, "s": 8828, "text": "Kotlin Array" }, { "code": null, "e": 8890, "s": 8841, "text": "How to Communicate Between Fragments in Android?" } ]
How to Switch between Window using Selenium in Python?
04 Jan, 2021 Selenium is an effective device for controlling an internet browser through the program. It is purposeful for all browsers, works on all fundamental OS and its scripts are written in numerous languages i.e Python, Java, C#, etc, we can be running with Python. It’s miles fantastically viable that we open a massive range of windows. Each window might also additionally require us to carry out a few moves for finishing a stop-to-stop flow. For this, we need to be capable of transfer among them. We want to interchange over the manage additionally after which do the desired operation, because, with the aid of using the default, the point of interest stays at the figure window. Requirement: You need to install chromedriver and set path. Click here to download for more information follows this link. WebDriver supports moving between these windows using the “switch_to_window()” method. driver.switch_to_window(“”) Step-by-step approach: If we open multiple windows then we want the print the title of every window page, but we print only a parent window of the title not an all window page title. This problem will solve through the driver.switch_to_window(“). Using this method we are capable of printing every page of the title. Taking any URL. We want the child window of this web page then click on any button using the find_element_by_xpath() method to find XPath. Create a handles variable who store of all handles value of open browser window handles=driver.window_handles Then using loop print all the titles of webpages. Implementation: Python3 # import selenium modulefrom selenium import webdriver # import select classfrom selenium.webdriver.support.ui import Select # using chrome driverdriver = webdriver.Chrome() # web page url and open first window pagedriver.get("http://demo.automationtesting.in/Windows.html") # find xpath of button for child window page# this page no. 2driver.find_element_by_xpath('//*[@id="Tabbed"]/a/button').click() # return all handles value of open browser windowhandles = driver.window_handlesfor i in handles: driver.switch_to.window(i) # print every open window page title print(driver.title) Output: Python Selenium-Exercises Python-selenium Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Jan, 2021" }, { "code": null, "e": 288, "s": 28, "text": "Selenium is an effective device for controlling an internet browser through the program. It is purposeful for all browsers, works on all fundamental OS and its scripts are written in numerous languages i.e Python, Java, C#, etc, we can be running with Python." }, { "code": null, "e": 708, "s": 288, "text": "It’s miles fantastically viable that we open a massive range of windows. Each window might also additionally require us to carry out a few moves for finishing a stop-to-stop flow. For this, we need to be capable of transfer among them. We want to interchange over the manage additionally after which do the desired operation, because, with the aid of using the default, the point of interest stays at the figure window." }, { "code": null, "e": 721, "s": 708, "text": "Requirement:" }, { "code": null, "e": 918, "s": 721, "text": "You need to install chromedriver and set path. Click here to download for more information follows this link. WebDriver supports moving between these windows using the “switch_to_window()” method." }, { "code": null, "e": 946, "s": 918, "text": "driver.switch_to_window(“”)" }, { "code": null, "e": 969, "s": 946, "text": "Step-by-step approach:" }, { "code": null, "e": 1263, "s": 969, "text": "If we open multiple windows then we want the print the title of every window page, but we print only a parent window of the title not an all window page title. This problem will solve through the driver.switch_to_window(“). Using this method we are capable of printing every page of the title." }, { "code": null, "e": 1279, "s": 1263, "text": "Taking any URL." }, { "code": null, "e": 1402, "s": 1279, "text": "We want the child window of this web page then click on any button using the find_element_by_xpath() method to find XPath." }, { "code": null, "e": 1482, "s": 1402, "text": "Create a handles variable who store of all handles value of open browser window" }, { "code": null, "e": 1512, "s": 1482, "text": "handles=driver.window_handles" }, { "code": null, "e": 1562, "s": 1512, "text": "Then using loop print all the titles of webpages." }, { "code": null, "e": 1578, "s": 1562, "text": "Implementation:" }, { "code": null, "e": 1586, "s": 1578, "text": "Python3" }, { "code": "# import selenium modulefrom selenium import webdriver # import select classfrom selenium.webdriver.support.ui import Select # using chrome driverdriver = webdriver.Chrome() # web page url and open first window pagedriver.get(\"http://demo.automationtesting.in/Windows.html\") # find xpath of button for child window page# this page no. 2driver.find_element_by_xpath('//*[@id=\"Tabbed\"]/a/button').click() # return all handles value of open browser windowhandles = driver.window_handlesfor i in handles: driver.switch_to.window(i) # print every open window page title print(driver.title)", "e": 2187, "s": 1586, "text": null }, { "code": null, "e": 2195, "s": 2187, "text": "Output:" }, { "code": null, "e": 2221, "s": 2195, "text": "Python Selenium-Exercises" }, { "code": null, "e": 2237, "s": 2221, "text": "Python-selenium" }, { "code": null, "e": 2244, "s": 2237, "text": "Python" }, { "code": null, "e": 2342, "s": 2244, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2374, "s": 2342, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2401, "s": 2374, "text": "Python Classes and Objects" }, { "code": null, "e": 2422, "s": 2401, "text": "Python OOPs Concepts" }, { "code": null, "e": 2445, "s": 2422, "text": "Introduction To PYTHON" }, { "code": null, "e": 2501, "s": 2445, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2532, "s": 2501, "text": "Python | os.path.join() method" }, { "code": null, "e": 2574, "s": 2532, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2616, "s": 2574, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2655, "s": 2616, "text": "Python | Get unique values from a list" } ]
How to check an array is empty or not using jQuery ?
13 Jan, 2022 In this article, we will check if an array is empty or not using jQuery. In JavaScript, arrays are a special type of object. If we use the typeof operator for arrays, it returns “object”. We can use jQuery’s isEmptyObject() method to check whether the array is empty or contains elements. The isEmptyObject() method accepts a single parameter of type Object, which is the object to be checked and returns a boolean value true if the object is empty and false if not empty. Syntax: $.isEmptyObject(array); Example 1: In the example below, we passed an empty array to the isEmptyObject() method. HTML <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- jQuery CDN Link --> <script src="https://code.jquery.com/jquery-2.1.3.js"> </script> <style> body { margin: 30px; font-family: sans-serif; text-align: center; } button { padding: 20px; background-color: green; color: white; cursor: pointer; } </style> <!-- Function to check if array is empty --> <script> function checkArray() { var array = []; if($.isEmptyObject(array)) { $("#write").text("The Array is Empty."); }else { $("#write").text("The Array is not Empty."); } } </script></head><body> <button id="button1" onclick="checkArray();"> CHECK ARRAY </button> <h2 id="write"></h2></body></html> Output: Example 2: In this example, we passed a non-empty array to the isEmptyObject() method. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> Check whether the array is empty or not using jQuery </title> <!-- jQuery CDN Link --> <script src="https://code.jquery.com/jquery-2.1.3.js"> </script> <style> body { margin-top: 30px; font-family: sans-serif; text-align: center; } button { padding: 20px; background-color: green; color: white; cursor: pointer; } </style> <!-- Function to check if array is empty --> <script> function checkArray() { var array = [20, 49, "gfg"]; if ($.isEmptyObject(array)) { $("#write").text("The Array is Empty."); } else { $("#write").text("The Array is not Empty."); } } </script></head> <body> <button id="button1" onclick="checkArray();"> CHECK ARRAY </button> <h2 id="write"></h2></body> </html> Output: CSS-Properties HTML-Questions jQuery-Methods jQuery-Questions CSS HTML JQuery Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Jan, 2022" }, { "code": null, "e": 317, "s": 28, "text": "In this article, we will check if an array is empty or not using jQuery. In JavaScript, arrays are a special type of object. If we use the typeof operator for arrays, it returns “object”. We can use jQuery’s isEmptyObject() method to check whether the array is empty or contains elements." }, { "code": null, "e": 501, "s": 317, "text": "The isEmptyObject() method accepts a single parameter of type Object, which is the object to be checked and returns a boolean value true if the object is empty and false if not empty." }, { "code": null, "e": 510, "s": 501, "text": "Syntax: " }, { "code": null, "e": 534, "s": 510, "text": "$.isEmptyObject(array);" }, { "code": null, "e": 623, "s": 534, "text": "Example 1: In the example below, we passed an empty array to the isEmptyObject() method." }, { "code": null, "e": 628, "s": 623, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <!-- jQuery CDN Link --> <script src=\"https://code.jquery.com/jquery-2.1.3.js\"> </script> <style> body { margin: 30px; font-family: sans-serif; text-align: center; } button { padding: 20px; background-color: green; color: white; cursor: pointer; } </style> <!-- Function to check if array is empty --> <script> function checkArray() { var array = []; if($.isEmptyObject(array)) { $(\"#write\").text(\"The Array is Empty.\"); }else { $(\"#write\").text(\"The Array is not Empty.\"); } } </script></head><body> <button id=\"button1\" onclick=\"checkArray();\"> CHECK ARRAY </button> <h2 id=\"write\"></h2></body></html>", "e": 1694, "s": 628, "text": null }, { "code": null, "e": 1702, "s": 1694, "text": "Output:" }, { "code": null, "e": 1789, "s": 1702, "text": "Example 2: In this example, we passed a non-empty array to the isEmptyObject() method." }, { "code": null, "e": 1794, "s": 1789, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title> Check whether the array is empty or not using jQuery </title> <!-- jQuery CDN Link --> <script src=\"https://code.jquery.com/jquery-2.1.3.js\"> </script> <style> body { margin-top: 30px; font-family: sans-serif; text-align: center; } button { padding: 20px; background-color: green; color: white; cursor: pointer; } </style> <!-- Function to check if array is empty --> <script> function checkArray() { var array = [20, 49, \"gfg\"]; if ($.isEmptyObject(array)) { $(\"#write\").text(\"The Array is Empty.\"); } else { $(\"#write\").text(\"The Array is not Empty.\"); } } </script></head> <body> <button id=\"button1\" onclick=\"checkArray();\"> CHECK ARRAY </button> <h2 id=\"write\"></h2></body> </html>", "e": 2965, "s": 1794, "text": null }, { "code": null, "e": 2973, "s": 2965, "text": "Output:" }, { "code": null, "e": 2988, "s": 2973, "text": "CSS-Properties" }, { "code": null, "e": 3003, "s": 2988, "text": "HTML-Questions" }, { "code": null, "e": 3018, "s": 3003, "text": "jQuery-Methods" }, { "code": null, "e": 3035, "s": 3018, "text": "jQuery-Questions" }, { "code": null, "e": 3039, "s": 3035, "text": "CSS" }, { "code": null, "e": 3044, "s": 3039, "text": "HTML" }, { "code": null, "e": 3051, "s": 3044, "text": "JQuery" }, { "code": null, "e": 3068, "s": 3051, "text": "Web Technologies" }, { "code": null, "e": 3073, "s": 3068, "text": "HTML" } ]
How to completely remove node.js from Windows ?
19 May, 2022 We can completely remove Node.js from windows using the following simple steps: Step 1: Whenever we install a package with command npm install <package name>, npm stores the cache inside the user file system. The default directory where the cache data is stored on Windows is %AppData%/npm-cache. So, we need to clean the cache first. The cache can be cleaned by using the following command. npm cache clean --force Step 2: After that, you can verify the cache by using the below command: npm cache verify Step 3: Now open control panel in the computer. Search for Program and features. Under the program and features click on Uninstall a program. Now search for Node.js and uninstall it. Step 4: Restart your computer or kill all node-related processes from Task Manager. Step 5: Look for folder in your computer and if they are present remove them. The folders and files may or may not exist in your computer depending on various factors like installed version or CPU architecture. C:\Program Files (x86)\Nodejs C:\Program Files\Nodejs C:\Users\{User}\AppData\Roaming\npm or open run and type appdata and click ok and open roaming there you will find npm. C:\Users\{User}\AppData\Roaming\npm-cache or open run and type appdata and click ok and open roaming there you will find npm-cache. C:\Users\{User}\.npmrc C:\Users\{User}\package.json C:\Users\{User}\package-lock.json C:\Users\{User}\AppData\Local\Temp\npm-* Step 6: After that check the environment path variables and make sure no references to npm or Node.js exist. Step 7: If Node.js is still not uninstalled then open the command prompt and type the below command: where node Step 8: If Node.js is not uninstalled the command will output the location of Node.js. Go to that location and uninstall the directory. Step 9: Restart the computer. Node.js is now completely uninstalled. rajatnagarkar223 NodeJS-Questions Picked Technical Scripter 2020 Node.js Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Installation of Node.js on Windows JWT Authentication with Node.js Difference between dependencies, devDependencies and peerDependencies Mongoose Populate() Method Mongoose find() Function Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n19 May, 2022" }, { "code": null, "e": 108, "s": 28, "text": "We can completely remove Node.js from windows using the following simple steps:" }, { "code": null, "e": 420, "s": 108, "text": "Step 1: Whenever we install a package with command npm install <package name>, npm stores the cache inside the user file system. The default directory where the cache data is stored on Windows is %AppData%/npm-cache. So, we need to clean the cache first. The cache can be cleaned by using the following command." }, { "code": null, "e": 445, "s": 420, "text": "npm cache clean --force " }, { "code": null, "e": 518, "s": 445, "text": "Step 2: After that, you can verify the cache by using the below command:" }, { "code": null, "e": 535, "s": 518, "text": "npm cache verify" }, { "code": null, "e": 718, "s": 535, "text": "Step 3: Now open control panel in the computer. Search for Program and features. Under the program and features click on Uninstall a program. Now search for Node.js and uninstall it." }, { "code": null, "e": 802, "s": 718, "text": "Step 4: Restart your computer or kill all node-related processes from Task Manager." }, { "code": null, "e": 1013, "s": 802, "text": "Step 5: Look for folder in your computer and if they are present remove them. The folders and files may or may not exist in your computer depending on various factors like installed version or CPU architecture." }, { "code": null, "e": 1043, "s": 1013, "text": "C:\\Program Files (x86)\\Nodejs" }, { "code": null, "e": 1067, "s": 1043, "text": "C:\\Program Files\\Nodejs" }, { "code": null, "e": 1187, "s": 1067, "text": "C:\\Users\\{User}\\AppData\\Roaming\\npm or open run and type appdata and click ok and open roaming there you will find npm." }, { "code": null, "e": 1319, "s": 1187, "text": "C:\\Users\\{User}\\AppData\\Roaming\\npm-cache or open run and type appdata and click ok and open roaming there you will find npm-cache." }, { "code": null, "e": 1342, "s": 1319, "text": "C:\\Users\\{User}\\.npmrc" }, { "code": null, "e": 1371, "s": 1342, "text": "C:\\Users\\{User}\\package.json" }, { "code": null, "e": 1405, "s": 1371, "text": "C:\\Users\\{User}\\package-lock.json" }, { "code": null, "e": 1469, "s": 1405, "text": "C:\\Users\\{User}\\AppData\\Local\\Temp\\npm-* " }, { "code": null, "e": 1578, "s": 1469, "text": "Step 6: After that check the environment path variables and make sure no references to npm or Node.js exist." }, { "code": null, "e": 1679, "s": 1578, "text": "Step 7: If Node.js is still not uninstalled then open the command prompt and type the below command:" }, { "code": null, "e": 1690, "s": 1679, "text": "where node" }, { "code": null, "e": 1826, "s": 1690, "text": "Step 8: If Node.js is not uninstalled the command will output the location of Node.js. Go to that location and uninstall the directory." }, { "code": null, "e": 1895, "s": 1826, "text": "Step 9: Restart the computer. Node.js is now completely uninstalled." }, { "code": null, "e": 1912, "s": 1895, "text": "rajatnagarkar223" }, { "code": null, "e": 1929, "s": 1912, "text": "NodeJS-Questions" }, { "code": null, "e": 1936, "s": 1929, "text": "Picked" }, { "code": null, "e": 1960, "s": 1936, "text": "Technical Scripter 2020" }, { "code": null, "e": 1968, "s": 1960, "text": "Node.js" }, { "code": null, "e": 1987, "s": 1968, "text": "Technical Scripter" }, { "code": null, "e": 2004, "s": 1987, "text": "Web Technologies" }, { "code": null, "e": 2102, "s": 2004, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2137, "s": 2102, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 2169, "s": 2137, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 2239, "s": 2169, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 2266, "s": 2239, "text": "Mongoose Populate() Method" }, { "code": null, "e": 2291, "s": 2266, "text": "Mongoose find() Function" }, { "code": null, "e": 2353, "s": 2291, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2414, "s": 2353, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2464, "s": 2414, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2507, "s": 2464, "text": "How to fetch data from an API in ReactJS ?" } ]
Scaling techniques in Machine Learning
04 Dec, 2021 Definition: Scaling is a technique of generating an endless sequence of values, upon which the measured objects are placed. Several scaling techniques are employed to review the connection between the objects. Following are the two categories under scaling techniques: It involves the direct comparison of objects. Comparative scale data must be interpreted in corresponding terms and have either ordinal or rank order properties. Types of comparative scales are: 1. Paired comparison: This technique is a widely used comparative scaling technique. In this technique, the respondent is asked to pick one object among the two objects with the help of some criterion. The respondent makes a series of judgements between objects. The data obtained is ordinal in nature. With n brands, [n(n-1)/2] paired comparisons are required. For example: A survey was conducted to find out consumer’s preference for dark chocolate or white chocolate. The outcome was as follows: Dark chocolate= 30% White chocolate= 70% Thus, it is visible that consumers prefer white chocolate over dark chocolate. 2. Rank order: In this technique, the respondent judges one item against others. Respondent are present with several objects and are asked to rank or order them according to some criterion. Rank order scaling is also ordinal in nature. Only (n-1) scaling decisions need to be made in this technique. For example: A respondent is asked to rate the following soft drinks: 3. Constant sum scaling: In this technique, the respondent is assigned with the constant sum of units, such as 100 points to attributes of a product to reflect their importance. If the attribute is not important, the respondent assigns it 0 or no points. If an attribute is twice as important as another attribute, it receives twice as many points. The sum of all points is 100, that is, constant. Hence, the name of the scale. For example: A respondent is asked to spend 500 rupees on product A, product B and product C of foods? 4. Q sort: It is a sophisticated form of rank order. In this technique, a set of objects is given to an individual to sort into piles to specified rating categories. For example: A respondent is given 10 brands of shampoos and asked to place them in 2 piles, ranging from “most preferred” to “least preferred“. pile 1 Most preferred pile 2 Least preferred Note: Generally the most preferred shampoo is placed on the top while the least preferred at the bottom. In non-comparative scales, each object of the stimulus set is scaled independently of the others. The resulting data are generally assumed to be ratio scaled. Types of Non-comparative scales are: 1. Continuous rating scales: It is a graphic continuum typically coordinated by two extremes. The extreme values are not predefined. It can be constructed easily and is simple to use. The respondent rates by placing the mark on a continuous line. For example: A respondent is asked to rate the service of Domino’s: Type 1 Following are the two categories under scaling techniques: Type 2 2. Itemised rating scales: It is a graphic continuum typically coordinated by two extremes. It is simple to use and can be constructed easily. The respondent is provided with a scale that has a number or brief description associated with each category. The categories are ordered in terms of scale position, and therefore the respondents are required to pick the required category that best describes the object being rated. The different forms of Itemised rating scales are – a. Itemised graphic scale, b. Itemised verbal scale, c. Itemised numeric scale Types of Itemised rating scaling are: a. Likert scale: This scale requires the respondent to indicate a degree of agreement or disagreement with the statements mentions on the left side of the object. The analysis is often conducted on an item-by-item basis, or a total score can be calculated. When arriving at a total score, the categories assigned to the negative statements by the respondent is scored by reversing the scale. For example: A well-known shampoo brand carried out Likert scaling technique to find the agreement or disagreement for ayurvedic shampoo. Statement Strongly disagree Disagree Neither agree nor disagree Agree Strongly agree Ayurvedic shampoo helps in maintaining hair 1 2 3 4 5 Ayurvedic shampoo damage hair 5 4 3 2 1 Ayurvedic shampoo cleans your hair 5 4 3 2 1 b. Semantic differential scale: The semantic differential is a 7 point rating scale with endpoints related to bipolar labels. The negative words or phrase sometimes appears on the left side or sometimes right side. This controls the tendency of the respondents, particularly those with very positive and very negative attitudes, to mark the right or left sides without reading the labels. Individual items on a semantic differential scale could also be scored on either a -3 to +3 or 1 to 7 scale. For example: A well-known shoe brand carried out semantic differential scaling technique to find out customer’s opinion towards their product. c. Staple scale: It is a unipolar rating scale with 10 categories scaled from -5 to +5. It does not have a neutral point, that is, zero. It is represented vertically. For example: A well-known shoe brand carried out a staple scaling technique to find out costumer’s opinion towards their product. adnanirshad158 rajeev0719singh Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Monte Carlo Tree Search (MCTS) Introduction to Recurrent Neural Network Markov Decision Process Support Vector Machine Algorithm DBSCAN Clustering in ML | Density based clustering Bagging vs Boosting in Machine Learning Normalization vs Standardization Types of Environments in AI Principal Component Analysis with Python Difference between Informed and Uninformed Search in AI
[ { "code": null, "e": 53, "s": 25, "text": "\n04 Dec, 2021" }, { "code": null, "e": 263, "s": 53, "text": "Definition: Scaling is a technique of generating an endless sequence of values, upon which the measured objects are placed. Several scaling techniques are employed to review the connection between the objects." }, { "code": null, "e": 322, "s": 263, "text": "Following are the two categories under scaling techniques:" }, { "code": null, "e": 484, "s": 322, "text": "It involves the direct comparison of objects. Comparative scale data must be interpreted in corresponding terms and have either ordinal or rank order properties." }, { "code": null, "e": 517, "s": 484, "text": "Types of comparative scales are:" }, { "code": null, "e": 539, "s": 517, "text": "1. Paired comparison:" }, { "code": null, "e": 602, "s": 539, "text": "This technique is a widely used comparative scaling technique." }, { "code": null, "e": 719, "s": 602, "text": "In this technique, the respondent is asked to pick one object among the two objects with the help of some criterion." }, { "code": null, "e": 780, "s": 719, "text": "The respondent makes a series of judgements between objects." }, { "code": null, "e": 820, "s": 780, "text": "The data obtained is ordinal in nature." }, { "code": null, "e": 879, "s": 820, "text": "With n brands, [n(n-1)/2] paired comparisons are required." }, { "code": null, "e": 1016, "s": 879, "text": "For example: A survey was conducted to find out consumer’s preference for dark chocolate or white chocolate. The outcome was as follows:" }, { "code": null, "e": 1057, "s": 1016, "text": "Dark chocolate= 30%\nWhite chocolate= 70%" }, { "code": null, "e": 1136, "s": 1057, "text": "Thus, it is visible that consumers prefer white chocolate over dark chocolate." }, { "code": null, "e": 1151, "s": 1136, "text": "2. Rank order:" }, { "code": null, "e": 1217, "s": 1151, "text": "In this technique, the respondent judges one item against others." }, { "code": null, "e": 1326, "s": 1217, "text": "Respondent are present with several objects and are asked to rank or order them according to some criterion." }, { "code": null, "e": 1372, "s": 1326, "text": "Rank order scaling is also ordinal in nature." }, { "code": null, "e": 1436, "s": 1372, "text": "Only (n-1) scaling decisions need to be made in this technique." }, { "code": null, "e": 1506, "s": 1436, "text": "For example: A respondent is asked to rate the following soft drinks:" }, { "code": null, "e": 1531, "s": 1506, "text": "3. Constant sum scaling:" }, { "code": null, "e": 1684, "s": 1531, "text": "In this technique, the respondent is assigned with the constant sum of units, such as 100 points to attributes of a product to reflect their importance." }, { "code": null, "e": 1761, "s": 1684, "text": "If the attribute is not important, the respondent assigns it 0 or no points." }, { "code": null, "e": 1855, "s": 1761, "text": "If an attribute is twice as important as another attribute, it receives twice as many points." }, { "code": null, "e": 1934, "s": 1855, "text": "The sum of all points is 100, that is, constant. Hence, the name of the scale." }, { "code": null, "e": 2037, "s": 1934, "text": "For example: A respondent is asked to spend 500 rupees on product A, product B and product C of foods?" }, { "code": null, "e": 2048, "s": 2037, "text": "4. Q sort:" }, { "code": null, "e": 2090, "s": 2048, "text": "It is a sophisticated form of rank order." }, { "code": null, "e": 2203, "s": 2090, "text": "In this technique, a set of objects is given to an individual to sort into piles to specified rating categories." }, { "code": null, "e": 2348, "s": 2203, "text": "For example: A respondent is given 10 brands of shampoos and asked to place them in 2 piles, ranging from “most preferred” to “least preferred“." }, { "code": null, "e": 2355, "s": 2348, "text": "pile 1" }, { "code": null, "e": 2417, "s": 2355, "text": " Most preferred" }, { "code": null, "e": 2424, "s": 2417, "text": "pile 2" }, { "code": null, "e": 2487, "s": 2424, "text": " Least preferred" }, { "code": null, "e": 2592, "s": 2487, "text": "Note: Generally the most preferred shampoo is placed on the top while the least preferred at the bottom." }, { "code": null, "e": 2752, "s": 2592, "text": " In non-comparative scales, each object of the stimulus set is scaled independently of the others. The resulting data are generally assumed to be ratio scaled." }, { "code": null, "e": 2789, "s": 2752, "text": "Types of Non-comparative scales are:" }, { "code": null, "e": 2819, "s": 2789, "text": "1. Continuous rating scales: " }, { "code": null, "e": 2884, "s": 2819, "text": "It is a graphic continuum typically coordinated by two extremes." }, { "code": null, "e": 2923, "s": 2884, "text": "The extreme values are not predefined." }, { "code": null, "e": 2974, "s": 2923, "text": "It can be constructed easily and is simple to use." }, { "code": null, "e": 3037, "s": 2974, "text": "The respondent rates by placing the mark on a continuous line." }, { "code": null, "e": 3105, "s": 3037, "text": "For example: A respondent is asked to rate the service of Domino’s:" }, { "code": null, "e": 3112, "s": 3105, "text": "Type 1" }, { "code": null, "e": 3171, "s": 3112, "text": "Following are the two categories under scaling techniques:" }, { "code": null, "e": 3178, "s": 3171, "text": "Type 2" }, { "code": null, "e": 3207, "s": 3178, "text": "2. Itemised rating scales: " }, { "code": null, "e": 3272, "s": 3207, "text": "It is a graphic continuum typically coordinated by two extremes." }, { "code": null, "e": 3323, "s": 3272, "text": "It is simple to use and can be constructed easily." }, { "code": null, "e": 3433, "s": 3323, "text": "The respondent is provided with a scale that has a number or brief description associated with each category." }, { "code": null, "e": 3605, "s": 3433, "text": "The categories are ordered in terms of scale position, and therefore the respondents are required to pick the required category that best describes the object being rated." }, { "code": null, "e": 3736, "s": 3605, "text": "The different forms of Itemised rating scales are – a. Itemised graphic scale, b. Itemised verbal scale, c. Itemised numeric scale" }, { "code": null, "e": 3774, "s": 3736, "text": "Types of Itemised rating scaling are:" }, { "code": null, "e": 3792, "s": 3774, "text": "a. Likert scale: " }, { "code": null, "e": 3938, "s": 3792, "text": "This scale requires the respondent to indicate a degree of agreement or disagreement with the statements mentions on the left side of the object." }, { "code": null, "e": 4032, "s": 3938, "text": "The analysis is often conducted on an item-by-item basis, or a total score can be calculated." }, { "code": null, "e": 4167, "s": 4032, "text": "When arriving at a total score, the categories assigned to the negative statements by the respondent is scored by reversing the scale." }, { "code": null, "e": 4305, "s": 4167, "text": "For example: A well-known shampoo brand carried out Likert scaling technique to find the agreement or disagreement for ayurvedic shampoo." }, { "code": null, "e": 4315, "s": 4305, "text": "Statement" }, { "code": null, "e": 4333, "s": 4315, "text": "Strongly disagree" }, { "code": null, "e": 4343, "s": 4333, "text": " Disagree" }, { "code": null, "e": 4370, "s": 4343, "text": "Neither agree nor disagree" }, { "code": null, "e": 4376, "s": 4370, "text": "Agree" }, { "code": null, "e": 4391, "s": 4376, "text": "Strongly agree" }, { "code": null, "e": 4435, "s": 4391, "text": "Ayurvedic shampoo helps in maintaining hair" }, { "code": null, "e": 4437, "s": 4435, "text": "1" }, { "code": null, "e": 4439, "s": 4437, "text": "2" }, { "code": null, "e": 4441, "s": 4439, "text": "3" }, { "code": null, "e": 4443, "s": 4441, "text": "4" }, { "code": null, "e": 4445, "s": 4443, "text": "5" }, { "code": null, "e": 4475, "s": 4445, "text": "Ayurvedic shampoo damage hair" }, { "code": null, "e": 4477, "s": 4475, "text": "5" }, { "code": null, "e": 4479, "s": 4477, "text": "4" }, { "code": null, "e": 4481, "s": 4479, "text": "3" }, { "code": null, "e": 4483, "s": 4481, "text": "2" }, { "code": null, "e": 4485, "s": 4483, "text": "1" }, { "code": null, "e": 4521, "s": 4485, "text": "Ayurvedic shampoo cleans your hair " }, { "code": null, "e": 4523, "s": 4521, "text": "5" }, { "code": null, "e": 4525, "s": 4523, "text": "4" }, { "code": null, "e": 4527, "s": 4525, "text": "3" }, { "code": null, "e": 4529, "s": 4527, "text": "2" }, { "code": null, "e": 4531, "s": 4529, "text": "1" }, { "code": null, "e": 4564, "s": 4531, "text": "b. Semantic differential scale:" }, { "code": null, "e": 4658, "s": 4564, "text": "The semantic differential is a 7 point rating scale with endpoints related to bipolar labels." }, { "code": null, "e": 4747, "s": 4658, "text": "The negative words or phrase sometimes appears on the left side or sometimes right side." }, { "code": null, "e": 4921, "s": 4747, "text": "This controls the tendency of the respondents, particularly those with very positive and very negative attitudes, to mark the right or left sides without reading the labels." }, { "code": null, "e": 5030, "s": 4921, "text": "Individual items on a semantic differential scale could also be scored on either a -3 to +3 or 1 to 7 scale." }, { "code": null, "e": 5174, "s": 5030, "text": "For example: A well-known shoe brand carried out semantic differential scaling technique to find out customer’s opinion towards their product." }, { "code": null, "e": 5195, "s": 5178, "text": "c. Staple scale:" }, { "code": null, "e": 5266, "s": 5195, "text": "It is a unipolar rating scale with 10 categories scaled from -5 to +5." }, { "code": null, "e": 5315, "s": 5266, "text": "It does not have a neutral point, that is, zero." }, { "code": null, "e": 5345, "s": 5315, "text": "It is represented vertically." }, { "code": null, "e": 5475, "s": 5345, "text": "For example: A well-known shoe brand carried out a staple scaling technique to find out costumer’s opinion towards their product." }, { "code": null, "e": 5490, "s": 5475, "text": "adnanirshad158" }, { "code": null, "e": 5506, "s": 5490, "text": "rajeev0719singh" }, { "code": null, "e": 5523, "s": 5506, "text": "Machine Learning" }, { "code": null, "e": 5540, "s": 5523, "text": "Machine Learning" }, { "code": null, "e": 5638, "s": 5540, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5674, "s": 5638, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 5715, "s": 5674, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 5739, "s": 5715, "text": "Markov Decision Process" }, { "code": null, "e": 5772, "s": 5739, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 5823, "s": 5772, "text": "DBSCAN Clustering in ML | Density based clustering" }, { "code": null, "e": 5863, "s": 5823, "text": "Bagging vs Boosting in Machine Learning" }, { "code": null, "e": 5896, "s": 5863, "text": "Normalization vs Standardization" }, { "code": null, "e": 5924, "s": 5896, "text": "Types of Environments in AI" }, { "code": null, "e": 5965, "s": 5924, "text": "Principal Component Analysis with Python" } ]
Highlight the maximum value in each column in Pandas
28 Jul, 2020 Let’s discuss how to highlight the maximum values in Pandas Dataframe. Lets first make a dataframe: Example: Python3 # Import Required Librariesimport pandas as pdimport numpy as np # Create a dictionary for the dataframedict = {'Name': ['Sukritin', 'Sumit Tyagi', 'Akriti Goel', 'Sanskriti', 'Abhishek Jain'], 'Age': [22, 20, 45, 21, 22], 'Marks': [90, 84, 33, 87, 82]} # Converting Dictionary to Pandas Dataframedf = pd.DataFrame(dict) # Print Dataframedf Output: Now, come to the highlighting part. Our objective is to highlight cells with maximum values in each column. Method 1: Highlighting Cell with maximum value in each column We will do this by using the highlight_max() method of DataFrame property. highlight_max() method takes 3 arguments, subset = name of the columns of which you want to find the maximum, color = name of the color with which you want to highlight the cell and axis = (0/1) based on which axis you want find the maximum. Python3 # Highlighting the maximum values of# last 2 columnsdf.style.highlight_max(color = 'lightgreen', axis = 0) Output: Method 2: Highlighting the text instead of cell Python3 # Defining custom function which returns # the list for df.style.apply() methoddef highlight_max(s): is_max = s == s.max() return ['color: green' if cell else '' for cell in is_max] df.style.apply(highlight_max) Output: Method 3: Highlighting cell with maximum values Python3 # Defining custom function which returns # the list for df.style.apply() methoddef highlight_max(s): is_max = s == s.max() return ['background: lightgreen' if cell else '' for cell in is_max] df.style.apply(highlight_max) Output: Method 4: Highlighting cell with maximum values but not highlighting the string values Python3 # Defining custom function which returns# the list for df.style.apply() methoddef highlight_max(s): if s.dtype == np.object: is_max = [False for _ in range(s.shape[0])] else: is_max = s == s.max() return ['background: lightgreen' if cell else '' for cell in is_max] df.style.apply(highlight_max) Output: 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 iterate through Excel rows in Python? Enumerate() in Python Rotate axis tick labels in Seaborn and Matplotlib Deque in Python Stack in Python Queue in Python Defaultdict in Python Different ways to create Pandas Dataframe sum() function in Python Check if element exists in list in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jul, 2020" }, { "code": null, "e": 128, "s": 28, "text": "Let’s discuss how to highlight the maximum values in Pandas Dataframe. Lets first make a dataframe:" }, { "code": null, "e": 137, "s": 128, "text": "Example:" }, { "code": null, "e": 145, "s": 137, "text": "Python3" }, { "code": "# Import Required Librariesimport pandas as pdimport numpy as np # Create a dictionary for the dataframedict = {'Name': ['Sukritin', 'Sumit Tyagi', 'Akriti Goel', 'Sanskriti', 'Abhishek Jain'], 'Age': [22, 20, 45, 21, 22], 'Marks': [90, 84, 33, 87, 82]} # Converting Dictionary to Pandas Dataframedf = pd.DataFrame(dict) # Print Dataframedf", "e": 520, "s": 145, "text": null }, { "code": null, "e": 530, "s": 520, "text": "Output: " }, { "code": null, "e": 638, "s": 530, "text": "Now, come to the highlighting part. Our objective is to highlight cells with maximum values in each column." }, { "code": null, "e": 700, "s": 638, "text": "Method 1: Highlighting Cell with maximum value in each column" }, { "code": null, "e": 1018, "s": 700, "text": "We will do this by using the highlight_max() method of DataFrame property. highlight_max() method takes 3 arguments, subset = name of the columns of which you want to find the maximum, color = name of the color with which you want to highlight the cell and axis = (0/1) based on which axis you want find the maximum. " }, { "code": null, "e": 1026, "s": 1018, "text": "Python3" }, { "code": "# Highlighting the maximum values of# last 2 columnsdf.style.highlight_max(color = 'lightgreen', axis = 0)", "e": 1133, "s": 1026, "text": null }, { "code": null, "e": 1142, "s": 1133, "text": "Output: " }, { "code": null, "e": 1191, "s": 1142, "text": "Method 2: Highlighting the text instead of cell " }, { "code": null, "e": 1199, "s": 1191, "text": "Python3" }, { "code": "# Defining custom function which returns # the list for df.style.apply() methoddef highlight_max(s): is_max = s == s.max() return ['color: green' if cell else '' for cell in is_max] df.style.apply(highlight_max)", "e": 1418, "s": 1199, "text": null }, { "code": null, "e": 1427, "s": 1418, "text": "Output: " }, { "code": null, "e": 1476, "s": 1427, "text": "Method 3: Highlighting cell with maximum values " }, { "code": null, "e": 1484, "s": 1476, "text": "Python3" }, { "code": "# Defining custom function which returns # the list for df.style.apply() methoddef highlight_max(s): is_max = s == s.max() return ['background: lightgreen' if cell else '' for cell in is_max] df.style.apply(highlight_max)", "e": 1713, "s": 1484, "text": null }, { "code": null, "e": 1722, "s": 1713, "text": "Output: " }, { "code": null, "e": 1810, "s": 1722, "text": "Method 4: Highlighting cell with maximum values but not highlighting the string values " }, { "code": null, "e": 1818, "s": 1810, "text": "Python3" }, { "code": "# Defining custom function which returns# the list for df.style.apply() methoddef highlight_max(s): if s.dtype == np.object: is_max = [False for _ in range(s.shape[0])] else: is_max = s == s.max() return ['background: lightgreen' if cell else '' for cell in is_max] df.style.apply(highlight_max)", "e": 2138, "s": 1818, "text": null }, { "code": null, "e": 2146, "s": 2138, "text": "Output:" }, { "code": null, "e": 2171, "s": 2146, "text": "pandas-dataframe-program" }, { "code": null, "e": 2195, "s": 2171, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2209, "s": 2195, "text": "Python-pandas" }, { "code": null, "e": 2216, "s": 2209, "text": "Python" }, { "code": null, "e": 2314, "s": 2216, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2359, "s": 2314, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 2381, "s": 2359, "text": "Enumerate() in Python" }, { "code": null, "e": 2431, "s": 2381, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 2447, "s": 2431, "text": "Deque in Python" }, { "code": null, "e": 2463, "s": 2447, "text": "Stack in Python" }, { "code": null, "e": 2479, "s": 2463, "text": "Queue in Python" }, { "code": null, "e": 2501, "s": 2479, "text": "Defaultdict in Python" }, { "code": null, "e": 2543, "s": 2501, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2568, "s": 2543, "text": "sum() function in Python" } ]
Spring Boot | How to access database using Spring Data JPA
10 Jun, 2020 Spring Data JPA is a method to implement JPA repositories to add the data access layer in applications easily. CRUD stands for create, retrieve, update, delete which are the possible operations which can be performed in a database. In this article, we will see an example of how to access data from a database(MySQL for this article) in a spring boot application using spring data JPA. Inorder to learn how to create a spring boot project, refer this article. A database is a collection of inter-related data which helps in efficient retrieval, insertion and deletion of data from database and organizes the data in the form of tables, views, schemas, reports etc. So, for any application, database is one of the most important modules and there needs to be a way to communicate with it. Therefore, the following steps are followed in order to access the database using Spring Data JPA: Go to spring initializr and create a new project with the following dependencies:Spring WebSpring Data JPAMySQL DriverDownload the starter project and import it in the IDE.After the project syncs, we will create a model class Company with the annotation @Entity which means that this class is mapped to the table in the database. Add the data members with the data types the same as the columns in the database and generate constructor and getters. Add the annotation @Id to the data member which will behave as the primary key attribute in the table and @Generatedvalue(strategy = generationtype.auto) in order to auto increment the primary key attribute. The following is the implementation of this class:@Entitypublic class Company { // Primary ID which increments // automatically when new entry // is added into the database @Id @GeneratedValue(strategy = GenerationType.AUTO) int id; String name; // In months int duration; String profile; // Can be 0 int stipend; boolean workFromHome; public Company() { } // Parameterized constructor public Company(String name, int duration, String profile, int stipend, boolean workFromHome) { this.name = name; this.duration = duration; this.profile = profile; this.stipend = stipend; this.workFromHome = workFromHome; } // Getters and setters of // the variables public int getId() { return id; } public String getName() { return name; } public int getDuration() { return duration; } public String getProfile() { return profile; } public int getStipend() { return stipend; } public void setId(int id) { this.id = id; } public boolean isWorkFromHome() { return workFromHome; }Now, create an interface CompanyRepository with the annotation @Repository which will implement the CrudRepository. The functions to perform the CRUD operations will be defined in the interface as shown below:@Repositorypublic interface CompanyRepository extends CrudRepository<Company, Integer> { Company findById(int id); List<Company> findAll(); void deleteById(int id);}Note: The functions won’t be implemented as they are already implemented in the CrudRepository.Now, we will create REST APIs(GET, POST, PUT, DELETE) as shown below:@RestControllerpublic class CompanyController { @Autowired private CompanyRepository repo; // Home Page @GetMapping("/") public String welcome() { return "<html><body>" + "<h1>WELCOME</h1>" + "</body></html>"; } // Get All Notes @GetMapping("/company") public List<Company> getAllNotes() { return repo.findAll(); } // Get the company details by // ID @GetMapping("/company/{id}") public Company getCompanyById( @PathVariable(value = "id") int id) { return repo.findById(id); } @PostMapping("/company") @ResponseStatus(HttpStatus.CREATED) public Company addCompany( @RequestBody Company company) { return repo.save(company); } @DeleteMapping("/delete/{id}") public void deleteStudent( @PathVariable(value = "id") int id) { repo.deleteById(id); } @PutMapping("/company/{id}") public ResponseEntity<Object> updateStudent( @RequestBody Company company, @PathVariable int id) { Optional<Company> companyRepo = Optional.ofNullable( repo.findById(id)); if (!companyRepo.isPresent()) return ResponseEntity .notFound() .build(); company.setId(id); repo.save(company); return ResponseEntity .noContent() .build(); }Now, open the application.properties file and add the following code. Replace the database_name with the database containing the table Company, username with the username of mysql server(default is root) and password with the mysql password.spring.datasource.url=jdbc:mysql://localhost:3306/database_namespring.datasource.username=usernamespring.datasource.password=passwordspring.jpa.hibernate.ddl-auto=updateThis completes the process of establishing a connection with the database. Now, we build and run the project and call the different APIs.Note: Postman is usually preferred to test call APIs, hence we have used the postman tool to test the project. Go to spring initializr and create a new project with the following dependencies:Spring WebSpring Data JPAMySQL Driver Spring Web Spring Data JPA MySQL Driver Download the starter project and import it in the IDE. After the project syncs, we will create a model class Company with the annotation @Entity which means that this class is mapped to the table in the database. Add the data members with the data types the same as the columns in the database and generate constructor and getters. Add the annotation @Id to the data member which will behave as the primary key attribute in the table and @Generatedvalue(strategy = generationtype.auto) in order to auto increment the primary key attribute. The following is the implementation of this class:@Entitypublic class Company { // Primary ID which increments // automatically when new entry // is added into the database @Id @GeneratedValue(strategy = GenerationType.AUTO) int id; String name; // In months int duration; String profile; // Can be 0 int stipend; boolean workFromHome; public Company() { } // Parameterized constructor public Company(String name, int duration, String profile, int stipend, boolean workFromHome) { this.name = name; this.duration = duration; this.profile = profile; this.stipend = stipend; this.workFromHome = workFromHome; } // Getters and setters of // the variables public int getId() { return id; } public String getName() { return name; } public int getDuration() { return duration; } public String getProfile() { return profile; } public int getStipend() { return stipend; } public void setId(int id) { this.id = id; } public boolean isWorkFromHome() { return workFromHome; } @Entitypublic class Company { // Primary ID which increments // automatically when new entry // is added into the database @Id @GeneratedValue(strategy = GenerationType.AUTO) int id; String name; // In months int duration; String profile; // Can be 0 int stipend; boolean workFromHome; public Company() { } // Parameterized constructor public Company(String name, int duration, String profile, int stipend, boolean workFromHome) { this.name = name; this.duration = duration; this.profile = profile; this.stipend = stipend; this.workFromHome = workFromHome; } // Getters and setters of // the variables public int getId() { return id; } public String getName() { return name; } public int getDuration() { return duration; } public String getProfile() { return profile; } public int getStipend() { return stipend; } public void setId(int id) { this.id = id; } public boolean isWorkFromHome() { return workFromHome; } Now, create an interface CompanyRepository with the annotation @Repository which will implement the CrudRepository. The functions to perform the CRUD operations will be defined in the interface as shown below:@Repositorypublic interface CompanyRepository extends CrudRepository<Company, Integer> { Company findById(int id); List<Company> findAll(); void deleteById(int id);}Note: The functions won’t be implemented as they are already implemented in the CrudRepository. @Repositorypublic interface CompanyRepository extends CrudRepository<Company, Integer> { Company findById(int id); List<Company> findAll(); void deleteById(int id);} Note: The functions won’t be implemented as they are already implemented in the CrudRepository. Now, we will create REST APIs(GET, POST, PUT, DELETE) as shown below:@RestControllerpublic class CompanyController { @Autowired private CompanyRepository repo; // Home Page @GetMapping("/") public String welcome() { return "<html><body>" + "<h1>WELCOME</h1>" + "</body></html>"; } // Get All Notes @GetMapping("/company") public List<Company> getAllNotes() { return repo.findAll(); } // Get the company details by // ID @GetMapping("/company/{id}") public Company getCompanyById( @PathVariable(value = "id") int id) { return repo.findById(id); } @PostMapping("/company") @ResponseStatus(HttpStatus.CREATED) public Company addCompany( @RequestBody Company company) { return repo.save(company); } @DeleteMapping("/delete/{id}") public void deleteStudent( @PathVariable(value = "id") int id) { repo.deleteById(id); } @PutMapping("/company/{id}") public ResponseEntity<Object> updateStudent( @RequestBody Company company, @PathVariable int id) { Optional<Company> companyRepo = Optional.ofNullable( repo.findById(id)); if (!companyRepo.isPresent()) return ResponseEntity .notFound() .build(); company.setId(id); repo.save(company); return ResponseEntity .noContent() .build(); } @RestControllerpublic class CompanyController { @Autowired private CompanyRepository repo; // Home Page @GetMapping("/") public String welcome() { return "<html><body>" + "<h1>WELCOME</h1>" + "</body></html>"; } // Get All Notes @GetMapping("/company") public List<Company> getAllNotes() { return repo.findAll(); } // Get the company details by // ID @GetMapping("/company/{id}") public Company getCompanyById( @PathVariable(value = "id") int id) { return repo.findById(id); } @PostMapping("/company") @ResponseStatus(HttpStatus.CREATED) public Company addCompany( @RequestBody Company company) { return repo.save(company); } @DeleteMapping("/delete/{id}") public void deleteStudent( @PathVariable(value = "id") int id) { repo.deleteById(id); } @PutMapping("/company/{id}") public ResponseEntity<Object> updateStudent( @RequestBody Company company, @PathVariable int id) { Optional<Company> companyRepo = Optional.ofNullable( repo.findById(id)); if (!companyRepo.isPresent()) return ResponseEntity .notFound() .build(); company.setId(id); repo.save(company); return ResponseEntity .noContent() .build(); } Now, open the application.properties file and add the following code. Replace the database_name with the database containing the table Company, username with the username of mysql server(default is root) and password with the mysql password.spring.datasource.url=jdbc:mysql://localhost:3306/database_namespring.datasource.username=usernamespring.datasource.password=passwordspring.jpa.hibernate.ddl-auto=update spring.datasource.url=jdbc:mysql://localhost:3306/database_namespring.datasource.username=usernamespring.datasource.password=passwordspring.jpa.hibernate.ddl-auto=update This completes the process of establishing a connection with the database. Now, we build and run the project and call the different APIs.Note: Postman is usually preferred to test call APIs, hence we have used the postman tool to test the project. Note: Postman is usually preferred to test call APIs, hence we have used the postman tool to test the project. Output: The database: Testing with the POSTMAN collection: java-advanced Java-Spring mysql DBMS Java Web Technologies Java DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jun, 2020" }, { "code": null, "e": 414, "s": 28, "text": "Spring Data JPA is a method to implement JPA repositories to add the data access layer in applications easily. CRUD stands for create, retrieve, update, delete which are the possible operations which can be performed in a database. In this article, we will see an example of how to access data from a database(MySQL for this article) in a spring boot application using spring data JPA." }, { "code": null, "e": 488, "s": 414, "text": "Inorder to learn how to create a spring boot project, refer this article." }, { "code": null, "e": 915, "s": 488, "text": "A database is a collection of inter-related data which helps in efficient retrieval, insertion and deletion of data from database and organizes the data in the form of tables, views, schemas, reports etc. So, for any application, database is one of the most important modules and there needs to be a way to communicate with it. Therefore, the following steps are followed in order to access the database using Spring Data JPA:" }, { "code": null, "e": 5520, "s": 915, "text": "Go to spring initializr and create a new project with the following dependencies:Spring WebSpring Data JPAMySQL DriverDownload the starter project and import it in the IDE.After the project syncs, we will create a model class Company with the annotation @Entity which means that this class is mapped to the table in the database. Add the data members with the data types the same as the columns in the database and generate constructor and getters. Add the annotation @Id to the data member which will behave as the primary key attribute in the table and @Generatedvalue(strategy = generationtype.auto) in order to auto increment the primary key attribute. The following is the implementation of this class:@Entitypublic class Company { // Primary ID which increments // automatically when new entry // is added into the database @Id @GeneratedValue(strategy = GenerationType.AUTO) int id; String name; // In months int duration; String profile; // Can be 0 int stipend; boolean workFromHome; public Company() { } // Parameterized constructor public Company(String name, int duration, String profile, int stipend, boolean workFromHome) { this.name = name; this.duration = duration; this.profile = profile; this.stipend = stipend; this.workFromHome = workFromHome; } // Getters and setters of // the variables public int getId() { return id; } public String getName() { return name; } public int getDuration() { return duration; } public String getProfile() { return profile; } public int getStipend() { return stipend; } public void setId(int id) { this.id = id; } public boolean isWorkFromHome() { return workFromHome; }Now, create an interface CompanyRepository with the annotation @Repository which will implement the CrudRepository. The functions to perform the CRUD operations will be defined in the interface as shown below:@Repositorypublic interface CompanyRepository extends CrudRepository<Company, Integer> { Company findById(int id); List<Company> findAll(); void deleteById(int id);}Note: The functions won’t be implemented as they are already implemented in the CrudRepository.Now, we will create REST APIs(GET, POST, PUT, DELETE) as shown below:@RestControllerpublic class CompanyController { @Autowired private CompanyRepository repo; // Home Page @GetMapping(\"/\") public String welcome() { return \"<html><body>\" + \"<h1>WELCOME</h1>\" + \"</body></html>\"; } // Get All Notes @GetMapping(\"/company\") public List<Company> getAllNotes() { return repo.findAll(); } // Get the company details by // ID @GetMapping(\"/company/{id}\") public Company getCompanyById( @PathVariable(value = \"id\") int id) { return repo.findById(id); } @PostMapping(\"/company\") @ResponseStatus(HttpStatus.CREATED) public Company addCompany( @RequestBody Company company) { return repo.save(company); } @DeleteMapping(\"/delete/{id}\") public void deleteStudent( @PathVariable(value = \"id\") int id) { repo.deleteById(id); } @PutMapping(\"/company/{id}\") public ResponseEntity<Object> updateStudent( @RequestBody Company company, @PathVariable int id) { Optional<Company> companyRepo = Optional.ofNullable( repo.findById(id)); if (!companyRepo.isPresent()) return ResponseEntity .notFound() .build(); company.setId(id); repo.save(company); return ResponseEntity .noContent() .build(); }Now, open the application.properties file and add the following code. Replace the database_name with the database containing the table Company, username with the username of mysql server(default is root) and password with the mysql password.spring.datasource.url=jdbc:mysql://localhost:3306/database_namespring.datasource.username=usernamespring.datasource.password=passwordspring.jpa.hibernate.ddl-auto=updateThis completes the process of establishing a connection with the database. Now, we build and run the project and call the different APIs.Note: Postman is usually preferred to test call APIs, hence we have used the postman tool to test the project." }, { "code": null, "e": 5639, "s": 5520, "text": "Go to spring initializr and create a new project with the following dependencies:Spring WebSpring Data JPAMySQL Driver" }, { "code": null, "e": 5650, "s": 5639, "text": "Spring Web" }, { "code": null, "e": 5666, "s": 5650, "text": "Spring Data JPA" }, { "code": null, "e": 5679, "s": 5666, "text": "MySQL Driver" }, { "code": null, "e": 5734, "s": 5679, "text": "Download the starter project and import it in the IDE." }, { "code": null, "e": 7496, "s": 5734, "text": "After the project syncs, we will create a model class Company with the annotation @Entity which means that this class is mapped to the table in the database. Add the data members with the data types the same as the columns in the database and generate constructor and getters. Add the annotation @Id to the data member which will behave as the primary key attribute in the table and @Generatedvalue(strategy = generationtype.auto) in order to auto increment the primary key attribute. The following is the implementation of this class:@Entitypublic class Company { // Primary ID which increments // automatically when new entry // is added into the database @Id @GeneratedValue(strategy = GenerationType.AUTO) int id; String name; // In months int duration; String profile; // Can be 0 int stipend; boolean workFromHome; public Company() { } // Parameterized constructor public Company(String name, int duration, String profile, int stipend, boolean workFromHome) { this.name = name; this.duration = duration; this.profile = profile; this.stipend = stipend; this.workFromHome = workFromHome; } // Getters and setters of // the variables public int getId() { return id; } public String getName() { return name; } public int getDuration() { return duration; } public String getProfile() { return profile; } public int getStipend() { return stipend; } public void setId(int id) { this.id = id; } public boolean isWorkFromHome() { return workFromHome; }" }, { "code": "@Entitypublic class Company { // Primary ID which increments // automatically when new entry // is added into the database @Id @GeneratedValue(strategy = GenerationType.AUTO) int id; String name; // In months int duration; String profile; // Can be 0 int stipend; boolean workFromHome; public Company() { } // Parameterized constructor public Company(String name, int duration, String profile, int stipend, boolean workFromHome) { this.name = name; this.duration = duration; this.profile = profile; this.stipend = stipend; this.workFromHome = workFromHome; } // Getters and setters of // the variables public int getId() { return id; } public String getName() { return name; } public int getDuration() { return duration; } public String getProfile() { return profile; } public int getStipend() { return stipend; } public void setId(int id) { this.id = id; } public boolean isWorkFromHome() { return workFromHome; }", "e": 8723, "s": 7496, "text": null }, { "code": null, "e": 9233, "s": 8723, "text": "Now, create an interface CompanyRepository with the annotation @Repository which will implement the CrudRepository. The functions to perform the CRUD operations will be defined in the interface as shown below:@Repositorypublic interface CompanyRepository extends CrudRepository<Company, Integer> { Company findById(int id); List<Company> findAll(); void deleteById(int id);}Note: The functions won’t be implemented as they are already implemented in the CrudRepository." }, { "code": "@Repositorypublic interface CompanyRepository extends CrudRepository<Company, Integer> { Company findById(int id); List<Company> findAll(); void deleteById(int id);}", "e": 9439, "s": 9233, "text": null }, { "code": null, "e": 9535, "s": 9439, "text": "Note: The functions won’t be implemented as they are already implemented in the CrudRepository." }, { "code": null, "e": 11041, "s": 9535, "text": "Now, we will create REST APIs(GET, POST, PUT, DELETE) as shown below:@RestControllerpublic class CompanyController { @Autowired private CompanyRepository repo; // Home Page @GetMapping(\"/\") public String welcome() { return \"<html><body>\" + \"<h1>WELCOME</h1>\" + \"</body></html>\"; } // Get All Notes @GetMapping(\"/company\") public List<Company> getAllNotes() { return repo.findAll(); } // Get the company details by // ID @GetMapping(\"/company/{id}\") public Company getCompanyById( @PathVariable(value = \"id\") int id) { return repo.findById(id); } @PostMapping(\"/company\") @ResponseStatus(HttpStatus.CREATED) public Company addCompany( @RequestBody Company company) { return repo.save(company); } @DeleteMapping(\"/delete/{id}\") public void deleteStudent( @PathVariable(value = \"id\") int id) { repo.deleteById(id); } @PutMapping(\"/company/{id}\") public ResponseEntity<Object> updateStudent( @RequestBody Company company, @PathVariable int id) { Optional<Company> companyRepo = Optional.ofNullable( repo.findById(id)); if (!companyRepo.isPresent()) return ResponseEntity .notFound() .build(); company.setId(id); repo.save(company); return ResponseEntity .noContent() .build(); }" }, { "code": "@RestControllerpublic class CompanyController { @Autowired private CompanyRepository repo; // Home Page @GetMapping(\"/\") public String welcome() { return \"<html><body>\" + \"<h1>WELCOME</h1>\" + \"</body></html>\"; } // Get All Notes @GetMapping(\"/company\") public List<Company> getAllNotes() { return repo.findAll(); } // Get the company details by // ID @GetMapping(\"/company/{id}\") public Company getCompanyById( @PathVariable(value = \"id\") int id) { return repo.findById(id); } @PostMapping(\"/company\") @ResponseStatus(HttpStatus.CREATED) public Company addCompany( @RequestBody Company company) { return repo.save(company); } @DeleteMapping(\"/delete/{id}\") public void deleteStudent( @PathVariable(value = \"id\") int id) { repo.deleteById(id); } @PutMapping(\"/company/{id}\") public ResponseEntity<Object> updateStudent( @RequestBody Company company, @PathVariable int id) { Optional<Company> companyRepo = Optional.ofNullable( repo.findById(id)); if (!companyRepo.isPresent()) return ResponseEntity .notFound() .build(); company.setId(id); repo.save(company); return ResponseEntity .noContent() .build(); }", "e": 12478, "s": 11041, "text": null }, { "code": null, "e": 12889, "s": 12478, "text": "Now, open the application.properties file and add the following code. Replace the database_name with the database containing the table Company, username with the username of mysql server(default is root) and password with the mysql password.spring.datasource.url=jdbc:mysql://localhost:3306/database_namespring.datasource.username=usernamespring.datasource.password=passwordspring.jpa.hibernate.ddl-auto=update" }, { "code": null, "e": 13059, "s": 12889, "text": "spring.datasource.url=jdbc:mysql://localhost:3306/database_namespring.datasource.username=usernamespring.datasource.password=passwordspring.jpa.hibernate.ddl-auto=update" }, { "code": null, "e": 13307, "s": 13059, "text": "This completes the process of establishing a connection with the database. Now, we build and run the project and call the different APIs.Note: Postman is usually preferred to test call APIs, hence we have used the postman tool to test the project." }, { "code": null, "e": 13418, "s": 13307, "text": "Note: Postman is usually preferred to test call APIs, hence we have used the postman tool to test the project." }, { "code": null, "e": 13426, "s": 13418, "text": "Output:" }, { "code": null, "e": 13440, "s": 13426, "text": "The database:" }, { "code": null, "e": 13477, "s": 13440, "text": "Testing with the POSTMAN collection:" }, { "code": null, "e": 13491, "s": 13477, "text": "java-advanced" }, { "code": null, "e": 13503, "s": 13491, "text": "Java-Spring" }, { "code": null, "e": 13509, "s": 13503, "text": "mysql" }, { "code": null, "e": 13514, "s": 13509, "text": "DBMS" }, { "code": null, "e": 13519, "s": 13514, "text": "Java" }, { "code": null, "e": 13536, "s": 13519, "text": "Web Technologies" }, { "code": null, "e": 13541, "s": 13536, "text": "Java" }, { "code": null, "e": 13546, "s": 13541, "text": "DBMS" } ]
How to add two complex numbers by passing structure to a function in C language?
In order to add two complex numbers in C programming language, the user has to take two complex numbers as structure members and perform addition operation on those two numbers by creating a user-defined function. Refer an algorithm given below for addition of two complex numbers. Step 1: Declare struct complex with data members. Step 2: Declare name for structure and variables. Step 3: Enter real and imaginary part for first complex number at run time. Step 4: Enter real and imaginary part for second complex number at runtime Step 5: Compute addition of number1 and number2 by calling function. Go to step 7. Step 6: Print the result. Step 7: Compute addition Declare temp variabletemp.real = num1.real + num2.real;temp.imag = num1.imag + num2.imag;return (temp); Declare temp variable temp.real = num1.real + num2.real; temp.imag = num1.imag + num2.imag; return (temp); Following is the C program for adding two complex numbers by passing structure to a function − Live Demo #include <stdio.h> typedef struct complex{ float real; float imag; } complex; complex addition(complex num1, complex num2); int main(){ complex num1, num2, value; printf("entering real and imag parts of first complex no:\n "); scanf("%f %f", &num1.real, &num1.imag); printf("entering real and imag parts of second complex no:\n "); scanf("%f %f", &num2.real, &num2.imag); value= addition(num1, num2); printf("result = %.1f + %.1fi", value.real, value.imag); return 0; } complex addition(complex num1, complex num2){ complex temp; temp.real = num1.real + num2.real; temp.imag = num1.imag + num2.imag; return (temp); } When the above program is executed, it produces the following result − entering real and imag parts of first complex no: entering real and imag parts of second complex no: result = 0.0 + 0.0i
[ { "code": null, "e": 1401, "s": 1187, "text": "In order to add two complex numbers in C programming language, the user has to take two complex numbers as structure members and perform addition operation on those two numbers by creating a user-defined function." }, { "code": null, "e": 1469, "s": 1401, "text": "Refer an algorithm given below for addition of two complex numbers." }, { "code": null, "e": 1958, "s": 1469, "text": "Step 1: Declare struct complex with data members.\nStep 2: Declare name for structure and variables.\nStep 3: Enter real and imaginary part for first complex number at run time.\nStep 4: Enter real and imaginary part for second complex number at runtime\nStep 5: Compute addition of number1 and number2 by calling function. Go to step 7.\nStep 6: Print the result.\nStep 7: Compute addition\nDeclare temp variabletemp.real = num1.real + num2.real;temp.imag = num1.imag + num2.imag;return (temp);" }, { "code": null, "e": 1980, "s": 1958, "text": "Declare temp variable" }, { "code": null, "e": 2015, "s": 1980, "text": "temp.real = num1.real + num2.real;" }, { "code": null, "e": 2050, "s": 2015, "text": "temp.imag = num1.imag + num2.imag;" }, { "code": null, "e": 2065, "s": 2050, "text": "return (temp);" }, { "code": null, "e": 2160, "s": 2065, "text": "Following is the C program for adding two complex numbers by passing structure to a function −" }, { "code": null, "e": 2171, "s": 2160, "text": " Live Demo" }, { "code": null, "e": 2830, "s": 2171, "text": "#include <stdio.h>\ntypedef struct complex{\n float real;\n float imag;\n} complex;\ncomplex addition(complex num1, complex num2);\nint main(){\n complex num1, num2, value;\n printf(\"entering real and imag parts of first complex no:\\n \");\n scanf(\"%f %f\", &num1.real, &num1.imag);\n printf(\"entering real and imag parts of second complex no:\\n \");\n scanf(\"%f %f\", &num2.real, &num2.imag);\n value= addition(num1, num2);\n printf(\"result = %.1f + %.1fi\", value.real, value.imag);\n return 0;\n}\ncomplex addition(complex num1, complex num2){\n complex temp;\n temp.real = num1.real + num2.real;\n temp.imag = num1.imag + num2.imag;\n return (temp);\n}" }, { "code": null, "e": 2901, "s": 2830, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 3022, "s": 2901, "text": "entering real and imag parts of first complex no:\nentering real and imag parts of second complex no:\nresult = 0.0 + 0.0i" } ]
How to set Scrollbar in TextBox in C#?
29 Nov, 2019 In Windows forms, TextBox plays an important role. With the help of TextBox, the user can enter data in the application, it can be of a single line or of multiple lines. In TextBox, you are allowed to set scrollbars when you are working with multiline TextBox with the help of ScrollBars property of the TextBox. The default value of this property is in Windows form, you can set this property in two different ways: 1. Design-Time: It is the simplest way to set the ScrollBars property of the TextBox as shown in the following steps: Step 1: Create a windows form.Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Drag the TextBox control from the ToolBox and Drop it on the windows form. You can place TextBox anywhere on the windows form according to your need. As shown in the below image: Step 3: After drag and drop you will go to the properties of the TextBox control to set the ScrollBars property of the TextBox.Output: Output: Note: Please remember the horizontal scroll bars will not be shown if the WordWrap property is set to true, regardless of the value of the ScrollBars property. 2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the ScrollBars property of the TextBox programmatically with the help of given syntax: public System.Windows.Forms.ScrollBars ScrollBars { get; set; } Here, the ScrollBars represent the ScrollBars enumeration values that indicate whether a multiline TextBox control appears with no scroll bars, a horizontal scroll bar, a vertical scroll bar, or both. And it will throw an InvalidEnumArgumentException if the value that is assigned to the property is not within the range of valid values for the enumeration. Following steps are used to set the ScrollBars property of the TextBox: Step 1 : Create a textbox using the TextBox() constructor provided by the TextBox class.// Creating textbox TextBox Mytextbox = new TextBox(); // Creating textbox TextBox Mytextbox = new TextBox(); Step 2 : After creating TextBox, set the ScrollBars property of the TextBox provided by the TextBox class.// Set ScrollBars property Mytextbox.ScrollBars = ScrollBars.Vertical; // Set ScrollBars property Mytextbox.ScrollBars = ScrollBars.Vertical; Step 3 : And last add this textbox control to from using Add() method.// Add this textbox to form this.Controls.Add(Mytextbox); Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel = new Label(); Mylablel.Location = new Point(96, 54); Mylablel.Text = "Introduction"; Mylablel.AutoSize = true; Mylablel.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel); // Creating and setting the properties of TextBox1 TextBox Mytextbox = new TextBox(); Mytextbox.Location = new Point(187, 51); Mytextbox.BackColor = Color.LightGray; Mytextbox.ForeColor = Color.DarkOliveGreen; Mytextbox.Height = 100; Mytextbox.Width = 200; Mytextbox.Name = "text_box1"; Mytextbox.Multiline = true; Mytextbox.ScrollBars = ScrollBars.Vertical; // Add this textbox to form this.Controls.Add(Mytextbox); }}}Output: // Add this textbox to form this.Controls.Add(Mytextbox); Example: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel = new Label(); Mylablel.Location = new Point(96, 54); Mylablel.Text = "Introduction"; Mylablel.AutoSize = true; Mylablel.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel); // Creating and setting the properties of TextBox1 TextBox Mytextbox = new TextBox(); Mytextbox.Location = new Point(187, 51); Mytextbox.BackColor = Color.LightGray; Mytextbox.ForeColor = Color.DarkOliveGreen; Mytextbox.Height = 100; Mytextbox.Width = 200; Mytextbox.Name = "text_box1"; Mytextbox.Multiline = true; Mytextbox.ScrollBars = ScrollBars.Vertical; // Add this textbox to form this.Controls.Add(Mytextbox); }}} Output: CSharp-Windows-Forms-Namespace C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Nov, 2019" }, { "code": null, "e": 445, "s": 28, "text": "In Windows forms, TextBox plays an important role. With the help of TextBox, the user can enter data in the application, it can be of a single line or of multiple lines. In TextBox, you are allowed to set scrollbars when you are working with multiline TextBox with the help of ScrollBars property of the TextBox. The default value of this property is in Windows form, you can set this property in two different ways:" }, { "code": null, "e": 563, "s": 445, "text": "1. Design-Time: It is the simplest way to set the ScrollBars property of the TextBox as shown in the following steps:" }, { "code": null, "e": 651, "s": 563, "text": "Step 1: Create a windows form.Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 838, "s": 651, "text": "Step 2: Drag the TextBox control from the ToolBox and Drop it on the windows form. You can place TextBox anywhere on the windows form according to your need. As shown in the below image:" }, { "code": null, "e": 973, "s": 838, "text": "Step 3: After drag and drop you will go to the properties of the TextBox control to set the ScrollBars property of the TextBox.Output:" }, { "code": null, "e": 981, "s": 973, "text": "Output:" }, { "code": null, "e": 1141, "s": 981, "text": "Note: Please remember the horizontal scroll bars will not be shown if the WordWrap property is set to true, regardless of the value of the ScrollBars property." }, { "code": null, "e": 1320, "s": 1141, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the ScrollBars property of the TextBox programmatically with the help of given syntax:" }, { "code": null, "e": 1384, "s": 1320, "text": "public System.Windows.Forms.ScrollBars ScrollBars { get; set; }" }, { "code": null, "e": 1814, "s": 1384, "text": "Here, the ScrollBars represent the ScrollBars enumeration values that indicate whether a multiline TextBox control appears with no scroll bars, a horizontal scroll bar, a vertical scroll bar, or both. And it will throw an InvalidEnumArgumentException if the value that is assigned to the property is not within the range of valid values for the enumeration. Following steps are used to set the ScrollBars property of the TextBox:" }, { "code": null, "e": 1958, "s": 1814, "text": "Step 1 : Create a textbox using the TextBox() constructor provided by the TextBox class.// Creating textbox\nTextBox Mytextbox = new TextBox();\n" }, { "code": null, "e": 2014, "s": 1958, "text": "// Creating textbox\nTextBox Mytextbox = new TextBox();\n" }, { "code": null, "e": 2192, "s": 2014, "text": "Step 2 : After creating TextBox, set the ScrollBars property of the TextBox provided by the TextBox class.// Set ScrollBars property\nMytextbox.ScrollBars = ScrollBars.Vertical;\n" }, { "code": null, "e": 2264, "s": 2192, "text": "// Set ScrollBars property\nMytextbox.ScrollBars = ScrollBars.Vertical;\n" }, { "code": null, "e": 3627, "s": 2264, "text": "Step 3 : And last add this textbox control to from using Add() method.// Add this textbox to form\nthis.Controls.Add(Mytextbox);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel = new Label(); Mylablel.Location = new Point(96, 54); Mylablel.Text = \"Introduction\"; Mylablel.AutoSize = true; Mylablel.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel); // Creating and setting the properties of TextBox1 TextBox Mytextbox = new TextBox(); Mytextbox.Location = new Point(187, 51); Mytextbox.BackColor = Color.LightGray; Mytextbox.ForeColor = Color.DarkOliveGreen; Mytextbox.Height = 100; Mytextbox.Width = 200; Mytextbox.Name = \"text_box1\"; Mytextbox.Multiline = true; Mytextbox.ScrollBars = ScrollBars.Vertical; // Add this textbox to form this.Controls.Add(Mytextbox); }}}Output:" }, { "code": null, "e": 3686, "s": 3627, "text": "// Add this textbox to form\nthis.Controls.Add(Mytextbox);\n" }, { "code": null, "e": 3695, "s": 3686, "text": "Example:" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel = new Label(); Mylablel.Location = new Point(96, 54); Mylablel.Text = \"Introduction\"; Mylablel.AutoSize = true; Mylablel.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel); // Creating and setting the properties of TextBox1 TextBox Mytextbox = new TextBox(); Mytextbox.Location = new Point(187, 51); Mytextbox.BackColor = Color.LightGray; Mytextbox.ForeColor = Color.DarkOliveGreen; Mytextbox.Height = 100; Mytextbox.Width = 200; Mytextbox.Name = \"text_box1\"; Mytextbox.Multiline = true; Mytextbox.ScrollBars = ScrollBars.Vertical; // Add this textbox to form this.Controls.Add(Mytextbox); }}}", "e": 4915, "s": 3695, "text": null }, { "code": null, "e": 4923, "s": 4915, "text": "Output:" }, { "code": null, "e": 4954, "s": 4923, "text": "CSharp-Windows-Forms-Namespace" }, { "code": null, "e": 4957, "s": 4954, "text": "C#" } ]
C program to calculate distance between two points
Given with the two points coordinates and the task is to find the distance between two points and display the result. In a two dimension plane there are two points let’s say A and B with the respective coordinates as (x1, y1) and (x2, y2) and to calculate the distance between them there is a direct formula which is given below ⟮x2−x1⟯2+⟮y2−y1⟯2Given below is the diagram representing two points and their differences(x2−x1)(x1,y1)(y2−y1)(x2,y2)Approach used below is as follows −Input the coordinates as x1, x2, y1 and y2Apply the formula to compute the difference between two pointsPrint the distanceAlgorithmStart Step 1-> declare function to calculate distance between two point void three_dis(float x1, float y1, float x2, float y2) set float dis = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2) * 1.0) print dis step 2-> In main() Set float x1 = 4 Set float y1 = 9 Set float x2 = 5 Set float y2 = 10 Call two_dis(x1, y1, x2, y2) StopExample#include <stdio.h> #include<math.h> //function to find distance bewteen 2 points void two_dis(float x1, float y1, float x2, float y2) { float dis = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2) * 1.0); printf("Distance between 2 points are : %f", dis); return; } int main() { float x1 = 4; float y1 = 9; float x2 = 5; float y2 = 10; two_dis(x1, y1, x2, y2); return 0; }OutputIF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUTDistance between 2 points are : 1.414214 Sunidhi Bansal Updated on 18-Oct-2019 11:10:35
[ { "code": null, "e": 1305, "s": 1187, "text": "Given with the two points coordinates and the task is to find the distance between two points and display the result." }, { "code": null, "e": 1516, "s": 1305, "text": "In a two dimension plane there are two points let’s say A and B with the respective coordinates as (x1, y1) and (x2, y2) and to calculate the distance between them there is a direct formula which is given below" } ]
How to Create Table in Hive?
04 Nov, 2020 In Apache Hive we can create tables to store structured data so that later on we can process it. The table in the hive is consists of multiple columns and records. The table we create in any database will be stored in the sub-directory of that database. The default location where the database is stored on HDFS is /user/hive/warehouse. The way of creating tables in the hive is very much similar to the way we create tables in SQL. We can perform the various operations with these tables like Joins, Filtering, etc. To perform the below operation make sure your hive is running. Below are the steps to launch a hive on your local system. Step 1: Start all your Hadoop Daemon start-dfs.sh # this will start namenode, datanode and secondary namenode start-yarn.sh # this will start node manager and resource manager jps # To check running daemons Step 2: Launch hive from terminal hive Let’s create a database first so that we can create tables inside it. The command for creating a database is shown below. Syntax To Make Database: CREATE DATABASE <database-name>; Command: CREATE DATABASE student_detail; # this will create database student_detail SHOW DATABASES; # list down all the available databases Now, to have access to this database we have to use it. Syntax: USE <database-name>; Command: USE student_detail; Syntax To Create Table in Hive CREATE TABLE [IF NOT EXISTS] <table-name> ( <column-name> <data-type>, <column-name> <data-type> COMMENT 'Your Comment', <column-name> <data-type>, . . . <column-name> <data-type> ) COMMENT 'Add if you want' LOCATION 'Location On HDFS' ROW FORMAT DELIMITED FIELDS TERMINATED BY ','; Note: 1. We can add a comment to the table as well as to each individual column. 2. ROW FORMAT DELIMITED shows that whenever a new line is encountered the new record entry will start. 3. FIELDS TERMINATED BY ‘,’ shows that we are using ‘,’ delimiter to separate each column. 4. We can also override the default database location with the LOCATION option. So let’s create the table student_data in our student_detail database with the help of the command shown below. CREATE TABLE IF NOT EXISTS student_data( Student_Name STRING COMMENT 'This col. Store the name of student', Student_Rollno INT COMMENT 'This col. Stores the rollno of student', Student_Marks FLOAT) ROW FORMAT DELIMITED FIELDS TERMINATED BY ','; We have successfully created the table student_data in our student_detail database with 3 different fields Student_Name, Student_Rollno, Student_Marks as STRING, INT, FLOAT respectively. We can list down the table available in our database with the help of the command explained below. Syntax: SHOW TABLES [IN <database_name>]; Command: SHOW TABLES IN student_detail; Now, Finally, let’s check the location on HDFS where our student_detail database and student_data table is made. Move to localhost:50070/ for Hadoop 2 and to localhost:9870/ for Hadoop 3. Then Utilities -> Browse the file system and go to /user/hive/warehouse which is a default location where hive databases are created. In the above image, we can observe that the student_data table is available in HDFS inside student_detail.db. Apache-Hive Hadoop Hadoop Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference Between Hadoop and Spark Hadoop Streaming Using Python - Word Count Problem Architecture of HBase Hadoop - Different Modes of Operation What is Big Data? Architecture and Working of Hive Applications of Big Data Introduction to Apache Pig What is Schema On Read and Schema On Write in Hadoop? What is Hadoop Streaming?
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Nov, 2020" }, { "code": null, "e": 570, "s": 52, "text": "In Apache Hive we can create tables to store structured data so that later on we can process it. The table in the hive is consists of multiple columns and records. The table we create in any database will be stored in the sub-directory of that database. The default location where the database is stored on HDFS is /user/hive/warehouse. The way of creating tables in the hive is very much similar to the way we create tables in SQL. We can perform the various operations with these tables like Joins, Filtering, etc. " }, { "code": null, "e": 692, "s": 570, "text": "To perform the below operation make sure your hive is running. Below are the steps to launch a hive on your local system." }, { "code": null, "e": 729, "s": 692, "text": "Step 1: Start all your Hadoop Daemon" }, { "code": null, "e": 969, "s": 729, "text": "start-dfs.sh # this will start namenode, datanode and secondary namenode\n\nstart-yarn.sh # this will start node manager and resource manager \n\njps # To check running daemons\n" }, { "code": null, "e": 1003, "s": 969, "text": "Step 2: Launch hive from terminal" }, { "code": null, "e": 1009, "s": 1003, "text": "hive\n" }, { "code": null, "e": 1131, "s": 1009, "text": "Let’s create a database first so that we can create tables inside it. The command for creating a database is shown below." }, { "code": null, "e": 1156, "s": 1131, "text": "Syntax To Make Database:" }, { "code": null, "e": 1190, "s": 1156, "text": "CREATE DATABASE <database-name>;\n" }, { "code": null, "e": 1199, "s": 1190, "text": "Command:" }, { "code": null, "e": 1352, "s": 1199, "text": "CREATE DATABASE student_detail; # this will create database student_detail\n\nSHOW DATABASES; # list down all the available databases\n" }, { "code": null, "e": 1408, "s": 1352, "text": "Now, to have access to this database we have to use it." }, { "code": null, "e": 1416, "s": 1408, "text": "Syntax:" }, { "code": null, "e": 1438, "s": 1416, "text": "USE <database-name>;\n" }, { "code": null, "e": 1447, "s": 1438, "text": "Command:" }, { "code": null, "e": 1468, "s": 1447, "text": "USE student_detail;\n" }, { "code": null, "e": 1499, "s": 1468, "text": "Syntax To Create Table in Hive" }, { "code": null, "e": 1795, "s": 1499, "text": "CREATE TABLE [IF NOT EXISTS] <table-name> (\n<column-name> <data-type>,\n<column-name> <data-type> COMMENT 'Your Comment',\n<column-name> <data-type>,\n.\n.\n.\n<column-name> <data-type>\n)\nCOMMENT 'Add if you want'\nLOCATION 'Location On HDFS'\nROW FORMAT DELIMITED\nFIELDS TERMINATED BY ',';\n" }, { "code": null, "e": 1801, "s": 1795, "text": "Note:" }, { "code": null, "e": 1876, "s": 1801, "text": "1. We can add a comment to the table as well as to each individual column." }, { "code": null, "e": 1980, "s": 1876, "text": "2. ROW FORMAT DELIMITED shows that whenever a new line is encountered the new record entry will start. " }, { "code": null, "e": 2072, "s": 1980, "text": "3. FIELDS TERMINATED BY ‘,’ shows that we are using ‘,’ delimiter to separate each column. " }, { "code": null, "e": 2152, "s": 2072, "text": "4. We can also override the default database location with the LOCATION option." }, { "code": null, "e": 2264, "s": 2152, "text": "So let’s create the table student_data in our student_detail database with the help of the command shown below." }, { "code": null, "e": 2512, "s": 2264, "text": "CREATE TABLE IF NOT EXISTS student_data(\nStudent_Name STRING COMMENT 'This col. Store the name of student', \nStudent_Rollno INT COMMENT 'This col. Stores the rollno of student',\nStudent_Marks FLOAT)\nROW FORMAT DELIMITED\nFIELDS TERMINATED BY ','; \n" }, { "code": null, "e": 2699, "s": 2512, "text": "We have successfully created the table student_data in our student_detail database with 3 different fields Student_Name, Student_Rollno, Student_Marks as STRING, INT, FLOAT respectively." }, { "code": null, "e": 2798, "s": 2699, "text": "We can list down the table available in our database with the help of the command explained below." }, { "code": null, "e": 2806, "s": 2798, "text": "Syntax:" }, { "code": null, "e": 2841, "s": 2806, "text": "SHOW TABLES [IN <database_name>];\n" }, { "code": null, "e": 2850, "s": 2841, "text": "Command:" }, { "code": null, "e": 2882, "s": 2850, "text": "SHOW TABLES IN student_detail;\n" }, { "code": null, "e": 3205, "s": 2882, "text": "Now, Finally, let’s check the location on HDFS where our student_detail database and student_data table is made. Move to localhost:50070/ for Hadoop 2 and to localhost:9870/ for Hadoop 3. Then Utilities -> Browse the file system and go to /user/hive/warehouse which is a default location where hive databases are created." }, { "code": null, "e": 3315, "s": 3205, "text": "In the above image, we can observe that the student_data table is available in HDFS inside student_detail.db." }, { "code": null, "e": 3327, "s": 3315, "text": "Apache-Hive" }, { "code": null, "e": 3334, "s": 3327, "text": "Hadoop" }, { "code": null, "e": 3341, "s": 3334, "text": "Hadoop" }, { "code": null, "e": 3439, "s": 3341, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3475, "s": 3439, "text": "Difference Between Hadoop and Spark" }, { "code": null, "e": 3526, "s": 3475, "text": "Hadoop Streaming Using Python - Word Count Problem" }, { "code": null, "e": 3548, "s": 3526, "text": "Architecture of HBase" }, { "code": null, "e": 3586, "s": 3548, "text": "Hadoop - Different Modes of Operation" }, { "code": null, "e": 3604, "s": 3586, "text": "What is Big Data?" }, { "code": null, "e": 3637, "s": 3604, "text": "Architecture and Working of Hive" }, { "code": null, "e": 3662, "s": 3637, "text": "Applications of Big Data" }, { "code": null, "e": 3689, "s": 3662, "text": "Introduction to Apache Pig" }, { "code": null, "e": 3743, "s": 3689, "text": "What is Schema On Read and Schema On Write in Hadoop?" } ]
Python | os.readlink() method
29 Jun, 2019 OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system. os.readlink() method in Python is used to resolve a symbolic link. This method returns the path to which symbolic link points. Syntax: os.readlink(path, *, dir_fd = None) Parameter:path: A path-like object representing a file path. A path-like object is either a string or bytes object representing a path.dir_fd (optional) : A file descriptor referring to a directory. The default value of this parameter is None.If the specified path is absolute then dir_fd is ignored. Note: The ‘*’ in parameter list indicates that all following parameters (Here in our case ‘dir_fd’) are keyword-only parameters and they can be provided using their name, not as positional parameter. Return Type: This method return a string object if the specified path is also a string object and a byte object if the specified path is a byte object. The returned value represents the path to which symbolic link points. # Python program to explain os.readlink() method # importing os module import os # Original file pathpath = "/home/ihritik/Documents/file.txt" # Create a symbolic link# of above path # using os.symlink() methodlink = "/home/ihritik/Desktop/file(symlink).txt"os.symlink(path, link) # So, link is a symbolic link# Now using os.readlink() method# resolve the symbolic linkoriginalPath = os.readlink(link) # print the path to which# symbolic link pointsprint("Symbolic link points to", originalPath) # If the given path is not a# symbolic link then # os.readlink() method will# raise an OSError Symbolic link points to /home/ihritik/Documents/file.txt Reference: https://docs.python.org/3/library/os.html python-os-module 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": "\n29 Jun, 2019" }, { "code": null, "e": 247, "s": 28, "text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality." }, { "code": null, "e": 442, "s": 247, "text": "All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system." }, { "code": null, "e": 569, "s": 442, "text": "os.readlink() method in Python is used to resolve a symbolic link. This method returns the path to which symbolic link points." }, { "code": null, "e": 613, "s": 569, "text": "Syntax: os.readlink(path, *, dir_fd = None)" }, { "code": null, "e": 914, "s": 613, "text": "Parameter:path: A path-like object representing a file path. A path-like object is either a string or bytes object representing a path.dir_fd (optional) : A file descriptor referring to a directory. The default value of this parameter is None.If the specified path is absolute then dir_fd is ignored." }, { "code": null, "e": 1114, "s": 914, "text": "Note: The ‘*’ in parameter list indicates that all following parameters (Here in our case ‘dir_fd’) are keyword-only parameters and they can be provided using their name, not as positional parameter." }, { "code": null, "e": 1336, "s": 1114, "text": "Return Type: This method return a string object if the specified path is also a string object and a byte object if the specified path is a byte object. The returned value represents the path to which symbolic link points." }, { "code": "# Python program to explain os.readlink() method # importing os module import os # Original file pathpath = \"/home/ihritik/Documents/file.txt\" # Create a symbolic link# of above path # using os.symlink() methodlink = \"/home/ihritik/Desktop/file(symlink).txt\"os.symlink(path, link) # So, link is a symbolic link# Now using os.readlink() method# resolve the symbolic linkoriginalPath = os.readlink(link) # print the path to which# symbolic link pointsprint(\"Symbolic link points to\", originalPath) # If the given path is not a# symbolic link then # os.readlink() method will# raise an OSError", "e": 1942, "s": 1336, "text": null }, { "code": null, "e": 2000, "s": 1942, "text": "Symbolic link points to /home/ihritik/Documents/file.txt\n" }, { "code": null, "e": 2053, "s": 2000, "text": "Reference: https://docs.python.org/3/library/os.html" }, { "code": null, "e": 2070, "s": 2053, "text": "python-os-module" }, { "code": null, "e": 2077, "s": 2070, "text": "Python" }, { "code": null, "e": 2175, "s": 2077, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2193, "s": 2175, "text": "Python Dictionary" }, { "code": null, "e": 2235, "s": 2193, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2257, "s": 2235, "text": "Enumerate() in Python" }, { "code": null, "e": 2292, "s": 2257, "text": "Read a file line by line in Python" }, { "code": null, "e": 2318, "s": 2292, "text": "Python String | replace()" }, { "code": null, "e": 2350, "s": 2318, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2379, "s": 2350, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2406, "s": 2379, "text": "Python Classes and Objects" }, { "code": null, "e": 2436, "s": 2406, "text": "Iterate over a list in Python" } ]
map key_comp() function in C++ STL
22 Jun, 2022 The map::key_comp() is a function in STL in C++ that returns a copy of comparison object used by container that compare keys. Syntax: map.key_comp() Return value: This method returns the comparison object used by container that compare keys. Below examples illustrate the working of key_comp() method: Example: CPP // C++ program to demonstrate map::key_comp(). #include <iostream>#include <map>using namespace std; int main(){ // Declare the map map<char, int> mymap; // Compare the key. map<char, int>::key_compare mycomp = mymap.key_comp(); // Populate the map mymap['x'] = 50; mymap['y'] = 100; mymap['z'] = 150; // Print the map cout << "mymap contain:\n"; char highest = mymap.rbegin()->first; // key value of last element map<char, int>::iterator it = mymap.begin(); do { cout << it->first << " => " << it->second << "\n"; } while (mycomp((*it++).first, highest)); cout << "\n"; return 0;} mymap contain: x => 50 y => 100 z => 150 Example 2: CPP // C++ program to demonstrate map::key_comp(). #include <iostream>#include <map>using namespace std; int main(){ // Declare the map map<char, int> mymap; // Compare the key. map<char, int>::key_compare mycomp = mymap.key_comp(); mymap['a'] = 100; mymap['b'] = 200; mymap['c'] = 300; cout << "mymap contain:\n"; char highest = mymap.rbegin()->first; // key value of last element map<char, int>::iterator it = mymap.begin(); do { cout << it->first << " => " << it->second << '\n'; } while (mycomp((*it++).first, highest)); cout << '\n'; return 0;} mymap contain: a => 100 b => 200 c => 300 Time complexity: O(1) utkarshgupta110092 CPP-Functions cpp-map Picked C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bitwise Operators in C/C++ vector erase() and clear() in C++ Inheritance in C++ Priority Queue in C++ Standard Template Library (STL) The C++ Standard Template Library (STL) Substring in C++ Object Oriented Programming in C++ C++ Classes and Objects Sorting a vector in C++ 2D Vector In C++ With User Defined Size
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Jun, 2022" }, { "code": null, "e": 188, "s": 54, "text": "The map::key_comp() is a function in STL in C++ that returns a copy of comparison object used by container that compare keys. Syntax:" }, { "code": null, "e": 203, "s": 188, "text": "map.key_comp()" }, { "code": null, "e": 366, "s": 203, "text": "Return value: This method returns the comparison object used by container that compare keys. Below examples illustrate the working of key_comp() method: Example: " }, { "code": null, "e": 370, "s": 366, "text": "CPP" }, { "code": "// C++ program to demonstrate map::key_comp(). #include <iostream>#include <map>using namespace std; int main(){ // Declare the map map<char, int> mymap; // Compare the key. map<char, int>::key_compare mycomp = mymap.key_comp(); // Populate the map mymap['x'] = 50; mymap['y'] = 100; mymap['z'] = 150; // Print the map cout << \"mymap contain:\\n\"; char highest = mymap.rbegin()->first; // key value of last element map<char, int>::iterator it = mymap.begin(); do { cout << it->first << \" => \" << it->second << \"\\n\"; } while (mycomp((*it++).first, highest)); cout << \"\\n\"; return 0;}", "e": 1068, "s": 370, "text": null }, { "code": null, "e": 1109, "s": 1068, "text": "mymap contain:\nx => 50\ny => 100\nz => 150" }, { "code": null, "e": 1121, "s": 1109, "text": "Example 2: " }, { "code": null, "e": 1125, "s": 1121, "text": "CPP" }, { "code": "// C++ program to demonstrate map::key_comp(). #include <iostream>#include <map>using namespace std; int main(){ // Declare the map map<char, int> mymap; // Compare the key. map<char, int>::key_compare mycomp = mymap.key_comp(); mymap['a'] = 100; mymap['b'] = 200; mymap['c'] = 300; cout << \"mymap contain:\\n\"; char highest = mymap.rbegin()->first; // key value of last element map<char, int>::iterator it = mymap.begin(); do { cout << it->first << \" => \" << it->second << '\\n'; } while (mycomp((*it++).first, highest)); cout << '\\n'; return 0;}", "e": 1793, "s": 1125, "text": null }, { "code": null, "e": 1835, "s": 1793, "text": "mymap contain:\na => 100\nb => 200\nc => 300" }, { "code": null, "e": 1857, "s": 1835, "text": "Time complexity: O(1)" }, { "code": null, "e": 1876, "s": 1857, "text": "utkarshgupta110092" }, { "code": null, "e": 1890, "s": 1876, "text": "CPP-Functions" }, { "code": null, "e": 1898, "s": 1890, "text": "cpp-map" }, { "code": null, "e": 1905, "s": 1898, "text": "Picked" }, { "code": null, "e": 1909, "s": 1905, "text": "C++" }, { "code": null, "e": 1913, "s": 1909, "text": "CPP" }, { "code": null, "e": 2011, "s": 1913, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2038, "s": 2011, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 2072, "s": 2038, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 2091, "s": 2072, "text": "Inheritance in C++" }, { "code": null, "e": 2145, "s": 2091, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 2185, "s": 2145, "text": "The C++ Standard Template Library (STL)" }, { "code": null, "e": 2202, "s": 2185, "text": "Substring in C++" }, { "code": null, "e": 2237, "s": 2202, "text": "Object Oriented Programming in C++" }, { "code": null, "e": 2261, "s": 2237, "text": "C++ Classes and Objects" }, { "code": null, "e": 2285, "s": 2261, "text": "Sorting a vector in C++" } ]
How can we align the JRadioButtons horizontally in Java?
A JRadioButton is a subclass of JToggleButton and it is a two-state button that can either selected or deselected. Unlike checkboxes, the radio buttons are associated with a group and only one radio button in a group can be selected and it can be implemented by using the ButtonGroup class. When the radio button in the group is selected, any other previously selected radio button in the group is deselected. We can align the radio buttons either horizontally or vertically by using BoxLayout. import java.awt.*; import javax.swing.*; public class HorizontalRadioButtonsTest extends JPanel { public HorizontalRadioButtonsTest(){ JRadioButton jrb1 = new JRadioButton(" RB1"); JRadioButton jrb2 = new JRadioButton(" RB2"); JRadioButton jrb3 = new JRadioButton(" RB3"); JRadioButton jrb4 = new JRadioButton(" RB4"); JRadioButton jrb5 = new JRadioButton(" RB5"); Box box1 = Box.createHorizontalBox(); box1.add(jrb1); box1.add(jrb2); box1.add(jrb3); box1.add(jrb4); box1.add(jrb5); JRadioButton jrb6 = new JRadioButton(" RB6"); JRadioButton jrb7 = new JRadioButton(" RB7"); JRadioButton jrb8 = new JRadioButton(" RB8"); JRadioButton jrb9 = new JRadioButton(" RB9"); JRadioButton jrb10 = new JRadioButton(" RB10"); Box box2 = Box.createHorizontalBox(); box2.add(jrb6); box2.add(jrb7); box2.add(jrb8); box2.add(jrb9); box2.add(jrb10); JRadioButton jrb11 = new JRadioButton(" RB11"); JRadioButton jrb12 = new JRadioButton(" RB12"); JRadioButton jrb13 = new JRadioButton(" RB13"); JRadioButton jrb14 = new JRadioButton(" RB14"); JRadioButton jrb15 = new JRadioButton(" RB15"); Box box3 = Box.createHorizontalBox(); box3.add(jrb11); box3.add(jrb12); box3.add(jrb13); box3.add(jrb14); box3.add(jrb15); JRadioButton jrb16 = new JRadioButton(" RB16"); JRadioButton jrb17 = new JRadioButton(" RB17"); JRadioButton jrb18 = new JRadioButton(" RB18"); JRadioButton jrb19 = new JRadioButton(" RB19"); JRadioButton jrb20 = new JRadioButton(" RB20"); Box box4 = Box.createHorizontalBox(); box4.add(jrb16); box4.add(jrb17); box4.add(jrb18); box4.add(jrb19); box4.add(jrb20); setLayout(new GridLayout(5, 1)); add(box1); add(box2); add(box3); add(box4); } public static void main(String[] args) { JFrame frame = new JFrame("HorizontalRadioButtons Test"); frame.add(new HorizontalRadioButtonsTest()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setSize(375, 250); frame.setVisible(true); } }
[ { "code": null, "e": 1682, "s": 1187, "text": "A JRadioButton is a subclass of JToggleButton and it is a two-state button that can either selected or deselected. Unlike checkboxes, the radio buttons are associated with a group and only one radio button in a group can be selected and it can be implemented by using the ButtonGroup class. When the radio button in the group is selected, any other previously selected radio button in the group is deselected. We can align the radio buttons either horizontally or vertically by using BoxLayout." }, { "code": null, "e": 3949, "s": 1682, "text": "import java.awt.*;\nimport javax.swing.*;\npublic class HorizontalRadioButtonsTest extends JPanel {\n public HorizontalRadioButtonsTest(){\n JRadioButton jrb1 = new JRadioButton(\" RB1\");\n JRadioButton jrb2 = new JRadioButton(\" RB2\");\n JRadioButton jrb3 = new JRadioButton(\" RB3\");\n JRadioButton jrb4 = new JRadioButton(\" RB4\");\n JRadioButton jrb5 = new JRadioButton(\" RB5\");\n Box box1 = Box.createHorizontalBox();\n box1.add(jrb1);\n box1.add(jrb2);\n box1.add(jrb3);\n box1.add(jrb4);\n box1.add(jrb5);\n JRadioButton jrb6 = new JRadioButton(\" RB6\");\n JRadioButton jrb7 = new JRadioButton(\" RB7\");\n JRadioButton jrb8 = new JRadioButton(\" RB8\");\n JRadioButton jrb9 = new JRadioButton(\" RB9\");\n JRadioButton jrb10 = new JRadioButton(\" RB10\");\n Box box2 = Box.createHorizontalBox();\n box2.add(jrb6);\n box2.add(jrb7);\n box2.add(jrb8);\n box2.add(jrb9);\n box2.add(jrb10);\n JRadioButton jrb11 = new JRadioButton(\" RB11\");\n JRadioButton jrb12 = new JRadioButton(\" RB12\");\n JRadioButton jrb13 = new JRadioButton(\" RB13\");\n JRadioButton jrb14 = new JRadioButton(\" RB14\");\n JRadioButton jrb15 = new JRadioButton(\" RB15\");\n Box box3 = Box.createHorizontalBox();\n box3.add(jrb11);\n box3.add(jrb12);\n box3.add(jrb13);\n box3.add(jrb14);\n box3.add(jrb15);\n JRadioButton jrb16 = new JRadioButton(\" RB16\");\n JRadioButton jrb17 = new JRadioButton(\" RB17\");\n JRadioButton jrb18 = new JRadioButton(\" RB18\");\n JRadioButton jrb19 = new JRadioButton(\" RB19\");\n JRadioButton jrb20 = new JRadioButton(\" RB20\");\n Box box4 = Box.createHorizontalBox();\n box4.add(jrb16);\n box4.add(jrb17);\n box4.add(jrb18);\n box4.add(jrb19);\n box4.add(jrb20);\n setLayout(new GridLayout(5, 1));\n add(box1);\n add(box2);\n add(box3);\n add(box4);\n }\n public static void main(String[] args) {\n JFrame frame = new JFrame(\"HorizontalRadioButtons Test\");\n frame.add(new HorizontalRadioButtonsTest());\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setLocationRelativeTo(null);\n frame.setSize(375, 250);\n frame.setVisible(true);\n }\n}" } ]
An Introduction to Making Dynamic and Interactive Plots with D3 | by Naveen Venkatesan | Towards Data Science
I’ve always been hesitant to learn how to use D3.js. It has always seemed much less intuitive than other libraries such as matplotlib, which I have written extensively about. However, here I find myself writing a tutorial on making a plot in D3 — if you are developing a website or web application and want dynamic and interactive data visualizations, it may be useful to be familiar with the library. In this article, I have compiled the results of many trial-and-errors in that hope that it can both serve me well as a reference and help you avoid some simple beginner mistakes in the process. The goal of this article will be to reproduce the plot of sample absorbances found in one of my earlier pieces: towardsdatascience.com Before we get started, I’d like to first take a step back. A lot of my previous work on Medium has been geared towards experimental scientists, as this is my own personal background. Speaking to that demographic, I believe that adding this new tool (D3) to your toolbox will help you make your data come alive, and be able to reach a wider audience than you normally would just by sharing your published journal articles. So, without further ado, let’s get started. As a disclaimer, a basic understanding of JavaScript, HTML, and CSS will certainly be helpful to you as a reader. To get started, we are going to need to create 3 files (put them all in the same folder on your computer): index.html — this is the main HTML file that we will be able to open in our web browser to see our visualizationstyle.css — we will use CSS to style a few of the elements in our visualizationplot.js — this will be the workhorse of our project, and contain all of the D3 code we need to make our plot index.html — this is the main HTML file that we will be able to open in our web browser to see our visualization style.css — we will use CSS to style a few of the elements in our visualization plot.js — this will be the workhorse of our project, and contain all of the D3 code we need to make our plot Our index.html will not contain too much in it, as we will manipulate the document using JavaScript. We start with the general skeleton code for any HTML file. <!DOCTYPE html><html></html> Within our html tag, we are going to create two sections: head and body. In the head section, we will add references to our CSS stylesheet, as well as a link to D3.js so we can use all the modules later. <!--Import D3 and our CSS in the head section--><head> <link rel='stylesheet' href='./style.css'> <script src="https://d3js.org/d3.v5.min.js"></script></head> Now, in the body of our HTML file, we will create a div called plot_area, which we will manipulate with our plot.js file, which we will also import into the current file. <!--Create div for our plot and import plot.js--><body> <div id='plot_area'></div> <script src='./plot.js'></script></body> We are done with all the edits to index.html — now let’s move on to the main workhorse of our visualization, JavaScript. D3 is a JavaScript library that is short for Data-Driven Documents, and provides a series of functions to use and manipulate SVGs (scalable vector graphics). The first thing we are going to want to do is define a height and width for our SVG (in pixels) — in addition to this, we will define a padding value, to ensure that our plot axes are not right up against the boundaries of our SVG frame. // Set SVG width, height, and paddingconst w = 500;const h = 500;const padding = 60; Next, we will need to load our data — to do this, we can make use of a built-in function, where format_fnc() is our JavaScript function to format our data, and manipulate_fnc() is our function that we will use to manipulate the data: d3.csv('path_to_file', format_fnc()).then(manipulate_fnc()); The filepath that we will use is the CSV file from my previous article, and we will pass this to a callback function that reformats our data into a multidimensional array. We can reference fields in each of our CSV rows by their column names (‘Wavelength’, ‘Sample_1_Absorbance’, and ‘Sample_2_Absorbance’) — we must add a + because d3.csv() loads data as a string by default, so this ensures that we are storing the numerical values. Our final data array, will have subarrays for each data point, where the first element will be the wavelength, the second element is sample 1 absorbance, and the third element is sample 2 absorbance. Finally, we pass our formatted data to a plot_data() function that we will write next. // Load our CSV datad3.csv('https://raw.githubusercontent.com/naveenv92/python-science-tutorial/master/intro/Absorbance_Data.csv', function (d) {return [ +d['Wavelength'], +d['Sample_1_Absorbance'], +d['Sample_2_Absorbance']]}).then(plot_data); Now, we can start building the plot_data() function — the first thing we will do is define values for the axis limits: // Data plotting functionfunction plot_data(data) { // Set axis limits const xMin = 400; const xMax = 950; const yMin = 0; const yMax = 2;} We will continue to add to the body of this function — we now need to set the axis scaling, which we will do using d3.scaleLinear(), since both our axis will have linear scaling. Onto this, we will chain two more methods: domain() and range(). The domain corresponds to the input values that we will pass to our scale, and the range corresponds to the output that will be drawn on the SVG (in pixels). You will notice that a main theme in D3 is that we can keep chaining an arbitrary number of methods. In both ranges, we will offset the endpoints by the value of our padding variable, so that we have some whitespace around our axes. Another interesting thing you will notice is that the y-axis range appears to be backwards! This is because the origin of the SVG is at the top left corner, so we need to flip the y-values in order to move this origin to the bottom left. // Set x and y-axis scalesconst xScale = d3.scaleLinear() .domain([xMin, xMax]) .range([padding, w - padding]);const yScale = d3.scaleLinear() .domain([yMin, yMax]) .range([h - padding, padding]); Although we have specified a domain for our input values, our scaling functions will still plot data outside these ranges. To ensure that all our data is in our x-axis domain, we will create a new array that contains only the points in this region: // Trim data points to only be in range of x-axislet data_in_range = [];data.forEach(function (e) { if (e[0] >= xMin && e[0] <= xMax) { data_in_range.push(e); }}); We can now create the SVG object — in D3, this is often driven by the functions d3.select() and d3.selectAll(). We will select the div we created earlier with id=plot_area and append an SVG to it with append('svg'). We can then edit attributes of the SVG with attr() and pass the height and width values we already defined. // Append an svg to the plot_area divconst svg = d3.select('#plot_area') .append('svg') .attr('width', w) .attr('height', h); To plot our first line (the absorbance of sample 1), we will append a path object to our SVG. Then, we can bind the relevant data to this line using the datum() function. We can then edit attributes as we did above, but to actually create the line, we need to edit the d attribute and use d3.line(). We will pass callback functions for the x and y-data, where we use the data points in conjunction with the xScale and yScale functions we created earlier. // Append path object for sample 1svg.append('path') .datum(data_in_range) .attr('stroke', 'black') .attr('stroke-width', 2) .attr('fill', 'none') .attr('d', d3.line() .x((d) => xScale(d[0])) .y((d) => yScale(d[1]))); If all goes well, we can now open the index.html file in our browser and should be greeted with the following: Baby steps! Now let’s add the second line, much in the way we did the first: // Append path object for sample 2svg.append('path') .datum(data_in_range) .attr('stroke', 'steelblue') .attr('stroke-width', 2) .attr('fill', 'none') .attr('d', d3.line() .x((d) => xScale(d[0])) .y((d) => yScale(d[2]))); We have successfully plotted both lines, but without any axes, there is no context for the data, so let’s add these. To create the x-axis, we use d3.axisBottom() and to create the y-axis we use d3.axisLeft(). All these two methods do, however, is make the x and y ticks point in the right direction (x-axis at the top of the SVG and y-axis at the left of the SVG) — we still need to translate them to their respective parts of the SVG, which we can do through the transform attribute: // Add x-axissvg.append('g') .style('font-size', '12px') .attr('transform', 'translate(0,' + (h - padding) + ')') .call(d3.axisBottom(xScale));// Add y-axissvg.append('g') .style('font-size', '12px') .attr('transform', 'translate(' + padding + ',0)') .call(d3.axisLeft(yScale)); D3 doesn’t directly have a method to create axis labels, so we do this by appending text objects. We can easily position the labels using the height and width variables we have stored already. In the following code block, I am offsetting the labels by 15 pixels from the edge of the SVG. Also, but setting the text-anchor property to middle, we can center the text object on the axis. For the y-axis label, we have to do one extra step. When rotating a text object, it gets rotated around the origin by default, even if we manually set the x and y attributes. To fix this, we will use a translation along with our rotation to reset the point of rotation, and rotate by -90 degrees. // Add x-axis labelsvg.append('text') .attr('x', w/2) .attr('y', h - 15) .attr('text-anchor', 'middle') .style('font-family', 'sans-serif') .text('Wavelength (nm)');// Add y-axis labelsvg.append('text') .attr('text-anchor', 'middle') .attr('transform', 'translate(15,' + h/2 + ')rotate(-90)') .style('font-family', 'sans-serif') .text('Absorbance (O.D.)'); Again, we’re pretty much on our own here as far as creating a legend. Our course of action will be as follows: Create lines for the legend by creating a 2-point datasetAppending text objects for each of the legend labels Create lines for the legend by creating a 2-point dataset Appending text objects for each of the legend labels Our legend lines with go from [750, 800] in our plot, and will be at y-values of 1.9 for Sample 1, and 1.7 for Sample 2. // Add legendsvg.append('path') .datum([[750, 1.9], [800, 1.9]]) .attr('stroke', 'black') .attr('stroke-width', 2) .attr('d', d3.line() .x((d) => xScale(d[0])) .y((d) => yScale(d[1])));svg.append('path') .datum([[750, 1.7], [800, 1.7]]) .attr('stroke', 'steelblue') .attr('stroke-width', 2) .attr('d', d3.line() .x((d) => xScale(d[0])) .y((d) => yScale(d[1]))); Now we can append text labels next to each of the newly-drawn lines: svg.append('text') .attr('x', xScale(805)) .attr('y', yScale(1.9)) .attr('alignment-baseline', 'central') .style('font-family', 'sans-serif') .style('font-size', '16px') .text('Sample 1');svg.append('text') .attr('x', xScale(805)) .attr('y', yScale(1.7)) .attr('alignment-baseline', 'central') .style('font-family', 'sans-serif') .style('font-size', '16px') .text('Sample 2'); Now, if you thought that we went through a lot of trouble to make the simple plot you see above — you’re probably right. Making static figures with other programming software such as R or Python is very straightforward. But making our plot dynamic is where the power of D3 is really shown. First, let’s create a little animation, where both of the lines start flat at 0 and then rise up to their values over the course of one second. To do this, we will go back and edit our initial plotting of the paths. We use the transition() method and duration() to change our attributes, in this case the d attribute. We set all the y-values to 0 initially, then change them to their respective values. // Append path object for sample 1svg.append('path') .datum(data_in_range) .attr('stroke', 'black') .attr('stroke-width', 2) .attr('fill', 'none') .attr('d', d3.line() .x((d) => xScale(d[0])) .y(yScale(0))) .transition() .duration(1000) .attr('d', d3.line() .x((d) => xScale(d[0])) .y((d) => yScale(d[1])));// Append path object for sample 2svg.append('path') .datum(data_in_range) .attr('stroke', 'steelblue') .attr('stroke-width', 2) .attr('fill', 'none') .attr('d', d3.line() .x((d) => xScale(d[0])) .y(yScale(0))) .transition() .duration(1000) .attr('d', d3.line() .x((d) => xScale(d[0])) .y((d) => yScale(d[2]))); Now, let’s make it so that we can use our mouse to hover over the actual data points and get their exact value. To do this, I am going to append circles for every data point. In this case, we will be use d3.selectAll() to select the circle objects we are going to create. We bind the data using data() instead of datum() because we are creating a new circle for each data point instead of using all the data points to create one path, as we did above. For each of the circles, we edit the attribute cx and cy for the circle’s x and y coordinates, respectively, and r for the circles’ radii. We will set the fill color to the same as the lines. Each of the circles then gets assigned a class value of points, which we will use CSS to modify. Finally, we set pointer-events to all so that if any part of the circle comes into the mouse pointer, we can trigger an event. To create the tooltips, we append title objects to each of the circle, and set their text attributes to be the data corresponding to that point. So when we hover over one of the points, we will see the data. // Append circles for hovering points for sample 1svg.selectAll('circle_samp_1') .data(data_in_range) .enter() .append('circle') .attr('cx', (d) => xScale(d[0])) .attr('cy', (d) => yScale(d[1])) .attr('r', 4) .attr('fill', 'black') .attr('class', 'points') .style('pointer-events', 'all') .append('title') .text(function (d) { return ( 'Wavelength: ' + d[0] + ' nm' + '\n' + 'Absorbance: ' + d[1] ); });// Append circles for hovering for sample 2svg.selectAll('circle_samp_2') .data(data_in_range) .enter() .append('circle') .attr('cx', (d) => xScale(d[0])) .attr('cy', (d) => yScale(d[2])) .attr('r', 4) .attr('fill', 'steelblue') .attr('class', 'points') .style('pointer-events', 'all') .append('title') .text(function (d) { return ( 'Wavelength: ' + d[0] + ' nm' + '\n' + 'Absorbance: ' + d[2] ); }); I want the circles that we drew above to be invisible right until we hover over them. We can do this very simply in our CSS by editing the visibility attribute. We start with them being hidden and then make them visible when we trigger the points:hover event. /* Make points visible on hover */.points {visibility: hidden;}.points:hover {visibility: visible;} And there you have it! An interactive version of our absorbance plot made with D3! Thank you for reading! All the analyses from this article can be found at this Github repository. I appreciate any feedback, and you can find me on Twitter and connect with me on LinkedIn for more updates and articles.
[ { "code": null, "e": 879, "s": 171, "text": "I’ve always been hesitant to learn how to use D3.js. It has always seemed much less intuitive than other libraries such as matplotlib, which I have written extensively about. However, here I find myself writing a tutorial on making a plot in D3 — if you are developing a website or web application and want dynamic and interactive data visualizations, it may be useful to be familiar with the library. In this article, I have compiled the results of many trial-and-errors in that hope that it can both serve me well as a reference and help you avoid some simple beginner mistakes in the process. The goal of this article will be to reproduce the plot of sample absorbances found in one of my earlier pieces:" }, { "code": null, "e": 902, "s": 879, "text": "towardsdatascience.com" }, { "code": null, "e": 1482, "s": 902, "text": "Before we get started, I’d like to first take a step back. A lot of my previous work on Medium has been geared towards experimental scientists, as this is my own personal background. Speaking to that demographic, I believe that adding this new tool (D3) to your toolbox will help you make your data come alive, and be able to reach a wider audience than you normally would just by sharing your published journal articles. So, without further ado, let’s get started. As a disclaimer, a basic understanding of JavaScript, HTML, and CSS will certainly be helpful to you as a reader." }, { "code": null, "e": 1589, "s": 1482, "text": "To get started, we are going to need to create 3 files (put them all in the same folder on your computer):" }, { "code": null, "e": 1889, "s": 1589, "text": "index.html — this is the main HTML file that we will be able to open in our web browser to see our visualizationstyle.css — we will use CSS to style a few of the elements in our visualizationplot.js — this will be the workhorse of our project, and contain all of the D3 code we need to make our plot" }, { "code": null, "e": 2002, "s": 1889, "text": "index.html — this is the main HTML file that we will be able to open in our web browser to see our visualization" }, { "code": null, "e": 2082, "s": 2002, "text": "style.css — we will use CSS to style a few of the elements in our visualization" }, { "code": null, "e": 2191, "s": 2082, "text": "plot.js — this will be the workhorse of our project, and contain all of the D3 code we need to make our plot" }, { "code": null, "e": 2351, "s": 2191, "text": "Our index.html will not contain too much in it, as we will manipulate the document using JavaScript. We start with the general skeleton code for any HTML file." }, { "code": null, "e": 2380, "s": 2351, "text": "<!DOCTYPE html><html></html>" }, { "code": null, "e": 2584, "s": 2380, "text": "Within our html tag, we are going to create two sections: head and body. In the head section, we will add references to our CSS stylesheet, as well as a link to D3.js so we can use all the modules later." }, { "code": null, "e": 2745, "s": 2584, "text": "<!--Import D3 and our CSS in the head section--><head> <link rel='stylesheet' href='./style.css'> <script src=\"https://d3js.org/d3.v5.min.js\"></script></head>" }, { "code": null, "e": 2916, "s": 2745, "text": "Now, in the body of our HTML file, we will create a div called plot_area, which we will manipulate with our plot.js file, which we will also import into the current file." }, { "code": null, "e": 3042, "s": 2916, "text": "<!--Create div for our plot and import plot.js--><body> <div id='plot_area'></div> <script src='./plot.js'></script></body>" }, { "code": null, "e": 3163, "s": 3042, "text": "We are done with all the edits to index.html — now let’s move on to the main workhorse of our visualization, JavaScript." }, { "code": null, "e": 3559, "s": 3163, "text": "D3 is a JavaScript library that is short for Data-Driven Documents, and provides a series of functions to use and manipulate SVGs (scalable vector graphics). The first thing we are going to want to do is define a height and width for our SVG (in pixels) — in addition to this, we will define a padding value, to ensure that our plot axes are not right up against the boundaries of our SVG frame." }, { "code": null, "e": 3644, "s": 3559, "text": "// Set SVG width, height, and paddingconst w = 500;const h = 500;const padding = 60;" }, { "code": null, "e": 3878, "s": 3644, "text": "Next, we will need to load our data — to do this, we can make use of a built-in function, where format_fnc() is our JavaScript function to format our data, and manipulate_fnc() is our function that we will use to manipulate the data:" }, { "code": null, "e": 3939, "s": 3878, "text": "d3.csv('path_to_file', format_fnc()).then(manipulate_fnc());" }, { "code": null, "e": 4661, "s": 3939, "text": "The filepath that we will use is the CSV file from my previous article, and we will pass this to a callback function that reformats our data into a multidimensional array. We can reference fields in each of our CSV rows by their column names (‘Wavelength’, ‘Sample_1_Absorbance’, and ‘Sample_2_Absorbance’) — we must add a + because d3.csv() loads data as a string by default, so this ensures that we are storing the numerical values. Our final data array, will have subarrays for each data point, where the first element will be the wavelength, the second element is sample 1 absorbance, and the third element is sample 2 absorbance. Finally, we pass our formatted data to a plot_data() function that we will write next." }, { "code": null, "e": 4909, "s": 4661, "text": "// Load our CSV datad3.csv('https://raw.githubusercontent.com/naveenv92/python-science-tutorial/master/intro/Absorbance_Data.csv', function (d) {return [ +d['Wavelength'], +d['Sample_1_Absorbance'], +d['Sample_2_Absorbance']]}).then(plot_data);" }, { "code": null, "e": 5028, "s": 4909, "text": "Now, we can start building the plot_data() function — the first thing we will do is define values for the axis limits:" }, { "code": null, "e": 5173, "s": 5028, "text": "// Data plotting functionfunction plot_data(data) { // Set axis limits const xMin = 400; const xMax = 950; const yMin = 0; const yMax = 2;}" }, { "code": null, "e": 6046, "s": 5173, "text": "We will continue to add to the body of this function — we now need to set the axis scaling, which we will do using d3.scaleLinear(), since both our axis will have linear scaling. Onto this, we will chain two more methods: domain() and range(). The domain corresponds to the input values that we will pass to our scale, and the range corresponds to the output that will be drawn on the SVG (in pixels). You will notice that a main theme in D3 is that we can keep chaining an arbitrary number of methods. In both ranges, we will offset the endpoints by the value of our padding variable, so that we have some whitespace around our axes. Another interesting thing you will notice is that the y-axis range appears to be backwards! This is because the origin of the SVG is at the top left corner, so we need to flip the y-values in order to move this origin to the bottom left." }, { "code": null, "e": 6307, "s": 6046, "text": "// Set x and y-axis scalesconst xScale = d3.scaleLinear() .domain([xMin, xMax]) .range([padding, w - padding]);const yScale = d3.scaleLinear() .domain([yMin, yMax]) .range([h - padding, padding]);" }, { "code": null, "e": 6556, "s": 6307, "text": "Although we have specified a domain for our input values, our scaling functions will still plot data outside these ranges. To ensure that all our data is in our x-axis domain, we will create a new array that contains only the points in this region:" }, { "code": null, "e": 6723, "s": 6556, "text": "// Trim data points to only be in range of x-axislet data_in_range = [];data.forEach(function (e) { if (e[0] >= xMin && e[0] <= xMax) { data_in_range.push(e); }});" }, { "code": null, "e": 7047, "s": 6723, "text": "We can now create the SVG object — in D3, this is often driven by the functions d3.select() and d3.selectAll(). We will select the div we created earlier with id=plot_area and append an SVG to it with append('svg'). We can then edit attributes of the SVG with attr() and pass the height and width values we already defined." }, { "code": null, "e": 7212, "s": 7047, "text": "// Append an svg to the plot_area divconst svg = d3.select('#plot_area') .append('svg') .attr('width', w) .attr('height', h);" }, { "code": null, "e": 7667, "s": 7212, "text": "To plot our first line (the absorbance of sample 1), we will append a path object to our SVG. Then, we can bind the relevant data to this line using the datum() function. We can then edit attributes as we did above, but to actually create the line, we need to edit the d attribute and use d3.line(). We will pass callback functions for the x and y-data, where we use the data points in conjunction with the xScale and yScale functions we created earlier." }, { "code": null, "e": 7925, "s": 7667, "text": "// Append path object for sample 1svg.append('path') .datum(data_in_range) .attr('stroke', 'black') .attr('stroke-width', 2) .attr('fill', 'none') .attr('d', d3.line() .x((d) => xScale(d[0])) .y((d) => yScale(d[1])));" }, { "code": null, "e": 8036, "s": 7925, "text": "If all goes well, we can now open the index.html file in our browser and should be greeted with the following:" }, { "code": null, "e": 8113, "s": 8036, "text": "Baby steps! Now let’s add the second line, much in the way we did the first:" }, { "code": null, "e": 8375, "s": 8113, "text": "// Append path object for sample 2svg.append('path') .datum(data_in_range) .attr('stroke', 'steelblue') .attr('stroke-width', 2) .attr('fill', 'none') .attr('d', d3.line() .x((d) => xScale(d[0])) .y((d) => yScale(d[2])));" }, { "code": null, "e": 8492, "s": 8375, "text": "We have successfully plotted both lines, but without any axes, there is no context for the data, so let’s add these." }, { "code": null, "e": 8860, "s": 8492, "text": "To create the x-axis, we use d3.axisBottom() and to create the y-axis we use d3.axisLeft(). All these two methods do, however, is make the x and y ticks point in the right direction (x-axis at the top of the SVG and y-axis at the left of the SVG) — we still need to translate them to their respective parts of the SVG, which we can do through the transform attribute:" }, { "code": null, "e": 9151, "s": 8860, "text": "// Add x-axissvg.append('g') .style('font-size', '12px') .attr('transform', 'translate(0,' + (h - padding) + ')') .call(d3.axisBottom(xScale));// Add y-axissvg.append('g') .style('font-size', '12px') .attr('transform', 'translate(' + padding + ',0)') .call(d3.axisLeft(yScale));" }, { "code": null, "e": 9536, "s": 9151, "text": "D3 doesn’t directly have a method to create axis labels, so we do this by appending text objects. We can easily position the labels using the height and width variables we have stored already. In the following code block, I am offsetting the labels by 15 pixels from the edge of the SVG. Also, but setting the text-anchor property to middle, we can center the text object on the axis." }, { "code": null, "e": 9833, "s": 9536, "text": "For the y-axis label, we have to do one extra step. When rotating a text object, it gets rotated around the origin by default, even if we manually set the x and y attributes. To fix this, we will use a translation along with our rotation to reset the point of rotation, and rotate by -90 degrees." }, { "code": null, "e": 10208, "s": 9833, "text": "// Add x-axis labelsvg.append('text') .attr('x', w/2) .attr('y', h - 15) .attr('text-anchor', 'middle') .style('font-family', 'sans-serif') .text('Wavelength (nm)');// Add y-axis labelsvg.append('text') .attr('text-anchor', 'middle') .attr('transform', 'translate(15,' + h/2 + ')rotate(-90)') .style('font-family', 'sans-serif') .text('Absorbance (O.D.)');" }, { "code": null, "e": 10319, "s": 10208, "text": "Again, we’re pretty much on our own here as far as creating a legend. Our course of action will be as follows:" }, { "code": null, "e": 10429, "s": 10319, "text": "Create lines for the legend by creating a 2-point datasetAppending text objects for each of the legend labels" }, { "code": null, "e": 10487, "s": 10429, "text": "Create lines for the legend by creating a 2-point dataset" }, { "code": null, "e": 10540, "s": 10487, "text": "Appending text objects for each of the legend labels" }, { "code": null, "e": 10661, "s": 10540, "text": "Our legend lines with go from [750, 800] in our plot, and will be at y-values of 1.9 for Sample 1, and 1.7 for Sample 2." }, { "code": null, "e": 11099, "s": 10661, "text": "// Add legendsvg.append('path') .datum([[750, 1.9], [800, 1.9]]) .attr('stroke', 'black') .attr('stroke-width', 2) .attr('d', d3.line() .x((d) => xScale(d[0])) .y((d) => yScale(d[1])));svg.append('path') .datum([[750, 1.7], [800, 1.7]]) .attr('stroke', 'steelblue') .attr('stroke-width', 2) .attr('d', d3.line() .x((d) => xScale(d[0])) .y((d) => yScale(d[1])));" }, { "code": null, "e": 11168, "s": 11099, "text": "Now we can append text labels next to each of the newly-drawn lines:" }, { "code": null, "e": 11569, "s": 11168, "text": "svg.append('text') .attr('x', xScale(805)) .attr('y', yScale(1.9)) .attr('alignment-baseline', 'central') .style('font-family', 'sans-serif') .style('font-size', '16px') .text('Sample 1');svg.append('text') .attr('x', xScale(805)) .attr('y', yScale(1.7)) .attr('alignment-baseline', 'central') .style('font-family', 'sans-serif') .style('font-size', '16px') .text('Sample 2');" }, { "code": null, "e": 12003, "s": 11569, "text": "Now, if you thought that we went through a lot of trouble to make the simple plot you see above — you’re probably right. Making static figures with other programming software such as R or Python is very straightforward. But making our plot dynamic is where the power of D3 is really shown. First, let’s create a little animation, where both of the lines start flat at 0 and then rise up to their values over the course of one second." }, { "code": null, "e": 12262, "s": 12003, "text": "To do this, we will go back and edit our initial plotting of the paths. We use the transition() method and duration() to change our attributes, in this case the d attribute. We set all the y-values to 0 initially, then change them to their respective values." }, { "code": null, "e": 13033, "s": 12262, "text": "// Append path object for sample 1svg.append('path') .datum(data_in_range) .attr('stroke', 'black') .attr('stroke-width', 2) .attr('fill', 'none') .attr('d', d3.line() .x((d) => xScale(d[0])) .y(yScale(0))) .transition() .duration(1000) .attr('d', d3.line() .x((d) => xScale(d[0])) .y((d) => yScale(d[1])));// Append path object for sample 2svg.append('path') .datum(data_in_range) .attr('stroke', 'steelblue') .attr('stroke-width', 2) .attr('fill', 'none') .attr('d', d3.line() .x((d) => xScale(d[0])) .y(yScale(0))) .transition() .duration(1000) .attr('d', d3.line() .x((d) => xScale(d[0])) .y((d) => yScale(d[2])));" }, { "code": null, "e": 13485, "s": 13033, "text": "Now, let’s make it so that we can use our mouse to hover over the actual data points and get their exact value. To do this, I am going to append circles for every data point. In this case, we will be use d3.selectAll() to select the circle objects we are going to create. We bind the data using data() instead of datum() because we are creating a new circle for each data point instead of using all the data points to create one path, as we did above." }, { "code": null, "e": 13901, "s": 13485, "text": "For each of the circles, we edit the attribute cx and cy for the circle’s x and y coordinates, respectively, and r for the circles’ radii. We will set the fill color to the same as the lines. Each of the circles then gets assigned a class value of points, which we will use CSS to modify. Finally, we set pointer-events to all so that if any part of the circle comes into the mouse pointer, we can trigger an event." }, { "code": null, "e": 14109, "s": 13901, "text": "To create the tooltips, we append title objects to each of the circle, and set their text attributes to be the data corresponding to that point. So when we hover over one of the points, we will see the data." }, { "code": null, "e": 14988, "s": 14109, "text": "// Append circles for hovering points for sample 1svg.selectAll('circle_samp_1') .data(data_in_range) .enter() .append('circle') .attr('cx', (d) => xScale(d[0])) .attr('cy', (d) => yScale(d[1])) .attr('r', 4) .attr('fill', 'black') .attr('class', 'points') .style('pointer-events', 'all') .append('title') .text(function (d) { return ( 'Wavelength: ' + d[0] + ' nm' + '\\n' + 'Absorbance: ' + d[1] ); });// Append circles for hovering for sample 2svg.selectAll('circle_samp_2') .data(data_in_range) .enter() .append('circle') .attr('cx', (d) => xScale(d[0])) .attr('cy', (d) => yScale(d[2])) .attr('r', 4) .attr('fill', 'steelblue') .attr('class', 'points') .style('pointer-events', 'all') .append('title') .text(function (d) { return ( 'Wavelength: ' + d[0] + ' nm' + '\\n' + 'Absorbance: ' + d[2] ); });" }, { "code": null, "e": 15248, "s": 14988, "text": "I want the circles that we drew above to be invisible right until we hover over them. We can do this very simply in our CSS by editing the visibility attribute. We start with them being hidden and then make them visible when we trigger the points:hover event." }, { "code": null, "e": 15348, "s": 15248, "text": "/* Make points visible on hover */.points {visibility: hidden;}.points:hover {visibility: visible;}" }, { "code": null, "e": 15431, "s": 15348, "text": "And there you have it! An interactive version of our absorbance plot made with D3!" } ]
How to build a basic line in D3.js | by Angelica Lo Duca | Towards Data Science
When dealing with data, one of the most important aspects is their presentation. For this reason, different tools and techniques exist for data visualization. In this tutorial, I will show you how to build a basic line in D3.js. D3.js is one of the most powerful libraries for data visualization in javascript. At this link you can find some basic tutorials to learn D3.js. The code can be downloaded from my Github repository and it is freely inspired to this example, extracted from d3 data gallery. Firstly, we start with data. We consider data related to the number of tourists arrivals in Italy, France, Spain, Germany, and United Kingdom from 1990 to 2019. We have a column for dates and another 5 columns, one for each Country. Then we start to build the HTML code: <!DOCTYPE html><html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v4.js"></script> </head> <body> <div id="line"></div> </body></html> Note that we use the version 4 of d3. Within the body we create a div which will contain the line. Now we can write the script, which will be inserted in the body. We set the dimensions and the margins of the graph: var margin = {top: 50, right: 30, bottom: 30, left: 100}, width = 600 - margin.left - margin.right, height = 400 - margin.top - margin.bottom; and we append a svg element to the div created in the HTML code and we specify their dimensions. We also add a grouping element g to the svg and we translate it to the margin.left and margin.top: var svg = d3.select("#line") .append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); Now we can read the CSV, by using the function d3.csv(data, preprocessing_function, processing_function) , where data represent the CSV data, the preprocessing_function permits to format data according to some criteria, the processing_function executes the operations needed to build the graph. We define the following preprocessing_function (note that we omit the function name, because we will put it inside the d3.csv function and a name is not needed): function(d){ return { date : d3.timeParse("%Y-%m-%d")(d.date), IT : d.IT , FR : d.FR, DE : d.DE, ES : d.ES, UK : d.UK} }, The only useful thing that we do is parsing dates as object dates. The other fields remain constant. Now we can define the processing_function. This function requires as input data contained in the CSV file. We add the X axis, using a time scale. We define the domain, which contains the range of possible values for the axis and the range, which contains the dimensions of the axis within the svg image. var x = d3.scaleTime() .domain(d3.extent(data, function(d) { return d.date; })) .range([ 0, width ]); We append the axis at the bottom of the svg object: svg.append("g") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x)); Similarly, we build the y axis, where the domain is specified by the maximum value in data. In our case, the maximum value is given by the United Kingdom series: var y = d3.scaleLinear() .domain([0, d3.max(data, function(d) { return +d.UK; })]) .range([ height, 0 ]); We append the y axis to the left of the svg object: svg.append("g") .call(d3.axisLeft(y)); Now we build a label for the y axis, we rotate it of 90 degrees and we append it to the svg object. svg.append("text") .attr("transform", "rotate(-90)") .attr("y", 0 - margin.left) .attr("x",0 - (height / 2)) .attr("dy", "1em") .attr("font-size", "12px") .style("text-anchor", "middle") .text("Total Number of Tourists Arrivals"); We can add also a title, simply by adding another text at the top of the svg object: svg.append("text") .attr("y", 0 - margin.top) .attr("x",(width / 2)) .attr("dy", "1em") .attr("font-weight", "bold") .attr("font-size", "16px") .style("text-anchor", "middle") .text("Total Number of Tourists Arrivals for Italy"); We can define a different color for each country. This can be done by defining a palette of colors. We define an array called countries , containing all the countries identifiers. var countries = ['IT', 'FR','DE','UK','ES']; var color = d3.scaleOrdinal() .domain(countries) .range(['#e41a1c','#377eb8','#4daf4a','#984ea3','#ff7f00']) We can add a line for each country. We use the svg element called path and we define its properties. Note that the color depends on the country. for(var i = 0; i < countries.length; i++) { svg.append("path") .datum(data) .attr("fill", "none") .attr("stroke", function(d){ return color(countries[i]) }) .attr("stroke-width", 1.5) .attr("d", d3.line() .x(function(d) { return x(d.date) }) .y(function(d) { return y(d[countries[i]]) }) ) } We can also draw a legend. The legend is composed of a rectangle, specifying the color, and a text, specifying the country identifier. var lineLegend = svg.selectAll(".lineLegend").data(countries) .enter().append("g") .attr("class","lineLegend") .attr("transform", function (d,i) { position = width - margin.right return "translate(" + position + "," + (i*20)+")"; });lineLegend.append("text").text(function (d) {return d;}) .attr("transform", "translate(15,9)"); //align texts with boxeslineLegend.append("rect") .attr("fill", function (d, i) {return color(d); }) .attr("width", 10).attr("height", 10); In this tutorial, I have illustrated the procedure to build a basic line chart in d3.js, which is a low-level JS library to manipulate the HTML and build very powerful SVG objects. In summarizing, the steps to build the graph are the following: On the HTML page, create a div tag statically, which will contain the chartWithin the JS script: read data for example from CSV files format the data according to what it is used for retrieve the div and hang an svg object hang the x and y axes on the svg object and assign them the domain (set of possible values) and the range (dimensions) hang on the svg object a line, a rectangle, or a point for each data hang a legend on the svg object (possibly) hang a title on the svg object. medium.datadriveninvestor.com towardsdatascience.com towardsdatascience.com You can use the d3-annotation library. Continue reading here. Follow me on Medium Sign up for my newsletter Connect on LinkedIn Follow me on Twitter Follow me on Facebook Follow me on Github
[ { "code": null, "e": 546, "s": 172, "text": "When dealing with data, one of the most important aspects is their presentation. For this reason, different tools and techniques exist for data visualization. In this tutorial, I will show you how to build a basic line in D3.js. D3.js is one of the most powerful libraries for data visualization in javascript. At this link you can find some basic tutorials to learn D3.js." }, { "code": null, "e": 674, "s": 546, "text": "The code can be downloaded from my Github repository and it is freely inspired to this example, extracted from d3 data gallery." }, { "code": null, "e": 835, "s": 674, "text": "Firstly, we start with data. We consider data related to the number of tourists arrivals in Italy, France, Spain, Germany, and United Kingdom from 1990 to 2019." }, { "code": null, "e": 945, "s": 835, "text": "We have a column for dates and another 5 columns, one for each Country. Then we start to build the HTML code:" }, { "code": null, "e": 1112, "s": 945, "text": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <script src=\"https://d3js.org/d3.v4.js\"></script> </head> <body> <div id=\"line\"></div> </body></html>" }, { "code": null, "e": 1276, "s": 1112, "text": "Note that we use the version 4 of d3. Within the body we create a div which will contain the line. Now we can write the script, which will be inserted in the body." }, { "code": null, "e": 1328, "s": 1276, "text": "We set the dimensions and the margins of the graph:" }, { "code": null, "e": 1477, "s": 1328, "text": "var margin = {top: 50, right: 30, bottom: 30, left: 100}, width = 600 - margin.left - margin.right, height = 400 - margin.top - margin.bottom;" }, { "code": null, "e": 1673, "s": 1477, "text": "and we append a svg element to the div created in the HTML code and we specify their dimensions. We also add a grouping element g to the svg and we translate it to the margin.left and margin.top:" }, { "code": null, "e": 1931, "s": 1673, "text": "var svg = d3.select(\"#line\") .append(\"svg\") .attr(\"width\", width + margin.left + margin.right) .attr(\"height\", height + margin.top + margin.bottom) .append(\"g\") .attr(\"transform\", \"translate(\" + margin.left + \",\" + margin.top + \")\");" }, { "code": null, "e": 2226, "s": 1931, "text": "Now we can read the CSV, by using the function d3.csv(data, preprocessing_function, processing_function) , where data represent the CSV data, the preprocessing_function permits to format data according to some criteria, the processing_function executes the operations needed to build the graph." }, { "code": null, "e": 2388, "s": 2226, "text": "We define the following preprocessing_function (note that we omit the function name, because we will put it inside the d3.csv function and a name is not needed):" }, { "code": null, "e": 2552, "s": 2388, "text": " function(d){ return { date : d3.timeParse(\"%Y-%m-%d\")(d.date), IT : d.IT , FR : d.FR, DE : d.DE, ES : d.ES, UK : d.UK} }," }, { "code": null, "e": 2760, "s": 2552, "text": "The only useful thing that we do is parsing dates as object dates. The other fields remain constant. Now we can define the processing_function. This function requires as input data contained in the CSV file." }, { "code": null, "e": 2957, "s": 2760, "text": "We add the X axis, using a time scale. We define the domain, which contains the range of possible values for the axis and the range, which contains the dimensions of the axis within the svg image." }, { "code": null, "e": 3069, "s": 2957, "text": "var x = d3.scaleTime() .domain(d3.extent(data, function(d) { return d.date; })) .range([ 0, width ]);" }, { "code": null, "e": 3121, "s": 3069, "text": "We append the axis at the bottom of the svg object:" }, { "code": null, "e": 3222, "s": 3121, "text": "svg.append(\"g\") .attr(\"transform\", \"translate(0,\" + height + \")\") .call(d3.axisBottom(x));" }, { "code": null, "e": 3384, "s": 3222, "text": "Similarly, we build the y axis, where the domain is specified by the maximum value in data. In our case, the maximum value is given by the United Kingdom series:" }, { "code": null, "e": 3500, "s": 3384, "text": "var y = d3.scaleLinear() .domain([0, d3.max(data, function(d) { return +d.UK; })]) .range([ height, 0 ]);" }, { "code": null, "e": 3552, "s": 3500, "text": "We append the y axis to the left of the svg object:" }, { "code": null, "e": 3595, "s": 3552, "text": "svg.append(\"g\") .call(d3.axisLeft(y));" }, { "code": null, "e": 3695, "s": 3595, "text": "Now we build a label for the y axis, we rotate it of 90 degrees and we append it to the svg object." }, { "code": null, "e": 3962, "s": 3695, "text": "svg.append(\"text\") .attr(\"transform\", \"rotate(-90)\") .attr(\"y\", 0 - margin.left) .attr(\"x\",0 - (height / 2)) .attr(\"dy\", \"1em\") .attr(\"font-size\", \"12px\") .style(\"text-anchor\", \"middle\") .text(\"Total Number of Tourists Arrivals\");" }, { "code": null, "e": 4047, "s": 3962, "text": "We can add also a title, simply by adding another text at the top of the svg object:" }, { "code": null, "e": 4312, "s": 4047, "text": "svg.append(\"text\") .attr(\"y\", 0 - margin.top) .attr(\"x\",(width / 2)) .attr(\"dy\", \"1em\") .attr(\"font-weight\", \"bold\") .attr(\"font-size\", \"16px\") .style(\"text-anchor\", \"middle\") .text(\"Total Number of Tourists Arrivals for Italy\");" }, { "code": null, "e": 4492, "s": 4312, "text": "We can define a different color for each country. This can be done by defining a palette of colors. We define an array called countries , containing all the countries identifiers." }, { "code": null, "e": 4654, "s": 4492, "text": "var countries = ['IT', 'FR','DE','UK','ES']; var color = d3.scaleOrdinal() .domain(countries) .range(['#e41a1c','#377eb8','#4daf4a','#984ea3','#ff7f00'])" }, { "code": null, "e": 4799, "s": 4654, "text": "We can add a line for each country. We use the svg element called path and we define its properties. Note that the color depends on the country." }, { "code": null, "e": 5155, "s": 4799, "text": "for(var i = 0; i < countries.length; i++) { svg.append(\"path\") .datum(data) .attr(\"fill\", \"none\") .attr(\"stroke\", function(d){ return color(countries[i]) }) .attr(\"stroke-width\", 1.5) .attr(\"d\", d3.line() .x(function(d) { return x(d.date) }) .y(function(d) { return y(d[countries[i]]) }) ) }" }, { "code": null, "e": 5290, "s": 5155, "text": "We can also draw a legend. The legend is composed of a rectangle, specifying the color, and a text, specifying the country identifier." }, { "code": null, "e": 5806, "s": 5290, "text": "var lineLegend = svg.selectAll(\".lineLegend\").data(countries) .enter().append(\"g\") .attr(\"class\",\"lineLegend\") .attr(\"transform\", function (d,i) { position = width - margin.right return \"translate(\" + position + \",\" + (i*20)+\")\"; });lineLegend.append(\"text\").text(function (d) {return d;}) .attr(\"transform\", \"translate(15,9)\"); //align texts with boxeslineLegend.append(\"rect\") .attr(\"fill\", function (d, i) {return color(d); }) .attr(\"width\", 10).attr(\"height\", 10);" }, { "code": null, "e": 6051, "s": 5806, "text": "In this tutorial, I have illustrated the procedure to build a basic line chart in d3.js, which is a low-level JS library to manipulate the HTML and build very powerful SVG objects. In summarizing, the steps to build the graph are the following:" }, { "code": null, "e": 6148, "s": 6051, "text": "On the HTML page, create a div tag statically, which will contain the chartWithin the JS script:" }, { "code": null, "e": 6185, "s": 6148, "text": "read data for example from CSV files" }, { "code": null, "e": 6234, "s": 6185, "text": "format the data according to what it is used for" }, { "code": null, "e": 6274, "s": 6234, "text": "retrieve the div and hang an svg object" }, { "code": null, "e": 6393, "s": 6274, "text": "hang the x and y axes on the svg object and assign them the domain (set of possible values) and the range (dimensions)" }, { "code": null, "e": 6462, "s": 6393, "text": "hang on the svg object a line, a rectangle, or a point for each data" }, { "code": null, "e": 6505, "s": 6462, "text": "hang a legend on the svg object (possibly)" }, { "code": null, "e": 6537, "s": 6505, "text": "hang a title on the svg object." }, { "code": null, "e": 6567, "s": 6537, "text": "medium.datadriveninvestor.com" }, { "code": null, "e": 6590, "s": 6567, "text": "towardsdatascience.com" }, { "code": null, "e": 6613, "s": 6590, "text": "towardsdatascience.com" }, { "code": null, "e": 6652, "s": 6613, "text": "You can use the d3-annotation library." }, { "code": null, "e": 6675, "s": 6652, "text": "Continue reading here." }, { "code": null, "e": 6695, "s": 6675, "text": "Follow me on Medium" }, { "code": null, "e": 6721, "s": 6695, "text": "Sign up for my newsletter" }, { "code": null, "e": 6741, "s": 6721, "text": "Connect on LinkedIn" }, { "code": null, "e": 6762, "s": 6741, "text": "Follow me on Twitter" }, { "code": null, "e": 6784, "s": 6762, "text": "Follow me on Facebook" } ]
How VOTing classifiers work!. A scikit-learn feature for enhancing... | by Mubarak Ganiyu | Towards Data Science
Classification is an important machine learning technique that is often used to predict categorical labels. It is a very practical approach for making binary predictions or predicting discrete values. The classifier, another name for classification model, might have the intention of predicting whether someone is eligible for a job or it could be used to classify the images of multiple objects in a store. Classification, like other machine learning techniques, use data sets. A dataset is a combination of multiple values from different variables. After obtaining an optimal dataset, it is split into two: the training and testing set. The training set often has a larger proportion of the dataset. It is likely to take up about 70% to 90% of the dataset. The training set is inserted into the machine learning algorithm to create a predictive model with an added step called cross-validation. Cross-validation is a great way to ensure that the built model does not overfit the training set and it also optimizes the versatility of the model. Then, the model can be used to predict the labels in the testing set. The predicted labels are further compared to the actual testing set labels via metrics such as confusion matrix, precision score, recall score, F1-score, roc auc score. Once the construction of the classification model is over, a data point’s values can be inserted into the algorithm and the algorithm makes a decision by attributing a specific label to this data point based on the variables’ inputs. Now imagine if different classification methods were asked to make decisions based on the data instances’ inputs. There are bound to be different answers. This is where voting classifiers come into play. A voting classifier is a classification method that employs multiple classifiers to make predictions. It is very applicable in situations when a data scientist or machine learning engineer is confused about which classification method to use. Therefore, using the predictions from multiple classifiers, the voting classifier makes predictions based on the most frequent one. A real life scenario could see a data scientist being confused about whether to use a random forest classifier or a logistic regressor to predict the type of flower based on their dimensions. Using the prompt above, a step-by-step guide has been created below on how to use python via Jupyter Notebooks to build voting classifiers. Starting with the code below, one can import the classifiers using scikit-learn. from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifierfrom sklearn.ensemble import VotingClassifier Using python via Jupyter Notebooks, the scikit-learn’s ensemble feature is accessed and a voting classifier is imported. There are three other classifiers in the code above: a random forest classifier, a logistic regressor and a KNearest Neighbor classifier. These three will be attributed to objects as seen below: log_clf = LogisticRegression()rnd_clf = RandomForestClassifier()knn_clf = KNeighborsClassifier() Afterwards, an object is created for the voting classifier. The voting classifier has two basic hyperparameters: estimators and voting. The estimators hyperparameter creates a list for the objects of the three classifiers above while assigning names to them. The voting hyperparameter is set to either hard or soft. If set to hard, the voting classifier will make judgments based on the predictions that appear the most. Otherwise, if set to soft, it will use a weighted approach to make its decision. I’d recommend setting it to soft when using an even number of classifiers because of its weighted approach and setting it to hard when using an odd number of classifiers because of its “majority carry the vote” approach. vot_clf = VotingClassifier(estimators = [('lr', log_clf), ('rnd', rnd_clf), ('knn', knn_clf)], voting = 'hard') The voting classifier like any other machine learning algorithm is used to fit the independent variables of the training dataset with the dependent variables from sklearn.datasets import load_iris from sklearn.model_selection import train_test_splitiris = load_iris()x, y = iris['data'], iris['target']x_train, x_test, y_train, y_test = train_test_split(X, y, random_state = 42, train_size = 0.85)vot_clf.fit(x_train, y_train) After fitting, it can be used to make predictions and the accuracy of its predictions is measured. pred = vot_clf.predict(x_test)accuracy_score(y_test, pred) Here is an image that shows how a voting classifier was used as a predictive model for a dataset and compared to other classifiers. The code was initially obtained from Aurelion Geron’s book, Hands-On Machine Learning with Scikit-Learn and TensorFlow Concepts, Tools, and Techniques to Build Intelligent Systems, and I ran them on Jupyter Notebooks. The voting classifier is a remarkable approach for classification because its methodology utilizes the collective judgment of multiple classifiers for predicting data points. I’d advise other aspiring data scientists and machine learning fanatics to try it out. Thank you for reading!
[ { "code": null, "e": 579, "s": 171, "text": "Classification is an important machine learning technique that is often used to predict categorical labels. It is a very practical approach for making binary predictions or predicting discrete values. The classifier, another name for classification model, might have the intention of predicting whether someone is eligible for a job or it could be used to classify the images of multiple objects in a store." }, { "code": null, "e": 930, "s": 579, "text": "Classification, like other machine learning techniques, use data sets. A dataset is a combination of multiple values from different variables. After obtaining an optimal dataset, it is split into two: the training and testing set. The training set often has a larger proportion of the dataset. It is likely to take up about 70% to 90% of the dataset." }, { "code": null, "e": 1456, "s": 930, "text": "The training set is inserted into the machine learning algorithm to create a predictive model with an added step called cross-validation. Cross-validation is a great way to ensure that the built model does not overfit the training set and it also optimizes the versatility of the model. Then, the model can be used to predict the labels in the testing set. The predicted labels are further compared to the actual testing set labels via metrics such as confusion matrix, precision score, recall score, F1-score, roc auc score." }, { "code": null, "e": 1690, "s": 1456, "text": "Once the construction of the classification model is over, a data point’s values can be inserted into the algorithm and the algorithm makes a decision by attributing a specific label to this data point based on the variables’ inputs." }, { "code": null, "e": 1894, "s": 1690, "text": "Now imagine if different classification methods were asked to make decisions based on the data instances’ inputs. There are bound to be different answers. This is where voting classifiers come into play." }, { "code": null, "e": 2269, "s": 1894, "text": "A voting classifier is a classification method that employs multiple classifiers to make predictions. It is very applicable in situations when a data scientist or machine learning engineer is confused about which classification method to use. Therefore, using the predictions from multiple classifiers, the voting classifier makes predictions based on the most frequent one." }, { "code": null, "e": 2461, "s": 2269, "text": "A real life scenario could see a data scientist being confused about whether to use a random forest classifier or a logistic regressor to predict the type of flower based on their dimensions." }, { "code": null, "e": 2601, "s": 2461, "text": "Using the prompt above, a step-by-step guide has been created below on how to use python via Jupyter Notebooks to build voting classifiers." }, { "code": null, "e": 2682, "s": 2601, "text": "Starting with the code below, one can import the classifiers using scikit-learn." }, { "code": null, "e": 2882, "s": 2682, "text": "from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifierfrom sklearn.ensemble import VotingClassifier" }, { "code": null, "e": 3198, "s": 2882, "text": "Using python via Jupyter Notebooks, the scikit-learn’s ensemble feature is accessed and a voting classifier is imported. There are three other classifiers in the code above: a random forest classifier, a logistic regressor and a KNearest Neighbor classifier. These three will be attributed to objects as seen below:" }, { "code": null, "e": 3295, "s": 3198, "text": "log_clf = LogisticRegression()rnd_clf = RandomForestClassifier()knn_clf = KNeighborsClassifier()" }, { "code": null, "e": 3611, "s": 3295, "text": "Afterwards, an object is created for the voting classifier. The voting classifier has two basic hyperparameters: estimators and voting. The estimators hyperparameter creates a list for the objects of the three classifiers above while assigning names to them. The voting hyperparameter is set to either hard or soft." }, { "code": null, "e": 4018, "s": 3611, "text": "If set to hard, the voting classifier will make judgments based on the predictions that appear the most. Otherwise, if set to soft, it will use a weighted approach to make its decision. I’d recommend setting it to soft when using an even number of classifiers because of its weighted approach and setting it to hard when using an odd number of classifiers because of its “majority carry the vote” approach." }, { "code": null, "e": 4130, "s": 4018, "text": "vot_clf = VotingClassifier(estimators = [('lr', log_clf), ('rnd', rnd_clf), ('knn', knn_clf)], voting = 'hard')" }, { "code": null, "e": 4288, "s": 4130, "text": "The voting classifier like any other machine learning algorithm is used to fit the independent variables of the training dataset with the dependent variables" }, { "code": null, "e": 4557, "s": 4288, "text": "from sklearn.datasets import load_iris from sklearn.model_selection import train_test_splitiris = load_iris()x, y = iris['data'], iris['target']x_train, x_test, y_train, y_test = train_test_split(X, y, random_state = 42, train_size = 0.85)vot_clf.fit(x_train, y_train)" }, { "code": null, "e": 4656, "s": 4557, "text": "After fitting, it can be used to make predictions and the accuracy of its predictions is measured." }, { "code": null, "e": 4715, "s": 4656, "text": "pred = vot_clf.predict(x_test)accuracy_score(y_test, pred)" }, { "code": null, "e": 5065, "s": 4715, "text": "Here is an image that shows how a voting classifier was used as a predictive model for a dataset and compared to other classifiers. The code was initially obtained from Aurelion Geron’s book, Hands-On Machine Learning with Scikit-Learn and TensorFlow Concepts, Tools, and Techniques to Build Intelligent Systems, and I ran them on Jupyter Notebooks." }, { "code": null, "e": 5327, "s": 5065, "text": "The voting classifier is a remarkable approach for classification because its methodology utilizes the collective judgment of multiple classifiers for predicting data points. I’d advise other aspiring data scientists and machine learning fanatics to try it out." } ]
How To Use Python’s New Match Statement | by Emmett Boudreau | Towards Data Science
Python 3.10 has been out for a little bit now, and has brought about a few new extra features. As with many of the releases, many of the changes to the language are not too significant and are not breaking. To be clear, this is not breaking in the traditional sense, where old code will be broken, but it is to say that code using the syntax in the future cannot use an older version of Python. However, one of the new changes made to Python is totally new and quite significant. This change is the match statement. This statement is something that has certainly been missed in Python prior, and can really help with the control flow of the language. Today I wanted to discuss the usage of that statement and go a bit more into detail on it. If you are a C or C++ programmer, it is likely that you have used or at least heard of using the match statement, just that it is renamed to the switch statement. This statement is used in order to control the flow of code execution. The statement can take a value and match it elegantly against one of a number of possible conditions. This is also called pattern matching, which is a term Rust programmers might be familiar with. The statement can be used a lot like a conditional statement, and basically follows a very similar syntax to those: from enum import Enumclass Command(Enum): QUIT = 0 RESET = 1match command: case Command.QUIT: quit() case Command.RESET: reset() We can match any condition and quickly move the control flow either into the block or beyond the block. While it is certainly possible to do so with simple conditionals, the match/case method is a lot prettier, and even out-performs using traditional conditional statements. Although it is a simple feature, it is quite welcome and rather cool for Python programmers. Now that we have used the match statement, let us talk a bit more about it. You might have realized that when we compared the match statement to other programming languages with similar types of expressions were all systems/low-level, imperative programming languages. The match statement itself falls into a very imperative area of computing. So that poses a very interesting question, why is it now in Python of all languages? We should consider that a lot of Python programmers might also write C++ or C, and that could be a valid reason in that switching back and forth, in some cases it could be missed. But the question I want to pose is whether or not this means that Python will be becoming more imperative in the future. Of course, we can expect that Python is going to remain quite declarative and high-level, but it would be interesting to speculate whether or not Python is going to be more usable on the lower-level side of things in the future. Of course, there is no way to know, but I would love to see more iterative features like this implemented in the future, as I think it really can serve to make the language a lot more versatile. One concern that some might have is in naming. There are a lot of legacy functions written in Python 3 that use match and case as variable names, so does that make this addition of the two a breaking change to that code? The short answer is yes, you can still use match and case as variable names. Match and case have become what are called soft keywords. This means that most of the time, they have no special meaning, but when used in certain applications, such as the a case block, they become key-words that the Python interpreter uses. Another weird thing to note about match and case is that it will not work with underscores. Underscores are another soft key-word in Python for wildcard variables, but in this one case, we can pass it through the case/match statement, but it will not alter the value of our match. The last question is perhaps the most important, and that is of scope. It is common for blocks of code in Python to have their own scope, so what scope is a variable declared in if we use it in a match block? Case blocks in Python do not have their own scope. This means that variables will be applied to the nearest available local scope. In other words, we can define variables inside of these blocks without initialization and use them around the function, which is something you might not expect given that this does not happen in most other circumstances. The match statement is certainly a cool new feature in the Python programming language. As to whether or not this hints at more features potentially coming in that follow this methodology, I am really excited to see how it turns out. The statement is certainly a welcome addition, though it does not necessarily provide that much new functionality. Another assumption we could make is that this could become a regular key-word in Python 4, once the language is ready to make breaking changes. Regardless, I think it is an interesting addition that I am going to be using from time to time in the future. Thank you for reading, and I hope you learned something new about Python’s latest feature!
[ { "code": null, "e": 567, "s": 172, "text": "Python 3.10 has been out for a little bit now, and has brought about a few new extra features. As with many of the releases, many of the changes to the language are not too significant and are not breaking. To be clear, this is not breaking in the traditional sense, where old code will be broken, but it is to say that code using the syntax in the future cannot use an older version of Python." }, { "code": null, "e": 914, "s": 567, "text": "However, one of the new changes made to Python is totally new and quite significant. This change is the match statement. This statement is something that has certainly been missed in Python prior, and can really help with the control flow of the language. Today I wanted to discuss the usage of that statement and go a bit more into detail on it." }, { "code": null, "e": 1461, "s": 914, "text": "If you are a C or C++ programmer, it is likely that you have used or at least heard of using the match statement, just that it is renamed to the switch statement. This statement is used in order to control the flow of code execution. The statement can take a value and match it elegantly against one of a number of possible conditions. This is also called pattern matching, which is a term Rust programmers might be familiar with. The statement can be used a lot like a conditional statement, and basically follows a very similar syntax to those:" }, { "code": null, "e": 1616, "s": 1461, "text": "from enum import Enumclass Command(Enum): QUIT = 0 RESET = 1match command: case Command.QUIT: quit() case Command.RESET: reset()" }, { "code": null, "e": 1984, "s": 1616, "text": "We can match any condition and quickly move the control flow either into the block or beyond the block. While it is certainly possible to do so with simple conditionals, the match/case method is a lot prettier, and even out-performs using traditional conditional statements. Although it is a simple feature, it is quite welcome and rather cool for Python programmers." }, { "code": null, "e": 2413, "s": 1984, "text": "Now that we have used the match statement, let us talk a bit more about it. You might have realized that when we compared the match statement to other programming languages with similar types of expressions were all systems/low-level, imperative programming languages. The match statement itself falls into a very imperative area of computing. So that poses a very interesting question, why is it now in Python of all languages?" }, { "code": null, "e": 3138, "s": 2413, "text": "We should consider that a lot of Python programmers might also write C++ or C, and that could be a valid reason in that switching back and forth, in some cases it could be missed. But the question I want to pose is whether or not this means that Python will be becoming more imperative in the future. Of course, we can expect that Python is going to remain quite declarative and high-level, but it would be interesting to speculate whether or not Python is going to be more usable on the lower-level side of things in the future. Of course, there is no way to know, but I would love to see more iterative features like this implemented in the future, as I think it really can serve to make the language a lot more versatile." }, { "code": null, "e": 3679, "s": 3138, "text": "One concern that some might have is in naming. There are a lot of legacy functions written in Python 3 that use match and case as variable names, so does that make this addition of the two a breaking change to that code? The short answer is yes, you can still use match and case as variable names. Match and case have become what are called soft keywords. This means that most of the time, they have no special meaning, but when used in certain applications, such as the a case block, they become key-words that the Python interpreter uses." }, { "code": null, "e": 3960, "s": 3679, "text": "Another weird thing to note about match and case is that it will not work with underscores. Underscores are another soft key-word in Python for wildcard variables, but in this one case, we can pass it through the case/match statement, but it will not alter the value of our match." }, { "code": null, "e": 4521, "s": 3960, "text": "The last question is perhaps the most important, and that is of scope. It is common for blocks of code in Python to have their own scope, so what scope is a variable declared in if we use it in a match block? Case blocks in Python do not have their own scope. This means that variables will be applied to the nearest available local scope. In other words, we can define variables inside of these blocks without initialization and use them around the function, which is something you might not expect given that this does not happen in most other circumstances." } ]
Find the Sub-array with sum closest to 0 - GeeksforGeeks
17 Dec, 2021 Given an array of both positive and negative numbers, the task is to find out the subarray whose sum is closest to 0. There can be multiple such subarrays, we need to output just 1 of them. Examples: Input : arr[] = {-1, 3, 2, -5, 4} Output : 1, 3 Subarray from index 1 to 3 has sum closest to 0 i.e. 3 + 2 + -5 = 0 Input : {2, -5, 4, -6, 3} Output : 0, 2 2 + -5 + 4 = 1 closest to 0 Asked in : Microsoft A Naive approach is to consider all subarrays one by one and update indexes of subarray with sum closest to 0. C++ Java Python3 C# Javascript // C++ program to find subarray with// sum closest to 0#include <bits/stdc++.h>using namespace std; // Function to find the subarraypair<int, int> findSubArray(int arr[], int n){ int start, end, min_sum = INT_MAX; // Pick a starting point for (int i = 0; i < n; i++) { // Consider current starting point // as a subarray and update minimum // sum and subarray indexes int curr_sum = arr[i]; if (min_sum > abs(curr_sum)) { min_sum = abs(curr_sum); start = i; end = i; } // Try all subarrays starting with i for (int j = i + 1; j < n; j++) { curr_sum = curr_sum + arr[j]; // update minimum sum // and subarray indexes if (min_sum > abs(curr_sum)) { min_sum = abs(curr_sum); start = i; end = j; } } } // Return starting and ending indexes pair<int, int> p = make_pair(start, end); return p;} // Drivers codeint main(){ int arr[] = { 2, -5, 4, -6, -3 }; int n = sizeof(arr) / sizeof(arr[0]); pair<int, int> point = findSubArray(arr, n); cout << "Subarray starting from "; cout << point.first << " to " << point.second; return 0;} // Java program to find subarray with// sum closest to 0 class GFG{ static class Pair { int first, second; public Pair(int first, int second) { this.first = first; this.second = second; } } // Function to find the subarray static Pair findSubArray(int arr[], int n) { int start = 0, end = 0, min_sum = Integer.MAX_VALUE; // Pick a starting point for (int i = 0; i < n; i++) { // Consider current starting point // as a subarray and update minimum // sum and subarray indexes int curr_sum = arr[i]; if (min_sum > Math.abs(curr_sum)) { min_sum = Math.abs(curr_sum); start = i; end = i; } // Try all subarrays starting with i for (int j = i + 1; j < n; j++) { curr_sum = curr_sum + arr[j]; // update minimum sum // and subarray indexes if (min_sum > Math.abs(curr_sum)) { min_sum = Math.abs(curr_sum); start = i; end = j; } } } // Return starting and ending indexes Pair p = new Pair(start, end); return p; } // Drivers code public static void main(String[] args) { int arr[] = {2, -5, 4, -6, -3}; int n = arr.length; Pair point = findSubArray(arr, n); System.out.println("Subarray starting from " + point.first + " to " + point.second); }} // This code has been contributed by 29AjayKumar # Python 3 program to find subarray with# sum closest to 0import sys # Function to find the subarraydef findSubArray(arr, n): min_sum = sys.maxsize # Pick a starting point for i in range(n): # Consider current starting point # as a subarray and update minimum # sum and subarray indexes curr_sum = arr[i] if (min_sum > abs(curr_sum)): min_sum = abs(curr_sum) start = i end = i # Try all subarrays starting with i for j in range(i + 1, n, 1): curr_sum = curr_sum + arr[j] # update minimum sum # and subarray indexes if (min_sum > abs(curr_sum)): min_sum = abs(curr_sum) start = i end = j # Return starting and ending indexes p = [start, end] return p # Driver Codeif __name__ == '__main__': arr = [2, -5, 4, -6, -3] n = len(arr) point = findSubArray(arr, n) print("Subarray starting from ", end = "") print(point[0], "to", point[1]) # This code is contributed by# Surendra_Gangwar // C# program to find subarray with// sum closest to 0using System; class GFG{ public class Pair { public int first, second; public Pair(int first, int second) { this.first = first; this.second = second; } } // Function to find the subarray static Pair findSubArray(int []arr, int n) { int start = 0, end = 0, min_sum = int.MaxValue; // Pick a starting point for (int i = 0; i < n; i++) { // Consider current starting point // as a subarray and update minimum // sum and subarray indexes int curr_sum = arr[i]; if (min_sum > Math.Abs(curr_sum)) { min_sum = Math.Abs(curr_sum); start = i; end = i; } // Try all subarrays starting with i for (int j = i + 1; j < n; j++) { curr_sum = curr_sum + arr[j]; // update minimum sum // and subarray indexes if (min_sum > Math.Abs(curr_sum)) { min_sum = Math.Abs(curr_sum); start = i; end = j; } } } // Return starting and ending indexes Pair p = new Pair(start, end); return p; } // Drivers code public static void Main(String[] args) { int []arr = {2, -5, 4, -6, -3}; int n = arr.Length; Pair point = findSubArray(arr, n); Console.WriteLine("Subarray starting from " + point.first + " to " + point.second); }} // This code is contributed by Princi Singh <script> // JavaScript program to find subarray with// sum closest to 0 // Function to find the subarrayfunction findSubArray(arr, n) { let start, end, min_sum = Number.MAX_SAFE_INTEGER; // Pick a starting point for (let i = 0; i < n; i++) { // Consider current starting point // as a subarray and update minimum // sum and subarray indexes let curr_sum = arr[i]; if (min_sum > Math.abs(curr_sum)) { min_sum = Math.abs(curr_sum); start = i; end = i; } // Try all subarrays starting with i for (let j = i + 1; j < n; j++) { curr_sum = curr_sum + arr[j]; // update minimum sum // and subarray indexes if (min_sum > Math.abs(curr_sum)) { min_sum = Math.abs(curr_sum); start = i; end = j; } } } // Return starting and ending indexes let p = [start, end]; return p;} // Drivers code let arr = [2, -5, 4, -6, -3];let n = arr.length; let point = findSubArray(arr, n);document.write("Subarray starting from ");document.write(point[0] + " to " + point[1]); </script> Output: Subarray starting from 0 to 2 Time Complexity: O(n2)An Efficient method is to perform following steps:- Maintain a Prefix sum array . Also maintain indexes in the prefix sum array.Sort the prefix sum array on the basis of sum.Find the two elements in a prefix sum array with minimum difference. Maintain a Prefix sum array . Also maintain indexes in the prefix sum array. Sort the prefix sum array on the basis of sum. Find the two elements in a prefix sum array with minimum difference. i.e. Find min(pre_sum[i] - pre_sum[i-1]) Return indexes of pre_sum with minimum difference.Subarray with (lower_index+1, upper_index) will have the sum closest to 0.Taking lower_index+1 because on subtracting value at lower_index we get the sum closest to 0. That’s why lower_index need not to be included. Return indexes of pre_sum with minimum difference. Subarray with (lower_index+1, upper_index) will have the sum closest to 0. Taking lower_index+1 because on subtracting value at lower_index we get the sum closest to 0. That’s why lower_index need not to be included. C++ Java Python3 C# Javascript // C++ program to find subarray with sum// closest to 0#include <bits/stdc++.h>using namespace std; struct prefix { int sum; int index;}; // Sort on the basis of sumbool comparison(prefix a, prefix b){ return a.sum < b.sum;} // Returns subarray with sum closest to 0.pair<int, int> findSubArray(int arr[], int n){ int start, end, min_diff = INT_MAX; prefix pre_sum[n + 1]; // To consider the case of subarray starting // from beginning of the array pre_sum[0].sum = 0; pre_sum[0].index = -1; // Store prefix sum with index for (int i = 1; i <= n; i++) { pre_sum[i].sum = pre_sum[i-1].sum + arr[i-1]; pre_sum[i].index = i - 1; } // Sort on the basis of sum sort(pre_sum, pre_sum + (n + 1), comparison); // Find two consecutive elements with minimum difference for (int i = 1; i <= n; i++) { int diff = pre_sum[i].sum - pre_sum[i-1].sum; // Update minimum difference // and starting and ending indexes if (min_diff > diff) { min_diff = diff; start = pre_sum[i-1].index; end = pre_sum[i].index; } } // Return starting and ending indexes pair<int, int> p = make_pair(start + 1, end); return p;} // Drivers codeint main(){ int arr[] = { 2, 3, -4, -1, 6 }; int n = sizeof(arr) / sizeof(arr[0]); pair<int, int> point = findSubArray(arr, n); cout << "Subarray starting from "; cout << point.first << " to " << point.second; return 0;} // Java program to find subarray with sum// closest to 0import java.util.*; class Prefix{ int sum, index;} class Pair{ int first, second; Pair(int a, int b) { first = a; second = b; }} class GFG{ // Returns subarray with sum closest to 0.static Pair findSubArray(int arr[], int n){ int start = -1, end = -1, min_diff = Integer.MAX_VALUE; Prefix pre_sum[] = new Prefix[n + 1]; for(int i = 0; i < n + 1; i++) pre_sum[i] = new Prefix(); // To consider the case of subarray starting // from beginning of the array pre_sum[0].sum = 0; pre_sum[0].index = -1; // Store prefix sum with index for(int i = 1; i <= n; i++) { pre_sum[i].sum = pre_sum[i - 1].sum + arr[i - 1]; pre_sum[i].index = i - 1; } // Sort on the basis of sum Arrays.sort(pre_sum, ((a, b) -> a.sum - b.sum)); // Find two consecutive elements with minimum // difference for(int i = 1; i <= n; i++) { int diff = pre_sum[i].sum - pre_sum[i - 1].sum; // Update minimum difference // and starting and ending indexes if (min_diff > diff) { min_diff = diff; start = pre_sum[i - 1].index; end = pre_sum[i].index; } } // Return starting and ending indexes Pair p = new Pair(start + 1, end); return p;} // Driver codepublic static void main(String[] args){ int arr[] = { 2, 3, -4, -1, 6 }; int n = arr.length; Pair point = findSubArray(arr, n); System.out.print("Subarray starting from "); System.out.println(point.first + " to " + point.second);}} // This code is contributed by jrishabh99 # Python3 program to find subarray# with sum closest to 0class prefix: def __init__(self, sum, index): self.sum = sum self.index = index # Returns subarray with sum closest to 0.def findSubArray(arr, n): start, end, min_diff = None, None, float('inf') pre_sum = [None] * (n + 1) # To consider the case of subarray # starting from beginning of the array pre_sum[0] = prefix(0, -1) # Store prefix sum with index for i in range(1, n + 1): pre_sum[i] = prefix(pre_sum[i - 1].sum + arr[i - 1], i - 1) # Sort on the basis of sum pre_sum.sort(key = lambda x: x.sum) # Find two consecutive elements # with minimum difference for i in range(1, n + 1): diff = pre_sum[i].sum - pre_sum[i - 1].sum # Update minimum difference # and starting and ending indexes if min_diff > diff: min_diff = diff start = pre_sum[i - 1].index end = pre_sum[i].index # Return starting and ending indexes return (start + 1, end) # Driver codeif __name__ == "__main__": arr = [2, 3, -4, -1, 6] n = len(arr) point = findSubArray(arr, n) print("Subarray starting from", point[0], "to", point[1]) # This code is contributed by Rituraj Jain // C# program to find subarray with sum// closest to 0using System; class Prefix : IComparable<Prefix>{ public int sum, index; public int CompareTo(Prefix p) { return this.sum-p.sum; }} class Pair{ public int first, second; public Pair(int a, int b) { first = a; second = b; }} public class GFG{ // Returns subarray with sum closest to 0.static Pair findSubArray(int []arr, int n){ int start = -1, end = -1, min_diff = int.MaxValue; Prefix []pre_sum = new Prefix[n + 1]; for(int i = 0; i < n + 1; i++) pre_sum[i] = new Prefix(); // To consider the case of subarray starting // from beginning of the array pre_sum[0].sum = 0; pre_sum[0].index = -1; // Store prefix sum with index for(int i = 1; i <= n; i++) { pre_sum[i].sum = pre_sum[i - 1].sum + arr[i - 1]; pre_sum[i].index = i - 1; } // Sort on the basis of sum Array.Sort(pre_sum); // Find two consecutive elements with minimum // difference for(int i = 1; i <= n; i++) { int diff = pre_sum[i].sum - pre_sum[i - 1].sum; // Update minimum difference // and starting and ending indexes if (min_diff > diff) { min_diff = diff; start = pre_sum[i - 1].index; end = pre_sum[i].index; } } // Return starting and ending indexes Pair p = new Pair(start + 1, end); return p;} // Driver codepublic static void Main(String[] args){ int []arr = { 2, 3, -4, -1, 6 }; int n = arr.Length; Pair point = findSubArray(arr, n); Console.Write("Subarray starting from "); Console.WriteLine(point.first + " to " + point.second);}} // This code is contributed by 29AjayKumar <script>// Javascript program to find subarray with sum// closest to 0class Prefix{ constructor() { this.sum = 0; this.index = 0; }} class Pair{ constructor(a, b) { this.first = a; this.second = b; }} // Returns subarray with sum closest to 0.function findSubArray(arr, n){ let start = -1, end = -1, min_diff = Number.MAX_VALUE; let pre_sum = new Array(n + 1); for(let i = 0; i < n + 1; i++) pre_sum[i] = new Prefix(); // To consider the case of subarray starting // from beginning of the array pre_sum[0].sum = 0; pre_sum[0].index = -1; // Store prefix sum with index for(let i = 1; i <= n; i++) { pre_sum[i].sum = pre_sum[i - 1].sum + arr[i - 1]; pre_sum[i].index = i - 1; } // Sort on the basis of sum pre_sum.sort(function(a, b) {return a.sum - b.sum}); // Find two consecutive elements with minimum // difference for(let i = 1; i <= n; i++) { let diff = pre_sum[i].sum - pre_sum[i - 1].sum; // Update minimum difference // and starting and ending indexes if (min_diff > diff) { min_diff = diff; start = pre_sum[i - 1].index; end = pre_sum[i].index; } } // Return starting and ending indexes let p = new Pair(start + 1, end); return p;} // Driver codelet arr = [2, 3, -4, -1, 6 ];let n = arr.length;let point = findSubArray(arr, n);document.write("Subarray starting from ");document.write(point.first + " to " + point.second); // This code is contributed by rag2127</script> Output: Subarray starting from 0 to 3 Time Complexity: O(n log n)Reference: https://www.careercup.com/question?id=14583859This 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. SURENDRA_GANGWAR rituraj_jain 29AjayKumar princi singh jrishabh99 gfgking rag2127 Microsoft prefix-sum Arrays Sorting Microsoft prefix-sum Arrays Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Window Sliding Technique Trapping Rain Water Reversal algorithm for array rotation Move all negative numbers to beginning and positive to end with constant extra space Program to find sum of elements in a given array
[ { "code": null, "e": 24822, "s": 24794, "text": "\n17 Dec, 2021" }, { "code": null, "e": 25024, "s": 24822, "text": "Given an array of both positive and negative numbers, the task is to find out the subarray whose sum is closest to 0. There can be multiple such subarrays, we need to output just 1 of them. Examples: " }, { "code": null, "e": 25210, "s": 25024, "text": "Input : arr[] = {-1, 3, 2, -5, 4}\nOutput : 1, 3\nSubarray from index 1 to 3 has sum closest to 0 i.e.\n3 + 2 + -5 = 0\n\nInput : {2, -5, 4, -6, 3} \nOutput : 0, 2\n2 + -5 + 4 = 1 closest to 0" }, { "code": null, "e": 25232, "s": 25210, "text": "Asked in : Microsoft " }, { "code": null, "e": 25345, "s": 25232, "text": "A Naive approach is to consider all subarrays one by one and update indexes of subarray with sum closest to 0. " }, { "code": null, "e": 25349, "s": 25345, "text": "C++" }, { "code": null, "e": 25354, "s": 25349, "text": "Java" }, { "code": null, "e": 25362, "s": 25354, "text": "Python3" }, { "code": null, "e": 25365, "s": 25362, "text": "C#" }, { "code": null, "e": 25376, "s": 25365, "text": "Javascript" }, { "code": "// C++ program to find subarray with// sum closest to 0#include <bits/stdc++.h>using namespace std; // Function to find the subarraypair<int, int> findSubArray(int arr[], int n){ int start, end, min_sum = INT_MAX; // Pick a starting point for (int i = 0; i < n; i++) { // Consider current starting point // as a subarray and update minimum // sum and subarray indexes int curr_sum = arr[i]; if (min_sum > abs(curr_sum)) { min_sum = abs(curr_sum); start = i; end = i; } // Try all subarrays starting with i for (int j = i + 1; j < n; j++) { curr_sum = curr_sum + arr[j]; // update minimum sum // and subarray indexes if (min_sum > abs(curr_sum)) { min_sum = abs(curr_sum); start = i; end = j; } } } // Return starting and ending indexes pair<int, int> p = make_pair(start, end); return p;} // Drivers codeint main(){ int arr[] = { 2, -5, 4, -6, -3 }; int n = sizeof(arr) / sizeof(arr[0]); pair<int, int> point = findSubArray(arr, n); cout << \"Subarray starting from \"; cout << point.first << \" to \" << point.second; return 0;}", "e": 26644, "s": 25376, "text": null }, { "code": "// Java program to find subarray with// sum closest to 0 class GFG{ static class Pair { int first, second; public Pair(int first, int second) { this.first = first; this.second = second; } } // Function to find the subarray static Pair findSubArray(int arr[], int n) { int start = 0, end = 0, min_sum = Integer.MAX_VALUE; // Pick a starting point for (int i = 0; i < n; i++) { // Consider current starting point // as a subarray and update minimum // sum and subarray indexes int curr_sum = arr[i]; if (min_sum > Math.abs(curr_sum)) { min_sum = Math.abs(curr_sum); start = i; end = i; } // Try all subarrays starting with i for (int j = i + 1; j < n; j++) { curr_sum = curr_sum + arr[j]; // update minimum sum // and subarray indexes if (min_sum > Math.abs(curr_sum)) { min_sum = Math.abs(curr_sum); start = i; end = j; } } } // Return starting and ending indexes Pair p = new Pair(start, end); return p; } // Drivers code public static void main(String[] args) { int arr[] = {2, -5, 4, -6, -3}; int n = arr.length; Pair point = findSubArray(arr, n); System.out.println(\"Subarray starting from \" + point.first + \" to \" + point.second); }} // This code has been contributed by 29AjayKumar", "e": 28342, "s": 26644, "text": null }, { "code": "# Python 3 program to find subarray with# sum closest to 0import sys # Function to find the subarraydef findSubArray(arr, n): min_sum = sys.maxsize # Pick a starting point for i in range(n): # Consider current starting point # as a subarray and update minimum # sum and subarray indexes curr_sum = arr[i] if (min_sum > abs(curr_sum)): min_sum = abs(curr_sum) start = i end = i # Try all subarrays starting with i for j in range(i + 1, n, 1): curr_sum = curr_sum + arr[j] # update minimum sum # and subarray indexes if (min_sum > abs(curr_sum)): min_sum = abs(curr_sum) start = i end = j # Return starting and ending indexes p = [start, end] return p # Driver Codeif __name__ == '__main__': arr = [2, -5, 4, -6, -3] n = len(arr) point = findSubArray(arr, n) print(\"Subarray starting from \", end = \"\") print(point[0], \"to\", point[1]) # This code is contributed by# Surendra_Gangwar", "e": 29440, "s": 28342, "text": null }, { "code": "// C# program to find subarray with// sum closest to 0using System; class GFG{ public class Pair { public int first, second; public Pair(int first, int second) { this.first = first; this.second = second; } } // Function to find the subarray static Pair findSubArray(int []arr, int n) { int start = 0, end = 0, min_sum = int.MaxValue; // Pick a starting point for (int i = 0; i < n; i++) { // Consider current starting point // as a subarray and update minimum // sum and subarray indexes int curr_sum = arr[i]; if (min_sum > Math.Abs(curr_sum)) { min_sum = Math.Abs(curr_sum); start = i; end = i; } // Try all subarrays starting with i for (int j = i + 1; j < n; j++) { curr_sum = curr_sum + arr[j]; // update minimum sum // and subarray indexes if (min_sum > Math.Abs(curr_sum)) { min_sum = Math.Abs(curr_sum); start = i; end = j; } } } // Return starting and ending indexes Pair p = new Pair(start, end); return p; } // Drivers code public static void Main(String[] args) { int []arr = {2, -5, 4, -6, -3}; int n = arr.Length; Pair point = findSubArray(arr, n); Console.WriteLine(\"Subarray starting from \" + point.first + \" to \" + point.second); }} // This code is contributed by Princi Singh", "e": 31149, "s": 29440, "text": null }, { "code": "<script> // JavaScript program to find subarray with// sum closest to 0 // Function to find the subarrayfunction findSubArray(arr, n) { let start, end, min_sum = Number.MAX_SAFE_INTEGER; // Pick a starting point for (let i = 0; i < n; i++) { // Consider current starting point // as a subarray and update minimum // sum and subarray indexes let curr_sum = arr[i]; if (min_sum > Math.abs(curr_sum)) { min_sum = Math.abs(curr_sum); start = i; end = i; } // Try all subarrays starting with i for (let j = i + 1; j < n; j++) { curr_sum = curr_sum + arr[j]; // update minimum sum // and subarray indexes if (min_sum > Math.abs(curr_sum)) { min_sum = Math.abs(curr_sum); start = i; end = j; } } } // Return starting and ending indexes let p = [start, end]; return p;} // Drivers code let arr = [2, -5, 4, -6, -3];let n = arr.length; let point = findSubArray(arr, n);document.write(\"Subarray starting from \");document.write(point[0] + \" to \" + point[1]); </script>", "e": 32330, "s": 31149, "text": null }, { "code": null, "e": 32340, "s": 32330, "text": "Output: " }, { "code": null, "e": 32370, "s": 32340, "text": "Subarray starting from 0 to 2" }, { "code": null, "e": 32445, "s": 32370, "text": "Time Complexity: O(n2)An Efficient method is to perform following steps:- " }, { "code": null, "e": 32638, "s": 32445, "text": "Maintain a Prefix sum array . Also maintain indexes in the prefix sum array.Sort the prefix sum array on the basis of sum.Find the two elements in a prefix sum array with minimum difference. " }, { "code": null, "e": 32715, "s": 32638, "text": "Maintain a Prefix sum array . Also maintain indexes in the prefix sum array." }, { "code": null, "e": 32762, "s": 32715, "text": "Sort the prefix sum array on the basis of sum." }, { "code": null, "e": 32833, "s": 32762, "text": "Find the two elements in a prefix sum array with minimum difference. " }, { "code": null, "e": 32876, "s": 32833, "text": "i.e. Find min(pre_sum[i] - pre_sum[i-1]) " }, { "code": null, "e": 33142, "s": 32876, "text": "Return indexes of pre_sum with minimum difference.Subarray with (lower_index+1, upper_index) will have the sum closest to 0.Taking lower_index+1 because on subtracting value at lower_index we get the sum closest to 0. That’s why lower_index need not to be included." }, { "code": null, "e": 33193, "s": 33142, "text": "Return indexes of pre_sum with minimum difference." }, { "code": null, "e": 33268, "s": 33193, "text": "Subarray with (lower_index+1, upper_index) will have the sum closest to 0." }, { "code": null, "e": 33410, "s": 33268, "text": "Taking lower_index+1 because on subtracting value at lower_index we get the sum closest to 0. That’s why lower_index need not to be included." }, { "code": null, "e": 33414, "s": 33410, "text": "C++" }, { "code": null, "e": 33419, "s": 33414, "text": "Java" }, { "code": null, "e": 33427, "s": 33419, "text": "Python3" }, { "code": null, "e": 33430, "s": 33427, "text": "C#" }, { "code": null, "e": 33441, "s": 33430, "text": "Javascript" }, { "code": "// C++ program to find subarray with sum// closest to 0#include <bits/stdc++.h>using namespace std; struct prefix { int sum; int index;}; // Sort on the basis of sumbool comparison(prefix a, prefix b){ return a.sum < b.sum;} // Returns subarray with sum closest to 0.pair<int, int> findSubArray(int arr[], int n){ int start, end, min_diff = INT_MAX; prefix pre_sum[n + 1]; // To consider the case of subarray starting // from beginning of the array pre_sum[0].sum = 0; pre_sum[0].index = -1; // Store prefix sum with index for (int i = 1; i <= n; i++) { pre_sum[i].sum = pre_sum[i-1].sum + arr[i-1]; pre_sum[i].index = i - 1; } // Sort on the basis of sum sort(pre_sum, pre_sum + (n + 1), comparison); // Find two consecutive elements with minimum difference for (int i = 1; i <= n; i++) { int diff = pre_sum[i].sum - pre_sum[i-1].sum; // Update minimum difference // and starting and ending indexes if (min_diff > diff) { min_diff = diff; start = pre_sum[i-1].index; end = pre_sum[i].index; } } // Return starting and ending indexes pair<int, int> p = make_pair(start + 1, end); return p;} // Drivers codeint main(){ int arr[] = { 2, 3, -4, -1, 6 }; int n = sizeof(arr) / sizeof(arr[0]); pair<int, int> point = findSubArray(arr, n); cout << \"Subarray starting from \"; cout << point.first << \" to \" << point.second; return 0;}", "e": 34937, "s": 33441, "text": null }, { "code": "// Java program to find subarray with sum// closest to 0import java.util.*; class Prefix{ int sum, index;} class Pair{ int first, second; Pair(int a, int b) { first = a; second = b; }} class GFG{ // Returns subarray with sum closest to 0.static Pair findSubArray(int arr[], int n){ int start = -1, end = -1, min_diff = Integer.MAX_VALUE; Prefix pre_sum[] = new Prefix[n + 1]; for(int i = 0; i < n + 1; i++) pre_sum[i] = new Prefix(); // To consider the case of subarray starting // from beginning of the array pre_sum[0].sum = 0; pre_sum[0].index = -1; // Store prefix sum with index for(int i = 1; i <= n; i++) { pre_sum[i].sum = pre_sum[i - 1].sum + arr[i - 1]; pre_sum[i].index = i - 1; } // Sort on the basis of sum Arrays.sort(pre_sum, ((a, b) -> a.sum - b.sum)); // Find two consecutive elements with minimum // difference for(int i = 1; i <= n; i++) { int diff = pre_sum[i].sum - pre_sum[i - 1].sum; // Update minimum difference // and starting and ending indexes if (min_diff > diff) { min_diff = diff; start = pre_sum[i - 1].index; end = pre_sum[i].index; } } // Return starting and ending indexes Pair p = new Pair(start + 1, end); return p;} // Driver codepublic static void main(String[] args){ int arr[] = { 2, 3, -4, -1, 6 }; int n = arr.length; Pair point = findSubArray(arr, n); System.out.print(\"Subarray starting from \"); System.out.println(point.first + \" to \" + point.second);}} // This code is contributed by jrishabh99", "e": 36674, "s": 34937, "text": null }, { "code": "# Python3 program to find subarray# with sum closest to 0class prefix: def __init__(self, sum, index): self.sum = sum self.index = index # Returns subarray with sum closest to 0.def findSubArray(arr, n): start, end, min_diff = None, None, float('inf') pre_sum = [None] * (n + 1) # To consider the case of subarray # starting from beginning of the array pre_sum[0] = prefix(0, -1) # Store prefix sum with index for i in range(1, n + 1): pre_sum[i] = prefix(pre_sum[i - 1].sum + arr[i - 1], i - 1) # Sort on the basis of sum pre_sum.sort(key = lambda x: x.sum) # Find two consecutive elements # with minimum difference for i in range(1, n + 1): diff = pre_sum[i].sum - pre_sum[i - 1].sum # Update minimum difference # and starting and ending indexes if min_diff > diff: min_diff = diff start = pre_sum[i - 1].index end = pre_sum[i].index # Return starting and ending indexes return (start + 1, end) # Driver codeif __name__ == \"__main__\": arr = [2, 3, -4, -1, 6] n = len(arr) point = findSubArray(arr, n) print(\"Subarray starting from\", point[0], \"to\", point[1]) # This code is contributed by Rituraj Jain", "e": 37981, "s": 36674, "text": null }, { "code": "// C# program to find subarray with sum// closest to 0using System; class Prefix : IComparable<Prefix>{ public int sum, index; public int CompareTo(Prefix p) { return this.sum-p.sum; }} class Pair{ public int first, second; public Pair(int a, int b) { first = a; second = b; }} public class GFG{ // Returns subarray with sum closest to 0.static Pair findSubArray(int []arr, int n){ int start = -1, end = -1, min_diff = int.MaxValue; Prefix []pre_sum = new Prefix[n + 1]; for(int i = 0; i < n + 1; i++) pre_sum[i] = new Prefix(); // To consider the case of subarray starting // from beginning of the array pre_sum[0].sum = 0; pre_sum[0].index = -1; // Store prefix sum with index for(int i = 1; i <= n; i++) { pre_sum[i].sum = pre_sum[i - 1].sum + arr[i - 1]; pre_sum[i].index = i - 1; } // Sort on the basis of sum Array.Sort(pre_sum); // Find two consecutive elements with minimum // difference for(int i = 1; i <= n; i++) { int diff = pre_sum[i].sum - pre_sum[i - 1].sum; // Update minimum difference // and starting and ending indexes if (min_diff > diff) { min_diff = diff; start = pre_sum[i - 1].index; end = pre_sum[i].index; } } // Return starting and ending indexes Pair p = new Pair(start + 1, end); return p;} // Driver codepublic static void Main(String[] args){ int []arr = { 2, 3, -4, -1, 6 }; int n = arr.Length; Pair point = findSubArray(arr, n); Console.Write(\"Subarray starting from \"); Console.WriteLine(point.first + \" to \" + point.second);}} // This code is contributed by 29AjayKumar", "e": 39813, "s": 37981, "text": null }, { "code": "<script>// Javascript program to find subarray with sum// closest to 0class Prefix{ constructor() { this.sum = 0; this.index = 0; }} class Pair{ constructor(a, b) { this.first = a; this.second = b; }} // Returns subarray with sum closest to 0.function findSubArray(arr, n){ let start = -1, end = -1, min_diff = Number.MAX_VALUE; let pre_sum = new Array(n + 1); for(let i = 0; i < n + 1; i++) pre_sum[i] = new Prefix(); // To consider the case of subarray starting // from beginning of the array pre_sum[0].sum = 0; pre_sum[0].index = -1; // Store prefix sum with index for(let i = 1; i <= n; i++) { pre_sum[i].sum = pre_sum[i - 1].sum + arr[i - 1]; pre_sum[i].index = i - 1; } // Sort on the basis of sum pre_sum.sort(function(a, b) {return a.sum - b.sum}); // Find two consecutive elements with minimum // difference for(let i = 1; i <= n; i++) { let diff = pre_sum[i].sum - pre_sum[i - 1].sum; // Update minimum difference // and starting and ending indexes if (min_diff > diff) { min_diff = diff; start = pre_sum[i - 1].index; end = pre_sum[i].index; } } // Return starting and ending indexes let p = new Pair(start + 1, end); return p;} // Driver codelet arr = [2, 3, -4, -1, 6 ];let n = arr.length;let point = findSubArray(arr, n);document.write(\"Subarray starting from \");document.write(point.first + \" to \" + point.second); // This code is contributed by rag2127</script>", "e": 41494, "s": 39813, "text": null }, { "code": null, "e": 41504, "s": 41494, "text": "Output: " }, { "code": null, "e": 41534, "s": 41504, "text": "Subarray starting from 0 to 3" }, { "code": null, "e": 42040, "s": 41534, "text": "Time Complexity: O(n log n)Reference: https://www.careercup.com/question?id=14583859This 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": 42057, "s": 42040, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 42070, "s": 42057, "text": "rituraj_jain" }, { "code": null, "e": 42082, "s": 42070, "text": "29AjayKumar" }, { "code": null, "e": 42095, "s": 42082, "text": "princi singh" }, { "code": null, "e": 42106, "s": 42095, "text": "jrishabh99" }, { "code": null, "e": 42114, "s": 42106, "text": "gfgking" }, { "code": null, "e": 42122, "s": 42114, "text": "rag2127" }, { "code": null, "e": 42132, "s": 42122, "text": "Microsoft" }, { "code": null, "e": 42143, "s": 42132, "text": "prefix-sum" }, { "code": null, "e": 42150, "s": 42143, "text": "Arrays" }, { "code": null, "e": 42158, "s": 42150, "text": "Sorting" }, { "code": null, "e": 42168, "s": 42158, "text": "Microsoft" }, { "code": null, "e": 42179, "s": 42168, "text": "prefix-sum" }, { "code": null, "e": 42186, "s": 42179, "text": "Arrays" }, { "code": null, "e": 42194, "s": 42186, "text": "Sorting" }, { "code": null, "e": 42292, "s": 42194, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42317, "s": 42292, "text": "Window Sliding Technique" }, { "code": null, "e": 42337, "s": 42317, "text": "Trapping Rain Water" }, { "code": null, "e": 42375, "s": 42337, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 42460, "s": 42375, "text": "Move all negative numbers to beginning and positive to end with constant extra space" } ]
How to prevent going back to the previous activity in Android?
There are so many situations, where we should not call back action when user click on back button. This example demonstrates how to integrate Android Login and register form. 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/actvity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:id = "@+id/parent" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" android:gravity = "center" android:orientation = "vertical"> <EditText android:id = "@+id/enterNumber" android:layout_width = "match_parent" android:hint = "Enter phone number" android:layout_height = "wrap_content" /> <TextView android:id = "@+id/text" android:textSize = "18sp" android:textAlignment = "center" android:text = "click" android:layout_width = "match_parent" android:layout_height = "wrap_content" /> </LinearLayout> Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.widget.Toast; public class MainActivity extends AppCompatActivity { int view = R.layout.activity_main; @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(view); } @Override public void onBackPressed() { // super.onBackPressed(); Toast.makeText(MainActivity.this,"There is no back action",Toast.LENGTH_LONG).show(); return; } } In the above, we have taken onBackPressed(), when user click on back button, it going to return empty as shown below - @Override public void onBackPressed() { // super.onBackPressed(); Toast.makeText(MainActivity.this,"There is no back action",Toast.LENGTH_LONG).show(); return; } Step 4 − Add the following code to manifest.java <?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.example.andy.myapplication"> <uses-permission android:name = "android.permission.VIBRATE" /> <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" android:noHistory = "true" android:screenOrientation = "portrait"> <intent-filter> <action android:name = "android.intent.action.MAIN" /> <category android:name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> In the above we have declared no History value is true means Main Activity doesn't maintain any previous activity information in activity manager. Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − In the above result, it has shown the default screen. When you click on back button, it will do nothing as shown below - Click here to download the project code
[ { "code": null, "e": 1161, "s": 1062, "text": "There are so many situations, where we should not call back action when user click on back button." }, { "code": null, "e": 1237, "s": 1161, "text": "This example demonstrates how to integrate Android Login and register form." }, { "code": null, "e": 1366, "s": 1237, "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": 1430, "s": 1366, "text": "Step 2 − Add the following code to res/layout/actvity_main.xml." }, { "code": null, "e": 2252, "s": 1430, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n android:id = \"@+id/parent\"\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 android:gravity = \"center\"\n android:orientation = \"vertical\">\n <EditText\n android:id = \"@+id/enterNumber\"\n android:layout_width = \"match_parent\"\n android:hint = \"Enter phone number\"\n android:layout_height = \"wrap_content\" />\n <TextView\n android:id = \"@+id/text\"\n android:textSize = \"18sp\"\n android:textAlignment = \"center\"\n android:text = \"click\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\" />\n</LinearLayout>" }, { "code": null, "e": 2309, "s": 2252, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3006, "s": 2309, "text": "package com.example.andy.myapplication;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n int view = R.layout.activity_main;\n @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(view);\n }\n @Override\n public void onBackPressed() {\n // super.onBackPressed();\n Toast.makeText(MainActivity.this,\"There is no back action\",Toast.LENGTH_LONG).show();\n return;\n }\n}" }, { "code": null, "e": 3125, "s": 3006, "text": "In the above, we have taken onBackPressed(), when user click on back button, it going to return empty as shown below -" }, { "code": null, "e": 3296, "s": 3125, "text": "@Override\npublic void onBackPressed() {\n // super.onBackPressed();\n Toast.makeText(MainActivity.this,\"There is no back action\",Toast.LENGTH_LONG).show();\n return;\n}" }, { "code": null, "e": 3345, "s": 3296, "text": "Step 4 − Add the following code to manifest.java" }, { "code": null, "e": 4220, "s": 3345, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.andy.myapplication\">\n <uses-permission android:name = \"android.permission.VIBRATE\" />\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\n android:name = \".MainActivity\"\n android:noHistory = \"true\"\n android:screenOrientation = \"portrait\">\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": 4367, "s": 4220, "text": "In the above we have declared no History value is true means Main Activity doesn't maintain any previous activity information in activity manager." }, { "code": null, "e": 4714, "s": 4367, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 4835, "s": 4714, "text": "In the above result, it has shown the default screen. When you click on back button, it will do nothing as shown below -" }, { "code": null, "e": 4875, "s": 4835, "text": "Click here to download the project code" } ]
Cucumber - Reports
We do test execution in order to understand the stability of a product, so be it manual test or an automated test, it is very important to generate a concise report that can depict the stability of a product. Hence, while we are automating our test scenario with Cucumber, it is essential to know, how better we can generate our Cucumber test reports. As we know that Cucumber is a BDD framework, it does not have a fancy reporting mechanism. In order to achieve this, we need to integrate Cucumber with other open source tool like Ant/Junit. Here, we will take examples of JUnit further because, it provides support for Java language. Let’s look into the details of different report format, which is available and easy to use − Pretty Format generates the Cucumber test report in the HTML format, i.e. an HTML file. It is the most readable report format. It generates the report in the same way as it is a feature file, so tracing is also made easy. Also, you can specify the location where you want this report to be placed after the test execution. It can be − Local Directory − We can specify target directory for report as any local directory of the machine where the test will run. Local Directory − We can specify target directory for report as any local directory of the machine where the test will run. Server Directory − Also we have a provision to specify a target directory as any directory on the server, which is publically accessible. This generally helps when we want our clients/stakeholders to view the test results at any given point of time. Server Directory − Also we have a provision to specify a target directory as any directory on the server, which is publically accessible. This generally helps when we want our clients/stakeholders to view the test results at any given point of time. Let’s automate an example of a pretty format. Step 1 − Create a Maven project named cucumberReport in Eclipse. Step 2 − Create a package named CucumberReport under src/test/java Step 3 − Create a feature file named cucumberReport.feature Write the following text within the file and save it. Feature − Cucumber Report #This is to check test result for Pass test case Scenario: Login functionality exists Given I have opened the browser When I open Facebook website Then Login button should exist #This is to check test result for Failed test case Scenario: Forgot password exists Given I have open the browser When I open Facebook website Then Forgot password link should exist Note − Here scenario first will pass, whereas the second scenario will fail. So that we can witness how the pass and failed report looks like. Step 4 − Create a step definition file. Select and right-click on the package outline. Select and right-click on the package outline. Click on ‘New’ file. Click on ‘New’ file. Give the file name as cucumberReport.java Give the file name as cucumberReport.java Write the following text within the file and save it. Write the following text within the file and save it. package CucumberReport; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import cucumber.annotation.en.Given; import cucumber.annotation.en.Then; import cucumber.annotation.en.When; public class cucumberReport { WebDriver driver = null; @Given("^I have open the browser$") public void openBrowser() { driver = new FirefoxDriver(); } @When("^I open Facebook website$") public void goToFacebook() { driver.navigate().to("https://www.facebook.com/"); } @Then("^Login button should exits$") public void loginButton() { if(driver.findElement(By.id("u_0_v")).isEnabled()) { System.out.println("Test 1 Pass"); } else { System.out.println("Test 1 Fail"); } } @Then("^Forgot password link should exist$") public void forgotPWD() { if(driver.findElement(By.id("")).isEnabled()) { System.out.println("Test 1 Pass"); } else { System.out.println("Test 1 Fail"); } } } Step 5 − Create a runner class file. Create a runner class named runTest.java inside the package. Create a runner class named runTest.java inside the package. Write the following code. Save the file. Write the following code. Save the file. package CucumberReport; import org.junit.runner.RunWith; import cucumber.junit.Cucumber; @RunWith(Cucumber.class) @Cucumber.Options( format = {"pretty", "html:target/Destination"} ) //Specifying pretty as a format option ensure that HTML report will be generated. //When we specify html:target/Destination - It will generate the HTML report inside the Destination folder, in the target folder of the maven project. public class runTest { } Run the test using option Select runTest.java file from package explorer. Right-click and select the option, Run as. Select JUnit test. Run the test using option Select runTest.java file from package explorer. Select runTest.java file from package explorer. Right-click and select the option, Run as. Right-click and select the option, Run as. Select JUnit test. Select JUnit test. You will observe the following things when you run this class file. Both the scenario will get executed one by one. A folder named Destination will be created inside the target directory. The report will be there named as “Index.html”. Open Index.html with web browser. You will see the report mentioned in the following image − It exactly highlights the color of failed scenario. Moreover, you will see highlight for failed step in that scenario. This makes the debugging very easy. By now we have seen how easy HTML report is. However, if we want to pass on this report information to any other application, that’s kind of tricky in case of HTML reports. Here comes the need of another reporting format. JSON-Java script object notation is another format for generating Cucumber test reports. JSON is an object containing a lot of information stored in text format. JSON reports bring a different value to the table. JSON report can also be used as a payload of information to be transferred between different servers. Further, it can be used to be displayed as a web page. In a nutshell, JSON reports can be used by other application. What is payload information? When data is sent over the Internet, each unit transmitted includes both header information and the actual data being sent. The header identifies the source and destination of the packet, while the actual data is referred to as the payload. In order to generate a JSON report, we just need to make a change in the runner file. Change the format option in the runner file as follows. Change the format option in the runner file as follows. package CucumberReport; import org.junit.runner.RunWith; import cucumber.junit.Cucumber; @RunWith(Cucumber.class) @Cucumber.Options( format={"json:target/Destination/cucumber.json"}) //When we specify json:target/Destination/cucumber.json - It will generate the JSON report inside the Destination folder, in the target folder of the maven project. public class runTest {} Run the test using option − Select runTest.java file from package explorer. Right click and select option Run as. Select JUnit test. Run the test using option − Select runTest.java file from package explorer. Select runTest.java file from package explorer. Right click and select option Run as. Right click and select option Run as. Select JUnit test. Select JUnit test. You will observe the following things when you run this class file. Both the scenario will get executed one by one. You will observe the following things when you run this class file. Both the scenario will get executed one by one. Both the scenario will get executed one by one. The report will be there named as cucumber.json (as provided in runner class). The report will be there named as cucumber.json (as provided in runner class). Open cucumber.json file with the text editor. Open cucumber.json file with the text editor. You will see the report mentioned in the following screenshot after placing line breaks − You will see the report mentioned in the following screenshot after placing line breaks − Note − JSON is less readable as compared to the HTML report format. Print Add Notes Bookmark this page
[ { "code": null, "e": 2405, "s": 1962, "text": "We do test execution in order to understand the stability of a product, so be it manual test or an automated test, it is very important to generate a concise report that can depict the stability of a product. Hence, while we are automating our test scenario with Cucumber, it is essential to know, how better we can generate our Cucumber test reports. As we know that Cucumber is a BDD framework, it does not have a fancy reporting mechanism." }, { "code": null, "e": 2598, "s": 2405, "text": "In order to achieve this, we need to integrate Cucumber with other open source tool like Ant/Junit. Here, we will take examples of JUnit further because, it provides support for Java language." }, { "code": null, "e": 2691, "s": 2598, "text": "Let’s look into the details of different report format, which is available and easy to use −" }, { "code": null, "e": 3026, "s": 2691, "text": "Pretty Format generates the Cucumber test report in the HTML format, i.e. an HTML file. It is the most readable report format. It generates the report in the same way as it is a feature file, so tracing is also made easy. Also, you can specify the location where you want this report to be placed after the test execution. It can be −" }, { "code": null, "e": 3150, "s": 3026, "text": "Local Directory − We can specify target directory for report as any local directory of the machine where the test will run." }, { "code": null, "e": 3274, "s": 3150, "text": "Local Directory − We can specify target directory for report as any local directory of the machine where the test will run." }, { "code": null, "e": 3524, "s": 3274, "text": "Server Directory − Also we have a provision to specify a target directory as any directory on the server, which is publically accessible. This generally helps when we want our clients/stakeholders to view the test results at any given point of time." }, { "code": null, "e": 3774, "s": 3524, "text": "Server Directory − Also we have a provision to specify a target directory as any directory on the server, which is publically accessible. This generally helps when we want our clients/stakeholders to view the test results at any given point of time." }, { "code": null, "e": 3820, "s": 3774, "text": "Let’s automate an example of a pretty format." }, { "code": null, "e": 3885, "s": 3820, "text": "Step 1 − Create a Maven project named cucumberReport in Eclipse." }, { "code": null, "e": 3952, "s": 3885, "text": "Step 2 − Create a package named CucumberReport under src/test/java" }, { "code": null, "e": 4012, "s": 3952, "text": "Step 3 − Create a feature file named cucumberReport.feature" }, { "code": null, "e": 4066, "s": 4012, "text": "Write the following text within the file and save it." }, { "code": null, "e": 4092, "s": 4066, "text": "Feature − Cucumber Report" }, { "code": null, "e": 4141, "s": 4092, "text": "#This is to check test result for Pass test case" }, { "code": null, "e": 4178, "s": 4141, "text": "Scenario: Login functionality exists" }, { "code": null, "e": 4210, "s": 4178, "text": "Given I have opened the browser" }, { "code": null, "e": 4239, "s": 4210, "text": "When I open Facebook website" }, { "code": null, "e": 4270, "s": 4239, "text": "Then Login button should exist" }, { "code": null, "e": 4321, "s": 4270, "text": "#This is to check test result for Failed test case" }, { "code": null, "e": 4354, "s": 4321, "text": "Scenario: Forgot password exists" }, { "code": null, "e": 4384, "s": 4354, "text": "Given I have open the browser" }, { "code": null, "e": 4413, "s": 4384, "text": "When I open Facebook website" }, { "code": null, "e": 4452, "s": 4413, "text": "Then Forgot password link should exist" }, { "code": null, "e": 4595, "s": 4452, "text": "Note − Here scenario first will pass, whereas the second scenario will fail. So that we can witness how the pass and failed report looks like." }, { "code": null, "e": 4635, "s": 4595, "text": "Step 4 − Create a step definition file." }, { "code": null, "e": 4682, "s": 4635, "text": "Select and right-click on the package outline." }, { "code": null, "e": 4729, "s": 4682, "text": "Select and right-click on the package outline." }, { "code": null, "e": 4750, "s": 4729, "text": "Click on ‘New’ file." }, { "code": null, "e": 4771, "s": 4750, "text": "Click on ‘New’ file." }, { "code": null, "e": 4813, "s": 4771, "text": "Give the file name as cucumberReport.java" }, { "code": null, "e": 4855, "s": 4813, "text": "Give the file name as cucumberReport.java" }, { "code": null, "e": 4909, "s": 4855, "text": "Write the following text within the file and save it." }, { "code": null, "e": 4963, "s": 4909, "text": "Write the following text within the file and save it." }, { "code": null, "e": 6050, "s": 4963, "text": "package CucumberReport;\n \nimport org.openqa.selenium.By; \nimport org.openqa.selenium.WebDriver; \nimport org.openqa.selenium.firefox.FirefoxDriver; \n\nimport cucumber.annotation.en.Given; \nimport cucumber.annotation.en.Then; \nimport cucumber.annotation.en.When; \n\npublic class cucumberReport { \n WebDriver driver = null; \n\t\n @Given(\"^I have open the browser$\") \n public void openBrowser() { \n driver = new FirefoxDriver();\n } \n\t\n @When(\"^I open Facebook website$\") \n public void goToFacebook() { \n driver.navigate().to(\"https://www.facebook.com/\"); \n } \n\t\n @Then(\"^Login button should exits$\") \n public void loginButton() { \n if(driver.findElement(By.id(\"u_0_v\")).isEnabled()) { \n System.out.println(\"Test 1 Pass\"); \n } else { \n System.out.println(\"Test 1 Fail\");\n }\n } \n\t\n @Then(\"^Forgot password link should exist$\") \n public void forgotPWD() { \n if(driver.findElement(By.id(\"\")).isEnabled()) { \n System.out.println(\"Test 1 Pass\"); \n } else {\n System.out.println(\"Test 1 Fail\");\n } \n } \n}" }, { "code": null, "e": 6087, "s": 6050, "text": "Step 5 − Create a runner class file." }, { "code": null, "e": 6148, "s": 6087, "text": "Create a runner class named runTest.java inside the package." }, { "code": null, "e": 6209, "s": 6148, "text": "Create a runner class named runTest.java inside the package." }, { "code": null, "e": 6250, "s": 6209, "text": "Write the following code. Save the file." }, { "code": null, "e": 6291, "s": 6250, "text": "Write the following code. Save the file." }, { "code": null, "e": 6749, "s": 6291, "text": "package CucumberReport; \n\nimport org.junit.runner.RunWith; \nimport cucumber.junit.Cucumber; \n\n@RunWith(Cucumber.class) \n@Cucumber.Options( \n format = {\"pretty\", \"html:target/Destination\"} ) \n\t\n//Specifying pretty as a format option ensure that HTML report will be generated. \n//When we specify html:target/Destination - It will generate the HTML report \n\ninside the Destination folder, in the target folder of the maven project. \n\npublic class runTest { }" }, { "code": null, "e": 6887, "s": 6749, "text": "Run the test using option\n\nSelect runTest.java file from package explorer.\nRight-click and select the option, Run as.\nSelect JUnit test.\n" }, { "code": null, "e": 6913, "s": 6887, "text": "Run the test using option" }, { "code": null, "e": 6961, "s": 6913, "text": "Select runTest.java file from package explorer." }, { "code": null, "e": 7009, "s": 6961, "text": "Select runTest.java file from package explorer." }, { "code": null, "e": 7052, "s": 7009, "text": "Right-click and select the option, Run as." }, { "code": null, "e": 7095, "s": 7052, "text": "Right-click and select the option, Run as." }, { "code": null, "e": 7114, "s": 7095, "text": "Select JUnit test." }, { "code": null, "e": 7133, "s": 7114, "text": "Select JUnit test." }, { "code": null, "e": 7201, "s": 7133, "text": "You will observe the following things when you run this class file." }, { "code": null, "e": 7249, "s": 7201, "text": "Both the scenario will get executed one by one." }, { "code": null, "e": 7321, "s": 7249, "text": "A folder named Destination will be created inside the target directory." }, { "code": null, "e": 7369, "s": 7321, "text": "The report will be there named as “Index.html”." }, { "code": null, "e": 7403, "s": 7369, "text": "Open Index.html with web browser." }, { "code": null, "e": 7462, "s": 7403, "text": "You will see the report mentioned in the following image −" }, { "code": null, "e": 7617, "s": 7462, "text": "It exactly highlights the color of failed scenario. Moreover, you will see highlight for failed step in that scenario. This makes the debugging very easy." }, { "code": null, "e": 8271, "s": 7617, "text": "By now we have seen how easy HTML report is. However, if we want to pass on this report information to any other application, that’s kind of tricky in case of HTML reports. Here comes the need of another reporting format. JSON-Java script object notation is another format for generating Cucumber test reports. JSON is an object containing a lot of information stored in text format. JSON reports bring a different value to the table. JSON report can also be used as a payload of information to be transferred between different servers. Further, it can be used to be displayed as a web page. In a nutshell, JSON reports can be used by other application." }, { "code": null, "e": 8627, "s": 8271, "text": "What is payload information? When data is sent over the Internet, each unit transmitted includes both header information and the actual data being sent. The header identifies the source and destination of the packet, while the actual data is referred to as the payload. In order to generate a JSON report, we just need to make a change in the runner file." }, { "code": null, "e": 8683, "s": 8627, "text": "Change the format option in the runner file as follows." }, { "code": null, "e": 8739, "s": 8683, "text": "Change the format option in the runner file as follows." }, { "code": null, "e": 9122, "s": 8739, "text": "package CucumberReport; \n\nimport org.junit.runner.RunWith; \nimport cucumber.junit.Cucumber; \n\n@RunWith(Cucumber.class) \n@Cucumber.Options( format={\"json:target/Destination/cucumber.json\"}) \n\n//When we specify json:target/Destination/cucumber.json - It will generate the JSON \nreport inside the Destination folder, in the target folder of the maven project.\n\npublic class runTest {}" }, { "code": null, "e": 9257, "s": 9122, "text": "Run the test using option −\n\nSelect runTest.java file from package explorer.\nRight click and select option Run as.\nSelect JUnit test.\n" }, { "code": null, "e": 9285, "s": 9257, "text": "Run the test using option −" }, { "code": null, "e": 9333, "s": 9285, "text": "Select runTest.java file from package explorer." }, { "code": null, "e": 9381, "s": 9333, "text": "Select runTest.java file from package explorer." }, { "code": null, "e": 9419, "s": 9381, "text": "Right click and select option Run as." }, { "code": null, "e": 9457, "s": 9419, "text": "Right click and select option Run as." }, { "code": null, "e": 9476, "s": 9457, "text": "Select JUnit test." }, { "code": null, "e": 9495, "s": 9476, "text": "Select JUnit test." }, { "code": null, "e": 9613, "s": 9495, "text": "You will observe the following things when you run this class file.\n\nBoth the scenario will get executed one by one.\n" }, { "code": null, "e": 9681, "s": 9613, "text": "You will observe the following things when you run this class file." }, { "code": null, "e": 9729, "s": 9681, "text": "Both the scenario will get executed one by one." }, { "code": null, "e": 9777, "s": 9729, "text": "Both the scenario will get executed one by one." }, { "code": null, "e": 9856, "s": 9777, "text": "The report will be there named as cucumber.json (as provided in runner class)." }, { "code": null, "e": 9935, "s": 9856, "text": "The report will be there named as cucumber.json (as provided in runner class)." }, { "code": null, "e": 9981, "s": 9935, "text": "Open cucumber.json file with the text editor." }, { "code": null, "e": 10027, "s": 9981, "text": "Open cucumber.json file with the text editor." }, { "code": null, "e": 10117, "s": 10027, "text": "You will see the report mentioned in the following screenshot after placing line breaks −" }, { "code": null, "e": 10207, "s": 10117, "text": "You will see the report mentioned in the following screenshot after placing line breaks −" }, { "code": null, "e": 10275, "s": 10207, "text": "Note − JSON is less readable as compared to the HTML report format." }, { "code": null, "e": 10282, "s": 10275, "text": " Print" }, { "code": null, "e": 10293, "s": 10282, "text": " Add Notes" } ]
Create a simple calculator using Java Swing
Swing API is a set of extensible GUI Components to ease the developer's life to create JAVA based Front End/GUI Applications. It is built on top of AWT API and acts as a replacement of AWT API since it has almost every control corresponding to AWT controls. Following example showcases a simple calculator application. import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; public class Calculator implements ActionListener { private static JTextField inputBox; Calculator(){} public static void main(String[] args) { createWindow(); } private static void createWindow() { JFrame frame = new JFrame("Calculator"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); createUI(frame); frame.setSize(200, 200); frame.setLocationRelativeTo(null); frame.setVisible(true); } private static void createUI(JFrame frame) { JPanel panel = new JPanel(); Calculator calculator = new Calculator(); GridBagLayout layout = new GridBagLayout(); GridBagConstraints gbc = new GridBagConstraints(); panel.setLayout(layout); inputBox = new JTextField(10); inputBox.setEditable(false); JButton button0 = new JButton("0");JButton button1 = new JButton("1"); JButton button2 = new JButton("2");JButton button3 = new JButton("3"); JButton button4 = new JButton("4");JButton button5 = new JButton("5"); JButton button6 = new JButton("6");JButton button7 = new JButton("7"); JButton button8 = new JButton("8");JButton button9 = new JButton("9"); JButton buttonPlus = new JButton("+");JButton buttonMinus = new JButton("-"); JButton buttonDivide = new JButton("/");JButton buttonMultiply = new JButton("x"); JButton buttonClear = new JButton("C");JButton buttonDot = new JButton("."); JButton buttonEquals = new JButton("="); button1.addActionListener(calculator);button2.addActionListener(calculator); button3.addActionListener(calculator);button4.addActionListener(calculator); button5.addActionListener(calculator);button6.addActionListener(calculator); button7.addActionListener(calculator);button8.addActionListener(calculator); button9.addActionListener(calculator);button0.addActionListener(calculator); buttonPlus.addActionListener(calculator);buttonMinus.addActionListener(calculator); buttonDivide.addActionListener(calculator);buttonMultiply.addActionListener(calculator); buttonClear.addActionListener(calculator);buttonDot.addActionListener(calculator); buttonEquals.addActionListener(calculator); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridx = 0; gbc.gridy = 0; panel.add(button1, gbc); gbc.gridx = 1; gbc.gridy = 0; panel.add(button2, gbc); gbc.gridx = 2; gbc.gridy = 0; panel.add(button3, gbc); gbc.gridx = 3; gbc.gridy = 0; panel.add(buttonPlus, gbc); gbc.gridx = 0; gbc.gridy = 1; panel.add(button4, gbc); gbc.gridx = 1; gbc.gridy = 1; panel.add(button5, gbc); gbc.gridx = 2; gbc.gridy = 1; panel.add(button6, gbc); gbc.gridx = 3; gbc.gridy = 1; panel.add(buttonMinus, gbc); gbc.gridx = 0; gbc.gridy = 2; panel.add(button7, gbc); gbc.gridx = 1; gbc.gridy = 2; panel.add(button8, gbc); gbc.gridx = 2; gbc.gridy = 2; panel.add(button9, gbc); gbc.gridx = 3; gbc.gridy = 2; panel.add(buttonDivide, gbc); gbc.gridx = 0; gbc.gridy = 3; panel.add(buttonDot, gbc); gbc.gridx = 1; gbc.gridy = 3; panel.add(button0, gbc); gbc.gridx = 2; gbc.gridy = 3; panel.add(buttonClear, gbc); gbc.gridx = 3; gbc.gridy = 3; panel.add(buttonMultiply, gbc); gbc.gridwidth = 3; gbc.gridx = 0; gbc.gridy = 4; panel.add(inputBox, gbc); gbc.gridx = 3; gbc.gridy = 4; panel.add(buttonEquals, gbc); frame.getContentPane().add(panel, BorderLayout.CENTER); } public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command.charAt(0) == 'C') { inputBox.setText(""); }else if (command.charAt(0) == '=') { inputBox.setText(evaluate(inputBox.getText())); }else { inputBox.setText(inputBox.getText() + command); } } public static String evaluate(String expression) { char[] arr = expression.toCharArray(); String operand1 = "";String operand2 = "";String operator = ""; double result = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] >= '0' && arr[i] <= '9' || arr[i] == '.') { if(operator.isEmpty()){ operand1 += arr[i]; }else{ operand2 += arr[i]; } } if(arr[i] == '+' || arr[i] == '-' || arr[i] == '/' || arr[i] == '*') { operator += arr[i]; } } if (operator.equals("+")) result = (Double.parseDouble(operand1) + Double.parseDouble(operand2)); else if (operator.equals("-")) result = (Double.parseDouble(operand1) - Double.parseDouble(operand2)); else if (operator.equals("/")) result = (Double.parseDouble(operand1) / Double.parseDouble(operand2)); else result = (Double.parseDouble(operand1) * Double.parseDouble(operand2)); return operand1 + operator + operand2 + "=" +result; } }
[ { "code": null, "e": 1320, "s": 1062, "text": "Swing API is a set of extensible GUI Components to ease the developer's life to create JAVA based Front End/GUI Applications. It is built on top of AWT API and acts as a replacement of AWT API since it has almost every control corresponding to AWT controls." }, { "code": null, "e": 1381, "s": 1320, "text": "Following example showcases a simple calculator application." }, { "code": null, "e": 6777, "s": 1381, "text": "import java.awt.BorderLayout;\nimport java.awt.GridBagConstraints;\nimport java.awt.GridBagLayout;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\nimport javax.swing.JTextField;\n\npublic class Calculator implements ActionListener {\n private static JTextField inputBox;\n\n Calculator(){}\n public static void main(String[] args) {\n createWindow();\n }\n\n private static void createWindow() { \n JFrame frame = new JFrame(\"Calculator\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n createUI(frame);\n frame.setSize(200, 200); \n frame.setLocationRelativeTo(null);\n frame.setVisible(true);\n }\n\n private static void createUI(JFrame frame) {\n JPanel panel = new JPanel();\n Calculator calculator = new Calculator();\n GridBagLayout layout = new GridBagLayout(); \n GridBagConstraints gbc = new GridBagConstraints();\n panel.setLayout(layout);\n \n inputBox = new JTextField(10); \n inputBox.setEditable(false);\n\n JButton button0 = new JButton(\"0\");JButton button1 = new JButton(\"1\");\n JButton button2 = new JButton(\"2\");JButton button3 = new JButton(\"3\");\n JButton button4 = new JButton(\"4\");JButton button5 = new JButton(\"5\");\n JButton button6 = new JButton(\"6\");JButton button7 = new JButton(\"7\");\n JButton button8 = new JButton(\"8\");JButton button9 = new JButton(\"9\");\n\n JButton buttonPlus = new JButton(\"+\");JButton buttonMinus = new JButton(\"-\");\n JButton buttonDivide = new JButton(\"/\");JButton buttonMultiply = new JButton(\"x\");\n JButton buttonClear = new JButton(\"C\");JButton buttonDot = new JButton(\".\");\n JButton buttonEquals = new JButton(\"=\");\n\n button1.addActionListener(calculator);button2.addActionListener(calculator);\n button3.addActionListener(calculator);button4.addActionListener(calculator);\n button5.addActionListener(calculator);button6.addActionListener(calculator);\n button7.addActionListener(calculator);button8.addActionListener(calculator);\n button9.addActionListener(calculator);button0.addActionListener(calculator);\n\n buttonPlus.addActionListener(calculator);buttonMinus.addActionListener(calculator);\n buttonDivide.addActionListener(calculator);buttonMultiply.addActionListener(calculator);\n buttonClear.addActionListener(calculator);buttonDot.addActionListener(calculator);\n buttonEquals.addActionListener(calculator);\n\n gbc.fill = GridBagConstraints.HORIZONTAL;\n gbc.gridx = 0; gbc.gridy = 0; panel.add(button1, gbc); \n gbc.gridx = 1; gbc.gridy = 0; panel.add(button2, gbc);\n gbc.gridx = 2; gbc.gridy = 0; panel.add(button3, gbc);\n gbc.gridx = 3; gbc.gridy = 0; panel.add(buttonPlus, gbc);\n gbc.gridx = 0; gbc.gridy = 1; panel.add(button4, gbc);\n gbc.gridx = 1; gbc.gridy = 1; panel.add(button5, gbc);\n gbc.gridx = 2; gbc.gridy = 1; panel.add(button6, gbc);\n gbc.gridx = 3; gbc.gridy = 1; panel.add(buttonMinus, gbc);\n gbc.gridx = 0; gbc.gridy = 2; panel.add(button7, gbc);\n gbc.gridx = 1; gbc.gridy = 2; panel.add(button8, gbc);\n gbc.gridx = 2; gbc.gridy = 2; panel.add(button9, gbc);\n gbc.gridx = 3; gbc.gridy = 2; panel.add(buttonDivide, gbc);\n gbc.gridx = 0; gbc.gridy = 3; panel.add(buttonDot, gbc);\n gbc.gridx = 1; gbc.gridy = 3; panel.add(button0, gbc);\n gbc.gridx = 2; gbc.gridy = 3; panel.add(buttonClear, gbc);\n gbc.gridx = 3; gbc.gridy = 3; panel.add(buttonMultiply, gbc);\n gbc.gridwidth = 3;\n\n gbc.gridx = 0; gbc.gridy = 4; panel.add(inputBox, gbc); \n gbc.gridx = 3; gbc.gridy = 4; panel.add(buttonEquals, gbc);\n frame.getContentPane().add(panel, BorderLayout.CENTER); \n }\n\n public void actionPerformed(ActionEvent e) {\n String command = e.getActionCommand();\n if (command.charAt(0) == 'C') { \n inputBox.setText(\"\");\n }else if (command.charAt(0) == '=') { \n inputBox.setText(evaluate(inputBox.getText()));\n }else { \n inputBox.setText(inputBox.getText() + command);\n }\n }\n \n public static String evaluate(String expression) {\n char[] arr = expression.toCharArray();\n String operand1 = \"\";String operand2 = \"\";String operator = \"\";\n double result = 0;\n\n for (int i = 0; i < arr.length; i++) {\n if (arr[i] >= '0' && arr[i] <= '9' || arr[i] == '.') {\n if(operator.isEmpty()){\n operand1 += arr[i];\n }else{\n operand2 += arr[i];\n }\n } \n\n if(arr[i] == '+' || arr[i] == '-' || arr[i] == '/' || arr[i] == '*') {\n operator += arr[i];\n }\n }\n\n if (operator.equals(\"+\"))\n result = (Double.parseDouble(operand1) + Double.parseDouble(operand2));\n else if (operator.equals(\"-\"))\n result = (Double.parseDouble(operand1) - Double.parseDouble(operand2));\n else if (operator.equals(\"/\"))\n result = (Double.parseDouble(operand1) / Double.parseDouble(operand2));\n else\n result = (Double.parseDouble(operand1) * Double.parseDouble(operand2)); \n return operand1 + operator + operand2 + \"=\" +result;\n } \n} " } ]
CSS Animations
CSS allows animation of HTML elements without using JavaScript or Flash! In this chapter you will learn about the following properties: @keyframes animation-name animation-duration animation-delay animation-iteration-count animation-direction animation-timing-function animation-fill-mode animation The numbers in the table specify the first browser version that fully supports the property. An animation lets an element gradually change from one style to another. You can change as many CSS properties you want, as many times as you want. To use CSS animation, you must first specify some keyframes for the animation. Keyframes hold what styles the element will have at certain times. When you specify CSS styles inside the @keyframes rule, the animation will gradually change from the current style to the new style at certain times. To get an animation to work, you must bind the animation to an element. The following example binds the "example" animation to the <div> element. The animation will last for 4 seconds, and it will gradually change the background-color of the <div> element from "red" to "yellow": Note: The animation-duration property defines how long an animation should take to complete. If the animation-duration property is not specified, no animation will occur, because the default value is 0s (0 seconds). In the example above we have specified when the style will change by using the keywords "from" and "to" (which represents 0% (start) and 100% (complete)). It is also possible to use percent. By using percent, you can add as many style changes as you like. The following example will change the background-color of the <div> element when the animation is 25% complete, 50% complete, and again when the animation is 100% complete: The following example will change both the background-color and the position of the <div> element when the animation is 25% complete, 50% complete, and again when the animation is 100% complete: The animation-delay property specifies a delay for the start of an animation. The following example has a 2 seconds delay before starting the animation: Negative values are also allowed. If using negative values, the animation will start as if it had already been playing for N seconds. In the following example, the animation will start as if it had already been playing for 2 seconds: The animation-iteration-count property specifies the number of times an animation should run. The following example will run the animation 3 times before it stops: The following example uses the value "infinite" to make the animation continue for ever: The animation-direction property specifies whether an animation should be played forwards, backwards or in alternate cycles. The animation-direction property can have the following values: normal - The animation is played as normal (forwards). This is default reverse - The animation is played in reverse direction (backwards) alternate - The animation is played forwards first, then backwards alternate-reverse - The animation is played backwards first, then forwards The following example will run the animation in reverse direction (backwards): The following example uses the value "alternate" to make the animation run forwards first, then backwards: The following example uses the value "alternate-reverse" to make the animation run backwards first, then forwards: The animation-timing-function property specifies the speed curve of the animation. The animation-timing-function property can have the following values: ease - Specifies an animation with a slow start, then fast, then end slowly (this is default) linear - Specifies an animation with the same speed from start to end ease-in - Specifies an animation with a slow start ease-out - Specifies an animation with a slow end ease-in-out - Specifies an animation with a slow start and end cubic-bezier(n,n,n,n) - Lets you define your own values in a cubic-bezier function The following example shows some of the different speed curves that can be used: CSS animations do not affect an element before the first keyframe is played or after the last keyframe is played. The animation-fill-mode property can override this behavior. The animation-fill-mode property specifies a style for the target element when the animation is not playing (before it starts, after it ends, or both). The animation-fill-mode property can have the following values: none - Default value. Animation will not apply any styles to the element before or after it is executing forwards - The element will retain the style values that is set by the last keyframe (depends on animation-direction and animation-iteration-count) backwards - The element will get the style values that is set by the first keyframe (depends on animation-direction), and retain this during the animation-delay period both - The animation will follow the rules for both forwards and backwards, extending the animation properties in both directions The following example lets the <div> element retain the style values from the last keyframe when the animation ends: The following example lets the <div> element get the style values set by the first keyframe before the animation starts (during the animation-delay period): The following example lets the <div> element get the style values set by the first keyframe before the animation starts, and retain the style values from the last keyframe when the animation ends: The example below uses six of the animation properties: The same animation effect as above can be achieved by using the shorthand animation property: Add a 2 second animation for the <div> element, which changes the color from red to blue. Call the animation "example". <style> div { width: 100px; height: 100px; background-color: red; animation-name: ; : 2s; } @keyframes example { from {: red;} to {: blue;} } </style> <body> <div>This is a div</div> </body> Start the Exercise The following table lists the @keyframes rule and all the CSS animation properties: We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 73, "s": 0, "text": "CSS allows animation of HTML elements without using JavaScript or Flash!" }, { "code": null, "e": 136, "s": 73, "text": "In this chapter you will learn about the following properties:" }, { "code": null, "e": 147, "s": 136, "text": "@keyframes" }, { "code": null, "e": 162, "s": 147, "text": "animation-name" }, { "code": null, "e": 181, "s": 162, "text": "animation-duration" }, { "code": null, "e": 197, "s": 181, "text": "animation-delay" }, { "code": null, "e": 223, "s": 197, "text": "animation-iteration-count" }, { "code": null, "e": 243, "s": 223, "text": "animation-direction" }, { "code": null, "e": 269, "s": 243, "text": "animation-timing-function" }, { "code": null, "e": 289, "s": 269, "text": "animation-fill-mode" }, { "code": null, "e": 299, "s": 289, "text": "animation" }, { "code": null, "e": 392, "s": 299, "text": "The numbers in the table specify the first browser version that fully supports the property." }, { "code": null, "e": 465, "s": 392, "text": "An animation lets an element gradually change from one style to another." }, { "code": null, "e": 540, "s": 465, "text": "You can change as many CSS properties you want, as many times as you want." }, { "code": null, "e": 620, "s": 540, "text": "To use CSS animation, you must first specify some keyframes for the \nanimation." }, { "code": null, "e": 687, "s": 620, "text": "Keyframes hold what styles the element will have at certain times." }, { "code": null, "e": 838, "s": 687, "text": "When you specify CSS styles inside the @keyframes\nrule, the animation will gradually change from the current style to the new style \nat certain times." }, { "code": null, "e": 910, "s": 838, "text": "To get an animation to work, you must bind the animation to an element." }, { "code": null, "e": 1120, "s": 910, "text": "The following example binds the \"example\" animation to the <div> element. \nThe animation will last for 4 seconds, and it will gradually change the \nbackground-color of the <div> element from \"red\" to \"yellow\":" }, { "code": null, "e": 1340, "s": 1120, "text": "Note: The animation-duration property \ndefines how long an animation should take to complete. If the animation-duration property is not specified, \nno animation will occur, because \nthe default value is 0s (0 seconds). " }, { "code": null, "e": 1496, "s": 1340, "text": "In the example above we have specified when the style will change by using \nthe keywords \"from\" and \"to\" (which represents 0% (start) and 100% (complete))." }, { "code": null, "e": 1598, "s": 1496, "text": "It is also possible to use percent. By using percent, you can add as many \nstyle changes as you like." }, { "code": null, "e": 1772, "s": 1598, "text": "The following example will change the background-color of the <div> \nelement when the animation is 25% complete, 50% complete, and again when the animation is 100% complete:" }, { "code": null, "e": 1968, "s": 1772, "text": "The following example will change both the background-color and the position of the <div> \nelement when the animation is 25% complete, 50% complete, and again when the animation is 100% complete:" }, { "code": null, "e": 2046, "s": 1968, "text": "The animation-delay property specifies a delay for the start of an animation." }, { "code": null, "e": 2121, "s": 2046, "text": "The following example has a 2 seconds delay before starting the animation:" }, { "code": null, "e": 2256, "s": 2121, "text": "Negative values are also allowed. If using negative values, the animation \nwill start as if it had already been playing for N seconds." }, { "code": null, "e": 2357, "s": 2256, "text": "In the following example, the animation will start as if it had already been \nplaying for 2 seconds:" }, { "code": null, "e": 2451, "s": 2357, "text": "The animation-iteration-count property specifies the number of times an animation should run." }, { "code": null, "e": 2521, "s": 2451, "text": "The following example will run the animation 3 times before it stops:" }, { "code": null, "e": 2611, "s": 2521, "text": "The following example uses the value \"infinite\" to make the animation \ncontinue for ever:" }, { "code": null, "e": 2738, "s": 2611, "text": "The animation-direction property specifies \nwhether an animation should be played forwards, backwards or in alternate \ncycles." }, { "code": null, "e": 2802, "s": 2738, "text": "The animation-direction property can have the following values:" }, { "code": null, "e": 2874, "s": 2802, "text": "normal - The animation is played as normal \n(forwards). This is default" }, { "code": null, "e": 2942, "s": 2874, "text": "reverse - The animation is played in \nreverse direction (backwards)" }, { "code": null, "e": 3010, "s": 2942, "text": "alternate - The animation is played \nforwards first, then backwards" }, { "code": null, "e": 3086, "s": 3010, "text": "alternate-reverse - The animation is played \nbackwards first, then forwards" }, { "code": null, "e": 3165, "s": 3086, "text": "The following example will run the animation in reverse direction (backwards):" }, { "code": null, "e": 3273, "s": 3165, "text": "The following example uses the value \"alternate\" to make the animation \nrun forwards first, then backwards:" }, { "code": null, "e": 3389, "s": 3273, "text": "The following example uses the value \"alternate-reverse\" to make the animation \nrun backwards first, then forwards:" }, { "code": null, "e": 3473, "s": 3389, "text": "The animation-timing-function property specifies the speed curve of the \nanimation." }, { "code": null, "e": 3543, "s": 3473, "text": "The animation-timing-function property can have the following values:" }, { "code": null, "e": 3637, "s": 3543, "text": "ease - Specifies an animation with a slow start, then fast, then end slowly (this is default)" }, { "code": null, "e": 3707, "s": 3637, "text": "linear - Specifies an animation with the same speed from start to end" }, { "code": null, "e": 3758, "s": 3707, "text": "ease-in - Specifies an animation with a slow start" }, { "code": null, "e": 3808, "s": 3758, "text": "ease-out - Specifies an animation with a slow end" }, { "code": null, "e": 3871, "s": 3808, "text": "ease-in-out - Specifies an animation with a slow start and end" }, { "code": null, "e": 3954, "s": 3871, "text": "cubic-bezier(n,n,n,n) - Lets you define your own values in a cubic-bezier function" }, { "code": null, "e": 4035, "s": 3954, "text": "The following example shows some of the different speed curves that can be used:" }, { "code": null, "e": 4212, "s": 4035, "text": "CSS animations do not affect an element before the first keyframe is played \nor after the last keyframe is played. The animation-fill-mode property can \noverride this behavior." }, { "code": null, "e": 4366, "s": 4212, "text": "The animation-fill-mode property specifies a \nstyle for the target element when the animation is not playing (before it \nstarts, after it ends, or both)." }, { "code": null, "e": 4430, "s": 4366, "text": "The animation-fill-mode property can have the following values:" }, { "code": null, "e": 4536, "s": 4430, "text": "none - Default value. Animation will not \napply any styles to the element before or after it is executing" }, { "code": null, "e": 4686, "s": 4536, "text": "forwards - The element will retain the \nstyle values that is set by the last keyframe (depends on animation-direction \nand animation-iteration-count)" }, { "code": null, "e": 4856, "s": 4686, "text": "backwards - The element will get the style \nvalues that is set by the first keyframe (depends on animation-direction), and \nretain this during the animation-delay period" }, { "code": null, "e": 4988, "s": 4856, "text": "both - The animation will follow the rules \nfor both forwards and backwards, extending the animation properties in both \ndirections" }, { "code": null, "e": 5106, "s": 4988, "text": "The following example lets the <div> element retain the style values from the \nlast keyframe when the animation ends:" }, { "code": null, "e": 5264, "s": 5106, "text": "The following example lets the <div> element get the style values set by the \nfirst keyframe before the animation starts (during the animation-delay period):" }, { "code": null, "e": 5463, "s": 5264, "text": "The following example lets the <div> element get the style values set \nby the first keyframe before the animation starts, and retain the style values \nfrom the last keyframe when the animation ends:" }, { "code": null, "e": 5519, "s": 5463, "text": "The example below uses six of the animation properties:" }, { "code": null, "e": 5614, "s": 5519, "text": "The same animation effect as above can be achieved by using the shorthand \nanimation property:" }, { "code": null, "e": 5734, "s": 5614, "text": "Add a 2 second animation for the <div> element, which changes the color from red to blue. Call the animation \"example\"." }, { "code": null, "e": 5944, "s": 5734, "text": "<style>\ndiv {\n width: 100px;\n height: 100px;\n background-color: red;\n animation-name: ;\n : 2s;\n}\n\n@keyframes example {\n from {: red;}\n to {: blue;}\n}\n</style>\n\n<body>\n <div>This is a div</div>\n</body>\n" }, { "code": null, "e": 5963, "s": 5944, "text": "Start the Exercise" }, { "code": null, "e": 6047, "s": 5963, "text": "The following table lists the @keyframes rule and all the CSS animation properties:" }, { "code": null, "e": 6080, "s": 6047, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 6122, "s": 6080, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 6229, "s": 6122, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 6248, "s": 6229, "text": "help@w3schools.com" } ]
Introduction to MCMC and Metropolis | Towards Data Science
Probabilistic modelling is all the rage these days but there was always one thing that bugged me when I first learned about it. Many Bayesian modelling methods require the computation of integrals and any worked examples I saw seemed to use Gaussian or Bernoulli distributions for the simple reason that it becomes an analytical nightmare (or even intractable) if you try to use anything more complicated than that. Restricting Bayesian modelling to the small subset of “well behaved” distributions can dramatically hinder your ability to model a problem well so it’s important that we come up with methods of overcoming this limitation. So what do I do if I don’t want to analytically compute some pesky integral? Enter Monte Carlo approximations. We know that we can compute an expectation by using samples from the target distribution and calculating their sample mean. Why’s that important? Well, what is an expectation but an integral... This method of estimating the integral has some nice guarantees courtesy of the central limit theorem. Firstly, this is an unbiased estimate of the expectation and secondly, we can calculate the variance of the estimate. Calculating integrals using Monte Carlo samples is all very well but how do we draw samples from the target distribution in general? Drawing Gaussian or uniform samples is easy, but anything more difficult and np.random is going to fail you. The simplest way of drawing samples is using the inverse CDF method but this relies on having access to the inverse CDF function which often doesn’t have a nice analytical form and only makes sense for 1-dimensional random variables. The Metropolis algorithm is one of the building blocks of many Markov Chain Monte Carlo (MCMC) sampling methods. It allows us to draw samples when all you have access to is the pdf of the target distribution. MCMC methods come with the caveat that we’re no longer taking independent samples so we can’t have the same guarantees for how the variance of our estimate reduces with the number of samples we take. If samples are drawn independently, the Central Limit Theorem tells us that the variance of our estimate will decrease inversely in proportion to the number of samples (N). For MCMC we can discount this by adjusting the number of samples from N to N_eff. N_eff is (almost) always smaller than N and is related to how correlated the samples in the chain are. The steps of the Metropolis algorithm are as follows: 1. Sample a starting point uniformly from the domain of the target distribution or from the prior distribution.2. Calculate the pdf at that point.3. Make a proposal for the new sample by taking a step from the current position in accordance with some state transition function.4. Calculate the new pdf value.5. Calculate the value of new pdf / old pdf.6. If the ratio is greater than 1, accept the step.7. If the ratio is less than 1: 1. Sample a uniform random variable. 2. If the ratio greater than the random sample, accept the step.8. Else reject the proposal, add the current position as a sample and take a new step. Note that the process described in 5–8 is equivalent to accepting a sample based on a Bernoulli probability with probability min(1, p(new)/p(old)), remember this for later... For any MCMC method, we want to ensure a property known as detailed balance or reversibility. If π satisfies this then π is a stationary distribution of the Markov chain (1). We can show this by summing over both sides of the equation. If we can guarantee detailed balance then we also know we’re sampling from the stationary distribution of the Markov chain which we will dictate to be our target distribution. This intuition of detailed balance is that since the transfer of probability ‘mass’ at each transition is the same from state i to state j as it is from state j to state i, after each transition of the chain, we remain at the stationary distribution. So now let’s show how the Metropolis algorithm satisfies this condition... To find p(i,j) such that it satisfies detailed balance, we first propose arbitrary “jump” probability q(i,j), and then obtain p(i,j) by only accepting the “jump” with probability α(i,j). When a “jump” is rejected, the state remains j=i. This “acceptance” idea is not unique to the Metropolis algorithm and exists in most variants of MCMC. This is subject to α being a valid probability distribution. So a valid form of α is: If the jumpy probability is symmetric then this can be simplified to: Otherwise, it can be left in its full form which is called Metropolis-Hasting MCMC. Now we can guarantee detailed balance, we can allow the Markov chain machinery to take over. If the Markov chain is ergodic (all states are irreducible), then at some point the chain will reach the stationary distribution and we are able to take samples from the target distribution. You might have also noticed that since alpha is a function of π(j)/π(i). The result of this means that the target distribution doesn’t need to be normalised. This is particularly helpful when using Metropolis for Bayesian posterior estimation where the evidence term is hard to compute. A common version of the Metropolis algorithm is called “Random walk Metropolis” where the proposed state is the current state plus a multivariate Gaussian with zero mean and covariance matrix σ2I. σ should be chosen to be large enough such that sufficiently many samples are rejected. This is to ensure a good exploration of the target distribution. The second thing to note is the concept of burn-in. Samples that are taken before the Markov chain reaches the stationary distribution should be removed as they’re not representative of the target distribution until the chain has converged. It’s somewhat difficult to identify how many samples should be removed but in general, 10–20% of samples are removed (or 10–100 effective samples). Here we implement random walk Metropolis for the sake of simplicity. def metropolis(pi, dims, n_samples, burn_in=0.1, var=1): theta_ = np.random.randn(dims)*var samples = [] while len(samples) < n_samples: theta = theta_ + np.random.randn(dims)*varratio = pi(theta)/pi(theta_) if np.random.rand(1) < ratio: sample = theta theta_ = theta samples.append(sample) else: sample = theta_ samples.append(sample) samples = np.array(samples) return samples[int(samples*burn_in):,:] We can see how this performs on the sum of two Gaussians (note this is an unnormalised distribution). from scipy.stats import multivariate_normaldef make_pdf(mean1, mean2, cov1, cov2): pdf1 = multivariate_normal(mean1, cov1) pdf2 = multivariate_normal(mean2, cov2) def pdf(x): return pdf1.pdf(x) * pdf2.pdf(x) return pdfpdf = make_pdf( [3, 3], [-1, -1], np.array([[1,0.1],[0.1,1]], dtype=float), np.array([[1,0.1],[0.1,1]], dtype=float),)samples = metropolis(pdf, 2, 1_000, 0.1) The gif above shows how the algorithm traverses the distribution, occasionally hopping between the two different modes of the distribution. Note, this also highlighted one of the weaknesses of the Metropolis algorithm, it deals relatively poorly with multi-model distributions. This is due to the fact that to explore a new mode, the step must be sufficiently large to hope from one mode to another. This either requires a large step size or a distribution with modes that are close together. Modifications such as Hamiltonian MCMC can help with this but generally, it is a problem with most MCMC methods. Video on detailed balance The original paper on the Metropolis-Hastings algorithm Paper on Hamiltonian dynamics (MCMC method used by stan and other probabilistic languages)
[ { "code": null, "e": 810, "s": 172, "text": "Probabilistic modelling is all the rage these days but there was always one thing that bugged me when I first learned about it. Many Bayesian modelling methods require the computation of integrals and any worked examples I saw seemed to use Gaussian or Bernoulli distributions for the simple reason that it becomes an analytical nightmare (or even intractable) if you try to use anything more complicated than that. Restricting Bayesian modelling to the small subset of “well behaved” distributions can dramatically hinder your ability to model a problem well so it’s important that we come up with methods of overcoming this limitation." }, { "code": null, "e": 921, "s": 810, "text": "So what do I do if I don’t want to analytically compute some pesky integral? Enter Monte Carlo approximations." }, { "code": null, "e": 1115, "s": 921, "text": "We know that we can compute an expectation by using samples from the target distribution and calculating their sample mean. Why’s that important? Well, what is an expectation but an integral..." }, { "code": null, "e": 1336, "s": 1115, "text": "This method of estimating the integral has some nice guarantees courtesy of the central limit theorem. Firstly, this is an unbiased estimate of the expectation and secondly, we can calculate the variance of the estimate." }, { "code": null, "e": 1578, "s": 1336, "text": "Calculating integrals using Monte Carlo samples is all very well but how do we draw samples from the target distribution in general? Drawing Gaussian or uniform samples is easy, but anything more difficult and np.random is going to fail you." }, { "code": null, "e": 1812, "s": 1578, "text": "The simplest way of drawing samples is using the inverse CDF method but this relies on having access to the inverse CDF function which often doesn’t have a nice analytical form and only makes sense for 1-dimensional random variables." }, { "code": null, "e": 2021, "s": 1812, "text": "The Metropolis algorithm is one of the building blocks of many Markov Chain Monte Carlo (MCMC) sampling methods. It allows us to draw samples when all you have access to is the pdf of the target distribution." }, { "code": null, "e": 2579, "s": 2021, "text": "MCMC methods come with the caveat that we’re no longer taking independent samples so we can’t have the same guarantees for how the variance of our estimate reduces with the number of samples we take. If samples are drawn independently, the Central Limit Theorem tells us that the variance of our estimate will decrease inversely in proportion to the number of samples (N). For MCMC we can discount this by adjusting the number of samples from N to N_eff. N_eff is (almost) always smaller than N and is related to how correlated the samples in the chain are." }, { "code": null, "e": 2633, "s": 2579, "text": "The steps of the Metropolis algorithm are as follows:" }, { "code": null, "e": 3262, "s": 2633, "text": "1. Sample a starting point uniformly from the domain of the target distribution or from the prior distribution.2. Calculate the pdf at that point.3. Make a proposal for the new sample by taking a step from the current position in accordance with some state transition function.4. Calculate the new pdf value.5. Calculate the value of new pdf / old pdf.6. If the ratio is greater than 1, accept the step.7. If the ratio is less than 1: 1. Sample a uniform random variable. 2. If the ratio greater than the random sample, accept the step.8. Else reject the proposal, add the current position as a sample and take a new step." }, { "code": null, "e": 3437, "s": 3262, "text": "Note that the process described in 5–8 is equivalent to accepting a sample based on a Bernoulli probability with probability min(1, p(new)/p(old)), remember this for later..." }, { "code": null, "e": 3531, "s": 3437, "text": "For any MCMC method, we want to ensure a property known as detailed balance or reversibility." }, { "code": null, "e": 3849, "s": 3531, "text": "If π satisfies this then π is a stationary distribution of the Markov chain (1). We can show this by summing over both sides of the equation. If we can guarantee detailed balance then we also know we’re sampling from the stationary distribution of the Markov chain which we will dictate to be our target distribution." }, { "code": null, "e": 4100, "s": 3849, "text": "This intuition of detailed balance is that since the transfer of probability ‘mass’ at each transition is the same from state i to state j as it is from state j to state i, after each transition of the chain, we remain at the stationary distribution." }, { "code": null, "e": 4175, "s": 4100, "text": "So now let’s show how the Metropolis algorithm satisfies this condition..." }, { "code": null, "e": 4514, "s": 4175, "text": "To find p(i,j) such that it satisfies detailed balance, we first propose arbitrary “jump” probability q(i,j), and then obtain p(i,j) by only accepting the “jump” with probability α(i,j). When a “jump” is rejected, the state remains j=i. This “acceptance” idea is not unique to the Metropolis algorithm and exists in most variants of MCMC." }, { "code": null, "e": 4600, "s": 4514, "text": "This is subject to α being a valid probability distribution. So a valid form of α is:" }, { "code": null, "e": 4670, "s": 4600, "text": "If the jumpy probability is symmetric then this can be simplified to:" }, { "code": null, "e": 4754, "s": 4670, "text": "Otherwise, it can be left in its full form which is called Metropolis-Hasting MCMC." }, { "code": null, "e": 5038, "s": 4754, "text": "Now we can guarantee detailed balance, we can allow the Markov chain machinery to take over. If the Markov chain is ergodic (all states are irreducible), then at some point the chain will reach the stationary distribution and we are able to take samples from the target distribution." }, { "code": null, "e": 5325, "s": 5038, "text": "You might have also noticed that since alpha is a function of π(j)/π(i). The result of this means that the target distribution doesn’t need to be normalised. This is particularly helpful when using Metropolis for Bayesian posterior estimation where the evidence term is hard to compute." }, { "code": null, "e": 5675, "s": 5325, "text": "A common version of the Metropolis algorithm is called “Random walk Metropolis” where the proposed state is the current state plus a multivariate Gaussian with zero mean and covariance matrix σ2I. σ should be chosen to be large enough such that sufficiently many samples are rejected. This is to ensure a good exploration of the target distribution." }, { "code": null, "e": 6064, "s": 5675, "text": "The second thing to note is the concept of burn-in. Samples that are taken before the Markov chain reaches the stationary distribution should be removed as they’re not representative of the target distribution until the chain has converged. It’s somewhat difficult to identify how many samples should be removed but in general, 10–20% of samples are removed (or 10–100 effective samples)." }, { "code": null, "e": 6133, "s": 6064, "text": "Here we implement random walk Metropolis for the sake of simplicity." }, { "code": null, "e": 6628, "s": 6133, "text": "def metropolis(pi, dims, n_samples, burn_in=0.1, var=1): theta_ = np.random.randn(dims)*var samples = [] while len(samples) < n_samples: theta = theta_ + np.random.randn(dims)*varratio = pi(theta)/pi(theta_) if np.random.rand(1) < ratio: sample = theta theta_ = theta samples.append(sample) else: sample = theta_ samples.append(sample) samples = np.array(samples) return samples[int(samples*burn_in):,:]" }, { "code": null, "e": 6730, "s": 6628, "text": "We can see how this performs on the sum of two Gaussians (note this is an unnormalised distribution)." }, { "code": null, "e": 7138, "s": 6730, "text": "from scipy.stats import multivariate_normaldef make_pdf(mean1, mean2, cov1, cov2): pdf1 = multivariate_normal(mean1, cov1) pdf2 = multivariate_normal(mean2, cov2) def pdf(x): return pdf1.pdf(x) * pdf2.pdf(x) return pdfpdf = make_pdf( [3, 3], [-1, -1], np.array([[1,0.1],[0.1,1]], dtype=float), np.array([[1,0.1],[0.1,1]], dtype=float),)samples = metropolis(pdf, 2, 1_000, 0.1)" }, { "code": null, "e": 7744, "s": 7138, "text": "The gif above shows how the algorithm traverses the distribution, occasionally hopping between the two different modes of the distribution. Note, this also highlighted one of the weaknesses of the Metropolis algorithm, it deals relatively poorly with multi-model distributions. This is due to the fact that to explore a new mode, the step must be sufficiently large to hope from one mode to another. This either requires a large step size or a distribution with modes that are close together. Modifications such as Hamiltonian MCMC can help with this but generally, it is a problem with most MCMC methods." }, { "code": null, "e": 7770, "s": 7744, "text": "Video on detailed balance" }, { "code": null, "e": 7826, "s": 7770, "text": "The original paper on the Metropolis-Hastings algorithm" } ]
Find maximum matching in a given Binary Tree - GeeksforGeeks
23 Feb, 2022 Given a Tree with N nodes values from 1 to N and N – 1 edges. The task is to find the maximum matching in the given tree. A matching in a tree is a collection of edges such that no pair of edges share a common node. Matching with the most edges is known as a maximum matching. Examples: Input: Below is the given graph: Output: 3 Explanation: Set of Edges in the above graph for maximum matching: (4, 5), (1, 2), (7, 8) Input: Below is the given graph: Output: 3 Explanation: Set of Edges in the above graph for maximum matching: (4, 5), (2, 3), (1, 7) Approach: This problem can be solved using Greedy Approach and the idea is to use post-order traversal in the tree and start with leaf edges and go up the order. Below are the steps: Perform DFS Traversal on the given tree with rooted node 1 and make parent as 0 and pass current nodes as a parent of the node in recursive DFS traversal.While performing traversal, for each node U and its parent node P if these nodes are unvisited then mark these nodes as visited and increment the maximum matching count by 1.Print the count of a maximum matching in the above step after DFS Traversal. Perform DFS Traversal on the given tree with rooted node 1 and make parent as 0 and pass current nodes as a parent of the node in recursive DFS traversal. While performing traversal, for each node U and its parent node P if these nodes are unvisited then mark these nodes as visited and increment the maximum matching count by 1. Print the count of a maximum matching in the above step after DFS Traversal. The Greedy algorithm is to repeatedly take any leaf-edge. TreeMatch(F:forest) M <- [] while F nonempty do { select any leaf-edge e M <- M + [e] F <- F - both ends of e } Why the greedy algorithm works correctly? Let’s, assume E is a leaf edge and consider any maximum matching N. Suppose N does not contain E. Then if we add E to N, only one vertex now has two edges incident with it. So we can delete one of the edges of N and attain a maximum matching containing E. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std;#define N 10000 // Adjacency list to store edgesvector<int> adj[N]; int used[N];int max_matching; // Add an edge between U and V in treevoid AddEdge(int u, int v){ // Edge from u to v adj[u].push_back(v); // Edge from V to U adj[v].push_back(u);} // Function that finds the maximum// matching of the DFSvoid Matching_dfs(int u, int p){ for (int i = 0; i < adj[u].size(); i++) { // Go further as we are not // allowed to go towards // its parent if (adj[u][i] != p) { Matching_dfs(adj[u][i], u); } } // If U and its parent P is // not taken then we must // take &mark them as taken if (!used[u] and !used[p] and p != 0) { // Increment size of edge set max_matching++; used[u] = used[p] = 1; }} // Function to find the maximum// matching in a graphvoid maxMatching(){ // Taking 1 as a root of the tree Matching_dfs(1, 0); // Print maximum Matching cout << max_matching << "\n";} // Driver Codeint main(){ int n = 5; // Joining edge between // two nodes in tree AddEdge(1, 2); AddEdge(1, 3); AddEdge(3, 4); AddEdge(3, 5); // Function Call maxMatching(); return 0;} // Java program for the above approachimport java.util.*; class GFG{ static final int N = 10000; // Adjacency list to store edges@SuppressWarnings("unchecked")static Vector<Integer>[] adj = new Vector[N]; static int used[] = new int[N];static int max_matching; // Add an edge between U and V in treestatic void AddEdge(int u, int v){ // Edge from u to v adj[u].add(v); // Edge from V to U adj[v].add(u);} // Function that finds the maximum// matching of the DFSstatic void Matching_dfs(int u, int p){ for(int i = 0; i < adj[u].size(); i++) { // Go further as we are not // allowed to go towards // its parent if (adj[u].get(i) != p) { Matching_dfs(adj[u].get(i), u); } } // If U and its parent P is // not taken then we must // take &mark them as taken if (used[u] == 0 && used[p] == 0 && p != 0) { // Increment size of edge set max_matching++; used[u] = used[p] = 1; }} // Function to find the maximum// matching in a graphstatic void maxMatching(){ // Taking 1 as a root of the tree Matching_dfs(1, 0); // Print maximum Matching System.out.print(max_matching + "\n");} // Driver Codepublic static void main(String[] args){ for(int i = 0; i < adj.length; i++) adj[i] = new Vector<Integer>(); // Joining edge between // two nodes in tree AddEdge(1, 2); AddEdge(1, 3); AddEdge(3, 4); AddEdge(3, 5); // Function call maxMatching();}} // This code is contributed by amal kumar choubey # Python3 program for the above approachN = 10000 # Adjacency list to store edgesadj = {} used = [0 for i in range(N)] max_matching = 0 # Add an edge between U and V in treedef AddEdge(u, v): if u not in adj: adj[u] = [] if v not in adj: adj[v] = [] # Edge from u to v adj[u].append(v) # Edge from V to U adj[v].append(u) # Function that finds the maximum# matching of the DFSdef Matching_dfs(u, p): global max_matching for i in range(len(adj[u])): # Go further as we are not # allowed to go towards # its parent if (adj[u][i] != p): Matching_dfs(adj[u][i], u) # If U and its parent P is # not taken then we must # take &mark them as taken if (not used[u] and not used[p] and p != 0): # Increment size of edge set max_matching += 1 used[u] = 1 used[p] = 1 # Function to find the maximum# matching in a graphdef maxMatching(): # Taking 1 as a root of the tree Matching_dfs(1, 0) # Print maximum Matching print(max_matching) # Driver Coden = 5 # Joining edge between# two nodes in treeAddEdge(1, 2)AddEdge(1, 3)AddEdge(3, 4)AddEdge(3, 5) # Function CallmaxMatching() # This code is contributed by avanitrachhadiya2155 // C# program for the above approachusing System;using System.Collections.Generic; class GFG{ static readonly int N = 10000; // Adjacency list to store edgesstatic List<int>[] adj = new List<int>[N]; static int []used = new int[N];static int max_matching; // Add an edge between U and V in treestatic void AddEdge(int u, int v){ // Edge from u to v adj[u].Add(v); // Edge from V to U adj[v].Add(u);} // Function that finds the maximum// matching of the DFSstatic void Matching_dfs(int u, int p){ for(int i = 0; i < adj[u].Count; i++) { // Go further as we are not // allowed to go towards // its parent if (adj[u][i] != p) { Matching_dfs(adj[u][i], u); } } // If U and its parent P is // not taken then we must // take &mark them as taken if (used[u] == 0 && used[p] == 0 && p != 0) { // Increment size of edge set max_matching++; used[u] = used[p] = 1; }} // Function to find the maximum// matching in a graphstatic void maxMatching(){ // Taking 1 as a root of the tree Matching_dfs(1, 0); // Print maximum Matching Console.Write(max_matching + "\n");} // Driver Codepublic static void Main(String[] args){ for(int i = 0; i < adj.Length; i++) adj[i] = new List<int>(); // Joining edge between // two nodes in tree AddEdge(1, 2); AddEdge(1, 3); AddEdge(3, 4); AddEdge(3, 5); // Function call maxMatching();}} // This code is contributed by amal kumar choubey <script> // Javascript Program to implement the above approach let N = 10000; // Adjacency list to store edges let adj = new Array(N); let used = new Array(N); used.fill(0); let max_matching = 0; // Add an edge between U and V in tree function AddEdge(u, v) { // Edge from u to v adj[u].push(v); // Edge from V to U adj[v].push(u); } // Function that finds the maximum // matching of the DFS function Matching_dfs(u, p) { for(let i = 0; i < adj[u].length; i++) { // Go further as we are not // allowed to go towards // its parent if (adj[u][i] != p) { Matching_dfs(adj[u][i], u); } } // If U and its parent P is // not taken then we must // take &mark them as taken if (used[u] == 0 && used[p] == 0 && p != 0) { // Increment size of edge set max_matching++; used[u] = used[p] = 1; } } // Function to find the maximum // matching in a graph function maxMatching() { // Taking 1 as a root of the tree Matching_dfs(1, 0); // Print maximum Matching document.write(max_matching + "</br>"); } for(let i = 0; i < adj.length; i++) adj[i] = []; // Joining edge between // two nodes in tree AddEdge(1, 2); AddEdge(1, 3); AddEdge(3, 4); AddEdge(3, 5); // Function call maxMatching(); </script> 2 Time Complexity: O(V + E), where V is the number of edges and E is the number of edges. Auxiliary Space: O(V) Bottom-up DFS approach: Another intuitive approach to solve this problem is to use DFS in a bottom-up manner and return two values at each level Maximum matching including the current node Maximum matching excluding the current node We will recurse on the left and right subtrees and get these values for both of them. We can then calculate new values for the current level based on these values. Let left_included denote maximum matching including root of left subtree and left_excluded denote the maximum matching excluding the root of left subtree. Similarly, for right_included and right_excluded. If we include the current node in maximum matching, then we have to exclude one of either left sub tree root or right sub tree root. Including both will cause overlapping on current node which is not allowed. By excluding either left or right sub tree root we can increase the maximum matching by 1 by including one of the edges from current_node -> left sub tree root or current_node -> right sub tree root. Thus maximum matching including current node will be given by current_including = max(max(left_including, right_excluding) + 1, max(left_excluding, right_including) + 1) If we exclude the current node then we can include both left and right subtree root. As matchings in left and right subtrees are independent of each other we can get maximum value by adding both matchings. Thus maximum matching excluding current node will be given by current_excluding = left_including + right_including We will return both these values from the current recursion level to upper recursion levels. After the recursion completes we will receive two values, maximum matching including root node and maximum matching excluding root node. The maximum of those two will give the maximum matching in the tree. Python3 class Node: def __init__(self, key): self.left = None self.right = None self.val = key def max_matching_helper(root): if not root: return (0, 0) if not root.left and not root.right: return (0, 0) left_included, left_excluded = max_matching_helper(root.left) right_included, right_excluded = max_matching_helper(root.right) # Maximum matching gincluding current node curr_included = max(max(left_included, right_excluded) + 1, max(left_excluded, right_included) + 1) # Maximum matching excluding current node curr_excluded = left_included + right_included return (curr_included, curr_excluded) def max_matching(root): # Taking 1 as a root of the tree root_including, root_excluding = max_matching_helper(root) # Return maximum Matching return max(root_including, root_excluding) # Driver coderoot = Node(1)root.left = Node(2)root.right = Node(7)root.left.left = Node(3)root.left.right = Node(4)root.left.right.left = Node(5)root.left.right.right = Node(6)root.right.left = Node(8)root.right.right = Node(9) print(max_matching(root)) # This code is contributed by Rathijeet Bhave 3 Time Complexity: O(V + E), where V is the number of edges and E is the number of edges. Auxiliary Space: O(V) Amal Kumar Choubey avanitrachhadiya2155 rathijeetbhave divyesh072019 sumitgumber28 DFS PostOrder Traversal Tree Traversals tree-traversal Trees Greedy Tree Greedy DFS Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Optimal Page Replacement Algorithm Program for Best Fit algorithm in Memory Management Program for First Fit algorithm in Memory Management Max Flow Problem Introduction Program for Worst Fit algorithm in Memory Management Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal AVL Tree | Set 1 (Insertion) Inorder Tree Traversal without Recursion
[ { "code": null, "e": 25292, "s": 25264, "text": "\n23 Feb, 2022" }, { "code": null, "e": 25414, "s": 25292, "text": "Given a Tree with N nodes values from 1 to N and N – 1 edges. The task is to find the maximum matching in the given tree." }, { "code": null, "e": 25571, "s": 25414, "text": "A matching in a tree is a collection of edges such that no pair of edges share a common node. Matching with the most edges is known as a maximum matching. " }, { "code": null, "e": 25582, "s": 25571, "text": "Examples: " }, { "code": null, "e": 25617, "s": 25582, "text": "Input: Below is the given graph: " }, { "code": null, "e": 25717, "s": 25617, "text": "Output: 3 Explanation: Set of Edges in the above graph for maximum matching: (4, 5), (1, 2), (7, 8)" }, { "code": null, "e": 25751, "s": 25717, "text": "Input: Below is the given graph: " }, { "code": null, "e": 25853, "s": 25751, "text": "Output: 3 Explanation: Set of Edges in the above graph for maximum matching: (4, 5), (2, 3), (1, 7) " }, { "code": null, "e": 26037, "s": 25853, "text": "Approach: This problem can be solved using Greedy Approach and the idea is to use post-order traversal in the tree and start with leaf edges and go up the order. Below are the steps: " }, { "code": null, "e": 26442, "s": 26037, "text": "Perform DFS Traversal on the given tree with rooted node 1 and make parent as 0 and pass current nodes as a parent of the node in recursive DFS traversal.While performing traversal, for each node U and its parent node P if these nodes are unvisited then mark these nodes as visited and increment the maximum matching count by 1.Print the count of a maximum matching in the above step after DFS Traversal." }, { "code": null, "e": 26597, "s": 26442, "text": "Perform DFS Traversal on the given tree with rooted node 1 and make parent as 0 and pass current nodes as a parent of the node in recursive DFS traversal." }, { "code": null, "e": 26772, "s": 26597, "text": "While performing traversal, for each node U and its parent node P if these nodes are unvisited then mark these nodes as visited and increment the maximum matching count by 1." }, { "code": null, "e": 26849, "s": 26772, "text": "Print the count of a maximum matching in the above step after DFS Traversal." }, { "code": null, "e": 26908, "s": 26849, "text": "The Greedy algorithm is to repeatedly take any leaf-edge. " }, { "code": null, "e": 27037, "s": 26908, "text": "TreeMatch(F:forest)\nM <- []\nwhile F nonempty do {\n select any leaf-edge e\n M <- M + [e]\n F <- F - both ends of e\n }" }, { "code": null, "e": 27335, "s": 27037, "text": "Why the greedy algorithm works correctly? Let’s, assume E is a leaf edge and consider any maximum matching N. Suppose N does not contain E. Then if we add E to N, only one vertex now has two edges incident with it. So we can delete one of the edges of N and attain a maximum matching containing E." }, { "code": null, "e": 27386, "s": 27335, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27390, "s": 27386, "text": "C++" }, { "code": null, "e": 27395, "s": 27390, "text": "Java" }, { "code": null, "e": 27403, "s": 27395, "text": "Python3" }, { "code": null, "e": 27406, "s": 27403, "text": "C#" }, { "code": null, "e": 27417, "s": 27406, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std;#define N 10000 // Adjacency list to store edgesvector<int> adj[N]; int used[N];int max_matching; // Add an edge between U and V in treevoid AddEdge(int u, int v){ // Edge from u to v adj[u].push_back(v); // Edge from V to U adj[v].push_back(u);} // Function that finds the maximum// matching of the DFSvoid Matching_dfs(int u, int p){ for (int i = 0; i < adj[u].size(); i++) { // Go further as we are not // allowed to go towards // its parent if (adj[u][i] != p) { Matching_dfs(adj[u][i], u); } } // If U and its parent P is // not taken then we must // take &mark them as taken if (!used[u] and !used[p] and p != 0) { // Increment size of edge set max_matching++; used[u] = used[p] = 1; }} // Function to find the maximum// matching in a graphvoid maxMatching(){ // Taking 1 as a root of the tree Matching_dfs(1, 0); // Print maximum Matching cout << max_matching << \"\\n\";} // Driver Codeint main(){ int n = 5; // Joining edge between // two nodes in tree AddEdge(1, 2); AddEdge(1, 3); AddEdge(3, 4); AddEdge(3, 5); // Function Call maxMatching(); return 0;}", "e": 28717, "s": 27417, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG{ static final int N = 10000; // Adjacency list to store edges@SuppressWarnings(\"unchecked\")static Vector<Integer>[] adj = new Vector[N]; static int used[] = new int[N];static int max_matching; // Add an edge between U and V in treestatic void AddEdge(int u, int v){ // Edge from u to v adj[u].add(v); // Edge from V to U adj[v].add(u);} // Function that finds the maximum// matching of the DFSstatic void Matching_dfs(int u, int p){ for(int i = 0; i < adj[u].size(); i++) { // Go further as we are not // allowed to go towards // its parent if (adj[u].get(i) != p) { Matching_dfs(adj[u].get(i), u); } } // If U and its parent P is // not taken then we must // take &mark them as taken if (used[u] == 0 && used[p] == 0 && p != 0) { // Increment size of edge set max_matching++; used[u] = used[p] = 1; }} // Function to find the maximum// matching in a graphstatic void maxMatching(){ // Taking 1 as a root of the tree Matching_dfs(1, 0); // Print maximum Matching System.out.print(max_matching + \"\\n\");} // Driver Codepublic static void main(String[] args){ for(int i = 0; i < adj.length; i++) adj[i] = new Vector<Integer>(); // Joining edge between // two nodes in tree AddEdge(1, 2); AddEdge(1, 3); AddEdge(3, 4); AddEdge(3, 5); // Function call maxMatching();}} // This code is contributed by amal kumar choubey", "e": 30310, "s": 28717, "text": null }, { "code": "# Python3 program for the above approachN = 10000 # Adjacency list to store edgesadj = {} used = [0 for i in range(N)] max_matching = 0 # Add an edge between U and V in treedef AddEdge(u, v): if u not in adj: adj[u] = [] if v not in adj: adj[v] = [] # Edge from u to v adj[u].append(v) # Edge from V to U adj[v].append(u) # Function that finds the maximum# matching of the DFSdef Matching_dfs(u, p): global max_matching for i in range(len(adj[u])): # Go further as we are not # allowed to go towards # its parent if (adj[u][i] != p): Matching_dfs(adj[u][i], u) # If U and its parent P is # not taken then we must # take &mark them as taken if (not used[u] and not used[p] and p != 0): # Increment size of edge set max_matching += 1 used[u] = 1 used[p] = 1 # Function to find the maximum# matching in a graphdef maxMatching(): # Taking 1 as a root of the tree Matching_dfs(1, 0) # Print maximum Matching print(max_matching) # Driver Coden = 5 # Joining edge between# two nodes in treeAddEdge(1, 2)AddEdge(1, 3)AddEdge(3, 4)AddEdge(3, 5) # Function CallmaxMatching() # This code is contributed by avanitrachhadiya2155", "e": 31589, "s": 30310, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ static readonly int N = 10000; // Adjacency list to store edgesstatic List<int>[] adj = new List<int>[N]; static int []used = new int[N];static int max_matching; // Add an edge between U and V in treestatic void AddEdge(int u, int v){ // Edge from u to v adj[u].Add(v); // Edge from V to U adj[v].Add(u);} // Function that finds the maximum// matching of the DFSstatic void Matching_dfs(int u, int p){ for(int i = 0; i < adj[u].Count; i++) { // Go further as we are not // allowed to go towards // its parent if (adj[u][i] != p) { Matching_dfs(adj[u][i], u); } } // If U and its parent P is // not taken then we must // take &mark them as taken if (used[u] == 0 && used[p] == 0 && p != 0) { // Increment size of edge set max_matching++; used[u] = used[p] = 1; }} // Function to find the maximum// matching in a graphstatic void maxMatching(){ // Taking 1 as a root of the tree Matching_dfs(1, 0); // Print maximum Matching Console.Write(max_matching + \"\\n\");} // Driver Codepublic static void Main(String[] args){ for(int i = 0; i < adj.Length; i++) adj[i] = new List<int>(); // Joining edge between // two nodes in tree AddEdge(1, 2); AddEdge(1, 3); AddEdge(3, 4); AddEdge(3, 5); // Function call maxMatching();}} // This code is contributed by amal kumar choubey", "e": 33159, "s": 31589, "text": null }, { "code": "<script> // Javascript Program to implement the above approach let N = 10000; // Adjacency list to store edges let adj = new Array(N); let used = new Array(N); used.fill(0); let max_matching = 0; // Add an edge between U and V in tree function AddEdge(u, v) { // Edge from u to v adj[u].push(v); // Edge from V to U adj[v].push(u); } // Function that finds the maximum // matching of the DFS function Matching_dfs(u, p) { for(let i = 0; i < adj[u].length; i++) { // Go further as we are not // allowed to go towards // its parent if (adj[u][i] != p) { Matching_dfs(adj[u][i], u); } } // If U and its parent P is // not taken then we must // take &mark them as taken if (used[u] == 0 && used[p] == 0 && p != 0) { // Increment size of edge set max_matching++; used[u] = used[p] = 1; } } // Function to find the maximum // matching in a graph function maxMatching() { // Taking 1 as a root of the tree Matching_dfs(1, 0); // Print maximum Matching document.write(max_matching + \"</br>\"); } for(let i = 0; i < adj.length; i++) adj[i] = []; // Joining edge between // two nodes in tree AddEdge(1, 2); AddEdge(1, 3); AddEdge(3, 4); AddEdge(3, 5); // Function call maxMatching(); </script>", "e": 34718, "s": 33159, "text": null }, { "code": null, "e": 34720, "s": 34718, "text": "2" }, { "code": null, "e": 34830, "s": 34720, "text": "Time Complexity: O(V + E), where V is the number of edges and E is the number of edges. Auxiliary Space: O(V)" }, { "code": null, "e": 34855, "s": 34830, "text": "Bottom-up DFS approach: " }, { "code": null, "e": 34976, "s": 34855, "text": "Another intuitive approach to solve this problem is to use DFS in a bottom-up manner and return two values at each level" }, { "code": null, "e": 35020, "s": 34976, "text": "Maximum matching including the current node" }, { "code": null, "e": 35064, "s": 35020, "text": "Maximum matching excluding the current node" }, { "code": null, "e": 35228, "s": 35064, "text": "We will recurse on the left and right subtrees and get these values for both of them. We can then calculate new values for the current level based on these values." }, { "code": null, "e": 35433, "s": 35228, "text": "Let left_included denote maximum matching including root of left subtree and left_excluded denote the maximum matching excluding the root of left subtree. Similarly, for right_included and right_excluded." }, { "code": null, "e": 35842, "s": 35433, "text": "If we include the current node in maximum matching, then we have to exclude one of either left sub tree root or right sub tree root. Including both will cause overlapping on current node which is not allowed. By excluding either left or right sub tree root we can increase the maximum matching by 1 by including one of the edges from current_node -> left sub tree root or current_node -> right sub tree root." }, { "code": null, "e": 35904, "s": 35842, "text": "Thus maximum matching including current node will be given by" }, { "code": null, "e": 36012, "s": 35904, "text": "current_including = max(max(left_including, right_excluding) + 1, max(left_excluding, right_including) + 1)" }, { "code": null, "e": 36218, "s": 36012, "text": "If we exclude the current node then we can include both left and right subtree root. As matchings in left and right subtrees are independent of each other we can get maximum value by adding both matchings." }, { "code": null, "e": 36280, "s": 36218, "text": "Thus maximum matching excluding current node will be given by" }, { "code": null, "e": 36333, "s": 36280, "text": "current_excluding = left_including + right_including" }, { "code": null, "e": 36563, "s": 36333, "text": "We will return both these values from the current recursion level to upper recursion levels. After the recursion completes we will receive two values, maximum matching including root node and maximum matching excluding root node." }, { "code": null, "e": 36632, "s": 36563, "text": "The maximum of those two will give the maximum matching in the tree." }, { "code": null, "e": 36640, "s": 36632, "text": "Python3" }, { "code": "class Node: def __init__(self, key): self.left = None self.right = None self.val = key def max_matching_helper(root): if not root: return (0, 0) if not root.left and not root.right: return (0, 0) left_included, left_excluded = max_matching_helper(root.left) right_included, right_excluded = max_matching_helper(root.right) # Maximum matching gincluding current node curr_included = max(max(left_included, right_excluded) + 1, max(left_excluded, right_included) + 1) # Maximum matching excluding current node curr_excluded = left_included + right_included return (curr_included, curr_excluded) def max_matching(root): # Taking 1 as a root of the tree root_including, root_excluding = max_matching_helper(root) # Return maximum Matching return max(root_including, root_excluding) # Driver coderoot = Node(1)root.left = Node(2)root.right = Node(7)root.left.left = Node(3)root.left.right = Node(4)root.left.right.left = Node(5)root.left.right.right = Node(6)root.right.left = Node(8)root.right.right = Node(9) print(max_matching(root)) # This code is contributed by Rathijeet Bhave", "e": 37795, "s": 36640, "text": null }, { "code": null, "e": 37797, "s": 37795, "text": "3" }, { "code": null, "e": 37886, "s": 37797, "text": " Time Complexity: O(V + E), where V is the number of edges and E is the number of edges." }, { "code": null, "e": 37909, "s": 37886, "text": " Auxiliary Space: O(V)" }, { "code": null, "e": 37928, "s": 37909, "text": "Amal Kumar Choubey" }, { "code": null, "e": 37949, "s": 37928, "text": "avanitrachhadiya2155" }, { "code": null, "e": 37964, "s": 37949, "text": "rathijeetbhave" }, { "code": null, "e": 37978, "s": 37964, "text": "divyesh072019" }, { "code": null, "e": 37992, "s": 37978, "text": "sumitgumber28" }, { "code": null, "e": 37996, "s": 37992, "text": "DFS" }, { "code": null, "e": 38016, "s": 37996, "text": "PostOrder Traversal" }, { "code": null, "e": 38032, "s": 38016, "text": "Tree Traversals" }, { "code": null, "e": 38047, "s": 38032, "text": "tree-traversal" }, { "code": null, "e": 38053, "s": 38047, "text": "Trees" }, { "code": null, "e": 38060, "s": 38053, "text": "Greedy" }, { "code": null, "e": 38065, "s": 38060, "text": "Tree" }, { "code": null, "e": 38072, "s": 38065, "text": "Greedy" }, { "code": null, "e": 38076, "s": 38072, "text": "DFS" }, { "code": null, "e": 38081, "s": 38076, "text": "Tree" }, { "code": null, "e": 38179, "s": 38081, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38214, "s": 38179, "text": "Optimal Page Replacement Algorithm" }, { "code": null, "e": 38266, "s": 38214, "text": "Program for Best Fit algorithm in Memory Management" }, { "code": null, "e": 38319, "s": 38266, "text": "Program for First Fit algorithm in Memory Management" }, { "code": null, "e": 38349, "s": 38319, "text": "Max Flow Problem Introduction" }, { "code": null, "e": 38402, "s": 38349, "text": "Program for Worst Fit algorithm in Memory Management" }, { "code": null, "e": 38452, "s": 38402, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 38487, "s": 38452, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 38521, "s": 38487, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 38550, "s": 38521, "text": "AVL Tree | Set 1 (Insertion)" } ]
C# Data Types
As explained in the variables chapter, a variable in C# must be a specified data type: int myNum = 5; // Integer (whole number) double myDoubleNum = 5.99D; // Floating point number char myLetter = 'D'; // Character bool myBool = true; // Boolean string myText = "Hello"; // String Try it Yourself » A data type specifies the size and type of variable values. It is important to use the correct data type for the corresponding variable; to avoid errors, to save time and memory, but it will also make your code more maintainable and readable. The most common data types are: Number types are divided into two groups: Integer types stores whole numbers, positive or negative (such as 123 or -456), without decimals. Valid types are int and long. Which type you should use, depends on the numeric value. Floating point types represents numbers with a fractional part, containing one or more decimals. Valid types are float and double. Even though there are many numeric types in C#, the most used for numbers are int (for whole numbers) and double (for floating point numbers). However, we will describe them all as you continue to read. The int data type can store whole numbers from -2147483648 to 2147483647. In general, and in our tutorial, the int data type is the preferred data type when we create variables with a numeric value. int myNum = 100000; Console.WriteLine(myNum); Try it Yourself » The long data type can store whole numbers from -9223372036854775808 to 9223372036854775807. This is used when int is not large enough to store the value. Note that you should end the value with an "L": long myNum = 15000000000L; Console.WriteLine(myNum); Try it Yourself » You should use a floating point type whenever you need a number with a decimal, such as 9.99 or 3.14515. The float data type can store fractional numbers from 3.4e−038 to 3.4e+038. Note that you should end the value with an "F": float myNum = 5.75F; Console.WriteLine(myNum); Try it Yourself » The double data type can store fractional numbers from 1.7e−308 to 1.7e+308. Note that you can end the value with a "D" (although not required): double myNum = 19.99D; Console.WriteLine(myNum); Try it Yourself » Use float or double? The precision of a floating point value indicates how many digits the value can have after the decimal point. The precision of float is only six or seven decimal digits, while double variables have a precision of about 15 digits. Therefore it is safer to use double for most calculations. A floating point number can also be a scientific number with an "e" to indicate the power of 10: float f1 = 35e3F; double d1 = 12E4D; Console.WriteLine(f1); Console.WriteLine(d1); Try it Yourself » A boolean data type is declared with the bool keyword and can only take the values true or false: bool isCSharpFun = true; bool isFishTasty = false; Console.WriteLine(isCSharpFun); // Outputs True Console.WriteLine(isFishTasty); // Outputs False Try it Yourself » Boolean values are mostly used for conditional testing, which you will learn more about in a later chapter. The char data type is used to store a single character. The character must be surrounded by single quotes, like 'A' or 'c': char myGrade = 'B'; Console.WriteLine(myGrade); Try it Yourself » The string data type is used to store a sequence of characters (text). String values must be surrounded by double quotes: string greeting = "Hello World"; Console.WriteLine(greeting); Try it Yourself » Add the correct data type for the following variables: myNum = 9; myDoubleNum = 8.99; myLetter = 'A'; myBoolean = false; myText = "Hello World"; Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 87, "s": 0, "text": "As explained in the variables chapter, a variable in C# must be a specified data type:" }, { "code": null, "e": 318, "s": 87, "text": "int myNum = 5; // Integer (whole number)\ndouble myDoubleNum = 5.99D; // Floating point number\nchar myLetter = 'D'; // Character\nbool myBool = true; // Boolean\nstring myText = \"Hello\"; // String\n" }, { "code": null, "e": 338, "s": 318, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 614, "s": 338, "text": "A data type specifies the size and type of variable values. It is important to use the correct data type for the corresponding variable; to avoid errors, to save time and memory, but it will also make your code more maintainable and readable. The most common \ndata types are:" }, { "code": null, "e": 656, "s": 614, "text": "Number types are divided into two groups:" }, { "code": null, "e": 843, "s": 656, "text": "Integer types stores whole numbers, positive or negative (such as 123 or -456), without decimals. \nValid types are int \nand long. Which type you should use, depends on the numeric value." }, { "code": null, "e": 975, "s": 843, "text": "Floating point types represents numbers with a fractional \npart, containing one or more decimals. Valid types are float and double." }, { "code": null, "e": 1180, "s": 975, "text": "Even though there are many numeric types in C#, the most used for numbers \nare int (for whole numbers) and double (for floating point numbers). However, we will describe them all as you continue to \nread." }, { "code": null, "e": 1381, "s": 1180, "text": "The int data type can store whole numbers from -2147483648 to 2147483647. In general, and in our tutorial, the int data type is \nthe preferred data type when we create variables with a numeric value." }, { "code": null, "e": 1428, "s": 1381, "text": "int myNum = 100000;\nConsole.WriteLine(myNum);\n" }, { "code": null, "e": 1448, "s": 1428, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 1651, "s": 1448, "text": "The long data type can store whole numbers from -9223372036854775808 to 9223372036854775807. This is used when int is not large enough to store the value. Note that you should end the value with an \"L\":" }, { "code": null, "e": 1705, "s": 1651, "text": "long myNum = 15000000000L;\nConsole.WriteLine(myNum);\n" }, { "code": null, "e": 1725, "s": 1705, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 1830, "s": 1725, "text": "You should use a floating point type whenever you need a number with a decimal, such as 9.99 or 3.14515." }, { "code": null, "e": 1954, "s": 1830, "text": "The float data type can store fractional numbers from 3.4e−038 to 3.4e+038. Note that you should end the value with an \"F\":" }, { "code": null, "e": 2002, "s": 1954, "text": "float myNum = 5.75F;\nConsole.WriteLine(myNum);\n" }, { "code": null, "e": 2022, "s": 2002, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 2167, "s": 2022, "text": "The double data type can store fractional numbers from 1.7e−308 to 1.7e+308. Note that you can end the value with a \"D\" (although not required):" }, { "code": null, "e": 2217, "s": 2167, "text": "double myNum = 19.99D;\nConsole.WriteLine(myNum);\n" }, { "code": null, "e": 2237, "s": 2217, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 2258, "s": 2237, "text": "Use float or double?" }, { "code": null, "e": 2550, "s": 2258, "text": "The precision of a floating point value indicates how many digits the value can have \nafter the decimal point.\nThe precision of float is only six or seven \ndecimal digits, while double variables have a precision \nof about 15 digits. Therefore it is safer to use double for most calculations." }, { "code": null, "e": 2647, "s": 2550, "text": "A floating point number can also be a scientific number with an \"e\" to indicate the power of 10:" }, { "code": null, "e": 2731, "s": 2647, "text": "float f1 = 35e3F;\ndouble d1 = 12E4D;\nConsole.WriteLine(f1);\nConsole.WriteLine(d1);\n" }, { "code": null, "e": 2751, "s": 2731, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 2849, "s": 2751, "text": "A boolean data type is declared with the bool keyword and can only take the values true or false:" }, { "code": null, "e": 3002, "s": 2849, "text": "bool isCSharpFun = true;\nbool isFishTasty = false;\nConsole.WriteLine(isCSharpFun); // Outputs True\nConsole.WriteLine(isFishTasty); // Outputs False\n" }, { "code": null, "e": 3022, "s": 3002, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 3130, "s": 3022, "text": "Boolean values are mostly used for conditional testing, which you will learn more about in a later chapter." }, { "code": null, "e": 3256, "s": 3130, "text": "The char data type is used to store a \nsingle character. The character must be \nsurrounded by single quotes, like 'A' or 'c':" }, { "code": null, "e": 3305, "s": 3256, "text": "char myGrade = 'B';\nConsole.WriteLine(myGrade);\n" }, { "code": null, "e": 3325, "s": 3305, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 3447, "s": 3325, "text": "The string data type is used to store a sequence of characters (text). String values must be surrounded by double quotes:" }, { "code": null, "e": 3510, "s": 3447, "text": "string greeting = \"Hello World\";\nConsole.WriteLine(greeting);\n" }, { "code": null, "e": 3530, "s": 3510, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 3585, "s": 3530, "text": "Add the correct data type for the following variables:" }, { "code": null, "e": 3681, "s": 3585, "text": " myNum = 9;\n myDoubleNum = 8.99;\n myLetter = 'A';\n myBoolean = false;\n myText = \"Hello World\";\n" }, { "code": null, "e": 3700, "s": 3681, "text": "Start the Exercise" }, { "code": null, "e": 3733, "s": 3700, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 3775, "s": 3733, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 3882, "s": 3775, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 3901, "s": 3882, "text": "help@w3schools.com" } ]
Writing a Python Package. A gentle introduction to the world of... | by Chinmay Shah | Towards Data Science
A few years back when I typed pip install opencv-python, a few seconds passed and something magical happened- I was able to use OpenCV; no need to build it from source, no compiler needed, it was definitely breathtaking. I could install any package I wanted and not worry about building it source/ installing or configuring the system variable. Over the years, I continued using pip and every time, it didn’t fail to fascinate me. It really made me wonder how simple a piece of technology can be. Being a Windows user, every time I installed something new, I had to configure the system path. So this definitely made my life simpler. A few months back I decided to write my own python package. I always found Graphs interesting and decided to write a full-fledged graph library and I started writing Grapho (it’s work in progress). Files in the same module can always be imported by all files in the directory. But what if you want to make your module available throughout your system? > You add a setup.py to your module (with relevant configuration of course). But what if you want python package available to everyone across the globe? > You publish your package on PyPI. (so everyone can pip install your-package-name) Enough talk, let’s write some code. Let’s write a simple function and package it. # hello.py def heythere(): print("hey there") # setup.py #!/usr/bin/env python# -*- coding: utf-8 -*-from setuptools import setup, find_packagessetup( author="Chinmay Shah", author_email='chinmayshah3899@gmail.com', classifiers=[ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.7', ], description="Says hello", license="MIT license", include_package_data=True, name='hello', version='0.1.0', zip_safe=False,) Setup.py is what pip looks for in a given directory. It uses something called setuptools[1] which enables packaging. It contains the name of your package, a brief description of your package, along with author information. And don’t fail to mention which python version it’s made for. All of this metadata is important. Looks simple? Let’s try this stuff out then. Let’s install it — pip install . But what does it mean when I say it installs it? First, it creates a wheel (.whl) file; which is an accepted file for package distribution.In the installation process, it uses this wheel file and installs it in site-package directory(Anaconda uses this).In-case of downloading it from the internet, a local cache is often created in pkgs folder. First, it creates a wheel (.whl) file; which is an accepted file for package distribution. In the installation process, it uses this wheel file and installs it in site-package directory(Anaconda uses this). In-case of downloading it from the internet, a local cache is often created in pkgs folder. pip is a package installer for Python used to install packages (mainly) from PyPI(Python Package Index). Launched in 2008 as an upgrade to easyinstall, even though both are built on top of setuptools. [1] PyPI is a vast package index where anyone can submit their package, and anyone across the globe can do pip install your-package-name . Look out for the next post, where I’ll be covering on how to write package as well as publishing it on PyPI. Have any thoughts? Reach out on Twitter, Linkedin or E-Mail. Reference: [1] Setuptools — https://setuptools.readthedocs.io/en/latest/
[ { "code": null, "e": 392, "s": 47, "text": "A few years back when I typed pip install opencv-python, a few seconds passed and something magical happened- I was able to use OpenCV; no need to build it from source, no compiler needed, it was definitely breathtaking. I could install any package I wanted and not worry about building it source/ installing or configuring the system variable." }, { "code": null, "e": 681, "s": 392, "text": "Over the years, I continued using pip and every time, it didn’t fail to fascinate me. It really made me wonder how simple a piece of technology can be. Being a Windows user, every time I installed something new, I had to configure the system path. So this definitely made my life simpler." }, { "code": null, "e": 879, "s": 681, "text": "A few months back I decided to write my own python package. I always found Graphs interesting and decided to write a full-fledged graph library and I started writing Grapho (it’s work in progress)." }, { "code": null, "e": 1033, "s": 879, "text": "Files in the same module can always be imported by all files in the directory. But what if you want to make your module available throughout your system?" }, { "code": null, "e": 1110, "s": 1033, "text": "> You add a setup.py to your module (with relevant configuration of course)." }, { "code": null, "e": 1186, "s": 1110, "text": "But what if you want python package available to everyone across the globe?" }, { "code": null, "e": 1270, "s": 1186, "text": "> You publish your package on PyPI. (so everyone can pip install your-package-name)" }, { "code": null, "e": 1352, "s": 1270, "text": "Enough talk, let’s write some code. Let’s write a simple function and package it." }, { "code": null, "e": 1363, "s": 1352, "text": "# hello.py" }, { "code": null, "e": 1399, "s": 1363, "text": "def heythere(): print(\"hey there\")" }, { "code": null, "e": 1410, "s": 1399, "text": "# setup.py" }, { "code": null, "e": 1809, "s": 1410, "text": "#!/usr/bin/env python# -*- coding: utf-8 -*-from setuptools import setup, find_packagessetup( author=\"Chinmay Shah\", author_email='chinmayshah3899@gmail.com', classifiers=[ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.7', ], description=\"Says hello\", license=\"MIT license\", include_package_data=True, name='hello', version='0.1.0', zip_safe=False,)" }, { "code": null, "e": 2129, "s": 1809, "text": "Setup.py is what pip looks for in a given directory. It uses something called setuptools[1] which enables packaging. It contains the name of your package, a brief description of your package, along with author information. And don’t fail to mention which python version it’s made for. All of this metadata is important." }, { "code": null, "e": 2207, "s": 2129, "text": "Looks simple? Let’s try this stuff out then. Let’s install it — pip install ." }, { "code": null, "e": 2256, "s": 2207, "text": "But what does it mean when I say it installs it?" }, { "code": null, "e": 2553, "s": 2256, "text": "First, it creates a wheel (.whl) file; which is an accepted file for package distribution.In the installation process, it uses this wheel file and installs it in site-package directory(Anaconda uses this).In-case of downloading it from the internet, a local cache is often created in pkgs folder." }, { "code": null, "e": 2644, "s": 2553, "text": "First, it creates a wheel (.whl) file; which is an accepted file for package distribution." }, { "code": null, "e": 2760, "s": 2644, "text": "In the installation process, it uses this wheel file and installs it in site-package directory(Anaconda uses this)." }, { "code": null, "e": 2852, "s": 2760, "text": "In-case of downloading it from the internet, a local cache is often created in pkgs folder." }, { "code": null, "e": 3057, "s": 2852, "text": "pip is a package installer for Python used to install packages (mainly) from PyPI(Python Package Index). Launched in 2008 as an upgrade to easyinstall, even though both are built on top of setuptools. [1]" }, { "code": null, "e": 3192, "s": 3057, "text": "PyPI is a vast package index where anyone can submit their package, and anyone across the globe can do pip install your-package-name ." }, { "code": null, "e": 3301, "s": 3192, "text": "Look out for the next post, where I’ll be covering on how to write package as well as publishing it on PyPI." }, { "code": null, "e": 3362, "s": 3301, "text": "Have any thoughts? Reach out on Twitter, Linkedin or E-Mail." }, { "code": null, "e": 3373, "s": 3362, "text": "Reference:" } ]
How to remove lines in a Matplotlib plot?
We will create two lines, i.e., line1 and line2. After that, we will pop the second line and will remove it. Create lists for line1 and line2. Create lists for line1 and line2. Plot line1 and line 2 using plot() method, line 2 with style =’dashed’. Plot line1 and line 2 using plot() method, line 2 with style =’dashed’. Set or retrieve auto-scaling margins(0.2). Set or retrieve auto-scaling margins(0.2). Pop line 2, and remove it using remove() method. Pop line 2, and remove it using remove() method. The final figure will have only one line, so use plt.show() method. The final figure will have only one line, so use plt.show() method. import matplotlib.pyplot as plt line1 = [2, 4, 8] line2 = [3, 6, 12] plt.plot(line1) line_2 = plt.plot(line2, linestyle='dashed') plt.margins(0.2) plt.title("With extra lines") plt.show() plt.plot(line1) l = line_2.pop(0) l.remove() plt.margins(0.2) plt.title("Removed extra lines") plt.show()
[ { "code": null, "e": 1171, "s": 1062, "text": "We will create two lines, i.e., line1 and line2. After that, we will pop the second line and will remove it." }, { "code": null, "e": 1205, "s": 1171, "text": "Create lists for line1 and line2." }, { "code": null, "e": 1239, "s": 1205, "text": "Create lists for line1 and line2." }, { "code": null, "e": 1311, "s": 1239, "text": "Plot line1 and line 2 using plot() method, line 2 with style =’dashed’." }, { "code": null, "e": 1383, "s": 1311, "text": "Plot line1 and line 2 using plot() method, line 2 with style =’dashed’." }, { "code": null, "e": 1426, "s": 1383, "text": "Set or retrieve auto-scaling margins(0.2)." }, { "code": null, "e": 1469, "s": 1426, "text": "Set or retrieve auto-scaling margins(0.2)." }, { "code": null, "e": 1518, "s": 1469, "text": "Pop line 2, and remove it using remove() method." }, { "code": null, "e": 1567, "s": 1518, "text": "Pop line 2, and remove it using remove() method." }, { "code": null, "e": 1635, "s": 1567, "text": "The final figure will have only one line, so use plt.show() method." }, { "code": null, "e": 1703, "s": 1635, "text": "The final figure will have only one line, so use plt.show() method." }, { "code": null, "e": 2001, "s": 1703, "text": "import matplotlib.pyplot as plt\n\nline1 = [2, 4, 8]\nline2 = [3, 6, 12]\n\nplt.plot(line1)\nline_2 = plt.plot(line2, linestyle='dashed')\nplt.margins(0.2)\nplt.title(\"With extra lines\")\nplt.show()\n\nplt.plot(line1)\nl = line_2.pop(0)\nl.remove()\nplt.margins(0.2)\nplt.title(\"Removed extra lines\")\n\nplt.show()" } ]
How can we sort a string without using predefined methods in Java?
A String is an object that represents an immutable sequence of characters and cannot be changed once created. The java.lang.String class can be used to create a string object. In the below program, we can sort the characters of a string without using any predefined methods of String class in Java. public class SortStringWithoutPredefinedMethodsTest { public static void main(String[] args) { String str = "jdkoepacmbtr"; System.out.println("Before Sorting:" + str); int j = 0; char temp = 0; char[] chars = str.toCharArray(); for(int i=0; i < chars.length; i++) { for(j=0; j < chars.length; j++) { if(chars[j] > chars[i]) { temp = chars[i]; chars[i] = chars[j]; chars[j] = temp; } } } System.out.println("After Sorting:"); for(int k=0; k < chars.length; k++) { System.out.println(chars[k]); } } } Before Sorting: jdkoepacmbtr After Sorting: a b c d e j k m o p r t
[ { "code": null, "e": 1238, "s": 1062, "text": "A String is an object that represents an immutable sequence of characters and cannot be changed once created. The java.lang.String class can be used to create a string object." }, { "code": null, "e": 1361, "s": 1238, "text": "In the below program, we can sort the characters of a string without using any predefined methods of String class in Java." }, { "code": null, "e": 2023, "s": 1361, "text": "public class SortStringWithoutPredefinedMethodsTest {\n public static void main(String[] args) {\n String str = \"jdkoepacmbtr\";\n System.out.println(\"Before Sorting:\" + str);\n int j = 0;\n char temp = 0;\n char[] chars = str.toCharArray();\n for(int i=0; i < chars.length; i++) {\n for(j=0; j < chars.length; j++) {\n if(chars[j] > chars[i]) {\n temp = chars[i];\n chars[i] = chars[j];\n chars[j] = temp;\n }\n }\n }\n System.out.println(\"After Sorting:\");\n for(int k=0; k < chars.length; k++) {\n System.out.println(chars[k]);\n }\n }\n}" }, { "code": null, "e": 2091, "s": 2023, "text": "Before Sorting: jdkoepacmbtr\nAfter Sorting:\na\nb\nc\nd\ne\nj\nk\nm\no\np\nr\nt" } ]
C# int.TryParse Method
Convert a string representation of number to an integer, using the int.TryParse method in C#. If the string cannot be converted, then the int.TryParse method returns false i.e. a Boolean value. Let’s say you have a string representation of a number. string myStr = "12"; Now to convert it to an integer, use the int.TryParse(). It will get converted and will return True. int.TryParse(myStr, out a); Live Demo using System.IO; using System; class Program { static void Main() { bool res; int a; string myStr = "12"; res = int.TryParse(myStr, out a); Console.WriteLine("String is a numeric representation: "+res); } } String is a numeric representation: True
[ { "code": null, "e": 1256, "s": 1062, "text": "Convert a string representation of number to an integer, using the int.TryParse method in C#. If the string cannot be converted, then the int.TryParse method returns false i.e. a Boolean value." }, { "code": null, "e": 1312, "s": 1256, "text": "Let’s say you have a string representation of a number." }, { "code": null, "e": 1333, "s": 1312, "text": "string myStr = \"12\";" }, { "code": null, "e": 1434, "s": 1333, "text": "Now to convert it to an integer, use the int.TryParse(). It will get converted and will return True." }, { "code": null, "e": 1462, "s": 1434, "text": "int.TryParse(myStr, out a);" }, { "code": null, "e": 1473, "s": 1462, "text": " Live Demo" }, { "code": null, "e": 1716, "s": 1473, "text": "using System.IO;\nusing System;\nclass Program {\n static void Main() {\n bool res;\n int a;\n string myStr = \"12\";\n res = int.TryParse(myStr, out a);\n Console.WriteLine(\"String is a numeric representation: \"+res);\n }\n}" }, { "code": null, "e": 1757, "s": 1716, "text": "String is a numeric representation: True" } ]
The Power of Permutation Testing. Getting creative when running... | by Kieran | Towards Data Science
Hypothesis testing has been around for decades, with well-established methods of determining whether the results that have been observed are significant. Yet sometimes it can be easy to lose track of which testing approach to use or whether it can be reliably applied to your situation. Companies often use surveys to track their NPS (Net Promoter Score), a measure that’s designed to reflect customer loyalty and potential for growth. The calculation is simple, ask customers how likely they are to recommend your business on a scale of 0–10, then subtract the percentage of negative responses from the percentage of positive. What’s less simple, however, is knowing when two scores are significantly different from each other. Traditional hypothesis testing is usually answering the question of whether two means, proportions, or variances are meaningfully different from one another. NPS does not slot neatly into those tests because it’s actually measuring the difference in two correlated proportions. What test statistic do you use for that? Some kind of solution is needed. If we’re conducting an experiment where a random sample of customers receives a new type of service, it’s not good enough to simply eye-ball our survey results, we want to know whether it has had a genuine impact on their NPS. Enter the permutation test, a technique that is so useful because it can be applied to any test statistic we define and makes no assumptions about the underlying distribution being normal. Permutation testing starts off with the null hypothesis that there is no difference between the two groups we are measuring. If that assumption is true, we should be able to randomly shuffle all of the observed values between the two groups without influencing their overall statistics. To check whether the null hypothesis can be rejected, the data is randomly shuffled, again and again, and the difference between the two randomly created groups is recorded each time. At the end of it all, the actual difference observed between the two groups can be compared with the thousands of simulations performed to see how surprising/unlikely it would be under the null hypothesis. In using this approach, we can dispense with any complex formulae and instead follow an intuitive process that captures what a null hypothesis and p-value really mean. Let’s see how this can be done in Python. Firstly, assume we have a dataset that includes the NPS survey responses of customers in two different groups: import pandas as pddf = pd.read_csv('nps_data.csv')df.head()| group | response || ------- | -------- || control | 7 || test | 3 || ... | ... || test | 5 | A handy technique I borrowed from Displayr shows that we don’t have to calculate the % of promoters and detractors each time in order to subtract one from the other. We can instead replace promoter scores with 100, detractor scores with -100, and neutrals with 0, so that taking the mean represents the overall NPS score. df.loc[df['response'].between(0, 6), 'recoded'] = -100 # Detractorsdf.loc[df['response'].between(7, 8), 'recoded'] = 0 # Neutralsdf.loc[df['response'].between(9, 10), 'recoded'] = 100 # Promoters Next, we need a process that can randomly shuffle all of the data and record the difference in NPS. import numpy as npdef simulate_difference_in_nps(nps_data: pd.DataFrame) -> float: """ Shuffle all of the responses and reassign them to each group, before calculating the absolute difference in NPS between the two groups in this simulated scenario. Parameters ---------- nps_data : pandas DataFrame Dataset containing the NPS scores of survey respondents from two different groups. Returns ------- float The absolute difference in NPS scores between the two groups once all of the responses had been shuffled and reassigned to each group. """ responses_in_single_group = nps_data.value_counts('group')[0] randomly_shuffled = np.random.permutation( nps_data['recoded'].values ) nps_1 = randomly_shuffled[:responses_in_single_group].mean() nps_2 = randomly_shuffled[responses_in_single_group:].mean() return abs(nps_2 - nps_1) The process will be repeated again and again to build a robust sample of simulations given that it would generally be impractical, even for a powerful computer, to explore every possible permutation of the results. This approach of taking a fixed number of samples rather than all possible permutations is known as the Monte Carlo method. num_simulations = 100000simulated_results = []for _ in range(num_simulations): simulated_results.append( simulate_difference_in_nps(nps_data=df) ) simulated_results = np.array(simulated_results) The final step is to determine whether we can reject the null hypothesis after comparing what we observed to the thousands of simulations run with random permutations of the data. # This would be calculated from the original data, but let's # hard-code a value for simplicityobserved_difference_in_nps = 1.6# Use 5% level of significancesignificance_level = 0.05# How often did we see a difference as extreme, or more extreme, # than what was observedsimulations_as_or_more_extreme = sum( simulated_results >= observed_difference_in_nps)# The observed result is statistically significant if its p-value is # less than the pre-defined significance level # i.e. it was very unlikely to occur under the null hypothesisnum_simulations = simulated_results.shape[0]p_value = simulations_greater_than_observed / num_simulations# Boolean which is True if significant, False otherwisesignificant_or_not = p_value < significance_level As a nice bonus, with all of those random simulations performed, we can even visualise how unusual our observed result would be under the null hypothesis. import matplotlib.pyplot as pltimport seaborn as sns# Plot permutation simulationsdensity_plot = sns.kdeplot(simulated_results, shade=True)density_plot.set( xlabel='Absolute Difference in NPS Scores Between Groups', ylabel='Proportion of Simulations', title='How Surprising Is Our Observed Result?')# Add a line to show the actual difference observed in the datadensity_plot.axvline( x=observed_difference_in_nps, color='red', linestyle='--')plt.legend( labels=['Observed Difference', 'Simulated'], loc='upper right')plt.show() And that’s that! We now have a template for performing a two-tailed test on NPS scores. It wouldn’t take much effort to refactor the code for one-tailed tests; simply record the difference for each permutation rather than the absolute difference. The implementation above helps explain the steps needed, but it’s a touch clunky and inefficient. Check out my GitHub repo to see how this process can be placed within a more efficient, unit-tested, helper class that can be parallelised across multiple cores when repeating the permutation process. The same repo also contains the demonstration below on how to use the code. This article focuses on NPS for illustration, but permutation testing can be applied to any domain, particularly ones in which we’re unsure what the distribution of the variable we are measuring looks like. As with any statistical approach, however, there are a few things to consider before using permutation testing. We still need to start with an appropriate sample size. If we only have 3 respondents in each group, any form of hypothesis testing is probably a pointless exercise.The null hypothesis states that the values for each group are exchangeable, so we are technically testing whether the values from Group 1 come from the same distribution as Group 2. Therefore permutation testing still has an assumption that the two groups have the same underlying variance, which may not always be valid1.Knowing how many permutations to perform can be tricky. In simple terms, it’s best to err on the side of caution and choose as many as our machine can handle within the amount of time we’re willing to wait. There is plenty of further reading on picking the number in advance2 3. We still need to start with an appropriate sample size. If we only have 3 respondents in each group, any form of hypothesis testing is probably a pointless exercise. The null hypothesis states that the values for each group are exchangeable, so we are technically testing whether the values from Group 1 come from the same distribution as Group 2. Therefore permutation testing still has an assumption that the two groups have the same underlying variance, which may not always be valid1. Knowing how many permutations to perform can be tricky. In simple terms, it’s best to err on the side of caution and choose as many as our machine can handle within the amount of time we’re willing to wait. There is plenty of further reading on picking the number in advance2 3. Keep those considerations in mind and you’ll safely add a whole new testing approach to your data science toolkit. Feel free to check out my other articles: A simple trick to avoid running out of memory How to Find the Right Number of Clusters How to Manage a Junior Data Scientist Making Your Loss Function Count [1] Rand R. Wilcox, 8 — COMPARING TWO INDEPENDENT GROUPS, Editor(s): Rand R. Wilcox, Applying Contemporary Statistical Techniques, Academic Press, 2003, Pages 237–284, ISBN 9780127515410, https://doi.org/10.1016/B978-012751541-0/50029-8.(https://www.sciencedirect.com/science/article/pii/B9780127515410500298)
[ { "code": null, "e": 459, "s": 172, "text": "Hypothesis testing has been around for decades, with well-established methods of determining whether the results that have been observed are significant. Yet sometimes it can be easy to lose track of which testing approach to use or whether it can be reliably applied to your situation." }, { "code": null, "e": 608, "s": 459, "text": "Companies often use surveys to track their NPS (Net Promoter Score), a measure that’s designed to reflect customer loyalty and potential for growth." }, { "code": null, "e": 800, "s": 608, "text": "The calculation is simple, ask customers how likely they are to recommend your business on a scale of 0–10, then subtract the percentage of negative responses from the percentage of positive." }, { "code": null, "e": 1179, "s": 800, "text": "What’s less simple, however, is knowing when two scores are significantly different from each other. Traditional hypothesis testing is usually answering the question of whether two means, proportions, or variances are meaningfully different from one another. NPS does not slot neatly into those tests because it’s actually measuring the difference in two correlated proportions." }, { "code": null, "e": 1220, "s": 1179, "text": "What test statistic do you use for that?" }, { "code": null, "e": 1480, "s": 1220, "text": "Some kind of solution is needed. If we’re conducting an experiment where a random sample of customers receives a new type of service, it’s not good enough to simply eye-ball our survey results, we want to know whether it has had a genuine impact on their NPS." }, { "code": null, "e": 1669, "s": 1480, "text": "Enter the permutation test, a technique that is so useful because it can be applied to any test statistic we define and makes no assumptions about the underlying distribution being normal." }, { "code": null, "e": 1956, "s": 1669, "text": "Permutation testing starts off with the null hypothesis that there is no difference between the two groups we are measuring. If that assumption is true, we should be able to randomly shuffle all of the observed values between the two groups without influencing their overall statistics." }, { "code": null, "e": 2346, "s": 1956, "text": "To check whether the null hypothesis can be rejected, the data is randomly shuffled, again and again, and the difference between the two randomly created groups is recorded each time. At the end of it all, the actual difference observed between the two groups can be compared with the thousands of simulations performed to see how surprising/unlikely it would be under the null hypothesis." }, { "code": null, "e": 2514, "s": 2346, "text": "In using this approach, we can dispense with any complex formulae and instead follow an intuitive process that captures what a null hypothesis and p-value really mean." }, { "code": null, "e": 2556, "s": 2514, "text": "Let’s see how this can be done in Python." }, { "code": null, "e": 2667, "s": 2556, "text": "Firstly, assume we have a dataset that includes the NPS survey responses of customers in two different groups:" }, { "code": null, "e": 2860, "s": 2667, "text": "import pandas as pddf = pd.read_csv('nps_data.csv')df.head()| group | response || ------- | -------- || control | 7 || test | 3 || ... | ... || test | 5 |" }, { "code": null, "e": 3182, "s": 2860, "text": "A handy technique I borrowed from Displayr shows that we don’t have to calculate the % of promoters and detractors each time in order to subtract one from the other. We can instead replace promoter scores with 100, detractor scores with -100, and neutrals with 0, so that taking the mean represents the overall NPS score." }, { "code": null, "e": 3381, "s": 3182, "text": "df.loc[df['response'].between(0, 6), 'recoded'] = -100 # Detractorsdf.loc[df['response'].between(7, 8), 'recoded'] = 0 # Neutralsdf.loc[df['response'].between(9, 10), 'recoded'] = 100 # Promoters" }, { "code": null, "e": 3481, "s": 3381, "text": "Next, we need a process that can randomly shuffle all of the data and record the difference in NPS." }, { "code": null, "e": 4405, "s": 3481, "text": "import numpy as npdef simulate_difference_in_nps(nps_data: pd.DataFrame) -> float: \"\"\" Shuffle all of the responses and reassign them to each group, before calculating the absolute difference in NPS between the two groups in this simulated scenario. Parameters ---------- nps_data : pandas DataFrame Dataset containing the NPS scores of survey respondents from two different groups. Returns ------- float The absolute difference in NPS scores between the two groups once all of the responses had been shuffled and reassigned to each group. \"\"\" responses_in_single_group = nps_data.value_counts('group')[0] randomly_shuffled = np.random.permutation( nps_data['recoded'].values ) nps_1 = randomly_shuffled[:responses_in_single_group].mean() nps_2 = randomly_shuffled[responses_in_single_group:].mean() return abs(nps_2 - nps_1)" }, { "code": null, "e": 4744, "s": 4405, "text": "The process will be repeated again and again to build a robust sample of simulations given that it would generally be impractical, even for a powerful computer, to explore every possible permutation of the results. This approach of taking a fixed number of samples rather than all possible permutations is known as the Monte Carlo method." }, { "code": null, "e": 4955, "s": 4744, "text": "num_simulations = 100000simulated_results = []for _ in range(num_simulations): simulated_results.append( simulate_difference_in_nps(nps_data=df) ) simulated_results = np.array(simulated_results)" }, { "code": null, "e": 5135, "s": 4955, "text": "The final step is to determine whether we can reject the null hypothesis after comparing what we observed to the thousands of simulations run with random permutations of the data." }, { "code": null, "e": 5883, "s": 5135, "text": "# This would be calculated from the original data, but let's # hard-code a value for simplicityobserved_difference_in_nps = 1.6# Use 5% level of significancesignificance_level = 0.05# How often did we see a difference as extreme, or more extreme, # than what was observedsimulations_as_or_more_extreme = sum( simulated_results >= observed_difference_in_nps)# The observed result is statistically significant if its p-value is # less than the pre-defined significance level # i.e. it was very unlikely to occur under the null hypothesisnum_simulations = simulated_results.shape[0]p_value = simulations_greater_than_observed / num_simulations# Boolean which is True if significant, False otherwisesignificant_or_not = p_value < significance_level" }, { "code": null, "e": 6038, "s": 5883, "text": "As a nice bonus, with all of those random simulations performed, we can even visualise how unusual our observed result would be under the null hypothesis." }, { "code": null, "e": 6593, "s": 6038, "text": "import matplotlib.pyplot as pltimport seaborn as sns# Plot permutation simulationsdensity_plot = sns.kdeplot(simulated_results, shade=True)density_plot.set( xlabel='Absolute Difference in NPS Scores Between Groups', ylabel='Proportion of Simulations', title='How Surprising Is Our Observed Result?')# Add a line to show the actual difference observed in the datadensity_plot.axvline( x=observed_difference_in_nps, color='red', linestyle='--')plt.legend( labels=['Observed Difference', 'Simulated'], loc='upper right')plt.show()" }, { "code": null, "e": 6610, "s": 6593, "text": "And that’s that!" }, { "code": null, "e": 6840, "s": 6610, "text": "We now have a template for performing a two-tailed test on NPS scores. It wouldn’t take much effort to refactor the code for one-tailed tests; simply record the difference for each permutation rather than the absolute difference." }, { "code": null, "e": 6938, "s": 6840, "text": "The implementation above helps explain the steps needed, but it’s a touch clunky and inefficient." }, { "code": null, "e": 7139, "s": 6938, "text": "Check out my GitHub repo to see how this process can be placed within a more efficient, unit-tested, helper class that can be parallelised across multiple cores when repeating the permutation process." }, { "code": null, "e": 7215, "s": 7139, "text": "The same repo also contains the demonstration below on how to use the code." }, { "code": null, "e": 7422, "s": 7215, "text": "This article focuses on NPS for illustration, but permutation testing can be applied to any domain, particularly ones in which we’re unsure what the distribution of the variable we are measuring looks like." }, { "code": null, "e": 7534, "s": 7422, "text": "As with any statistical approach, however, there are a few things to consider before using permutation testing." }, { "code": null, "e": 8300, "s": 7534, "text": "We still need to start with an appropriate sample size. If we only have 3 respondents in each group, any form of hypothesis testing is probably a pointless exercise.The null hypothesis states that the values for each group are exchangeable, so we are technically testing whether the values from Group 1 come from the same distribution as Group 2. Therefore permutation testing still has an assumption that the two groups have the same underlying variance, which may not always be valid1.Knowing how many permutations to perform can be tricky. In simple terms, it’s best to err on the side of caution and choose as many as our machine can handle within the amount of time we’re willing to wait. There is plenty of further reading on picking the number in advance2 3." }, { "code": null, "e": 8466, "s": 8300, "text": "We still need to start with an appropriate sample size. If we only have 3 respondents in each group, any form of hypothesis testing is probably a pointless exercise." }, { "code": null, "e": 8789, "s": 8466, "text": "The null hypothesis states that the values for each group are exchangeable, so we are technically testing whether the values from Group 1 come from the same distribution as Group 2. Therefore permutation testing still has an assumption that the two groups have the same underlying variance, which may not always be valid1." }, { "code": null, "e": 9068, "s": 8789, "text": "Knowing how many permutations to perform can be tricky. In simple terms, it’s best to err on the side of caution and choose as many as our machine can handle within the amount of time we’re willing to wait. There is plenty of further reading on picking the number in advance2 3." }, { "code": null, "e": 9183, "s": 9068, "text": "Keep those considerations in mind and you’ll safely add a whole new testing approach to your data science toolkit." }, { "code": null, "e": 9225, "s": 9183, "text": "Feel free to check out my other articles:" }, { "code": null, "e": 9271, "s": 9225, "text": "A simple trick to avoid running out of memory" }, { "code": null, "e": 9312, "s": 9271, "text": "How to Find the Right Number of Clusters" }, { "code": null, "e": 9350, "s": 9312, "text": "How to Manage a Junior Data Scientist" }, { "code": null, "e": 9382, "s": 9350, "text": "Making Your Loss Function Count" } ]
Simple Ways to Apply Lambda Function in Python | by Chi Nguyen | Towards Data Science
An anonymous function is a function without a name. In Python, an anonymous function is determined using lambda keyword. It is because lambda functions do not require a name when it is defined, unlike regular functions. Instead of using def keyword, we use lambda keyword to construct a function. That’s why the anonymous function is also referred to as the lambda function. A lambda function can have several arguments but only have one expression. The following syntax is used to declare a lambda function: lambda argument(s): expression There are thousands of use cases using lambda functions. However, when function objects are required, they are most often applied. Moreover, there is no “return” statement in a lambda definition; instead, it always includes a returned expression. Therefore, for simplicity, you can consider using lambda function. Besides, it is better to use lambda functions when the function expression is small to improve readability. In other words, lambda can only have one expression, hence don’t use a lambda function if your function can’t be stated in a single line of code. Later, we will explore several examples of using the lambda function to understand its use case better. I will explain the usage of the lambda function by applying it to different examples. First, let’s create a simple data frame for manipulation. grade = {'Class':['A1', 'A2', 'A3', 'A4','A5'], 'MathScore':[3.2, 3.3, 2.1, 2.9, 3.6], 'ChemistryScore': [3.2, 3.6,3.3,2.1,4.6]}grade = pd.DataFrame(grade) The dataset illustrates average scores of Maths and Chemistry for five classes from A1 to A5. For example, I want to evaluate the Mathematical ability of each class based on a special formula, which is getting the Math score to the power of the Math score itself, then dividing the result by 2. Here is how I compute by using lambdafunction. grade['evaluate']=grade['MathScore'].apply(lambda x: round((x**x)/2,2)) The apply method calls lambda function, and applies the computation to each row of the data frame. Besides, apply can also do the modification for every column in the data frame. In that case, specify one more argument as axis = 0 in the apply function. My result after the calculation is stored in the “evaluate” column, as you can see below. Output: In another example with our data frame (Figure 1) above, I want to categorize classes based on their performances in Maths and Chemistry. We can use lambda to figure that out easily. grade['group']=grade['MathScore'].apply(lambda x: 'Excellent' if x>=3.0 else 'Average') Output: Suppose I have a list as below: list = [[5,6],[12,32,43],[3,43,42]] To find the sub-list with maximum values, I may apply lambda function and maxas follows: max(list, key=lambda x: sum(x)) As a result, [3,43,42] is the sub-list with the highest total value among the three sub-lists. In case I want to make a comparison between values and get the result of a greater value. Let’s see how we can make it happen with lambda and if-else. Greater = lambda x, y : x if(x > y) else yGreater(0.002, 0.5897) And the result turns out to be 0.5897. Simple, right? Continue to use the example data frame from figure 1, I will find out how many Math scores are greater than the average score. The filter method can filter the data by applying lambda function to the series. Here is how it goes: mean = mean(grade['MathScore'])list(filter(lambda x: x> mean,grade['MathScore'])) And the output is a list of math scores that are greater than its mean: [3.2, 3.3, 3.6] In another case, I want to find the intersection for nested lists with filter method. See what I have in two lists below: group1 = [1, 2,3,43,23,42,8,3,7]group2 = [[3, 34, 23, 32, 42], [6, 11, 9], [1, 3,9,7,2,8]] Now, by applying the following code, I can find out a list in which values in group 2 are also present in group 1: [list(filter(lambda x: x in group1, sublist)) for sublist in group2] Output: [[3, 23, 42], [], [1, 3, 7, 2, 8]] To shortly explain, the filter method examines each sub-list’s item to determine if it is included in group 1. The list comprehension is applied to each sub-list in group 2. Above are some simple examples of lambda.I hope you find them useful. If you have any interesting applications, don't hesitate to share them with me.
[ { "code": null, "e": 546, "s": 171, "text": "An anonymous function is a function without a name. In Python, an anonymous function is determined using lambda keyword. It is because lambda functions do not require a name when it is defined, unlike regular functions. Instead of using def keyword, we use lambda keyword to construct a function. That’s why the anonymous function is also referred to as the lambda function." }, { "code": null, "e": 680, "s": 546, "text": "A lambda function can have several arguments but only have one expression. The following syntax is used to declare a lambda function:" }, { "code": null, "e": 711, "s": 680, "text": "lambda argument(s): expression" }, { "code": null, "e": 842, "s": 711, "text": "There are thousands of use cases using lambda functions. However, when function objects are required, they are most often applied." }, { "code": null, "e": 1025, "s": 842, "text": "Moreover, there is no “return” statement in a lambda definition; instead, it always includes a returned expression. Therefore, for simplicity, you can consider using lambda function." }, { "code": null, "e": 1279, "s": 1025, "text": "Besides, it is better to use lambda functions when the function expression is small to improve readability. In other words, lambda can only have one expression, hence don’t use a lambda function if your function can’t be stated in a single line of code." }, { "code": null, "e": 1383, "s": 1279, "text": "Later, we will explore several examples of using the lambda function to understand its use case better." }, { "code": null, "e": 1527, "s": 1383, "text": "I will explain the usage of the lambda function by applying it to different examples. First, let’s create a simple data frame for manipulation." }, { "code": null, "e": 1697, "s": 1527, "text": "grade = {'Class':['A1', 'A2', 'A3', 'A4','A5'], 'MathScore':[3.2, 3.3, 2.1, 2.9, 3.6], 'ChemistryScore': [3.2, 3.6,3.3,2.1,4.6]}grade = pd.DataFrame(grade)" }, { "code": null, "e": 1791, "s": 1697, "text": "The dataset illustrates average scores of Maths and Chemistry for five classes from A1 to A5." }, { "code": null, "e": 2039, "s": 1791, "text": "For example, I want to evaluate the Mathematical ability of each class based on a special formula, which is getting the Math score to the power of the Math score itself, then dividing the result by 2. Here is how I compute by using lambdafunction." }, { "code": null, "e": 2111, "s": 2039, "text": "grade['evaluate']=grade['MathScore'].apply(lambda x: round((x**x)/2,2))" }, { "code": null, "e": 2455, "s": 2111, "text": "The apply method calls lambda function, and applies the computation to each row of the data frame. Besides, apply can also do the modification for every column in the data frame. In that case, specify one more argument as axis = 0 in the apply function. My result after the calculation is stored in the “evaluate” column, as you can see below." }, { "code": null, "e": 2463, "s": 2455, "text": "Output:" }, { "code": null, "e": 2646, "s": 2463, "text": "In another example with our data frame (Figure 1) above, I want to categorize classes based on their performances in Maths and Chemistry. We can use lambda to figure that out easily." }, { "code": null, "e": 2734, "s": 2646, "text": "grade['group']=grade['MathScore'].apply(lambda x: 'Excellent' if x>=3.0 else 'Average')" }, { "code": null, "e": 2742, "s": 2734, "text": "Output:" }, { "code": null, "e": 2774, "s": 2742, "text": "Suppose I have a list as below:" }, { "code": null, "e": 2810, "s": 2774, "text": "list = [[5,6],[12,32,43],[3,43,42]]" }, { "code": null, "e": 2899, "s": 2810, "text": "To find the sub-list with maximum values, I may apply lambda function and maxas follows:" }, { "code": null, "e": 2931, "s": 2899, "text": "max(list, key=lambda x: sum(x))" }, { "code": null, "e": 3026, "s": 2931, "text": "As a result, [3,43,42] is the sub-list with the highest total value among the three sub-lists." }, { "code": null, "e": 3177, "s": 3026, "text": "In case I want to make a comparison between values and get the result of a greater value. Let’s see how we can make it happen with lambda and if-else." }, { "code": null, "e": 3242, "s": 3177, "text": "Greater = lambda x, y : x if(x > y) else yGreater(0.002, 0.5897)" }, { "code": null, "e": 3296, "s": 3242, "text": "And the result turns out to be 0.5897. Simple, right?" }, { "code": null, "e": 3525, "s": 3296, "text": "Continue to use the example data frame from figure 1, I will find out how many Math scores are greater than the average score. The filter method can filter the data by applying lambda function to the series. Here is how it goes:" }, { "code": null, "e": 3607, "s": 3525, "text": "mean = mean(grade['MathScore'])list(filter(lambda x: x> mean,grade['MathScore']))" }, { "code": null, "e": 3695, "s": 3607, "text": "And the output is a list of math scores that are greater than its mean: [3.2, 3.3, 3.6]" }, { "code": null, "e": 3817, "s": 3695, "text": "In another case, I want to find the intersection for nested lists with filter method. See what I have in two lists below:" }, { "code": null, "e": 3908, "s": 3817, "text": "group1 = [1, 2,3,43,23,42,8,3,7]group2 = [[3, 34, 23, 32, 42], [6, 11, 9], [1, 3,9,7,2,8]]" }, { "code": null, "e": 4023, "s": 3908, "text": "Now, by applying the following code, I can find out a list in which values in group 2 are also present in group 1:" }, { "code": null, "e": 4092, "s": 4023, "text": "[list(filter(lambda x: x in group1, sublist)) for sublist in group2]" }, { "code": null, "e": 4135, "s": 4092, "text": "Output: [[3, 23, 42], [], [1, 3, 7, 2, 8]]" }, { "code": null, "e": 4309, "s": 4135, "text": "To shortly explain, the filter method examines each sub-list’s item to determine if it is included in group 1. The list comprehension is applied to each sub-list in group 2." } ]
DAX Text - FIXED function
Rounds a number and returns the result as text. You can specify the number of digits to the right of the decimal points. You can also specify whether the result be returned with or without commas. FIXED (<number>, [<decimals>, [<no_commas>]]) number The number you want to round and convert to text, or A column containing a number. decimals Optional. The number of digits to the right of the decimal point. If omitted, 2. no_commas Optional. Can be specified only if decimals are specified. Otherwise, should be omitted. True () or 1: Does not display the commas in the returned text. False () or 0 or omitted: Displays the commas in the returned text. A number represented as text. If no_commas is FALSE or 0 or is omitted, then the returned text includes commas. You have two options to format a column containing numbers − By using a formatting command from the Ribbon. Using the DAX FIXED function. The difference between the two options is that the FIXED function converts its result to text, whereas with the formatting command the result is still a number. Numbers can never have more than 15 significant digits, but decimals can be as large as 127. = FIXED ([Sales Amount],2) 53 Lectures 5.5 hours Abhay Gadiya 24 Lectures 2 hours Randy Minder 26 Lectures 4.5 hours Randy Minder Print Add Notes Bookmark this page
[ { "code": null, "e": 2198, "s": 2001, "text": "Rounds a number and returns the result as text. You can specify the number of digits to the right of the decimal points. You can also specify whether the result be returned with or without commas." }, { "code": null, "e": 2246, "s": 2198, "text": "FIXED (<number>, [<decimals>, [<no_commas>]]) \n" }, { "code": null, "e": 2253, "s": 2246, "text": "number" }, { "code": null, "e": 2306, "s": 2253, "text": "The number you want to round and convert to text, or" }, { "code": null, "e": 2336, "s": 2306, "text": "A column containing a number." }, { "code": null, "e": 2345, "s": 2336, "text": "decimals" }, { "code": null, "e": 2355, "s": 2345, "text": "Optional." }, { "code": null, "e": 2411, "s": 2355, "text": "The number of digits to the right of the decimal point." }, { "code": null, "e": 2426, "s": 2411, "text": "If omitted, 2." }, { "code": null, "e": 2436, "s": 2426, "text": "no_commas" }, { "code": null, "e": 2446, "s": 2436, "text": "Optional." }, { "code": null, "e": 2525, "s": 2446, "text": "Can be specified only if decimals are specified. Otherwise, should be omitted." }, { "code": null, "e": 2589, "s": 2525, "text": "True () or 1: Does not display the commas in the returned text." }, { "code": null, "e": 2657, "s": 2589, "text": "False () or 0 or omitted: Displays the commas in the returned text." }, { "code": null, "e": 2687, "s": 2657, "text": "A number represented as text." }, { "code": null, "e": 2769, "s": 2687, "text": "If no_commas is FALSE or 0 or is omitted, then the returned text includes commas." }, { "code": null, "e": 2830, "s": 2769, "text": "You have two options to format a column containing numbers −" }, { "code": null, "e": 2877, "s": 2830, "text": "By using a formatting command from the Ribbon." }, { "code": null, "e": 2907, "s": 2877, "text": "Using the DAX FIXED function." }, { "code": null, "e": 3068, "s": 2907, "text": "The difference between the two options is that the FIXED function converts its result to text, whereas with the formatting command the result is still a number." }, { "code": null, "e": 3161, "s": 3068, "text": "Numbers can never have more than 15 significant digits, but decimals can be as large as 127." }, { "code": null, "e": 3189, "s": 3161, "text": "= FIXED ([Sales Amount],2) " }, { "code": null, "e": 3224, "s": 3189, "text": "\n 53 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3238, "s": 3224, "text": " Abhay Gadiya" }, { "code": null, "e": 3271, "s": 3238, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 3285, "s": 3271, "text": " Randy Minder" }, { "code": null, "e": 3320, "s": 3285, "text": "\n 26 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3334, "s": 3320, "text": " Randy Minder" }, { "code": null, "e": 3341, "s": 3334, "text": " Print" }, { "code": null, "e": 3352, "s": 3341, "text": " Add Notes" } ]
Find frequency of each element in a limited range array in less than O(n) time - GeeksforGeeks
15 Feb, 2022 Given a sorted array of positive integers, the count number of occurrences for each element in the array. Assume all elements in the array are less than some constant M.Do this without traversing the complete array. i.e. expected time complexity is less than O(n). Examples: Input: arr[] = [1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10] Output: Element 1 occurs 3 times Element 2 occurs 1 times Element 3 occurs 2 times Element 5 occurs 2 times Element 8 occurs 3 times Element 9 occurs 2 times Element 10 occurs 1 times Input: arr[] = [2, 2, 6, 6, 7, 7, 7, 11] Output: Element 2 occurs 2 times Element 6 occurs 2 times Element 7 occurs 3 times Element 11 occurs 1 times Method 1: This method uses the technique of Linear Search without using auxiliary space. Approach: The idea is to traverse the input array and increment the frequency of the element if the current element and the previous element are same, otherwise reset the frequency and print the element and its frequency. Algorithm: Initialise frequency to 1 and index to 1.Traverse the array from the index position and check if the current element is equal to previous element.If yes, increment the frequency and index and repeat the step 2. Otherwise, print the element and its frequency and repeat step 2.At last(corner case), print the last element and its frequency. Initialise frequency to 1 and index to 1. Traverse the array from the index position and check if the current element is equal to previous element. If yes, increment the frequency and index and repeat the step 2. Otherwise, print the element and its frequency and repeat step 2. At last(corner case), print the last element and its frequency. Implementation: C++ Java Python3 C# Javascript // C++ program to count number of occurrences of// each element in the array in O(n) time and O(1) space #include <iostream>using namespace std;void findFrequencies(int ele[], int n){ int freq = 1; int idx = 1; int element = ele[0]; while (idx < n) { // check if the current element is equal to // previous element. if (ele[idx - 1] == ele[idx]) { freq++; idx++; } else { cout << element << " " << freq << endl; element = ele[idx]; idx++; // reset the frequency freq = 1; } } // print the last element and its frequency cout << element << " " << freq;} int main(){ cout << "---frequencies in a sorted array----" << endl; int arr[] = { 10, 20, 30, 30, 30, 40, 50, 50, 50, 50, 70 }; int n = sizeof(arr) / sizeof(arr[0]); findFrequencies(arr, n);} // This code is contributed by anushkaseehh // Java program to count number of occurrences of// each element in the array in O(n) time and O(1) space function void findFrequencies(ele) { var freq = 1; var idx = 1; var element = ele[0]; while (idx < ele.length) { // check if the current element is equal to // previous element. if (ele[idx - 1] == ele[idx]) { freq++; idx++; } else { document.write(element + " " + freq+ "<br>"); element = ele[idx]; idx++; // reset the frequency freq = 1; } } // print the last element and its frequency document.write(element + " " + freq +"<br>"); } // Driver code document.write( "---frequencies in a sorted array----"+"<br>"); findFrequencies(new Array (10, 20, 30, 30, 30, 40, 50, 50, 50, 50, 70 )); //this code is contributed by shivanisinghss2110 # python program to count number of occurrences of# each element in the array in O(n) time and O(1) spacedef findFrequencies(ele, n): freq = 1 idx = 1 element = ele[0] while (idx < n): # check if the current element is equal to # previous element. if (ele[idx - 1] == ele[idx]): freq += 1 idx += 1 else: print(element , " " ,freq); element = ele[idx] idx += 1 # reset the frequency freq = 1 # print the last element and its frequency print(element , " " , freq); print( "---frequencies in a sorted array----" );arr = [10, 20, 30, 30, 30, 40, 50, 50, 50, 50, 70 ];n = len(arr)findFrequencies(arr, n) # This code is contributed by shivanisinghss2110 // C# program to count number of occurrences of// each element in the array in O(n) time and O(1) spaceusing System;class GFG { public static void findFrequencies(int[] ele) { int freq = 1; int idx = 1; int element = ele[0]; while (idx < ele.Length) { // check if the current element is equal to // previous element. if (ele[idx - 1] == ele[idx]) { freq++; idx++; } else { Console.WriteLine(element + " " + freq); element = ele[idx]; idx++; // reset the frequency freq = 1; } } // print the last element and its frequency Console.WriteLine(element + " " + freq); } // Driver code public static void Main(String[] args) { Console.WriteLine( "---frequencies in a sorted array----"); findFrequencies(new int[] { 10, 20, 30, 30, 30, 40, 50, 50, 50, 50, 70 }); }} <script>// JavaScript program to count number of occurrences of// each element in the array in O(n) time and O(1) space function void findFrequencies(ele) { var freq = 1; var idx = 1; var element = ele[0]; while (idx < ele.length) { // check if the current element is equal to // previous element. if (ele[idx - 1] == ele[idx]) { freq++; idx++; } else { document.write(element + " " + freq); element = ele[idx]; idx++; // reset the frequency freq = 1; } } // print the last element and its frequency document.write(element + " " + freq); } // Driver code document.write( "---frequencies in a sorted array----"); findFrequencies(new var[] { 10, 20, 30, 30, 30, 40, 50, 50, 50, 50, 70 }); // This code is contributed by shivanisinghss2110</script> ---frequencies in a sorted array---- 10 1 20 1 30 3 40 1 50 4 70 1 Method 2: This method uses the technique of Linear Search to solve the following. Approach: The idea is to traverse the input array and for each distinct element of the array, store its frequency in a HashMap, and finally print the HashMap. Algorithm: Create a HashMap to map the frequency to element, i.e to store element-frequency pair.Traverse the array from start to end.For each element in the array update the frequency, i.e hm[array[i]]++Traverse the HashMap and print the element frequency pair. Create a HashMap to map the frequency to element, i.e to store element-frequency pair.Traverse the array from start to end.For each element in the array update the frequency, i.e hm[array[i]]++Traverse the HashMap and print the element frequency pair. Create a HashMap to map the frequency to element, i.e to store element-frequency pair. Traverse the array from start to end. For each element in the array update the frequency, i.e hm[array[i]]++ Traverse the HashMap and print the element frequency pair. Implementation: C++ Java Python3 C# Javascript // C++ program to count number of occurrences of// each element in the array #include <iostream>#include <bits/stdc++.h>using namespace std; // It prints number of// occurrences of each element in the array.void findFrequency(int arr[], int n){ // HashMap to store frequencies unordered_map<int, int> mp; // traverse the array for (int i = 0; i < n; i++) { // update the frequency mp[arr[i]]++; } // traverse the hashmap for (auto i : mp) { cout << "Element " << i.first << " occurs " << i.second << " times" << endl; }} // Driver functionint main(){ int arr[] = { 1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10 }; int n = sizeof(arr) / sizeof(arr[0]); findFrequency(arr, n); return 0;} // Java program to count number// of occurrences of each// element in the arrayimport java.io.*;import java.util.*;class GFG{ // It prints number of // occurrences of each // element in the array. static void findFrequency(int [] arr, int n) { Map<Integer, Integer> mp = new HashMap<Integer, Integer>(); // traverse the array for (int i = 0; i < n; i++) { // update the frequency if (!mp.containsKey(arr[i])) mp.put(arr[i],0); mp.put(arr[i],mp.get(arr[i])+1); } // traverse the hashmap for (Map.Entry<Integer, Integer> kvp : mp.entrySet()) { System.out.println("Element " + kvp.getKey() + " occurs " + kvp.getValue() + " times"); } } // Driver function public static void main (String[] args) { int [] arr = {1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10}; int n = arr.length; findFrequency(arr, n); }} // This code is contributed by avanitrachhadiya2155 # Python program to count number of occurrences of# each element in the array #include <iostream> # It prints number of# occurrences of each element in the array.def findFrequency(arr, n): # HashMap to store frequencies mp = {} # traverse the array for i in range(n): # update the frequency if arr[i] not in mp: mp[arr[i]] = 0 mp[arr[i]] += 1 # traverse the hashmap for i in mp: print("Element", i, "occurs", mp[i], "times") # Driver functionarr = [1, 1, 1, 2, 3, 3, 5, 5,8, 8, 8, 9, 9, 10]n = len(arr) findFrequency(arr, n) # This code is contributed by shubhamsingh10 // C# program to count number// of occurrences of each// element in the arrayusing System;using System.Collections.Generic;class GFG{ // It prints number of// occurrences of each// element in the array.static void findFrequency(int [] arr, int n){ // HashMap to store frequencies Dictionary <int, int > mp = new Dictionary<int, int>(); // traverse the array for (int i = 0; i < n; i++) { // update the frequency if (!mp.ContainsKey(arr[i])) mp[arr[i]] = 0; mp[arr[i]]++; } // traverse the hashmap foreach(KeyValuePair<int, int> kvp in mp) Console.WriteLine("Element " + kvp.Key + " occurs " + kvp.Value + " times");} // Driver functionpublic static void Main(){ int [] arr = {1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10}; int n = arr.Length; findFrequency(arr, n);}} // This code is contributed by Chitranayal <script> // Javascript program to count number// of occurrences of each// element in the array // It prints number of// occurrences of each// element in the array.function findFrequency(arr, n){ let mp = new Map(); // Traverse the array for(let i = 0; i < n; i++) { // Update the frequency if (!mp.has(arr[i])) mp.set(arr[i],0); mp.set(arr[i], mp.get(arr[i]) + 1); } // Traverse the hashmap for(let [key, value] of mp.entries()) { document.write("Element " + key + " occurs " + value + " times<br>"); }} // Driver codelet arr = [ 1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10 ];let n = arr.length; findFrequency(arr, n); // This code is contributed by patel2127 </script> Element 10 occurs 1 times Element 2 occurs 1 times Element 9 occurs 2 times Element 1 occurs 3 times Element 8 occurs 3 times Element 3 occurs 2 times Element 5 occurs 2 times Complexity Analysis: Time Complexity:O(n), only one traversal of the array is needed. Space Complexity:O(n), to store the elements in the HashMap O(n) extra space is needed. Method 3: This method uses the technique of Binary Search to arrive at the solution. Approach: The problem can be solved in less than O(n) time if all its elements are sorted, i.e. if similar elements exist in the array then the elements are in a contiguous subarray or it can be said that if ends of a subarray are same then all the elements inside the subarray are equal. So the count of that element is the size of the subarray and all the elements of that subarray need not be counted. Algorithm: Create a HashMap (hm) to store the frequency of elements.Create a recursive function that accepts an array and size.Check if the first element of the array is equal to the last element. If equal then all the elements are the same and update the frequency by hm[array[0]+=sizeElse divide the array into two equal halves and call the function recursively for both the halves.Traverse the hashmap and print the element frequency pair. Create a HashMap (hm) to store the frequency of elements.Create a recursive function that accepts an array and size.Check if the first element of the array is equal to the last element. If equal then all the elements are the same and update the frequency by hm[array[0]+=sizeElse divide the array into two equal halves and call the function recursively for both the halves.Traverse the hashmap and print the element frequency pair. Create a HashMap (hm) to store the frequency of elements. Create a recursive function that accepts an array and size. Check if the first element of the array is equal to the last element. If equal then all the elements are the same and update the frequency by hm[array[0]+=size Else divide the array into two equal halves and call the function recursively for both the halves. Traverse the hashmap and print the element frequency pair. Implementation: C++ Java Python3 C# Javascript // C++ program to count number of occurrences of// each element in the array in less than O(n) time#include <iostream>#include <vector>using namespace std; // A recursive function to count number of occurrences// for each element in the array without traversing// the whole arrayvoid findFrequencyUtil(int arr[], int low, int high, vector<int>& freq){ // If element at index low is equal to element // at index high in the array if (arr[low] == arr[high]) { // increment the frequency of the element // by count of elements between high and low freq[arr[low]] += high - low + 1; } else { // Find mid and recurse for left and right // subarray int mid = (low + high) / 2; findFrequencyUtil(arr, low, mid, freq); findFrequencyUtil(arr, mid + 1, high, freq); }} // A wrapper over recursive function// findFrequencyUtil(). It print number of// occurrences of each element in the array.void findFrequency(int arr[], int n){ // create a empty vector to store frequencies // and initialize it by 0. Size of vector is // maximum value (which is last value in sorted // array) plus 1. vector<int> freq(arr[n - 1] + 1, 0); // Fill the vector with frequency findFrequencyUtil(arr, 0, n - 1, freq); // Print the frequencies for (int i = 0; i <= arr[n - 1]; i++) if (freq[i] != 0) cout << "Element " << i << " occurs " << freq[i] << " times" << endl;} // Driver functionint main(){ int arr[] = { 1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10 }; int n = sizeof(arr) / sizeof(arr[0]); findFrequency(arr, n); return 0;} // Java program to count number of occurrences of// each element in the array in less than O(n) timeimport java.util.*; class GFG { // A recursive function to count number of occurrences // for each element in the array without traversing // the whole array static void findFrequencyUtil(int arr[], int low, int high, int[] freq) { // If element at index low is equal to element // at index high in the array if (arr[low] == arr[high]) { // increment the frequency of the element // by count of elements between high and low freq[arr[low]] += high - low + 1; } else { // Find mid and recurse for left and right // subarray int mid = (low + high) / 2; findFrequencyUtil(arr, low, mid, freq); findFrequencyUtil(arr, mid + 1, high, freq); } } // A wrapper over recursive function // findFrequencyUtil(). It print number of // occurrences of each element in the array. static void findFrequency(int arr[], int n) { // create a empty vector to store frequencies // and initialize it by 0. Size of vector is // maximum value (which is last value in sorted // array) plus 1. int[] freq = new int[arr[n - 1] + 1]; // Fill the vector with frequency findFrequencyUtil(arr, 0, n - 1, freq); // Print the frequencies for (int i = 0; i <= arr[n - 1]; i++) if (freq[i] != 0) System.out.println("Element " + i + " occurs " + freq[i] + " times"); } // Driver Code public static void main(String[] args) { int arr[] = { 1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10 }; int n = arr.length; findFrequency(arr, n); }} // This code is contributed by 29AjayKumar # Python 3 program to count number of occurrences of# each element in the array in less than O(n) time # A recursive function to count number of occurrences# for each element in the array without traversing# the whole arraydef findFrequencyUtil(arr, low, high, freq): # If element at index low is equal to element # at index high in the array if (arr[low] == arr[high]): # increment the frequency of the element # by count of elements between high and low freq[arr[low]] += high - low + 1 else: # Find mid and recurse for left # and right subarray mid = int((low + high) / 2) findFrequencyUtil(arr, low, mid, freq) findFrequencyUtil(arr, mid + 1, high, freq) # A wrapper over recursive function# findFrequencyUtil(). It print number of# occurrences of each element in the array.def findFrequency(arr, n): # create a empty vector to store frequencies # and initialize it by 0. Size of vector is # maximum value (which is last value in sorted # array) plus 1. freq = [0 for i in range(n - 1 + 1)] # Fill the vector with frequency findFrequencyUtil(arr, 0, n - 1, freq) # Print the frequencies for i in range(0, arr[n - 1] + 1, 1): if (freq[i] != 0): print("Element", i, "occurs", freq[i], "times") # Driver Codeif __name__ == '__main__': arr = [1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10] n = len(arr) findFrequency(arr, n) # This code is contributed by# Surendra_Gangwar // C# program to count number of occurrences of// each element in the array in less than O(n) timeusing System; class GFG { // A recursive function to count number of occurrences // for each element in the array without traversing // the whole array static void findFrequencyUtil(int[] arr, int low, int high, int[] freq) { // If element at index low is equal to element // at index high in the array if (arr[low] == arr[high]) { // increment the frequency of the element // by count of elements between high and low freq[arr[low]] += high - low + 1; } else { // Find mid and recurse for left and right // subarray int mid = (low + high) / 2; findFrequencyUtil(arr, low, mid, freq); findFrequencyUtil(arr, mid + 1, high, freq); } } // A wrapper over recursive function // findFrequencyUtil(). It print number of // occurrences of each element in the array. static void findFrequency(int[] arr, int n) { // create a empty vector to store frequencies // and initialize it by 0. Size of vector is // maximum value (which is last value in sorted // array) plus 1. int[] freq = new int[arr[n - 1] + 1]; // Fill the vector with frequency findFrequencyUtil(arr, 0, n - 1, freq); // Print the frequencies for (int i = 0; i <= arr[n - 1]; i++) if (freq[i] != 0) Console.WriteLine("Element " + i + " occurs " + freq[i] + " times"); } // Driver Code public static void Main(String[] args) { int[] arr = { 1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10 }; int n = arr.Length; findFrequency(arr, n); }} // This code is contributed by Princi Singh <script>// Javascript program to count number of occurrences of// each element in the array in less than O(n) time // A recursive function to count number of occurrences // for each element in the array without traversing // the whole array function findFrequencyUtil(arr, low, high, freq) { // If element at index low is equal to element // at index high in the array if (arr[low] == arr[high]) { // increment the frequency of the element // by count of elements between high and low freq[arr[low]] += high - low + 1; } else { // Find mid and recurse for left and right // subarray let mid = Math.floor((low + high) / 2); findFrequencyUtil(arr, low, mid, freq); findFrequencyUtil(arr, mid + 1, high, freq); } } // A wrapper over recursive function // findFrequencyUtil(). It print number of // occurrences of each element in the array. function findFrequency(arr, n) { // create a empty vector to store frequencies // and initialize it by 0. Size of vector is // maximum value (which is last value in sorted // array) plus 1. let freq = new Array(arr[n - 1] + 1); for(let i = 0; i < arr[n - 1] + 1; i++) { freq[i] = 0; } // Fill the vector with frequency findFrequencyUtil(arr, 0, n - 1, freq); // Print the frequencies for (let i = 0; i <= arr[n - 1]; i++) if (freq[i] != 0) document.write("Element " + i + " occurs " + freq[i] + " times<br>"); } // Driver Code let arr = [1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10 ]; let n = arr.length; findFrequency(arr, n); // This code is contributed by rag2127.</script> Element 1 occurs 3 times Element 2 occurs 1 times Element 3 occurs 2 times Element 5 occurs 2 times Element 8 occurs 3 times Element 9 occurs 2 times Element 10 occurs 1 times Complexity Analysis: Time Complexity: O(m log n). Where m is the number of distinct elements in the array of size n. Since m <= M (a constant) (elements are in a limited range), the time complexity of this solution is O(log n). Space Complexity:O(n). To store the elements in the HashMap O(n) extra space is needed. Method 4 In this method we use the same array as the hash map by modifying it’s content. Let’s dry run a example. arr = { 1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10 }; Step 1 :- Subtract 1 from each element of the array arr = {0 ,0 ,0 ,1 ,2 ,2 ,4 ,4 ,7 ,7 ,7 ,8 ,8 ,9 } Step 2 :- Add n to the index at which the current array element points. for example :- when i=0, arr[arr[0]%n] = 0 adding n to the arr[0], arr[0] = 14; when i=1, arr[arr[1]%n] = 14 adding n to arr[0] ,arr[0] = 28; Similarly finding the modified array in the same way we will get array as arr = {42 ,14 ,28 ,1 ,30, 2, 4, 46, 35, 21, 7, 8, 8, 9} Step 3 :- Now in step 2 if you have noticed we added the n value to the index at which a particular element points to. So if we have more than one time have a element that point to the same index then in that case the division of the modified number with the n gives us the the frequency of the number. for example at i=0; arr[0] =42; arr[0] / n = 3 it means that 0 appeared three times in the modified array as you can see in the arr of step 1. at i=1; arr[1] =14; arr[1]/14 = 1 it means that 1 appeared once in the modified array as you can see in the arr of step 1 . and similarly for other values we can calculate. C++ Java C# Javascript // C++ program to count number of occurrences of// each element in the array #include <iostream>#include <bits/stdc++.h>using namespace std; // It prints number of occurrences of each element in the// array.void findFrequency(int input[], int n){ for (int i = 0; i < n; i++) input[i]--; for (int i = 0; i < n; i++) input[input[i] % n] += n; for (int i = 0; i < n; i++) { if (input[i] / n) cout << "Element " << (i + 1) << " occurs " << input[i] / n << " times" << endl; // Change the element back to original value input[i] = input[i] % n + 1; }} // Driver functionint main(){ int arr[] = { 1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10 }; int n = sizeof(arr) / sizeof(arr[0]); findFrequency(arr, n); return 0;} // This code is contributed by aditya kumar(adiyakumar129) // Java program to count number of occurrences of each// element in the arrayimport java.io.*;import java.util.*;class GFG { // It prints number of occurrences of each element in // the array. static void findFrequency(int[] input, int n) { for (int i = 0; i < n; i++) input[i]--; for (int i = 0; i < n; i++) input[input[i] % n] += n; for (int i = 0; i < n; i++) { if ((input[i] / n) != 0) System.out.println( "Element " + (i + 1) + " occurs " + input[i] / n + " times"); // Change the element back to original value input[i] = input[i] % n + 1; } } // Driver function public static void main(String[] args) { int[] arr = { 1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10 }; int n = arr.length; findFrequency(arr, n); }} // This code is contributed by aditya kumar(adiyakumar129) // C# program to count number of occurrences of each element// in the arrayusing System; public class GFG { // It prints number of occurrences of each element in // the array. static void findFrequency(int[] input, int n) { for (int i = 0; i < n; i++) input[i]--; for (int i = 0; i < n; i++) input[input[i] % n] += n; for (int i = 0; i < n; i++) { if ((input[i] / n) != 0) Console.WriteLine( "Element " + (i + 1) + " occurs " + input[i] / n + " times"); // Change the element back to original value input[i] = input[i] % n + 1; } } // Driver function public static void Main(String[] args) { int[] arr = { 1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10 }; int n = arr.Length; findFrequency(arr, n); }} // This code is contributed by shikhasingrajput <script>// Javascript program to count number of occurrences of// each element in the array // It prints number of// occurrences of each element in the array.function findFrequency(input, n){ for (let i = 0; i < n; i++) input[i]--; for (let i = 0; i < n; i++) input[input[i] % n] += n; console.log(input) for (let i = 0; i < n; i++) { if (Math.floor(input[i] / n)) document.write("Element " + (i + 1) + " occurs " + Math.floor(input[i] / n) + " times <br>"); // Change the element back to original value input[i] = input[i] % n + 1; }} // Driver functionlet arr = [1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10];let n = arr.length; findFrequency(arr, n); // This code is contributed by Saurabh Jaiswal</script> Element 1 occurs 3 times Element 2 occurs 1 times Element 3 occurs 2 times Element 5 occurs 2 times Element 8 occurs 3 times Element 9 occurs 2 times Element 10 occurs 1 times https://youtu.be/B2hI-QPoisk This article is contributed by Aditya Goel. 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. SURENDRA_GANGWAR 29AjayKumar princi singh andrew1234 SHUBHAMSINGH10 ukasp avanitrachhadiya2155 rag2127 patel2127 satyaramanaidu anushikasethh shivanisinghss2110 adityakumar129 shikhasingrajput _saurabh_jaiswal Arrays Divide and Conquer Arrays Divide and Conquer Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java Linear Search Merge Sort QuickSort Binary Search Maximum and minimum of an array using minimum number of comparisons Program for Tower of Hanoi
[ { "code": null, "e": 25338, "s": 25310, "text": "\n15 Feb, 2022" }, { "code": null, "e": 25604, "s": 25338, "text": "Given a sorted array of positive integers, the count number of occurrences for each element in the array. Assume all elements in the array are less than some constant M.Do this without traversing the complete array. i.e. expected time complexity is less than O(n). " }, { "code": null, "e": 25615, "s": 25604, "text": "Examples: " }, { "code": null, "e": 26026, "s": 25615, "text": "Input: arr[] = [1, 1, 1, 2, 3, 3, 5,\n 5, 8, 8, 8, 9, 9, 10] \nOutput:\nElement 1 occurs 3 times\nElement 2 occurs 1 times\nElement 3 occurs 2 times\nElement 5 occurs 2 times\nElement 8 occurs 3 times\nElement 9 occurs 2 times\nElement 10 occurs 1 times\n\nInput: arr[] = [2, 2, 6, 6, 7, 7, 7, 11] \nOutput:\nElement 2 occurs 2 times\nElement 6 occurs 2 times\nElement 7 occurs 3 times\nElement 11 occurs 1 times" }, { "code": null, "e": 26115, "s": 26026, "text": "Method 1: This method uses the technique of Linear Search without using auxiliary space." }, { "code": null, "e": 26338, "s": 26115, "text": "Approach: The idea is to traverse the input array and increment the frequency of the element if the current element and the previous element are same, otherwise reset the frequency and print the element and its frequency." }, { "code": null, "e": 26690, "s": 26338, "text": "Algorithm: Initialise frequency to 1 and index to 1.Traverse the array from the index position and check if the current element is equal to previous element.If yes, increment the frequency and index and repeat the step 2. Otherwise, print the element and its frequency and repeat step 2.At last(corner case), print the last element and its frequency." }, { "code": null, "e": 26732, "s": 26690, "text": "Initialise frequency to 1 and index to 1." }, { "code": null, "e": 26839, "s": 26732, "text": "Traverse the array from the index position and check if the current element is equal to previous element." }, { "code": null, "e": 26970, "s": 26839, "text": "If yes, increment the frequency and index and repeat the step 2. Otherwise, print the element and its frequency and repeat step 2." }, { "code": null, "e": 27034, "s": 26970, "text": "At last(corner case), print the last element and its frequency." }, { "code": null, "e": 27050, "s": 27034, "text": "Implementation:" }, { "code": null, "e": 27054, "s": 27050, "text": "C++" }, { "code": null, "e": 27059, "s": 27054, "text": "Java" }, { "code": null, "e": 27067, "s": 27059, "text": "Python3" }, { "code": null, "e": 27070, "s": 27067, "text": "C#" }, { "code": null, "e": 27081, "s": 27070, "text": "Javascript" }, { "code": "// C++ program to count number of occurrences of// each element in the array in O(n) time and O(1) space #include <iostream>using namespace std;void findFrequencies(int ele[], int n){ int freq = 1; int idx = 1; int element = ele[0]; while (idx < n) { // check if the current element is equal to // previous element. if (ele[idx - 1] == ele[idx]) { freq++; idx++; } else { cout << element << \" \" << freq << endl; element = ele[idx]; idx++; // reset the frequency freq = 1; } } // print the last element and its frequency cout << element << \" \" << freq;} int main(){ cout << \"---frequencies in a sorted array----\" << endl; int arr[] = { 10, 20, 30, 30, 30, 40, 50, 50, 50, 50, 70 }; int n = sizeof(arr) / sizeof(arr[0]); findFrequencies(arr, n);} // This code is contributed by anushkaseehh", "e": 28043, "s": 27081, "text": null }, { "code": "// Java program to count number of occurrences of// each element in the array in O(n) time and O(1) space function void findFrequencies(ele) { var freq = 1; var idx = 1; var element = ele[0]; while (idx < ele.length) { // check if the current element is equal to // previous element. if (ele[idx - 1] == ele[idx]) { freq++; idx++; } else { document.write(element + \" \" + freq+ \"<br>\"); element = ele[idx]; idx++; // reset the frequency freq = 1; } } // print the last element and its frequency document.write(element + \" \" + freq +\"<br>\"); } // Driver code document.write( \"---frequencies in a sorted array----\"+\"<br>\"); findFrequencies(new Array (10, 20, 30, 30, 30, 40, 50, 50, 50, 50, 70 )); //this code is contributed by shivanisinghss2110", "e": 29090, "s": 28043, "text": null }, { "code": "# python program to count number of occurrences of# each element in the array in O(n) time and O(1) spacedef findFrequencies(ele, n): freq = 1 idx = 1 element = ele[0] while (idx < n): # check if the current element is equal to # previous element. if (ele[idx - 1] == ele[idx]): freq += 1 idx += 1 else: print(element , \" \" ,freq); element = ele[idx] idx += 1 # reset the frequency freq = 1 # print the last element and its frequency print(element , \" \" , freq); print( \"---frequencies in a sorted array----\" );arr = [10, 20, 30, 30, 30, 40, 50, 50, 50, 50, 70 ];n = len(arr)findFrequencies(arr, n) # This code is contributed by shivanisinghss2110", "e": 29898, "s": 29090, "text": null }, { "code": "// C# program to count number of occurrences of// each element in the array in O(n) time and O(1) spaceusing System;class GFG { public static void findFrequencies(int[] ele) { int freq = 1; int idx = 1; int element = ele[0]; while (idx < ele.Length) { // check if the current element is equal to // previous element. if (ele[idx - 1] == ele[idx]) { freq++; idx++; } else { Console.WriteLine(element + \" \" + freq); element = ele[idx]; idx++; // reset the frequency freq = 1; } } // print the last element and its frequency Console.WriteLine(element + \" \" + freq); } // Driver code public static void Main(String[] args) { Console.WriteLine( \"---frequencies in a sorted array----\"); findFrequencies(new int[] { 10, 20, 30, 30, 30, 40, 50, 50, 50, 50, 70 }); }}", "e": 31002, "s": 29898, "text": null }, { "code": "<script>// JavaScript program to count number of occurrences of// each element in the array in O(n) time and O(1) space function void findFrequencies(ele) { var freq = 1; var idx = 1; var element = ele[0]; while (idx < ele.length) { // check if the current element is equal to // previous element. if (ele[idx - 1] == ele[idx]) { freq++; idx++; } else { document.write(element + \" \" + freq); element = ele[idx]; idx++; // reset the frequency freq = 1; } } // print the last element and its frequency document.write(element + \" \" + freq); } // Driver code document.write( \"---frequencies in a sorted array----\"); findFrequencies(new var[] { 10, 20, 30, 30, 30, 40, 50, 50, 50, 50, 70 }); // This code is contributed by shivanisinghss2110</script>", "e": 32102, "s": 31002, "text": null }, { "code": null, "e": 32169, "s": 32102, "text": "---frequencies in a sorted array----\n10 1\n20 1\n30 3\n40 1\n50 4\n70 1" }, { "code": null, "e": 32255, "s": 32172, "text": "Method 2: This method uses the technique of Linear Search to solve the following. " }, { "code": null, "e": 32414, "s": 32255, "text": "Approach: The idea is to traverse the input array and for each distinct element of the array, store its frequency in a HashMap, and finally print the HashMap." }, { "code": null, "e": 32677, "s": 32414, "text": "Algorithm: Create a HashMap to map the frequency to element, i.e to store element-frequency pair.Traverse the array from start to end.For each element in the array update the frequency, i.e hm[array[i]]++Traverse the HashMap and print the element frequency pair." }, { "code": null, "e": 32929, "s": 32677, "text": "Create a HashMap to map the frequency to element, i.e to store element-frequency pair.Traverse the array from start to end.For each element in the array update the frequency, i.e hm[array[i]]++Traverse the HashMap and print the element frequency pair." }, { "code": null, "e": 33016, "s": 32929, "text": "Create a HashMap to map the frequency to element, i.e to store element-frequency pair." }, { "code": null, "e": 33054, "s": 33016, "text": "Traverse the array from start to end." }, { "code": null, "e": 33125, "s": 33054, "text": "For each element in the array update the frequency, i.e hm[array[i]]++" }, { "code": null, "e": 33184, "s": 33125, "text": "Traverse the HashMap and print the element frequency pair." }, { "code": null, "e": 33200, "s": 33184, "text": "Implementation:" }, { "code": null, "e": 33204, "s": 33200, "text": "C++" }, { "code": null, "e": 33209, "s": 33204, "text": "Java" }, { "code": null, "e": 33217, "s": 33209, "text": "Python3" }, { "code": null, "e": 33220, "s": 33217, "text": "C#" }, { "code": null, "e": 33231, "s": 33220, "text": "Javascript" }, { "code": "// C++ program to count number of occurrences of// each element in the array #include <iostream>#include <bits/stdc++.h>using namespace std; // It prints number of// occurrences of each element in the array.void findFrequency(int arr[], int n){ // HashMap to store frequencies unordered_map<int, int> mp; // traverse the array for (int i = 0; i < n; i++) { // update the frequency mp[arr[i]]++; } // traverse the hashmap for (auto i : mp) { cout << \"Element \" << i.first << \" occurs \" << i.second << \" times\" << endl; }} // Driver functionint main(){ int arr[] = { 1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10 }; int n = sizeof(arr) / sizeof(arr[0]); findFrequency(arr, n); return 0;}", "e": 34003, "s": 33231, "text": null }, { "code": "// Java program to count number// of occurrences of each// element in the arrayimport java.io.*;import java.util.*;class GFG{ // It prints number of // occurrences of each // element in the array. static void findFrequency(int [] arr, int n) { Map<Integer, Integer> mp = new HashMap<Integer, Integer>(); // traverse the array for (int i = 0; i < n; i++) { // update the frequency if (!mp.containsKey(arr[i])) mp.put(arr[i],0); mp.put(arr[i],mp.get(arr[i])+1); } // traverse the hashmap for (Map.Entry<Integer, Integer> kvp : mp.entrySet()) { System.out.println(\"Element \" + kvp.getKey() + \" occurs \" + kvp.getValue() + \" times\"); } } // Driver function public static void main (String[] args) { int [] arr = {1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10}; int n = arr.length; findFrequency(arr, n); }} // This code is contributed by avanitrachhadiya2155", "e": 35065, "s": 34003, "text": null }, { "code": "# Python program to count number of occurrences of# each element in the array #include <iostream> # It prints number of# occurrences of each element in the array.def findFrequency(arr, n): # HashMap to store frequencies mp = {} # traverse the array for i in range(n): # update the frequency if arr[i] not in mp: mp[arr[i]] = 0 mp[arr[i]] += 1 # traverse the hashmap for i in mp: print(\"Element\", i, \"occurs\", mp[i], \"times\") # Driver functionarr = [1, 1, 1, 2, 3, 3, 5, 5,8, 8, 8, 9, 9, 10]n = len(arr) findFrequency(arr, n) # This code is contributed by shubhamsingh10", "e": 35716, "s": 35065, "text": null }, { "code": "// C# program to count number// of occurrences of each// element in the arrayusing System;using System.Collections.Generic;class GFG{ // It prints number of// occurrences of each// element in the array.static void findFrequency(int [] arr, int n){ // HashMap to store frequencies Dictionary <int, int > mp = new Dictionary<int, int>(); // traverse the array for (int i = 0; i < n; i++) { // update the frequency if (!mp.ContainsKey(arr[i])) mp[arr[i]] = 0; mp[arr[i]]++; } // traverse the hashmap foreach(KeyValuePair<int, int> kvp in mp) Console.WriteLine(\"Element \" + kvp.Key + \" occurs \" + kvp.Value + \" times\");} // Driver functionpublic static void Main(){ int [] arr = {1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10}; int n = arr.Length; findFrequency(arr, n);}} // This code is contributed by Chitranayal", "e": 36743, "s": 35716, "text": null }, { "code": "<script> // Javascript program to count number// of occurrences of each// element in the array // It prints number of// occurrences of each// element in the array.function findFrequency(arr, n){ let mp = new Map(); // Traverse the array for(let i = 0; i < n; i++) { // Update the frequency if (!mp.has(arr[i])) mp.set(arr[i],0); mp.set(arr[i], mp.get(arr[i]) + 1); } // Traverse the hashmap for(let [key, value] of mp.entries()) { document.write(\"Element \" + key + \" occurs \" + value + \" times<br>\"); }} // Driver codelet arr = [ 1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10 ];let n = arr.length; findFrequency(arr, n); // This code is contributed by patel2127 </script>", "e": 37547, "s": 36743, "text": null }, { "code": null, "e": 37723, "s": 37547, "text": "Element 10 occurs 1 times\nElement 2 occurs 1 times\nElement 9 occurs 2 times\nElement 1 occurs 3 times\nElement 8 occurs 3 times\nElement 3 occurs 2 times\nElement 5 occurs 2 times" }, { "code": null, "e": 37745, "s": 37723, "text": "Complexity Analysis: " }, { "code": null, "e": 37810, "s": 37745, "text": "Time Complexity:O(n), only one traversal of the array is needed." }, { "code": null, "e": 37898, "s": 37810, "text": "Space Complexity:O(n), to store the elements in the HashMap O(n) extra space is needed." }, { "code": null, "e": 37985, "s": 37898, "text": "Method 3: This method uses the technique of Binary Search to arrive at the solution. " }, { "code": null, "e": 38392, "s": 37985, "text": "Approach: The problem can be solved in less than O(n) time if all its elements are sorted, i.e. if similar elements exist in the array then the elements are in a contiguous subarray or it can be said that if ends of a subarray are same then all the elements inside the subarray are equal. So the count of that element is the size of the subarray and all the elements of that subarray need not be counted. " }, { "code": null, "e": 38835, "s": 38392, "text": "Algorithm: Create a HashMap (hm) to store the frequency of elements.Create a recursive function that accepts an array and size.Check if the first element of the array is equal to the last element. If equal then all the elements are the same and update the frequency by hm[array[0]+=sizeElse divide the array into two equal halves and call the function recursively for both the halves.Traverse the hashmap and print the element frequency pair." }, { "code": null, "e": 39267, "s": 38835, "text": "Create a HashMap (hm) to store the frequency of elements.Create a recursive function that accepts an array and size.Check if the first element of the array is equal to the last element. If equal then all the elements are the same and update the frequency by hm[array[0]+=sizeElse divide the array into two equal halves and call the function recursively for both the halves.Traverse the hashmap and print the element frequency pair." }, { "code": null, "e": 39325, "s": 39267, "text": "Create a HashMap (hm) to store the frequency of elements." }, { "code": null, "e": 39385, "s": 39325, "text": "Create a recursive function that accepts an array and size." }, { "code": null, "e": 39545, "s": 39385, "text": "Check if the first element of the array is equal to the last element. If equal then all the elements are the same and update the frequency by hm[array[0]+=size" }, { "code": null, "e": 39644, "s": 39545, "text": "Else divide the array into two equal halves and call the function recursively for both the halves." }, { "code": null, "e": 39703, "s": 39644, "text": "Traverse the hashmap and print the element frequency pair." }, { "code": null, "e": 39721, "s": 39703, "text": "Implementation: " }, { "code": null, "e": 39725, "s": 39721, "text": "C++" }, { "code": null, "e": 39730, "s": 39725, "text": "Java" }, { "code": null, "e": 39738, "s": 39730, "text": "Python3" }, { "code": null, "e": 39741, "s": 39738, "text": "C#" }, { "code": null, "e": 39752, "s": 39741, "text": "Javascript" }, { "code": "// C++ program to count number of occurrences of// each element in the array in less than O(n) time#include <iostream>#include <vector>using namespace std; // A recursive function to count number of occurrences// for each element in the array without traversing// the whole arrayvoid findFrequencyUtil(int arr[], int low, int high, vector<int>& freq){ // If element at index low is equal to element // at index high in the array if (arr[low] == arr[high]) { // increment the frequency of the element // by count of elements between high and low freq[arr[low]] += high - low + 1; } else { // Find mid and recurse for left and right // subarray int mid = (low + high) / 2; findFrequencyUtil(arr, low, mid, freq); findFrequencyUtil(arr, mid + 1, high, freq); }} // A wrapper over recursive function// findFrequencyUtil(). It print number of// occurrences of each element in the array.void findFrequency(int arr[], int n){ // create a empty vector to store frequencies // and initialize it by 0. Size of vector is // maximum value (which is last value in sorted // array) plus 1. vector<int> freq(arr[n - 1] + 1, 0); // Fill the vector with frequency findFrequencyUtil(arr, 0, n - 1, freq); // Print the frequencies for (int i = 0; i <= arr[n - 1]; i++) if (freq[i] != 0) cout << \"Element \" << i << \" occurs \" << freq[i] << \" times\" << endl;} // Driver functionint main(){ int arr[] = { 1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10 }; int n = sizeof(arr) / sizeof(arr[0]); findFrequency(arr, n); return 0;}", "e": 41442, "s": 39752, "text": null }, { "code": "// Java program to count number of occurrences of// each element in the array in less than O(n) timeimport java.util.*; class GFG { // A recursive function to count number of occurrences // for each element in the array without traversing // the whole array static void findFrequencyUtil(int arr[], int low, int high, int[] freq) { // If element at index low is equal to element // at index high in the array if (arr[low] == arr[high]) { // increment the frequency of the element // by count of elements between high and low freq[arr[low]] += high - low + 1; } else { // Find mid and recurse for left and right // subarray int mid = (low + high) / 2; findFrequencyUtil(arr, low, mid, freq); findFrequencyUtil(arr, mid + 1, high, freq); } } // A wrapper over recursive function // findFrequencyUtil(). It print number of // occurrences of each element in the array. static void findFrequency(int arr[], int n) { // create a empty vector to store frequencies // and initialize it by 0. Size of vector is // maximum value (which is last value in sorted // array) plus 1. int[] freq = new int[arr[n - 1] + 1]; // Fill the vector with frequency findFrequencyUtil(arr, 0, n - 1, freq); // Print the frequencies for (int i = 0; i <= arr[n - 1]; i++) if (freq[i] != 0) System.out.println(\"Element \" + i + \" occurs \" + freq[i] + \" times\"); } // Driver Code public static void main(String[] args) { int arr[] = { 1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10 }; int n = arr.length; findFrequency(arr, n); }} // This code is contributed by 29AjayKumar", "e": 43327, "s": 41442, "text": null }, { "code": "# Python 3 program to count number of occurrences of# each element in the array in less than O(n) time # A recursive function to count number of occurrences# for each element in the array without traversing# the whole arraydef findFrequencyUtil(arr, low, high, freq): # If element at index low is equal to element # at index high in the array if (arr[low] == arr[high]): # increment the frequency of the element # by count of elements between high and low freq[arr[low]] += high - low + 1 else: # Find mid and recurse for left # and right subarray mid = int((low + high) / 2) findFrequencyUtil(arr, low, mid, freq) findFrequencyUtil(arr, mid + 1, high, freq) # A wrapper over recursive function# findFrequencyUtil(). It print number of# occurrences of each element in the array.def findFrequency(arr, n): # create a empty vector to store frequencies # and initialize it by 0. Size of vector is # maximum value (which is last value in sorted # array) plus 1. freq = [0 for i in range(n - 1 + 1)] # Fill the vector with frequency findFrequencyUtil(arr, 0, n - 1, freq) # Print the frequencies for i in range(0, arr[n - 1] + 1, 1): if (freq[i] != 0): print(\"Element\", i, \"occurs\", freq[i], \"times\") # Driver Codeif __name__ == '__main__': arr = [1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10] n = len(arr) findFrequency(arr, n) # This code is contributed by# Surendra_Gangwar", "e": 44899, "s": 43327, "text": null }, { "code": "// C# program to count number of occurrences of// each element in the array in less than O(n) timeusing System; class GFG { // A recursive function to count number of occurrences // for each element in the array without traversing // the whole array static void findFrequencyUtil(int[] arr, int low, int high, int[] freq) { // If element at index low is equal to element // at index high in the array if (arr[low] == arr[high]) { // increment the frequency of the element // by count of elements between high and low freq[arr[low]] += high - low + 1; } else { // Find mid and recurse for left and right // subarray int mid = (low + high) / 2; findFrequencyUtil(arr, low, mid, freq); findFrequencyUtil(arr, mid + 1, high, freq); } } // A wrapper over recursive function // findFrequencyUtil(). It print number of // occurrences of each element in the array. static void findFrequency(int[] arr, int n) { // create a empty vector to store frequencies // and initialize it by 0. Size of vector is // maximum value (which is last value in sorted // array) plus 1. int[] freq = new int[arr[n - 1] + 1]; // Fill the vector with frequency findFrequencyUtil(arr, 0, n - 1, freq); // Print the frequencies for (int i = 0; i <= arr[n - 1]; i++) if (freq[i] != 0) Console.WriteLine(\"Element \" + i + \" occurs \" + freq[i] + \" times\"); } // Driver Code public static void Main(String[] args) { int[] arr = { 1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10 }; int n = arr.Length; findFrequency(arr, n); }} // This code is contributed by Princi Singh", "e": 46776, "s": 44899, "text": null }, { "code": "<script>// Javascript program to count number of occurrences of// each element in the array in less than O(n) time // A recursive function to count number of occurrences // for each element in the array without traversing // the whole array function findFrequencyUtil(arr, low, high, freq) { // If element at index low is equal to element // at index high in the array if (arr[low] == arr[high]) { // increment the frequency of the element // by count of elements between high and low freq[arr[low]] += high - low + 1; } else { // Find mid and recurse for left and right // subarray let mid = Math.floor((low + high) / 2); findFrequencyUtil(arr, low, mid, freq); findFrequencyUtil(arr, mid + 1, high, freq); } } // A wrapper over recursive function // findFrequencyUtil(). It print number of // occurrences of each element in the array. function findFrequency(arr, n) { // create a empty vector to store frequencies // and initialize it by 0. Size of vector is // maximum value (which is last value in sorted // array) plus 1. let freq = new Array(arr[n - 1] + 1); for(let i = 0; i < arr[n - 1] + 1; i++) { freq[i] = 0; } // Fill the vector with frequency findFrequencyUtil(arr, 0, n - 1, freq); // Print the frequencies for (let i = 0; i <= arr[n - 1]; i++) if (freq[i] != 0) document.write(\"Element \" + i + \" occurs \" + freq[i] + \" times<br>\"); } // Driver Code let arr = [1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10 ]; let n = arr.length; findFrequency(arr, n); // This code is contributed by rag2127.</script>", "e": 48693, "s": 46776, "text": null }, { "code": null, "e": 48869, "s": 48693, "text": "Element 1 occurs 3 times\nElement 2 occurs 1 times\nElement 3 occurs 2 times\nElement 5 occurs 2 times\nElement 8 occurs 3 times\nElement 9 occurs 2 times\nElement 10 occurs 1 times" }, { "code": null, "e": 48891, "s": 48869, "text": "Complexity Analysis: " }, { "code": null, "e": 49098, "s": 48891, "text": "Time Complexity: O(m log n). Where m is the number of distinct elements in the array of size n. Since m <= M (a constant) (elements are in a limited range), the time complexity of this solution is O(log n)." }, { "code": null, "e": 49186, "s": 49098, "text": "Space Complexity:O(n). To store the elements in the HashMap O(n) extra space is needed." }, { "code": null, "e": 49196, "s": 49186, "text": "Method 4 " }, { "code": null, "e": 49277, "s": 49196, "text": "In this method we use the same array as the hash map by modifying it’s content." }, { "code": null, "e": 49303, "s": 49277, "text": "Let’s dry run a example. " }, { "code": null, "e": 49356, "s": 49303, "text": "arr = { 1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10 };" }, { "code": null, "e": 49408, "s": 49356, "text": "Step 1 :- Subtract 1 from each element of the array" }, { "code": null, "e": 49459, "s": 49408, "text": "arr = {0 ,0 ,0 ,1 ,2 ,2 ,4 ,4 ,7 ,7 ,7 ,8 ,8 ,9 }" }, { "code": null, "e": 49531, "s": 49459, "text": "Step 2 :- Add n to the index at which the current array element points." }, { "code": null, "e": 49547, "s": 49531, "text": "for example :- " }, { "code": null, "e": 49613, "s": 49547, "text": "when i=0, arr[arr[0]%n] = 0 adding n to the arr[0], arr[0] = 14;" }, { "code": null, "e": 49675, "s": 49613, "text": "when i=1, arr[arr[1]%n] = 14 adding n to arr[0] ,arr[0] = 28;" }, { "code": null, "e": 49751, "s": 49675, "text": "Similarly finding the modified array in the same way we will get array as " }, { "code": null, "e": 49807, "s": 49751, "text": "arr = {42 ,14 ,28 ,1 ,30, 2, 4, 46, 35, 21, 7, 8, 8, 9}" }, { "code": null, "e": 50111, "s": 49807, "text": "Step 3 :- Now in step 2 if you have noticed we added the n value to the index at which a particular element points to. So if we have more than one time have a element that point to the same index then in that case the division of the modified number with the n gives us the the frequency of the number. " }, { "code": null, "e": 50124, "s": 50111, "text": "for example " }, { "code": null, "e": 50256, "s": 50124, "text": "at i=0; arr[0] =42; arr[0] / n = 3 it means that 0 appeared three times in the modified array as you can see in the arr of step 1." }, { "code": null, "e": 50380, "s": 50256, "text": "at i=1; arr[1] =14; arr[1]/14 = 1 it means that 1 appeared once in the modified array as you can see in the arr of step 1 ." }, { "code": null, "e": 50429, "s": 50380, "text": "and similarly for other values we can calculate." }, { "code": null, "e": 50433, "s": 50429, "text": "C++" }, { "code": null, "e": 50438, "s": 50433, "text": "Java" }, { "code": null, "e": 50441, "s": 50438, "text": "C#" }, { "code": null, "e": 50452, "s": 50441, "text": "Javascript" }, { "code": "// C++ program to count number of occurrences of// each element in the array #include <iostream>#include <bits/stdc++.h>using namespace std; // It prints number of occurrences of each element in the// array.void findFrequency(int input[], int n){ for (int i = 0; i < n; i++) input[i]--; for (int i = 0; i < n; i++) input[input[i] % n] += n; for (int i = 0; i < n; i++) { if (input[i] / n) cout << \"Element \" << (i + 1) << \" occurs \" << input[i] / n << \" times\" << endl; // Change the element back to original value input[i] = input[i] % n + 1; }} // Driver functionint main(){ int arr[] = { 1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10 }; int n = sizeof(arr) / sizeof(arr[0]); findFrequency(arr, n); return 0;} // This code is contributed by aditya kumar(adiyakumar129)", "e": 51316, "s": 50452, "text": null }, { "code": "// Java program to count number of occurrences of each// element in the arrayimport java.io.*;import java.util.*;class GFG { // It prints number of occurrences of each element in // the array. static void findFrequency(int[] input, int n) { for (int i = 0; i < n; i++) input[i]--; for (int i = 0; i < n; i++) input[input[i] % n] += n; for (int i = 0; i < n; i++) { if ((input[i] / n) != 0) System.out.println( \"Element \" + (i + 1) + \" occurs \" + input[i] / n + \" times\"); // Change the element back to original value input[i] = input[i] % n + 1; } } // Driver function public static void main(String[] args) { int[] arr = { 1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10 }; int n = arr.length; findFrequency(arr, n); }} // This code is contributed by aditya kumar(adiyakumar129)", "e": 52289, "s": 51316, "text": null }, { "code": "// C# program to count number of occurrences of each element// in the arrayusing System; public class GFG { // It prints number of occurrences of each element in // the array. static void findFrequency(int[] input, int n) { for (int i = 0; i < n; i++) input[i]--; for (int i = 0; i < n; i++) input[input[i] % n] += n; for (int i = 0; i < n; i++) { if ((input[i] / n) != 0) Console.WriteLine( \"Element \" + (i + 1) + \" occurs \" + input[i] / n + \" times\"); // Change the element back to original value input[i] = input[i] % n + 1; } } // Driver function public static void Main(String[] args) { int[] arr = { 1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10 }; int n = arr.Length; findFrequency(arr, n); }} // This code is contributed by shikhasingrajput", "e": 53233, "s": 52289, "text": null }, { "code": "<script>// Javascript program to count number of occurrences of// each element in the array // It prints number of// occurrences of each element in the array.function findFrequency(input, n){ for (let i = 0; i < n; i++) input[i]--; for (let i = 0; i < n; i++) input[input[i] % n] += n; console.log(input) for (let i = 0; i < n; i++) { if (Math.floor(input[i] / n)) document.write(\"Element \" + (i + 1) + \" occurs \" + Math.floor(input[i] / n) + \" times <br>\"); // Change the element back to original value input[i] = input[i] % n + 1; }} // Driver functionlet arr = [1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10];let n = arr.length; findFrequency(arr, n); // This code is contributed by Saurabh Jaiswal</script>", "e": 54027, "s": 53233, "text": null }, { "code": null, "e": 54204, "s": 54027, "text": "Element 1 occurs 3 times\nElement 2 occurs 1 times\nElement 3 occurs 2 times\nElement 5 occurs 2 times\nElement 8 occurs 3 times\nElement 9 occurs 2 times\nElement 10 occurs 1 times\n" }, { "code": null, "e": 54653, "s": 54204, "text": "https://youtu.be/B2hI-QPoisk This article is contributed by Aditya Goel. 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": 54670, "s": 54653, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 54682, "s": 54670, "text": "29AjayKumar" }, { "code": null, "e": 54695, "s": 54682, "text": "princi singh" }, { "code": null, "e": 54706, "s": 54695, "text": "andrew1234" }, { "code": null, "e": 54721, "s": 54706, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 54727, "s": 54721, "text": "ukasp" }, { "code": null, "e": 54748, "s": 54727, "text": "avanitrachhadiya2155" }, { "code": null, "e": 54756, "s": 54748, "text": "rag2127" }, { "code": null, "e": 54766, "s": 54756, "text": "patel2127" }, { "code": null, "e": 54781, "s": 54766, "text": "satyaramanaidu" }, { "code": null, "e": 54795, "s": 54781, "text": "anushikasethh" }, { "code": null, "e": 54814, "s": 54795, "text": "shivanisinghss2110" }, { "code": null, "e": 54829, "s": 54814, "text": "adityakumar129" }, { "code": null, "e": 54846, "s": 54829, "text": "shikhasingrajput" }, { "code": null, "e": 54863, "s": 54846, "text": "_saurabh_jaiswal" }, { "code": null, "e": 54870, "s": 54863, "text": "Arrays" }, { "code": null, "e": 54889, "s": 54870, "text": "Divide and Conquer" }, { "code": null, "e": 54896, "s": 54889, "text": "Arrays" }, { "code": null, "e": 54915, "s": 54896, "text": "Divide and Conquer" }, { "code": null, "e": 55013, "s": 54915, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 55022, "s": 55013, "text": "Comments" }, { "code": null, "e": 55035, "s": 55022, "text": "Old Comments" }, { "code": null, "e": 55083, "s": 55035, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 55127, "s": 55083, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 55150, "s": 55127, "text": "Introduction to Arrays" }, { "code": null, "e": 55182, "s": 55150, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 55196, "s": 55182, "text": "Linear Search" }, { "code": null, "e": 55207, "s": 55196, "text": "Merge Sort" }, { "code": null, "e": 55217, "s": 55207, "text": "QuickSort" }, { "code": null, "e": 55231, "s": 55217, "text": "Binary Search" }, { "code": null, "e": 55299, "s": 55231, "text": "Maximum and minimum of an array using minimum number of comparisons" } ]
How to detect end of ScrollView in Android?
This example demonstrates how do I detect end of scrollView 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"?> <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"> <ScrollView android:id="@+id/scrollView" android:layout_width="match_parent" android:layout_height="match_parent"> <WebView android:id="@+id/webView" android:layout_width="match_parent" android:layout_height="wrap_content"> </WebView> </ScrollView> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.view.ViewTreeObserver; import android.webkit.WebView; import android.widget.ScrollView; import android.widget.Toast; public class MainActivity extends AppCompatActivity implements View.OnTouchListener, ViewTreeObserver.OnScrollChangedListener { ScrollView scrollView; WebView webView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); scrollView = findViewById(R.id.scrollView); webView = findViewById(R.id.webView); scrollView.setOnTouchListener(this); scrollView.getViewTreeObserver().addOnScrollChangedListener(this); webView.loadData(getResources().getString(R.string.sample_data), "text/html", null); } public void onScrollChanged(){ View view = scrollView.getChildAt(scrollView.getChildCount() - 1); int topDetector = scrollView.getScrollY(); int bottomDetector = view.getBottom() - (scrollView.getHeight() + scrollView.getScrollY()); if(bottomDetector == 0 ){ Toast.makeText(getBaseContext(),"Scroll View bottom reached",Toast.LENGTH_SHORT).show(); } if(topDetector <= 0){ Toast.makeText(getBaseContext(),"Scroll View top reached",Toast.LENGTH_SHORT).show(); } } @Override public boolean onTouch(View v, MotionEvent event) { return false; } } Step 4 – Open res/values/strings.xml and add the following code − <resources> <string name="app_name">Sample</string> <string name="sample_data"> <![CDATA[<html>]]> <![CDATA[<style>]]> p.small { line-height: 1.5; font-size: 12px; } <![CDATA[</style>]]> <![CDATA[<body><p align="justify" class="small">]]> Chupa chups carrot cake pastry cupcake caramels sugar plum chocolate cupcake tootsie roll. Cupcake chocolate donut caramels sesame snaps brownie cake halvah. Sesame snaps sesame snaps gummies candy carrot cake. Fruitcake bonbon liquorice topping biscuit candy canes fruitcake marzipan cake. Tart tootsie roll tart gummi bears apple pie danish powder pastry gummies. Tiramisu sesame snaps icing pudding. Marzipan sweet roll cookie marshmallow. Tiramisu bear claw bear claw sesame snaps pie marzipan. Icing candy candy canes danish. Tart lollipop jujubes cake soufflé. Cheesecake bear claw marshmallow chocolate cake donut sweet. Tootsie roll topping chocolate bar cupcake cake oat cake oat cake bonbon cotton candy. Jelly-o croissant dragée lemon drops chocolate bar. Gingerbread cotton candy oat cake marshmallow. <![CDATA[<br><br>]]> Lemon drops carrot cake wafer jelly cheesecake chocolate cake gingerbread. Dessert cookie oat cake pie. Liquorice liquorice dragée lollipop danish jujubes pudding carrot cake. Jelly beans cotton candy sweet caramels gummies pastry. Wafer wafer muffin sweet roll. Chocolate topping gummi bears gummies. Oat cake bonbon brownie chocolate bar. Tart tart gingerbread chupa chups chocolate bar gummies. C 0roissant oat cake ice cream liquorice tootsie roll. Pudding wafer gummies. Apple pie marshmallow chupa chups. Cookie cheesecake carrot cake jelly beans tiramisu lemon drops. Bonbon sweet roll wafer. <![CDATA[<br><br>]]> Lemon drops muffin bear claw cake gingerbread apple pie lollipop cheesecake. Powder bear claw marshmallow. Tootsie roll gummi bears wafer brownie. Sesame snaps soufflé bear claw chocolate danish candy. Wafer oat cake ice cream pastry cake muffin toffee tootsie roll. Cake oat cake marshmallow. Gummi bears gingerbread cake danish muffin marzipan donut cotton candy. Ice cream topping cake candy gummi bears brownie. Marshmallow chocolate icing candy canes topping. Pastry gummies powder sesame snaps sugar plum sugar plum. Lemon drops gummies gummi bears tootsie roll powder jelly-o jelly-o. Lollipop jujubes sweet brownie croissant soufflé chupa chups bear claw. Sugar plum sugar plum lollipop croissant lemon drops sweet jujubes soufflé sweet roll. <![CDATA[<br><br>]]> Liquorice jelly-o candy lollipop croissant sweet icing brownie biscuit. Wafer dessert cake marzipan gummies jujubes bonbon tootsie roll ice cream. Chocolate bar bear claw candy canes lemon drops jelly apple pie cotton candy jujubes. Donut toffee candy canes dragée cake toffee. Icing cookie biscuit cheesecake dragée. Gummi bears tiramisu sesame snaps muffin halvah. Sweet jujubes chocolate cake muffin pie bonbon cupcake. Pastry jujubes pastry fruitcake. Jelly beans dessert gingerbread cupcake gingerbread marshmallow carrot cake. Macaroon carrot cake candy canes jelly powder. Soufflé macaroon liquorice candy canes lollipop. Marzipan fruitcake fruitcake gummi bears gummies chocolate cake. Jelly sesame snaps topping sweet. <![CDATA[<br><br>]]> Chupa chups macaroon muffin. Topping jujubes biscuit tart jujubes pudding. Brownie oat cake cookie. Lemon drops pudding tiramisu dessert marzipan. Danish cake candy canes bonbon. Gummi bears carrot cake apple pie lollipop. Tart candy canes chocolate cake lemon drops carrot cake topping cheesecake apple pie cake. Bear claw pudding macaroon croissant halvah caramels. Danish cake pastry sugar plum lollipop ice cream gummi bears gummi bears sugar plum. Chocolate macaroon tootsie roll. Halvah tootsie roll sweet roll powder gummi bears chocolate cake. Sugar plum gingerbread brownie. Wafer chocolate cake bonbon ice cream biscuit dragée tiramisu croissant apple pie. <![CDATA[</p></body></html>]]> </string> </resources> Step 4 – Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.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 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": 1134, "s": 1062, "text": "This example demonstrates how do I detect end of scrollView in android." }, { "code": null, "e": 1263, "s": 1134, "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": 1328, "s": 1263, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1935, "s": 1328, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <ScrollView\n android:id=\"@+id/scrollView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\">\n <WebView\n android:id=\"@+id/webView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\">\n </WebView>\n </ScrollView>\n</RelativeLayout>" }, { "code": null, "e": 1992, "s": 1935, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3521, "s": 1992, "text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.view.ViewTreeObserver;\nimport android.webkit.WebView;\nimport android.widget.ScrollView;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity implements View.OnTouchListener,\n ViewTreeObserver.OnScrollChangedListener {\n ScrollView scrollView;\n WebView webView;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n scrollView = findViewById(R.id.scrollView);\n webView = findViewById(R.id.webView);\n scrollView.setOnTouchListener(this);\n scrollView.getViewTreeObserver().addOnScrollChangedListener(this);\n webView.loadData(getResources().getString(R.string.sample_data), \"text/html\", null);\n }\n public void onScrollChanged(){\n View view = scrollView.getChildAt(scrollView.getChildCount() - 1);\n int topDetector = scrollView.getScrollY();\n int bottomDetector = view.getBottom() - (scrollView.getHeight() + scrollView.getScrollY());\n if(bottomDetector == 0 ){\n Toast.makeText(getBaseContext(),\"Scroll View bottom reached\",Toast.LENGTH_SHORT).show();\n }\n if(topDetector <= 0){\n Toast.makeText(getBaseContext(),\"Scroll View top reached\",Toast.LENGTH_SHORT).show();\n }\n }\n @Override\n public boolean onTouch(View v, MotionEvent event) {\n return false;\n }\n}" }, { "code": null, "e": 3587, "s": 3521, "text": "Step 4 – Open res/values/strings.xml and add the following code −" }, { "code": null, "e": 8041, "s": 3587, "text": "<resources>\n <string name=\"app_name\">Sample</string>\n <string name=\"sample_data\">\n <![CDATA[<html>]]>\n <![CDATA[<style>]]>\n p.small {\n line-height: 1.5;\n font-size: 12px;\n }\n <![CDATA[</style>]]>\n <![CDATA[<body><p align=\"justify\" class=\"small\">]]>\n Chupa chups carrot cake pastry cupcake caramels sugar plum chocolate cupcake tootsie roll.\n Cupcake chocolate donut caramels sesame snaps brownie cake halvah.\n Sesame snaps sesame snaps gummies candy carrot cake.\n Fruitcake bonbon liquorice topping biscuit candy canes fruitcake marzipan cake.\n Tart tootsie roll tart gummi bears apple pie danish powder pastry gummies.\n Tiramisu sesame snaps icing pudding. Marzipan sweet roll cookie marshmallow.\n Tiramisu bear claw bear claw sesame snaps pie marzipan.\n Icing candy candy canes danish. Tart lollipop jujubes cake soufflé.\n Cheesecake bear claw marshmallow chocolate cake donut sweet.\n Tootsie roll topping chocolate bar cupcake cake oat cake oat cake bonbon cotton candy.\n Jelly-o croissant dragée lemon drops chocolate bar. Gingerbread cotton candy oat cake marshmallow.\n <![CDATA[<br><br>]]>\n Lemon drops carrot cake wafer jelly cheesecake chocolate cake gingerbread.\n Dessert cookie oat cake pie. Liquorice liquorice dragée lollipop danish jujubes pudding carrot cake.\n Jelly beans cotton candy sweet caramels gummies pastry. Wafer wafer muffin sweet roll.\n Chocolate topping gummi bears gummies. Oat cake bonbon brownie chocolate bar.\n Tart tart gingerbread chupa chups chocolate bar gummies. C\n 0roissant oat cake ice cream liquorice tootsie roll. Pudding wafer gummies.\n Apple pie marshmallow chupa chups. Cookie cheesecake carrot cake jelly beans tiramisu lemon drops.\n Bonbon sweet roll wafer.\n <![CDATA[<br><br>]]>\n Lemon drops muffin bear claw cake gingerbread apple pie lollipop cheesecake.\n Powder bear claw marshmallow. Tootsie roll gummi bears wafer brownie.\n Sesame snaps soufflé bear claw chocolate danish candy.\n Wafer oat cake ice cream pastry cake muffin toffee tootsie roll. Cake oat cake marshmallow.\n Gummi bears gingerbread cake danish muffin marzipan donut cotton candy.\n Ice cream topping cake candy gummi bears brownie. Marshmallow chocolate icing candy canes topping.\n Pastry gummies powder sesame snaps sugar plum sugar plum.\n Lemon drops gummies gummi bears tootsie roll powder jelly-o jelly-o.\n Lollipop jujubes sweet brownie croissant soufflé chupa chups bear claw.\n Sugar plum sugar plum lollipop croissant lemon drops sweet jujubes soufflé sweet roll.\n <![CDATA[<br><br>]]>\n Liquorice jelly-o candy lollipop croissant sweet icing brownie biscuit.\n Wafer dessert cake marzipan gummies jujubes bonbon tootsie roll ice cream.\n Chocolate bar bear claw candy canes lemon drops jelly apple pie cotton candy jujubes.\n Donut toffee candy canes dragée cake toffee. Icing cookie biscuit cheesecake dragée.\n Gummi bears tiramisu sesame snaps muffin halvah. Sweet jujubes chocolate cake muffin pie bonbon cupcake.\n Pastry jujubes pastry fruitcake. Jelly beans dessert gingerbread cupcake gingerbread marshmallow carrot cake.\n Macaroon carrot cake candy canes jelly powder. Soufflé macaroon liquorice candy canes lollipop.\n Marzipan fruitcake fruitcake gummi bears gummies chocolate cake. Jelly sesame snaps topping sweet.\n <![CDATA[<br><br>]]>\n Chupa chups macaroon muffin. Topping jujubes biscuit tart jujubes pudding.\n Brownie oat cake cookie. Lemon drops pudding tiramisu dessert marzipan.\n Danish cake candy canes bonbon. Gummi bears carrot cake apple pie lollipop.\n Tart candy canes chocolate cake lemon drops carrot cake topping cheesecake apple pie cake.\n Bear claw pudding macaroon croissant halvah caramels.\n Danish cake pastry sugar plum lollipop ice cream gummi bears gummi bears sugar plum.\n Chocolate macaroon tootsie roll. Halvah tootsie roll sweet roll powder gummi bears chocolate cake.\n Sugar plum gingerbread brownie. Wafer chocolate cake bonbon ice cream biscuit dragée tiramisu croissant apple pie.\n <![CDATA[</p></body></html>]]>\n </string>\n</resources>" }, { "code": null, "e": 8096, "s": 8041, "text": "Step 4 – Add the following code to androidManifest.xml" }, { "code": null, "e": 8766, "s": 8096, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.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": 9114, "s": 8766, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 9155, "s": 9114, "text": "Click here to download the project code." } ]
Neural Networks: Problems & Solutions | by Sayan Sinha | Towards Data Science
Though the concept of artificial neural network has been in existence since the 1950s, it’s only recently that we have capable hardware to turn theory into practice. Neural networks are supposed to be able to mimic any continuous function. But many a times we are stuck with networks not performing up to the mark, or it takes a whole lot of time to get decent results. One should approach the problem statistically rather than going with gut feelings regarding the changes which should be brought about in the architecture of the network. One of the first steps should be proper preprocessing of data. Other than mean normalisation and scaling, Principal Component Analysis may be useful in speeding up training. If the dimension of the data is reduced to such an extent that a proper amount of variance is still retained, one can save on space without compromising much on the quality of the data. Also, neural networks can be trained faster when they are provided with less data. Reduction in dimension can be achieved by decomposing the covariance matrix of the training data using singular value decomposition into three matrices. The first matrix is supposed to be contain eigenvectors. Furthermore, the set of vectors present in the matrix are orthonormal, hence they may be treated as basis vectors. We pick the first few vectors out of this matrix, the number being equal to the number of dimensions we wish to reduce the data into. Making a transformation of the original matrix (with original dimensions) with the matrix we obtain in the previous step, we get a new matrix, which is both reduced in dimension and linearly transformed. The above steps are mathematical in nature, but essentially we simply “projected” the data from the higher dimension to a lower dimension, similar to projecting points in a plane on a well-fitting line in a way that the distances a point has to “travel” is minimised. An Octave implementation of the PCA would be : function [U, S] = pca(X) [m, n] = size(X); U = zeros(n); S = zeros(n); Sigma=(1/m)*(X' * X); [U, S, V] =svd(Sigma);endfunction Z = projectData(X, U, K) Z = zeros(size(X, 1), K); U_reduce = U(:, 1:K); Z = X*U_reduce;endload ('<data>'); % Loads the dataset into % variable X[X_norm, mu, sigma] = Normalise(X); % Performs normalisation[U, S] = pca(X_norm); % Performs PCAK = input("Enter reduced dimension");Z = projectData(X_norm, U, K); One may use PCA for visualising the data by reducing it to 3D or 2D. But, a more recommended method would be to make use of t-distributed stochastic neighbour embedding, which is based on a probability distribution, unlike PCA. t-SNE tries to minimise the difference between the conditional probability in the higher and the reduced dimensions. The conditional probability is high for points close together (measured by their Euclidean distance) and is low for the once which are far apart. Points are grouped according to the obtained distribution. The variance is chosen such that points in dense areas are given a smaller variance compared to points in sparse areas. Though it was proved by George Cybenko in 1989 that neural networks with even a single hidden layer can approximate any continuous function, it may be desired to introduce polynomial features of higher degree into the network, in order to obtain better predictions. One might consider increasing the number of hidden layers. In fact, the number of layers of a network is equal to the highest degree of a polynomial it should be able to represent. Though this could also be achieved by raising the number of neurons in the existing layers too, that would require far more neurons (and hence an increased computational time) compared to adding hidden layers to the network, for approximating a function with a similar amount of error. On the other hand, making neural nets “deep” results in unstable gradients. This can be divided into two parts, namely the vanishing and the exploding gradient problems. The weights of a neural network are generally initialised with random values, having a mean 0 and standard deviation 1, placed roughly on a Gaussian distribution. This makes sure that most of the weights are between -1 and 1. The sigmoid function gives us a maximum derivative of 0.25 (when the input is zero). This, combined with the fact that the weights belong to a limited range helps makes sure that the absolute value of their product too is less than 0.25. The gradient of a perceptron comprises the product of many such terms, each being less than 0.25. The deeper we go into the layers, we’ll have more and more such terms, resulting in the vanishing gradient issue. Essentially, the gradient of a perceptron of an outer hidden layer (closer to the input layer) would be given by the sum of products of the gradients of the deeper layers and the weights assigned to each of the links between them. Hence, it is apparent that shallow layers would have very less gradient. This would result in their weights changing less during learning and becoming almost stagnant in due course of time. The first layers are supposed to carry most of the information, but we see it gets trained the least. Hence, the problem of vanishing gradient eventually leads to the death of the network. There might be circumstances in which the weight might go beyond one while training. In that case, one might wonder how vanishing gradients could still create problems. Well, this might lead to the exploding gradient problem, in which the gradient in the earlier layers become huge. If the weights are large and the bias is such that it’s product with the derivative of the sigmoid of the activation function too keeps it on the higher side, this problem would occur. But, on the other hand, that’s a little difficult to achieve, for, increased weight may result in higher value for the input to the activation function, where the derivative of sigmoid would be pretty low. This also helps establish the fact that the vanishing gradient issue is difficult to prevent. In order to address this problem, we choose other activation functions, avoiding sigmoid. Though sigmoid is a popular choice as it squashes the input between zero and one, and also for its derivative can be written as a function of sigmoid itself, neural networks relying on it might suffer from unstable gradients. Moreover, the sigmoid outputs are not zero centred, they are all positive. This means, all the gradients would either be positive or negative depending on the gradient of units on the next layer. The most recommended activation function one may use is Maxout. Maxout maintains two sets of parameters. The one which yields higher value to be presented as input to the activation function is used. Also, the weights may be varied according to certain input conditions. One such attempt leads to Leaky Rectified Linear Units. In this special case, the gradient remains 1 when the input is greater than 0, and it gets a small negative slope when it’s less than 0, proportional to the input. Another trouble which is encountered in neural networks, especially when they are deep is internal covariate shift. The statistical distribution of the input keeps changing as training proceeds. This can cause a significant change in the domain and hence, reduce training efficiency. A solution to the problem is to perform normalisation for every mini batch. We compute the mean and variance for all such batches, instead of the entire data. The input is normalised before feeding it into almost every hidden layer. The process is commonly known as batch normalisation. Applying batch normalisation can assist in overcoming the issue of vanishing gradients as well. Regularisation can be improved by implementing dropout. Often certain nodes in the network are randomly switched off, from some or all the layers of a neural network. Hence, in every iteration, we get a new network and the resulting network (obtained at the end of training) is a combination of all of them. This also helps in addressing the problem of overfitting. Whatever tweaks are applied, one must always keep a track of the percentage of dead neurons in the network, and adjust the learning rate accordingly. Certain diagnostics may be performed on the parameters to get better statistics. Plots on bias and variance are two important factors here. They can be determined by plotting curves with the output of the loss function (without regularisation) on the training and the cross validation data sets versus the number of training examples. In the figure above, the curve in red represents the cross validation data while the colour blue has been used to mark the training data set. The first figure is the one which would be roughly obtained when the architecture is suffering from high bias. It means, the architecture is poor, hence it gives pretty high errors even on the training data set. Addition of more features into the network (like adding more hidden layers, and hence introducing polynomial features) could be useful. If it is suffering from high variance, it means the trained parameters fits the training set well, but performs poorly when tested on “unseen” data (the training or the validation set). This could be because the model “over-fits” the training data. Getting more data could act as a fix. Reducing the number of hidden layers in the network might also be useful in this case. Playing with the regularisation parameter could help as well. Increasing its value could fix high variance whereas a decrease should assist in fixing high bias. An Octave implementation of plotting diagnostic curves would be: function [error_train, error_val] = ... learningCurve(X, y, Xval, yval, lambda) m = size(X, 1); error_train = zeros(m, 1); error_val = zeros(m, 1); for i = 1:m X_here = X(1:i,:); y_here = y(1:i); theta = train(X_here, y_here, lambda); error_train(i) = LossFunction(X_here,y_here,theta,0); error_val(i) = LossFunction(Xval,yval,theta,0); end;endlambda = input("Enter regularisation parameter");[theta] = train(X_poly, y, lambda);graphics_toolkit "gnuplot";figure(1);[error_train, error_val] = ... learningCurve(X_poly, y, X_poly_val, yval, lambda); plot(1:m, error_train, 1:m, error_val);xlabel('Number of training examples'); ylabel('Error');legend('Train', 'Cross Validation'); Though it has been noticed that a huge number of training data could increase the performance of any network, getting a lot of data might be costly and time consuming. In case the network is suffering from high bias or vanishing gradients issue, more data would be of no use. Hence simple mathematics should be implemented as it would guide us which step we should descend towards. References:* Machine Learning, Stanford University* Convolutional Neural Networks for Visual Recognition, Stanford University* Michael A. Nielsen, “Neural Networks and Deep Learning”, Determination Press, 2015* Batch Normalization — What the hey? (by Karl N.)* Paper summary → Character-level Convolutional Networks for Text Classification (by Nishant Nikhil)Code repository: https://github.com/americast/ML_ANg
[ { "code": null, "e": 1155, "s": 172, "text": "Though the concept of artificial neural network has been in existence since the 1950s, it’s only recently that we have capable hardware to turn theory into practice. Neural networks are supposed to be able to mimic any continuous function. But many a times we are stuck with networks not performing up to the mark, or it takes a whole lot of time to get decent results. One should approach the problem statistically rather than going with gut feelings regarding the changes which should be brought about in the architecture of the network. One of the first steps should be proper preprocessing of data. Other than mean normalisation and scaling, Principal Component Analysis may be useful in speeding up training. If the dimension of the data is reduced to such an extent that a proper amount of variance is still retained, one can save on space without compromising much on the quality of the data. Also, neural networks can be trained faster when they are provided with less data." }, { "code": null, "e": 1818, "s": 1155, "text": "Reduction in dimension can be achieved by decomposing the covariance matrix of the training data using singular value decomposition into three matrices. The first matrix is supposed to be contain eigenvectors. Furthermore, the set of vectors present in the matrix are orthonormal, hence they may be treated as basis vectors. We pick the first few vectors out of this matrix, the number being equal to the number of dimensions we wish to reduce the data into. Making a transformation of the original matrix (with original dimensions) with the matrix we obtain in the previous step, we get a new matrix, which is both reduced in dimension and linearly transformed." }, { "code": null, "e": 2086, "s": 1818, "text": "The above steps are mathematical in nature, but essentially we simply “projected” the data from the higher dimension to a lower dimension, similar to projecting points in a plane on a well-fitting line in a way that the distances a point has to “travel” is minimised." }, { "code": null, "e": 2133, "s": 2086, "text": "An Octave implementation of the PCA would be :" }, { "code": null, "e": 2649, "s": 2133, "text": "function [U, S] = pca(X) [m, n] = size(X); U = zeros(n); S = zeros(n); Sigma=(1/m)*(X' * X); [U, S, V] =svd(Sigma);endfunction Z = projectData(X, U, K) Z = zeros(size(X, 1), K); U_reduce = U(:, 1:K); Z = X*U_reduce;endload ('<data>'); % Loads the dataset into % variable X[X_norm, mu, sigma] = Normalise(X); % Performs normalisation[U, S] = pca(X_norm); % Performs PCAK = input(\"Enter reduced dimension\");Z = projectData(X_norm, U, K);" }, { "code": null, "e": 2994, "s": 2649, "text": "One may use PCA for visualising the data by reducing it to 3D or 2D. But, a more recommended method would be to make use of t-distributed stochastic neighbour embedding, which is based on a probability distribution, unlike PCA. t-SNE tries to minimise the difference between the conditional probability in the higher and the reduced dimensions." }, { "code": null, "e": 3319, "s": 2994, "text": "The conditional probability is high for points close together (measured by their Euclidean distance) and is low for the once which are far apart. Points are grouped according to the obtained distribution. The variance is chosen such that points in dense areas are given a smaller variance compared to points in sparse areas." }, { "code": null, "e": 4222, "s": 3319, "text": "Though it was proved by George Cybenko in 1989 that neural networks with even a single hidden layer can approximate any continuous function, it may be desired to introduce polynomial features of higher degree into the network, in order to obtain better predictions. One might consider increasing the number of hidden layers. In fact, the number of layers of a network is equal to the highest degree of a polynomial it should be able to represent. Though this could also be achieved by raising the number of neurons in the existing layers too, that would require far more neurons (and hence an increased computational time) compared to adding hidden layers to the network, for approximating a function with a similar amount of error. On the other hand, making neural nets “deep” results in unstable gradients. This can be divided into two parts, namely the vanishing and the exploding gradient problems." }, { "code": null, "e": 4898, "s": 4222, "text": "The weights of a neural network are generally initialised with random values, having a mean 0 and standard deviation 1, placed roughly on a Gaussian distribution. This makes sure that most of the weights are between -1 and 1. The sigmoid function gives us a maximum derivative of 0.25 (when the input is zero). This, combined with the fact that the weights belong to a limited range helps makes sure that the absolute value of their product too is less than 0.25. The gradient of a perceptron comprises the product of many such terms, each being less than 0.25. The deeper we go into the layers, we’ll have more and more such terms, resulting in the vanishing gradient issue." }, { "code": null, "e": 5508, "s": 4898, "text": "Essentially, the gradient of a perceptron of an outer hidden layer (closer to the input layer) would be given by the sum of products of the gradients of the deeper layers and the weights assigned to each of the links between them. Hence, it is apparent that shallow layers would have very less gradient. This would result in their weights changing less during learning and becoming almost stagnant in due course of time. The first layers are supposed to carry most of the information, but we see it gets trained the least. Hence, the problem of vanishing gradient eventually leads to the death of the network." }, { "code": null, "e": 6366, "s": 5508, "text": "There might be circumstances in which the weight might go beyond one while training. In that case, one might wonder how vanishing gradients could still create problems. Well, this might lead to the exploding gradient problem, in which the gradient in the earlier layers become huge. If the weights are large and the bias is such that it’s product with the derivative of the sigmoid of the activation function too keeps it on the higher side, this problem would occur. But, on the other hand, that’s a little difficult to achieve, for, increased weight may result in higher value for the input to the activation function, where the derivative of sigmoid would be pretty low. This also helps establish the fact that the vanishing gradient issue is difficult to prevent. In order to address this problem, we choose other activation functions, avoiding sigmoid." }, { "code": null, "e": 6788, "s": 6366, "text": "Though sigmoid is a popular choice as it squashes the input between zero and one, and also for its derivative can be written as a function of sigmoid itself, neural networks relying on it might suffer from unstable gradients. Moreover, the sigmoid outputs are not zero centred, they are all positive. This means, all the gradients would either be positive or negative depending on the gradient of units on the next layer." }, { "code": null, "e": 7279, "s": 6788, "text": "The most recommended activation function one may use is Maxout. Maxout maintains two sets of parameters. The one which yields higher value to be presented as input to the activation function is used. Also, the weights may be varied according to certain input conditions. One such attempt leads to Leaky Rectified Linear Units. In this special case, the gradient remains 1 when the input is greater than 0, and it gets a small negative slope when it’s less than 0, proportional to the input." }, { "code": null, "e": 7946, "s": 7279, "text": "Another trouble which is encountered in neural networks, especially when they are deep is internal covariate shift. The statistical distribution of the input keeps changing as training proceeds. This can cause a significant change in the domain and hence, reduce training efficiency. A solution to the problem is to perform normalisation for every mini batch. We compute the mean and variance for all such batches, instead of the entire data. The input is normalised before feeding it into almost every hidden layer. The process is commonly known as batch normalisation. Applying batch normalisation can assist in overcoming the issue of vanishing gradients as well." }, { "code": null, "e": 8312, "s": 7946, "text": "Regularisation can be improved by implementing dropout. Often certain nodes in the network are randomly switched off, from some or all the layers of a neural network. Hence, in every iteration, we get a new network and the resulting network (obtained at the end of training) is a combination of all of them. This also helps in addressing the problem of overfitting." }, { "code": null, "e": 8462, "s": 8312, "text": "Whatever tweaks are applied, one must always keep a track of the percentage of dead neurons in the network, and adjust the learning rate accordingly." }, { "code": null, "e": 8797, "s": 8462, "text": "Certain diagnostics may be performed on the parameters to get better statistics. Plots on bias and variance are two important factors here. They can be determined by plotting curves with the output of the loss function (without regularisation) on the training and the cross validation data sets versus the number of training examples." }, { "code": null, "e": 9822, "s": 8797, "text": "In the figure above, the curve in red represents the cross validation data while the colour blue has been used to mark the training data set. The first figure is the one which would be roughly obtained when the architecture is suffering from high bias. It means, the architecture is poor, hence it gives pretty high errors even on the training data set. Addition of more features into the network (like adding more hidden layers, and hence introducing polynomial features) could be useful. If it is suffering from high variance, it means the trained parameters fits the training set well, but performs poorly when tested on “unseen” data (the training or the validation set). This could be because the model “over-fits” the training data. Getting more data could act as a fix. Reducing the number of hidden layers in the network might also be useful in this case. Playing with the regularisation parameter could help as well. Increasing its value could fix high variance whereas a decrease should assist in fixing high bias." }, { "code": null, "e": 9887, "s": 9822, "text": "An Octave implementation of plotting diagnostic curves would be:" }, { "code": null, "e": 10675, "s": 9887, "text": "function [error_train, error_val] = ... learningCurve(X, y, Xval, yval, lambda) m = size(X, 1); error_train = zeros(m, 1); error_val = zeros(m, 1); for i = 1:m X_here = X(1:i,:); y_here = y(1:i); theta = train(X_here, y_here, lambda);\t error_train(i) = LossFunction(X_here,y_here,theta,0); error_val(i) = LossFunction(Xval,yval,theta,0); end;endlambda = input(\"Enter regularisation parameter\");[theta] = train(X_poly, y, lambda);graphics_toolkit \"gnuplot\";figure(1);[error_train, error_val] = ... learningCurve(X_poly, y, X_poly_val, yval, lambda); plot(1:m, error_train, 1:m, error_val);xlabel('Number of training examples'); ylabel('Error');legend('Train', 'Cross Validation');" }, { "code": null, "e": 11057, "s": 10675, "text": "Though it has been noticed that a huge number of training data could increase the performance of any network, getting a lot of data might be costly and time consuming. In case the network is suffering from high bias or vanishing gradients issue, more data would be of no use. Hence simple mathematics should be implemented as it would guide us which step we should descend towards." } ]
Check whether a point exists in circle sector or not. - GeeksforGeeks
31 Mar, 2021 We have a circle centered at origin (0, 0). As input we are given with starting angle of the circle sector and the size of the circle sector in percentage. Examples: Input : Radius = 8 StartAngle = 0 Percentage = 12 x = 3 y = 4 Output : Point (3, 4) exists in the circle sector Input : Radius = 12 Startangle = 45 Percentage = 25 x = 3 y = 4 Output : Point (3, 4) does not exist in the circle sector Source:wikibooks.org In this image starting angle is 0 degree, radius r and suppose that percentage of colored area is 12% then we calculate Ending Angle as 360/percentage + starting angle. To find whether a point (x, y) exists in a circle sector (centered at origin) or not we find polar coordinates of that point and then go through the following steps: Convert x, y to polar coordinates using this Angle = atan(y/x); Radius = sqrt(x * x + y * y);Then Angle must be between StartingAngle and EndingAngle, and Radius between 0 and your Radius. Convert x, y to polar coordinates using this Angle = atan(y/x); Radius = sqrt(x * x + y * y); Then Angle must be between StartingAngle and EndingAngle, and Radius between 0 and your Radius. C++ Java Python3 C# Javascript // C++ program to check if a point lies inside a circle// sector.#include<bits/stdc++.h>using namespace std; void checkPoint(int radius, int x, int y, float percent, float startAngle){ // calculate endAngle float endAngle = 360/percent + startAngle; // Calculate polar co-ordinates float polarradius = sqrt(x*x+y*y); float Angle = atan(y/x); // Check whether polarradius is less then radius of circle // or not and Angle is between startAngle and endAngle // or not if (Angle>=startAngle && Angle<=endAngle && polarradius<radius) printf("Point (%d, %d) exist in the circle sector\n", x, y); else printf("Point (%d, %d) does not exist in the circle sector\n", x, y);} // Driver codeint main(){ int radius = 8, x = 3, y = 4; float percent = 12, startAngle = 0; checkPoint(radius, x, y, percent, startAngle); return 0;} // Java program to check if// a point lies inside a circle// sector. class GFG{static void checkPoint(int radius, int x, int y, float percent, float startAngle){ // calculate endAngle float endAngle = 360/percent + startAngle; // Calculate polar co-ordinates double polarradius = Math.sqrt(x*x+y*y); double Angle = Math.atan(y/x); // Check whether polarradius is // less then radius of circle // or not and Angle is between // startAngle and endAngle // or not if (Angle>=startAngle && Angle<=endAngle && polarradius<radius) System.out.print("Point"+"("+x+","+y+")"+ " exist in the circle sector\n"); else System.out.print("Point"+"("+x+","+y+")"+ " exist in the circle sector\n");} // Driver Program to test above functionpublic static void main(String arg[]){ int radius = 8, x = 3, y = 4; float percent = 12, startAngle = 0; checkPoint(radius, x, y, percent, startAngle);}} // This code is contributed// by Anant Agarwal. # Python3 program to check if a point# lies inside a circle sector.import math def checkPoint(radius, x, y, percent, startAngle): # calculate endAngle endAngle = 360 / percent + startAngle # Calculate polar co-ordinates polarradius = math.sqrt(x * x + y * y) Angle = math.atan(y / x) # Check whether polarradius is less # then radius of circle or not and # Angle is between startAngle and # endAngle or not if (Angle >= startAngle and Angle <= endAngle and polarradius < radius): print("Point (", x, ",", y, ") " "exist in the circle sector") else: print("Point (", x, ",", y, ") " "does not exist in the circle sector") # Driver coderadius, x, y = 8, 3, 4percent, startAngle = 12, 0 checkPoint(radius, x, y, percent, startAngle) # This code is contributed by# Smitha Dinesh Semwal // C# program to check if a point lies// inside a circle sector.using System.IO;using System; class GFG { static void checkPoint(int radius, int x, int y, float percent, float startAngle) { // calculate endAngle float endAngle = 360 / percent + startAngle; // Calculate polar co-ordinates float polarradius = (float)Math.Sqrt(x * x + y * y); float Angle = (float)Math.Atan(y / x); // Check whether polarradius is less then // radius of circle or not and Angle is // between startAngle and endAngle or not if (Angle >= startAngle && Angle <= endAngle && polarradius < radius) Console.Write("Point ({0}, {1}) exist in " + "the circle sector", x, y); else Console.Write("Point ({0}, {1}) does not " + "exist in the circle sector", x, y); } // Driver code public static void Main() { int radius = 8, x = 3, y = 4; float percent = 12, startAngle = 0; checkPoint(radius, x, y, percent, startAngle); }} // This code is contributed by Smitha Dinesh Semwal <script> // Javascript program to check if// a point lies inside a circle// sector.function checkPoint(radius, x, y, percent, startAngle){ // Calculate endAngle let endAngle = 360 / percent + startAngle; // Calculate polar co-ordinates let polarradius = Math.sqrt(x * x + y * y); let Angle = Math.atan(y / x); // Check whether polarradius is // less then radius of circle // or not and Angle is between // startAngle and endAngle // or not if (Angle >= startAngle && Angle <= endAngle && polarradius < radius) document.write("Point" + "(" + x + "," + y + ")" + " exist in the circle sector\n"); else document.write("Point" + "(" + x + "," + y + ")" + " exist in the circle sector\n");} // Driver code let radius = 8, x = 3, y = 4;let percent = 12, startAngle = 0; checkPoint(radius, x, y, percent, startAngle); // This code is contributed by splevel62 </script> Output : Point(3, 4) exists in the circle sector Time complexity = O(1) This article is contributed by Niteesh kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Smitha Dinesh Semwal splevel62 Geometric Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Haversine formula to find distance between two points on a sphere Equation of circle when three points on the circle are given Program to find slope of a line Program to find line passing through 2 Points Maximum Manhattan distance between a distinct pair from N coordinates Orientation of 3 ordered points Check if a line touches or intersects a circle Minimum Cost Polygon Triangulation Quickhull Algorithm for Convex Hull Minimum number of Cuboids required to form a Cube
[ { "code": null, "e": 26509, "s": 26481, "text": "\n31 Mar, 2021" }, { "code": null, "e": 26666, "s": 26509, "text": "We have a circle centered at origin (0, 0). As input we are given with starting angle of the circle sector and the size of the circle sector in percentage. " }, { "code": null, "e": 26677, "s": 26666, "text": "Examples: " }, { "code": null, "e": 26992, "s": 26677, "text": "Input : Radius = 8 \n StartAngle = 0 \n Percentage = 12 \n x = 3 y = 4 \nOutput : Point (3, 4) exists in the circle \n sector\n\nInput : Radius = 12 \n Startangle = 45\n Percentage = 25 \n x = 3 y = 4 \nOutput : Point (3, 4) does not exist in \n the circle sector" }, { "code": null, "e": 27015, "s": 26994, "text": "Source:wikibooks.org" }, { "code": null, "e": 27184, "s": 27015, "text": "In this image starting angle is 0 degree, radius r and suppose that percentage of colored area is 12% then we calculate Ending Angle as 360/percentage + starting angle." }, { "code": null, "e": 27350, "s": 27184, "text": "To find whether a point (x, y) exists in a circle sector (centered at origin) or not we find polar coordinates of that point and then go through the following steps:" }, { "code": null, "e": 27539, "s": 27350, "text": "Convert x, y to polar coordinates using this Angle = atan(y/x); Radius = sqrt(x * x + y * y);Then Angle must be between StartingAngle and EndingAngle, and Radius between 0 and your Radius." }, { "code": null, "e": 27633, "s": 27539, "text": "Convert x, y to polar coordinates using this Angle = atan(y/x); Radius = sqrt(x * x + y * y);" }, { "code": null, "e": 27729, "s": 27633, "text": "Then Angle must be between StartingAngle and EndingAngle, and Radius between 0 and your Radius." }, { "code": null, "e": 27733, "s": 27729, "text": "C++" }, { "code": null, "e": 27738, "s": 27733, "text": "Java" }, { "code": null, "e": 27746, "s": 27738, "text": "Python3" }, { "code": null, "e": 27749, "s": 27746, "text": "C#" }, { "code": null, "e": 27760, "s": 27749, "text": "Javascript" }, { "code": "// C++ program to check if a point lies inside a circle// sector.#include<bits/stdc++.h>using namespace std; void checkPoint(int radius, int x, int y, float percent, float startAngle){ // calculate endAngle float endAngle = 360/percent + startAngle; // Calculate polar co-ordinates float polarradius = sqrt(x*x+y*y); float Angle = atan(y/x); // Check whether polarradius is less then radius of circle // or not and Angle is between startAngle and endAngle // or not if (Angle>=startAngle && Angle<=endAngle && polarradius<radius) printf(\"Point (%d, %d) exist in the circle sector\\n\", x, y); else printf(\"Point (%d, %d) does not exist in the circle sector\\n\", x, y);} // Driver codeint main(){ int radius = 8, x = 3, y = 4; float percent = 12, startAngle = 0; checkPoint(radius, x, y, percent, startAngle); return 0;}", "e": 28737, "s": 27760, "text": null }, { "code": "// Java program to check if// a point lies inside a circle// sector. class GFG{static void checkPoint(int radius, int x, int y, float percent, float startAngle){ // calculate endAngle float endAngle = 360/percent + startAngle; // Calculate polar co-ordinates double polarradius = Math.sqrt(x*x+y*y); double Angle = Math.atan(y/x); // Check whether polarradius is // less then radius of circle // or not and Angle is between // startAngle and endAngle // or not if (Angle>=startAngle && Angle<=endAngle && polarradius<radius) System.out.print(\"Point\"+\"(\"+x+\",\"+y+\")\"+ \" exist in the circle sector\\n\"); else System.out.print(\"Point\"+\"(\"+x+\",\"+y+\")\"+ \" exist in the circle sector\\n\");} // Driver Program to test above functionpublic static void main(String arg[]){ int radius = 8, x = 3, y = 4; float percent = 12, startAngle = 0; checkPoint(radius, x, y, percent, startAngle);}} // This code is contributed// by Anant Agarwal.", "e": 29781, "s": 28737, "text": null }, { "code": "# Python3 program to check if a point# lies inside a circle sector.import math def checkPoint(radius, x, y, percent, startAngle): # calculate endAngle endAngle = 360 / percent + startAngle # Calculate polar co-ordinates polarradius = math.sqrt(x * x + y * y) Angle = math.atan(y / x) # Check whether polarradius is less # then radius of circle or not and # Angle is between startAngle and # endAngle or not if (Angle >= startAngle and Angle <= endAngle and polarradius < radius): print(\"Point (\", x, \",\", y, \") \" \"exist in the circle sector\") else: print(\"Point (\", x, \",\", y, \") \" \"does not exist in the circle sector\") # Driver coderadius, x, y = 8, 3, 4percent, startAngle = 12, 0 checkPoint(radius, x, y, percent, startAngle) # This code is contributed by# Smitha Dinesh Semwal", "e": 30662, "s": 29781, "text": null }, { "code": "// C# program to check if a point lies// inside a circle sector.using System.IO;using System; class GFG { static void checkPoint(int radius, int x, int y, float percent, float startAngle) { // calculate endAngle float endAngle = 360 / percent + startAngle; // Calculate polar co-ordinates float polarradius = (float)Math.Sqrt(x * x + y * y); float Angle = (float)Math.Atan(y / x); // Check whether polarradius is less then // radius of circle or not and Angle is // between startAngle and endAngle or not if (Angle >= startAngle && Angle <= endAngle && polarradius < radius) Console.Write(\"Point ({0}, {1}) exist in \" + \"the circle sector\", x, y); else Console.Write(\"Point ({0}, {1}) does not \" + \"exist in the circle sector\", x, y); } // Driver code public static void Main() { int radius = 8, x = 3, y = 4; float percent = 12, startAngle = 0; checkPoint(radius, x, y, percent, startAngle); }} // This code is contributed by Smitha Dinesh Semwal", "e": 31898, "s": 30662, "text": null }, { "code": "<script> // Javascript program to check if// a point lies inside a circle// sector.function checkPoint(radius, x, y, percent, startAngle){ // Calculate endAngle let endAngle = 360 / percent + startAngle; // Calculate polar co-ordinates let polarradius = Math.sqrt(x * x + y * y); let Angle = Math.atan(y / x); // Check whether polarradius is // less then radius of circle // or not and Angle is between // startAngle and endAngle // or not if (Angle >= startAngle && Angle <= endAngle && polarradius < radius) document.write(\"Point\" + \"(\" + x + \",\" + y + \")\" + \" exist in the circle sector\\n\"); else document.write(\"Point\" + \"(\" + x + \",\" + y + \")\" + \" exist in the circle sector\\n\");} // Driver code let radius = 8, x = 3, y = 4;let percent = 12, startAngle = 0; checkPoint(radius, x, y, percent, startAngle); // This code is contributed by splevel62 </script>", "e": 32914, "s": 31898, "text": null }, { "code": null, "e": 32924, "s": 32914, "text": "Output : " }, { "code": null, "e": 32964, "s": 32924, "text": "Point(3, 4) exists in the circle sector" }, { "code": null, "e": 32987, "s": 32964, "text": "Time complexity = O(1)" }, { "code": null, "e": 33413, "s": 32987, "text": "This article is contributed by Niteesh kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 33434, "s": 33413, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 33444, "s": 33434, "text": "splevel62" }, { "code": null, "e": 33454, "s": 33444, "text": "Geometric" }, { "code": null, "e": 33464, "s": 33454, "text": "Geometric" }, { "code": null, "e": 33562, "s": 33464, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33628, "s": 33562, "text": "Haversine formula to find distance between two points on a sphere" }, { "code": null, "e": 33689, "s": 33628, "text": "Equation of circle when three points on the circle are given" }, { "code": null, "e": 33721, "s": 33689, "text": "Program to find slope of a line" }, { "code": null, "e": 33767, "s": 33721, "text": "Program to find line passing through 2 Points" }, { "code": null, "e": 33837, "s": 33767, "text": "Maximum Manhattan distance between a distinct pair from N coordinates" }, { "code": null, "e": 33869, "s": 33837, "text": "Orientation of 3 ordered points" }, { "code": null, "e": 33916, "s": 33869, "text": "Check if a line touches or intersects a circle" }, { "code": null, "e": 33951, "s": 33916, "text": "Minimum Cost Polygon Triangulation" }, { "code": null, "e": 33987, "s": 33951, "text": "Quickhull Algorithm for Convex Hull" } ]
Advanced C++ with Boost Library - GeeksforGeeks
27 Dec, 2021 Boost Libraries are intended to be widely useful, and usable across a broad spectrum of applications. For example, they are helpful for handling large numbers having a range beyond the long long, long double data type (264) in C++. Installation Please refer to this Article for the installation of boost. We can download the zip file. After that, we just need to extract the whole in a specified folder of gcc or we can do this easily by command prompt. Example Applications We can efficiently use this library in Competitive Programming but before this, we must ensure that your online judge must support boost. Here are some cool tricks that you can use: 1) Big Integer Data Type: We can use either int128_t, int256_t, int512_t, or int1024_t data type according to your requirement. By using these ones, we can achieve precision up to 1024 easily. Below C++ implementation code for finding the product of large numbers: CPP // CPP Program to demonstrate Big Integer data type#include <boost/multiprecision/cpp_int.hpp>using namespace boost::multiprecision;using namespace std; int128_t boost_product(long long A, long long B){ int128_t ans = (int128_t)A * B; return ans;} int main(){ long long first = 98745636214564698; long long second = 7459874565236544789; cout << "Product of " << first << " * " << second << " = \n" << boost_product(first, second); return 0;} Product of 98745636214564698 * 7459874565236544789 = 736630060025131838840151335215258722 2) Arbitrary Precision Data Type: We can use any precision with the help of the cpp_int data type if we are not sure about how much precision is needed in the future. It automatically converts the desired precision at the Run-time. Below implementation of C++ code for finding the factorial of 30. CPP // CPP Program to demonstrate Arbitrary precision data type#include <boost/multiprecision/cpp_int.hpp>using namespace boost::multiprecision;using namespace std; cpp_int boost_factorial(int num){ cpp_int fact = 1; for (int i = num; i > 1; --i) fact *= i; return fact;} int main(){ int num = 30; cout << "Factorial of " << num << " = " << boost_factorial(num); return 0;} Output: Factorial of 30 = 265252859812191058636308480000000 3) Multiprecision Float: With Boost Multiprecision float, we can achieve precision up to 50 and 100 decimal with cpp_float_50 and cpp_dec_float_100 respectively. Below is C++ code to calculate the area of a circle with different precision by using a float, decimal, and cpp_float_50 types: CPP // CPP Program to demonstrate Boost Multiprecision float#include <boost/math/constants/constants.hpp>#include <boost/multiprecision/cpp_dec_float.hpp>#include <iostream> using boost::multiprecision::cpp_dec_float_50; using namespace std; template <typename T> inline T area_of_a_circle(T r){ // pi represent predefined constant having value // 3.1415926535897932384... using boost::math::constants::pi; return pi<T>() * r * r;} int main(){ float radius_f = 123.0 / 100; float area_f = area_of_a_circle(radius_f); double radius_d = 123.0 / 100; double area_d = area_of_a_circle(radius_d); cpp_dec_float_50 r_mp = 123.0 / 100; cpp_dec_float_50 area_mp = area_of_a_circle(r_mp); // numeric_limits::digits10 represent the number // of decimal digits that can be held of particular // data type without any loss. // Area by using float data type cout << "Float: " << setprecision(numeric_limits<float>::digits10) << area_f << endl; // Area by using double data type cout << "Double: " << setprecision(numeric_limits<double>::digits10) << area_d << endl; // Area by using Boost Multiprecision cout << "Boost Multiprecision: " << setprecision( numeric_limits<cpp_dec_float_50>::digits10) << area_mp << endl; return 0;} Float: 4.75292 Double: 4.752915525616 Boost Multiprecision: 4.7529155256159980531876290929438093413108253981451 This article is contributed by Shubham Bansal. 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. anshikajain26 cpp-advanced cpp-boost C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Vector in C++ STL Initialize a vector in C++ (6 different ways) std::sort() in C++ STL Socket Programming in C/C++ Bitwise Operators in C/C++ Virtual Function in C++ Templates in C++ with Examples rand() and srand() in C/C++ unordered_map in C++ STL Friend class and function in C++
[ { "code": null, "e": 26962, "s": 26934, "text": "\n27 Dec, 2021" }, { "code": null, "e": 27195, "s": 26962, "text": "Boost Libraries are intended to be widely useful, and usable across a broad spectrum of applications. For example, they are helpful for handling large numbers having a range beyond the long long, long double data type (264) in C++. " }, { "code": null, "e": 27208, "s": 27195, "text": "Installation" }, { "code": null, "e": 27417, "s": 27208, "text": "Please refer to this Article for the installation of boost. We can download the zip file. After that, we just need to extract the whole in a specified folder of gcc or we can do this easily by command prompt." }, { "code": null, "e": 27438, "s": 27417, "text": "Example Applications" }, { "code": null, "e": 27621, "s": 27438, "text": "We can efficiently use this library in Competitive Programming but before this, we must ensure that your online judge must support boost. Here are some cool tricks that you can use: " }, { "code": null, "e": 27815, "s": 27621, "text": "1) Big Integer Data Type: We can use either int128_t, int256_t, int512_t, or int1024_t data type according to your requirement. By using these ones, we can achieve precision up to 1024 easily. " }, { "code": null, "e": 27887, "s": 27815, "text": "Below C++ implementation code for finding the product of large numbers:" }, { "code": null, "e": 27891, "s": 27887, "text": "CPP" }, { "code": "// CPP Program to demonstrate Big Integer data type#include <boost/multiprecision/cpp_int.hpp>using namespace boost::multiprecision;using namespace std; int128_t boost_product(long long A, long long B){ int128_t ans = (int128_t)A * B; return ans;} int main(){ long long first = 98745636214564698; long long second = 7459874565236544789; cout << \"Product of \" << first << \" * \" << second << \" = \\n\" << boost_product(first, second); return 0;}", "e": 28367, "s": 27891, "text": null }, { "code": null, "e": 28458, "s": 28367, "text": "Product of 98745636214564698 * 7459874565236544789 = \n736630060025131838840151335215258722" }, { "code": null, "e": 28691, "s": 28458, "text": "2) Arbitrary Precision Data Type: We can use any precision with the help of the cpp_int data type if we are not sure about how much precision is needed in the future. It automatically converts the desired precision at the Run-time. " }, { "code": null, "e": 28758, "s": 28691, "text": "Below implementation of C++ code for finding the factorial of 30. " }, { "code": null, "e": 28762, "s": 28758, "text": "CPP" }, { "code": "// CPP Program to demonstrate Arbitrary precision data type#include <boost/multiprecision/cpp_int.hpp>using namespace boost::multiprecision;using namespace std; cpp_int boost_factorial(int num){ cpp_int fact = 1; for (int i = num; i > 1; --i) fact *= i; return fact;} int main(){ int num = 30; cout << \"Factorial of \" << num << \" = \" << boost_factorial(num); return 0;}", "e": 29165, "s": 28762, "text": null }, { "code": null, "e": 29174, "s": 29165, "text": "Output: " }, { "code": null, "e": 29226, "s": 29174, "text": "Factorial of 30 = 265252859812191058636308480000000" }, { "code": null, "e": 29389, "s": 29226, "text": "3) Multiprecision Float: With Boost Multiprecision float, we can achieve precision up to 50 and 100 decimal with cpp_float_50 and cpp_dec_float_100 respectively. " }, { "code": null, "e": 29517, "s": 29389, "text": "Below is C++ code to calculate the area of a circle with different precision by using a float, decimal, and cpp_float_50 types:" }, { "code": null, "e": 29521, "s": 29517, "text": "CPP" }, { "code": "// CPP Program to demonstrate Boost Multiprecision float#include <boost/math/constants/constants.hpp>#include <boost/multiprecision/cpp_dec_float.hpp>#include <iostream> using boost::multiprecision::cpp_dec_float_50; using namespace std; template <typename T> inline T area_of_a_circle(T r){ // pi represent predefined constant having value // 3.1415926535897932384... using boost::math::constants::pi; return pi<T>() * r * r;} int main(){ float radius_f = 123.0 / 100; float area_f = area_of_a_circle(radius_f); double radius_d = 123.0 / 100; double area_d = area_of_a_circle(radius_d); cpp_dec_float_50 r_mp = 123.0 / 100; cpp_dec_float_50 area_mp = area_of_a_circle(r_mp); // numeric_limits::digits10 represent the number // of decimal digits that can be held of particular // data type without any loss. // Area by using float data type cout << \"Float: \" << setprecision(numeric_limits<float>::digits10) << area_f << endl; // Area by using double data type cout << \"Double: \" << setprecision(numeric_limits<double>::digits10) << area_d << endl; // Area by using Boost Multiprecision cout << \"Boost Multiprecision: \" << setprecision( numeric_limits<cpp_dec_float_50>::digits10) << area_mp << endl; return 0;}", "e": 30862, "s": 29521, "text": null }, { "code": null, "e": 30974, "s": 30862, "text": "Float: 4.75292\nDouble: 4.752915525616\nBoost Multiprecision: 4.7529155256159980531876290929438093413108253981451" }, { "code": null, "e": 31398, "s": 30974, "text": "This article is contributed by Shubham Bansal. 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": 31412, "s": 31398, "text": "anshikajain26" }, { "code": null, "e": 31425, "s": 31412, "text": "cpp-advanced" }, { "code": null, "e": 31435, "s": 31425, "text": "cpp-boost" }, { "code": null, "e": 31439, "s": 31435, "text": "C++" }, { "code": null, "e": 31443, "s": 31439, "text": "CPP" }, { "code": null, "e": 31541, "s": 31443, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31550, "s": 31541, "text": "Comments" }, { "code": null, "e": 31563, "s": 31550, "text": "Old Comments" }, { "code": null, "e": 31581, "s": 31563, "text": "Vector in C++ STL" }, { "code": null, "e": 31627, "s": 31581, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 31650, "s": 31627, "text": "std::sort() in C++ STL" }, { "code": null, "e": 31678, "s": 31650, "text": "Socket Programming in C/C++" }, { "code": null, "e": 31705, "s": 31678, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 31729, "s": 31705, "text": "Virtual Function in C++" }, { "code": null, "e": 31760, "s": 31729, "text": "Templates in C++ with Examples" }, { "code": null, "e": 31788, "s": 31760, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 31813, "s": 31788, "text": "unordered_map in C++ STL" } ]
CUDA - Installation
In this chapter, we will learn how to install CUDA. For installing the CUDA toolkit on Windows, you’ll need − A CUDA enabled Nvidia GPU. A supported version of Microsoft Windows. A supported version of Visual Studio. The latest CUDA toolkit. Note that natively, CUDA allows only 64b applications. That is, you cannot develop 32b CUDA applications natively (exception: they can be developed only on the GeForce series GPUs). 32b applications can be developed on x86_64 using the cross-development capabilities of the CUDA toolkit. For compiling CUDA programs to 32b, follow these steps − Step 1 − Add <installpath>\bin to your path. Step 2 − Add -m32 to your nvcc options. Step 3 − Link with the 32-bit libs in <installpath>\lib (instead of <installpath>\lib64). You can download the latest CUDA toolkit from here. As can be seen from the above tables, support for x86_32 is limited. Presently, only the GeForce series is supported for 32b CUDA applications. If you have a supported version of Windows and Visual Studio, then proceed. Otherwise, first install the required software. Verifying if your system has a CUDA capable GPU − Open a RUN window and run the command − control /name Microsoft.DeviceManager, and verify from the given information. If you do not have a CUDA capable GPU, or a GPU, then halt. In this section, we will see how to install the latest CUDA toolkit. Step 1 − Visit − https://developer.nvidia.com and select the desired operating system. Step 2 − Select the type of installation that you would like to perform. The network installer will initially be a very small executable, which will download the required files when run. The standalone installer will download each required file at once and won’t require an Internet connection later to install. Step 3 − Download the base installer. The CUDA toolkit will also install the required GPU drivers, along with the required libraries and header files to develop CUDA applications. It will also install some sample code to help starters. If you run the executable by double-clicking on it, just follow the on-screen directions and the toolkit will be installed. This is the graphical way of installation, and the downside of this method is that you do not have control on what packages to install. This can be avoided if you install the toolkit using CLI. Here is a list of possible packages that you can control − For example, to install only the compiler and the occupancy calculator, use the following command − <PackageName>.exe -s nvcc_9.1 occupancy_calculator_9.1 Follow these steps to verify the installation − Step 1 − Check the CUDA toolkit version by typing nvcc -V in the command prompt. Step 2 − Run deviceQuery.cu located at: C:\ProgramData\NVIDIA Corporation\CUDA Samples\v9.1\bin\win64\Release to view your GPU card information. The output will look like − Step 3 − Run the bandWidth test located at C:\ProgramData\NVIDIA Corporation\CUDA Samples\v9.1\bin\win64\Release. This ensures that the host and the device are able to communicate properly with each other. The output will look like − If any of the above tests fail, it means the toolkit has not been installed properly. Re-install by following the above instructions. CUDA can be uninstalled without any fuss from the ‘Control Panel’ of Windows. At this point, the CUDA toolkit is installed. You can get started by running the sample programs provided in the toolkit. For doing development work using CUDA on Visual Studio, it needs to be configured. To do this, go to − File → New | Project... NVIDIA → CUDA →. Now, select a template for your CUDA Toolkit version (We are using 9.1 in this tutorial). To specify a custom CUDA Toolkit location, under CUDA C/C++, select Common, and set the CUDA Toolkit Custom Directory. Print Add Notes Bookmark this page
[ { "code": null, "e": 1944, "s": 1892, "text": "In this chapter, we will learn how to install CUDA." }, { "code": null, "e": 2002, "s": 1944, "text": "For installing the CUDA toolkit on Windows, you’ll need −" }, { "code": null, "e": 2029, "s": 2002, "text": "A CUDA enabled Nvidia GPU." }, { "code": null, "e": 2071, "s": 2029, "text": "A supported version of Microsoft Windows." }, { "code": null, "e": 2109, "s": 2071, "text": "A supported version of Visual Studio." }, { "code": null, "e": 2134, "s": 2109, "text": "The latest CUDA toolkit." }, { "code": null, "e": 2479, "s": 2134, "text": "Note that natively, CUDA allows only 64b applications. That is, you cannot develop 32b CUDA applications natively (exception: they can be developed only on the GeForce series GPUs). 32b applications can be developed on x86_64 using the cross-development capabilities of the CUDA toolkit. For compiling CUDA programs to 32b, follow these steps −" }, { "code": null, "e": 2524, "s": 2479, "text": "Step 1 − Add <installpath>\\bin to your path." }, { "code": null, "e": 2564, "s": 2524, "text": "Step 2 − Add -m32 to your nvcc options." }, { "code": null, "e": 2654, "s": 2564, "text": "Step 3 − Link with the 32-bit libs in <installpath>\\lib (instead of <installpath>\\lib64)." }, { "code": null, "e": 2706, "s": 2654, "text": "You can download the latest CUDA toolkit from here." }, { "code": null, "e": 2974, "s": 2706, "text": "As can be seen from the above tables, support for x86_32 is limited. Presently, only the GeForce series is supported for 32b CUDA applications. If you have a supported version of Windows and Visual Studio, then proceed. Otherwise, first install the required software." }, { "code": null, "e": 3203, "s": 2974, "text": "Verifying if your system has a CUDA capable GPU − Open a RUN window and run the command − control /name Microsoft.DeviceManager, and verify from the given information. If you do not have a CUDA capable GPU, or a GPU, then halt." }, { "code": null, "e": 3272, "s": 3203, "text": "In this section, we will see how to install the latest CUDA toolkit." }, { "code": null, "e": 3359, "s": 3272, "text": "Step 1 − Visit − https://developer.nvidia.com and select the desired operating system." }, { "code": null, "e": 3671, "s": 3359, "text": "Step 2 − Select the type of installation that you would like to perform. The network installer will initially be a very small executable, which will download the required files when run. The standalone installer will download each required file at once and won’t require an Internet connection later to install." }, { "code": null, "e": 3709, "s": 3671, "text": "Step 3 − Download the base installer." }, { "code": null, "e": 4284, "s": 3709, "text": "The CUDA toolkit will also install the required GPU drivers, along with the required libraries and header files to develop CUDA applications. It will also install some sample code to help starters. If you run the executable by double-clicking on it, just follow the on-screen directions and the toolkit will be installed. This is the graphical way of installation, and the downside of this method is that you do not have control on what packages to install. This can be avoided if you install the toolkit using CLI. Here is a list of possible packages that you can control −" }, { "code": null, "e": 4384, "s": 4284, "text": "For example, to install only the compiler and the occupancy calculator, use the following command −" }, { "code": null, "e": 4440, "s": 4384, "text": "<PackageName>.exe -s nvcc_9.1 occupancy_calculator_9.1\n" }, { "code": null, "e": 4488, "s": 4440, "text": "Follow these steps to verify the installation −" }, { "code": null, "e": 4569, "s": 4488, "text": "Step 1 − Check the CUDA toolkit version by typing nvcc -V in the command prompt." }, { "code": null, "e": 4742, "s": 4569, "text": "Step 2 − Run deviceQuery.cu located at: C:\\ProgramData\\NVIDIA Corporation\\CUDA Samples\\v9.1\\bin\\win64\\Release to view your GPU card information. The output will look like −" }, { "code": null, "e": 4976, "s": 4742, "text": "Step 3 − Run the bandWidth test located at C:\\ProgramData\\NVIDIA Corporation\\CUDA Samples\\v9.1\\bin\\win64\\Release. This ensures that the host and the device are able to communicate properly with each other. The output will look like −" }, { "code": null, "e": 5110, "s": 4976, "text": "If any of the above tests fail, it means the toolkit has not been installed properly. Re-install by following the above instructions." }, { "code": null, "e": 5188, "s": 5110, "text": "CUDA can be uninstalled without any fuss from the ‘Control Panel’ of Windows." }, { "code": null, "e": 5310, "s": 5188, "text": "At this point, the CUDA toolkit is installed. You can get started by running the sample programs provided in the toolkit." }, { "code": null, "e": 5663, "s": 5310, "text": "For doing development work using CUDA on Visual Studio, it needs to be configured. To do this, go to − File → New | Project... NVIDIA → CUDA →. Now, select a template for your CUDA Toolkit version (We are using 9.1 in this tutorial). To specify a custom CUDA Toolkit location, under CUDA C/C++, select Common, and set the CUDA Toolkit Custom Directory." }, { "code": null, "e": 5670, "s": 5663, "text": " Print" }, { "code": null, "e": 5681, "s": 5670, "text": " Add Notes" } ]
Cordova - Back Button
You will usually want to use Android back button for some app functionality like returning to previous screen. To be able to implement your own functionality, you first need to disable exiting the app when the back button is pressed. document.addEventListener("backbutton", onBackKeyDown, false); function onBackKeyDown(e) { e.preventDefault(); alert('Back Button is Pressed!'); } Now when we press the native Android back button, the alert will appear on the screen instead of exiting the app. This is done by using e.preventDefault(). 45 Lectures 2 hours Skillbakerystudios 16 Lectures 1 hours Nilay Mehta Print Add Notes Bookmark this page
[ { "code": null, "e": 2414, "s": 2180, "text": "You will usually want to use Android back button for some app functionality like returning to previous screen. To be able to implement your own functionality, you first need to disable exiting the app when the back button is pressed." }, { "code": null, "e": 2572, "s": 2414, "text": "document.addEventListener(\"backbutton\", onBackKeyDown, false); \nfunction onBackKeyDown(e) { \n e.preventDefault(); \n alert('Back Button is Pressed!'); \n}" }, { "code": null, "e": 2728, "s": 2572, "text": "Now when we press the native Android back button, the alert will appear on the screen instead of exiting the app. This is done by using e.preventDefault()." }, { "code": null, "e": 2761, "s": 2728, "text": "\n 45 Lectures \n 2 hours \n" }, { "code": null, "e": 2781, "s": 2761, "text": " Skillbakerystudios" }, { "code": null, "e": 2814, "s": 2781, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 2827, "s": 2814, "text": " Nilay Mehta" }, { "code": null, "e": 2834, "s": 2827, "text": " Print" }, { "code": null, "e": 2845, "s": 2834, "text": " Add Notes" } ]
Spring JDBC - Environment Setup
This chapter will guide you on how to prepare a development environment to start your work with Spring Framework. It will also teach you how to set up JDK, Maven and Eclipse on your machine before you set up Spring Framework − You can download the latest version of SDK from Oracle's Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively. If you are running Windows and have installed the JDK in C:\jdk-11.0.11, you would have to put the following line in your C:\autoexec.bat file. set PATH=C:\jdk-11.0.11;%PATH% set JAVA_HOME=C:\jdk-11.0.11 Alternatively, on Windows NT/2000/XP, you will have to right-click on My Computer, select Properties → Advanced → Environment Variables. Then, you will have to update the PATH value and click the OK button. On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk-11.0.11 and you use the C shell, you will have to put the following into your .cshrc file. setenv PATH /usr/local/jdk-11.0.11/bin:$PATH setenv JAVA_HOME /usr/local/jdk-11.0.11 Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, you will have to compile and run a simple program to confirm that the IDE knows where you have installed Java. Otherwise, you will have to carry out a proper setup as given in the document of the IDE. All the examples in this tutorial have been written using Eclipse IDE. So we would suggest you should have the latest version of Eclipse installed on your machine. To install Eclipse IDE, download the latest Eclipse binaries from www.eclipse.org/downloads. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:\eclipse on Windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately. Eclipse can be started by executing the following commands on Windows machine, or you can simply double-click on eclipse.exe %C:\eclipse\eclipse.exe Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine − $/usr/local/eclipse/eclipse After a successful startup, if everything is fine then it should display the following result − Download Maven 3.8.4 from https://maven.apache.org/download.cgi. Extract the archive, to the directory you wish to install Maven 3.8.4. The subdirectory apache-maven-3.8.4 will be created from the archive. Add M2_HOME, M2, MAVEN_OPTS to environment variables. Set the environment variables using system properties. M2_HOME=C:\Program Files\Apache Software Foundation\apache-maven-3.8.4 M2=%M2_HOME%\bin MAVEN_OPTS=-Xms256m -Xmx512m Open command terminal and set environment variables. export M2_HOME=/usr/local/apache-maven/apache-maven-3.8.4 export M2=$M2_HOME/bin export MAVEN_OPTS=-Xms256m -Xmx512m Open command terminal and set environment variables. export M2_HOME=/usr/local/apache-maven/apache-maven-3.8.4 export M2=$M2_HOME/bin export MAVEN_OPTS=-Xms256m -Xmx512m Now append M2 variable to System Path. Now open console and execute the following mvn command. Finally, verify the output of the above commands, which should be as follows − Apache Maven 3.8.4 (9b656c72d54e5bacbed989b64718c159fe39b537) Maven home: C:\Program Files\Apache Software Foundation\apache-maven-3.8.4 Java version: 11.0.11, vendor: Oracle Corporation, runtime: C:\Program Files\Java\jdk11.0.11\ Default locale: en_IN, platform encoding: Cp1252 OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows" Apache Maven 3.8.4 (9b656c72d54e5bacbed989b64718c159fe39b537) Java version: 11.0.11 Java home: /usr/local/java-current/jre Apache Maven 3.8.4 (9b656c72d54e5bacbed989b64718c159fe39b537) Java version: 11.0.11 Java home: /Library/Java/Home/jre Print Add Notes Bookmark this page
[ { "code": null, "e": 2623, "s": 2396, "text": "This chapter will guide you on how to prepare a development environment to start your work with Spring Framework. It will also teach you how to set up JDK, Maven and Eclipse on your machine before you set up Spring Framework −" }, { "code": null, "e": 3019, "s": 2623, "text": "You can download the latest version of SDK from Oracle's Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively." }, { "code": null, "e": 3163, "s": 3019, "text": "If you are running Windows and have installed the JDK in C:\\jdk-11.0.11, you would have to put the following line in your C:\\autoexec.bat file." }, { "code": null, "e": 3226, "s": 3163, "text": "set PATH=C:\\jdk-11.0.11;%PATH% \nset JAVA_HOME=C:\\jdk-11.0.11 \n" }, { "code": null, "e": 3433, "s": 3226, "text": "Alternatively, on Windows NT/2000/XP, you will have to right-click on My Computer, select Properties → Advanced → Environment Variables. Then, you will have to update the PATH value and click the OK button." }, { "code": null, "e": 3598, "s": 3433, "text": "On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk-11.0.11 and you use the C shell, you will have to put the following into your .cshrc file." }, { "code": null, "e": 3685, "s": 3598, "text": "setenv PATH /usr/local/jdk-11.0.11/bin:$PATH \nsetenv JAVA_HOME /usr/local/jdk-11.0.11\n" }, { "code": null, "e": 4022, "s": 3685, "text": "Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, you will have to compile and run a simple program to confirm that the IDE knows where you have installed Java. Otherwise, you will have to carry out a proper setup as given in the document of the IDE." }, { "code": null, "e": 4186, "s": 4022, "text": "All the examples in this tutorial have been written using Eclipse IDE. So we would suggest you should have the latest version of Eclipse installed on your machine." }, { "code": null, "e": 4494, "s": 4186, "text": "To install Eclipse IDE, download the latest Eclipse binaries from www.eclipse.org/downloads. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:\\eclipse on Windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately." }, { "code": null, "e": 4619, "s": 4494, "text": "Eclipse can be started by executing the following commands on Windows machine, or you can simply double-click on eclipse.exe" }, { "code": null, "e": 4645, "s": 4619, "text": "%C:\\eclipse\\eclipse.exe \n" }, { "code": null, "e": 4745, "s": 4645, "text": "Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine −" }, { "code": null, "e": 4774, "s": 4745, "text": "$/usr/local/eclipse/eclipse\n" }, { "code": null, "e": 4870, "s": 4774, "text": "After a successful startup, if everything is fine then it should display the following result −" }, { "code": null, "e": 4935, "s": 4870, "text": "Download Maven 3.8.4 from https://maven.apache.org/download.cgi." }, { "code": null, "e": 5076, "s": 4935, "text": "Extract the archive, to the directory you wish to install Maven 3.8.4. The subdirectory apache-maven-3.8.4 will be created from the archive." }, { "code": null, "e": 5130, "s": 5076, "text": "Add M2_HOME, M2, MAVEN_OPTS to environment variables." }, { "code": null, "e": 5185, "s": 5130, "text": "Set the environment variables using system properties." }, { "code": null, "e": 5302, "s": 5185, "text": "M2_HOME=C:\\Program Files\\Apache Software Foundation\\apache-maven-3.8.4 M2=%M2_HOME%\\bin MAVEN_OPTS=-Xms256m -Xmx512m" }, { "code": null, "e": 5355, "s": 5302, "text": "Open command terminal and set environment variables." }, { "code": null, "e": 5436, "s": 5355, "text": "export M2_HOME=/usr/local/apache-maven/apache-maven-3.8.4 export M2=$M2_HOME/bin" }, { "code": null, "e": 5472, "s": 5436, "text": "export MAVEN_OPTS=-Xms256m -Xmx512m" }, { "code": null, "e": 5525, "s": 5472, "text": "Open command terminal and set environment variables." }, { "code": null, "e": 5583, "s": 5525, "text": "export M2_HOME=/usr/local/apache-maven/apache-maven-3.8.4" }, { "code": null, "e": 5606, "s": 5583, "text": "export M2=$M2_HOME/bin" }, { "code": null, "e": 5642, "s": 5606, "text": "export MAVEN_OPTS=-Xms256m -Xmx512m" }, { "code": null, "e": 5681, "s": 5642, "text": "Now append M2 variable to System Path." }, { "code": null, "e": 5737, "s": 5681, "text": "Now open console and execute the following mvn command." }, { "code": null, "e": 5816, "s": 5737, "text": "Finally, verify the output of the above commands, which should be as follows −" }, { "code": null, "e": 5878, "s": 5816, "text": "Apache Maven 3.8.4 (9b656c72d54e5bacbed989b64718c159fe39b537)" }, { "code": null, "e": 5953, "s": 5878, "text": "Maven home: C:\\Program Files\\Apache Software Foundation\\apache-maven-3.8.4" }, { "code": null, "e": 6047, "s": 5953, "text": "Java version: 11.0.11, vendor: Oracle Corporation, runtime: C:\\Program Files\\Java\\jdk11.0.11\\" }, { "code": null, "e": 6096, "s": 6047, "text": "Default locale: en_IN, platform encoding: Cp1252" }, { "code": null, "e": 6169, "s": 6096, "text": "OS name: \"windows 10\", version: \"10.0\", arch: \"amd64\", family: \"windows\"" }, { "code": null, "e": 6231, "s": 6169, "text": "Apache Maven 3.8.4 (9b656c72d54e5bacbed989b64718c159fe39b537)" }, { "code": null, "e": 6253, "s": 6231, "text": "Java version: 11.0.11" }, { "code": null, "e": 6292, "s": 6253, "text": "Java home: /usr/local/java-current/jre" }, { "code": null, "e": 6354, "s": 6292, "text": "Apache Maven 3.8.4 (9b656c72d54e5bacbed989b64718c159fe39b537)" }, { "code": null, "e": 6376, "s": 6354, "text": "Java version: 11.0.11" }, { "code": null, "e": 6410, "s": 6376, "text": "Java home: /Library/Java/Home/jre" }, { "code": null, "e": 6417, "s": 6410, "text": " Print" }, { "code": null, "e": 6428, "s": 6417, "text": " Add Notes" } ]
How to adjust transparency (alpha) in Seaborn pairplot using Matplotlib?
To adjust transparency, i.e., aplha in Seaborn pairplot, we can change the value of alpha. Create a dataframe using Pandas with two keys, col1 and col2. Create a dataframe using Pandas with two keys, col1 and col2. Initialize the variable, alpha, for transparency. Initialize the variable, alpha, for transparency. Use pairplot() method to plot pairwise relationships in a dataset. Use df (from step 1), kind="scatter", and set the plot size, edgecolor, facecolor, linewidth and alpha vaues in the arguments. Use pairplot() method to plot pairwise relationships in a dataset. Use df (from step 1), kind="scatter", and set the plot size, edgecolor, facecolor, linewidth and alpha vaues in the arguments. To display the figure, use show() method. To display the figure, use show() method. import pandas as pd import seaborn as sns from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True df = pd.DataFrame({"col1": [1, 3, 5, 7, 1], "col2": [1, 5, 7, 9, 1]}) alpha = 0.75 sns.pairplot(df, kind="scatter", plot_kws=dict(s=100, edgecolor="red", fc='green', linewidth=2.5, alpha=alpha)) plt.show()
[ { "code": null, "e": 1153, "s": 1062, "text": "To adjust transparency, i.e., aplha in Seaborn pairplot, we can change the value of alpha." }, { "code": null, "e": 1215, "s": 1153, "text": "Create a dataframe using Pandas with two keys, col1 and col2." }, { "code": null, "e": 1277, "s": 1215, "text": "Create a dataframe using Pandas with two keys, col1 and col2." }, { "code": null, "e": 1327, "s": 1277, "text": "Initialize the variable, alpha, for transparency." }, { "code": null, "e": 1377, "s": 1327, "text": "Initialize the variable, alpha, for transparency." }, { "code": null, "e": 1571, "s": 1377, "text": "Use pairplot() method to plot pairwise relationships in a dataset. Use df (from step 1), kind=\"scatter\", and set the plot size, edgecolor, facecolor, linewidth and alpha vaues in the arguments." }, { "code": null, "e": 1765, "s": 1571, "text": "Use pairplot() method to plot pairwise relationships in a dataset. Use df (from step 1), kind=\"scatter\", and set the plot size, edgecolor, facecolor, linewidth and alpha vaues in the arguments." }, { "code": null, "e": 1807, "s": 1765, "text": "To display the figure, use show() method." }, { "code": null, "e": 1849, "s": 1807, "text": "To display the figure, use show() method." }, { "code": null, "e": 2224, "s": 1849, "text": "import pandas as pd\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\ndf = pd.DataFrame({\"col1\": [1, 3, 5, 7, 1], \"col2\": [1, 5, 7, 9, 1]})\nalpha = 0.75\nsns.pairplot(df, kind=\"scatter\", plot_kws=dict(s=100, edgecolor=\"red\",\n fc='green', linewidth=2.5, alpha=alpha))\nplt.show()" } ]
C# | Dictionary.Keys Property - GeeksforGeeks
03 Apr, 2019 This property is used to get a collection containing the keys in the Dictionary. Syntax: public System.Collections.Generic.Dictionary<TKey, TValue>.KeyCollection Keys { get; } Return Value : It returns a collection containing the keys in the Dictionary. Below are the programs to illustrate the use of above-discussed property: Example 1: // C# code to get the keys// in the Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary of // strings, with string keys. Dictionary<string, string> myDict = new Dictionary<string, string>(); // Adding key/value pairs in myDict myDict.Add("Australia", "Canberra"); myDict.Add("Belgium", "Brussels"); myDict.Add("Netherlands", "Amsterdam"); myDict.Add("China", "Beijing"); myDict.Add("Russia", "Moscow"); myDict.Add("India", "New Delhi"); // To get count of key/value pairs in myDict Console.WriteLine("Total key/value pairs"+ " in myDict are : " + myDict.Count); // To get the keys alone, // use the Keys property. Dictionary<string, string>.KeyCollection keyColl = myDict.Keys; // The elements of the KeyCollection // are strongly typed with the type // that was specified for dictionary // keys foreach(string s in keyColl) { Console.WriteLine("Key = {0}", s); } }} Total key/value pairs in myDict are : 6 Key = Australia Key = Belgium Key = Netherlands Key = China Key = Russia Key = India Example 2: // C# code to get the keys in the Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary of // strings, with string keys. Dictionary<int, int> myDict = new Dictionary<int, int>(); // Adding key/value pairs in myDict myDict.Add(9, 8); myDict.Add(3, 4); myDict.Add(4, 7); myDict.Add(1, 7); // To get count of key/value pairs in myDict Console.WriteLine("Total key/value pairs "+ "in myDict are : " + myDict.Count); // To get the keys alone, // use the Keys property. Dictionary<int, int>.KeyCollection keyColl = myDict.Keys; // The elements of the KeyCollection // are strongly typed with the type // that was specified for dictionary keys. foreach(int s in keyColl) { Console.WriteLine("Key = {0}", s); } }} Total key/value pairs in myDict are : 4 Key = 9 Key = 3 Key = 4 Key = 1 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.keys?view=netframework-4.7.2 CSharp Dictionary Class CSharp-Generic-Namespace C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 50 C# Interview Questions & Answers Extension Method in C# HashSet in C# with Examples Partial Classes in C# C# | Inheritance Convert String to Character Array in C# Linked List Implementation in C# C# | How to insert an element in an Array? C# | List Class Difference between Hashtable and Dictionary in C#
[ { "code": null, "e": 23911, "s": 23883, "text": "\n03 Apr, 2019" }, { "code": null, "e": 23992, "s": 23911, "text": "This property is used to get a collection containing the keys in the Dictionary." }, { "code": null, "e": 24000, "s": 23992, "text": "Syntax:" }, { "code": null, "e": 24087, "s": 24000, "text": "public System.Collections.Generic.Dictionary<TKey, TValue>.KeyCollection Keys { get; }" }, { "code": null, "e": 24165, "s": 24087, "text": "Return Value : It returns a collection containing the keys in the Dictionary." }, { "code": null, "e": 24239, "s": 24165, "text": "Below are the programs to illustrate the use of above-discussed property:" }, { "code": null, "e": 24250, "s": 24239, "text": "Example 1:" }, { "code": "// C# code to get the keys// in the Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary of // strings, with string keys. Dictionary<string, string> myDict = new Dictionary<string, string>(); // Adding key/value pairs in myDict myDict.Add(\"Australia\", \"Canberra\"); myDict.Add(\"Belgium\", \"Brussels\"); myDict.Add(\"Netherlands\", \"Amsterdam\"); myDict.Add(\"China\", \"Beijing\"); myDict.Add(\"Russia\", \"Moscow\"); myDict.Add(\"India\", \"New Delhi\"); // To get count of key/value pairs in myDict Console.WriteLine(\"Total key/value pairs\"+ \" in myDict are : \" + myDict.Count); // To get the keys alone, // use the Keys property. Dictionary<string, string>.KeyCollection keyColl = myDict.Keys; // The elements of the KeyCollection // are strongly typed with the type // that was specified for dictionary // keys foreach(string s in keyColl) { Console.WriteLine(\"Key = {0}\", s); } }}", "e": 25467, "s": 24250, "text": null }, { "code": null, "e": 25593, "s": 25467, "text": "Total key/value pairs in myDict are : 6\nKey = Australia\nKey = Belgium\nKey = Netherlands\nKey = China\nKey = Russia\nKey = India\n" }, { "code": null, "e": 25604, "s": 25593, "text": "Example 2:" }, { "code": "// C# code to get the keys in the Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary of // strings, with string keys. Dictionary<int, int> myDict = new Dictionary<int, int>(); // Adding key/value pairs in myDict myDict.Add(9, 8); myDict.Add(3, 4); myDict.Add(4, 7); myDict.Add(1, 7); // To get count of key/value pairs in myDict Console.WriteLine(\"Total key/value pairs \"+ \"in myDict are : \" + myDict.Count); // To get the keys alone, // use the Keys property. Dictionary<int, int>.KeyCollection keyColl = myDict.Keys; // The elements of the KeyCollection // are strongly typed with the type // that was specified for dictionary keys. foreach(int s in keyColl) { Console.WriteLine(\"Key = {0}\", s); } }}", "e": 26630, "s": 25604, "text": null }, { "code": null, "e": 26703, "s": 26630, "text": "Total key/value pairs in myDict are : 4\nKey = 9\nKey = 3\nKey = 4\nKey = 1\n" }, { "code": null, "e": 26714, "s": 26703, "text": "Reference:" }, { "code": null, "e": 26827, "s": 26714, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.keys?view=netframework-4.7.2" }, { "code": null, "e": 26851, "s": 26827, "text": "CSharp Dictionary Class" }, { "code": null, "e": 26876, "s": 26851, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 26879, "s": 26876, "text": "C#" }, { "code": null, "e": 26977, "s": 26879, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26986, "s": 26977, "text": "Comments" }, { "code": null, "e": 26999, "s": 26986, "text": "Old Comments" }, { "code": null, "e": 27039, "s": 26999, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 27062, "s": 27039, "text": "Extension Method in C#" }, { "code": null, "e": 27090, "s": 27062, "text": "HashSet in C# with Examples" }, { "code": null, "e": 27112, "s": 27090, "text": "Partial Classes in C#" }, { "code": null, "e": 27129, "s": 27112, "text": "C# | Inheritance" }, { "code": null, "e": 27169, "s": 27129, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 27202, "s": 27169, "text": "Linked List Implementation in C#" }, { "code": null, "e": 27245, "s": 27202, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 27261, "s": 27245, "text": "C# | List Class" } ]
PHP mysqli_field_count() Function
The mysqli_field_count() function is used to get the number of fields (columns) in the result set of the recently executed MySQL query . mysqli_field_count($con) con(Mandatory) This is an object representing a connection to MySQL Server. PHP mysqli_field_count() function returns an integer value indicating the number of columns in the result set of the last query. If the last query is not a SELECT query (no result set) this function returns 0. This function was first introduced in PHP Version 5 and works works in all the later versions. Following example demonstrates the usage of the mysqli_field_count() function (in procedural style) − <?php //Creating a connection $con = mysqli_connect("localhost", "root", "password", "mydb"); //Query to retrieve all the records of the employee table mysqli_query($con, "Select * from employee"); //Field Count $count = mysqli_field_count($con); print("Field Count: ".$count); //Closing the connection mysqli_close($con); ?> This will produce following result − Field Count: 6 In object oriented style the syntax of this function is $con -> field_count;, Where, $con is the connection object − <?php //Creating a connection $con = new mysqli("localhost", "root", "password", "mydb"); //Query to retrieve all the records of the employee table $con -> query("Select FIRST_NAME, LAST_NAME, AGE from employee"); //Field Count $count = $con->field_count; print("Field Count: ".$count); //Closing the connection $con -> close(); ?> This will produce following result − Field Count: 3 Following is another example of the mysqli_field_count() function <?php //Creating a connection $con = mysqli_connect("localhost", "root", "password", "mydb"); print("Field Count: ".mysqli_field_count($con)."\n"); //INSERT Query mysqli_query($con, "INSERT INTO employee (FIRST_NAME, AGE) VALUES (Archana, 25), (Bhuvan, 29)"); print("Field Count: ".mysqli_field_count($con)); //Closing the connection mysqli_close($con); ?> This will produce following result − Field Count: 0 Field Count: 0 <?php $connection_mysql = mysqli_connect("localhost","root", "password", "mydb"); if (mysqli_connect_errno($connection_mysql)){ echo "Failed to connect to MySQL: " . mysqli_connect_error(); } mysqli_query($connection_mysql,"SELECT * FROM employee"); print(mysqli_field_count($connection_mysql)); mysqli_close($connection_mysql); ?> This will produce following result − 6 45 Lectures 9 hours Malhar Lathkar 34 Lectures 4 hours Syed Raza 84 Lectures 5.5 hours Frahaan Hussain 17 Lectures 1 hours Nivedita Jain 100 Lectures 34 hours Azaz Patel 43 Lectures 5.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2894, "s": 2757, "text": "The mysqli_field_count() function is used to get the number of fields (columns) in the result set of the recently executed MySQL query ." }, { "code": null, "e": 2920, "s": 2894, "text": "mysqli_field_count($con)\n" }, { "code": null, "e": 2935, "s": 2920, "text": "con(Mandatory)" }, { "code": null, "e": 2996, "s": 2935, "text": "This is an object representing a connection to MySQL Server." }, { "code": null, "e": 3206, "s": 2996, "text": "PHP mysqli_field_count() function returns an integer value indicating the number of columns in the result set of the last query. If the last query is not a SELECT query (no result set) this function returns 0." }, { "code": null, "e": 3301, "s": 3206, "text": "This function was first introduced in PHP Version 5 and works works in all the later versions." }, { "code": null, "e": 3403, "s": 3301, "text": "Following example demonstrates the usage of the mysqli_field_count() function (in procedural style) −" }, { "code": null, "e": 3759, "s": 3403, "text": "<?php\n //Creating a connection\n $con = mysqli_connect(\"localhost\", \"root\", \"password\", \"mydb\");\n\n //Query to retrieve all the records of the employee table\n mysqli_query($con, \"Select * from employee\");\n\n //Field Count\n $count = mysqli_field_count($con);\n print(\"Field Count: \".$count);\n\n //Closing the connection\n mysqli_close($con);\n?>" }, { "code": null, "e": 3796, "s": 3759, "text": "This will produce following result −" }, { "code": null, "e": 3812, "s": 3796, "text": "Field Count: 6\n" }, { "code": null, "e": 3929, "s": 3812, "text": "In object oriented style the syntax of this function is $con -> field_count;, Where, $con is the connection object −" }, { "code": null, "e": 4291, "s": 3929, "text": "<?php\n //Creating a connection\n $con = new mysqli(\"localhost\", \"root\", \"password\", \"mydb\");\n\n //Query to retrieve all the records of the employee table\n $con -> query(\"Select FIRST_NAME, LAST_NAME, AGE from employee\");\n\n //Field Count\n $count = $con->field_count;\n print(\"Field Count: \".$count);\n\n //Closing the connection\n $con -> close();\n?>" }, { "code": null, "e": 4328, "s": 4291, "text": "This will produce following result −" }, { "code": null, "e": 4344, "s": 4328, "text": "Field Count: 3\n" }, { "code": null, "e": 4410, "s": 4344, "text": "Following is another example of the mysqli_field_count() function" }, { "code": null, "e": 4796, "s": 4410, "text": "<?php\n //Creating a connection\n $con = mysqli_connect(\"localhost\", \"root\", \"password\", \"mydb\");\n\n print(\"Field Count: \".mysqli_field_count($con).\"\\n\");\n\n //INSERT Query\n mysqli_query($con, \"INSERT INTO employee (FIRST_NAME, AGE) VALUES (Archana, 25), (Bhuvan, 29)\");\n print(\"Field Count: \".mysqli_field_count($con));\n \n //Closing the connection\n mysqli_close($con);\n?>" }, { "code": null, "e": 4833, "s": 4796, "text": "This will produce following result −" }, { "code": null, "e": 4864, "s": 4833, "text": "Field Count: 0\nField Count: 0\n" }, { "code": null, "e": 5232, "s": 4864, "text": "<?php\n $connection_mysql = mysqli_connect(\"localhost\",\"root\", \"password\", \"mydb\");\n \n if (mysqli_connect_errno($connection_mysql)){\n echo \"Failed to connect to MySQL: \" . mysqli_connect_error();\n }\n \n mysqli_query($connection_mysql,\"SELECT * FROM employee\");\n print(mysqli_field_count($connection_mysql));\n \n mysqli_close($connection_mysql);\n?>" }, { "code": null, "e": 5269, "s": 5232, "text": "This will produce following result −" }, { "code": null, "e": 5272, "s": 5269, "text": "6\n" }, { "code": null, "e": 5305, "s": 5272, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 5321, "s": 5305, "text": " Malhar Lathkar" }, { "code": null, "e": 5354, "s": 5321, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 5365, "s": 5354, "text": " Syed Raza" }, { "code": null, "e": 5400, "s": 5365, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5417, "s": 5400, "text": " Frahaan Hussain" }, { "code": null, "e": 5450, "s": 5417, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 5465, "s": 5450, "text": " Nivedita Jain" }, { "code": null, "e": 5500, "s": 5465, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 5512, "s": 5500, "text": " Azaz Patel" }, { "code": null, "e": 5547, "s": 5512, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5575, "s": 5547, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 5582, "s": 5575, "text": " Print" }, { "code": null, "e": 5593, "s": 5582, "text": " Add Notes" } ]