title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Count ways to N'th Stair(Order does not matter) | Practice | GeeksforGeeks
There are N stairs, and a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time. Count the number of ways, the person can reach the top (order does not matter). Note: Order does not matter means for n = 4 {1 2 1},{2 1 1},{1 1 2} are considered same. Example 1: Input: N = 4 Output: 3 Explanation: Three ways to reach at 4th stair. They are {1, 1, 1, 1}, {1, 1, 2}, {2, 2}. Example 2: Input: N = 5 Output: 3 Explanation: Three ways to reach at 5th stair. They are {1, 1, 1, 1, 1}, {1, 1, 2, 1} and {1, 2, 2}. Your Task: You don't need to read or print anyhting. Your task is to complete the function nthStair() which takes N as input parameter and returns the total number of ways to reach at Nth stair. Expected Time Complexity: O(N) Expected Space Complexity: O(N) Constraints: 1 ≤ N ≤ 104 +1 syedmohdgulambaquer1 week ago int dp[10001][3]; int solve(int arr[], int n, int i) { if(n == 0) { return 1; } if(i == 0) { return 0; } if(dp[n][i] != -1) { return dp[n][i]; } if(n >= arr[i-1]) { return dp[n][i] = solve(arr, n - arr[i-1] , i) + solve(arr, n , i-1); } return dp[n][i] = solve(arr, n , i-1); } int nthStair(int n) { memset(dp, -1, sizeof(dp)); int arr[2] = {1,2}; return solve(arr, n, 2); } 0 jintan2 weeks ago int nthStair(int n){ vector<int> v(n+1, 1); for(int i = 2; i<n+1; i++){ v[i] += v[i-2]; } return v[n]; } +2 user_692 months ago DP ki jrurat h kya h isme :) int nthStair(int n){ if(n==0) return 1; if(n%2==0) return 1+nthStair(n-1); else return nthStair(n-1); } +2 kashyapjhon3 months ago C++ Solution Time=(0.01/1.12) EASY: int nthStair(int n){ // Code here vector<int> dp(n+1,0); dp[1]=1; dp[2]=2; for(int i=3;i<=n;i++){ dp[i]=dp[i-2]+1; } return dp[n]; } +1 abhishekvicky123454 months ago /*Java 1 line code*/ class Solution{ public long nthStair(int n) { return n/2+1; }} 0 himanshukug19cs5 months ago java sol long[] dp = new long[n+1]; dp[0]=0; dp[1]=1; if(n>1){ dp[2]=2; for(int i=3;i<=n;i++){ dp[i]=dp[i-2]+1; }} return dp[n]; } +4 utkarsh51k5 months ago Fir ganja phook k difficulty set kiya gya hai 0 goyalgarvit809 This comment was deleted. +1 2001shivank7 months ago hey, Kindly understand that logic of “return (n/2)+1” is correct. But Why???..............see there is 1 way of climbing 1 step one by 1 , while n/2 is for when the person climbs 2 steps once and rest all as 1, 2 steps twice and then rest all as 1. Example for understanding n/2-----→ n=5 --→ {2,1,1}, {2,2,1}...........................n=6-→ {2,2,2},{2,2,1,1},{2,1,1,1,1} +1 yashkatiyar6307 months ago simple solution int nthStair(int n){ return (n/2)+1; } using recursion+memorization class Solution{ public: int dp[10001][3]; Solution(){memset(dp,-1,sizeof(dp));} int knapSack(int n,int val[],int i) { if(n==0)return 1; if(n<0||i<1)return 0; if(dp[n][i]!=-1)return dp[n][i]; else return dp[n][i]=knapSack(n-val[i-1],val,i)+knapSack(n,val,i-1); } int nthStair(int n){ int arr[2]={1,2}; return knapSack(n,arr,2); } }; We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
[ { "code": null, "e": 457, "s": 238, "text": "There are N stairs, and a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time. Count the number of ways, the person can reach the top (order does not matter)." }, { "code": null, "e": 548, "s": 457, "text": "Note:\nOrder does not matter means for n = 4 {1 2 1},{2 1 1},{1 1 2} are considered same.\n " }, { "code": null, "e": 559, "s": 548, "text": "Example 1:" }, { "code": null, "e": 672, "s": 559, "text": "Input: N = 4\nOutput: 3\nExplanation: Three ways to reach at 4th stair.\nThey are {1, 1, 1, 1}, {1, 1, 2}, {2, 2}.\n" }, { "code": null, "e": 683, "s": 672, "text": "Example 2:" }, { "code": null, "e": 808, "s": 683, "text": "Input: N = 5\nOutput: 3\nExplanation: Three ways to reach at 5th stair.\nThey are {1, 1, 1, 1, 1}, {1, 1, 2, 1} and\n{1, 2, 2}.\n" }, { "code": null, "e": 1006, "s": 808, "text": "\nYour Task:\nYou don't need to read or print anyhting. Your task is to complete the function nthStair() which takes N as input parameter and returns the total number of ways to reach at Nth stair.\n " }, { "code": null, "e": 1071, "s": 1006, "text": "Expected Time Complexity: O(N)\nExpected Space Complexity: O(N)\n " }, { "code": null, "e": 1096, "s": 1071, "text": "Constraints:\n1 ≤ N ≤ 104" }, { "code": null, "e": 1099, "s": 1096, "text": "+1" }, { "code": null, "e": 1129, "s": 1099, "text": "syedmohdgulambaquer1 week ago" }, { "code": null, "e": 1750, "s": 1129, "text": "int dp[10001][3];\n\t int solve(int arr[], int n, int i) {\n\t \n\t if(n == 0) {\n\t return 1;\n\t }\n\t \n\t if(i == 0) {\n\t return 0;\n\t }\n\t \n\t if(dp[n][i] != -1) {\n\t return dp[n][i];\n\t }\n\t \n\t if(n >= arr[i-1]) {\n\t return dp[n][i] = solve(arr, n - arr[i-1] , i) + solve(arr, n , i-1);\n\t } \n\t \n\t return dp[n][i] = solve(arr, n , i-1);\n\t \n\t \n\t }\n\t\tint nthStair(int n) {\n\t\t \n\t\t memset(dp, -1, sizeof(dp));\n\t\t int arr[2] = {1,2};\n\t\t \n\t\t return solve(arr, n, 2);\n\t\t}" }, { "code": null, "e": 1752, "s": 1750, "text": "0" }, { "code": null, "e": 1770, "s": 1752, "text": "jintan2 weeks ago" }, { "code": null, "e": 1905, "s": 1770, "text": "int nthStair(int n){\n vector<int> v(n+1, 1);\n for(int i = 2; i<n+1; i++){\n v[i] += v[i-2];\n }\n return v[n];\n }" }, { "code": null, "e": 1910, "s": 1907, "text": "+2" }, { "code": null, "e": 1930, "s": 1910, "text": "user_692 months ago" }, { "code": null, "e": 1959, "s": 1930, "text": "DP ki jrurat h kya h isme :)" }, { "code": null, "e": 2115, "s": 1959, "text": "\t\tint nthStair(int n){\n\t\t if(n==0)\n\t\t return 1;\n\t\t if(n%2==0)\n\t\t return 1+nthStair(n-1);\n\t\t else\n\t\t return nthStair(n-1);\n\t\t}" }, { "code": null, "e": 2118, "s": 2115, "text": "+2" }, { "code": null, "e": 2142, "s": 2118, "text": "kashyapjhon3 months ago" }, { "code": null, "e": 2178, "s": 2142, "text": "C++ Solution Time=(0.01/1.12) EASY:" }, { "code": null, "e": 2348, "s": 2178, "text": "int nthStair(int n){ // Code here vector<int> dp(n+1,0); dp[1]=1; dp[2]=2; for(int i=3;i<=n;i++){ dp[i]=dp[i-2]+1; } return dp[n]; }" }, { "code": null, "e": 2351, "s": 2348, "text": "+1" }, { "code": null, "e": 2382, "s": 2351, "text": "abhishekvicky123454 months ago" }, { "code": null, "e": 2403, "s": 2382, "text": "/*Java 1 line code*/" }, { "code": null, "e": 2478, "s": 2403, "text": "class Solution{ public long nthStair(int n) { return n/2+1; }}" }, { "code": null, "e": 2480, "s": 2478, "text": "0" }, { "code": null, "e": 2508, "s": 2480, "text": "himanshukug19cs5 months ago" }, { "code": null, "e": 2517, "s": 2508, "text": "java sol" }, { "code": null, "e": 2706, "s": 2519, "text": " long[] dp = new long[n+1]; dp[0]=0; dp[1]=1; if(n>1){ dp[2]=2; for(int i=3;i<=n;i++){ dp[i]=dp[i-2]+1; }} return dp[n]; }" }, { "code": null, "e": 2709, "s": 2706, "text": "+4" }, { "code": null, "e": 2732, "s": 2709, "text": "utkarsh51k5 months ago" }, { "code": null, "e": 2778, "s": 2732, "text": "Fir ganja phook k difficulty set kiya gya hai" }, { "code": null, "e": 2780, "s": 2778, "text": "0" }, { "code": null, "e": 2795, "s": 2780, "text": "goyalgarvit809" }, { "code": null, "e": 2821, "s": 2795, "text": "This comment was deleted." }, { "code": null, "e": 2824, "s": 2821, "text": "+1" }, { "code": null, "e": 2848, "s": 2824, "text": "2001shivank7 months ago" }, { "code": null, "e": 3222, "s": 2848, "text": "hey, Kindly understand that logic of “return (n/2)+1” is correct. But Why???..............see there is 1 way of climbing 1 step one by 1 , while n/2 is for when the person climbs 2 steps once and rest all as 1, 2 steps twice and then rest all as 1. Example for understanding n/2-----→ n=5 --→ {2,1,1}, {2,2,1}...........................n=6-→ {2,2,2},{2,2,1,1},{2,1,1,1,1} " }, { "code": null, "e": 3225, "s": 3222, "text": "+1" }, { "code": null, "e": 3252, "s": 3225, "text": "yashkatiyar6307 months ago" }, { "code": null, "e": 3268, "s": 3252, "text": "simple solution" }, { "code": null, "e": 3315, "s": 3268, "text": "int nthStair(int n){\n\t\t return (n/2)+1;\n\t\t}" }, { "code": null, "e": 3344, "s": 3315, "text": "using recursion+memorization" }, { "code": null, "e": 3738, "s": 3344, "text": "class Solution{\n\tpublic:\n\tint dp[10001][3];\n Solution(){memset(dp,-1,sizeof(dp));} \n int knapSack(int n,int val[],int i)\n {\n if(n==0)return 1;\n if(n<0||i<1)return 0;\n if(dp[n][i]!=-1)return dp[n][i];\n else return dp[n][i]=knapSack(n-val[i-1],val,i)+knapSack(n,val,i-1);\n }\n\tint nthStair(int n){\n\t int arr[2]={1,2};\n\t return knapSack(n,arr,2);\n\t}\n};" }, { "code": null, "e": 3888, "s": 3742, "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": 3924, "s": 3888, "text": " Login to access your submissions. " }, { "code": null, "e": 3934, "s": 3924, "text": "\nProblem\n" }, { "code": null, "e": 3944, "s": 3934, "text": "\nContest\n" }, { "code": null, "e": 4007, "s": 3944, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4192, "s": 4007, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 4476, "s": 4192, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 4622, "s": 4476, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 4699, "s": 4622, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 4740, "s": 4699, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 4768, "s": 4740, "text": "Disable browser extensions." }, { "code": null, "e": 4839, "s": 4768, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 5026, "s": 4839, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
Java notify() Method in Threads Synchronization with Examples
17 Jun, 2021 The notify() method is defined in the Object class, which is Java’s top-level class. It’s used to wake up only one thread that’s waiting for an object, and that thread then begins execution. The thread class notify() method is used to wake up a single thread. If multiple threads are waiting for notification, and we use the notify() method, only one thread will receive the notification, and the others will have to wait for more. This method does not return any value. It is used with the wait() method, in order to communicate between the threads as a thread that goes into waiting for state by wait() method, will be there until any other thread calls either notify() or notifyAll() method. Syntax: public final void notify() ; Implementation: The synchronized keyword is used for exclusive accessing. wait() instructs the calling thread to shut down the monitor and sleep until another thread enters the monitor and calls notify(). notify() wakes up the first thread that called wait() on the same object. Example Java // Java program to Illustrate notify() method in Thread// Synchronization. // Importing required classesimport java.io.*;import java.util.*; // Class 1// Thread1// Helper class extending Thread classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating object(thread) of class 2 Thread2 objB = new Thread2(); // Starting the thread objB.start(); synchronized (objB) { // Try block to check for exceptions try { // Display message only System.out.println( "Waiting for Thread 2 to complete..."); // wait() method for thread to be in waiting // state objB.wait(); } // Catch block to handle the exceptions catch (InterruptedException e) { // Print the exception along with line // number using printStackTrace() method e.printStackTrace(); } // Print and display the total threads on the // console System.out.println("Total is: " + objB.total); } }}// Class 2// Thread2// Helper class extending Thread classclass Thread2 extends Thread { int total; // run() method which is called automatically when // start() is initiated for the same // @Override public void run() { synchronized (this) { // iterating over using the for loo for (int i = 0; i < 10; i++) { total += i; } // Waking up the thread in waiting state // using notify() method notify(); } }} Waiting for Thread 2 to complete... Total is: 45 Picked Java 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 Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 53, "s": 25, "text": "\n17 Jun, 2021" }, { "code": null, "e": 524, "s": 53, "text": "The notify() method is defined in the Object class, which is Java’s top-level class. It’s used to wake up only one thread that’s waiting for an object, and that thread then begins execution. The thread class notify() method is used to wake up a single thread. If multiple threads are waiting for notification, and we use the notify() method, only one thread will receive the notification, and the others will have to wait for more. This method does not return any value." }, { "code": null, "e": 748, "s": 524, "text": "It is used with the wait() method, in order to communicate between the threads as a thread that goes into waiting for state by wait() method, will be there until any other thread calls either notify() or notifyAll() method." }, { "code": null, "e": 756, "s": 748, "text": "Syntax:" }, { "code": null, "e": 786, "s": 756, "text": "public final void notify() ; " }, { "code": null, "e": 802, "s": 786, "text": "Implementation:" }, { "code": null, "e": 860, "s": 802, "text": "The synchronized keyword is used for exclusive accessing." }, { "code": null, "e": 991, "s": 860, "text": "wait() instructs the calling thread to shut down the monitor and sleep until another thread enters the monitor and calls notify()." }, { "code": null, "e": 1065, "s": 991, "text": "notify() wakes up the first thread that called wait() on the same object." }, { "code": null, "e": 1073, "s": 1065, "text": "Example" }, { "code": null, "e": 1078, "s": 1073, "text": "Java" }, { "code": "// Java program to Illustrate notify() method in Thread// Synchronization. // Importing required classesimport java.io.*;import java.util.*; // Class 1// Thread1// Helper class extending Thread classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating object(thread) of class 2 Thread2 objB = new Thread2(); // Starting the thread objB.start(); synchronized (objB) { // Try block to check for exceptions try { // Display message only System.out.println( \"Waiting for Thread 2 to complete...\"); // wait() method for thread to be in waiting // state objB.wait(); } // Catch block to handle the exceptions catch (InterruptedException e) { // Print the exception along with line // number using printStackTrace() method e.printStackTrace(); } // Print and display the total threads on the // console System.out.println(\"Total is: \" + objB.total); } }}// Class 2// Thread2// Helper class extending Thread classclass Thread2 extends Thread { int total; // run() method which is called automatically when // start() is initiated for the same // @Override public void run() { synchronized (this) { // iterating over using the for loo for (int i = 0; i < 10; i++) { total += i; } // Waking up the thread in waiting state // using notify() method notify(); } }}", "e": 2828, "s": 1078, "text": null }, { "code": null, "e": 2877, "s": 2828, "text": "Waiting for Thread 2 to complete...\nTotal is: 45" }, { "code": null, "e": 2884, "s": 2877, "text": "Picked" }, { "code": null, "e": 2889, "s": 2884, "text": "Java" }, { "code": null, "e": 2894, "s": 2889, "text": "Java" }, { "code": null, "e": 2992, "s": 2894, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3007, "s": 2992, "text": "Stream In Java" }, { "code": null, "e": 3028, "s": 3007, "text": "Introduction to Java" }, { "code": null, "e": 3049, "s": 3028, "text": "Constructors in Java" }, { "code": null, "e": 3068, "s": 3049, "text": "Exceptions in Java" }, { "code": null, "e": 3085, "s": 3068, "text": "Generics in Java" }, { "code": null, "e": 3115, "s": 3085, "text": "Functional Interfaces in Java" }, { "code": null, "e": 3141, "s": 3115, "text": "Java Programming Examples" }, { "code": null, "e": 3157, "s": 3141, "text": "Strings in Java" }, { "code": null, "e": 3194, "s": 3157, "text": "Differences between JDK, JRE and JVM" } ]
PHP | log(), log10() Functions
30 Oct, 2020 Logarithm is the counter operation to exponentiation. The logarithm of a number is in fact the exponent to which the other number i.e. the base must be raised to produce that number. If the Euler’s Number ‘e’ is used as the base of any logarithmic operation it is then known as Natural Logarithmic Operation, another popular logarithmic operation is to take 10 as the base. In PHP, the log() function is used to calculate the natural logarithm of a number if no base is specified and the log10() function calculates the base 10 logarithm of a number. log() Function Syntax: float log ($arg, $base) Parameters: The function can accept at most two parameters as follows: $arg: This is a required parameter that refers to the number of whose the logarithm is to be calculated. $base: This is an optional parameter that refers to the base of the logarithmic operation. If not given, M_E i.e. the Euler’s Number is used as Base to calculate the Natural Logarithm. Return Type: This function returns the result of the logarithmic operation. Examples: Input : $arg = M_E * M_E; Output : 2 Input : $arg = 1024; $base = 2; Output : 10 Below program illustrates the working of log() in PHP: <?php// PHP code to illustrate the working of log() Function $arg = 81;$base = 3;for(;$base<=$arg;$base*=$base) echo 'log('.$arg.', '.$base.') = '.log($arg, $base)."\n";?> Output: log(81, 3) = 4 log(81, 9) = 2 log(81, 81) = 1 log10() Function Syntax: float log10 ($arg) Parameters: The function accepts a single parameter $arg which refers to the number of whose the logarithm is to be calculated. Return Type: This function returns the result of the Base 10 logarithmic operation. Examples: Input : $arg = 100; Output : 2 Input : $arg = 10000; $base = 4; Output : 10 Below program illustrates the working of log10() in PHP: <?php// PHP code to illustrate the working of log10() Function $arg = 100000;for(;$arg>=10;$arg/=10) echo 'log10('.$arg.') = '.log10($arg)."\n";?> Output: log10(100000) = 5 log10(10000) = 4 log10(1000) = 3 log10(100) = 2 log10(10) = 1 Important points to note: log() function is a very popular method to calculate logarithmic values. PHP | exp() function is the functional counterpart of log(). arorakashish0911 PHP-function PHP-math PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from localserver database and display on HTML table using PHP ? Difference between HTTP GET and POST Methods Different ways for passing data to view in Laravel PHP | file_exists( ) Function PHP | Ternary Operator 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": "\n30 Oct, 2020" }, { "code": null, "e": 428, "s": 54, "text": "Logarithm is the counter operation to exponentiation. The logarithm of a number is in fact the exponent to which the other number i.e. the base must be raised to produce that number. If the Euler’s Number ‘e’ is used as the base of any logarithmic operation it is then known as Natural Logarithmic Operation, another popular logarithmic operation is to take 10 as the base." }, { "code": null, "e": 605, "s": 428, "text": "In PHP, the log() function is used to calculate the natural logarithm of a number if no base is specified and the log10() function calculates the base 10 logarithm of a number." }, { "code": null, "e": 620, "s": 605, "text": "log() Function" }, { "code": null, "e": 628, "s": 620, "text": "Syntax:" }, { "code": null, "e": 653, "s": 628, "text": "float log ($arg, $base)\n" }, { "code": null, "e": 724, "s": 653, "text": "Parameters: The function can accept at most two parameters as follows:" }, { "code": null, "e": 829, "s": 724, "text": "$arg: This is a required parameter that refers to the number of whose the logarithm is to be calculated." }, { "code": null, "e": 1014, "s": 829, "text": "$base: This is an optional parameter that refers to the base of the logarithmic operation. If not given, M_E i.e. the Euler’s Number is used as Base to calculate the Natural Logarithm." }, { "code": null, "e": 1090, "s": 1014, "text": "Return Type: This function returns the result of the logarithmic operation." }, { "code": null, "e": 1100, "s": 1090, "text": "Examples:" }, { "code": null, "e": 1196, "s": 1100, "text": "Input : $arg = M_E * M_E;\nOutput : 2\n\nInput : $arg = 1024;\n $base = 2;\nOutput : 10 \n" }, { "code": null, "e": 1251, "s": 1196, "text": "Below program illustrates the working of log() in PHP:" }, { "code": "<?php// PHP code to illustrate the working of log() Function $arg = 81;$base = 3;for(;$base<=$arg;$base*=$base) echo 'log('.$arg.', '.$base.') = '.log($arg, $base).\"\\n\";?>", "e": 1424, "s": 1251, "text": null }, { "code": null, "e": 1432, "s": 1424, "text": "Output:" }, { "code": null, "e": 1479, "s": 1432, "text": "log(81, 3) = 4\nlog(81, 9) = 2\nlog(81, 81) = 1\n" }, { "code": null, "e": 1496, "s": 1479, "text": "log10() Function" }, { "code": null, "e": 1504, "s": 1496, "text": "Syntax:" }, { "code": null, "e": 1524, "s": 1504, "text": "float log10 ($arg)\n" }, { "code": null, "e": 1652, "s": 1524, "text": "Parameters: The function accepts a single parameter $arg which refers to the number of whose the logarithm is to be calculated." }, { "code": null, "e": 1736, "s": 1652, "text": "Return Type: This function returns the result of the Base 10 logarithmic operation." }, { "code": null, "e": 1746, "s": 1736, "text": "Examples:" }, { "code": null, "e": 1837, "s": 1746, "text": "Input : $arg = 100;\nOutput : 2\n\nInput : $arg = 10000;\n $base = 4;\nOutput : 10 \n" }, { "code": null, "e": 1894, "s": 1837, "text": "Below program illustrates the working of log10() in PHP:" }, { "code": "<?php// PHP code to illustrate the working of log10() Function $arg = 100000;for(;$arg>=10;$arg/=10) echo 'log10('.$arg.') = '.log10($arg).\"\\n\";?>", "e": 2042, "s": 1894, "text": null }, { "code": null, "e": 2050, "s": 2042, "text": "Output:" }, { "code": null, "e": 2131, "s": 2050, "text": "log10(100000) = 5\nlog10(10000) = 4\nlog10(1000) = 3\nlog10(100) = 2\nlog10(10) = 1\n" }, { "code": null, "e": 2157, "s": 2131, "text": "Important points to note:" }, { "code": null, "e": 2230, "s": 2157, "text": "log() function is a very popular method to calculate logarithmic values." }, { "code": null, "e": 2291, "s": 2230, "text": "PHP | exp() function is the functional counterpart of log()." }, { "code": null, "e": 2308, "s": 2291, "text": "arorakashish0911" }, { "code": null, "e": 2321, "s": 2308, "text": "PHP-function" }, { "code": null, "e": 2330, "s": 2321, "text": "PHP-math" }, { "code": null, "e": 2334, "s": 2330, "text": "PHP" }, { "code": null, "e": 2351, "s": 2334, "text": "Web Technologies" }, { "code": null, "e": 2355, "s": 2351, "text": "PHP" }, { "code": null, "e": 2453, "s": 2355, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2535, "s": 2453, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 2580, "s": 2535, "text": "Difference between HTTP GET and POST Methods" }, { "code": null, "e": 2631, "s": 2580, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 2661, "s": 2631, "text": "PHP | file_exists( ) Function" }, { "code": null, "e": 2684, "s": 2661, "text": "PHP | Ternary Operator" }, { "code": null, "e": 2717, "s": 2684, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2779, "s": 2717, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2840, "s": 2779, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2890, "s": 2840, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
HTML5 - Geolocation
HTML5 Geolocation API lets you share your location with your favorite web sites. A JavaScript can capture your latitude and longitude and can be sent to backend web server and do fancy location-aware things like finding local businesses or showing your location on a map. Today most of the browsers and mobile devices support Geolocation API. The geolocation APIs work with a new property of the global navigator object ie. Geolocation object which can be created as follows − var geolocation = navigator.geolocation; The geolocation object is a service object that allows widgets to retrieve information about the geographic location of the device. The geolocation object provides the following methods − This method retrieves the current geographic location of the user. This method retrieves periodic updates about the current geographic location of the device. This method cancels an ongoing watchPosition call. Following is a sample code to use any of the above method − function getLocation() { var geolocation = navigator.geolocation; geolocation.getCurrentPosition(showLocation, errorHandler); } Here showLocation and errorHandler are callback methods which would be used to get actual position as explained in next section and to handle errors if there is any. Geolocation methods getCurrentPosition() and getPositionUsingMethodName() specify the callback method that retrieves the location information. These methods are called asynchronously with an object Position which stores the complete location information. The Position object specifies the current geographic location of the device. The location is expressed as a set of geographic coordinates together with information about heading and speed. The following table describes the properties of the Position object. For the optional properties if the system cannot provide a value, the value of the property is set to null. Following is a sample code which makes use of Position object. Here showLocation method is a callback method − function showLocation( position ) { var latitude = position.coords.latitude; var longitude = position.coords.longitude; ... } Geolocation is complicated, and it is very much required to catch any error and handle it gracefully. The geolocations methods getCurrentPosition() and watchPosition() make use of an error handler callback method which gives PositionError object. This object has following two properties − The following table describes the possible error codes returned in the PositionError object. Following is a sample code which makes use of PositionError object. Here errorHandler method is a callback method − function errorHandler( err ) { if (err.code == 1) { // access is denied } ... } Following is the actual syntax of getCurrentPosition() method − getCurrentPosition(callback, ErrorCallback, options) Here third argument is the PositionOptions object which specifies a set of options for retrieving the geographic location of the device. Following are the options which can be specified as third argument − Following is a sample code which shows how to use above mentioned methods − function getLocation() { var geolocation = navigator.geolocation; geolocation.getCurrentPosition(showLocation, errorHandler, {maximumAge: 75000});
[ { "code": null, "e": 3014, "s": 2742, "text": "HTML5 Geolocation API lets you share your location with your favorite web sites. A JavaScript can capture your latitude and longitude and can be sent to backend web server and do fancy location-aware things like finding local businesses or showing your location on a map." }, { "code": null, "e": 3219, "s": 3014, "text": "Today most of the browsers and mobile devices support Geolocation API. The geolocation APIs work with a new property of the global navigator object ie. Geolocation object which can be created as follows −" }, { "code": null, "e": 3261, "s": 3219, "text": "var geolocation = navigator.geolocation;\n" }, { "code": null, "e": 3393, "s": 3261, "text": "The geolocation object is a service object that allows widgets to retrieve information about the geographic location of the device." }, { "code": null, "e": 3449, "s": 3393, "text": "The geolocation object provides the following methods −" }, { "code": null, "e": 3516, "s": 3449, "text": "This method retrieves the current geographic location of the user." }, { "code": null, "e": 3608, "s": 3516, "text": "This method retrieves periodic updates about the current geographic location of the device." }, { "code": null, "e": 3659, "s": 3608, "text": "This method cancels an ongoing watchPosition call." }, { "code": null, "e": 3719, "s": 3659, "text": "Following is a sample code to use any of the above method −" }, { "code": null, "e": 3853, "s": 3719, "text": "function getLocation() {\n var geolocation = navigator.geolocation;\n geolocation.getCurrentPosition(showLocation, errorHandler);\n}" }, { "code": null, "e": 4019, "s": 3853, "text": "Here showLocation and errorHandler are callback methods which would be used to get actual position as explained in next section and to handle errors if there is any." }, { "code": null, "e": 4274, "s": 4019, "text": "Geolocation methods getCurrentPosition() and getPositionUsingMethodName() specify the callback method that retrieves the location information. These methods are called asynchronously with an object Position which stores the complete location information." }, { "code": null, "e": 4463, "s": 4274, "text": "The Position object specifies the current geographic location of the device. The location is expressed as a set of geographic coordinates together with information about heading and speed." }, { "code": null, "e": 4640, "s": 4463, "text": "The following table describes the properties of the Position object. For the optional properties if the system cannot provide a value, the value of the property is set to null." }, { "code": null, "e": 4751, "s": 4640, "text": "Following is a sample code which makes use of Position object. Here showLocation method is a callback method −" }, { "code": null, "e": 4886, "s": 4751, "text": "function showLocation( position ) {\n var latitude = position.coords.latitude;\n var longitude = position.coords.longitude;\n ...\n}" }, { "code": null, "e": 4988, "s": 4886, "text": "Geolocation is complicated, and it is very much required to catch any error and handle it gracefully." }, { "code": null, "e": 5176, "s": 4988, "text": "The geolocations methods getCurrentPosition() and watchPosition() make use of an error handler callback method which gives PositionError object. This object has following two properties −" }, { "code": null, "e": 5269, "s": 5176, "text": "The following table describes the possible error codes returned in the PositionError object." }, { "code": null, "e": 5385, "s": 5269, "text": "Following is a sample code which makes use of PositionError object. Here errorHandler method is a callback method −" }, { "code": null, "e": 5491, "s": 5385, "text": "function errorHandler( err ) {\n \n if (err.code == 1) {\n \n // access is denied\n }\n ...\n}" }, { "code": null, "e": 5555, "s": 5491, "text": "Following is the actual syntax of getCurrentPosition() method −" }, { "code": null, "e": 5609, "s": 5555, "text": "getCurrentPosition(callback, ErrorCallback, options)\n" }, { "code": null, "e": 5746, "s": 5609, "text": "Here third argument is the PositionOptions object which specifies a set of options for retrieving the geographic location of the device." }, { "code": null, "e": 5815, "s": 5746, "text": "Following are the options which can be specified as third argument −" }, { "code": null, "e": 5891, "s": 5815, "text": "Following is a sample code which shows how to use above mentioned methods −" } ]
PyQt - QRadioButton Widget
A QRadioButton class object presents a selectable button with a text label. The user can select one of many options presented on the form. This class is derived from QAbstractButton class. Radio buttons are autoexclusive by default. Hence, only one of the radio buttons in the parent window can be selected at a time. If one is selected, previously selected button is automatically deselected. Radio buttons can also be put in a QGroupBox or QButtonGroup to create more than one selectable fields on the parent window. The following listed methods of QRadioButton class are most commonly used. setChecked() Changes the state of radio button setText() Sets the label associated with the button text() Retrieves the caption of button isChecked() Checks if the button is selected Default signal associated with QRadioButton object is toggled(), although other signals inherited from QAbstractButton class can also be implemented. Here two mutually exclusive radio buttons are constructed on a top level window. Default state of b1 is set to checked by the statement − Self.b1.setChecked(True) The toggled() signal of both the buttons is connected to btnstate() function. Use of lambda allows the source of signal to be passed to the function as an argument. self.b1.toggled.connect(lambda:self.btnstate(self.b1)) self.b2.toggled.connect(lambda:self.btnstate(self.b2)) The btnstate() function checks state of button emitting toggled() signal. if b.isChecked() == True: print b.text()+" is selected" else: print b.text()+" is deselected" import sys from PyQt4.QtCore import * from PyQt4.QtGui import * class Radiodemo(QWidget): def __init__(self, parent = None): super(Radiodemo, self).__init__(parent) layout = QHBoxLayout() self.b1 = QRadioButton("Button1") self.b1.setChecked(True) self.b1.toggled.connect(lambda:self.btnstate(self.b1)) layout.addWidget(self.b1) self.b2 = QRadioButton("Button2") self.b2.toggled.connect(lambda:self.btnstate(self.b2)) layout.addWidget(self.b2) self.setLayout(layout) self.setWindowTitle("RadioButton demo") def btnstate(self,b): if b.text() == "Button1": if b.isChecked() == True: print b.text()+" is selected" else: print b.text()+" is deselected" if b.text() == "Button2": if b.isChecked() == True: print b.text()+" is selected" else: print b.text()+" is deselected" def main(): app = QApplication(sys.argv) ex = Radiodemo() ex.show() sys.exit(app.exec_()) if __name__ == '__main__': main() The above code produces the following output − Button1 is deselected Button2 is selected Button2 is deselected Button1 is selected
[ { "code": null, "e": 2249, "s": 2060, "text": "A QRadioButton class object presents a selectable button with a text label. The user can select one of many options presented on the form. This class is derived from QAbstractButton class." }, { "code": null, "e": 2579, "s": 2249, "text": "Radio buttons are autoexclusive by default. Hence, only one of the radio buttons in the parent window can be selected at a time. If one is selected, previously selected button is automatically deselected. Radio buttons can also be put in a QGroupBox or QButtonGroup to create more than one selectable fields on the parent window." }, { "code": null, "e": 2654, "s": 2579, "text": "The following listed methods of QRadioButton class are most commonly used." }, { "code": null, "e": 2667, "s": 2654, "text": "setChecked()" }, { "code": null, "e": 2701, "s": 2667, "text": "Changes the state of radio button" }, { "code": null, "e": 2711, "s": 2701, "text": "setText()" }, { "code": null, "e": 2753, "s": 2711, "text": "Sets the label associated with the button" }, { "code": null, "e": 2760, "s": 2753, "text": "text()" }, { "code": null, "e": 2792, "s": 2760, "text": "Retrieves the caption of button" }, { "code": null, "e": 2804, "s": 2792, "text": "isChecked()" }, { "code": null, "e": 2837, "s": 2804, "text": "Checks if the button is selected" }, { "code": null, "e": 2987, "s": 2837, "text": "Default signal associated with QRadioButton object is toggled(), although other signals inherited from QAbstractButton class can also be implemented." }, { "code": null, "e": 3068, "s": 2987, "text": "Here two mutually exclusive radio buttons are constructed on a top level window." }, { "code": null, "e": 3125, "s": 3068, "text": "Default state of b1 is set to checked by the statement −" }, { "code": null, "e": 3151, "s": 3125, "text": "Self.b1.setChecked(True)\n" }, { "code": null, "e": 3316, "s": 3151, "text": "The toggled() signal of both the buttons is connected to btnstate() function. Use of lambda allows the source of signal to be passed to the function as an argument." }, { "code": null, "e": 3427, "s": 3316, "text": "self.b1.toggled.connect(lambda:self.btnstate(self.b1))\nself.b2.toggled.connect(lambda:self.btnstate(self.b2))\n" }, { "code": null, "e": 3501, "s": 3427, "text": "The btnstate() function checks state of button emitting toggled() signal." }, { "code": null, "e": 4715, "s": 3501, "text": "if b.isChecked() == True:\n print b.text()+\" is selected\"\n else:\n print b.text()+\" is deselected\"\n\t\t\nimport sys\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\n\nclass Radiodemo(QWidget):\n\n def __init__(self, parent = None):\n super(Radiodemo, self).__init__(parent)\n\t\t\n layout = QHBoxLayout()\n self.b1 = QRadioButton(\"Button1\")\n self.b1.setChecked(True)\n self.b1.toggled.connect(lambda:self.btnstate(self.b1))\n layout.addWidget(self.b1)\n\t\t\n self.b2 = QRadioButton(\"Button2\")\n self.b2.toggled.connect(lambda:self.btnstate(self.b2))\n\n layout.addWidget(self.b2)\n self.setLayout(layout)\n self.setWindowTitle(\"RadioButton demo\")\n\t\t\n def btnstate(self,b):\n\t\n if b.text() == \"Button1\":\n if b.isChecked() == True:\n print b.text()+\" is selected\"\n else:\n print b.text()+\" is deselected\"\n\t\t\t\t\n if b.text() == \"Button2\":\n if b.isChecked() == True:\n print b.text()+\" is selected\"\n else:\n print b.text()+\" is deselected\"\n\t\t\t\t\ndef main():\n\n app = QApplication(sys.argv)\n ex = Radiodemo()\n ex.show()\n sys.exit(app.exec_())\n\t\nif __name__ == '__main__':\n main()" }, { "code": null, "e": 4762, "s": 4715, "text": "The above code produces the following output −" } ]
How to Eliminate Duplicate Values Based on Only One Column of the Table in SQL?
28 Nov, 2021 In SQL, some rows contain duplicate entries in a column. For deleting such rows, we need to use the DELETE keyword along with self-joining the table with itself. The same is illustrated below. For this article, we will be using the Microsoft SQL Server as our database. Step 1: Create a Database. For this use the below command to create a database named GeeksForGeeks. Query: CREATE DATABASE GeeksForGeeks Output: Step 2: Use the GeeksForGeeks database. For this use the below command. Query: USE GeeksForGeeks Output: Step 3: Create a table BONUSES inside the database GeeksForGeeks. This table has 3 columns namely EMPLOYEE_ID, EMPLOYEE_NAME, and EMPLOYEE_BONUS containing the id of the employee, the name of the employee, and his/her bonus. Query: CREATE TABLE BONUSES( EMPLOYEE_ID INT, EMPLOYEE_NAME VARCHAR(10), EMPLOYEE_BONUS INT); Output: Step 4: Describe the structure of the table BONUSES. Query: EXEC SP_COLUMNS BONUSES; Output: Step 5: Insert 10 rows into the BONUSES table. Query: INSERT INTO BONUSES VALUES(1,'RAJ',10000); INSERT INTO BONUSES VALUES(2,'RAJIV',10000); INSERT INTO BONUSES VALUES(3,'RAJ',20000); INSERT INTO BONUSES VALUES(4,'SAMEER',20000); INSERT INTO BONUSES VALUES(5,'PANKAJ',30000); INSERT INTO BONUSES VALUES(6,'HARRY',30000); INSERT INTO BONUSES VALUES(7,'VAUN',40000); INSERT INTO BONUSES VALUES(8,'SANGWOO',40000); INSERT INTO BONUSES VALUES(9,'SAM',50000); INSERT INTO BONUSES VALUES(10,'TIM',50000); Output: Step 6: Display all the rows of the BONUSES table. Query: SELECT * FROM BONUSES; Output: Step 7: Delete rows from the table BONUSES which have duplicate entries in the column EMPLOYEE_BONUS. To achieve this, we use the DELETE function by self joining(use JOIN function on 2 aliases of the table i.e. B1 and B2) the table with itself and comparing the entries of the column EMPLOYEE_BONUS for different entries of the column EMPLOYEE_ID because ID is unique for each employee. Syntax: DELETE T1 FROM TABLE_NAME T1 JOIN TABLE_NAME T2 ON T1.COLUMN_NAME1 = T2.COLUMN_NAME1 AND T2.COLUMN_NAME2 < T1.COLUMN_NAME2; Query: DELETE B1 FROM BONUSES B1 JOIN BONUSES B2 ON B1.EMPLOYEE_BONUS = B2.EMPLOYEE_BONUS AND B2.EMPLOYEE_ID < B1.EMPLOYEE_ID; Output: Step 8: Display all the rows of the updated BONUSES table. Query: SELECT * FROM BONUSES; Note – No row has duplicate entries in the column EMPLOYEE_BONUS. Output: Step 9: Delete rows from the table BONUSES which have duplicate entries in the column EMPLOYEE_NAME. Query: DELETE B1 FROM BONUSES B1 JOIN BONUSES B2 ON B1.EMPLOYEE_NAME = B2.EMPLOYEE_NAME AND B2.EMPLOYEE_ID < B1.EMPLOYEE_ID; Output: Step 10: Display all the rows of the updated BONUSES table. Query: SELECT * FROM BONUSES; Note: No row has duplicate entries in the column EMPLOYEE_NAME. Output: Picked SQL-Query SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Nov, 2021" }, { "code": null, "e": 298, "s": 28, "text": "In SQL, some rows contain duplicate entries in a column. For deleting such rows, we need to use the DELETE keyword along with self-joining the table with itself. The same is illustrated below. For this article, we will be using the Microsoft SQL Server as our database." }, { "code": null, "e": 398, "s": 298, "text": "Step 1: Create a Database. For this use the below command to create a database named GeeksForGeeks." }, { "code": null, "e": 405, "s": 398, "text": "Query:" }, { "code": null, "e": 435, "s": 405, "text": "CREATE DATABASE GeeksForGeeks" }, { "code": null, "e": 443, "s": 435, "text": "Output:" }, { "code": null, "e": 515, "s": 443, "text": "Step 2: Use the GeeksForGeeks database. For this use the below command." }, { "code": null, "e": 522, "s": 515, "text": "Query:" }, { "code": null, "e": 540, "s": 522, "text": "USE GeeksForGeeks" }, { "code": null, "e": 548, "s": 540, "text": "Output:" }, { "code": null, "e": 773, "s": 548, "text": "Step 3: Create a table BONUSES inside the database GeeksForGeeks. This table has 3 columns namely EMPLOYEE_ID, EMPLOYEE_NAME, and EMPLOYEE_BONUS containing the id of the employee, the name of the employee, and his/her bonus." }, { "code": null, "e": 780, "s": 773, "text": "Query:" }, { "code": null, "e": 867, "s": 780, "text": "CREATE TABLE BONUSES(\nEMPLOYEE_ID INT,\nEMPLOYEE_NAME VARCHAR(10),\nEMPLOYEE_BONUS INT);" }, { "code": null, "e": 875, "s": 867, "text": "Output:" }, { "code": null, "e": 928, "s": 875, "text": "Step 4: Describe the structure of the table BONUSES." }, { "code": null, "e": 935, "s": 928, "text": "Query:" }, { "code": null, "e": 960, "s": 935, "text": "EXEC SP_COLUMNS BONUSES;" }, { "code": null, "e": 968, "s": 960, "text": "Output:" }, { "code": null, "e": 1015, "s": 968, "text": "Step 5: Insert 10 rows into the BONUSES table." }, { "code": null, "e": 1022, "s": 1015, "text": "Query:" }, { "code": null, "e": 1468, "s": 1022, "text": "INSERT INTO BONUSES VALUES(1,'RAJ',10000);\nINSERT INTO BONUSES VALUES(2,'RAJIV',10000);\nINSERT INTO BONUSES VALUES(3,'RAJ',20000);\nINSERT INTO BONUSES VALUES(4,'SAMEER',20000);\nINSERT INTO BONUSES VALUES(5,'PANKAJ',30000);\nINSERT INTO BONUSES VALUES(6,'HARRY',30000);\nINSERT INTO BONUSES VALUES(7,'VAUN',40000);\nINSERT INTO BONUSES VALUES(8,'SANGWOO',40000);\nINSERT INTO BONUSES VALUES(9,'SAM',50000);\nINSERT INTO BONUSES VALUES(10,'TIM',50000);" }, { "code": null, "e": 1476, "s": 1468, "text": "Output:" }, { "code": null, "e": 1527, "s": 1476, "text": "Step 6: Display all the rows of the BONUSES table." }, { "code": null, "e": 1534, "s": 1527, "text": "Query:" }, { "code": null, "e": 1557, "s": 1534, "text": "SELECT * FROM BONUSES;" }, { "code": null, "e": 1565, "s": 1557, "text": "Output:" }, { "code": null, "e": 1952, "s": 1565, "text": "Step 7: Delete rows from the table BONUSES which have duplicate entries in the column EMPLOYEE_BONUS. To achieve this, we use the DELETE function by self joining(use JOIN function on 2 aliases of the table i.e. B1 and B2) the table with itself and comparing the entries of the column EMPLOYEE_BONUS for different entries of the column EMPLOYEE_ID because ID is unique for each employee." }, { "code": null, "e": 1960, "s": 1952, "text": "Syntax:" }, { "code": null, "e": 2084, "s": 1960, "text": "DELETE T1 FROM TABLE_NAME T1\nJOIN TABLE_NAME T2\nON T1.COLUMN_NAME1 = T2.COLUMN_NAME1\nAND T2.COLUMN_NAME2 < T1.COLUMN_NAME2;" }, { "code": null, "e": 2091, "s": 2084, "text": "Query:" }, { "code": null, "e": 2211, "s": 2091, "text": "DELETE B1 FROM BONUSES B1\nJOIN BONUSES B2\nON B1.EMPLOYEE_BONUS = B2.EMPLOYEE_BONUS\nAND B2.EMPLOYEE_ID < B1.EMPLOYEE_ID;" }, { "code": null, "e": 2219, "s": 2211, "text": "Output:" }, { "code": null, "e": 2278, "s": 2219, "text": "Step 8: Display all the rows of the updated BONUSES table." }, { "code": null, "e": 2285, "s": 2278, "text": "Query:" }, { "code": null, "e": 2308, "s": 2285, "text": "SELECT * FROM BONUSES;" }, { "code": null, "e": 2374, "s": 2308, "text": "Note – No row has duplicate entries in the column EMPLOYEE_BONUS." }, { "code": null, "e": 2382, "s": 2374, "text": "Output:" }, { "code": null, "e": 2483, "s": 2382, "text": "Step 9: Delete rows from the table BONUSES which have duplicate entries in the column EMPLOYEE_NAME." }, { "code": null, "e": 2490, "s": 2483, "text": "Query:" }, { "code": null, "e": 2608, "s": 2490, "text": "DELETE B1 FROM BONUSES B1\nJOIN BONUSES B2\nON B1.EMPLOYEE_NAME = B2.EMPLOYEE_NAME\nAND B2.EMPLOYEE_ID < B1.EMPLOYEE_ID;" }, { "code": null, "e": 2616, "s": 2608, "text": "Output:" }, { "code": null, "e": 2676, "s": 2616, "text": "Step 10: Display all the rows of the updated BONUSES table." }, { "code": null, "e": 2683, "s": 2676, "text": "Query:" }, { "code": null, "e": 2706, "s": 2683, "text": "SELECT * FROM BONUSES;" }, { "code": null, "e": 2770, "s": 2706, "text": "Note: No row has duplicate entries in the column EMPLOYEE_NAME." }, { "code": null, "e": 2778, "s": 2770, "text": "Output:" }, { "code": null, "e": 2785, "s": 2778, "text": "Picked" }, { "code": null, "e": 2795, "s": 2785, "text": "SQL-Query" }, { "code": null, "e": 2806, "s": 2795, "text": "SQL-Server" }, { "code": null, "e": 2810, "s": 2806, "text": "SQL" }, { "code": null, "e": 2814, "s": 2810, "text": "SQL" } ]
Multidimensional data analysis in Python
24 Jan, 2022 Multi-dimensional data analysis is an informative analysis of data which takes many relationships into account. Let’s shed light on some basic techniques used for analysing multidimensional/multivariate data using open source libraries written in Python. Find the link for data used for illustration from here.Following code is used to read 2D tabular data from zoo_data.csv. Python3 import pandas as pd zoo_data = pd.read_csv("zoo_data.csv", encoding = 'utf-8', index_col = ["animal_name"]) # print first 5 rows of zoo dataprint(zoo_data.head()) Output: Note: The type of data we have here is typically categorical. The techniques used in this case study for categorical data analysis are very basic ones which are simple to understand, interpret and implement. These include cluster analysis, correlation analysis, PCA(Principal component analysis) and EDA(Exploratory Data Analysis) analysis. Cluster Analysis: As the data we have is based on the characteristics of different types of animals, we can classify animals into different groups(clusters) or subgroups using some well known clustering techniques namely KMeans clustering, DBscan, Hierarchical clustering & KNN(K-Nearest Neighbours) clustering. For sake of simplicity, KMeans clustering ought to be a better option in this case. Clustering data using Kmeans clustering technique can be achieved using KMeans module of cluster class of sklearn library as follows: Python3 # from sklearn.cluster import KMeansclusters = 7 kmeans = KMeans(n_clusters = clusters)kmeans.fit(zoo_data) print(kmeans.labels_) Output: Here, overall cluster inertia comes out to be 119.70392382759556. This value is stored in kmeans.inertia_ variable. EDA Analysis: To perform EDA analysis, we need to reduce dimensionality of multivariate data we have to trivariate/bivariate(2D/3D) data. We can achieve this task using PCA(Principal Component Analysis). For more information refer to https://www.geeksforgeeks.org/dimensionality-reduction/PCA can be carried out using PCA module of class decomposition of library sklearn as follows: Python3 # from sklearn.decomposition import PCA pca = PCA(3)pca.fit(zoo_data) pca_data = pd.DataFrame(pca.transform(zoo_data)) print(pca_data.head()) Output: Data output above represents reduced trivariate(3D) data on which we can perform EDA analysis. Note: Reduced Data produced by PCA can be used indirectly for performing various analysis but is not directly human interpretable.Scatter plot is a 2D/3D plot which is helpful in analysis of various clusters in 2D/3D data. Scatter plot of 3D reduced data we produced earlier can be plotted as follows:The code below is a Pythonic code which generates an array of colors(where number of colors are approximately equal to number of clusters) sorted in order of their hue, value and saturation values. Here each color is associated with a single cluster and will be used to denote an animal as a 3D point while plotting it in a 3D plot/space(Scatter Plot in this case). Python3 from matplotlib import colors as mcolorsimport math ''' Generating different colors in ascending order of their hsv values '''colors = list(zip(*sorted(( tuple(mcolors.rgb_to_hsv( mcolors.to_rgba(color)[:3])), name) for name, color in dict( mcolors.BASE_COLORS, **mcolors.CSS4_COLORS ).items())))[1] # number of steps to taken generate n(clusters) colorsskips = math.floor(len(colors[5 : -5])/clusters)cluster_colors = colors[5 : -5 : skips] The code below is a pythonic code which generates a 3D scatter plot where each data point has a color related to its corresponding cluster. Python3 from mpl_toolkits.mplot3d import Axes3Dimport matplotlib.pyplot as plt fig = plt.figure()ax = fig.add_subplot(111, projection = '3d')ax.scatter(pca_data[0], pca_data[1], pca_data[2], c = list(map(lambda label : cluster_colors[label], kmeans.labels_))) str_labels = list(map(lambda label:'% s' % label, kmeans.labels_)) list(map(lambda data1, data2, data3, str_label: ax.text(data1, data2, data3, s = str_label, size = 16.5, zorder = 20, color = 'k'), pca_data[0], pca_data[1], pca_data[2], str_labels)) plt.show() Output: Closely analysing the scatter plot can lead to hypothesis that the clusters formed using the initial data doesn’t have good enough explanatory power. To solve this issue, we need to bring down our set of features to a more useful set of features using which we can generate useful clusters. One way of producing such a set of features is to carry out correlation analysis. This can be done by plotting heatmaps and trisurface plots as follows: Python3 import seaborn as sns # generating correlation heatmapsns.heatmap(zoo_data.corr(), annot = True) # posting correlation heatmap to output consoleplt.show() Output: Following code is used to generate a trisurface plot of correlation matrix by making a list of tuples where a tuple contains coordinates and correlation value in order of animal names.Pseudocode for above explanation: # PseudoCode tuple -> (position_in_dataframe(feature1), position_in_dataframe(feature2), correlation(feature1, feature2)) Code for generating trisurface plot for correlation matrix: Python3 from matplotlib import cm # generating correlation datadf = zoo_data.corr()df.index = range(0, len(df))df.rename(columns = dict(zip(df.columns, df.index)), inplace = True)df = df.astype(object) ''' Generating coordinates withcorresponding correlation values '''for i in range(0, len(df)): for j in range(0, len(df)): if i != j: df.iloc[i, j] = (i, j, df.iloc[i, j]) else : df.iloc[i, j] = (i, j, 0) df_list = [] # flattening dataframe valuesfor sub_list in df.values: df_list.extend(sub_list) # converting list of tuples into trivariate dataframeplot_df = pd.DataFrame(df_list) fig = plt.figure()ax = Axes3D(fig) # plotting 3D trisurface plotax.plot_trisurf(plot_df[0], plot_df[1], plot_df[2], cmap = cm.jet, linewidth = 0.2) plt.show() Output: Using heatmap and trisurface plot, we can make some inferences on how to select a smaller set of features used for performing cluster analysis. Generally, feature pairs with extreme correlation values carry high explanatory power and can be used for further analysis. In this case, looking at both the plots, we arrive at a rational list of 7 features:[“milk”, “eggs”, “hair”, “toothed”, “feathers”, “breathes”, “aquatic”] Running cluster analysis again on the subsetted feature set, we can generate a scatter plot with better inference on how to spread different animals among various groups. We observe a reduced overall inertia of 14.479670329670329, which is indeed a lot less from the initial inertia. rkbhola5 Technical Scripter 2018 Machine Learning Python Technical Scripter Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Getting started with Machine Learning Introduction to Recurrent Neural Network Support Vector Machine Algorithm Random Forest Regression in Python Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas How to get column names in Pandas dataframe Different ways to create Pandas Dataframe
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Jan, 2022" }, { "code": null, "e": 432, "s": 54, "text": "Multi-dimensional data analysis is an informative analysis of data which takes many relationships into account. Let’s shed light on some basic techniques used for analysing multidimensional/multivariate data using open source libraries written in Python. Find the link for data used for illustration from here.Following code is used to read 2D tabular data from zoo_data.csv. " }, { "code": null, "e": 440, "s": 432, "text": "Python3" }, { "code": "import pandas as pd zoo_data = pd.read_csv(\"zoo_data.csv\", encoding = 'utf-8', index_col = [\"animal_name\"]) # print first 5 rows of zoo dataprint(zoo_data.head())", "e": 632, "s": 440, "text": null }, { "code": null, "e": 642, "s": 632, "text": "Output: " }, { "code": null, "e": 1515, "s": 642, "text": "Note: The type of data we have here is typically categorical. The techniques used in this case study for categorical data analysis are very basic ones which are simple to understand, interpret and implement. These include cluster analysis, correlation analysis, PCA(Principal component analysis) and EDA(Exploratory Data Analysis) analysis. Cluster Analysis: As the data we have is based on the characteristics of different types of animals, we can classify animals into different groups(clusters) or subgroups using some well known clustering techniques namely KMeans clustering, DBscan, Hierarchical clustering & KNN(K-Nearest Neighbours) clustering. For sake of simplicity, KMeans clustering ought to be a better option in this case. Clustering data using Kmeans clustering technique can be achieved using KMeans module of cluster class of sklearn library as follows: " }, { "code": null, "e": 1523, "s": 1515, "text": "Python3" }, { "code": "# from sklearn.cluster import KMeansclusters = 7 kmeans = KMeans(n_clusters = clusters)kmeans.fit(zoo_data) print(kmeans.labels_)", "e": 1653, "s": 1523, "text": null }, { "code": null, "e": 1663, "s": 1653, "text": "Output: " }, { "code": null, "e": 2166, "s": 1663, "text": "Here, overall cluster inertia comes out to be 119.70392382759556. This value is stored in kmeans.inertia_ variable. EDA Analysis: To perform EDA analysis, we need to reduce dimensionality of multivariate data we have to trivariate/bivariate(2D/3D) data. We can achieve this task using PCA(Principal Component Analysis). For more information refer to https://www.geeksforgeeks.org/dimensionality-reduction/PCA can be carried out using PCA module of class decomposition of library sklearn as follows: " }, { "code": null, "e": 2174, "s": 2166, "text": "Python3" }, { "code": "# from sklearn.decomposition import PCA pca = PCA(3)pca.fit(zoo_data) pca_data = pd.DataFrame(pca.transform(zoo_data)) print(pca_data.head())", "e": 2316, "s": 2174, "text": null }, { "code": null, "e": 2326, "s": 2316, "text": "Output: " }, { "code": null, "e": 3089, "s": 2326, "text": "Data output above represents reduced trivariate(3D) data on which we can perform EDA analysis. Note: Reduced Data produced by PCA can be used indirectly for performing various analysis but is not directly human interpretable.Scatter plot is a 2D/3D plot which is helpful in analysis of various clusters in 2D/3D data. Scatter plot of 3D reduced data we produced earlier can be plotted as follows:The code below is a Pythonic code which generates an array of colors(where number of colors are approximately equal to number of clusters) sorted in order of their hue, value and saturation values. Here each color is associated with a single cluster and will be used to denote an animal as a 3D point while plotting it in a 3D plot/space(Scatter Plot in this case). " }, { "code": null, "e": 3097, "s": 3089, "text": "Python3" }, { "code": "from matplotlib import colors as mcolorsimport math ''' Generating different colors in ascending order of their hsv values '''colors = list(zip(*sorted(( tuple(mcolors.rgb_to_hsv( mcolors.to_rgba(color)[:3])), name) for name, color in dict( mcolors.BASE_COLORS, **mcolors.CSS4_COLORS ).items())))[1] # number of steps to taken generate n(clusters) colorsskips = math.floor(len(colors[5 : -5])/clusters)cluster_colors = colors[5 : -5 : skips]", "e": 3718, "s": 3097, "text": null }, { "code": null, "e": 3859, "s": 3718, "text": "The code below is a pythonic code which generates a 3D scatter plot where each data point has a color related to its corresponding cluster. " }, { "code": null, "e": 3867, "s": 3859, "text": "Python3" }, { "code": "from mpl_toolkits.mplot3d import Axes3Dimport matplotlib.pyplot as plt fig = plt.figure()ax = fig.add_subplot(111, projection = '3d')ax.scatter(pca_data[0], pca_data[1], pca_data[2], c = list(map(lambda label : cluster_colors[label], kmeans.labels_))) str_labels = list(map(lambda label:'% s' % label, kmeans.labels_)) list(map(lambda data1, data2, data3, str_label: ax.text(data1, data2, data3, s = str_label, size = 16.5, zorder = 20, color = 'k'), pca_data[0], pca_data[1], pca_data[2], str_labels)) plt.show()", "e": 4459, "s": 3867, "text": null }, { "code": null, "e": 4468, "s": 4459, "text": "Output: " }, { "code": null, "e": 4913, "s": 4468, "text": "Closely analysing the scatter plot can lead to hypothesis that the clusters formed using the initial data doesn’t have good enough explanatory power. To solve this issue, we need to bring down our set of features to a more useful set of features using which we can generate useful clusters. One way of producing such a set of features is to carry out correlation analysis. This can be done by plotting heatmaps and trisurface plots as follows: " }, { "code": null, "e": 4921, "s": 4913, "text": "Python3" }, { "code": "import seaborn as sns # generating correlation heatmapsns.heatmap(zoo_data.corr(), annot = True) # posting correlation heatmap to output consoleplt.show()", "e": 5076, "s": 4921, "text": null }, { "code": null, "e": 5086, "s": 5076, "text": "Output: " }, { "code": null, "e": 5306, "s": 5086, "text": "Following code is used to generate a trisurface plot of correlation matrix by making a list of tuples where a tuple contains coordinates and correlation value in order of animal names.Pseudocode for above explanation: " }, { "code": null, "e": 5448, "s": 5306, "text": "# PseudoCode\ntuple -> (position_in_dataframe(feature1),\n position_in_dataframe(feature2),\n correlation(feature1, feature2))" }, { "code": null, "e": 5510, "s": 5448, "text": "Code for generating trisurface plot for correlation matrix: " }, { "code": null, "e": 5518, "s": 5510, "text": "Python3" }, { "code": "from matplotlib import cm # generating correlation datadf = zoo_data.corr()df.index = range(0, len(df))df.rename(columns = dict(zip(df.columns, df.index)), inplace = True)df = df.astype(object) ''' Generating coordinates withcorresponding correlation values '''for i in range(0, len(df)): for j in range(0, len(df)): if i != j: df.iloc[i, j] = (i, j, df.iloc[i, j]) else : df.iloc[i, j] = (i, j, 0) df_list = [] # flattening dataframe valuesfor sub_list in df.values: df_list.extend(sub_list) # converting list of tuples into trivariate dataframeplot_df = pd.DataFrame(df_list) fig = plt.figure()ax = Axes3D(fig) # plotting 3D trisurface plotax.plot_trisurf(plot_df[0], plot_df[1], plot_df[2], cmap = cm.jet, linewidth = 0.2) plt.show()", "e": 6316, "s": 5518, "text": null }, { "code": null, "e": 6326, "s": 6316, "text": "Output: " }, { "code": null, "e": 6921, "s": 6326, "text": "Using heatmap and trisurface plot, we can make some inferences on how to select a smaller set of features used for performing cluster analysis. Generally, feature pairs with extreme correlation values carry high explanatory power and can be used for further analysis. In this case, looking at both the plots, we arrive at a rational list of 7 features:[“milk”, “eggs”, “hair”, “toothed”, “feathers”, “breathes”, “aquatic”] Running cluster analysis again on the subsetted feature set, we can generate a scatter plot with better inference on how to spread different animals among various groups. " }, { "code": null, "e": 7035, "s": 6921, "text": "We observe a reduced overall inertia of 14.479670329670329, which is indeed a lot less from the initial inertia. " }, { "code": null, "e": 7044, "s": 7035, "text": "rkbhola5" }, { "code": null, "e": 7068, "s": 7044, "text": "Technical Scripter 2018" }, { "code": null, "e": 7085, "s": 7068, "text": "Machine Learning" }, { "code": null, "e": 7092, "s": 7085, "text": "Python" }, { "code": null, "e": 7111, "s": 7092, "text": "Technical Scripter" }, { "code": null, "e": 7128, "s": 7111, "text": "Machine Learning" }, { "code": null, "e": 7226, "s": 7128, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7249, "s": 7226, "text": "ML | Linear Regression" }, { "code": null, "e": 7287, "s": 7249, "text": "Getting started with Machine Learning" }, { "code": null, "e": 7328, "s": 7287, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 7361, "s": 7328, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 7396, "s": 7361, "text": "Random Forest Regression in Python" }, { "code": null, "e": 7424, "s": 7396, "text": "Read JSON file using Python" }, { "code": null, "e": 7446, "s": 7424, "text": "Python map() function" }, { "code": null, "e": 7496, "s": 7446, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 7540, "s": 7496, "text": "How to get column names in Pandas dataframe" } ]
Scatter plots in R Language
10 Dec, 2021 A scatter plot is a set of dotted points to represent individual pieces of data in the horizontal and vertical axis. A graph in which the values of two variables are plotted along X-axis and Y-axis, the pattern of the resulting points reveals a correlation between them. We can create a scatter plot in R Programming Language using the plot() function. Syntax: plot(x, y, main, xlab, ylab, xlim, ylim, axes) Parameters: x: This parameter sets the horizontal coordinates. y: This parameter sets the vertical coordinates. xlab: This parameter is the label for horizontal axis. ylab: This parameter is the label for vertical axis. main: This parameter main is the title of the chart. xlim: This parameter is used for plotting values of x. ylim: This parameter is used for plotting values of y. axes: This parameter indicates whether both axes should be drawn on the plot. In order to create Scatterplot Chart: We use the data set “mtcars”.Use the columns “wt” and “mpg” in mtcars. We use the data set “mtcars”. Use the columns “wt” and “mpg” in mtcars. Example: R input <- mtcars[, c('wt', 'mpg')]print(head(input)) Output: In order to create a Scatterplot graph: We are using the required parameters to plot the graph.In this ‘xlab’ describes the X-axis and ‘ylab’ describes the Y-axis. We are using the required parameters to plot the graph. In this ‘xlab’ describes the X-axis and ‘ylab’ describes the Y-axis. Example: R # Get the input values.input <- mtcars[, c('wt', 'mpg')] # Plot the chart for cars with# weight between 1.5 to 4 and# mileage between 10 and 25.plot(x = input$wt, y = input$mpg, xlab = "Weight", ylab = "Milage", xlim = c(1.5, 4), ylim = c(10, 25), main = "Weight vs Milage") Output: When we have two or more variables and we want to correlate between one variable and others so we use a scatterplot matrix. pairs() function is used to create matrices of scatterplots. Syntax: pairs(formula, data) Parameters: formula: This parameter represents the series of variables used in pairs. data: This parameter represents the data set from which the variables will be taken. Example: R # Plot the matrices between# 4 variables giving 12 plots. # One variable with 3 others# and total 4 variables.pairs(~wt + mpg + disp + cyl, data = mtcars, main = "Scatterplot Matrix") Output: In order to create Scatterplot Chart: We are using the ggplot2 package provides ggplot() and geom_point() function for creating a scatterplot.Also we are using the columns “wt” and “mpg” in mtcars. We are using the ggplot2 package provides ggplot() and geom_point() function for creating a scatterplot. Also we are using the columns “wt” and “mpg” in mtcars. Example: R # Loading ggplot2 packagelibrary(ggplot2) # Creating scatterplot with fitted values.# An additional function stst_smooth# is used for linear regression.ggplot(mtcars, aes(x = log(mpg), y = log(drat))) + geom_point(aes(color = factor(gear))) + stat_smooth(method = "lm", col = "#C42126", se = FALSE, size = 1) Output: To create Scatterplot Chart, Add a sub-title: We use the additional function, In ggplot we add the data set “mtcars” with this adding ‘aes’, ‘geom_point’.Use the Title, Caption, Subtitle. We use the additional function, In ggplot we add the data set “mtcars” with this adding ‘aes’, ‘geom_point’. Use the Title, Caption, Subtitle. Example: Python3 # Loading ggplot2 packagelibrary(ggplot2) # Creating scatterplot with fitted values.# An additional function stst_smooth# is used for linear regression.new_graph<-ggplot(mtcars, aes(x = log(mpg), y = log(drat))) + geom_point(aes(color = factor(gear))) + stat_smooth(method = "lm", col = "#C42126", se = FALSE, size = 1) # in above example lm is used for linear regression# and se stands for standard error.# Adding title with dynamic namenew_graph + labs( title = "Relation between Mile per hours and drat", subtitle = "Relationship break down by gear class", caption = "Authors own computation") Output: Here we will use scatterplot3D package to create 3D scatterplots, this package can plot scatterplot in 3D using scatterplot3d() methods. R # 3D Scatterplotlibrary(scatterplot3d)attach(mtcars) scatterplot3d(mpg, cyl, hp, main = "3D Scatterplot") Output: kumar_satyam Picked R-plots R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change column name of a given DataFrame in R Filter data by multiple conditions in R using Dplyr Group by function in R using Dplyr How to Replace specific values in column in R DataFrame ? How to filter R DataFrame by values in a column? Loops in R (for, while, repeat) Convert Factor to Numeric and Numeric to Factor in R Programming Adding elements in a vector in R programming - append() method Creating a Data Frame from Vectors in R Programming How to change Row Names of DataFrame in R ?
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Dec, 2021" }, { "code": null, "e": 299, "s": 28, "text": "A scatter plot is a set of dotted points to represent individual pieces of data in the horizontal and vertical axis. A graph in which the values of two variables are plotted along X-axis and Y-axis, the pattern of the resulting points reveals a correlation between them." }, { "code": null, "e": 381, "s": 299, "text": "We can create a scatter plot in R Programming Language using the plot() function." }, { "code": null, "e": 436, "s": 381, "text": "Syntax: plot(x, y, main, xlab, ylab, xlim, ylim, axes)" }, { "code": null, "e": 449, "s": 436, "text": "Parameters: " }, { "code": null, "e": 500, "s": 449, "text": "x: This parameter sets the horizontal coordinates." }, { "code": null, "e": 549, "s": 500, "text": "y: This parameter sets the vertical coordinates." }, { "code": null, "e": 604, "s": 549, "text": "xlab: This parameter is the label for horizontal axis." }, { "code": null, "e": 657, "s": 604, "text": "ylab: This parameter is the label for vertical axis." }, { "code": null, "e": 710, "s": 657, "text": "main: This parameter main is the title of the chart." }, { "code": null, "e": 765, "s": 710, "text": "xlim: This parameter is used for plotting values of x." }, { "code": null, "e": 820, "s": 765, "text": "ylim: This parameter is used for plotting values of y." }, { "code": null, "e": 898, "s": 820, "text": "axes: This parameter indicates whether both axes should be drawn on the plot." }, { "code": null, "e": 936, "s": 898, "text": "In order to create Scatterplot Chart:" }, { "code": null, "e": 1007, "s": 936, "text": "We use the data set “mtcars”.Use the columns “wt” and “mpg” in mtcars." }, { "code": null, "e": 1037, "s": 1007, "text": "We use the data set “mtcars”." }, { "code": null, "e": 1079, "s": 1037, "text": "Use the columns “wt” and “mpg” in mtcars." }, { "code": null, "e": 1089, "s": 1079, "text": "Example: " }, { "code": null, "e": 1091, "s": 1089, "text": "R" }, { "code": "input <- mtcars[, c('wt', 'mpg')]print(head(input))", "e": 1143, "s": 1091, "text": null }, { "code": null, "e": 1151, "s": 1143, "text": "Output:" }, { "code": null, "e": 1192, "s": 1151, "text": "In order to create a Scatterplot graph: " }, { "code": null, "e": 1316, "s": 1192, "text": "We are using the required parameters to plot the graph.In this ‘xlab’ describes the X-axis and ‘ylab’ describes the Y-axis." }, { "code": null, "e": 1372, "s": 1316, "text": "We are using the required parameters to plot the graph." }, { "code": null, "e": 1441, "s": 1372, "text": "In this ‘xlab’ describes the X-axis and ‘ylab’ describes the Y-axis." }, { "code": null, "e": 1451, "s": 1441, "text": "Example: " }, { "code": null, "e": 1453, "s": 1451, "text": "R" }, { "code": "# Get the input values.input <- mtcars[, c('wt', 'mpg')] # Plot the chart for cars with# weight between 1.5 to 4 and# mileage between 10 and 25.plot(x = input$wt, y = input$mpg, xlab = \"Weight\", ylab = \"Milage\", xlim = c(1.5, 4), ylim = c(10, 25), main = \"Weight vs Milage\")", "e": 1750, "s": 1453, "text": null }, { "code": null, "e": 1759, "s": 1750, "text": "Output: " }, { "code": null, "e": 1883, "s": 1759, "text": "When we have two or more variables and we want to correlate between one variable and others so we use a scatterplot matrix." }, { "code": null, "e": 1944, "s": 1883, "text": "pairs() function is used to create matrices of scatterplots." }, { "code": null, "e": 1973, "s": 1944, "text": "Syntax: pairs(formula, data)" }, { "code": null, "e": 1986, "s": 1973, "text": "Parameters: " }, { "code": null, "e": 2060, "s": 1986, "text": "formula: This parameter represents the series of variables used in pairs." }, { "code": null, "e": 2145, "s": 2060, "text": "data: This parameter represents the data set from which the variables will be taken." }, { "code": null, "e": 2155, "s": 2145, "text": "Example: " }, { "code": null, "e": 2157, "s": 2155, "text": "R" }, { "code": "# Plot the matrices between# 4 variables giving 12 plots. # One variable with 3 others# and total 4 variables.pairs(~wt + mpg + disp + cyl, data = mtcars, main = \"Scatterplot Matrix\")", "e": 2344, "s": 2157, "text": null }, { "code": null, "e": 2353, "s": 2344, "text": "Output: " }, { "code": null, "e": 2392, "s": 2353, "text": "In order to create Scatterplot Chart: " }, { "code": null, "e": 2552, "s": 2392, "text": "We are using the ggplot2 package provides ggplot() and geom_point() function for creating a scatterplot.Also we are using the columns “wt” and “mpg” in mtcars." }, { "code": null, "e": 2657, "s": 2552, "text": "We are using the ggplot2 package provides ggplot() and geom_point() function for creating a scatterplot." }, { "code": null, "e": 2713, "s": 2657, "text": "Also we are using the columns “wt” and “mpg” in mtcars." }, { "code": null, "e": 2723, "s": 2713, "text": "Example: " }, { "code": null, "e": 2725, "s": 2723, "text": "R" }, { "code": "# Loading ggplot2 packagelibrary(ggplot2) # Creating scatterplot with fitted values.# An additional function stst_smooth# is used for linear regression.ggplot(mtcars, aes(x = log(mpg), y = log(drat))) + geom_point(aes(color = factor(gear))) + stat_smooth(method = \"lm\", col = \"#C42126\", se = FALSE, size = 1)", "e": 3059, "s": 2725, "text": null }, { "code": null, "e": 3067, "s": 3059, "text": "Output:" }, { "code": null, "e": 3114, "s": 3067, "text": "To create Scatterplot Chart, Add a sub-title: " }, { "code": null, "e": 3256, "s": 3114, "text": "We use the additional function, In ggplot we add the data set “mtcars” with this adding ‘aes’, ‘geom_point’.Use the Title, Caption, Subtitle." }, { "code": null, "e": 3365, "s": 3256, "text": "We use the additional function, In ggplot we add the data set “mtcars” with this adding ‘aes’, ‘geom_point’." }, { "code": null, "e": 3399, "s": 3365, "text": "Use the Title, Caption, Subtitle." }, { "code": null, "e": 3409, "s": 3399, "text": "Example: " }, { "code": null, "e": 3417, "s": 3409, "text": "Python3" }, { "code": "# Loading ggplot2 packagelibrary(ggplot2) # Creating scatterplot with fitted values.# An additional function stst_smooth# is used for linear regression.new_graph<-ggplot(mtcars, aes(x = log(mpg), y = log(drat))) + geom_point(aes(color = factor(gear))) + stat_smooth(method = \"lm\", col = \"#C42126\", se = FALSE, size = 1) # in above example lm is used for linear regression# and se stands for standard error.# Adding title with dynamic namenew_graph + labs( title = \"Relation between Mile per hours and drat\", subtitle = \"Relationship break down by gear class\", caption = \"Authors own computation\")", "e": 4156, "s": 3417, "text": null }, { "code": null, "e": 4164, "s": 4156, "text": "Output:" }, { "code": null, "e": 4301, "s": 4164, "text": "Here we will use scatterplot3D package to create 3D scatterplots, this package can plot scatterplot in 3D using scatterplot3d() methods." }, { "code": null, "e": 4303, "s": 4301, "text": "R" }, { "code": "# 3D Scatterplotlibrary(scatterplot3d)attach(mtcars) scatterplot3d(mpg, cyl, hp, main = \"3D Scatterplot\")", "e": 4422, "s": 4303, "text": null }, { "code": null, "e": 4430, "s": 4422, "text": "Output:" }, { "code": null, "e": 4443, "s": 4430, "text": "kumar_satyam" }, { "code": null, "e": 4450, "s": 4443, "text": "Picked" }, { "code": null, "e": 4458, "s": 4450, "text": "R-plots" }, { "code": null, "e": 4469, "s": 4458, "text": "R Language" }, { "code": null, "e": 4567, "s": 4469, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4612, "s": 4567, "text": "Change column name of a given DataFrame in R" }, { "code": null, "e": 4664, "s": 4612, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 4699, "s": 4664, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 4757, "s": 4699, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 4806, "s": 4757, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 4838, "s": 4806, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 4903, "s": 4838, "text": "Convert Factor to Numeric and Numeric to Factor in R Programming" }, { "code": null, "e": 4966, "s": 4903, "text": "Adding elements in a vector in R programming - append() method" }, { "code": null, "e": 5018, "s": 4966, "text": "Creating a Data Frame from Vectors in R Programming" } ]
SQL Query to Exclude Records if it Matches an Entry in Another Table
17 May, 2022 In this article, we will see, how to write the SQL Query to exclude records if it matches an entry in another table. We can perform the above function using the NOT IN operator in SQL. For obtaining the list of values we can write the subquery. NOT IN operators acts as a negation of In operator and return the results excluding the items present in the specified list. Syntax: NOT IN SELECT * FROM table_name WHERE column_name NOT IN (list); Now, for the demonstration follow the below steps: Step 1: Create a database we can use the following command to create a database called geeks. Query: CREATE DATABASE geeks; Step 2: Use the database Use the below SQL statement to switch the database context to geeks: Query: USE geeks; Step 3: Table definition We have two tables named ‘demo_table1’ and ‘demo_table2’ in our geek’s database. Query(demo_table1): CREATE TABLE demo_table1( NAME VARCHAR(20), AGE INT, CITY VARCHAR(20) ); Query(demo_table2): CREATE TABLE demo_table2( NAME VARCHAR(20), AGE int); Step 4: Insert data into a table Query(demo_table1): INSERT INTO demo_table1 VALUES ('Romy',23,'Delhi'), ('Rahul',23,'Delhi'), ('Nikhil',24,'Punjab'), ('Ranvir',23,'Punjab'), ('Samiksha',23,'Banglore'), ('Ashtha',24,'Banglore'), ('Tannu',30,'Patna'), ('Girish',30,'Patna'), ('Ram', 20 , 'Patna'), ('Raj', 12, 'Delhi'); Query(demo_table2): INSERT INTO demo_table2 VALUES ('Fanny',25 ), ('Prem', 30), ('Preeti',21), ('Samita',32), ('Rahul',23), ('Ranvir',23); Step 5: View the content Execute the below query to see the content of the table Query: SELECT * FROM demo_table1; Output: Query: SELECT * FROM demo_table2; Output: Step 6: Exclude data from demo_table1 based on matches found in demo_table2 For the demonstration, exclude the data from demo_table1 whose values in the NAME column match the entries in the Name column of demo_table2. Query: SELECT * FROM demo_table1 WHERE NAME NOT IN (SELECT NAME FROM demo_table2); Output: We can see in the image that two entries are excluded as the values match from entry in demo_table2. Alternate Method: Alternatively, to exclude rows from demo_table1 whose values in the NAME column match the rows in the NAME column in demo_table2, we can perform it with left join. As we know, the left join returns all the rows in the left table and only matches rows in the right table, so the right table column’s values will be NULL if they don’t have matching rows. Hence, we will this concept of the left join with a condition that the right table’s column value is null. The query for the above content using Left Join and Condition: select t1.* from demo_table1 t1 left join demo_table2 t2 on t1.name = t2.name where t2.name is null This returns, the required data set. cr10acsmbyomnuv8xm2zdncmpmtnnbpo1eqf2v0z Picked SQL-Query SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 May, 2022" }, { "code": null, "e": 273, "s": 28, "text": "In this article, we will see, how to write the SQL Query to exclude records if it matches an entry in another table. We can perform the above function using the NOT IN operator in SQL. For obtaining the list of values we can write the subquery." }, { "code": null, "e": 398, "s": 273, "text": "NOT IN operators acts as a negation of In operator and return the results excluding the items present in the specified list." }, { "code": null, "e": 414, "s": 398, "text": "Syntax: NOT IN " }, { "code": null, "e": 472, "s": 414, "text": "SELECT * FROM table_name WHERE column_name NOT IN (list);" }, { "code": null, "e": 523, "s": 472, "text": "Now, for the demonstration follow the below steps:" }, { "code": null, "e": 549, "s": 523, "text": "Step 1: Create a database" }, { "code": null, "e": 617, "s": 549, "text": "we can use the following command to create a database called geeks." }, { "code": null, "e": 624, "s": 617, "text": "Query:" }, { "code": null, "e": 647, "s": 624, "text": "CREATE DATABASE geeks;" }, { "code": null, "e": 672, "s": 647, "text": "Step 2: Use the database" }, { "code": null, "e": 741, "s": 672, "text": "Use the below SQL statement to switch the database context to geeks:" }, { "code": null, "e": 748, "s": 741, "text": "Query:" }, { "code": null, "e": 759, "s": 748, "text": "USE geeks;" }, { "code": null, "e": 784, "s": 759, "text": "Step 3: Table definition" }, { "code": null, "e": 865, "s": 784, "text": "We have two tables named ‘demo_table1’ and ‘demo_table2’ in our geek’s database." }, { "code": null, "e": 885, "s": 865, "text": "Query(demo_table1):" }, { "code": null, "e": 958, "s": 885, "text": "CREATE TABLE demo_table1(\nNAME VARCHAR(20),\nAGE INT,\nCITY VARCHAR(20) );" }, { "code": null, "e": 978, "s": 958, "text": "Query(demo_table2):" }, { "code": null, "e": 1032, "s": 978, "text": "CREATE TABLE demo_table2(\nNAME VARCHAR(20),\nAGE int);" }, { "code": null, "e": 1065, "s": 1032, "text": "Step 4: Insert data into a table" }, { "code": null, "e": 1085, "s": 1065, "text": "Query(demo_table1):" }, { "code": null, "e": 1351, "s": 1085, "text": "INSERT INTO demo_table1 VALUES\n('Romy',23,'Delhi'),\n('Rahul',23,'Delhi'),\n('Nikhil',24,'Punjab'),\n('Ranvir',23,'Punjab'),\n('Samiksha',23,'Banglore'),\n('Ashtha',24,'Banglore'),\n('Tannu',30,'Patna'),\n('Girish',30,'Patna'),\n('Ram', 20 , 'Patna'),\n('Raj', 12, 'Delhi');" }, { "code": null, "e": 1371, "s": 1351, "text": "Query(demo_table2):" }, { "code": null, "e": 1491, "s": 1371, "text": "INSERT INTO demo_table2 VALUES\n('Fanny',25 ),\n('Prem', 30), \n('Preeti',21),\n('Samita',32),\n('Rahul',23),\n('Ranvir',23);" }, { "code": null, "e": 1516, "s": 1491, "text": "Step 5: View the content" }, { "code": null, "e": 1572, "s": 1516, "text": "Execute the below query to see the content of the table" }, { "code": null, "e": 1579, "s": 1572, "text": "Query:" }, { "code": null, "e": 1606, "s": 1579, "text": "SELECT * FROM demo_table1;" }, { "code": null, "e": 1614, "s": 1606, "text": "Output:" }, { "code": null, "e": 1621, "s": 1614, "text": "Query:" }, { "code": null, "e": 1648, "s": 1621, "text": "SELECT * FROM demo_table2;" }, { "code": null, "e": 1656, "s": 1648, "text": "Output:" }, { "code": null, "e": 1732, "s": 1656, "text": "Step 6: Exclude data from demo_table1 based on matches found in demo_table2" }, { "code": null, "e": 1874, "s": 1732, "text": "For the demonstration, exclude the data from demo_table1 whose values in the NAME column match the entries in the Name column of demo_table2." }, { "code": null, "e": 1881, "s": 1874, "text": "Query:" }, { "code": null, "e": 1957, "s": 1881, "text": "SELECT * FROM demo_table1 WHERE NAME NOT IN (SELECT NAME FROM demo_table2);" }, { "code": null, "e": 1965, "s": 1957, "text": "Output:" }, { "code": null, "e": 2066, "s": 1965, "text": "We can see in the image that two entries are excluded as the values match from entry in demo_table2." }, { "code": null, "e": 2084, "s": 2066, "text": "Alternate Method:" }, { "code": null, "e": 2248, "s": 2084, "text": "Alternatively, to exclude rows from demo_table1 whose values in the NAME column match the rows in the NAME column in demo_table2, we can perform it with left join." }, { "code": null, "e": 2544, "s": 2248, "text": "As we know, the left join returns all the rows in the left table and only matches rows in the right table, so the right table column’s values will be NULL if they don’t have matching rows. Hence, we will this concept of the left join with a condition that the right table’s column value is null." }, { "code": null, "e": 2607, "s": 2544, "text": "The query for the above content using Left Join and Condition:" }, { "code": null, "e": 2708, "s": 2607, "text": "select t1.* from demo_table1 t1 left join demo_table2 t2 on t1.name = t2.name where t2.name is null" }, { "code": null, "e": 2745, "s": 2708, "text": "This returns, the required data set." }, { "code": null, "e": 2786, "s": 2745, "text": "cr10acsmbyomnuv8xm2zdncmpmtnnbpo1eqf2v0z" }, { "code": null, "e": 2793, "s": 2786, "text": "Picked" }, { "code": null, "e": 2803, "s": 2793, "text": "SQL-Query" }, { "code": null, "e": 2814, "s": 2803, "text": "SQL-Server" }, { "code": null, "e": 2818, "s": 2814, "text": "SQL" }, { "code": null, "e": 2822, "s": 2818, "text": "SQL" } ]
Kotlin for loop - GeeksforGeeks
20 May, 2019 In Kotlin, for loop is equivalent to foreach loop of other languages like C#. Here for loop is used to traverse through any data structure which provides an iterator. It is used very differently then the for loop of other programming languages like Java or C. The syntax of for loop in Kotlin: for(item in collection) { // code to execute } In Kotlin, for loop is used to iterate through the following because all of them provides iterator. Range Array String Collection You can traverse through Range because it provides iterator. There are many ways you can iterate through Range. The in operator used in for loop to check value lies within the Range or not.Below programs are example of traversing the range in different ways and in is the operator to check the value in the range. If value lies in between range then it returns true and prints the value. Iterate through range to print the values:fun main(args: Array<String>){ for (i in 1..6) { print("$i ") }}Output:1 2 3 4 5 6 fun main(args: Array<String>){ for (i in 1..6) { print("$i ") }} Output: 1 2 3 4 5 6 Iterate through range to jump using step-3 :fun main(args: Array<String>){ for (i in 1..10 step 3) { print("$i ") }}Output:1 4 7 10 fun main(args: Array<String>){ for (i in 1..10 step 3) { print("$i ") }} Output: 1 4 7 10 You can not iterate through Range from top to down without using DownTo :fun main(args: Array<String>){ for (i in 5..1) { print("$i ") } println("It prints nothing")}Output:It prints nothing fun main(args: Array<String>){ for (i in 5..1) { print("$i ") } println("It prints nothing")} Output: It prints nothing Iterate through Range from top to down with using downTo :fun main(args: Array<String>){ for (i in 5 downTo 1) { print("$i ") }}Output:5 4 3 2 1 fun main(args: Array<String>){ for (i in 5 downTo 1) { print("$i ") }} Output: 5 4 3 2 1 Iterate through Range from top to down with using downTo and step 3:fun main(args: Array<String>){ for (i in 10 downTo 1 step 3) { print("$i ") }}Output:10 7 4 1Iterate through array using for loop –An array is a data structure which contains same data type like Integer or String. Array can be traversed using for loop because it also provides iterator. Each array has a starting index and by default, it is 0.There are the following you can traverse array:Without using Index propertyWith Using Index propertyUsing withIndex Library FunctionTraverse an array without using index property:fun main(args: Array<String>) { var numbers = arrayOf(1,2,3,4,5,6,7,8,9,10) for (num in numbers){ if(num%2 == 0){ print("$num ") } }}Output:2 4 6 8 10Traverse an array with using index property:fun main(args: Array<String>) { var planets = arrayOf("Earth", "Mars", "Venus", "Jupiter", "Saturn") for (i in planets.indices) { println(planets[i]) }}Output:Earth Mars Venus Jupiter Saturn Traverse an array using withIndex() Library Function:fun main(args: Array<String>) { var planets = arrayOf("Earth", "Mars", "Venus", "Jupiter", "Saturn") for ((index,value) in planets.withIndex()) { println("Element at $index th index is $value") }}Output:Element at 0 th index is Earth Element at 1 th index is Mars Element at 2 th index is Venus Element at 3 th index is Jupiter Element at 4 th index is Saturn Iterate through string using for loop –A string can be traversed using the for loop because it also provides iterator.There are following ways to traverse the string:Without using Index propertyWith Using Index propertyUsing withIndex Library Functionfun main(args: Array<String>) { var name = "Geeks" var name2 = "forGeeks" // traversing string without using index property for (alphabet in name) print("$alphabet ") // traversing string with using index property for (i in name2.indices) print(name2[i]+" ") println(" ") // traversing string using withIndex() library function for ((index,value) in name.withIndex()) println("Element at $index th index is $value")}Output:G e e k s f o r G e e k s Element at 0 th index is G Element at 1 th index is e Element at 2 th index is e Element at 3 th index is k Element at 4 th index is s Iterate through collection using for loop –You can traverse the collection using the for loop. There are three types of collections list, map and set.In the listOf() function we can pass the different data types at the same time.Below is the program to traverse the list using for loop.fun main(args: Array<String>) { // read only, fix-size var collection = listOf(1,2,3,"listOf", "mapOf", "setOf") for (element in collection) { println(element) }}Output:1 2 3 listOf mapOf setOf My Personal Notes arrow_drop_upSave fun main(args: Array<String>){ for (i in 10 downTo 1 step 3) { print("$i ") }} Output: 10 7 4 1 An array is a data structure which contains same data type like Integer or String. Array can be traversed using for loop because it also provides iterator. Each array has a starting index and by default, it is 0. There are the following you can traverse array: Without using Index property With Using Index property Using withIndex Library Function Traverse an array without using index property:fun main(args: Array<String>) { var numbers = arrayOf(1,2,3,4,5,6,7,8,9,10) for (num in numbers){ if(num%2 == 0){ print("$num ") } }}Output:2 4 6 8 10 fun main(args: Array<String>) { var numbers = arrayOf(1,2,3,4,5,6,7,8,9,10) for (num in numbers){ if(num%2 == 0){ print("$num ") } }} Output: 2 4 6 8 10 Traverse an array with using index property:fun main(args: Array<String>) { var planets = arrayOf("Earth", "Mars", "Venus", "Jupiter", "Saturn") for (i in planets.indices) { println(planets[i]) }}Output:Earth Mars Venus Jupiter Saturn fun main(args: Array<String>) { var planets = arrayOf("Earth", "Mars", "Venus", "Jupiter", "Saturn") for (i in planets.indices) { println(planets[i]) }} Output: Earth Mars Venus Jupiter Saturn Traverse an array using withIndex() Library Function:fun main(args: Array<String>) { var planets = arrayOf("Earth", "Mars", "Venus", "Jupiter", "Saturn") for ((index,value) in planets.withIndex()) { println("Element at $index th index is $value") }}Output:Element at 0 th index is Earth Element at 1 th index is Mars Element at 2 th index is Venus Element at 3 th index is Jupiter Element at 4 th index is Saturn fun main(args: Array<String>) { var planets = arrayOf("Earth", "Mars", "Venus", "Jupiter", "Saturn") for ((index,value) in planets.withIndex()) { println("Element at $index th index is $value") }} Output: Element at 0 th index is Earth Element at 1 th index is Mars Element at 2 th index is Venus Element at 3 th index is Jupiter Element at 4 th index is Saturn A string can be traversed using the for loop because it also provides iterator. There are following ways to traverse the string: Without using Index property With Using Index property Using withIndex Library Function fun main(args: Array<String>) { var name = "Geeks" var name2 = "forGeeks" // traversing string without using index property for (alphabet in name) print("$alphabet ") // traversing string with using index property for (i in name2.indices) print(name2[i]+" ") println(" ") // traversing string using withIndex() library function for ((index,value) in name.withIndex()) println("Element at $index th index is $value")} Output: G e e k s f o r G e e k s Element at 0 th index is G Element at 1 th index is e Element at 2 th index is e Element at 3 th index is k Element at 4 th index is s You can traverse the collection using the for loop. There are three types of collections list, map and set.In the listOf() function we can pass the different data types at the same time. Below is the program to traverse the list using for loop. fun main(args: Array<String>) { // read only, fix-size var collection = listOf(1,2,3,"listOf", "mapOf", "setOf") for (element in collection) { println(element) }} Output: 1 2 3 listOf mapOf setOf Kotlin Control-flow Kotlin Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Android RecyclerView in Kotlin Retrofit with Kotlin Coroutine in Android How to Get Current Location in Android? Android Menus Kotlin Higher-Order Functions ImageView in Android with Example How to Build a Weather App in Android? Android SQLite Database in Kotlin MVP (Model View Presenter) Architecture Pattern in Android with Example
[ { "code": null, "e": 25337, "s": 25309, "text": "\n20 May, 2019" }, { "code": null, "e": 25597, "s": 25337, "text": "In Kotlin, for loop is equivalent to foreach loop of other languages like C#. Here for loop is used to traverse through any data structure which provides an iterator. It is used very differently then the for loop of other programming languages like Java or C." }, { "code": null, "e": 25631, "s": 25597, "text": "The syntax of for loop in Kotlin:" }, { "code": null, "e": 25686, "s": 25631, "text": "for(item in collection) {\n // code to execute\n}\n" }, { "code": null, "e": 25786, "s": 25686, "text": "In Kotlin, for loop is used to iterate through the following because all of them provides iterator." }, { "code": null, "e": 25792, "s": 25786, "text": "Range" }, { "code": null, "e": 25798, "s": 25792, "text": "Array" }, { "code": null, "e": 25805, "s": 25798, "text": "String" }, { "code": null, "e": 25816, "s": 25805, "text": "Collection" }, { "code": null, "e": 26204, "s": 25816, "text": "You can traverse through Range because it provides iterator. There are many ways you can iterate through Range. The in operator used in for loop to check value lies within the Range or not.Below programs are example of traversing the range in different ways and in is the operator to check the value in the range. If value lies in between range then it returns true and prints the value." }, { "code": null, "e": 26342, "s": 26204, "text": "Iterate through range to print the values:fun main(args: Array<String>){ for (i in 1..6) { print(\"$i \") }}Output:1 2 3 4 5 6" }, { "code": "fun main(args: Array<String>){ for (i in 1..6) { print(\"$i \") }}", "e": 26420, "s": 26342, "text": null }, { "code": null, "e": 26428, "s": 26420, "text": "Output:" }, { "code": null, "e": 26440, "s": 26428, "text": "1 2 3 4 5 6" }, { "code": null, "e": 26585, "s": 26440, "text": "Iterate through range to jump using step-3 :fun main(args: Array<String>){ for (i in 1..10 step 3) { print(\"$i \") }}Output:1 4 7 10" }, { "code": "fun main(args: Array<String>){ for (i in 1..10 step 3) { print(\"$i \") }}", "e": 26671, "s": 26585, "text": null }, { "code": null, "e": 26679, "s": 26671, "text": "Output:" }, { "code": null, "e": 26688, "s": 26679, "text": "1 4 7 10" }, { "code": null, "e": 26895, "s": 26688, "text": "You can not iterate through Range from top to down without using DownTo :fun main(args: Array<String>){ for (i in 5..1) { print(\"$i \") } println(\"It prints nothing\")}Output:It prints nothing" }, { "code": "fun main(args: Array<String>){ for (i in 5..1) { print(\"$i \") } println(\"It prints nothing\")}", "e": 27005, "s": 26895, "text": null }, { "code": null, "e": 27013, "s": 27005, "text": "Output:" }, { "code": null, "e": 27031, "s": 27013, "text": "It prints nothing" }, { "code": null, "e": 27189, "s": 27031, "text": "Iterate through Range from top to down with using downTo :fun main(args: Array<String>){ for (i in 5 downTo 1) { print(\"$i \") }}Output:5 4 3 2 1" }, { "code": "fun main(args: Array<String>){ for (i in 5 downTo 1) { print(\"$i \") }}", "e": 27273, "s": 27189, "text": null }, { "code": null, "e": 27281, "s": 27273, "text": "Output:" }, { "code": null, "e": 27291, "s": 27281, "text": "5 4 3 2 1" }, { "code": null, "e": 30188, "s": 27291, "text": "Iterate through Range from top to down with using downTo and step 3:fun main(args: Array<String>){ for (i in 10 downTo 1 step 3) { print(\"$i \") }}Output:10 7 4 1Iterate through array using for loop –An array is a data structure which contains same data type like Integer or String. Array can be traversed using for loop because it also provides iterator. Each array has a starting index and by default, it is 0.There are the following you can traverse array:Without using Index propertyWith Using Index propertyUsing withIndex Library FunctionTraverse an array without using index property:fun main(args: Array<String>) { var numbers = arrayOf(1,2,3,4,5,6,7,8,9,10) for (num in numbers){ if(num%2 == 0){ print(\"$num \") } }}Output:2 4 6 8 10Traverse an array with using index property:fun main(args: Array<String>) { var planets = arrayOf(\"Earth\", \"Mars\", \"Venus\", \"Jupiter\", \"Saturn\") for (i in planets.indices) { println(planets[i]) }}Output:Earth\nMars\nVenus\nJupiter\nSaturn\nTraverse an array using withIndex() Library Function:fun main(args: Array<String>) { var planets = arrayOf(\"Earth\", \"Mars\", \"Venus\", \"Jupiter\", \"Saturn\") for ((index,value) in planets.withIndex()) { println(\"Element at $index th index is $value\") }}Output:Element at 0 th index is Earth\nElement at 1 th index is Mars\nElement at 2 th index is Venus\nElement at 3 th index is Jupiter\nElement at 4 th index is Saturn\nIterate through string using for loop –A string can be traversed using the for loop because it also provides iterator.There are following ways to traverse the string:Without using Index propertyWith Using Index propertyUsing withIndex Library Functionfun main(args: Array<String>) { var name = \"Geeks\" var name2 = \"forGeeks\" // traversing string without using index property for (alphabet in name) print(\"$alphabet \") // traversing string with using index property for (i in name2.indices) print(name2[i]+\" \") println(\" \") // traversing string using withIndex() library function for ((index,value) in name.withIndex()) println(\"Element at $index th index is $value\")}Output:G e e k s f o r G e e k s \nElement at 0 th index is G\nElement at 1 th index is e\nElement at 2 th index is e\nElement at 3 th index is k\nElement at 4 th index is s\nIterate through collection using for loop –You can traverse the collection using the for loop. There are three types of collections list, map and set.In the listOf() function we can pass the different data types at the same time.Below is the program to traverse the list using for loop.fun main(args: Array<String>) { // read only, fix-size var collection = listOf(1,2,3,\"listOf\", \"mapOf\", \"setOf\") for (element in collection) { println(element) }}Output:1\n2\n3\nlistOf\nmapOf\nsetOf\nMy Personal Notes\narrow_drop_upSave" }, { "code": "fun main(args: Array<String>){ for (i in 10 downTo 1 step 3) { print(\"$i \") }}", "e": 30280, "s": 30188, "text": null }, { "code": null, "e": 30288, "s": 30280, "text": "Output:" }, { "code": null, "e": 30297, "s": 30288, "text": "10 7 4 1" }, { "code": null, "e": 30510, "s": 30297, "text": "An array is a data structure which contains same data type like Integer or String. Array can be traversed using for loop because it also provides iterator. Each array has a starting index and by default, it is 0." }, { "code": null, "e": 30558, "s": 30510, "text": "There are the following you can traverse array:" }, { "code": null, "e": 30587, "s": 30558, "text": "Without using Index property" }, { "code": null, "e": 30613, "s": 30587, "text": "With Using Index property" }, { "code": null, "e": 30646, "s": 30613, "text": "Using withIndex Library Function" }, { "code": null, "e": 30880, "s": 30646, "text": "Traverse an array without using index property:fun main(args: Array<String>) { var numbers = arrayOf(1,2,3,4,5,6,7,8,9,10) for (num in numbers){ if(num%2 == 0){ print(\"$num \") } }}Output:2 4 6 8 10" }, { "code": "fun main(args: Array<String>) { var numbers = arrayOf(1,2,3,4,5,6,7,8,9,10) for (num in numbers){ if(num%2 == 0){ print(\"$num \") } }}", "e": 31050, "s": 30880, "text": null }, { "code": null, "e": 31058, "s": 31050, "text": "Output:" }, { "code": null, "e": 31069, "s": 31058, "text": "2 4 6 8 10" }, { "code": null, "e": 31325, "s": 31069, "text": "Traverse an array with using index property:fun main(args: Array<String>) { var planets = arrayOf(\"Earth\", \"Mars\", \"Venus\", \"Jupiter\", \"Saturn\") for (i in planets.indices) { println(planets[i]) }}Output:Earth\nMars\nVenus\nJupiter\nSaturn\n" }, { "code": "fun main(args: Array<String>) { var planets = arrayOf(\"Earth\", \"Mars\", \"Venus\", \"Jupiter\", \"Saturn\") for (i in planets.indices) { println(planets[i]) }}", "e": 31498, "s": 31325, "text": null }, { "code": null, "e": 31506, "s": 31498, "text": "Output:" }, { "code": null, "e": 31539, "s": 31506, "text": "Earth\nMars\nVenus\nJupiter\nSaturn\n" }, { "code": null, "e": 31971, "s": 31539, "text": "Traverse an array using withIndex() Library Function:fun main(args: Array<String>) { var planets = arrayOf(\"Earth\", \"Mars\", \"Venus\", \"Jupiter\", \"Saturn\") for ((index,value) in planets.withIndex()) { println(\"Element at $index th index is $value\") }}Output:Element at 0 th index is Earth\nElement at 1 th index is Mars\nElement at 2 th index is Venus\nElement at 3 th index is Jupiter\nElement at 4 th index is Saturn\n" }, { "code": "fun main(args: Array<String>) { var planets = arrayOf(\"Earth\", \"Mars\", \"Venus\", \"Jupiter\", \"Saturn\") for ((index,value) in planets.withIndex()) { println(\"Element at $index th index is $value\") }}", "e": 32186, "s": 31971, "text": null }, { "code": null, "e": 32194, "s": 32186, "text": "Output:" }, { "code": null, "e": 32352, "s": 32194, "text": "Element at 0 th index is Earth\nElement at 1 th index is Mars\nElement at 2 th index is Venus\nElement at 3 th index is Jupiter\nElement at 4 th index is Saturn\n" }, { "code": null, "e": 32432, "s": 32352, "text": "A string can be traversed using the for loop because it also provides iterator." }, { "code": null, "e": 32481, "s": 32432, "text": "There are following ways to traverse the string:" }, { "code": null, "e": 32510, "s": 32481, "text": "Without using Index property" }, { "code": null, "e": 32536, "s": 32510, "text": "With Using Index property" }, { "code": null, "e": 32569, "s": 32536, "text": "Using withIndex Library Function" }, { "code": "fun main(args: Array<String>) { var name = \"Geeks\" var name2 = \"forGeeks\" // traversing string without using index property for (alphabet in name) print(\"$alphabet \") // traversing string with using index property for (i in name2.indices) print(name2[i]+\" \") println(\" \") // traversing string using withIndex() library function for ((index,value) in name.withIndex()) println(\"Element at $index th index is $value\")}", "e": 33032, "s": 32569, "text": null }, { "code": null, "e": 33040, "s": 33032, "text": "Output:" }, { "code": null, "e": 33204, "s": 33040, "text": "G e e k s f o r G e e k s \nElement at 0 th index is G\nElement at 1 th index is e\nElement at 2 th index is e\nElement at 3 th index is k\nElement at 4 th index is s\n" }, { "code": null, "e": 33391, "s": 33204, "text": "You can traverse the collection using the for loop. There are three types of collections list, map and set.In the listOf() function we can pass the different data types at the same time." }, { "code": null, "e": 33449, "s": 33391, "text": "Below is the program to traverse the list using for loop." }, { "code": "fun main(args: Array<String>) { // read only, fix-size var collection = listOf(1,2,3,\"listOf\", \"mapOf\", \"setOf\") for (element in collection) { println(element) }}", "e": 33635, "s": 33449, "text": null }, { "code": null, "e": 33643, "s": 33635, "text": "Output:" }, { "code": null, "e": 33669, "s": 33643, "text": "1\n2\n3\nlistOf\nmapOf\nsetOf\n" }, { "code": null, "e": 33689, "s": 33669, "text": "Kotlin Control-flow" }, { "code": null, "e": 33696, "s": 33689, "text": "Kotlin" }, { "code": null, "e": 33794, "s": 33696, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33825, "s": 33794, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 33867, "s": 33825, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 33907, "s": 33867, "text": "How to Get Current Location in Android?" }, { "code": null, "e": 33921, "s": 33907, "text": "Android Menus" }, { "code": null, "e": 33951, "s": 33921, "text": "Kotlin Higher-Order Functions" }, { "code": null, "e": 33985, "s": 33951, "text": "ImageView in Android with Example" }, { "code": null, "e": 34024, "s": 33985, "text": "How to Build a Weather App in Android?" }, { "code": null, "e": 34058, "s": 34024, "text": "Android SQLite Database in Kotlin" } ]
Sunny Number - GeeksforGeeks
07 Jun, 2021 Given a positive integer N, the task is to check whether the given number N is Sunny Number or not. A number N is a sunny number if N + 1 is a perfect square. Examples: Input: N = 8 Output: Yes Explanation: Since 9 is a perfect square. therefore 8 is a sunny number. Input: N = 11 Output: No Explanation: Since 12 is not a perfect square. therefore 8 is not a sunny number. Approach: The idea is to check whether (N + 1) is a perfect square or not.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach #include "bits/stdc++.h"using namespace std; // Function check whether x is a// perfect square or notbool isPerfectSquare(long double x){ // Find floating point value of // square root of x. long double sr = sqrt(x); // If square root is an integer return((sr - floor(sr)) == 0);} // Function to check Sunny Numbervoid checkSunnyNumber(int N){ // Check if (N + 1) is a perfect // square or not if (isPerfectSquare(N + 1)) { cout << "Yes\n"; } // If (N+1) is not a perfect square else { cout << "No\n"; }} // Driver Codeint main(){ // Given Number int N = 8; // Function call checkSunnyNumber(N); return 0;} // Java program for the above approachimport java.util.*; class GFG { // Function check whether x is a// perfect square or notstatic boolean isPerfectSquare(double x){ // Find floating point value of // square root of x. double sr = Math.sqrt(x); // If square root is an integer return((sr - Math.floor(sr)) == 0);} // Function to check Sunny Numberstatic void checkSunnyNumber(int N){ // Check if (N + 1) is a perfect // square or not if (isPerfectSquare(N + 1)) { System.out.println("Yes"); } // If (N+1) is not a perfect square else { System.out.println("No"); }} // Driver codepublic static void main(String[] args){ // Given Number int N = 8; // Function call checkSunnyNumber(N);}} // This code is contributed by offbeat # Python3 program for the above approachfrom math import * # Function check whether x is a# perfect square or notdef isPerfectSquare(x): # Find floating point value of # square root of x. sr = sqrt(x) # If square root is an integer return((sr - floor(sr)) == 0) # Function to check Sunny Numberdef checkSunnyNumber(N): # Check if (N + 1) is a perfect # square or not if (isPerfectSquare(N + 1)): print("Yes") # If (N+1) is not a perfect square else: print("No") # Driver Codeif __name__ == '__main__': # Given Number N = 8 # Function call checkSunnyNumber(N) # This code is contributed by Bhupendra_Singh // C# program for the above approachusing System; class GFG { // Function check whether x is// a perfect square or notstatic bool isPerfectSquare(double x){ // Find floating point value of // square root of x. double sr = Math.Sqrt(x); // If square root is an integer return((sr - Math.Floor(sr)) == 0);} // Function to check sunny numberstatic void checkSunnyNumber(int N){ // Check if (N + 1) is a perfect // square or not if (isPerfectSquare(N + 1)) { Console.WriteLine("Yes"); } // If (N+1) is not a perfect square else { Console.WriteLine("No"); }} // Driver codepublic static void Main(String[] args){ // Given Number int N = 8; // Function call checkSunnyNumber(N);}} // This code is contributed by Rohit_ranjan <script>// Javascript program for the above approach // Function check whether x is a// perfect square or notfunction isPerfectSquare(x){ // Find floating point value of // square root of x. var sr = Math.sqrt(x); // If square root is an integer return((sr - Math.floor(sr)) == 0);} // Function to check Sunny Numberfunction checkSunnyNumber(N){ // Check if (N + 1) is a perfect // square or not if (isPerfectSquare(N + 1)) { document.write( "Yes"); } // If (N+1) is not a perfect square else { document.write( "No"); }} // Driver Code// Given Numbervar N = 8; // Function callcheckSunnyNumber(N); // This code is contributed by noob2000.</script> Yes Time Complexity: O(1) Auxiliary Space: O(1) offbeat Rohit_ranjan bgangwar59 aditya7409 noob2000 maths-perfect-square Mathematical School Programming Write From Home Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to find GCD or HCF of two numbers Median in a stream of integers (running integers) Program to multiply two matrices Merge two sorted arrays Generate all permutation of a set in Python Python Dictionary Arrays in C/C++ Reverse a string in Java Inheritance in C++ Types of Operating Systems
[ { "code": null, "e": 25667, "s": 25639, "text": "\n07 Jun, 2021" }, { "code": null, "e": 25767, "s": 25667, "text": "Given a positive integer N, the task is to check whether the given number N is Sunny Number or not." }, { "code": null, "e": 25826, "s": 25767, "text": "A number N is a sunny number if N + 1 is a perfect square." }, { "code": null, "e": 25838, "s": 25826, "text": "Examples: " }, { "code": null, "e": 25936, "s": 25838, "text": "Input: N = 8 Output: Yes Explanation: Since 9 is a perfect square. therefore 8 is a sunny number." }, { "code": null, "e": 26044, "s": 25936, "text": "Input: N = 11 Output: No Explanation: Since 12 is not a perfect square. therefore 8 is not a sunny number. " }, { "code": null, "e": 26170, "s": 26044, "text": "Approach: The idea is to check whether (N + 1) is a perfect square or not.Below is the implementation of the above approach: " }, { "code": null, "e": 26174, "s": 26170, "text": "C++" }, { "code": null, "e": 26179, "s": 26174, "text": "Java" }, { "code": null, "e": 26187, "s": 26179, "text": "Python3" }, { "code": null, "e": 26190, "s": 26187, "text": "C#" }, { "code": null, "e": 26201, "s": 26190, "text": "Javascript" }, { "code": "// C++ program for the above approach #include \"bits/stdc++.h\"using namespace std; // Function check whether x is a// perfect square or notbool isPerfectSquare(long double x){ // Find floating point value of // square root of x. long double sr = sqrt(x); // If square root is an integer return((sr - floor(sr)) == 0);} // Function to check Sunny Numbervoid checkSunnyNumber(int N){ // Check if (N + 1) is a perfect // square or not if (isPerfectSquare(N + 1)) { cout << \"Yes\\n\"; } // If (N+1) is not a perfect square else { cout << \"No\\n\"; }} // Driver Codeint main(){ // Given Number int N = 8; // Function call checkSunnyNumber(N); return 0;}", "e": 26917, "s": 26201, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG { // Function check whether x is a// perfect square or notstatic boolean isPerfectSquare(double x){ // Find floating point value of // square root of x. double sr = Math.sqrt(x); // If square root is an integer return((sr - Math.floor(sr)) == 0);} // Function to check Sunny Numberstatic void checkSunnyNumber(int N){ // Check if (N + 1) is a perfect // square or not if (isPerfectSquare(N + 1)) { System.out.println(\"Yes\"); } // If (N+1) is not a perfect square else { System.out.println(\"No\"); }} // Driver codepublic static void main(String[] args){ // Given Number int N = 8; // Function call checkSunnyNumber(N);}} // This code is contributed by offbeat", "e": 27726, "s": 26917, "text": null }, { "code": "# Python3 program for the above approachfrom math import * # Function check whether x is a# perfect square or notdef isPerfectSquare(x): # Find floating point value of # square root of x. sr = sqrt(x) # If square root is an integer return((sr - floor(sr)) == 0) # Function to check Sunny Numberdef checkSunnyNumber(N): # Check if (N + 1) is a perfect # square or not if (isPerfectSquare(N + 1)): print(\"Yes\") # If (N+1) is not a perfect square else: print(\"No\") # Driver Codeif __name__ == '__main__': # Given Number N = 8 # Function call checkSunnyNumber(N) # This code is contributed by Bhupendra_Singh", "e": 28405, "s": 27726, "text": null }, { "code": "// C# program for the above approachusing System; class GFG { // Function check whether x is// a perfect square or notstatic bool isPerfectSquare(double x){ // Find floating point value of // square root of x. double sr = Math.Sqrt(x); // If square root is an integer return((sr - Math.Floor(sr)) == 0);} // Function to check sunny numberstatic void checkSunnyNumber(int N){ // Check if (N + 1) is a perfect // square or not if (isPerfectSquare(N + 1)) { Console.WriteLine(\"Yes\"); } // If (N+1) is not a perfect square else { Console.WriteLine(\"No\"); }} // Driver codepublic static void Main(String[] args){ // Given Number int N = 8; // Function call checkSunnyNumber(N);}} // This code is contributed by Rohit_ranjan", "e": 29210, "s": 28405, "text": null }, { "code": "<script>// Javascript program for the above approach // Function check whether x is a// perfect square or notfunction isPerfectSquare(x){ // Find floating point value of // square root of x. var sr = Math.sqrt(x); // If square root is an integer return((sr - Math.floor(sr)) == 0);} // Function to check Sunny Numberfunction checkSunnyNumber(N){ // Check if (N + 1) is a perfect // square or not if (isPerfectSquare(N + 1)) { document.write( \"Yes\"); } // If (N+1) is not a perfect square else { document.write( \"No\"); }} // Driver Code// Given Numbervar N = 8; // Function callcheckSunnyNumber(N); // This code is contributed by noob2000.</script>", "e": 29912, "s": 29210, "text": null }, { "code": null, "e": 29916, "s": 29912, "text": "Yes" }, { "code": null, "e": 29940, "s": 29918, "text": "Time Complexity: O(1)" }, { "code": null, "e": 29962, "s": 29940, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 29970, "s": 29962, "text": "offbeat" }, { "code": null, "e": 29983, "s": 29970, "text": "Rohit_ranjan" }, { "code": null, "e": 29994, "s": 29983, "text": "bgangwar59" }, { "code": null, "e": 30005, "s": 29994, "text": "aditya7409" }, { "code": null, "e": 30014, "s": 30005, "text": "noob2000" }, { "code": null, "e": 30035, "s": 30014, "text": "maths-perfect-square" }, { "code": null, "e": 30048, "s": 30035, "text": "Mathematical" }, { "code": null, "e": 30067, "s": 30048, "text": "School Programming" }, { "code": null, "e": 30083, "s": 30067, "text": "Write From Home" }, { "code": null, "e": 30096, "s": 30083, "text": "Mathematical" }, { "code": null, "e": 30194, "s": 30096, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30236, "s": 30194, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 30286, "s": 30236, "text": "Median in a stream of integers (running integers)" }, { "code": null, "e": 30319, "s": 30286, "text": "Program to multiply two matrices" }, { "code": null, "e": 30343, "s": 30319, "text": "Merge two sorted arrays" }, { "code": null, "e": 30387, "s": 30343, "text": "Generate all permutation of a set in Python" }, { "code": null, "e": 30405, "s": 30387, "text": "Python Dictionary" }, { "code": null, "e": 30421, "s": 30405, "text": "Arrays in C/C++" }, { "code": null, "e": 30446, "s": 30421, "text": "Reverse a string in Java" }, { "code": null, "e": 30465, "s": 30446, "text": "Inheritance in C++" } ]
HTML | <select> name Attribute - GeeksforGeeks
27 May, 2019 The HTML <select> name Attribute is used to specify a name for the drop-down list. It is used to reference the form-data after submitting the form or to reference the element in a JavaScript. Syntax: <select name="text"> Attribute Values: It contains the value i.e name which specify the name for the <select> element. Example: <!DOCTYPE html><html> <head> <title> HTML Select name Attribute </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <h2 style="font-family: Impact;"> HTML Select name Attribute </h2> <br> Select your preferred course from the drop-down list: <br> <select name="Courses Titles" id="myCourses"> <option value="C++">c++</option> <option value="Placement">Placement</option> <option value="Java">Java</option> <option value="Python">Python</option> </select> </body> </html> Output: Supported Browsers: Google Chrome Firefox Edge Opera Apple Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Attributes HTML Web Technologies HTML 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 ? REST API (Introduction) How to position a div at the bottom of its container using CSS? Form validation using HTML and JavaScript HTML Cheat Sheet - A Basic Guide to HTML Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26149, "s": 26121, "text": "\n27 May, 2019" }, { "code": null, "e": 26341, "s": 26149, "text": "The HTML <select> name Attribute is used to specify a name for the drop-down list. It is used to reference the form-data after submitting the form or to reference the element in a JavaScript." }, { "code": null, "e": 26349, "s": 26341, "text": "Syntax:" }, { "code": null, "e": 26371, "s": 26349, "text": "<select name=\"text\"> " }, { "code": null, "e": 26469, "s": 26371, "text": "Attribute Values: It contains the value i.e name which specify the name for the <select> element." }, { "code": null, "e": 26478, "s": 26469, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML Select name Attribute </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h2 style=\"font-family: Impact;\"> HTML Select name Attribute </h2> <br> Select your preferred course from the drop-down list: <br> <select name=\"Courses Titles\" id=\"myCourses\"> <option value=\"C++\">c++</option> <option value=\"Placement\">Placement</option> <option value=\"Java\">Java</option> <option value=\"Python\">Python</option> </select> </body> </html>", "e": 27087, "s": 26478, "text": null }, { "code": null, "e": 27095, "s": 27087, "text": "Output:" }, { "code": null, "e": 27115, "s": 27095, "text": "Supported Browsers:" }, { "code": null, "e": 27129, "s": 27115, "text": "Google Chrome" }, { "code": null, "e": 27137, "s": 27129, "text": "Firefox" }, { "code": null, "e": 27142, "s": 27137, "text": "Edge" }, { "code": null, "e": 27148, "s": 27142, "text": "Opera" }, { "code": null, "e": 27161, "s": 27148, "text": "Apple Safari" }, { "code": null, "e": 27298, "s": 27161, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 27314, "s": 27298, "text": "HTML-Attributes" }, { "code": null, "e": 27319, "s": 27314, "text": "HTML" }, { "code": null, "e": 27336, "s": 27319, "text": "Web Technologies" }, { "code": null, "e": 27341, "s": 27336, "text": "HTML" }, { "code": null, "e": 27439, "s": 27341, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27489, "s": 27439, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27513, "s": 27489, "text": "REST API (Introduction)" }, { "code": null, "e": 27577, "s": 27513, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 27619, "s": 27577, "text": "Form validation using HTML and JavaScript" }, { "code": null, "e": 27660, "s": 27619, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 27700, "s": 27660, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27733, "s": 27700, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27778, "s": 27733, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27821, "s": 27778, "text": "How to fetch data from an API in ReactJS ?" } ]
Get Indian Railways Station code Using Python - GeeksforGeeks
29 Dec, 2020 Web scraping is a technique to fetch data from websites. While surfing on the web, many websites don’t allow the user to save data for personal use. One way is to manually copy-paste the data, which both tedious and time-consuming. Web Scraping is the automation of the data extraction process from websites. This event is done with the help of web scraping software known as web scrapers. In this article, we are going to write Python scripts to scrape the Railways Station code using their city name. Examples: Input: new-delhi Output: NDLS Input: Patna Output: PNBE bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal. pip install bs4 requests: Request allows you to send HTTP/1.1 requests extremely easily. This module also does not come built-in with Python. To install this type the below command in the terminal. pip install requests Let’s see the stepwise execution of the script. Step 1: Import all dependence Python3 # import moduleimport requestsfrom bs4 import BeautifulSoup Step 2: Create a URL get function Python3 # user define function # Scrape the data def getdata(url): r = requests.get(url) return r.text Step 3:Now merge the City name into URL and pass the URL into the getdata() function and Convert that data into HTML code. Python3 # input by geekstation = "new-delhi" # urlurl = "https://www.mapsofindia.com/railways/station-code/"+station+".html" # pass the url# into getdata functionhtmldata=getdata(url)soup = BeautifulSoup(htmldata, 'html.parser') # display html codeprint(soup) Output: Step 4: Traverse the Station code from the HTML document. Python3 # traverse the station codedata = []for item in soup.find("table", class_="extrtable").find_all('b'): data.append(item.get_text())print(data[-1]) Output: NDLS Python web-scraping-exercises python-utility Web-scraping Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26205, "s": 26177, "text": "\n29 Dec, 2020" }, { "code": null, "e": 26595, "s": 26205, "text": "Web scraping is a technique to fetch data from websites. While surfing on the web, many websites don’t allow the user to save data for personal use. One way is to manually copy-paste the data, which both tedious and time-consuming. Web Scraping is the automation of the data extraction process from websites. This event is done with the help of web scraping software known as web scrapers." }, { "code": null, "e": 26708, "s": 26595, "text": "In this article, we are going to write Python scripts to scrape the Railways Station code using their city name." }, { "code": null, "e": 26718, "s": 26708, "text": "Examples:" }, { "code": null, "e": 26776, "s": 26718, "text": "Input: new-delhi\nOutput: NDLS\n\nInput: Patna\nOutput: PNBE\n" }, { "code": null, "e": 26969, "s": 26776, "text": "bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal." }, { "code": null, "e": 26986, "s": 26969, "text": "pip install bs4\n" }, { "code": null, "e": 27168, "s": 26986, "text": "requests: Request allows you to send HTTP/1.1 requests extremely easily. This module also does not come built-in with Python. To install this type the below command in the terminal." }, { "code": null, "e": 27190, "s": 27168, "text": "pip install requests\n" }, { "code": null, "e": 27238, "s": 27190, "text": "Let’s see the stepwise execution of the script." }, { "code": null, "e": 27268, "s": 27238, "text": "Step 1: Import all dependence" }, { "code": null, "e": 27276, "s": 27268, "text": "Python3" }, { "code": "# import moduleimport requestsfrom bs4 import BeautifulSoup", "e": 27336, "s": 27276, "text": null }, { "code": null, "e": 27370, "s": 27336, "text": "Step 2: Create a URL get function" }, { "code": null, "e": 27378, "s": 27370, "text": "Python3" }, { "code": "# user define function # Scrape the data def getdata(url): r = requests.get(url) return r.text", "e": 27481, "s": 27378, "text": null }, { "code": null, "e": 27604, "s": 27481, "text": "Step 3:Now merge the City name into URL and pass the URL into the getdata() function and Convert that data into HTML code." }, { "code": null, "e": 27612, "s": 27604, "text": "Python3" }, { "code": "# input by geekstation = \"new-delhi\" # urlurl = \"https://www.mapsofindia.com/railways/station-code/\"+station+\".html\" # pass the url# into getdata functionhtmldata=getdata(url)soup = BeautifulSoup(htmldata, 'html.parser') # display html codeprint(soup)", "e": 27867, "s": 27612, "text": null }, { "code": null, "e": 27875, "s": 27867, "text": "Output:" }, { "code": null, "e": 27933, "s": 27875, "text": "Step 4: Traverse the Station code from the HTML document." }, { "code": null, "e": 27941, "s": 27933, "text": "Python3" }, { "code": "# traverse the station codedata = []for item in soup.find(\"table\", class_=\"extrtable\").find_all('b'): data.append(item.get_text())print(data[-1])", "e": 28090, "s": 27941, "text": null }, { "code": null, "e": 28098, "s": 28090, "text": "Output:" }, { "code": null, "e": 28104, "s": 28098, "text": "NDLS\n" }, { "code": null, "e": 28134, "s": 28104, "text": "Python web-scraping-exercises" }, { "code": null, "e": 28149, "s": 28134, "text": "python-utility" }, { "code": null, "e": 28162, "s": 28149, "text": "Web-scraping" }, { "code": null, "e": 28169, "s": 28162, "text": "Python" }, { "code": null, "e": 28267, "s": 28169, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28285, "s": 28267, "text": "Python Dictionary" }, { "code": null, "e": 28320, "s": 28285, "text": "Read a file line by line in Python" }, { "code": null, "e": 28352, "s": 28320, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28374, "s": 28352, "text": "Enumerate() in Python" }, { "code": null, "e": 28416, "s": 28374, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28446, "s": 28416, "text": "Iterate over a list in Python" }, { "code": null, "e": 28472, "s": 28446, "text": "Python String | replace()" }, { "code": null, "e": 28501, "s": 28472, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28545, "s": 28501, "text": "Reading and Writing to text files in Python" } ]
Java Program to Replace All Line Breaks from Strings - GeeksforGeeks
28 Oct, 2021 Given a string, write a Java program to replace all line breaks from the given String. Examples Input - Geeks For Geeks Output - Geeks For Geeks Line Break: A line break (“\n”) is a single character that defines the line change. In order to replace all line breaks from strings replace() function can be used. String replace(): This method returns a new String object that contains the same sequence of characters as the original string, but with a given character replaced by another given character. Syntax: public String replace(char old,char new) Parameters: old: old character new: new character Returns value: Returns a string by replacing an old character with the new character Java // Java Program to Replace All// Line Breaks from Strings public class remove { public static void main(String[] args) { String s = "Replace\n" + " all\n" + " line\n" + " breaks\n" + " from\n" + " strings"; System.out.println( "Original String with line breaks - " + s); // replacing line breaks from string s = s.replace("\n", ""); System.out.println( "String after replacing line breaks - " + s); }} Original String with line breaks - Replace all line breaks from strings String after replacing line breaks - Replace all line breaks from strings nishkarshgandhi Java-Strings Picked Java Java Programs Java-Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Program to print ASCII Value of a character
[ { "code": null, "e": 25225, "s": 25197, "text": "\n28 Oct, 2021" }, { "code": null, "e": 25312, "s": 25225, "text": "Given a string, write a Java program to replace all line breaks from the given String." }, { "code": null, "e": 25321, "s": 25312, "text": "Examples" }, { "code": null, "e": 25395, "s": 25321, "text": "Input - Geeks\n For\n Geeks\n \nOutput - Geeks For Geeks" }, { "code": null, "e": 25480, "s": 25395, "text": "Line Break: A line break (“\\n”) is a single character that defines the line change. " }, { "code": null, "e": 25561, "s": 25480, "text": "In order to replace all line breaks from strings replace() function can be used." }, { "code": null, "e": 25753, "s": 25561, "text": "String replace(): This method returns a new String object that contains the same sequence of characters as the original string, but with a given character replaced by another given character." }, { "code": null, "e": 25761, "s": 25753, "text": "Syntax:" }, { "code": null, "e": 25802, "s": 25761, "text": "public String replace(char old,char new)" }, { "code": null, "e": 25814, "s": 25802, "text": "Parameters:" }, { "code": null, "e": 25833, "s": 25814, "text": "old: old character" }, { "code": null, "e": 25852, "s": 25833, "text": "new: new character" }, { "code": null, "e": 25937, "s": 25852, "text": "Returns value: Returns a string by replacing an old character with the new character" }, { "code": null, "e": 25942, "s": 25937, "text": "Java" }, { "code": "// Java Program to Replace All// Line Breaks from Strings public class remove { public static void main(String[] args) { String s = \"Replace\\n\" + \" all\\n\" + \" line\\n\" + \" breaks\\n\" + \" from\\n\" + \" strings\"; System.out.println( \"Original String with line breaks - \" + s); // replacing line breaks from string s = s.replace(\"\\n\", \"\"); System.out.println( \"String after replacing line breaks - \" + s); }}", "e": 26521, "s": 25942, "text": null }, { "code": null, "e": 26672, "s": 26521, "text": "Original String with line breaks - Replace\n all\n line\n breaks\n from\n strings\nString after replacing line breaks - Replace all line breaks from strings" }, { "code": null, "e": 26688, "s": 26672, "text": "nishkarshgandhi" }, { "code": null, "e": 26701, "s": 26688, "text": "Java-Strings" }, { "code": null, "e": 26708, "s": 26701, "text": "Picked" }, { "code": null, "e": 26713, "s": 26708, "text": "Java" }, { "code": null, "e": 26727, "s": 26713, "text": "Java Programs" }, { "code": null, "e": 26740, "s": 26727, "text": "Java-Strings" }, { "code": null, "e": 26745, "s": 26740, "text": "Java" }, { "code": null, "e": 26843, "s": 26745, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26858, "s": 26843, "text": "Stream In Java" }, { "code": null, "e": 26879, "s": 26858, "text": "Constructors in Java" }, { "code": null, "e": 26898, "s": 26879, "text": "Exceptions in Java" }, { "code": null, "e": 26928, "s": 26898, "text": "Functional Interfaces in Java" }, { "code": null, "e": 26974, "s": 26928, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27000, "s": 26974, "text": "Java Programming Examples" }, { "code": null, "e": 27034, "s": 27000, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 27081, "s": 27034, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 27113, "s": 27081, "text": "How to Iterate HashMap in Java?" } ]
C | Operators | Question 16 - GeeksforGeeks
28 Jun, 2021 Predict the output of the below program: #include <stdio.h>int main(){ printf("%d", 1 << 2 + 3 << 4); return 0;} (A) 112(B) 52(C) 512(D) 0Answer: (C)Explanation: The main logic behind the program is the precedence and associativity of the operators. The addition(+) operator has higher precedence than shift(<<) operator. So, the expression boils down to 1 << (2 + 3) << 4 which in turn reduces to (1 << 5) << 4 as the shift operator has left-to-right associativity.Quiz of this Question C-Operators Operators C Language C Quiz Operators Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Left Shift and Right Shift Operators in C/C++ Function Pointer in C rand() and srand() in C/C++ std::string class in C++ Compiling a C program:- Behind the Scenes Operator Precedence and Associativity in C C | File Handling | Question 1 Output of C programs | Set 64 (Pointers) C | Arrays | Question 7
[ { "code": null, "e": 25519, "s": 25491, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25560, "s": 25519, "text": "Predict the output of the below program:" }, { "code": "#include <stdio.h>int main(){ printf(\"%d\", 1 << 2 + 3 << 4); return 0;}", "e": 25638, "s": 25560, "text": null }, { "code": null, "e": 26013, "s": 25638, "text": "(A) 112(B) 52(C) 512(D) 0Answer: (C)Explanation: The main logic behind the program is the precedence and associativity of the operators. The addition(+) operator has higher precedence than shift(<<) operator. So, the expression boils down to 1 << (2 + 3) << 4 which in turn reduces to (1 << 5) << 4 as the shift operator has left-to-right associativity.Quiz of this Question" }, { "code": null, "e": 26025, "s": 26013, "text": "C-Operators" }, { "code": null, "e": 26035, "s": 26025, "text": "Operators" }, { "code": null, "e": 26046, "s": 26035, "text": "C Language" }, { "code": null, "e": 26053, "s": 26046, "text": "C Quiz" }, { "code": null, "e": 26063, "s": 26053, "text": "Operators" }, { "code": null, "e": 26161, "s": 26063, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26178, "s": 26161, "text": "Substring in C++" }, { "code": null, "e": 26224, "s": 26178, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 26246, "s": 26224, "text": "Function Pointer in C" }, { "code": null, "e": 26274, "s": 26246, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 26299, "s": 26274, "text": "std::string class in C++" }, { "code": null, "e": 26341, "s": 26299, "text": "Compiling a C program:- Behind the Scenes" }, { "code": null, "e": 26384, "s": 26341, "text": "Operator Precedence and Associativity in C" }, { "code": null, "e": 26415, "s": 26384, "text": "C | File Handling | Question 1" }, { "code": null, "e": 26456, "s": 26415, "text": "Output of C programs | Set 64 (Pointers)" } ]
Python - Filtering text using Enchant - GeeksforGeeks
26 May, 2020 Enchant is a module in Python which is used to check the spelling of a word, gives suggestions to correct words. Also, gives antonym and synonym of words. It checks whether a word exists in dictionary or not. Enchant also provides the enchant.tokenize module to tokenize text. Tokenizing involves splitting words from the body of the text. But at times not all the words are required to be tokenized. Suppose we are spell checking, then it is customary to ignore email addresses and URLs. This can be achieved by modifying the tokenization process with filters.Currently implemented filters are : EmailFilter URLFilter WikiWordFilter Example 1 : EmailFilter # import the required modulesfrom enchant.tokenize import get_tokenizerfrom enchant.tokenize import EmailFilter # the text to be tokenizedtext = "The email is [email protected]" # getting tokenizer classtokenizer = get_tokenizer("en_US") # printing tokens without filteringprint("Printing tokens without filtering:")token_list = []for words in tokenizer(text): token_list.append(words)print(token_list) # getting tokenizer class with filtertokenizer_filter = get_tokenizer("en_US", [EmailFilter]) # printing tokens after filteringprint("\nPrinting tokens after filtering:")token_list_filter = []for words in tokenizer_filter(text): token_list_filter.append(words)print(token_list_filter) Output : Printing tokens without filtering:[(‘The’, 0), (’email’, 4), (‘is’, 10), (‘abc’, 13), (‘gmail’, 17), (‘com’, 23)] Printing tokens after filtering:[(‘The’, 0), (’email’, 4), (‘is’, 10) Example 2 : URLFilter # import the required modulesfrom enchant.tokenize import get_tokenizerfrom enchant.tokenize import URLFilter # the text to be tokenizedtext = "This is an URL: https://www.geeksforgeeks.org/" # getting tokenizer classtokenizer = get_tokenizer("en_US") # printing tokens without filteringprint("Printing tokens without filtering:")token_list = []for words in tokenizer(text): token_list.append(words)print(token_list) # getting tokenizer class with filtertokenizer_filter = get_tokenizer("en_US", [URLFilter]) # printing tokens after filteringprint("\nPrinting tokens after filtering:")token_list_filter = []for words in tokenizer_filter(text): token_list_filter.append(words)print(token_list_filter) Output : Printing tokens without filtering:[(‘This’, 0), (‘is’, 5), (‘an’, 8), (‘URL’, 11), (‘https’, 16), (‘www’, 24), (‘geeksforgeeks’, 28), (‘org’, 42)] Printing tokens after filtering:[(‘This’, 0), (‘is’, 5), (‘an’, 8), (‘URL’, 11)] Example 3 : WikiWordFilterA WikiWord is a word which consists of two or more words with initial capitals, run together. # import the required modulesfrom enchant.tokenize import get_tokenizerfrom enchant.tokenize import WikiWordFilter # the text to be tokenizedtext = "VersionFiveDotThree is an example of WikiWord" # getting tokenizer classtokenizer = get_tokenizer("en_US") # printing tokens without filteringprint("Printing tokens without filtering:")token_list = []for words in tokenizer(text): token_list.append(words)print(token_list) # getting tokenizer class with filtertokenizer_filter = get_tokenizer("en_US", [WikiWordFilter]) # printing tokens after filteringprint("\nPrinting tokens after filtering:")token_list_filter = []for words in tokenizer_filter(text): token_list_filter.append(words)print(token_list_filter) Output : Printing tokens without filtering:[(‘VersionFiveDotThree’, 0), (‘is’, 20), (‘an’, 23), (‘example’, 26), (‘of’, 34), (‘WikiWord’, 37)] Printing tokens after filtering:[(‘is’, 20), (‘an’, 23), (‘example’, 26), (‘of’, 34)] Python Enchant-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 26133, "s": 26105, "text": "\n26 May, 2020" }, { "code": null, "e": 26342, "s": 26133, "text": "Enchant is a module in Python which is used to check the spelling of a word, gives suggestions to correct words. Also, gives antonym and synonym of words. It checks whether a word exists in dictionary or not." }, { "code": null, "e": 26730, "s": 26342, "text": "Enchant also provides the enchant.tokenize module to tokenize text. Tokenizing involves splitting words from the body of the text. But at times not all the words are required to be tokenized. Suppose we are spell checking, then it is customary to ignore email addresses and URLs. This can be achieved by modifying the tokenization process with filters.Currently implemented filters are :" }, { "code": null, "e": 26742, "s": 26730, "text": "EmailFilter" }, { "code": null, "e": 26752, "s": 26742, "text": "URLFilter" }, { "code": null, "e": 26767, "s": 26752, "text": "WikiWordFilter" }, { "code": null, "e": 26791, "s": 26767, "text": "Example 1 : EmailFilter" }, { "code": "# import the required modulesfrom enchant.tokenize import get_tokenizerfrom enchant.tokenize import EmailFilter # the text to be tokenizedtext = \"The email is [email protected]\" # getting tokenizer classtokenizer = get_tokenizer(\"en_US\") # printing tokens without filteringprint(\"Printing tokens without filtering:\")token_list = []for words in tokenizer(text): token_list.append(words)print(token_list) # getting tokenizer class with filtertokenizer_filter = get_tokenizer(\"en_US\", [EmailFilter]) # printing tokens after filteringprint(\"\\nPrinting tokens after filtering:\")token_list_filter = []for words in tokenizer_filter(text): token_list_filter.append(words)print(token_list_filter)", "e": 27486, "s": 26791, "text": null }, { "code": null, "e": 27495, "s": 27486, "text": "Output :" }, { "code": null, "e": 27609, "s": 27495, "text": "Printing tokens without filtering:[(‘The’, 0), (’email’, 4), (‘is’, 10), (‘abc’, 13), (‘gmail’, 17), (‘com’, 23)]" }, { "code": null, "e": 27679, "s": 27609, "text": "Printing tokens after filtering:[(‘The’, 0), (’email’, 4), (‘is’, 10)" }, { "code": null, "e": 27701, "s": 27679, "text": "Example 2 : URLFilter" }, { "code": "# import the required modulesfrom enchant.tokenize import get_tokenizerfrom enchant.tokenize import URLFilter # the text to be tokenizedtext = \"This is an URL: https://www.geeksforgeeks.org/\" # getting tokenizer classtokenizer = get_tokenizer(\"en_US\") # printing tokens without filteringprint(\"Printing tokens without filtering:\")token_list = []for words in tokenizer(text): token_list.append(words)print(token_list) # getting tokenizer class with filtertokenizer_filter = get_tokenizer(\"en_US\", [URLFilter]) # printing tokens after filteringprint(\"\\nPrinting tokens after filtering:\")token_list_filter = []for words in tokenizer_filter(text): token_list_filter.append(words)print(token_list_filter)", "e": 28414, "s": 27701, "text": null }, { "code": null, "e": 28423, "s": 28414, "text": "Output :" }, { "code": null, "e": 28570, "s": 28423, "text": "Printing tokens without filtering:[(‘This’, 0), (‘is’, 5), (‘an’, 8), (‘URL’, 11), (‘https’, 16), (‘www’, 24), (‘geeksforgeeks’, 28), (‘org’, 42)]" }, { "code": null, "e": 28651, "s": 28570, "text": "Printing tokens after filtering:[(‘This’, 0), (‘is’, 5), (‘an’, 8), (‘URL’, 11)]" }, { "code": null, "e": 28771, "s": 28651, "text": "Example 3 : WikiWordFilterA WikiWord is a word which consists of two or more words with initial capitals, run together." }, { "code": "# import the required modulesfrom enchant.tokenize import get_tokenizerfrom enchant.tokenize import WikiWordFilter # the text to be tokenizedtext = \"VersionFiveDotThree is an example of WikiWord\" # getting tokenizer classtokenizer = get_tokenizer(\"en_US\") # printing tokens without filteringprint(\"Printing tokens without filtering:\")token_list = []for words in tokenizer(text): token_list.append(words)print(token_list) # getting tokenizer class with filtertokenizer_filter = get_tokenizer(\"en_US\", [WikiWordFilter]) # printing tokens after filteringprint(\"\\nPrinting tokens after filtering:\")token_list_filter = []for words in tokenizer_filter(text): token_list_filter.append(words)print(token_list_filter)", "e": 29491, "s": 28771, "text": null }, { "code": null, "e": 29500, "s": 29491, "text": "Output :" }, { "code": null, "e": 29634, "s": 29500, "text": "Printing tokens without filtering:[(‘VersionFiveDotThree’, 0), (‘is’, 20), (‘an’, 23), (‘example’, 26), (‘of’, 34), (‘WikiWord’, 37)]" }, { "code": null, "e": 29720, "s": 29634, "text": "Printing tokens after filtering:[(‘is’, 20), (‘an’, 23), (‘example’, 26), (‘of’, 34)]" }, { "code": null, "e": 29742, "s": 29720, "text": "Python Enchant-module" }, { "code": null, "e": 29749, "s": 29742, "text": "Python" }, { "code": null, "e": 29847, "s": 29749, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29865, "s": 29847, "text": "Python Dictionary" }, { "code": null, "e": 29897, "s": 29865, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29919, "s": 29897, "text": "Enumerate() in Python" }, { "code": null, "e": 29961, "s": 29919, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29990, "s": 29961, "text": "*args and **kwargs in Python" }, { "code": null, "e": 30034, "s": 29990, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 30071, "s": 30034, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 30107, "s": 30071, "text": "Convert integer to string in Python" }, { "code": null, "e": 30149, "s": 30107, "text": "Check if element exists in list in Python" } ]
How to update a plot on same figure during the loop? - GeeksforGeeks
01 Jul, 2021 We can use matplotlib to update a plot on every iteration during the loop. With the help of matplotlib.pyplot.draw() function we can update the plot on the same figure during the loop. Using matplotlib.pyplot.draw(): It is used to update a figure that has been changed. It will redraw the current figure. Syntax: figure.canvas.draw() Before this we use figure.ion() function to run a GUI event loop. Without using figure.ion() we may not be able to see the GUI plot. In the given example firstly we are importing all the necessary libraries that we are going to use. And then creating X and Y. X holds the values from 0 to 10 which evenly spaced into 100 values. e.g. we are creating values from 2 to 3 with evenly spaced 5 values (np.linspace(2, 3, 5)) It should output like these 5 values from 2 to 3 evenly spaced array([2 , 2.25, 2.5 , 2.75, 3 ]). After that we are initializing GUI using plt.ion() function, now we have to create a subplot, so we can plot X and Y values. After that we are running a for loop up to some iterations and creating a new_y values which hold our updating value then we are updating the values of X and Y using set_xdata() and set_ydata(). And canvas.draw() will plot the updated values and canvas.flush_events() holds the GUI event till the UI events have been processed. This will run till the loop ends and values will be updated continuously. Code: Python3 # importing librariesimport numpy as npimport timeimport matplotlib.pyplot as plt # creating initial data values# of x and yx = np.linspace(0, 10, 100)y = np.sin(x) # to run GUI event loopplt.ion() # here we are creating sub plotsfigure, ax = plt.subplots(figsize=(10, 8))line1, = ax.plot(x, y) # setting titleplt.title("Geeks For Geeks", fontsize=20) # setting x-axis label and y-axis labelplt.xlabel("X-axis")plt.ylabel("Y-axis") # Loopfor _ in range(50): # creating new Y values new_y = np.sin(x-0.5*_) # updating data values line1.set_xdata(x) line1.set_ydata(new_y) # drawing updated values figure.canvas.draw() # This will run the GUI event # loop until all UI events # currently waiting have been processed figure.canvas.flush_events() time.sleep(0.1) Output: Updating plot Here, figure.canvas.flush_events() is used to clear the old figure before plotting the updated figure. Example 2: In this example code, we are updating the value of y in a loop using set_xdata() and redrawing the figure every time using canvas.draw(). Python3 from math import piimport matplotlib.pyplot as pltimport numpy as npimport time # generating random data valuesx = np.linspace(1, 1000, 5000)y = np.random.randint(1, 1000, 5000) # enable interactive modeplt.ion() # creating subplot and figurefig = plt.figure()ax = fig.add_subplot(111)line1, = ax.plot(x, y) # setting labelsplt.xlabel("X-axis")plt.ylabel("Y-axis")plt.title("Updating plot...") # loopingfor _ in range(50): # updating the value of x and y line1.set_xdata(x*_) line1.set_ydata(y) # re-drawing the figure fig.canvas.draw() # to flush the GUI events fig.canvas.flush_events() time.sleep(0.1) Output: Updating plot. saurabh1990aror Picked Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Convert integer to string in Python
[ { "code": null, "e": 26240, "s": 26212, "text": "\n01 Jul, 2021" }, { "code": null, "e": 26425, "s": 26240, "text": "We can use matplotlib to update a plot on every iteration during the loop. With the help of matplotlib.pyplot.draw() function we can update the plot on the same figure during the loop." }, { "code": null, "e": 26545, "s": 26425, "text": "Using matplotlib.pyplot.draw(): It is used to update a figure that has been changed. It will redraw the current figure." }, { "code": null, "e": 26574, "s": 26545, "text": "Syntax: figure.canvas.draw()" }, { "code": null, "e": 26707, "s": 26574, "text": "Before this we use figure.ion() function to run a GUI event loop. Without using figure.ion() we may not be able to see the GUI plot." }, { "code": null, "e": 27620, "s": 26707, "text": "In the given example firstly we are importing all the necessary libraries that we are going to use. And then creating X and Y. X holds the values from 0 to 10 which evenly spaced into 100 values. e.g. we are creating values from 2 to 3 with evenly spaced 5 values (np.linspace(2, 3, 5)) It should output like these 5 values from 2 to 3 evenly spaced array([2 , 2.25, 2.5 , 2.75, 3 ]). After that we are initializing GUI using plt.ion() function, now we have to create a subplot, so we can plot X and Y values. After that we are running a for loop up to some iterations and creating a new_y values which hold our updating value then we are updating the values of X and Y using set_xdata() and set_ydata(). And canvas.draw() will plot the updated values and canvas.flush_events() holds the GUI event till the UI events have been processed. This will run till the loop ends and values will be updated continuously." }, { "code": null, "e": 27626, "s": 27620, "text": "Code:" }, { "code": null, "e": 27634, "s": 27626, "text": "Python3" }, { "code": "# importing librariesimport numpy as npimport timeimport matplotlib.pyplot as plt # creating initial data values# of x and yx = np.linspace(0, 10, 100)y = np.sin(x) # to run GUI event loopplt.ion() # here we are creating sub plotsfigure, ax = plt.subplots(figsize=(10, 8))line1, = ax.plot(x, y) # setting titleplt.title(\"Geeks For Geeks\", fontsize=20) # setting x-axis label and y-axis labelplt.xlabel(\"X-axis\")plt.ylabel(\"Y-axis\") # Loopfor _ in range(50): # creating new Y values new_y = np.sin(x-0.5*_) # updating data values line1.set_xdata(x) line1.set_ydata(new_y) # drawing updated values figure.canvas.draw() # This will run the GUI event # loop until all UI events # currently waiting have been processed figure.canvas.flush_events() time.sleep(0.1)", "e": 28433, "s": 27634, "text": null }, { "code": null, "e": 28442, "s": 28433, "text": "Output: " }, { "code": null, "e": 28456, "s": 28442, "text": "Updating plot" }, { "code": null, "e": 28560, "s": 28456, "text": "Here, figure.canvas.flush_events() is used to clear the old figure before plotting the updated figure." }, { "code": null, "e": 28709, "s": 28560, "text": "Example 2: In this example code, we are updating the value of y in a loop using set_xdata() and redrawing the figure every time using canvas.draw()." }, { "code": null, "e": 28717, "s": 28709, "text": "Python3" }, { "code": "from math import piimport matplotlib.pyplot as pltimport numpy as npimport time # generating random data valuesx = np.linspace(1, 1000, 5000)y = np.random.randint(1, 1000, 5000) # enable interactive modeplt.ion() # creating subplot and figurefig = plt.figure()ax = fig.add_subplot(111)line1, = ax.plot(x, y) # setting labelsplt.xlabel(\"X-axis\")plt.ylabel(\"Y-axis\")plt.title(\"Updating plot...\") # loopingfor _ in range(50): # updating the value of x and y line1.set_xdata(x*_) line1.set_ydata(y) # re-drawing the figure fig.canvas.draw() # to flush the GUI events fig.canvas.flush_events() time.sleep(0.1)", "e": 29355, "s": 28717, "text": null }, { "code": null, "e": 29363, "s": 29355, "text": "Output:" }, { "code": null, "e": 29378, "s": 29363, "text": "Updating plot." }, { "code": null, "e": 29394, "s": 29378, "text": "saurabh1990aror" }, { "code": null, "e": 29401, "s": 29394, "text": "Picked" }, { "code": null, "e": 29419, "s": 29401, "text": "Python-matplotlib" }, { "code": null, "e": 29426, "s": 29419, "text": "Python" }, { "code": null, "e": 29524, "s": 29426, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29542, "s": 29524, "text": "Python Dictionary" }, { "code": null, "e": 29577, "s": 29542, "text": "Read a file line by line in Python" }, { "code": null, "e": 29609, "s": 29577, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29631, "s": 29609, "text": "Enumerate() in Python" }, { "code": null, "e": 29673, "s": 29631, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29703, "s": 29673, "text": "Iterate over a list in Python" }, { "code": null, "e": 29729, "s": 29703, "text": "Python String | replace()" }, { "code": null, "e": 29758, "s": 29729, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29802, "s": 29758, "text": "Reading and Writing to text files in Python" } ]
Node.js - Quick Guide
Node.js is a server-side platform built on Google Chrome's JavaScript Engine (V8 Engine). Node.js was developed by Ryan Dahl in 2009 and its latest version is v0.10.36. The definition of Node.js as supplied by its official documentation is as follows − Node.js is a platform built on Chrome's JavaScript runtime for easily building fast and scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices. Node.js is an open source, cross-platform runtime environment for developing server-side and networking applications. Node.js applications are written in JavaScript, and can be run within the Node.js runtime on OS X, Microsoft Windows, and Linux. Node.js also provides a rich library of various JavaScript modules which simplifies the development of web applications using Node.js to a great extent. Node.js = Runtime Environment + JavaScript Library Following are some of the important features that make Node.js the first choice of software architects. Asynchronous and Event Driven − All APIs of Node.js library are asynchronous, that is, non-blocking. It essentially means a Node.js based server never waits for an API to return data. The server moves to the next API after calling it and a notification mechanism of Events of Node.js helps the server to get a response from the previous API call. Asynchronous and Event Driven − All APIs of Node.js library are asynchronous, that is, non-blocking. It essentially means a Node.js based server never waits for an API to return data. The server moves to the next API after calling it and a notification mechanism of Events of Node.js helps the server to get a response from the previous API call. Very Fast − Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in code execution. Very Fast − Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in code execution. Single Threaded but Highly Scalable − Node.js uses a single threaded model with event looping. Event mechanism helps the server to respond in a non-blocking way and makes the server highly scalable as opposed to traditional servers which create limited threads to handle requests. Node.js uses a single threaded program and the same program can provide service to a much larger number of requests than traditional servers like Apache HTTP Server. Single Threaded but Highly Scalable − Node.js uses a single threaded model with event looping. Event mechanism helps the server to respond in a non-blocking way and makes the server highly scalable as opposed to traditional servers which create limited threads to handle requests. Node.js uses a single threaded program and the same program can provide service to a much larger number of requests than traditional servers like Apache HTTP Server. No Buffering − Node.js applications never buffer any data. These applications simply output the data in chunks. No Buffering − Node.js applications never buffer any data. These applications simply output the data in chunks. License − Node.js is released under the MIT license. License − Node.js is released under the MIT license. Following is the link on github wiki containing an exhaustive list of projects, application and companies which are using Node.js. This list includes eBay, General Electric, GoDaddy, Microsoft, PayPal, Uber, Wikipins, Yahoo!, and Yammer to name a few. Projects, Applications, and Companies Using Node Projects, Applications, and Companies Using Node The following diagram depicts some important parts of Node.js which we will discuss in detail in the subsequent chapters. Following are the areas where Node.js is proving itself as a perfect technology partner. I/O bound Applications Data Streaming Applications Data Intensive Real-time Applications (DIRT) JSON APIs based Applications Single Page Applications It is not advisable to use Node.js for CPU intensive applications. You really do not need to set up your own environment to start learning Node.js. Reason is very simple, we already have set up Node.js environment online, so that you can execute all the available examples online and learn through practice. Feel free to modify any example and check the results with different options. Try the following example using the Live Demo option available at the top right corner of the below sample code box (on our website) − /* Hello World! program in Node.js */ console.log("Hello World!"); For most of the examples given in this tutorial, you will find a Try it option, so just make use of it and enjoy your learning. If you are still willing to set up your environment for Node.js, you need the following two softwares available on your computer, (a) Text Editor and (b) The Node.js binary installables. This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi. Name and version of text editor can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on windows as well as Linux or UNIX. The files you create with your editor are called source files and contain program source code. The source files for Node.js programs are typically named with the extension ".js". Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, and finally execute it. The source code written in source file is simply javascript. The Node.js interpreter will be used to interpret and execute your javascript code. Node.js distribution comes as a binary installable for SunOS , Linux, Mac OS X, and Windows operating systems with the 32-bit (386) and 64-bit (amd64) x86 processor architectures. Following section guides you on how to install Node.js binary distribution on various OS. Download latest version of Node.js installable archive file from Node.js Downloads. At the time of writing this tutorial, following are the versions available on different OS. Based on your OS architecture, download and extract the archive node-v6.3.1-osname.tar.gz into /tmp, and then finally move extracted files into /usr/local/nodejs directory. For example: $ cd /tmp $ wget http://nodejs.org/dist/v6.3.1/node-v6.3.1-linux-x64.tar.gz $ tar xvfz node-v6.3.1-linux-x64.tar.gz $ mkdir -p /usr/local/nodejs $ mv node-v6.3.1-linux-x64/* /usr/local/nodejs Add /usr/local/nodejs/bin to the PATH environment variable. Use the MSI file and follow the prompts to install the Node.js. By default, the installer uses the Node.js distribution in C:\Program Files\nodejs. The installer should set the C:\Program Files\nodejs\bin directory in window's PATH environment variable. Restart any open command prompts for the change to take effect. Create a js file named main.js on your machine (Windows or Linux) having the following code. /* Hello, World! program in node.js */ console.log("Hello, World!") Now execute main.js file using Node.js interpreter to see the result − $ node main.js If everything is fine with your installation, this should produce the following result − Hello, World! Before creating an actual "Hello, World!" application using Node.js, let us see the components of a Node.js application. A Node.js application consists of the following three important components − Import required modules − We use the require directive to load Node.js modules. Import required modules − We use the require directive to load Node.js modules. Create server − A server which will listen to client's requests similar to Apache HTTP Server. Create server − A server which will listen to client's requests similar to Apache HTTP Server. Read request and return response − The server created in an earlier step will read the HTTP request made by the client which can be a browser or a console and return the response. Read request and return response − The server created in an earlier step will read the HTTP request made by the client which can be a browser or a console and return the response. We use the require directive to load the http module and store the returned HTTP instance into an http variable as follows − var http = require("http"); We use the created http instance and call http.createServer() method to create a server instance and then we bind it at port 8081 using the listen method associated with the server instance. Pass it a function with parameters request and response. Write the sample implementation to always return "Hello World". http.createServer(function (request, response) { // Send the HTTP header // HTTP Status: 200 : OK // Content Type: text/plain response.writeHead(200, {'Content-Type': 'text/plain'}); // Send the response body as "Hello World" response.end('Hello World\n'); }).listen(8081); // Console will print the message console.log('Server running at http://127.0.0.1:8081/'); The above code is enough to create an HTTP server which listens, i.e., waits for a request over 8081 port on the local machine. Let's put step 1 and 2 together in a file called main.js and start our HTTP server as shown below − var http = require("http"); http.createServer(function (request, response) { // Send the HTTP header // HTTP Status: 200 : OK // Content Type: text/plain response.writeHead(200, {'Content-Type': 'text/plain'}); // Send the response body as "Hello World" response.end('Hello World\n'); }).listen(8081); // Console will print the message console.log('Server running at http://127.0.0.1:8081/'); Now execute the main.js to start the server as follows − $ node main.js Verify the Output. Server has started. Server running at http://127.0.0.1:8081/ Open http://127.0.0.1:8081/ in any browser and observe the following result. Congratulations, you have your first HTTP server up and running which is responding to all the HTTP requests at port 8081. REPL stands for Read Eval Print Loop and it represents a computer environment like a Windows console or Unix/Linux shell where a command is entered and the system responds with an output in an interactive mode. Node.js or Node comes bundled with a REPL environment. It performs the following tasks − Read − Reads user's input, parses the input into JavaScript data-structure, and stores in memory. Read − Reads user's input, parses the input into JavaScript data-structure, and stores in memory. Eval − Takes and evaluates the data structure. Eval − Takes and evaluates the data structure. Print − Prints the result. Print − Prints the result. Loop − Loops the above command until the user presses ctrl-c twice. Loop − Loops the above command until the user presses ctrl-c twice. The REPL feature of Node is very useful in experimenting with Node.js codes and to debug JavaScript codes. To simplify your learning, we have set up an easy to use Node.js REPL environment online, where you can practice Node.js syntax − Launch Node.js REPL Terminal REPL can be started by simply running node on shell/console without any arguments as follows. $ node You will see the REPL Command prompt > where you can type any Node.js command − $ node > Let's try a simple mathematics at the Node.js REPL command prompt − $ node > 1 + 3 4 > 1 + ( 2 * 3 ) - 4 3 > You can make use variables to store values and print later like any conventional script. If var keyword is not used, then the value is stored in the variable and printed. Whereas if var keyword is used, then the value is stored but not printed. You can print variables using console.log(). $ node > x = 10 10 > var y = 10 undefined > x + y 20 > console.log("Hello World") Hello World undefined Node REPL supports multiline expression similar to JavaScript. Let's check the following do-while loop in action − $ node > var x = 0 undefined > do { ... x++; ... console.log("x: " + x); ... } while ( x < 5 ); x: 1 x: 2 x: 3 x: 4 x: 5 undefined > ... comes automatically when you press Enter after the opening bracket. Node automatically checks the continuity of expressions. You can use underscore (_) to get the last result − $ node > var x = 10 undefined > var y = 20 undefined > x + y 30 > var sum = _ undefined > console.log(sum) 30 undefined > ctrl + c − terminate the current command. ctrl + c − terminate the current command. ctrl + c twice − terminate the Node REPL. ctrl + c twice − terminate the Node REPL. ctrl + d − terminate the Node REPL. ctrl + d − terminate the Node REPL. Up/Down Keys − see command history and modify previous commands. Up/Down Keys − see command history and modify previous commands. tab Keys − list of current commands. tab Keys − list of current commands. .help − list of all commands. .help − list of all commands. .break − exit from multiline expression. .break − exit from multiline expression. .clear − exit from multiline expression. .clear − exit from multiline expression. .save filename − save the current Node REPL session to a file. .save filename − save the current Node REPL session to a file. .load filename − load file content in current Node REPL session. .load filename − load file content in current Node REPL session. As mentioned above, you will need to use ctrl-c twice to come out of Node.js REPL. $ node > (^C again to quit) > Node Package Manager (NPM) provides two main functionalities − Online repositories for node.js packages/modules which are searchable on search.nodejs.org Online repositories for node.js packages/modules which are searchable on search.nodejs.org Command line utility to install Node.js packages, do version management and dependency management of Node.js packages. Command line utility to install Node.js packages, do version management and dependency management of Node.js packages. NPM comes bundled with Node.js installables after v0.6.3 version. To verify the same, open console and type the following command and see the result − $ npm --version 2.7.1 If you are running an old version of NPM then it is quite easy to update it to the latest version. Just use the following command from root − $ sudo npm install npm -g /usr/bin/npm -> /usr/lib/node_modules/npm/bin/npm-cli.js [email protected] /usr/lib/node_modules/npm There is a simple syntax to install any Node.js module − $ npm install <Module Name> For example, following is the command to install a famous Node.js web framework module called express − $ npm install express Now you can use this module in your js file as following − var express = require('express'); By default, NPM installs any dependency in the local mode. Here local mode refers to the package installation in node_modules directory lying in the folder where Node application is present. Locally deployed packages are accessible via require() method. For example, when we installed express module, it created node_modules directory in the current directory where it installed the express module. $ ls -l total 0 drwxr-xr-x 3 root root 20 Mar 17 02:23 node_modules Alternatively, you can use npm ls command to list down all the locally installed modules. Globally installed packages/dependencies are stored in system directory. Such dependencies can be used in CLI (Command Line Interface) function of any node.js but cannot be imported using require() in Node application directly. Now let's try installing the express module using global installation. $ npm install express -g This will produce a similar result but the module will be installed globally. Here, the first line shows the module version and the location where it is getting installed. [email protected] /usr/lib/node_modules/express ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ([email protected]) ├── [email protected] ([email protected]) ├── [email protected] ([email protected]) ├── [email protected] ([email protected], [email protected]) ├── [email protected] ([email protected], [email protected], [email protected]) ├── [email protected] ([email protected]) ├── [email protected] ([email protected], [email protected]) └── [email protected] ([email protected], [email protected]) You can use the following command to check all the modules installed globally − $ npm ls -g package.json is present in the root directory of any Node application/module and is used to define the properties of a package. Let's open package.json of express package present in node_modules/express/ { "name": "express", "description": "Fast, unopinionated, minimalist web framework", "version": "4.11.2", "author": { "name": "TJ Holowaychuk", "email": "[email protected]" }, "contributors": [{ "name": "Aaron Heckmann", "email": "[email protected]" }, { "name": "Ciaran Jessup", "email": "[email protected]" }, { "name": "Douglas Christopher Wilson", "email": "[email protected]" }, { "name": "Guillermo Rauch", "email": "[email protected]" }, { "name": "Jonathan Ong", "email": "[email protected]" }, { "name": "Roman Shtylman", "email": "[email protected]" }, { "name": "Young Jae Sim", "email": "[email protected]" } ], "license": "MIT", "repository": { "type": "git", "url": "https://github.com/strongloop/express" }, "homepage": "https://expressjs.com/", "keywords": [ "express", "framework", "sinatra", "web", "rest", "restful", "router", "app", "api" ], "dependencies": { "accepts": "~1.2.3", "content-disposition": "0.5.0", "cookie-signature": "1.0.5", "debug": "~2.1.1", "depd": "~1.0.0", "escape-html": "1.0.1", "etag": "~1.5.1", "finalhandler": "0.3.3", "fresh": "0.2.4", "media-typer": "0.3.0", "methods": "~1.1.1", "on-finished": "~2.2.0", "parseurl": "~1.3.0", "path-to-regexp": "0.1.3", "proxy-addr": "~1.0.6", "qs": "2.3.3", "range-parser": "~1.0.2", "send": "0.11.1", "serve-static": "~1.8.1", "type-is": "~1.5.6", "vary": "~1.0.0", "cookie": "0.1.2", "merge-descriptors": "0.0.2", "utils-merge": "1.0.0" }, "devDependencies": { "after": "0.8.1", "ejs": "2.1.4", "istanbul": "0.3.5", "marked": "0.3.3", "mocha": "~2.1.0", "should": "~4.6.2", "supertest": "~0.15.0", "hjs": "~0.0.6", "body-parser": "~1.11.0", "connect-redis": "~2.2.0", "cookie-parser": "~1.3.3", "express-session": "~1.10.2", "jade": "~1.9.1", "method-override": "~2.3.1", "morgan": "~1.5.1", "multiparty": "~4.1.1", "vhost": "~3.0.0" }, "engines": { "node": ">= 0.10.0" }, "files": [ "LICENSE", "History.md", "Readme.md", "index.js", "lib/" ], "scripts": { "test": "mocha --require test/support/env --reporter spec --bail --check-leaks test/ test/acceptance/", "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --require test/support/env --reporter dot --check-leaks test/ test/acceptance/", "test-tap": "mocha --require test/support/env --reporter tap --check-leaks test/ test/acceptance/", "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --require test/support/env --reporter spec --check-leaks test/ test/acceptance/" }, "gitHead": "63ab25579bda70b4927a179b580a9c580b6c7ada", "bugs": { "url": "https://github.com/strongloop/express/issues" }, "_id": "[email protected]", "_shasum": "8df3d5a9ac848585f00a0777601823faecd3b148", "_from": "express@*", "_npmVersion": "1.4.28", "_npmUser": { "name": "dougwilson", "email": "[email protected]" }, "maintainers": [{ "name": "tjholowaychuk", "email": "[email protected]" }, { "name": "jongleberry", "email": "[email protected]" }, { "name": "shtylman", "email": "[email protected]" }, { "name": "dougwilson", "email": "[email protected]" }, { "name": "aredridel", "email": "[email protected]" }, { "name": "strongloop", "email": "[email protected]" }, { "name": "rfeng", "email": "[email protected]" }], "dist": { "shasum": "8df3d5a9ac848585f00a0777601823faecd3b148", "tarball": "https://registry.npmjs.org/express/-/express-4.11.2.tgz" }, "directories": {}, "_resolved": "https://registry.npmjs.org/express/-/express-4.11.2.tgz", "readme": "ERROR: No README data found!" } name − name of the package name − name of the package version − version of the package version − version of the package description − description of the package description − description of the package homepage − homepage of the package homepage − homepage of the package author − author of the package author − author of the package contributors − name of the contributors to the package contributors − name of the contributors to the package dependencies − list of dependencies. NPM automatically installs all the dependencies mentioned here in the node_module folder of the package. dependencies − list of dependencies. NPM automatically installs all the dependencies mentioned here in the node_module folder of the package. repository − repository type and URL of the package repository − repository type and URL of the package main − entry point of the package main − entry point of the package keywords − keywords keywords − keywords Use the following command to uninstall a Node.js module. $ npm uninstall express Once NPM uninstalls the package, you can verify it by looking at the content of /node_modules/ directory or type the following command − $ npm ls Update package.json and change the version of the dependency to be updated and run the following command. $ npm update express Search a package name using NPM. $ npm search express Creating a module requires package.json to be generated. Let's generate package.json using NPM, which will generate the basic skeleton of the package.json. $ npm init This utility will walk you through creating a package.json file. It only covers the most common items, and tries to guess sane defaults. See 'npm help json' for definitive documentation on these fields and exactly what they do. Use 'npm install <pkg> --save' afterwards to install a package and save it as a dependency in the package.json file. Press ^C at any time to quit. name: (webmaster) You will need to provide all the required information about your module. You can take help from the above-mentioned package.json file to understand the meanings of various information demanded. Once package.json is generated, use the following command to register yourself with NPM repository site using a valid email address. $ npm adduser Username: mcmohd Password: Email: (this IS public) [email protected] It is time now to publish your module − $ npm publish If everything is fine with your module, then it will be published in the repository and will be accessible to install using NPM like any other Node.js module. Callback is an asynchronous equivalent for a function. A callback function is called at the completion of a given task. Node makes heavy use of callbacks. All the APIs of Node are written in such a way that they support callbacks. For example, a function to read a file may start reading file and return the control to the execution environment immediately so that the next instruction can be executed. Once file I/O is complete, it will call the callback function while passing the callback function, the content of the file as a parameter. So there is no blocking or wait for File I/O. This makes Node.js highly scalable, as it can process a high number of requests without waiting for any function to return results. Create a text file named input.txt with the following content − Tutorials Point is giving self learning content to teach the world in simple and easy way!!!!! Create a js file named main.js with the following code − var fs = require("fs"); var data = fs.readFileSync('input.txt'); console.log(data.toString()); console.log("Program Ended"); Now run the main.js to see the result − $ node main.js Verify the Output. Tutorials Point is giving self learning content to teach the world in simple and easy way!!!!! Program Ended Create a text file named input.txt with the following content. Tutorials Point is giving self learning content to teach the world in simple and easy way!!!!! Update main.js to have the following code − var fs = require("fs"); fs.readFile('input.txt', function (err, data) { if (err) return console.error(err); console.log(data.toString()); }); console.log("Program Ended"); Now run the main.js to see the result − $ node main.js Verify the Output. Program Ended Tutorials Point is giving self learning content to teach the world in simple and easy way!!!!! These two examples explain the concept of blocking and non-blocking calls. The first example shows that the program blocks until it reads the file and then only it proceeds to end the program. The first example shows that the program blocks until it reads the file and then only it proceeds to end the program. The second example shows that the program does not wait for file reading and proceeds to print "Program Ended" and at the same time, the program without blocking continues reading the file. The second example shows that the program does not wait for file reading and proceeds to print "Program Ended" and at the same time, the program without blocking continues reading the file. Thus, a blocking program executes very much in sequence. From the programming point of view, it is easier to implement the logic but non-blocking programs do not execute in sequence. In case a program needs to use any data to be processed, it should be kept within the same block to make it sequential execution. Node.js is a single-threaded application, but it can support concurrency via the concept of event and callbacks. Every API of Node.js is asynchronous and being single-threaded, they use async function calls to maintain concurrency. Node uses observer pattern. Node thread keeps an event loop and whenever a task gets completed, it fires the corresponding event which signals the event-listener function to execute. Node.js uses events heavily and it is also one of the reasons why Node.js is pretty fast compared to other similar technologies. As soon as Node starts its server, it simply initiates its variables, declares functions and then simply waits for the event to occur. In an event-driven application, there is generally a main loop that listens for events, and then triggers a callback function when one of those events is detected. Although events look quite similar to callbacks, the difference lies in the fact that callback functions are called when an asynchronous function returns its result, whereas event handling works on the observer pattern. The functions that listen to events act as Observers. Whenever an event gets fired, its listener function starts executing. Node.js has multiple in-built events available through events module and EventEmitter class which are used to bind events and event-listeners as follows − // Import events module var events = require('events'); // Create an eventEmitter object var eventEmitter = new events.EventEmitter(); Following is the syntax to bind an event handler with an event − // Bind event and event handler as follows eventEmitter.on('eventName', eventHandler); We can fire an event programmatically as follows − // Fire an event eventEmitter.emit('eventName'); Create a js file named main.js with the following code − // Import events module var events = require('events'); // Create an eventEmitter object var eventEmitter = new events.EventEmitter(); // Create an event handler as follows var connectHandler = function connected() { console.log('connection succesful.'); // Fire the data_received event eventEmitter.emit('data_received'); } // Bind the connection event with the handler eventEmitter.on('connection', connectHandler); // Bind the data_received event with the anonymous function eventEmitter.on('data_received', function() { console.log('data received succesfully.'); }); // Fire the connection event eventEmitter.emit('connection'); console.log("Program Ended."); Now let's try to run the above program and check its output − $ node main.js IT should produce the following result − connection successful. data received successfully. Program Ended. In Node Application, any async function accepts a callback as the last parameter and a callback function accepts an error as the first parameter. Let's revisit the previous example again. Create a text file named input.txt with the following content. Tutorials Point is giving self learning content to teach the world in simple and easy way!!!!! Create a js file named main.js having the following code − var fs = require("fs"); fs.readFile('input.txt', function (err, data) { if (err) { console.log(err.stack); return; } console.log(data.toString()); }); console.log("Program Ended"); Here fs.readFile() is a async function whose purpose is to read a file. If an error occurs during the read operation, then the err object will contain the corresponding error, else data will contain the contents of the file. readFile passes err and data to the callback function after the read operation is complete, which finally prints the content. Program Ended Tutorials Point is giving self learning content to teach the world in simple and easy way!!!!! Many objects in a Node emit events, for example, a net.Server emits an event each time a peer connects to it, an fs.readStream emits an event when the file is opened. All objects which emit events are the instances of events.EventEmitter. As we have seen in the previous section, EventEmitter class lies in the events module. It is accessible via the following code − // Import events module var events = require('events'); // Create an eventEmitter object var eventEmitter = new events.EventEmitter(); When an EventEmitter instance faces any error, it emits an 'error' event. When a new listener is added, 'newListener' event is fired and when a listener is removed, 'removeListener' event is fired. EventEmitter provides multiple properties like on and emit. on property is used to bind a function with the event and emit is used to fire an event. addListener(event, listener) Adds a listener at the end of the listeners array for the specified event. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of event and listener will result in the listener being added multiple times. Returns emitter, so calls can be chained. on(event, listener) Adds a listener at the end of the listeners array for the specified event. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of event and listener will result in the listener being added multiple times. Returns emitter, so calls can be chained. once(event, listener) Adds a one time listener to the event. This listener is invoked only the next time the event is fired, after which it is removed. Returns emitter, so calls can be chained. removeListener(event, listener) Removes a listener from the listener array for the specified event. Caution − It changes the array indices in the listener array behind the listener. removeListener will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specified event, then removeListener must be called multiple times to remove each instance. Returns emitter, so calls can be chained. removeAllListeners([event]) Removes all listeners, or those of the specified event. It's not a good idea to remove listeners that were added elsewhere in the code, especially when it's on an emitter that you didn't create (e.g. sockets or file streams). Returns emitter, so calls can be chained. setMaxListeners(n) By default, EventEmitters will print a warning if more than 10 listeners are added for a particular event. This is a useful default which helps finding memory leaks. Obviously not all Emitters should be limited to 10. This function allows that to be increased. Set to zero for unlimited. listeners(event) Returns an array of listeners for the specified event. emit(event, [arg1], [arg2], [...]) Execute each of the listeners in order with the supplied arguments. Returns true if the event had listeners, false otherwise. listenerCount(emitter, event) Returns the number of listeners for a given event. newListener event − String: the event name event − String: the event name listener − Function: the event handler function listener − Function: the event handler function This event is emitted any time a listener is added. When this event is triggered, the listener may not yet have been added to the array of listeners for the event. removeListener event − String The event name event − String The event name listener − Function The event handler function listener − Function The event handler function This event is emitted any time someone removes a listener. When this event is triggered, the listener may not yet have been removed from the array of listeners for the event. Create a js file named main.js with the following Node.js code − var events = require('events'); var eventEmitter = new events.EventEmitter(); // listener #1 var listner1 = function listner1() { console.log('listner1 executed.'); } // listener #2 var listner2 = function listner2() { console.log('listner2 executed.'); } // Bind the connection event with the listner1 function eventEmitter.addListener('connection', listner1); // Bind the connection event with the listner2 function eventEmitter.on('connection', listner2); var eventListeners = require('events').EventEmitter.listenerCount (eventEmitter,'connection'); console.log(eventListeners + " Listner(s) listening to connection event"); // Fire the connection event eventEmitter.emit('connection'); // Remove the binding of listner1 function eventEmitter.removeListener('connection', listner1); console.log("Listner1 will not listen now."); // Fire the connection event eventEmitter.emit('connection'); eventListeners = require('events').EventEmitter.listenerCount(eventEmitter,'connection'); console.log(eventListeners + " Listner(s) listening to connection event"); console.log("Program Ended."); Now run the main.js to see the result − $ node main.js Verify the Output. 2 Listner(s) listening to connection event listner1 executed. listner2 executed. Listner1 will not listen now. listner2 executed. 1 Listner(s) listening to connection event Program Ended. Pure JavaScript is Unicode friendly, but it is not so for binary data. While dealing with TCP streams or the file system, it's necessary to handle octet streams. Node provides Buffer class which provides instances to store raw data similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. Buffer class is a global class that can be accessed in an application without importing the buffer module. Node Buffer can be constructed in a variety of ways. Following is the syntax to create an uninitiated Buffer of 10 octets − var buf = new Buffer(10); Following is the syntax to create a Buffer from a given array − var buf = new Buffer([10, 20, 30, 40, 50]); Following is the syntax to create a Buffer from a given string and optionally encoding type − var buf = new Buffer("Simply Easy Learning", "utf-8"); Though "utf8" is the default encoding, you can use any of the following encodings "ascii", "utf8", "utf16le", "ucs2", "base64" or "hex". Following is the syntax of the method to write into a Node Buffer − buf.write(string[, offset][, length][, encoding]) Here is the description of the parameters used − string − This is the string data to be written to buffer. string − This is the string data to be written to buffer. offset − This is the index of the buffer to start writing at. Default value is 0. offset − This is the index of the buffer to start writing at. Default value is 0. length − This is the number of bytes to write. Defaults to buffer.length. length − This is the number of bytes to write. Defaults to buffer.length. encoding − Encoding to use. 'utf8' is the default encoding. encoding − Encoding to use. 'utf8' is the default encoding. This method returns the number of octets written. If there is not enough space in the buffer to fit the entire string, it will write a part of the string. buf = new Buffer(256); len = buf.write("Simply Easy Learning"); console.log("Octets written : "+ len); When the above program is executed, it produces the following result − Octets written : 20 Following is the syntax of the method to read data from a Node Buffer − buf.toString([encoding][, start][, end]) Here is the description of the parameters used − encoding − Encoding to use. 'utf8' is the default encoding. encoding − Encoding to use. 'utf8' is the default encoding. start − Beginning index to start reading, defaults to 0. start − Beginning index to start reading, defaults to 0. end − End index to end reading, defaults is complete buffer. end − End index to end reading, defaults is complete buffer. This method decodes and returns a string from buffer data encoded using the specified character set encoding. buf = new Buffer(26); for (var i = 0 ; i < 26 ; i++) { buf[i] = i + 97; } console.log( buf.toString('ascii')); // outputs: abcdefghijklmnopqrstuvwxyz console.log( buf.toString('ascii',0,5)); // outputs: abcde console.log( buf.toString('utf8',0,5)); // outputs: abcde console.log( buf.toString(undefined,0,5)); // encoding defaults to 'utf8', outputs abcde When the above program is executed, it produces the following result − abcdefghijklmnopqrstuvwxyz abcde abcde abcde Following is the syntax of the method to convert a Node Buffer into JSON object − buf.toJSON() This method returns a JSON-representation of the Buffer instance. var buf = new Buffer('Simply Easy Learning'); var json = buf.toJSON(buf); console.log(json); When the above program is executed, it produces the following result − { type: 'Buffer', data: [ 83, 105, 109, 112, 108, 121, 32, 69, 97, 115, 121, 32, 76, 101, 97, 114, 110, 105, 110, 103 ] } Following is the syntax of the method to concatenate Node buffers to a single Node Buffer − Buffer.concat(list[, totalLength]) Here is the description of the parameters used − list − Array List of Buffer objects to be concatenated. list − Array List of Buffer objects to be concatenated. totalLength − This is the total length of the buffers when concatenated. totalLength − This is the total length of the buffers when concatenated. This method returns a Buffer instance. var buffer1 = new Buffer('TutorialsPoint '); var buffer2 = new Buffer('Simply Easy Learning'); var buffer3 = Buffer.concat([buffer1,buffer2]); console.log("buffer3 content: " + buffer3.toString()); When the above program is executed, it produces the following result − buffer3 content: TutorialsPoint Simply Easy Learning Following is the syntax of the method to compare two Node buffers − buf.compare(otherBuffer); Here is the description of the parameters used − otherBuffer − This is the other buffer which will be compared with buf otherBuffer − This is the other buffer which will be compared with buf Returns a number indicating whether it comes before or after or is the same as the otherBuffer in sort order. var buffer1 = new Buffer('ABC'); var buffer2 = new Buffer('ABCD'); var result = buffer1.compare(buffer2); if(result < 0) { console.log(buffer1 +" comes before " + buffer2); } else if(result === 0) { console.log(buffer1 +" is same as " + buffer2); } else { console.log(buffer1 +" comes after " + buffer2); } When the above program is executed, it produces the following result − ABC comes before ABCD Following is the syntax of the method to copy a node buffer − buf.copy(targetBuffer[, targetStart][, sourceStart][, sourceEnd]) Here is the description of the parameters used − targetBuffer − Buffer object where buffer will be copied. targetBuffer − Buffer object where buffer will be copied. targetStart − Number, Optional, Default: 0 targetStart − Number, Optional, Default: 0 sourceStart − Number, Optional, Default: 0 sourceStart − Number, Optional, Default: 0 sourceEnd − Number, Optional, Default: buffer.length sourceEnd − Number, Optional, Default: buffer.length No return value. Copies data from a region of this buffer to a region in the target buffer even if the target memory region overlaps with the source. If undefined, the targetStart and sourceStart parameters default to 0, while sourceEnd defaults to buffer.length. var buffer1 = new Buffer('ABC'); //copy a buffer var buffer2 = new Buffer(3); buffer1.copy(buffer2); console.log("buffer2 content: " + buffer2.toString()); When the above program is executed, it produces the following result − buffer2 content: ABC Following is the syntax of the method to get a sub-buffer of a node buffer − buf.slice([start][, end]) Here is the description of the parameters used − start − Number, Optional, Default: 0 start − Number, Optional, Default: 0 end − Number, Optional, Default: buffer.length end − Number, Optional, Default: buffer.length Returns a new buffer which references the same memory as the old one, but offset and cropped by the start (defaults to 0) and end (defaults to buffer.length) indexes. Negative indexes start from the end of the buffer. var buffer1 = new Buffer('TutorialsPoint'); //slicing a buffer var buffer2 = buffer1.slice(0,9); console.log("buffer2 content: " + buffer2.toString()); When the above program is executed, it produces the following result − buffer2 content: Tutorials Following is the syntax of the method to get a size of a node buffer in bytes − buf.length; Returns the size of a buffer in bytes. var buffer = new Buffer('TutorialsPoint'); //length of the buffer console.log("buffer length: " + buffer.length); When the above program is executed, it produces following result − buffer length: 14 new Buffer(size) Allocates a new buffer of size octets. Note that the size must be no more than kMaxLength. Otherwise, a RangeError will be thrown here. new Buffer(buffer) Copies the passed buffer data onto a new Buffer instance. new Buffer(str[, encoding]) Allocates a new buffer containing the given str. encoding defaults to 'utf8'. buf.length Returns the size of the buffer in bytes. Note that this is not necessarily the size of the contents. length refers to the amount of memory allocated for the buffer object. It does not change when the contents of the buffer are changed. buf.write(string[, offset][, length][, encoding]) Writes a string to the buffer at offset using the given encoding. offset defaults to 0, encoding defaults to 'utf8'. length is the number of bytes to write. Returns the number of octets written. buf.writeUIntLE(value, offset, byteLength[, noAssert]) Writes a value to the buffer at the specified offset and byteLength. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of value and offset. Defaults to false. buf.writeUIntBE(value, offset, byteLength[, noAssert]) Writes a value to the buffer at the specified offset and byteLength. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of value and offset. Defaults to false. buf.writeIntLE(value, offset, byteLength[, noAssert]) Writes a value to the buffer at the specified offset and byteLength. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of value and offset. Defaults to false. buf.writeIntBE(value, offset, byteLength[, noAssert]) Writes a value to the buffer at the specified offset and byteLength. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of value and offset. Defaults to false. buf.readUIntLE(offset, byteLength[, noAssert]) A generalized version of all numeric read methods. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of offset. It means that the offset may be beyond the end of the buffer. Defaults to false. buf.readUIntBE(offset, byteLength[, noAssert]) A generalized version of all numeric read methods. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of offset. It means that the offset may be beyond the end of the buffer. Defaults to false. buf.readIntLE(offset, byteLength[, noAssert]) A generalized version of all numeric read methods. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of offset. It means that the offset may be beyond the end of the buffer. Defaults to false. buf.readIntBE(offset, byteLength[, noAssert]) A generalized version of all numeric read methods. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of offset. It means that the offset may be beyond the end of the buffer. Defaults to false. buf.toString([encoding][, start][, end]) Decodes and returns a string from buffer data encoded using the specified character set encoding. buf.toJSON() Returns a JSON-representation of the Buffer instance. JSON.stringify implicitly calls this function when stringifying a Buffer instance. buf[index] Get and set the octet at index. The values refer to individual bytes, so the legal range is between 0x00 and 0xFF hex or 0 and 255. buf.equals(otherBuffer) Returns a boolean if this buffer and otherBuffer have the same bytes. buf.compare(otherBuffer) Returns a number indicating whether this buffer comes before or after or is the same as the otherBuffer in sort order. buf.copy(targetBuffer[, targetStart][, sourceStart][, sourceEnd]) Copies data from a region of this buffer to a region in the target buffer even if the target memory region overlaps with the source. If undefined, the targetStart and sourceStart parameters default to 0, while sourceEnd defaults to buffer.length. buf.slice([start][, end]) Returns a new buffer which references the same memory as the old, but offset and cropped by the start (defaults to 0) and end (defaults to buffer.length) indexes. Negative indexes start from the end of the buffer. buf.readUInt8(offset[, noAssert]) Reads an unsigned 8 bit integer from the buffer at the specified offset. Set noAssert to true to skip validation of offset. It means that the offset may be beyond the end of the buffer. Defaults to false. buf.readUInt16LE(offset[, noAssert]) Reads an unsigned 16-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false. buf.readUInt16BE(offset[, noAssert]) Reads an unsigned 16-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false. buf.readUInt32LE(offset[, noAssert]) Reads an unsigned 32-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false. buf.readUInt32BE(offset[, noAssert]) Reads an unsigned 32-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false. buf.readInt8(offset[, noAssert]) Reads a signed 8-bit integer from the buffer at the specified offset. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false. buf.readInt16LE(offset[, noAssert]) Reads a signed 16-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false. buf.readInt16BE(offset[, noAssert]) Reads a signed 16-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false. buf.readInt32LE(offset[, noAssert]) Reads a signed 32-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false. buf.readInt32BE(offset[, noAssert]) Reads a signed 32-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false. buf.readFloatLE(offset[, noAssert]) Reads a 32-bit float from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false. buf.readFloatBE(offset[, noAssert]) Reads a 32-bit float from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false. buf.readDoubleLE(offset[, noAssert]) Reads a 64-bit double from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false. buf.readDoubleBE(offset[, noAssert]) Reads a 64-bit double from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false. buf.writeUInt8(value, offset[, noAssert]) Writes a value to the buffer at the specified offset. Note that the value must be a valid unsigned 8-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false. buf.writeUInt16LE(value, offset[, noAssert]) Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid unsigned 16-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of correctness. Defaults to false. buf.writeUInt16BE(value, offset[, noAssert]) Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid unsigned 16-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false. buf.writeUInt32LE(value, offset[, noAssert]) Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid unsigned 32-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false. buf.writeUInt32BE(value, offset[, noAssert]) Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid unsigned 32-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false. buf.writeInt8(value, offset[, noAssert]) Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid signed 8-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false. buf.writeInt16LE(value, offset[, noAssert]) Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid signed 16-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false. buf.writeInt16BE(value, offset[, noAssert]) Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid signed 16-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false. buf.writeInt32LE(value, offset[, noAssert]) Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid signed 32-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false. buf.writeInt32BE(value, offset[, noAssert]) Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid signed 32-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of correctness. Defaults to false. buf.writeFloatLE(value, offset[, noAssert]) Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid 32-bit float. Set noAssert to true to skip validation of value and offset. It means that the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false. buf.writeFloatBE(value, offset[, noAssert]) Writes a value to the buffer at the specified offset with the specified endian format. Note, value must be a valid 32-bit float. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false. buf.writeDoubleLE(value, offset[, noAssert]) Writes a value to the buffer at the specified offset with the specified endian format. Note, value must be a valid 64-bit double. Set noAssert to true to skip validation of value and offset. It means that value may be too large for the specific function and offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false. buf.writeDoubleBE(value, offset[, noAssert]) Writes a value to the buffer at the specified offset with the specified endian format. Note, value must be a valid 64-bit double. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false. buf.fill(value[, offset][, end]) Fills the buffer with the specified value. If the offset (defaults to 0) and end (defaults to buffer.length) are not given, it will fill the entire buffer. Buffer.isEncoding(encoding) Returns true if the encoding is a valid encoding argument, false otherwise. Buffer.isBuffer(obj) Tests if obj is a Buffer. Buffer.byteLength(string[, encoding]) Gives the actual byte length of a string. encoding defaults to 'utf8'. It is not the same as String.prototype.length, since String.prototype.length returns the number of characters in a string. Buffer.concat(list[, totalLength]) Returns a buffer which is the result of concatenating all the buffers in the list together. Buffer.compare(buf1, buf2) The same as buf1.compare(buf2). Useful for sorting an array of buffers. Streams are objects that let you read data from a source or write data to a destination in continuous fashion. In Node.js, there are four types of streams − Readable − Stream which is used for read operation. Readable − Stream which is used for read operation. Writable − Stream which is used for write operation. Writable − Stream which is used for write operation. Duplex − Stream which can be used for both read and write operation. Duplex − Stream which can be used for both read and write operation. Transform − A type of duplex stream where the output is computed based on input. Transform − A type of duplex stream where the output is computed based on input. Each type of Stream is an EventEmitter instance and throws several events at different instance of times. For example, some of the commonly used events are − data − This event is fired when there is data is available to read. data − This event is fired when there is data is available to read. end − This event is fired when there is no more data to read. end − This event is fired when there is no more data to read. error − This event is fired when there is any error receiving or writing data. error − This event is fired when there is any error receiving or writing data. finish − This event is fired when all the data has been flushed to underlying system. finish − This event is fired when all the data has been flushed to underlying system. This tutorial provides a basic understanding of the commonly used operations on Streams. Create a text file named input.txt having the following content − Tutorials Point is giving self learning content to teach the world in simple and easy way!!!!! Create a js file named main.js with the following code − var fs = require("fs"); var data = ''; // Create a readable stream var readerStream = fs.createReadStream('input.txt'); // Set the encoding to be utf8. readerStream.setEncoding('UTF8'); // Handle stream events --> data, end, and error readerStream.on('data', function(chunk) { data += chunk; }); readerStream.on('end',function() { console.log(data); }); readerStream.on('error', function(err) { console.log(err.stack); }); console.log("Program Ended"); Now run the main.js to see the result − $ node main.js Verify the Output. Program Ended Tutorials Point is giving self learning content to teach the world in simple and easy way!!!!! Create a js file named main.js with the following code − var fs = require("fs"); var data = 'Simply Easy Learning'; // Create a writable stream var writerStream = fs.createWriteStream('output.txt'); // Write the data to stream with encoding to be utf8 writerStream.write(data,'UTF8'); // Mark the end of file writerStream.end(); // Handle stream events --> finish, and error writerStream.on('finish', function() { console.log("Write completed."); }); writerStream.on('error', function(err) { console.log(err.stack); }); console.log("Program Ended"); Now run the main.js to see the result − $ node main.js Verify the Output. Program Ended Write completed. Now open output.txt created in your current directory; it should contain the following − Simply Easy Learning Piping is a mechanism where we provide the output of one stream as the input to another stream. It is normally used to get data from one stream and to pass the output of that stream to another stream. There is no limit on piping operations. Now we'll show a piping example for reading from one file and writing it to another file. Create a js file named main.js with the following code − var fs = require("fs"); // Create a readable stream var readerStream = fs.createReadStream('input.txt'); // Create a writable stream var writerStream = fs.createWriteStream('output.txt'); // Pipe the read and write operations // read input.txt and write data to output.txt readerStream.pipe(writerStream); console.log("Program Ended"); Now run the main.js to see the result − $ node main.js Verify the Output. Program Ended Open output.txt created in your current directory; it should contain the following − Tutorials Point is giving self learning content to teach the world in simple and easy way!!!!! Chaining is a mechanism to connect the output of one stream to another stream and create a chain of multiple stream operations. It is normally used with piping operations. Now we'll use piping and chaining to first compress a file and then decompress the same. Create a js file named main.js with the following code − var fs = require("fs"); var zlib = require('zlib'); // Compress the file input.txt to input.txt.gz fs.createReadStream('input.txt') .pipe(zlib.createGzip()) .pipe(fs.createWriteStream('input.txt.gz')); console.log("File Compressed."); Now run the main.js to see the result − $ node main.js Verify the Output. File Compressed. You will find that input.txt has been compressed and it created a file input.txt.gz in the current directory. Now let's try to decompress the same file using the following code − var fs = require("fs"); var zlib = require('zlib'); // Decompress the file input.txt.gz to input.txt fs.createReadStream('input.txt.gz') .pipe(zlib.createGunzip()) .pipe(fs.createWriteStream('input.txt')); console.log("File Decompressed."); Now run the main.js to see the result − $ node main.js Verify the Output. File Decompressed. Node implements File I/O using simple wrappers around standard POSIX functions. The Node File System (fs) module can be imported using the following syntax − var fs = require("fs") Every method in the fs module has synchronous as well as asynchronous forms. Asynchronous methods take the last parameter as the completion function callback and the first parameter of the callback function as error. It is better to use an asynchronous method instead of a synchronous method, as the former never blocks a program during its execution, whereas the second one does. Create a text file named input.txt with the following content − Tutorials Point is giving self learning content to teach the world in simple and easy way!!!!! Let us create a js file named main.js with the following code − var fs = require("fs"); // Asynchronous read fs.readFile('input.txt', function (err, data) { if (err) { return console.error(err); } console.log("Asynchronous read: " + data.toString()); }); // Synchronous read var data = fs.readFileSync('input.txt'); console.log("Synchronous read: " + data.toString()); console.log("Program Ended"); Now run the main.js to see the result − $ node main.js Verify the Output. Synchronous read: Tutorials Point is giving self learning content to teach the world in simple and easy way!!!!! Program Ended Asynchronous read: Tutorials Point is giving self learning content to teach the world in simple and easy way!!!!! The following sections in this chapter provide a set of good examples on major File I/O methods. Following is the syntax of the method to open a file in asynchronous mode − fs.open(path, flags[, mode], callback) Here is the description of the parameters used − path − This is the string having file name including path. path − This is the string having file name including path. flags − Flags indicate the behavior of the file to be opened. All possible values have been mentioned below. flags − Flags indicate the behavior of the file to be opened. All possible values have been mentioned below. mode − It sets the file mode (permission and sticky bits), but only if the file was created. It defaults to 0666, readable and writeable. mode − It sets the file mode (permission and sticky bits), but only if the file was created. It defaults to 0666, readable and writeable. callback − This is the callback function which gets two arguments (err, fd). callback − This is the callback function which gets two arguments (err, fd). Flags for read/write operations are − r Open file for reading. An exception occurs if the file does not exist. r+ Open file for reading and writing. An exception occurs if the file does not exist. rs Open file for reading in synchronous mode. rs+ Open file for reading and writing, asking the OS to open it synchronously. See notes for 'rs' about using this with caution. w Open file for writing. The file is created (if it does not exist) or truncated (if it exists). wx Like 'w' but fails if the path exists. w+ Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists). wx+ Like 'w+' but fails if path exists. a Open file for appending. The file is created if it does not exist. ax Like 'a' but fails if the path exists. a+ Open file for reading and appending. The file is created if it does not exist. ax+ Like 'a+' but fails if the the path exists. Let us create a js file named main.js having the following code to open a file input.txt for reading and writing. var fs = require("fs"); // Asynchronous - Opening File console.log("Going to open file!"); fs.open('input.txt', 'r+', function(err, fd) { if (err) { return console.error(err); } console.log("File opened successfully!"); }); Now run the main.js to see the result − $ node main.js Verify the Output. Going to open file! File opened successfully! Following is the syntax of the method to get the information about a file − fs.stat(path, callback) Here is the description of the parameters used − path − This is the string having file name including path. path − This is the string having file name including path. callback − This is the callback function which gets two arguments (err, stats) where stats is an object of fs.Stats type which is printed below in the example. callback − This is the callback function which gets two arguments (err, stats) where stats is an object of fs.Stats type which is printed below in the example. Apart from the important attributes which are printed below in the example, there are several useful methods available in fs.Stats class which can be used to check file type. These methods are given in the following table. stats.isFile() Returns true if file type of a simple file. stats.isDirectory() Returns true if file type of a directory. stats.isBlockDevice() Returns true if file type of a block device. stats.isCharacterDevice() Returns true if file type of a character device. stats.isSymbolicLink() Returns true if file type of a symbolic link. stats.isFIFO() Returns true if file type of a FIFO. stats.isSocket() Returns true if file type of asocket. Let us create a js file named main.js with the following code − var fs = require("fs"); console.log("Going to get file info!"); fs.stat('input.txt', function (err, stats) { if (err) { return console.error(err); } console.log(stats); console.log("Got file info successfully!"); // Check file type console.log("isFile ? " + stats.isFile()); console.log("isDirectory ? " + stats.isDirectory()); }); Now run the main.js to see the result − $ node main.js Verify the Output. Going to get file info! { dev: 1792, mode: 33188, nlink: 1, uid: 48, gid: 48, rdev: 0, blksize: 4096, ino: 4318127, size: 97, blocks: 8, atime: Sun Mar 22 2015 13:40:00 GMT-0500 (CDT), mtime: Sun Mar 22 2015 13:40:57 GMT-0500 (CDT), ctime: Sun Mar 22 2015 13:40:57 GMT-0500 (CDT) } Got file info successfully! isFile ? true isDirectory ? false Following is the syntax of one of the methods to write into a file − fs.writeFile(filename, data[, options], callback) This method will over-write the file if the file already exists. If you want to write into an existing file then you should use another method available. Here is the description of the parameters used − path − This is the string having the file name including path. path − This is the string having the file name including path. data − This is the String or Buffer to be written into the file. data − This is the String or Buffer to be written into the file. options − The third parameter is an object which will hold {encoding, mode, flag}. By default. encoding is utf8, mode is octal value 0666. and flag is 'w' options − The third parameter is an object which will hold {encoding, mode, flag}. By default. encoding is utf8, mode is octal value 0666. and flag is 'w' callback − This is the callback function which gets a single parameter err that returns an error in case of any writing error. callback − This is the callback function which gets a single parameter err that returns an error in case of any writing error. Let us create a js file named main.js having the following code − var fs = require("fs"); console.log("Going to write into existing file"); fs.writeFile('input.txt', 'Simply Easy Learning!', function(err) { if (err) { return console.error(err); } console.log("Data written successfully!"); console.log("Let's read newly written data"); fs.readFile('input.txt', function (err, data) { if (err) { return console.error(err); } console.log("Asynchronous read: " + data.toString()); }); }); Now run the main.js to see the result − $ node main.js Verify the Output. Going to write into existing file Data written successfully! Let's read newly written data Asynchronous read: Simply Easy Learning! Following is the syntax of one of the methods to read from a file − fs.read(fd, buffer, offset, length, position, callback) This method will use file descriptor to read the file. If you want to read the file directly using the file name, then you should use another method available. Here is the description of the parameters used − fd − This is the file descriptor returned by fs.open(). fd − This is the file descriptor returned by fs.open(). buffer − This is the buffer that the data will be written to. buffer − This is the buffer that the data will be written to. offset − This is the offset in the buffer to start writing at. offset − This is the offset in the buffer to start writing at. length − This is an integer specifying the number of bytes to read. length − This is an integer specifying the number of bytes to read. position − This is an integer specifying where to begin reading from in the file. If position is null, data will be read from the current file position. position − This is an integer specifying where to begin reading from in the file. If position is null, data will be read from the current file position. callback − This is the callback function which gets the three arguments, (err, bytesRead, buffer). callback − This is the callback function which gets the three arguments, (err, bytesRead, buffer). Let us create a js file named main.js with the following code − var fs = require("fs"); var buf = new Buffer(1024); console.log("Going to open an existing file"); fs.open('input.txt', 'r+', function(err, fd) { if (err) { return console.error(err); } console.log("File opened successfully!"); console.log("Going to read the file"); fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){ if (err){ console.log(err); } console.log(bytes + " bytes read"); // Print only read bytes to avoid junk. if(bytes > 0){ console.log(buf.slice(0, bytes).toString()); } }); }); Now run the main.js to see the result − $ node main.js Verify the Output. Going to open an existing file File opened successfully! Going to read the file 97 bytes read Tutorials Point is giving self learning content to teach the world in simple and easy way!!!!! Following is the syntax to close an opened file − fs.close(fd, callback) Here is the description of the parameters used − fd − This is the file descriptor returned by file fs.open() method. fd − This is the file descriptor returned by file fs.open() method. callback − This is the callback function No arguments other than a possible exception are given to the completion callback. callback − This is the callback function No arguments other than a possible exception are given to the completion callback. Let us create a js file named main.js having the following code − var fs = require("fs"); var buf = new Buffer(1024); console.log("Going to open an existing file"); fs.open('input.txt', 'r+', function(err, fd) { if (err) { return console.error(err); } console.log("File opened successfully!"); console.log("Going to read the file"); fs.read(fd, buf, 0, buf.length, 0, function(err, bytes) { if (err) { console.log(err); } // Print only read bytes to avoid junk. if(bytes > 0) { console.log(buf.slice(0, bytes).toString()); } // Close the opened file. fs.close(fd, function(err) { if (err) { console.log(err); } console.log("File closed successfully."); }); }); }); Now run the main.js to see the result − $ node main.js Verify the Output. Going to open an existing file File opened successfully! Going to read the file Tutorials Point is giving self learning content to teach the world in simple and easy way!!!!! File closed successfully. Following is the syntax of the method to truncate an opened file − fs.ftruncate(fd, len, callback) Here is the description of the parameters used − fd − This is the file descriptor returned by fs.open(). fd − This is the file descriptor returned by fs.open(). len − This is the length of the file after which the file will be truncated. len − This is the length of the file after which the file will be truncated. callback − This is the callback function No arguments other than a possible exception are given to the completion callback. callback − This is the callback function No arguments other than a possible exception are given to the completion callback. Let us create a js file named main.js having the following code − var fs = require("fs"); var buf = new Buffer(1024); console.log("Going to open an existing file"); fs.open('input.txt', 'r+', function(err, fd) { if (err) { return console.error(err); } console.log("File opened successfully!"); console.log("Going to truncate the file after 10 bytes"); // Truncate the opened file. fs.ftruncate(fd, 10, function(err) { if (err) { console.log(err); } console.log("File truncated successfully."); console.log("Going to read the same file"); fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){ if (err) { console.log(err); } // Print only read bytes to avoid junk. if(bytes > 0) { console.log(buf.slice(0, bytes).toString()); } // Close the opened file. fs.close(fd, function(err) { if (err) { console.log(err); } console.log("File closed successfully."); }); }); }); }); Now run the main.js to see the result − $ node main.js Verify the Output. Going to open an existing file File opened successfully! Going to truncate the file after 10 bytes File truncated successfully. Going to read the same file Tutorials File closed successfully. Following is the syntax of the method to delete a file − fs.unlink(path, callback) Here is the description of the parameters used − path − This is the file name including path. path − This is the file name including path. callback − This is the callback function No arguments other than a possible exception are given to the completion callback. callback − This is the callback function No arguments other than a possible exception are given to the completion callback. Let us create a js file named main.js having the following code − var fs = require("fs"); console.log("Going to delete an existing file"); fs.unlink('input.txt', function(err) { if (err) { return console.error(err); } console.log("File deleted successfully!"); }); Now run the main.js to see the result − $ node main.js Verify the Output. Going to delete an existing file File deleted successfully! Following is the syntax of the method to create a directory − fs.mkdir(path[, mode], callback) Here is the description of the parameters used − path − This is the directory name including path. path − This is the directory name including path. mode − This is the directory permission to be set. Defaults to 0777. mode − This is the directory permission to be set. Defaults to 0777. callback − This is the callback function No arguments other than a possible exception are given to the completion callback. callback − This is the callback function No arguments other than a possible exception are given to the completion callback. Let us create a js file named main.js having the following code − var fs = require("fs"); console.log("Going to create directory /tmp/test"); fs.mkdir('/tmp/test',function(err) { if (err) { return console.error(err); } console.log("Directory created successfully!"); }); Now run the main.js to see the result − $ node main.js Verify the Output. Going to create directory /tmp/test Directory created successfully! Following is the syntax of the method to read a directory − fs.readdir(path, callback) Here is the description of the parameters used − path − This is the directory name including path. path − This is the directory name including path. callback − This is the callback function which gets two arguments (err, files) where files is an array of the names of the files in the directory excluding '.' and '..'. callback − This is the callback function which gets two arguments (err, files) where files is an array of the names of the files in the directory excluding '.' and '..'. Let us create a js file named main.js having the following code − var fs = require("fs"); console.log("Going to read directory /tmp"); fs.readdir("/tmp/",function(err, files) { if (err) { return console.error(err); } files.forEach( function (file) { console.log( file ); }); }); Now run the main.js to see the result − $ node main.js Verify the Output. Going to read directory /tmp ccmzx99o.out ccyCSbkF.out employee.ser hsperfdata_apache test test.txt Following is the syntax of the method to remove a directory − fs.rmdir(path, callback) Here is the description of the parameters used − path − This is the directory name including path. path − This is the directory name including path. callback − This is the callback function No arguments other than a possible exception are given to the completion callback. callback − This is the callback function No arguments other than a possible exception are given to the completion callback. Let us create a js file named main.js having the following code − var fs = require("fs"); console.log("Going to delete directory /tmp/test"); fs.rmdir("/tmp/test",function(err) { if (err) { return console.error(err); } console.log("Going to read directory /tmp"); fs.readdir("/tmp/",function(err, files) { if (err) { return console.error(err); } files.forEach( function (file) { console.log( file ); }); }); }); Now run the main.js to see the result − $ node main.js Verify the Output. Going to read directory /tmp ccmzx99o.out ccyCSbkF.out employee.ser hsperfdata_apache test.txt fs.rename(oldPath, newPath, callback) Asynchronous rename(). No arguments other than a possible exception are given to the completion callback. fs.ftruncate(fd, len, callback) Asynchronous ftruncate(). No arguments other than a possible exception are given to the completion callback. fs.ftruncateSync(fd, len) Synchronous ftruncate(). fs.truncate(path, len, callback) Asynchronous truncate(). No arguments other than a possible exception are given to the completion callback. fs.truncateSync(path, len) Synchronous truncate(). fs.chown(path, uid, gid, callback) Asynchronous chown(). No arguments other than a possible exception are given to the completion callback. fs.chownSync(path, uid, gid) Synchronous chown(). fs.fchown(fd, uid, gid, callback) Asynchronous fchown(). No arguments other than a possible exception are given to the completion callback. fs.fchownSync(fd, uid, gid) Synchronous fchown(). fs.lchown(path, uid, gid, callback) Asynchronous lchown(). No arguments other than a possible exception are given to the completion callback. fs.lchownSync(path, uid, gid) Synchronous lchown(). fs.chmod(path, mode, callback) Asynchronous chmod(). No arguments other than a possible exception are given to the completion callback. fs.chmodSync(path, mode) Synchronous chmod(). fs.fchmod(fd, mode, callback) Asynchronous fchmod(). No arguments other than a possible exception are given to the completion callback. fs.fchmodSync(fd, mode) Synchronous fchmod(). fs.lchmod(path, mode, callback) Asynchronous lchmod(). No arguments other than a possible exception are given to the completion callback. Only available on Mac OS X. fs.lchmodSync(path, mode) Synchronous lchmod(). fs.stat(path, callback) Asynchronous stat(). The callback gets two arguments (err, stats) where stats is an fs.Stats object. fs.lstat(path, callback) Asynchronous lstat(). The callback gets two arguments (err, stats) where stats is an fs.Stats object. lstat() is identical to stat(), except that if path is a symbolic link, then the link itself is stat-ed, not the file that it refers to. fs.fstat(fd, callback) Asynchronous fstat(). The callback gets two arguments (err, stats) where stats is an fs.Stats object. fstat() is identical to stat(), except that the file to be stat-ed is specified by the file descriptor fd. fs.statSync(path) Synchronous stat(). Returns an instance of fs.Stats. fs.lstatSync(path) Synchronous lstat(). Returns an instance of fs.Stats. fs.fstatSync(fd) Synchronous fstat(). Returns an instance of fs.Stats. fs.link(srcpath, dstpath, callback) Asynchronous link(). No arguments other than a possible exception are given to the completion callback. fs.linkSync(srcpath, dstpath) Synchronous link(). fs.symlink(srcpath, dstpath[, type], callback) Asynchronous symlink(). No arguments other than a possible exception are given to the completion callback. The type argument can be set to 'dir', 'file', or 'junction' (default is 'file') and is only available on Windows (ignored on other platforms). Note that Windows junction points require the destination path to be absolute. When using 'junction', the destination argument will automatically be normalized to absolute path. fs.symlinkSync(srcpath, dstpath[, type]) Synchronous symlink(). fs.readlink(path, callback) Asynchronous readlink(). The callback gets two arguments (err, linkString). fs.realpath(path[, cache], callback) Asynchronous realpath(). The callback gets two arguments (err, resolvedPath). May use process.cwd to resolve relative paths. cache is an object literal of mapped paths that can be used to force a specific path resolution or avoid additional fs.stat calls for known real paths. fs.realpathSync(path[, cache]) Synchronous realpath(). Returns the resolved path. fs.unlink(path, callback) Asynchronous unlink(). No arguments other than a possible exception are given to the completion callback. fs.unlinkSync(path) Synchronous unlink(). fs.rmdir(path, callback) Asynchronous rmdir(). No arguments other than a possible exception are given to the completion callback. fs.rmdirSync(path) Synchronous rmdir(). fs.mkdir(path[, mode], callback) Asynchronous mkdir(2). No arguments other than a possible exception are given to the completion callback. mode defaults to 0777. fs.mkdirSync(path[, mode]) Synchronous mkdir(). fs.readdir(path, callback) Asynchronous readdir(3). Reads the contents of a directory. The callback gets two arguments (err, files) where files is an array of the names of the files in the directory excluding '.' and '..'. fs.readdirSync(path) Synchronous readdir(). Returns an array of filenames excluding '.' and '..'. fs.close(fd, callback) Asynchronous close(). No arguments other than a possible exception are given to the completion callback. fs.closeSync(fd) Synchronous close(). fs.open(path, flags[, mode], callback) Asynchronous file open. fs.openSync(path, flags[, mode]) Synchronous version of fs.open(). fs.utimes(path, atime, mtime, callback) fs.utimesSync(path, atime, mtime) Change file timestamps of the file referenced by the supplied path. fs.futimes(fd, atime, mtime, callback) fs.futimesSync(fd, atime, mtime) Change the file timestamps of a file referenced by the supplied file descriptor. fs.fsync(fd, callback) Asynchronous fsync. No arguments other than a possible exception are given to the completion callback. fs.fsyncSync(fd) Synchronous fsync. fs.write(fd, buffer, offset, length[, position], callback) Write buffer to the file specified by fd. fs.write(fd, data[, position[, encoding]], callback) Write data to the file specified by fd. If data is not a Buffer instance then the value will be coerced to a string. fs.writeSync(fd, buffer, offset, length[, position]) Synchronous versions of fs.write(). Returns the number of bytes written. fs.writeSync(fd, data[, position[, encoding]]) Synchronous versions of fs.write(). Returns the number of bytes written. fs.read(fd, buffer, offset, length, position, callback) Read data from the file specified by fd. fs.readSync(fd, buffer, offset, length, position) Synchronous version of fs.read. Returns the number of bytesRead. fs.readFile(filename[, options], callback) Asynchronously reads the entire contents of a file. fs.readFileSync(filename[, options]) Synchronous version of fs.readFile. Returns the contents of the filename. fs.writeFile(filename, data[, options], callback) Asynchronously writes data to a file, replacing the file if it already exists. data can be a string or a buffer. fs.writeFileSync(filename, data[, options]) The synchronous version of fs.writeFile. fs.appendFile(filename, data[, options], callback) Asynchronously append data to a file, creating the file if it does not exist. data can be a string or a buffer. fs.appendFileSync(filename, data[, options]) The synchronous version of fs.appendFile. fs.watchFile(filename[, options], listener) Watch for changes on filename. The callback listener will be called each time the file is accessed. fs.unwatchFile(filename[, listener]) Stop watching for changes on filename. If listener is specified, only that particular listener is removed. Otherwise, all listeners are removed and you have effectively stopped watching filename. fs.watch(filename[, options][, listener]) Watch for changes on filename, where filename is either a file or an directory. The returned object is an fs.FSWatcher. fs.exists(path, callback) Test whether or not the given path exists by checking with the file system. Then call the callback argument with either true or false. fs.existsSync(path) Synchronous version of fs.exists. fs.access(path[, mode], callback) Tests a user's permissions for the file specified by path. mode is an optional integer that specifies the accessibility checks to be performed. fs.accessSync(path[, mode]) Synchronous version of fs.access. It throws if any accessibility checks fail, and does nothing otherwise. fs.createReadStream(path[, options]) Returns a new ReadStream object. fs.createWriteStream(path[, options]) Returns a new WriteStream object. fs.symlink(srcpath, dstpath[, type], callback) Asynchronous symlink(). No arguments other than a possible exception are given to the completion callback. The type argument can be set to 'dir', 'file', or 'junction' (default is 'file') and is only available on Windows (ignored on other platforms). Note that Windows junction points require the destination path to be absolute. When using 'junction', the destination argument will automatically be normalized to absolute path. Node.js global objects are global in nature and they are available in all modules. We do not need to include these objects in our application, rather we can use them directly. These objects are modules, functions, strings and object itself as explained below. The __filename represents the filename of the code being executed. This is the resolved absolute path of this code file. For a main program, this is not necessarily the same filename used in the command line. The value inside a module is the path to that module file. Create a js file named main.js with the following code − // Let's try to print the value of __filename console.log( __filename ); Now run the main.js to see the result − $ node main.js Based on the location of your program, it will print the main file name as follows − /web/com/1427091028_21099/main.js The __dirname represents the name of the directory that the currently executing script resides in. Create a js file named main.js with the following code − // Let's try to print the value of __dirname console.log( __dirname ); Now run the main.js to see the result − $ node main.js Based on the location of your program, it will print current directory name as follows − /web/com/1427091028_21099 The setTimeout(cb, ms) global function is used to run callback cb after at least ms milliseconds. The actual delay depends on external factors like OS timer granularity and system load. A timer cannot span more than 24.8 days. This function returns an opaque value that represents the timer which can be used to clear the timer. Create a js file named main.js with the following code − function printHello() { console.log( "Hello, World!"); } // Now call above function after 2 seconds setTimeout(printHello, 2000); Now run the main.js to see the result − $ node main.js Verify the output is printed after a little delay. Hello, World! The clearTimeout(t) global function is used to stop a timer that was previously created with setTimeout(). Here t is the timer returned by the setTimeout() function. Create a js file named main.js with the following code − function printHello() { console.log( "Hello, World!"); } // Now call above function after 2 seconds var t = setTimeout(printHello, 2000); // Now clear the timer clearTimeout(t); Now run the main.js to see the result − $ node main.js Verify the output where you will not find anything printed. The setInterval(cb, ms) global function is used to run callback cb repeatedly after at least ms milliseconds. The actual delay depends on external factors like OS timer granularity and system load. A timer cannot span more than 24.8 days. This function returns an opaque value that represents the timer which can be used to clear the timer using the function clearInterval(t). Create a js file named main.js with the following code − function printHello() { console.log( "Hello, World!"); } // Now call above function after 2 seconds setInterval(printHello, 2000); Now run the main.js to see the result − $ node main.js The above program will execute printHello() after every 2 second. Due to system limitation. The following table provides a list of other objects which we use frequently in our applications. For a more detail, you can refer to the official documentation. Used to print information on stdout and stderr. Used to get information on current process. Provides multiple events related to process activities. There are several utility modules available in Node.js module library. These modules are very common and are frequently used while developing any Node based application. Provides basic operating-system related utility functions. Provides utilities for handling and transforming file paths. Provides both servers and clients as streams. Acts as a network wrapper. Provides functions to do actual DNS lookup as well as to use underlying operating system name resolution functionalities. Provides ways to handle multiple different I/O operations as a single group. A Web Server is a software application which handles HTTP requests sent by the HTTP client, like web browsers, and returns web pages in response to the clients. Web servers usually deliver html documents along with images, style sheets, and scripts. Most of the web servers support server-side scripts, using scripting languages or redirecting the task to an application server which retrieves data from a database and performs complex logic and then sends a result to the HTTP client through the Web server. Apache web server is one of the most commonly used web servers. It is an open source project. A Web application is usually divided into four layers − Client − This layer consists of web browsers, mobile browsers or applications which can make HTTP requests to the web server. Client − This layer consists of web browsers, mobile browsers or applications which can make HTTP requests to the web server. Server − This layer has the Web server which can intercept the requests made by the clients and pass them the response. Server − This layer has the Web server which can intercept the requests made by the clients and pass them the response. Business − This layer contains the application server which is utilized by the web server to do the required processing. This layer interacts with the data layer via the database or some external programs. Business − This layer contains the application server which is utilized by the web server to do the required processing. This layer interacts with the data layer via the database or some external programs. Data − This layer contains the databases or any other source of data. Data − This layer contains the databases or any other source of data. Node.js provides an http module which can be used to create an HTTP client of a server. Following is the bare minimum structure of the HTTP server which listens at 8081 port. Create a js file named server.js − File: server.js var http = require('http'); var fs = require('fs'); var url = require('url'); // Create a server http.createServer( function (request, response) { // Parse the request containing file name var pathname = url.parse(request.url).pathname; // Print the name of the file for which request is made. console.log("Request for " + pathname + " received."); // Read the requested file content from file system fs.readFile(pathname.substr(1), function (err, data) { if (err) { console.log(err); // HTTP Status: 404 : NOT FOUND // Content Type: text/plain response.writeHead(404, {'Content-Type': 'text/html'}); } else { //Page found // HTTP Status: 200 : OK // Content Type: text/plain response.writeHead(200, {'Content-Type': 'text/html'}); // Write the content of the file to response body response.write(data.toString()); } // Send the response body response.end(); }); }).listen(8081); // Console will print the message console.log('Server running at http://127.0.0.1:8081/'); Next let's create the following html file named index.htm in the same directory where you created server.js. File: index.htm <html> <head> <title>Sample Page</title> </head> <body> Hello World! </body> </html> Now let us run the server.js to see the result − $ node server.js Verify the Output. Server running at http://127.0.0.1:8081/ Open http://127.0.0.1:8081/index.htm in any browser to see the following result. Verify the Output at server end. Server running at http://127.0.0.1:8081/ Request for /index.htm received. A web client can be created using http module. Let's check the following example. Create a js file named client.js − File: client.js var http = require('http'); // Options to be used by request var options = { host: 'localhost', port: '8081', path: '/index.htm' }; // Callback function is used to deal with response var callback = function(response) { // Continuously update stream with data var body = ''; response.on('data', function(data) { body += data; }); response.on('end', function() { // Data received completely. console.log(body); }); } // Make a request to the server var req = http.request(options, callback); req.end(); Now run the client.js from a different command terminal other than server.js to see the result − $ node client.js Verify the Output. <html> <head> <title>Sample Page</title> </head> <body> Hello World! </body> </html> Verify the Output at server end. Server running at http://127.0.0.1:8081/ Request for /index.htm received. Express is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications. It facilitates the rapid development of Node based Web applications. Following are some of the core features of Express framework − Allows to set up middlewares to respond to HTTP Requests. Allows to set up middlewares to respond to HTTP Requests. Defines a routing table which is used to perform different actions based on HTTP Method and URL. Defines a routing table which is used to perform different actions based on HTTP Method and URL. Allows to dynamically render HTML Pages based on passing arguments to templates. Allows to dynamically render HTML Pages based on passing arguments to templates. Firstly, install the Express framework globally using NPM so that it can be used to create a web application using node terminal. $ npm install express --save The above command saves the installation locally in the node_modules directory and creates a directory express inside node_modules. You should install the following important modules along with express − body-parser − This is a node.js middleware for handling JSON, Raw, Text and URL encoded form data. body-parser − This is a node.js middleware for handling JSON, Raw, Text and URL encoded form data. cookie-parser − Parse Cookie header and populate req.cookies with an object keyed by the cookie names. cookie-parser − Parse Cookie header and populate req.cookies with an object keyed by the cookie names. multer − This is a node.js middleware for handling multipart/form-data. multer − This is a node.js middleware for handling multipart/form-data. $ npm install body-parser --save $ npm install cookie-parser --save $ npm install multer --save Following is a very basic Express app which starts a server and listens on port 8081 for connection. This app responds with Hello World! for requests to the homepage. For every other path, it will respond with a 404 Not Found. var express = require('express'); var app = express(); app.get('/', function (req, res) { res.send('Hello World'); }) var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("Example app listening at http://%s:%s", host, port) }) Save the above code in a file named server.js and run it with the following command. $ node server.js You will see the following output − Example app listening at http://0.0.0.0:8081 Open http://127.0.0.1:8081/ in any browser to see the following result. Express application uses a callback function whose parameters are request and response objects. app.get('/', function (req, res) { // -- }) Request Object − The request object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on. Request Object − The request object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on. Response Object − The response object represents the HTTP response that an Express app sends when it gets an HTTP request. Response Object − The response object represents the HTTP response that an Express app sends when it gets an HTTP request. You can print req and res objects which provide a lot of information related to HTTP request and response including cookies, sessions, URL, etc. We have seen a basic application which serves HTTP request for the homepage. Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on). We will extend our Hello World program to handle more types of HTTP requests. var express = require('express'); var app = express(); // This responds with "Hello World" on the homepage app.get('/', function (req, res) { console.log("Got a GET request for the homepage"); res.send('Hello GET'); }) // This responds a POST request for the homepage app.post('/', function (req, res) { console.log("Got a POST request for the homepage"); res.send('Hello POST'); }) // This responds a DELETE request for the /del_user page. app.delete('/del_user', function (req, res) { console.log("Got a DELETE request for /del_user"); res.send('Hello DELETE'); }) // This responds a GET request for the /list_user page. app.get('/list_user', function (req, res) { console.log("Got a GET request for /list_user"); res.send('Page Listing'); }) // This responds a GET request for abcd, abxcd, ab123cd, and so on app.get('/ab*cd', function(req, res) { console.log("Got a GET request for /ab*cd"); res.send('Page Pattern Match'); }) var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("Example app listening at http://%s:%s", host, port) }) Save the above code in a file named server.js and run it with the following command. $ node server.js You will see the following output − Example app listening at http://0.0.0.0:8081 Now you can try different requests at http://127.0.0.1:8081 to see the output generated by server.js. Following are a few screens shots showing different responses for different URLs. Screen showing again http://127.0.0.1:8081/list_user Screen showing again http://127.0.0.1:8081/abcd Screen showing again http://127.0.0.1:8081/abcdefg Express provides a built-in middleware express.static to serve static files, such as images, CSS, JavaScript, etc. You simply need to pass the name of the directory where you keep your static assets, to the express.static middleware to start serving the files directly. For example, if you keep your images, CSS, and JavaScript files in a directory named public, you can do this − app.use(express.static('public')); We will keep a few images in public/images sub-directory as follows − node_modules server.js public/ public/images public/images/logo.png Let's modify "Hello Word" app to add the functionality to handle static files. var express = require('express'); var app = express(); app.use(express.static('public')); app.get('/', function (req, res) { res.send('Hello World'); }) var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("Example app listening at http://%s:%s", host, port) }) Save the above code in a file named server.js and run it with the following command. $ node server.js Now open http://127.0.0.1:8081/images/logo.png in any browser and see observe following result. Here is a simple example which passes two values using HTML FORM GET method. We are going to use process_get router inside server.js to handle this input. <html> <body> <form action = "http://127.0.0.1:8081/process_get" method = "GET"> First Name: <input type = "text" name = "first_name"> <br> Last Name: <input type = "text" name = "last_name"> <input type = "submit" value = "Submit"> </form> </body> </html> Let's save above code in index.htm and modify server.js to handle home page requests as well as the input sent by the HTML form. var express = require('express'); var app = express(); app.use(express.static('public')); app.get('/index.htm', function (req, res) { res.sendFile( __dirname + "/" + "index.htm" ); }) app.get('/process_get', function (req, res) { // Prepare output in JSON format response = { first_name:req.query.first_name, last_name:req.query.last_name }; console.log(response); res.end(JSON.stringify(response)); }) var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("Example app listening at http://%s:%s", host, port) }) Accessing the HTML document using http://127.0.0.1:8081/index.htm will generate the following form − First Name: Last Name: Now you can enter the First and Last Name and then click submit button to see the result and it should return the following result − {"first_name":"John","last_name":"Paul"} Here is a simple example which passes two values using HTML FORM POST method. We are going to use process_get router inside server.js to handle this input. <html> <body> <form action = "http://127.0.0.1:8081/process_post" method = "POST"> First Name: <input type = "text" name = "first_name"> <br> Last Name: <input type = "text" name = "last_name"> <input type = "submit" value = "Submit"> </form> </body> </html> Let's save the above code in index.htm and modify server.js to handle home page requests as well as the input sent by the HTML form. var express = require('express'); var app = express(); var bodyParser = require('body-parser'); // Create application/x-www-form-urlencoded parser var urlencodedParser = bodyParser.urlencoded({ extended: false }) app.use(express.static('public')); app.get('/index.htm', function (req, res) { res.sendFile( __dirname + "/" + "index.htm" ); }) app.post('/process_post', urlencodedParser, function (req, res) { // Prepare output in JSON format response = { first_name:req.body.first_name, last_name:req.body.last_name }; console.log(response); res.end(JSON.stringify(response)); }) var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("Example app listening at http://%s:%s", host, port) }) Accessing the HTML document using http://127.0.0.1:8081/index.htm will generate the following form − First Name: Last Name: Now you can enter the First and Last Name and then click the submit button to see the following result − {"first_name":"John","last_name":"Paul"} The following HTML code creates a file uploader form. This form has method attribute set to POST and enctype attribute is set to multipart/form-data <html> <head> <title>File Uploading Form</title> </head> <body> <h3>File Upload:</h3> Select a file to upload: <br /> <form action = "http://127.0.0.1:8081/file_upload" method = "POST" enctype = "multipart/form-data"> <input type="file" name="file" size="50" /> <br /> <input type = "submit" value = "Upload File" /> </form> </body> </html> Let's save above code in index.htm and modify server.js to handle home page requests as well as file upload. var express = require('express'); var app = express(); var fs = require("fs"); var bodyParser = require('body-parser'); var multer = require('multer'); app.use(express.static('public')); app.use(bodyParser.urlencoded({ extended: false })); app.use(multer({ dest: '/tmp/'})); app.get('/index.htm', function (req, res) { res.sendFile( __dirname + "/" + "index.htm" ); }) app.post('/file_upload', function (req, res) { console.log(req.files.file.name); console.log(req.files.file.path); console.log(req.files.file.type); var file = __dirname + "/" + req.files.file.name; fs.readFile( req.files.file.path, function (err, data) { fs.writeFile(file, data, function (err) { if( err ) { console.log( err ); } else { response = { message:'File uploaded successfully', filename:req.files.file.name }; } console.log( response ); res.end( JSON.stringify( response ) ); }); }); }) var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("Example app listening at http://%s:%s", host, port) }) Accessing the HTML document using http://127.0.0.1:8081/index.htm will generate the following form − File Upload: Select a file to upload: NOTE: This is just dummy form and would not work, but it must work at your server. You can send cookies to a Node.js server which can handle the same using the following middleware option. Following is a simple example to print all the cookies sent by the client. var express = require('express') var cookieParser = require('cookie-parser') var app = express() app.use(cookieParser()) app.get('/', function(req, res) { console.log("Cookies: ", req.cookies) }) app.listen(8081) REST stands for REpresentational State Transfer. REST is web standards based architecture and uses HTTP Protocol. It revolves around resource where every component is a resource and a resource is accessed by a common interface using HTTP standard methods. REST was first introduced by Roy Fielding in 2000. A REST Server simply provides access to resources and REST client accesses and modifies the resources using HTTP protocol. Here each resource is identified by URIs/ global IDs. REST uses various representation to represent a resource like text, JSON, XML but JSON is the most popular one. Following four HTTP methods are commonly used in REST based architecture. GET − This is used to provide a read only access to a resource. GET − This is used to provide a read only access to a resource. PUT − This is used to create a new resource. PUT − This is used to create a new resource. DELETE − This is used to remove a resource. DELETE − This is used to remove a resource. POST − This is used to update a existing resource or create a new resource. POST − This is used to update a existing resource or create a new resource. A web service is a collection of open protocols and standards used for exchanging data between applications or systems. Software applications written in various programming languages and running on various platforms can use web services to exchange data over computer networks like the Internet in a manner similar to inter-process communication on a single computer. This interoperability (e.g., communication between Java and Python, or Windows and Linux applications) is due to the use of open standards. Web services based on REST Architecture are known as RESTful web services. These webservices uses HTTP methods to implement the concept of REST architecture. A RESTful web service usually defines a URI, Uniform Resource Identifier a service, which provides resource representation such as JSON and set of HTTP Methods. Consider we have a JSON based database of users having the following users in a file users.json: { "user1" : { "name" : "mahesh", "password" : "password1", "profession" : "teacher", "id": 1 }, "user2" : { "name" : "suresh", "password" : "password2", "profession" : "librarian", "id": 2 }, "user3" : { "name" : "ramesh", "password" : "password3", "profession" : "clerk", "id": 3 } } Based on this information we are going to provide following RESTful APIs. I'm keeping most of the part of all the examples in the form of hard coding assuming you already know how to pass values from front end using Ajax or simple form data and how to process them using express Request object. Let's implement our first RESTful API listUsers using the following code in a server.js file − server.js var express = require('express'); var app = express(); var fs = require("fs"); app.get('/listUsers', function (req, res) { fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) { console.log( data ); res.end( data ); }); }) var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("Example app listening at http://%s:%s", host, port) }) Now try to access defined API using URL: http://127.0.0.1:8081/listUsers and HTTP Method : GET on local machine using any REST client. This should produce following result − You can change given IP address when you will put the solution in production environment. { "user1" : { "name" : "mahesh", "password" : "password1", "profession" : "teacher", "id": 1 }, "user2" : { "name" : "suresh", "password" : "password2", "profession" : "librarian", "id": 2 }, "user3" : { "name" : "ramesh", "password" : "password3", "profession" : "clerk", "id": 3 } } Following API will show you how to add new user in the list. Following is the detail of the new user − user = { "user4" : { "name" : "mohit", "password" : "password4", "profession" : "teacher", "id": 4 } } You can accept the same input in the form of JSON using Ajax call but for teaching point of view, we are making it hard coded here. Following is the addUser API to a new user in the database − server.js var express = require('express'); var app = express(); var fs = require("fs"); var user = { "user4" : { "name" : "mohit", "password" : "password4", "profession" : "teacher", "id": 4 } } app.post('/addUser', function (req, res) { // First read existing users. fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) { data = JSON.parse( data ); data["user4"] = user["user4"]; console.log( data ); res.end( JSON.stringify(data)); }); }) var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("Example app listening at http://%s:%s", host, port) }) Now try to access defined API using URL: http://127.0.0.1:8081/addUser and HTTP Method : POST on local machine using any REST client. This should produce following result − { "user1":{"name":"mahesh","password":"password1","profession":"teacher","id":1}, "user2":{"name":"suresh","password":"password2","profession":"librarian","id":2}, "user3":{"name":"ramesh","password":"password3","profession":"clerk","id":3}, "user4":{"name":"mohit","password":"password4","profession":"teacher","id":4} } Now we will implement an API which will be called using user ID and it will display the detail of the corresponding user. server.js var express = require('express'); var app = express(); var fs = require("fs"); app.get('/:id', function (req, res) { // First read existing users. fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) { var users = JSON.parse( data ); var user = users["user" + req.params.id] console.log( user ); res.end( JSON.stringify(user)); }); }) var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("Example app listening at http://%s:%s", host, port) }) Now try to access defined API using URL: http://127.0.0.1:8081/2 and HTTP Method : GET on local machine using any REST client. This should produce following result − {"name":"suresh","password":"password2","profession":"librarian","id":2} This API is very similar to addUser API where we receive input data through req.body and then based on user ID we delete that user from the database. To keep our program simple we assume we are going to delete user with ID 2. server.js var express = require('express'); var app = express(); var fs = require("fs"); var id = 2; app.delete('/deleteUser', function (req, res) { // First read existing users. fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) { data = JSON.parse( data ); delete data["user" + 2]; console.log( data ); res.end( JSON.stringify(data)); }); }) var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("Example app listening at http://%s:%s", host, port) }) Now try to access defined API using URL: http://127.0.0.1:8081/deleteUser and HTTP Method : DELETE on local machine using any REST client. This should produce following result − {"user1":{"name":"mahesh","password":"password1","profession":"teacher","id":1}, "user3":{"name":"ramesh","password":"password3","profession":"clerk","id":3}} Node.js runs in a single-thread mode, but it uses an event-driven paradigm to handle concurrency. It also facilitates creation of child processes to leverage parallel processing on multi-core CPU based systems. Child processes always have three streams child.stdin, child.stdout, and child.stderr which may be shared with the stdio streams of the parent process. Node provides child_process module which has the following three major ways to create a child process. exec − child_process.exec method runs a command in a shell/console and buffers the output. exec − child_process.exec method runs a command in a shell/console and buffers the output. spawn − child_process.spawn launches a new process with a given command. spawn − child_process.spawn launches a new process with a given command. fork − The child_process.fork method is a special case of the spawn() to create child processes. fork − The child_process.fork method is a special case of the spawn() to create child processes. child_process.exec method runs a command in a shell and buffers the output. It has the following signature − child_process.exec(command[, options], callback) Here is the description of the parameters used − command (String) The command to run, with space-separated arguments command (String) The command to run, with space-separated arguments options (Object) may comprise one or more of the following options − cwd (String) Current working directory of the child process env (Object) Environment key-value pairs encoding (String) (Default: 'utf8') shell (String) Shell to execute the command with (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should understand the -c switch on UNIX or /s /c on Windows. On Windows, command line parsing should be compatible with cmd.exe.) timeout (Number) (Default: 0) maxBuffer (Number) (Default: 200*1024) killSignal (String) (Default: 'SIGTERM') uid (Number) Sets the user identity of the process. gid (Number) Sets the group identity of the process. options (Object) may comprise one or more of the following options − cwd (String) Current working directory of the child process cwd (String) Current working directory of the child process env (Object) Environment key-value pairs env (Object) Environment key-value pairs encoding (String) (Default: 'utf8') encoding (String) (Default: 'utf8') shell (String) Shell to execute the command with (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should understand the -c switch on UNIX or /s /c on Windows. On Windows, command line parsing should be compatible with cmd.exe.) shell (String) Shell to execute the command with (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should understand the -c switch on UNIX or /s /c on Windows. On Windows, command line parsing should be compatible with cmd.exe.) timeout (Number) (Default: 0) timeout (Number) (Default: 0) maxBuffer (Number) (Default: 200*1024) maxBuffer (Number) (Default: 200*1024) killSignal (String) (Default: 'SIGTERM') killSignal (String) (Default: 'SIGTERM') uid (Number) Sets the user identity of the process. uid (Number) Sets the user identity of the process. gid (Number) Sets the group identity of the process. gid (Number) Sets the group identity of the process. callback The function gets three arguments error, stdout, and stderr which are called with the output when the process terminates. callback The function gets three arguments error, stdout, and stderr which are called with the output when the process terminates. The exec() method returns a buffer with a max size and waits for the process to end and tries to return all the buffered data at once. Let us create two js files named support.js and master.js − File: support.js console.log("Child Process " + process.argv[2] + " executed." ); File: master.js const fs = require('fs'); const child_process = require('child_process'); for(var i=0; i<3; i++) { var workerProcess = child_process.exec('node support.js '+i,function (error, stdout, stderr) { if (error) { console.log(error.stack); console.log('Error code: '+error.code); console.log('Signal received: '+error.signal); } console.log('stdout: ' + stdout); console.log('stderr: ' + stderr); }); workerProcess.on('exit', function (code) { console.log('Child process exited with exit code '+code); }); } Now run the master.js to see the result − $ node master.js Verify the Output. Server has started. Child process exited with exit code 0 stdout: Child Process 1 executed. stderr: Child process exited with exit code 0 stdout: Child Process 0 executed. stderr: Child process exited with exit code 0 stdout: Child Process 2 executed. child_process.spawn method launches a new process with a given command. It has the following signature − child_process.spawn(command[, args][, options]) Here is the description of the parameters used − command (String) The command to run command (String) The command to run args (Array) List of string arguments args (Array) List of string arguments options (Object) may comprise one or more of the following options − cwd (String) Current working directory of the child process. env (Object) Environment key-value pairs. stdio (Array) String Child's stdio configuration. customFds (Array) Deprecated File descriptors for the child to use for stdio. detached (Boolean) The child will be a process group leader. uid (Number) Sets the user identity of the process. gid (Number) Sets the group identity of the process. options (Object) may comprise one or more of the following options − cwd (String) Current working directory of the child process. cwd (String) Current working directory of the child process. env (Object) Environment key-value pairs. env (Object) Environment key-value pairs. stdio (Array) String Child's stdio configuration. stdio (Array) String Child's stdio configuration. customFds (Array) Deprecated File descriptors for the child to use for stdio. customFds (Array) Deprecated File descriptors for the child to use for stdio. detached (Boolean) The child will be a process group leader. detached (Boolean) The child will be a process group leader. uid (Number) Sets the user identity of the process. uid (Number) Sets the user identity of the process. gid (Number) Sets the group identity of the process. gid (Number) Sets the group identity of the process. The spawn() method returns streams (stdout &stderr) and it should be used when the process returns a volume amount of data. spawn() starts receiving the response as soon as the process starts executing. Create two js files named support.js and master.js − File: support.js console.log("Child Process " + process.argv[2] + " executed." ); File: master.js const fs = require('fs'); const child_process = require('child_process'); for(var i = 0; i<3; i++) { var workerProcess = child_process.spawn('node', ['support.js', i]); workerProcess.stdout.on('data', function (data) { console.log('stdout: ' + data); }); workerProcess.stderr.on('data', function (data) { console.log('stderr: ' + data); }); workerProcess.on('close', function (code) { console.log('child process exited with code ' + code); }); } Now run the master.js to see the result − $ node master.js Verify the Output. Server has started stdout: Child Process 0 executed. child process exited with code 0 stdout: Child Process 1 executed. stdout: Child Process 2 executed. child process exited with code 0 child process exited with code 0 child_process.fork method is a special case of spawn() to create Node processes. It has the following signature − child_process.fork(modulePath[, args][, options]) Here is the description of the parameters used − modulePath (String) The module to run in the child. modulePath (String) The module to run in the child. args (Array) List of string arguments args (Array) List of string arguments options (Object) may comprise one or more of the following options − cwd (String) Current working directory of the child process. env (Object) Environment key-value pairs. execPath (String) Executable used to create the child process. execArgv (Array) List of string arguments passed to the executable (Default: process.execArgv). silent (Boolean) If true, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent, see the "pipe" and "inherit" options for spawn()'s stdio for more details (default is false). uid (Number) Sets the user identity of the process. gid (Number) Sets the group identity of the process. options (Object) may comprise one or more of the following options − cwd (String) Current working directory of the child process. cwd (String) Current working directory of the child process. env (Object) Environment key-value pairs. env (Object) Environment key-value pairs. execPath (String) Executable used to create the child process. execPath (String) Executable used to create the child process. execArgv (Array) List of string arguments passed to the executable (Default: process.execArgv). execArgv (Array) List of string arguments passed to the executable (Default: process.execArgv). silent (Boolean) If true, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent, see the "pipe" and "inherit" options for spawn()'s stdio for more details (default is false). silent (Boolean) If true, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent, see the "pipe" and "inherit" options for spawn()'s stdio for more details (default is false). uid (Number) Sets the user identity of the process. uid (Number) Sets the user identity of the process. gid (Number) Sets the group identity of the process. gid (Number) Sets the group identity of the process. The fork method returns an object with a built-in communication channel in addition to having all the methods in a normal ChildProcess instance. Create two js files named support.js and master.js − File: support.js console.log("Child Process " + process.argv[2] + " executed." ); File: master.js const fs = require('fs'); const child_process = require('child_process'); for(var i=0; i<3; i++) { var worker_process = child_process.fork("support.js", [i]); worker_process.on('close', function (code) { console.log('child process exited with code ' + code); }); } Now run the master.js to see the result − $ node master.js Verify the Output. Server has started. Child Process 0 executed. Child Process 1 executed. Child Process 2 executed. child process exited with code 0 child process exited with code 0 child process exited with code 0 JXcore, which is an open source project, introduces a unique feature for packaging and encryption of source files and other assets into JX packages. Consider you have a large project consisting of many files. JXcore can pack them all into a single file to simplify the distribution. This chapter provides a quick overview of the whole process starting from installing JXcore. Installing JXcore is quite simple. Here we have provided step-by-step instructions on how to install JXcore on your system. Follow the steps given below − Download the JXcore package from https://github.com/jxcore/jxcore, as per your operating system and machine architecture. We downloaded a package for Cenots running on 64-bit machine. $ wget https://s3.amazonaws.com/nodejx/jx_rh64.zip Unpack the downloaded file jx_rh64.zipand copy the jx binary into /usr/bin or may be in any other directory based on your system setup. $ unzip jx_rh64.zip $ cp jx_rh64/jx /usr/bin Set your PATH variable appropriately to run jx from anywhere you like. $ export PATH=$PATH:/usr/bin You can verify your installation by issuing a simple command as shown below. You should find it working and printing its version number as follows − $ jx --version v0.10.32 Consider you have a project with the following directories where you kept all your files including Node.js, main file, index.js, and all the modules installed locally. drwxr-xr-x 2 root root 4096 Nov 13 12:42 images -rwxr-xr-x 1 root root 30457 Mar 6 12:19 index.htm -rwxr-xr-x 1 root root 30452 Mar 1 12:54 index.js drwxr-xr-x 23 root root 4096 Jan 15 03:48 node_modules drwxr-xr-x 2 root root 4096 Mar 21 06:10 scripts drwxr-xr-x 2 root root 4096 Feb 15 11:56 style To package the above project, you simply need to go inside this directory and issue the following jx command. Assuming index.js is the entry file for your Node.js project − $ jx package index.js index Here you could have used any other package name instead of index. We have used index because we wanted to keep our main file name as index.jx. However, the above command will pack everything and will create the following two files − index.jxp This is an intermediate file which contains the complete project detail needed to compile the project. index.jxp This is an intermediate file which contains the complete project detail needed to compile the project. index.jx This is the binary file having the complete package that is ready to be shipped to your client or to your production environment. index.jx This is the binary file having the complete package that is ready to be shipped to your client or to your production environment. Consider your original Node.js project was running as follows − $ node index.js command_line_arguments After compiling your package using JXcore, it can be started as follows − $ jx index.jx command_line_arguments To know more on JXcore, you can check its official website. 44 Lectures 7.5 hours Eduonix Learning Solutions 88 Lectures 17 hours Eduonix Learning Solutions 32 Lectures 1.5 hours Richard Wells 8 Lectures 33 mins Anant Rungta 9 Lectures 2.5 hours SHIVPRASAD KOIRALA 97 Lectures 6 hours Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2271, "s": 2018, "text": "Node.js is a server-side platform built on Google Chrome's JavaScript Engine (V8 Engine). Node.js was developed by Ryan Dahl in 2009 and its latest version is v0.10.36. The definition of Node.js as supplied by its official documentation is as follows −" }, { "code": null, "e": 2571, "s": 2271, "text": "Node.js is a platform built on Chrome's JavaScript runtime for easily building fast and scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices." }, { "code": null, "e": 2818, "s": 2571, "text": "Node.js is an open source, cross-platform runtime environment for developing server-side and networking applications. Node.js applications are written in JavaScript, and can be run within the Node.js runtime on OS X, Microsoft Windows, and Linux." }, { "code": null, "e": 2971, "s": 2818, "text": "Node.js also provides a rich library of various JavaScript modules which simplifies the development of web applications using Node.js to a great extent." }, { "code": null, "e": 3023, "s": 2971, "text": "Node.js = Runtime Environment + JavaScript Library\n" }, { "code": null, "e": 3127, "s": 3023, "text": "Following are some of the important features that make Node.js the first choice of software architects." }, { "code": null, "e": 3474, "s": 3127, "text": "Asynchronous and Event Driven − All APIs of Node.js library are asynchronous, that is, non-blocking. It essentially means a Node.js based server never waits for an API to return data. The server moves to the next API after calling it and a notification mechanism of Events of Node.js helps the server to get a response from the previous API call." }, { "code": null, "e": 3821, "s": 3474, "text": "Asynchronous and Event Driven − All APIs of Node.js library are asynchronous, that is, non-blocking. It essentially means a Node.js based server never waits for an API to return data. The server moves to the next API after calling it and a notification mechanism of Events of Node.js helps the server to get a response from the previous API call." }, { "code": null, "e": 3934, "s": 3821, "text": "Very Fast − Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in code execution." }, { "code": null, "e": 4047, "s": 3934, "text": "Very Fast − Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in code execution." }, { "code": null, "e": 4494, "s": 4047, "text": "Single Threaded but Highly Scalable − Node.js uses a single threaded model with event looping. Event mechanism helps the server to respond in a non-blocking way and makes the server highly scalable as opposed to traditional servers which create limited threads to handle requests. Node.js uses a single threaded program and the same program can provide service to a much larger number of requests than traditional servers like Apache HTTP Server." }, { "code": null, "e": 4941, "s": 4494, "text": "Single Threaded but Highly Scalable − Node.js uses a single threaded model with event looping. Event mechanism helps the server to respond in a non-blocking way and makes the server highly scalable as opposed to traditional servers which create limited threads to handle requests. Node.js uses a single threaded program and the same program can provide service to a much larger number of requests than traditional servers like Apache HTTP Server." }, { "code": null, "e": 5053, "s": 4941, "text": "No Buffering − Node.js applications never buffer any data. These applications simply output the data in chunks." }, { "code": null, "e": 5165, "s": 5053, "text": "No Buffering − Node.js applications never buffer any data. These applications simply output the data in chunks." }, { "code": null, "e": 5218, "s": 5165, "text": "License − Node.js is released under the MIT license." }, { "code": null, "e": 5271, "s": 5218, "text": "License − Node.js is released under the MIT license." }, { "code": null, "e": 5523, "s": 5271, "text": "Following is the link on github wiki containing an exhaustive list of projects, application and companies which are using Node.js. This list includes eBay, General Electric, GoDaddy, Microsoft, PayPal, Uber, Wikipins, Yahoo!, and Yammer to name a few." }, { "code": null, "e": 5572, "s": 5523, "text": "Projects, Applications, and Companies Using Node" }, { "code": null, "e": 5621, "s": 5572, "text": "Projects, Applications, and Companies Using Node" }, { "code": null, "e": 5743, "s": 5621, "text": "The following diagram depicts some important parts of Node.js which we will discuss in detail in the subsequent chapters." }, { "code": null, "e": 5832, "s": 5743, "text": "Following are the areas where Node.js is proving itself as a perfect technology partner." }, { "code": null, "e": 5855, "s": 5832, "text": "I/O bound Applications" }, { "code": null, "e": 5883, "s": 5855, "text": "Data Streaming Applications" }, { "code": null, "e": 5928, "s": 5883, "text": "Data Intensive Real-time Applications (DIRT)" }, { "code": null, "e": 5957, "s": 5928, "text": "JSON APIs based Applications" }, { "code": null, "e": 5982, "s": 5957, "text": "Single Page Applications" }, { "code": null, "e": 6049, "s": 5982, "text": "It is not advisable to use Node.js for CPU intensive applications." }, { "code": null, "e": 6368, "s": 6049, "text": "You really do not need to set up your own environment to start learning Node.js. Reason is very simple, we already have set up Node.js environment online, so that you can execute all the available examples online and learn through practice. Feel free to modify any example and check the results with different options." }, { "code": null, "e": 6503, "s": 6368, "text": "Try the following example using the Live Demo option available at the top right corner of the below sample code box (on our website) −" }, { "code": null, "e": 6570, "s": 6503, "text": "/* Hello World! program in Node.js */\nconsole.log(\"Hello World!\");" }, { "code": null, "e": 6698, "s": 6570, "text": "For most of the examples given in this tutorial, you will find a Try it option, so just make use of it and enjoy your learning." }, { "code": null, "e": 6885, "s": 6698, "text": "If you are still willing to set up your environment for Node.js, you need the following two softwares available on your computer, (a) Text Editor and (b) The Node.js binary installables." }, { "code": null, "e": 7029, "s": 6885, "text": "This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi." }, { "code": null, "e": 7211, "s": 7029, "text": "Name and version of text editor can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on windows as well as Linux or UNIX." }, { "code": null, "e": 7390, "s": 7211, "text": "The files you create with your editor are called source files and contain program source code. The source files for Node.js programs are typically named with the extension \".js\"." }, { "code": null, "e": 7571, "s": 7390, "text": "Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, and finally execute it." }, { "code": null, "e": 7716, "s": 7571, "text": "The source code written in source file is simply javascript. The Node.js interpreter will be used to interpret and execute your javascript code." }, { "code": null, "e": 7897, "s": 7716, "text": "Node.js distribution comes as a binary installable for SunOS , Linux, Mac OS X, and Windows operating systems with the 32-bit (386) and 64-bit (amd64) x86 processor architectures. " }, { "code": null, "e": 7987, "s": 7897, "text": "Following section guides you on how to install Node.js binary distribution on various OS." }, { "code": null, "e": 8164, "s": 7987, "text": "Download latest version of Node.js installable archive file from Node.js Downloads. At the time of writing this tutorial, following are the versions available on different OS." }, { "code": null, "e": 8350, "s": 8164, "text": "Based on your OS architecture, download and extract the archive node-v6.3.1-osname.tar.gz into /tmp, and then finally move extracted files into /usr/local/nodejs directory. For example:" }, { "code": null, "e": 8543, "s": 8350, "text": "$ cd /tmp\n$ wget http://nodejs.org/dist/v6.3.1/node-v6.3.1-linux-x64.tar.gz\n$ tar xvfz node-v6.3.1-linux-x64.tar.gz\n$ mkdir -p /usr/local/nodejs\n$ mv node-v6.3.1-linux-x64/* /usr/local/nodejs\n" }, { "code": null, "e": 8603, "s": 8543, "text": "Add /usr/local/nodejs/bin to the PATH environment variable." }, { "code": null, "e": 8921, "s": 8603, "text": "Use the MSI file and follow the prompts to install the Node.js. By default, the installer uses the Node.js distribution in C:\\Program Files\\nodejs. The installer should set the C:\\Program Files\\nodejs\\bin directory in window's PATH environment variable. Restart any open command prompts for the change to take effect." }, { "code": null, "e": 9014, "s": 8921, "text": "Create a js file named main.js on your machine (Windows or Linux) having the following code." }, { "code": null, "e": 9082, "s": 9014, "text": "/* Hello, World! program in node.js */\nconsole.log(\"Hello, World!\")" }, { "code": null, "e": 9153, "s": 9082, "text": "Now execute main.js file using Node.js interpreter to see the result −" }, { "code": null, "e": 9168, "s": 9153, "text": "$ node main.js" }, { "code": null, "e": 9257, "s": 9168, "text": "If everything is fine with your installation, this should produce the following result −" }, { "code": null, "e": 9272, "s": 9257, "text": "Hello, World!\n" }, { "code": null, "e": 9470, "s": 9272, "text": "Before creating an actual \"Hello, World!\" application using Node.js, let us see the components of a Node.js application. A Node.js application consists of the following three important components −" }, { "code": null, "e": 9550, "s": 9470, "text": "Import required modules − We use the require directive to load Node.js modules." }, { "code": null, "e": 9630, "s": 9550, "text": "Import required modules − We use the require directive to load Node.js modules." }, { "code": null, "e": 9725, "s": 9630, "text": "Create server − A server which will listen to client's requests similar to Apache HTTP Server." }, { "code": null, "e": 9820, "s": 9725, "text": "Create server − A server which will listen to client's requests similar to Apache HTTP Server." }, { "code": null, "e": 10000, "s": 9820, "text": "Read request and return response − The server created in an earlier step will read the HTTP request made by the client which can be a browser or a console and return the response." }, { "code": null, "e": 10180, "s": 10000, "text": "Read request and return response − The server created in an earlier step will read the HTTP request made by the client which can be a browser or a console and return the response." }, { "code": null, "e": 10305, "s": 10180, "text": "We use the require directive to load the http module and store the returned HTTP instance into an http variable as follows −" }, { "code": null, "e": 10334, "s": 10305, "text": "var http = require(\"http\");\n" }, { "code": null, "e": 10646, "s": 10334, "text": "We use the created http instance and call http.createServer() method to create a server instance and then we bind it at port 8081 using the listen method associated with the server instance. Pass it a function with parameters request and response. Write the sample implementation to always return \"Hello World\"." }, { "code": null, "e": 11035, "s": 10646, "text": "http.createServer(function (request, response) {\n // Send the HTTP header \n // HTTP Status: 200 : OK\n // Content Type: text/plain\n response.writeHead(200, {'Content-Type': 'text/plain'});\n \n // Send the response body as \"Hello World\"\n response.end('Hello World\\n');\n}).listen(8081);\n\n// Console will print the message\nconsole.log('Server running at http://127.0.0.1:8081/');" }, { "code": null, "e": 11163, "s": 11035, "text": "The above code is enough to create an HTTP server which listens, i.e., waits for a request over 8081 port on the local machine." }, { "code": null, "e": 11263, "s": 11163, "text": "Let's put step 1 and 2 together in a file called main.js and start our HTTP server as shown below −" }, { "code": null, "e": 11681, "s": 11263, "text": "var http = require(\"http\");\n\nhttp.createServer(function (request, response) {\n // Send the HTTP header \n // HTTP Status: 200 : OK\n // Content Type: text/plain\n response.writeHead(200, {'Content-Type': 'text/plain'});\n \n // Send the response body as \"Hello World\"\n response.end('Hello World\\n');\n}).listen(8081);\n\n// Console will print the message\nconsole.log('Server running at http://127.0.0.1:8081/');" }, { "code": null, "e": 11738, "s": 11681, "text": "Now execute the main.js to start the server as follows −" }, { "code": null, "e": 11753, "s": 11738, "text": "$ node main.js" }, { "code": null, "e": 11792, "s": 11753, "text": "Verify the Output. Server has started." }, { "code": null, "e": 11834, "s": 11792, "text": "Server running at http://127.0.0.1:8081/\n" }, { "code": null, "e": 11911, "s": 11834, "text": "Open http://127.0.0.1:8081/ in any browser and observe the following result." }, { "code": null, "e": 12034, "s": 11911, "text": "Congratulations, you have your first HTTP server up and running which is responding to all the HTTP requests at port 8081." }, { "code": null, "e": 12334, "s": 12034, "text": "REPL stands for Read Eval Print Loop and it represents a computer environment like a Windows console or Unix/Linux shell where a command is entered and the system responds with an output in an interactive mode. Node.js or Node comes bundled with a REPL environment. It performs the following tasks −" }, { "code": null, "e": 12432, "s": 12334, "text": "Read − Reads user's input, parses the input into JavaScript data-structure, and stores in memory." }, { "code": null, "e": 12530, "s": 12432, "text": "Read − Reads user's input, parses the input into JavaScript data-structure, and stores in memory." }, { "code": null, "e": 12577, "s": 12530, "text": "Eval − Takes and evaluates the data structure." }, { "code": null, "e": 12624, "s": 12577, "text": "Eval − Takes and evaluates the data structure." }, { "code": null, "e": 12651, "s": 12624, "text": "Print − Prints the result." }, { "code": null, "e": 12678, "s": 12651, "text": "Print − Prints the result." }, { "code": null, "e": 12746, "s": 12678, "text": "Loop − Loops the above command until the user presses ctrl-c twice." }, { "code": null, "e": 12814, "s": 12746, "text": "Loop − Loops the above command until the user presses ctrl-c twice." }, { "code": null, "e": 12921, "s": 12814, "text": "The REPL feature of Node is very useful in experimenting with Node.js codes and to debug JavaScript codes." }, { "code": null, "e": 13081, "s": 12921, "text": "To simplify your learning, we have set up an easy to use Node.js REPL environment online, where you can practice Node.js syntax − Launch Node.js REPL Terminal " }, { "code": null, "e": 13175, "s": 13081, "text": "REPL can be started by simply running node on shell/console without any arguments as follows." }, { "code": null, "e": 13183, "s": 13175, "text": "$ node\n" }, { "code": null, "e": 13263, "s": 13183, "text": "You will see the REPL Command prompt > where you can type any Node.js command −" }, { "code": null, "e": 13273, "s": 13263, "text": "$ node\n>\n" }, { "code": null, "e": 13341, "s": 13273, "text": "Let's try a simple mathematics at the Node.js REPL command prompt −" }, { "code": null, "e": 13383, "s": 13341, "text": "$ node\n> 1 + 3\n4\n> 1 + ( 2 * 3 ) - 4\n3\n>\n" }, { "code": null, "e": 13673, "s": 13383, "text": "You can make use variables to store values and print later like any conventional script. If var keyword is not used, then the value is stored in the variable and printed. Whereas if var keyword is used, then the value is stored but not printed. You can print variables using console.log()." }, { "code": null, "e": 13778, "s": 13673, "text": "$ node\n> x = 10\n10\n> var y = 10\nundefined\n> x + y\n20\n> console.log(\"Hello World\")\nHello World\nundefined\n" }, { "code": null, "e": 13893, "s": 13778, "text": "Node REPL supports multiline expression similar to JavaScript. Let's check the following do-while loop in action −" }, { "code": null, "e": 14037, "s": 13893, "text": "$ node\n> var x = 0\nundefined\n> do {\n ... x++;\n ... console.log(\"x: \" + x);\n ... } \nwhile ( x < 5 );\nx: 1\nx: 2\nx: 3\nx: 4\nx: 5\nundefined\n>\n" }, { "code": null, "e": 14166, "s": 14037, "text": "... comes automatically when you press Enter after the opening bracket. Node automatically checks the continuity of expressions." }, { "code": null, "e": 14218, "s": 14166, "text": "You can use underscore (_) to get the last result −" }, { "code": null, "e": 14341, "s": 14218, "text": "$ node\n> var x = 10\nundefined\n> var y = 20\nundefined\n> x + y\n30\n> var sum = _\nundefined\n> console.log(sum)\n30\nundefined\n>\n" }, { "code": null, "e": 14383, "s": 14341, "text": "ctrl + c − terminate the current command." }, { "code": null, "e": 14425, "s": 14383, "text": "ctrl + c − terminate the current command." }, { "code": null, "e": 14467, "s": 14425, "text": "ctrl + c twice − terminate the Node REPL." }, { "code": null, "e": 14509, "s": 14467, "text": "ctrl + c twice − terminate the Node REPL." }, { "code": null, "e": 14545, "s": 14509, "text": "ctrl + d − terminate the Node REPL." }, { "code": null, "e": 14581, "s": 14545, "text": "ctrl + d − terminate the Node REPL." }, { "code": null, "e": 14646, "s": 14581, "text": "Up/Down Keys − see command history and modify previous commands." }, { "code": null, "e": 14711, "s": 14646, "text": "Up/Down Keys − see command history and modify previous commands." }, { "code": null, "e": 14748, "s": 14711, "text": "tab Keys − list of current commands." }, { "code": null, "e": 14785, "s": 14748, "text": "tab Keys − list of current commands." }, { "code": null, "e": 14815, "s": 14785, "text": ".help − list of all commands." }, { "code": null, "e": 14845, "s": 14815, "text": ".help − list of all commands." }, { "code": null, "e": 14886, "s": 14845, "text": ".break − exit from multiline expression." }, { "code": null, "e": 14927, "s": 14886, "text": ".break − exit from multiline expression." }, { "code": null, "e": 14968, "s": 14927, "text": ".clear − exit from multiline expression." }, { "code": null, "e": 15009, "s": 14968, "text": ".clear − exit from multiline expression." }, { "code": null, "e": 15072, "s": 15009, "text": ".save filename − save the current Node REPL session to a file." }, { "code": null, "e": 15135, "s": 15072, "text": ".save filename − save the current Node REPL session to a file." }, { "code": null, "e": 15200, "s": 15135, "text": ".load filename − load file content in current Node REPL session." }, { "code": null, "e": 15265, "s": 15200, "text": ".load filename − load file content in current Node REPL session." }, { "code": null, "e": 15348, "s": 15265, "text": "As mentioned above, you will need to use ctrl-c twice to come out of Node.js REPL." }, { "code": null, "e": 15379, "s": 15348, "text": "$ node\n>\n(^C again to quit)\n>\n" }, { "code": null, "e": 15442, "s": 15379, "text": "Node Package Manager (NPM) provides two main functionalities −" }, { "code": null, "e": 15533, "s": 15442, "text": "Online repositories for node.js packages/modules which are searchable on search.nodejs.org" }, { "code": null, "e": 15624, "s": 15533, "text": "Online repositories for node.js packages/modules which are searchable on search.nodejs.org" }, { "code": null, "e": 15743, "s": 15624, "text": "Command line utility to install Node.js packages, do version management and dependency management of Node.js packages." }, { "code": null, "e": 15862, "s": 15743, "text": "Command line utility to install Node.js packages, do version management and dependency management of Node.js packages." }, { "code": null, "e": 16013, "s": 15862, "text": "NPM comes bundled with Node.js installables after v0.6.3 version. To verify the same, open console and type the following command and see the result −" }, { "code": null, "e": 16036, "s": 16013, "text": "$ npm --version\n2.7.1\n" }, { "code": null, "e": 16178, "s": 16036, "text": "If you are running an old version of NPM then it is quite easy to update it to the latest version. Just use the following command from root −" }, { "code": null, "e": 16298, "s": 16178, "text": "$ sudo npm install npm -g\n/usr/bin/npm -> /usr/lib/node_modules/npm/bin/npm-cli.js\[email protected] /usr/lib/node_modules/npm\n" }, { "code": null, "e": 16355, "s": 16298, "text": "There is a simple syntax to install any Node.js module −" }, { "code": null, "e": 16384, "s": 16355, "text": "$ npm install <Module Name>\n" }, { "code": null, "e": 16488, "s": 16384, "text": "For example, following is the command to install a famous Node.js web framework module called express −" }, { "code": null, "e": 16511, "s": 16488, "text": "$ npm install express\n" }, { "code": null, "e": 16570, "s": 16511, "text": "Now you can use this module in your js file as following −" }, { "code": null, "e": 16605, "s": 16570, "text": "var express = require('express');\n" }, { "code": null, "e": 17004, "s": 16605, "text": "By default, NPM installs any dependency in the local mode. Here local mode refers to the package installation in node_modules directory lying in the folder where Node application is present. Locally deployed packages are accessible via require() method. For example, when we installed express module, it created node_modules directory in the current directory where it installed the express module." }, { "code": null, "e": 17073, "s": 17004, "text": "$ ls -l\ntotal 0\ndrwxr-xr-x 3 root root 20 Mar 17 02:23 node_modules\n" }, { "code": null, "e": 17163, "s": 17073, "text": "Alternatively, you can use npm ls command to list down all the locally installed modules." }, { "code": null, "e": 17462, "s": 17163, "text": "Globally installed packages/dependencies are stored in system directory. Such dependencies can be used in CLI (Command Line Interface) function of any node.js but cannot be imported using require() in Node application directly. Now let's try installing the express module using global installation." }, { "code": null, "e": 17488, "s": 17462, "text": "$ npm install express -g\n" }, { "code": null, "e": 17660, "s": 17488, "text": "This will produce a similar result but the module will be installed globally. Here, the first line shows the module version and the location where it is getting installed." }, { "code": null, "e": 18395, "s": 17660, "text": "[email protected] /usr/lib/node_modules/express\n├── [email protected]\n├── [email protected]\n├── [email protected]\n├── [email protected]\n├── [email protected]\n├── [email protected]\n├── [email protected]\n├── [email protected]\n├── [email protected]\n├── [email protected]\n├── [email protected]\n├── [email protected]\n├── [email protected]\n├── [email protected]\n├── [email protected]\n├── [email protected]\n├── [email protected] ([email protected])\n├── [email protected] ([email protected])\n├── [email protected] ([email protected])\n├── [email protected] ([email protected], [email protected])\n├── [email protected] ([email protected], [email protected], [email protected])\n├── [email protected] ([email protected])\n├── [email protected] ([email protected], [email protected])\n└── [email protected] ([email protected], [email protected])\n" }, { "code": null, "e": 18475, "s": 18395, "text": "You can use the following command to check all the modules installed globally −" }, { "code": null, "e": 18488, "s": 18475, "text": "$ npm ls -g\n" }, { "code": null, "e": 18692, "s": 18488, "text": "package.json is present in the root directory of any Node application/module and is used to define the properties of a package. Let's open package.json of express package present in node_modules/express/" }, { "code": null, "e": 23147, "s": 18692, "text": "{\n \"name\": \"express\",\n \"description\": \"Fast, unopinionated, minimalist web framework\",\n \"version\": \"4.11.2\",\n \"author\": {\n \n \"name\": \"TJ Holowaychuk\",\n \"email\": \"[email protected]\"\n },\n \n \"contributors\": [{\n \"name\": \"Aaron Heckmann\",\n \"email\": \"[email protected]\"\n }, \n \n {\n \"name\": \"Ciaran Jessup\",\n \"email\": \"[email protected]\"\n },\n \n {\n \"name\": \"Douglas Christopher Wilson\",\n \"email\": \"[email protected]\"\n },\n \n {\n \"name\": \"Guillermo Rauch\",\n \"email\": \"[email protected]\"\n },\n \n {\n \"name\": \"Jonathan Ong\",\n \"email\": \"[email protected]\"\n },\n \n {\n \"name\": \"Roman Shtylman\",\n \"email\": \"[email protected]\"\n },\n \n {\n \"name\": \"Young Jae Sim\",\n \"email\": \"[email protected]\"\n } ],\n \n \"license\": \"MIT\", \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/strongloop/express\"\n },\n \n \"homepage\": \"https://expressjs.com/\", \"keywords\": [\n \"express\",\n \"framework\",\n \"sinatra\",\n \"web\",\n \"rest\",\n \"restful\",\n \"router\",\n \"app\",\n \"api\"\n ],\n \n \"dependencies\": {\n \"accepts\": \"~1.2.3\",\n \"content-disposition\": \"0.5.0\",\n \"cookie-signature\": \"1.0.5\",\n \"debug\": \"~2.1.1\",\n \"depd\": \"~1.0.0\",\n \"escape-html\": \"1.0.1\",\n \"etag\": \"~1.5.1\",\n \"finalhandler\": \"0.3.3\",\n \"fresh\": \"0.2.4\",\n \"media-typer\": \"0.3.0\",\n \"methods\": \"~1.1.1\",\n \"on-finished\": \"~2.2.0\",\n \"parseurl\": \"~1.3.0\",\n \"path-to-regexp\": \"0.1.3\",\n \"proxy-addr\": \"~1.0.6\",\n \"qs\": \"2.3.3\",\n \"range-parser\": \"~1.0.2\",\n \"send\": \"0.11.1\",\n \"serve-static\": \"~1.8.1\",\n \"type-is\": \"~1.5.6\",\n \"vary\": \"~1.0.0\",\n \"cookie\": \"0.1.2\",\n \"merge-descriptors\": \"0.0.2\",\n \"utils-merge\": \"1.0.0\"\n },\n \n \"devDependencies\": {\n \"after\": \"0.8.1\",\n \"ejs\": \"2.1.4\",\n \"istanbul\": \"0.3.5\",\n \"marked\": \"0.3.3\",\n \"mocha\": \"~2.1.0\",\n \"should\": \"~4.6.2\",\n \"supertest\": \"~0.15.0\",\n \"hjs\": \"~0.0.6\",\n \"body-parser\": \"~1.11.0\",\n \"connect-redis\": \"~2.2.0\",\n \"cookie-parser\": \"~1.3.3\",\n \"express-session\": \"~1.10.2\",\n \"jade\": \"~1.9.1\",\n \"method-override\": \"~2.3.1\",\n \"morgan\": \"~1.5.1\",\n \"multiparty\": \"~4.1.1\",\n \"vhost\": \"~3.0.0\"\n },\n \n \"engines\": {\n \"node\": \">= 0.10.0\"\n },\n \n \"files\": [\n \"LICENSE\",\n \"History.md\",\n \"Readme.md\",\n \"index.js\",\n \"lib/\"\n ],\n \n \"scripts\": {\n \"test\": \"mocha --require test/support/env \n --reporter spec --bail --check-leaks test/ test/acceptance/\",\n \"test-cov\": \"istanbul cover node_modules/mocha/bin/_mocha \n -- --require test/support/env --reporter dot --check-leaks test/ test/acceptance/\",\n \"test-tap\": \"mocha --require test/support/env \n --reporter tap --check-leaks test/ test/acceptance/\",\n \"test-travis\": \"istanbul cover node_modules/mocha/bin/_mocha \n --report lcovonly -- --require test/support/env \n --reporter spec --check-leaks test/ test/acceptance/\"\n },\n \n \"gitHead\": \"63ab25579bda70b4927a179b580a9c580b6c7ada\",\n \"bugs\": {\n \"url\": \"https://github.com/strongloop/express/issues\"\n },\n \n \"_id\": \"[email protected]\",\n \"_shasum\": \"8df3d5a9ac848585f00a0777601823faecd3b148\",\n \"_from\": \"express@*\",\n \"_npmVersion\": \"1.4.28\",\n \"_npmUser\": {\n \"name\": \"dougwilson\",\n \"email\": \"[email protected]\"\n },\n \n \"maintainers\": [{\n \"name\": \"tjholowaychuk\",\n \"email\": \"[email protected]\"\n },\n \n {\n \"name\": \"jongleberry\",\n \"email\": \"[email protected]\"\n },\n \n {\n \"name\": \"shtylman\",\n \"email\": \"[email protected]\"\n },\n \n {\n \"name\": \"dougwilson\",\n \"email\": \"[email protected]\"\n },\n \n {\n \"name\": \"aredridel\",\n \"email\": \"[email protected]\"\n },\n \n {\n \"name\": \"strongloop\",\n \"email\": \"[email protected]\"\n },\n \n {\n \"name\": \"rfeng\",\n \"email\": \"[email protected]\"\n }],\n \n \"dist\": {\n \"shasum\": \"8df3d5a9ac848585f00a0777601823faecd3b148\",\n \"tarball\": \"https://registry.npmjs.org/express/-/express-4.11.2.tgz\"\n },\n \n \"directories\": {},\n \"_resolved\": \"https://registry.npmjs.org/express/-/express-4.11.2.tgz\",\n \"readme\": \"ERROR: No README data found!\"\n}" }, { "code": null, "e": 23174, "s": 23147, "text": "name − name of the package" }, { "code": null, "e": 23201, "s": 23174, "text": "name − name of the package" }, { "code": null, "e": 23234, "s": 23201, "text": "version − version of the package" }, { "code": null, "e": 23267, "s": 23234, "text": "version − version of the package" }, { "code": null, "e": 23308, "s": 23267, "text": "description − description of the package" }, { "code": null, "e": 23349, "s": 23308, "text": "description − description of the package" }, { "code": null, "e": 23384, "s": 23349, "text": "homepage − homepage of the package" }, { "code": null, "e": 23419, "s": 23384, "text": "homepage − homepage of the package" }, { "code": null, "e": 23450, "s": 23419, "text": "author − author of the package" }, { "code": null, "e": 23481, "s": 23450, "text": "author − author of the package" }, { "code": null, "e": 23536, "s": 23481, "text": "contributors − name of the contributors to the package" }, { "code": null, "e": 23591, "s": 23536, "text": "contributors − name of the contributors to the package" }, { "code": null, "e": 23733, "s": 23591, "text": "dependencies − list of dependencies. NPM automatically installs all the dependencies mentioned here in the node_module folder of the package." }, { "code": null, "e": 23875, "s": 23733, "text": "dependencies − list of dependencies. NPM automatically installs all the dependencies mentioned here in the node_module folder of the package." }, { "code": null, "e": 23927, "s": 23875, "text": "repository − repository type and URL of the package" }, { "code": null, "e": 23979, "s": 23927, "text": "repository − repository type and URL of the package" }, { "code": null, "e": 24013, "s": 23979, "text": "main − entry point of the package" }, { "code": null, "e": 24047, "s": 24013, "text": "main − entry point of the package" }, { "code": null, "e": 24067, "s": 24047, "text": "keywords − keywords" }, { "code": null, "e": 24087, "s": 24067, "text": "keywords − keywords" }, { "code": null, "e": 24144, "s": 24087, "text": "Use the following command to uninstall a Node.js module." }, { "code": null, "e": 24169, "s": 24144, "text": "$ npm uninstall express\n" }, { "code": null, "e": 24306, "s": 24169, "text": "Once NPM uninstalls the package, you can verify it by looking at the content of /node_modules/ directory or type the following command −" }, { "code": null, "e": 24316, "s": 24306, "text": "$ npm ls\n" }, { "code": null, "e": 24422, "s": 24316, "text": "Update package.json and change the version of the dependency to be updated and run the following command." }, { "code": null, "e": 24444, "s": 24422, "text": "$ npm update express\n" }, { "code": null, "e": 24477, "s": 24444, "text": "Search a package name using NPM." }, { "code": null, "e": 24499, "s": 24477, "text": "$ npm search express\n" }, { "code": null, "e": 24655, "s": 24499, "text": "Creating a module requires package.json to be generated. Let's generate package.json using NPM, which will generate the basic skeleton of the package.json." }, { "code": null, "e": 25063, "s": 24655, "text": "$ npm init\nThis utility will walk you through creating a package.json file.\nIt only covers the most common items, and tries to guess sane defaults.\n\nSee 'npm help json' for definitive documentation on these fields\nand exactly what they do.\n\nUse 'npm install <pkg> --save' afterwards to install a package and\nsave it as a dependency in the package.json file.\n\nPress ^C at any time to quit.\nname: (webmaster)\n" }, { "code": null, "e": 25390, "s": 25063, "text": "You will need to provide all the required information about your module. You can take help from the above-mentioned package.json file to understand the meanings of various information demanded. Once package.json is generated, use the following command to register yourself with NPM repository site using a valid email address." }, { "code": null, "e": 25473, "s": 25390, "text": "$ npm adduser\nUsername: mcmohd\nPassword:\nEmail: (this IS public) [email protected]\n" }, { "code": null, "e": 25513, "s": 25473, "text": "It is time now to publish your module −" }, { "code": null, "e": 25528, "s": 25513, "text": "$ npm publish\n" }, { "code": null, "e": 25687, "s": 25528, "text": "If everything is fine with your module, then it will be published in the repository and will be accessible to install using NPM like any other Node.js module." }, { "code": null, "e": 25918, "s": 25687, "text": "Callback is an asynchronous equivalent for a function. A callback function is called at the completion of a given task. Node makes heavy use of callbacks. All the APIs of Node are written in such a way that they support callbacks." }, { "code": null, "e": 26407, "s": 25918, "text": "For example, a function to read a file may start reading file and return the control to the execution environment immediately so that the next instruction can be executed. Once file I/O is complete, it will call the callback function while passing the callback function, the content of the file as a parameter. So there is no blocking or wait for File I/O. This makes Node.js highly scalable, as it can process a high number of requests without waiting for any function to return results." }, { "code": null, "e": 26471, "s": 26407, "text": "Create a text file named input.txt with the following content −" }, { "code": null, "e": 26567, "s": 26471, "text": "Tutorials Point is giving self learning content\nto teach the world in simple and easy way!!!!!\n" }, { "code": null, "e": 26624, "s": 26567, "text": "Create a js file named main.js with the following code −" }, { "code": null, "e": 26750, "s": 26624, "text": "var fs = require(\"fs\");\nvar data = fs.readFileSync('input.txt');\n\nconsole.log(data.toString());\nconsole.log(\"Program Ended\");" }, { "code": null, "e": 26790, "s": 26750, "text": "Now run the main.js to see the result −" }, { "code": null, "e": 26806, "s": 26790, "text": "$ node main.js\n" }, { "code": null, "e": 26825, "s": 26806, "text": "Verify the Output." }, { "code": null, "e": 26935, "s": 26825, "text": "Tutorials Point is giving self learning content\nto teach the world in simple and easy way!!!!!\nProgram Ended\n" }, { "code": null, "e": 26998, "s": 26935, "text": "Create a text file named input.txt with the following content." }, { "code": null, "e": 27093, "s": 26998, "text": "Tutorials Point is giving self learning content\nto teach the world in simple and easy way!!!!!" }, { "code": null, "e": 27137, "s": 27093, "text": "Update main.js to have the following code −" }, { "code": null, "e": 27317, "s": 27137, "text": "var fs = require(\"fs\");\n\nfs.readFile('input.txt', function (err, data) {\n if (err) return console.error(err);\n console.log(data.toString());\n});\n\nconsole.log(\"Program Ended\");" }, { "code": null, "e": 27357, "s": 27317, "text": "Now run the main.js to see the result −" }, { "code": null, "e": 27373, "s": 27357, "text": "$ node main.js\n" }, { "code": null, "e": 27392, "s": 27373, "text": "Verify the Output." }, { "code": null, "e": 27502, "s": 27392, "text": "Program Ended\nTutorials Point is giving self learning content\nto teach the world in simple and easy way!!!!!\n" }, { "code": null, "e": 27577, "s": 27502, "text": "These two examples explain the concept of blocking and non-blocking calls." }, { "code": null, "e": 27695, "s": 27577, "text": "The first example shows that the program blocks until it reads the file and then only it proceeds to end the program." }, { "code": null, "e": 27813, "s": 27695, "text": "The first example shows that the program blocks until it reads the file and then only it proceeds to end the program." }, { "code": null, "e": 28003, "s": 27813, "text": "The second example shows that the program does not wait for file reading and proceeds to print \"Program Ended\" and at the same time, the program without blocking continues reading the file." }, { "code": null, "e": 28193, "s": 28003, "text": "The second example shows that the program does not wait for file reading and proceeds to print \"Program Ended\" and at the same time, the program without blocking continues reading the file." }, { "code": null, "e": 28506, "s": 28193, "text": "Thus, a blocking program executes very much in sequence. From the programming point of view, it is easier to implement the logic but non-blocking programs do not execute in sequence. In case a program needs to use any data to be processed, it should be kept within the same block to make it sequential execution." }, { "code": null, "e": 28921, "s": 28506, "text": "Node.js is a single-threaded application, but it can support concurrency via the concept of event and callbacks. Every API of Node.js is asynchronous and being single-threaded, they use async function calls to maintain concurrency. Node uses observer pattern. Node thread keeps an event loop and whenever a task gets completed, it fires the corresponding event which signals the event-listener function to execute." }, { "code": null, "e": 29186, "s": 28921, "text": "Node.js uses events heavily and it is also one of the reasons why Node.js is pretty fast compared to other similar technologies. As soon as Node starts its server, it simply initiates its variables, declares functions and then simply waits for the event to occur. " }, { "code": null, "e": 29350, "s": 29186, "text": "In an event-driven application, there is generally a main loop that listens for events, and then triggers a callback function when one of those events is detected." }, { "code": null, "e": 29849, "s": 29350, "text": "Although events look quite similar to callbacks, the difference lies in the fact that callback functions are called when an asynchronous function returns its result, whereas event handling works on the observer pattern. The functions that listen to events act as Observers. Whenever an event gets fired, its listener function starts executing. Node.js has multiple in-built events available through events module and EventEmitter class which are used to bind events and event-listeners as follows −" }, { "code": null, "e": 29986, "s": 29849, "text": "// Import events module\nvar events = require('events');\n\n// Create an eventEmitter object\nvar eventEmitter = new events.EventEmitter();\n" }, { "code": null, "e": 30051, "s": 29986, "text": "Following is the syntax to bind an event handler with an event −" }, { "code": null, "e": 30140, "s": 30051, "text": "// Bind event and event handler as follows\neventEmitter.on('eventName', eventHandler);\n" }, { "code": null, "e": 30191, "s": 30140, "text": "We can fire an event programmatically as follows −" }, { "code": null, "e": 30242, "s": 30191, "text": "// Fire an event \neventEmitter.emit('eventName');\n" }, { "code": null, "e": 30299, "s": 30242, "text": "Create a js file named main.js with the following code −" }, { "code": null, "e": 30987, "s": 30299, "text": "// Import events module\nvar events = require('events');\n\n// Create an eventEmitter object\nvar eventEmitter = new events.EventEmitter();\n\n// Create an event handler as follows\nvar connectHandler = function connected() {\n console.log('connection succesful.');\n \n // Fire the data_received event \n eventEmitter.emit('data_received');\n}\n\n// Bind the connection event with the handler\neventEmitter.on('connection', connectHandler);\n \n// Bind the data_received event with the anonymous function\neventEmitter.on('data_received', function() {\n console.log('data received succesfully.');\n});\n\n// Fire the connection event \neventEmitter.emit('connection');\n\nconsole.log(\"Program Ended.\");" }, { "code": null, "e": 31049, "s": 30987, "text": "Now let's try to run the above program and check its output −" }, { "code": null, "e": 31065, "s": 31049, "text": "$ node main.js\n" }, { "code": null, "e": 31106, "s": 31065, "text": "IT should produce the following result −" }, { "code": null, "e": 31173, "s": 31106, "text": "connection successful.\ndata received successfully.\nProgram Ended.\n" }, { "code": null, "e": 31424, "s": 31173, "text": "In Node Application, any async function accepts a callback as the last parameter and a callback function accepts an error as the first parameter. Let's revisit the previous example again. Create a text file named input.txt with the following content." }, { "code": null, "e": 31519, "s": 31424, "text": "Tutorials Point is giving self learning content\nto teach the world in simple and easy way!!!!!" }, { "code": null, "e": 31578, "s": 31519, "text": "Create a js file named main.js having the following code −" }, { "code": null, "e": 31781, "s": 31578, "text": "var fs = require(\"fs\");\n\nfs.readFile('input.txt', function (err, data) {\n if (err) {\n console.log(err.stack);\n return;\n }\n console.log(data.toString());\n});\nconsole.log(\"Program Ended\");" }, { "code": null, "e": 32132, "s": 31781, "text": "Here fs.readFile() is a async function whose purpose is to read a file. If an error occurs during the read operation, then the err object will contain the corresponding error, else data will contain the contents of the file. readFile passes err and data to the callback function after the read operation is complete, which finally prints the content." }, { "code": null, "e": 32242, "s": 32132, "text": "Program Ended\nTutorials Point is giving self learning content\nto teach the world in simple and easy way!!!!!\n" }, { "code": null, "e": 32481, "s": 32242, "text": "Many objects in a Node emit events, for example, a net.Server emits an event each time a peer connects to it, an fs.readStream emits an event when the file is opened. All objects which emit events are the instances of events.EventEmitter." }, { "code": null, "e": 32610, "s": 32481, "text": "As we have seen in the previous section, EventEmitter class lies in the events module. It is accessible via the following code −" }, { "code": null, "e": 32747, "s": 32610, "text": "// Import events module\nvar events = require('events');\n\n// Create an eventEmitter object\nvar eventEmitter = new events.EventEmitter();\n" }, { "code": null, "e": 32945, "s": 32747, "text": "When an EventEmitter instance faces any error, it emits an 'error' event. When a new listener is added, 'newListener' event is fired and when a listener is removed, 'removeListener' event is fired." }, { "code": null, "e": 33094, "s": 32945, "text": "EventEmitter provides multiple properties like on and emit. on property is used to bind a function with the event and emit is used to fire an event." }, { "code": null, "e": 33123, "s": 33094, "text": "addListener(event, listener)" }, { "code": null, "e": 33428, "s": 33123, "text": "Adds a listener at the end of the listeners array for the specified event. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of event and listener will result in the listener being added multiple times. Returns emitter, so calls can be chained." }, { "code": null, "e": 33448, "s": 33428, "text": "on(event, listener)" }, { "code": null, "e": 33753, "s": 33448, "text": "Adds a listener at the end of the listeners array for the specified event. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of event and listener will result in the listener being added multiple times. Returns emitter, so calls can be chained." }, { "code": null, "e": 33775, "s": 33753, "text": "once(event, listener)" }, { "code": null, "e": 33947, "s": 33775, "text": "Adds a one time listener to the event. This listener is invoked only the next time the event is fired, after which it is removed. Returns emitter, so calls can be chained." }, { "code": null, "e": 33979, "s": 33947, "text": "removeListener(event, listener)" }, { "code": null, "e": 34435, "s": 33979, "text": "Removes a listener from the listener array for the specified event. Caution − It changes the array indices in the listener array behind the listener. removeListener will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specified event, then removeListener must be called multiple times to remove each instance. Returns emitter, so calls can be chained." }, { "code": null, "e": 34463, "s": 34435, "text": "removeAllListeners([event])" }, { "code": null, "e": 34731, "s": 34463, "text": "Removes all listeners, or those of the specified event. It's not a good idea to remove listeners that were added elsewhere in the code, especially when it's on an emitter that you didn't create (e.g. sockets or file streams). Returns emitter, so calls can be chained." }, { "code": null, "e": 34750, "s": 34731, "text": "setMaxListeners(n)" }, { "code": null, "e": 35038, "s": 34750, "text": "By default, EventEmitters will print a warning if more than 10 listeners are added for a particular event. This is a useful default which helps finding memory leaks. Obviously not all Emitters should be limited to 10. This function allows that to be increased. Set to zero for unlimited." }, { "code": null, "e": 35055, "s": 35038, "text": "listeners(event)" }, { "code": null, "e": 35110, "s": 35055, "text": "Returns an array of listeners for the specified event." }, { "code": null, "e": 35145, "s": 35110, "text": "emit(event, [arg1], [arg2], [...])" }, { "code": null, "e": 35271, "s": 35145, "text": "Execute each of the listeners in order with the supplied arguments. Returns true if the event had listeners, false otherwise." }, { "code": null, "e": 35301, "s": 35271, "text": "listenerCount(emitter, event)" }, { "code": null, "e": 35352, "s": 35301, "text": "Returns the number of listeners for a given event." }, { "code": null, "e": 35364, "s": 35352, "text": "newListener" }, { "code": null, "e": 35395, "s": 35364, "text": "event − String: the event name" }, { "code": null, "e": 35426, "s": 35395, "text": "event − String: the event name" }, { "code": null, "e": 35474, "s": 35426, "text": "listener − Function: the event handler function" }, { "code": null, "e": 35522, "s": 35474, "text": "listener − Function: the event handler function" }, { "code": null, "e": 35686, "s": 35522, "text": "This event is emitted any time a listener is added. When this event is triggered, the listener may not yet have been added to the array of listeners for the event." }, { "code": null, "e": 35701, "s": 35686, "text": "removeListener" }, { "code": null, "e": 35731, "s": 35701, "text": "event − String The event name" }, { "code": null, "e": 35761, "s": 35731, "text": "event − String The event name" }, { "code": null, "e": 35808, "s": 35761, "text": "listener − Function The event handler function" }, { "code": null, "e": 35855, "s": 35808, "text": "listener − Function The event handler function" }, { "code": null, "e": 36030, "s": 35855, "text": "This event is emitted any time someone removes a listener. When this event is triggered, the listener may not yet have been removed from the array of listeners for the event." }, { "code": null, "e": 36095, "s": 36030, "text": "Create a js file named main.js with the following Node.js code −" }, { "code": null, "e": 37207, "s": 36095, "text": "var events = require('events');\nvar eventEmitter = new events.EventEmitter();\n\n// listener #1\nvar listner1 = function listner1() {\n console.log('listner1 executed.');\n}\n\n// listener #2\nvar listner2 = function listner2() {\n console.log('listner2 executed.');\n}\n\n// Bind the connection event with the listner1 function\neventEmitter.addListener('connection', listner1);\n\n// Bind the connection event with the listner2 function\neventEmitter.on('connection', listner2);\n\nvar eventListeners = require('events').EventEmitter.listenerCount\n (eventEmitter,'connection');\nconsole.log(eventListeners + \" Listner(s) listening to connection event\");\n\n// Fire the connection event \neventEmitter.emit('connection');\n\n// Remove the binding of listner1 function\neventEmitter.removeListener('connection', listner1);\nconsole.log(\"Listner1 will not listen now.\");\n\n// Fire the connection event \neventEmitter.emit('connection');\n\neventListeners = require('events').EventEmitter.listenerCount(eventEmitter,'connection');\nconsole.log(eventListeners + \" Listner(s) listening to connection event\");\n\nconsole.log(\"Program Ended.\");" }, { "code": null, "e": 37247, "s": 37207, "text": "Now run the main.js to see the result −" }, { "code": null, "e": 37263, "s": 37247, "text": "$ node main.js\n" }, { "code": null, "e": 37282, "s": 37263, "text": "Verify the Output." }, { "code": null, "e": 37471, "s": 37282, "text": "2 Listner(s) listening to connection event\nlistner1 executed.\nlistner2 executed.\nListner1 will not listen now.\nlistner2 executed.\n1 Listner(s) listening to connection event\nProgram Ended.\n" }, { "code": null, "e": 37799, "s": 37471, "text": "Pure JavaScript is Unicode friendly, but it is not so for binary data. While dealing with TCP streams or the file system, it's necessary to handle octet streams. Node provides Buffer class which provides instances to store raw data similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap." }, { "code": null, "e": 37906, "s": 37799, "text": "Buffer class is a global class that can be accessed in an application without importing the buffer module." }, { "code": null, "e": 37959, "s": 37906, "text": "Node Buffer can be constructed in a variety of ways." }, { "code": null, "e": 38030, "s": 37959, "text": "Following is the syntax to create an uninitiated Buffer of 10 octets −" }, { "code": null, "e": 38057, "s": 38030, "text": "var buf = new Buffer(10);\n" }, { "code": null, "e": 38121, "s": 38057, "text": "Following is the syntax to create a Buffer from a given array −" }, { "code": null, "e": 38166, "s": 38121, "text": "var buf = new Buffer([10, 20, 30, 40, 50]);\n" }, { "code": null, "e": 38260, "s": 38166, "text": "Following is the syntax to create a Buffer from a given string and optionally encoding type −" }, { "code": null, "e": 38316, "s": 38260, "text": "var buf = new Buffer(\"Simply Easy Learning\", \"utf-8\");\n" }, { "code": null, "e": 38453, "s": 38316, "text": "Though \"utf8\" is the default encoding, you can use any of the following encodings \"ascii\", \"utf8\", \"utf16le\", \"ucs2\", \"base64\" or \"hex\"." }, { "code": null, "e": 38521, "s": 38453, "text": "Following is the syntax of the method to write into a Node Buffer −" }, { "code": null, "e": 38572, "s": 38521, "text": "buf.write(string[, offset][, length][, encoding])\n" }, { "code": null, "e": 38621, "s": 38572, "text": "Here is the description of the parameters used −" }, { "code": null, "e": 38679, "s": 38621, "text": "string − This is the string data to be written to buffer." }, { "code": null, "e": 38737, "s": 38679, "text": "string − This is the string data to be written to buffer." }, { "code": null, "e": 38819, "s": 38737, "text": "offset − This is the index of the buffer to start writing at. Default value is 0." }, { "code": null, "e": 38901, "s": 38819, "text": "offset − This is the index of the buffer to start writing at. Default value is 0." }, { "code": null, "e": 38975, "s": 38901, "text": "length − This is the number of bytes to write. Defaults to buffer.length." }, { "code": null, "e": 39049, "s": 38975, "text": "length − This is the number of bytes to write. Defaults to buffer.length." }, { "code": null, "e": 39109, "s": 39049, "text": "encoding − Encoding to use. 'utf8' is the default encoding." }, { "code": null, "e": 39169, "s": 39109, "text": "encoding − Encoding to use. 'utf8' is the default encoding." }, { "code": null, "e": 39324, "s": 39169, "text": "This method returns the number of octets written. If there is not enough space in the buffer to fit the entire string, it will write a part of the string." }, { "code": null, "e": 39429, "s": 39324, "text": "buf = new Buffer(256);\nlen = buf.write(\"Simply Easy Learning\");\n\nconsole.log(\"Octets written : \"+ len);" }, { "code": null, "e": 39500, "s": 39429, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 39521, "s": 39500, "text": "Octets written : 20\n" }, { "code": null, "e": 39593, "s": 39521, "text": "Following is the syntax of the method to read data from a Node Buffer −" }, { "code": null, "e": 39635, "s": 39593, "text": "buf.toString([encoding][, start][, end])\n" }, { "code": null, "e": 39684, "s": 39635, "text": "Here is the description of the parameters used −" }, { "code": null, "e": 39744, "s": 39684, "text": "encoding − Encoding to use. 'utf8' is the default encoding." }, { "code": null, "e": 39804, "s": 39744, "text": "encoding − Encoding to use. 'utf8' is the default encoding." }, { "code": null, "e": 39861, "s": 39804, "text": "start − Beginning index to start reading, defaults to 0." }, { "code": null, "e": 39918, "s": 39861, "text": "start − Beginning index to start reading, defaults to 0." }, { "code": null, "e": 39979, "s": 39918, "text": "end − End index to end reading, defaults is complete buffer." }, { "code": null, "e": 40040, "s": 39979, "text": "end − End index to end reading, defaults is complete buffer." }, { "code": null, "e": 40150, "s": 40040, "text": "This method decodes and returns a string from buffer data encoded using the specified character set encoding." }, { "code": null, "e": 40520, "s": 40150, "text": "buf = new Buffer(26);\nfor (var i = 0 ; i < 26 ; i++) {\n buf[i] = i + 97;\n}\n\nconsole.log( buf.toString('ascii')); // outputs: abcdefghijklmnopqrstuvwxyz\nconsole.log( buf.toString('ascii',0,5)); // outputs: abcde\nconsole.log( buf.toString('utf8',0,5)); // outputs: abcde\nconsole.log( buf.toString(undefined,0,5)); // encoding defaults to 'utf8', outputs abcde" }, { "code": null, "e": 40591, "s": 40520, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 40637, "s": 40591, "text": "abcdefghijklmnopqrstuvwxyz\nabcde\nabcde\nabcde\n" }, { "code": null, "e": 40719, "s": 40637, "text": "Following is the syntax of the method to convert a Node Buffer into JSON object −" }, { "code": null, "e": 40733, "s": 40719, "text": "buf.toJSON()\n" }, { "code": null, "e": 40799, "s": 40733, "text": "This method returns a JSON-representation of the Buffer instance." }, { "code": null, "e": 40893, "s": 40799, "text": "var buf = new Buffer('Simply Easy Learning');\nvar json = buf.toJSON(buf);\n\nconsole.log(json);" }, { "code": null, "e": 40964, "s": 40893, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 41219, "s": 40964, "text": "{ type: 'Buffer',\n data: \n [ \n 83,\n 105,\n 109,\n 112,\n 108,\n 121,\n 32,\n 69,\n 97,\n 115,\n 121,\n 32,\n 76,\n 101,\n 97,\n 114,\n 110,\n 105,\n 110,\n 103 \n ]\n}\n" }, { "code": null, "e": 41311, "s": 41219, "text": "Following is the syntax of the method to concatenate Node buffers to a single Node Buffer −" }, { "code": null, "e": 41347, "s": 41311, "text": "Buffer.concat(list[, totalLength])\n" }, { "code": null, "e": 41396, "s": 41347, "text": "Here is the description of the parameters used −" }, { "code": null, "e": 41452, "s": 41396, "text": "list − Array List of Buffer objects to be concatenated." }, { "code": null, "e": 41508, "s": 41452, "text": "list − Array List of Buffer objects to be concatenated." }, { "code": null, "e": 41581, "s": 41508, "text": "totalLength − This is the total length of the buffers when concatenated." }, { "code": null, "e": 41654, "s": 41581, "text": "totalLength − This is the total length of the buffers when concatenated." }, { "code": null, "e": 41693, "s": 41654, "text": "This method returns a Buffer instance." }, { "code": null, "e": 41892, "s": 41693, "text": "var buffer1 = new Buffer('TutorialsPoint ');\nvar buffer2 = new Buffer('Simply Easy Learning');\nvar buffer3 = Buffer.concat([buffer1,buffer2]);\n\nconsole.log(\"buffer3 content: \" + buffer3.toString());" }, { "code": null, "e": 41963, "s": 41892, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 42017, "s": 41963, "text": "buffer3 content: TutorialsPoint Simply Easy Learning\n" }, { "code": null, "e": 42085, "s": 42017, "text": "Following is the syntax of the method to compare two Node buffers −" }, { "code": null, "e": 42112, "s": 42085, "text": "buf.compare(otherBuffer);\n" }, { "code": null, "e": 42161, "s": 42112, "text": "Here is the description of the parameters used −" }, { "code": null, "e": 42232, "s": 42161, "text": "otherBuffer − This is the other buffer which will be compared with buf" }, { "code": null, "e": 42303, "s": 42232, "text": "otherBuffer − This is the other buffer which will be compared with buf" }, { "code": null, "e": 42413, "s": 42303, "text": "Returns a number indicating whether it comes before or after or is the same as the otherBuffer in sort order." }, { "code": null, "e": 42730, "s": 42413, "text": "var buffer1 = new Buffer('ABC');\nvar buffer2 = new Buffer('ABCD');\nvar result = buffer1.compare(buffer2);\n\nif(result < 0) {\n console.log(buffer1 +\" comes before \" + buffer2);\n} else if(result === 0) {\n console.log(buffer1 +\" is same as \" + buffer2);\n} else {\n console.log(buffer1 +\" comes after \" + buffer2);\n}" }, { "code": null, "e": 42801, "s": 42730, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 42824, "s": 42801, "text": "ABC comes before ABCD\n" }, { "code": null, "e": 42886, "s": 42824, "text": "Following is the syntax of the method to copy a node buffer −" }, { "code": null, "e": 42953, "s": 42886, "text": "buf.copy(targetBuffer[, targetStart][, sourceStart][, sourceEnd])\n" }, { "code": null, "e": 43002, "s": 42953, "text": "Here is the description of the parameters used −" }, { "code": null, "e": 43060, "s": 43002, "text": "targetBuffer − Buffer object where buffer will be copied." }, { "code": null, "e": 43118, "s": 43060, "text": "targetBuffer − Buffer object where buffer will be copied." }, { "code": null, "e": 43161, "s": 43118, "text": "targetStart − Number, Optional, Default: 0" }, { "code": null, "e": 43204, "s": 43161, "text": "targetStart − Number, Optional, Default: 0" }, { "code": null, "e": 43247, "s": 43204, "text": "sourceStart − Number, Optional, Default: 0" }, { "code": null, "e": 43290, "s": 43247, "text": "sourceStart − Number, Optional, Default: 0" }, { "code": null, "e": 43343, "s": 43290, "text": "sourceEnd − Number, Optional, Default: buffer.length" }, { "code": null, "e": 43396, "s": 43343, "text": "sourceEnd − Number, Optional, Default: buffer.length" }, { "code": null, "e": 43660, "s": 43396, "text": "No return value. Copies data from a region of this buffer to a region in the target buffer even if the target memory region overlaps with the source. If undefined, the targetStart and sourceStart parameters default to 0, while sourceEnd defaults to buffer.length." }, { "code": null, "e": 43817, "s": 43660, "text": "var buffer1 = new Buffer('ABC');\n\n//copy a buffer\nvar buffer2 = new Buffer(3);\nbuffer1.copy(buffer2);\nconsole.log(\"buffer2 content: \" + buffer2.toString());" }, { "code": null, "e": 43888, "s": 43817, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 43910, "s": 43888, "text": "buffer2 content: ABC\n" }, { "code": null, "e": 43987, "s": 43910, "text": "Following is the syntax of the method to get a sub-buffer of a node buffer −" }, { "code": null, "e": 44014, "s": 43987, "text": "buf.slice([start][, end])\n" }, { "code": null, "e": 44063, "s": 44014, "text": "Here is the description of the parameters used −" }, { "code": null, "e": 44100, "s": 44063, "text": "start − Number, Optional, Default: 0" }, { "code": null, "e": 44137, "s": 44100, "text": "start − Number, Optional, Default: 0" }, { "code": null, "e": 44184, "s": 44137, "text": "end − Number, Optional, Default: buffer.length" }, { "code": null, "e": 44231, "s": 44184, "text": "end − Number, Optional, Default: buffer.length" }, { "code": null, "e": 44449, "s": 44231, "text": "Returns a new buffer which references the same memory as the old one, but offset and cropped by the start (defaults to 0) and end (defaults to buffer.length) indexes. Negative indexes start from the end of the buffer." }, { "code": null, "e": 44602, "s": 44449, "text": "var buffer1 = new Buffer('TutorialsPoint');\n\n//slicing a buffer\nvar buffer2 = buffer1.slice(0,9);\nconsole.log(\"buffer2 content: \" + buffer2.toString());" }, { "code": null, "e": 44673, "s": 44602, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 44701, "s": 44673, "text": "buffer2 content: Tutorials\n" }, { "code": null, "e": 44781, "s": 44701, "text": "Following is the syntax of the method to get a size of a node buffer in bytes −" }, { "code": null, "e": 44794, "s": 44781, "text": "buf.length;\n" }, { "code": null, "e": 44833, "s": 44794, "text": "Returns the size of a buffer in bytes." }, { "code": null, "e": 44948, "s": 44833, "text": "var buffer = new Buffer('TutorialsPoint');\n\n//length of the buffer\nconsole.log(\"buffer length: \" + buffer.length);" }, { "code": null, "e": 45015, "s": 44948, "text": "When the above program is executed, it produces following result −" }, { "code": null, "e": 45034, "s": 45015, "text": "buffer length: 14\n" }, { "code": null, "e": 45051, "s": 45034, "text": "new Buffer(size)" }, { "code": null, "e": 45187, "s": 45051, "text": "Allocates a new buffer of size octets. Note that the size must be no more than kMaxLength. Otherwise, a RangeError will be thrown here." }, { "code": null, "e": 45206, "s": 45187, "text": "new Buffer(buffer)" }, { "code": null, "e": 45264, "s": 45206, "text": "Copies the passed buffer data onto a new Buffer instance." }, { "code": null, "e": 45292, "s": 45264, "text": "new Buffer(str[, encoding])" }, { "code": null, "e": 45370, "s": 45292, "text": "Allocates a new buffer containing the given str. encoding defaults to 'utf8'." }, { "code": null, "e": 45381, "s": 45370, "text": "buf.length" }, { "code": null, "e": 45617, "s": 45381, "text": "Returns the size of the buffer in bytes. Note that this is not necessarily the size of the contents. length refers to the amount of memory allocated for the buffer object. It does not change when the contents of the buffer are changed." }, { "code": null, "e": 45667, "s": 45617, "text": "buf.write(string[, offset][, length][, encoding])" }, { "code": null, "e": 45862, "s": 45667, "text": "Writes a string to the buffer at offset using the given encoding. offset defaults to 0, encoding defaults to 'utf8'. length is the number of bytes to write. Returns the number of octets written." }, { "code": null, "e": 45917, "s": 45862, "text": "buf.writeUIntLE(value, offset, byteLength[, noAssert])" }, { "code": null, "e": 46102, "s": 45917, "text": "Writes a value to the buffer at the specified offset and byteLength. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of value and offset. Defaults to false." }, { "code": null, "e": 46157, "s": 46102, "text": "buf.writeUIntBE(value, offset, byteLength[, noAssert])" }, { "code": null, "e": 46342, "s": 46157, "text": "Writes a value to the buffer at the specified offset and byteLength. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of value and offset. Defaults to false." }, { "code": null, "e": 46396, "s": 46342, "text": "buf.writeIntLE(value, offset, byteLength[, noAssert])" }, { "code": null, "e": 46581, "s": 46396, "text": "Writes a value to the buffer at the specified offset and byteLength. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of value and offset. Defaults to false." }, { "code": null, "e": 46635, "s": 46581, "text": "buf.writeIntBE(value, offset, byteLength[, noAssert])" }, { "code": null, "e": 46820, "s": 46635, "text": "Writes a value to the buffer at the specified offset and byteLength. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of value and offset. Defaults to false." }, { "code": null, "e": 46867, "s": 46820, "text": "buf.readUIntLE(offset, byteLength[, noAssert])" }, { "code": null, "e": 47086, "s": 46867, "text": "A generalized version of all numeric read methods. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of offset. It means that the offset may be beyond the end of the buffer. Defaults to false." }, { "code": null, "e": 47133, "s": 47086, "text": "buf.readUIntBE(offset, byteLength[, noAssert])" }, { "code": null, "e": 47352, "s": 47133, "text": "A generalized version of all numeric read methods. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of offset. It means that the offset may be beyond the end of the buffer. Defaults to false." }, { "code": null, "e": 47398, "s": 47352, "text": "buf.readIntLE(offset, byteLength[, noAssert])" }, { "code": null, "e": 47617, "s": 47398, "text": "A generalized version of all numeric read methods. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of offset. It means that the offset may be beyond the end of the buffer. Defaults to false." }, { "code": null, "e": 47663, "s": 47617, "text": "buf.readIntBE(offset, byteLength[, noAssert])" }, { "code": null, "e": 47882, "s": 47663, "text": "A generalized version of all numeric read methods. Supports up to 48 bits of accuracy. Set noAssert to true to skip validation of offset. It means that the offset may be beyond the end of the buffer. Defaults to false." }, { "code": null, "e": 47923, "s": 47882, "text": "buf.toString([encoding][, start][, end])" }, { "code": null, "e": 48021, "s": 47923, "text": "Decodes and returns a string from buffer data encoded using the specified character set encoding." }, { "code": null, "e": 48034, "s": 48021, "text": "buf.toJSON()" }, { "code": null, "e": 48171, "s": 48034, "text": "Returns a JSON-representation of the Buffer instance. JSON.stringify implicitly calls this function when stringifying a Buffer instance." }, { "code": null, "e": 48182, "s": 48171, "text": "buf[index]" }, { "code": null, "e": 48314, "s": 48182, "text": "Get and set the octet at index. The values refer to individual bytes, so the legal range is between 0x00 and 0xFF hex or 0 and 255." }, { "code": null, "e": 48338, "s": 48314, "text": "buf.equals(otherBuffer)" }, { "code": null, "e": 48408, "s": 48338, "text": "Returns a boolean if this buffer and otherBuffer have the same bytes." }, { "code": null, "e": 48433, "s": 48408, "text": "buf.compare(otherBuffer)" }, { "code": null, "e": 48552, "s": 48433, "text": "Returns a number indicating whether this buffer comes before or after or is the same as the otherBuffer in sort order." }, { "code": null, "e": 48618, "s": 48552, "text": "buf.copy(targetBuffer[, targetStart][, sourceStart][, sourceEnd])" }, { "code": null, "e": 48865, "s": 48618, "text": "Copies data from a region of this buffer to a region in the target buffer even if the target memory region overlaps with the source. If undefined, the targetStart and sourceStart parameters default to 0, while sourceEnd defaults to buffer.length." }, { "code": null, "e": 48891, "s": 48865, "text": "buf.slice([start][, end])" }, { "code": null, "e": 49105, "s": 48891, "text": "Returns a new buffer which references the same memory as the old, but offset and cropped by the start (defaults to 0) and end (defaults to buffer.length) indexes. Negative indexes start from the end of the buffer." }, { "code": null, "e": 49139, "s": 49105, "text": "buf.readUInt8(offset[, noAssert])" }, { "code": null, "e": 49344, "s": 49139, "text": "Reads an unsigned 8 bit integer from the buffer at the specified offset. Set noAssert to true to skip validation of offset. It means that the offset may be beyond the end of the buffer. Defaults to false." }, { "code": null, "e": 49381, "s": 49344, "text": "buf.readUInt16LE(offset[, noAssert])" }, { "code": null, "e": 49615, "s": 49381, "text": "Reads an unsigned 16-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false." }, { "code": null, "e": 49652, "s": 49615, "text": "buf.readUInt16BE(offset[, noAssert])" }, { "code": null, "e": 49886, "s": 49652, "text": "Reads an unsigned 16-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false." }, { "code": null, "e": 49923, "s": 49886, "text": "buf.readUInt32LE(offset[, noAssert])" }, { "code": null, "e": 50157, "s": 49923, "text": "Reads an unsigned 32-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false." }, { "code": null, "e": 50194, "s": 50157, "text": "buf.readUInt32BE(offset[, noAssert])" }, { "code": null, "e": 50428, "s": 50194, "text": "Reads an unsigned 32-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false." }, { "code": null, "e": 50461, "s": 50428, "text": "buf.readInt8(offset[, noAssert])" }, { "code": null, "e": 50658, "s": 50461, "text": "Reads a signed 8-bit integer from the buffer at the specified offset. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false." }, { "code": null, "e": 50694, "s": 50658, "text": "buf.readInt16LE(offset[, noAssert])" }, { "code": null, "e": 50925, "s": 50694, "text": "Reads a signed 16-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false." }, { "code": null, "e": 50961, "s": 50925, "text": "buf.readInt16BE(offset[, noAssert])" }, { "code": null, "e": 51192, "s": 50961, "text": "Reads a signed 16-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false." }, { "code": null, "e": 51228, "s": 51192, "text": "buf.readInt32LE(offset[, noAssert])" }, { "code": null, "e": 51459, "s": 51228, "text": "Reads a signed 32-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false." }, { "code": null, "e": 51495, "s": 51459, "text": "buf.readInt32BE(offset[, noAssert])" }, { "code": null, "e": 51726, "s": 51495, "text": "Reads a signed 32-bit integer from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false." }, { "code": null, "e": 51762, "s": 51726, "text": "buf.readFloatLE(offset[, noAssert])" }, { "code": null, "e": 51984, "s": 51762, "text": "Reads a 32-bit float from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false." }, { "code": null, "e": 52020, "s": 51984, "text": "buf.readFloatBE(offset[, noAssert])" }, { "code": null, "e": 52242, "s": 52020, "text": "Reads a 32-bit float from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false." }, { "code": null, "e": 52279, "s": 52242, "text": "buf.readDoubleLE(offset[, noAssert])" }, { "code": null, "e": 52502, "s": 52279, "text": "Reads a 64-bit double from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false." }, { "code": null, "e": 52539, "s": 52502, "text": "buf.readDoubleBE(offset[, noAssert])" }, { "code": null, "e": 52762, "s": 52539, "text": "Reads a 64-bit double from the buffer at the specified offset with the specified endian format. Set noAssert to true to skip validation of offset. It means the offset may be beyond the end of the buffer. Defaults to false." }, { "code": null, "e": 52804, "s": 52762, "text": "buf.writeUInt8(value, offset[, noAssert])" }, { "code": null, "e": 53218, "s": 52804, "text": "Writes a value to the buffer at the specified offset. Note that the value must be a valid unsigned 8-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false." }, { "code": null, "e": 53263, "s": 53218, "text": "buf.writeUInt16LE(value, offset[, noAssert])" }, { "code": null, "e": 53711, "s": 53263, "text": "Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid unsigned 16-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of correctness. Defaults to false." }, { "code": null, "e": 53756, "s": 53711, "text": "buf.writeUInt16BE(value, offset[, noAssert])" }, { "code": null, "e": 54208, "s": 53756, "text": "Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid unsigned 16-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false." }, { "code": null, "e": 54253, "s": 54208, "text": "buf.writeUInt32LE(value, offset[, noAssert])" }, { "code": null, "e": 54705, "s": 54253, "text": "Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid unsigned 32-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false." }, { "code": null, "e": 54750, "s": 54705, "text": "buf.writeUInt32BE(value, offset[, noAssert])" }, { "code": null, "e": 55202, "s": 54750, "text": "Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid unsigned 32-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false." }, { "code": null, "e": 55243, "s": 55202, "text": "buf.writeInt8(value, offset[, noAssert])" }, { "code": null, "e": 55692, "s": 55243, "text": "Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid signed 8-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false." }, { "code": null, "e": 55736, "s": 55692, "text": "buf.writeInt16LE(value, offset[, noAssert])" }, { "code": null, "e": 56186, "s": 55736, "text": "Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid signed 16-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false." }, { "code": null, "e": 56230, "s": 56186, "text": "buf.writeInt16BE(value, offset[, noAssert])" }, { "code": null, "e": 56676, "s": 56230, "text": "Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid signed 16-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false." }, { "code": null, "e": 56720, "s": 56676, "text": "buf.writeInt32LE(value, offset[, noAssert])" }, { "code": null, "e": 57170, "s": 56720, "text": "Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid signed 32-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false." }, { "code": null, "e": 57214, "s": 57170, "text": "buf.writeInt32BE(value, offset[, noAssert])" }, { "code": null, "e": 57660, "s": 57214, "text": "Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid signed 32-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of correctness. Defaults to false." }, { "code": null, "e": 57704, "s": 57660, "text": "buf.writeFloatLE(value, offset[, noAssert])" }, { "code": null, "e": 58150, "s": 57704, "text": "Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a valid 32-bit float. Set noAssert to true to skip validation of value and offset. It means that the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false." }, { "code": null, "e": 58194, "s": 58150, "text": "buf.writeFloatBE(value, offset[, noAssert])" }, { "code": null, "e": 58627, "s": 58194, "text": "Writes a value to the buffer at the specified offset with the specified endian format. Note, value must be a valid 32-bit float. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false." }, { "code": null, "e": 58672, "s": 58627, "text": "buf.writeDoubleLE(value, offset[, noAssert])" }, { "code": null, "e": 59103, "s": 58672, "text": "Writes a value to the buffer at the specified offset with the specified endian format. Note, value must be a valid 64-bit double. Set noAssert to true to skip validation of value and offset. It means that value may be too large for the specific function and offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false." }, { "code": null, "e": 59148, "s": 59103, "text": "buf.writeDoubleBE(value, offset[, noAssert])" }, { "code": null, "e": 59582, "s": 59148, "text": "Writes a value to the buffer at the specified offset with the specified endian format. Note, value must be a valid 64-bit double. Set noAssert to true to skip validation of value and offset. It means the value may be too large for the specific function and the offset may be beyond the end of the buffer leading to the values being silently dropped. It should not be used unless you are certain of its correctness. Defaults to false." }, { "code": null, "e": 59615, "s": 59582, "text": "buf.fill(value[, offset][, end])" }, { "code": null, "e": 59771, "s": 59615, "text": "Fills the buffer with the specified value. If the offset (defaults to 0) and end (defaults to buffer.length) are not given, it will fill the entire buffer." }, { "code": null, "e": 59799, "s": 59771, "text": "Buffer.isEncoding(encoding)" }, { "code": null, "e": 59875, "s": 59799, "text": "Returns true if the encoding is a valid encoding argument, false otherwise." }, { "code": null, "e": 59896, "s": 59875, "text": "Buffer.isBuffer(obj)" }, { "code": null, "e": 59922, "s": 59896, "text": "Tests if obj is a Buffer." }, { "code": null, "e": 59960, "s": 59922, "text": "Buffer.byteLength(string[, encoding])" }, { "code": null, "e": 60154, "s": 59960, "text": "Gives the actual byte length of a string. encoding defaults to 'utf8'. It is not the same as String.prototype.length, since String.prototype.length returns the number of characters in a string." }, { "code": null, "e": 60189, "s": 60154, "text": "Buffer.concat(list[, totalLength])" }, { "code": null, "e": 60281, "s": 60189, "text": "Returns a buffer which is the result of concatenating all the buffers in the list together." }, { "code": null, "e": 60308, "s": 60281, "text": "Buffer.compare(buf1, buf2)" }, { "code": null, "e": 60380, "s": 60308, "text": "The same as buf1.compare(buf2). Useful for sorting an array of buffers." }, { "code": null, "e": 60537, "s": 60380, "text": "Streams are objects that let you read data from a source or write data to a destination in continuous fashion. In Node.js, there are four types of streams −" }, { "code": null, "e": 60589, "s": 60537, "text": "Readable − Stream which is used for read operation." }, { "code": null, "e": 60641, "s": 60589, "text": "Readable − Stream which is used for read operation." }, { "code": null, "e": 60694, "s": 60641, "text": "Writable − Stream which is used for write operation." }, { "code": null, "e": 60747, "s": 60694, "text": "Writable − Stream which is used for write operation." }, { "code": null, "e": 60816, "s": 60747, "text": "Duplex − Stream which can be used for both read and write operation." }, { "code": null, "e": 60885, "s": 60816, "text": "Duplex − Stream which can be used for both read and write operation." }, { "code": null, "e": 60966, "s": 60885, "text": "Transform − A type of duplex stream where the output is computed based on input." }, { "code": null, "e": 61047, "s": 60966, "text": "Transform − A type of duplex stream where the output is computed based on input." }, { "code": null, "e": 61205, "s": 61047, "text": "Each type of Stream is an EventEmitter instance and throws several events at different instance of times. For example, some of the commonly used events are −" }, { "code": null, "e": 61273, "s": 61205, "text": "data − This event is fired when there is data is available to read." }, { "code": null, "e": 61341, "s": 61273, "text": "data − This event is fired when there is data is available to read." }, { "code": null, "e": 61403, "s": 61341, "text": "end − This event is fired when there is no more data to read." }, { "code": null, "e": 61465, "s": 61403, "text": "end − This event is fired when there is no more data to read." }, { "code": null, "e": 61544, "s": 61465, "text": "error − This event is fired when there is any error receiving or writing data." }, { "code": null, "e": 61623, "s": 61544, "text": "error − This event is fired when there is any error receiving or writing data." }, { "code": null, "e": 61709, "s": 61623, "text": "finish − This event is fired when all the data has been flushed to underlying system." }, { "code": null, "e": 61795, "s": 61709, "text": "finish − This event is fired when all the data has been flushed to underlying system." }, { "code": null, "e": 61884, "s": 61795, "text": "This tutorial provides a basic understanding of the commonly used operations on Streams." }, { "code": null, "e": 61950, "s": 61884, "text": "Create a text file named input.txt having the following content −" }, { "code": null, "e": 62046, "s": 61950, "text": "Tutorials Point is giving self learning content\nto teach the world in simple and easy way!!!!!\n" }, { "code": null, "e": 62103, "s": 62046, "text": "Create a js file named main.js with the following code −" }, { "code": null, "e": 62572, "s": 62103, "text": "var fs = require(\"fs\");\nvar data = '';\n\n// Create a readable stream\nvar readerStream = fs.createReadStream('input.txt');\n\n// Set the encoding to be utf8. \nreaderStream.setEncoding('UTF8');\n\n// Handle stream events --> data, end, and error\nreaderStream.on('data', function(chunk) {\n data += chunk;\n});\n\nreaderStream.on('end',function() {\n console.log(data);\n});\n\nreaderStream.on('error', function(err) {\n console.log(err.stack);\n});\n\nconsole.log(\"Program Ended\");" }, { "code": null, "e": 62612, "s": 62572, "text": "Now run the main.js to see the result −" }, { "code": null, "e": 62628, "s": 62612, "text": "$ node main.js\n" }, { "code": null, "e": 62647, "s": 62628, "text": "Verify the Output." }, { "code": null, "e": 62757, "s": 62647, "text": "Program Ended\nTutorials Point is giving self learning content\nto teach the world in simple and easy way!!!!!\n" }, { "code": null, "e": 62814, "s": 62757, "text": "Create a js file named main.js with the following code −" }, { "code": null, "e": 63319, "s": 62814, "text": "var fs = require(\"fs\");\nvar data = 'Simply Easy Learning';\n\n// Create a writable stream\nvar writerStream = fs.createWriteStream('output.txt');\n\n// Write the data to stream with encoding to be utf8\nwriterStream.write(data,'UTF8');\n\n// Mark the end of file\nwriterStream.end();\n\n// Handle stream events --> finish, and error\nwriterStream.on('finish', function() {\n console.log(\"Write completed.\");\n});\n\nwriterStream.on('error', function(err) {\n console.log(err.stack);\n});\n\nconsole.log(\"Program Ended\");" }, { "code": null, "e": 63359, "s": 63319, "text": "Now run the main.js to see the result −" }, { "code": null, "e": 63375, "s": 63359, "text": "$ node main.js\n" }, { "code": null, "e": 63394, "s": 63375, "text": "Verify the Output." }, { "code": null, "e": 63426, "s": 63394, "text": "Program Ended\nWrite completed.\n" }, { "code": null, "e": 63515, "s": 63426, "text": "Now open output.txt created in your current directory; it should contain the following −" }, { "code": null, "e": 63537, "s": 63515, "text": "Simply Easy Learning\n" }, { "code": null, "e": 63868, "s": 63537, "text": "Piping is a mechanism where we provide the output of one stream as the input to another stream. It is normally used to get data from one stream and to pass the output of that stream to another stream. There is no limit on piping operations. Now we'll show a piping example for reading from one file and writing it to another file." }, { "code": null, "e": 63925, "s": 63868, "text": "Create a js file named main.js with the following code −" }, { "code": null, "e": 64265, "s": 63925, "text": "var fs = require(\"fs\");\n\n// Create a readable stream\nvar readerStream = fs.createReadStream('input.txt');\n\n// Create a writable stream\nvar writerStream = fs.createWriteStream('output.txt');\n\n// Pipe the read and write operations\n// read input.txt and write data to output.txt\nreaderStream.pipe(writerStream);\n\nconsole.log(\"Program Ended\");" }, { "code": null, "e": 64305, "s": 64265, "text": "Now run the main.js to see the result −" }, { "code": null, "e": 64321, "s": 64305, "text": "$ node main.js\n" }, { "code": null, "e": 64340, "s": 64321, "text": "Verify the Output." }, { "code": null, "e": 64355, "s": 64340, "text": "Program Ended\n" }, { "code": null, "e": 64440, "s": 64355, "text": "Open output.txt created in your current directory; it should contain the following −" }, { "code": null, "e": 64536, "s": 64440, "text": "Tutorials Point is giving self learning content\nto teach the world in simple and easy way!!!!!\n" }, { "code": null, "e": 64797, "s": 64536, "text": "Chaining is a mechanism to connect the output of one stream to another stream and create a chain of multiple stream operations. It is normally used with piping operations. Now we'll use piping and chaining to first compress a file and then decompress the same." }, { "code": null, "e": 64854, "s": 64797, "text": "Create a js file named main.js with the following code −" }, { "code": null, "e": 65099, "s": 64854, "text": "var fs = require(\"fs\");\nvar zlib = require('zlib');\n\n// Compress the file input.txt to input.txt.gz\nfs.createReadStream('input.txt')\n .pipe(zlib.createGzip())\n .pipe(fs.createWriteStream('input.txt.gz'));\n \nconsole.log(\"File Compressed.\");" }, { "code": null, "e": 65139, "s": 65099, "text": "Now run the main.js to see the result −" }, { "code": null, "e": 65155, "s": 65139, "text": "$ node main.js\n" }, { "code": null, "e": 65174, "s": 65155, "text": "Verify the Output." }, { "code": null, "e": 65192, "s": 65174, "text": "File Compressed.\n" }, { "code": null, "e": 65371, "s": 65192, "text": "You will find that input.txt has been compressed and it created a file input.txt.gz in the current directory. Now let's try to decompress the same file using the following code −" }, { "code": null, "e": 65622, "s": 65371, "text": "var fs = require(\"fs\");\nvar zlib = require('zlib');\n\n// Decompress the file input.txt.gz to input.txt\nfs.createReadStream('input.txt.gz')\n .pipe(zlib.createGunzip())\n .pipe(fs.createWriteStream('input.txt'));\n \nconsole.log(\"File Decompressed.\");" }, { "code": null, "e": 65662, "s": 65622, "text": "Now run the main.js to see the result −" }, { "code": null, "e": 65678, "s": 65662, "text": "$ node main.js\n" }, { "code": null, "e": 65697, "s": 65678, "text": "Verify the Output." }, { "code": null, "e": 65717, "s": 65697, "text": "File Decompressed.\n" }, { "code": null, "e": 65875, "s": 65717, "text": "Node implements File I/O using simple wrappers around standard POSIX functions. The Node File System (fs) module can be imported using the following syntax −" }, { "code": null, "e": 65899, "s": 65875, "text": "var fs = require(\"fs\")\n" }, { "code": null, "e": 66280, "s": 65899, "text": "Every method in the fs module has synchronous as well as asynchronous forms. Asynchronous methods take the last parameter as the completion function callback and the first parameter of the callback function as error. It is better to use an asynchronous method instead of a synchronous method, as the former never blocks a program during its execution, whereas the second one does." }, { "code": null, "e": 66344, "s": 66280, "text": "Create a text file named input.txt with the following content −" }, { "code": null, "e": 66440, "s": 66344, "text": "Tutorials Point is giving self learning content\nto teach the world in simple and easy way!!!!!\n" }, { "code": null, "e": 66504, "s": 66440, "text": "Let us create a js file named main.js with the following code −" }, { "code": null, "e": 66857, "s": 66504, "text": "var fs = require(\"fs\");\n\n// Asynchronous read\nfs.readFile('input.txt', function (err, data) {\n if (err) {\n return console.error(err);\n }\n console.log(\"Asynchronous read: \" + data.toString());\n});\n\n// Synchronous read\nvar data = fs.readFileSync('input.txt');\nconsole.log(\"Synchronous read: \" + data.toString());\n\nconsole.log(\"Program Ended\");" }, { "code": null, "e": 66897, "s": 66857, "text": "Now run the main.js to see the result −" }, { "code": null, "e": 66913, "s": 66897, "text": "$ node main.js\n" }, { "code": null, "e": 66932, "s": 66913, "text": "Verify the Output." }, { "code": null, "e": 67175, "s": 66932, "text": "Synchronous read: Tutorials Point is giving self learning content\nto teach the world in simple and easy way!!!!!\n\nProgram Ended\nAsynchronous read: Tutorials Point is giving self learning content\nto teach the world in simple and easy way!!!!!\n" }, { "code": null, "e": 67272, "s": 67175, "text": "The following sections in this chapter provide a set of good examples on major File I/O methods." }, { "code": null, "e": 67348, "s": 67272, "text": "Following is the syntax of the method to open a file in asynchronous mode −" }, { "code": null, "e": 67388, "s": 67348, "text": "fs.open(path, flags[, mode], callback)\n" }, { "code": null, "e": 67437, "s": 67388, "text": "Here is the description of the parameters used −" }, { "code": null, "e": 67496, "s": 67437, "text": "path − This is the string having file name including path." }, { "code": null, "e": 67555, "s": 67496, "text": "path − This is the string having file name including path." }, { "code": null, "e": 67664, "s": 67555, "text": "flags − Flags indicate the behavior of the file to be opened. All possible values have been mentioned below." }, { "code": null, "e": 67773, "s": 67664, "text": "flags − Flags indicate the behavior of the file to be opened. All possible values have been mentioned below." }, { "code": null, "e": 67911, "s": 67773, "text": "mode − It sets the file mode (permission and sticky bits), but only if the file was created. It defaults to 0666, readable and writeable." }, { "code": null, "e": 68049, "s": 67911, "text": "mode − It sets the file mode (permission and sticky bits), but only if the file was created. It defaults to 0666, readable and writeable." }, { "code": null, "e": 68126, "s": 68049, "text": "callback − This is the callback function which gets two arguments (err, fd)." }, { "code": null, "e": 68203, "s": 68126, "text": "callback − This is the callback function which gets two arguments (err, fd)." }, { "code": null, "e": 68241, "s": 68203, "text": "Flags for read/write operations are −" }, { "code": null, "e": 68243, "s": 68241, "text": "r" }, { "code": null, "e": 68314, "s": 68243, "text": "Open file for reading. An exception occurs if the file does not exist." }, { "code": null, "e": 68317, "s": 68314, "text": "r+" }, { "code": null, "e": 68400, "s": 68317, "text": "Open file for reading and writing. An exception occurs if the file does not exist." }, { "code": null, "e": 68403, "s": 68400, "text": "rs" }, { "code": null, "e": 68446, "s": 68403, "text": "Open file for reading in synchronous mode." }, { "code": null, "e": 68450, "s": 68446, "text": "rs+" }, { "code": null, "e": 68575, "s": 68450, "text": "Open file for reading and writing, asking the OS to open it synchronously. See notes for 'rs' about using this with caution." }, { "code": null, "e": 68577, "s": 68575, "text": "w" }, { "code": null, "e": 68672, "s": 68577, "text": "Open file for writing. The file is created (if it does not exist) or truncated (if it exists)." }, { "code": null, "e": 68675, "s": 68672, "text": "wx" }, { "code": null, "e": 68714, "s": 68675, "text": "Like 'w' but fails if the path exists." }, { "code": null, "e": 68717, "s": 68714, "text": "w+" }, { "code": null, "e": 68824, "s": 68717, "text": "Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists)." }, { "code": null, "e": 68828, "s": 68824, "text": "wx+" }, { "code": null, "e": 68864, "s": 68828, "text": "Like 'w+' but fails if path exists." }, { "code": null, "e": 68866, "s": 68864, "text": "a" }, { "code": null, "e": 68933, "s": 68866, "text": "Open file for appending. The file is created if it does not exist." }, { "code": null, "e": 68936, "s": 68933, "text": "ax" }, { "code": null, "e": 68975, "s": 68936, "text": "Like 'a' but fails if the path exists." }, { "code": null, "e": 68978, "s": 68975, "text": "a+" }, { "code": null, "e": 69057, "s": 68978, "text": "Open file for reading and appending. The file is created if it does not exist." }, { "code": null, "e": 69061, "s": 69057, "text": "ax+" }, { "code": null, "e": 69105, "s": 69061, "text": "Like 'a+' but fails if the the path exists." }, { "code": null, "e": 69219, "s": 69105, "text": "Let us create a js file named main.js having the following code to open a file input.txt for reading and writing." }, { "code": null, "e": 69464, "s": 69219, "text": "var fs = require(\"fs\");\n\n// Asynchronous - Opening File\nconsole.log(\"Going to open file!\");\nfs.open('input.txt', 'r+', function(err, fd) {\n if (err) {\n return console.error(err);\n }\n console.log(\"File opened successfully!\"); \n});" }, { "code": null, "e": 69504, "s": 69464, "text": "Now run the main.js to see the result −" }, { "code": null, "e": 69520, "s": 69504, "text": "$ node main.js\n" }, { "code": null, "e": 69539, "s": 69520, "text": "Verify the Output." }, { "code": null, "e": 69586, "s": 69539, "text": "Going to open file!\nFile opened successfully!\n" }, { "code": null, "e": 69662, "s": 69586, "text": "Following is the syntax of the method to get the information about a file −" }, { "code": null, "e": 69687, "s": 69662, "text": "fs.stat(path, callback)\n" }, { "code": null, "e": 69736, "s": 69687, "text": "Here is the description of the parameters used −" }, { "code": null, "e": 69795, "s": 69736, "text": "path − This is the string having file name including path." }, { "code": null, "e": 69854, "s": 69795, "text": "path − This is the string having file name including path." }, { "code": null, "e": 70014, "s": 69854, "text": "callback − This is the callback function which gets two arguments (err, stats) where stats is an object of fs.Stats type which is printed below in the example." }, { "code": null, "e": 70174, "s": 70014, "text": "callback − This is the callback function which gets two arguments (err, stats) where stats is an object of fs.Stats type which is printed below in the example." }, { "code": null, "e": 70398, "s": 70174, "text": "Apart from the important attributes which are printed below in the example, there are several useful methods available in fs.Stats class which can be used to check file type. These methods are given in the following table." }, { "code": null, "e": 70413, "s": 70398, "text": "stats.isFile()" }, { "code": null, "e": 70457, "s": 70413, "text": "Returns true if file type of a simple file." }, { "code": null, "e": 70477, "s": 70457, "text": "stats.isDirectory()" }, { "code": null, "e": 70519, "s": 70477, "text": "Returns true if file type of a directory." }, { "code": null, "e": 70541, "s": 70519, "text": "stats.isBlockDevice()" }, { "code": null, "e": 70586, "s": 70541, "text": "Returns true if file type of a block device." }, { "code": null, "e": 70612, "s": 70586, "text": "stats.isCharacterDevice()" }, { "code": null, "e": 70661, "s": 70612, "text": "Returns true if file type of a character device." }, { "code": null, "e": 70684, "s": 70661, "text": "stats.isSymbolicLink()" }, { "code": null, "e": 70730, "s": 70684, "text": "Returns true if file type of a symbolic link." }, { "code": null, "e": 70745, "s": 70730, "text": "stats.isFIFO()" }, { "code": null, "e": 70782, "s": 70745, "text": "Returns true if file type of a FIFO." }, { "code": null, "e": 70799, "s": 70782, "text": "stats.isSocket()" }, { "code": null, "e": 70837, "s": 70799, "text": "Returns true if file type of asocket." }, { "code": null, "e": 70901, "s": 70837, "text": "Let us create a js file named main.js with the following code −" }, { "code": null, "e": 71269, "s": 70901, "text": "var fs = require(\"fs\");\n\nconsole.log(\"Going to get file info!\");\nfs.stat('input.txt', function (err, stats) {\n if (err) {\n return console.error(err);\n }\n console.log(stats);\n console.log(\"Got file info successfully!\");\n \n // Check file type\n console.log(\"isFile ? \" + stats.isFile());\n console.log(\"isDirectory ? \" + stats.isDirectory()); \n});" }, { "code": null, "e": 71309, "s": 71269, "text": "Now run the main.js to see the result −" }, { "code": null, "e": 71325, "s": 71309, "text": "$ node main.js\n" }, { "code": null, "e": 71344, "s": 71325, "text": "Verify the Output." }, { "code": null, "e": 71730, "s": 71344, "text": "Going to get file info!\n{ \n dev: 1792,\n mode: 33188,\n nlink: 1,\n uid: 48,\n gid: 48,\n rdev: 0,\n blksize: 4096,\n ino: 4318127,\n size: 97,\n blocks: 8,\n atime: Sun Mar 22 2015 13:40:00 GMT-0500 (CDT),\n mtime: Sun Mar 22 2015 13:40:57 GMT-0500 (CDT),\n ctime: Sun Mar 22 2015 13:40:57 GMT-0500 (CDT) \n}\nGot file info successfully!\nisFile ? true\nisDirectory ? false\n" }, { "code": null, "e": 71799, "s": 71730, "text": "Following is the syntax of one of the methods to write into a file −" }, { "code": null, "e": 71850, "s": 71799, "text": "fs.writeFile(filename, data[, options], callback)\n" }, { "code": null, "e": 72004, "s": 71850, "text": "This method will over-write the file if the file already exists. If you want to write into an existing file then you should use another method available." }, { "code": null, "e": 72053, "s": 72004, "text": "Here is the description of the parameters used −" }, { "code": null, "e": 72116, "s": 72053, "text": "path − This is the string having the file name including path." }, { "code": null, "e": 72179, "s": 72116, "text": "path − This is the string having the file name including path." }, { "code": null, "e": 72245, "s": 72179, "text": "data − This is the String or Buffer to be written into the file." }, { "code": null, "e": 72311, "s": 72245, "text": "data − This is the String or Buffer to be written into the file." }, { "code": null, "e": 72466, "s": 72311, "text": "options − The third parameter is an object which will hold {encoding, mode, flag}. By default. encoding is utf8, mode is octal value 0666. and flag is 'w'" }, { "code": null, "e": 72621, "s": 72466, "text": "options − The third parameter is an object which will hold {encoding, mode, flag}. By default. encoding is utf8, mode is octal value 0666. and flag is 'w'" }, { "code": null, "e": 72748, "s": 72621, "text": "callback − This is the callback function which gets a single parameter err that returns an error in case of any writing error." }, { "code": null, "e": 72875, "s": 72748, "text": "callback − This is the callback function which gets a single parameter err that returns an error in case of any writing error." }, { "code": null, "e": 72941, "s": 72875, "text": "Let us create a js file named main.js having the following code −" }, { "code": null, "e": 73421, "s": 72941, "text": "var fs = require(\"fs\");\n\nconsole.log(\"Going to write into existing file\");\nfs.writeFile('input.txt', 'Simply Easy Learning!', function(err) {\n if (err) {\n return console.error(err);\n }\n \n console.log(\"Data written successfully!\");\n console.log(\"Let's read newly written data\");\n \n fs.readFile('input.txt', function (err, data) {\n if (err) {\n return console.error(err);\n }\n console.log(\"Asynchronous read: \" + data.toString());\n });\n});" }, { "code": null, "e": 73461, "s": 73421, "text": "Now run the main.js to see the result −" }, { "code": null, "e": 73477, "s": 73461, "text": "$ node main.js\n" }, { "code": null, "e": 73496, "s": 73477, "text": "Verify the Output." }, { "code": null, "e": 73629, "s": 73496, "text": "Going to write into existing file\nData written successfully!\nLet's read newly written data\nAsynchronous read: Simply Easy Learning!\n" }, { "code": null, "e": 73697, "s": 73629, "text": "Following is the syntax of one of the methods to read from a file −" }, { "code": null, "e": 73754, "s": 73697, "text": "fs.read(fd, buffer, offset, length, position, callback)\n" }, { "code": null, "e": 73914, "s": 73754, "text": "This method will use file descriptor to read the file. If you want to read the file directly using the file name, then you should use another method available." }, { "code": null, "e": 73963, "s": 73914, "text": "Here is the description of the parameters used −" }, { "code": null, "e": 74019, "s": 73963, "text": "fd − This is the file descriptor returned by fs.open()." }, { "code": null, "e": 74075, "s": 74019, "text": "fd − This is the file descriptor returned by fs.open()." }, { "code": null, "e": 74137, "s": 74075, "text": "buffer − This is the buffer that the data will be written to." }, { "code": null, "e": 74199, "s": 74137, "text": "buffer − This is the buffer that the data will be written to." }, { "code": null, "e": 74262, "s": 74199, "text": "offset − This is the offset in the buffer to start writing at." }, { "code": null, "e": 74325, "s": 74262, "text": "offset − This is the offset in the buffer to start writing at." }, { "code": null, "e": 74393, "s": 74325, "text": "length − This is an integer specifying the number of bytes to read." }, { "code": null, "e": 74461, "s": 74393, "text": "length − This is an integer specifying the number of bytes to read." }, { "code": null, "e": 74614, "s": 74461, "text": "position − This is an integer specifying where to begin reading from in the file. If position is null, data will be read from the current file position." }, { "code": null, "e": 74767, "s": 74614, "text": "position − This is an integer specifying where to begin reading from in the file. If position is null, data will be read from the current file position." }, { "code": null, "e": 74866, "s": 74767, "text": "callback − This is the callback function which gets the three arguments, (err, bytesRead, buffer)." }, { "code": null, "e": 74965, "s": 74866, "text": "callback − This is the callback function which gets the three arguments, (err, bytesRead, buffer)." }, { "code": null, "e": 75029, "s": 74965, "text": "Let us create a js file named main.js with the following code −" }, { "code": null, "e": 75619, "s": 75029, "text": "var fs = require(\"fs\");\nvar buf = new Buffer(1024);\n\nconsole.log(\"Going to open an existing file\");\nfs.open('input.txt', 'r+', function(err, fd) {\n if (err) {\n return console.error(err);\n }\n console.log(\"File opened successfully!\");\n console.log(\"Going to read the file\");\n \n fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){\n if (err){\n console.log(err);\n }\n console.log(bytes + \" bytes read\");\n \n // Print only read bytes to avoid junk.\n if(bytes > 0){\n console.log(buf.slice(0, bytes).toString());\n }\n });\n});" }, { "code": null, "e": 75659, "s": 75619, "text": "Now run the main.js to see the result −" }, { "code": null, "e": 75675, "s": 75659, "text": "$ node main.js\n" }, { "code": null, "e": 75694, "s": 75675, "text": "Verify the Output." }, { "code": null, "e": 75884, "s": 75694, "text": "Going to open an existing file\nFile opened successfully!\nGoing to read the file\n97 bytes read\nTutorials Point is giving self learning content\nto teach the world in simple and easy way!!!!!\n" }, { "code": null, "e": 75934, "s": 75884, "text": "Following is the syntax to close an opened file −" }, { "code": null, "e": 75958, "s": 75934, "text": "fs.close(fd, callback)\n" }, { "code": null, "e": 76007, "s": 75958, "text": "Here is the description of the parameters used −" }, { "code": null, "e": 76075, "s": 76007, "text": "fd − This is the file descriptor returned by file fs.open() method." }, { "code": null, "e": 76143, "s": 76075, "text": "fd − This is the file descriptor returned by file fs.open() method." }, { "code": null, "e": 76267, "s": 76143, "text": "callback − This is the callback function No arguments other than a possible exception are given to the completion callback." }, { "code": null, "e": 76391, "s": 76267, "text": "callback − This is the callback function No arguments other than a possible exception are given to the completion callback." }, { "code": null, "e": 76457, "s": 76391, "text": "Let us create a js file named main.js having the following code −" }, { "code": null, "e": 77193, "s": 76457, "text": "var fs = require(\"fs\");\nvar buf = new Buffer(1024);\n\nconsole.log(\"Going to open an existing file\");\nfs.open('input.txt', 'r+', function(err, fd) {\n if (err) {\n return console.error(err);\n }\n console.log(\"File opened successfully!\");\n console.log(\"Going to read the file\");\n \n fs.read(fd, buf, 0, buf.length, 0, function(err, bytes) {\n if (err) {\n console.log(err);\n }\n\n // Print only read bytes to avoid junk.\n if(bytes > 0) {\n console.log(buf.slice(0, bytes).toString());\n }\n\n // Close the opened file.\n fs.close(fd, function(err) {\n if (err) {\n console.log(err);\n } \n console.log(\"File closed successfully.\");\n });\n });\n});" }, { "code": null, "e": 77233, "s": 77193, "text": "Now run the main.js to see the result −" }, { "code": null, "e": 77249, "s": 77233, "text": "$ node main.js\n" }, { "code": null, "e": 77268, "s": 77249, "text": "Verify the Output." }, { "code": null, "e": 77471, "s": 77268, "text": "Going to open an existing file\nFile opened successfully!\nGoing to read the file\nTutorials Point is giving self learning content\nto teach the world in simple and easy way!!!!!\n\nFile closed successfully.\n" }, { "code": null, "e": 77538, "s": 77471, "text": "Following is the syntax of the method to truncate an opened file −" }, { "code": null, "e": 77571, "s": 77538, "text": "fs.ftruncate(fd, len, callback)\n" }, { "code": null, "e": 77620, "s": 77571, "text": "Here is the description of the parameters used −" }, { "code": null, "e": 77676, "s": 77620, "text": "fd − This is the file descriptor returned by fs.open()." }, { "code": null, "e": 77732, "s": 77676, "text": "fd − This is the file descriptor returned by fs.open()." }, { "code": null, "e": 77809, "s": 77732, "text": "len − This is the length of the file after which the file will be truncated." }, { "code": null, "e": 77886, "s": 77809, "text": "len − This is the length of the file after which the file will be truncated." }, { "code": null, "e": 78010, "s": 77886, "text": "callback − This is the callback function No arguments other than a possible exception are given to the completion callback." }, { "code": null, "e": 78134, "s": 78010, "text": "callback − This is the callback function No arguments other than a possible exception are given to the completion callback." }, { "code": null, "e": 78200, "s": 78134, "text": "Let us create a js file named main.js having the following code −" }, { "code": null, "e": 79243, "s": 78200, "text": "var fs = require(\"fs\");\nvar buf = new Buffer(1024);\n\nconsole.log(\"Going to open an existing file\");\nfs.open('input.txt', 'r+', function(err, fd) {\n if (err) {\n return console.error(err);\n }\n console.log(\"File opened successfully!\");\n console.log(\"Going to truncate the file after 10 bytes\");\n \n // Truncate the opened file.\n fs.ftruncate(fd, 10, function(err) {\n if (err) {\n console.log(err);\n } \n console.log(\"File truncated successfully.\");\n console.log(\"Going to read the same file\"); \n \n fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){\n if (err) {\n console.log(err);\n }\n\n // Print only read bytes to avoid junk.\n if(bytes > 0) {\n console.log(buf.slice(0, bytes).toString());\n }\n\n // Close the opened file.\n fs.close(fd, function(err) {\n if (err) {\n console.log(err);\n } \n console.log(\"File closed successfully.\");\n });\n });\n });\n});" }, { "code": null, "e": 79283, "s": 79243, "text": "Now run the main.js to see the result −" }, { "code": null, "e": 79299, "s": 79283, "text": "$ node main.js\n" }, { "code": null, "e": 79318, "s": 79299, "text": "Verify the Output." }, { "code": null, "e": 79512, "s": 79318, "text": "Going to open an existing file\nFile opened successfully!\nGoing to truncate the file after 10 bytes\nFile truncated successfully.\nGoing to read the same file\nTutorials \nFile closed successfully.\n" }, { "code": null, "e": 79569, "s": 79512, "text": "Following is the syntax of the method to delete a file −" }, { "code": null, "e": 79596, "s": 79569, "text": "fs.unlink(path, callback)\n" }, { "code": null, "e": 79645, "s": 79596, "text": "Here is the description of the parameters used −" }, { "code": null, "e": 79690, "s": 79645, "text": "path − This is the file name including path." }, { "code": null, "e": 79735, "s": 79690, "text": "path − This is the file name including path." }, { "code": null, "e": 79859, "s": 79735, "text": "callback − This is the callback function No arguments other than a possible exception are given to the completion callback." }, { "code": null, "e": 79983, "s": 79859, "text": "callback − This is the callback function No arguments other than a possible exception are given to the completion callback." }, { "code": null, "e": 80049, "s": 79983, "text": "Let us create a js file named main.js having the following code −" }, { "code": null, "e": 80264, "s": 80049, "text": "var fs = require(\"fs\");\n\nconsole.log(\"Going to delete an existing file\");\nfs.unlink('input.txt', function(err) {\n if (err) {\n return console.error(err);\n }\n console.log(\"File deleted successfully!\");\n});" }, { "code": null, "e": 80304, "s": 80264, "text": "Now run the main.js to see the result −" }, { "code": null, "e": 80320, "s": 80304, "text": "$ node main.js\n" }, { "code": null, "e": 80339, "s": 80320, "text": "Verify the Output." }, { "code": null, "e": 80400, "s": 80339, "text": "Going to delete an existing file\nFile deleted successfully!\n" }, { "code": null, "e": 80462, "s": 80400, "text": "Following is the syntax of the method to create a directory −" }, { "code": null, "e": 80496, "s": 80462, "text": "fs.mkdir(path[, mode], callback)\n" }, { "code": null, "e": 80545, "s": 80496, "text": "Here is the description of the parameters used −" }, { "code": null, "e": 80595, "s": 80545, "text": "path − This is the directory name including path." }, { "code": null, "e": 80645, "s": 80595, "text": "path − This is the directory name including path." }, { "code": null, "e": 80714, "s": 80645, "text": "mode − This is the directory permission to be set. Defaults to 0777." }, { "code": null, "e": 80783, "s": 80714, "text": "mode − This is the directory permission to be set. Defaults to 0777." }, { "code": null, "e": 80907, "s": 80783, "text": "callback − This is the callback function No arguments other than a possible exception are given to the completion callback." }, { "code": null, "e": 81031, "s": 80907, "text": "callback − This is the callback function No arguments other than a possible exception are given to the completion callback." }, { "code": null, "e": 81097, "s": 81031, "text": "Let us create a js file named main.js having the following code −" }, { "code": null, "e": 81318, "s": 81097, "text": "var fs = require(\"fs\");\n\nconsole.log(\"Going to create directory /tmp/test\");\nfs.mkdir('/tmp/test',function(err) {\n if (err) {\n return console.error(err);\n }\n console.log(\"Directory created successfully!\");\n});" }, { "code": null, "e": 81358, "s": 81318, "text": "Now run the main.js to see the result −" }, { "code": null, "e": 81374, "s": 81358, "text": "$ node main.js\n" }, { "code": null, "e": 81393, "s": 81374, "text": "Verify the Output." }, { "code": null, "e": 81462, "s": 81393, "text": "Going to create directory /tmp/test\nDirectory created successfully!\n" }, { "code": null, "e": 81522, "s": 81462, "text": "Following is the syntax of the method to read a directory −" }, { "code": null, "e": 81550, "s": 81522, "text": "fs.readdir(path, callback)\n" }, { "code": null, "e": 81599, "s": 81550, "text": "Here is the description of the parameters used −" }, { "code": null, "e": 81649, "s": 81599, "text": "path − This is the directory name including path." }, { "code": null, "e": 81699, "s": 81649, "text": "path − This is the directory name including path." }, { "code": null, "e": 81869, "s": 81699, "text": "callback − This is the callback function which gets two arguments (err, files) where files is an array of the names of the files in the directory excluding '.' and '..'." }, { "code": null, "e": 82039, "s": 81869, "text": "callback − This is the callback function which gets two arguments (err, files) where files is an array of the names of the files in the directory excluding '.' and '..'." }, { "code": null, "e": 82105, "s": 82039, "text": "Let us create a js file named main.js having the following code −" }, { "code": null, "e": 82343, "s": 82105, "text": "var fs = require(\"fs\");\n\nconsole.log(\"Going to read directory /tmp\");\nfs.readdir(\"/tmp/\",function(err, files) {\n if (err) {\n return console.error(err);\n }\n files.forEach( function (file) {\n console.log( file );\n });\n});" }, { "code": null, "e": 82383, "s": 82343, "text": "Now run the main.js to see the result −" }, { "code": null, "e": 82399, "s": 82383, "text": "$ node main.js\n" }, { "code": null, "e": 82418, "s": 82399, "text": "Verify the Output." }, { "code": null, "e": 82519, "s": 82418, "text": "Going to read directory /tmp\nccmzx99o.out\nccyCSbkF.out\nemployee.ser\nhsperfdata_apache\ntest\ntest.txt\n" }, { "code": null, "e": 82581, "s": 82519, "text": "Following is the syntax of the method to remove a directory −" }, { "code": null, "e": 82607, "s": 82581, "text": "fs.rmdir(path, callback)\n" }, { "code": null, "e": 82656, "s": 82607, "text": "Here is the description of the parameters used −" }, { "code": null, "e": 82706, "s": 82656, "text": "path − This is the directory name including path." }, { "code": null, "e": 82756, "s": 82706, "text": "path − This is the directory name including path." }, { "code": null, "e": 82880, "s": 82756, "text": "callback − This is the callback function No arguments other than a possible exception are given to the completion callback." }, { "code": null, "e": 83004, "s": 82880, "text": "callback − This is the callback function No arguments other than a possible exception are given to the completion callback." }, { "code": null, "e": 83070, "s": 83004, "text": "Let us create a js file named main.js having the following code −" }, { "code": null, "e": 83484, "s": 83070, "text": "var fs = require(\"fs\");\n\nconsole.log(\"Going to delete directory /tmp/test\");\nfs.rmdir(\"/tmp/test\",function(err) {\n if (err) {\n return console.error(err);\n }\n console.log(\"Going to read directory /tmp\");\n \n fs.readdir(\"/tmp/\",function(err, files) {\n if (err) {\n return console.error(err);\n }\n files.forEach( function (file) {\n console.log( file );\n });\n });\n});" }, { "code": null, "e": 83524, "s": 83484, "text": "Now run the main.js to see the result −" }, { "code": null, "e": 83540, "s": 83524, "text": "$ node main.js\n" }, { "code": null, "e": 83559, "s": 83540, "text": "Verify the Output." }, { "code": null, "e": 83655, "s": 83559, "text": "Going to read directory /tmp\nccmzx99o.out\nccyCSbkF.out\nemployee.ser\nhsperfdata_apache\ntest.txt\n" }, { "code": null, "e": 83693, "s": 83655, "text": "fs.rename(oldPath, newPath, callback)" }, { "code": null, "e": 83799, "s": 83693, "text": "Asynchronous rename(). No arguments other than a possible exception are given to the completion callback." }, { "code": null, "e": 83831, "s": 83799, "text": "fs.ftruncate(fd, len, callback)" }, { "code": null, "e": 83940, "s": 83831, "text": "Asynchronous ftruncate(). No arguments other than a possible exception are given to the completion callback." }, { "code": null, "e": 83966, "s": 83940, "text": "fs.ftruncateSync(fd, len)" }, { "code": null, "e": 83991, "s": 83966, "text": "Synchronous ftruncate()." }, { "code": null, "e": 84024, "s": 83991, "text": "fs.truncate(path, len, callback)" }, { "code": null, "e": 84132, "s": 84024, "text": "Asynchronous truncate(). No arguments other than a possible exception are given to the completion callback." }, { "code": null, "e": 84159, "s": 84132, "text": "fs.truncateSync(path, len)" }, { "code": null, "e": 84183, "s": 84159, "text": "Synchronous truncate()." }, { "code": null, "e": 84218, "s": 84183, "text": "fs.chown(path, uid, gid, callback)" }, { "code": null, "e": 84323, "s": 84218, "text": "Asynchronous chown(). No arguments other than a possible exception are given to the completion callback." }, { "code": null, "e": 84352, "s": 84323, "text": "fs.chownSync(path, uid, gid)" }, { "code": null, "e": 84373, "s": 84352, "text": "Synchronous chown()." }, { "code": null, "e": 84407, "s": 84373, "text": "fs.fchown(fd, uid, gid, callback)" }, { "code": null, "e": 84513, "s": 84407, "text": "Asynchronous fchown(). No arguments other than a possible exception are given to the completion callback." }, { "code": null, "e": 84541, "s": 84513, "text": "fs.fchownSync(fd, uid, gid)" }, { "code": null, "e": 84563, "s": 84541, "text": "Synchronous fchown()." }, { "code": null, "e": 84599, "s": 84563, "text": "fs.lchown(path, uid, gid, callback)" }, { "code": null, "e": 84705, "s": 84599, "text": "Asynchronous lchown(). No arguments other than a possible exception are given to the completion callback." }, { "code": null, "e": 84735, "s": 84705, "text": "fs.lchownSync(path, uid, gid)" }, { "code": null, "e": 84757, "s": 84735, "text": "Synchronous lchown()." }, { "code": null, "e": 84788, "s": 84757, "text": "fs.chmod(path, mode, callback)" }, { "code": null, "e": 84893, "s": 84788, "text": "Asynchronous chmod(). No arguments other than a possible exception are given to the completion callback." }, { "code": null, "e": 84918, "s": 84893, "text": "fs.chmodSync(path, mode)" }, { "code": null, "e": 84939, "s": 84918, "text": "Synchronous chmod()." }, { "code": null, "e": 84969, "s": 84939, "text": "fs.fchmod(fd, mode, callback)" }, { "code": null, "e": 85075, "s": 84969, "text": "Asynchronous fchmod(). No arguments other than a possible exception are given to the completion callback." }, { "code": null, "e": 85099, "s": 85075, "text": "fs.fchmodSync(fd, mode)" }, { "code": null, "e": 85121, "s": 85099, "text": "Synchronous fchmod()." }, { "code": null, "e": 85153, "s": 85121, "text": "fs.lchmod(path, mode, callback)" }, { "code": null, "e": 85287, "s": 85153, "text": "Asynchronous lchmod(). No arguments other than a possible exception are given to the completion callback. Only available on Mac OS X." }, { "code": null, "e": 85313, "s": 85287, "text": "fs.lchmodSync(path, mode)" }, { "code": null, "e": 85335, "s": 85313, "text": "Synchronous lchmod()." }, { "code": null, "e": 85359, "s": 85335, "text": "fs.stat(path, callback)" }, { "code": null, "e": 85460, "s": 85359, "text": "Asynchronous stat(). The callback gets two arguments (err, stats) where stats is an fs.Stats object." }, { "code": null, "e": 85485, "s": 85460, "text": "fs.lstat(path, callback)" }, { "code": null, "e": 85724, "s": 85485, "text": "Asynchronous lstat(). The callback gets two arguments (err, stats) where stats is an fs.Stats object. lstat() is identical to stat(), except that if path is a symbolic link, then the link itself is stat-ed, not the file that it refers to." }, { "code": null, "e": 85747, "s": 85724, "text": "fs.fstat(fd, callback)" }, { "code": null, "e": 85956, "s": 85747, "text": "Asynchronous fstat(). The callback gets two arguments (err, stats) where stats is an fs.Stats object. fstat() is identical to stat(), except that the file to be stat-ed is specified by the file descriptor fd." }, { "code": null, "e": 85974, "s": 85956, "text": "fs.statSync(path)" }, { "code": null, "e": 86027, "s": 85974, "text": "Synchronous stat(). Returns an instance of fs.Stats." }, { "code": null, "e": 86046, "s": 86027, "text": "fs.lstatSync(path)" }, { "code": null, "e": 86100, "s": 86046, "text": "Synchronous lstat(). Returns an instance of fs.Stats." }, { "code": null, "e": 86117, "s": 86100, "text": "fs.fstatSync(fd)" }, { "code": null, "e": 86171, "s": 86117, "text": "Synchronous fstat(). Returns an instance of fs.Stats." }, { "code": null, "e": 86207, "s": 86171, "text": "fs.link(srcpath, dstpath, callback)" }, { "code": null, "e": 86311, "s": 86207, "text": "Asynchronous link(). No arguments other than a possible exception are given to the completion callback." }, { "code": null, "e": 86341, "s": 86311, "text": "fs.linkSync(srcpath, dstpath)" }, { "code": null, "e": 86361, "s": 86341, "text": "Synchronous link()." }, { "code": null, "e": 86408, "s": 86361, "text": "fs.symlink(srcpath, dstpath[, type], callback)" }, { "code": null, "e": 86837, "s": 86408, "text": "Asynchronous symlink(). No arguments other than a possible exception are given to the completion callback. The type argument can be set to 'dir', 'file', or 'junction' (default is 'file') and is only available on Windows (ignored on other platforms). Note that Windows junction points require the destination path to be absolute. When using 'junction', the destination argument will automatically be normalized to absolute path." }, { "code": null, "e": 86878, "s": 86837, "text": "fs.symlinkSync(srcpath, dstpath[, type])" }, { "code": null, "e": 86901, "s": 86878, "text": "Synchronous symlink()." }, { "code": null, "e": 86929, "s": 86901, "text": "fs.readlink(path, callback)" }, { "code": null, "e": 87005, "s": 86929, "text": "Asynchronous readlink(). The callback gets two arguments (err, linkString)." }, { "code": null, "e": 87042, "s": 87005, "text": "fs.realpath(path[, cache], callback)" }, { "code": null, "e": 87319, "s": 87042, "text": "Asynchronous realpath(). The callback gets two arguments (err, resolvedPath). May use process.cwd to resolve relative paths. cache is an object literal of mapped paths that can be used to force a specific path resolution or avoid additional fs.stat calls for known real paths." }, { "code": null, "e": 87350, "s": 87319, "text": "fs.realpathSync(path[, cache])" }, { "code": null, "e": 87401, "s": 87350, "text": "Synchronous realpath(). Returns the resolved path." }, { "code": null, "e": 87427, "s": 87401, "text": "fs.unlink(path, callback)" }, { "code": null, "e": 87533, "s": 87427, "text": "Asynchronous unlink(). No arguments other than a possible exception are given to the completion callback." }, { "code": null, "e": 87553, "s": 87533, "text": "fs.unlinkSync(path)" }, { "code": null, "e": 87575, "s": 87553, "text": "Synchronous unlink()." }, { "code": null, "e": 87600, "s": 87575, "text": "fs.rmdir(path, callback)" }, { "code": null, "e": 87705, "s": 87600, "text": "Asynchronous rmdir(). No arguments other than a possible exception are given to the completion callback." }, { "code": null, "e": 87724, "s": 87705, "text": "fs.rmdirSync(path)" }, { "code": null, "e": 87745, "s": 87724, "text": "Synchronous rmdir()." }, { "code": null, "e": 87778, "s": 87745, "text": "fs.mkdir(path[, mode], callback)" }, { "code": null, "e": 87907, "s": 87778, "text": "Asynchronous mkdir(2). No arguments other than a possible exception are given to the completion callback. mode defaults to 0777." }, { "code": null, "e": 87934, "s": 87907, "text": "fs.mkdirSync(path[, mode])" }, { "code": null, "e": 87955, "s": 87934, "text": "Synchronous mkdir()." }, { "code": null, "e": 87982, "s": 87955, "text": "fs.readdir(path, callback)" }, { "code": null, "e": 88178, "s": 87982, "text": "Asynchronous readdir(3). Reads the contents of a directory. The callback gets two arguments (err, files) where files is an array of the names of the files in the directory excluding '.' and '..'." }, { "code": null, "e": 88199, "s": 88178, "text": "fs.readdirSync(path)" }, { "code": null, "e": 88276, "s": 88199, "text": "Synchronous readdir(). Returns an array of filenames excluding '.' and '..'." }, { "code": null, "e": 88299, "s": 88276, "text": "fs.close(fd, callback)" }, { "code": null, "e": 88404, "s": 88299, "text": "Asynchronous close(). No arguments other than a possible exception are given to the completion callback." }, { "code": null, "e": 88421, "s": 88404, "text": "fs.closeSync(fd)" }, { "code": null, "e": 88442, "s": 88421, "text": "Synchronous close()." }, { "code": null, "e": 88481, "s": 88442, "text": "fs.open(path, flags[, mode], callback)" }, { "code": null, "e": 88505, "s": 88481, "text": "Asynchronous file open." }, { "code": null, "e": 88538, "s": 88505, "text": "fs.openSync(path, flags[, mode])" }, { "code": null, "e": 88572, "s": 88538, "text": "Synchronous version of fs.open()." }, { "code": null, "e": 88612, "s": 88572, "text": "fs.utimes(path, atime, mtime, callback)" }, { "code": null, "e": 88648, "s": 88614, "text": "fs.utimesSync(path, atime, mtime)" }, { "code": null, "e": 88716, "s": 88648, "text": "Change file timestamps of the file referenced by the supplied path." }, { "code": null, "e": 88755, "s": 88716, "text": "fs.futimes(fd, atime, mtime, callback)" }, { "code": null, "e": 88790, "s": 88757, "text": "fs.futimesSync(fd, atime, mtime)" }, { "code": null, "e": 88871, "s": 88790, "text": "Change the file timestamps of a file referenced by the supplied file descriptor." }, { "code": null, "e": 88894, "s": 88871, "text": "fs.fsync(fd, callback)" }, { "code": null, "e": 88997, "s": 88894, "text": "Asynchronous fsync. No arguments other than a possible exception are given to the completion callback." }, { "code": null, "e": 89014, "s": 88997, "text": "fs.fsyncSync(fd)" }, { "code": null, "e": 89033, "s": 89014, "text": "Synchronous fsync." }, { "code": null, "e": 89092, "s": 89033, "text": "fs.write(fd, buffer, offset, length[, position], callback)" }, { "code": null, "e": 89134, "s": 89092, "text": "Write buffer to the file specified by fd." }, { "code": null, "e": 89187, "s": 89134, "text": "fs.write(fd, data[, position[, encoding]], callback)" }, { "code": null, "e": 89304, "s": 89187, "text": "Write data to the file specified by fd. If data is not a Buffer instance then the value will be coerced to a string." }, { "code": null, "e": 89357, "s": 89304, "text": "fs.writeSync(fd, buffer, offset, length[, position])" }, { "code": null, "e": 89430, "s": 89357, "text": "Synchronous versions of fs.write(). Returns the number of bytes written." }, { "code": null, "e": 89477, "s": 89430, "text": "fs.writeSync(fd, data[, position[, encoding]])" }, { "code": null, "e": 89550, "s": 89477, "text": "Synchronous versions of fs.write(). Returns the number of bytes written." }, { "code": null, "e": 89606, "s": 89550, "text": "fs.read(fd, buffer, offset, length, position, callback)" }, { "code": null, "e": 89647, "s": 89606, "text": "Read data from the file specified by fd." }, { "code": null, "e": 89697, "s": 89647, "text": "fs.readSync(fd, buffer, offset, length, position)" }, { "code": null, "e": 89762, "s": 89697, "text": "Synchronous version of fs.read. Returns the number of bytesRead." }, { "code": null, "e": 89805, "s": 89762, "text": "fs.readFile(filename[, options], callback)" }, { "code": null, "e": 89857, "s": 89805, "text": "Asynchronously reads the entire contents of a file." }, { "code": null, "e": 89894, "s": 89857, "text": "fs.readFileSync(filename[, options])" }, { "code": null, "e": 89968, "s": 89894, "text": "Synchronous version of fs.readFile. Returns the contents of the filename." }, { "code": null, "e": 90018, "s": 89968, "text": "fs.writeFile(filename, data[, options], callback)" }, { "code": null, "e": 90131, "s": 90018, "text": "Asynchronously writes data to a file, replacing the file if it already exists. data can be a string or a buffer." }, { "code": null, "e": 90175, "s": 90131, "text": "fs.writeFileSync(filename, data[, options])" }, { "code": null, "e": 90216, "s": 90175, "text": "The synchronous version of fs.writeFile." }, { "code": null, "e": 90267, "s": 90216, "text": "fs.appendFile(filename, data[, options], callback)" }, { "code": null, "e": 90379, "s": 90267, "text": "Asynchronously append data to a file, creating the file if it does not exist. data can be a string or a buffer." }, { "code": null, "e": 90424, "s": 90379, "text": "fs.appendFileSync(filename, data[, options])" }, { "code": null, "e": 90466, "s": 90424, "text": "The synchronous version of fs.appendFile." }, { "code": null, "e": 90510, "s": 90466, "text": "fs.watchFile(filename[, options], listener)" }, { "code": null, "e": 90610, "s": 90510, "text": "Watch for changes on filename. The callback listener will be called each time the file is accessed." }, { "code": null, "e": 90647, "s": 90610, "text": "fs.unwatchFile(filename[, listener])" }, { "code": null, "e": 90843, "s": 90647, "text": "Stop watching for changes on filename. If listener is specified, only that particular listener is removed. Otherwise, all listeners are removed and you have effectively stopped watching filename." }, { "code": null, "e": 90885, "s": 90843, "text": "fs.watch(filename[, options][, listener])" }, { "code": null, "e": 91005, "s": 90885, "text": "Watch for changes on filename, where filename is either a file or an directory. The returned object is an fs.FSWatcher." }, { "code": null, "e": 91031, "s": 91005, "text": "fs.exists(path, callback)" }, { "code": null, "e": 91166, "s": 91031, "text": "Test whether or not the given path exists by checking with the file system. Then call the callback argument with either true or false." }, { "code": null, "e": 91186, "s": 91166, "text": "fs.existsSync(path)" }, { "code": null, "e": 91220, "s": 91186, "text": "Synchronous version of fs.exists." }, { "code": null, "e": 91254, "s": 91220, "text": "fs.access(path[, mode], callback)" }, { "code": null, "e": 91398, "s": 91254, "text": "Tests a user's permissions for the file specified by path. mode is an optional integer that specifies the accessibility checks to be performed." }, { "code": null, "e": 91426, "s": 91398, "text": "fs.accessSync(path[, mode])" }, { "code": null, "e": 91532, "s": 91426, "text": "Synchronous version of fs.access. It throws if any accessibility checks fail, and does nothing otherwise." }, { "code": null, "e": 91569, "s": 91532, "text": "fs.createReadStream(path[, options])" }, { "code": null, "e": 91602, "s": 91569, "text": "Returns a new ReadStream object." }, { "code": null, "e": 91640, "s": 91602, "text": "fs.createWriteStream(path[, options])" }, { "code": null, "e": 91674, "s": 91640, "text": "Returns a new WriteStream object." }, { "code": null, "e": 91721, "s": 91674, "text": "fs.symlink(srcpath, dstpath[, type], callback)" }, { "code": null, "e": 92150, "s": 91721, "text": "Asynchronous symlink(). No arguments other than a possible exception are given to the completion callback. The type argument can be set to 'dir', 'file', or 'junction' (default is 'file') and is only available on Windows (ignored on other platforms). Note that Windows junction points require the destination path to be absolute. When using 'junction', the destination argument will automatically be normalized to absolute path." }, { "code": null, "e": 92410, "s": 92150, "text": "Node.js global objects are global in nature and they are available in all modules. We do not need to include these objects in our application, rather we can use them directly. These objects are modules, functions, strings and object itself as explained below." }, { "code": null, "e": 92678, "s": 92410, "text": "The __filename represents the filename of the code being executed. This is the resolved absolute path of this code file. For a main program, this is not necessarily the same filename used in the command line. The value inside a module is the path to that module file." }, { "code": null, "e": 92735, "s": 92678, "text": "Create a js file named main.js with the following code −" }, { "code": null, "e": 92809, "s": 92735, "text": "// Let's try to print the value of __filename\n\nconsole.log( __filename );" }, { "code": null, "e": 92849, "s": 92809, "text": "Now run the main.js to see the result −" }, { "code": null, "e": 92865, "s": 92849, "text": "$ node main.js\n" }, { "code": null, "e": 92950, "s": 92865, "text": "Based on the location of your program, it will print the main file name as follows −" }, { "code": null, "e": 92985, "s": 92950, "text": "/web/com/1427091028_21099/main.js\n" }, { "code": null, "e": 93084, "s": 92985, "text": "The __dirname represents the name of the directory that the currently executing script resides in." }, { "code": null, "e": 93141, "s": 93084, "text": "Create a js file named main.js with the following code −" }, { "code": null, "e": 93213, "s": 93141, "text": "// Let's try to print the value of __dirname\n\nconsole.log( __dirname );" }, { "code": null, "e": 93253, "s": 93213, "text": "Now run the main.js to see the result −" }, { "code": null, "e": 93269, "s": 93253, "text": "$ node main.js\n" }, { "code": null, "e": 93358, "s": 93269, "text": "Based on the location of your program, it will print current directory name as follows −" }, { "code": null, "e": 93385, "s": 93358, "text": "/web/com/1427091028_21099\n" }, { "code": null, "e": 93612, "s": 93385, "text": "The setTimeout(cb, ms) global function is used to run callback cb after at least ms milliseconds. The actual delay depends on external factors like OS timer granularity and system load. A timer cannot span more than 24.8 days." }, { "code": null, "e": 93714, "s": 93612, "text": "This function returns an opaque value that represents the timer which can be used to clear the timer." }, { "code": null, "e": 93771, "s": 93714, "text": "Create a js file named main.js with the following code −" }, { "code": null, "e": 93905, "s": 93771, "text": "function printHello() {\n console.log( \"Hello, World!\");\n}\n\n// Now call above function after 2 seconds\nsetTimeout(printHello, 2000);" }, { "code": null, "e": 93945, "s": 93905, "text": "Now run the main.js to see the result −" }, { "code": null, "e": 93961, "s": 93945, "text": "$ node main.js\n" }, { "code": null, "e": 94012, "s": 93961, "text": "Verify the output is printed after a little delay." }, { "code": null, "e": 94027, "s": 94012, "text": "Hello, World!\n" }, { "code": null, "e": 94193, "s": 94027, "text": "The clearTimeout(t) global function is used to stop a timer that was previously created with setTimeout(). Here t is the timer returned by the setTimeout() function." }, { "code": null, "e": 94250, "s": 94193, "text": "Create a js file named main.js with the following code −" }, { "code": null, "e": 94433, "s": 94250, "text": "function printHello() {\n console.log( \"Hello, World!\");\n}\n\n// Now call above function after 2 seconds\nvar t = setTimeout(printHello, 2000);\n\n// Now clear the timer\nclearTimeout(t);" }, { "code": null, "e": 94473, "s": 94433, "text": "Now run the main.js to see the result −" }, { "code": null, "e": 94489, "s": 94473, "text": "$ node main.js\n" }, { "code": null, "e": 94549, "s": 94489, "text": "Verify the output where you will not find anything printed." }, { "code": null, "e": 94788, "s": 94549, "text": "The setInterval(cb, ms) global function is used to run callback cb repeatedly after at least ms milliseconds. The actual delay depends on external factors like OS timer granularity and system load. A timer cannot span more than 24.8 days." }, { "code": null, "e": 94926, "s": 94788, "text": "This function returns an opaque value that represents the timer which can be used to clear the timer using the function clearInterval(t)." }, { "code": null, "e": 94983, "s": 94926, "text": "Create a js file named main.js with the following code −" }, { "code": null, "e": 95118, "s": 94983, "text": "function printHello() {\n console.log( \"Hello, World!\");\n}\n\n// Now call above function after 2 seconds\nsetInterval(printHello, 2000);" }, { "code": null, "e": 95158, "s": 95118, "text": "Now run the main.js to see the result −" }, { "code": null, "e": 95174, "s": 95158, "text": "$ node main.js\n" }, { "code": null, "e": 95266, "s": 95174, "text": "The above program will execute printHello() after every 2 second. Due to system limitation." }, { "code": null, "e": 95428, "s": 95266, "text": "The following table provides a list of other objects which we use frequently in our applications. For a more detail, you can refer to the official documentation." }, { "code": null, "e": 95477, "s": 95428, "text": " Used to print information on stdout and stderr." }, { "code": null, "e": 95577, "s": 95477, "text": "Used to get information on current process. Provides multiple events related to process activities." }, { "code": null, "e": 95747, "s": 95577, "text": "There are several utility modules available in Node.js module library. These modules are very common and are frequently used while developing any Node based application." }, { "code": null, "e": 95806, "s": 95747, "text": "Provides basic operating-system related utility functions." }, { "code": null, "e": 95867, "s": 95806, "text": "Provides utilities for handling and transforming file paths." }, { "code": null, "e": 95940, "s": 95867, "text": "Provides both servers and clients as streams. Acts as a network wrapper." }, { "code": null, "e": 96062, "s": 95940, "text": "Provides functions to do actual DNS lookup as well as to use underlying operating system name resolution functionalities." }, { "code": null, "e": 96139, "s": 96062, "text": "Provides ways to handle multiple different I/O operations as a single group." }, { "code": null, "e": 96389, "s": 96139, "text": "A Web Server is a software application which handles HTTP requests sent by the HTTP client, like web browsers, and returns web pages in response to the clients. Web servers usually deliver html documents along with images, style sheets, and scripts." }, { "code": null, "e": 96648, "s": 96389, "text": "Most of the web servers support server-side scripts, using scripting languages or redirecting the task to an application server which retrieves data from a database and performs complex logic and then sends a result to the HTTP client through the Web server." }, { "code": null, "e": 96742, "s": 96648, "text": "Apache web server is one of the most commonly used web servers. It is an open source project." }, { "code": null, "e": 96798, "s": 96742, "text": "A Web application is usually divided into four layers −" }, { "code": null, "e": 96924, "s": 96798, "text": "Client − This layer consists of web browsers, mobile browsers or applications which can make HTTP requests to the web server." }, { "code": null, "e": 97050, "s": 96924, "text": "Client − This layer consists of web browsers, mobile browsers or applications which can make HTTP requests to the web server." }, { "code": null, "e": 97170, "s": 97050, "text": "Server − This layer has the Web server which can intercept the requests made by the clients and pass them the response." }, { "code": null, "e": 97290, "s": 97170, "text": "Server − This layer has the Web server which can intercept the requests made by the clients and pass them the response." }, { "code": null, "e": 97496, "s": 97290, "text": "Business − This layer contains the application server which is utilized by the web server to do the required processing. This layer interacts with the data layer via the database or some external programs." }, { "code": null, "e": 97702, "s": 97496, "text": "Business − This layer contains the application server which is utilized by the web server to do the required processing. This layer interacts with the data layer via the database or some external programs." }, { "code": null, "e": 97772, "s": 97702, "text": "Data − This layer contains the databases or any other source of data." }, { "code": null, "e": 97842, "s": 97772, "text": "Data − This layer contains the databases or any other source of data." }, { "code": null, "e": 98017, "s": 97842, "text": "Node.js provides an http module which can be used to create an HTTP client of a server. Following is the bare minimum structure of the HTTP server which listens at 8081 port." }, { "code": null, "e": 98052, "s": 98017, "text": "Create a js file named server.js −" }, { "code": null, "e": 98068, "s": 98052, "text": "File: server.js" }, { "code": null, "e": 99230, "s": 98068, "text": "var http = require('http');\nvar fs = require('fs');\nvar url = require('url');\n\n// Create a server\nhttp.createServer( function (request, response) { \n // Parse the request containing file name\n var pathname = url.parse(request.url).pathname;\n \n // Print the name of the file for which request is made.\n console.log(\"Request for \" + pathname + \" received.\");\n \n // Read the requested file content from file system\n fs.readFile(pathname.substr(1), function (err, data) {\n if (err) {\n console.log(err);\n \n // HTTP Status: 404 : NOT FOUND\n // Content Type: text/plain\n response.writeHead(404, {'Content-Type': 'text/html'});\n } else {\t\n //Page found\t \n // HTTP Status: 200 : OK\n // Content Type: text/plain\n response.writeHead(200, {'Content-Type': 'text/html'});\t\n \n // Write the content of the file to response body\n response.write(data.toString());\t\t\n }\n \n // Send the response body \n response.end();\n }); \n}).listen(8081);\n\n// Console will print the message\nconsole.log('Server running at http://127.0.0.1:8081/');" }, { "code": null, "e": 99339, "s": 99230, "text": "Next let's create the following html file named index.htm in the same directory where you created server.js." }, { "code": null, "e": 99355, "s": 99339, "text": "File: index.htm" }, { "code": null, "e": 99468, "s": 99355, "text": "<html>\n <head>\n <title>Sample Page</title>\n </head>\n \n <body>\n Hello World!\n </body>\n</html>" }, { "code": null, "e": 99517, "s": 99468, "text": "Now let us run the server.js to see the result −" }, { "code": null, "e": 99535, "s": 99517, "text": "$ node server.js\n" }, { "code": null, "e": 99554, "s": 99535, "text": "Verify the Output." }, { "code": null, "e": 99596, "s": 99554, "text": "Server running at http://127.0.0.1:8081/\n" }, { "code": null, "e": 99677, "s": 99596, "text": "Open http://127.0.0.1:8081/index.htm in any browser to see the following result." }, { "code": null, "e": 99710, "s": 99677, "text": "Verify the Output at server end." }, { "code": null, "e": 99785, "s": 99710, "text": "Server running at http://127.0.0.1:8081/\nRequest for /index.htm received.\n" }, { "code": null, "e": 99867, "s": 99785, "text": "A web client can be created using http module. Let's check the following example." }, { "code": null, "e": 99902, "s": 99867, "text": "Create a js file named client.js −" }, { "code": null, "e": 99918, "s": 99902, "text": "File: client.js" }, { "code": null, "e": 100473, "s": 99918, "text": "var http = require('http');\n\n// Options to be used by request \nvar options = {\n host: 'localhost',\n port: '8081',\n path: '/index.htm' \n};\n\n// Callback function is used to deal with response\nvar callback = function(response) {\n // Continuously update stream with data\n var body = '';\n response.on('data', function(data) {\n body += data;\n });\n \n response.on('end', function() {\n // Data received completely.\n console.log(body);\n });\n}\n// Make a request to the server\nvar req = http.request(options, callback);\nreq.end();" }, { "code": null, "e": 100570, "s": 100473, "text": "Now run the client.js from a different command terminal other than server.js to see the result −" }, { "code": null, "e": 100588, "s": 100570, "text": "$ node client.js\n" }, { "code": null, "e": 100607, "s": 100588, "text": "Verify the Output." }, { "code": null, "e": 100721, "s": 100607, "text": "<html>\n <head>\n <title>Sample Page</title>\n </head>\n \n <body>\n Hello World!\n </body>\n</html>\n" }, { "code": null, "e": 100754, "s": 100721, "text": "Verify the Output at server end." }, { "code": null, "e": 100829, "s": 100754, "text": "Server running at http://127.0.0.1:8081/\nRequest for /index.htm received.\n" }, { "code": null, "e": 101108, "s": 100829, "text": "Express is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications. It facilitates the rapid development of Node based Web applications. Following are some of the core features of Express framework −" }, { "code": null, "e": 101166, "s": 101108, "text": "Allows to set up middlewares to respond to HTTP Requests." }, { "code": null, "e": 101224, "s": 101166, "text": "Allows to set up middlewares to respond to HTTP Requests." }, { "code": null, "e": 101321, "s": 101224, "text": "Defines a routing table which is used to perform different actions based on HTTP Method and URL." }, { "code": null, "e": 101418, "s": 101321, "text": "Defines a routing table which is used to perform different actions based on HTTP Method and URL." }, { "code": null, "e": 101499, "s": 101418, "text": "Allows to dynamically render HTML Pages based on passing arguments to templates." }, { "code": null, "e": 101580, "s": 101499, "text": "Allows to dynamically render HTML Pages based on passing arguments to templates." }, { "code": null, "e": 101710, "s": 101580, "text": "Firstly, install the Express framework globally using NPM so that it can be used to create a web application using node terminal." }, { "code": null, "e": 101740, "s": 101710, "text": "$ npm install express --save\n" }, { "code": null, "e": 101944, "s": 101740, "text": "The above command saves the installation locally in the node_modules directory and creates a directory express inside node_modules. You should install the following important modules along with express −" }, { "code": null, "e": 102043, "s": 101944, "text": "body-parser − This is a node.js middleware for handling JSON, Raw, Text and URL encoded form data." }, { "code": null, "e": 102142, "s": 102043, "text": "body-parser − This is a node.js middleware for handling JSON, Raw, Text and URL encoded form data." }, { "code": null, "e": 102245, "s": 102142, "text": "cookie-parser − Parse Cookie header and populate req.cookies with an object keyed by the cookie names." }, { "code": null, "e": 102348, "s": 102245, "text": "cookie-parser − Parse Cookie header and populate req.cookies with an object keyed by the cookie names." }, { "code": null, "e": 102420, "s": 102348, "text": "multer − This is a node.js middleware for handling multipart/form-data." }, { "code": null, "e": 102492, "s": 102420, "text": "multer − This is a node.js middleware for handling multipart/form-data." }, { "code": null, "e": 102589, "s": 102492, "text": "$ npm install body-parser --save\n$ npm install cookie-parser --save\n$ npm install multer --save\n" }, { "code": null, "e": 102816, "s": 102589, "text": "Following is a very basic Express app which starts a server and listens on port 8081 for connection. This app responds with Hello World! for requests to the homepage. For every other path, it will respond with a 404 Not Found." }, { "code": null, "e": 103133, "s": 102816, "text": "var express = require('express');\nvar app = express();\n\napp.get('/', function (req, res) {\n res.send('Hello World');\n})\n\nvar server = app.listen(8081, function () {\n var host = server.address().address\n var port = server.address().port\n \n console.log(\"Example app listening at http://%s:%s\", host, port)\n})" }, { "code": null, "e": 103218, "s": 103133, "text": "Save the above code in a file named server.js and run it with the following command." }, { "code": null, "e": 103236, "s": 103218, "text": "$ node server.js\n" }, { "code": null, "e": 103272, "s": 103236, "text": "You will see the following output −" }, { "code": null, "e": 103318, "s": 103272, "text": "Example app listening at http://0.0.0.0:8081\n" }, { "code": null, "e": 103390, "s": 103318, "text": "Open http://127.0.0.1:8081/ in any browser to see the following result." }, { "code": null, "e": 103486, "s": 103390, "text": "Express application uses a callback function whose parameters are request and response objects." }, { "code": null, "e": 103534, "s": 103486, "text": "app.get('/', function (req, res) {\n // --\n})\n" }, { "code": null, "e": 103690, "s": 103534, "text": "Request Object − The request object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on." }, { "code": null, "e": 103846, "s": 103690, "text": "Request Object − The request object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on." }, { "code": null, "e": 103969, "s": 103846, "text": "Response Object − The response object represents the HTTP response that an Express app sends when it gets an HTTP request." }, { "code": null, "e": 104092, "s": 103969, "text": "Response Object − The response object represents the HTTP response that an Express app sends when it gets an HTTP request." }, { "code": null, "e": 104237, "s": 104092, "text": "You can print req and res objects which provide a lot of information related to HTTP request and response including cookies, sessions, URL, etc." }, { "code": null, "e": 104502, "s": 104237, "text": "We have seen a basic application which serves HTTP request for the homepage. Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on)." }, { "code": null, "e": 104580, "s": 104502, "text": "We will extend our Hello World program to handle more types of HTTP requests." }, { "code": null, "e": 105744, "s": 104580, "text": "var express = require('express');\nvar app = express();\n\n// This responds with \"Hello World\" on the homepage\napp.get('/', function (req, res) {\n console.log(\"Got a GET request for the homepage\");\n res.send('Hello GET');\n})\n\n// This responds a POST request for the homepage\napp.post('/', function (req, res) {\n console.log(\"Got a POST request for the homepage\");\n res.send('Hello POST');\n})\n\n// This responds a DELETE request for the /del_user page.\napp.delete('/del_user', function (req, res) {\n console.log(\"Got a DELETE request for /del_user\");\n res.send('Hello DELETE');\n})\n\n// This responds a GET request for the /list_user page.\napp.get('/list_user', function (req, res) {\n console.log(\"Got a GET request for /list_user\");\n res.send('Page Listing');\n})\n\n// This responds a GET request for abcd, abxcd, ab123cd, and so on\napp.get('/ab*cd', function(req, res) { \n console.log(\"Got a GET request for /ab*cd\");\n res.send('Page Pattern Match');\n})\n\nvar server = app.listen(8081, function () {\n var host = server.address().address\n var port = server.address().port\n \n console.log(\"Example app listening at http://%s:%s\", host, port)\n})" }, { "code": null, "e": 105829, "s": 105744, "text": "Save the above code in a file named server.js and run it with the following command." }, { "code": null, "e": 105847, "s": 105829, "text": "$ node server.js\n" }, { "code": null, "e": 105883, "s": 105847, "text": "You will see the following output −" }, { "code": null, "e": 105929, "s": 105883, "text": "Example app listening at http://0.0.0.0:8081\n" }, { "code": null, "e": 106113, "s": 105929, "text": "Now you can try different requests at http://127.0.0.1:8081 to see the output generated by server.js. Following are a few screens shots showing different responses for different URLs." }, { "code": null, "e": 106166, "s": 106113, "text": "Screen showing again http://127.0.0.1:8081/list_user" }, { "code": null, "e": 106214, "s": 106166, "text": "Screen showing again http://127.0.0.1:8081/abcd" }, { "code": null, "e": 106265, "s": 106214, "text": "Screen showing again http://127.0.0.1:8081/abcdefg" }, { "code": null, "e": 106380, "s": 106265, "text": "Express provides a built-in middleware express.static to serve static files, such as images, CSS, JavaScript, etc." }, { "code": null, "e": 106646, "s": 106380, "text": "You simply need to pass the name of the directory where you keep your static assets, to the express.static middleware to start serving the files directly. For example, if you keep your images, CSS, and JavaScript files in a directory named public, you can do this −" }, { "code": null, "e": 106682, "s": 106646, "text": "app.use(express.static('public'));\n" }, { "code": null, "e": 106752, "s": 106682, "text": "We will keep a few images in public/images sub-directory as follows −" }, { "code": null, "e": 106821, "s": 106752, "text": "node_modules\nserver.js\npublic/\npublic/images\npublic/images/logo.png\n" }, { "code": null, "e": 106900, "s": 106821, "text": "Let's modify \"Hello Word\" app to add the functionality to handle static files." }, { "code": null, "e": 107250, "s": 106900, "text": "var express = require('express');\nvar app = express();\n\napp.use(express.static('public'));\n\napp.get('/', function (req, res) {\n res.send('Hello World');\n})\n\nvar server = app.listen(8081, function () {\n var host = server.address().address\n var port = server.address().port\n\n console.log(\"Example app listening at http://%s:%s\", host, port)\n})" }, { "code": null, "e": 107335, "s": 107250, "text": "Save the above code in a file named server.js and run it with the following command." }, { "code": null, "e": 107353, "s": 107335, "text": "$ node server.js\n" }, { "code": null, "e": 107449, "s": 107353, "text": "Now open http://127.0.0.1:8081/images/logo.png in any browser and see observe following result." }, { "code": null, "e": 107604, "s": 107449, "text": "Here is a simple example which passes two values using HTML FORM GET method. We are going to use process_get router inside server.js to handle this input." }, { "code": null, "e": 107921, "s": 107604, "text": "<html>\n <body>\n \n <form action = \"http://127.0.0.1:8081/process_get\" method = \"GET\">\n First Name: <input type = \"text\" name = \"first_name\"> <br>\n Last Name: <input type = \"text\" name = \"last_name\">\n <input type = \"submit\" value = \"Submit\">\n </form>\n \n </body>\n</html>" }, { "code": null, "e": 108050, "s": 107921, "text": "Let's save above code in index.htm and modify server.js to handle home page requests as well as the input sent by the HTML form." }, { "code": null, "e": 108680, "s": 108050, "text": "var express = require('express');\nvar app = express();\n\napp.use(express.static('public'));\napp.get('/index.htm', function (req, res) {\n res.sendFile( __dirname + \"/\" + \"index.htm\" );\n})\n\napp.get('/process_get', function (req, res) {\n // Prepare output in JSON format\n response = {\n first_name:req.query.first_name,\n last_name:req.query.last_name\n };\n console.log(response);\n res.end(JSON.stringify(response));\n})\n\nvar server = app.listen(8081, function () {\n var host = server.address().address\n var port = server.address().port\n \n console.log(\"Example app listening at http://%s:%s\", host, port)\n})" }, { "code": null, "e": 108781, "s": 108680, "text": "Accessing the HTML document using http://127.0.0.1:8081/index.htm will generate the following form −" }, { "code": null, "e": 108818, "s": 108781, "text": "\n\n\nFirst Name:\n\n\n\nLast Name:\n\n\n\n\n\n\n\n" }, { "code": null, "e": 108951, "s": 108818, "text": "Now you can enter the First and Last Name and then click submit button to see the result and it should return the following result −" }, { "code": null, "e": 108993, "s": 108951, "text": "{\"first_name\":\"John\",\"last_name\":\"Paul\"}\n" }, { "code": null, "e": 109149, "s": 108993, "text": "Here is a simple example which passes two values using HTML FORM POST method. We are going to use process_get router inside server.js to handle this input." }, { "code": null, "e": 109467, "s": 109149, "text": "<html>\n <body>\n \n <form action = \"http://127.0.0.1:8081/process_post\" method = \"POST\">\n First Name: <input type = \"text\" name = \"first_name\"> <br>\n Last Name: <input type = \"text\" name = \"last_name\">\n <input type = \"submit\" value = \"Submit\">\n </form>\n \n </body>\n</html>" }, { "code": null, "e": 109600, "s": 109467, "text": "Let's save the above code in index.htm and modify server.js to handle home page requests as well as the input sent by the HTML form." }, { "code": null, "e": 110407, "s": 109600, "text": "var express = require('express');\nvar app = express();\nvar bodyParser = require('body-parser');\n\n// Create application/x-www-form-urlencoded parser\nvar urlencodedParser = bodyParser.urlencoded({ extended: false })\n\napp.use(express.static('public'));\napp.get('/index.htm', function (req, res) {\n res.sendFile( __dirname + \"/\" + \"index.htm\" );\n})\n\napp.post('/process_post', urlencodedParser, function (req, res) {\n // Prepare output in JSON format\n response = {\n first_name:req.body.first_name,\n last_name:req.body.last_name\n };\n console.log(response);\n res.end(JSON.stringify(response));\n})\n\nvar server = app.listen(8081, function () {\n var host = server.address().address\n var port = server.address().port\n \n console.log(\"Example app listening at http://%s:%s\", host, port)\n})" }, { "code": null, "e": 110508, "s": 110407, "text": "Accessing the HTML document using http://127.0.0.1:8081/index.htm will generate the following form −" }, { "code": null, "e": 110545, "s": 110508, "text": "\n\n\nFirst Name:\n\n\n\nLast Name:\n\n\n\n\n\n\n\n" }, { "code": null, "e": 110650, "s": 110545, "text": "Now you can enter the First and Last Name and then click the submit button to see the following result −" }, { "code": null, "e": 110692, "s": 110650, "text": "{\"first_name\":\"John\",\"last_name\":\"Paul\"}\n" }, { "code": null, "e": 110841, "s": 110692, "text": "The following HTML code creates a file uploader form. This form has method attribute set to POST and enctype attribute is set to multipart/form-data" }, { "code": null, "e": 111276, "s": 110841, "text": "<html>\n <head>\n <title>File Uploading Form</title>\n </head>\n\n <body>\n <h3>File Upload:</h3>\n Select a file to upload: <br />\n \n <form action = \"http://127.0.0.1:8081/file_upload\" method = \"POST\" \n enctype = \"multipart/form-data\">\n <input type=\"file\" name=\"file\" size=\"50\" />\n <br />\n <input type = \"submit\" value = \"Upload File\" />\n </form>\n \n </body>\n</html>" }, { "code": null, "e": 111385, "s": 111276, "text": "Let's save above code in index.htm and modify server.js to handle home page requests as well as file upload." }, { "code": null, "e": 112629, "s": 111385, "text": "var express = require('express');\nvar app = express();\nvar fs = require(\"fs\");\n\nvar bodyParser = require('body-parser');\nvar multer = require('multer');\n\napp.use(express.static('public'));\napp.use(bodyParser.urlencoded({ extended: false }));\napp.use(multer({ dest: '/tmp/'}));\n\napp.get('/index.htm', function (req, res) {\n res.sendFile( __dirname + \"/\" + \"index.htm\" );\n})\n\napp.post('/file_upload', function (req, res) {\n console.log(req.files.file.name);\n console.log(req.files.file.path);\n console.log(req.files.file.type);\n var file = __dirname + \"/\" + req.files.file.name;\n \n fs.readFile( req.files.file.path, function (err, data) {\n fs.writeFile(file, data, function (err) {\n if( err ) {\n console.log( err );\n } else {\n response = {\n message:'File uploaded successfully',\n filename:req.files.file.name\n };\n }\n \n console.log( response );\n res.end( JSON.stringify( response ) );\n });\n });\n})\n\nvar server = app.listen(8081, function () {\n var host = server.address().address\n var port = server.address().port\n \n console.log(\"Example app listening at http://%s:%s\", host, port)\n})" }, { "code": null, "e": 112730, "s": 112629, "text": "Accessing the HTML document using http://127.0.0.1:8081/index.htm will generate the following form −" }, { "code": null, "e": 112856, "s": 112730, "text": "File Upload:\nSelect a file to upload: \n\n\n\nNOTE: This is just dummy form and would not work, but it must work at your server.\n" }, { "code": null, "e": 113037, "s": 112856, "text": "You can send cookies to a Node.js server which can handle the same using the following middleware option. Following is a simple example to print all the cookies sent by the client." }, { "code": null, "e": 113260, "s": 113037, "text": "var express = require('express')\nvar cookieParser = require('cookie-parser')\n\nvar app = express()\napp.use(cookieParser())\n\napp.get('/', function(req, res) {\n console.log(\"Cookies: \", req.cookies)\n})\napp.listen(8081)" }, { "code": null, "e": 113567, "s": 113260, "text": "REST stands for REpresentational State Transfer. REST is web standards based architecture and uses HTTP Protocol. It revolves around resource where every component is a resource and a resource is accessed by a common interface using HTTP standard methods. REST was first introduced by Roy Fielding in 2000." }, { "code": null, "e": 113856, "s": 113567, "text": "A REST Server simply provides access to resources and REST client accesses and modifies the resources using HTTP protocol. Here each resource is identified by URIs/ global IDs. REST uses various representation to represent a resource like text, JSON, XML but JSON is the most popular one." }, { "code": null, "e": 113930, "s": 113856, "text": "Following four HTTP methods are commonly used in REST based architecture." }, { "code": null, "e": 113994, "s": 113930, "text": "GET − This is used to provide a read only access to a resource." }, { "code": null, "e": 114058, "s": 113994, "text": "GET − This is used to provide a read only access to a resource." }, { "code": null, "e": 114103, "s": 114058, "text": "PUT − This is used to create a new resource." }, { "code": null, "e": 114148, "s": 114103, "text": "PUT − This is used to create a new resource." }, { "code": null, "e": 114192, "s": 114148, "text": "DELETE − This is used to remove a resource." }, { "code": null, "e": 114236, "s": 114192, "text": "DELETE − This is used to remove a resource." }, { "code": null, "e": 114312, "s": 114236, "text": "POST − This is used to update a existing resource or create a new resource." }, { "code": null, "e": 114388, "s": 114312, "text": "POST − This is used to update a existing resource or create a new resource." }, { "code": null, "e": 114896, "s": 114388, "text": "A web service is a collection of open protocols and standards used for exchanging data between applications or systems. Software applications written in various programming languages and running on various platforms can use web services to exchange data over computer networks like the Internet in a manner similar to inter-process communication on a single computer. This interoperability (e.g., communication between Java and Python, or Windows and Linux applications) is due to the use of open standards." }, { "code": null, "e": 115215, "s": 114896, "text": "Web services based on REST Architecture are known as RESTful web services. These webservices uses HTTP methods to implement the concept of REST architecture. A RESTful web service usually defines a URI, Uniform Resource Identifier a service, which provides resource representation such as JSON and set of HTTP Methods." }, { "code": null, "e": 115312, "s": 115215, "text": "Consider we have a JSON based database of users having the following users in a file users.json:" }, { "code": null, "e": 115695, "s": 115312, "text": "{\n \"user1\" : {\n \"name\" : \"mahesh\",\n \"password\" : \"password1\",\n \"profession\" : \"teacher\",\n \"id\": 1\n },\n \n \"user2\" : {\n \"name\" : \"suresh\",\n \"password\" : \"password2\",\n \"profession\" : \"librarian\",\n \"id\": 2\n },\n \n \"user3\" : {\n \"name\" : \"ramesh\",\n \"password\" : \"password3\",\n \"profession\" : \"clerk\",\n \"id\": 3\n }\n}" }, { "code": null, "e": 115769, "s": 115695, "text": "Based on this information we are going to provide following RESTful APIs." }, { "code": null, "e": 115990, "s": 115769, "text": "I'm keeping most of the part of all the examples in the form of hard coding assuming you already know how to pass values from front end using Ajax or simple form data and how to process them using express Request object." }, { "code": null, "e": 116085, "s": 115990, "text": "Let's implement our first RESTful API listUsers using the following code in a server.js file −" }, { "code": null, "e": 116095, "s": 116085, "text": "server.js" }, { "code": null, "e": 116549, "s": 116095, "text": "var express = require('express');\nvar app = express();\nvar fs = require(\"fs\");\n\napp.get('/listUsers', function (req, res) {\n fs.readFile( __dirname + \"/\" + \"users.json\", 'utf8', function (err, data) {\n console.log( data );\n res.end( data );\n });\n})\n\nvar server = app.listen(8081, function () {\n var host = server.address().address\n var port = server.address().port\n console.log(\"Example app listening at http://%s:%s\", host, port)\n})" }, { "code": null, "e": 116724, "s": 116549, "text": "Now try to access defined API using URL: http://127.0.0.1:8081/listUsers and HTTP Method : GET on local machine using any REST client. This should produce following result −" }, { "code": null, "e": 116814, "s": 116724, "text": "You can change given IP address when you will put the solution in production environment." }, { "code": null, "e": 117197, "s": 116814, "text": "{\n \"user1\" : {\n \"name\" : \"mahesh\",\n \"password\" : \"password1\",\n \"profession\" : \"teacher\",\n \"id\": 1\n },\n \n \"user2\" : {\n \"name\" : \"suresh\",\n \"password\" : \"password2\",\n \"profession\" : \"librarian\",\n \"id\": 2\n },\n \n \"user3\" : {\n \"name\" : \"ramesh\",\n \"password\" : \"password3\",\n \"profession\" : \"clerk\",\n \"id\": 3\n }\n}" }, { "code": null, "e": 117300, "s": 117197, "text": "Following API will show you how to add new user in the list. Following is the detail of the new user −" }, { "code": null, "e": 117433, "s": 117300, "text": "user = {\n \"user4\" : {\n \"name\" : \"mohit\",\n \"password\" : \"password4\",\n \"profession\" : \"teacher\",\n \"id\": 4\n }\n}" }, { "code": null, "e": 117626, "s": 117433, "text": "You can accept the same input in the form of JSON using Ajax call but for teaching point of view, we are making it hard coded here. Following is the addUser API to a new user in the database −" }, { "code": null, "e": 117636, "s": 117626, "text": "server.js" }, { "code": null, "e": 118345, "s": 117636, "text": "var express = require('express');\nvar app = express();\nvar fs = require(\"fs\");\n\nvar user = {\n \"user4\" : {\n \"name\" : \"mohit\",\n \"password\" : \"password4\",\n \"profession\" : \"teacher\",\n \"id\": 4\n }\n}\n\napp.post('/addUser', function (req, res) {\n // First read existing users.\n fs.readFile( __dirname + \"/\" + \"users.json\", 'utf8', function (err, data) {\n data = JSON.parse( data );\n data[\"user4\"] = user[\"user4\"];\n console.log( data );\n res.end( JSON.stringify(data));\n });\n})\n\nvar server = app.listen(8081, function () {\n var host = server.address().address\n var port = server.address().port\n console.log(\"Example app listening at http://%s:%s\", host, port)\n})" }, { "code": null, "e": 118519, "s": 118345, "text": "Now try to access defined API using URL: http://127.0.0.1:8081/addUser and HTTP Method : POST on local machine using any REST client. This should produce following result −" }, { "code": null, "e": 118853, "s": 118519, "text": "{\n \"user1\":{\"name\":\"mahesh\",\"password\":\"password1\",\"profession\":\"teacher\",\"id\":1},\n \"user2\":{\"name\":\"suresh\",\"password\":\"password2\",\"profession\":\"librarian\",\"id\":2},\n \"user3\":{\"name\":\"ramesh\",\"password\":\"password3\",\"profession\":\"clerk\",\"id\":3},\n \"user4\":{\"name\":\"mohit\",\"password\":\"password4\",\"profession\":\"teacher\",\"id\":4}\n}" }, { "code": null, "e": 118975, "s": 118853, "text": "Now we will implement an API which will be called using user ID and it will display the detail of the corresponding user." }, { "code": null, "e": 118985, "s": 118975, "text": "server.js" }, { "code": null, "e": 119567, "s": 118985, "text": "var express = require('express');\nvar app = express();\nvar fs = require(\"fs\");\n\napp.get('/:id', function (req, res) {\n // First read existing users.\n fs.readFile( __dirname + \"/\" + \"users.json\", 'utf8', function (err, data) {\n var users = JSON.parse( data );\n var user = users[\"user\" + req.params.id] \n console.log( user );\n res.end( JSON.stringify(user));\n });\n})\n\nvar server = app.listen(8081, function () {\n var host = server.address().address\n var port = server.address().port\n console.log(\"Example app listening at http://%s:%s\", host, port)\n})" }, { "code": null, "e": 119733, "s": 119567, "text": "Now try to access defined API using URL: http://127.0.0.1:8081/2 and HTTP Method : GET on local machine using any REST client. This should produce following result −" }, { "code": null, "e": 119807, "s": 119733, "text": "{\"name\":\"suresh\",\"password\":\"password2\",\"profession\":\"librarian\",\"id\":2}\n" }, { "code": null, "e": 120033, "s": 119807, "text": "This API is very similar to addUser API where we receive input data through req.body and then based on user ID we delete that user from the database. To keep our program simple we assume we are going to delete user with ID 2." }, { "code": null, "e": 120043, "s": 120033, "text": "server.js" }, { "code": null, "e": 120634, "s": 120043, "text": "var express = require('express');\nvar app = express();\nvar fs = require(\"fs\");\n\nvar id = 2;\n\napp.delete('/deleteUser', function (req, res) {\n // First read existing users.\n fs.readFile( __dirname + \"/\" + \"users.json\", 'utf8', function (err, data) {\n data = JSON.parse( data );\n delete data[\"user\" + 2];\n \n console.log( data );\n res.end( JSON.stringify(data));\n });\n})\n\nvar server = app.listen(8081, function () {\n var host = server.address().address\n var port = server.address().port\n console.log(\"Example app listening at http://%s:%s\", host, port)\n})" }, { "code": null, "e": 120812, "s": 120634, "text": "Now try to access defined API using URL: http://127.0.0.1:8081/deleteUser and HTTP Method : DELETE on local machine using any REST client. This should produce following result −" }, { "code": null, "e": 120972, "s": 120812, "text": "{\"user1\":{\"name\":\"mahesh\",\"password\":\"password1\",\"profession\":\"teacher\",\"id\":1},\n\"user3\":{\"name\":\"ramesh\",\"password\":\"password3\",\"profession\":\"clerk\",\"id\":3}}\n" }, { "code": null, "e": 121183, "s": 120972, "text": "Node.js runs in a single-thread mode, but it uses an event-driven paradigm to handle concurrency. It also facilitates creation of child processes to leverage parallel processing on multi-core CPU based systems." }, { "code": null, "e": 121335, "s": 121183, "text": "Child processes always have three streams child.stdin, child.stdout, and child.stderr which may be shared with the stdio streams of the parent process." }, { "code": null, "e": 121438, "s": 121335, "text": "Node provides child_process module which has the following three major ways to create a child process." }, { "code": null, "e": 121529, "s": 121438, "text": "exec − child_process.exec method runs a command in a shell/console and buffers the output." }, { "code": null, "e": 121620, "s": 121529, "text": "exec − child_process.exec method runs a command in a shell/console and buffers the output." }, { "code": null, "e": 121693, "s": 121620, "text": "spawn − child_process.spawn launches a new process with a given command." }, { "code": null, "e": 121766, "s": 121693, "text": "spawn − child_process.spawn launches a new process with a given command." }, { "code": null, "e": 121863, "s": 121766, "text": "fork − The child_process.fork method is a special case of the spawn() to create child processes." }, { "code": null, "e": 121960, "s": 121863, "text": "fork − The child_process.fork method is a special case of the spawn() to create child processes." }, { "code": null, "e": 122069, "s": 121960, "text": "child_process.exec method runs a command in a shell and buffers the output. It has the following signature −" }, { "code": null, "e": 122119, "s": 122069, "text": "child_process.exec(command[, options], callback)\n" }, { "code": null, "e": 122168, "s": 122119, "text": "Here is the description of the parameters used −" }, { "code": null, "e": 122236, "s": 122168, "text": "command (String) The command to run, with space-separated arguments" }, { "code": null, "e": 122304, "s": 122236, "text": "command (String) The command to run, with space-separated arguments" }, { "code": null, "e": 122969, "s": 122304, "text": "options (Object) may comprise one or more of the following options −\n\ncwd (String) Current working directory of the child process\nenv (Object) Environment key-value pairs\nencoding (String) (Default: 'utf8')\nshell (String) Shell to execute the command with (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should understand the -c switch on UNIX or /s /c on Windows. On Windows, command line parsing should be compatible with cmd.exe.)\ntimeout (Number) (Default: 0)\nmaxBuffer (Number) (Default: 200*1024)\nkillSignal (String) (Default: 'SIGTERM')\nuid (Number) Sets the user identity of the process. \ngid (Number) Sets the group identity of the process.\n\n" }, { "code": null, "e": 123038, "s": 122969, "text": "options (Object) may comprise one or more of the following options −" }, { "code": null, "e": 123098, "s": 123038, "text": "cwd (String) Current working directory of the child process" }, { "code": null, "e": 123158, "s": 123098, "text": "cwd (String) Current working directory of the child process" }, { "code": null, "e": 123199, "s": 123158, "text": "env (Object) Environment key-value pairs" }, { "code": null, "e": 123240, "s": 123199, "text": "env (Object) Environment key-value pairs" }, { "code": null, "e": 123276, "s": 123240, "text": "encoding (String) (Default: 'utf8')" }, { "code": null, "e": 123312, "s": 123276, "text": "encoding (String) (Default: 'utf8')" }, { "code": null, "e": 123552, "s": 123312, "text": "shell (String) Shell to execute the command with (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should understand the -c switch on UNIX or /s /c on Windows. On Windows, command line parsing should be compatible with cmd.exe.)" }, { "code": null, "e": 123792, "s": 123552, "text": "shell (String) Shell to execute the command with (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should understand the -c switch on UNIX or /s /c on Windows. On Windows, command line parsing should be compatible with cmd.exe.)" }, { "code": null, "e": 123822, "s": 123792, "text": "timeout (Number) (Default: 0)" }, { "code": null, "e": 123852, "s": 123822, "text": "timeout (Number) (Default: 0)" }, { "code": null, "e": 123891, "s": 123852, "text": "maxBuffer (Number) (Default: 200*1024)" }, { "code": null, "e": 123930, "s": 123891, "text": "maxBuffer (Number) (Default: 200*1024)" }, { "code": null, "e": 123971, "s": 123930, "text": "killSignal (String) (Default: 'SIGTERM')" }, { "code": null, "e": 124012, "s": 123971, "text": "killSignal (String) (Default: 'SIGTERM')" }, { "code": null, "e": 124065, "s": 124012, "text": "uid (Number) Sets the user identity of the process. " }, { "code": null, "e": 124118, "s": 124065, "text": "uid (Number) Sets the user identity of the process. " }, { "code": null, "e": 124171, "s": 124118, "text": "gid (Number) Sets the group identity of the process." }, { "code": null, "e": 124224, "s": 124171, "text": "gid (Number) Sets the group identity of the process." }, { "code": null, "e": 124355, "s": 124224, "text": "callback The function gets three arguments error, stdout, and stderr which are called with the output when the process terminates." }, { "code": null, "e": 124486, "s": 124355, "text": "callback The function gets three arguments error, stdout, and stderr which are called with the output when the process terminates." }, { "code": null, "e": 124621, "s": 124486, "text": "The exec() method returns a buffer with a max size and waits for the process to end and tries to return all the buffered data at once." }, { "code": null, "e": 124682, "s": 124621, "text": "Let us create two js files named support.js and master.js −\n" }, { "code": null, "e": 124699, "s": 124682, "text": "File: support.js" }, { "code": null, "e": 124765, "s": 124699, "text": "console.log(\"Child Process \" + process.argv[2] + \" executed.\" );\n" }, { "code": null, "e": 124781, "s": 124765, "text": "File: master.js" }, { "code": null, "e": 125367, "s": 124781, "text": "const fs = require('fs');\nconst child_process = require('child_process');\n\nfor(var i=0; i<3; i++) {\n var workerProcess = child_process.exec('node support.js '+i,function \n (error, stdout, stderr) {\n \n if (error) {\n console.log(error.stack);\n console.log('Error code: '+error.code);\n console.log('Signal received: '+error.signal);\n }\n console.log('stdout: ' + stdout);\n console.log('stderr: ' + stderr);\n });\n\n workerProcess.on('exit', function (code) {\n console.log('Child process exited with exit code '+code);\n });\n}" }, { "code": null, "e": 125409, "s": 125367, "text": "Now run the master.js to see the result −" }, { "code": null, "e": 125427, "s": 125409, "text": "$ node master.js\n" }, { "code": null, "e": 125466, "s": 125427, "text": "Verify the Output. Server has started." }, { "code": null, "e": 125701, "s": 125466, "text": "Child process exited with exit code 0\nstdout: Child Process 1 executed.\n\nstderr:\nChild process exited with exit code 0\nstdout: Child Process 0 executed.\n\nstderr:\nChild process exited with exit code 0\nstdout: Child Process 2 executed.\n" }, { "code": null, "e": 125806, "s": 125701, "text": "child_process.spawn method launches a new process with a given command. It has the following signature −" }, { "code": null, "e": 125855, "s": 125806, "text": "child_process.spawn(command[, args][, options])\n" }, { "code": null, "e": 125904, "s": 125855, "text": "Here is the description of the parameters used −" }, { "code": null, "e": 125940, "s": 125904, "text": "command (String) The command to run" }, { "code": null, "e": 125976, "s": 125940, "text": "command (String) The command to run" }, { "code": null, "e": 126014, "s": 125976, "text": "args (Array) List of string arguments" }, { "code": null, "e": 126052, "s": 126014, "text": "args (Array) List of string arguments" }, { "code": null, "e": 126521, "s": 126052, "text": "options (Object) may comprise one or more of the following options −\n\ncwd (String) Current working directory of the child process.\nenv (Object) Environment key-value pairs.\nstdio (Array) String Child's stdio configuration.\ncustomFds (Array) Deprecated File descriptors for the child to use for stdio.\ndetached (Boolean) The child will be a process group leader.\nuid (Number) Sets the user identity of the process.\ngid (Number) Sets the group identity of the process.\n\n" }, { "code": null, "e": 126590, "s": 126521, "text": "options (Object) may comprise one or more of the following options −" }, { "code": null, "e": 126651, "s": 126590, "text": "cwd (String) Current working directory of the child process." }, { "code": null, "e": 126712, "s": 126651, "text": "cwd (String) Current working directory of the child process." }, { "code": null, "e": 126754, "s": 126712, "text": "env (Object) Environment key-value pairs." }, { "code": null, "e": 126796, "s": 126754, "text": "env (Object) Environment key-value pairs." }, { "code": null, "e": 126846, "s": 126796, "text": "stdio (Array) String Child's stdio configuration." }, { "code": null, "e": 126896, "s": 126846, "text": "stdio (Array) String Child's stdio configuration." }, { "code": null, "e": 126974, "s": 126896, "text": "customFds (Array) Deprecated File descriptors for the child to use for stdio." }, { "code": null, "e": 127052, "s": 126974, "text": "customFds (Array) Deprecated File descriptors for the child to use for stdio." }, { "code": null, "e": 127113, "s": 127052, "text": "detached (Boolean) The child will be a process group leader." }, { "code": null, "e": 127174, "s": 127113, "text": "detached (Boolean) The child will be a process group leader." }, { "code": null, "e": 127226, "s": 127174, "text": "uid (Number) Sets the user identity of the process." }, { "code": null, "e": 127278, "s": 127226, "text": "uid (Number) Sets the user identity of the process." }, { "code": null, "e": 127331, "s": 127278, "text": "gid (Number) Sets the group identity of the process." }, { "code": null, "e": 127384, "s": 127331, "text": "gid (Number) Sets the group identity of the process." }, { "code": null, "e": 127587, "s": 127384, "text": "The spawn() method returns streams (stdout &stderr) and it should be used when the process returns a volume amount of data. spawn() starts receiving the response as soon as the process starts executing." }, { "code": null, "e": 127640, "s": 127587, "text": "Create two js files named support.js and master.js −" }, { "code": null, "e": 127657, "s": 127640, "text": "File: support.js" }, { "code": null, "e": 127723, "s": 127657, "text": "console.log(\"Child Process \" + process.argv[2] + \" executed.\" );\n" }, { "code": null, "e": 127739, "s": 127723, "text": "File: master.js" }, { "code": null, "e": 128229, "s": 127739, "text": "const fs = require('fs');\nconst child_process = require('child_process');\n \nfor(var i = 0; i<3; i++) {\n var workerProcess = child_process.spawn('node', ['support.js', i]);\n\n workerProcess.stdout.on('data', function (data) {\n console.log('stdout: ' + data);\n });\n\n workerProcess.stderr.on('data', function (data) {\n console.log('stderr: ' + data);\n });\n\n workerProcess.on('close', function (code) {\n console.log('child process exited with code ' + code);\n });\n}" }, { "code": null, "e": 128271, "s": 128229, "text": "Now run the master.js to see the result −" }, { "code": null, "e": 128289, "s": 128271, "text": "$ node master.js\n" }, { "code": null, "e": 128327, "s": 128289, "text": "Verify the Output. Server has started" }, { "code": null, "e": 128532, "s": 128327, "text": "stdout: Child Process 0 executed.\n\nchild process exited with code 0\nstdout: Child Process 1 executed.\n\nstdout: Child Process 2 executed.\n\nchild process exited with code 0\nchild process exited with code 0\n" }, { "code": null, "e": 128646, "s": 128532, "text": "child_process.fork method is a special case of spawn() to create Node processes. It has the following signature −" }, { "code": null, "e": 128697, "s": 128646, "text": "child_process.fork(modulePath[, args][, options])\n" }, { "code": null, "e": 128746, "s": 128697, "text": "Here is the description of the parameters used −" }, { "code": null, "e": 128798, "s": 128746, "text": "modulePath (String) The module to run in the child." }, { "code": null, "e": 128850, "s": 128798, "text": "modulePath (String) The module to run in the child." }, { "code": null, "e": 128888, "s": 128850, "text": "args (Array) List of string arguments" }, { "code": null, "e": 128926, "s": 128888, "text": "args (Array) List of string arguments" }, { "code": null, "e": 129604, "s": 128926, "text": "options (Object) may comprise one or more of the following options −\n\ncwd (String) Current working directory of the child process.\nenv (Object) Environment key-value pairs.\nexecPath (String) Executable used to create the child process.\nexecArgv (Array) List of string arguments passed to the executable (Default: process.execArgv).\nsilent (Boolean) If true, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent, see the \"pipe\" and \"inherit\" options for spawn()'s stdio for more details (default is false).\nuid (Number) Sets the user identity of the process. \ngid (Number) Sets the group identity of the process.\n\n" }, { "code": null, "e": 129673, "s": 129604, "text": "options (Object) may comprise one or more of the following options −" }, { "code": null, "e": 129734, "s": 129673, "text": "cwd (String) Current working directory of the child process." }, { "code": null, "e": 129795, "s": 129734, "text": "cwd (String) Current working directory of the child process." }, { "code": null, "e": 129837, "s": 129795, "text": "env (Object) Environment key-value pairs." }, { "code": null, "e": 129879, "s": 129837, "text": "env (Object) Environment key-value pairs." }, { "code": null, "e": 129942, "s": 129879, "text": "execPath (String) Executable used to create the child process." }, { "code": null, "e": 130005, "s": 129942, "text": "execPath (String) Executable used to create the child process." }, { "code": null, "e": 130101, "s": 130005, "text": "execArgv (Array) List of string arguments passed to the executable (Default: process.execArgv)." }, { "code": null, "e": 130197, "s": 130101, "text": "execArgv (Array) List of string arguments passed to the executable (Default: process.execArgv)." }, { "code": null, "e": 130435, "s": 130197, "text": "silent (Boolean) If true, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent, see the \"pipe\" and \"inherit\" options for spawn()'s stdio for more details (default is false)." }, { "code": null, "e": 130673, "s": 130435, "text": "silent (Boolean) If true, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent, see the \"pipe\" and \"inherit\" options for spawn()'s stdio for more details (default is false)." }, { "code": null, "e": 130726, "s": 130673, "text": "uid (Number) Sets the user identity of the process. " }, { "code": null, "e": 130779, "s": 130726, "text": "uid (Number) Sets the user identity of the process. " }, { "code": null, "e": 130832, "s": 130779, "text": "gid (Number) Sets the group identity of the process." }, { "code": null, "e": 130885, "s": 130832, "text": "gid (Number) Sets the group identity of the process." }, { "code": null, "e": 131030, "s": 130885, "text": "The fork method returns an object with a built-in communication channel in addition to having all the methods in a normal ChildProcess instance." }, { "code": null, "e": 131083, "s": 131030, "text": "Create two js files named support.js and master.js −" }, { "code": null, "e": 131100, "s": 131083, "text": "File: support.js" }, { "code": null, "e": 131166, "s": 131100, "text": "console.log(\"Child Process \" + process.argv[2] + \" executed.\" );\n" }, { "code": null, "e": 131182, "s": 131166, "text": "File: master.js" }, { "code": null, "e": 131466, "s": 131182, "text": "const fs = require('fs');\nconst child_process = require('child_process');\n \nfor(var i=0; i<3; i++) {\n var worker_process = child_process.fork(\"support.js\", [i]);\t\n\n worker_process.on('close', function (code) {\n console.log('child process exited with code ' + code);\n });\n}" }, { "code": null, "e": 131508, "s": 131466, "text": "Now run the master.js to see the result −" }, { "code": null, "e": 131526, "s": 131508, "text": "$ node master.js\n" }, { "code": null, "e": 131565, "s": 131526, "text": "Verify the Output. Server has started." }, { "code": null, "e": 131743, "s": 131565, "text": "Child Process 0 executed.\nChild Process 1 executed.\nChild Process 2 executed.\nchild process exited with code 0\nchild process exited with code 0\nchild process exited with code 0\n" }, { "code": null, "e": 131892, "s": 131743, "text": "JXcore, which is an open source project, introduces a unique feature for packaging and encryption of source files and other assets into JX packages." }, { "code": null, "e": 132119, "s": 131892, "text": "Consider you have a large project consisting of many files. JXcore can pack them all into a single file to simplify the distribution. This chapter provides a quick overview of the whole process starting from installing JXcore." }, { "code": null, "e": 132274, "s": 132119, "text": "Installing JXcore is quite simple. Here we have provided step-by-step instructions on how to install JXcore on your system. Follow the steps given below −" }, { "code": null, "e": 132458, "s": 132274, "text": "Download the JXcore package from https://github.com/jxcore/jxcore, as per your operating system and machine architecture. We downloaded a package for Cenots running on 64-bit machine." }, { "code": null, "e": 132510, "s": 132458, "text": "$ wget https://s3.amazonaws.com/nodejx/jx_rh64.zip\n" }, { "code": null, "e": 132646, "s": 132510, "text": "Unpack the downloaded file jx_rh64.zipand copy the jx binary into /usr/bin or may be in any other directory based on your system setup." }, { "code": null, "e": 132692, "s": 132646, "text": "$ unzip jx_rh64.zip\n$ cp jx_rh64/jx /usr/bin\n" }, { "code": null, "e": 132763, "s": 132692, "text": "Set your PATH variable appropriately to run jx from anywhere you like." }, { "code": null, "e": 132793, "s": 132763, "text": "$ export PATH=$PATH:/usr/bin\n" }, { "code": null, "e": 132942, "s": 132793, "text": "You can verify your installation by issuing a simple command as shown below. You should find it working and printing its version number as follows −" }, { "code": null, "e": 132967, "s": 132942, "text": "$ jx --version\nv0.10.32\n" }, { "code": null, "e": 133135, "s": 132967, "text": "Consider you have a project with the following directories where you kept all your files including Node.js, main file, index.js, and all the modules installed locally." }, { "code": null, "e": 133447, "s": 133135, "text": "drwxr-xr-x 2 root root 4096 Nov 13 12:42 images\n-rwxr-xr-x 1 root root 30457 Mar 6 12:19 index.htm\n-rwxr-xr-x 1 root root 30452 Mar 1 12:54 index.js\ndrwxr-xr-x 23 root root 4096 Jan 15 03:48 node_modules\ndrwxr-xr-x 2 root root 4096 Mar 21 06:10 scripts\ndrwxr-xr-x 2 root root 4096 Feb 15 11:56 style\n" }, { "code": null, "e": 133620, "s": 133447, "text": "To package the above project, you simply need to go inside this directory and issue the following jx command. Assuming index.js is the entry file for your Node.js project −" }, { "code": null, "e": 133649, "s": 133620, "text": "$ jx package index.js index\n" }, { "code": null, "e": 133882, "s": 133649, "text": "Here you could have used any other package name instead of index. We have used index because we wanted to keep our main file name as index.jx. However, the above command will pack everything and will create the following two files −" }, { "code": null, "e": 133995, "s": 133882, "text": "index.jxp This is an intermediate file which contains the complete project detail needed to compile the project." }, { "code": null, "e": 134108, "s": 133995, "text": "index.jxp This is an intermediate file which contains the complete project detail needed to compile the project." }, { "code": null, "e": 134247, "s": 134108, "text": "index.jx This is the binary file having the complete package that is ready to be shipped to your client or to your production environment." }, { "code": null, "e": 134386, "s": 134247, "text": "index.jx This is the binary file having the complete package that is ready to be shipped to your client or to your production environment." }, { "code": null, "e": 134450, "s": 134386, "text": "Consider your original Node.js project was running as follows −" }, { "code": null, "e": 134490, "s": 134450, "text": "$ node index.js command_line_arguments\n" }, { "code": null, "e": 134564, "s": 134490, "text": "After compiling your package using JXcore, it can be started as follows −" }, { "code": null, "e": 134602, "s": 134564, "text": "$ jx index.jx command_line_arguments\n" }, { "code": null, "e": 134662, "s": 134602, "text": "To know more on JXcore, you can check its official website." }, { "code": null, "e": 134697, "s": 134662, "text": "\n 44 Lectures \n 7.5 hours \n" }, { "code": null, "e": 134725, "s": 134697, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 134759, "s": 134725, "text": "\n 88 Lectures \n 17 hours \n" }, { "code": null, "e": 134787, "s": 134759, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 134822, "s": 134787, "text": "\n 32 Lectures \n 1.5 hours \n" }, { "code": null, "e": 134837, "s": 134822, "text": " Richard Wells" }, { "code": null, "e": 134868, "s": 134837, "text": "\n 8 Lectures \n 33 mins\n" }, { "code": null, "e": 134882, "s": 134868, "text": " Anant Rungta" }, { "code": null, "e": 134916, "s": 134882, "text": "\n 9 Lectures \n 2.5 hours \n" }, { "code": null, "e": 134936, "s": 134916, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 134969, "s": 134936, "text": "\n 97 Lectures \n 6 hours \n" }, { "code": null, "e": 134989, "s": 134969, "text": " Skillbakerystudios" }, { "code": null, "e": 134996, "s": 134989, "text": " Print" }, { "code": null, "e": 135007, "s": 134996, "text": " Add Notes" } ]
Classification with PyCaret: A better machine learning library | by Dario Radečić | Towards Data Science
A few days back I’ve covered the basics of the PyCaret library, and also how to use it to handle regression tasks. If you are new here, PyCaret is a low-code machine learning library that does everything for you — from model selection to deployment. Reading the previous two articles isn’t a prerequisite, but feel free to go through them if you haven’t used the library before. Classification problems are the most common type of machine learning problems — is message spam or not, will the customer leave, is the test result positive or negative — to state a few examples. For that reason, we need to know how to handle classification tasks, and how to do so with ease. If you’re more of a video person, or just want to reinforce your knowledge, feel free to watch our video on the topic. Source code is included: For developers, PyCaret is considered to be better and more friendly than Scikit-Learn. Both are great, don’t get me wrong, but PyCaret will save you so much time that would otherwise be spent on model selection and fine-tuning. And that’s the least fun part of the job. This article assumes you’re familiar with the concept of classification in machine learning. You don’t have to be an expert, but its assumed you know how to fit a model to data in other libraries. The article is structured as follows: Dataset overview and cleaningModel selection and trainingModel visualization and interpretationPredictions and saving the modelConclusion Dataset overview and cleaning Model selection and training Model visualization and interpretation Predictions and saving the model Conclusion Without much ado, let’s get started! In most of my classification-based articles, I like to go with the Titanic dataset. There are multiple reasons why, the most obvious one being that it is fairly simple, but not too simple with regards to data cleaning and preparation. We can load it in Pandas directly from GitHub: data = pd.read_csv('https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv') data.head() Now we can proceed with the data cleaning itself. Here’s what I want to do: Drop irrelevant columns (Ticket and PassengerId) Remap Sex column to zeros and ones Check if a passenger had a unique title (like doctor) or had something more generic (like Mr., Miss.) — can be extracted from the Name column Check if cabin information was known — if the value of Cabin column is not NaN Create dummy variables from the Embarked column — 3 options Fill Age values with the simple mean And here’s the code: data.drop(['Ticket', 'PassengerId'], axis=1, inplace=True) gender_mapper = {'male': 0, 'female': 1} data['Sex'].replace(gender_mapper, inplace=True) data['Title'] = data['Name'].apply(lambda x: x.split(',')[1].strip().split(' ')[0]) data['Title'] = [0 if x in ['Mr.', 'Miss.', 'Mrs.'] else 1 for x in data['Title']] data = data.rename(columns={'Title': 'Title_Unusual'}) data.drop('Name', axis=1, inplace=True) data['Cabin_Known'] = [0 if str(x) == 'nan' else 1 for x in data['Cabin']] data.drop('Cabin', axis=1, inplace=True) emb_dummies = pd.get_dummies(data['Embarked'], drop_first=True, prefix='Embarked') data = pd.concat([data, emb_dummies], axis=1) data.drop('Embarked', axis=1, inplace=True) data['Age'] = data['Age'].fillna(int(data['Age'].mean())) I encourage you to just copy the code, as it’s easy to make a typo, and you aren’t here to practice data preparation. Here’s how the dataset looks like now: This looks much better. There are still some things we could do, but let’s call it a day and proceed with the modeling. To start, let’s import the classification module from the PyCaret library and perform a basic setup: from pycaret.classification import * clf = setup(data, target='Survived', session_id=42) I’ve set the random seed to 42, so you can reproduce the results. After a couple of seconds, you’ll see a success message on the screen alongside a table that shows a bunch of information on your data. Read through it if you wish. Next, we will compare the performance of various machine learning models and see which one does the best overall: compare_models() Yes, it is as simple as a function call. Execution will take anywhere from a couple of seconds to a minute because several algorithms are trained with cross-validation. Once done, you should see this table: It seems like Light Gradient Boosting approach did the best overall, so we can use it to create our model: model = create_model('lightgbm') You are free to perform additional hyperparameter tuning through the tune_model() function, but it didn’t improve the performance in my case. We’ll make a couple of visualizations and interpretations in the next section. To start, let’s see what the plot_model() function has to offer: plot_model(model) Area under ROC (Receiver Operating Characteristics) curve tells us how good the model is at distinguishing between classes — predicting survived as survived, and died as died. If this still isn’t quite interpretable as you would wish, here’s how to plot the confusion matrix: plot_model(model, 'confusion_matrix') The model is actually pretty decent if we take into account how easy it was to build it. Next, let’s use SHAP values to explain our model. SHAP, or SHapley Additive exPlanations, is a way to explain the outputs of a machine learning model. We can use it to see which features are most important by plotting the SHAP values of every feature for every sample. Great! Let’s now make a final evaluation on the test set and save the model to a file. Once we’re satisfied with how the model behaves, we can evaluate it on the test set (previously unseen data): predictions = predict_model(model) When we called the setup() function, at the beginning of the article, PyCaret performed the train/test split in the 70:30 ratio. This ratio can be changed, of course, but I’m satisfied with the default. The results are a bit worse on the test set, but that’s expected. Before saving the model to a file, we need to finalize it: finalize_model(model) Now the model can be saved: save_model(model, 'titanic_lgbm') The model is now saved in the same folder where the notebook is. To load it later, you would use the load_model() function with a file path as an argument. I hope you’ve followed along, spent some more time on data preparation, and got a better model as a result. PyCaret sure does a lot of the things for us, so we can spend our time doing more important things. There’s a lot more to explore, and that’s coming soon. Thanks for reading. Join my private email list for more helpful insights. Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you. medium.com Originally published at https://betterdatascience.com on July 18, 2020.
[ { "code": null, "e": 551, "s": 172, "text": "A few days back I’ve covered the basics of the PyCaret library, and also how to use it to handle regression tasks. If you are new here, PyCaret is a low-code machine learning library that does everything for you — from model selection to deployment. Reading the previous two articles isn’t a prerequisite, but feel free to go through them if you haven’t used the library before." }, { "code": null, "e": 844, "s": 551, "text": "Classification problems are the most common type of machine learning problems — is message spam or not, will the customer leave, is the test result positive or negative — to state a few examples. For that reason, we need to know how to handle classification tasks, and how to do so with ease." }, { "code": null, "e": 988, "s": 844, "text": "If you’re more of a video person, or just want to reinforce your knowledge, feel free to watch our video on the topic. Source code is included:" }, { "code": null, "e": 1259, "s": 988, "text": "For developers, PyCaret is considered to be better and more friendly than Scikit-Learn. Both are great, don’t get me wrong, but PyCaret will save you so much time that would otherwise be spent on model selection and fine-tuning. And that’s the least fun part of the job." }, { "code": null, "e": 1456, "s": 1259, "text": "This article assumes you’re familiar with the concept of classification in machine learning. You don’t have to be an expert, but its assumed you know how to fit a model to data in other libraries." }, { "code": null, "e": 1494, "s": 1456, "text": "The article is structured as follows:" }, { "code": null, "e": 1632, "s": 1494, "text": "Dataset overview and cleaningModel selection and trainingModel visualization and interpretationPredictions and saving the modelConclusion" }, { "code": null, "e": 1662, "s": 1632, "text": "Dataset overview and cleaning" }, { "code": null, "e": 1691, "s": 1662, "text": "Model selection and training" }, { "code": null, "e": 1730, "s": 1691, "text": "Model visualization and interpretation" }, { "code": null, "e": 1763, "s": 1730, "text": "Predictions and saving the model" }, { "code": null, "e": 1774, "s": 1763, "text": "Conclusion" }, { "code": null, "e": 1811, "s": 1774, "text": "Without much ado, let’s get started!" }, { "code": null, "e": 2046, "s": 1811, "text": "In most of my classification-based articles, I like to go with the Titanic dataset. There are multiple reasons why, the most obvious one being that it is fairly simple, but not too simple with regards to data cleaning and preparation." }, { "code": null, "e": 2093, "s": 2046, "text": "We can load it in Pandas directly from GitHub:" }, { "code": null, "e": 2205, "s": 2093, "text": "data = pd.read_csv('https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv') data.head()" }, { "code": null, "e": 2281, "s": 2205, "text": "Now we can proceed with the data cleaning itself. Here’s what I want to do:" }, { "code": null, "e": 2330, "s": 2281, "text": "Drop irrelevant columns (Ticket and PassengerId)" }, { "code": null, "e": 2365, "s": 2330, "text": "Remap Sex column to zeros and ones" }, { "code": null, "e": 2507, "s": 2365, "text": "Check if a passenger had a unique title (like doctor) or had something more generic (like Mr., Miss.) — can be extracted from the Name column" }, { "code": null, "e": 2586, "s": 2507, "text": "Check if cabin information was known — if the value of Cabin column is not NaN" }, { "code": null, "e": 2646, "s": 2586, "text": "Create dummy variables from the Embarked column — 3 options" }, { "code": null, "e": 2683, "s": 2646, "text": "Fill Age values with the simple mean" }, { "code": null, "e": 2704, "s": 2683, "text": "And here’s the code:" }, { "code": null, "e": 3462, "s": 2704, "text": "data.drop(['Ticket', 'PassengerId'], axis=1, inplace=True) gender_mapper = {'male': 0, 'female': 1} data['Sex'].replace(gender_mapper, inplace=True) data['Title'] = data['Name'].apply(lambda x: x.split(',')[1].strip().split(' ')[0]) data['Title'] = [0 if x in ['Mr.', 'Miss.', 'Mrs.'] else 1 for x in data['Title']] data = data.rename(columns={'Title': 'Title_Unusual'}) data.drop('Name', axis=1, inplace=True) data['Cabin_Known'] = [0 if str(x) == 'nan' else 1 for x in data['Cabin']] data.drop('Cabin', axis=1, inplace=True) emb_dummies = pd.get_dummies(data['Embarked'], drop_first=True, prefix='Embarked') data = pd.concat([data, emb_dummies], axis=1) data.drop('Embarked', axis=1, inplace=True) data['Age'] = data['Age'].fillna(int(data['Age'].mean()))" }, { "code": null, "e": 3619, "s": 3462, "text": "I encourage you to just copy the code, as it’s easy to make a typo, and you aren’t here to practice data preparation. Here’s how the dataset looks like now:" }, { "code": null, "e": 3739, "s": 3619, "text": "This looks much better. There are still some things we could do, but let’s call it a day and proceed with the modeling." }, { "code": null, "e": 3840, "s": 3739, "text": "To start, let’s import the classification module from the PyCaret library and perform a basic setup:" }, { "code": null, "e": 3929, "s": 3840, "text": "from pycaret.classification import * clf = setup(data, target='Survived', session_id=42)" }, { "code": null, "e": 3995, "s": 3929, "text": "I’ve set the random seed to 42, so you can reproduce the results." }, { "code": null, "e": 4274, "s": 3995, "text": "After a couple of seconds, you’ll see a success message on the screen alongside a table that shows a bunch of information on your data. Read through it if you wish. Next, we will compare the performance of various machine learning models and see which one does the best overall:" }, { "code": null, "e": 4291, "s": 4274, "text": "compare_models()" }, { "code": null, "e": 4498, "s": 4291, "text": "Yes, it is as simple as a function call. Execution will take anywhere from a couple of seconds to a minute because several algorithms are trained with cross-validation. Once done, you should see this table:" }, { "code": null, "e": 4605, "s": 4498, "text": "It seems like Light Gradient Boosting approach did the best overall, so we can use it to create our model:" }, { "code": null, "e": 4638, "s": 4605, "text": "model = create_model('lightgbm')" }, { "code": null, "e": 4780, "s": 4638, "text": "You are free to perform additional hyperparameter tuning through the tune_model() function, but it didn’t improve the performance in my case." }, { "code": null, "e": 4859, "s": 4780, "text": "We’ll make a couple of visualizations and interpretations in the next section." }, { "code": null, "e": 4924, "s": 4859, "text": "To start, let’s see what the plot_model() function has to offer:" }, { "code": null, "e": 4942, "s": 4924, "text": "plot_model(model)" }, { "code": null, "e": 5118, "s": 4942, "text": "Area under ROC (Receiver Operating Characteristics) curve tells us how good the model is at distinguishing between classes — predicting survived as survived, and died as died." }, { "code": null, "e": 5218, "s": 5118, "text": "If this still isn’t quite interpretable as you would wish, here’s how to plot the confusion matrix:" }, { "code": null, "e": 5256, "s": 5218, "text": "plot_model(model, 'confusion_matrix')" }, { "code": null, "e": 5395, "s": 5256, "text": "The model is actually pretty decent if we take into account how easy it was to build it. Next, let’s use SHAP values to explain our model." }, { "code": null, "e": 5614, "s": 5395, "text": "SHAP, or SHapley Additive exPlanations, is a way to explain the outputs of a machine learning model. We can use it to see which features are most important by plotting the SHAP values of every feature for every sample." }, { "code": null, "e": 5701, "s": 5614, "text": "Great! Let’s now make a final evaluation on the test set and save the model to a file." }, { "code": null, "e": 5811, "s": 5701, "text": "Once we’re satisfied with how the model behaves, we can evaluate it on the test set (previously unseen data):" }, { "code": null, "e": 5846, "s": 5811, "text": "predictions = predict_model(model)" }, { "code": null, "e": 6049, "s": 5846, "text": "When we called the setup() function, at the beginning of the article, PyCaret performed the train/test split in the 70:30 ratio. This ratio can be changed, of course, but I’m satisfied with the default." }, { "code": null, "e": 6174, "s": 6049, "text": "The results are a bit worse on the test set, but that’s expected. Before saving the model to a file, we need to finalize it:" }, { "code": null, "e": 6196, "s": 6174, "text": "finalize_model(model)" }, { "code": null, "e": 6224, "s": 6196, "text": "Now the model can be saved:" }, { "code": null, "e": 6258, "s": 6224, "text": "save_model(model, 'titanic_lgbm')" }, { "code": null, "e": 6414, "s": 6258, "text": "The model is now saved in the same folder where the notebook is. To load it later, you would use the load_model() function with a file path as an argument." }, { "code": null, "e": 6622, "s": 6414, "text": "I hope you’ve followed along, spent some more time on data preparation, and got a better model as a result. PyCaret sure does a lot of the things for us, so we can spend our time doing more important things." }, { "code": null, "e": 6697, "s": 6622, "text": "There’s a lot more to explore, and that’s coming soon. Thanks for reading." }, { "code": null, "e": 6751, "s": 6697, "text": "Join my private email list for more helpful insights." }, { "code": null, "e": 6934, "s": 6751, "text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you." }, { "code": null, "e": 6945, "s": 6934, "text": "medium.com" } ]
C# | Multiple inheritance using interfaces - GeeksforGeeks
19 Feb, 2019 In Multiple inheritance, one class can have more than one superclass and inherit features from all its parent classes. As shown in the below diagram, class C inherits the features of class A and B. But C# does not support multiple class inheritance. To overcome this problem we use interfaces to achieve multiple class inheritance. With the help of the interface, class C( as shown in the above diagram) can get the features of class A and B. Example 1: First of all, we try to inherit the features of Geeks1 and Geeks2 class into GeeksforGeeks class, then the compiler will give an error because C# directly does not support multiple class inheritance. // C# program to illustrate// multiple class inheritanceusing System;using System.Collections; // Parent class 1class Geeks1 { // Providing the implementation // of languages() method public void languages() { // Creating ArrayList ArrayList My_list = new ArrayList(); // Adding elements in the // My_list ArrayList My_list.Add("C"); My_list.Add("C++"); My_list.Add("C#"); My_list.Add("Java"); Console.WriteLine("Languages provided by GeeksforGeeks:"); foreach(var elements in My_list) { Console.WriteLine(elements); } }} // Parent class 2class Geeks2 { // Providing the implementation // of courses() method public void courses() { // Creating ArrayList ArrayList My_list = new ArrayList(); // Adding elements in the // My_list ArrayList My_list.Add("System Design"); My_list.Add("Fork Python"); My_list.Add("Geeks Classes DSA"); My_list.Add("Fork Java"); Console.WriteLine("\nCourses provided by GeeksforGeeks:"); foreach(var elements in My_list) { Console.WriteLine(elements); } }} // Child classclass GeeksforGeeks : Geeks1, Geeks2 {} public class GFG { // Main method static public void Main() { // Creating object of GeeksforGeeks class GeeksforGeeks obj = new GeeksforGeeks(); obj.languages(); obj.courses(); }} Runtime Error: prog.cs(61, 30): error CS1721: `GeeksforGeeks’: Classes cannot have multiple base classes (`Geeks1′ and `Geeks2′)prog.cs(35, 7): (Location of the symbol related to previous error) But we can indirectly inherit the features of Geeks1 and Geek2 class into GeeksforGeeks class using interfaces. As shown in the below diagram. Example 2: Both GFG1 and GFG2 interfaces are implemented by Geeks1 and Geeks2 class. Now Geeks1 and Geeks2 class define languages() and courses() method. When a GeeksforGeeks class inherits GFG1 and GFG2 interfaces you need not to redefine languages() and courses() method just simply create the objects of Geeks1 and Geeks2 class and access the languages() and courses() method using these objects in GeeksforGeeks class. // C# program to illustrate how to// implement multiple class inheritance// using interfacesusing System;using System.Collections; // Interface 1interface GFG1 { void languages();} // Parent class 1class Geeks1 : GFG1 { // Providing the implementation // of languages() method public void languages() { // Creating ArrayList ArrayList My_list = new ArrayList(); // Adding elements in the // My_list ArrayList My_list.Add("C"); My_list.Add("C++"); My_list.Add("C#"); My_list.Add("Java"); Console.WriteLine("Languages provided by GeeksforGeeks:"); foreach(var elements in My_list) { Console.WriteLine(elements); } }} // Interface 2interface GFG2 { void courses();} // Parent class 2class Geeks2 : GFG2 { // Providing the implementation // of courses() method public void courses() { // Creating ArrayList ArrayList My_list = new ArrayList(); // Adding elements in the // My_list ArrayList My_list.Add("System Design"); My_list.Add("Fork Python"); My_list.Add("Geeks Classes DSA"); My_list.Add("Fork Java"); Console.WriteLine("\nCourses provided by GeeksforGeeks:"); foreach(var elements in My_list) { Console.WriteLine(elements); } }} // Child classclass GeeksforGeeks : GFG1, GFG2 { // Creating objects of Geeks1 and Geeks2 class Geeks1 obj1 = new Geeks1(); Geeks2 obj2 = new Geeks2(); public void languages() { obj1.languages(); } public void courses() { obj2.courses(); }} // Driver Classpublic class GFG { // Main method static public void Main() { // Creating object of GeeksforGeeks class GeeksforGeeks obj = new GeeksforGeeks(); obj.languages(); obj.courses(); }} Output: Languages provided by GeeksforGeeks: C C++ C# Java Courses provided by GeeksforGeeks: System Design Fork Python Geeks Classes DSA Fork Java CSharp-Inheritance CSharp-Interfaces CSharp-OOP C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates Extension Method in C# C# | String.IndexOf( ) Method | Set - 1 C# | Replace() Method Introduction to .NET Framework C# | Data Types C# | Arrays HashSet in C# with Examples Common Language Runtime (CLR) in C#
[ { "code": null, "e": 25411, "s": 25383, "text": "\n19 Feb, 2019" }, { "code": null, "e": 25609, "s": 25411, "text": "In Multiple inheritance, one class can have more than one superclass and inherit features from all its parent classes. As shown in the below diagram, class C inherits the features of class A and B." }, { "code": null, "e": 25854, "s": 25609, "text": "But C# does not support multiple class inheritance. To overcome this problem we use interfaces to achieve multiple class inheritance. With the help of the interface, class C( as shown in the above diagram) can get the features of class A and B." }, { "code": null, "e": 26065, "s": 25854, "text": "Example 1: First of all, we try to inherit the features of Geeks1 and Geeks2 class into GeeksforGeeks class, then the compiler will give an error because C# directly does not support multiple class inheritance." }, { "code": "// C# program to illustrate// multiple class inheritanceusing System;using System.Collections; // Parent class 1class Geeks1 { // Providing the implementation // of languages() method public void languages() { // Creating ArrayList ArrayList My_list = new ArrayList(); // Adding elements in the // My_list ArrayList My_list.Add(\"C\"); My_list.Add(\"C++\"); My_list.Add(\"C#\"); My_list.Add(\"Java\"); Console.WriteLine(\"Languages provided by GeeksforGeeks:\"); foreach(var elements in My_list) { Console.WriteLine(elements); } }} // Parent class 2class Geeks2 { // Providing the implementation // of courses() method public void courses() { // Creating ArrayList ArrayList My_list = new ArrayList(); // Adding elements in the // My_list ArrayList My_list.Add(\"System Design\"); My_list.Add(\"Fork Python\"); My_list.Add(\"Geeks Classes DSA\"); My_list.Add(\"Fork Java\"); Console.WriteLine(\"\\nCourses provided by GeeksforGeeks:\"); foreach(var elements in My_list) { Console.WriteLine(elements); } }} // Child classclass GeeksforGeeks : Geeks1, Geeks2 {} public class GFG { // Main method static public void Main() { // Creating object of GeeksforGeeks class GeeksforGeeks obj = new GeeksforGeeks(); obj.languages(); obj.courses(); }}", "e": 27568, "s": 26065, "text": null }, { "code": null, "e": 27583, "s": 27568, "text": "Runtime Error:" }, { "code": null, "e": 27763, "s": 27583, "text": "prog.cs(61, 30): error CS1721: `GeeksforGeeks’: Classes cannot have multiple base classes (`Geeks1′ and `Geeks2′)prog.cs(35, 7): (Location of the symbol related to previous error)" }, { "code": null, "e": 27906, "s": 27763, "text": "But we can indirectly inherit the features of Geeks1 and Geek2 class into GeeksforGeeks class using interfaces. As shown in the below diagram." }, { "code": null, "e": 28329, "s": 27906, "text": "Example 2: Both GFG1 and GFG2 interfaces are implemented by Geeks1 and Geeks2 class. Now Geeks1 and Geeks2 class define languages() and courses() method. When a GeeksforGeeks class inherits GFG1 and GFG2 interfaces you need not to redefine languages() and courses() method just simply create the objects of Geeks1 and Geeks2 class and access the languages() and courses() method using these objects in GeeksforGeeks class." }, { "code": "// C# program to illustrate how to// implement multiple class inheritance// using interfacesusing System;using System.Collections; // Interface 1interface GFG1 { void languages();} // Parent class 1class Geeks1 : GFG1 { // Providing the implementation // of languages() method public void languages() { // Creating ArrayList ArrayList My_list = new ArrayList(); // Adding elements in the // My_list ArrayList My_list.Add(\"C\"); My_list.Add(\"C++\"); My_list.Add(\"C#\"); My_list.Add(\"Java\"); Console.WriteLine(\"Languages provided by GeeksforGeeks:\"); foreach(var elements in My_list) { Console.WriteLine(elements); } }} // Interface 2interface GFG2 { void courses();} // Parent class 2class Geeks2 : GFG2 { // Providing the implementation // of courses() method public void courses() { // Creating ArrayList ArrayList My_list = new ArrayList(); // Adding elements in the // My_list ArrayList My_list.Add(\"System Design\"); My_list.Add(\"Fork Python\"); My_list.Add(\"Geeks Classes DSA\"); My_list.Add(\"Fork Java\"); Console.WriteLine(\"\\nCourses provided by GeeksforGeeks:\"); foreach(var elements in My_list) { Console.WriteLine(elements); } }} // Child classclass GeeksforGeeks : GFG1, GFG2 { // Creating objects of Geeks1 and Geeks2 class Geeks1 obj1 = new Geeks1(); Geeks2 obj2 = new Geeks2(); public void languages() { obj1.languages(); } public void courses() { obj2.courses(); }} // Driver Classpublic class GFG { // Main method static public void Main() { // Creating object of GeeksforGeeks class GeeksforGeeks obj = new GeeksforGeeks(); obj.languages(); obj.courses(); }}", "e": 30237, "s": 28329, "text": null }, { "code": null, "e": 30245, "s": 30237, "text": "Output:" }, { "code": null, "e": 30387, "s": 30245, "text": "Languages provided by GeeksforGeeks:\nC\nC++\nC#\nJava\n\nCourses provided by GeeksforGeeks:\nSystem Design\nFork Python\nGeeks Classes DSA\nFork Java\n" }, { "code": null, "e": 30406, "s": 30387, "text": "CSharp-Inheritance" }, { "code": null, "e": 30424, "s": 30406, "text": "CSharp-Interfaces" }, { "code": null, "e": 30435, "s": 30424, "text": "CSharp-OOP" }, { "code": null, "e": 30438, "s": 30435, "text": "C#" }, { "code": null, "e": 30536, "s": 30438, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30564, "s": 30536, "text": "C# Dictionary with examples" }, { "code": null, "e": 30579, "s": 30564, "text": "C# | Delegates" }, { "code": null, "e": 30602, "s": 30579, "text": "Extension Method in C#" }, { "code": null, "e": 30642, "s": 30602, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 30664, "s": 30642, "text": "C# | Replace() Method" }, { "code": null, "e": 30695, "s": 30664, "text": "Introduction to .NET Framework" }, { "code": null, "e": 30711, "s": 30695, "text": "C# | Data Types" }, { "code": null, "e": 30723, "s": 30711, "text": "C# | Arrays" }, { "code": null, "e": 30751, "s": 30723, "text": "HashSet in C# with Examples" } ]
Minimum cost to make two strings identical by deleting the digits - GeeksforGeeks
28 May, 2021 Given two strings X and Y consisting of only digits ‘0’ to ‘9’. Find minimum cost required to make the given two strings identical. Only operation allowed is to delete characters from any of the string. The cost of operation of deleting the digit ‘d’ is d units. Input: X = 3759, Y = 9350 Output: 23 Explanation For making both string identical, delete characters 3, 7, 5 from first string and delete characters 3, 5, 0 from second string. Total cost of operation is 3 + 7 + 5 + 3 + 5 + 0 = 23 Input: X = 3198, Y = 98 Output: 4 This problem is a variation of Longest Common Subsequence( LCS ) and this one. The idea is simple, instead of finding the length of longest common subsequence, find the maximum cost by adding identical characters from both the string.Now to find the minimum cost, subtract the above result from total cost of both strings i.e., costX = Cost of removing all characters from string 'X' CostY = Cost of removing all characters from string 'Y' cost_Id = Cost of removing identical characters from both strings Minimum cost to make both string identical = costX + costY - cost_Id Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript /* C++ code to find minimum cost to make two strings identical */#include <bits/stdc++.h>using namespace std; /* Function to returns cost of removing the identical characters in LCS for X[0..m-1], Y[0..n-1] */int lcs(char* X, char* Y, int m, int n){ int L[m + 1][n + 1]; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains cost of removing identical characters in LCS of X[0..i-1] and Y[0..j-1] */ for (int i = 0; i <= m; ++i) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; // If both characters are same, add both // of them else if (X[i - 1] == Y[j - 1]) L[i][j] = L[i - 1][j - 1] + 2 * (X[i - 1] - '0'); // Otherwise find the maximum cost among them else L[i][j] = max(L[i - 1][j], L[i][j - 1]); } } return L[m][n];} // Returns cost of making X[] and Y[] identicalint findMinCost(char X[], char Y[]){ // Find LCS of X[] and Y[] int m = strlen(X), n = strlen(Y); // Initialize the cost variable int cost = 0; // Find cost of all characters in // both strings for (int i = 0; i < m; ++i) cost += X[i] - '0'; for (int i = 0; i < n; ++i) cost += Y[i] - '0'; return cost - lcs(X, Y, m, n);} /* Driver program to test above function */int main(){ char X[] = "3759"; char Y[] = "9350"; cout << "Minimum Cost to make two strings " << "identical is = " << findMinCost(X, Y); return 0;} // Java code to find minimum cost to// make two strings identicalimport java.util.*;import java.lang.*; public class GfG{ /* Function to returns cost of removing the identicalcharacters in LCS for X[0..m-1], Y[0..n-1] */static int lcs(char[] X, char[] Y, int m, int n){ int[][] L=new int[m + 1][n + 1]; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains cost of removing identical characters in LCS of X[0..i-1] and Y[0..j-1] */ for (int i = 0; i <= m; ++i) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; // If both characters are same, // add both of them else if (X[i - 1] == Y[j - 1]) L[i][j] = L[i - 1][j - 1] + 2 * (X[i - 1] - '0'); // Otherwise find the maximum // cost among them else L[i][j] = L[i - 1][j] > L[i][j - 1] ? L[i - 1][j] : L[i][j - 1]; } } return L[m][n];} // Returns cost of making X[] and Y[] identicalstatic int findMinCost(char X[], char Y[]){ // Find LCS of X[] and Y[] int m = X.length, n = Y.length; // Initialize the cost variable int cost = 0; // Find cost of all characters in // both strings for (int i = 0; i < m; ++i) cost += X[i] - '0'; for (int i = 0; i < n; ++i) cost += Y[i] - '0'; return cost - lcs(X, Y, m, n);} // driver function public static void main(String argc[]){ char X[] = ("3759").toCharArray(); char Y[] = ("9350").toCharArray(); System.out.println("Minimum Cost to make two strings"+ " identical is = " +findMinCost(X, Y)); }} // This code is contributed by Prerna Saini # Python3 code to find minimum cost to make two strings# identical # Function to returns cost of removing the identical# characters in LCS for X[0..m-1], Y[0..n-1]def lcs(X, Y, m, n): L=[[0 for i in range(n+1)]for i in range(m+1)] # Following steps build L[m+1][n+1] in bottom # up fashion. Note that L[i][j] contains cost # of removing identical characters in LCS of # X[0..i-1] and Y[0..j-1] for i in range(m+1): for j in range(n+1): if (i == 0 or j == 0): L[i][j] = 0 # If both characters are same, add both # of them elif (X[i - 1] == Y[j - 1]): L[i][j] = L[i - 1][j - 1] + 2 * (ord(X[i - 1]) - 48) # Otherwise find the maximum cost among them else: L[i][j] = max(L[i - 1][j], L[i][j - 1]) return L[m][n] # Returns cost of making X[] and Y[] identicaldef findMinCost( X, Y): # Find LCS of X[] and Y[] m = len(X) n = len(Y) # Initialize the cost variable cost = 0 # Find cost of all acters in # both strings for i in range(m): cost += ord(X[i]) - 48 for i in range(n): cost += ord(Y[i]) - 48 ans=cost - lcs(X, Y, m, n) return ans # Driver program to test above functionX = "3759"Y = "9350"print("Minimum Cost to make two strings ", "identical is = " ,findMinCost(X, Y)) #this code is contributed by sahilshelangia // C# code to find minimum cost to// make two strings identicalusing System; public class GfG{ /* Function to returns cost of removing the identical characters in LCS for X[0..m-1], Y[0..n-1] */ static int lcs(string X, string Y, int m, int n) { int [,]L=new int[m + 1,n + 1]; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains cost of removing identical characters in LCS of X[0..i-1] and Y[0..j-1] */ for (int i = 0; i <= m; ++i) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i,j] = 0; // If both characters are same, // add both of them else if (X[i - 1] == Y[j - 1]) L[i,j] = L[i - 1,j - 1] + 2 * (X[i - 1] - '0'); // Otherwise find the maximum // cost among them else L[i,j] = L[i - 1,j] > L[i,j - 1] ? L[i - 1,j] : L[i,j - 1]; } } return L[m,n]; } // Returns cost of making X[] and Y[] identical static int findMinCost( string X, string Y) { // Find LCS of X[] and Y[] int m = X.Length, n = Y.Length; // Initialize the cost variable int cost = 0; // Find cost of all characters in // both strings for (int i = 0; i < m; ++i) cost += X[i] - '0'; for (int i = 0; i < n; ++i) cost += Y[i] - '0'; return cost - lcs(X, Y, m, n); } // Driver function public static void Main() { string X = "3759"; string Y= "9350"; Console.WriteLine("Minimum Cost to make two strings"+ " identical is = " +findMinCost(X, Y)); }} // This code is contributed by vt_m <?php// PHP code to find minimum cost to// make two strings identical /* Function to returns cost of removing the identicalcharacters in LCS for X[0..m-1], Y[0..n-1] */function lcs( $X, $Y, $m, $n){ $L = array($m + 1,$n+ 1); /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains cost of removing identical characters in LCS of X[0..i-1] and Y[0..j-1] */ for ($i = 0; $i <= $m; ++$i) { for ($j = 0; $j <= $n; $j++) { if ($i == 0 || $j == 0) $L[$i][$j] = 0; // If both characters are same, // add both of them else if ($X[$i - 1] == $Y[$j - 1]) $L[$i][$j] = $L[$i - 1][$j - 1] + 2 * ($X[$i - 1] - '0'); // Otherwise find the maximum // cost among them else $L[$i][$j] = $L[$i - 1][$j] > $L[$i][$j - 1] ? $L[$i - 1][$j] : $L[$i][$j - 1]; } } return $L[$m][$n];} // Returns cost of making X[] and Y[] identicalfunction findMinCost($X, $Y){ // Find LCS of X[] and Y[] $m = sizeof($X); $n = sizeof($Y); // Initialize the cost variable $cost = 0; // Find cost of all characters in // both strings for ($i = 0; $i < $m; ++$i) $cost += $X[$i] - '0'; for ($i = 0; $i < $n; ++$i) $cost += $Y[$i] - '0'; return $cost - lcs($X, $Y, $m, $n);} // Driver code $X = str_split("3759"); $Y = str_split("9350"); echo("Minimum Cost to make two strings". " identical is = " .findMinCost($X, $Y)); // This code is contributed by Code_Mech. <script> // Javascript code to find minimum cost to make two strings identical /* Function to returns cost of removing the identical characters in LCS for X[0..m-1], Y[0..n-1] */ function lcs(X, Y, m, n) { let L=new Array(m + 1); for (let i = 0; i <= m; ++i) { L[i] = new Array(n + 1); for (let j = 0; j <= n; j++) { L[i][j] = 0; } } /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains cost of removing identical characters in LCS of X[0..i-1] and Y[0..j-1] */ for (let i = 0; i <= m; ++i) { for (let j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; // If both characters are same, // add both of them else if (X[i - 1] == Y[j - 1]) L[i][j] = L[i - 1][j - 1] + 2 * (X[i - 1] - '0'); // Otherwise find the maximum // cost among them else L[i][j] = L[i - 1][j] > L[i][j - 1] ? L[i - 1][j] : L[i][j - 1]; } } return L[m][n]; } // Returns cost of making X[] and Y[] identical function findMinCost(X, Y) { // Find LCS of X[] and Y[] let m = X.length, n = Y.length; // Initialize the cost variable let cost = 0; // Find cost of all characters in // both strings for (let i = 0; i < m; ++i) cost += X[i].charCodeAt() - '0'.charCodeAt(); for (let i = 0; i < n; ++i) cost += Y[i].charCodeAt() - '0'.charCodeAt(); return cost - lcs(X, Y, m, n); } let X = ("3759").split(''); let Y = ("9350").split(''); document.write("Minimum Cost to make two strings"+ " identical is = " +findMinCost(X, Y)); </script> Output: Minimum Cost to make two strings identical is = 23 Time complexity: O(m*n) Auxiliary space: O(m*n) sahilshelangia Code_Mech rameshtravel07 Dynamic Programming Strings Strings Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Subset Sum Problem | DP-25 Coin Change | DP-7 Matrix Chain Multiplication | DP-8 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": 26265, "s": 26237, "text": "\n28 May, 2021" }, { "code": null, "e": 26530, "s": 26265, "text": "Given two strings X and Y consisting of only digits ‘0’ to ‘9’. Find minimum cost required to make the given two strings identical. Only operation allowed is to delete characters from any of the string. The cost of operation of deleting the digit ‘d’ is d units. " }, { "code": null, "e": 26799, "s": 26530, "text": "Input: X = 3759, Y = 9350\nOutput: 23\nExplanation\nFor making both string identical, delete\ncharacters 3, 7, 5 from first string and\ndelete characters 3, 5, 0 from second \nstring. Total cost of operation is\n3 + 7 + 5 + 3 + 5 + 0 = 23\n\nInput: X = 3198, Y = 98\nOutput: 4" }, { "code": null, "e": 27131, "s": 26801, "text": "This problem is a variation of Longest Common Subsequence( LCS ) and this one. The idea is simple, instead of finding the length of longest common subsequence, find the maximum cost by adding identical characters from both the string.Now to find the minimum cost, subtract the above result from total cost of both strings i.e., " }, { "code": null, "e": 27429, "s": 27131, "text": "costX = Cost of removing all characters\n from string 'X'\nCostY = Cost of removing all characters \n from string 'Y'\ncost_Id = Cost of removing identical characters\n from both strings\n\nMinimum cost to make both string identical = \n costX + costY - cost_Id" }, { "code": null, "e": 27478, "s": 27429, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 27482, "s": 27478, "text": "C++" }, { "code": null, "e": 27487, "s": 27482, "text": "Java" }, { "code": null, "e": 27495, "s": 27487, "text": "Python3" }, { "code": null, "e": 27498, "s": 27495, "text": "C#" }, { "code": null, "e": 27502, "s": 27498, "text": "PHP" }, { "code": null, "e": 27513, "s": 27502, "text": "Javascript" }, { "code": "/* C++ code to find minimum cost to make two strings identical */#include <bits/stdc++.h>using namespace std; /* Function to returns cost of removing the identical characters in LCS for X[0..m-1], Y[0..n-1] */int lcs(char* X, char* Y, int m, int n){ int L[m + 1][n + 1]; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains cost of removing identical characters in LCS of X[0..i-1] and Y[0..j-1] */ for (int i = 0; i <= m; ++i) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; // If both characters are same, add both // of them else if (X[i - 1] == Y[j - 1]) L[i][j] = L[i - 1][j - 1] + 2 * (X[i - 1] - '0'); // Otherwise find the maximum cost among them else L[i][j] = max(L[i - 1][j], L[i][j - 1]); } } return L[m][n];} // Returns cost of making X[] and Y[] identicalint findMinCost(char X[], char Y[]){ // Find LCS of X[] and Y[] int m = strlen(X), n = strlen(Y); // Initialize the cost variable int cost = 0; // Find cost of all characters in // both strings for (int i = 0; i < m; ++i) cost += X[i] - '0'; for (int i = 0; i < n; ++i) cost += Y[i] - '0'; return cost - lcs(X, Y, m, n);} /* Driver program to test above function */int main(){ char X[] = \"3759\"; char Y[] = \"9350\"; cout << \"Minimum Cost to make two strings \" << \"identical is = \" << findMinCost(X, Y); return 0;}", "e": 29105, "s": 27513, "text": null }, { "code": "// Java code to find minimum cost to// make two strings identicalimport java.util.*;import java.lang.*; public class GfG{ /* Function to returns cost of removing the identicalcharacters in LCS for X[0..m-1], Y[0..n-1] */static int lcs(char[] X, char[] Y, int m, int n){ int[][] L=new int[m + 1][n + 1]; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains cost of removing identical characters in LCS of X[0..i-1] and Y[0..j-1] */ for (int i = 0; i <= m; ++i) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; // If both characters are same, // add both of them else if (X[i - 1] == Y[j - 1]) L[i][j] = L[i - 1][j - 1] + 2 * (X[i - 1] - '0'); // Otherwise find the maximum // cost among them else L[i][j] = L[i - 1][j] > L[i][j - 1] ? L[i - 1][j] : L[i][j - 1]; } } return L[m][n];} // Returns cost of making X[] and Y[] identicalstatic int findMinCost(char X[], char Y[]){ // Find LCS of X[] and Y[] int m = X.length, n = Y.length; // Initialize the cost variable int cost = 0; // Find cost of all characters in // both strings for (int i = 0; i < m; ++i) cost += X[i] - '0'; for (int i = 0; i < n; ++i) cost += Y[i] - '0'; return cost - lcs(X, Y, m, n);} // driver function public static void main(String argc[]){ char X[] = (\"3759\").toCharArray(); char Y[] = (\"9350\").toCharArray(); System.out.println(\"Minimum Cost to make two strings\"+ \" identical is = \" +findMinCost(X, Y)); }} // This code is contributed by Prerna Saini", "e": 30883, "s": 29105, "text": null }, { "code": "# Python3 code to find minimum cost to make two strings# identical # Function to returns cost of removing the identical# characters in LCS for X[0..m-1], Y[0..n-1]def lcs(X, Y, m, n): L=[[0 for i in range(n+1)]for i in range(m+1)] # Following steps build L[m+1][n+1] in bottom # up fashion. Note that L[i][j] contains cost # of removing identical characters in LCS of # X[0..i-1] and Y[0..j-1] for i in range(m+1): for j in range(n+1): if (i == 0 or j == 0): L[i][j] = 0 # If both characters are same, add both # of them elif (X[i - 1] == Y[j - 1]): L[i][j] = L[i - 1][j - 1] + 2 * (ord(X[i - 1]) - 48) # Otherwise find the maximum cost among them else: L[i][j] = max(L[i - 1][j], L[i][j - 1]) return L[m][n] # Returns cost of making X[] and Y[] identicaldef findMinCost( X, Y): # Find LCS of X[] and Y[] m = len(X) n = len(Y) # Initialize the cost variable cost = 0 # Find cost of all acters in # both strings for i in range(m): cost += ord(X[i]) - 48 for i in range(n): cost += ord(Y[i]) - 48 ans=cost - lcs(X, Y, m, n) return ans # Driver program to test above functionX = \"3759\"Y = \"9350\"print(\"Minimum Cost to make two strings \", \"identical is = \" ,findMinCost(X, Y)) #this code is contributed by sahilshelangia", "e": 32314, "s": 30883, "text": null }, { "code": "// C# code to find minimum cost to// make two strings identicalusing System; public class GfG{ /* Function to returns cost of removing the identical characters in LCS for X[0..m-1], Y[0..n-1] */ static int lcs(string X, string Y, int m, int n) { int [,]L=new int[m + 1,n + 1]; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains cost of removing identical characters in LCS of X[0..i-1] and Y[0..j-1] */ for (int i = 0; i <= m; ++i) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i,j] = 0; // If both characters are same, // add both of them else if (X[i - 1] == Y[j - 1]) L[i,j] = L[i - 1,j - 1] + 2 * (X[i - 1] - '0'); // Otherwise find the maximum // cost among them else L[i,j] = L[i - 1,j] > L[i,j - 1] ? L[i - 1,j] : L[i,j - 1]; } } return L[m,n]; } // Returns cost of making X[] and Y[] identical static int findMinCost( string X, string Y) { // Find LCS of X[] and Y[] int m = X.Length, n = Y.Length; // Initialize the cost variable int cost = 0; // Find cost of all characters in // both strings for (int i = 0; i < m; ++i) cost += X[i] - '0'; for (int i = 0; i < n; ++i) cost += Y[i] - '0'; return cost - lcs(X, Y, m, n); } // Driver function public static void Main() { string X = \"3759\"; string Y= \"9350\"; Console.WriteLine(\"Minimum Cost to make two strings\"+ \" identical is = \" +findMinCost(X, Y)); }} // This code is contributed by vt_m", "e": 34236, "s": 32314, "text": null }, { "code": "<?php// PHP code to find minimum cost to// make two strings identical /* Function to returns cost of removing the identicalcharacters in LCS for X[0..m-1], Y[0..n-1] */function lcs( $X, $Y, $m, $n){ $L = array($m + 1,$n+ 1); /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains cost of removing identical characters in LCS of X[0..i-1] and Y[0..j-1] */ for ($i = 0; $i <= $m; ++$i) { for ($j = 0; $j <= $n; $j++) { if ($i == 0 || $j == 0) $L[$i][$j] = 0; // If both characters are same, // add both of them else if ($X[$i - 1] == $Y[$j - 1]) $L[$i][$j] = $L[$i - 1][$j - 1] + 2 * ($X[$i - 1] - '0'); // Otherwise find the maximum // cost among them else $L[$i][$j] = $L[$i - 1][$j] > $L[$i][$j - 1] ? $L[$i - 1][$j] : $L[$i][$j - 1]; } } return $L[$m][$n];} // Returns cost of making X[] and Y[] identicalfunction findMinCost($X, $Y){ // Find LCS of X[] and Y[] $m = sizeof($X); $n = sizeof($Y); // Initialize the cost variable $cost = 0; // Find cost of all characters in // both strings for ($i = 0; $i < $m; ++$i) $cost += $X[$i] - '0'; for ($i = 0; $i < $n; ++$i) $cost += $Y[$i] - '0'; return $cost - lcs($X, $Y, $m, $n);} // Driver code $X = str_split(\"3759\"); $Y = str_split(\"9350\"); echo(\"Minimum Cost to make two strings\". \" identical is = \" .findMinCost($X, $Y)); // This code is contributed by Code_Mech.", "e": 35885, "s": 34236, "text": null }, { "code": "<script> // Javascript code to find minimum cost to make two strings identical /* Function to returns cost of removing the identical characters in LCS for X[0..m-1], Y[0..n-1] */ function lcs(X, Y, m, n) { let L=new Array(m + 1); for (let i = 0; i <= m; ++i) { L[i] = new Array(n + 1); for (let j = 0; j <= n; j++) { L[i][j] = 0; } } /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains cost of removing identical characters in LCS of X[0..i-1] and Y[0..j-1] */ for (let i = 0; i <= m; ++i) { for (let j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; // If both characters are same, // add both of them else if (X[i - 1] == Y[j - 1]) L[i][j] = L[i - 1][j - 1] + 2 * (X[i - 1] - '0'); // Otherwise find the maximum // cost among them else L[i][j] = L[i - 1][j] > L[i][j - 1] ? L[i - 1][j] : L[i][j - 1]; } } return L[m][n]; } // Returns cost of making X[] and Y[] identical function findMinCost(X, Y) { // Find LCS of X[] and Y[] let m = X.length, n = Y.length; // Initialize the cost variable let cost = 0; // Find cost of all characters in // both strings for (let i = 0; i < m; ++i) cost += X[i].charCodeAt() - '0'.charCodeAt(); for (let i = 0; i < n; ++i) cost += Y[i].charCodeAt() - '0'.charCodeAt(); return cost - lcs(X, Y, m, n); } let X = (\"3759\").split(''); let Y = (\"9350\").split(''); document.write(\"Minimum Cost to make two strings\"+ \" identical is = \" +findMinCost(X, Y)); </script>", "e": 37877, "s": 35885, "text": null }, { "code": null, "e": 37887, "s": 37877, "text": "Output: " }, { "code": null, "e": 37939, "s": 37887, "text": "Minimum Cost to make two strings identical is = 23" }, { "code": null, "e": 37988, "s": 37939, "text": "Time complexity: O(m*n) Auxiliary space: O(m*n) " }, { "code": null, "e": 38003, "s": 37988, "text": "sahilshelangia" }, { "code": null, "e": 38013, "s": 38003, "text": "Code_Mech" }, { "code": null, "e": 38028, "s": 38013, "text": "rameshtravel07" }, { "code": null, "e": 38048, "s": 38028, "text": "Dynamic Programming" }, { "code": null, "e": 38056, "s": 38048, "text": "Strings" }, { "code": null, "e": 38064, "s": 38056, "text": "Strings" }, { "code": null, "e": 38084, "s": 38064, "text": "Dynamic Programming" }, { "code": null, "e": 38182, "s": 38084, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38213, "s": 38182, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 38246, "s": 38213, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 38273, "s": 38246, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 38292, "s": 38273, "text": "Coin Change | DP-7" }, { "code": null, "e": 38327, "s": 38292, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 38373, "s": 38327, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 38398, "s": 38373, "text": "Reverse a string in Java" }, { "code": null, "e": 38458, "s": 38398, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 38473, "s": 38458, "text": "C++ Data Types" } ]
Object.freeze( ) in JavaScript - GeeksforGeeks
17 Sep, 2021 Object and Object Constructors in JavaScript? In the living world of object-oriented programming we already know the importance of classes and objects but unlike other programming languages, JavaScript does not have the traditional classes as seen in other languages. But JavaScript has objects and constructors which work mostly in the same way to perform the same kind of operations. Constructors are general JavaScript functions which are used with the “new” keyword. Constructors are of two types in JavaScript i.e. built-in constructors(array and object) and custom constructors(define properties and methods for specific objects). Constructors can be useful when we need a way to create an object “type” that can be used multiple times without having to redefine the object every time and this could be achieved using the Object Constructor function. It’s a convention to capitalize the name of constructors to distinguish them from regular functions. For instance, consider the following code: function Automobile(color) { this.color=color; } var vehicle1 = new Automobile ("red"); The function “Automobile()” is an object constructor, and its properties and methods i.e “color” is declared inside it by prefixing it with the keyword “this”. Objects defined using an object constructor are then made instants using the keyword “new”. When new Automobile() is called, JavaScript does two things: It creates a fresh new object(instance) Automobile() and assigns it to a variable.It sets the constructor property i.e “color” of the object to Automobile. It creates a fresh new object(instance) Automobile() and assigns it to a variable. It sets the constructor property i.e “color” of the object to Automobile. Object.freeze() Method Among the Object constructor methods, there is a method Object.freeze() which is used to freeze an object. Freezing an object does not allow new properties to be added to an object and prevents from removing or altering the existing properties. Object.freeze() preserves the enumerability, configurability, writability and the prototype of the object. It returns the passed object and does not create a frozen copy.Applications: Object.freeze() is used for freezing objects and arrays. Object.freeze() is used to make an object immutable. Syntax: Object.freeze(obj) Parameters Used: obj : It is the object which has to be freezed. obj : It is the object which has to be freezed. Return Value: Object.freeze() returns the object that was passed to the function.Examples of the above function are provided below.Examples: Input : const obj1 = { property1: 'initial_data'}; const obj2 = Object.freeze(obj1); obj2.property1 = 'new_data'; console.log(obj2.property1); Output : "initial_data" Explanation : In this example, the object “obj2” has been assigned property from object “obj1” and the properties of “obj1” are frozen therefore new property and values are prevented from being added to “obj2”. Input : var obj = { prop: function() {}, name: 'adam' }; console.log(obj); obj.name = 'billy'; delete obj.prop; console.log(obj); var o = Object.freeze(obj); obj.name = 'chris'; console.log(obj); Output : Object { prop: function () {}, name: "adam" } Object { name: "billy" } Object { name: "billy" } Explanation : In this example, the object “obj” has been assigned “prop: function” which has been later deleted since the object “obj wasn’t frozen. After that, a new object “o” has been assigned the frozen values of “obj” which prevented it from further updations.Codes for the above function are provided below.Code 1: html <script><!-- creating an object constructor and assigning values to it -->const obj1 = { property1: 'initial_data'}; <!--creating a second object which will freeze the properties of the first object-->const obj2 = Object.freeze(obj1); <!-- Updating the properties of the frozen object -->obj2.property1 = 'new_data'; <!-- Displaying the properties of the frozen object -->console.log(obj2.property1);</script> OUTPUT : "initial_data" Code 2: html <script><!-- creating an object constructor and assigning values to it -->var obj = { prop: function() {}, name: 'adam' }; <!-- Displaying the properties of the object created -->console.log(obj); <!-- Updating the properties of the object -->obj.name = 'billy';delete obj.prop;<!-- Displaying the updated properties of the object -->console.log(obj); <!-- Freezing the object using object.freeze() method -->var o = Object.freeze(obj); <!-- Updating the properties of the frozen object -->obj.name = 'chris'; <!-- Displaying the properties of the frozen object -->console.log(obj); </script> OUTPUT : Object { prop: function () {}, name: "adam" } Object { name: "billy" } Object { name: "billy" } Exceptions : It causes a TypeError if the argument passed is not an object . Supported Browsers: Google Chrome 6.0 and above Internet Explorer 9.0 and above Mozilla 4.0 and above Opera 11.1 and above Safari 5.0 and above Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze gupta0509shubham ysachin2314 javascript-functions javascript-object JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? Difference Between PUT and PATCH Request How to read a local text file using JavaScript? JavaScript | console.log() with Examples How to Use the JavaScript Fetch API to Get Data?
[ { "code": null, "e": 25929, "s": 25901, "text": "\n17 Sep, 2021" }, { "code": null, "e": 26317, "s": 25929, "text": "Object and Object Constructors in JavaScript? In the living world of object-oriented programming we already know the importance of classes and objects but unlike other programming languages, JavaScript does not have the traditional classes as seen in other languages. But JavaScript has objects and constructors which work mostly in the same way to perform the same kind of operations. " }, { "code": null, "e": 26568, "s": 26317, "text": "Constructors are general JavaScript functions which are used with the “new” keyword. Constructors are of two types in JavaScript i.e. built-in constructors(array and object) and custom constructors(define properties and methods for specific objects)." }, { "code": null, "e": 26889, "s": 26568, "text": "Constructors can be useful when we need a way to create an object “type” that can be used multiple times without having to redefine the object every time and this could be achieved using the Object Constructor function. It’s a convention to capitalize the name of constructors to distinguish them from regular functions." }, { "code": null, "e": 26933, "s": 26889, "text": "For instance, consider the following code: " }, { "code": null, "e": 27024, "s": 26933, "text": "function Automobile(color) {\n this.color=color;\n}\n\nvar vehicle1 = new Automobile (\"red\");" }, { "code": null, "e": 27339, "s": 27024, "text": "The function “Automobile()” is an object constructor, and its properties and methods i.e “color” is declared inside it by prefixing it with the keyword “this”. Objects defined using an object constructor are then made instants using the keyword “new”. When new Automobile() is called, JavaScript does two things: " }, { "code": null, "e": 27495, "s": 27339, "text": "It creates a fresh new object(instance) Automobile() and assigns it to a variable.It sets the constructor property i.e “color” of the object to Automobile." }, { "code": null, "e": 27578, "s": 27495, "text": "It creates a fresh new object(instance) Automobile() and assigns it to a variable." }, { "code": null, "e": 27652, "s": 27578, "text": "It sets the constructor property i.e “color” of the object to Automobile." }, { "code": null, "e": 28106, "s": 27652, "text": "Object.freeze() Method Among the Object constructor methods, there is a method Object.freeze() which is used to freeze an object. Freezing an object does not allow new properties to be added to an object and prevents from removing or altering the existing properties. Object.freeze() preserves the enumerability, configurability, writability and the prototype of the object. It returns the passed object and does not create a frozen copy.Applications: " }, { "code": null, "e": 28163, "s": 28106, "text": "Object.freeze() is used for freezing objects and arrays." }, { "code": null, "e": 28216, "s": 28163, "text": "Object.freeze() is used to make an object immutable." }, { "code": null, "e": 28226, "s": 28216, "text": "Syntax: " }, { "code": null, "e": 28245, "s": 28226, "text": "Object.freeze(obj)" }, { "code": null, "e": 28264, "s": 28245, "text": "Parameters Used: " }, { "code": null, "e": 28312, "s": 28264, "text": "obj : It is the object which has to be freezed." }, { "code": null, "e": 28360, "s": 28312, "text": "obj : It is the object which has to be freezed." }, { "code": null, "e": 28503, "s": 28360, "text": "Return Value: Object.freeze() returns the object that was passed to the function.Examples of the above function are provided below.Examples: " }, { "code": null, "e": 28695, "s": 28503, "text": "Input : const obj1 = { property1: 'initial_data'};\n const obj2 = Object.freeze(obj1);\n obj2.property1 = 'new_data';\n console.log(obj2.property1);\n\nOutput : \"initial_data\"" }, { "code": null, "e": 28908, "s": 28695, "text": "Explanation : In this example, the object “obj2” has been assigned property from object “obj1” and the properties of “obj1” are frozen therefore new property and values are prevented from being added to “obj2”. " }, { "code": null, "e": 29284, "s": 28908, "text": "Input : var obj = { prop: function() {}, name: 'adam' };\n console.log(obj);\n obj.name = 'billy';\n delete obj.prop;\n console.log(obj);\n var o = Object.freeze(obj);\n obj.name = 'chris';\n console.log(obj);\n\nOutput : Object { prop: function () {}, name: \"adam\" }\n Object { name: \"billy\" }\n Object { name: \"billy\" }" }, { "code": null, "e": 29606, "s": 29284, "text": "Explanation : In this example, the object “obj” has been assigned “prop: function” which has been later deleted since the object “obj wasn’t frozen. After that, a new object “o” has been assigned the frozen values of “obj” which prevented it from further updations.Codes for the above function are provided below.Code 1: " }, { "code": null, "e": 29611, "s": 29606, "text": "html" }, { "code": "<script><!-- creating an object constructor and assigning values to it -->const obj1 = { property1: 'initial_data'}; <!--creating a second object which will freeze the properties of the first object-->const obj2 = Object.freeze(obj1); <!-- Updating the properties of the frozen object -->obj2.property1 = 'new_data'; <!-- Displaying the properties of the frozen object -->console.log(obj2.property1);</script>", "e": 30022, "s": 29611, "text": null }, { "code": null, "e": 30033, "s": 30022, "text": "OUTPUT : " }, { "code": null, "e": 30048, "s": 30033, "text": "\"initial_data\"" }, { "code": null, "e": 30057, "s": 30048, "text": "Code 2: " }, { "code": null, "e": 30062, "s": 30057, "text": "html" }, { "code": "<script><!-- creating an object constructor and assigning values to it -->var obj = { prop: function() {}, name: 'adam' }; <!-- Displaying the properties of the object created -->console.log(obj); <!-- Updating the properties of the object -->obj.name = 'billy';delete obj.prop;<!-- Displaying the updated properties of the object -->console.log(obj); <!-- Freezing the object using object.freeze() method -->var o = Object.freeze(obj); <!-- Updating the properties of the frozen object -->obj.name = 'chris'; <!-- Displaying the properties of the frozen object -->console.log(obj); </script>", "e": 30656, "s": 30062, "text": null }, { "code": null, "e": 30667, "s": 30656, "text": "OUTPUT : " }, { "code": null, "e": 30763, "s": 30667, "text": "Object { prop: function () {}, name: \"adam\" }\nObject { name: \"billy\" }\nObject { name: \"billy\" }" }, { "code": null, "e": 30778, "s": 30763, "text": "Exceptions : " }, { "code": null, "e": 30842, "s": 30778, "text": "It causes a TypeError if the argument passed is not an object ." }, { "code": null, "e": 30862, "s": 30842, "text": "Supported Browsers:" }, { "code": null, "e": 30890, "s": 30862, "text": "Google Chrome 6.0 and above" }, { "code": null, "e": 30922, "s": 30890, "text": "Internet Explorer 9.0 and above" }, { "code": null, "e": 30944, "s": 30922, "text": "Mozilla 4.0 and above" }, { "code": null, "e": 30965, "s": 30944, "text": "Opera 11.1 and above" }, { "code": null, "e": 30986, "s": 30965, "text": "Safari 5.0 and above" }, { "code": null, "e": 31093, "s": 30986, "text": "Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze " }, { "code": null, "e": 31110, "s": 31093, "text": "gupta0509shubham" }, { "code": null, "e": 31122, "s": 31110, "text": "ysachin2314" }, { "code": null, "e": 31143, "s": 31122, "text": "javascript-functions" }, { "code": null, "e": 31161, "s": 31143, "text": "javascript-object" }, { "code": null, "e": 31172, "s": 31161, "text": "JavaScript" }, { "code": null, "e": 31270, "s": 31172, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31310, "s": 31270, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31355, "s": 31310, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31416, "s": 31355, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 31488, "s": 31416, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 31540, "s": 31488, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 31586, "s": 31540, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 31627, "s": 31586, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 31675, "s": 31627, "text": "How to read a local text file using JavaScript?" }, { "code": null, "e": 31716, "s": 31675, "text": "JavaScript | console.log() with Examples" } ]
Maximum profit by buying and selling a share at most twice - GeeksforGeeks
14 Mar, 2022 In daily share trading, a buyer buys shares in the morning and sells them on the same day. If the trader is allowed to make at most 2 transactions in a day, whereas the second transaction can only start after the first one is complete (Buy->sell->Buy->sell). Given stock prices throughout the day, find out the maximum profit that a share trader could have made. Examples: Input: price[] = {10, 22, 5, 75, 65, 80} Output: 87 Trader earns 87 as sum of 12, 75 Buy at 10, sell at 22, Buy at 5 and sell at 80 Input: price[] = {2, 30, 15, 10, 8, 25, 80} Output: 100 Trader earns 100 as sum of 28 and 72 Buy at price 2, sell at 30, buy at 8 and sell at 80 Input: price[] = {100, 30, 15, 10, 8, 25, 80}; Output: 72 Buy at price 8 and sell at 80. Input: price[] = {90, 80, 70, 60, 50} Output: 0 Not possible to earn. A Simple Solution is to consider every index ‘i’ and do the following Max profit with at most two transactions = MAX {max profit with one transaction and subarray price[0..i] + max profit with one transaction and subarray price[i+1..n-1] } i varies from 0 to n-1. Maximum possible using one transaction can be calculated using the following O(n) algorithm The maximum difference between two elements such that the larger element appears after the smaller numberThe time complexity of the above simple solution is O(n2). We can do this O(n) using the following Efficient Solution. The idea is to store the maximum possible profit of every subarray and solve the problem in the following two phases. 1) Create a table profit[0..n-1] and initialize all values in it 0.2) Traverse price[] from right to left and update profit[i] such that profit[i] stores maximum profit achievable from one transaction in subarray price[i..n-1]3) Traverse price[] from left to right and update profit[i] such that profit[i] stores maximum profit such that profit[i] contains maximum achievable profit from two transactions in subarray price[0..i].4) Return profit[n-1] To do step 2, we need to keep track of the maximum price from right to left side, and to do step 3, we need to keep track of the minimum price from left to right. Why we traverse in reverse directions? The idea is to save space, in the third step, we use the same array for both purposes, maximum with 1 transaction and maximum with 2 transactions. After iteration i, the array profit[0..i] contains the maximum profit with 2 transactions, and profit[i+1..n-1] contains profit with two transactions. Below are the implementations of the above idea. C++ Java Python3 C# PHP Javascript // C++ program to find maximum// possible profit with at most// two transactions#include <bits/stdc++.h>using namespace std; // Returns maximum profit with// two transactions on a given// list of stock prices, price[0..n-1]int maxProfit(int price[], int n){ // Create profit array and // initialize it as 0 int* profit = new int[n]; for (int i = 0; i < n; i++) profit[i] = 0; /* Get the maximum profit with only one transaction allowed. After this loop, profit[i] contains maximum profit from price[i..n-1] using at most one trans. */ int max_price = price[n - 1]; for (int i = n - 2; i >= 0; i--) { // max_price has maximum // of price[i..n-1] if (price[i] > max_price) max_price = price[i]; // we can get profit[i] by taking maximum of: // a) previous maximum, i.e., profit[i+1] // b) profit by buying at price[i] and selling at // max_price profit[i] = max(profit[i + 1], max_price - price[i]); } /* Get the maximum profit with two transactions allowed After this loop, profit[n-1] contains the result */ int min_price = price[0]; for (int i = 1; i < n; i++) { // min_price is minimum price in price[0..i] if (price[i] < min_price) min_price = price[i]; // Maximum profit is maximum of: // a) previous maximum, i.e., profit[i-1] // b) (Buy, Sell) at (min_price, price[i]) and add // profit of other trans. stored in profit[i] profit[i] = max(profit[i - 1], profit[i] + (price[i] - min_price)); } int result = profit[n - 1]; delete[] profit; // To avoid memory leak return result;} // Driver codeint main(){ int price[] = { 2, 30, 15, 10, 8, 25, 80 }; int n = sizeof(price) / sizeof(price[0]); cout << "Maximum Profit = " << maxProfit(price, n); return 0;} class Profit { // Returns maximum profit // with two transactions on a // given list of stock prices, // price[0..n-1] static int maxProfit(int price[], int n) { // Create profit array // and initialize it as 0 int profit[] = new int[n]; for (int i = 0; i < n; i++) profit[i] = 0; /* Get the maximum profit with only one transaction allowed. After this loop, profit[i] contains maximum profit from price[i..n-1] using at most one trans. */ int max_price = price[n - 1]; for (int i = n - 2; i >= 0; i--) { // max_price has maximum // of price[i..n-1] if (price[i] > max_price) max_price = price[i]; // we can get profit[i] // by taking maximum of: // a) previous maximum, // i.e., profit[i+1] // b) profit by buying // at price[i] and selling // at // max_price profit[i] = Math.max(profit[i + 1], max_price - price[i]); } /* Get the maximum profit with two transactions allowed After this loop, profit[n-1] contains the result */ int min_price = price[0]; for (int i = 1; i < n; i++) { // min_price is minimum // price in price[0..i] if (price[i] < min_price) min_price = price[i]; // Maximum profit is maximum of: // a) previous maximum, i.e., profit[i-1] // b) (Buy, Sell) at (min_price, price[i]) and // add // profit of other trans. // stored in profit[i] profit[i] = Math.max( profit[i - 1], profit[i] + (price[i] - min_price)); } int result = profit[n - 1]; return result; } // Driver Code public static void main(String args[]) { int price[] = { 2, 30, 15, 10, 8, 25, 80 }; int n = price.length; System.out.println("Maximum Profit = " + maxProfit(price, n)); } } /* This code is contributed by Rajat Mishra */ # Returns maximum profit with# two transactions on a given# list of stock prices price[0..n-1] def maxProfit(price, n): # Create profit array and initialize it as 0 profit = [0]*n # Get the maximum profit # with only one transaction # allowed. After this loop, # profit[i] contains maximum # profit from price[i..n-1] # using at most one trans. max_price = price[n-1] for i in range(n-2, 0, -1): if price[i] > max_price: max_price = price[i] # we can get profit[i] by # taking maximum of: # a) previous maximum, # i.e., profit[i+1] # b) profit by buying at # price[i] and selling at # max_price profit[i] = max(profit[i+1], max_price - price[i]) # Get the maximum profit # with two transactions allowed # After this loop, profit[n-1] # contains the result min_price = price[0] for i in range(1, n): if price[i] < min_price: min_price = price[i] # Maximum profit is maximum of: # a) previous maximum, # i.e., profit[i-1] # b) (Buy, Sell) at # (min_price, A[i]) and add # profit of other trans. # stored in profit[i] profit[i] = max(profit[i-1], profit[i]+(price[i]-min_price)) result = profit[n-1] return result # Driver functionprice = [2, 30, 15, 10, 8, 25, 80]print ("Maximum profit is", maxProfit(price, len(price))) # This code is contributed by __Devesh Agrawal__ // C# program to find maximum possible profit// with at most two transactionsusing System; class GFG { // Returns maximum profit with two // transactions on a given list of // stock prices, price[0..n-1] static int maxProfit(int[] price, int n) { // Create profit array and initialize // it as 0 int[] profit = new int[n]; for (int i = 0; i < n; i++) profit[i] = 0; /* Get the maximum profit with only one transaction allowed. After this loop, profit[i] contains maximum profit from price[i..n-1] using at most one trans. */ int max_price = price[n - 1]; for (int i = n - 2; i >= 0; i--) { // max_price has maximum of // price[i..n-1] if (price[i] > max_price) max_price = price[i]; // we can get profit[i] by taking // maximum of: // a) previous maximum, i.e., // profit[i+1] // b) profit by buying at price[i] // and selling at max_price profit[i] = Math.Max(profit[i + 1], max_price - price[i]); } /* Get the maximum profit with two transactions allowed After this loop, profit[n-1] contains the result */ int min_price = price[0]; for (int i = 1; i < n; i++) { // min_price is minimum price in // price[0..i] if (price[i] < min_price) min_price = price[i]; // Maximum profit is maximum of: // a) previous maximum, i.e., // profit[i-1] // b) (Buy, Sell) at (min_price, // price[i]) and add profit of // other trans. stored in // profit[i] profit[i] = Math.Max( profit[i - 1], profit[i] + (price[i] - min_price)); } int result = profit[n - 1]; return result; } // Driver code public static void Main() { int[] price = { 2, 30, 15, 10, 8, 25, 80 }; int n = price.Length; Console.Write("Maximum Profit = " + maxProfit(price, n)); }} // This code is contributed by nitin mittal. <?php// PHP program to find maximum// possible profit with at most// two transactions // Returns maximum profit with// two transactions on a given// list of stock prices, price[0..n-1]function maxProfit($price, $n){ // Create profit array and // initialize it as 0 $profit = array(); for ($i = 0; $i < $n; $i++) $profit[$i] = 0; // Get the maximum profit with // only one transaction allowed. // After this loop, profit[i] // contains maximum profit from // price[i..n-1] using at most // one trans. $max_price = $price[$n - 1]; for ($i = $n - 2; $i >= 0; $i--) { // max_price has maximum // of price[i..n-1] if ($price[$i] > $max_price) $max_price = $price[$i]; // we can get profit[i] by // taking maximum of: // a) previous maximum, // i.e., profit[i+1] // b) profit by buying at // price[i] and selling at // max_price if($profit[$i + 1] > $max_price-$price[$i]) $profit[$i] = $profit[$i + 1]; else $profit[$i] = $max_price - $price[$i]; } // Get the maximum profit with // two transactions allowed. // After this loop, profit[n-1] // contains the result $min_price = $price[0]; for ($i = 1; $i < $n; $i++) { // min_price is minimum // price in price[0..i] if ($price[$i] < $min_price) $min_price = $price[$i]; // Maximum profit is maximum of: // a) previous maximum, // i.e., profit[i-1] // b) (Buy, Sell) at (min_price, // price[i]) and add // profit of other trans. // stored in profit[i] $profit[$i] = max($profit[$i - 1], $profit[$i] + ($price[$i] - $min_price)); } $result = $profit[$n - 1]; return $result;} // Driver Code$price = array(2, 30, 15, 10, 8, 25, 80);$n = sizeof($price);echo "Maximum Profit = ". maxProfit($price, $n); // This code is contributed// by Arnab Kundu?> <script> // JavaScript program to find maximum// possible profit with at most// two transactions // Returns maximum profit with// two transactions on a given// list of stock prices, price[0..n-1]function maxProfit(price, n){ // Create profit array and // initialize it as 0 let profit = new Array(n); for(let i = 0; i < n; i++) profit[i] = 0; /* Get the maximum profit with only one transaction allowed. After this loop, profit[i] contains maximum profit from price[i..n-1] using at most one trans. */ let max_price = price[n - 1]; for(let i = n - 2; i >= 0; i--) { // max_price has maximum // of price[i..n-1] if (price[i] > max_price) max_price = price[i]; // We can get profit[i] by taking maximum of: // a) previous maximum, i.e., profit[i+1] // b) profit by buying at price[i] and selling at // max_price profit[i] = Math.max(profit[i + 1], max_price - price[i]); } // Get the maximum profit with // two transactions allowed // After this loop, profit[n-1] // contains the result let min_price = price[0]; for(let i = 1; i < n; i++) { // min_price is minimum price // in price[0..i] if (price[i] < min_price) min_price = price[i]; // Maximum profit is maximum of: // a) previous maximum, i.e., profit[i-1] // b) (Buy, Sell) at (min_price, price[i]) and add // profit of other trans. stored in profit[i] profit[i] = Math.max(profit[i - 1], profit[i] + (price[i] - min_price)); } let result = profit[n - 1]; return result;} // Driver codelet price = [ 2, 30, 15, 10, 8, 25, 80 ];let n = price.length; document.write("Maximum Profit = " + maxProfit(price, n)); // This code is contributed by Surbhi Tyagi. </script> Maximum Profit = 100 The time complexity of the above solution is O(n). Algorithmic Paradigm: Dynamic Programming Another approach: Initialize four variables for taking care of the first buy, first sell, second buy, second sell. Set first buy and second buy as INT_MIN and first and second sell as 0. This is to ensure to get profit from transactions. Iterate through the array and return the second sell as it will store maximum profit. C++ Java Python3 C# Javascript #include <iostream>#include<climits>using namespace std; int maxtwobuysell(int arr[],int size) { int first_buy = INT_MIN; int first_sell = 0; int second_buy = INT_MIN; int second_sell = 0; for(int i=0;i<size;i++) { first_buy = max(first_buy,-arr[i]);//we set prices to negative, so the calculation of profit will be convenient first_sell = max(first_sell,first_buy+arr[i]); second_buy = max(second_buy,first_sell-arr[i]);//we can buy the second only after first is sold second_sell = max(second_sell,second_buy+arr[i]); } return second_sell;} int main() { int arr[] = {2, 30, 15, 10, 8, 25, 80}; int size = sizeof(arr)/sizeof(arr[0]); cout<<maxtwobuysell(arr,size); return 0;} import java.util.*;class GFG{ static int maxtwobuysell(int arr[],int size) { int first_buy = Integer.MIN_VALUE; int first_sell = 0; int second_buy = Integer.MIN_VALUE; int second_sell = 0; for(int i = 0; i < size; i++) { first_buy = Math.max(first_buy,-arr[i]); first_sell = Math.max(first_sell,first_buy+arr[i]); second_buy = Math.max(second_buy,first_sell-arr[i]); second_sell = Math.max(second_sell,second_buy+arr[i]); } return second_sell;} public static void main(String[] args){ int arr[] = {2, 30, 15, 10, 8, 25, 80}; int size = arr.length; System.out.print(maxtwobuysell(arr,size));}} // This code is contributed by gauravrajput1 import sys def maxtwobuysell(arr, size): first_buy = -sys.maxsize; first_sell = 0; second_buy = -sys.maxsize; second_sell = 0; for i in range(size): first_buy = max(first_buy, -arr[i]); first_sell = max(first_sell, first_buy + arr[i]); second_buy = max(second_buy, first_sell - arr[i]); second_sell = max(second_sell, second_buy + arr[i]); return second_sell; if __name__ == '__main__': arr = [ 2, 30, 15, 10, 8, 25, 80 ]; size = len(arr); print(maxtwobuysell(arr, size)); # This code is contributed by gauravrajput1 using System; public class GFG{ static int maxtwobuysell(int []arr,int size) { int first_buy = int.MinValue; int first_sell = 0; int second_buy = int.MinValue; int second_sell = 0; for(int i = 0; i < size; i++) { first_buy = Math.Max(first_buy,-arr[i]); first_sell = Math.Max(first_sell,first_buy+arr[i]); second_buy = Math.Max(second_buy,first_sell-arr[i]); second_sell = Math.Max(second_sell,second_buy+arr[i]); } return second_sell;} public static void Main(String[] args){ int []arr = {2, 30, 15, 10, 8, 25, 80}; int size = arr.Length; Console.Write(maxtwobuysell(arr,size));}} // This code is contributed by gauravrajput1 <script> function maxtwobuysell(arr , size) { var first_buy = -1000; var first_sell = 0; var second_buy = -1000; var second_sell = 0; for (var i = 0; i < size; i++) { first_buy = Math.max(first_buy, -arr[i]); first_sell = Math.max(first_sell, first_buy + arr[i]); second_buy = Math.max(second_buy, first_sell - arr[i]); second_sell = Math.max(second_sell, second_buy + arr[i]); } return second_sell; } var arr = [ 2, 30, 15, 10, 8, 25, 80 ]; var size = arr.length; document.write(maxtwobuysell(arr, size)); // This code is contributed by gauravrajput1</script> 100 Time Complexity: O(N) Auxiliary Space: O(1) nitin mittal andrew1234 rambabuy nidhi_biet doshiruhal marix101 divyeshrabadiya07 Mukul Lunia katariarishu95 RohitOberoi surbhityagi15 Rajput-Ji pranavkushwaha506 rajsanghavi9 ambujsingh2000 dewanshipaul84 umadevi9616 GauravRajput1 juyal_sid amartyaghoshgfg sharmanandini1677 Dynamic Programming Mathematical Dynamic Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Floyd Warshall Algorithm | DP-16 Matrix Chain Multiplication | DP-8 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Edit Distance | DP-5 Overlapping Subproblems Property in Dynamic Programming | DP-1 Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples
[ { "code": null, "e": 26185, "s": 26157, "text": "\n14 Mar, 2022" }, { "code": null, "e": 26548, "s": 26185, "text": "In daily share trading, a buyer buys shares in the morning and sells them on the same day. If the trader is allowed to make at most 2 transactions in a day, whereas the second transaction can only start after the first one is complete (Buy->sell->Buy->sell). Given stock prices throughout the day, find out the maximum profit that a share trader could have made." }, { "code": null, "e": 26559, "s": 26548, "text": "Examples: " }, { "code": null, "e": 27009, "s": 26559, "text": "Input: price[] = {10, 22, 5, 75, 65, 80}\nOutput: 87\nTrader earns 87 as sum of 12, 75 \nBuy at 10, sell at 22, \nBuy at 5 and sell at 80\nInput: price[] = {2, 30, 15, 10, 8, 25, 80}\nOutput: 100\nTrader earns 100 as sum of 28 and 72\nBuy at price 2, sell at 30, buy at 8 and sell at 80\nInput: price[] = {100, 30, 15, 10, 8, 25, 80};\nOutput: 72\nBuy at price 8 and sell at 80.\nInput: price[] = {90, 80, 70, 60, 50}\nOutput: 0\nNot possible to earn." }, { "code": null, "e": 27080, "s": 27009, "text": "A Simple Solution is to consider every index ‘i’ and do the following " }, { "code": null, "e": 27274, "s": 27080, "text": "Max profit with at most two transactions = MAX {max profit with one transaction and subarray price[0..i] + max profit with one transaction and subarray price[i+1..n-1] } i varies from 0 to n-1." }, { "code": null, "e": 27530, "s": 27274, "text": "Maximum possible using one transaction can be calculated using the following O(n) algorithm The maximum difference between two elements such that the larger element appears after the smaller numberThe time complexity of the above simple solution is O(n2)." }, { "code": null, "e": 27708, "s": 27530, "text": "We can do this O(n) using the following Efficient Solution. The idea is to store the maximum possible profit of every subarray and solve the problem in the following two phases." }, { "code": null, "e": 28159, "s": 27708, "text": "1) Create a table profit[0..n-1] and initialize all values in it 0.2) Traverse price[] from right to left and update profit[i] such that profit[i] stores maximum profit achievable from one transaction in subarray price[i..n-1]3) Traverse price[] from left to right and update profit[i] such that profit[i] stores maximum profit such that profit[i] contains maximum achievable profit from two transactions in subarray price[0..i].4) Return profit[n-1]" }, { "code": null, "e": 28659, "s": 28159, "text": "To do step 2, we need to keep track of the maximum price from right to left side, and to do step 3, we need to keep track of the minimum price from left to right. Why we traverse in reverse directions? The idea is to save space, in the third step, we use the same array for both purposes, maximum with 1 transaction and maximum with 2 transactions. After iteration i, the array profit[0..i] contains the maximum profit with 2 transactions, and profit[i+1..n-1] contains profit with two transactions." }, { "code": null, "e": 28708, "s": 28659, "text": "Below are the implementations of the above idea." }, { "code": null, "e": 28712, "s": 28708, "text": "C++" }, { "code": null, "e": 28717, "s": 28712, "text": "Java" }, { "code": null, "e": 28725, "s": 28717, "text": "Python3" }, { "code": null, "e": 28728, "s": 28725, "text": "C#" }, { "code": null, "e": 28732, "s": 28728, "text": "PHP" }, { "code": null, "e": 28743, "s": 28732, "text": "Javascript" }, { "code": "// C++ program to find maximum// possible profit with at most// two transactions#include <bits/stdc++.h>using namespace std; // Returns maximum profit with// two transactions on a given// list of stock prices, price[0..n-1]int maxProfit(int price[], int n){ // Create profit array and // initialize it as 0 int* profit = new int[n]; for (int i = 0; i < n; i++) profit[i] = 0; /* Get the maximum profit with only one transaction allowed. After this loop, profit[i] contains maximum profit from price[i..n-1] using at most one trans. */ int max_price = price[n - 1]; for (int i = n - 2; i >= 0; i--) { // max_price has maximum // of price[i..n-1] if (price[i] > max_price) max_price = price[i]; // we can get profit[i] by taking maximum of: // a) previous maximum, i.e., profit[i+1] // b) profit by buying at price[i] and selling at // max_price profit[i] = max(profit[i + 1], max_price - price[i]); } /* Get the maximum profit with two transactions allowed After this loop, profit[n-1] contains the result */ int min_price = price[0]; for (int i = 1; i < n; i++) { // min_price is minimum price in price[0..i] if (price[i] < min_price) min_price = price[i]; // Maximum profit is maximum of: // a) previous maximum, i.e., profit[i-1] // b) (Buy, Sell) at (min_price, price[i]) and add // profit of other trans. stored in profit[i] profit[i] = max(profit[i - 1], profit[i] + (price[i] - min_price)); } int result = profit[n - 1]; delete[] profit; // To avoid memory leak return result;} // Driver codeint main(){ int price[] = { 2, 30, 15, 10, 8, 25, 80 }; int n = sizeof(price) / sizeof(price[0]); cout << \"Maximum Profit = \" << maxProfit(price, n); return 0;}", "e": 30675, "s": 28743, "text": null }, { "code": "class Profit { // Returns maximum profit // with two transactions on a // given list of stock prices, // price[0..n-1] static int maxProfit(int price[], int n) { // Create profit array // and initialize it as 0 int profit[] = new int[n]; for (int i = 0; i < n; i++) profit[i] = 0; /* Get the maximum profit with only one transaction allowed. After this loop, profit[i] contains maximum profit from price[i..n-1] using at most one trans. */ int max_price = price[n - 1]; for (int i = n - 2; i >= 0; i--) { // max_price has maximum // of price[i..n-1] if (price[i] > max_price) max_price = price[i]; // we can get profit[i] // by taking maximum of: // a) previous maximum, // i.e., profit[i+1] // b) profit by buying // at price[i] and selling // at // max_price profit[i] = Math.max(profit[i + 1], max_price - price[i]); } /* Get the maximum profit with two transactions allowed After this loop, profit[n-1] contains the result */ int min_price = price[0]; for (int i = 1; i < n; i++) { // min_price is minimum // price in price[0..i] if (price[i] < min_price) min_price = price[i]; // Maximum profit is maximum of: // a) previous maximum, i.e., profit[i-1] // b) (Buy, Sell) at (min_price, price[i]) and // add // profit of other trans. // stored in profit[i] profit[i] = Math.max( profit[i - 1], profit[i] + (price[i] - min_price)); } int result = profit[n - 1]; return result; } // Driver Code public static void main(String args[]) { int price[] = { 2, 30, 15, 10, 8, 25, 80 }; int n = price.length; System.out.println(\"Maximum Profit = \" + maxProfit(price, n)); } } /* This code is contributed by Rajat Mishra */", "e": 32921, "s": 30675, "text": null }, { "code": "# Returns maximum profit with# two transactions on a given# list of stock prices price[0..n-1] def maxProfit(price, n): # Create profit array and initialize it as 0 profit = [0]*n # Get the maximum profit # with only one transaction # allowed. After this loop, # profit[i] contains maximum # profit from price[i..n-1] # using at most one trans. max_price = price[n-1] for i in range(n-2, 0, -1): if price[i] > max_price: max_price = price[i] # we can get profit[i] by # taking maximum of: # a) previous maximum, # i.e., profit[i+1] # b) profit by buying at # price[i] and selling at # max_price profit[i] = max(profit[i+1], max_price - price[i]) # Get the maximum profit # with two transactions allowed # After this loop, profit[n-1] # contains the result min_price = price[0] for i in range(1, n): if price[i] < min_price: min_price = price[i] # Maximum profit is maximum of: # a) previous maximum, # i.e., profit[i-1] # b) (Buy, Sell) at # (min_price, A[i]) and add # profit of other trans. # stored in profit[i] profit[i] = max(profit[i-1], profit[i]+(price[i]-min_price)) result = profit[n-1] return result # Driver functionprice = [2, 30, 15, 10, 8, 25, 80]print (\"Maximum profit is\", maxProfit(price, len(price))) # This code is contributed by __Devesh Agrawal__", "e": 34409, "s": 32921, "text": null }, { "code": "// C# program to find maximum possible profit// with at most two transactionsusing System; class GFG { // Returns maximum profit with two // transactions on a given list of // stock prices, price[0..n-1] static int maxProfit(int[] price, int n) { // Create profit array and initialize // it as 0 int[] profit = new int[n]; for (int i = 0; i < n; i++) profit[i] = 0; /* Get the maximum profit with only one transaction allowed. After this loop, profit[i] contains maximum profit from price[i..n-1] using at most one trans. */ int max_price = price[n - 1]; for (int i = n - 2; i >= 0; i--) { // max_price has maximum of // price[i..n-1] if (price[i] > max_price) max_price = price[i]; // we can get profit[i] by taking // maximum of: // a) previous maximum, i.e., // profit[i+1] // b) profit by buying at price[i] // and selling at max_price profit[i] = Math.Max(profit[i + 1], max_price - price[i]); } /* Get the maximum profit with two transactions allowed After this loop, profit[n-1] contains the result */ int min_price = price[0]; for (int i = 1; i < n; i++) { // min_price is minimum price in // price[0..i] if (price[i] < min_price) min_price = price[i]; // Maximum profit is maximum of: // a) previous maximum, i.e., // profit[i-1] // b) (Buy, Sell) at (min_price, // price[i]) and add profit of // other trans. stored in // profit[i] profit[i] = Math.Max( profit[i - 1], profit[i] + (price[i] - min_price)); } int result = profit[n - 1]; return result; } // Driver code public static void Main() { int[] price = { 2, 30, 15, 10, 8, 25, 80 }; int n = price.Length; Console.Write(\"Maximum Profit = \" + maxProfit(price, n)); }} // This code is contributed by nitin mittal.", "e": 36646, "s": 34409, "text": null }, { "code": "<?php// PHP program to find maximum// possible profit with at most// two transactions // Returns maximum profit with// two transactions on a given// list of stock prices, price[0..n-1]function maxProfit($price, $n){ // Create profit array and // initialize it as 0 $profit = array(); for ($i = 0; $i < $n; $i++) $profit[$i] = 0; // Get the maximum profit with // only one transaction allowed. // After this loop, profit[i] // contains maximum profit from // price[i..n-1] using at most // one trans. $max_price = $price[$n - 1]; for ($i = $n - 2; $i >= 0; $i--) { // max_price has maximum // of price[i..n-1] if ($price[$i] > $max_price) $max_price = $price[$i]; // we can get profit[i] by // taking maximum of: // a) previous maximum, // i.e., profit[i+1] // b) profit by buying at // price[i] and selling at // max_price if($profit[$i + 1] > $max_price-$price[$i]) $profit[$i] = $profit[$i + 1]; else $profit[$i] = $max_price - $price[$i]; } // Get the maximum profit with // two transactions allowed. // After this loop, profit[n-1] // contains the result $min_price = $price[0]; for ($i = 1; $i < $n; $i++) { // min_price is minimum // price in price[0..i] if ($price[$i] < $min_price) $min_price = $price[$i]; // Maximum profit is maximum of: // a) previous maximum, // i.e., profit[i-1] // b) (Buy, Sell) at (min_price, // price[i]) and add // profit of other trans. // stored in profit[i] $profit[$i] = max($profit[$i - 1], $profit[$i] + ($price[$i] - $min_price)); } $result = $profit[$n - 1]; return $result;} // Driver Code$price = array(2, 30, 15, 10, 8, 25, 80);$n = sizeof($price);echo \"Maximum Profit = \". maxProfit($price, $n); // This code is contributed// by Arnab Kundu?>", "e": 38729, "s": 36646, "text": null }, { "code": "<script> // JavaScript program to find maximum// possible profit with at most// two transactions // Returns maximum profit with// two transactions on a given// list of stock prices, price[0..n-1]function maxProfit(price, n){ // Create profit array and // initialize it as 0 let profit = new Array(n); for(let i = 0; i < n; i++) profit[i] = 0; /* Get the maximum profit with only one transaction allowed. After this loop, profit[i] contains maximum profit from price[i..n-1] using at most one trans. */ let max_price = price[n - 1]; for(let i = n - 2; i >= 0; i--) { // max_price has maximum // of price[i..n-1] if (price[i] > max_price) max_price = price[i]; // We can get profit[i] by taking maximum of: // a) previous maximum, i.e., profit[i+1] // b) profit by buying at price[i] and selling at // max_price profit[i] = Math.max(profit[i + 1], max_price - price[i]); } // Get the maximum profit with // two transactions allowed // After this loop, profit[n-1] // contains the result let min_price = price[0]; for(let i = 1; i < n; i++) { // min_price is minimum price // in price[0..i] if (price[i] < min_price) min_price = price[i]; // Maximum profit is maximum of: // a) previous maximum, i.e., profit[i-1] // b) (Buy, Sell) at (min_price, price[i]) and add // profit of other trans. stored in profit[i] profit[i] = Math.max(profit[i - 1], profit[i] + (price[i] - min_price)); } let result = profit[n - 1]; return result;} // Driver codelet price = [ 2, 30, 15, 10, 8, 25, 80 ];let n = price.length; document.write(\"Maximum Profit = \" + maxProfit(price, n)); // This code is contributed by Surbhi Tyagi. </script>", "e": 40644, "s": 38729, "text": null }, { "code": null, "e": 40668, "s": 40647, "text": "Maximum Profit = 100" }, { "code": null, "e": 40720, "s": 40668, "text": "The time complexity of the above solution is O(n). " }, { "code": null, "e": 40763, "s": 40720, "text": "Algorithmic Paradigm: Dynamic Programming " }, { "code": null, "e": 40781, "s": 40763, "text": "Another approach:" }, { "code": null, "e": 41087, "s": 40781, "text": "Initialize four variables for taking care of the first buy, first sell, second buy, second sell. Set first buy and second buy as INT_MIN and first and second sell as 0. This is to ensure to get profit from transactions. Iterate through the array and return the second sell as it will store maximum profit." }, { "code": null, "e": 41091, "s": 41087, "text": "C++" }, { "code": null, "e": 41096, "s": 41091, "text": "Java" }, { "code": null, "e": 41104, "s": 41096, "text": "Python3" }, { "code": null, "e": 41107, "s": 41104, "text": "C#" }, { "code": null, "e": 41118, "s": 41107, "text": "Javascript" }, { "code": "#include <iostream>#include<climits>using namespace std; int maxtwobuysell(int arr[],int size) { int first_buy = INT_MIN; int first_sell = 0; int second_buy = INT_MIN; int second_sell = 0; for(int i=0;i<size;i++) { first_buy = max(first_buy,-arr[i]);//we set prices to negative, so the calculation of profit will be convenient first_sell = max(first_sell,first_buy+arr[i]); second_buy = max(second_buy,first_sell-arr[i]);//we can buy the second only after first is sold second_sell = max(second_sell,second_buy+arr[i]); } return second_sell;} int main() { int arr[] = {2, 30, 15, 10, 8, 25, 80}; int size = sizeof(arr)/sizeof(arr[0]); cout<<maxtwobuysell(arr,size); return 0;}", "e": 41901, "s": 41118, "text": null }, { "code": "import java.util.*;class GFG{ static int maxtwobuysell(int arr[],int size) { int first_buy = Integer.MIN_VALUE; int first_sell = 0; int second_buy = Integer.MIN_VALUE; int second_sell = 0; for(int i = 0; i < size; i++) { first_buy = Math.max(first_buy,-arr[i]); first_sell = Math.max(first_sell,first_buy+arr[i]); second_buy = Math.max(second_buy,first_sell-arr[i]); second_sell = Math.max(second_sell,second_buy+arr[i]); } return second_sell;} public static void main(String[] args){ int arr[] = {2, 30, 15, 10, 8, 25, 80}; int size = arr.length; System.out.print(maxtwobuysell(arr,size));}} // This code is contributed by gauravrajput1", "e": 42641, "s": 41901, "text": null }, { "code": "import sys def maxtwobuysell(arr, size): first_buy = -sys.maxsize; first_sell = 0; second_buy = -sys.maxsize; second_sell = 0; for i in range(size): first_buy = max(first_buy, -arr[i]); first_sell = max(first_sell, first_buy + arr[i]); second_buy = max(second_buy, first_sell - arr[i]); second_sell = max(second_sell, second_buy + arr[i]); return second_sell; if __name__ == '__main__': arr = [ 2, 30, 15, 10, 8, 25, 80 ]; size = len(arr); print(maxtwobuysell(arr, size)); # This code is contributed by gauravrajput1", "e": 43221, "s": 42641, "text": null }, { "code": "using System; public class GFG{ static int maxtwobuysell(int []arr,int size) { int first_buy = int.MinValue; int first_sell = 0; int second_buy = int.MinValue; int second_sell = 0; for(int i = 0; i < size; i++) { first_buy = Math.Max(first_buy,-arr[i]); first_sell = Math.Max(first_sell,first_buy+arr[i]); second_buy = Math.Max(second_buy,first_sell-arr[i]); second_sell = Math.Max(second_sell,second_buy+arr[i]); } return second_sell;} public static void Main(String[] args){ int []arr = {2, 30, 15, 10, 8, 25, 80}; int size = arr.Length; Console.Write(maxtwobuysell(arr,size));}} // This code is contributed by gauravrajput1", "e": 43950, "s": 43221, "text": null }, { "code": "<script> function maxtwobuysell(arr , size) { var first_buy = -1000; var first_sell = 0; var second_buy = -1000; var second_sell = 0; for (var i = 0; i < size; i++) { first_buy = Math.max(first_buy, -arr[i]); first_sell = Math.max(first_sell, first_buy + arr[i]); second_buy = Math.max(second_buy, first_sell - arr[i]); second_sell = Math.max(second_sell, second_buy + arr[i]); } return second_sell; } var arr = [ 2, 30, 15, 10, 8, 25, 80 ]; var size = arr.length; document.write(maxtwobuysell(arr, size)); // This code is contributed by gauravrajput1</script>", "e": 44640, "s": 43950, "text": null }, { "code": null, "e": 44644, "s": 44640, "text": "100" }, { "code": null, "e": 44666, "s": 44644, "text": "Time Complexity: O(N)" }, { "code": null, "e": 44688, "s": 44666, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 44701, "s": 44688, "text": "nitin mittal" }, { "code": null, "e": 44712, "s": 44701, "text": "andrew1234" }, { "code": null, "e": 44721, "s": 44712, "text": "rambabuy" }, { "code": null, "e": 44732, "s": 44721, "text": "nidhi_biet" }, { "code": null, "e": 44743, "s": 44732, "text": "doshiruhal" }, { "code": null, "e": 44752, "s": 44743, "text": "marix101" }, { "code": null, "e": 44770, "s": 44752, "text": "divyeshrabadiya07" }, { "code": null, "e": 44782, "s": 44770, "text": "Mukul Lunia" }, { "code": null, "e": 44797, "s": 44782, "text": "katariarishu95" }, { "code": null, "e": 44809, "s": 44797, "text": "RohitOberoi" }, { "code": null, "e": 44823, "s": 44809, "text": "surbhityagi15" }, { "code": null, "e": 44833, "s": 44823, "text": "Rajput-Ji" }, { "code": null, "e": 44851, "s": 44833, "text": "pranavkushwaha506" }, { "code": null, "e": 44864, "s": 44851, "text": "rajsanghavi9" }, { "code": null, "e": 44879, "s": 44864, "text": "ambujsingh2000" }, { "code": null, "e": 44894, "s": 44879, "text": "dewanshipaul84" }, { "code": null, "e": 44906, "s": 44894, "text": "umadevi9616" }, { "code": null, "e": 44920, "s": 44906, "text": "GauravRajput1" }, { "code": null, "e": 44930, "s": 44920, "text": "juyal_sid" }, { "code": null, "e": 44946, "s": 44930, "text": "amartyaghoshgfg" }, { "code": null, "e": 44964, "s": 44946, "text": "sharmanandini1677" }, { "code": null, "e": 44984, "s": 44964, "text": "Dynamic Programming" }, { "code": null, "e": 44997, "s": 44984, "text": "Mathematical" }, { "code": null, "e": 45017, "s": 44997, "text": "Dynamic Programming" }, { "code": null, "e": 45030, "s": 45017, "text": "Mathematical" }, { "code": null, "e": 45128, "s": 45030, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45161, "s": 45128, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 45196, "s": 45161, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 45264, "s": 45196, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 45285, "s": 45264, "text": "Edit Distance | DP-5" }, { "code": null, "e": 45348, "s": 45285, "text": "Overlapping Subproblems Property in Dynamic Programming | DP-1" }, { "code": null, "e": 45408, "s": 45348, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 45423, "s": 45408, "text": "C++ Data Types" }, { "code": null, "e": 45466, "s": 45423, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 45490, "s": 45466, "text": "Merge two sorted arrays" } ]
Sort a string in increasing order of given priorities - GeeksforGeeks
10 Jun, 2021 Given an alphanumeric string S of length N, the task is to sort the string in increasing order of their priority based on the following conditions: Characters with even ASCII values have higher priority than characters with odd ASCII values. Even digits have higher priority than odd digits. Digits have higher priority than characters. For characters or digits having the same parity, the priority is in increasing order of their ASCII values. Examples: Input: S = “abcd1234”Output: 1324bdacExplanation: The ASCII value of “a” is 97.The ASCII value of “b” is 98.The ASCII value of “c” is 99.The ASCII value of “d” is 100.Since characters with even ASCII value have higher priority, “b” and “d” are placed first followed by “a” and “c”.Similarly, even digits have more priority than odd digits. Therefore, they are placed first.Since the numbers have a higher priority than characters, the sorted string is “1324bdac” Input: S = “adb123”Output: bda132 Approach: The idea is to separate the characters with odd and even ASCII values and also the digits with odd and even parity. Then, join these substrings in the order of their priorities. Follow the steps below to solve the problem: Initialize two variables, say digits and characters, to store the characters and digits separately.Sort the strings digits and characters with respect to the ASCII table.Now, traverse all the characters in characters and append each character with an odd parity to a variable say oddChars and each character with an even parity to another variable say, evenChars.Similarly, for the string digits, separate the odd and even parity digits, say oddDigs and evenDigs.Finally, concatenate the string as oddChars + evenChars + oddDigs + evenDigs. Initialize two variables, say digits and characters, to store the characters and digits separately. Sort the strings digits and characters with respect to the ASCII table. Now, traverse all the characters in characters and append each character with an odd parity to a variable say oddChars and each character with an even parity to another variable say, evenChars. Similarly, for the string digits, separate the odd and even parity digits, say oddDigs and evenDigs. Finally, concatenate the string as oddChars + evenChars + oddDigs + evenDigs. Below is the implementation of the above approach: C++14 Java Python3 C# Javascript // C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to sort the string s// based on the given conditionsstring sortString(string s){ // Stores digits of given string string digits = ""; // Stores characters of given string string character = ""; // Iterate over characters of the string for (int i = 0; i < s.size(); ++i) { if (s[i] >= '0' && s[i] <= '9') { digits += s[i]; } else { character += s[i]; } } // Sort the string of digits sort(digits.begin(), digits.end()); // Sort the string of characters sort(character.begin(), character.end()); // Stores odd and even characters string OddChar = "", EvenChar = ""; // Separate odd and even digits for (int i = 0; i < digits.length(); ++i) { if ((digits[i] - '0') % 2 == 1) { OddChar += digits[i]; } else { EvenChar += digits[i]; } } // Concatenate strings in the order // odd characters followed by even OddChar += EvenChar; EvenChar = ""; // Separate the odd and even chars for (int i = 0; i < character.length(); ++i) { if ((character[i] - 'a') % 2 == 1) { OddChar += character[i]; } else { EvenChar += character[i]; } } // Final string OddChar += EvenChar; // Return the final string return OddChar; } // Driver Code int main() { // Given string string s = "abcd1234"; // Returns the sorted string cout << sortString(s); return 0; } // Java program for the above approachimport java.util.*;class GFG{ // Function to sort the String s // based on the given conditions static String sortString(String s) { // Stores digits of given String String digits = ""; // Stores characters of given String String character = ""; // Iterate over characters of the String for (int i = 0; i < s.length(); ++i) { if (s.charAt(i) >= '0' && s.charAt(i) <= '9') { digits += s.charAt(i); } else { character += s.charAt(i); } } // Sort the String of digits digits = sort(digits); // Sort the String of characters character = sort(character); // Stores odd and even characters String OddChar = "", EvenChar = ""; // Separate odd and even digits for (int i = 0; i < digits.length(); ++i) { if ((digits.charAt(i) - '0') % 2 == 1) { OddChar += digits.charAt(i); } else { EvenChar += digits.charAt(i); } } // Concatenate Strings in the order // odd characters followed by even OddChar += EvenChar; EvenChar = ""; // Separate the odd and even chars for (int i = 0; i < character.length(); ++i) { if ((character.charAt(i) - 'a') % 2 == 1) { OddChar += character.charAt(i); } else { EvenChar += character.charAt(i); } } // Final String OddChar += EvenChar; // Return the final String return OddChar; } static String sort(String inputString) { // convert input string to char array char tempArray[] = inputString.toCharArray(); // sort tempArray Arrays.sort(tempArray); // return new sorted string return new String(tempArray); } // Driver Code public static void main(String[] args) { // Given String String s = "abcd1234"; // Returns the sorted String System.out.print(sortString(s)); }} // This code is contributed by shikhasingrajput # Python3 program for the above approach # Function to sort the string s# based on the given conditionsdef sortString(s): # Stores digits of given string digits = "" # Stores characters of given string character = "" # Iterate over characters of the string for i in range(len(s)): if (s[i] >= '0' and s[i] <= '9'): digits += s[i] else: character += s[i] # Sort the string of digits Digits = list(digits) Digits.sort() # Sort the string of characters Character = list(character) Character.sort() # Stores odd and even characters OddChar, EvenChar = "", "" # Separate odd and even digits for i in range(len(Digits)): if ((ord(digits[i]) - ord('0')) % 2 == 1): OddChar += Digits[i] else: EvenChar += Digits[i] # Concatenate strings in the order # odd characters followed by even OddChar += EvenChar EvenChar = "" # Separate the odd and even chars for i in range(len(Character)): if ((ord(Character[i]) - ord('a')) % 2 == 1): OddChar += Character[i] else: EvenChar += Character[i] # Final string OddChar += EvenChar # Return the final string return OddChar # Driver Code # Given strings = "abcd1234" # Returns the sorted stringprint(sortString(list(s))) # This code is contributed by divyesh072019 // C# program for the above approachusing System;class GFG{ // Function to sort the string s // based on the given conditions static string sortString(char[] s) { // Stores digits of given string string digits = ""; // Stores characters of given string string character = ""; // Iterate over characters of the string for (int i = 0; i < s.Length; ++i) { if (s[i] >= '0' && s[i] <= '9') { digits += s[i]; } else { character += s[i]; } } // Sort the string of digits char[] Digits = digits.ToCharArray(); Array.Sort(Digits); // Sort the string of characters char[] Character = character.ToCharArray(); Array.Sort(Character); // Stores odd and even characters string OddChar = "", EvenChar = ""; // Separate odd and even digits for (int i = 0; i < Digits.Length; ++i) { if ((digits[i] - '0') % 2 == 1) { OddChar += Digits[i]; } else { EvenChar += Digits[i]; } } // Concatenate strings in the order // odd characters followed by even OddChar += EvenChar; EvenChar = ""; // Separate the odd and even chars for (int i = 0; i < Character.Length; ++i) { if ((Character[i] - 'a') % 2 == 1) { OddChar += Character[i]; } else { EvenChar += Character[i]; } } // Final string OddChar += EvenChar; // Return the final string return OddChar; } // Driver code static void Main() { // Given string string s = "abcd1234"; // Returns the sorted string Console.WriteLine(sortString(s.ToCharArray())); }} // This code is contributed by divyehrabadiya07 <script> // Javascript program for the above approach // Function to sort the string s // based on the given conditions function sortString(s) { // Stores digits of given string let digits = ""; // Stores characters of given string let character = ""; // Iterate over characters of the string for (let i = 0; i < s.length; ++i) { if (s[i].charCodeAt() >= '0'.charCodeAt() && s[i].charCodeAt() <= '9'.charCodeAt()) { digits += s[i]; } else { character += s[i]; } } // Sort the string of digits let Digits = digits.split(''); Digits.sort(); // Sort the string of characters let Character = character.split(''); Character.sort(); // Stores odd and even characters let OddChar = "", EvenChar = ""; // Separate odd and even digits for (let i = 0; i < Digits.length; ++i) { if ((digits[i].charCodeAt() - '0'.charCodeAt()) % 2 == 1) { OddChar += Digits[i]; } else { EvenChar += Digits[i]; } } // Concatenate strings in the order // odd characters followed by even OddChar += EvenChar; EvenChar = ""; // Separate the odd and even chars for (let i = 0; i < Character.length; ++i) { if ((Character[i].charCodeAt() - 'a'.charCodeAt()) % 2 == 1) { OddChar += Character[i]; } else { EvenChar += Character[i]; } } // Final string OddChar += EvenChar; // Return the final string return OddChar; } // Given string let s = "abcd1234"; // Returns the sorted string document.write(sortString(s.split(''))); // This code is contributed by suresh07.</script> 1324bdac Time Complexity: O(N)Auxiliary Space: O(N) divyeshrabadiya07 shikhasingrajput divyesh072019 suresh07 clintra ASCII substring Mathematical Sorting Strings Strings Mathematical Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Sieve of Eratosthenes
[ { "code": null, "e": 26841, "s": 26813, "text": "\n10 Jun, 2021" }, { "code": null, "e": 26989, "s": 26841, "text": "Given an alphanumeric string S of length N, the task is to sort the string in increasing order of their priority based on the following conditions:" }, { "code": null, "e": 27083, "s": 26989, "text": "Characters with even ASCII values have higher priority than characters with odd ASCII values." }, { "code": null, "e": 27133, "s": 27083, "text": "Even digits have higher priority than odd digits." }, { "code": null, "e": 27178, "s": 27133, "text": "Digits have higher priority than characters." }, { "code": null, "e": 27286, "s": 27178, "text": "For characters or digits having the same parity, the priority is in increasing order of their ASCII values." }, { "code": null, "e": 27296, "s": 27286, "text": "Examples:" }, { "code": null, "e": 27759, "s": 27296, "text": "Input: S = “abcd1234”Output: 1324bdacExplanation: The ASCII value of “a” is 97.The ASCII value of “b” is 98.The ASCII value of “c” is 99.The ASCII value of “d” is 100.Since characters with even ASCII value have higher priority, “b” and “d” are placed first followed by “a” and “c”.Similarly, even digits have more priority than odd digits. Therefore, they are placed first.Since the numbers have a higher priority than characters, the sorted string is “1324bdac”" }, { "code": null, "e": 27793, "s": 27759, "text": "Input: S = “adb123”Output: bda132" }, { "code": null, "e": 28026, "s": 27793, "text": "Approach: The idea is to separate the characters with odd and even ASCII values and also the digits with odd and even parity. Then, join these substrings in the order of their priorities. Follow the steps below to solve the problem:" }, { "code": null, "e": 28567, "s": 28026, "text": "Initialize two variables, say digits and characters, to store the characters and digits separately.Sort the strings digits and characters with respect to the ASCII table.Now, traverse all the characters in characters and append each character with an odd parity to a variable say oddChars and each character with an even parity to another variable say, evenChars.Similarly, for the string digits, separate the odd and even parity digits, say oddDigs and evenDigs.Finally, concatenate the string as oddChars + evenChars + oddDigs + evenDigs." }, { "code": null, "e": 28667, "s": 28567, "text": "Initialize two variables, say digits and characters, to store the characters and digits separately." }, { "code": null, "e": 28739, "s": 28667, "text": "Sort the strings digits and characters with respect to the ASCII table." }, { "code": null, "e": 28933, "s": 28739, "text": "Now, traverse all the characters in characters and append each character with an odd parity to a variable say oddChars and each character with an even parity to another variable say, evenChars." }, { "code": null, "e": 29034, "s": 28933, "text": "Similarly, for the string digits, separate the odd and even parity digits, say oddDigs and evenDigs." }, { "code": null, "e": 29112, "s": 29034, "text": "Finally, concatenate the string as oddChars + evenChars + oddDigs + evenDigs." }, { "code": null, "e": 29163, "s": 29112, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 29169, "s": 29163, "text": "C++14" }, { "code": null, "e": 29174, "s": 29169, "text": "Java" }, { "code": null, "e": 29182, "s": 29174, "text": "Python3" }, { "code": null, "e": 29185, "s": 29182, "text": "C#" }, { "code": null, "e": 29196, "s": 29185, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to sort the string s// based on the given conditionsstring sortString(string s){ // Stores digits of given string string digits = \"\"; // Stores characters of given string string character = \"\"; // Iterate over characters of the string for (int i = 0; i < s.size(); ++i) { if (s[i] >= '0' && s[i] <= '9') { digits += s[i]; } else { character += s[i]; } } // Sort the string of digits sort(digits.begin(), digits.end()); // Sort the string of characters sort(character.begin(), character.end()); // Stores odd and even characters string OddChar = \"\", EvenChar = \"\"; // Separate odd and even digits for (int i = 0; i < digits.length(); ++i) { if ((digits[i] - '0') % 2 == 1) { OddChar += digits[i]; } else { EvenChar += digits[i]; } } // Concatenate strings in the order // odd characters followed by even OddChar += EvenChar; EvenChar = \"\"; // Separate the odd and even chars for (int i = 0; i < character.length(); ++i) { if ((character[i] - 'a') % 2 == 1) { OddChar += character[i]; } else { EvenChar += character[i]; } } // Final string OddChar += EvenChar; // Return the final string return OddChar; } // Driver Code int main() { // Given string string s = \"abcd1234\"; // Returns the sorted string cout << sortString(s); return 0; }", "e": 30663, "s": 29196, "text": null }, { "code": "// Java program for the above approachimport java.util.*;class GFG{ // Function to sort the String s // based on the given conditions static String sortString(String s) { // Stores digits of given String String digits = \"\"; // Stores characters of given String String character = \"\"; // Iterate over characters of the String for (int i = 0; i < s.length(); ++i) { if (s.charAt(i) >= '0' && s.charAt(i) <= '9') { digits += s.charAt(i); } else { character += s.charAt(i); } } // Sort the String of digits digits = sort(digits); // Sort the String of characters character = sort(character); // Stores odd and even characters String OddChar = \"\", EvenChar = \"\"; // Separate odd and even digits for (int i = 0; i < digits.length(); ++i) { if ((digits.charAt(i) - '0') % 2 == 1) { OddChar += digits.charAt(i); } else { EvenChar += digits.charAt(i); } } // Concatenate Strings in the order // odd characters followed by even OddChar += EvenChar; EvenChar = \"\"; // Separate the odd and even chars for (int i = 0; i < character.length(); ++i) { if ((character.charAt(i) - 'a') % 2 == 1) { OddChar += character.charAt(i); } else { EvenChar += character.charAt(i); } } // Final String OddChar += EvenChar; // Return the final String return OddChar; } static String sort(String inputString) { // convert input string to char array char tempArray[] = inputString.toCharArray(); // sort tempArray Arrays.sort(tempArray); // return new sorted string return new String(tempArray); } // Driver Code public static void main(String[] args) { // Given String String s = \"abcd1234\"; // Returns the sorted String System.out.print(sortString(s)); }} // This code is contributed by shikhasingrajput", "e": 32853, "s": 30663, "text": null }, { "code": "# Python3 program for the above approach # Function to sort the string s# based on the given conditionsdef sortString(s): # Stores digits of given string digits = \"\" # Stores characters of given string character = \"\" # Iterate over characters of the string for i in range(len(s)): if (s[i] >= '0' and s[i] <= '9'): digits += s[i] else: character += s[i] # Sort the string of digits Digits = list(digits) Digits.sort() # Sort the string of characters Character = list(character) Character.sort() # Stores odd and even characters OddChar, EvenChar = \"\", \"\" # Separate odd and even digits for i in range(len(Digits)): if ((ord(digits[i]) - ord('0')) % 2 == 1): OddChar += Digits[i] else: EvenChar += Digits[i] # Concatenate strings in the order # odd characters followed by even OddChar += EvenChar EvenChar = \"\" # Separate the odd and even chars for i in range(len(Character)): if ((ord(Character[i]) - ord('a')) % 2 == 1): OddChar += Character[i] else: EvenChar += Character[i] # Final string OddChar += EvenChar # Return the final string return OddChar # Driver Code # Given strings = \"abcd1234\" # Returns the sorted stringprint(sortString(list(s))) # This code is contributed by divyesh072019", "e": 34316, "s": 32853, "text": null }, { "code": "// C# program for the above approachusing System;class GFG{ // Function to sort the string s // based on the given conditions static string sortString(char[] s) { // Stores digits of given string string digits = \"\"; // Stores characters of given string string character = \"\"; // Iterate over characters of the string for (int i = 0; i < s.Length; ++i) { if (s[i] >= '0' && s[i] <= '9') { digits += s[i]; } else { character += s[i]; } } // Sort the string of digits char[] Digits = digits.ToCharArray(); Array.Sort(Digits); // Sort the string of characters char[] Character = character.ToCharArray(); Array.Sort(Character); // Stores odd and even characters string OddChar = \"\", EvenChar = \"\"; // Separate odd and even digits for (int i = 0; i < Digits.Length; ++i) { if ((digits[i] - '0') % 2 == 1) { OddChar += Digits[i]; } else { EvenChar += Digits[i]; } } // Concatenate strings in the order // odd characters followed by even OddChar += EvenChar; EvenChar = \"\"; // Separate the odd and even chars for (int i = 0; i < Character.Length; ++i) { if ((Character[i] - 'a') % 2 == 1) { OddChar += Character[i]; } else { EvenChar += Character[i]; } } // Final string OddChar += EvenChar; // Return the final string return OddChar; } // Driver code static void Main() { // Given string string s = \"abcd1234\"; // Returns the sorted string Console.WriteLine(sortString(s.ToCharArray())); }} // This code is contributed by divyehrabadiya07", "e": 36017, "s": 34316, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to sort the string s // based on the given conditions function sortString(s) { // Stores digits of given string let digits = \"\"; // Stores characters of given string let character = \"\"; // Iterate over characters of the string for (let i = 0; i < s.length; ++i) { if (s[i].charCodeAt() >= '0'.charCodeAt() && s[i].charCodeAt() <= '9'.charCodeAt()) { digits += s[i]; } else { character += s[i]; } } // Sort the string of digits let Digits = digits.split(''); Digits.sort(); // Sort the string of characters let Character = character.split(''); Character.sort(); // Stores odd and even characters let OddChar = \"\", EvenChar = \"\"; // Separate odd and even digits for (let i = 0; i < Digits.length; ++i) { if ((digits[i].charCodeAt() - '0'.charCodeAt()) % 2 == 1) { OddChar += Digits[i]; } else { EvenChar += Digits[i]; } } // Concatenate strings in the order // odd characters followed by even OddChar += EvenChar; EvenChar = \"\"; // Separate the odd and even chars for (let i = 0; i < Character.length; ++i) { if ((Character[i].charCodeAt() - 'a'.charCodeAt()) % 2 == 1) { OddChar += Character[i]; } else { EvenChar += Character[i]; } } // Final string OddChar += EvenChar; // Return the final string return OddChar; } // Given string let s = \"abcd1234\"; // Returns the sorted string document.write(sortString(s.split(''))); // This code is contributed by suresh07.</script>", "e": 37849, "s": 36017, "text": null }, { "code": null, "e": 37858, "s": 37849, "text": "1324bdac" }, { "code": null, "e": 37903, "s": 37860, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 37923, "s": 37905, "text": "divyeshrabadiya07" }, { "code": null, "e": 37940, "s": 37923, "text": "shikhasingrajput" }, { "code": null, "e": 37954, "s": 37940, "text": "divyesh072019" }, { "code": null, "e": 37963, "s": 37954, "text": "suresh07" }, { "code": null, "e": 37971, "s": 37963, "text": "clintra" }, { "code": null, "e": 37977, "s": 37971, "text": "ASCII" }, { "code": null, "e": 37987, "s": 37977, "text": "substring" }, { "code": null, "e": 38000, "s": 37987, "text": "Mathematical" }, { "code": null, "e": 38008, "s": 38000, "text": "Sorting" }, { "code": null, "e": 38016, "s": 38008, "text": "Strings" }, { "code": null, "e": 38024, "s": 38016, "text": "Strings" }, { "code": null, "e": 38037, "s": 38024, "text": "Mathematical" }, { "code": null, "e": 38045, "s": 38037, "text": "Sorting" }, { "code": null, "e": 38143, "s": 38045, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38167, "s": 38143, "text": "Merge two sorted arrays" }, { "code": null, "e": 38210, "s": 38167, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 38224, "s": 38210, "text": "Prime Numbers" }, { "code": null, "e": 38266, "s": 38224, "text": "Program to find GCD or HCF of two numbers" } ]
std::next vs std::advance in C++ - GeeksforGeeks
02 Aug, 2017 std::advance and std::next are used to advance the iterator by a certain position, such that we can make the iterator point to a desired position. Although both have same purpose, but their implementation is different from each other. This makes it important for us to understand the difference between the two.In C++11, std::next() will advance by one by default, whereas std::advance() requires a distance. Syntactical Difference: Syntax of std::advance and std::next is:// Definition of std::advance() template void advance( InputIt& it, Distance n ); it: Iterator to be advanced n: Distance to be advanced // Definition of std::next() ForwardIterator next (ForwardIterator it, typename iterator_traits::difference_type n = 1); it: Iterator pointing to base position n: Distance to be advanced from base position. Return type: std::advance does not return anything, whereas std::next returns an iterator after advancing n positions from the given base position.As in the syntax of std::next(), it will at least advance the iterator by one position, even if we do not specify the position which it has to advance as it has a default value one, whereas if we use std::advance, it has no such default argument.WorkingArgument Modification: std::advance modifies it arguments such that it points to the desired position, whereas, std::next does not modify its argument, infact it returns a new iterator pointing to the desired position.// C++ program to demonstrate// std::advance vs std::next#include <iostream>#include <iterator>#include <deque>#include <algorithm>using namespace std;int main(){ // Declaring first container deque<int> v1 = { 1, 2, 3 }; // Declaring second container for // copying values deque<int> v2 = { 4, 5, 6 }; deque<int>::iterator ii; ii = v1.begin(); // ii points to 1 in v1 deque<int>::iterator iii; iii = std::next(ii, 2); // ii not modified // For std::advance // std::advance(ii, 2) // ii modified and now points to 3 // Using copy() std::copy(ii, iii, std::back_inserter(v2)); // v2 now contains 4 5 6 1 2 // Displaying v1 and v2 cout << "v1 = "; int i; for (i = 0; i < 3; ++i) { cout << v1[i] << " "; } cout << "\nv2 = "; for (i = 0; i < 5; ++i) { cout << v2[i] << " "; } return 0;}Output:v1 = 1 2 3 v2 = 4 5 6 1 2 Explanation: As can be seen, we want to make ii point to 2 spaces ahead of where it is pointing, so if we use std::advance ii will be pointing to two spaces ahead, whereas if we use std::next, then ii will not be advanced, but an iterator pointing to the new position will be returned, and will be stored in iii.Pre-requisite: std::next requires the iterator passed as argument to be of type at least forward iterator, whereas std::advance doesnot have such restrictions, as it can work with any iterator, even with input iterator or better than it. Syntactical Difference: Syntax of std::advance and std::next is:// Definition of std::advance() template void advance( InputIt& it, Distance n ); it: Iterator to be advanced n: Distance to be advanced // Definition of std::next() ForwardIterator next (ForwardIterator it, typename iterator_traits::difference_type n = 1); it: Iterator pointing to base position n: Distance to be advanced from base position. Return type: std::advance does not return anything, whereas std::next returns an iterator after advancing n positions from the given base position.As in the syntax of std::next(), it will at least advance the iterator by one position, even if we do not specify the position which it has to advance as it has a default value one, whereas if we use std::advance, it has no such default argument. // Definition of std::advance() template void advance( InputIt& it, Distance n ); it: Iterator to be advanced n: Distance to be advanced // Definition of std::next() ForwardIterator next (ForwardIterator it, typename iterator_traits::difference_type n = 1); it: Iterator pointing to base position n: Distance to be advanced from base position. Return type: std::advance does not return anything, whereas std::next returns an iterator after advancing n positions from the given base position. As in the syntax of std::next(), it will at least advance the iterator by one position, even if we do not specify the position which it has to advance as it has a default value one, whereas if we use std::advance, it has no such default argument. WorkingArgument Modification: std::advance modifies it arguments such that it points to the desired position, whereas, std::next does not modify its argument, infact it returns a new iterator pointing to the desired position.// C++ program to demonstrate// std::advance vs std::next#include <iostream>#include <iterator>#include <deque>#include <algorithm>using namespace std;int main(){ // Declaring first container deque<int> v1 = { 1, 2, 3 }; // Declaring second container for // copying values deque<int> v2 = { 4, 5, 6 }; deque<int>::iterator ii; ii = v1.begin(); // ii points to 1 in v1 deque<int>::iterator iii; iii = std::next(ii, 2); // ii not modified // For std::advance // std::advance(ii, 2) // ii modified and now points to 3 // Using copy() std::copy(ii, iii, std::back_inserter(v2)); // v2 now contains 4 5 6 1 2 // Displaying v1 and v2 cout << "v1 = "; int i; for (i = 0; i < 3; ++i) { cout << v1[i] << " "; } cout << "\nv2 = "; for (i = 0; i < 5; ++i) { cout << v2[i] << " "; } return 0;}Output:v1 = 1 2 3 v2 = 4 5 6 1 2 Explanation: As can be seen, we want to make ii point to 2 spaces ahead of where it is pointing, so if we use std::advance ii will be pointing to two spaces ahead, whereas if we use std::next, then ii will not be advanced, but an iterator pointing to the new position will be returned, and will be stored in iii. Argument Modification: std::advance modifies it arguments such that it points to the desired position, whereas, std::next does not modify its argument, infact it returns a new iterator pointing to the desired position.// C++ program to demonstrate// std::advance vs std::next#include <iostream>#include <iterator>#include <deque>#include <algorithm>using namespace std;int main(){ // Declaring first container deque<int> v1 = { 1, 2, 3 }; // Declaring second container for // copying values deque<int> v2 = { 4, 5, 6 }; deque<int>::iterator ii; ii = v1.begin(); // ii points to 1 in v1 deque<int>::iterator iii; iii = std::next(ii, 2); // ii not modified // For std::advance // std::advance(ii, 2) // ii modified and now points to 3 // Using copy() std::copy(ii, iii, std::back_inserter(v2)); // v2 now contains 4 5 6 1 2 // Displaying v1 and v2 cout << "v1 = "; int i; for (i = 0; i < 3; ++i) { cout << v1[i] << " "; } cout << "\nv2 = "; for (i = 0; i < 5; ++i) { cout << v2[i] << " "; } return 0;}Output:v1 = 1 2 3 v2 = 4 5 6 1 2 Explanation: As can be seen, we want to make ii point to 2 spaces ahead of where it is pointing, so if we use std::advance ii will be pointing to two spaces ahead, whereas if we use std::next, then ii will not be advanced, but an iterator pointing to the new position will be returned, and will be stored in iii. // C++ program to demonstrate// std::advance vs std::next#include <iostream>#include <iterator>#include <deque>#include <algorithm>using namespace std;int main(){ // Declaring first container deque<int> v1 = { 1, 2, 3 }; // Declaring second container for // copying values deque<int> v2 = { 4, 5, 6 }; deque<int>::iterator ii; ii = v1.begin(); // ii points to 1 in v1 deque<int>::iterator iii; iii = std::next(ii, 2); // ii not modified // For std::advance // std::advance(ii, 2) // ii modified and now points to 3 // Using copy() std::copy(ii, iii, std::back_inserter(v2)); // v2 now contains 4 5 6 1 2 // Displaying v1 and v2 cout << "v1 = "; int i; for (i = 0; i < 3; ++i) { cout << v1[i] << " "; } cout << "\nv2 = "; for (i = 0; i < 5; ++i) { cout << v2[i] << " "; } return 0;} Output: v1 = 1 2 3 v2 = 4 5 6 1 2 Explanation: As can be seen, we want to make ii point to 2 spaces ahead of where it is pointing, so if we use std::advance ii will be pointing to two spaces ahead, whereas if we use std::next, then ii will not be advanced, but an iterator pointing to the new position will be returned, and will be stored in iii. Pre-requisite: std::next requires the iterator passed as argument to be of type at least forward iterator, whereas std::advance doesnot have such restrictions, as it can work with any iterator, even with input iterator or better than it. 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. cpp-iterator STL C++ Difference Between STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ C++ Classes and Objects Bitwise Operators in C/C++ Virtual Function in C++ Templates in C++ with Examples Difference between BFS and DFS Class method vs Static method in Python Differences between TCP and UDP Difference between var, let and const keywords in JavaScript Differences between IPv4 and IPv6
[ { "code": null, "e": 25629, "s": 25601, "text": "\n02 Aug, 2017" }, { "code": null, "e": 26038, "s": 25629, "text": "std::advance and std::next are used to advance the iterator by a certain position, such that we can make the iterator point to a desired position. Although both have same purpose, but their implementation is different from each other. This makes it important for us to understand the difference between the two.In C++11, std::next() will advance by one by default, whereas std::advance() requires a distance." }, { "code": null, "e": 28548, "s": 26038, "text": "Syntactical Difference: Syntax of std::advance and std::next is:// Definition of std::advance()\ntemplate\nvoid advance( InputIt& it, Distance n );\n\nit: Iterator to be advanced\nn: Distance to be advanced\n// Definition of std::next()\nForwardIterator next (ForwardIterator it,\n typename iterator_traits::difference_type n = 1);\n\nit: Iterator pointing to base position\nn: Distance to be advanced from base position.\nReturn type: std::advance does not return anything, whereas std::next returns an iterator after advancing n positions from the given base position.As in the syntax of std::next(), it will at least advance the iterator by one position, even if we do not specify the position which it has to advance as it has a default value one, whereas if we use std::advance, it has no such default argument.WorkingArgument Modification: std::advance modifies it arguments such that it points to the desired position, whereas, std::next does not modify its argument, infact it returns a new iterator pointing to the desired position.// C++ program to demonstrate// std::advance vs std::next#include <iostream>#include <iterator>#include <deque>#include <algorithm>using namespace std;int main(){ // Declaring first container deque<int> v1 = { 1, 2, 3 }; // Declaring second container for // copying values deque<int> v2 = { 4, 5, 6 }; deque<int>::iterator ii; ii = v1.begin(); // ii points to 1 in v1 deque<int>::iterator iii; iii = std::next(ii, 2); // ii not modified // For std::advance // std::advance(ii, 2) // ii modified and now points to 3 // Using copy() std::copy(ii, iii, std::back_inserter(v2)); // v2 now contains 4 5 6 1 2 // Displaying v1 and v2 cout << \"v1 = \"; int i; for (i = 0; i < 3; ++i) { cout << v1[i] << \" \"; } cout << \"\\nv2 = \"; for (i = 0; i < 5; ++i) { cout << v2[i] << \" \"; } return 0;}Output:v1 = 1 2 3\nv2 = 4 5 6 1 2 \nExplanation: As can be seen, we want to make ii point to 2 spaces ahead of where it is pointing, so if we use std::advance ii will be pointing to two spaces ahead, whereas if we use std::next, then ii will not be advanced, but an iterator pointing to the new position will be returned, and will be stored in iii.Pre-requisite: std::next requires the iterator passed as argument to be of type at least forward iterator, whereas std::advance doesnot have such restrictions, as it can work with any iterator, even with input iterator or better than it." }, { "code": null, "e": 29359, "s": 28548, "text": "Syntactical Difference: Syntax of std::advance and std::next is:// Definition of std::advance()\ntemplate\nvoid advance( InputIt& it, Distance n );\n\nit: Iterator to be advanced\nn: Distance to be advanced\n// Definition of std::next()\nForwardIterator next (ForwardIterator it,\n typename iterator_traits::difference_type n = 1);\n\nit: Iterator pointing to base position\nn: Distance to be advanced from base position.\nReturn type: std::advance does not return anything, whereas std::next returns an iterator after advancing n positions from the given base position.As in the syntax of std::next(), it will at least advance the iterator by one position, even if we do not specify the position which it has to advance as it has a default value one, whereas if we use std::advance, it has no such default argument." }, { "code": null, "e": 29498, "s": 29359, "text": "// Definition of std::advance()\ntemplate\nvoid advance( InputIt& it, Distance n );\n\nit: Iterator to be advanced\nn: Distance to be advanced\n" }, { "code": null, "e": 29714, "s": 29498, "text": "// Definition of std::next()\nForwardIterator next (ForwardIterator it,\n typename iterator_traits::difference_type n = 1);\n\nit: Iterator pointing to base position\nn: Distance to be advanced from base position.\n" }, { "code": null, "e": 29862, "s": 29714, "text": "Return type: std::advance does not return anything, whereas std::next returns an iterator after advancing n positions from the given base position." }, { "code": null, "e": 30109, "s": 29862, "text": "As in the syntax of std::next(), it will at least advance the iterator by one position, even if we do not specify the position which it has to advance as it has a default value one, whereas if we use std::advance, it has no such default argument." }, { "code": null, "e": 31572, "s": 30109, "text": "WorkingArgument Modification: std::advance modifies it arguments such that it points to the desired position, whereas, std::next does not modify its argument, infact it returns a new iterator pointing to the desired position.// C++ program to demonstrate// std::advance vs std::next#include <iostream>#include <iterator>#include <deque>#include <algorithm>using namespace std;int main(){ // Declaring first container deque<int> v1 = { 1, 2, 3 }; // Declaring second container for // copying values deque<int> v2 = { 4, 5, 6 }; deque<int>::iterator ii; ii = v1.begin(); // ii points to 1 in v1 deque<int>::iterator iii; iii = std::next(ii, 2); // ii not modified // For std::advance // std::advance(ii, 2) // ii modified and now points to 3 // Using copy() std::copy(ii, iii, std::back_inserter(v2)); // v2 now contains 4 5 6 1 2 // Displaying v1 and v2 cout << \"v1 = \"; int i; for (i = 0; i < 3; ++i) { cout << v1[i] << \" \"; } cout << \"\\nv2 = \"; for (i = 0; i < 5; ++i) { cout << v2[i] << \" \"; } return 0;}Output:v1 = 1 2 3\nv2 = 4 5 6 1 2 \nExplanation: As can be seen, we want to make ii point to 2 spaces ahead of where it is pointing, so if we use std::advance ii will be pointing to two spaces ahead, whereas if we use std::next, then ii will not be advanced, but an iterator pointing to the new position will be returned, and will be stored in iii." }, { "code": null, "e": 33028, "s": 31572, "text": "Argument Modification: std::advance modifies it arguments such that it points to the desired position, whereas, std::next does not modify its argument, infact it returns a new iterator pointing to the desired position.// C++ program to demonstrate// std::advance vs std::next#include <iostream>#include <iterator>#include <deque>#include <algorithm>using namespace std;int main(){ // Declaring first container deque<int> v1 = { 1, 2, 3 }; // Declaring second container for // copying values deque<int> v2 = { 4, 5, 6 }; deque<int>::iterator ii; ii = v1.begin(); // ii points to 1 in v1 deque<int>::iterator iii; iii = std::next(ii, 2); // ii not modified // For std::advance // std::advance(ii, 2) // ii modified and now points to 3 // Using copy() std::copy(ii, iii, std::back_inserter(v2)); // v2 now contains 4 5 6 1 2 // Displaying v1 and v2 cout << \"v1 = \"; int i; for (i = 0; i < 3; ++i) { cout << v1[i] << \" \"; } cout << \"\\nv2 = \"; for (i = 0; i < 5; ++i) { cout << v2[i] << \" \"; } return 0;}Output:v1 = 1 2 3\nv2 = 4 5 6 1 2 \nExplanation: As can be seen, we want to make ii point to 2 spaces ahead of where it is pointing, so if we use std::advance ii will be pointing to two spaces ahead, whereas if we use std::next, then ii will not be advanced, but an iterator pointing to the new position will be returned, and will be stored in iii." }, { "code": "// C++ program to demonstrate// std::advance vs std::next#include <iostream>#include <iterator>#include <deque>#include <algorithm>using namespace std;int main(){ // Declaring first container deque<int> v1 = { 1, 2, 3 }; // Declaring second container for // copying values deque<int> v2 = { 4, 5, 6 }; deque<int>::iterator ii; ii = v1.begin(); // ii points to 1 in v1 deque<int>::iterator iii; iii = std::next(ii, 2); // ii not modified // For std::advance // std::advance(ii, 2) // ii modified and now points to 3 // Using copy() std::copy(ii, iii, std::back_inserter(v2)); // v2 now contains 4 5 6 1 2 // Displaying v1 and v2 cout << \"v1 = \"; int i; for (i = 0; i < 3; ++i) { cout << v1[i] << \" \"; } cout << \"\\nv2 = \"; for (i = 0; i < 5; ++i) { cout << v2[i] << \" \"; } return 0;}", "e": 33920, "s": 33028, "text": null }, { "code": null, "e": 33928, "s": 33920, "text": "Output:" }, { "code": null, "e": 33956, "s": 33928, "text": "v1 = 1 2 3\nv2 = 4 5 6 1 2 \n" }, { "code": null, "e": 34269, "s": 33956, "text": "Explanation: As can be seen, we want to make ii point to 2 spaces ahead of where it is pointing, so if we use std::advance ii will be pointing to two spaces ahead, whereas if we use std::next, then ii will not be advanced, but an iterator pointing to the new position will be returned, and will be stored in iii." }, { "code": null, "e": 34507, "s": 34269, "text": "Pre-requisite: std::next requires the iterator passed as argument to be of type at least forward iterator, whereas std::advance doesnot have such restrictions, as it can work with any iterator, even with input iterator or better than it." }, { "code": null, "e": 34810, "s": 34507, "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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 34935, "s": 34810, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 34948, "s": 34935, "text": "cpp-iterator" }, { "code": null, "e": 34952, "s": 34948, "text": "STL" }, { "code": null, "e": 34956, "s": 34952, "text": "C++" }, { "code": null, "e": 34975, "s": 34956, "text": "Difference Between" }, { "code": null, "e": 34979, "s": 34975, "text": "STL" }, { "code": null, "e": 34983, "s": 34979, "text": "CPP" }, { "code": null, "e": 35081, "s": 34983, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35100, "s": 35081, "text": "Inheritance in C++" }, { "code": null, "e": 35124, "s": 35100, "text": "C++ Classes and Objects" }, { "code": null, "e": 35151, "s": 35124, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 35175, "s": 35151, "text": "Virtual Function in C++" }, { "code": null, "e": 35206, "s": 35175, "text": "Templates in C++ with Examples" }, { "code": null, "e": 35237, "s": 35206, "text": "Difference between BFS and DFS" }, { "code": null, "e": 35277, "s": 35237, "text": "Class method vs Static method in Python" }, { "code": null, "e": 35309, "s": 35277, "text": "Differences between TCP and UDP" }, { "code": null, "e": 35370, "s": 35309, "text": "Difference between var, let and const keywords in JavaScript" } ]
ChoiceFormat format() method in Java with Examples - GeeksforGeeks
19 Aug, 2021 The format() method of java.text.ChoiceFormat class is used to get the appended string builder of the format value of particular limit value passed as parameter and text passed as parameter in this method. Syntax: public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition status) Parameter: This method takes the following parameter as follow number: which is the particular limit of choiceformat object for which format have to be found and appended toAppendTo: which is the new text which is to be appended with the format status: which determines if there is no special status to be returned Return Value: This method return appended value of text and format in the form of StringBuffer object. Exception: This method throws NullPointerException if toAppendto value is null.Below are the examples to illustrate the format() method:Example 1: Java // Java program to demonstrate// format() method import java.text.*;import java.util.*;import java.io.*; public class GFG { public static void main(String[] argv) { try { // creating and initializing ChoiceFormat ChoiceFormat cf1 = new ChoiceFormat( "4#wed| 5#thu | 6#fri | 7#sat"); // creating and initializing StringBuffer StringBuffer str = new StringBuffer("Sun"); // getting the required format with appended text // ChoiceFormat Object // using format() method StringBuffer value = cf1.format(6, str, null); // display the result System.out.print("Formated text with appended value: " + value.toString()); } catch (NullPointerException e) { System.out.println("str is null"); System.out.println("Exception thrown: " + e); } }} Formated text with appended value: Sunfri Example 2: Java // Java program to demonstrate// format() method import java.text.*;import java.util.*;import java.io.*; public class GFG { public static void main(String[] argv) { try { // creating and initializing ChoiceFormat ChoiceFormat cf1 = new ChoiceFormat( "4#wed| 5#thu | 6#fri | 7#sat"); // creating and initializing StringBuffer StringBuffer str = null; // getting the required format with appended text // ChoiceFormat Object // using format() method StringBuffer value = cf1.format(6, str, null); // display the result System.out.print("Formated text with appended value: " + value.toString()); } catch (NullPointerException e) { System.out.println("str is null"); System.out.println("Exception thrown: " + e); } }} str is null Exception thrown: java.lang.NullPointerException Reference: https://docs.oracle.com/javase/9/docs/api/java/text/ChoiceFormat.html#format-double-java.lang.StringBuffer-java.text.FieldPosition- gulshankumarar231 Java- ChoiceFormat Java-Functions Java-text package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n19 Aug, 2021" }, { "code": null, "e": 25441, "s": 25225, "text": "The format() method of java.text.ChoiceFormat class is used to get the appended string builder of the format value of particular limit value passed as parameter and text passed as parameter in this method. Syntax: " }, { "code": null, "e": 25580, "s": 25441, "text": "public StringBuffer format(double number,\n StringBuffer toAppendTo,\n FieldPosition status)" }, { "code": null, "e": 25645, "s": 25580, "text": "Parameter: This method takes the following parameter as follow " }, { "code": null, "e": 25753, "s": 25645, "text": "number: which is the particular limit of choiceformat object for which format have to be found and appended" }, { "code": null, "e": 25827, "s": 25753, "text": "toAppendTo: which is the new text which is to be appended with the format" }, { "code": null, "e": 25897, "s": 25827, "text": "status: which determines if there is no special status to be returned" }, { "code": null, "e": 26149, "s": 25897, "text": "Return Value: This method return appended value of text and format in the form of StringBuffer object. Exception: This method throws NullPointerException if toAppendto value is null.Below are the examples to illustrate the format() method:Example 1: " }, { "code": null, "e": 26154, "s": 26149, "text": "Java" }, { "code": "// Java program to demonstrate// format() method import java.text.*;import java.util.*;import java.io.*; public class GFG { public static void main(String[] argv) { try { // creating and initializing ChoiceFormat ChoiceFormat cf1 = new ChoiceFormat( \"4#wed| 5#thu | 6#fri | 7#sat\"); // creating and initializing StringBuffer StringBuffer str = new StringBuffer(\"Sun\"); // getting the required format with appended text // ChoiceFormat Object // using format() method StringBuffer value = cf1.format(6, str, null); // display the result System.out.print(\"Formated text with appended value: \" + value.toString()); } catch (NullPointerException e) { System.out.println(\"str is null\"); System.out.println(\"Exception thrown: \" + e); } }}", "e": 27122, "s": 26154, "text": null }, { "code": null, "e": 27165, "s": 27122, "text": "Formated text with appended value: Sunfri " }, { "code": null, "e": 27180, "s": 27167, "text": "Example 2: " }, { "code": null, "e": 27185, "s": 27180, "text": "Java" }, { "code": "// Java program to demonstrate// format() method import java.text.*;import java.util.*;import java.io.*; public class GFG { public static void main(String[] argv) { try { // creating and initializing ChoiceFormat ChoiceFormat cf1 = new ChoiceFormat( \"4#wed| 5#thu | 6#fri | 7#sat\"); // creating and initializing StringBuffer StringBuffer str = null; // getting the required format with appended text // ChoiceFormat Object // using format() method StringBuffer value = cf1.format(6, str, null); // display the result System.out.print(\"Formated text with appended value: \" + value.toString()); } catch (NullPointerException e) { System.out.println(\"str is null\"); System.out.println(\"Exception thrown: \" + e); } }}", "e": 28134, "s": 27185, "text": null }, { "code": null, "e": 28195, "s": 28134, "text": "str is null\nException thrown: java.lang.NullPointerException" }, { "code": null, "e": 28341, "s": 28197, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/text/ChoiceFormat.html#format-double-java.lang.StringBuffer-java.text.FieldPosition- " }, { "code": null, "e": 28359, "s": 28341, "text": "gulshankumarar231" }, { "code": null, "e": 28378, "s": 28359, "text": "Java- ChoiceFormat" }, { "code": null, "e": 28393, "s": 28378, "text": "Java-Functions" }, { "code": null, "e": 28411, "s": 28393, "text": "Java-text package" }, { "code": null, "e": 28416, "s": 28411, "text": "Java" }, { "code": null, "e": 28421, "s": 28416, "text": "Java" }, { "code": null, "e": 28519, "s": 28421, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28534, "s": 28519, "text": "Stream In Java" }, { "code": null, "e": 28555, "s": 28534, "text": "Constructors in Java" }, { "code": null, "e": 28574, "s": 28555, "text": "Exceptions in Java" }, { "code": null, "e": 28604, "s": 28574, "text": "Functional Interfaces in Java" }, { "code": null, "e": 28650, "s": 28604, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28667, "s": 28650, "text": "Generics in Java" }, { "code": null, "e": 28688, "s": 28667, "text": "Introduction to Java" }, { "code": null, "e": 28731, "s": 28688, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 28767, "s": 28731, "text": "Internal Working of HashMap in Java" } ]
How to download a file using Express.js ? - GeeksforGeeks
17 Jan, 2022 Express.js is a routing and middleware framework for handling the different routing of the webpage and it works between the request and response cycle and works on the top of the node.js server. In this article, we will discuss how to download a file using express.js. To download a file using express.js we are going to see two scenarios: Downloading a single file using res.download() function which takes two parameters the path of the file and a function to handle if any error occurs.Downloading multiple files as a zipped folder for this we would use the “express-zip” npm package which creates a zipped folder using the zip() function which takes an array of objects as a parameter. Each object has two fields path and file name. Downloading a single file using res.download() function which takes two parameters the path of the file and a function to handle if any error occurs. Downloading multiple files as a zipped folder for this we would use the “express-zip” npm package which creates a zipped folder using the zip() function which takes an array of objects as a parameter. Each object has two fields path and file name. Let’s first initialize the project and discuss each scenario one by one: Step 1: create an “app.js” file and initialize your project with npm. npm init Step 2: Now install two npm packages: “express” and “express-zip“. npm install express npm install express-zip Step 3: Create an “index.html” file and then create a folder named “Files” inside your project folder. In the files folder creates the below mentioned four text files: single_gfg.txt multiple_one_gfg.txt multiple_two_gfg.txt multiple_three_gfg.txt The final project structure will look like this: Project Structure Step 4: Now let us code the “index.html” file. In it we will create two forms: One with GET route as – ‘/single‘ (to handle the single file download request). One with GET route as – ‘/multiple‘ (to handle the multiple file download request). index.html 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>Download</title></head> <body> <br> <!-- Form to handle single file download request--> <form action="/single" method="get"> <button type="submit">Download Single File</button> </form> <br><br> <!-- Form to handle single file download request--> <form action="/multiple" method="get"> <button type="submit">Download Multiple File</button> </form></body> </html> Step 5: Now code the “app.js” file. In it, we create GET request functions to handle the download requests using express. We use “express-zip” and res.download() as mentioned at the start. app.js file Javascript // Requiring express package for routingconst express = require('express') // Creating appconst app = express(); // Requiring express-zip for downloading a zip fileconst zip = require('express-zip'); // The folder path for the filesconst folderPath = __dirname+'/Files'; // GET request for single fileapp.get('/single',function(req,res) { console.log('single file'); // Download function provided by express res.download(folderPath+'/single_gfg.txt', function(err) { if(err) { console.log(err); } })}) // GET request for multiple file download as zipapp.get('/multiple', function(req, res) { console.log('Multiple file download') // zip method which take file path // and name as objects res.zip([ { path: folderPath+'/multiple_one_gfg.txt', name: 'one_gfg.txt'}, { path: folderPath+'/multiple_two_gfg.txt', name: 'two_gfg.txt'}, { path: folderPath+'/multiple_three_gfg.txt', name: 'three_gfg.txt'} ])}) // GET request to the root of the appapp.get('/', function(req, res){ res.sendFile(__dirname+'/index.html');}) // Creating server at port 3000app.listen(3000,function(req,res){ console.log('Server started to listen at 3000');}) Step 5: Now run the app using your terminal. node app.js Output: Go to any browser and type http://localhost:3000 Output You can go to the Downloads folder and extract the zip folder. So this is how we can download files using express in Node.js rs1686740 simranarora5sos Express.js NodeJS-Questions Picked 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 Difference between promise and async await in Node.js How to use an ES6 import in Node.js? Mongoose | findByIdAndUpdate() Function Node.js fs.readdirSync() Method Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25839, "s": 25811, "text": "\n17 Jan, 2022" }, { "code": null, "e": 26109, "s": 25839, "text": "Express.js is a routing and middleware framework for handling the different routing of the webpage and it works between the request and response cycle and works on the top of the node.js server. In this article, we will discuss how to download a file using express.js." }, { "code": null, "e": 26180, "s": 26109, "text": "To download a file using express.js we are going to see two scenarios:" }, { "code": null, "e": 26577, "s": 26180, "text": "Downloading a single file using res.download() function which takes two parameters the path of the file and a function to handle if any error occurs.Downloading multiple files as a zipped folder for this we would use the “express-zip” npm package which creates a zipped folder using the zip() function which takes an array of objects as a parameter. Each object has two fields path and file name." }, { "code": null, "e": 26727, "s": 26577, "text": "Downloading a single file using res.download() function which takes two parameters the path of the file and a function to handle if any error occurs." }, { "code": null, "e": 26975, "s": 26727, "text": "Downloading multiple files as a zipped folder for this we would use the “express-zip” npm package which creates a zipped folder using the zip() function which takes an array of objects as a parameter. Each object has two fields path and file name." }, { "code": null, "e": 27048, "s": 26975, "text": "Let’s first initialize the project and discuss each scenario one by one:" }, { "code": null, "e": 27118, "s": 27048, "text": "Step 1: create an “app.js” file and initialize your project with npm." }, { "code": null, "e": 27127, "s": 27118, "text": "npm init" }, { "code": null, "e": 27194, "s": 27127, "text": "Step 2: Now install two npm packages: “express” and “express-zip“." }, { "code": null, "e": 27238, "s": 27194, "text": "npm install express\nnpm install express-zip" }, { "code": null, "e": 27406, "s": 27238, "text": "Step 3: Create an “index.html” file and then create a folder named “Files” inside your project folder. In the files folder creates the below mentioned four text files:" }, { "code": null, "e": 27421, "s": 27406, "text": "single_gfg.txt" }, { "code": null, "e": 27442, "s": 27421, "text": "multiple_one_gfg.txt" }, { "code": null, "e": 27463, "s": 27442, "text": "multiple_two_gfg.txt" }, { "code": null, "e": 27486, "s": 27463, "text": "multiple_three_gfg.txt" }, { "code": null, "e": 27535, "s": 27486, "text": "The final project structure will look like this:" }, { "code": null, "e": 27553, "s": 27535, "text": "Project Structure" }, { "code": null, "e": 27632, "s": 27553, "text": "Step 4: Now let us code the “index.html” file. In it we will create two forms:" }, { "code": null, "e": 27713, "s": 27632, "text": "One with GET route as – ‘/single‘ (to handle the single file download request)." }, { "code": null, "e": 27798, "s": 27713, "text": "One with GET route as – ‘/multiple‘ (to handle the multiple file download request)." }, { "code": null, "e": 27810, "s": 27798, "text": "index.html " }, { "code": null, "e": 27815, "s": 27810, "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>Download</title></head> <body> <br> <!-- Form to handle single file download request--> <form action=\"/single\" method=\"get\"> <button type=\"submit\">Download Single File</button> </form> <br><br> <!-- Form to handle single file download request--> <form action=\"/multiple\" method=\"get\"> <button type=\"submit\">Download Multiple File</button> </form></body> </html>", "e": 28432, "s": 27815, "text": null }, { "code": null, "e": 28621, "s": 28432, "text": "Step 5: Now code the “app.js” file. In it, we create GET request functions to handle the download requests using express. We use “express-zip” and res.download() as mentioned at the start." }, { "code": null, "e": 28633, "s": 28621, "text": "app.js file" }, { "code": null, "e": 28644, "s": 28633, "text": "Javascript" }, { "code": "// Requiring express package for routingconst express = require('express') // Creating appconst app = express(); // Requiring express-zip for downloading a zip fileconst zip = require('express-zip'); // The folder path for the filesconst folderPath = __dirname+'/Files'; // GET request for single fileapp.get('/single',function(req,res) { console.log('single file'); // Download function provided by express res.download(folderPath+'/single_gfg.txt', function(err) { if(err) { console.log(err); } })}) // GET request for multiple file download as zipapp.get('/multiple', function(req, res) { console.log('Multiple file download') // zip method which take file path // and name as objects res.zip([ { path: folderPath+'/multiple_one_gfg.txt', name: 'one_gfg.txt'}, { path: folderPath+'/multiple_two_gfg.txt', name: 'two_gfg.txt'}, { path: folderPath+'/multiple_three_gfg.txt', name: 'three_gfg.txt'} ])}) // GET request to the root of the appapp.get('/', function(req, res){ res.sendFile(__dirname+'/index.html');}) // Creating server at port 3000app.listen(3000,function(req,res){ console.log('Server started to listen at 3000');})", "e": 29909, "s": 28644, "text": null }, { "code": null, "e": 29954, "s": 29909, "text": "Step 5: Now run the app using your terminal." }, { "code": null, "e": 29966, "s": 29954, "text": "node app.js" }, { "code": null, "e": 30023, "s": 29966, "text": "Output: Go to any browser and type http://localhost:3000" }, { "code": null, "e": 30030, "s": 30023, "text": "Output" }, { "code": null, "e": 30155, "s": 30030, "text": "You can go to the Downloads folder and extract the zip folder. So this is how we can download files using express in Node.js" }, { "code": null, "e": 30165, "s": 30155, "text": "rs1686740" }, { "code": null, "e": 30181, "s": 30165, "text": "simranarora5sos" }, { "code": null, "e": 30192, "s": 30181, "text": "Express.js" }, { "code": null, "e": 30209, "s": 30192, "text": "NodeJS-Questions" }, { "code": null, "e": 30216, "s": 30209, "text": "Picked" }, { "code": null, "e": 30224, "s": 30216, "text": "Node.js" }, { "code": null, "e": 30241, "s": 30224, "text": "Web Technologies" }, { "code": null, "e": 30339, "s": 30241, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30369, "s": 30339, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 30423, "s": 30369, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 30460, "s": 30423, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 30500, "s": 30460, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 30532, "s": 30500, "text": "Node.js fs.readdirSync() Method" }, { "code": null, "e": 30572, "s": 30532, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30617, "s": 30572, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30660, "s": 30617, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 30710, "s": 30660, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
CSS | translateZ() function - GeeksforGeeks
07 Aug, 2019 The translateZ() function is an inbuilt function which is used to reposition the element along the z-axis in 3D space. Syntax: translateZ( t ) Parameters: This function accepts single parameter t which holds the length of translation corresponding to z-axis. Below examples illustrate the translateZ() function in CSS: Example 1: <!DOCTYPE html><html> <head> <title> CSS translateZ() function </title> <style> body { text-align: center; } h1 { color: green; } .translateZ_image { transform: perspective(200px) translateZ(100px); } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>CSS translateZ() function</h2> <h4>Original Image</h4> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png" alt="GeeksforGeeks logo"> <br> <h4>Translated image</h4> <img class="translateZ_image" src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png" alt="GeeksforGeeks logo"></body> </html> Output: Example 2: <!DOCTYPE html><html> <head> <title> CSS translateZ() function </title> <style> body { text-align: center; } h1 { color: green; } .GFG { font-size: 35px; font-weight: bold; color: green; } .geeks { transform: perspective( 200px) translateZ(100px); } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>CSS translateZ() function</h2> <h4>Original Element</h4> <div class="GFG"> Welcome to GeeksforGeeks </div> <h4>Translated Element</h4> <div class="GFG geeks"> Welcome to GeeksforGeeks </div></body> </html> Output: Supported Browsers: The browsers supported by translateZ() function are listed below: Google Chrome Internet Explorer Firefox Safari Opera CSS-Functions CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a web page using HTML and CSS How to set space between the flexbox ? Form validation using jQuery Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26621, "s": 26593, "text": "\n07 Aug, 2019" }, { "code": null, "e": 26740, "s": 26621, "text": "The translateZ() function is an inbuilt function which is used to reposition the element along the z-axis in 3D space." }, { "code": null, "e": 26748, "s": 26740, "text": "Syntax:" }, { "code": null, "e": 26764, "s": 26748, "text": "translateZ( t )" }, { "code": null, "e": 26880, "s": 26764, "text": "Parameters: This function accepts single parameter t which holds the length of translation corresponding to z-axis." }, { "code": null, "e": 26940, "s": 26880, "text": "Below examples illustrate the translateZ() function in CSS:" }, { "code": null, "e": 26951, "s": 26940, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS translateZ() function </title> <style> body { text-align: center; } h1 { color: green; } .translateZ_image { transform: perspective(200px) translateZ(100px); } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>CSS translateZ() function</h2> <h4>Original Image</h4> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png\" alt=\"GeeksforGeeks logo\"> <br> <h4>Translated image</h4> <img class=\"translateZ_image\" src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png\" alt=\"GeeksforGeeks logo\"></body> </html>", "e": 27734, "s": 26951, "text": null }, { "code": null, "e": 27742, "s": 27734, "text": "Output:" }, { "code": null, "e": 27753, "s": 27742, "text": "Example 2:" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS translateZ() function </title> <style> body { text-align: center; } h1 { color: green; } .GFG { font-size: 35px; font-weight: bold; color: green; } .geeks { transform: perspective( 200px) translateZ(100px); } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>CSS translateZ() function</h2> <h4>Original Element</h4> <div class=\"GFG\"> Welcome to GeeksforGeeks </div> <h4>Translated Element</h4> <div class=\"GFG geeks\"> Welcome to GeeksforGeeks </div></body> </html>", "e": 28476, "s": 27753, "text": null }, { "code": null, "e": 28484, "s": 28476, "text": "Output:" }, { "code": null, "e": 28570, "s": 28484, "text": "Supported Browsers: The browsers supported by translateZ() function are listed below:" }, { "code": null, "e": 28584, "s": 28570, "text": "Google Chrome" }, { "code": null, "e": 28602, "s": 28584, "text": "Internet Explorer" }, { "code": null, "e": 28610, "s": 28602, "text": "Firefox" }, { "code": null, "e": 28617, "s": 28610, "text": "Safari" }, { "code": null, "e": 28623, "s": 28617, "text": "Opera" }, { "code": null, "e": 28637, "s": 28623, "text": "CSS-Functions" }, { "code": null, "e": 28641, "s": 28637, "text": "CSS" }, { "code": null, "e": 28658, "s": 28641, "text": "Web Technologies" }, { "code": null, "e": 28756, "s": 28658, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28793, "s": 28756, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28832, "s": 28793, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 28861, "s": 28832, "text": "Form validation using jQuery" }, { "code": null, "e": 28903, "s": 28861, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 28938, "s": 28903, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 28978, "s": 28938, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29011, "s": 28978, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29056, "s": 29011, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29099, "s": 29056, "text": "How to fetch data from an API in ReactJS ?" } ]
Ruby | Numeric abs() function - GeeksforGeeks
19 Jan, 2021 The abs is an inbuilt method in Ruby returns the absolute value of a number. Syntax: num.abs Parameters: The function needs the number whose absolute value is to be returned. Return Value: It returns the absolute value of a numbers. Example 1: Ruby # Ruby program for abs() method in Numeric # Initialize two numbersnum = -19 # Prints absolute value of numputs num.abs() Output: 19 Example 2: Ruby # Ruby program for abs() method in Numeric # Initialize two numbersnum = 100 # Prints absolute value of numputs num.abs() Output: 100 arorakashish0911 Ruby Numeric-class Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Ruby | Data Types Ruby | Hash delete() function Ruby | Array count() operation Ruby | Enumerator each_with_index function Ruby | String reverse Method Ruby | Array reject() function Ruby | Types of Iterators Ruby Mixins Ruby | Method overriding Ruby | Array collect() operation
[ { "code": null, "e": 25127, "s": 25099, "text": "\n19 Jan, 2021" }, { "code": null, "e": 25206, "s": 25127, "text": "The abs is an inbuilt method in Ruby returns the absolute value of a number. " }, { "code": null, "e": 25222, "s": 25206, "text": "Syntax: num.abs" }, { "code": null, "e": 25305, "s": 25222, "text": "Parameters: The function needs the number whose absolute value is to be returned. " }, { "code": null, "e": 25363, "s": 25305, "text": "Return Value: It returns the absolute value of a numbers." }, { "code": null, "e": 25376, "s": 25363, "text": "Example 1: " }, { "code": null, "e": 25381, "s": 25376, "text": "Ruby" }, { "code": "# Ruby program for abs() method in Numeric # Initialize two numbersnum = -19 # Prints absolute value of numputs num.abs()", "e": 25504, "s": 25381, "text": null }, { "code": null, "e": 25513, "s": 25504, "text": "Output: " }, { "code": null, "e": 25516, "s": 25513, "text": "19" }, { "code": null, "e": 25528, "s": 25516, "text": "Example 2: " }, { "code": null, "e": 25533, "s": 25528, "text": "Ruby" }, { "code": "# Ruby program for abs() method in Numeric # Initialize two numbersnum = 100 # Prints absolute value of numputs num.abs()", "e": 25656, "s": 25533, "text": null }, { "code": null, "e": 25665, "s": 25656, "text": "Output: " }, { "code": null, "e": 25669, "s": 25665, "text": "100" }, { "code": null, "e": 25688, "s": 25671, "text": "arorakashish0911" }, { "code": null, "e": 25707, "s": 25688, "text": "Ruby Numeric-class" }, { "code": null, "e": 25720, "s": 25707, "text": "Ruby-Methods" }, { "code": null, "e": 25725, "s": 25720, "text": "Ruby" }, { "code": null, "e": 25823, "s": 25725, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25841, "s": 25823, "text": "Ruby | Data Types" }, { "code": null, "e": 25871, "s": 25841, "text": "Ruby | Hash delete() function" }, { "code": null, "e": 25902, "s": 25871, "text": "Ruby | Array count() operation" }, { "code": null, "e": 25945, "s": 25902, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 25974, "s": 25945, "text": "Ruby | String reverse Method" }, { "code": null, "e": 26005, "s": 25974, "text": "Ruby | Array reject() function" }, { "code": null, "e": 26031, "s": 26005, "text": "Ruby | Types of Iterators" }, { "code": null, "e": 26043, "s": 26031, "text": "Ruby Mixins" }, { "code": null, "e": 26068, "s": 26043, "text": "Ruby | Method overriding" } ]
Check divisibility in a binary stream - GeeksforGeeks
30 May, 2018 Stream of binary number is coming, the task is to tell the number formed so far is divisible by a given number n.At any given time, you will get 0 or 1 and tell whether the number formed with these bits is divisible by n or not. Generally, e-commerce companies ask this type of questions. It was asked me in Microsoft interview. Actually that question was a bit simple, interviewer fixed the n to 3. /* Simple implementation of the logic, without error handling compiled with Microsoft visual studio 2015 */void CheckDivisibility2(int n){ int num = 0; std::cout << "press any key other than" " 0 and 1 to terminate \n"; while (true) { int incomingBit; // read next incoming bit via standard // input. 0, 00, 000.. are same as int 0 // ans 1, 01, 001, 00..001 is same as 1. std::cin >> incomingBit; // Update value of num formed so far if (incomingBit == 1) num = (num * 2 + 1); else if (incomingBit == 0) num = (num * 2); else break; if (num % n == 0) std::cout << "yes \n"; else std::cout << "no \n"; }} Problem in this solution: What about the overflow. Since 0 and 1 will keep on coming and the number formed will go out of range of integer. In order to implement this technique, we need to observe how the value of a binary number changes, when it is appended by 0 or 1. Let’s take an example. Suppose you have binary number 1.If it is appended by 0 it will become 10 (2 in decimal) means 2 times of the previous value.If it is appended by 1 it will become 11(3 in decimal), 2 times of previous value +1. How does it help in getting the remainder?Any number (n) can be written in the form m = an + r where a, n and r are integers and r is the remainder. So when m is multiplied by any number so the remainder. Suppose m is multiplied by x so m will be mx = xan + xr. so (mx)%n = (xan)%n + (xr)%n = 0 + (xr)%n = (xr)%n; We need to just do the above calculation (calculation of value of number when it is appended by 0 or 1 ) only over remainder. When a binary number is appended by 0 (means multiplied by 2), the new remainder can be calculated based on current remainder only. r = 2*r % n; And when a binary number is appended by 1. r = (2*r + 1) % n; // C++ program to check divisibility in a stream#include <iostream>using namespace std; /* A very simple implementation of the logic, without error handling. just to demonstrate the above theory. This simple version not restricting user from typing 000, 00 , 000.. , because this all will be same as 0 for integer same is true for 1, 01, 001, 000...001 is same as 1, so ignore this type of error handling while reading just see the main logic is correct. */void CheckDivisibility(int n){ int remainder = 0; std::cout << "press any key other than 0" " and 1 to terminate \n"; while (true) { // Read next incoming bit via standard // input. 0, 00, 000.. are same as int 0 // ans 1, 01, 001, 00..001 is same as 1. int incomingBit; cin >> incomingBit; // Update remainder if (incomingBit == 1) remainder = (remainder * 2 + 1) % n; else if (incomingBit == 0) remainder = (remainder * 2) % n; else break; // If remainder is 0. if (remainder % n == 0) cout << "yes \n"; else cout << "no \n"; }} // Driver codeint main(){ CheckDivisibility(3); return 0;} Input: 1 0 1 0 1 -1 Output: Press any key other than 0 and 1 to terminate no no no no yes Related Articles:DFA based divisionCheck if a stream is Multiple of 3 This article is contributed by Puneet. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above array-stream divisibility Bit Magic Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Little and Big Endian Mystery Cyclic Redundancy Check and Modulo-2 Division Binary representation of a given number Add two numbers without using arithmetic operators Josephus problem | Set 1 (A O(n) Solution) Bit Fields in C Find the element that appears once Bits manipulation (Important tactics) Set, Clear and Toggle a given bit of a number in C C++ bitset and its application
[ { "code": null, "e": 26565, "s": 26537, "text": "\n30 May, 2018" }, { "code": null, "e": 26794, "s": 26565, "text": "Stream of binary number is coming, the task is to tell the number formed so far is divisible by a given number n.At any given time, you will get 0 or 1 and tell whether the number formed with these bits is divisible by n or not." }, { "code": null, "e": 26965, "s": 26794, "text": "Generally, e-commerce companies ask this type of questions. It was asked me in Microsoft interview. Actually that question was a bit simple, interviewer fixed the n to 3." }, { "code": "/* Simple implementation of the logic, without error handling compiled with Microsoft visual studio 2015 */void CheckDivisibility2(int n){ int num = 0; std::cout << \"press any key other than\" \" 0 and 1 to terminate \\n\"; while (true) { int incomingBit; // read next incoming bit via standard // input. 0, 00, 000.. are same as int 0 // ans 1, 01, 001, 00..001 is same as 1. std::cin >> incomingBit; // Update value of num formed so far if (incomingBit == 1) num = (num * 2 + 1); else if (incomingBit == 0) num = (num * 2); else break; if (num % n == 0) std::cout << \"yes \\n\"; else std::cout << \"no \\n\"; }}", "e": 27742, "s": 26965, "text": null }, { "code": null, "e": 27882, "s": 27742, "text": "Problem in this solution: What about the overflow. Since 0 and 1 will keep on coming and the number formed will go out of range of integer." }, { "code": null, "e": 28014, "s": 27884, "text": "In order to implement this technique, we need to observe how the value of a binary number changes, when it is appended by 0 or 1." }, { "code": null, "e": 28248, "s": 28014, "text": "Let’s take an example. Suppose you have binary number 1.If it is appended by 0 it will become 10 (2 in decimal) means 2 times of the previous value.If it is appended by 1 it will become 11(3 in decimal), 2 times of previous value +1." }, { "code": null, "e": 28562, "s": 28248, "text": "How does it help in getting the remainder?Any number (n) can be written in the form m = an + r where a, n and r are integers and r is the remainder. So when m is multiplied by any number so the remainder. Suppose m is multiplied by x so m will be mx = xan + xr. so (mx)%n = (xan)%n + (xr)%n = 0 + (xr)%n = (xr)%n;" }, { "code": null, "e": 28688, "s": 28562, "text": "We need to just do the above calculation (calculation of value of number when it is appended by 0 or 1 ) only over remainder." }, { "code": null, "e": 28899, "s": 28688, "text": "When a binary number is appended by 0 (means \nmultiplied by 2), the new remainder can be \ncalculated based on current remainder only.\nr = 2*r % n;\n\nAnd when a binary number is appended by 1.\nr = (2*r + 1) % n; " }, { "code": "// C++ program to check divisibility in a stream#include <iostream>using namespace std; /* A very simple implementation of the logic, without error handling. just to demonstrate the above theory. This simple version not restricting user from typing 000, 00 , 000.. , because this all will be same as 0 for integer same is true for 1, 01, 001, 000...001 is same as 1, so ignore this type of error handling while reading just see the main logic is correct. */void CheckDivisibility(int n){ int remainder = 0; std::cout << \"press any key other than 0\" \" and 1 to terminate \\n\"; while (true) { // Read next incoming bit via standard // input. 0, 00, 000.. are same as int 0 // ans 1, 01, 001, 00..001 is same as 1. int incomingBit; cin >> incomingBit; // Update remainder if (incomingBit == 1) remainder = (remainder * 2 + 1) % n; else if (incomingBit == 0) remainder = (remainder * 2) % n; else break; // If remainder is 0. if (remainder % n == 0) cout << \"yes \\n\"; else cout << \"no \\n\"; }} // Driver codeint main(){ CheckDivisibility(3); return 0;}", "e": 30150, "s": 28899, "text": null }, { "code": null, "e": 30157, "s": 30150, "text": "Input:" }, { "code": null, "e": 30171, "s": 30157, "text": "1\n0\n1\n0\n1\n-1\n" }, { "code": null, "e": 30179, "s": 30171, "text": "Output:" }, { "code": null, "e": 30248, "s": 30179, "text": "Press any key other than 0 and 1 to terminate \nno \nno \nno \nno \nyes \n" }, { "code": null, "e": 30318, "s": 30248, "text": "Related Articles:DFA based divisionCheck if a stream is Multiple of 3" }, { "code": null, "e": 30612, "s": 30318, "text": "This article is contributed by Puneet. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 30736, "s": 30612, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 30749, "s": 30736, "text": "array-stream" }, { "code": null, "e": 30762, "s": 30749, "text": "divisibility" }, { "code": null, "e": 30772, "s": 30762, "text": "Bit Magic" }, { "code": null, "e": 30782, "s": 30772, "text": "Bit Magic" }, { "code": null, "e": 30880, "s": 30782, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30910, "s": 30880, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 30956, "s": 30910, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 30996, "s": 30956, "text": "Binary representation of a given number" }, { "code": null, "e": 31047, "s": 30996, "text": "Add two numbers without using arithmetic operators" }, { "code": null, "e": 31090, "s": 31047, "text": "Josephus problem | Set 1 (A O(n) Solution)" }, { "code": null, "e": 31106, "s": 31090, "text": "Bit Fields in C" }, { "code": null, "e": 31141, "s": 31106, "text": "Find the element that appears once" }, { "code": null, "e": 31179, "s": 31141, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 31230, "s": 31179, "text": "Set, Clear and Toggle a given bit of a number in C" } ]
Create a Drop Caps Effect using CSS - GeeksforGeeks
23 Nov, 2020 Drop caps are define as the first capital letter of a paragraph in much larger font size that has the depth of two or more lines of normal text. The task can be done by using the CSS ::first-letter pseudo-element to create beautiful drop caps effect. The ::first-letter selector in CSS is used to apply style to the first letter of the first line of a block-level element, the condition is it should not be preceded by other content ( such as images or inline tables). Syntax: ::first-letter { // CSS Property } Example: HTML <!DOCTYPE html><html> <head> <style> .gfg::first-letter { font-size: 250%; color: green; } div::first-letter { font-size: 250%; color: blue; font-weight: bold; } </style></head> <body style="text-align: center;"> <h1 style="color:green;"> How to create drop caps effect using CSS </h1> <p> <div>Geeks</div> <div>For</div> <div>Geeks</div> </p> <p class="gfg"> A computer science portal for geeks. </p></body> </html> Output: Supported Browsers: Google Chrome Internet Explorer Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc HTML-Misc CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a web page using HTML and CSS Form validation using jQuery How to style a checkbox using CSS? Search Bar using HTML, CSS and JavaScript How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 26621, "s": 26593, "text": "\n23 Nov, 2020" }, { "code": null, "e": 26767, "s": 26621, "text": "Drop caps are define as the first capital letter of a paragraph in much larger font size that has the depth of two or more lines of normal text. " }, { "code": null, "e": 27091, "s": 26767, "text": "The task can be done by using the CSS ::first-letter pseudo-element to create beautiful drop caps effect. The ::first-letter selector in CSS is used to apply style to the first letter of the first line of a block-level element, the condition is it should not be preceded by other content ( such as images or inline tables)." }, { "code": null, "e": 27099, "s": 27091, "text": "Syntax:" }, { "code": null, "e": 27139, "s": 27099, "text": "::first-letter {\n // CSS Property \n}" }, { "code": null, "e": 27148, "s": 27139, "text": "Example:" }, { "code": null, "e": 27153, "s": 27148, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> .gfg::first-letter { font-size: 250%; color: green; } div::first-letter { font-size: 250%; color: blue; font-weight: bold; } </style></head> <body style=\"text-align: center;\"> <h1 style=\"color:green;\"> How to create drop caps effect using CSS </h1> <p> <div>Geeks</div> <div>For</div> <div>Geeks</div> </p> <p class=\"gfg\"> A computer science portal for geeks. </p></body> </html>", "e": 27733, "s": 27153, "text": null }, { "code": null, "e": 27741, "s": 27733, "text": "Output:" }, { "code": null, "e": 27761, "s": 27741, "text": "Supported Browsers:" }, { "code": null, "e": 27775, "s": 27761, "text": "Google Chrome" }, { "code": null, "e": 27793, "s": 27775, "text": "Internet Explorer" }, { "code": null, "e": 27801, "s": 27793, "text": "Firefox" }, { "code": null, "e": 27807, "s": 27801, "text": "Opera" }, { "code": null, "e": 27814, "s": 27807, "text": "Safari" }, { "code": null, "e": 27951, "s": 27814, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 27960, "s": 27951, "text": "CSS-Misc" }, { "code": null, "e": 27970, "s": 27960, "text": "HTML-Misc" }, { "code": null, "e": 27974, "s": 27970, "text": "CSS" }, { "code": null, "e": 27979, "s": 27974, "text": "HTML" }, { "code": null, "e": 27996, "s": 27979, "text": "Web Technologies" }, { "code": null, "e": 28001, "s": 27996, "text": "HTML" }, { "code": null, "e": 28099, "s": 28001, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28138, "s": 28099, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 28175, "s": 28138, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28204, "s": 28175, "text": "Form validation using jQuery" }, { "code": null, "e": 28239, "s": 28204, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 28281, "s": 28239, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 28341, "s": 28281, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 28394, "s": 28341, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 28455, "s": 28394, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 28479, "s": 28455, "text": "REST API (Introduction)" } ]
How to make a div fill a remaining horizontal space using CSS? - GeeksforGeeks
10 May, 2022 The width property is used to fill a div remaining horizontal space using CSS. By setting the width to 100% it takes the whole width available of its parent. Syntax: width: 100%; Example 1: This example use width property to fill the horizontal space. It set width to 100% to fill it completely. html <!DOCTYPE html><html> <head> <title> make a div fill remaining horizontal space </title> <!-- Style to fill remaining horizontal space --> <style> #main { height: 100px; border: 1px solid black; font-size: 20px; font-weight: bold; color: white; } #left { float: left; width: 180px; height: 100%; background-color: green; } #right { width: 100%; height: 100%; background-color: blue; } </style></head> <body style = "text-align:center;"> <div id = "main"> <div id="left"> DIV_1 </div> <div id="right"> DIV_2 </div> </div></body> </html> Output: Example 2: This example use width property to fill the horizontal space. It set width to 100% to fill it completely. html <!DOCTYPE html> <html> <head> <title> Title </title> <style> #main { height: 100px; border: 1px solid black; font-size: 20px; font-weight: bold; color: white; } #left { float: left; width: 100px; height: 100%; background-color: green; } #center { float: left; width: 100px; height: 100%; background-color: blue; } #right { width: 100%; height: 100%; background-color: green; } </style></head> <body style = "text-align:center;"> <div id = "main"> <div id="left"> DIV_1 </div> <div id="center"> DIV_2 </div> <div id="right"> DIV_3 </div> </div> </body> </html> Output: CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. hardikkoriintern CSS-Misc HTML-Misc Picked Web-Programs CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? How to set space between the flexbox ? How to Upload Image into Database and Display it using PHP ? How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction)
[ { "code": null, "e": 26603, "s": 26575, "text": "\n10 May, 2022" }, { "code": null, "e": 26762, "s": 26603, "text": "The width property is used to fill a div remaining horizontal space using CSS. By setting the width to 100% it takes the whole width available of its parent. " }, { "code": null, "e": 26770, "s": 26762, "text": "Syntax:" }, { "code": null, "e": 26783, "s": 26770, "text": "width: 100%;" }, { "code": null, "e": 26901, "s": 26783, "text": "Example 1: This example use width property to fill the horizontal space. It set width to 100% to fill it completely. " }, { "code": null, "e": 26906, "s": 26901, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> make a div fill remaining horizontal space </title> <!-- Style to fill remaining horizontal space --> <style> #main { height: 100px; border: 1px solid black; font-size: 20px; font-weight: bold; color: white; } #left { float: left; width: 180px; height: 100%; background-color: green; } #right { width: 100%; height: 100%; background-color: blue; } </style></head> <body style = \"text-align:center;\"> <div id = \"main\"> <div id=\"left\"> DIV_1 </div> <div id=\"right\"> DIV_2 </div> </div></body> </html> ", "e": 27753, "s": 26906, "text": null }, { "code": null, "e": 27761, "s": 27753, "text": "Output:" }, { "code": null, "e": 27882, "s": 27764, "text": "Example 2: This example use width property to fill the horizontal space. It set width to 100% to fill it completely. " }, { "code": null, "e": 27887, "s": 27882, "text": "html" }, { "code": "<!DOCTYPE html> <html> <head> <title> Title </title> <style> #main { height: 100px; border: 1px solid black; font-size: 20px; font-weight: bold; color: white; } #left { float: left; width: 100px; height: 100%; background-color: green; } #center { float: left; width: 100px; height: 100%; background-color: blue; } #right { width: 100%; height: 100%; background-color: green; } </style></head> <body style = \"text-align:center;\"> <div id = \"main\"> <div id=\"left\"> DIV_1 </div> <div id=\"center\"> DIV_2 </div> <div id=\"right\"> DIV_3 </div> </div> </body> </html>", "e": 28819, "s": 27887, "text": null }, { "code": null, "e": 28827, "s": 28819, "text": "Output:" }, { "code": null, "e": 29015, "s": 28829, "text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples." }, { "code": null, "e": 29152, "s": 29015, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 29169, "s": 29152, "text": "hardikkoriintern" }, { "code": null, "e": 29178, "s": 29169, "text": "CSS-Misc" }, { "code": null, "e": 29188, "s": 29178, "text": "HTML-Misc" }, { "code": null, "e": 29195, "s": 29188, "text": "Picked" }, { "code": null, "e": 29208, "s": 29195, "text": "Web-Programs" }, { "code": null, "e": 29212, "s": 29208, "text": "CSS" }, { "code": null, "e": 29217, "s": 29212, "text": "HTML" }, { "code": null, "e": 29234, "s": 29217, "text": "Web Technologies" }, { "code": null, "e": 29239, "s": 29234, "text": "HTML" }, { "code": null, "e": 29337, "s": 29239, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29385, "s": 29337, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 29422, "s": 29385, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 29486, "s": 29422, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 29525, "s": 29486, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 29586, "s": 29525, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 29634, "s": 29586, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 29694, "s": 29634, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 29747, "s": 29694, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 29808, "s": 29747, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Fit Smooth Curve to Plot of Data in R - GeeksforGeeks
16 May, 2021 In this article, we will learn about the concept to fit a smooth curve to the plot of data in R Programming. Smoothing is an important concept in data analysis. It is also known n as curve fitting and low pass filtering. The most common non-parametric method used for smoothing is loess() function. Loess is an abbreviation for Local Regression used to fit multiple regressions in the local neighborhoods. The span argument is used to control the size of the neighborhood. The size ranges between 0 and 1. The greater is the span value, the more smooth will be the fitted curve. Use of Loess() function: Loess() function is used on a numerical vector to smoothen it. It is also used to predict the Y locally. Syntax: loess(y ~ x) Return: It smooth curve to plot of data Example 1: Below is an implementation to fit a smooth curve to a plot: R # Create example dataset.seed(159632) x <- 1:80y <- sort(rnorm(80)) # Apply loess functionvalues <- loess(y ~ x) plot(x, y) lines(predict(values), col = "blue", lwd = 2) Output: In the above example loess() function is used to fit a smooth curve into plot. The lwd parameter is used to specify the line type of the smooth curve. The arguments x and y are used to provide coordination to the plot. The loess function will then set a smooth curve in the plot. Example 2: Another example is illustrated using loess() function: R x <- c(7 ,5, 2, 9, 1, 9, 17, 8, 9, 10)y <- c(12, 14, 16, 18, 20, 2, 4, 6, 8, 7 )values <- loess(y ~ x) plot(x, y)lines(predict(values), col = 'red', lwd = 2) Output: In the above example, X and Y axis values are plotted. The smooth curve is fitted using the loess function. The prediction will be an array of the appropriate dimensions in a smooth fitted curve. Picked R-Charts R-Graphs R-plots R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to import an Excel File into R ? Time Series Analysis in R R - if statement How to filter R dataframe by multiple conditions?
[ { "code": null, "e": 26487, "s": 26459, "text": "\n16 May, 2021" }, { "code": null, "e": 27066, "s": 26487, "text": "In this article, we will learn about the concept to fit a smooth curve to the plot of data in R Programming. Smoothing is an important concept in data analysis. It is also known n as curve fitting and low pass filtering. The most common non-parametric method used for smoothing is loess() function. Loess is an abbreviation for Local Regression used to fit multiple regressions in the local neighborhoods. The span argument is used to control the size of the neighborhood. The size ranges between 0 and 1. The greater is the span value, the more smooth will be the fitted curve." }, { "code": null, "e": 27196, "s": 27066, "text": "Use of Loess() function: Loess() function is used on a numerical vector to smoothen it. It is also used to predict the Y locally." }, { "code": null, "e": 27217, "s": 27196, "text": "Syntax: loess(y ~ x)" }, { "code": null, "e": 27258, "s": 27217, "text": "Return: It smooth curve to plot of data " }, { "code": null, "e": 27329, "s": 27258, "text": "Example 1: Below is an implementation to fit a smooth curve to a plot:" }, { "code": null, "e": 27331, "s": 27329, "text": "R" }, { "code": "# Create example dataset.seed(159632) x <- 1:80y <- sort(rnorm(80)) # Apply loess functionvalues <- loess(y ~ x) plot(x, y) lines(predict(values), col = \"blue\", lwd = 2)", "e": 27548, "s": 27331, "text": null }, { "code": null, "e": 27556, "s": 27548, "text": "Output:" }, { "code": null, "e": 27836, "s": 27556, "text": "In the above example loess() function is used to fit a smooth curve into plot. The lwd parameter is used to specify the line type of the smooth curve. The arguments x and y are used to provide coordination to the plot. The loess function will then set a smooth curve in the plot." }, { "code": null, "e": 27902, "s": 27836, "text": "Example 2: Another example is illustrated using loess() function:" }, { "code": null, "e": 27904, "s": 27902, "text": "R" }, { "code": "x <- c(7 ,5, 2, 9, 1, 9, 17, 8, 9, 10)y <- c(12, 14, 16, 18, 20, 2, 4, 6, 8, 7 )values <- loess(y ~ x) plot(x, y)lines(predict(values), col = 'red', lwd = 2)", "e": 28075, "s": 27904, "text": null }, { "code": null, "e": 28084, "s": 28075, "text": "Output: " }, { "code": null, "e": 28280, "s": 28084, "text": "In the above example, X and Y axis values are plotted. The smooth curve is fitted using the loess function. The prediction will be an array of the appropriate dimensions in a smooth fitted curve." }, { "code": null, "e": 28287, "s": 28280, "text": "Picked" }, { "code": null, "e": 28296, "s": 28287, "text": "R-Charts" }, { "code": null, "e": 28305, "s": 28296, "text": "R-Graphs" }, { "code": null, "e": 28313, "s": 28305, "text": "R-plots" }, { "code": null, "e": 28324, "s": 28313, "text": "R Language" }, { "code": null, "e": 28422, "s": 28324, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28474, "s": 28422, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 28509, "s": 28474, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 28547, "s": 28509, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 28605, "s": 28547, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28648, "s": 28605, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 28697, "s": 28648, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 28734, "s": 28697, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 28760, "s": 28734, "text": "Time Series Analysis in R" }, { "code": null, "e": 28777, "s": 28760, "text": "R - if statement" } ]
Pairing Heap - GeeksforGeeks
01 Dec, 2021 Pairing Heap is like a simplified form Fibonacci Heap. It also maintains the property of min heap which is parent value is less than its child nodes value. It can be considered as a self-adjusting binomial heap.Each node has a pointer towards the left child and left child points towards the next sibling of the child. Example of Pairing Heap is given below: Join or Merge in Pairing Heap To join the two heap, first, we compare the root node of the heap if the root node of the first heap is smaller than the root node of the second heap then root node of the second heap becomes a left child of the root node of the first heap otherwise vice-versa. The time complexity of this process is O(1).Example of Merge is given Below: Insertion in Pairing Heap: To insert a new node in heap, create a new node and Merge it with existing heap as explained above. Therefore, the time complexity of this function is O(1). Example of Insertion is given below: Deletion in Pairing Heap: Deletion in Pairing Heap only happens at the root node. First delete links between root, left child and all the siblings of the left child. Then Merge tree subtrees that are obtained by detaching the left child and all siblings by the two pass method and delete the root node. Merge the detached subtrees from left to right in one pass and then merge the subtrees from right to left to form the new heap without violation of conditions of min-heap. This process takes O(log n) time where n is the number of nodes. Example of Deletion is given below: Below is the implementation of the above approach: CPP14 Python3 #include<bits/stdc++.h>using namespace std; // Heap structurestruct HeapNode { int key; HeapNode *leftChild; HeapNode *nextSibling; HeapNode(): leftChild(NULL), nextSibling(NULL) {} // creates a new node HeapNode(int key_, HeapNode *leftChild_, HeapNode *nextSibling_): key(key_), leftChild(leftChild_), nextSibling(nextSibling_) {} // Adds a child and sibling to the node void addChild(HeapNode *node) { if(leftChild == NULL) leftChild = node; else { node->nextSibling = leftChild; leftChild = node; } }}; // Returns true if root of the tree// is null otherwise returns falsebool Empty(HeapNode *node) { return (node == NULL);} // Function to merge two heapsHeapNode *Merge(HeapNode *A, HeapNode *B){ // If any of the two-nodes is null // the return the not null node if(A == NULL) return B; if(B == NULL) return A; // To maintain the min heap condition compare // the nodes and node with minimum value become // parent of the other node if(A->key < B->key) { A->addChild(B); return A; } else { B->addChild(A); return B; } return NULL; // Unreachable} // Returns the root value of the heapint Top(HeapNode *node) { return node->key;} // Function to insert the new node in the heapHeapNode *Insert(HeapNode *node, int key) { return Merge(node, new HeapNode(key, NULL, NULL));} // This method is used when we want to delete root nodeHeapNode *TwoPassMerge(HeapNode *node) { if(node == NULL || node->nextSibling == NULL) return node; else { HeapNode *A, *B, *newNode; A = node; B = node->nextSibling; newNode = node->nextSibling->nextSibling; A->nextSibling = NULL; B->nextSibling = NULL; return Merge(Merge(A, B), TwoPassMerge(newNode)); } return NULL; // Unreachable} // Function to delete the root node in heapHeapNode *Delete(HeapNode *node) { return TwoPassMerge(node->leftChild);} struct PairingHeap { HeapNode *root; PairingHeap(): root(NULL) {} bool Empty(void) { return ::Empty(root); } int Top(void) { return ::Top(root); } void Insert(int key) { root = ::Insert(root, key); } void Delete(void) { root = ::Delete(root); } void Join(PairingHeap other) { root = ::Merge(root, other.root); } }; // Driver Codeint main(void) { PairingHeap heap1, heap2; heap2.Insert(5); heap2.Insert(2); heap2.Insert(6); heap1.Insert(1); heap1.Insert(3); heap1.Insert(4); heap1.Join(heap2); cout << heap1.Top() << endl; heap1.Delete(); cout << heap1.Top() << endl; cout<< (heap1.Empty()?"True":"False"); return 0;} # Heap structureclass HeapNode: # creates a new node def __init__(self, key_=None, leftChild_=None, nextSibling_=None): self.key = key_ self.leftChild = leftChild_ self.nextSibling = nextSibling_ # Adds a child and sibling to the node def addChild(self, node): if(self.leftChild == None): self.leftChild = node else: node.nextSibling = self.leftChild self.leftChild = node # Returns true if root of the tree# is None otherwise returns false def Empty(node): return (node == None) # Function to merge two heaps def Merge(A, B): # If any of the two-nodes is None # the return the not None node if(A == None): return B if(B == None): return A # To maintain the min heap condition compare # the nodes and node with minimum value become # parent of the other node if(A.key < B.key): A.addChild(B) return A B.addChild(A) return B # Returns the root value of the heap def Top(node): return node.key # Function to insert the new node in the heapdef Insert(node, key): return Merge(node, HeapNode(key,)) # This method is used when we want to delete root nodedef TwoPassMerge(node): if(node == None or node.nextSibling == None): return node A = node B = node.nextSibling newNode = node.nextSibling.nextSibling A.nextSibling = None B.nextSibling = None return Merge(Merge(A, B), TwoPassMerge(newNode)) # Function to delete the root node in heapdef Delete(node): return TwoPassMerge(node.leftChild) class PairingHeap: def __init__(self): self.root = None def Empty(self): return Empty(self.root) def Top(self): return Top(self.root) def Insert(self, key): self.root = Insert(self.root, key) def Delete(self): self.root = Delete(self.root) def Join(self, other): self.root = Merge(self.root, other.root) # Driver Codeif __name__ == '__main__': heap1, heap2 = PairingHeap(), PairingHeap() heap2.Insert(5) heap2.Insert(2) heap2.Insert(6) heap1.Insert(1) heap1.Insert(3) heap1.Insert(4) heap1.Join(heap2) print(heap1.Top()) heap1.Delete() print(heap1.Top()) print(heap1.Empty())# This code is contributed by Amartya Ghosh 1 2 False Time Complexity: Insertion: O(1)Merge: O(1)Deletion: O(logN) Auxiliary Space: O(1). pankajsharmagfg amartyaghoshgfg Data Structures Advanced Data Structure Data Structures Heap Data Structures Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Ordered Set and GNU C++ PBDS 2-3 Trees | (Search, Insert and Deletion) Extendible Hashing (Dynamic approach to DBMS) Suffix Array | Set 1 (Introduction) Interval Tree SDE SHEET - A Complete Guide for SDE Preparation Top 50 Array Coding Problems for Interviews DSA Sheet by Love Babbar Doubly Linked List | Set 1 (Introduction and Insertion) Introduction to Algorithms
[ { "code": null, "e": 25707, "s": 25679, "text": "\n01 Dec, 2021" }, { "code": null, "e": 26068, "s": 25707, "text": "Pairing Heap is like a simplified form Fibonacci Heap. It also maintains the property of min heap which is parent value is less than its child nodes value. It can be considered as a self-adjusting binomial heap.Each node has a pointer towards the left child and left child points towards the next sibling of the child. Example of Pairing Heap is given below: " }, { "code": null, "e": 26439, "s": 26068, "text": "Join or Merge in Pairing Heap To join the two heap, first, we compare the root node of the heap if the root node of the first heap is smaller than the root node of the second heap then root node of the second heap becomes a left child of the root node of the first heap otherwise vice-versa. The time complexity of this process is O(1).Example of Merge is given Below: " }, { "code": null, "e": 26662, "s": 26439, "text": "Insertion in Pairing Heap: To insert a new node in heap, create a new node and Merge it with existing heap as explained above. Therefore, the time complexity of this function is O(1). Example of Insertion is given below: " }, { "code": null, "e": 27240, "s": 26662, "text": "Deletion in Pairing Heap: Deletion in Pairing Heap only happens at the root node. First delete links between root, left child and all the siblings of the left child. Then Merge tree subtrees that are obtained by detaching the left child and all siblings by the two pass method and delete the root node. Merge the detached subtrees from left to right in one pass and then merge the subtrees from right to left to form the new heap without violation of conditions of min-heap. This process takes O(log n) time where n is the number of nodes. Example of Deletion is given below: " }, { "code": null, "e": 27293, "s": 27240, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27299, "s": 27293, "text": "CPP14" }, { "code": null, "e": 27307, "s": 27299, "text": "Python3" }, { "code": "#include<bits/stdc++.h>using namespace std; // Heap structurestruct HeapNode { int key; HeapNode *leftChild; HeapNode *nextSibling; HeapNode(): leftChild(NULL), nextSibling(NULL) {} // creates a new node HeapNode(int key_, HeapNode *leftChild_, HeapNode *nextSibling_): key(key_), leftChild(leftChild_), nextSibling(nextSibling_) {} // Adds a child and sibling to the node void addChild(HeapNode *node) { if(leftChild == NULL) leftChild = node; else { node->nextSibling = leftChild; leftChild = node; } }}; // Returns true if root of the tree// is null otherwise returns falsebool Empty(HeapNode *node) { return (node == NULL);} // Function to merge two heapsHeapNode *Merge(HeapNode *A, HeapNode *B){ // If any of the two-nodes is null // the return the not null node if(A == NULL) return B; if(B == NULL) return A; // To maintain the min heap condition compare // the nodes and node with minimum value become // parent of the other node if(A->key < B->key) { A->addChild(B); return A; } else { B->addChild(A); return B; } return NULL; // Unreachable} // Returns the root value of the heapint Top(HeapNode *node) { return node->key;} // Function to insert the new node in the heapHeapNode *Insert(HeapNode *node, int key) { return Merge(node, new HeapNode(key, NULL, NULL));} // This method is used when we want to delete root nodeHeapNode *TwoPassMerge(HeapNode *node) { if(node == NULL || node->nextSibling == NULL) return node; else { HeapNode *A, *B, *newNode; A = node; B = node->nextSibling; newNode = node->nextSibling->nextSibling; A->nextSibling = NULL; B->nextSibling = NULL; return Merge(Merge(A, B), TwoPassMerge(newNode)); } return NULL; // Unreachable} // Function to delete the root node in heapHeapNode *Delete(HeapNode *node) { return TwoPassMerge(node->leftChild);} struct PairingHeap { HeapNode *root; PairingHeap(): root(NULL) {} bool Empty(void) { return ::Empty(root); } int Top(void) { return ::Top(root); } void Insert(int key) { root = ::Insert(root, key); } void Delete(void) { root = ::Delete(root); } void Join(PairingHeap other) { root = ::Merge(root, other.root); } }; // Driver Codeint main(void) { PairingHeap heap1, heap2; heap2.Insert(5); heap2.Insert(2); heap2.Insert(6); heap1.Insert(1); heap1.Insert(3); heap1.Insert(4); heap1.Join(heap2); cout << heap1.Top() << endl; heap1.Delete(); cout << heap1.Top() << endl; cout<< (heap1.Empty()?\"True\":\"False\"); return 0;}", "e": 30147, "s": 27307, "text": null }, { "code": "# Heap structureclass HeapNode: # creates a new node def __init__(self, key_=None, leftChild_=None, nextSibling_=None): self.key = key_ self.leftChild = leftChild_ self.nextSibling = nextSibling_ # Adds a child and sibling to the node def addChild(self, node): if(self.leftChild == None): self.leftChild = node else: node.nextSibling = self.leftChild self.leftChild = node # Returns true if root of the tree# is None otherwise returns false def Empty(node): return (node == None) # Function to merge two heaps def Merge(A, B): # If any of the two-nodes is None # the return the not None node if(A == None): return B if(B == None): return A # To maintain the min heap condition compare # the nodes and node with minimum value become # parent of the other node if(A.key < B.key): A.addChild(B) return A B.addChild(A) return B # Returns the root value of the heap def Top(node): return node.key # Function to insert the new node in the heapdef Insert(node, key): return Merge(node, HeapNode(key,)) # This method is used when we want to delete root nodedef TwoPassMerge(node): if(node == None or node.nextSibling == None): return node A = node B = node.nextSibling newNode = node.nextSibling.nextSibling A.nextSibling = None B.nextSibling = None return Merge(Merge(A, B), TwoPassMerge(newNode)) # Function to delete the root node in heapdef Delete(node): return TwoPassMerge(node.leftChild) class PairingHeap: def __init__(self): self.root = None def Empty(self): return Empty(self.root) def Top(self): return Top(self.root) def Insert(self, key): self.root = Insert(self.root, key) def Delete(self): self.root = Delete(self.root) def Join(self, other): self.root = Merge(self.root, other.root) # Driver Codeif __name__ == '__main__': heap1, heap2 = PairingHeap(), PairingHeap() heap2.Insert(5) heap2.Insert(2) heap2.Insert(6) heap1.Insert(1) heap1.Insert(3) heap1.Insert(4) heap1.Join(heap2) print(heap1.Top()) heap1.Delete() print(heap1.Top()) print(heap1.Empty())# This code is contributed by Amartya Ghosh", "e": 32451, "s": 30147, "text": null }, { "code": null, "e": 32461, "s": 32451, "text": "1\n2\nFalse" }, { "code": null, "e": 32549, "s": 32463, "text": "Time Complexity: Insertion: O(1)Merge: O(1)Deletion: O(logN) Auxiliary Space: O(1). " }, { "code": null, "e": 32565, "s": 32549, "text": "pankajsharmagfg" }, { "code": null, "e": 32581, "s": 32565, "text": "amartyaghoshgfg" }, { "code": null, "e": 32597, "s": 32581, "text": "Data Structures" }, { "code": null, "e": 32621, "s": 32597, "text": "Advanced Data Structure" }, { "code": null, "e": 32637, "s": 32621, "text": "Data Structures" }, { "code": null, "e": 32642, "s": 32637, "text": "Heap" }, { "code": null, "e": 32658, "s": 32642, "text": "Data Structures" }, { "code": null, "e": 32663, "s": 32658, "text": "Heap" }, { "code": null, "e": 32761, "s": 32663, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32790, "s": 32761, "text": "Ordered Set and GNU C++ PBDS" }, { "code": null, "e": 32832, "s": 32790, "text": "2-3 Trees | (Search, Insert and Deletion)" }, { "code": null, "e": 32878, "s": 32832, "text": "Extendible Hashing (Dynamic approach to DBMS)" }, { "code": null, "e": 32914, "s": 32878, "text": "Suffix Array | Set 1 (Introduction)" }, { "code": null, "e": 32928, "s": 32914, "text": "Interval Tree" }, { "code": null, "e": 32977, "s": 32928, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 33021, "s": 32977, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 33046, "s": 33021, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 33102, "s": 33046, "text": "Doubly Linked List | Set 1 (Introduction and Insertion)" } ]
Fontstyle module in Python - GeeksforGeeks
17 Jan, 2022 Sometimes terminal text can be hard to read, the fontstyle module is package hosted on pypi.org for manipulating text. It can be used to break up the noise with some additional formatting, add colors, font weights and other styles to make it more readable. It also supports substring formatting for extra prettiness! pip install fontstyle Format text Preserve formatting Remove formatting 1) fonstyle.apply(): This method adds formatting to the entire input argument string. Syntax: fonstyle.apply(“STRING”,”all/possible/formatting/options”) Available Colors: BLACK, BLUE, CYAN, DARKCYAN, GREEN, PURPLE, RED, YELLOW, WHITE BackGround of Text: BLACK_BG, BLUE_BG, CYAN_BG, GREEN_BG, PURPLE_BG, RED_BG, YELLOW_BG, WHITE_BG Formatting Arguments: ‘BLINK’, ‘BOLD’, ‘FAINT’, ‘HIDDEN’, ‘ITALIC’, ‘INVERSE’, ‘STRIKE’, ‘UNDERLINE’, ‘END’ 2) fontstyle.erase(): This method is used to remove the formatting. 3) fontstyle.preserve(): This method returns the original text before formatting without removing the actual formatting of the text. Below are some programs which depict the use of fontstyle module in Python: Example 1: Python3 # import moduleimport fontstyle # format texttext = fontstyle.apply('GEEKSFORGEEKS', 'bold/Italic/red/GREEN_BG') # display textprint(text) Output: Here, we apply various formatting arguments like font color, background color, bold, italic on the given string. Example 2: Python3 # import required moduleimport fontstyle # display formatted textprint(fontstyle.apply('GEEKSFORGEEKS', 'bold/Italic/red/UNDERLINE/GREEN_BG')) print(fontstyle.apply('GEEKSFORGEEKS', 'bold/Italic/red/INVERSE/UNDERLINE/GREEN_BG')) Output: Here is another example of how to format text using this module. Example 3: Python3 # import moduleimport fontstyle # apply formattingtext = fontstyle.apply( 'GEEKSFORGEEKS', 'bold/Italic/red/INVERSE/2UNDERLINE/GREEN_BG') # display textprint(text) # preserved textprint(fontstyle.preserve(text)) Output: In this program, preserve() method is used to display the original text before formatting. Note: You must specify which formatting you want to erase else it will erase last updated formatting Example 4: Python3 # import required moduleimport fontstyle # format texttext = fontstyle.apply( 'GEEKSFORGEEKS', 'bold/Italic/red/INVERSE/2UNDERLINE/GREEN_BG') # display textprint(text) # remove formattingtext = fontstyle.erase(a, 'bold/Italic/red/INVERSE/2UNDERLINE/GREEN_BG') # display original textprint(text) Output: adnanirshad158 python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n17 Jan, 2022" }, { "code": null, "e": 25854, "s": 25537, "text": "Sometimes terminal text can be hard to read, the fontstyle module is package hosted on pypi.org for manipulating text. It can be used to break up the noise with some additional formatting, add colors, font weights and other styles to make it more readable. It also supports substring formatting for extra prettiness!" }, { "code": null, "e": 25876, "s": 25854, "text": "pip install fontstyle" }, { "code": null, "e": 25888, "s": 25876, "text": "Format text" }, { "code": null, "e": 25908, "s": 25888, "text": "Preserve formatting" }, { "code": null, "e": 25926, "s": 25908, "text": "Remove formatting" }, { "code": null, "e": 26012, "s": 25926, "text": "1) fonstyle.apply(): This method adds formatting to the entire input argument string." }, { "code": null, "e": 26079, "s": 26012, "text": "Syntax: fonstyle.apply(“STRING”,”all/possible/formatting/options”)" }, { "code": null, "e": 26160, "s": 26079, "text": "Available Colors: BLACK, BLUE, CYAN, DARKCYAN, GREEN, PURPLE, RED, YELLOW, WHITE" }, { "code": null, "e": 26257, "s": 26160, "text": "BackGround of Text: BLACK_BG, BLUE_BG, CYAN_BG, GREEN_BG, PURPLE_BG, RED_BG, YELLOW_BG, WHITE_BG" }, { "code": null, "e": 26365, "s": 26257, "text": "Formatting Arguments: ‘BLINK’, ‘BOLD’, ‘FAINT’, ‘HIDDEN’, ‘ITALIC’, ‘INVERSE’, ‘STRIKE’, ‘UNDERLINE’, ‘END’" }, { "code": null, "e": 26434, "s": 26365, "text": "2) fontstyle.erase(): This method is used to remove the formatting. " }, { "code": null, "e": 26567, "s": 26434, "text": "3) fontstyle.preserve(): This method returns the original text before formatting without removing the actual formatting of the text." }, { "code": null, "e": 26643, "s": 26567, "text": "Below are some programs which depict the use of fontstyle module in Python:" }, { "code": null, "e": 26654, "s": 26643, "text": "Example 1:" }, { "code": null, "e": 26662, "s": 26654, "text": "Python3" }, { "code": "# import moduleimport fontstyle # format texttext = fontstyle.apply('GEEKSFORGEEKS', 'bold/Italic/red/GREEN_BG') # display textprint(text)", "e": 26801, "s": 26662, "text": null }, { "code": null, "e": 26809, "s": 26801, "text": "Output:" }, { "code": null, "e": 26922, "s": 26809, "text": "Here, we apply various formatting arguments like font color, background color, bold, italic on the given string." }, { "code": null, "e": 26933, "s": 26922, "text": "Example 2:" }, { "code": null, "e": 26941, "s": 26933, "text": "Python3" }, { "code": "# import required moduleimport fontstyle # display formatted textprint(fontstyle.apply('GEEKSFORGEEKS', 'bold/Italic/red/UNDERLINE/GREEN_BG')) print(fontstyle.apply('GEEKSFORGEEKS', 'bold/Italic/red/INVERSE/UNDERLINE/GREEN_BG'))", "e": 27212, "s": 26941, "text": null }, { "code": null, "e": 27220, "s": 27212, "text": "Output:" }, { "code": null, "e": 27285, "s": 27220, "text": "Here is another example of how to format text using this module." }, { "code": null, "e": 27296, "s": 27285, "text": "Example 3:" }, { "code": null, "e": 27304, "s": 27296, "text": "Python3" }, { "code": "# import moduleimport fontstyle # apply formattingtext = fontstyle.apply( 'GEEKSFORGEEKS', 'bold/Italic/red/INVERSE/2UNDERLINE/GREEN_BG') # display textprint(text) # preserved textprint(fontstyle.preserve(text))", "e": 27519, "s": 27304, "text": null }, { "code": null, "e": 27527, "s": 27519, "text": "Output:" }, { "code": null, "e": 27618, "s": 27527, "text": "In this program, preserve() method is used to display the original text before formatting." }, { "code": null, "e": 27719, "s": 27618, "text": "Note: You must specify which formatting you want to erase else it will erase last updated formatting" }, { "code": null, "e": 27730, "s": 27719, "text": "Example 4:" }, { "code": null, "e": 27738, "s": 27730, "text": "Python3" }, { "code": "# import required moduleimport fontstyle # format texttext = fontstyle.apply( 'GEEKSFORGEEKS', 'bold/Italic/red/INVERSE/2UNDERLINE/GREEN_BG') # display textprint(text) # remove formattingtext = fontstyle.erase(a, 'bold/Italic/red/INVERSE/2UNDERLINE/GREEN_BG') # display original textprint(text)", "e": 28036, "s": 27738, "text": null }, { "code": null, "e": 28044, "s": 28036, "text": "Output:" }, { "code": null, "e": 28059, "s": 28044, "text": "adnanirshad158" }, { "code": null, "e": 28074, "s": 28059, "text": "python-modules" }, { "code": null, "e": 28081, "s": 28074, "text": "Python" }, { "code": null, "e": 28179, "s": 28081, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28211, "s": 28179, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28253, "s": 28211, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28295, "s": 28253, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28351, "s": 28295, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28378, "s": 28351, "text": "Python Classes and Objects" }, { "code": null, "e": 28417, "s": 28378, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28448, "s": 28417, "text": "Python | os.path.join() method" }, { "code": null, "e": 28470, "s": 28448, "text": "Defaultdict in Python" }, { "code": null, "e": 28499, "s": 28470, "text": "Create a directory in Python" } ]
How to change Matplotlib color bar size in Python? - GeeksforGeeks
03 Jan, 2021 Colorbar is a separate axis that provides a current colormap indicating mapping of data-points into colors. In this article, We are going to change Matplotlib color bar size in Python. There are several ways with which you can resize your color-bar or adjust its position. Let’s see it one by one. Method 1: Resizing color-bar using shrink keyword argument Using the shrink attribute of colorbar() function we can scale the size of the colorbar. Syntax : matplotlib.pyplot.colorbar(mappable=None, shrink=scale) Basically, we are multiplying by some factor to the original size of the color-bar. In the below example by using 0.5 as a factor, We are having the original color-bar size. Example 1: Python3 # importing libraryimport matplotlib.pyplot as plt # Some data to show as an imagedata = [[1, 2, 3], [4, 5, 6]] # Call imshow() to display 2-D data as an imageimg = plt.imshow(data) # Scaling colorbar by factor 0.5plt.colorbar(shrink=0.5)plt.show() Output: Using_shrink_attribute Example 2: In this example, we are using factor 0.75. Similarly, you can use any factor to change the color-bar size. The default value of the shrink attribute is 1. Python3 import matplotlib.pyplot as pltimport matplotlib.image as mpimgfig, ax = plt.subplots() # getting rid of axisplt.axis('off') # Reading saved image from folderimg = mpimg.imread(r'img.jpg') # displaying imageplt.imshow(img) # Scaling by factor 0.75plt.colorbar(shrink=0.75)plt.show() Output: Using_shrink_attribute Method 2: Using AxesDivider class With this class, you can change the size of the colorbar axes however height will be the same as the current axes. Here we are using axes_divider.make_axes_locatable function which returns the AxisDivider object for our current axes in which our image is shown. Example: Python3 # importing librariesimport matplotlib.pyplot as pltfrom mpl_toolkits.axes_grid1 import make_axes_locatable fig, ax = plt.subplots()# Reading image from folder img = mpimg.imread(r'img.jpg')image = plt.imshow(img) # Locating current axesdivider = make_axes_locatable(ax) # creating new axes on the right# side of current axes(ax).# The width of cax will be 5% of ax# and the padding between cax and ax# will be fixed at 0.05 inch.colorbar_axes = divider.append_axes("right", size="10%", pad=0.1)# Using new axes for colorbarplt.colorbar(image, cax=colorbar_axes)plt.show() Output: Using_AxisDivider Picked Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n03 Jan, 2021" }, { "code": null, "e": 25835, "s": 25537, "text": "Colorbar is a separate axis that provides a current colormap indicating mapping of data-points into colors. In this article, We are going to change Matplotlib color bar size in Python. There are several ways with which you can resize your color-bar or adjust its position. Let’s see it one by one." }, { "code": null, "e": 25894, "s": 25835, "text": "Method 1: Resizing color-bar using shrink keyword argument" }, { "code": null, "e": 25984, "s": 25894, "text": "Using the shrink attribute of colorbar() function we can scale the size of the colorbar. " }, { "code": null, "e": 26049, "s": 25984, "text": "Syntax : matplotlib.pyplot.colorbar(mappable=None, shrink=scale)" }, { "code": null, "e": 26223, "s": 26049, "text": "Basically, we are multiplying by some factor to the original size of the color-bar. In the below example by using 0.5 as a factor, We are having the original color-bar size." }, { "code": null, "e": 26236, "s": 26223, "text": "Example 1: " }, { "code": null, "e": 26244, "s": 26236, "text": "Python3" }, { "code": "# importing libraryimport matplotlib.pyplot as plt # Some data to show as an imagedata = [[1, 2, 3], [4, 5, 6]] # Call imshow() to display 2-D data as an imageimg = plt.imshow(data) # Scaling colorbar by factor 0.5plt.colorbar(shrink=0.5)plt.show()", "e": 26503, "s": 26244, "text": null }, { "code": null, "e": 26512, "s": 26503, "text": "Output: " }, { "code": null, "e": 26535, "s": 26512, "text": "Using_shrink_attribute" }, { "code": null, "e": 26701, "s": 26535, "text": "Example 2: In this example, we are using factor 0.75. Similarly, you can use any factor to change the color-bar size. The default value of the shrink attribute is 1." }, { "code": null, "e": 26709, "s": 26701, "text": "Python3" }, { "code": "import matplotlib.pyplot as pltimport matplotlib.image as mpimgfig, ax = plt.subplots() # getting rid of axisplt.axis('off') # Reading saved image from folderimg = mpimg.imread(r'img.jpg') # displaying imageplt.imshow(img) # Scaling by factor 0.75plt.colorbar(shrink=0.75)plt.show()", "e": 26996, "s": 26709, "text": null }, { "code": null, "e": 27005, "s": 26996, "text": "Output: " }, { "code": null, "e": 27028, "s": 27005, "text": "Using_shrink_attribute" }, { "code": null, "e": 27062, "s": 27028, "text": "Method 2: Using AxesDivider class" }, { "code": null, "e": 27324, "s": 27062, "text": "With this class, you can change the size of the colorbar axes however height will be the same as the current axes. Here we are using axes_divider.make_axes_locatable function which returns the AxisDivider object for our current axes in which our image is shown." }, { "code": null, "e": 27334, "s": 27324, "text": "Example: " }, { "code": null, "e": 27342, "s": 27334, "text": "Python3" }, { "code": "# importing librariesimport matplotlib.pyplot as pltfrom mpl_toolkits.axes_grid1 import make_axes_locatable fig, ax = plt.subplots()# Reading image from folder img = mpimg.imread(r'img.jpg')image = plt.imshow(img) # Locating current axesdivider = make_axes_locatable(ax) # creating new axes on the right# side of current axes(ax).# The width of cax will be 5% of ax# and the padding between cax and ax# will be fixed at 0.05 inch.colorbar_axes = divider.append_axes(\"right\", size=\"10%\", pad=0.1)# Using new axes for colorbarplt.colorbar(image, cax=colorbar_axes)plt.show()", "e": 27989, "s": 27342, "text": null }, { "code": null, "e": 27998, "s": 27989, "text": "Output: " }, { "code": null, "e": 28016, "s": 27998, "text": "Using_AxisDivider" }, { "code": null, "e": 28023, "s": 28016, "text": "Picked" }, { "code": null, "e": 28041, "s": 28023, "text": "Python-matplotlib" }, { "code": null, "e": 28048, "s": 28041, "text": "Python" }, { "code": null, "e": 28146, "s": 28048, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28178, "s": 28146, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28220, "s": 28178, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28262, "s": 28220, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28289, "s": 28262, "text": "Python Classes and Objects" }, { "code": null, "e": 28345, "s": 28289, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28367, "s": 28345, "text": "Defaultdict in Python" }, { "code": null, "e": 28406, "s": 28367, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28437, "s": 28406, "text": "Python | os.path.join() method" }, { "code": null, "e": 28466, "s": 28437, "text": "Create a directory in Python" } ]
Inherit a class to another file in Sass - GeeksforGeeks
14 Aug, 2020 Sass or syntactically awesome style sheets is a CSS preprocessor that gives CSS such powers that are not available in plain CSS. It gives the power of using expressions, variables, nesting, mixins(Sass form of functions), inheritance, and more. Other well-known CSS preprocessor examples include Less and Stylus but Sass is more popular. Sass includes two syntaxes: SCSS(Sassy CSS) Sass SCSS or Sassy CSS SCSS uses the .scss syntax and it is very similar to regular CSS. SCSS is fully compliant with CSS. SCSS can be assumed as a superset of CSS. Any valid CSS style is a valid SCSS. Because of the similarity with CSS, it takes less time to get started with it. Example: $heading-color: #e94e1b; //Using Sass Variablesh4 { color: $heading-color;} The indented syntax or Sass This is the original syntax of Sass. It uses .sass file extension. It uses all the features of Sass but instead of using the curly-braces, it uses indentation to describe the format of the document. It is not fully compliant with CSS. Example $heading-color: #e94e1b; h4 color: $heading-color @import and @use: A single CSS file can eventually grow larger and it’ll be a tough job to maintain large stylesheets. So, it would be easier if there’s a way to separate classes into various files. So one can import only the necessary files. In this way the stylesheet will be smaller and also maintenance will be easier. The stylesheet will also maintain the DRY(Don’t Repeat Yourself) rule. Approach 1: To import another stylesheet into a stylesheet, the @import keyword is used. The CSS or Scss files to be imported can reside in the same folder or somewhere else on the internet. Syntax: @import 'file-name'; @import url('url of the stylesheet') Example @import './buttons.scss';@import url('https://example.com/css/breadcrumbs.scss'); Compiled CSS @import url(‘https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css’);.btn-large {border-radius: 3rem;border: 4px solid black;background: black;color: white;width: 20rem;height: 10rem;display: flex;align-items: center;justify-content: center;} This is a feasible solution to import a CSS file into another file. But Sass has deprecated @import and will eventually remove it. Instead of using @import, Sass now supports @use because CSS also has a @import feature and there are some other major drawbacks of using @import which is a topic for another article. Approach 2: The @use has to be used with a namespace. Suppose a file buttons residing on the same directory has a color variable called primary-color. To use the variable in other files, the below syntax will be followed. Syntax: @use 'file-name'; Example: @use 'buttons'; .card { color: buttons.$primary-color;} Compiled CSS: .btn-large { border-radius: 3rem; border: 4px solid black; background: black; color: white; width: 20rem; height: 10rem; display: flex; align-items: center; justify-content: center; } The namespace is used because of the naming conflicts that exist in @import. If two imported files contain two different variables of the same name, @import will force to use the variable value defined in the last imported file. The @use also gives the ability to use a user-defined namespace. Example: @use 'buttons' as btn; .card { color: btn.$primary-color;} The as keyword allows defining custom namespaces. An important thing to note here is that the Live Sass Compiler on VS Code is based on LibSass and LibSass currently doesn’t support the @use function. So it is better to use the Dart Sass which generally is the first to implement new features. Installing Dart Sass is easy. This post here describes the steps. Inheriting Styles from other classes The previous section briefly described how to import and use styles stored in another file using the @import and the @use operator. To inherit a style from another class or id, the @extend keyword is used. Let’s see an example, suppose the buttons class has a color: green; and opacity: .5; property, now to inherit these styles into another class, the @extend keyword will be used. Example: buttons.scss file /* buttons.scss file */.btn { color: red; opacity: 0.5;} style.scss file /*style.scss filewhere the style is to be inherited */@use 'buttons'; .new-btn { @extend .btn;} So, the above code will inherit the properties from .btn class to the .new-btn class. Now, let’s take a look at the compiled CSS file. Compiled CSS /* style.css */ .btn, .new-btn { color: red; opacity: 0.5; } One thing to note here is that the styles from the .btn class are not getting copied to the new-btn class, rather it comma separates the original selector which reduces duplicate code. Conclusion So, in this article, the @include, @use and the @extend keyword used in Sass are described briefly. Inheriting can also be achieved using mixins. To read about the mixin, you can check this article. Though if the style doesn’t take any parameters, it is better to use the @extend method. SASS CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a web page using HTML and CSS Form validation using jQuery Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26621, "s": 26593, "text": "\n14 Aug, 2020" }, { "code": null, "e": 26959, "s": 26621, "text": "Sass or syntactically awesome style sheets is a CSS preprocessor that gives CSS such powers that are not available in plain CSS. It gives the power of using expressions, variables, nesting, mixins(Sass form of functions), inheritance, and more. Other well-known CSS preprocessor examples include Less and Stylus but Sass is more popular." }, { "code": null, "e": 26987, "s": 26959, "text": "Sass includes two syntaxes:" }, { "code": null, "e": 27003, "s": 26987, "text": "SCSS(Sassy CSS)" }, { "code": null, "e": 27008, "s": 27003, "text": "Sass" }, { "code": null, "e": 27026, "s": 27008, "text": "SCSS or Sassy CSS" }, { "code": null, "e": 27284, "s": 27026, "text": "SCSS uses the .scss syntax and it is very similar to regular CSS. SCSS is fully compliant with CSS. SCSS can be assumed as a superset of CSS. Any valid CSS style is a valid SCSS. Because of the similarity with CSS, it takes less time to get started with it." }, { "code": null, "e": 27293, "s": 27284, "text": "Example:" }, { "code": "$heading-color: #e94e1b; //Using Sass Variablesh4 { color: $heading-color;}", "e": 27372, "s": 27293, "text": null }, { "code": null, "e": 27400, "s": 27372, "text": "The indented syntax or Sass" }, { "code": null, "e": 27635, "s": 27400, "text": "This is the original syntax of Sass. It uses .sass file extension. It uses all the features of Sass but instead of using the curly-braces, it uses indentation to describe the format of the document. It is not fully compliant with CSS." }, { "code": null, "e": 27643, "s": 27635, "text": "Example" }, { "code": "$heading-color: #e94e1b; h4 color: $heading-color", "e": 27694, "s": 27643, "text": null }, { "code": null, "e": 27712, "s": 27694, "text": "@import and @use:" }, { "code": null, "e": 28089, "s": 27712, "text": "A single CSS file can eventually grow larger and it’ll be a tough job to maintain large stylesheets. So, it would be easier if there’s a way to separate classes into various files. So one can import only the necessary files. In this way the stylesheet will be smaller and also maintenance will be easier. The stylesheet will also maintain the DRY(Don’t Repeat Yourself) rule. " }, { "code": null, "e": 28280, "s": 28089, "text": "Approach 1: To import another stylesheet into a stylesheet, the @import keyword is used. The CSS or Scss files to be imported can reside in the same folder or somewhere else on the internet." }, { "code": null, "e": 28288, "s": 28280, "text": "Syntax:" }, { "code": null, "e": 28347, "s": 28288, "text": "@import 'file-name';\n@import url('url of the stylesheet')\n" }, { "code": null, "e": 28355, "s": 28347, "text": "Example" }, { "code": "@import './buttons.scss';@import url('https://example.com/css/breadcrumbs.scss');", "e": 28437, "s": 28355, "text": null }, { "code": null, "e": 28450, "s": 28437, "text": "Compiled CSS" }, { "code": null, "e": 28715, "s": 28450, "text": "@import url(‘https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css’);.btn-large {border-radius: 3rem;border: 4px solid black;background: black;color: white;width: 20rem;height: 10rem;display: flex;align-items: center;justify-content: center;}" }, { "code": null, "e": 29030, "s": 28715, "text": "This is a feasible solution to import a CSS file into another file. But Sass has deprecated @import and will eventually remove it. Instead of using @import, Sass now supports @use because CSS also has a @import feature and there are some other major drawbacks of using @import which is a topic for another article." }, { "code": null, "e": 29252, "s": 29030, "text": "Approach 2: The @use has to be used with a namespace. Suppose a file buttons residing on the same directory has a color variable called primary-color. To use the variable in other files, the below syntax will be followed." }, { "code": null, "e": 29260, "s": 29252, "text": "Syntax:" }, { "code": null, "e": 29278, "s": 29260, "text": "@use 'file-name';" }, { "code": null, "e": 29287, "s": 29278, "text": "Example:" }, { "code": "@use 'buttons'; .card { color: buttons.$primary-color;}", "e": 29347, "s": 29287, "text": null }, { "code": null, "e": 29361, "s": 29347, "text": "Compiled CSS:" }, { "code": null, "e": 29563, "s": 29361, "text": ".btn-large {\n border-radius: 3rem;\n border: 4px solid black;\n background: black;\n color: white;\n width: 20rem;\n height: 10rem;\n display: flex;\n align-items: center;\n justify-content: center;\n}" }, { "code": null, "e": 29792, "s": 29563, "text": "The namespace is used because of the naming conflicts that exist in @import. If two imported files contain two different variables of the same name, @import will force to use the variable value defined in the last imported file." }, { "code": null, "e": 29857, "s": 29792, "text": "The @use also gives the ability to use a user-defined namespace." }, { "code": null, "e": 29866, "s": 29857, "text": "Example:" }, { "code": "@use 'buttons' as btn; .card { color: btn.$primary-color;}", "e": 29929, "s": 29866, "text": null }, { "code": null, "e": 29979, "s": 29929, "text": "The as keyword allows defining custom namespaces." }, { "code": null, "e": 30289, "s": 29979, "text": "An important thing to note here is that the Live Sass Compiler on VS Code is based on LibSass and LibSass currently doesn’t support the @use function. So it is better to use the Dart Sass which generally is the first to implement new features. Installing Dart Sass is easy. This post here describes the steps." }, { "code": null, "e": 30326, "s": 30289, "text": "Inheriting Styles from other classes" }, { "code": null, "e": 30709, "s": 30326, "text": "The previous section briefly described how to import and use styles stored in another file using the @import and the @use operator. To inherit a style from another class or id, the @extend keyword is used. Let’s see an example, suppose the buttons class has a color: green; and opacity: .5; property, now to inherit these styles into another class, the @extend keyword will be used." }, { "code": null, "e": 30718, "s": 30709, "text": "Example:" }, { "code": null, "e": 30736, "s": 30718, "text": "buttons.scss file" }, { "code": "/* buttons.scss file */.btn { color: red; opacity: 0.5;}", "e": 30795, "s": 30736, "text": null }, { "code": null, "e": 30811, "s": 30795, "text": "style.scss file" }, { "code": "/*style.scss filewhere the style is to be inherited */@use 'buttons'; .new-btn { @extend .btn;}", "e": 30909, "s": 30811, "text": null }, { "code": null, "e": 30995, "s": 30909, "text": "So, the above code will inherit the properties from .btn class to the .new-btn class." }, { "code": null, "e": 31044, "s": 30995, "text": "Now, let’s take a look at the compiled CSS file." }, { "code": null, "e": 31057, "s": 31044, "text": "Compiled CSS" }, { "code": null, "e": 31123, "s": 31057, "text": "/* style.css */\n.btn, .new-btn {\n color: red;\n opacity: 0.5;\n}\n" }, { "code": null, "e": 31308, "s": 31123, "text": "One thing to note here is that the styles from the .btn class are not getting copied to the new-btn class, rather it comma separates the original selector which reduces duplicate code." }, { "code": null, "e": 31319, "s": 31308, "text": "Conclusion" }, { "code": null, "e": 31608, "s": 31319, "text": "So, in this article, the @include, @use and the @extend keyword used in Sass are described briefly. Inheriting can also be achieved using mixins. To read about the mixin, you can check this article. Though if the style doesn’t take any parameters, it is better to use the @extend method. " }, { "code": null, "e": 31613, "s": 31608, "text": "SASS" }, { "code": null, "e": 31617, "s": 31613, "text": "CSS" }, { "code": null, "e": 31634, "s": 31617, "text": "Web Technologies" }, { "code": null, "e": 31732, "s": 31634, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31771, "s": 31732, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 31808, "s": 31771, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 31837, "s": 31808, "text": "Form validation using jQuery" }, { "code": null, "e": 31879, "s": 31837, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 31914, "s": 31879, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 31954, "s": 31914, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31987, "s": 31954, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 32032, "s": 31987, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 32075, "s": 32032, "text": "How to fetch data from an API in ReactJS ?" } ]
HTTP headers | Accept - GeeksforGeeks
07 Nov, 2019 The HTTP Accept header is a request type header. The Accept header is used to inform the server by the client that which content type is understandable by the client expressed as MIME-types. By using the Content-negotiation the server selects a proposal of the content type and informs the client of its choice with the Content-type response header. If the Accept header is not present in the request, then the server assumes that the client accepts all types of media. Syntax: Accept: <MIME_type>/<MIME_subtype> | <MIME_type>/* | */* Directives: This header accept below mentioned directives: <MIME_type>/<MIME_subtype>: This directive holds the type/subtype of the web content that the client will received by content-type header which is chosen by the server from Accept header. Basically it holds the single mime type like text/html. <MIME_type>/*: This directive holds the type but can accept any subtyping like image/* means the image can be jpg, png, or can svg everything will be accepted. */* This directive accepts any kind of type/subtype. Example: This example accepts the text type with the subtype of html.Accept: text/html Accept: text/html This example accept any image subtype does not bother.Accept: image/* Accept: image/* To check this Accept in action go to Inspect Element -> Network check the request header for Accept like below, Accept is highlighted you can see. Supported Browsers: The browsers are compatible with HTTP Accept header are listed below: Google Chrome Internet Explorer Firefox Safari Opera HTTP-headers Picked Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to create footer to stay at the bottom of a Web page? Node.js fs.readFileSync() Method How to set the default value for an HTML <select> element ? File uploading in React.js How to apply style to parent if it has child with CSS?
[ { "code": null, "e": 25869, "s": 25841, "text": "\n07 Nov, 2019" }, { "code": null, "e": 26339, "s": 25869, "text": "The HTTP Accept header is a request type header. The Accept header is used to inform the server by the client that which content type is understandable by the client expressed as MIME-types. By using the Content-negotiation the server selects a proposal of the content type and informs the client of its choice with the Content-type response header. If the Accept header is not present in the request, then the server assumes that the client accepts all types of media." }, { "code": null, "e": 26347, "s": 26339, "text": "Syntax:" }, { "code": null, "e": 26404, "s": 26347, "text": "Accept: <MIME_type>/<MIME_subtype> | <MIME_type>/* | */*" }, { "code": null, "e": 26463, "s": 26404, "text": "Directives: This header accept below mentioned directives:" }, { "code": null, "e": 26707, "s": 26463, "text": "<MIME_type>/<MIME_subtype>: This directive holds the type/subtype of the web content that the client will received by content-type header which is chosen by the server from Accept header. Basically it holds the single mime type like text/html." }, { "code": null, "e": 26867, "s": 26707, "text": "<MIME_type>/*: This directive holds the type but can accept any subtyping like image/* means the image can be jpg, png, or can svg everything will be accepted." }, { "code": null, "e": 26920, "s": 26867, "text": "*/* This directive accepts any kind of type/subtype." }, { "code": null, "e": 26929, "s": 26920, "text": "Example:" }, { "code": null, "e": 27007, "s": 26929, "text": "This example accepts the text type with the subtype of html.Accept: text/html" }, { "code": null, "e": 27025, "s": 27007, "text": "Accept: text/html" }, { "code": null, "e": 27095, "s": 27025, "text": "This example accept any image subtype does not bother.Accept: image/*" }, { "code": null, "e": 27111, "s": 27095, "text": "Accept: image/*" }, { "code": null, "e": 27258, "s": 27111, "text": "To check this Accept in action go to Inspect Element -> Network check the request header for Accept like below, Accept is highlighted you can see." }, { "code": null, "e": 27348, "s": 27258, "text": "Supported Browsers: The browsers are compatible with HTTP Accept header are listed below:" }, { "code": null, "e": 27362, "s": 27348, "text": "Google Chrome" }, { "code": null, "e": 27380, "s": 27362, "text": "Internet Explorer" }, { "code": null, "e": 27388, "s": 27380, "text": "Firefox" }, { "code": null, "e": 27395, "s": 27388, "text": "Safari" }, { "code": null, "e": 27401, "s": 27395, "text": "Opera" }, { "code": null, "e": 27414, "s": 27401, "text": "HTTP-headers" }, { "code": null, "e": 27421, "s": 27414, "text": "Picked" }, { "code": null, "e": 27438, "s": 27421, "text": "Web Technologies" }, { "code": null, "e": 27536, "s": 27438, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27576, "s": 27536, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27621, "s": 27576, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27664, "s": 27621, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27725, "s": 27664, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27797, "s": 27725, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27855, "s": 27797, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 27888, "s": 27855, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 27948, "s": 27888, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 27975, "s": 27948, "text": "File uploading in React.js" } ]
How to validate GUID (Globally Unique Identifier) using Regular Expression - GeeksforGeeks
02 Feb, 2021 Given string str, the task is to check whether the given string is valid GUID (Globally Unique Identifier) or not by using Regular Expression.The valid GUID (Globally Unique Identifier) must specify the following conditions: It should be a 128-bit number.It should be 36 characters (32 hexadecimal characters and 4 hyphens) long.It should be displayed in five groups separated by hyphens (-).Microsoft GUIDs are sometimes represented with surrounding braces. It should be a 128-bit number. It should be 36 characters (32 hexadecimal characters and 4 hyphens) long. It should be displayed in five groups separated by hyphens (-). Microsoft GUIDs are sometimes represented with surrounding braces. Examples: Input: str = “123e4567-e89b-12d3-a456-9AC7CBDCEE52” Output: true Explanation: The given string satisfies all the above mentioned conditions. Therefore, it is a valid GUID (Globally Unique Identifier).Input: str = “123e4567-h89b-12d3-a456-9AC7CBDCEE52” Output: false Explanation: The given string contains ‘h’, the valid hexadecimal characters should be followed by character from a-f, A-F, and 0-9. Therefore, it is not a valid GUID (Globally Unique Identifier).Input: str = “123e4567-h89b-12d3-a456” Output: false Explanation: The given string has 20 characters. Therefore, it is not a valid GUID (Globally Unique Identifier). Approach: The idea is to use Regular Expression to solve this problem. The following steps can be followed to compute the answer: Get the String. Create a regular expression to check valid GUID (Globally Unique Identifier) as mentioned below: regex = “^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$” Where: ^ represents the starting of the string.[{]? represents the ‘{‘ character that is optional.[0-9a-fA-F]{8} represents the 8 characters from a-f, A-F, and 0-9.– represents the hyphens.([0-9a-fA-F]{4}-){3} represents the 4 characters from a-f, A-F, and 0-9 that is repeated 3 times separated by a hyphen (-).[0-9a-fA-F]{12} represents the 12 characters from a-f, A-F, and 0-9.[}]? represents the ‘}’ character that is optional.$ represents the ending of the string. ^ represents the starting of the string. [{]? represents the ‘{‘ character that is optional. [0-9a-fA-F]{8} represents the 8 characters from a-f, A-F, and 0-9. – represents the hyphens. ([0-9a-fA-F]{4}-){3} represents the 4 characters from a-f, A-F, and 0-9 that is repeated 3 times separated by a hyphen (-). [0-9a-fA-F]{12} represents the 12 characters from a-f, A-F, and 0-9. [}]? represents the ‘}’ character that is optional. $ represents the ending of the string. Match the given string with the Regular Expression. In Java, this can be done by using Pattern.matcher(). Return true if the string matches with the given regular expression, else return false. Below is the implementation of the above approach: C++ Java Python3 // C++ program to validate the// GUID (Globally Unique Identifier) using Regular Expression#include <iostream>#include <regex>using namespace std; // Function to validate the GUID (Globally Unique Identifier).bool isValidGUID(string str){ // Regex to check valid GUID (Globally Unique Identifier). const regex pattern("^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$"); // If the GUID (Globally Unique Identifier) // is empty return false if (str.empty()) { return false; } // Return true if the GUID (Globally Unique Identifier) // matched the ReGex if(regex_match(str, pattern)) { return true; } else { return false; }} // Driver Codeint main(){ // Test Case 1: string str1 = "123e4567-e89b-12d3-a456-9AC7CBDCEE52"; cout << isValidGUID(str1) << endl; // Test Case 2: string str2 = "{123e4567-e89b-12d3-a456-9AC7CBDCEE52}"; cout << isValidGUID(str2) << endl; // Test Case 3: string str3 = "123e4567-h89b-12d3-a456-9AC7CBDCEE52"; cout << isValidGUID(str3) << endl; // Test Case 4: string str4 = "123e4567-h89b-12d3-a456"; cout << isValidGUID(str4) << endl; return 0;} // This code is contributed by yuvraj_chandra // Java program to validate// GUID (Globally Unique Identifier)// using regular expression import java.util.regex.*; class GFG { // Function to validate // GUID (Globally Unique Identifier) // using regular expression public static boolean isValidGUID(String str) { // Regex to check valid // GUID (Globally Unique Identifier) String regex = "^[{]?[0-9a-fA-F]{8}" + "-([0-9a-fA-F]{4}-)" + "{3}[0-9a-fA-F]{12}[}]?$"; // Compile the ReGex Pattern p = Pattern.compile(regex); // If the string is empty // return false if (str == null) { return false; } // Find match between given string // and regular expression // uSing Pattern.matcher() Matcher m = p.matcher(str); // Return if the string // matched the ReGex return m.matches(); } // Driver code public static void main(String args[]) { // Test Case 1: String str2 = "123e4567-e89b-12d3" + "-a456-9AC7CBDCEE52"; System.out.println( isValidGUID(str2)); // Test Case 2: String str3 = "{123e4567-e89b-12d3-" + "a456-9AC7CBDCEE52}"; System.out.println( isValidGUID(str3)); // Test Case 3: String str1 = "123e4567-h89b-12d3-a456" + "-9AC7CBDCEE52"; System.out.println( isValidGUID(str1)); // Test Case 4: String str4 = "123e4567-h89b-12d3-a456"; System.out.println( isValidGUID(str4)); }} # Python3 program to validate# GUID (Globally Unique Identifier)# using regular expressionimport re # Function to validate GUID# (Globally Unique Identifier)def isValidGUID(str): # Regex to check valid # GUID (Globally Unique Identifier) regex = "^[{]?[0-9a-fA-F]{8}" + "-([0-9a-fA-F]{4}-)" + "{3}[0-9a-fA-F]{12}[}]?$" # Compile the ReGex p = re.compile(regex) # If the string is empty # return false if (str == None): return False # Return if the string # matched the ReGex if(re.search(p, str)): return True else: return False # Driver code # Test Case 1:str1 = "123e4567-e89b-12d3" + "-a456-9AC7CBDCEE52"print(isValidGUID(str1)) # Test Case 2:str2 = "{123e4567-e89b-12d3-" + "a456-9AC7CBDCEE52}"print(isValidGUID(str2)) # Test Case 3:str3 = "123e4567-h89b-12d3-a456" + "-9AC7CBDCEE52"print(isValidGUID(str3)) # Test Case 4:str4 = "123e4567-h89b-12d3-a456"print(isValidGUID(str4)) # This code is contributed by avanitrachhadiya2155 true true false false avanitrachhadiya2155 yuvraj_chandra CPP-regex java-regular-expression regular-expression Pattern Searching Strings Strings Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Removing string that is an anagram of an earlier string Count N-length strings consisting only of vowels sorted lexicographically Boyer Moore Algorithm | Good Suffix heuristic Check whether two strings contain same characters in same order How to check Aadhaar number is valid or not using Regular Expression 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 Longest Common Subsequence | DP-4
[ { "code": null, "e": 26653, "s": 26625, "text": "\n02 Feb, 2021" }, { "code": null, "e": 26879, "s": 26653, "text": "Given string str, the task is to check whether the given string is valid GUID (Globally Unique Identifier) or not by using Regular Expression.The valid GUID (Globally Unique Identifier) must specify the following conditions: " }, { "code": null, "e": 27113, "s": 26879, "text": "It should be a 128-bit number.It should be 36 characters (32 hexadecimal characters and 4 hyphens) long.It should be displayed in five groups separated by hyphens (-).Microsoft GUIDs are sometimes represented with surrounding braces." }, { "code": null, "e": 27144, "s": 27113, "text": "It should be a 128-bit number." }, { "code": null, "e": 27219, "s": 27144, "text": "It should be 36 characters (32 hexadecimal characters and 4 hyphens) long." }, { "code": null, "e": 27283, "s": 27219, "text": "It should be displayed in five groups separated by hyphens (-)." }, { "code": null, "e": 27350, "s": 27283, "text": "Microsoft GUIDs are sometimes represented with surrounding braces." }, { "code": null, "e": 27361, "s": 27350, "text": "Examples: " }, { "code": null, "e": 27990, "s": 27361, "text": "Input: str = “123e4567-e89b-12d3-a456-9AC7CBDCEE52” Output: true Explanation: The given string satisfies all the above mentioned conditions. Therefore, it is a valid GUID (Globally Unique Identifier).Input: str = “123e4567-h89b-12d3-a456-9AC7CBDCEE52” Output: false Explanation: The given string contains ‘h’, the valid hexadecimal characters should be followed by character from a-f, A-F, and 0-9. Therefore, it is not a valid GUID (Globally Unique Identifier).Input: str = “123e4567-h89b-12d3-a456” Output: false Explanation: The given string has 20 characters. Therefore, it is not a valid GUID (Globally Unique Identifier). " }, { "code": null, "e": 28120, "s": 27990, "text": "Approach: The idea is to use Regular Expression to solve this problem. The following steps can be followed to compute the answer:" }, { "code": null, "e": 28136, "s": 28120, "text": "Get the String." }, { "code": null, "e": 28234, "s": 28136, "text": "Create a regular expression to check valid GUID (Globally Unique Identifier) as mentioned below: " }, { "code": null, "e": 28306, "s": 28234, "text": "regex = “^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$” " }, { "code": null, "e": 28776, "s": 28306, "text": "Where: ^ represents the starting of the string.[{]? represents the ‘{‘ character that is optional.[0-9a-fA-F]{8} represents the 8 characters from a-f, A-F, and 0-9.– represents the hyphens.([0-9a-fA-F]{4}-){3} represents the 4 characters from a-f, A-F, and 0-9 that is repeated 3 times separated by a hyphen (-).[0-9a-fA-F]{12} represents the 12 characters from a-f, A-F, and 0-9.[}]? represents the ‘}’ character that is optional.$ represents the ending of the string." }, { "code": null, "e": 28817, "s": 28776, "text": "^ represents the starting of the string." }, { "code": null, "e": 28869, "s": 28817, "text": "[{]? represents the ‘{‘ character that is optional." }, { "code": null, "e": 28936, "s": 28869, "text": "[0-9a-fA-F]{8} represents the 8 characters from a-f, A-F, and 0-9." }, { "code": null, "e": 28962, "s": 28936, "text": "– represents the hyphens." }, { "code": null, "e": 29086, "s": 28962, "text": "([0-9a-fA-F]{4}-){3} represents the 4 characters from a-f, A-F, and 0-9 that is repeated 3 times separated by a hyphen (-)." }, { "code": null, "e": 29155, "s": 29086, "text": "[0-9a-fA-F]{12} represents the 12 characters from a-f, A-F, and 0-9." }, { "code": null, "e": 29207, "s": 29155, "text": "[}]? represents the ‘}’ character that is optional." }, { "code": null, "e": 29246, "s": 29207, "text": "$ represents the ending of the string." }, { "code": null, "e": 29352, "s": 29246, "text": "Match the given string with the Regular Expression. In Java, this can be done by using Pattern.matcher()." }, { "code": null, "e": 29440, "s": 29352, "text": "Return true if the string matches with the given regular expression, else return false." }, { "code": null, "e": 29492, "s": 29440, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 29496, "s": 29492, "text": "C++" }, { "code": null, "e": 29501, "s": 29496, "text": "Java" }, { "code": null, "e": 29509, "s": 29501, "text": "Python3" }, { "code": "// C++ program to validate the// GUID (Globally Unique Identifier) using Regular Expression#include <iostream>#include <regex>using namespace std; // Function to validate the GUID (Globally Unique Identifier).bool isValidGUID(string str){ // Regex to check valid GUID (Globally Unique Identifier). const regex pattern(\"^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$\"); // If the GUID (Globally Unique Identifier) // is empty return false if (str.empty()) { return false; } // Return true if the GUID (Globally Unique Identifier) // matched the ReGex if(regex_match(str, pattern)) { return true; } else { return false; }} // Driver Codeint main(){ // Test Case 1: string str1 = \"123e4567-e89b-12d3-a456-9AC7CBDCEE52\"; cout << isValidGUID(str1) << endl; // Test Case 2: string str2 = \"{123e4567-e89b-12d3-a456-9AC7CBDCEE52}\"; cout << isValidGUID(str2) << endl; // Test Case 3: string str3 = \"123e4567-h89b-12d3-a456-9AC7CBDCEE52\"; cout << isValidGUID(str3) << endl; // Test Case 4: string str4 = \"123e4567-h89b-12d3-a456\"; cout << isValidGUID(str4) << endl; return 0;} // This code is contributed by yuvraj_chandra", "e": 30685, "s": 29509, "text": null }, { "code": "// Java program to validate// GUID (Globally Unique Identifier)// using regular expression import java.util.regex.*; class GFG { // Function to validate // GUID (Globally Unique Identifier) // using regular expression public static boolean isValidGUID(String str) { // Regex to check valid // GUID (Globally Unique Identifier) String regex = \"^[{]?[0-9a-fA-F]{8}\" + \"-([0-9a-fA-F]{4}-)\" + \"{3}[0-9a-fA-F]{12}[}]?$\"; // Compile the ReGex Pattern p = Pattern.compile(regex); // If the string is empty // return false if (str == null) { return false; } // Find match between given string // and regular expression // uSing Pattern.matcher() Matcher m = p.matcher(str); // Return if the string // matched the ReGex return m.matches(); } // Driver code public static void main(String args[]) { // Test Case 1: String str2 = \"123e4567-e89b-12d3\" + \"-a456-9AC7CBDCEE52\"; System.out.println( isValidGUID(str2)); // Test Case 2: String str3 = \"{123e4567-e89b-12d3-\" + \"a456-9AC7CBDCEE52}\"; System.out.println( isValidGUID(str3)); // Test Case 3: String str1 = \"123e4567-h89b-12d3-a456\" + \"-9AC7CBDCEE52\"; System.out.println( isValidGUID(str1)); // Test Case 4: String str4 = \"123e4567-h89b-12d3-a456\"; System.out.println( isValidGUID(str4)); }}", "e": 32336, "s": 30685, "text": null }, { "code": "# Python3 program to validate# GUID (Globally Unique Identifier)# using regular expressionimport re # Function to validate GUID# (Globally Unique Identifier)def isValidGUID(str): # Regex to check valid # GUID (Globally Unique Identifier) regex = \"^[{]?[0-9a-fA-F]{8}\" + \"-([0-9a-fA-F]{4}-)\" + \"{3}[0-9a-fA-F]{12}[}]?$\" # Compile the ReGex p = re.compile(regex) # If the string is empty # return false if (str == None): return False # Return if the string # matched the ReGex if(re.search(p, str)): return True else: return False # Driver code # Test Case 1:str1 = \"123e4567-e89b-12d3\" + \"-a456-9AC7CBDCEE52\"print(isValidGUID(str1)) # Test Case 2:str2 = \"{123e4567-e89b-12d3-\" + \"a456-9AC7CBDCEE52}\"print(isValidGUID(str2)) # Test Case 3:str3 = \"123e4567-h89b-12d3-a456\" + \"-9AC7CBDCEE52\"print(isValidGUID(str3)) # Test Case 4:str4 = \"123e4567-h89b-12d3-a456\"print(isValidGUID(str4)) # This code is contributed by avanitrachhadiya2155", "e": 33339, "s": 32336, "text": null }, { "code": null, "e": 33361, "s": 33339, "text": "true\ntrue\nfalse\nfalse" }, { "code": null, "e": 33384, "s": 33363, "text": "avanitrachhadiya2155" }, { "code": null, "e": 33399, "s": 33384, "text": "yuvraj_chandra" }, { "code": null, "e": 33409, "s": 33399, "text": "CPP-regex" }, { "code": null, "e": 33433, "s": 33409, "text": "java-regular-expression" }, { "code": null, "e": 33452, "s": 33433, "text": "regular-expression" }, { "code": null, "e": 33470, "s": 33452, "text": "Pattern Searching" }, { "code": null, "e": 33478, "s": 33470, "text": "Strings" }, { "code": null, "e": 33486, "s": 33478, "text": "Strings" }, { "code": null, "e": 33504, "s": 33486, "text": "Pattern Searching" }, { "code": null, "e": 33602, "s": 33504, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33658, "s": 33602, "text": "Removing string that is an anagram of an earlier string" }, { "code": null, "e": 33732, "s": 33658, "text": "Count N-length strings consisting only of vowels sorted lexicographically" }, { "code": null, "e": 33778, "s": 33732, "text": "Boyer Moore Algorithm | Good Suffix heuristic" }, { "code": null, "e": 33842, "s": 33778, "text": "Check whether two strings contain same characters in same order" }, { "code": null, "e": 33911, "s": 33842, "text": "How to check Aadhaar number is valid or not using Regular Expression" }, { "code": null, "e": 33957, "s": 33911, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 33982, "s": 33957, "text": "Reverse a string in Java" }, { "code": null, "e": 34042, "s": 33982, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 34057, "s": 34042, "text": "C++ Data Types" } ]
Angular 2 - Forms
Angular 2 can also design forms which can use two-way binding using the ngModel directive. Let’s see how we can achieve this. Step 1 − Create a model which is a products model. Create a file called products.ts file. Step 2 − Place the following code in the file. export class Product { constructor ( public productid: number, public productname: string ) { } } This is a simple class which has 2 properties, productid and productname. Step 3 − Create a product form component called product-form.component.ts component and add the following code − import { Component } from '@angular/core'; import { Product } from './products'; @Component ({ selector: 'product-form', templateUrl: './product-form.component.html' }) export class ProductFormComponent { model = new Product(1,'ProductA'); } The following points need to be noted about the above program. Create an object of the Product class and add values to the productid and productname. Create an object of the Product class and add values to the productid and productname. Use the templateUrl to specify the location of our product-form.component.html which will render the component. Use the templateUrl to specify the location of our product-form.component.html which will render the component. Step 4 − Create the actual form. Create a file called product-form.component.html and place the following code. <div class = "container"> <h1>Product Form</h1> <form> <div class = "form-group"> <label for = "productid">ID</label> <input type = "text" class = "form-control" id = "productid" required [(ngModel)] = "model.productid" name = "id"> </div> <div class = "form-group"> <label for = "name">Name</label> <input type = "text" class = "form-control" id = "name" [(ngModel)] = "model.productname" name = "name"> </div> </form> </div> The following point needs to be noted about the above program. The ngModel directive is used to bind the object of the product to the separate elements on the form. The ngModel directive is used to bind the object of the product to the separate elements on the form. Step 5 − Place the following code in the app.component.ts file. import { Component } from '@angular/core'; @Component ({ selector: 'my-app', template: '<product-form></product-form>' }) export class AppComponent { } Step 6 − Place the below code in the app.module.ts file import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { FormsModule } from '@angular/forms'; import { ProductFormComponent } from './product-form.component'; @NgModule ({ imports: [ BrowserModule,FormsModule], declarations: [ AppComponent,ProductFormComponent], bootstrap: [ AppComponent ] }) export class AppModule { } Step 7 − Save all the code and run the application using npm. Go to your browser, you will see the following output. 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2423, "s": 2297, "text": "Angular 2 can also design forms which can use two-way binding using the ngModel directive. Let’s see how we can achieve this." }, { "code": null, "e": 2513, "s": 2423, "text": "Step 1 − Create a model which is a products model. Create a file called products.ts file." }, { "code": null, "e": 2560, "s": 2513, "text": "Step 2 − Place the following code in the file." }, { "code": null, "e": 2682, "s": 2560, "text": "export class Product { \n constructor ( \n public productid: number, \n public productname: string \n ) { } \n}" }, { "code": null, "e": 2756, "s": 2682, "text": "This is a simple class which has 2 properties, productid and productname." }, { "code": null, "e": 2869, "s": 2756, "text": "Step 3 − Create a product form component called product-form.component.ts component and add the following code −" }, { "code": null, "e": 3122, "s": 2869, "text": "import { Component } from '@angular/core';\nimport { Product } from './products';\n\n@Component ({\n selector: 'product-form',\n templateUrl: './product-form.component.html'\n})\n\nexport class ProductFormComponent {\n model = new Product(1,'ProductA');\n}" }, { "code": null, "e": 3185, "s": 3122, "text": "The following points need to be noted about the above program." }, { "code": null, "e": 3272, "s": 3185, "text": "Create an object of the Product class and add values to the productid and productname." }, { "code": null, "e": 3359, "s": 3272, "text": "Create an object of the Product class and add values to the productid and productname." }, { "code": null, "e": 3471, "s": 3359, "text": "Use the templateUrl to specify the location of our product-form.component.html which will render the component." }, { "code": null, "e": 3583, "s": 3471, "text": "Use the templateUrl to specify the location of our product-form.component.html which will render the component." }, { "code": null, "e": 3695, "s": 3583, "text": "Step 4 − Create the actual form. Create a file called product-form.component.html and place the following code." }, { "code": null, "e": 4222, "s": 3695, "text": "<div class = \"container\">\n <h1>Product Form</h1>\n <form>\n <div class = \"form-group\">\n <label for = \"productid\">ID</label>\n <input type = \"text\" class = \"form-control\" id = \"productid\" required\n [(ngModel)] = \"model.productid\" name = \"id\">\n </div>\n \n <div class = \"form-group\">\n <label for = \"name\">Name</label>\n <input type = \"text\" class = \"form-control\" id = \"name\"\n [(ngModel)] = \"model.productname\" name = \"name\">\n </div>\n </form>\n</div>" }, { "code": null, "e": 4285, "s": 4222, "text": "The following point needs to be noted about the above program." }, { "code": null, "e": 4387, "s": 4285, "text": "The ngModel directive is used to bind the object of the product to the separate elements on the form." }, { "code": null, "e": 4489, "s": 4387, "text": "The ngModel directive is used to bind the object of the product to the separate elements on the form." }, { "code": null, "e": 4553, "s": 4489, "text": "Step 5 − Place the following code in the app.component.ts file." }, { "code": null, "e": 4712, "s": 4553, "text": "import { Component } from '@angular/core';\n\n@Component ({\n selector: 'my-app',\n template: '<product-form></product-form>'\n})\nexport class AppComponent { }" }, { "code": null, "e": 4768, "s": 4712, "text": "Step 6 − Place the below code in the app.module.ts file" }, { "code": null, "e": 5200, "s": 4768, "text": "import { NgModule } from '@angular/core';\nimport { BrowserModule } from '@angular/platform-browser';\nimport { AppComponent } from './app.component';\nimport { FormsModule } from '@angular/forms';\nimport { ProductFormComponent } from './product-form.component';\n\n@NgModule ({\n imports: [ BrowserModule,FormsModule],\n declarations: [ AppComponent,ProductFormComponent],\n bootstrap: [ AppComponent ]\n})\nexport class AppModule { }" }, { "code": null, "e": 5317, "s": 5200, "text": "Step 7 − Save all the code and run the application using npm. Go to your browser, you will see the following output." }, { "code": null, "e": 5352, "s": 5317, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5366, "s": 5352, "text": " Anadi Sharma" }, { "code": null, "e": 5401, "s": 5366, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5415, "s": 5401, "text": " Anadi Sharma" }, { "code": null, "e": 5450, "s": 5415, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 5470, "s": 5450, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 5505, "s": 5470, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5522, "s": 5505, "text": " Frahaan Hussain" }, { "code": null, "e": 5555, "s": 5522, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 5567, "s": 5555, "text": " Senol Atac" }, { "code": null, "e": 5602, "s": 5567, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5614, "s": 5602, "text": " Senol Atac" }, { "code": null, "e": 5621, "s": 5614, "text": " Print" }, { "code": null, "e": 5632, "s": 5621, "text": " Add Notes" } ]
Angular10 getLocaleCurrencyName() Function - GeeksforGeeks
28 Apr, 2021 In this article, we are going to see what is getLocaleCurrencyName in Angular 10 and how to use it. The getLocaleCurrencyName is used to get the currency name for the given locale. Syntax: getLocaleCurrencyName(locale: string): string | null NgModule: Module used by getLocaleCurrencyName is: CommonModule Approach: Create the angular app to be used In app.module.ts import LOCALE_ID because we need locale to be imported for using get getLocaleCurrencyName . import { LOCALE_ID, NgModule } from '@angular/core'; In app.component.ts import getLocaleCurrencyName and LOCALE_ID inject LOCALE_ID as a public variable and write the code for getting first day of week using locale variable. In app.component.html show the local variable using string interpolation serve the angular app using ng serve to see the output. Parameters: locale: A string containing locale code with rules. Return value: string : String containing the currency name. Example 1: app.module.ts import { LOCALE_ID, NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [ { provide: LOCALE_ID, useValue: 'en-GB' }, ], bootstrap: [AppComponent]})export class AppModule { } app.component.ts import {FormStyle, getLocaleCurrencyName, TranslationWidth } from '@angular/common'; import {Component, Inject,OnInit, LOCALE_ID } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html'})export class AppComponent { curr = getLocaleCurrencyName(this.locale); constructor( @Inject(LOCALE_ID) public locale: string,){} } app.component.html <h1> GeeksforGeeks</h1><p>Locale Currency Name is : {{curr}}</p> Output: Example 2: app.module.ts import { LOCALE_ID, NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [ { provide: LOCALE_ID, useValue: 'en-GB' }, ], bootstrap: [AppComponent]})export class AppModule { } app.component.ts import {FormStyle, getLocaleCurrencyName, TranslationWidth } from '@angular/common'; import { Component, Inject,OnInit, LOCALE_ID } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html'})export class AppComponent { curr = getLocaleCurrencyName(this.locale); constructor( @Inject(LOCALE_ID) public locale: string,){} } app.component.html <h1> GeeksforGeeks</h1><p>Currency Name is : {{curr}}, example: ( {{100 | currency}})</p> Output: Reference: https://angular.io/api/common/getLocaleCurrencyName Angular10 AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular PrimeNG Messages Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26354, "s": 26326, "text": "\n28 Apr, 2021" }, { "code": null, "e": 26454, "s": 26354, "text": "In this article, we are going to see what is getLocaleCurrencyName in Angular 10 and how to use it." }, { "code": null, "e": 26535, "s": 26454, "text": "The getLocaleCurrencyName is used to get the currency name for the given locale." }, { "code": null, "e": 26543, "s": 26535, "text": "Syntax:" }, { "code": null, "e": 26597, "s": 26543, "text": "getLocaleCurrencyName(locale: string): string | null\n" }, { "code": null, "e": 26648, "s": 26597, "text": "NgModule: Module used by getLocaleCurrencyName is:" }, { "code": null, "e": 26661, "s": 26648, "text": "CommonModule" }, { "code": null, "e": 26671, "s": 26661, "text": "Approach:" }, { "code": null, "e": 26705, "s": 26671, "text": "Create the angular app to be used" }, { "code": null, "e": 26815, "s": 26705, "text": "In app.module.ts import LOCALE_ID because we need locale to be imported for using get getLocaleCurrencyName ." }, { "code": null, "e": 26868, "s": 26815, "text": "import { LOCALE_ID, NgModule } from '@angular/core';" }, { "code": null, "e": 26931, "s": 26868, "text": "In app.component.ts import getLocaleCurrencyName and LOCALE_ID" }, { "code": null, "e": 27041, "s": 26931, "text": "inject LOCALE_ID as a public variable and write the code for getting first day of week using locale variable." }, { "code": null, "e": 27114, "s": 27041, "text": "In app.component.html show the local variable using string interpolation" }, { "code": null, "e": 27170, "s": 27114, "text": "serve the angular app using ng serve to see the output." }, { "code": null, "e": 27182, "s": 27170, "text": "Parameters:" }, { "code": null, "e": 27234, "s": 27182, "text": "locale: A string containing locale code with rules." }, { "code": null, "e": 27248, "s": 27234, "text": "Return value:" }, { "code": null, "e": 27294, "s": 27248, "text": "string : String containing the currency name." }, { "code": null, "e": 27305, "s": 27294, "text": "Example 1:" }, { "code": null, "e": 27319, "s": 27305, "text": "app.module.ts" }, { "code": "import { LOCALE_ID, NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [ { provide: LOCALE_ID, useValue: 'en-GB' }, ], bootstrap: [AppComponent]})export class AppModule { }", "e": 27792, "s": 27319, "text": null }, { "code": null, "e": 27809, "s": 27792, "text": "app.component.ts" }, { "code": "import {FormStyle, getLocaleCurrencyName, TranslationWidth } from '@angular/common'; import {Component, Inject,OnInit, LOCALE_ID } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html'})export class AppComponent { curr = getLocaleCurrencyName(this.locale); constructor( @Inject(LOCALE_ID) public locale: string,){} }", "e": 28238, "s": 27809, "text": null }, { "code": null, "e": 28257, "s": 28238, "text": "app.component.html" }, { "code": "<h1> GeeksforGeeks</h1><p>Locale Currency Name is : {{curr}}</p>", "e": 28327, "s": 28257, "text": null }, { "code": null, "e": 28335, "s": 28327, "text": "Output:" }, { "code": null, "e": 28346, "s": 28335, "text": "Example 2:" }, { "code": null, "e": 28360, "s": 28346, "text": "app.module.ts" }, { "code": "import { LOCALE_ID, NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [ { provide: LOCALE_ID, useValue: 'en-GB' }, ], bootstrap: [AppComponent]})export class AppModule { }", "e": 28832, "s": 28360, "text": null }, { "code": null, "e": 28849, "s": 28832, "text": "app.component.ts" }, { "code": "import {FormStyle, getLocaleCurrencyName, TranslationWidth } from '@angular/common'; import { Component, Inject,OnInit, LOCALE_ID } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html'})export class AppComponent { curr = getLocaleCurrencyName(this.locale); constructor( @Inject(LOCALE_ID) public locale: string,){} }", "e": 29279, "s": 28849, "text": null }, { "code": null, "e": 29298, "s": 29279, "text": "app.component.html" }, { "code": "<h1> GeeksforGeeks</h1><p>Currency Name is : {{curr}}, example: ( {{100 | currency}})</p>", "e": 29393, "s": 29298, "text": null }, { "code": null, "e": 29401, "s": 29393, "text": "Output:" }, { "code": null, "e": 29465, "s": 29401, "text": "Reference: https://angular.io/api/common/getLocaleCurrencyName " }, { "code": null, "e": 29475, "s": 29465, "text": "Angular10" }, { "code": null, "e": 29485, "s": 29475, "text": "AngularJS" }, { "code": null, "e": 29502, "s": 29485, "text": "Web Technologies" }, { "code": null, "e": 29600, "s": 29502, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29635, "s": 29600, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 29670, "s": 29635, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 29705, "s": 29670, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 29729, "s": 29705, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 29782, "s": 29729, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 29822, "s": 29782, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29855, "s": 29822, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29900, "s": 29855, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29943, "s": 29900, "text": "How to fetch data from an API in ReactJS ?" } ]
Find the minimum number of moves needed to move from one cell of matrix to another - GeeksforGeeks
30 Mar, 2021 Given a N X N matrix (M) filled with 1 , 0 , 2 , 3 . Find the minimum numbers of moves needed to move from source to destination (sink) . while traversing through blank cells only. You can traverse up, down, right and left. A value of cell 1 means Source. A value of cell 2 means Destination. A value of cell 3 means Blank cell. A value of cell 0 means Blank Wall. Note : there is only single source and single destination.they may be more than one path from source to destination(sink).each move in matrix we consider as ‘1’ Examples: Input : M[3][3] = {{ 0 , 3 , 2 }, { 3 , 3 , 0 }, { 1 , 3 , 0 }}; Output : 4 Input : M[4][4] = {{ 3 , 3 , 1 , 0 }, { 3 , 0 , 3 , 3 }, { 2 , 3 , 0 , 3 }, { 0 , 3 , 3 , 3 }}; Output : 4 Asked in: Adobe Interview . The idea is to use a Level graph ( Breadth First Traversal ). Consider each cell as a node and each boundary between any two adjacent cells be an edge. so the total number of Node is N*N. 1. Create an empty Graph having N*N node ( Vertex ).2. Push all nodes into a graph.3. Note down the source and sink vertices.4. Now Apply level graph concept ( that we achieve using BFS). In which we find the level of every node from the source vertex. After that, we return ‘Level[d]’ ( d is the destination ). (which is the minimum move from source to sink ) 1. Create an empty Graph having N*N node ( Vertex ). 2. Push all nodes into a graph. 3. Note down the source and sink vertices. 4. Now Apply level graph concept ( that we achieve using BFS). In which we find the level of every node from the source vertex. After that, we return ‘Level[d]’ ( d is the destination ). (which is the minimum move from source to sink ) Below is the implementation of the above idea. C++ Python3 // C++ program to find the minimum numbers// of moves needed to move from source to// destination .#include<bits/stdc++.h>using namespace std;#define N 4 class Graph{ int V ; list < int > *adj;public : Graph( int V ) { this->V = V ; adj = new list<int>[V]; } void addEdge( int s , int d ) ; int BFS ( int s , int d) ;}; // add edge to graphvoid Graph :: addEdge ( int s , int d ){ adj[s].push_back(d); adj[d].push_back(s);} // Level BFS function to find minimum path// from source to sinkint Graph :: BFS(int s, int d){ // Base case if (s == d) return 0; // make initial distance of all vertex -1 // from source int *level = new int[V]; for (int i = 0; i < V; i++) level[i] = -1 ; // Create a queue for BFS list<int> queue; // Mark the source node level[s] = '0' level[s] = 0 ; queue.push_back(s); // it will be used to get all adjacent // vertices of a vertex list<int>::iterator i; while (!queue.empty()) { // Dequeue a vertex from queue s = queue.front(); queue.pop_front(); // Get all adjacent vertices of the // dequeued vertex s. If a adjacent has // not been visited ( level[i] < '0') , // then update level[i] == parent_level[s] + 1 // and enqueue it for (i = adj[s].begin(); i != adj[s].end(); ++i) { // Else, continue to do BFS if (level[*i] < 0 || level[*i] > level[s] + 1 ) { level[*i] = level[s] + 1 ; queue.push_back(*i); } } } // return minimum moves from source to sink return level[d] ;} bool isSafe(int i, int j, int M[][N]){ if ((i < 0 || i >= N) || (j < 0 || j >= N ) || M[i][j] == 0) return false; return true;} // Returns minimum numbers of moves from a source (a// cell with value 1) to a destination (a cell with// value 2)int MinimumPath(int M[][N]){ int s , d ; // source and destination int V = N*N+2; Graph g(V); // create graph with n*n node // each cell consider as node int k = 1 ; // Number of current vertex for (int i =0 ; i < N ; i++) { for (int j = 0 ; j < N; j++) { if (M[i][j] != 0) { // connect all 4 adjacent cell to // current cell if ( isSafe ( i , j+1 , M ) ) g.addEdge ( k , k+1 ); if ( isSafe ( i , j-1 , M ) ) g.addEdge ( k , k-1 ); if (j< N-1 && isSafe ( i+1 , j , M ) ) g.addEdge ( k , k+N ); if ( i > 0 && isSafe ( i-1 , j , M ) ) g.addEdge ( k , k-N ); } // source index if( M[i][j] == 1 ) s = k ; // destination index if (M[i][j] == 2) d = k; k++; } } // find minimum moves return g.BFS (s, d) ;} // driver program to check above functionint main(){ int M[N][N] = {{ 3 , 3 , 1 , 0 }, { 3 , 0 , 3 , 3 }, { 2 , 3 , 0 , 3 }, { 0 , 3 , 3 , 3 } }; cout << MinimumPath(M) << endl; return 0;} # Python3 program to find the minimum numbers# of moves needed to move from source to# destination . class Graph: def __init__(self, V): self.V = V self.adj = [[] for i in range(V)] # add edge to graph def addEdge (self, s , d ): self.adj[s].append(d) self.adj[d].append(s) # Level BFS function to find minimum # path from source to sink def BFS(self, s, d): # Base case if (s == d): return 0 # make initial distance of all # vertex -1 from source level = [-1] * self.V # Create a queue for BFS queue = [] # Mark the source node level[s] = '0' level[s] = 0 queue.append(s) # it will be used to get all adjacent # vertices of a vertex while (len(queue) != 0): # Dequeue a vertex from queue s = queue.pop() # Get all adjacent vertices of the # dequeued vertex s. If a adjacent has # not been visited ( level[i] < '0') , # then update level[i] == parent_level[s] + 1 # and enqueue it i = 0 while i < len(self.adj[s]): # Else, continue to do BFS if (level[self.adj[s][i]] < 0 or level[self.adj[s][i]] > level[s] + 1 ): level[self.adj[s][i]] = level[s] + 1 queue.append(self.adj[s][i]) i += 1 # return minimum moves from source # to sink return level[d] def isSafe(i, j, M): global N if ((i < 0 or i >= N) or (j < 0 or j >= N ) or M[i][j] == 0): return False return True # Returns minimum numbers of moves from a# source (a cell with value 1) to a destination# (a cell with value 2)def MinimumPath(M): global N s , d = None, None # source and destination V = N * N + 2 g = Graph(V) # create graph with n*n node # each cell consider as node k = 1 # Number of current vertex for i in range(N): for j in range(N): if (M[i][j] != 0): # connect all 4 adjacent cell to # current cell if (isSafe (i , j + 1 , M)): g.addEdge (k , k + 1) if (isSafe (i , j - 1 , M)): g.addEdge (k , k - 1) if (j < N - 1 and isSafe (i + 1 , j , M)): g.addEdge (k , k + N) if (i > 0 and isSafe (i - 1 , j , M)): g.addEdge (k , k - N) # source index if(M[i][j] == 1): s = k # destination index if (M[i][j] == 2): d = k k += 1 # find minimum moves return g.BFS (s, d) # Driver CodeN = 4M = [[3 , 3 , 1 , 0 ], [3 , 0 , 3 , 3 ], [2 , 3 , 0 , 3 ], [0 , 3 , 3 , 3]] print(MinimumPath(M)) # This code is contributed by PranchalK Output: 4 Another Approach: (DFS Implementation of the problem) The same can be implemented using DFS where the complete path from the source is compared to get the minimum moves to the destination. Approach: Loop through every element in the input matrix and create a Graph from that matrixCreate a graph with N*N vertices.Add the edge from the k vertex to k+1/ k-1 (if the edge is to the left or right element in the matrix) or k to k+N/ k-N(if the edge is to the top or bottom element in the matrix).Always check whether the element exists in the matrix and element != 0.if(element == 1) map the source if (element == 2) map the destination.Perform DFS to the graph formed, from source to destination.Base condition: if source==destination returns 0 as the number of minimum moves.Minimum moves will be the minimum(the result of DFS performed on the unvisited adjacent vertices). Loop through every element in the input matrix and create a Graph from that matrixCreate a graph with N*N vertices.Add the edge from the k vertex to k+1/ k-1 (if the edge is to the left or right element in the matrix) or k to k+N/ k-N(if the edge is to the top or bottom element in the matrix).Always check whether the element exists in the matrix and element != 0.if(element == 1) map the source if (element == 2) map the destination. Create a graph with N*N vertices.Add the edge from the k vertex to k+1/ k-1 (if the edge is to the left or right element in the matrix) or k to k+N/ k-N(if the edge is to the top or bottom element in the matrix).Always check whether the element exists in the matrix and element != 0.if(element == 1) map the source if (element == 2) map the destination. Create a graph with N*N vertices. Add the edge from the k vertex to k+1/ k-1 (if the edge is to the left or right element in the matrix) or k to k+N/ k-N(if the edge is to the top or bottom element in the matrix). Always check whether the element exists in the matrix and element != 0. if(element == 1) map the source if (element == 2) map the destination. Perform DFS to the graph formed, from source to destination.Base condition: if source==destination returns 0 as the number of minimum moves.Minimum moves will be the minimum(the result of DFS performed on the unvisited adjacent vertices). Base condition: if source==destination returns 0 as the number of minimum moves.Minimum moves will be the minimum(the result of DFS performed on the unvisited adjacent vertices). Base condition: if source==destination returns 0 as the number of minimum moves. Minimum moves will be the minimum(the result of DFS performed on the unvisited adjacent vertices). Below is the implementation of the above approach: C++ Python3 // C++ program for the above approach#include <bits/stdc++.h>#define N 4 // To be used in DFS while comparing the// minimum element#define MAX (INT_MAX - 1)using namespace std; // Graph with the adjacency// list representationoclass Graph {private: int V; vector<int>* adj; public: Graph(int V) : V{ V } { // Initializing the // adjacency list adj = new vector<int>[V]; } // Clearing the memory after // its use (best practice) ~Graph() { delete[] adj; } // Adding the element to the // adjacency list matrix // representation void add_edges(int u, int v) { adj[u].push_back(v); } // performing the DFS for the minimum moves int DFS(int s, int d, unordered_set<int>& visited) { // Base condition for the recursion if (s == d) return 0; // Initializing the result int res{ MAX }; visited.insert(s); for (int item : adj[s]) if (visited.find(item) == visited.end()) // comparing the res with // the result of DFS // to get the minimum moves res = min(res, 1 + DFS(item, d, visited)); return res; }}; // ruling out the cases where the element// to be inserted is outside the matrixbool is_safe(int arr[][4], int i, int j){ if ((i < 0 || i >= N) || (j < 0 || j >= N) || arr[i][j] == 0) return false; return true;} int min_moves(int arr[][N]){ int s{ -1 }, d{ -1 }, V{ N * N }; /* k be the variable which represents the positions( 0 - N*N ) inside the graph. */ // k moves from top-left to bottom-right int k{ 0 }; Graph g{ V }; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // Adding the edge if (arr[i][j] != 0) { if (is_safe(arr, i, j + 1)) g.add_edges(k, k + 1); // left if (is_safe(arr, i, j - 1)) g.add_edges(k, k - 1); // right if (is_safe(arr, i + 1, j)) g.add_edges(k, k + N); // bottom if (is_safe(arr, i - 1, j)) g.add_edges(k, k - N); // top } // Source from which DFS to be // performed if (arr[i][j] == 1) s = k; // Destination else if (arr[i][j] == 2) d = k; // Moving k from top-left // to bottom-right k++; } } unordered_set<int> visited; // DFS performed from // source to destination return g.DFS(s, d, visited);} int32_t main(){ int arr[][N] = { { 3, 3, 1, 0 }, { 3, 0, 3, 3 }, { 2, 3, 0, 3 }, { 0, 3, 3, 3 } }; // if(min_moves(arr) == MAX) there // doesn't exist a path // from source to destination cout << min_moves(arr) << endl; return 0; // the DFS approach and code // is contributed by Lisho // Thomas} # Python3 program for the above approach # To be used in DFS while comparing the# minimum element# define MAX (I4T_MAX - 1)visited = {}adj = [[] for i in range(16)] # Performing the DFS for the minimum movesdef add_edges(u, v): global adj adj[u].append(v) def DFS(s, d): global visited # Base condition for the recursion if (s == d): return 0 # Initializing the result res = 10**9 visited[s] = 1 for item in adj[s]: if (item not in visited): # Comparing the res with # the result of DFS # to get the minimum moves res = min(res, 1 + DFS(item, d)) return res # Ruling out the cases where the element# to be inserted is outside the matrixdef is_safe(arr, i, j): if ((i < 0 or i >= 4) or (j < 0 or j >= 4) or arr[i][j] == 0): return False return True def min_moves(arr): s, d, V = -1,-1, 16 # k be the variable which represents the # positions( 0 - 4*4 ) inside the graph. # k moves from top-left to bottom-right k = 0 for i in range(4): for j in range(4): # Adding the edge if (arr[i][j] != 0): if (is_safe(arr, i, j + 1)): add_edges(k, k + 1) # left if (is_safe(arr, i, j - 1)): add_edges(k, k - 1) # right if (is_safe(arr, i + 1, j)): add_edges(k, k + 4) # bottom if (is_safe(arr, i - 1, j)): add_edges(k, k - 4) # top # Source from which DFS to be # performed if (arr[i][j] == 1): s = k # Destination elif (arr[i][j] == 2): d = k # Moving k from top-left # to bottom-right k += 1 # DFS performed from # source to destination return DFS(s, d) # Driver codeif __name__ == '__main__': arr = [ [ 3, 3, 1, 0 ], [ 3, 0, 3, 3 ], [ 2, 3, 0, 3 ], [ 0, 3, 3, 3 ] ] # If(min_moves(arr) == MAX) there # doesn't exist a path # from source to destination print(min_moves(arr)) # This code is contributed by mohit kumar 29 4 This article is contributed by Nishant 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. PranchalKatiyar thomaslisho mohit kumar 29 BFS Shortest Path Graph Graph Shortest Path BFS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Topological Sorting Bellman–Ford Algorithm | DP-23 Detect Cycle in a Directed Graph Floyd Warshall Algorithm | DP-16 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Traveling Salesman Problem (TSP) Implementation Ford-Fulkerson Algorithm for Maximum Flow Problem Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) Strongly Connected Components
[ { "code": null, "e": 25066, "s": 25038, "text": "\n30 Mar, 2021" }, { "code": null, "e": 25432, "s": 25066, "text": "Given a N X N matrix (M) filled with 1 , 0 , 2 , 3 . Find the minimum numbers of moves needed to move from source to destination (sink) . while traversing through blank cells only. You can traverse up, down, right and left. A value of cell 1 means Source. A value of cell 2 means Destination. A value of cell 3 means Blank cell. A value of cell 0 means Blank Wall. " }, { "code": null, "e": 25594, "s": 25432, "text": "Note : there is only single source and single destination.they may be more than one path from source to destination(sink).each move in matrix we consider as ‘1’ " }, { "code": null, "e": 25605, "s": 25594, "text": "Examples: " }, { "code": null, "e": 25885, "s": 25605, "text": "Input : M[3][3] = {{ 0 , 3 , 2 },\n { 3 , 3 , 0 },\n { 1 , 3 , 0 }};\nOutput : 4 \n\nInput : M[4][4] = {{ 3 , 3 , 1 , 0 },\n { 3 , 0 , 3 , 3 },\n { 2 , 3 , 0 , 3 },\n { 0 , 3 , 3 , 3 }};\nOutput : 4" }, { "code": null, "e": 25913, "s": 25885, "text": "Asked in: Adobe Interview ." }, { "code": null, "e": 26103, "s": 25913, "text": "The idea is to use a Level graph ( Breadth First Traversal ). Consider each cell as a node and each boundary between any two adjacent cells be an edge. so the total number of Node is N*N. " }, { "code": null, "e": 26465, "s": 26103, "text": "1. Create an empty Graph having N*N node ( Vertex ).2. Push all nodes into a graph.3. Note down the source and sink vertices.4. Now Apply level graph concept ( that we achieve using BFS). In which we find the level of every node from the source vertex. After that, we return ‘Level[d]’ ( d is the destination ). (which is the minimum move from source to sink )" }, { "code": null, "e": 26518, "s": 26465, "text": "1. Create an empty Graph having N*N node ( Vertex )." }, { "code": null, "e": 26550, "s": 26518, "text": "2. Push all nodes into a graph." }, { "code": null, "e": 26593, "s": 26550, "text": "3. Note down the source and sink vertices." }, { "code": null, "e": 26830, "s": 26593, "text": "4. Now Apply level graph concept ( that we achieve using BFS). In which we find the level of every node from the source vertex. After that, we return ‘Level[d]’ ( d is the destination ). (which is the minimum move from source to sink )" }, { "code": null, "e": 26879, "s": 26830, "text": "Below is the implementation of the above idea. " }, { "code": null, "e": 26883, "s": 26879, "text": "C++" }, { "code": null, "e": 26891, "s": 26883, "text": "Python3" }, { "code": "// C++ program to find the minimum numbers// of moves needed to move from source to// destination .#include<bits/stdc++.h>using namespace std;#define N 4 class Graph{ int V ; list < int > *adj;public : Graph( int V ) { this->V = V ; adj = new list<int>[V]; } void addEdge( int s , int d ) ; int BFS ( int s , int d) ;}; // add edge to graphvoid Graph :: addEdge ( int s , int d ){ adj[s].push_back(d); adj[d].push_back(s);} // Level BFS function to find minimum path// from source to sinkint Graph :: BFS(int s, int d){ // Base case if (s == d) return 0; // make initial distance of all vertex -1 // from source int *level = new int[V]; for (int i = 0; i < V; i++) level[i] = -1 ; // Create a queue for BFS list<int> queue; // Mark the source node level[s] = '0' level[s] = 0 ; queue.push_back(s); // it will be used to get all adjacent // vertices of a vertex list<int>::iterator i; while (!queue.empty()) { // Dequeue a vertex from queue s = queue.front(); queue.pop_front(); // Get all adjacent vertices of the // dequeued vertex s. If a adjacent has // not been visited ( level[i] < '0') , // then update level[i] == parent_level[s] + 1 // and enqueue it for (i = adj[s].begin(); i != adj[s].end(); ++i) { // Else, continue to do BFS if (level[*i] < 0 || level[*i] > level[s] + 1 ) { level[*i] = level[s] + 1 ; queue.push_back(*i); } } } // return minimum moves from source to sink return level[d] ;} bool isSafe(int i, int j, int M[][N]){ if ((i < 0 || i >= N) || (j < 0 || j >= N ) || M[i][j] == 0) return false; return true;} // Returns minimum numbers of moves from a source (a// cell with value 1) to a destination (a cell with// value 2)int MinimumPath(int M[][N]){ int s , d ; // source and destination int V = N*N+2; Graph g(V); // create graph with n*n node // each cell consider as node int k = 1 ; // Number of current vertex for (int i =0 ; i < N ; i++) { for (int j = 0 ; j < N; j++) { if (M[i][j] != 0) { // connect all 4 adjacent cell to // current cell if ( isSafe ( i , j+1 , M ) ) g.addEdge ( k , k+1 ); if ( isSafe ( i , j-1 , M ) ) g.addEdge ( k , k-1 ); if (j< N-1 && isSafe ( i+1 , j , M ) ) g.addEdge ( k , k+N ); if ( i > 0 && isSafe ( i-1 , j , M ) ) g.addEdge ( k , k-N ); } // source index if( M[i][j] == 1 ) s = k ; // destination index if (M[i][j] == 2) d = k; k++; } } // find minimum moves return g.BFS (s, d) ;} // driver program to check above functionint main(){ int M[N][N] = {{ 3 , 3 , 1 , 0 }, { 3 , 0 , 3 , 3 }, { 2 , 3 , 0 , 3 }, { 0 , 3 , 3 , 3 } }; cout << MinimumPath(M) << endl; return 0;}", "e": 30104, "s": 26891, "text": null }, { "code": "# Python3 program to find the minimum numbers# of moves needed to move from source to# destination . class Graph: def __init__(self, V): self.V = V self.adj = [[] for i in range(V)] # add edge to graph def addEdge (self, s , d ): self.adj[s].append(d) self.adj[d].append(s) # Level BFS function to find minimum # path from source to sink def BFS(self, s, d): # Base case if (s == d): return 0 # make initial distance of all # vertex -1 from source level = [-1] * self.V # Create a queue for BFS queue = [] # Mark the source node level[s] = '0' level[s] = 0 queue.append(s) # it will be used to get all adjacent # vertices of a vertex while (len(queue) != 0): # Dequeue a vertex from queue s = queue.pop() # Get all adjacent vertices of the # dequeued vertex s. If a adjacent has # not been visited ( level[i] < '0') , # then update level[i] == parent_level[s] + 1 # and enqueue it i = 0 while i < len(self.adj[s]): # Else, continue to do BFS if (level[self.adj[s][i]] < 0 or level[self.adj[s][i]] > level[s] + 1 ): level[self.adj[s][i]] = level[s] + 1 queue.append(self.adj[s][i]) i += 1 # return minimum moves from source # to sink return level[d] def isSafe(i, j, M): global N if ((i < 0 or i >= N) or (j < 0 or j >= N ) or M[i][j] == 0): return False return True # Returns minimum numbers of moves from a# source (a cell with value 1) to a destination# (a cell with value 2)def MinimumPath(M): global N s , d = None, None # source and destination V = N * N + 2 g = Graph(V) # create graph with n*n node # each cell consider as node k = 1 # Number of current vertex for i in range(N): for j in range(N): if (M[i][j] != 0): # connect all 4 adjacent cell to # current cell if (isSafe (i , j + 1 , M)): g.addEdge (k , k + 1) if (isSafe (i , j - 1 , M)): g.addEdge (k , k - 1) if (j < N - 1 and isSafe (i + 1 , j , M)): g.addEdge (k , k + N) if (i > 0 and isSafe (i - 1 , j , M)): g.addEdge (k , k - N) # source index if(M[i][j] == 1): s = k # destination index if (M[i][j] == 2): d = k k += 1 # find minimum moves return g.BFS (s, d) # Driver CodeN = 4M = [[3 , 3 , 1 , 0 ], [3 , 0 , 3 , 3 ], [2 , 3 , 0 , 3 ], [0 , 3 , 3 , 3]] print(MinimumPath(M)) # This code is contributed by PranchalK", "e": 33090, "s": 30104, "text": null }, { "code": null, "e": 33100, "s": 33090, "text": "Output: " }, { "code": null, "e": 33102, "s": 33100, "text": "4" }, { "code": null, "e": 33156, "s": 33102, "text": "Another Approach: (DFS Implementation of the problem)" }, { "code": null, "e": 33292, "s": 33156, "text": "The same can be implemented using DFS where the complete path from the source is compared to get the minimum moves to the destination. " }, { "code": null, "e": 33302, "s": 33292, "text": "Approach:" }, { "code": null, "e": 33976, "s": 33302, "text": "Loop through every element in the input matrix and create a Graph from that matrixCreate a graph with N*N vertices.Add the edge from the k vertex to k+1/ k-1 (if the edge is to the left or right element in the matrix) or k to k+N/ k-N(if the edge is to the top or bottom element in the matrix).Always check whether the element exists in the matrix and element != 0.if(element == 1) map the source if (element == 2) map the destination.Perform DFS to the graph formed, from source to destination.Base condition: if source==destination returns 0 as the number of minimum moves.Minimum moves will be the minimum(the result of DFS performed on the unvisited adjacent vertices)." }, { "code": null, "e": 34412, "s": 33976, "text": "Loop through every element in the input matrix and create a Graph from that matrixCreate a graph with N*N vertices.Add the edge from the k vertex to k+1/ k-1 (if the edge is to the left or right element in the matrix) or k to k+N/ k-N(if the edge is to the top or bottom element in the matrix).Always check whether the element exists in the matrix and element != 0.if(element == 1) map the source if (element == 2) map the destination." }, { "code": null, "e": 34766, "s": 34412, "text": "Create a graph with N*N vertices.Add the edge from the k vertex to k+1/ k-1 (if the edge is to the left or right element in the matrix) or k to k+N/ k-N(if the edge is to the top or bottom element in the matrix).Always check whether the element exists in the matrix and element != 0.if(element == 1) map the source if (element == 2) map the destination." }, { "code": null, "e": 34800, "s": 34766, "text": "Create a graph with N*N vertices." }, { "code": null, "e": 34980, "s": 34800, "text": "Add the edge from the k vertex to k+1/ k-1 (if the edge is to the left or right element in the matrix) or k to k+N/ k-N(if the edge is to the top or bottom element in the matrix)." }, { "code": null, "e": 35052, "s": 34980, "text": "Always check whether the element exists in the matrix and element != 0." }, { "code": null, "e": 35123, "s": 35052, "text": "if(element == 1) map the source if (element == 2) map the destination." }, { "code": null, "e": 35362, "s": 35123, "text": "Perform DFS to the graph formed, from source to destination.Base condition: if source==destination returns 0 as the number of minimum moves.Minimum moves will be the minimum(the result of DFS performed on the unvisited adjacent vertices)." }, { "code": null, "e": 35541, "s": 35362, "text": "Base condition: if source==destination returns 0 as the number of minimum moves.Minimum moves will be the minimum(the result of DFS performed on the unvisited adjacent vertices)." }, { "code": null, "e": 35622, "s": 35541, "text": "Base condition: if source==destination returns 0 as the number of minimum moves." }, { "code": null, "e": 35721, "s": 35622, "text": "Minimum moves will be the minimum(the result of DFS performed on the unvisited adjacent vertices)." }, { "code": null, "e": 35773, "s": 35721, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 35777, "s": 35773, "text": "C++" }, { "code": null, "e": 35785, "s": 35777, "text": "Python3" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>#define N 4 // To be used in DFS while comparing the// minimum element#define MAX (INT_MAX - 1)using namespace std; // Graph with the adjacency// list representationoclass Graph {private: int V; vector<int>* adj; public: Graph(int V) : V{ V } { // Initializing the // adjacency list adj = new vector<int>[V]; } // Clearing the memory after // its use (best practice) ~Graph() { delete[] adj; } // Adding the element to the // adjacency list matrix // representation void add_edges(int u, int v) { adj[u].push_back(v); } // performing the DFS for the minimum moves int DFS(int s, int d, unordered_set<int>& visited) { // Base condition for the recursion if (s == d) return 0; // Initializing the result int res{ MAX }; visited.insert(s); for (int item : adj[s]) if (visited.find(item) == visited.end()) // comparing the res with // the result of DFS // to get the minimum moves res = min(res, 1 + DFS(item, d, visited)); return res; }}; // ruling out the cases where the element// to be inserted is outside the matrixbool is_safe(int arr[][4], int i, int j){ if ((i < 0 || i >= N) || (j < 0 || j >= N) || arr[i][j] == 0) return false; return true;} int min_moves(int arr[][N]){ int s{ -1 }, d{ -1 }, V{ N * N }; /* k be the variable which represents the positions( 0 - N*N ) inside the graph. */ // k moves from top-left to bottom-right int k{ 0 }; Graph g{ V }; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // Adding the edge if (arr[i][j] != 0) { if (is_safe(arr, i, j + 1)) g.add_edges(k, k + 1); // left if (is_safe(arr, i, j - 1)) g.add_edges(k, k - 1); // right if (is_safe(arr, i + 1, j)) g.add_edges(k, k + N); // bottom if (is_safe(arr, i - 1, j)) g.add_edges(k, k - N); // top } // Source from which DFS to be // performed if (arr[i][j] == 1) s = k; // Destination else if (arr[i][j] == 2) d = k; // Moving k from top-left // to bottom-right k++; } } unordered_set<int> visited; // DFS performed from // source to destination return g.DFS(s, d, visited);} int32_t main(){ int arr[][N] = { { 3, 3, 1, 0 }, { 3, 0, 3, 3 }, { 2, 3, 0, 3 }, { 0, 3, 3, 3 } }; // if(min_moves(arr) == MAX) there // doesn't exist a path // from source to destination cout << min_moves(arr) << endl; return 0; // the DFS approach and code // is contributed by Lisho // Thomas}", "e": 38936, "s": 35785, "text": null }, { "code": "# Python3 program for the above approach # To be used in DFS while comparing the# minimum element# define MAX (I4T_MAX - 1)visited = {}adj = [[] for i in range(16)] # Performing the DFS for the minimum movesdef add_edges(u, v): global adj adj[u].append(v) def DFS(s, d): global visited # Base condition for the recursion if (s == d): return 0 # Initializing the result res = 10**9 visited[s] = 1 for item in adj[s]: if (item not in visited): # Comparing the res with # the result of DFS # to get the minimum moves res = min(res, 1 + DFS(item, d)) return res # Ruling out the cases where the element# to be inserted is outside the matrixdef is_safe(arr, i, j): if ((i < 0 or i >= 4) or (j < 0 or j >= 4) or arr[i][j] == 0): return False return True def min_moves(arr): s, d, V = -1,-1, 16 # k be the variable which represents the # positions( 0 - 4*4 ) inside the graph. # k moves from top-left to bottom-right k = 0 for i in range(4): for j in range(4): # Adding the edge if (arr[i][j] != 0): if (is_safe(arr, i, j + 1)): add_edges(k, k + 1) # left if (is_safe(arr, i, j - 1)): add_edges(k, k - 1) # right if (is_safe(arr, i + 1, j)): add_edges(k, k + 4) # bottom if (is_safe(arr, i - 1, j)): add_edges(k, k - 4) # top # Source from which DFS to be # performed if (arr[i][j] == 1): s = k # Destination elif (arr[i][j] == 2): d = k # Moving k from top-left # to bottom-right k += 1 # DFS performed from # source to destination return DFS(s, d) # Driver codeif __name__ == '__main__': arr = [ [ 3, 3, 1, 0 ], [ 3, 0, 3, 3 ], [ 2, 3, 0, 3 ], [ 0, 3, 3, 3 ] ] # If(min_moves(arr) == MAX) there # doesn't exist a path # from source to destination print(min_moves(arr)) # This code is contributed by mohit kumar 29", "e": 41217, "s": 38936, "text": null }, { "code": null, "e": 41219, "s": 41217, "text": "4" }, { "code": null, "e": 41645, "s": 41219, "text": "This article is contributed by Nishant 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 41661, "s": 41645, "text": "PranchalKatiyar" }, { "code": null, "e": 41673, "s": 41661, "text": "thomaslisho" }, { "code": null, "e": 41688, "s": 41673, "text": "mohit kumar 29" }, { "code": null, "e": 41692, "s": 41688, "text": "BFS" }, { "code": null, "e": 41706, "s": 41692, "text": "Shortest Path" }, { "code": null, "e": 41712, "s": 41706, "text": "Graph" }, { "code": null, "e": 41718, "s": 41712, "text": "Graph" }, { "code": null, "e": 41732, "s": 41718, "text": "Shortest Path" }, { "code": null, "e": 41736, "s": 41732, "text": "BFS" }, { "code": null, "e": 41834, "s": 41736, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41843, "s": 41834, "text": "Comments" }, { "code": null, "e": 41856, "s": 41843, "text": "Old Comments" }, { "code": null, "e": 41914, "s": 41856, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 41934, "s": 41914, "text": "Topological Sorting" }, { "code": null, "e": 41965, "s": 41934, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 41998, "s": 41965, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 42031, "s": 41998, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 42099, "s": 42031, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 42147, "s": 42099, "text": "Traveling Salesman Problem (TSP) Implementation" }, { "code": null, "e": 42197, "s": 42147, "text": "Ford-Fulkerson Algorithm for Maximum Flow Problem" }, { "code": null, "e": 42272, "s": 42197, "text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)" } ]
Scraping Live Traffic Data in 3 Lines of Code, Step-by-Step | by Nathan Thomas | Towards Data Science
In light of the recent pandemic, lockdown measures imposed by policymakers have halted the majority of economic activity. Due to the lagging nature of economic data, it’s not always easy to gauge in the data how consumers are behaving in real-time. In fact, data often has at least a one-month time lag, making it difficult to assess if people are actually moving around or not. Therefore, governments, scientists and economists alike have been looking at high-frequency data, which provides a real-time view of how movement in the global economy has changed since restrictions have been imposed. A popular gauge of how activity has fared has been traffic data, provided by TomTom. This data covers 416 cities across 57 countries and calculates travel times of all vehicles on the entire road network. On TomTom’s website, the average congestion level is shown as a live traffic chart. I’ve chosen to look at Milan: We’re able to hover over the chart to get each individual data point, but there’s no way of downloading the data from the website. So there are two options: Spend hours hovering over each point and recording each value...Scrape it! Spend hours hovering over each point and recording each value... Scrape it! Inspecting the data On any website, it’s common for the site to load in a range of different information when loading the page. This may include cookies, data files, images and more. We are able to see what’s under the hood by inspecting the page. In Chrome, this is made easy by pressing ‘Ctrl+shift+I’. A window will come up which will show all the data that has been loaded into the page. The tab that we want is the Network tab, shown at the top of the pop-up window. If you can’t see all the data, hit ‘Ctrl+R’ to reload the page and watch as all the data loads in. On the Name tab, you’ll see many different file types: .js, .json, .svg, .otf and more. So how do we know which one contains the underlying data for our chart? Firstly, we need to filter by XHR. This is short for XML HTTP request. It’s common for data on a webpage to be loaded using this format. We can then filter by size — underlying data is usually one of the largest files contained in the page (likely to be in kilobytes rather than bytes). Finally, more often than not, source data will come in the form of a .json file. This stands for Javascript Object Notation, and it’s a common way for large amounts of data to be stored. However, looking at our dataset, it’s not immediately obvious where the json file is. As a next step, let’s look at the type column. Since we’ve filtered by xhr, we should only see xhr types in this column. Having said that, when we look down the column, we can see both xhr and fetch. The fetch type implies that this data is being loaded from an API, or Automated Processing Interface. Looking at the data with the fetch type, the filename for this specific object is “ITA_milan”. Looks like we’ve got our data! We can check it’s correct by opening it in a new tab. When we open the new tab, we see that this indeed the data we want, under the link: https://api.midway.tomtom.com/ranking/live/ITA_milan, which is being retrieved from an API. Great — now let’s load this data into python and start cleaning it to replicate the live chart. Retrieving and cleaning the data First of all, requests is the module that we’ll use to load the data. Using requests.get() on the url we found earlier, we can show this file as a json and unpack it using the json module in python (yes, using only three lines of code): %matplotlib inlineimport matplotlib.pyplot as pltimport pandas as pdimport jsonimport requests# retrieve json fileurl_ = "https://api.midway.tomtom.com/ranking/live/ITA_milan"italy_req = requests.get(url)italy_json = italy_req.json() This gives us the following output: {'data': [{'JamsDelay': 13.5,'TrafficIndexLive': 6,'TrafficIndexHistoric': 17,'UpdateTime': 1586608290000,'JamsLength': 1.4,'JamsCount': 4},{'JamsDelay': 4.2,'TrafficIndexLive': 6,'TrafficIndexHistoric': 17,'UpdateTime': 1586609190000,'JamsLength': 0.4,'JamsCount': 2},{'JamsDelay': 5.8,'TrafficIndexLive': 6,'TrafficIndexHistoric': 18,'UpdateTime': 1586610090000,'JamsLength': 0.4,'JamsCount': 2}, This file may look slightly confusing, with a lot of different punctuation and parentheses. It’s simpler than it looks — the json file is actually a dictionary called ‘data’, with a list of dictionaries contained within it. So to get to the information that we want; (“Time” and “TrafficIndexLive”), we have to call the keys for each point we want to retrieve. For example, to get the first value of the live traffic index, we would enter the following: italy_json["data"][0]["TrafficIndexLive"] We can then append each item in this dictionary to a list, converting each list to a column in a pandas DataFrame: Using dictionaries and a little bit of data cleaning, and we’ve got it! Let’s validate that the data matches the live chart by plotting it: And there we have it! In a few lines of code, we were able to retrieve data from a chart that we couldn’t have otherwise accessed. Turns out what they say is true: If you can see it, you can scrape it! Thanks for reading! Please feel free to leave any comments for any insights you may have. The full Jupyter Notebook which contains the source code I used to do this project can be found on my Github repository. References: [1] TomTom, 2020. “Milan traffic report”. Available at: https://www.tomtom.com/en_gb/traffic-index/milan-traffic/ Disclaimer: All views expressed in this article are my own, and are not in any way associated with Vanguard or any other financial entity. I am not a trader and am not making any money from the methods used in this article. This is not financial advice.
[ { "code": null, "e": 963, "s": 47, "text": "In light of the recent pandemic, lockdown measures imposed by policymakers have halted the majority of economic activity. Due to the lagging nature of economic data, it’s not always easy to gauge in the data how consumers are behaving in real-time. In fact, data often has at least a one-month time lag, making it difficult to assess if people are actually moving around or not. Therefore, governments, scientists and economists alike have been looking at high-frequency data, which provides a real-time view of how movement in the global economy has changed since restrictions have been imposed. A popular gauge of how activity has fared has been traffic data, provided by TomTom. This data covers 416 cities across 57 countries and calculates travel times of all vehicles on the entire road network. On TomTom’s website, the average congestion level is shown as a live traffic chart. I’ve chosen to look at Milan:" }, { "code": null, "e": 1120, "s": 963, "text": "We’re able to hover over the chart to get each individual data point, but there’s no way of downloading the data from the website. So there are two options:" }, { "code": null, "e": 1195, "s": 1120, "text": "Spend hours hovering over each point and recording each value...Scrape it!" }, { "code": null, "e": 1260, "s": 1195, "text": "Spend hours hovering over each point and recording each value..." }, { "code": null, "e": 1271, "s": 1260, "text": "Scrape it!" }, { "code": null, "e": 1291, "s": 1271, "text": "Inspecting the data" }, { "code": null, "e": 1743, "s": 1291, "text": "On any website, it’s common for the site to load in a range of different information when loading the page. This may include cookies, data files, images and more. We are able to see what’s under the hood by inspecting the page. In Chrome, this is made easy by pressing ‘Ctrl+shift+I’. A window will come up which will show all the data that has been loaded into the page. The tab that we want is the Network tab, shown at the top of the pop-up window." }, { "code": null, "e": 2476, "s": 1743, "text": "If you can’t see all the data, hit ‘Ctrl+R’ to reload the page and watch as all the data loads in. On the Name tab, you’ll see many different file types: .js, .json, .svg, .otf and more. So how do we know which one contains the underlying data for our chart? Firstly, we need to filter by XHR. This is short for XML HTTP request. It’s common for data on a webpage to be loaded using this format. We can then filter by size — underlying data is usually one of the largest files contained in the page (likely to be in kilobytes rather than bytes). Finally, more often than not, source data will come in the form of a .json file. This stands for Javascript Object Notation, and it’s a common way for large amounts of data to be stored." }, { "code": null, "e": 3316, "s": 2476, "text": "However, looking at our dataset, it’s not immediately obvious where the json file is. As a next step, let’s look at the type column. Since we’ve filtered by xhr, we should only see xhr types in this column. Having said that, when we look down the column, we can see both xhr and fetch. The fetch type implies that this data is being loaded from an API, or Automated Processing Interface. Looking at the data with the fetch type, the filename for this specific object is “ITA_milan”. Looks like we’ve got our data! We can check it’s correct by opening it in a new tab. When we open the new tab, we see that this indeed the data we want, under the link: https://api.midway.tomtom.com/ranking/live/ITA_milan, which is being retrieved from an API. Great — now let’s load this data into python and start cleaning it to replicate the live chart." }, { "code": null, "e": 3349, "s": 3316, "text": "Retrieving and cleaning the data" }, { "code": null, "e": 3586, "s": 3349, "text": "First of all, requests is the module that we’ll use to load the data. Using requests.get() on the url we found earlier, we can show this file as a json and unpack it using the json module in python (yes, using only three lines of code):" }, { "code": null, "e": 3820, "s": 3586, "text": "%matplotlib inlineimport matplotlib.pyplot as pltimport pandas as pdimport jsonimport requests# retrieve json fileurl_ = \"https://api.midway.tomtom.com/ranking/live/ITA_milan\"italy_req = requests.get(url)italy_json = italy_req.json()" }, { "code": null, "e": 3856, "s": 3820, "text": "This gives us the following output:" }, { "code": null, "e": 4255, "s": 3856, "text": "{'data': [{'JamsDelay': 13.5,'TrafficIndexLive': 6,'TrafficIndexHistoric': 17,'UpdateTime': 1586608290000,'JamsLength': 1.4,'JamsCount': 4},{'JamsDelay': 4.2,'TrafficIndexLive': 6,'TrafficIndexHistoric': 17,'UpdateTime': 1586609190000,'JamsLength': 0.4,'JamsCount': 2},{'JamsDelay': 5.8,'TrafficIndexLive': 6,'TrafficIndexHistoric': 18,'UpdateTime': 1586610090000,'JamsLength': 0.4,'JamsCount': 2}," }, { "code": null, "e": 4709, "s": 4255, "text": "This file may look slightly confusing, with a lot of different punctuation and parentheses. It’s simpler than it looks — the json file is actually a dictionary called ‘data’, with a list of dictionaries contained within it. So to get to the information that we want; (“Time” and “TrafficIndexLive”), we have to call the keys for each point we want to retrieve. For example, to get the first value of the live traffic index, we would enter the following:" }, { "code": null, "e": 4751, "s": 4709, "text": "italy_json[\"data\"][0][\"TrafficIndexLive\"]" }, { "code": null, "e": 4866, "s": 4751, "text": "We can then append each item in this dictionary to a list, converting each list to a column in a pandas DataFrame:" }, { "code": null, "e": 5006, "s": 4866, "text": "Using dictionaries and a little bit of data cleaning, and we’ve got it! Let’s validate that the data matches the live chart by plotting it:" }, { "code": null, "e": 5208, "s": 5006, "text": "And there we have it! In a few lines of code, we were able to retrieve data from a chart that we couldn’t have otherwise accessed. Turns out what they say is true: If you can see it, you can scrape it!" }, { "code": null, "e": 5419, "s": 5208, "text": "Thanks for reading! Please feel free to leave any comments for any insights you may have. The full Jupyter Notebook which contains the source code I used to do this project can be found on my Github repository." }, { "code": null, "e": 5431, "s": 5419, "text": "References:" }, { "code": null, "e": 5545, "s": 5431, "text": "[1] TomTom, 2020. “Milan traffic report”. Available at: https://www.tomtom.com/en_gb/traffic-index/milan-traffic/" } ]
Triangular Number | Practice | GeeksforGeeks
Given a number N.Check whether it is a triangular number or not. Note: A number is termed as a triangular number if we can represent it in the form of a triangular grid of points such that the points form an equilateral triangle and each row contains as many points as the row number, i.e., the first row has one point, the second row has two points, the third row has three points and so on. The starting triangular numbers are 1, 3 (1+2), 6 (1+2+3), 10 (1+2+3+4). Example 1: Input: N=55 Output: 1 Explanation: 55 is a triangular number. It can be represented in 10 rows. Example 2: Input: N=56 Output: 0 Explanation: 56 is not a triangular number. Your Task: You don't need to read input or print anything. Your task is to complete the function isTriangular() that takes a number N as input parameter and returns 1 if it is a triangular number. Otherwise, it returns 0. Expected Time complexity:O(LogN) Expected Auxillary Space:O(1) Constraints: 1<=N<=106 +2 hritikpatani2 months ago int isTriangular(int N){ int temp = N*2; int jabe = sqrt(temp); if(((jabe+1)*jabe == temp) || ((jabe-1)*jabe == temp)) return 1; return 0; } Fucking 27 lakhs TCs in 1.6 fking seconds. 0 naveenguttedar8443 months ago int isTriangular(int N){ //code here N=N*8+1; double squr=Math.sqrt(N); if ((int)squr==squr) return 1; return 0; } 0 psanjeev0443 months ago class Solution { int isTriangular(int N){ int m = 2 * N; for(int i = 1; i * i < m; i++){ if((i*i) == (m - i)) return 1; } return 0; }} +1 debujjal47 months ago if(N < 0){return 0;} int sum = 0; for(int i = 1; sum <= N; i++){ sum = sum + i; if(sum == N){return 1;} } return 0; 0 Din Djarin9 months ago Din Djarin int isTriangular(int N){ N = 2*N ; for( int i = 1 ; i*( i + 1 ) <= N ; i++ ) if( i*( i + 1 ) == N ) return 1; return 0 ; } 0 ANKIT SINHA9 months ago ANKIT SINHA https://uploads.disquscdn.c... 0 Rohit Saka10 months ago Rohit Saka class Solution { int isTriangular(int N){ if(N < 0){ return 0; } int sum = 0; for(int i = 1; sum <= N; i++){ sum = sum + i; if(sum == N){ return 1; } } return 0; }} 0 BHOOPEN SAWANT10 months ago BHOOPEN SAWANT CPP code -int isTriangular(int N){ return (int(sqrt(2*N))*(int(sqrt(2*N)+1))==2*N); } 0 Mufeed Amir1 year ago Mufeed Amir Python Solution: class Solution: def isTriangular(self, n): import math as mt i=mt.floor(mt.sqrt(2*n)) if i*(i+1)//2==n: return 1 return 0 0 Gazal1 year ago Gazal JAVA SOL. 0.2SECclass GFG {public static void main (String[] args) {//codeScanner sc=new Scanner(System.in);int t=sc.nextInt();int x,i=1;while(t-->0){ int n=sc.nextInt(); i=1; while(n>0) { n-=i; //ques is about sum of natural numbers i++; } if(n==0) System.out.println(1); else System.out.println(0);}}} 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": 704, "s": 238, "text": "Given a number N.Check whether it is a triangular number or not.\nNote: A number is termed as a triangular number if we can represent it in the form of a triangular grid of points such that the points form an equilateral triangle and each row contains as many points as the row number, i.e., the first row has one point, the second row has two points, the third row has three points and so on.\nThe starting triangular numbers are 1, 3 (1+2), 6 (1+2+3), 10 (1+2+3+4)." }, { "code": null, "e": 715, "s": 704, "text": "Example 1:" }, { "code": null, "e": 811, "s": 715, "text": "Input:\nN=55\nOutput:\n1\nExplanation:\n55 is a triangular number.\nIt can be represented in 10 rows." }, { "code": null, "e": 822, "s": 811, "text": "Example 2:" }, { "code": null, "e": 888, "s": 822, "text": "Input:\nN=56\nOutput:\n0\nExplanation:\n56 is not a triangular number." }, { "code": null, "e": 1111, "s": 888, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function isTriangular() that takes a number N as input parameter and returns 1 if it is a triangular number. Otherwise, it returns 0." }, { "code": null, "e": 1177, "s": 1111, "text": "\nExpected Time complexity:O(LogN)\nExpected Auxillary Space:O(1)\n " }, { "code": null, "e": 1200, "s": 1177, "text": "Constraints:\n1<=N<=106" }, { "code": null, "e": 1203, "s": 1200, "text": "+2" }, { "code": null, "e": 1228, "s": 1203, "text": "hritikpatani2 months ago" }, { "code": null, "e": 1405, "s": 1228, "text": "int isTriangular(int N){ int temp = N*2; int jabe = sqrt(temp); if(((jabe+1)*jabe == temp) || ((jabe-1)*jabe == temp)) return 1; return 0; }" }, { "code": null, "e": 1452, "s": 1409, "text": "Fucking 27 lakhs TCs in 1.6 fking seconds." }, { "code": null, "e": 1454, "s": 1452, "text": "0" }, { "code": null, "e": 1484, "s": 1454, "text": "naveenguttedar8443 months ago" }, { "code": null, "e": 1641, "s": 1484, "text": "int isTriangular(int N){\n //code here\n \n N=N*8+1;\n double squr=Math.sqrt(N);\n if ((int)squr==squr) return 1;\n return 0;\n }" }, { "code": null, "e": 1645, "s": 1643, "text": "0" }, { "code": null, "e": 1669, "s": 1645, "text": "psanjeev0443 months ago" }, { "code": null, "e": 1837, "s": 1669, "text": "class Solution { int isTriangular(int N){ int m = 2 * N; for(int i = 1; i * i < m; i++){ if((i*i) == (m - i)) return 1; } return 0; }}" }, { "code": null, "e": 1840, "s": 1837, "text": "+1" }, { "code": null, "e": 1862, "s": 1840, "text": "debujjal47 months ago" }, { "code": null, "e": 1888, "s": 1862, "text": " if(N < 0){return 0;}" }, { "code": null, "e": 1901, "s": 1888, "text": "int sum = 0;" }, { "code": null, "e": 1932, "s": 1901, "text": "for(int i = 1; sum <= N; i++){" }, { "code": null, "e": 1947, "s": 1932, "text": "sum = sum + i;" }, { "code": null, "e": 1971, "s": 1947, "text": "if(sum == N){return 1;}" }, { "code": null, "e": 1973, "s": 1971, "text": "}" }, { "code": null, "e": 1983, "s": 1973, "text": "return 0;" }, { "code": null, "e": 1987, "s": 1985, "text": "0" }, { "code": null, "e": 2010, "s": 1987, "text": "Din Djarin9 months ago" }, { "code": null, "e": 2021, "s": 2010, "text": "Din Djarin" }, { "code": null, "e": 2063, "s": 2021, "text": "int isTriangular(int N){ N = 2*N ;" }, { "code": null, "e": 2172, "s": 2063, "text": " for( int i = 1 ; i*( i + 1 ) <= N ; i++ ) if( i*( i + 1 ) == N ) return 1;" }, { "code": null, "e": 2196, "s": 2172, "text": " return 0 ; }" }, { "code": null, "e": 2198, "s": 2196, "text": "0" }, { "code": null, "e": 2222, "s": 2198, "text": "ANKIT SINHA9 months ago" }, { "code": null, "e": 2234, "s": 2222, "text": "ANKIT SINHA" }, { "code": null, "e": 2265, "s": 2234, "text": "https://uploads.disquscdn.c..." }, { "code": null, "e": 2267, "s": 2265, "text": "0" }, { "code": null, "e": 2291, "s": 2267, "text": "Rohit Saka10 months ago" }, { "code": null, "e": 2302, "s": 2291, "text": "Rohit Saka" }, { "code": null, "e": 2581, "s": 2302, "text": "class Solution { int isTriangular(int N){ if(N < 0){ return 0; } int sum = 0; for(int i = 1; sum <= N; i++){ sum = sum + i; if(sum == N){ return 1; } } return 0; }}" }, { "code": null, "e": 2583, "s": 2581, "text": "0" }, { "code": null, "e": 2611, "s": 2583, "text": "BHOOPEN SAWANT10 months ago" }, { "code": null, "e": 2626, "s": 2611, "text": "BHOOPEN SAWANT" }, { "code": null, "e": 2723, "s": 2626, "text": "CPP code -int isTriangular(int N){ return (int(sqrt(2*N))*(int(sqrt(2*N)+1))==2*N); }" }, { "code": null, "e": 2725, "s": 2723, "text": "0" }, { "code": null, "e": 2747, "s": 2725, "text": "Mufeed Amir1 year ago" }, { "code": null, "e": 2759, "s": 2747, "text": "Mufeed Amir" }, { "code": null, "e": 2776, "s": 2759, "text": "Python Solution:" }, { "code": null, "e": 2879, "s": 2776, "text": "class Solution: def isTriangular(self, n): import math as mt i=mt.floor(mt.sqrt(2*n))" }, { "code": null, "e": 2925, "s": 2879, "text": " if i*(i+1)//2==n: return 1" }, { "code": null, "e": 2944, "s": 2925, "text": " return 0" }, { "code": null, "e": 2946, "s": 2944, "text": "0" }, { "code": null, "e": 2962, "s": 2946, "text": "Gazal1 year ago" }, { "code": null, "e": 2968, "s": 2962, "text": "Gazal" }, { "code": null, "e": 3319, "s": 2968, "text": "JAVA SOL. 0.2SECclass GFG {public static void main (String[] args) {//codeScanner sc=new Scanner(System.in);int t=sc.nextInt();int x,i=1;while(t-->0){ int n=sc.nextInt(); i=1; while(n>0) { n-=i; //ques is about sum of natural numbers i++; } if(n==0) System.out.println(1); else System.out.println(0);}}}" }, { "code": null, "e": 3465, "s": 3319, "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": 3501, "s": 3465, "text": " Login to access your submissions. " }, { "code": null, "e": 3511, "s": 3501, "text": "\nProblem\n" }, { "code": null, "e": 3521, "s": 3511, "text": "\nContest\n" }, { "code": null, "e": 3584, "s": 3521, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3732, "s": 3584, "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": 3940, "s": 3732, "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": 4046, "s": 3940, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Material - File Icons
This chapter explains the usage of Google's (Material) File icons. Assume that custom is the CSS class name where we defined the size and color, as shown in the example given below. <!DOCTYPE html> <html> <head> <link href = "https://fonts.googleapis.com/icon?family=Material+Icons" rel = "stylesheet"> <style> i.custom {font-size: 2em; color: green;} </style> </head> <body> <i class = "material-icons custom">accessibility</i> </body> </html> The following table contains the usage and results of Google's (Material) File icons. Replace the < body > tag of the above program with the code given in the table to get the respective outputs − 26 Lectures 2 hours Neha Gupta 20 Lectures 2 hours Asif Hussain 43 Lectures 5 hours Sharad Kumar 411 Lectures 38.5 hours In28Minutes Official 71 Lectures 10 hours Chaand Sheikh 207 Lectures 33 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2748, "s": 2566, "text": "This chapter explains the usage of Google's (Material) File icons. Assume that custom is the CSS class name where we defined the size and color, as shown in the example given below." }, { "code": null, "e": 3066, "s": 2748, "text": "<!DOCTYPE html>\n<html>\n <head>\n <link href = \"https://fonts.googleapis.com/icon?family=Material+Icons\" rel = \"stylesheet\">\n\t\t\n <style>\n i.custom {font-size: 2em; color: green;}\n </style>\n\t\t\n </head>\n\t\n <body>\n <i class = \"material-icons custom\">accessibility</i>\n </body>\n\t\n</html>" }, { "code": null, "e": 3263, "s": 3066, "text": "The following table contains the usage and results of Google's (Material) File icons. Replace the < body > tag of the above program with the code given in the table to get the respective outputs −" }, { "code": null, "e": 3296, "s": 3263, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 3308, "s": 3296, "text": " Neha Gupta" }, { "code": null, "e": 3341, "s": 3308, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 3355, "s": 3341, "text": " Asif Hussain" }, { "code": null, "e": 3388, "s": 3355, "text": "\n 43 Lectures \n 5 hours \n" }, { "code": null, "e": 3402, "s": 3388, "text": " Sharad Kumar" }, { "code": null, "e": 3439, "s": 3402, "text": "\n 411 Lectures \n 38.5 hours \n" }, { "code": null, "e": 3461, "s": 3439, "text": " In28Minutes Official" }, { "code": null, "e": 3495, "s": 3461, "text": "\n 71 Lectures \n 10 hours \n" }, { "code": null, "e": 3510, "s": 3495, "text": " Chaand Sheikh" }, { "code": null, "e": 3545, "s": 3510, "text": "\n 207 Lectures \n 33 hours \n" }, { "code": null, "e": 3573, "s": 3545, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3580, "s": 3573, "text": " Print" }, { "code": null, "e": 3591, "s": 3580, "text": " Add Notes" } ]
How to flatten a shallow list in Python?
A simple and straightforward solution is to append items from sublists in a flat list using two nested for loops. lst = [[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]] flatlist = [] for sublist in lst: for item in sublist: flatlist.append(item) print (flatlist) A more compact and Pythonic solution is to use chain() function from itertools module. >>> lst =[[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]] >>> import itertools >>> flatlist = list(itertools.chain(*lst)) >>> flatlist [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120]
[ { "code": null, "e": 1176, "s": 1062, "text": "A simple and straightforward solution is to append items from sublists in a flat list using two nested for loops." }, { "code": null, "e": 1343, "s": 1176, "text": "lst = [[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]]\nflatlist = []\nfor sublist in lst:\n for item in sublist:\n flatlist.append(item)\nprint (flatlist)" }, { "code": null, "e": 1430, "s": 1343, "text": "A more compact and Pythonic solution is to use chain() function from itertools module." }, { "code": null, "e": 1627, "s": 1430, "text": ">>> lst =[[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]]\n>>> import itertools\n>>> flatlist = list(itertools.chain(*lst))\n>>> flatlist\n[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120]" } ]
How to delete/remove an element from a C# array?
To delete an elements from a C# array, we will shift the elements from the position the user want the element to delete. Here, first we have 5 elements − int[] arr = new int[5] {35, 50, 55, 77, 98}; Now let’s say we need to delete the element at 2nd position i.e. variable “pos = 2” is set, for that shift the elements after the specified position − // Shifting elements for (i = pos-1; i < 4; i++) { arr[i] = arr[i + 1]; } Now display the result as shown in the complete code below. Live Demo using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Demo { class Program { static void Main() { int i = 0; int pos; int[] arr = new int[5] {35, 50, 55, 77, 98}; Console.WriteLine("Elements before deletion:"); for (i = 0; i < 5; i++) { Console.WriteLine("Element[" + (i) + "]: "+arr[i]); } // Let's say the position to delete the item is 2 i.e. arr[1] pos = 2; // Shifting elements for (i = pos-1; i < 4; i++) { arr[i] = arr[i + 1]; } Console.WriteLine("Elements after deletion: "); for (i = 0; i < 4; i++) { Console.WriteLine("Element[" + (i + 1) + "]: "+arr[i]); } Console.WriteLine(); } } } Elements before deletion: Element[0]: 35 Element[1]: 50 Element[2]: 55 Element[3]: 77 Element[4]: 98 Elements after deletion: Element[1]: 35 Element[2]: 55 Element[3]: 77 Element[4]: 98
[ { "code": null, "e": 1308, "s": 1187, "text": "To delete an elements from a C# array, we will shift the elements from the position the user want the element to delete." }, { "code": null, "e": 1341, "s": 1308, "text": "Here, first we have 5 elements −" }, { "code": null, "e": 1386, "s": 1341, "text": "int[] arr = new int[5] {35, 50, 55, 77, 98};" }, { "code": null, "e": 1537, "s": 1386, "text": "Now let’s say we need to delete the element at 2nd position i.e. variable “pos = 2” is set, for that shift the elements after the specified position −" }, { "code": null, "e": 1614, "s": 1537, "text": "// Shifting elements\nfor (i = pos-1; i < 4; i++) {\n arr[i] = arr[i + 1];\n}" }, { "code": null, "e": 1674, "s": 1614, "text": "Now display the result as shown in the complete code below." }, { "code": null, "e": 1685, "s": 1674, "text": " Live Demo" }, { "code": null, "e": 2514, "s": 1685, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace Demo {\n class Program {\n static void Main() {\n int i = 0;\n int pos;\n int[] arr = new int[5] {35, 50, 55, 77, 98};\n\n Console.WriteLine(\"Elements before deletion:\");\n for (i = 0; i < 5; i++) {\n Console.WriteLine(\"Element[\" + (i) + \"]: \"+arr[i]);\n }\n\n // Let's say the position to delete the item is 2 i.e. arr[1]\n pos = 2;\n // Shifting elements\n for (i = pos-1; i < 4; i++) {\n arr[i] = arr[i + 1];\n }\n Console.WriteLine(\"Elements after deletion: \");\n for (i = 0; i < 4; i++) {\n Console.WriteLine(\"Element[\" + (i + 1) + \"]: \"+arr[i]);\n }\n Console.WriteLine();\n }\n }\n}" }, { "code": null, "e": 2700, "s": 2514, "text": "Elements before deletion:\nElement[0]: 35\nElement[1]: 50\nElement[2]: 55\nElement[3]: 77\nElement[4]: 98\nElements after deletion:\nElement[1]: 35\nElement[2]: 55\nElement[3]: 77\nElement[4]: 98" } ]
Connell Sequence
26 May, 2022 Given an integer ‘n’, generate the first ‘n’ terms of the Connell Sequence. Connell Sequence is the sequence formed with the first odd number, i.e 1 as its first term. The subsequent terms of the sequence are made up of the first two even numbers, i.e 2 and 4, followed by the next three odd numbers, i.e 5, 7 and 9, followed by the next four even numbers, i.e 10, 12, 14 and 16 and so on .... the sequence continues.Formula: a[n] = 2 * n - floor((1 + sqrt(8 * n - 7))/2) ; n > 1 Examples: Input : 6 Output : 1 2 4 5 7 9 Input : 12 Output : 1 2 4 5 7 9 10 12 14 16 17 19 It may be noted here that writing the terms in new lines as, first term in first line, next two terms in next line, next three terms in next line and so on, gives an interesting pattern as:Line 1 : 1 Line 2 : 2 4 Line 3 : 5 7 9 Line 4 : 10 12 14 16 Line 5 : 17 19 21 23 25 and so on... The pattern is every last number of a particular line is equal to that line number squared. For example In line 2 last number is 4 which is equal to its line number squared, i.e 2^2In line 5 last number is 25 which is equal to its line number squared, i.e 5^2 In line 2 last number is 4 which is equal to its line number squared, i.e 2^2 In line 5 last number is 25 which is equal to its line number squared, i.e 5^2 Below is a simple implementation where we generate result by alternatively adding odd and even number of elements. We use size of current list to decide next number of elements to push. C++ Java Python3 C# Javascript // CPP code to generate first 'n' terms// of Connell Sequence#include <bits/stdc++.h>using namespace std; // Function to generate a fixed number// of even or odd terms. The size of r// decides whether numbers to be generated// even or odd.vector<long long int> gen(long long int n, vector<long long int> r){ long long int a = r[r.size() - 1]; a++; for (int i = 1; i <= n; a += 2, i++) r.push_back(a); return r;} // Generating the first 'n' terms of// Connell Sequencevector<long long int> connell(long long int n){ vector<long long int> res; long long int k = 1; // A dummy 0 is inserted at the // beginning for consistency res.push_back(0); while (1) { // Calling function gen() to generate // 'k' number of terms res = gen(k, res); k++; int j = res.size() - 1; while (j != n && j + k > n) k--; // Checking if 'n' terms are // already generated if (j >= n) break; } // Removing the previously inserted dummy 0 res.erase(res.begin()); return res;} // Driver Methodint main(){ long long int n = 10; cout << "The first " << n << " terms are" << endl; vector<long long int> res = conell(n); for (int i = 0; i < res.size(); i++) cout << res[i] << " "; cout << endl; return 0;} // Java code to generate// first 'n' terms// of Connell Sequenceimport java.util.*; class GFG{ // Function to generate a // fixed number of even or // odd terms. The size of r // decides whether numbers // to be generated even or odd. static Vector<Long> gen(long n, Vector<Long> r) { long a = r.get(r.size() - 1); a++; for (int i = 1; i <= n; a += 2, i++) { r.add(a); } return r; } // Generating the first // 'n' terms of // Connell Sequence static Vector<Long> connell(long n) { Vector<Long> res = new Vector<Long>(); long k = 1; // A dummy 0 is inserted // at the beginning for // consistency res.add(0L); while (true) { // Calling function // gen() to generate // 'k' number of terms res = gen(k, res); k++; int j = res.size() - 1; while (j != n && j + k > n) { k--; } // Checking if 'n' // terms are already // generated if (j >= n) { break; } } // Removing the previously // inserted dummy 0 res.remove(0); return res; } // Driver Code public static void main(String[] args) { long n = 10; System.out.println("The first " + n + " terms are"); Vector<Long> res = conell(n); for (int i = 0; i < res.size(); i++) { System.out.print(res.get(i) + " "); } System.out.println(); }} // This code has been contributed// by Rajput-Ji # Python3 code to generate first 'n' terms# of Connell Sequence # Function to generate a fixed number# of even or odd terms. The size of r# decides whether numbers to be generated# even or odd.def gen(n, r): a = r[-1] a += 1 for i in range(1, n + 1): r.append(a) a += 2 return r # Generating the first 'n' terms of# Connell Sequencedef connell(n): res = [] k = 1 # A dummy 0 is inserted at the # beginning for consistency res.append(0) while 1: # Calling function gen() to generate # 'k' number of terms res = gen(k, res) k += 1 j = len(res) - 1 while j != n and j + k > n: k -= 1 # Checking if 'n' terms are # already generated if j >= n: break # Removing the previously inserted dummy 0 res.remove(res[0]) return res # Driver Codeif __name__ == "__main__": n = 10 print("The first %d terms are" % n) res = conell(n) for i in range(len(res)): print(res[i], end = " ") print() # This code is contributed by# sanjeev2552 // C# code to generate// first 'n' terms// of Connell Sequenceusing System;using System.Collections.Generic; class GFG{ // Function to generate a // fixed number of even or // odd terms. The size of r // decides whether numbers // to be generated even or odd. static List<long> gen(long n, List<long> r) { long a = r[r.Count - 1]; a++; for (int i = 1; i <= n; a += 2, i++) r.Add(a); return r; } // Generating the first // 'n' terms of // Connell Sequence static List<long> connell(long n) { List<long> res = new List<long>(); long k = 1; // A dummy 0 is inserted // at the beginning for // consistency res.Add(0); while (true) { // Calling function // gen() to generate // 'k' number of terms res = gen(k, res); k++; int j = res.Count - 1; while (j != n && j + k > n) k--; // Checking if 'n' // terms are already // generated if (j >= n) break; } // Removing the previously // inserted dummy 0 res.RemoveAt(0); return res; } // Driver Code static void Main() { long n = 10; Console.WriteLine("The first " + n + " terms are"); List<long> res = conell(n); for (int i = 0; i < res.Count; i++) Console.Write(res[i] + " "); Console.WriteLine(); }} // This code is contributed by// Manish Shaw(manishshaw1) <script> // Javascript code to generate first 'n' terms// of Connell Sequence // Function to generate a fixed number// of even or odd terms. The size of r// decides whether numbers to be generated// even or odd.function gen(n, r){ var a = r[r.length - 1]; a++; for (var i = 1; i <= n; a += 2, i++) r.push(a); return r;} // Generating the first 'n' terms of// Connell Sequencefunction connell(n){ var res = []; var k = 1; // A dummy 0 is inserted at the // beginning for consistency res.push(0); while (1) { // Calling function gen() to generate // 'k' number of terms res = gen(k, res); k++; var j = res.length - 1; while (j != n && j + k > n) k--; // Checking if 'n' terms are // already generated if (j >= n) break; } // Removing the previously inserted dummy 0 res.shift(); return res;} // Driver Methodvar n = 10;document.write( "The first " + n + " terms are" + "<br>");var res = conell(n);for (var i = 0; i < res.length; i++) document.write( res[i] + " "); // This code is contributed by rrrtnx.</script> Output: The first 10 terms are 1 2 4 5 7 9 10 12 14 16 manishshaw1 Rajput-Ji sanjeev2552 PSKP_95 rrrtnx surinderdawra388 series Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n26 May, 2022" }, { "code": null, "e": 482, "s": 54, "text": "Given an integer ‘n’, generate the first ‘n’ terms of the Connell Sequence. Connell Sequence is the sequence formed with the first odd number, i.e 1 as its first term. The subsequent terms of the sequence are made up of the first two even numbers, i.e 2 and 4, followed by the next three odd numbers, i.e 5, 7 and 9, followed by the next four even numbers, i.e 10, 12, 14 and 16 and so on .... the sequence continues.Formula: " }, { "code": null, "e": 538, "s": 482, "text": "a[n] = 2 * n - floor((1 + sqrt(8 * n - 7))/2) ; n > 1" }, { "code": null, "e": 550, "s": 538, "text": "Examples: " }, { "code": null, "e": 632, "s": 550, "text": "Input : 6\nOutput : 1 2 4 5 7 9\n\nInput : 12\nOutput : 1 2 4 5 7 9 10 12 14 16 17 19" }, { "code": null, "e": 1026, "s": 634, "text": "It may be noted here that writing the terms in new lines as, first term in first line, next two terms in next line, next three terms in next line and so on, gives an interesting pattern as:Line 1 : 1 Line 2 : 2 4 Line 3 : 5 7 9 Line 4 : 10 12 14 16 Line 5 : 17 19 21 23 25 and so on... The pattern is every last number of a particular line is equal to that line number squared. For example " }, { "code": null, "e": 1182, "s": 1026, "text": "In line 2 last number is 4 which is equal to its line number squared, i.e 2^2In line 5 last number is 25 which is equal to its line number squared, i.e 5^2" }, { "code": null, "e": 1260, "s": 1182, "text": "In line 2 last number is 4 which is equal to its line number squared, i.e 2^2" }, { "code": null, "e": 1339, "s": 1260, "text": "In line 5 last number is 25 which is equal to its line number squared, i.e 5^2" }, { "code": null, "e": 1526, "s": 1339, "text": "Below is a simple implementation where we generate result by alternatively adding odd and even number of elements. We use size of current list to decide next number of elements to push. " }, { "code": null, "e": 1530, "s": 1526, "text": "C++" }, { "code": null, "e": 1535, "s": 1530, "text": "Java" }, { "code": null, "e": 1543, "s": 1535, "text": "Python3" }, { "code": null, "e": 1546, "s": 1543, "text": "C#" }, { "code": null, "e": 1557, "s": 1546, "text": "Javascript" }, { "code": "// CPP code to generate first 'n' terms// of Connell Sequence#include <bits/stdc++.h>using namespace std; // Function to generate a fixed number// of even or odd terms. The size of r// decides whether numbers to be generated// even or odd.vector<long long int> gen(long long int n, vector<long long int> r){ long long int a = r[r.size() - 1]; a++; for (int i = 1; i <= n; a += 2, i++) r.push_back(a); return r;} // Generating the first 'n' terms of// Connell Sequencevector<long long int> connell(long long int n){ vector<long long int> res; long long int k = 1; // A dummy 0 is inserted at the // beginning for consistency res.push_back(0); while (1) { // Calling function gen() to generate // 'k' number of terms res = gen(k, res); k++; int j = res.size() - 1; while (j != n && j + k > n) k--; // Checking if 'n' terms are // already generated if (j >= n) break; } // Removing the previously inserted dummy 0 res.erase(res.begin()); return res;} // Driver Methodint main(){ long long int n = 10; cout << \"The first \" << n << \" terms are\" << endl; vector<long long int> res = conell(n); for (int i = 0; i < res.size(); i++) cout << res[i] << \" \"; cout << endl; return 0;}", "e": 2924, "s": 1557, "text": null }, { "code": "// Java code to generate// first 'n' terms// of Connell Sequenceimport java.util.*; class GFG{ // Function to generate a // fixed number of even or // odd terms. The size of r // decides whether numbers // to be generated even or odd. static Vector<Long> gen(long n, Vector<Long> r) { long a = r.get(r.size() - 1); a++; for (int i = 1; i <= n; a += 2, i++) { r.add(a); } return r; } // Generating the first // 'n' terms of // Connell Sequence static Vector<Long> connell(long n) { Vector<Long> res = new Vector<Long>(); long k = 1; // A dummy 0 is inserted // at the beginning for // consistency res.add(0L); while (true) { // Calling function // gen() to generate // 'k' number of terms res = gen(k, res); k++; int j = res.size() - 1; while (j != n && j + k > n) { k--; } // Checking if 'n' // terms are already // generated if (j >= n) { break; } } // Removing the previously // inserted dummy 0 res.remove(0); return res; } // Driver Code public static void main(String[] args) { long n = 10; System.out.println(\"The first \" + n + \" terms are\"); Vector<Long> res = conell(n); for (int i = 0; i < res.size(); i++) { System.out.print(res.get(i) + \" \"); } System.out.println(); }} // This code has been contributed// by Rajput-Ji", "e": 4782, "s": 2924, "text": null }, { "code": "# Python3 code to generate first 'n' terms# of Connell Sequence # Function to generate a fixed number# of even or odd terms. The size of r# decides whether numbers to be generated# even or odd.def gen(n, r): a = r[-1] a += 1 for i in range(1, n + 1): r.append(a) a += 2 return r # Generating the first 'n' terms of# Connell Sequencedef connell(n): res = [] k = 1 # A dummy 0 is inserted at the # beginning for consistency res.append(0) while 1: # Calling function gen() to generate # 'k' number of terms res = gen(k, res) k += 1 j = len(res) - 1 while j != n and j + k > n: k -= 1 # Checking if 'n' terms are # already generated if j >= n: break # Removing the previously inserted dummy 0 res.remove(res[0]) return res # Driver Codeif __name__ == \"__main__\": n = 10 print(\"The first %d terms are\" % n) res = conell(n) for i in range(len(res)): print(res[i], end = \" \") print() # This code is contributed by# sanjeev2552", "e": 5867, "s": 4782, "text": null }, { "code": "// C# code to generate// first 'n' terms// of Connell Sequenceusing System;using System.Collections.Generic; class GFG{ // Function to generate a // fixed number of even or // odd terms. The size of r // decides whether numbers // to be generated even or odd. static List<long> gen(long n, List<long> r) { long a = r[r.Count - 1]; a++; for (int i = 1; i <= n; a += 2, i++) r.Add(a); return r; } // Generating the first // 'n' terms of // Connell Sequence static List<long> connell(long n) { List<long> res = new List<long>(); long k = 1; // A dummy 0 is inserted // at the beginning for // consistency res.Add(0); while (true) { // Calling function // gen() to generate // 'k' number of terms res = gen(k, res); k++; int j = res.Count - 1; while (j != n && j + k > n) k--; // Checking if 'n' // terms are already // generated if (j >= n) break; } // Removing the previously // inserted dummy 0 res.RemoveAt(0); return res; } // Driver Code static void Main() { long n = 10; Console.WriteLine(\"The first \" + n + \" terms are\"); List<long> res = conell(n); for (int i = 0; i < res.Count; i++) Console.Write(res[i] + \" \"); Console.WriteLine(); }} // This code is contributed by// Manish Shaw(manishshaw1)", "e": 7574, "s": 5867, "text": null }, { "code": "<script> // Javascript code to generate first 'n' terms// of Connell Sequence // Function to generate a fixed number// of even or odd terms. The size of r// decides whether numbers to be generated// even or odd.function gen(n, r){ var a = r[r.length - 1]; a++; for (var i = 1; i <= n; a += 2, i++) r.push(a); return r;} // Generating the first 'n' terms of// Connell Sequencefunction connell(n){ var res = []; var k = 1; // A dummy 0 is inserted at the // beginning for consistency res.push(0); while (1) { // Calling function gen() to generate // 'k' number of terms res = gen(k, res); k++; var j = res.length - 1; while (j != n && j + k > n) k--; // Checking if 'n' terms are // already generated if (j >= n) break; } // Removing the previously inserted dummy 0 res.shift(); return res;} // Driver Methodvar n = 10;document.write( \"The first \" + n + \" terms are\" + \"<br>\");var res = conell(n);for (var i = 0; i < res.length; i++) document.write( res[i] + \" \"); // This code is contributed by rrrtnx.</script>", "e": 8735, "s": 7574, "text": null }, { "code": null, "e": 8745, "s": 8735, "text": "Output: " }, { "code": null, "e": 8793, "s": 8745, "text": "The first 10 terms are\n1 2 4 5 7 9 10 12 14 16 " }, { "code": null, "e": 8807, "s": 8795, "text": "manishshaw1" }, { "code": null, "e": 8817, "s": 8807, "text": "Rajput-Ji" }, { "code": null, "e": 8829, "s": 8817, "text": "sanjeev2552" }, { "code": null, "e": 8837, "s": 8829, "text": "PSKP_95" }, { "code": null, "e": 8844, "s": 8837, "text": "rrrtnx" }, { "code": null, "e": 8861, "s": 8844, "text": "surinderdawra388" }, { "code": null, "e": 8868, "s": 8861, "text": "series" }, { "code": null, "e": 8881, "s": 8868, "text": "Mathematical" }, { "code": null, "e": 8894, "s": 8881, "text": "Mathematical" }, { "code": null, "e": 8901, "s": 8894, "text": "series" } ]
Mobile Testing - Appium Framework
Appium is an open-source test automation framework for testing native and hybrid apps and mobile web apps. It drives iOS and Android apps using the WebDriver protocol. It’s free and (mostly) open source. It’s free and (mostly) open source. It has a very well supported and active Google group. It has a very well supported and active Google group. It’s in the Selenium 3 spec so should be future proof. It’s in the Selenium 3 spec so should be future proof. It supports both Android and iOS. It supports both Android and iOS. It does not require anything to be installed on the device – no server or code changes required. It does not require anything to be installed on the device – no server or code changes required. No support for intelligent waits. On iOS, you can only execute one test at a time per Mac. Limited support for gestures. Limited support for Android < 4.1 Step 1 − The prerequisites to use Appium is Java SDK (minimum 1.6). If you don’t have Java installed on your system, then follow the steps given below. Download JDK and JRE from Oracle JavaSE Download JDK and JRE from Oracle JavaSE Accept license agreement. Accept license agreement. Install JDK and JRE. Install JDK and JRE. Set environment variable as shown in the screenshot below. Set environment variable as shown in the screenshot below. Step 2 − Download Android Studio from SDK (It will take time because of the size of the file). Double click the exe and run the installer. Continue with all default options. Set the ANDROID_HOME. Step 3 − Install Android images and tools. Click on SDK Manager − Select the necessary package. For example, if we are building an App for Android 4.4.2, then make sure the following packages are checked under the Tools section − Android SDK Tools rev 22.6.3 Android Platform-tools rev 19.0.1 Android SDK Build-tools rev 19.1 Select the necessary package. For example, if we are building an App for Android 4.4.2, then make sure the following packages are checked under the Tools section − Android SDK Tools rev 22.6.3 Android Platform-tools rev 19.0.1 Android SDK Build-tools rev 19.1 Step 4 − Create Android Virtual Devices − Open Android Studio and click AVD Manager in the toolbar. AVDs allow us to test and run our Android apps. Open Android Studio and click AVD Manager in the toolbar. AVDs allow us to test and run our Android apps. Use the following settings for a Nexus5 AVD − Device: Nexus 5 (4.95, 1080 x 1920; xxhdpi) Target: Google APIs x86 (Google Inc.) - API Level 19 Make sure you select the target with Google APIs in the name. CPU: Intel Atom (x86) Check the box for Use Host GPU Click OK. Use the following settings for a Nexus5 AVD − Device: Nexus 5 (4.95, 1080 x 1920; xxhdpi) Device: Nexus 5 (4.95, 1080 x 1920; xxhdpi) Target: Google APIs x86 (Google Inc.) - API Level 19 Target: Google APIs x86 (Google Inc.) - API Level 19 Make sure you select the target with Google APIs in the name. Make sure you select the target with Google APIs in the name. CPU: Intel Atom (x86) CPU: Intel Atom (x86) Check the box for Use Host GPU Check the box for Use Host GPU Click OK. Click OK. You should now see the AVD you created in the AVD Manager, where you can start it, delete it, or create another one! You should now see the AVD you created in the AVD Manager, where you can start it, delete it, or create another one! Step 5 − Download Appium jar files from Appium To test an App with Appium, follow the steps given below − Step 1 − Create a test Project in the Android Studio named as “RobotiumTest”. Choose all the default options until you reach to the main page. Step 2 − Add the Appium jars into your project. Click Project → App → copy all the jars in lib. Select the copied jars except Selenium, Java client and Junit Jar, then right-click on it and click on "Add as Library". Step 3 − Click on build.gradle in the App. You will see all the libraries added, as shown in the following screenshot. Step 4 − Now create a Java class as shown below − AppiumDriver driver; @Before public void testCaseSetup()throws Exception { //service.start(); //reader.readFile(); DesiredCapabilities cap = new DesiredCapabilities(); cap.setCapability(MobileCapabilityType.PLATFORM_NAME,"Android"); cap.setCapability(MobileCapabilityType.DEVICE_NAME, "Android device"); cap.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, "4000"); cap.setCapability(MobileCapabilityType.APP, "c://apk//sample.apk"); driver = new AndroidDriver<MobileElement>("http://127.0.0.1:4444/wd/hub",cap); } @Test public void testcase1()throws Exception { driver.findElementByID("Example").click(); Asser.assertTrue(driver.findElementByID("Example").isDisplayed)); } @After public void testCaseTearDown() { driver.quit(); } Step 5 − Running the Test case. Click on build variant and select Unit Testing. Start the Appium server with the specific port "4444". Download the Appium for Windows from here. Double click on the .exe and install Appium. Click on the icon to up the UI. Change the port if required, as shown below. Click the Play button to start the server. Download the Appium for Windows from here. Double click on the .exe and install Appium. Click on the icon to up the UI. Change the port if required, as shown below. Click the Play button to start the server. Connect the device with USB debugging on or start an emulator. Right-click the test class and click on "Run".
[ { "code": null, "e": 2447, "s": 2279, "text": "Appium is an open-source test automation framework for testing native and hybrid apps and mobile web apps. It drives iOS and Android apps using the WebDriver protocol." }, { "code": null, "e": 2483, "s": 2447, "text": "It’s free and (mostly) open source." }, { "code": null, "e": 2519, "s": 2483, "text": "It’s free and (mostly) open source." }, { "code": null, "e": 2573, "s": 2519, "text": "It has a very well supported and active Google group." }, { "code": null, "e": 2627, "s": 2573, "text": "It has a very well supported and active Google group." }, { "code": null, "e": 2682, "s": 2627, "text": "It’s in the Selenium 3 spec so should be future proof." }, { "code": null, "e": 2737, "s": 2682, "text": "It’s in the Selenium 3 spec so should be future proof." }, { "code": null, "e": 2771, "s": 2737, "text": "It supports both Android and iOS." }, { "code": null, "e": 2805, "s": 2771, "text": "It supports both Android and iOS." }, { "code": null, "e": 2902, "s": 2805, "text": "It does not require anything to be installed on the device – no server or code changes required." }, { "code": null, "e": 2999, "s": 2902, "text": "It does not require anything to be installed on the device – no server or code changes required." }, { "code": null, "e": 3033, "s": 2999, "text": "No support for intelligent waits." }, { "code": null, "e": 3090, "s": 3033, "text": "On iOS, you can only execute one test at a time per Mac." }, { "code": null, "e": 3120, "s": 3090, "text": "Limited support for gestures." }, { "code": null, "e": 3154, "s": 3120, "text": "Limited support for Android < 4.1" }, { "code": null, "e": 3306, "s": 3154, "text": "Step 1 − The prerequisites to use Appium is Java SDK (minimum 1.6). If you don’t have Java installed on your system, then follow the steps given below." }, { "code": null, "e": 3346, "s": 3306, "text": "Download JDK and JRE from Oracle JavaSE" }, { "code": null, "e": 3386, "s": 3346, "text": "Download JDK and JRE from Oracle JavaSE" }, { "code": null, "e": 3412, "s": 3386, "text": "Accept license agreement." }, { "code": null, "e": 3438, "s": 3412, "text": "Accept license agreement." }, { "code": null, "e": 3459, "s": 3438, "text": "Install JDK and JRE." }, { "code": null, "e": 3480, "s": 3459, "text": "Install JDK and JRE." }, { "code": null, "e": 3539, "s": 3480, "text": "Set environment variable as shown in the screenshot below." }, { "code": null, "e": 3598, "s": 3539, "text": "Set environment variable as shown in the screenshot below." }, { "code": null, "e": 3693, "s": 3598, "text": "Step 2 − Download Android Studio from SDK (It will take time because of the size of the file)." }, { "code": null, "e": 3737, "s": 3693, "text": "Double click the exe and run the installer." }, { "code": null, "e": 3772, "s": 3737, "text": "Continue with all default options." }, { "code": null, "e": 3794, "s": 3772, "text": "Set the ANDROID_HOME." }, { "code": null, "e": 3837, "s": 3794, "text": "Step 3 − Install Android images and tools." }, { "code": null, "e": 3860, "s": 3837, "text": "Click on SDK Manager −" }, { "code": null, "e": 4123, "s": 3860, "text": "Select the necessary package. For example, if we are building an App for Android 4.4.2, then make sure the following packages are checked under the Tools section −\n\nAndroid SDK Tools rev 22.6.3\nAndroid Platform-tools rev 19.0.1\nAndroid SDK Build-tools rev 19.1\n\n" }, { "code": null, "e": 4287, "s": 4123, "text": "Select the necessary package. For example, if we are building an App for Android 4.4.2, then make sure the following packages are checked under the Tools section −" }, { "code": null, "e": 4316, "s": 4287, "text": "Android SDK Tools rev 22.6.3" }, { "code": null, "e": 4350, "s": 4316, "text": "Android Platform-tools rev 19.0.1" }, { "code": null, "e": 4383, "s": 4350, "text": "Android SDK Build-tools rev 19.1" }, { "code": null, "e": 4425, "s": 4383, "text": "Step 4 − Create Android Virtual Devices −" }, { "code": null, "e": 4531, "s": 4425, "text": "Open Android Studio and click AVD Manager in the toolbar. AVDs allow us to test and run our Android apps." }, { "code": null, "e": 4637, "s": 4531, "text": "Open Android Studio and click AVD Manager in the toolbar. AVDs allow us to test and run our Android apps." }, { "code": null, "e": 4908, "s": 4637, "text": "Use the following settings for a Nexus5 AVD −\n\nDevice: Nexus 5 (4.95, 1080 x 1920; xxhdpi)\nTarget: Google APIs x86 (Google Inc.) - API Level 19\nMake sure you select the target with Google APIs in the name.\nCPU: Intel Atom (x86)\nCheck the box for Use Host GPU\nClick OK.\n\n" }, { "code": null, "e": 4954, "s": 4908, "text": "Use the following settings for a Nexus5 AVD −" }, { "code": null, "e": 4998, "s": 4954, "text": "Device: Nexus 5 (4.95, 1080 x 1920; xxhdpi)" }, { "code": null, "e": 5042, "s": 4998, "text": "Device: Nexus 5 (4.95, 1080 x 1920; xxhdpi)" }, { "code": null, "e": 5095, "s": 5042, "text": "Target: Google APIs x86 (Google Inc.) - API Level 19" }, { "code": null, "e": 5148, "s": 5095, "text": "Target: Google APIs x86 (Google Inc.) - API Level 19" }, { "code": null, "e": 5210, "s": 5148, "text": "Make sure you select the target with Google APIs in the name." }, { "code": null, "e": 5272, "s": 5210, "text": "Make sure you select the target with Google APIs in the name." }, { "code": null, "e": 5294, "s": 5272, "text": "CPU: Intel Atom (x86)" }, { "code": null, "e": 5316, "s": 5294, "text": "CPU: Intel Atom (x86)" }, { "code": null, "e": 5347, "s": 5316, "text": "Check the box for Use Host GPU" }, { "code": null, "e": 5378, "s": 5347, "text": "Check the box for Use Host GPU" }, { "code": null, "e": 5388, "s": 5378, "text": "Click OK." }, { "code": null, "e": 5398, "s": 5388, "text": "Click OK." }, { "code": null, "e": 5515, "s": 5398, "text": "You should now see the AVD you created in the AVD Manager, where you can start it, delete it, or create another one!" }, { "code": null, "e": 5632, "s": 5515, "text": "You should now see the AVD you created in the AVD Manager, where you can start it, delete it, or create another one!" }, { "code": null, "e": 5680, "s": 5632, "text": "Step 5 − Download Appium jar files from Appium " }, { "code": null, "e": 5739, "s": 5680, "text": "To test an App with Appium, follow the steps given below −" }, { "code": null, "e": 5817, "s": 5739, "text": "Step 1 − Create a test Project in the Android Studio named as “RobotiumTest”." }, { "code": null, "e": 5882, "s": 5817, "text": "Choose all the default options until you reach to the main page." }, { "code": null, "e": 6099, "s": 5882, "text": "Step 2 − Add the Appium jars into your project. Click Project → App → copy all the jars in lib. Select the copied jars except Selenium, Java client and Junit Jar, then right-click on it and click on \"Add as Library\"." }, { "code": null, "e": 6218, "s": 6099, "text": "Step 3 − Click on build.gradle in the App. You will see all the libraries added, as shown in the following screenshot." }, { "code": null, "e": 6268, "s": 6218, "text": "Step 4 − Now create a Java class as shown below −" }, { "code": null, "e": 7048, "s": 6268, "text": "AppiumDriver driver;\n@Before\n\npublic void testCaseSetup()throws Exception {\n //service.start();\n //reader.readFile();\n\t\n DesiredCapabilities cap = new DesiredCapabilities();\n\t\n cap.setCapability(MobileCapabilityType.PLATFORM_NAME,\"Android\");\n cap.setCapability(MobileCapabilityType.DEVICE_NAME, \"Android device\");\n cap.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, \"4000\");\n cap.setCapability(MobileCapabilityType.APP, \"c://apk//sample.apk\");\n\t\n driver = new AndroidDriver<MobileElement>(\"http://127.0.0.1:4444/wd/hub\",cap);\n}\n\n@Test\npublic void testcase1()throws Exception {\n driver.findElementByID(\"Example\").click();\n Asser.assertTrue(driver.findElementByID(\"Example\").isDisplayed));\n}\n\n@After\npublic void testCaseTearDown() {\n driver.quit();\n}" }, { "code": null, "e": 7080, "s": 7048, "text": "Step 5 − Running the Test case." }, { "code": null, "e": 7128, "s": 7080, "text": "Click on build variant and select Unit Testing." }, { "code": null, "e": 7394, "s": 7128, "text": "Start the Appium server with the specific port \"4444\".\n\nDownload the Appium for Windows from here.\nDouble click on the .exe and install Appium.\nClick on the icon to up the UI.\nChange the port if required, as shown below.\nClick the Play button to start the server.\n\n" }, { "code": null, "e": 7437, "s": 7394, "text": "Download the Appium for Windows from here." }, { "code": null, "e": 7482, "s": 7437, "text": "Double click on the .exe and install Appium." }, { "code": null, "e": 7514, "s": 7482, "text": "Click on the icon to up the UI." }, { "code": null, "e": 7559, "s": 7514, "text": "Change the port if required, as shown below." }, { "code": null, "e": 7602, "s": 7559, "text": "Click the Play button to start the server." }, { "code": null, "e": 7665, "s": 7602, "text": "Connect the device with USB debugging on or start an emulator." } ]
MATLAB - Transpose of a Matrix
The transpose operation switches the rows and columns in a matrix. It is represented by a single quote('). Create a script file with the following code − a = [ 10 12 23 ; 14 8 6; 27 8 9] b = a' When you run the file, it displays the following result − a = 10 12 23 14 8 6 27 8 9 b = 10 14 27 12 8 8 23 6 9
[ { "code": null, "e": 2382, "s": 2275, "text": "The transpose operation switches the rows and columns in a matrix. It is represented by a single quote(')." }, { "code": null, "e": 2429, "s": 2382, "text": "Create a script file with the following code −" }, { "code": null, "e": 2469, "s": 2429, "text": "a = [ 10 12 23 ; 14 8 6; 27 8 9]\nb = a'" }, { "code": null, "e": 2527, "s": 2469, "text": "When you run the file, it displays the following result −" } ]
How to get all ID of the DOM elements with JavaScript ?
31 Dec, 2019 Given a HTML document and the task is to get the all ID of the DOM elements in an array. There are two methods to solve this problem which are discusses below: Approach 1: First select all elements using $(‘*’) selector, which selects every element of the document. Use .each() method to traverse all element and check if it has ID. If it has ID then push it in the array. Example: This example implements the above approach. <!DOCTYPE HTML><html> <head> <title> How to get all ID of the DOM elements with JavaScript ? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script></head> <body style="text-align:center;"> <h1 style="color: green"> GeeksForGeeks </h1> <p id="GFG_UP"></p> <button onclick="gfg_Run()"> Click Here </button> <p id="GFG_DOWN" style="color:green;"></p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to get " + "all IDs in an array."; function gfg_Run() { var ID = []; $("*").each(function() { if (this.id) { ID.push(this.id); } }); el_down.innerHTML = ID; } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Approach 2: First select all elements using $(‘*’) selector, Which selects every element of the Document. Use .map() method to traverse all element and check if it has ID. If it has ID then push it in the array using .get() method. Example 2: This example implements the above approach. <!DOCTYPE HTML><html> <head> <title> How to get all ID of the DOM elements with JavaScript ? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script></head> <body style="text-align:center;"> <h1 style="color: green"> GeeksForGeeks </h1> <p id="GFG_UP"></p> <button onclick="gfg_Run()"> Click Here </button> <p id="GFG_DOWN" style="color:green;"></p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to " + "get all IDs in an array."; function gfg_Run() { var ID = []; ID = $("*").map(function() { if (this.id) { return this.id; } }).get(); el_down.innerHTML = ID; } </script></body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript-Misc JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Dec, 2019" }, { "code": null, "e": 188, "s": 28, "text": "Given a HTML document and the task is to get the all ID of the DOM elements in an array. There are two methods to solve this problem which are discusses below:" }, { "code": null, "e": 200, "s": 188, "text": "Approach 1:" }, { "code": null, "e": 294, "s": 200, "text": "First select all elements using $(‘*’) selector, which selects every element of the document." }, { "code": null, "e": 361, "s": 294, "text": "Use .each() method to traverse all element and check if it has ID." }, { "code": null, "e": 401, "s": 361, "text": "If it has ID then push it in the array." }, { "code": null, "e": 454, "s": 401, "text": "Example: This example implements the above approach." }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to get all ID of the DOM elements with JavaScript ? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style=\"color: green\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"></p> <button onclick=\"gfg_Run()\"> Click Here </button> <p id=\"GFG_DOWN\" style=\"color:green;\"></p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); el_up.innerHTML = \"Click on the button to get \" + \"all IDs in an array.\"; function gfg_Run() { var ID = []; $(\"*\").each(function() { if (this.id) { ID.push(this.id); } }); el_down.innerHTML = ID; } </script></body> </html>", "e": 1438, "s": 454, "text": null }, { "code": null, "e": 1446, "s": 1438, "text": "Output:" }, { "code": null, "e": 1477, "s": 1446, "text": "Before clicking on the button:" }, { "code": null, "e": 1507, "s": 1477, "text": "After clicking on the button:" }, { "code": null, "e": 1519, "s": 1507, "text": "Approach 2:" }, { "code": null, "e": 1613, "s": 1519, "text": "First select all elements using $(‘*’) selector, Which selects every element of the Document." }, { "code": null, "e": 1679, "s": 1613, "text": "Use .map() method to traverse all element and check if it has ID." }, { "code": null, "e": 1739, "s": 1679, "text": "If it has ID then push it in the array using .get() method." }, { "code": null, "e": 1794, "s": 1739, "text": "Example 2: This example implements the above approach." }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to get all ID of the DOM elements with JavaScript ? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style=\"color: green\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"></p> <button onclick=\"gfg_Run()\"> Click Here </button> <p id=\"GFG_DOWN\" style=\"color:green;\"></p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); el_up.innerHTML = \"Click on the button to \" + \"get all IDs in an array.\"; function gfg_Run() { var ID = []; ID = $(\"*\").map(function() { if (this.id) { return this.id; } }).get(); el_down.innerHTML = ID; } </script></body> </html>", "e": 2792, "s": 1794, "text": null }, { "code": null, "e": 2800, "s": 2792, "text": "Output:" }, { "code": null, "e": 2831, "s": 2800, "text": "Before clicking on the button:" }, { "code": null, "e": 2861, "s": 2831, "text": "After clicking on the button:" }, { "code": null, "e": 2877, "s": 2861, "text": "JavaScript-Misc" }, { "code": null, "e": 2888, "s": 2877, "text": "JavaScript" }, { "code": null, "e": 2905, "s": 2888, "text": "Web Technologies" }, { "code": null, "e": 2932, "s": 2905, "text": "Web technologies Questions" } ]
Program to check if the String is Empty in Java
22 Jan, 2020 Given a string str, the task is to check if this string is empty or not, in Java. Examples: Input: str = "" Output: True Input: str = "GFG" Output: False Approach: Get the String to be checked in str We can simply check if the string is empty or not using the isEmpty() method of String classSyntax:if (str.isEmpty()) if (str.isEmpty()) Print true if the above condition is true. Else print false. Below is the implementation of the above approach: // Java Program to check if// the String is empty in Java class GFG { // Function to check if the String is empty public static boolean isStringEmpty(String str) { // check if the string is empty or not // using the isEmpty() method // and return the result if (str.isEmpty()) return true; else return false; } // Driver code public static void main(String[] args) { String str1 = "GeeksforGeeks"; String str2 = ""; System.out.println("Is string \"" + str1 + "\" empty? " + isStringEmpty(str1)); System.out.println("Is string \"" + str2 + "\" empty? " + isStringEmpty(str2)); }} Is string "GeeksforGeeks" empty? false Is string "" empty? true Java-String-Programs Java Strings Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples Stream In Java Write a program to reverse an array or string Write a program to print all permutations of a given string C++ Data Types Different Methods to Reverse a String in C++ Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jan, 2020" }, { "code": null, "e": 110, "s": 28, "text": "Given a string str, the task is to check if this string is empty or not, in Java." }, { "code": null, "e": 120, "s": 110, "text": "Examples:" }, { "code": null, "e": 185, "s": 120, "text": "Input: str = \"\" \nOutput: True\n\nInput: str = \"GFG\"\nOutput: False\n" }, { "code": null, "e": 195, "s": 185, "text": "Approach:" }, { "code": null, "e": 231, "s": 195, "text": "Get the String to be checked in str" }, { "code": null, "e": 350, "s": 231, "text": "We can simply check if the string is empty or not using the isEmpty() method of String classSyntax:if (str.isEmpty())\n" }, { "code": null, "e": 370, "s": 350, "text": "if (str.isEmpty())\n" }, { "code": null, "e": 431, "s": 370, "text": "Print true if the above condition is true. Else print false." }, { "code": null, "e": 482, "s": 431, "text": "Below is the implementation of the above approach:" }, { "code": "// Java Program to check if// the String is empty in Java class GFG { // Function to check if the String is empty public static boolean isStringEmpty(String str) { // check if the string is empty or not // using the isEmpty() method // and return the result if (str.isEmpty()) return true; else return false; } // Driver code public static void main(String[] args) { String str1 = \"GeeksforGeeks\"; String str2 = \"\"; System.out.println(\"Is string \\\"\" + str1 + \"\\\" empty? \" + isStringEmpty(str1)); System.out.println(\"Is string \\\"\" + str2 + \"\\\" empty? \" + isStringEmpty(str2)); }}", "e": 1283, "s": 482, "text": null }, { "code": null, "e": 1348, "s": 1283, "text": "Is string \"GeeksforGeeks\" empty? false\nIs string \"\" empty? true\n" }, { "code": null, "e": 1369, "s": 1348, "text": "Java-String-Programs" }, { "code": null, "e": 1374, "s": 1369, "text": "Java" }, { "code": null, "e": 1382, "s": 1374, "text": "Strings" }, { "code": null, "e": 1390, "s": 1382, "text": "Strings" }, { "code": null, "e": 1395, "s": 1390, "text": "Java" }, { "code": null, "e": 1493, "s": 1395, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1544, "s": 1493, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 1575, "s": 1544, "text": "How to iterate any Map in Java" }, { "code": null, "e": 1594, "s": 1575, "text": "Interfaces in Java" }, { "code": null, "e": 1624, "s": 1594, "text": "HashMap in Java with Examples" }, { "code": null, "e": 1639, "s": 1624, "text": "Stream In Java" }, { "code": null, "e": 1685, "s": 1639, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 1745, "s": 1685, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 1760, "s": 1745, "text": "C++ Data Types" }, { "code": null, "e": 1805, "s": 1760, "text": "Different Methods to Reverse a String in C++" } ]
How to get the maximum number of occupied rows and columns in a worksheet in Selenium with python?
We can get the maximum number of occupied rows and columns in a worksheet in Selenium. Excel is a spreadsheet which is saved with the .xlsx extension. An excel workbook has multiple sheets and each sheet consists of rows and columns. Out of all the worksheets, while we are accessing a particular sheet that is called as an active sheet. Each cell inside a sheet has a unique address which is a combination of row and column numbers. The column number starts from alphabetic character A and row number starts from the number 1. A cell can contain numerous types of values and they are the main component of a worksheet. To work with excel in Selenium with python, we need to take help of OpenPyXL library. This library is responsible for reading and writing operations on Excel, having the extensions like xlsx, xlsm, xltm, xltx. To install OpenPyXL library, we have to execute the command pip install openpyxl. This is because OpenPyXL does not come by default with python. After this we should import openpyxl in our code and then we should be ready to interact with excel. To get the count of the occupied rows in a worksheet, first of all we need to load the entire workbook by specifying the path where it is located. This is achieved with load_workbook() method. Next we need to identify the active sheet among all the worksheets with the help of active method. Finally we need to use the max_row method that gives the count of the number of occupied rows. Please note this method is to be used with the worksheet level object. And we need to use the max_column method that gives the count of the number of occupied columns. Please note this method is to be used with the worksheet level object. wrkbk = load_workbook("C:\\work\\SeleniumPython.xlsx") # to identify the active sheet sh = wrkbk.active # identify the number of occupied rows sh.max_row # identify the number of occupied rows sh.max_column Coding Implementation to count the maximum number of occupied rows and columns. import openpyxl # load excel with its path wrkbk = load_workbook("C:\\work\\SeleniumPython.xlsx") # to get the active work sheet sh = wrkbk.active # get the value of row 2 and column 3 c=sh.cell(row=2,column=3) # to set the value in row 2 and column 3 sh.cell(row=2,column=3).value = "Tutorialspoint" # to print the value in console print(sh.cell(row=2,column=3).value) # to print the maximum number of occupied rows in console print(sh.max_row) # to print the maximum number of occupied columns in console print(sh.max_column)
[ { "code": null, "e": 1296, "s": 1062, "text": "We can get the maximum number of occupied rows and columns in a\nworksheet in Selenium. Excel is a spreadsheet which is saved with the .xlsx\nextension. An excel workbook has multiple sheets and each sheet consists of rows\nand columns." }, { "code": null, "e": 1496, "s": 1296, "text": "Out of all the worksheets, while we are accessing a particular sheet that is called as\nan active sheet. Each cell inside a sheet has a unique address which is a combination\nof row and column numbers." }, { "code": null, "e": 1682, "s": 1496, "text": "The column number starts from alphabetic character A and row number starts from\nthe number 1. A cell can contain numerous types of values and they are the main\ncomponent of a worksheet." }, { "code": null, "e": 1892, "s": 1682, "text": "To work with excel in Selenium with python, we need to take help of OpenPyXL\nlibrary. This library is responsible for reading and writing operations on Excel,\nhaving the extensions like xlsx, xlsm, xltm, xltx." }, { "code": null, "e": 2138, "s": 1892, "text": "To install OpenPyXL library, we have to execute the command pip install openpyxl. This is because OpenPyXL does not come by default with python. After this we should import openpyxl in our code and then we should be ready to interact with excel." }, { "code": null, "e": 2430, "s": 2138, "text": "To get the count of the occupied rows in a worksheet, first of all we need to load\nthe entire workbook by specifying the path where it is located. This is achieved with\nload_workbook() method. Next we need to identify the active sheet among all the\nworksheets with the help of active method." }, { "code": null, "e": 2596, "s": 2430, "text": "Finally we need to use the max_row method that gives the count of the number of\noccupied rows. Please note this method is to be used with the worksheet level\nobject." }, { "code": null, "e": 2764, "s": 2596, "text": "And we need to use the max_column method that gives the count of the number\nof occupied columns. Please note this method is to be used with the worksheet\nlevel object." }, { "code": null, "e": 2971, "s": 2764, "text": "wrkbk = load_workbook(\"C:\\\\work\\\\SeleniumPython.xlsx\")\n# to identify the active sheet\nsh = wrkbk.active\n# identify the number of occupied rows\nsh.max_row\n# identify the number of occupied rows\nsh.max_column" }, { "code": null, "e": 3051, "s": 2971, "text": "Coding Implementation to count the maximum number of occupied rows and\ncolumns." }, { "code": null, "e": 3579, "s": 3051, "text": "import openpyxl\n# load excel with its path\nwrkbk = load_workbook(\"C:\\\\work\\\\SeleniumPython.xlsx\")\n# to get the active work sheet\nsh = wrkbk.active\n# get the value of row 2 and column 3\nc=sh.cell(row=2,column=3)\n# to set the value in row 2 and column 3\nsh.cell(row=2,column=3).value = \"Tutorialspoint\"\n# to print the value in console\nprint(sh.cell(row=2,column=3).value)\n# to print the maximum number of occupied rows in console\nprint(sh.max_row)\n# to print the maximum number of occupied columns in console\nprint(sh.max_column)" } ]
Java Program to convert boolean to integer
To convert boolean to integer, let us first declare a variable of boolean primitive. boolean bool = true; Now, to convert it to integer, let us now take an integer variable and return a value “1” for “true” and “0” for “false”. int val = (bool) ? 1 : 0; Let us now see the complete example to convert boolean to integer in Java. Live Demo public class Demo { public static void main(String[] args) { // boolean boolean bool = true; System.out.println("Boolean Value: "+bool); int val = (bool) ? 1 : 0; // Integer System.out.println("Integer value: "+val); } } Boolean Value: true Integer value: 1
[ { "code": null, "e": 1147, "s": 1062, "text": "To convert boolean to integer, let us first declare a variable of boolean primitive." }, { "code": null, "e": 1168, "s": 1147, "text": "boolean bool = true;" }, { "code": null, "e": 1290, "s": 1168, "text": "Now, to convert it to integer, let us now take an integer variable and return a value “1” for “true” and “0” for “false”." }, { "code": null, "e": 1316, "s": 1290, "text": "int val = (bool) ? 1 : 0;" }, { "code": null, "e": 1391, "s": 1316, "text": "Let us now see the complete example to convert boolean to integer in Java." }, { "code": null, "e": 1402, "s": 1391, "text": " Live Demo" }, { "code": null, "e": 1665, "s": 1402, "text": "public class Demo {\n public static void main(String[] args) {\n // boolean\n boolean bool = true;\n System.out.println(\"Boolean Value: \"+bool);\n int val = (bool) ? 1 : 0;\n // Integer\n System.out.println(\"Integer value: \"+val);\n }\n}" }, { "code": null, "e": 1702, "s": 1665, "text": "Boolean Value: true\nInteger value: 1" } ]
Numpy ndarray.flatten() function | Python
22 Apr, 2020 numpy.ndarray.flatten() function return a copy of the array collapsed into one dimension. Syntax : numpy.ndarray.flatten(order=’C’) Parameters :order : [{‘C’, ‘F’, ‘A’, ‘K’}, optional] ‘C’ means to flatten in row-major (C-style) order. ‘F’ means to flatten in column-major (Fortran- style) order. ‘A’ means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise. ‘K’ means to flatten a in the order the elements occur in memory. The default is ‘C’. Return : [ndarray] A copy of the input array, flattened to one dimension. Code #1 : # Python program explaining# numpy.ndarray.flatten() function # importing numpy as geek import numpy as geek arr = geek.array([[5, 6], [7, 8]]) gfg = arr.flatten() print( gfg ) Output : [5 6 7 8] Code #2 : # Python program explaining# numpy.ndarray.flatten() function # importing numpy as geek import numpy as geek arr = geek.array([[5, 6], [7, 8]]) gfg = arr.flatten('F') print( gfg ) Output : [5 6 7 8] Python numpy-ndarray Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 118, "s": 28, "text": "numpy.ndarray.flatten() function return a copy of the array collapsed into one dimension." }, { "code": null, "e": 160, "s": 118, "text": "Syntax : numpy.ndarray.flatten(order=’C’)" }, { "code": null, "e": 519, "s": 160, "text": "Parameters :order : [{‘C’, ‘F’, ‘A’, ‘K’}, optional] ‘C’ means to flatten in row-major (C-style) order. ‘F’ means to flatten in column-major (Fortran- style) order. ‘A’ means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise. ‘K’ means to flatten a in the order the elements occur in memory. The default is ‘C’." }, { "code": null, "e": 593, "s": 519, "text": "Return : [ndarray] A copy of the input array, flattened to one dimension." }, { "code": null, "e": 603, "s": 593, "text": "Code #1 :" }, { "code": "# Python program explaining# numpy.ndarray.flatten() function # importing numpy as geek import numpy as geek arr = geek.array([[5, 6], [7, 8]]) gfg = arr.flatten() print( gfg )", "e": 784, "s": 603, "text": null }, { "code": null, "e": 793, "s": 784, "text": "Output :" }, { "code": null, "e": 804, "s": 793, "text": "[5 6 7 8]\n" }, { "code": null, "e": 815, "s": 804, "text": " Code #2 :" }, { "code": "# Python program explaining# numpy.ndarray.flatten() function # importing numpy as geek import numpy as geek arr = geek.array([[5, 6], [7, 8]]) gfg = arr.flatten('F') print( gfg )", "e": 999, "s": 815, "text": null }, { "code": null, "e": 1008, "s": 999, "text": "Output :" }, { "code": null, "e": 1019, "s": 1008, "text": "[5 6 7 8]\n" }, { "code": null, "e": 1040, "s": 1019, "text": "Python numpy-ndarray" }, { "code": null, "e": 1053, "s": 1040, "text": "Python-numpy" }, { "code": null, "e": 1060, "s": 1053, "text": "Python" } ]
Python Set | difference()
31 May, 2020 The difference between the two sets in Python is equal to the difference between the number of elements in two sets. The function difference() returns a set that is the difference between two sets. Let’s try to find out what will be the difference between two sets A and B. Then (set A – set B) will be the elements present in set A but not in B and (set B – set A) will be the elements present in set B but not in set A.Example: set A = {10, 20, 30, 40, 80} set B = {100, 30, 80, 40, 60} set A - set B = {10, 20} set B - set A = {100, 60} Explanation: A - B is equal to the elements present in A but not in B B - A is equal to the elements present in B but not in A Let’s look at the Venn diagram of the following difference set function. Syntax: set_A.difference(set_B) for (A - B) set _B.difference(set_A) for (B - A) In this program, we will try to find out the difference between two sets set_A and set_B, both the way: # Python code to get the difference between two sets# using difference() between set A and set B # Driver CodeA = {10, 20, 30, 40, 80}B = {100, 30, 80, 40, 60}print (A.difference(B))print (B.difference(A)) {10, 20} {100, 60} We can also use – operator to find the difference between two sets. # Python code to get the difference between two sets# using difference() between set A and set B # Driver CodeA = {10, 20, 30, 40, 80}B = {100, 30, 80, 40, 60}print (A - B)print (B - A) {10, 20} {100, 60} If we have equal sets then it will return the null set. # Python code to get the difference between two sets# using difference() between set A and set B # Driver CodeA = {10, 20, 30, 40, 80}B = {10, 20, 30, 40, 80, 100}print (A - B) set() Akanksha_Rai vishnu_paregi python-set Python python-set Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n31 May, 2020" }, { "code": null, "e": 482, "s": 52, "text": "The difference between the two sets in Python is equal to the difference between the number of elements in two sets. The function difference() returns a set that is the difference between two sets. Let’s try to find out what will be the difference between two sets A and B. Then (set A – set B) will be the elements present in set A but not in B and (set B – set A) will be the elements present in set B but not in set A.Example:" }, { "code": null, "e": 735, "s": 482, "text": "set A = {10, 20, 30, 40, 80}\nset B = {100, 30, 80, 40, 60}\n\nset A - set B = {10, 20}\nset B - set A = {100, 60}\n\nExplanation: A - B is equal to the elements present in A but not in B\n B - A is equal to the elements present in B but not in A\n" }, { "code": null, "e": 808, "s": 735, "text": "Let’s look at the Venn diagram of the following difference set function." }, { "code": null, "e": 816, "s": 808, "text": "Syntax:" }, { "code": null, "e": 890, "s": 816, "text": "set_A.difference(set_B) for (A - B)\nset _B.difference(set_A) for (B - A)\n" }, { "code": null, "e": 994, "s": 890, "text": "In this program, we will try to find out the difference between two sets set_A and set_B, both the way:" }, { "code": "# Python code to get the difference between two sets# using difference() between set A and set B # Driver CodeA = {10, 20, 30, 40, 80}B = {100, 30, 80, 40, 60}print (A.difference(B))print (B.difference(A))", "e": 1201, "s": 994, "text": null }, { "code": null, "e": 1221, "s": 1201, "text": "{10, 20}\n{100, 60}\n" }, { "code": null, "e": 1289, "s": 1221, "text": "We can also use – operator to find the difference between two sets." }, { "code": "# Python code to get the difference between two sets# using difference() between set A and set B # Driver CodeA = {10, 20, 30, 40, 80}B = {100, 30, 80, 40, 60}print (A - B)print (B - A)", "e": 1476, "s": 1289, "text": null }, { "code": null, "e": 1496, "s": 1476, "text": "{10, 20}\n{100, 60}\n" }, { "code": null, "e": 1552, "s": 1496, "text": "If we have equal sets then it will return the null set." }, { "code": "# Python code to get the difference between two sets# using difference() between set A and set B # Driver CodeA = {10, 20, 30, 40, 80}B = {10, 20, 30, 40, 80, 100}print (A - B)", "e": 1730, "s": 1552, "text": null }, { "code": null, "e": 1737, "s": 1730, "text": "set()\n" }, { "code": null, "e": 1750, "s": 1737, "text": "Akanksha_Rai" }, { "code": null, "e": 1764, "s": 1750, "text": "vishnu_paregi" }, { "code": null, "e": 1775, "s": 1764, "text": "python-set" }, { "code": null, "e": 1782, "s": 1775, "text": "Python" }, { "code": null, "e": 1793, "s": 1782, "text": "python-set" } ]
HTML | <th> bgcolor Attribute
26 Jun, 2019 The HTML <th> bgcolor Attribute is used to specify the background color of a table header cell. It is not supported by HTML 5. Syntax: <th bgcolor="color_name | hex_number | rgb_number"> Attribute Values: color_name: It sets the background color by using the color name. For example “red”. hex_number: It sets the background color by using the color hex code. For example “#0000ff”. rgb_number: It sets the background color by using the rgb code. For example: “RGB(0, 153, 0)” . Example: <!DOCTYPE html><html> <head> <title> HTML th bgcolor Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML th bgcolor Attribute</h2> <table width="500" border="1"> <tr> <th bgcolor="green">Name</th> <th bgcolor="yellow">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 <th> bgcolor attribute are listed below: Google Chrome Internet Explorer Firefox Safari Opera HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Jun, 2019" }, { "code": null, "e": 155, "s": 28, "text": "The HTML <th> bgcolor Attribute is used to specify the background color of a table header cell. It is not supported by HTML 5." }, { "code": null, "e": 163, "s": 155, "text": "Syntax:" }, { "code": null, "e": 215, "s": 163, "text": "<th bgcolor=\"color_name | hex_number | rgb_number\">" }, { "code": null, "e": 233, "s": 215, "text": "Attribute Values:" }, { "code": null, "e": 318, "s": 233, "text": "color_name: It sets the background color by using the color name. For example “red”." }, { "code": null, "e": 411, "s": 318, "text": "hex_number: It sets the background color by using the color hex code. For example “#0000ff”." }, { "code": null, "e": 507, "s": 411, "text": "rgb_number: It sets the background color by using the rgb code. For example: “RGB(0, 153, 0)” ." }, { "code": null, "e": 516, "s": 507, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML th bgcolor Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML th bgcolor Attribute</h2> <table width=\"500\" border=\"1\"> <tr> <th bgcolor=\"green\">Name</th> <th bgcolor=\"yellow\">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": 1018, "s": 516, "text": null }, { "code": null, "e": 1026, "s": 1018, "text": "Output:" }, { "code": null, "e": 1117, "s": 1026, "text": "Supported Browsers: The browser supported by HTML <th> bgcolor attribute are listed below:" }, { "code": null, "e": 1131, "s": 1117, "text": "Google Chrome" }, { "code": null, "e": 1149, "s": 1131, "text": "Internet Explorer" }, { "code": null, "e": 1157, "s": 1149, "text": "Firefox" }, { "code": null, "e": 1164, "s": 1157, "text": "Safari" }, { "code": null, "e": 1170, "s": 1164, "text": "Opera" }, { "code": null, "e": 1186, "s": 1170, "text": "HTML-Attributes" }, { "code": null, "e": 1191, "s": 1186, "text": "HTML" }, { "code": null, "e": 1208, "s": 1191, "text": "Web Technologies" }, { "code": null, "e": 1213, "s": 1208, "text": "HTML" } ]
Priority Queue using Binary Heap
29 Oct, 2021 Priority Queue is an extension of the queue with the following properties: Every item has a priority associated with it.An element with high priority is dequeued before an element with low priority.If two elements have the same priority, they are served according to their order in the queue. Every item has a priority associated with it. An element with high priority is dequeued before an element with low priority. If two elements have the same priority, they are served according to their order in the queue. A Binary Heap is a Binary Tree with the following properties: It is a Complete Tree. This property of Binary Heap makes them suitable to be stored in an array.A Binary Heap is either Min Heap or Max Heap.In a Min Binary Heap, the key at the root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree.Similarly, in a Max Binary Heap, the key at the root must be maximum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree. It is a Complete Tree. This property of Binary Heap makes them suitable to be stored in an array. A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at the root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree. Similarly, in a Max Binary Heap, the key at the root must be maximum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree. insert(p): Inserts a new element with priority p. extractMax(): Extracts an element with maximum priority. remove(i): Removes an element pointed by an iterator i. getMax(): Returns an element with maximum priority. changePriority(i, p): Changes the priority of an element pointed by i to p. Suppose below is the given Binary Heap that follows all the properties of Binary Max Heap. Now a node with value 32 need to be insert in the above heap: To insert an element, attach the new element to any leaf. For Example A node with priority 32 can be added to the leaf of the node 11. But this violates the heap property. To maintain the heap property, shift up the new node 32. Shift Up Operation get node with 32 at the correct position: Swap the incorrectly placed node with its parent until the heap property is satisfied. For Example: As node 11 is less than node 32 so, swap node 11 and node 32. Then, swap node 14 and node 32. And at last, swap node 31 and node 32. ExtractMax: The maximum value is stored at the root of the tree. But the root of the tree cannot be directly removed. First, it is replaced with any one of the leaves and then removed. For Example: To remove Node 45, it is first replaced with node 11. But this violates the heap property, so move the replaced node down. For that, use shift down operation. ShiftDown operation: Swap the incorrectly placed node with a larger child until the heap property is satisfied. For Example: Node 11 is swapped with node 32 then, with node 31 and in last it is swapped with node 14. ChangePriority: Let the changed element shift up or down depending on whether its priority decreased or increased. For Example: Change the priority of nodes 11 to 35, due to this change the node has to shift up the node in order to maintain the heap property. Remove: To remove an element, change its priority to a value larger than the current maximum, then shift it up, and then extract it using extract max. Find the current maximum using getMax. GetMax: The max value is stored at the root of the tree. To getmax, just return the value at the root of the tree. Since the heap is maintained in form of a complete binary tree, because of this fact the heap can be represented in the form of an array. To keep the tree complete and shallow, while inserting a new element insert it in the leftmost vacant position in the last level i.e., at the end of our array. Similarly, while extracting maximum replace the root with the last leaf at the last level i.e., the last element of the array. Below is the illustration of the same: Below is the program to implement Priority Queue using Binary Heap: C++ Java Python3 C# Javascript // C++ code to implement priority-queue// using array implementation of// binary heap #include <bits/stdc++.h>using namespace std; int H[50];int size = -1; // Function to return the index of the// parent node of a given nodeint parent(int i){ return (i - 1) / 2;} // Function to return the index of the// left child of the given nodeint leftChild(int i){ return ((2 * i) + 1);} // Function to return the index of the// right child of the given nodeint rightChild(int i){ return ((2 * i) + 2);} // Function to shift up the node in order// to maintain the heap propertyvoid shiftUp(int i){ while (i > 0 && H[parent(i)] < H[i]) { // Swap parent and current node swap(H[parent(i)], H[i]); // Update i to parent of i i = parent(i); }} // Function to shift down the node in// order to maintain the heap propertyvoid shiftDown(int i){ int maxIndex = i; // Left Child int l = leftChild(i); if (l <= size && H[l] > H[maxIndex]) { maxIndex = l; } // Right Child int r = rightChild(i); if (r <= size && H[r] > H[maxIndex]) { maxIndex = r; } // If i not same as maxIndex if (i != maxIndex) { swap(H[i], H[maxIndex]); shiftDown(maxIndex); }} // Function to insert a new element// in the Binary Heapvoid insert(int p){ size = size + 1; H[size] = p; // Shift Up to maintain heap property shiftUp(size);} // Function to extract the element with// maximum priorityint extractMax(){ int result = H[0]; // Replace the value at the root // with the last leaf H[0] = H[size]; size = size - 1; // Shift down the replaced element // to maintain the heap property shiftDown(0); return result;} // Function to change the priority// of an elementvoid changePriority(int i, int p){ int oldp = H[i]; H[i] = p; if (p > oldp) { shiftUp(i); } else { shiftDown(i); }} // Function to get value of the current// maximum elementint getMax(){ return H[0];} // Function to remove the element// located at given indexvoid remove(int i){ H[i] = getMax() + 1; // Shift the node to the root // of the heap shiftUp(i); // Extract the node extractMax();} // Driver Codeint main(){ /* 45 / \ 31 14 / \ / \ 13 20 7 11 / \ 12 7 Create a priority queue shown in example in a binary max heap form. Queue will be represented in the form of array as: 45 31 14 13 20 7 11 12 7 */ // Insert the element to the // priority queue insert(45); insert(20); insert(14); insert(12); insert(31); insert(7); insert(11); insert(13); insert(7); int i = 0; // Priority queue before extracting max cout << "Priority Queue : "; while (i <= size) { cout << H[i] << " "; i++; } cout << "\n"; // Node with maximum priority cout << "Node with maximum priority : " << extractMax() << "\n"; // Priority queue after extracting max cout << "Priority queue after " << "extracting maximum : "; int j = 0; while (j <= size) { cout << H[j] << " "; j++; } cout << "\n"; // Change the priority of element // present at index 2 to 49 changePriority(2, 49); cout << "Priority queue after " << "priority change : "; int k = 0; while (k <= size) { cout << H[k] << " "; k++; } cout << "\n"; // Remove element at index 3 remove(3); cout << "Priority queue after " << "removing the element : "; int l = 0; while (l <= size) { cout << H[l] << " "; l++; } return 0;} // Java code to implement// priority-queue using// array implementation of// binary heapimport java.util.*;class GFG{ static int []H = new int[50];static int size = -1; // Function to return the index of the// parent node of a given nodestatic int parent(int i){ return (i - 1) / 2;} // Function to return the index of the// left child of the given nodestatic int leftChild(int i){ return ((2 * i) + 1);} // Function to return the index of the// right child of the given nodestatic int rightChild(int i){ return ((2 * i) + 2);} // Function to shift up the// node in order to maintain// the heap propertystatic void shiftUp(int i){ while (i > 0 && H[parent(i)] < H[i]) { // Swap parent and current node swap(parent(i), i); // Update i to parent of i i = parent(i); }} // Function to shift down the node in// order to maintain the heap propertystatic void shiftDown(int i){ int maxIndex = i; // Left Child int l = leftChild(i); if (l <= size && H[l] > H[maxIndex]) { maxIndex = l; } // Right Child int r = rightChild(i); if (r <= size && H[r] > H[maxIndex]) { maxIndex = r; } // If i not same as maxIndex if (i != maxIndex) { swap(i, maxIndex); shiftDown(maxIndex); }} // Function to insert a// new element in// the Binary Heapstatic void insert(int p){ size = size + 1; H[size] = p; // Shift Up to maintain // heap property shiftUp(size);} // Function to extract// the element with// maximum prioritystatic int extractMax(){ int result = H[0]; // Replace the value // at the root with // the last leaf H[0] = H[size]; size = size - 1; // Shift down the replaced // element to maintain the // heap property shiftDown(0); return result;} // Function to change the priority// of an elementstatic void changePriority(int i, int p){ int oldp = H[i]; H[i] = p; if (p > oldp) { shiftUp(i); } else { shiftDown(i); }} // Function to get value of// the current maximum elementstatic int getMax(){ return H[0];} // Function to remove the element// located at given indexstatic void remove(int i){ H[i] = getMax() + 1; // Shift the node to the root // of the heap shiftUp(i); // Extract the node extractMax();} static void swap(int i, int j){ int temp= H[i]; H[i] = H[j]; H[j] = temp;} // Driver Codepublic static void main(String[] args){ /* 45 / \ 31 14 / \ / \ 13 20 7 11 / \ 12 7 Create a priority queue shown in example in a binary max heap form. Queue will be represented in the form of array as: 45 31 14 13 20 7 11 12 7 */ // Insert the element to the // priority queue insert(45); insert(20); insert(14); insert(12); insert(31); insert(7); insert(11); insert(13); insert(7); int i = 0; // Priority queue before extracting max System.out.print("Priority Queue : "); while (i <= size) { System.out.print(H[i] + " "); i++; } System.out.print("\n"); // Node with maximum priority System.out.print("Node with maximum priority : " + extractMax() + "\n"); // Priority queue after extracting max System.out.print("Priority queue after " + "extracting maximum : "); int j = 0; while (j <= size) { System.out.print(H[j] + " "); j++; } System.out.print("\n"); // Change the priority of element // present at index 2 to 49 changePriority(2, 49); System.out.print("Priority queue after " + "priority change : "); int k = 0; while (k <= size) { System.out.print(H[k] + " "); k++; } System.out.print("\n"); // Remove element at index 3 remove(3); System.out.print("Priority queue after " + "removing the element : "); int l = 0; while (l <= size) { System.out.print(H[l] + " "); l++; }}} // This code is contributed by 29AjayKumar # Python3 code to implement priority-queue# using array implementation of# binary heap H = [0]*50size = -1 # Function to return the index of the# parent node of a given nodedef parent(i) : return (i - 1) // 2 # Function to return the index of the# left child of the given nodedef leftChild(i) : return ((2 * i) + 1) # Function to return the index of the# right child of the given nodedef rightChild(i) : return ((2 * i) + 2) # Function to shift up the # node in order to maintain # the heap propertydef shiftUp(i) : while (i > 0 and H[parent(i)] < H[i]) : # Swap parent and current node swap(parent(i), i) # Update i to parent of i i = parent(i) # Function to shift down the node in# order to maintain the heap propertydef shiftDown(i) : maxIndex = i # Left Child l = leftChild(i) if (l <= size and H[l] > H[maxIndex]) : maxIndex = l # Right Child r = rightChild(i) if (r <= size and H[r] > H[maxIndex]) : maxIndex = r # If i not same as maxIndex if (i != maxIndex) : swap(i, maxIndex) shiftDown(maxIndex) # Function to insert a # new element in # the Binary Heapdef insert(p) : global size size = size + 1 H[size] = p # Shift Up to maintain # heap property shiftUp(size) # Function to extract # the element with# maximum prioritydef extractMax() : global size result = H[0] # Replace the value # at the root with # the last leaf H[0] = H[size] size = size - 1 # Shift down the replaced # element to maintain the # heap property shiftDown(0) return result # Function to change the priority# of an elementdef changePriority(i,p) : oldp = H[i] H[i] = p if (p > oldp) : shiftUp(i) else : shiftDown(i) # Function to get value of # the current maximum elementdef getMax() : return H[0] # Function to remove the element# located at given indexdef Remove(i) : H[i] = getMax() + 1 # Shift the node to the root # of the heap shiftUp(i) # Extract the node extractMax() def swap(i, j) : temp = H[i] H[i] = H[j] H[j] = temp # Insert the element to the# priority queueinsert(45)insert(20)insert(14)insert(12)insert(31)insert(7)insert(11)insert(13)insert(7) i = 0 # Priority queue before extracting maxprint("Priority Queue : ", end = "")while (i <= size) : print(H[i], end = " ") i += 1 print() # Node with maximum priorityprint("Node with maximum priority :" , extractMax()) # Priority queue after extracting maxprint("Priority queue after extracting maximum : ", end = "")j = 0while (j <= size) : print(H[j], end = " ") j += 1 print() # Change the priority of element# present at index 2 to 49changePriority(2, 49)print("Priority queue after priority change : ", end = "")k = 0while (k <= size) : print(H[k], end = " ") k += 1 print() # Remove element at index 3Remove(3)print("Priority queue after removing the element : ", end = "")l = 0while (l <= size) : print(H[l], end = " ") l += 1 # This code is contributed by divyeshrabadiya07. // C# code to implement priority-queue// using array implementation of// binary heapusing System; class GFG{ static int []H = new int[50];static int size = -1; // Function to return the index of the// parent node of a given nodestatic int parent(int i){ return (i - 1) / 2;} // Function to return the index of the// left child of the given nodestatic int leftChild(int i){ return ((2 * i) + 1);} // Function to return the index of the// right child of the given nodestatic int rightChild(int i){ return ((2 * i) + 2);} // Function to shift up the// node in order to maintain// the heap propertystatic void shiftUp(int i){ while (i > 0 && H[parent(i)] < H[i]) { // Swap parent and current node swap(parent(i), i); // Update i to parent of i i = parent(i); }} // Function to shift down the node in// order to maintain the heap propertystatic void shiftDown(int i){ int maxIndex = i; // Left Child int l = leftChild(i); if (l <= size && H[l] > H[maxIndex]) { maxIndex = l; } // Right Child int r = rightChild(i); if (r <= size && H[r] > H[maxIndex]) { maxIndex = r; } // If i not same as maxIndex if (i != maxIndex) { swap(i, maxIndex); shiftDown(maxIndex); }} // Function to insert a// new element in// the Binary Heapstatic void insert(int p){ size = size + 1; H[size] = p; // Shift Up to maintain // heap property shiftUp(size);} // Function to extract// the element with// maximum prioritystatic int extractMax(){ int result = H[0]; // Replace the value // at the root with // the last leaf H[0] = H[size]; size = size - 1; // Shift down the replaced // element to maintain the // heap property shiftDown(0); return result;} // Function to change the priority// of an elementstatic void changePriority(int i, int p){ int oldp = H[i]; H[i] = p; if (p > oldp) { shiftUp(i); } else { shiftDown(i); }} // Function to get value of// the current maximum elementstatic int getMax(){ return H[0];} // Function to remove the element// located at given indexstatic void Remove(int i){ H[i] = getMax() + 1; // Shift the node to the root // of the heap shiftUp(i); // Extract the node extractMax();} static void swap(int i, int j){ int temp = H[i]; H[i] = H[j]; H[j] = temp;} // Driver Codepublic static void Main(String[] args){ /* 45 / \ 31 14 / \ / \ 13 20 7 11 / \ 12 7 Create a priority queue shown in example in a binary max heap form. Queue will be represented in the form of array as: 45 31 14 13 20 7 11 12 7 */ // Insert the element to the // priority queue insert(45); insert(20); insert(14); insert(12); insert(31); insert(7); insert(11); insert(13); insert(7); int i = 0; // Priority queue before extracting max Console.Write("Priority Queue : "); while (i <= size) { Console.Write(H[i] + " "); i++; } Console.Write("\n"); // Node with maximum priority Console.Write("Node with maximum priority : " + extractMax() + "\n"); // Priority queue after extracting max Console.Write("Priority queue after " + "extracting maximum : "); int j = 0; while (j <= size) { Console.Write(H[j] + " "); j++; } Console.Write("\n"); // Change the priority of element // present at index 2 to 49 changePriority(2, 49); Console.Write("Priority queue after " + "priority change : "); int k = 0; while (k <= size) { Console.Write(H[k] + " "); k++; } Console.Write("\n"); // Remove element at index 3 Remove(3); Console.Write("Priority queue after " + "removing the element : "); int l = 0; while (l <= size) { Console.Write(H[l] + " "); l++; }}} // This code is contributed by Amit Katiyar <script> // Javascript code to implement priority-queue// using array implementation of// binary heap var H = Array(50).fill(0);var size = -1; // Function to return the index of the// parent node of a given nodefunction parent(i){ return parseInt((i - 1) / 2);} // Function to return the index of the// left child of the given nodefunction leftChild(i){ return parseInt((2 * i) + 1);} // Function to return the index of the// right child of the given nodefunction rightChild(i){ return parseInt((2 * i) + 2);} // Function to shift up the node in order// to maintain the heap propertyfunction shiftUp( i){ while (i > 0 && H[parent(i)] < H[i]) { // Swap parent and current node swap(parent(i), i); // Update i to parent of i i = parent(i); }} function swap(i, j){ var temp = H[i]; H[i] = H[j]; H[j] = temp;} // Function to shift down the node in// order to maintain the heap propertyfunction shiftDown( i){ var maxIndex = i; // Left Child var l = leftChild(i); if (l <= size && H[l] > H[maxIndex]) { maxIndex = l; } // Right Child var r = rightChild(i); if (r <= size && H[r] > H[maxIndex]) { maxIndex = r; } // If i not same as maxIndex if (i != maxIndex) { swap(i, maxIndex); shiftDown(maxIndex); }} // Function to insert a new element// in the Binary Heapfunction insert( p){ size = size + 1; H[size] = p; // Shift Up to maintain heap property shiftUp(size);} // Function to extract the element with// maximum priorityfunction extractMax(){ var result = H[0]; // Replace the value at the root // with the last leaf H[0] = H[size]; size = size - 1; // Shift down the replaced element // to maintain the heap property shiftDown(0); return result;} // Function to change the priority// of an elementfunction changePriority(i, p){ var oldp = H[i]; H[i] = p; if (p > oldp) { shiftUp(i); } else { shiftDown(i); }} // Function to get value of the current// maximum elementfunction getMax(){ return H[0];} // Function to remove the element// located at given indexfunction remove(i){ H[i] = getMax() + 1; // Shift the node to the root // of the heap shiftUp(i); // Extract the node extractMax();} // Driver Code/* 45 / \ 31 14 / \ / \ 13 20 7 11 / \ 12 7Create a priority queue shown inexample in a binary max heap form.Queue will be represented in theform of array as:45 31 14 13 20 7 11 12 7 */// Insert the element to the// priority queueinsert(45);insert(20);insert(14);insert(12);insert(31);insert(7);insert(11);insert(13);insert(7);var i = 0;// Priority queue before extracting maxdocument.write( "Priority Queue : ");while (i <= size) { document.write( H[i] + " "); i++;}document.write( "<br>");// Node with maximum prioritydocument.write( "Node with maximum priority : " + extractMax() + "<br>");// Priority queue after extracting maxdocument.write( "Priority queue after " + "extracting maximum : ");var j = 0;while (j <= size) { document.write( H[j] + " "); j++;}document.write( "<br>"); // Change the priority of element// present at index 2 to 49changePriority(2, 49);document.write( "Priority queue after " + "priority change : ");var k = 0;while (k <= size) { document.write( H[k] + " "); k++;}document.write( "<br>"); // Remove element at index 3remove(3);document.write( "Priority queue after " + "removing the element : ");var l = 0;while (l <= size) { document.write( H[l] + " "); l++;} // This code is contributed by noob2000.</script> Priority Queue : 45 31 14 13 20 7 11 12 7 Node with maximum priority : 45 Priority queue after extracting maximum : 31 20 14 13 7 7 11 12 Priority queue after priority change : 49 20 31 13 7 7 11 12 Priority queue after removing the element : 49 20 31 12 7 7 11 Time Complexity: The time complexity of all the operation is O(log N) except for GetMax() which has time complexity of O(1). Auxiliary Space: O(N) 29AjayKumar amit143katiyar divyeshrabadiya07 noob2000 cpp-priority-queue Data Structures-Heap min-heap priority-queue Arrays Data Structures Heap Data Structures Arrays Heap priority-queue Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Oct, 2021" }, { "code": null, "e": 131, "s": 54, "text": "Priority Queue is an extension of the queue with the following properties: " }, { "code": null, "e": 349, "s": 131, "text": "Every item has a priority associated with it.An element with high priority is dequeued before an element with low priority.If two elements have the same priority, they are served according to their order in the queue." }, { "code": null, "e": 395, "s": 349, "text": "Every item has a priority associated with it." }, { "code": null, "e": 474, "s": 395, "text": "An element with high priority is dequeued before an element with low priority." }, { "code": null, "e": 569, "s": 474, "text": "If two elements have the same priority, they are served according to their order in the queue." }, { "code": null, "e": 633, "s": 569, "text": "A Binary Heap is a Binary Tree with the following properties: " }, { "code": null, "e": 1125, "s": 633, "text": "It is a Complete Tree. This property of Binary Heap makes them suitable to be stored in an array.A Binary Heap is either Min Heap or Max Heap.In a Min Binary Heap, the key at the root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree.Similarly, in a Max Binary Heap, the key at the root must be maximum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree." }, { "code": null, "e": 1223, "s": 1125, "text": "It is a Complete Tree. This property of Binary Heap makes them suitable to be stored in an array." }, { "code": null, "e": 1269, "s": 1223, "text": "A Binary Heap is either Min Heap or Max Heap." }, { "code": null, "e": 1439, "s": 1269, "text": "In a Min Binary Heap, the key at the root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree." }, { "code": null, "e": 1620, "s": 1439, "text": "Similarly, in a Max Binary Heap, the key at the root must be maximum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree." }, { "code": null, "e": 1670, "s": 1620, "text": "insert(p): Inserts a new element with priority p." }, { "code": null, "e": 1727, "s": 1670, "text": "extractMax(): Extracts an element with maximum priority." }, { "code": null, "e": 1783, "s": 1727, "text": "remove(i): Removes an element pointed by an iterator i." }, { "code": null, "e": 1835, "s": 1783, "text": "getMax(): Returns an element with maximum priority." }, { "code": null, "e": 1911, "s": 1835, "text": "changePriority(i, p): Changes the priority of an element pointed by i to p." }, { "code": null, "e": 2004, "s": 1911, "text": "Suppose below is the given Binary Heap that follows all the properties of Binary Max Heap. " }, { "code": null, "e": 2297, "s": 2004, "text": "Now a node with value 32 need to be insert in the above heap: To insert an element, attach the new element to any leaf. For Example A node with priority 32 can be added to the leaf of the node 11. But this violates the heap property. To maintain the heap property, shift up the new node 32. " }, { "code": null, "e": 2593, "s": 2297, "text": "Shift Up Operation get node with 32 at the correct position: Swap the incorrectly placed node with its parent until the heap property is satisfied. For Example: As node 11 is less than node 32 so, swap node 11 and node 32. Then, swap node 14 and node 32. And at last, swap node 31 and node 32. " }, { "code": null, "e": 2952, "s": 2593, "text": "ExtractMax: The maximum value is stored at the root of the tree. But the root of the tree cannot be directly removed. First, it is replaced with any one of the leaves and then removed. For Example: To remove Node 45, it is first replaced with node 11. But this violates the heap property, so move the replaced node down. For that, use shift down operation. " }, { "code": null, "e": 3170, "s": 2952, "text": "ShiftDown operation: Swap the incorrectly placed node with a larger child until the heap property is satisfied. For Example: Node 11 is swapped with node 32 then, with node 31 and in last it is swapped with node 14. " }, { "code": null, "e": 3430, "s": 3170, "text": "ChangePriority: Let the changed element shift up or down depending on whether its priority decreased or increased. For Example: Change the priority of nodes 11 to 35, due to this change the node has to shift up the node in order to maintain the heap property." }, { "code": null, "e": 3620, "s": 3430, "text": "Remove: To remove an element, change its priority to a value larger than the current maximum, then shift it up, and then extract it using extract max. Find the current maximum using getMax." }, { "code": null, "e": 3735, "s": 3620, "text": "GetMax: The max value is stored at the root of the tree. To getmax, just return the value at the root of the tree." }, { "code": null, "e": 4201, "s": 3735, "text": "Since the heap is maintained in form of a complete binary tree, because of this fact the heap can be represented in the form of an array. To keep the tree complete and shallow, while inserting a new element insert it in the leftmost vacant position in the last level i.e., at the end of our array. Similarly, while extracting maximum replace the root with the last leaf at the last level i.e., the last element of the array. Below is the illustration of the same: " }, { "code": null, "e": 4270, "s": 4201, "text": "Below is the program to implement Priority Queue using Binary Heap: " }, { "code": null, "e": 4274, "s": 4270, "text": "C++" }, { "code": null, "e": 4279, "s": 4274, "text": "Java" }, { "code": null, "e": 4287, "s": 4279, "text": "Python3" }, { "code": null, "e": 4290, "s": 4287, "text": "C#" }, { "code": null, "e": 4301, "s": 4290, "text": "Javascript" }, { "code": "// C++ code to implement priority-queue// using array implementation of// binary heap #include <bits/stdc++.h>using namespace std; int H[50];int size = -1; // Function to return the index of the// parent node of a given nodeint parent(int i){ return (i - 1) / 2;} // Function to return the index of the// left child of the given nodeint leftChild(int i){ return ((2 * i) + 1);} // Function to return the index of the// right child of the given nodeint rightChild(int i){ return ((2 * i) + 2);} // Function to shift up the node in order// to maintain the heap propertyvoid shiftUp(int i){ while (i > 0 && H[parent(i)] < H[i]) { // Swap parent and current node swap(H[parent(i)], H[i]); // Update i to parent of i i = parent(i); }} // Function to shift down the node in// order to maintain the heap propertyvoid shiftDown(int i){ int maxIndex = i; // Left Child int l = leftChild(i); if (l <= size && H[l] > H[maxIndex]) { maxIndex = l; } // Right Child int r = rightChild(i); if (r <= size && H[r] > H[maxIndex]) { maxIndex = r; } // If i not same as maxIndex if (i != maxIndex) { swap(H[i], H[maxIndex]); shiftDown(maxIndex); }} // Function to insert a new element// in the Binary Heapvoid insert(int p){ size = size + 1; H[size] = p; // Shift Up to maintain heap property shiftUp(size);} // Function to extract the element with// maximum priorityint extractMax(){ int result = H[0]; // Replace the value at the root // with the last leaf H[0] = H[size]; size = size - 1; // Shift down the replaced element // to maintain the heap property shiftDown(0); return result;} // Function to change the priority// of an elementvoid changePriority(int i, int p){ int oldp = H[i]; H[i] = p; if (p > oldp) { shiftUp(i); } else { shiftDown(i); }} // Function to get value of the current// maximum elementint getMax(){ return H[0];} // Function to remove the element// located at given indexvoid remove(int i){ H[i] = getMax() + 1; // Shift the node to the root // of the heap shiftUp(i); // Extract the node extractMax();} // Driver Codeint main(){ /* 45 / \\ 31 14 / \\ / \\ 13 20 7 11 / \\ 12 7 Create a priority queue shown in example in a binary max heap form. Queue will be represented in the form of array as: 45 31 14 13 20 7 11 12 7 */ // Insert the element to the // priority queue insert(45); insert(20); insert(14); insert(12); insert(31); insert(7); insert(11); insert(13); insert(7); int i = 0; // Priority queue before extracting max cout << \"Priority Queue : \"; while (i <= size) { cout << H[i] << \" \"; i++; } cout << \"\\n\"; // Node with maximum priority cout << \"Node with maximum priority : \" << extractMax() << \"\\n\"; // Priority queue after extracting max cout << \"Priority queue after \" << \"extracting maximum : \"; int j = 0; while (j <= size) { cout << H[j] << \" \"; j++; } cout << \"\\n\"; // Change the priority of element // present at index 2 to 49 changePriority(2, 49); cout << \"Priority queue after \" << \"priority change : \"; int k = 0; while (k <= size) { cout << H[k] << \" \"; k++; } cout << \"\\n\"; // Remove element at index 3 remove(3); cout << \"Priority queue after \" << \"removing the element : \"; int l = 0; while (l <= size) { cout << H[l] << \" \"; l++; } return 0;}", "e": 8013, "s": 4301, "text": null }, { "code": "// Java code to implement// priority-queue using// array implementation of// binary heapimport java.util.*;class GFG{ static int []H = new int[50];static int size = -1; // Function to return the index of the// parent node of a given nodestatic int parent(int i){ return (i - 1) / 2;} // Function to return the index of the// left child of the given nodestatic int leftChild(int i){ return ((2 * i) + 1);} // Function to return the index of the// right child of the given nodestatic int rightChild(int i){ return ((2 * i) + 2);} // Function to shift up the// node in order to maintain// the heap propertystatic void shiftUp(int i){ while (i > 0 && H[parent(i)] < H[i]) { // Swap parent and current node swap(parent(i), i); // Update i to parent of i i = parent(i); }} // Function to shift down the node in// order to maintain the heap propertystatic void shiftDown(int i){ int maxIndex = i; // Left Child int l = leftChild(i); if (l <= size && H[l] > H[maxIndex]) { maxIndex = l; } // Right Child int r = rightChild(i); if (r <= size && H[r] > H[maxIndex]) { maxIndex = r; } // If i not same as maxIndex if (i != maxIndex) { swap(i, maxIndex); shiftDown(maxIndex); }} // Function to insert a// new element in// the Binary Heapstatic void insert(int p){ size = size + 1; H[size] = p; // Shift Up to maintain // heap property shiftUp(size);} // Function to extract// the element with// maximum prioritystatic int extractMax(){ int result = H[0]; // Replace the value // at the root with // the last leaf H[0] = H[size]; size = size - 1; // Shift down the replaced // element to maintain the // heap property shiftDown(0); return result;} // Function to change the priority// of an elementstatic void changePriority(int i, int p){ int oldp = H[i]; H[i] = p; if (p > oldp) { shiftUp(i); } else { shiftDown(i); }} // Function to get value of// the current maximum elementstatic int getMax(){ return H[0];} // Function to remove the element// located at given indexstatic void remove(int i){ H[i] = getMax() + 1; // Shift the node to the root // of the heap shiftUp(i); // Extract the node extractMax();} static void swap(int i, int j){ int temp= H[i]; H[i] = H[j]; H[j] = temp;} // Driver Codepublic static void main(String[] args){ /* 45 / \\ 31 14 / \\ / \\ 13 20 7 11 / \\ 12 7 Create a priority queue shown in example in a binary max heap form. Queue will be represented in the form of array as: 45 31 14 13 20 7 11 12 7 */ // Insert the element to the // priority queue insert(45); insert(20); insert(14); insert(12); insert(31); insert(7); insert(11); insert(13); insert(7); int i = 0; // Priority queue before extracting max System.out.print(\"Priority Queue : \"); while (i <= size) { System.out.print(H[i] + \" \"); i++; } System.out.print(\"\\n\"); // Node with maximum priority System.out.print(\"Node with maximum priority : \" + extractMax() + \"\\n\"); // Priority queue after extracting max System.out.print(\"Priority queue after \" + \"extracting maximum : \"); int j = 0; while (j <= size) { System.out.print(H[j] + \" \"); j++; } System.out.print(\"\\n\"); // Change the priority of element // present at index 2 to 49 changePriority(2, 49); System.out.print(\"Priority queue after \" + \"priority change : \"); int k = 0; while (k <= size) { System.out.print(H[k] + \" \"); k++; } System.out.print(\"\\n\"); // Remove element at index 3 remove(3); System.out.print(\"Priority queue after \" + \"removing the element : \"); int l = 0; while (l <= size) { System.out.print(H[l] + \" \"); l++; }}} // This code is contributed by 29AjayKumar", "e": 11920, "s": 8013, "text": null }, { "code": "# Python3 code to implement priority-queue# using array implementation of# binary heap H = [0]*50size = -1 # Function to return the index of the# parent node of a given nodedef parent(i) : return (i - 1) // 2 # Function to return the index of the# left child of the given nodedef leftChild(i) : return ((2 * i) + 1) # Function to return the index of the# right child of the given nodedef rightChild(i) : return ((2 * i) + 2) # Function to shift up the # node in order to maintain # the heap propertydef shiftUp(i) : while (i > 0 and H[parent(i)] < H[i]) : # Swap parent and current node swap(parent(i), i) # Update i to parent of i i = parent(i) # Function to shift down the node in# order to maintain the heap propertydef shiftDown(i) : maxIndex = i # Left Child l = leftChild(i) if (l <= size and H[l] > H[maxIndex]) : maxIndex = l # Right Child r = rightChild(i) if (r <= size and H[r] > H[maxIndex]) : maxIndex = r # If i not same as maxIndex if (i != maxIndex) : swap(i, maxIndex) shiftDown(maxIndex) # Function to insert a # new element in # the Binary Heapdef insert(p) : global size size = size + 1 H[size] = p # Shift Up to maintain # heap property shiftUp(size) # Function to extract # the element with# maximum prioritydef extractMax() : global size result = H[0] # Replace the value # at the root with # the last leaf H[0] = H[size] size = size - 1 # Shift down the replaced # element to maintain the # heap property shiftDown(0) return result # Function to change the priority# of an elementdef changePriority(i,p) : oldp = H[i] H[i] = p if (p > oldp) : shiftUp(i) else : shiftDown(i) # Function to get value of # the current maximum elementdef getMax() : return H[0] # Function to remove the element# located at given indexdef Remove(i) : H[i] = getMax() + 1 # Shift the node to the root # of the heap shiftUp(i) # Extract the node extractMax() def swap(i, j) : temp = H[i] H[i] = H[j] H[j] = temp # Insert the element to the# priority queueinsert(45)insert(20)insert(14)insert(12)insert(31)insert(7)insert(11)insert(13)insert(7) i = 0 # Priority queue before extracting maxprint(\"Priority Queue : \", end = \"\")while (i <= size) : print(H[i], end = \" \") i += 1 print() # Node with maximum priorityprint(\"Node with maximum priority :\" , extractMax()) # Priority queue after extracting maxprint(\"Priority queue after extracting maximum : \", end = \"\")j = 0while (j <= size) : print(H[j], end = \" \") j += 1 print() # Change the priority of element# present at index 2 to 49changePriority(2, 49)print(\"Priority queue after priority change : \", end = \"\")k = 0while (k <= size) : print(H[k], end = \" \") k += 1 print() # Remove element at index 3Remove(3)print(\"Priority queue after removing the element : \", end = \"\")l = 0while (l <= size) : print(H[l], end = \" \") l += 1 # This code is contributed by divyeshrabadiya07.", "e": 15198, "s": 11920, "text": null }, { "code": "// C# code to implement priority-queue// using array implementation of// binary heapusing System; class GFG{ static int []H = new int[50];static int size = -1; // Function to return the index of the// parent node of a given nodestatic int parent(int i){ return (i - 1) / 2;} // Function to return the index of the// left child of the given nodestatic int leftChild(int i){ return ((2 * i) + 1);} // Function to return the index of the// right child of the given nodestatic int rightChild(int i){ return ((2 * i) + 2);} // Function to shift up the// node in order to maintain// the heap propertystatic void shiftUp(int i){ while (i > 0 && H[parent(i)] < H[i]) { // Swap parent and current node swap(parent(i), i); // Update i to parent of i i = parent(i); }} // Function to shift down the node in// order to maintain the heap propertystatic void shiftDown(int i){ int maxIndex = i; // Left Child int l = leftChild(i); if (l <= size && H[l] > H[maxIndex]) { maxIndex = l; } // Right Child int r = rightChild(i); if (r <= size && H[r] > H[maxIndex]) { maxIndex = r; } // If i not same as maxIndex if (i != maxIndex) { swap(i, maxIndex); shiftDown(maxIndex); }} // Function to insert a// new element in// the Binary Heapstatic void insert(int p){ size = size + 1; H[size] = p; // Shift Up to maintain // heap property shiftUp(size);} // Function to extract// the element with// maximum prioritystatic int extractMax(){ int result = H[0]; // Replace the value // at the root with // the last leaf H[0] = H[size]; size = size - 1; // Shift down the replaced // element to maintain the // heap property shiftDown(0); return result;} // Function to change the priority// of an elementstatic void changePriority(int i, int p){ int oldp = H[i]; H[i] = p; if (p > oldp) { shiftUp(i); } else { shiftDown(i); }} // Function to get value of// the current maximum elementstatic int getMax(){ return H[0];} // Function to remove the element// located at given indexstatic void Remove(int i){ H[i] = getMax() + 1; // Shift the node to the root // of the heap shiftUp(i); // Extract the node extractMax();} static void swap(int i, int j){ int temp = H[i]; H[i] = H[j]; H[j] = temp;} // Driver Codepublic static void Main(String[] args){ /* 45 / \\ 31 14 / \\ / \\ 13 20 7 11 / \\ 12 7 Create a priority queue shown in example in a binary max heap form. Queue will be represented in the form of array as: 45 31 14 13 20 7 11 12 7 */ // Insert the element to the // priority queue insert(45); insert(20); insert(14); insert(12); insert(31); insert(7); insert(11); insert(13); insert(7); int i = 0; // Priority queue before extracting max Console.Write(\"Priority Queue : \"); while (i <= size) { Console.Write(H[i] + \" \"); i++; } Console.Write(\"\\n\"); // Node with maximum priority Console.Write(\"Node with maximum priority : \" + extractMax() + \"\\n\"); // Priority queue after extracting max Console.Write(\"Priority queue after \" + \"extracting maximum : \"); int j = 0; while (j <= size) { Console.Write(H[j] + \" \"); j++; } Console.Write(\"\\n\"); // Change the priority of element // present at index 2 to 49 changePriority(2, 49); Console.Write(\"Priority queue after \" + \"priority change : \"); int k = 0; while (k <= size) { Console.Write(H[k] + \" \"); k++; } Console.Write(\"\\n\"); // Remove element at index 3 Remove(3); Console.Write(\"Priority queue after \" + \"removing the element : \"); int l = 0; while (l <= size) { Console.Write(H[l] + \" \"); l++; }}} // This code is contributed by Amit Katiyar", "e": 19416, "s": 15198, "text": null }, { "code": "<script> // Javascript code to implement priority-queue// using array implementation of// binary heap var H = Array(50).fill(0);var size = -1; // Function to return the index of the// parent node of a given nodefunction parent(i){ return parseInt((i - 1) / 2);} // Function to return the index of the// left child of the given nodefunction leftChild(i){ return parseInt((2 * i) + 1);} // Function to return the index of the// right child of the given nodefunction rightChild(i){ return parseInt((2 * i) + 2);} // Function to shift up the node in order// to maintain the heap propertyfunction shiftUp( i){ while (i > 0 && H[parent(i)] < H[i]) { // Swap parent and current node swap(parent(i), i); // Update i to parent of i i = parent(i); }} function swap(i, j){ var temp = H[i]; H[i] = H[j]; H[j] = temp;} // Function to shift down the node in// order to maintain the heap propertyfunction shiftDown( i){ var maxIndex = i; // Left Child var l = leftChild(i); if (l <= size && H[l] > H[maxIndex]) { maxIndex = l; } // Right Child var r = rightChild(i); if (r <= size && H[r] > H[maxIndex]) { maxIndex = r; } // If i not same as maxIndex if (i != maxIndex) { swap(i, maxIndex); shiftDown(maxIndex); }} // Function to insert a new element// in the Binary Heapfunction insert( p){ size = size + 1; H[size] = p; // Shift Up to maintain heap property shiftUp(size);} // Function to extract the element with// maximum priorityfunction extractMax(){ var result = H[0]; // Replace the value at the root // with the last leaf H[0] = H[size]; size = size - 1; // Shift down the replaced element // to maintain the heap property shiftDown(0); return result;} // Function to change the priority// of an elementfunction changePriority(i, p){ var oldp = H[i]; H[i] = p; if (p > oldp) { shiftUp(i); } else { shiftDown(i); }} // Function to get value of the current// maximum elementfunction getMax(){ return H[0];} // Function to remove the element// located at given indexfunction remove(i){ H[i] = getMax() + 1; // Shift the node to the root // of the heap shiftUp(i); // Extract the node extractMax();} // Driver Code/* 45 / \\ 31 14 / \\ / \\ 13 20 7 11 / \\ 12 7Create a priority queue shown inexample in a binary max heap form.Queue will be represented in theform of array as:45 31 14 13 20 7 11 12 7 */// Insert the element to the// priority queueinsert(45);insert(20);insert(14);insert(12);insert(31);insert(7);insert(11);insert(13);insert(7);var i = 0;// Priority queue before extracting maxdocument.write( \"Priority Queue : \");while (i <= size) { document.write( H[i] + \" \"); i++;}document.write( \"<br>\");// Node with maximum prioritydocument.write( \"Node with maximum priority : \" + extractMax() + \"<br>\");// Priority queue after extracting maxdocument.write( \"Priority queue after \" + \"extracting maximum : \");var j = 0;while (j <= size) { document.write( H[j] + \" \"); j++;}document.write( \"<br>\"); // Change the priority of element// present at index 2 to 49changePriority(2, 49);document.write( \"Priority queue after \" + \"priority change : \");var k = 0;while (k <= size) { document.write( H[k] + \" \"); k++;}document.write( \"<br>\"); // Remove element at index 3remove(3);document.write( \"Priority queue after \" + \"removing the element : \");var l = 0;while (l <= size) { document.write( H[l] + \" \"); l++;} // This code is contributed by noob2000.</script>", "e": 23086, "s": 19416, "text": null }, { "code": null, "e": 23352, "s": 23086, "text": "Priority Queue : 45 31 14 13 20 7 11 12 7 \nNode with maximum priority : 45 \nPriority queue after extracting maximum : 31 20 14 13 7 7 11 12 \nPriority queue after priority change : 49 20 31 13 7 7 11 12 \nPriority queue after removing the element : 49 20 31 12 7 7 11" }, { "code": null, "e": 23502, "s": 23354, "text": "Time Complexity: The time complexity of all the operation is O(log N) except for GetMax() which has time complexity of O(1). Auxiliary Space: O(N) " }, { "code": null, "e": 23514, "s": 23502, "text": "29AjayKumar" }, { "code": null, "e": 23529, "s": 23514, "text": "amit143katiyar" }, { "code": null, "e": 23547, "s": 23529, "text": "divyeshrabadiya07" }, { "code": null, "e": 23556, "s": 23547, "text": "noob2000" }, { "code": null, "e": 23575, "s": 23556, "text": "cpp-priority-queue" }, { "code": null, "e": 23596, "s": 23575, "text": "Data Structures-Heap" }, { "code": null, "e": 23605, "s": 23596, "text": "min-heap" }, { "code": null, "e": 23620, "s": 23605, "text": "priority-queue" }, { "code": null, "e": 23627, "s": 23620, "text": "Arrays" }, { "code": null, "e": 23643, "s": 23627, "text": "Data Structures" }, { "code": null, "e": 23648, "s": 23643, "text": "Heap" }, { "code": null, "e": 23664, "s": 23648, "text": "Data Structures" }, { "code": null, "e": 23671, "s": 23664, "text": "Arrays" }, { "code": null, "e": 23676, "s": 23671, "text": "Heap" }, { "code": null, "e": 23691, "s": 23676, "text": "priority-queue" } ]
Python Script to Logout Computer
14 Jul, 2019 As we know, Python is a popular scripting language because of its versatile features. In this article, we will write a Python script to logout a computer. Let’s start with how to logout the system with Python. To logout your computer/PC/laptop only by using a Python script, you have to use the os.system() function with the code “shutdown -l” . The shutdown -l command is the windows shell command for logging off. Let’s start with how to log out the system with Python. Note: For this to work, you have to import os library in the ide. If you don’t have it, then ‘pip install os‘ through the Command Prompt. Causion: Please ensure that you save and close all the program before running this code on the IDLE, as the below program will immediately log out your computer. Below is the Python implementation – import os logout = input("Do you wish to log out your computer ? (yes / no): ") if logout == 'no': exit()else: os.system("shutdown -l") Output:Here is the Python Program which will ask the user to log out the computer providing the option of Yes or No. Also, when you type yes & then press the ENTER key, the system will be log out instantly. python-utility Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Jul, 2019" }, { "code": null, "e": 444, "s": 28, "text": "As we know, Python is a popular scripting language because of its versatile features. In this article, we will write a Python script to logout a computer. Let’s start with how to logout the system with Python. To logout your computer/PC/laptop only by using a Python script, you have to use the os.system() function with the code “shutdown -l” . The shutdown -l command is the windows shell command for logging off." }, { "code": null, "e": 500, "s": 444, "text": "Let’s start with how to log out the system with Python." }, { "code": null, "e": 638, "s": 500, "text": "Note: For this to work, you have to import os library in the ide. If you don’t have it, then ‘pip install os‘ through the Command Prompt." }, { "code": null, "e": 800, "s": 638, "text": "Causion: Please ensure that you save and close all the program before running this code on the IDLE, as the below program will immediately log out your computer." }, { "code": null, "e": 837, "s": 800, "text": "Below is the Python implementation –" }, { "code": "import os logout = input(\"Do you wish to log out your computer ? (yes / no): \") if logout == 'no': exit()else: os.system(\"shutdown -l\")", "e": 981, "s": 837, "text": null }, { "code": null, "e": 1188, "s": 981, "text": "Output:Here is the Python Program which will ask the user to log out the computer providing the option of Yes or No. Also, when you type yes & then press the ENTER key, the system will be log out instantly." }, { "code": null, "e": 1203, "s": 1188, "text": "python-utility" }, { "code": null, "e": 1210, "s": 1203, "text": "Python" }, { "code": null, "e": 1226, "s": 1210, "text": "Python Programs" } ]
Number of shortest paths in an Undirected Weighted Graph
05 Jul, 2021 Given a weighted undirected graph G and an integer S, the task is to print the distances of the shortest paths and the count of the number of the shortest paths for each node from a given vertex, S. Examples: Input: S =1, G = Output: Shortest Paths distances are : 0 1 2 4 5 3 2 1 3 Numbers of the shortest Paths are: 1 1 1 2 3 1 1 1 2 Explanation: The distance of the shortest paths to vertex 1 is 0 and there is only 1 such path, which is {1}.The distance of the shortest paths to vertex 2 is 1 and there is only 1 such path, which is {1→2}.The distance of the shortest paths to vertex 3 is 2 and there is only 1 such path, which is {1→2→3}.The distance of the shortest paths to vertex 4 is 4 and there exist 2 such paths, which are {{1→2→3→4}, {1→2→3→6→4}}.The distance of the shortest paths to vertex 5 is 5 and there exist 3 such paths, which are {{1→2→3→4→5}, {1→2→3→6→4→5}, {1→2→3→6→5}}.The distance of the shortest paths to vertex 6 is 3 and there is only 1 such path, which is {1→2→3→6}.The distance of the shortest paths to vertex 7 is 2 and there is only 1 such path, which is {1→8→7}.The distance of the shortest paths to vertex 8 is 1 and there is only 1 such path, which is {1→8}.The distance of the shortest paths to vertex 9 is 3 and there exist 2 such paths, which are {{1→8→9}, {1→2→3→9}}. The distance of the shortest paths to vertex 1 is 0 and there is only 1 such path, which is {1}. The distance of the shortest paths to vertex 2 is 1 and there is only 1 such path, which is {1→2}. The distance of the shortest paths to vertex 3 is 2 and there is only 1 such path, which is {1→2→3}. The distance of the shortest paths to vertex 4 is 4 and there exist 2 such paths, which are {{1→2→3→4}, {1→2→3→6→4}}. The distance of the shortest paths to vertex 5 is 5 and there exist 3 such paths, which are {{1→2→3→4→5}, {1→2→3→6→4→5}, {1→2→3→6→5}}. The distance of the shortest paths to vertex 6 is 3 and there is only 1 such path, which is {1→2→3→6}. The distance of the shortest paths to vertex 7 is 2 and there is only 1 such path, which is {1→8→7}. The distance of the shortest paths to vertex 8 is 1 and there is only 1 such path, which is {1→8}. The distance of the shortest paths to vertex 9 is 3 and there exist 2 such paths, which are {{1→8→9}, {1→2→3→9}}. Approach: The given problem can be solved using the Dijkstra Algorithm. Follow the steps below to solve the problem: Form the adjacency List of the given graph using ArrayList<ArrayList<>> and store it in a variable, say adj. Initialize two integers, Arrays say Dist[] and Paths[] all elements as 0 to store the shortest distances of each node and count of paths with the shortest distance from the source Node, S. Define a function, say Dijkstra() to find the shortest distances of each node and count the paths with the shortest distance:Initialize a min PriorityQueue say PQ and a HashSet of Strings say settled to store if the edge is visited or not.Assign 0 to Dist[S] and 1 to Paths[S].Now iterate until PQ is not empty() and perform the following operations:Find the top Node of the PQ and store the Node value in a variable u.Pop the top element of PQ.Iterate over the ArrayList adj[u] and perform the following operationsStore the adjacent node in a variable say to and edge cost in a variable say cost:If edge {u, to} is visited, then continue.If dist[to] is greater than dist[u]+cost, then assign dist[u]+cost to dist[to] and then assign Paths[u] to Paths[to].Otherwise, if Paths[to] is equal to dist[u]+cost, then increment Paths[to] by 1.Now, Mark, the current edge {u, to} visited in settled. Initialize a min PriorityQueue say PQ and a HashSet of Strings say settled to store if the edge is visited or not. Assign 0 to Dist[S] and 1 to Paths[S]. Now iterate until PQ is not empty() and perform the following operations:Find the top Node of the PQ and store the Node value in a variable u.Pop the top element of PQ.Iterate over the ArrayList adj[u] and perform the following operationsStore the adjacent node in a variable say to and edge cost in a variable say cost:If edge {u, to} is visited, then continue.If dist[to] is greater than dist[u]+cost, then assign dist[u]+cost to dist[to] and then assign Paths[u] to Paths[to].Otherwise, if Paths[to] is equal to dist[u]+cost, then increment Paths[to] by 1.Now, Mark, the current edge {u, to} visited in settled. Find the top Node of the PQ and store the Node value in a variable u. Pop the top element of PQ. Iterate over the ArrayList adj[u] and perform the following operationsStore the adjacent node in a variable say to and edge cost in a variable say cost:If edge {u, to} is visited, then continue.If dist[to] is greater than dist[u]+cost, then assign dist[u]+cost to dist[to] and then assign Paths[u] to Paths[to].Otherwise, if Paths[to] is equal to dist[u]+cost, then increment Paths[to] by 1.Now, Mark, the current edge {u, to} visited in settled. Store the adjacent node in a variable say to and edge cost in a variable say cost: If edge {u, to} is visited, then continue. If dist[to] is greater than dist[u]+cost, then assign dist[u]+cost to dist[to] and then assign Paths[u] to Paths[to]. Otherwise, if Paths[to] is equal to dist[u]+cost, then increment Paths[to] by 1. Now, Mark, the current edge {u, to} visited in settled. Call the function Dijkstra(). Finally, print the Arrays dist[] and Paths[]. Below is the implementation of the above approach: Java // Java program for the above approachimport java.io.*;import java.util.*;class GFG { // Node class static class Node implements Comparator<Node> { // Stores the node public int node; // Stores the weight // of the edge public int cost; public Node() {} // Constructor public Node(int node, int cost) { this.node = node; this.cost = cost; } // Costume comparator @Override public int compare(Node node1, Node node2) { if (node1.cost < node2.cost) return -1; if (node1.cost > node2.cost) return 1; return 0; } } // Function to insert a node // in adjacency list static void addEdge(ArrayList<ArrayList<Node> > adj, int x, int y, int w) { adj.get(x).add(new Node(y, w)); adj.get(y).add(new Node(x, w)); } // Auxiliary function to find shortest paths using // Dijekstra static void dijkstra(ArrayList<ArrayList<Node> > adj, int src, int n, int dist[], int paths[]) { // Stores the distances of every node in shortest // order PriorityQueue<Node> pq = new PriorityQueue<Node>(n + 1, new Node()); // Stores if a vertex has been visited or not Set<String> settled = new HashSet<String>(); // Adds the source node with 0 distance to pq pq.add(new Node(src, 0)); dist[src] = 0; paths[src] = 1; // While pq is not empty() while (!pq.isEmpty()) { // Stores the top node of pq int u = pq.peek().node; // Stores the distance // of node u from s int d = pq.peek().cost; // Pop the top element pq.poll(); for (int i = 0; i < adj.get(u).size(); i++) { int to = adj.get(u).get(i).node; int cost = adj.get(u).get(i).cost; // If edge is marked if (settled.contains(to + " " + u)) continue; // If dist[to] is greater // than dist[u] + cost if (dist[to] > dist[u] + cost) { // Add the node to to the pq pq.add(new Node(to, d + cost)); // Update dist[to] dist[to] = dist[u] + cost; // Update paths[to] paths[to] = paths[u]; } // Otherwise else if (dist[to] == dist[u] + cost) { paths[to] = (paths[to] + paths[u]); } // Mark the edge visited settled.add(to + " " + u); } } } // Function to find the count of shortest path and // distances from source node to every other node static void findShortestPaths(ArrayList<ArrayList<Node> > adj, int s, int n) { // Stores the distances of a // node from source node int[] dist = new int[n + 5]; // Stores the count of shortest // paths of a node from // source node int[] paths = new int[n + 5]; for (int i = 0; i <= n; i++) dist[i] = Integer.MAX_VALUE; for (int i = 0; i <= n; i++) paths[i] = 0; // Function call to find // the shortest paths dijkstra(adj, s, n, dist, paths); System.out.print("Shortest Paths distances are : "); for (int i = 1; i <= n; i++) { System.out.print(dist[i] + " "); } System.out.println(); System.out.print( "Numbers of the shortest Paths are: "); for (int i = 1; i <= n; i++) System.out.print(paths[i] + " "); } // Driver Code public static void main(String[] args) { // Input int N = 9; int M = 14; ArrayList<ArrayList<Node> > adj = new ArrayList<>(); for (int i = 0; i <= N; i++) { adj.add(new ArrayList<Node>()); } addEdge(adj, 1, 2, 1); addEdge(adj, 2, 3, 1); addEdge(adj, 3, 4, 2); addEdge(adj, 4, 5, 1); addEdge(adj, 5, 6, 2); addEdge(adj, 6, 7, 2); addEdge(adj, 7, 8, 1); addEdge(adj, 8, 1, 1); addEdge(adj, 2, 8, 2); addEdge(adj, 3, 9, 1); addEdge(adj, 8, 9, 2); addEdge(adj, 7, 9, 2); addEdge(adj, 3, 6, 1); addEdge(adj, 4, 6, 1); // Function call findShortestPaths(adj, 1, N); }} Shortest Paths distances are : 0 1 2 4 5 3 2 1 3 Numbers of the shortest Paths are: 1 1 1 2 3 1 1 1 2 Time Complexity: O(M + N * log(N)) Auxiliary Space: O(M) Shortest Path Graph Graph Shortest Path Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Jul, 2021" }, { "code": null, "e": 251, "s": 52, "text": "Given a weighted undirected graph G and an integer S, the task is to print the distances of the shortest paths and the count of the number of the shortest paths for each node from a given vertex, S." }, { "code": null, "e": 261, "s": 251, "text": "Examples:" }, { "code": null, "e": 279, "s": 261, "text": "Input: S =1, G = " }, { "code": null, "e": 416, "s": 279, "text": "Output: Shortest Paths distances are : 0 1 2 4 5 3 2 1 3 Numbers of the shortest Paths are: 1 1 1 2 3 1 1 1 2 Explanation:" }, { "code": null, "e": 1375, "s": 416, "text": "The distance of the shortest paths to vertex 1 is 0 and there is only 1 such path, which is {1}.The distance of the shortest paths to vertex 2 is 1 and there is only 1 such path, which is {1→2}.The distance of the shortest paths to vertex 3 is 2 and there is only 1 such path, which is {1→2→3}.The distance of the shortest paths to vertex 4 is 4 and there exist 2 such paths, which are {{1→2→3→4}, {1→2→3→6→4}}.The distance of the shortest paths to vertex 5 is 5 and there exist 3 such paths, which are {{1→2→3→4→5}, {1→2→3→6→4→5}, {1→2→3→6→5}}.The distance of the shortest paths to vertex 6 is 3 and there is only 1 such path, which is {1→2→3→6}.The distance of the shortest paths to vertex 7 is 2 and there is only 1 such path, which is {1→8→7}.The distance of the shortest paths to vertex 8 is 1 and there is only 1 such path, which is {1→8}.The distance of the shortest paths to vertex 9 is 3 and there exist 2 such paths, which are {{1→8→9}, {1→2→3→9}}." }, { "code": null, "e": 1472, "s": 1375, "text": "The distance of the shortest paths to vertex 1 is 0 and there is only 1 such path, which is {1}." }, { "code": null, "e": 1571, "s": 1472, "text": "The distance of the shortest paths to vertex 2 is 1 and there is only 1 such path, which is {1→2}." }, { "code": null, "e": 1672, "s": 1571, "text": "The distance of the shortest paths to vertex 3 is 2 and there is only 1 such path, which is {1→2→3}." }, { "code": null, "e": 1790, "s": 1672, "text": "The distance of the shortest paths to vertex 4 is 4 and there exist 2 such paths, which are {{1→2→3→4}, {1→2→3→6→4}}." }, { "code": null, "e": 1925, "s": 1790, "text": "The distance of the shortest paths to vertex 5 is 5 and there exist 3 such paths, which are {{1→2→3→4→5}, {1→2→3→6→4→5}, {1→2→3→6→5}}." }, { "code": null, "e": 2028, "s": 1925, "text": "The distance of the shortest paths to vertex 6 is 3 and there is only 1 such path, which is {1→2→3→6}." }, { "code": null, "e": 2129, "s": 2028, "text": "The distance of the shortest paths to vertex 7 is 2 and there is only 1 such path, which is {1→8→7}." }, { "code": null, "e": 2228, "s": 2129, "text": "The distance of the shortest paths to vertex 8 is 1 and there is only 1 such path, which is {1→8}." }, { "code": null, "e": 2342, "s": 2228, "text": "The distance of the shortest paths to vertex 9 is 3 and there exist 2 such paths, which are {{1→8→9}, {1→2→3→9}}." }, { "code": null, "e": 2459, "s": 2342, "text": "Approach: The given problem can be solved using the Dijkstra Algorithm. Follow the steps below to solve the problem:" }, { "code": null, "e": 2568, "s": 2459, "text": "Form the adjacency List of the given graph using ArrayList<ArrayList<>> and store it in a variable, say adj." }, { "code": null, "e": 2757, "s": 2568, "text": "Initialize two integers, Arrays say Dist[] and Paths[] all elements as 0 to store the shortest distances of each node and count of paths with the shortest distance from the source Node, S." }, { "code": null, "e": 3649, "s": 2757, "text": "Define a function, say Dijkstra() to find the shortest distances of each node and count the paths with the shortest distance:Initialize a min PriorityQueue say PQ and a HashSet of Strings say settled to store if the edge is visited or not.Assign 0 to Dist[S] and 1 to Paths[S].Now iterate until PQ is not empty() and perform the following operations:Find the top Node of the PQ and store the Node value in a variable u.Pop the top element of PQ.Iterate over the ArrayList adj[u] and perform the following operationsStore the adjacent node in a variable say to and edge cost in a variable say cost:If edge {u, to} is visited, then continue.If dist[to] is greater than dist[u]+cost, then assign dist[u]+cost to dist[to] and then assign Paths[u] to Paths[to].Otherwise, if Paths[to] is equal to dist[u]+cost, then increment Paths[to] by 1.Now, Mark, the current edge {u, to} visited in settled." }, { "code": null, "e": 3764, "s": 3649, "text": "Initialize a min PriorityQueue say PQ and a HashSet of Strings say settled to store if the edge is visited or not." }, { "code": null, "e": 3803, "s": 3764, "text": "Assign 0 to Dist[S] and 1 to Paths[S]." }, { "code": null, "e": 4418, "s": 3803, "text": "Now iterate until PQ is not empty() and perform the following operations:Find the top Node of the PQ and store the Node value in a variable u.Pop the top element of PQ.Iterate over the ArrayList adj[u] and perform the following operationsStore the adjacent node in a variable say to and edge cost in a variable say cost:If edge {u, to} is visited, then continue.If dist[to] is greater than dist[u]+cost, then assign dist[u]+cost to dist[to] and then assign Paths[u] to Paths[to].Otherwise, if Paths[to] is equal to dist[u]+cost, then increment Paths[to] by 1.Now, Mark, the current edge {u, to} visited in settled." }, { "code": null, "e": 4488, "s": 4418, "text": "Find the top Node of the PQ and store the Node value in a variable u." }, { "code": null, "e": 4515, "s": 4488, "text": "Pop the top element of PQ." }, { "code": null, "e": 4962, "s": 4515, "text": "Iterate over the ArrayList adj[u] and perform the following operationsStore the adjacent node in a variable say to and edge cost in a variable say cost:If edge {u, to} is visited, then continue.If dist[to] is greater than dist[u]+cost, then assign dist[u]+cost to dist[to] and then assign Paths[u] to Paths[to].Otherwise, if Paths[to] is equal to dist[u]+cost, then increment Paths[to] by 1.Now, Mark, the current edge {u, to} visited in settled." }, { "code": null, "e": 5045, "s": 4962, "text": "Store the adjacent node in a variable say to and edge cost in a variable say cost:" }, { "code": null, "e": 5088, "s": 5045, "text": "If edge {u, to} is visited, then continue." }, { "code": null, "e": 5206, "s": 5088, "text": "If dist[to] is greater than dist[u]+cost, then assign dist[u]+cost to dist[to] and then assign Paths[u] to Paths[to]." }, { "code": null, "e": 5287, "s": 5206, "text": "Otherwise, if Paths[to] is equal to dist[u]+cost, then increment Paths[to] by 1." }, { "code": null, "e": 5343, "s": 5287, "text": "Now, Mark, the current edge {u, to} visited in settled." }, { "code": null, "e": 5373, "s": 5343, "text": "Call the function Dijkstra()." }, { "code": null, "e": 5419, "s": 5373, "text": "Finally, print the Arrays dist[] and Paths[]." }, { "code": null, "e": 5470, "s": 5419, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 5475, "s": 5470, "text": "Java" }, { "code": "// Java program for the above approachimport java.io.*;import java.util.*;class GFG { // Node class static class Node implements Comparator<Node> { // Stores the node public int node; // Stores the weight // of the edge public int cost; public Node() {} // Constructor public Node(int node, int cost) { this.node = node; this.cost = cost; } // Costume comparator @Override public int compare(Node node1, Node node2) { if (node1.cost < node2.cost) return -1; if (node1.cost > node2.cost) return 1; return 0; } } // Function to insert a node // in adjacency list static void addEdge(ArrayList<ArrayList<Node> > adj, int x, int y, int w) { adj.get(x).add(new Node(y, w)); adj.get(y).add(new Node(x, w)); } // Auxiliary function to find shortest paths using // Dijekstra static void dijkstra(ArrayList<ArrayList<Node> > adj, int src, int n, int dist[], int paths[]) { // Stores the distances of every node in shortest // order PriorityQueue<Node> pq = new PriorityQueue<Node>(n + 1, new Node()); // Stores if a vertex has been visited or not Set<String> settled = new HashSet<String>(); // Adds the source node with 0 distance to pq pq.add(new Node(src, 0)); dist[src] = 0; paths[src] = 1; // While pq is not empty() while (!pq.isEmpty()) { // Stores the top node of pq int u = pq.peek().node; // Stores the distance // of node u from s int d = pq.peek().cost; // Pop the top element pq.poll(); for (int i = 0; i < adj.get(u).size(); i++) { int to = adj.get(u).get(i).node; int cost = adj.get(u).get(i).cost; // If edge is marked if (settled.contains(to + \" \" + u)) continue; // If dist[to] is greater // than dist[u] + cost if (dist[to] > dist[u] + cost) { // Add the node to to the pq pq.add(new Node(to, d + cost)); // Update dist[to] dist[to] = dist[u] + cost; // Update paths[to] paths[to] = paths[u]; } // Otherwise else if (dist[to] == dist[u] + cost) { paths[to] = (paths[to] + paths[u]); } // Mark the edge visited settled.add(to + \" \" + u); } } } // Function to find the count of shortest path and // distances from source node to every other node static void findShortestPaths(ArrayList<ArrayList<Node> > adj, int s, int n) { // Stores the distances of a // node from source node int[] dist = new int[n + 5]; // Stores the count of shortest // paths of a node from // source node int[] paths = new int[n + 5]; for (int i = 0; i <= n; i++) dist[i] = Integer.MAX_VALUE; for (int i = 0; i <= n; i++) paths[i] = 0; // Function call to find // the shortest paths dijkstra(adj, s, n, dist, paths); System.out.print(\"Shortest Paths distances are : \"); for (int i = 1; i <= n; i++) { System.out.print(dist[i] + \" \"); } System.out.println(); System.out.print( \"Numbers of the shortest Paths are: \"); for (int i = 1; i <= n; i++) System.out.print(paths[i] + \" \"); } // Driver Code public static void main(String[] args) { // Input int N = 9; int M = 14; ArrayList<ArrayList<Node> > adj = new ArrayList<>(); for (int i = 0; i <= N; i++) { adj.add(new ArrayList<Node>()); } addEdge(adj, 1, 2, 1); addEdge(adj, 2, 3, 1); addEdge(adj, 3, 4, 2); addEdge(adj, 4, 5, 1); addEdge(adj, 5, 6, 2); addEdge(adj, 6, 7, 2); addEdge(adj, 7, 8, 1); addEdge(adj, 8, 1, 1); addEdge(adj, 2, 8, 2); addEdge(adj, 3, 9, 1); addEdge(adj, 8, 9, 2); addEdge(adj, 7, 9, 2); addEdge(adj, 3, 6, 1); addEdge(adj, 4, 6, 1); // Function call findShortestPaths(adj, 1, N); }}", "e": 10140, "s": 5475, "text": null }, { "code": null, "e": 10244, "s": 10140, "text": "Shortest Paths distances are : 0 1 2 4 5 3 2 1 3 \nNumbers of the shortest Paths are: 1 1 1 2 3 1 1 1 2\n" }, { "code": null, "e": 10302, "s": 10244, "text": "Time Complexity: O(M + N * log(N)) Auxiliary Space: O(M)" }, { "code": null, "e": 10316, "s": 10302, "text": "Shortest Path" }, { "code": null, "e": 10322, "s": 10316, "text": "Graph" }, { "code": null, "e": 10328, "s": 10322, "text": "Graph" }, { "code": null, "e": 10342, "s": 10328, "text": "Shortest Path" } ]
How to set Background Color in HTML ?
01 Apr, 2021 In this article, we will see how to set the background color of an element. The purpose of using style attribute is to add styles to the elements. Using style attribute with different elements results in change in that element only. This attribute can be used as inline, internal or external. The style attribute provides number of properties which can be used to improve a simple html page. The background color can be changed in three ways: Inline style attribute Internal CSS External CSS The HTML5 doesn’t support the ‘bgcolor’ attribute of <body> tag, therefore we need to use the inline style attribute and internal CSS options for changing the color of a web page. For internal CSS add <style> tag at beginning of html file and add the tag to which the changes are being applied in this case the <body> tag is used. Syntax: /* For inline style attribute */ <tag style="property:value"> /* For internal CSS attribute */ <style> tagName{ property:value; } </style> Example 1: Below is the example that illustrates the use of inline CSS. HTML <!DOCTYPE html><html> <!--This line changes the color of background--><body style="background-color:pink"> <h1 style="color:green;text-align:center;"> GeeksForGeeks </h1> <h3 style="text-align:center;"> How to change color of Background? </h3></body> </html> Output: This will be displayed when html file is opened in browser. Example 2: Below is the example that illustrates the use of internal CSS. HTML <!DOCTYPE html><html> <head> <style> body { background-color: powderblue; } h1 { color: green; text-align: center; } h3 { text-align: center; } </style></head> <body> <h1>GeeksForGeeks</h1> <h3> How to change color of Background?(Using Internal CSS) </h3></body> </html> Output:This will be displayed when html file is opened in browser External CSS: In external CSS, we create a separate file which has all the style data for the html file. Storing the file externally makes it easier to apply changes to the HTML page. CSS-Properties CSS-Questions HTML-Attributes HTML-Questions HTML-Tags Picked CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n01 Apr, 2021" }, { "code": null, "e": 445, "s": 53, "text": "In this article, we will see how to set the background color of an element. The purpose of using style attribute is to add styles to the elements. Using style attribute with different elements results in change in that element only. This attribute can be used as inline, internal or external. The style attribute provides number of properties which can be used to improve a simple html page." }, { "code": null, "e": 496, "s": 445, "text": "The background color can be changed in three ways:" }, { "code": null, "e": 519, "s": 496, "text": "Inline style attribute" }, { "code": null, "e": 532, "s": 519, "text": "Internal CSS" }, { "code": null, "e": 545, "s": 532, "text": "External CSS" }, { "code": null, "e": 876, "s": 545, "text": "The HTML5 doesn’t support the ‘bgcolor’ attribute of <body> tag, therefore we need to use the inline style attribute and internal CSS options for changing the color of a web page. For internal CSS add <style> tag at beginning of html file and add the tag to which the changes are being applied in this case the <body> tag is used." }, { "code": null, "e": 884, "s": 876, "text": "Syntax:" }, { "code": null, "e": 1032, "s": 884, "text": "/* For inline style attribute */\n<tag style=\"property:value\">\n\n/* For internal CSS attribute */\n<style>\n tagName{\n property:value;\n }\n</style>" }, { "code": null, "e": 1104, "s": 1032, "text": "Example 1: Below is the example that illustrates the use of inline CSS." }, { "code": null, "e": 1109, "s": 1104, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <!--This line changes the color of background--><body style=\"background-color:pink\"> <h1 style=\"color:green;text-align:center;\"> GeeksForGeeks </h1> <h3 style=\"text-align:center;\"> How to change color of Background? </h3></body> </html>", "e": 1398, "s": 1109, "text": null }, { "code": null, "e": 1466, "s": 1398, "text": "Output: This will be displayed when html file is opened in browser." }, { "code": null, "e": 1540, "s": 1466, "text": "Example 2: Below is the example that illustrates the use of internal CSS." }, { "code": null, "e": 1545, "s": 1540, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> body { background-color: powderblue; } h1 { color: green; text-align: center; } h3 { text-align: center; } </style></head> <body> <h1>GeeksForGeeks</h1> <h3> How to change color of Background?(Using Internal CSS) </h3></body> </html>", "e": 1940, "s": 1545, "text": null }, { "code": null, "e": 2006, "s": 1940, "text": "Output:This will be displayed when html file is opened in browser" }, { "code": null, "e": 2190, "s": 2006, "text": "External CSS: In external CSS, we create a separate file which has all the style data for the html file. Storing the file externally makes it easier to apply changes to the HTML page." }, { "code": null, "e": 2205, "s": 2190, "text": "CSS-Properties" }, { "code": null, "e": 2219, "s": 2205, "text": "CSS-Questions" }, { "code": null, "e": 2235, "s": 2219, "text": "HTML-Attributes" }, { "code": null, "e": 2250, "s": 2235, "text": "HTML-Questions" }, { "code": null, "e": 2260, "s": 2250, "text": "HTML-Tags" }, { "code": null, "e": 2267, "s": 2260, "text": "Picked" }, { "code": null, "e": 2271, "s": 2267, "text": "CSS" }, { "code": null, "e": 2276, "s": 2271, "text": "HTML" }, { "code": null, "e": 2293, "s": 2276, "text": "Web Technologies" }, { "code": null, "e": 2298, "s": 2293, "text": "HTML" } ]
Myth about the file name and class name in Java
17 Feb, 2021 The first lecture note given during java class is “In java file name and class name should be the same”. When the above law is violated a compiler error message will appear as below Java /***** File name: Trial.java ******/public class Geeks { public static void main(String[] args) { System.out.println("Hello world"); }} Output: javac Trial.java Trial.java:9: error: class Geeks is public, should be declared in a file named Geeks.java public class Geeks ^ 1 error But the myth can be violated in such a way to compile the above file. Java /***** File name: Trial.java ******/class Geeks { public static void main(String[] args) { System.out.println("Hello world"); }} Step 1: javac Trial.java Step 1 will create a Geeks.class (byte code) without any error message since the class is not public.Step 2: java Geeks Now the output will be Hello worldThe myth about the file name and class name should be same only when the class is declared in public.The above program works as follows: Now, this .class file can be executed. By the above features, some more miracles can be done. It is possible to have many classes in a java file. For debugging purposes, this approach can be used. Each class can be executed separately to test their functionalities(only on one condition: Inheritance concept should not be used). But in general, it is good to follow the myth.Example 1: Java /*** File name: Trial.java ***/class ForGeeks { public static void main(String[] args) { System.out.println("For Geeks class"); }} class GeeksTest { public static void main(String[] args) { System.out.println("Geeks Test class"); }} When the above file is compiled as javac Trial.java this will create 2 .class files as ForGeeks.class and GeeksTest.class . Since each class has separate main() stub they can be tested individually. When java ForGeeks is executed the output is For Geeks class. When java GeeksTest is executed the output is Geeks Test class. Example 2: Java // Program to find area of triangleclass Triangle { int x, y; void printArea() { System.out.println("Area of triangle is: " + x * y / 2); }} class Demo { public static void main(String args[]) { // Object creation Triangle t = new Triangle(); t.x = 10; t.y = 13; t.printArea(); }} Note: There are two classes here, Triangle and Demo. Then which class name must be considered as the file name? The class name Demo must be taken as the file name. The reason behind taking Demo as the file name is that it has the main method and execution begins from the main method. Filename: Demo.java Compilation: javac Demo.java Run: java Demo Output: Area of triangle:65 Myth about the file name and class name in Java | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersMyth about the file name and class name in Java | GeeksforGeeksWatch laterShareCopy link3/9InfoShoppingTap 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:52•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=2q_LoVmev7g" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Sowmya.L.R. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above mangalgiaishwarya2 smundada06 Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Feb, 2021" }, { "code": null, "e": 235, "s": 52, "text": "The first lecture note given during java class is “In java file name and class name should be the same”. When the above law is violated a compiler error message will appear as below " }, { "code": null, "e": 240, "s": 235, "text": "Java" }, { "code": "/***** File name: Trial.java ******/public class Geeks { public static void main(String[] args) { System.out.println(\"Hello world\"); }}", "e": 392, "s": 240, "text": null }, { "code": null, "e": 402, "s": 392, "text": "Output: " }, { "code": null, "e": 562, "s": 402, "text": "javac Trial.java\nTrial.java:9: error: class Geeks is public, should be\n declared in a file named Geeks.java\npublic class Geeks\n^\n1 error \n\n\n" }, { "code": null, "e": 634, "s": 562, "text": "But the myth can be violated in such a way to compile the above file. " }, { "code": null, "e": 639, "s": 634, "text": "Java" }, { "code": "/***** File name: Trial.java ******/class Geeks { public static void main(String[] args) { System.out.println(\"Hello world\"); }}", "e": 784, "s": 639, "text": null }, { "code": null, "e": 794, "s": 784, "text": "Step 1: " }, { "code": null, "e": 814, "s": 794, "text": "javac Trial.java\n\n\n" }, { "code": null, "e": 925, "s": 814, "text": "Step 1 will create a Geeks.class (byte code) without any error message since the class is not public.Step 2: " }, { "code": null, "e": 939, "s": 925, "text": "java Geeks\n\n\n" }, { "code": null, "e": 1112, "s": 939, "text": "Now the output will be Hello worldThe myth about the file name and class name should be same only when the class is declared in public.The above program works as follows: " }, { "code": null, "e": 1500, "s": 1112, "text": "Now, this .class file can be executed. By the above features, some more miracles can be done. It is possible to have many classes in a java file. For debugging purposes, this approach can be used. Each class can be executed separately to test their functionalities(only on one condition: Inheritance concept should not be used). But in general, it is good to follow the myth.Example 1: " }, { "code": null, "e": 1505, "s": 1500, "text": "Java" }, { "code": "/*** File name: Trial.java ***/class ForGeeks { public static void main(String[] args) { System.out.println(\"For Geeks class\"); }} class GeeksTest { public static void main(String[] args) { System.out.println(\"Geeks Test class\"); }}", "e": 1771, "s": 1505, "text": null }, { "code": null, "e": 1972, "s": 1771, "text": "When the above file is compiled as javac Trial.java this will create 2 .class files as ForGeeks.class and GeeksTest.class . Since each class has separate main() stub they can be tested individually. " }, { "code": null, "e": 2034, "s": 1972, "text": "When java ForGeeks is executed the output is For Geeks class." }, { "code": null, "e": 2098, "s": 2034, "text": "When java GeeksTest is executed the output is Geeks Test class." }, { "code": null, "e": 2111, "s": 2098, "text": "Example 2: " }, { "code": null, "e": 2116, "s": 2111, "text": "Java" }, { "code": "// Program to find area of triangleclass Triangle { int x, y; void printArea() { System.out.println(\"Area of triangle is: \" + x * y / 2); }} class Demo { public static void main(String args[]) { // Object creation Triangle t = new Triangle(); t.x = 10; t.y = 13; t.printArea(); }}", "e": 2461, "s": 2116, "text": null }, { "code": null, "e": 2748, "s": 2461, "text": "Note: There are two classes here, Triangle and Demo. Then which class name must be considered as the file name? The class name Demo must be taken as the file name. The reason behind taking Demo as the file name is that it has the main method and execution begins from the main method. " }, { "code": null, "e": 2843, "s": 2748, "text": "Filename: Demo.java\nCompilation: javac Demo.java\nRun: java Demo\nOutput: Area of triangle:65\n\n\n" }, { "code": null, "e": 3758, "s": 2843, "text": "Myth about the file name and class name in Java | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersMyth about the file name and class name in Java | GeeksforGeeksWatch laterShareCopy link3/9InfoShoppingTap 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:52•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=2q_LoVmev7g\" 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": 4146, "s": 3758, "text": "This article is contributed by Sowmya.L.R. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 4165, "s": 4146, "text": "mangalgiaishwarya2" }, { "code": null, "e": 4176, "s": 4165, "text": "smundada06" }, { "code": null, "e": 4181, "s": 4176, "text": "Java" }, { "code": null, "e": 4186, "s": 4181, "text": "Java" } ]
Thue-Morse sequence
05 Apr, 2021 Thue–Morse sequence, or Prouhet–Thue–Morse sequence, is an infinite binary sequence of 0s and 1s. The sequence is obtained by starting with 0 and successively appending the Boolean complement of the sequence obtained so far.First few steps : Start with 0 Append complement of 0, we get 01 Append complement of 01, we get 0110 Append complement of 0110, we get 01101001 Given a whole number n. The task is to find the nth string formed of by Thue–Morse sequence i.e prefix of length 2n-1 of Thue–Morse sequence. Examples: Input : n = 4 Output : 01101001 We get 0, 01, 0110 and 01101001 in fourth iteration. Input : n = 3 Output : 0110 The idea is to initialize the output string with 0, then run a loop n – 1 times and for each iteration find the complement of the string and append it to the string.Below is implementation of this approach: C++ Java Python3 C# PHP C++ Javascript // CPP Program to find nth term of Thue-Morse sequence.#include <bits/stdc++.h>using namespace std; // Return the complement of the binary string.string complement(string s){ string comps; // finding the complement of the string. for (int i = 0; i < s.length(); i++) { // if character is 0, append 1 if (s.at(i) == '0') comps += '1'; // if character is 1, append 0. else comps += '0'; } return comps;} // Return the nth term of Thue-Morse sequence.string nthTerm(int n){ // Initialing the string to 0 string s = "0"; // Running the loop for n - 1 time. for (int i = 1; i < n; i++) // appending the complement of // the string to the string. s += complement(s); return s;}// Driven Programint main(){ int n = 4; cout << nthTerm(n) << endl; return 0;} // Java Program to find nth// term of Thue-Morse sequence. class GFG{ // Return the complement // of the binary String. static String complement(String s) { String comps = ""; // finding the complement // of the String. for (int i = 0; i < s.length(); i++) { // if character is 0, // append 1 if (s.charAt(i) == '0') comps += '1'; // if character is 1, // append 0. else comps += '0'; } return comps; } // Return the nth term // of Thue-Morse sequence. static String nthTerm(int n) { // Initialing the // String to 0 String s = "0"; // Running the loop // for n - 1 time. for (int i = 1; i < n; i++) // appending the complement of // the String to the String. s += complement(s); return s; } // Driven Codepublic static void main(String[] args) { int n = 4; System.out.print(nthTerm(n)); }} // This code is contributed by// mits # Python3 Program to find nth term of# Thue-Morse sequence. # Return the complement of the# binary string.def complement(s): comps = ""; # finding the complement # of the string. for i in range(len(s)): # if character is 0, append 1 if (s[i] == '0'): comps += '1'; # if character is 1, append 0. else: comps += '0'; return comps; # Return the nth term of# Thue-Morse sequence.def nthTerm(n): # Initialing the string to 0 s = "0"; # Running the loop for n - 1 time. for i in range(1, n): # appending the complement of # the string to the string. s += complement(s); return s; # Driver Coden = 4;print(nthTerm(n)); # This code is contributed# by mits // C# Program to find nth// term of Thue-Morse sequence.using System; class GFG{ // Return the complement // of the binary string. static string complement(string s) { string comps = ""; // finding the complement // of the string. for (int i = 0; i < s.Length; i++) { // if character is 0, // append 1 if (s[i] == '0') comps += '1'; // if character is 1, // append 0. else comps += '0'; } return comps; } // Return the nth term // of Thue-Morse sequence. static string nthTerm(int n) { // Initialing the // string to 0 string s = "0"; // Running the loop // for n - 1 time. for (int i = 1; i < n; i++) // appending the complement of // the string to the string. s += complement(s); return s; } // Driven Code static void Main() { int n = 4; Console.Write(nthTerm(n)); }} // This code is contributed by// Manish Shaw(manishshaw1) <?php// PHP Program to find nth// term of Thue-Morse sequence. // Return the complement// of the binary string.function complement($s){ $comps = ""; // finding the complement // of the string. for ($i = 0; $i < strlen($s); $i++) { // if character is // 0, append 1 if ($s[$i] == '0') $comps .= '1'; // if character is // 1, append 0. else $comps .= '0'; } return $comps;} // Return the nth term// of Thue-Morse sequence.function nthTerm($n){ // Initialing the // string to 0 $s = "0"; // Running the loop // for n - 1 time. for ($i = 1; $i < $n; $i++) // appending the complement of // the string to the string. $s .= complement($s); return $s;} // Driven Code$n = 4;echo nthTerm($n); // This code is contributed// by mits?> #include <iostream>using namespace std; int main() { cout<<"GFG!"; return 0;} <script> // JavaScript Program to find nth// term of Thue-Morse sequence. // Return the complement // of the binary string. function complement(s) { let comps = ""; // finding the complement // of the string. for (let i = 0; i < s.length; i++) { // if character is 0, // append 1 if (s[i] == '0') comps += '1'; // if character is 1, // append 0. else comps += '0'; } return comps; } // Return the nth term // of Thue-Morse sequence. function nthTerm(n) { // Initialing the // string to 0 let s = "0"; // Running the loop // for n - 1 time. for (let i = 1; i < n; i++) // appending the complement of // the string to the string. s += complement(s); return s; } // Driver program let n = 4; document.write(nthTerm(n)); // This code is contributed by susmitakundugoaldanga.</script> Output: 01101001 manishshaw1 Mithun Kumar ManasChhabra2 susmitakundugoaldanga binary-string Mathematical Strings Strings Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Apr, 2021" }, { "code": null, "e": 295, "s": 52, "text": "Thue–Morse sequence, or Prouhet–Thue–Morse sequence, is an infinite binary sequence of 0s and 1s. The sequence is obtained by starting with 0 and successively appending the Boolean complement of the sequence obtained so far.First few steps : " }, { "code": null, "e": 422, "s": 295, "text": "Start with 0 Append complement of 0, we get 01 Append complement of 01, we get 0110 Append complement of 0110, we get 01101001" }, { "code": null, "e": 576, "s": 422, "text": "Given a whole number n. The task is to find the nth string formed of by Thue–Morse sequence i.e prefix of length 2n-1 of Thue–Morse sequence. Examples: " }, { "code": null, "e": 690, "s": 576, "text": "Input : n = 4\nOutput : 01101001\nWe get 0, 01, 0110 and 01101001\nin fourth iteration.\n\nInput : n = 3\nOutput : 0110" }, { "code": null, "e": 899, "s": 690, "text": "The idea is to initialize the output string with 0, then run a loop n – 1 times and for each iteration find the complement of the string and append it to the string.Below is implementation of this approach: " }, { "code": null, "e": 903, "s": 899, "text": "C++" }, { "code": null, "e": 908, "s": 903, "text": "Java" }, { "code": null, "e": 916, "s": 908, "text": "Python3" }, { "code": null, "e": 919, "s": 916, "text": "C#" }, { "code": null, "e": 923, "s": 919, "text": "PHP" }, { "code": null, "e": 927, "s": 923, "text": "C++" }, { "code": null, "e": 938, "s": 927, "text": "Javascript" }, { "code": "// CPP Program to find nth term of Thue-Morse sequence.#include <bits/stdc++.h>using namespace std; // Return the complement of the binary string.string complement(string s){ string comps; // finding the complement of the string. for (int i = 0; i < s.length(); i++) { // if character is 0, append 1 if (s.at(i) == '0') comps += '1'; // if character is 1, append 0. else comps += '0'; } return comps;} // Return the nth term of Thue-Morse sequence.string nthTerm(int n){ // Initialing the string to 0 string s = \"0\"; // Running the loop for n - 1 time. for (int i = 1; i < n; i++) // appending the complement of // the string to the string. s += complement(s); return s;}// Driven Programint main(){ int n = 4; cout << nthTerm(n) << endl; return 0;}", "e": 1810, "s": 938, "text": null }, { "code": "// Java Program to find nth// term of Thue-Morse sequence. class GFG{ // Return the complement // of the binary String. static String complement(String s) { String comps = \"\"; // finding the complement // of the String. for (int i = 0; i < s.length(); i++) { // if character is 0, // append 1 if (s.charAt(i) == '0') comps += '1'; // if character is 1, // append 0. else comps += '0'; } return comps; } // Return the nth term // of Thue-Morse sequence. static String nthTerm(int n) { // Initialing the // String to 0 String s = \"0\"; // Running the loop // for n - 1 time. for (int i = 1; i < n; i++) // appending the complement of // the String to the String. s += complement(s); return s; } // Driven Codepublic static void main(String[] args) { int n = 4; System.out.print(nthTerm(n)); }} // This code is contributed by// mits", "e": 2973, "s": 1810, "text": null }, { "code": "# Python3 Program to find nth term of# Thue-Morse sequence. # Return the complement of the# binary string.def complement(s): comps = \"\"; # finding the complement # of the string. for i in range(len(s)): # if character is 0, append 1 if (s[i] == '0'): comps += '1'; # if character is 1, append 0. else: comps += '0'; return comps; # Return the nth term of# Thue-Morse sequence.def nthTerm(n): # Initialing the string to 0 s = \"0\"; # Running the loop for n - 1 time. for i in range(1, n): # appending the complement of # the string to the string. s += complement(s); return s; # Driver Coden = 4;print(nthTerm(n)); # This code is contributed# by mits", "e": 3735, "s": 2973, "text": null }, { "code": "// C# Program to find nth// term of Thue-Morse sequence.using System; class GFG{ // Return the complement // of the binary string. static string complement(string s) { string comps = \"\"; // finding the complement // of the string. for (int i = 0; i < s.Length; i++) { // if character is 0, // append 1 if (s[i] == '0') comps += '1'; // if character is 1, // append 0. else comps += '0'; } return comps; } // Return the nth term // of Thue-Morse sequence. static string nthTerm(int n) { // Initialing the // string to 0 string s = \"0\"; // Running the loop // for n - 1 time. for (int i = 1; i < n; i++) // appending the complement of // the string to the string. s += complement(s); return s; } // Driven Code static void Main() { int n = 4; Console.Write(nthTerm(n)); }} // This code is contributed by// Manish Shaw(manishshaw1)", "e": 4901, "s": 3735, "text": null }, { "code": "<?php// PHP Program to find nth// term of Thue-Morse sequence. // Return the complement// of the binary string.function complement($s){ $comps = \"\"; // finding the complement // of the string. for ($i = 0; $i < strlen($s); $i++) { // if character is // 0, append 1 if ($s[$i] == '0') $comps .= '1'; // if character is // 1, append 0. else $comps .= '0'; } return $comps;} // Return the nth term// of Thue-Morse sequence.function nthTerm($n){ // Initialing the // string to 0 $s = \"0\"; // Running the loop // for n - 1 time. for ($i = 1; $i < $n; $i++) // appending the complement of // the string to the string. $s .= complement($s); return $s;} // Driven Code$n = 4;echo nthTerm($n); // This code is contributed// by mits?>", "e": 5773, "s": 4901, "text": null }, { "code": "#include <iostream>using namespace std; int main() { cout<<\"GFG!\"; return 0;}", "e": 5858, "s": 5773, "text": null }, { "code": "<script> // JavaScript Program to find nth// term of Thue-Morse sequence. // Return the complement // of the binary string. function complement(s) { let comps = \"\"; // finding the complement // of the string. for (let i = 0; i < s.length; i++) { // if character is 0, // append 1 if (s[i] == '0') comps += '1'; // if character is 1, // append 0. else comps += '0'; } return comps; } // Return the nth term // of Thue-Morse sequence. function nthTerm(n) { // Initialing the // string to 0 let s = \"0\"; // Running the loop // for n - 1 time. for (let i = 1; i < n; i++) // appending the complement of // the string to the string. s += complement(s); return s; } // Driver program let n = 4; document.write(nthTerm(n)); // This code is contributed by susmitakundugoaldanga.</script>", "e": 6994, "s": 5858, "text": null }, { "code": null, "e": 7004, "s": 6994, "text": "Output: " }, { "code": null, "e": 7013, "s": 7004, "text": "01101001" }, { "code": null, "e": 7027, "s": 7015, "text": "manishshaw1" }, { "code": null, "e": 7040, "s": 7027, "text": "Mithun Kumar" }, { "code": null, "e": 7054, "s": 7040, "text": "ManasChhabra2" }, { "code": null, "e": 7076, "s": 7054, "text": "susmitakundugoaldanga" }, { "code": null, "e": 7090, "s": 7076, "text": "binary-string" }, { "code": null, "e": 7103, "s": 7090, "text": "Mathematical" }, { "code": null, "e": 7111, "s": 7103, "text": "Strings" }, { "code": null, "e": 7119, "s": 7111, "text": "Strings" }, { "code": null, "e": 7132, "s": 7119, "text": "Mathematical" } ]
Node.js URL.href API
14 Oct, 2021 The url.href is an inbuilt application programming interface of class URL with in the url module which Gets and sets the serialized URL. Getting the value of the href property is equivalent to calling the url.toString() method.Setting the value of this property to a new value is equivalent to creating a new URL object using new URL(value). Each of the URL object’s properties will be modified. Syntax: const url.href Return value: It gets and sets the serialized URL.Below programs illustrate the use of url.href Method:Example 1: javascript // node program to demonstrate the // url.href API as Setter //importing the module 'url'const http = require('url'); // creating and initializing myURLconst myURL = new URL('https://example.com:80/foo#ram'); // Display href value of myURL before changeconsole.log("Before Change");console.log(myURL.href); // assigning serialized URL// using hrefconsole.log();myURL.href = 'https://example.com/bar'; // Display href value of myURL after changeconsole.log("After Change");console.log(myURL.href); Output: Example 2: javascript // node program to demonstrate the // url.href API as Getter //importing the module 'url'const http = require('url'); // creating and initializing myURLconst myURL = new URL('https://example.org/foo#ram'); // getting the serialized URL// using hrefconst href = myURL.href; // Display hostname value console.log(href); Output: Reference: https://nodejs.org/api/url.html#url_url_href mridulmanochagfg sweetyty Node-URL Node.js Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to install the previous version of node.js and npm ? Node.js fs.writeFile() Method Difference between promise and async await in Node.js Mongoose | findByIdAndUpdate() Function JWT Authentication with Node.js Installation of Node.js on Windows Node.js forEach() function What are the differences between npm and npx ? How to read and write Excel file in Node.js ? Difference between dependencies, devDependencies and peerDependencies
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Oct, 2021" }, { "code": null, "e": 425, "s": 28, "text": "The url.href is an inbuilt application programming interface of class URL with in the url module which Gets and sets the serialized URL. Getting the value of the href property is equivalent to calling the url.toString() method.Setting the value of this property to a new value is equivalent to creating a new URL object using new URL(value). Each of the URL object’s properties will be modified. " }, { "code": null, "e": 435, "s": 425, "text": "Syntax: " }, { "code": null, "e": 451, "s": 435, "text": "const url.href " }, { "code": null, "e": 567, "s": 451, "text": "Return value: It gets and sets the serialized URL.Below programs illustrate the use of url.href Method:Example 1: " }, { "code": null, "e": 578, "s": 567, "text": "javascript" }, { "code": "// node program to demonstrate the // url.href API as Setter //importing the module 'url'const http = require('url'); // creating and initializing myURLconst myURL = new URL('https://example.com:80/foo#ram'); // Display href value of myURL before changeconsole.log(\"Before Change\");console.log(myURL.href); // assigning serialized URL// using hrefconsole.log();myURL.href = 'https://example.com/bar'; // Display href value of myURL after changeconsole.log(\"After Change\");console.log(myURL.href);", "e": 1086, "s": 578, "text": null }, { "code": null, "e": 1096, "s": 1086, "text": "Output: " }, { "code": null, "e": 1108, "s": 1096, "text": "Example 2: " }, { "code": null, "e": 1119, "s": 1108, "text": "javascript" }, { "code": "// node program to demonstrate the // url.href API as Getter //importing the module 'url'const http = require('url'); // creating and initializing myURLconst myURL = new URL('https://example.org/foo#ram'); // getting the serialized URL// using hrefconst href = myURL.href; // Display hostname value console.log(href);", "e": 1442, "s": 1119, "text": null }, { "code": null, "e": 1452, "s": 1442, "text": "Output: " }, { "code": null, "e": 1508, "s": 1452, "text": "Reference: https://nodejs.org/api/url.html#url_url_href" }, { "code": null, "e": 1525, "s": 1508, "text": "mridulmanochagfg" }, { "code": null, "e": 1534, "s": 1525, "text": "sweetyty" }, { "code": null, "e": 1543, "s": 1534, "text": "Node-URL" }, { "code": null, "e": 1551, "s": 1543, "text": "Node.js" }, { "code": null, "e": 1649, "s": 1551, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1706, "s": 1649, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 1736, "s": 1706, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 1790, "s": 1736, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 1830, "s": 1790, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 1862, "s": 1830, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 1897, "s": 1862, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 1924, "s": 1897, "text": "Node.js forEach() function" }, { "code": null, "e": 1971, "s": 1924, "text": "What are the differences between npm and npx ?" }, { "code": null, "e": 2017, "s": 1971, "text": "How to read and write Excel file in Node.js ?" } ]
Brent's Cycle Detection Algorithm - GeeksforGeeks
CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More Competitive Programming Data Structures with C++ Data Science Explore More Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More DSA- Self Paced CIP JAVA / Python / C++ Explore More School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more School Guide Python Programming Learn To Make Apps Explore more All Courses TutorialsAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin ML & Data ScienceMachine LearningData Science Machine Learning Data Science CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP Software DesignsSoftware Design PatternsSystem Design Tutorial Software Design Patterns System Design Tutorial School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes School Programming MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Student Chapter Geek on the Top Internship Careers JobsApply for JobsPost a JobJOB-A-THON Apply for Jobs Post a Job JOB-A-THON PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems All DSA Problems Problem of the Day Interview Series: Weekly Contests Bi-Wizard Coding: School Contests Contests and Events Practice SDE Sheet Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems Top 50 Array Problems Top 50 String Problems Top 50 Tree Problems Top 50 Graph Problems Top 50 DP Problems WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri Geeks Digest Quizzes Geeks Campus Gblog Articles IDE Campus Mantri Sign In Sign In Home Saved Videos Courses For Working Professionals LIVE DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More Self-Paced DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More For Students LIVE Competitive Programming Data Structures with C++ Data Science Explore More Self-Paced DSA- Self Paced CIP JAVA / Python / C++ Explore More School Courses School Guide Python Programming Learn To Make Apps Explore more Algorithms Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Analysis of Algorithms Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Interview Corner Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes Languages C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin ML & Data Science Machine Learning Data Science CS Subjects Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering GATE GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS Web Technologies HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP Software Designs Software Design Patterns System Design Tutorial School Learning School Programming Mathematics Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Maths Notes (Class 8-12) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes NCERT Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution RD Sharma Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Physics Notes (Class 8-11) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes CS Exams/PSUs ISRO ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam UGC NET UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers Student Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Student Chapter Geek on the Top Internship Careers Curated DSA Lists Top 50 Array Problems Top 50 String Problems Top 50 Tree Problems Top 50 Graph Problems Top 50 DP Problems Tutorials Jobs Apply for Jobs Post a Job JOB-A-THON Practice All DSA Problems Problem of the Day Interview Series: Weekly Contests Bi-Wizard Coding: School Contests Contests and Events Practice SDE Sheet For Working Professionals LIVE DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More Self-Paced DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More For Students LIVE Competitive Programming Data Structures with C++ Data Science Explore More Competitive Programming Data Structures with C++ Data Science Explore More Self-Paced DSA- Self Paced CIP JAVA / Python / C++ Explore More DSA- Self Paced CIP JAVA / Python / C++ Explore More School Courses School Guide Python Programming Learn To Make Apps Explore more School Guide Python Programming Learn To Make Apps Explore more Algorithms Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Analysis of Algorithms Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Interview Corner Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes Languages C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin ML & Data Science Machine Learning Data Science Machine Learning Data Science CS Subjects Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering GATE GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS Web Technologies HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP Software Designs Software Design Patterns System Design Tutorial Software Design Patterns System Design Tutorial School Learning School Programming School Programming Mathematics Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Maths Notes (Class 8-12) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes NCERT Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution RD Sharma Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Physics Notes (Class 8-11) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes CS Exams/PSUs ISRO ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam UGC NET UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers Student Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Student Chapter Geek on the Top Internship Careers Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Student Chapter Geek on the Top Internship Careers Curated DSA Lists Top 50 Array Problems Top 50 String Problems Top 50 Tree Problems Top 50 Graph Problems Top 50 DP Problems Top 50 Array Problems Top 50 String Problems Top 50 Tree Problems Top 50 Graph Problems Top 50 DP Problems Tutorials Jobs Apply for Jobs Post a Job JOB-A-THON Apply for Jobs Post a Job JOB-A-THON Practice All DSA Problems Problem of the Day Interview Series: Weekly Contests Bi-Wizard Coding: School Contests Contests and Events Practice SDE Sheet All DSA Problems Problem of the Day Interview Series: Weekly Contests Bi-Wizard Coding: School Contests Contests and Events Practice SDE Sheet GBlog Puzzles What's New ? Array Matrix Strings Hashing Linked List Stack Queue Binary Tree Binary Search Tree Heap Graph Searching Sorting Divide & Conquer Mathematical Geometric Bitwise Greedy Backtracking Branch and Bound Dynamic Programming Pattern Searching Randomized Linked List | Set 1 (Introduction) Linked List | Set 2 (Inserting a node) Reverse a linked list Stack Data Structure (Introduction and Program) Linked List | Set 3 (Deleting a node) Doubly Linked List | Set 1 (Introduction and Insertion) LinkedList in Java Detect loop in a linked list Linked List vs Array Find the middle of a given linked list Merge two sorted linked lists Implement a stack using singly linked list Queue - Linked List Implementation Delete a Linked List node at a given position Merge Sort for Linked Lists Implementing a Linked List in Java using Class Function to check if a singly linked list is palindrome Find Length of a Linked List (Iterative and Recursive) Detect and Remove Loop in a Linked List Circular Linked List | Set 1 (Introduction and Applications) Reverse a Linked List in groups of given size | Set 1 Search an element in a Linked List (Iterative and Recursive) Program for n'th node from the end of a Linked List Write a function to delete a Linked List Write a function to get the intersection point of two Linked Lists Remove duplicates from a sorted linked list Top 20 Linked List Interview Question Add two numbers represented by linked lists | Set 1 Remove duplicates from an unsorted linked list Write a function to get Nth node in a Linked List Linked List | Set 1 (Introduction) Linked List | Set 2 (Inserting a node) Reverse a linked list Stack Data Structure (Introduction and Program) Linked List | Set 3 (Deleting a node) Doubly Linked List | Set 1 (Introduction and Insertion) LinkedList in Java Detect loop in a linked list Linked List vs Array Find the middle of a given linked list Merge two sorted linked lists Implement a stack using singly linked list Queue - Linked List Implementation Delete a Linked List node at a given position Merge Sort for Linked Lists Implementing a Linked List in Java using Class Function to check if a singly linked list is palindrome Find Length of a Linked List (Iterative and Recursive) Detect and Remove Loop in a Linked List Circular Linked List | Set 1 (Introduction and Applications) Reverse a Linked List in groups of given size | Set 1 Search an element in a Linked List (Iterative and Recursive) Program for n'th node from the end of a Linked List Write a function to delete a Linked List Write a function to get the intersection point of two Linked Lists Remove duplicates from a sorted linked list Top 20 Linked List Interview Question Add two numbers represented by linked lists | Set 1 Remove duplicates from an unsorted linked list Write a function to get Nth node in a Linked List Difficulty Level : Hard Given a linked list, check if the the linked list has loop or not. Below diagram shows a linked list with a loop. We have discussed Floyd’s algorithm to detect cycle in linked list. Brent’s cycle detection algorithm is similar to floyd’s algorithm as it also uses two pointer technique. But there is some difference in their approaches. Here we make one pointer stationary till every iteration and teleport it to other pointer at every power of two. The start of the cycle is determined by the smallest power of two at which they meet. This improves upon the constant factor of Floyd’s algorithm by reducing the number of calls. Move fast pointer (or second_pointer) in powers of 2 until we find a loop. After every power, we reset slow pointer (or first_pointer) to previous value of second pointer. Reset length to 0 after every every power.The condition for loop testing is first_pointer and second_pointer become same. And loop is not present if second_pointer becomes NULL.When we come out of loop, we have length of loop.We reset first_pointer to head and second_pointer to node at position head + length.Now we move both pointers one by one to find beginning of loop. Move fast pointer (or second_pointer) in powers of 2 until we find a loop. After every power, we reset slow pointer (or first_pointer) to previous value of second pointer. Reset length to 0 after every every power. The condition for loop testing is first_pointer and second_pointer become same. And loop is not present if second_pointer becomes NULL. When we come out of loop, we have length of loop. We reset first_pointer to head and second_pointer to node at position head + length. Now we move both pointers one by one to find beginning of loop. Comparison with Floyd’s Algorithm: 1) Finds the length of loop in first cycle detection loop itself. No extra work is required for this. 2) We only move second in every iteration and avoid moving first (which can be costly if moving to next node involves evaluating a function). C++ C Python3 // CPP program to implement Brent's cycle// detection algorithm to detect cycle in// a linked list.#include <iostream>using namespace std; /* Link list node */struct Node { int data; struct Node* next;}; /* This function detects loop in the listIf loop was there in the list then it returns,the first node of loop otherwise returns NULL */struct Node* detectCycle(struct Node* head){ // if head is null then no loop if (head == NULL) return NULL; struct Node* first_pointer = head; struct Node* second_pointer = head->next; int power = 1; int length = 1; // This loop runs till we find the loop. // If there is no loop then second_pointer // ends at NULL . while (second_pointer != NULL && second_pointer != first_pointer) { // condition after which we will // update the power and length as // smallest power of two gives the // start of cycle. if (length == power) { // updating the power. power *= 2; // updating the length length = 0; first_pointer = second_pointer; } second_pointer = second_pointer->next; ++length; } // if it is null then no loop if (second_pointer == NULL) return NULL; // Otherwise length stores actual length // of loop. // If needed, we can also print length of // loop. // printf("Length of loop is %d\n", length); // Now set first_pointer to the beginning // and second_pointer to beginning plus // cycle length which is length. first_pointer = second_pointer = head; while (length > 0) { second_pointer = second_pointer->next; --length; } // Now move both pointers at same speed so // that they meet at the beginning of loop. while (second_pointer != first_pointer) { second_pointer = second_pointer->next; first_pointer = first_pointer->next; } // If needed, we can also print length of // loop. // printf("Length of loop is %d", length); return first_pointer;} struct Node* newNode(int key){ struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); temp->data = key; temp->next = NULL; return temp;} // Driver program to test above functionint main(){ struct Node* head = newNode(50); head->next = newNode(20); head->next->next = newNode(15); head->next->next->next = newNode(4); head->next->next->next->next = newNode(10); // Create a loop for testing head->next->next->next->next->next = head->next->next; Node *res = detectCycle(head); if (res == NULL) cout <<"No loop"; else cout <<"Loop is present at "<< res->data; return 0;} // this code is contributed by shivanisinghss2110 // CPP program to implement Brent's cycle// detection algorithm to detect cycle in// a linked list.#include <stdio.h>#include <stdlib.h> /* Link list node */struct Node { int data; struct Node* next;}; /* This function detects loop in the listIf loop was there in the list then it returns,the first node of loop otherwise returns NULL */struct Node* detectCycle(struct Node* head){ // if head is null then no loop if (head == NULL) return NULL; struct Node* first_pointer = head; struct Node* second_pointer = head->next; int power = 1; int length = 1; // This loop runs till we find the loop. // If there is no loop then second_pointer // ends at NULL . while (second_pointer != NULL && second_pointer != first_pointer) { // condition after which we will // update the power and length as // smallest power of two gives the // start of cycle. if (length == power) { // updating the power. power *= 2; // updating the length length = 0; first_pointer = second_pointer; } second_pointer = second_pointer->next; ++length; } // if it is null then no loop if (second_pointer == NULL) return NULL; // Otherwise length stores actual length // of loop. // If needed, we can also print length of // loop. // printf("Length of loop is %d\n", length); // Now set first_pointer to the beginning // and second_pointer to beginning plus // cycle length which is length. first_pointer = second_pointer = head; while (length > 0) { second_pointer = second_pointer->next; --length; } // Now move both pointers at same speed so // that they meet at the beginning of loop. while (second_pointer != first_pointer) { second_pointer = second_pointer->next; first_pointer = first_pointer->next; } // If needed, we can also print length of // loop. // printf("Length of loop is %d", length); return first_pointer;} struct Node* newNode(int key){ struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); temp->data = key; temp->next = NULL; return temp;} // Driver program to test above functionint main(){ struct Node* head = newNode(50); head->next = newNode(20); head->next->next = newNode(15); head->next->next->next = newNode(4); head->next->next->next->next = newNode(10); // Create a loop for testing head->next->next->next->next->next = head->next->next; Node *res = detectCycle(head); if (res == NULL) printf("No loop"); else printf("Loop is present at %d", res->data); return 0;} # Python program to implement# Brent's cycle detection# algorithm to detect cycle# in a linked list. # Node classclass Node: # Constructor to initialize # the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to insert a new Node # at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Utility function to print # the linked LinkedList def printList(self): temp = self.head while(temp): print (temp.data,end=" ") temp = temp.next def detectCycle(self): # if head is null # then no loop temp=self.head if not (temp): return False first_p=temp second_p=temp.next power = 1 length = 1 # This loop runs till we # find the loop. If there # is no loop then second # pointer ends at NULL while (second_p and second_p!= first_p): # condition after which # we will update the power # and length as smallest # power of two gives # the start of cycle. if (length == power): # updating the power. power *= 2 # updating the length length = 0 first_p = second_p second_p = second_p.next length=length+1 # if it is null then no loop if not (second_p) : return # Otherwise length stores # actual length of loop. # If needed, we can also # print length of loop. # print("Length of loop is ") # print (length) # Now set first_pointer # to the beginning and # second_pointer to # beginning plus cycle # length which is length. first_p = second_p = self.head while (length > 0): second_p = second_p.next length=length-1 # Now move both pointers # at same speed so that # they meet at the # beginning of loop. while (second_p!= first_p) : second_p = second_p.next first_p = first_p.next return first_p # Driver program for testingllist = LinkedList()llist.push(50)llist.push(20)llist.push(15)llist.push(4)llist.push(10) # Create a loop for testingllist.head.next.next.next.next.next = llist.head.next.next;res=llist.detectCycle()if( res.data): print ("loop found at ",end=' ') print (res.data)else : print ("No Loop ") # This code is contributed by Gitanjali Output: Loop is present at 15 Time Complexity: O(m + n) where m is the smallest index of the sequence which is the beginning of a cycle, and n is the cycle’s length. Auxiliary Space : – O(1) auxiliaryReferences : https://en.wikipedia.org/wiki/Cycle_detection#Brent’s_algorithm github anikakapoor shivanisinghss2110 Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Circular Linked List | Set 2 (Traversal) Swap nodes in a linked list without swapping data Program to implement Singly Linked List in C++ using class Circular Singly Linked List | Insertion Given a linked list which is sorted, how will you insert in sorted way Delete a node in a Doubly Linked List Real-time application of Data Structures Linked List Implementation in C# Insert a node at a specific position in a linked list Move last element to front of a given Linked List
[ { "code": null, "e": 419, "s": 0, "text": "CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses" }, { "code": null, "e": 600, "s": 419, "text": "For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More" }, { "code": null, "e": 685, "s": 600, "text": "LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More" }, { "code": null, "e": 702, "s": 685, "text": "DSA Live Classes" }, { "code": null, "e": 716, "s": 702, "text": "System Design" }, { "code": null, "e": 741, "s": 716, "text": "Java Backend Development" }, { "code": null, "e": 757, "s": 741, "text": "Full Stack LIVE" }, { "code": null, "e": 770, "s": 757, "text": "Explore More" }, { "code": null, "e": 842, "s": 770, "text": "Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More" }, { "code": null, "e": 858, "s": 842, "text": "DSA- Self Paced" }, { "code": null, "e": 869, "s": 858, "text": "SDE Theory" }, { "code": null, "e": 894, "s": 869, "text": "Must-Do Coding Questions" }, { "code": null, "e": 907, "s": 894, "text": "Explore More" }, { "code": null, "e": 1054, "s": 907, "text": "For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More" }, { "code": null, "e": 1130, "s": 1054, "text": "LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More" }, { "code": null, "e": 1154, "s": 1130, "text": "Competitive Programming" }, { "code": null, "e": 1179, "s": 1154, "text": "Data Structures with C++" }, { "code": null, "e": 1192, "s": 1179, "text": "Data Science" }, { "code": null, "e": 1205, "s": 1192, "text": "Explore More" }, { "code": null, "e": 1265, "s": 1205, "text": "Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More" }, { "code": null, "e": 1281, "s": 1265, "text": "DSA- Self Paced" }, { "code": null, "e": 1285, "s": 1281, "text": "CIP" }, { "code": null, "e": 1305, "s": 1285, "text": "JAVA / Python / C++" }, { "code": null, "e": 1318, "s": 1305, "text": "Explore More" }, { "code": null, "e": 1393, "s": 1318, "text": "School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more" }, { "code": null, "e": 1406, "s": 1393, "text": "School Guide" }, { "code": null, "e": 1425, "s": 1406, "text": "Python Programming" }, { "code": null, "e": 1444, "s": 1425, "text": "Learn To Make Apps" }, { "code": null, "e": 1457, "s": 1444, "text": "Explore more" }, { "code": null, "e": 1469, "s": 1457, "text": "All Courses" }, { "code": null, "e": 3985, "s": 1469, "text": "TutorialsAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers" }, { "code": null, "e": 4566, "s": 3985, "text": "AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms" }, { "code": null, "e": 4899, "s": 4566, "text": "Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question" }, { "code": null, "e": 4919, "s": 4899, "text": "Asymptotic Analysis" }, { "code": null, "e": 4949, "s": 4919, "text": "Worst, Average and Best Cases" }, { "code": null, "e": 4970, "s": 4949, "text": "Asymptotic Notations" }, { "code": null, "e": 5006, "s": 4970, "text": "Little o and little omega notations" }, { "code": null, "e": 5035, "s": 5006, "text": "Lower and Upper Bound Theory" }, { "code": null, "e": 5053, "s": 5035, "text": "Analysis of Loops" }, { "code": null, "e": 5073, "s": 5053, "text": "Solving Recurrences" }, { "code": null, "e": 5092, "s": 5073, "text": "Amortized Analysis" }, { "code": null, "e": 5128, "s": 5092, "text": "What does 'Space Complexity' mean ?" }, { "code": null, "e": 5157, "s": 5128, "text": "Pseudo-polynomial Algorithms" }, { "code": null, "e": 5194, "s": 5157, "text": "Polynomial Time Approximation Scheme" }, { "code": null, "e": 5221, "s": 5194, "text": "A Time Complexity Question" }, { "code": null, "e": 5242, "s": 5221, "text": "Searching Algorithms" }, { "code": null, "e": 5261, "s": 5242, "text": "Sorting Algorithms" }, { "code": null, "e": 5278, "s": 5261, "text": "Graph Algorithms" }, { "code": null, "e": 5296, "s": 5278, "text": "Pattern Searching" }, { "code": null, "e": 5317, "s": 5296, "text": "Geometric Algorithms" }, { "code": null, "e": 5330, "s": 5317, "text": "Mathematical" }, { "code": null, "e": 5349, "s": 5330, "text": "Bitwise Algorithms" }, { "code": null, "e": 5371, "s": 5349, "text": "Randomized Algorithms" }, { "code": null, "e": 5389, "s": 5371, "text": "Greedy Algorithms" }, { "code": null, "e": 5409, "s": 5389, "text": "Dynamic Programming" }, { "code": null, "e": 5428, "s": 5409, "text": "Divide and Conquer" }, { "code": null, "e": 5441, "s": 5428, "text": "Backtracking" }, { "code": null, "e": 5458, "s": 5441, "text": "Branch and Bound" }, { "code": null, "e": 5473, "s": 5458, "text": "All Algorithms" }, { "code": null, "e": 5616, "s": 5473, "text": "Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures" }, { "code": null, "e": 5623, "s": 5616, "text": "Arrays" }, { "code": null, "e": 5635, "s": 5623, "text": "Linked List" }, { "code": null, "e": 5641, "s": 5635, "text": "Stack" }, { "code": null, "e": 5647, "s": 5641, "text": "Queue" }, { "code": null, "e": 5659, "s": 5647, "text": "Binary Tree" }, { "code": null, "e": 5678, "s": 5659, "text": "Binary Search Tree" }, { "code": null, "e": 5683, "s": 5678, "text": "Heap" }, { "code": null, "e": 5691, "s": 5683, "text": "Hashing" }, { "code": null, "e": 5697, "s": 5691, "text": "Graph" }, { "code": null, "e": 5721, "s": 5697, "text": "Advanced Data Structure" }, { "code": null, "e": 5728, "s": 5721, "text": "Matrix" }, { "code": null, "e": 5736, "s": 5728, "text": "Strings" }, { "code": null, "e": 5756, "s": 5736, "text": "All Data Structures" }, { "code": null, "e": 5976, "s": 5756, "text": "Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes" }, { "code": null, "e": 5996, "s": 5976, "text": "Company Preparation" }, { "code": null, "e": 6007, "s": 5996, "text": "Top Topics" }, { "code": null, "e": 6034, "s": 6007, "text": "Practice Company Questions" }, { "code": null, "e": 6056, "s": 6034, "text": "Interview Experiences" }, { "code": null, "e": 6079, "s": 6056, "text": "Experienced Interviews" }, { "code": null, "e": 6101, "s": 6079, "text": "Internship Interviews" }, { "code": null, "e": 6126, "s": 6101, "text": "Competititve Programming" }, { "code": null, "e": 6142, "s": 6126, "text": "Design Patterns" }, { "code": null, "e": 6165, "s": 6142, "text": "System Design Tutorial" }, { "code": null, "e": 6189, "s": 6165, "text": "Multiple Choice Quizzes" }, { "code": null, "e": 6270, "s": 6189, "text": "LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin" }, { "code": null, "e": 6272, "s": 6270, "text": "C" }, { "code": null, "e": 6276, "s": 6272, "text": "C++" }, { "code": null, "e": 6281, "s": 6276, "text": "Java" }, { "code": null, "e": 6288, "s": 6281, "text": "Python" }, { "code": null, "e": 6291, "s": 6288, "text": "C#" }, { "code": null, "e": 6302, "s": 6291, "text": "JavaScript" }, { "code": null, "e": 6309, "s": 6302, "text": "jQuery" }, { "code": null, "e": 6313, "s": 6309, "text": "SQL" }, { "code": null, "e": 6317, "s": 6313, "text": "PHP" }, { "code": null, "e": 6323, "s": 6317, "text": "Scala" }, { "code": null, "e": 6328, "s": 6323, "text": "Perl" }, { "code": null, "e": 6340, "s": 6328, "text": "Go Language" }, { "code": null, "e": 6345, "s": 6340, "text": "HTML" }, { "code": null, "e": 6349, "s": 6345, "text": "CSS" }, { "code": null, "e": 6356, "s": 6349, "text": "Kotlin" }, { "code": null, "e": 6402, "s": 6356, "text": "ML & Data ScienceMachine LearningData Science" }, { "code": null, "e": 6419, "s": 6402, "text": "Machine Learning" }, { "code": null, "e": 6432, "s": 6419, "text": "Data Science" }, { "code": null, "e": 6599, "s": 6432, "text": "CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering" }, { "code": null, "e": 6611, "s": 6599, "text": "Mathematics" }, { "code": null, "e": 6628, "s": 6611, "text": "Operating System" }, { "code": null, "e": 6633, "s": 6628, "text": "DBMS" }, { "code": null, "e": 6651, "s": 6633, "text": "Computer Networks" }, { "code": null, "e": 6690, "s": 6651, "text": "Computer Organization and Architecture" }, { "code": null, "e": 6712, "s": 6690, "text": "Theory of Computation" }, { "code": null, "e": 6728, "s": 6712, "text": "Compiler Design" }, { "code": null, "e": 6742, "s": 6728, "text": "Digital Logic" }, { "code": null, "e": 6763, "s": 6742, "text": "Software Engineering" }, { "code": null, "e": 6938, "s": 6763, "text": "GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS" }, { "code": null, "e": 6966, "s": 6938, "text": "GATE Computer Science Notes" }, { "code": null, "e": 6984, "s": 6966, "text": "Last Minute Notes" }, { "code": null, "e": 7006, "s": 6984, "text": "GATE CS Solved Papers" }, { "code": null, "e": 7048, "s": 7006, "text": "GATE CS Original Papers and Official Keys" }, { "code": null, "e": 7064, "s": 7048, "text": "GATE 2021 Dates" }, { "code": null, "e": 7086, "s": 7064, "text": "GATE CS 2021 Syllabus" }, { "code": null, "e": 7115, "s": 7086, "text": "Important Topics for GATE CS" }, { "code": null, "e": 7189, "s": 7115, "text": "Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP" }, { "code": null, "e": 7194, "s": 7189, "text": "HTML" }, { "code": null, "e": 7198, "s": 7194, "text": "CSS" }, { "code": null, "e": 7209, "s": 7198, "text": "JavaScript" }, { "code": null, "e": 7219, "s": 7209, "text": "AngularJS" }, { "code": null, "e": 7227, "s": 7219, "text": "ReactJS" }, { "code": null, "e": 7234, "s": 7227, "text": "NodeJS" }, { "code": null, "e": 7244, "s": 7234, "text": "Bootstrap" }, { "code": null, "e": 7251, "s": 7244, "text": "jQuery" }, { "code": null, "e": 7255, "s": 7251, "text": "PHP" }, { "code": null, "e": 7318, "s": 7255, "text": "Software DesignsSoftware Design PatternsSystem Design Tutorial" }, { "code": null, "e": 7343, "s": 7318, "text": "Software Design Patterns" }, { "code": null, "e": 7366, "s": 7343, "text": "System Design Tutorial" }, { "code": null, "e": 7923, "s": 7366, "text": "School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes" }, { "code": null, "e": 7942, "s": 7923, "text": "School Programming" }, { "code": null, "e": 8034, "s": 7942, "text": "MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus" }, { "code": null, "e": 8048, "s": 8034, "text": "Number System" }, { "code": null, "e": 8056, "s": 8048, "text": "Algebra" }, { "code": null, "e": 8069, "s": 8056, "text": "Trigonometry" }, { "code": null, "e": 8080, "s": 8069, "text": "Statistics" }, { "code": null, "e": 8092, "s": 8080, "text": "Probability" }, { "code": null, "e": 8101, "s": 8092, "text": "Geometry" }, { "code": null, "e": 8113, "s": 8101, "text": "Mensuration" }, { "code": null, "e": 8122, "s": 8113, "text": "Calculus" }, { "code": null, "e": 8215, "s": 8122, "text": "Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes" }, { "code": null, "e": 8229, "s": 8215, "text": "Class 8 Notes" }, { "code": null, "e": 8243, "s": 8229, "text": "Class 9 Notes" }, { "code": null, "e": 8258, "s": 8243, "text": "Class 10 Notes" }, { "code": null, "e": 8273, "s": 8258, "text": "Class 11 Notes" }, { "code": null, "e": 8288, "s": 8273, "text": "Class 12 Notes" }, { "code": null, "e": 8417, "s": 8288, "text": "NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution" }, { "code": null, "e": 8440, "s": 8417, "text": "Class 8 Maths Solution" }, { "code": null, "e": 8463, "s": 8440, "text": "Class 9 Maths Solution" }, { "code": null, "e": 8487, "s": 8463, "text": "Class 10 Maths Solution" }, { "code": null, "e": 8511, "s": 8487, "text": "Class 11 Maths Solution" }, { "code": null, "e": 8535, "s": 8511, "text": "Class 12 Maths Solution" }, { "code": null, "e": 8668, "s": 8535, "text": "RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution" }, { "code": null, "e": 8691, "s": 8668, "text": "Class 8 Maths Solution" }, { "code": null, "e": 8714, "s": 8691, "text": "Class 9 Maths Solution" }, { "code": null, "e": 8738, "s": 8714, "text": "Class 10 Maths Solution" }, { "code": null, "e": 8762, "s": 8738, "text": "Class 11 Maths Solution" }, { "code": null, "e": 8786, "s": 8762, "text": "Class 12 Maths Solution" }, { "code": null, "e": 8867, "s": 8786, "text": "Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes" }, { "code": null, "e": 8881, "s": 8867, "text": "Class 8 Notes" }, { "code": null, "e": 8895, "s": 8881, "text": "Class 9 Notes" }, { "code": null, "e": 8910, "s": 8895, "text": "Class 10 Notes" }, { "code": null, "e": 8925, "s": 8910, "text": "Class 11 Notes" }, { "code": null, "e": 9131, "s": 8925, "text": "CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers" }, { "code": null, "e": 9242, "s": 9131, "text": "ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam" }, { "code": null, "e": 9284, "s": 9242, "text": "ISRO CS Original Papers and Official Keys" }, { "code": null, "e": 9306, "s": 9284, "text": "ISRO CS Solved Papers" }, { "code": null, "e": 9351, "s": 9306, "text": "ISRO CS Syllabus for Scientist/Engineer Exam" }, { "code": null, "e": 9434, "s": 9351, "text": "UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers" }, { "code": null, "e": 9460, "s": 9434, "text": "UGC NET CS Notes Paper II" }, { "code": null, "e": 9487, "s": 9460, "text": "UGC NET CS Notes Paper III" }, { "code": null, "e": 9512, "s": 9487, "text": "UGC NET CS Solved Papers" }, { "code": null, "e": 9717, "s": 9512, "text": "StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers" }, { "code": null, "e": 9743, "s": 9717, "text": "Campus Ambassador Program" }, { "code": null, "e": 9769, "s": 9743, "text": "School Ambassador Program" }, { "code": null, "e": 9777, "s": 9769, "text": "Project" }, { "code": null, "e": 9795, "s": 9777, "text": "Geek of the Month" }, { "code": null, "e": 9820, "s": 9795, "text": "Campus Geek of the Month" }, { "code": null, "e": 9837, "s": 9820, "text": "Placement Course" }, { "code": null, "e": 9862, "s": 9837, "text": "Competititve Programming" }, { "code": null, "e": 9875, "s": 9862, "text": "Testimonials" }, { "code": null, "e": 9891, "s": 9875, "text": "Student Chapter" }, { "code": null, "e": 9907, "s": 9891, "text": "Geek on the Top" }, { "code": null, "e": 9918, "s": 9907, "text": "Internship" }, { "code": null, "e": 9926, "s": 9918, "text": "Careers" }, { "code": null, "e": 9965, "s": 9926, "text": "JobsApply for JobsPost a JobJOB-A-THON" }, { "code": null, "e": 9980, "s": 9965, "text": "Apply for Jobs" }, { "code": null, "e": 9991, "s": 9980, "text": "Post a Job" }, { "code": null, "e": 10002, "s": 9991, "text": "JOB-A-THON" }, { "code": null, "e": 10267, "s": 10002, "text": "PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems" }, { "code": null, "e": 10284, "s": 10267, "text": "All DSA Problems" }, { "code": null, "e": 10303, "s": 10284, "text": "Problem of the Day" }, { "code": null, "e": 10337, "s": 10303, "text": "Interview Series: Weekly Contests" }, { "code": null, "e": 10371, "s": 10337, "text": "Bi-Wizard Coding: School Contests" }, { "code": null, "e": 10391, "s": 10371, "text": "Contests and Events" }, { "code": null, "e": 10410, "s": 10391, "text": "Practice SDE Sheet" }, { "code": null, "e": 10530, "s": 10410, "text": "Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems" }, { "code": null, "e": 10552, "s": 10530, "text": "Top 50 Array Problems" }, { "code": null, "e": 10575, "s": 10552, "text": "Top 50 String Problems" }, { "code": null, "e": 10596, "s": 10575, "text": "Top 50 Tree Problems" }, { "code": null, "e": 10618, "s": 10596, "text": "Top 50 Graph Problems" }, { "code": null, "e": 10637, "s": 10618, "text": "Top 50 DP Problems" }, { "code": null, "e": 10908, "s": 10641, "text": "WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri" }, { "code": null, "e": 10921, "s": 10908, "text": "Geeks Digest" }, { "code": null, "e": 10929, "s": 10921, "text": "Quizzes" }, { "code": null, "e": 10942, "s": 10929, "text": "Geeks Campus" }, { "code": null, "e": 10957, "s": 10942, "text": "Gblog Articles" }, { "code": null, "e": 10961, "s": 10957, "text": "IDE" }, { "code": null, "e": 10975, "s": 10961, "text": "Campus Mantri" }, { "code": null, "e": 10983, "s": 10975, "text": "Sign In" }, { "code": null, "e": 10991, "s": 10983, "text": "Sign In" }, { "code": null, "e": 10996, "s": 10991, "text": "Home" }, { "code": null, "e": 11009, "s": 10996, "text": "Saved Videos" }, { "code": null, "e": 11017, "s": 11009, "text": "Courses" }, { "code": null, "e": 15482, "s": 11017, "text": "\n\nFor Working Professionals\n \n\n\n\nLIVE\n \n\n\nDSA Live Classes\n\nSystem Design\n\nJava Backend Development\n\nFull Stack LIVE\n\nExplore More\n\n\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nSDE Theory\n\nMust-Do Coding Questions\n\nExplore More\n\n\nFor Students\n \n\n\n\nLIVE\n \n\n\nCompetitive Programming\n\nData Structures with C++\n\nData Science\n\nExplore More\n\n\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nCIP\n\nJAVA / Python / C++\n\nExplore More\n\n\nSchool Courses\n \n\n\nSchool Guide\n\nPython Programming\n\nLearn To Make Apps\n\nExplore more\n\n\nAlgorithms\n \n\n\nSearching Algorithms\n\nSorting Algorithms\n\nGraph Algorithms\n\nPattern Searching\n\nGeometric Algorithms\n\nMathematical\n\nBitwise Algorithms\n\nRandomized Algorithms\n\nGreedy Algorithms\n\nDynamic Programming\n\nDivide and Conquer\n\nBacktracking\n\nBranch and Bound\n\nAll Algorithms\n\n\nAnalysis of Algorithms\n \n\n\nAsymptotic Analysis\n\nWorst, Average and Best Cases\n\nAsymptotic Notations\n\nLittle o and little omega notations\n\nLower and Upper Bound Theory\n\nAnalysis of Loops\n\nSolving Recurrences\n\nAmortized Analysis\n\nWhat does 'Space Complexity' mean ?\n\nPseudo-polynomial Algorithms\n\nPolynomial Time Approximation Scheme\n\nA Time Complexity Question\n\n\nData Structures\n \n\n\nArrays\n\nLinked List\n\nStack\n\nQueue\n\nBinary Tree\n\nBinary Search Tree\n\nHeap\n\nHashing\n\nGraph\n\nAdvanced Data Structure\n\nMatrix\n\nStrings\n\nAll Data Structures\n\n\nInterview Corner\n \n\n\nCompany Preparation\n\nTop Topics\n\nPractice Company Questions\n\nInterview Experiences\n\nExperienced Interviews\n\nInternship Interviews\n\nCompetititve Programming\n\nDesign Patterns\n\nSystem Design Tutorial\n\nMultiple Choice Quizzes\n\n\nLanguages\n \n\n\nC\n\nC++\n\nJava\n\nPython\n\nC#\n\nJavaScript\n\njQuery\n\nSQL\n\nPHP\n\nScala\n\nPerl\n\nGo Language\n\nHTML\n\nCSS\n\nKotlin\n\n\nML & Data Science\n \n\n\nMachine Learning\n\nData Science\n\n\nCS Subjects\n \n\n\nMathematics\n\nOperating System\n\nDBMS\n\nComputer Networks\n\nComputer Organization and Architecture\n\nTheory of Computation\n\nCompiler Design\n\nDigital Logic\n\nSoftware Engineering\n\n\nGATE\n \n\n\nGATE Computer Science Notes\n\nLast Minute Notes\n\nGATE CS Solved Papers\n\nGATE CS Original Papers and Official Keys\n\nGATE 2021 Dates\n\nGATE CS 2021 Syllabus\n\nImportant Topics for GATE CS\n\n\nWeb Technologies\n \n\n\nHTML\n\nCSS\n\nJavaScript\n\nAngularJS\n\nReactJS\n\nNodeJS\n\nBootstrap\n\njQuery\n\nPHP\n\n\nSoftware Designs\n \n\n\nSoftware Design Patterns\n\nSystem Design Tutorial\n\n\nSchool Learning\n \n\n\nSchool Programming\n\n\nMathematics\n \n\n\nNumber System\n\nAlgebra\n\nTrigonometry\n\nStatistics\n\nProbability\n\nGeometry\n\nMensuration\n\nCalculus\n\n\nMaths Notes (Class 8-12)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\nClass 12 Notes\n\n\nNCERT Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n\n\nRD Sharma Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n\n\nPhysics Notes (Class 8-11)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\n\nCS Exams/PSUs\n \n\n\n\nISRO\n \n\n\nISRO CS Original Papers and Official Keys\n\nISRO CS Solved Papers\n\nISRO CS Syllabus for Scientist/Engineer Exam\n\n\nUGC NET\n \n\n\nUGC NET CS Notes Paper II\n\nUGC NET CS Notes Paper III\n\nUGC NET CS Solved Papers\n\n\nStudent\n \n\n\nCampus Ambassador Program\n\nSchool Ambassador Program\n\nProject\n\nGeek of the Month\n\nCampus Geek of the Month\n\nPlacement Course\n\nCompetititve Programming\n\nTestimonials\n\nStudent Chapter\n\nGeek on the Top\n\nInternship\n\nCareers\n\n\nCurated DSA Lists\n \n\n\nTop 50 Array Problems\n\nTop 50 String Problems\n\nTop 50 Tree Problems\n\nTop 50 Graph Problems\n\nTop 50 DP Problems\n\n\nTutorials\n \n\n\n\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n\n\nPractice\n \n\n\nAll DSA Problems\n\nProblem of the Day\n\nInterview Series: Weekly Contests\n\nBi-Wizard Coding: School Contests\n\nContests and Events\n\nPractice SDE Sheet\n" }, { "code": null, "e": 15536, "s": 15482, "text": "\nFor Working Professionals\n \n\n" }, { "code": null, "e": 15659, "s": 15536, "text": "\nLIVE\n \n\n\nDSA Live Classes\n\nSystem Design\n\nJava Backend Development\n\nFull Stack LIVE\n\nExplore More\n" }, { "code": null, "e": 15678, "s": 15659, "text": "\nDSA Live Classes\n" }, { "code": null, "e": 15694, "s": 15678, "text": "\nSystem Design\n" }, { "code": null, "e": 15721, "s": 15694, "text": "\nJava Backend Development\n" }, { "code": null, "e": 15739, "s": 15721, "text": "\nFull Stack LIVE\n" }, { "code": null, "e": 15754, "s": 15739, "text": "\nExplore More\n" }, { "code": null, "e": 15862, "s": 15754, "text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nSDE Theory\n\nMust-Do Coding Questions\n\nExplore More\n" }, { "code": null, "e": 15880, "s": 15862, "text": "\nDSA- Self Paced\n" }, { "code": null, "e": 15893, "s": 15880, "text": "\nSDE Theory\n" }, { "code": null, "e": 15920, "s": 15893, "text": "\nMust-Do Coding Questions\n" }, { "code": null, "e": 15935, "s": 15920, "text": "\nExplore More\n" }, { "code": null, "e": 15976, "s": 15935, "text": "\nFor Students\n \n\n" }, { "code": null, "e": 16088, "s": 15976, "text": "\nLIVE\n \n\n\nCompetitive Programming\n\nData Structures with C++\n\nData Science\n\nExplore More\n" }, { "code": null, "e": 16114, "s": 16088, "text": "\nCompetitive Programming\n" }, { "code": null, "e": 16141, "s": 16114, "text": "\nData Structures with C++\n" }, { "code": null, "e": 16156, "s": 16141, "text": "\nData Science\n" }, { "code": null, "e": 16171, "s": 16156, "text": "\nExplore More\n" }, { "code": null, "e": 16267, "s": 16171, "text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nCIP\n\nJAVA / Python / C++\n\nExplore More\n" }, { "code": null, "e": 16285, "s": 16267, "text": "\nDSA- Self Paced\n" }, { "code": null, "e": 16291, "s": 16285, "text": "\nCIP\n" }, { "code": null, "e": 16313, "s": 16291, "text": "\nJAVA / Python / C++\n" }, { "code": null, "e": 16328, "s": 16313, "text": "\nExplore More\n" }, { "code": null, "e": 16439, "s": 16328, "text": "\nSchool Courses\n \n\n\nSchool Guide\n\nPython Programming\n\nLearn To Make Apps\n\nExplore more\n" }, { "code": null, "e": 16454, "s": 16439, "text": "\nSchool Guide\n" }, { "code": null, "e": 16475, "s": 16454, "text": "\nPython Programming\n" }, { "code": null, "e": 16496, "s": 16475, "text": "\nLearn To Make Apps\n" }, { "code": null, "e": 16511, "s": 16496, "text": "\nExplore more\n" }, { "code": null, "e": 16816, "s": 16511, "text": "\nAlgorithms\n \n\n\nSearching Algorithms\n\nSorting Algorithms\n\nGraph Algorithms\n\nPattern Searching\n\nGeometric Algorithms\n\nMathematical\n\nBitwise Algorithms\n\nRandomized Algorithms\n\nGreedy Algorithms\n\nDynamic Programming\n\nDivide and Conquer\n\nBacktracking\n\nBranch and Bound\n\nAll Algorithms\n" }, { "code": null, "e": 16839, "s": 16816, "text": "\nSearching Algorithms\n" }, { "code": null, "e": 16860, "s": 16839, "text": "\nSorting Algorithms\n" }, { "code": null, "e": 16879, "s": 16860, "text": "\nGraph Algorithms\n" }, { "code": null, "e": 16899, "s": 16879, "text": "\nPattern Searching\n" }, { "code": null, "e": 16922, "s": 16899, "text": "\nGeometric Algorithms\n" }, { "code": null, "e": 16937, "s": 16922, "text": "\nMathematical\n" }, { "code": null, "e": 16958, "s": 16937, "text": "\nBitwise Algorithms\n" }, { "code": null, "e": 16982, "s": 16958, "text": "\nRandomized Algorithms\n" }, { "code": null, "e": 17002, "s": 16982, "text": "\nGreedy Algorithms\n" }, { "code": null, "e": 17024, "s": 17002, "text": "\nDynamic Programming\n" }, { "code": null, "e": 17045, "s": 17024, "text": "\nDivide and Conquer\n" }, { "code": null, "e": 17060, "s": 17045, "text": "\nBacktracking\n" }, { "code": null, "e": 17079, "s": 17060, "text": "\nBranch and Bound\n" }, { "code": null, "e": 17096, "s": 17079, "text": "\nAll Algorithms\n" }, { "code": null, "e": 17481, "s": 17096, "text": "\nAnalysis of Algorithms\n \n\n\nAsymptotic Analysis\n\nWorst, Average and Best Cases\n\nAsymptotic Notations\n\nLittle o and little omega notations\n\nLower and Upper Bound Theory\n\nAnalysis of Loops\n\nSolving Recurrences\n\nAmortized Analysis\n\nWhat does 'Space Complexity' mean ?\n\nPseudo-polynomial Algorithms\n\nPolynomial Time Approximation Scheme\n\nA Time Complexity Question\n" }, { "code": null, "e": 17503, "s": 17481, "text": "\nAsymptotic Analysis\n" }, { "code": null, "e": 17535, "s": 17503, "text": "\nWorst, Average and Best Cases\n" }, { "code": null, "e": 17558, "s": 17535, "text": "\nAsymptotic Notations\n" }, { "code": null, "e": 17596, "s": 17558, "text": "\nLittle o and little omega notations\n" }, { "code": null, "e": 17627, "s": 17596, "text": "\nLower and Upper Bound Theory\n" }, { "code": null, "e": 17647, "s": 17627, "text": "\nAnalysis of Loops\n" }, { "code": null, "e": 17669, "s": 17647, "text": "\nSolving Recurrences\n" }, { "code": null, "e": 17690, "s": 17669, "text": "\nAmortized Analysis\n" }, { "code": null, "e": 17728, "s": 17690, "text": "\nWhat does 'Space Complexity' mean ?\n" }, { "code": null, "e": 17759, "s": 17728, "text": "\nPseudo-polynomial Algorithms\n" }, { "code": null, "e": 17798, "s": 17759, "text": "\nPolynomial Time Approximation Scheme\n" }, { "code": null, "e": 17827, "s": 17798, "text": "\nA Time Complexity Question\n" }, { "code": null, "e": 18024, "s": 17827, "text": "\nData Structures\n \n\n\nArrays\n\nLinked List\n\nStack\n\nQueue\n\nBinary Tree\n\nBinary Search Tree\n\nHeap\n\nHashing\n\nGraph\n\nAdvanced Data Structure\n\nMatrix\n\nStrings\n\nAll Data Structures\n" }, { "code": null, "e": 18033, "s": 18024, "text": "\nArrays\n" }, { "code": null, "e": 18047, "s": 18033, "text": "\nLinked List\n" }, { "code": null, "e": 18055, "s": 18047, "text": "\nStack\n" }, { "code": null, "e": 18063, "s": 18055, "text": "\nQueue\n" }, { "code": null, "e": 18077, "s": 18063, "text": "\nBinary Tree\n" }, { "code": null, "e": 18098, "s": 18077, "text": "\nBinary Search Tree\n" }, { "code": null, "e": 18105, "s": 18098, "text": "\nHeap\n" }, { "code": null, "e": 18115, "s": 18105, "text": "\nHashing\n" }, { "code": null, "e": 18123, "s": 18115, "text": "\nGraph\n" }, { "code": null, "e": 18149, "s": 18123, "text": "\nAdvanced Data Structure\n" }, { "code": null, "e": 18158, "s": 18149, "text": "\nMatrix\n" }, { "code": null, "e": 18168, "s": 18158, "text": "\nStrings\n" }, { "code": null, "e": 18190, "s": 18168, "text": "\nAll Data Structures\n" }, { "code": null, "e": 18458, "s": 18190, "text": "\nInterview Corner\n \n\n\nCompany Preparation\n\nTop Topics\n\nPractice Company Questions\n\nInterview Experiences\n\nExperienced Interviews\n\nInternship Interviews\n\nCompetititve Programming\n\nDesign Patterns\n\nSystem Design Tutorial\n\nMultiple Choice Quizzes\n" }, { "code": null, "e": 18480, "s": 18458, "text": "\nCompany Preparation\n" }, { "code": null, "e": 18493, "s": 18480, "text": "\nTop Topics\n" }, { "code": null, "e": 18522, "s": 18493, "text": "\nPractice Company Questions\n" }, { "code": null, "e": 18546, "s": 18522, "text": "\nInterview Experiences\n" }, { "code": null, "e": 18571, "s": 18546, "text": "\nExperienced Interviews\n" }, { "code": null, "e": 18595, "s": 18571, "text": "\nInternship Interviews\n" }, { "code": null, "e": 18622, "s": 18595, "text": "\nCompetititve Programming\n" }, { "code": null, "e": 18640, "s": 18622, "text": "\nDesign Patterns\n" }, { "code": null, "e": 18665, "s": 18640, "text": "\nSystem Design Tutorial\n" }, { "code": null, "e": 18691, "s": 18665, "text": "\nMultiple Choice Quizzes\n" }, { "code": null, "e": 18830, "s": 18691, "text": "\nLanguages\n \n\n\nC\n\nC++\n\nJava\n\nPython\n\nC#\n\nJavaScript\n\njQuery\n\nSQL\n\nPHP\n\nScala\n\nPerl\n\nGo Language\n\nHTML\n\nCSS\n\nKotlin\n" }, { "code": null, "e": 18834, "s": 18830, "text": "\nC\n" }, { "code": null, "e": 18840, "s": 18834, "text": "\nC++\n" }, { "code": null, "e": 18847, "s": 18840, "text": "\nJava\n" }, { "code": null, "e": 18856, "s": 18847, "text": "\nPython\n" }, { "code": null, "e": 18861, "s": 18856, "text": "\nC#\n" }, { "code": null, "e": 18874, "s": 18861, "text": "\nJavaScript\n" }, { "code": null, "e": 18883, "s": 18874, "text": "\njQuery\n" }, { "code": null, "e": 18889, "s": 18883, "text": "\nSQL\n" }, { "code": null, "e": 18895, "s": 18889, "text": "\nPHP\n" }, { "code": null, "e": 18903, "s": 18895, "text": "\nScala\n" }, { "code": null, "e": 18910, "s": 18903, "text": "\nPerl\n" }, { "code": null, "e": 18924, "s": 18910, "text": "\nGo Language\n" }, { "code": null, "e": 18931, "s": 18924, "text": "\nHTML\n" }, { "code": null, "e": 18937, "s": 18931, "text": "\nCSS\n" }, { "code": null, "e": 18946, "s": 18937, "text": "\nKotlin\n" }, { "code": null, "e": 19024, "s": 18946, "text": "\nML & Data Science\n \n\n\nMachine Learning\n\nData Science\n" }, { "code": null, "e": 19043, "s": 19024, "text": "\nMachine Learning\n" }, { "code": null, "e": 19058, "s": 19043, "text": "\nData Science\n" }, { "code": null, "e": 19271, "s": 19058, "text": "\nCS Subjects\n \n\n\nMathematics\n\nOperating System\n\nDBMS\n\nComputer Networks\n\nComputer Organization and Architecture\n\nTheory of Computation\n\nCompiler Design\n\nDigital Logic\n\nSoftware Engineering\n" }, { "code": null, "e": 19285, "s": 19271, "text": "\nMathematics\n" }, { "code": null, "e": 19304, "s": 19285, "text": "\nOperating System\n" }, { "code": null, "e": 19311, "s": 19304, "text": "\nDBMS\n" }, { "code": null, "e": 19331, "s": 19311, "text": "\nComputer Networks\n" }, { "code": null, "e": 19372, "s": 19331, "text": "\nComputer Organization and Architecture\n" }, { "code": null, "e": 19396, "s": 19372, "text": "\nTheory of Computation\n" }, { "code": null, "e": 19414, "s": 19396, "text": "\nCompiler Design\n" }, { "code": null, "e": 19430, "s": 19414, "text": "\nDigital Logic\n" }, { "code": null, "e": 19453, "s": 19430, "text": "\nSoftware Engineering\n" }, { "code": null, "e": 19670, "s": 19453, "text": "\nGATE\n \n\n\nGATE Computer Science Notes\n\nLast Minute Notes\n\nGATE CS Solved Papers\n\nGATE CS Original Papers and Official Keys\n\nGATE 2021 Dates\n\nGATE CS 2021 Syllabus\n\nImportant Topics for GATE CS\n" }, { "code": null, "e": 19700, "s": 19670, "text": "\nGATE Computer Science Notes\n" }, { "code": null, "e": 19720, "s": 19700, "text": "\nLast Minute Notes\n" }, { "code": null, "e": 19744, "s": 19720, "text": "\nGATE CS Solved Papers\n" }, { "code": null, "e": 19788, "s": 19744, "text": "\nGATE CS Original Papers and Official Keys\n" }, { "code": null, "e": 19806, "s": 19788, "text": "\nGATE 2021 Dates\n" }, { "code": null, "e": 19830, "s": 19806, "text": "\nGATE CS 2021 Syllabus\n" }, { "code": null, "e": 19861, "s": 19830, "text": "\nImportant Topics for GATE CS\n" }, { "code": null, "e": 19981, "s": 19861, "text": "\nWeb Technologies\n \n\n\nHTML\n\nCSS\n\nJavaScript\n\nAngularJS\n\nReactJS\n\nNodeJS\n\nBootstrap\n\njQuery\n\nPHP\n" }, { "code": null, "e": 19988, "s": 19981, "text": "\nHTML\n" }, { "code": null, "e": 19994, "s": 19988, "text": "\nCSS\n" }, { "code": null, "e": 20007, "s": 19994, "text": "\nJavaScript\n" }, { "code": null, "e": 20019, "s": 20007, "text": "\nAngularJS\n" }, { "code": null, "e": 20029, "s": 20019, "text": "\nReactJS\n" }, { "code": null, "e": 20038, "s": 20029, "text": "\nNodeJS\n" }, { "code": null, "e": 20050, "s": 20038, "text": "\nBootstrap\n" }, { "code": null, "e": 20059, "s": 20050, "text": "\njQuery\n" }, { "code": null, "e": 20065, "s": 20059, "text": "\nPHP\n" }, { "code": null, "e": 20160, "s": 20065, "text": "\nSoftware Designs\n \n\n\nSoftware Design Patterns\n\nSystem Design Tutorial\n" }, { "code": null, "e": 20187, "s": 20160, "text": "\nSoftware Design Patterns\n" }, { "code": null, "e": 20212, "s": 20187, "text": "\nSystem Design Tutorial\n" }, { "code": null, "e": 20276, "s": 20212, "text": "\nSchool Learning\n \n\n\nSchool Programming\n" }, { "code": null, "e": 20297, "s": 20276, "text": "\nSchool Programming\n" }, { "code": null, "e": 20433, "s": 20297, "text": "\nMathematics\n \n\n\nNumber System\n\nAlgebra\n\nTrigonometry\n\nStatistics\n\nProbability\n\nGeometry\n\nMensuration\n\nCalculus\n" }, { "code": null, "e": 20449, "s": 20433, "text": "\nNumber System\n" }, { "code": null, "e": 20459, "s": 20449, "text": "\nAlgebra\n" }, { "code": null, "e": 20474, "s": 20459, "text": "\nTrigonometry\n" }, { "code": null, "e": 20487, "s": 20474, "text": "\nStatistics\n" }, { "code": null, "e": 20501, "s": 20487, "text": "\nProbability\n" }, { "code": null, "e": 20512, "s": 20501, "text": "\nGeometry\n" }, { "code": null, "e": 20526, "s": 20512, "text": "\nMensuration\n" }, { "code": null, "e": 20537, "s": 20526, "text": "\nCalculus\n" }, { "code": null, "e": 20668, "s": 20537, "text": "\nMaths Notes (Class 8-12)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\nClass 12 Notes\n" }, { "code": null, "e": 20684, "s": 20668, "text": "\nClass 8 Notes\n" }, { "code": null, "e": 20700, "s": 20684, "text": "\nClass 9 Notes\n" }, { "code": null, "e": 20717, "s": 20700, "text": "\nClass 10 Notes\n" }, { "code": null, "e": 20734, "s": 20717, "text": "\nClass 11 Notes\n" }, { "code": null, "e": 20751, "s": 20734, "text": "\nClass 12 Notes\n" }, { "code": null, "e": 20918, "s": 20751, "text": "\nNCERT Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n" }, { "code": null, "e": 20943, "s": 20918, "text": "\nClass 8 Maths Solution\n" }, { "code": null, "e": 20968, "s": 20943, "text": "\nClass 9 Maths Solution\n" }, { "code": null, "e": 20994, "s": 20968, "text": "\nClass 10 Maths Solution\n" }, { "code": null, "e": 21020, "s": 20994, "text": "\nClass 11 Maths Solution\n" }, { "code": null, "e": 21046, "s": 21020, "text": "\nClass 12 Maths Solution\n" }, { "code": null, "e": 21217, "s": 21046, "text": "\nRD Sharma Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n" }, { "code": null, "e": 21242, "s": 21217, "text": "\nClass 8 Maths Solution\n" }, { "code": null, "e": 21267, "s": 21242, "text": "\nClass 9 Maths Solution\n" }, { "code": null, "e": 21293, "s": 21267, "text": "\nClass 10 Maths Solution\n" }, { "code": null, "e": 21319, "s": 21293, "text": "\nClass 11 Maths Solution\n" }, { "code": null, "e": 21345, "s": 21319, "text": "\nClass 12 Maths Solution\n" }, { "code": null, "e": 21462, "s": 21345, "text": "\nPhysics Notes (Class 8-11)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n" }, { "code": null, "e": 21478, "s": 21462, "text": "\nClass 8 Notes\n" }, { "code": null, "e": 21494, "s": 21478, "text": "\nClass 9 Notes\n" }, { "code": null, "e": 21511, "s": 21494, "text": "\nClass 10 Notes\n" }, { "code": null, "e": 21528, "s": 21511, "text": "\nClass 11 Notes\n" }, { "code": null, "e": 21570, "s": 21528, "text": "\nCS Exams/PSUs\n \n\n" }, { "code": null, "e": 21715, "s": 21570, "text": "\nISRO\n \n\n\nISRO CS Original Papers and Official Keys\n\nISRO CS Solved Papers\n\nISRO CS Syllabus for Scientist/Engineer Exam\n" }, { "code": null, "e": 21759, "s": 21715, "text": "\nISRO CS Original Papers and Official Keys\n" }, { "code": null, "e": 21783, "s": 21759, "text": "\nISRO CS Solved Papers\n" }, { "code": null, "e": 21830, "s": 21783, "text": "\nISRO CS Syllabus for Scientist/Engineer Exam\n" }, { "code": null, "e": 21947, "s": 21830, "text": "\nUGC NET\n \n\n\nUGC NET CS Notes Paper II\n\nUGC NET CS Notes Paper III\n\nUGC NET CS Solved Papers\n" }, { "code": null, "e": 21975, "s": 21947, "text": "\nUGC NET CS Notes Paper II\n" }, { "code": null, "e": 22004, "s": 21975, "text": "\nUGC NET CS Notes Paper III\n" }, { "code": null, "e": 22031, "s": 22004, "text": "\nUGC NET CS Solved Papers\n" }, { "code": null, "e": 22288, "s": 22031, "text": "\nStudent\n \n\n\nCampus Ambassador Program\n\nSchool Ambassador Program\n\nProject\n\nGeek of the Month\n\nCampus Geek of the Month\n\nPlacement Course\n\nCompetititve Programming\n\nTestimonials\n\nStudent Chapter\n\nGeek on the Top\n\nInternship\n\nCareers\n" }, { "code": null, "e": 22316, "s": 22288, "text": "\nCampus Ambassador Program\n" }, { "code": null, "e": 22344, "s": 22316, "text": "\nSchool Ambassador Program\n" }, { "code": null, "e": 22354, "s": 22344, "text": "\nProject\n" }, { "code": null, "e": 22374, "s": 22354, "text": "\nGeek of the Month\n" }, { "code": null, "e": 22401, "s": 22374, "text": "\nCampus Geek of the Month\n" }, { "code": null, "e": 22420, "s": 22401, "text": "\nPlacement Course\n" }, { "code": null, "e": 22447, "s": 22420, "text": "\nCompetititve Programming\n" }, { "code": null, "e": 22462, "s": 22447, "text": "\nTestimonials\n" }, { "code": null, "e": 22480, "s": 22462, "text": "\nStudent Chapter\n" }, { "code": null, "e": 22498, "s": 22480, "text": "\nGeek on the Top\n" }, { "code": null, "e": 22511, "s": 22498, "text": "\nInternship\n" }, { "code": null, "e": 22521, "s": 22511, "text": "\nCareers\n" }, { "code": null, "e": 22679, "s": 22521, "text": "\nCurated DSA Lists\n \n\n\nTop 50 Array Problems\n\nTop 50 String Problems\n\nTop 50 Tree Problems\n\nTop 50 Graph Problems\n\nTop 50 DP Problems\n" }, { "code": null, "e": 22703, "s": 22679, "text": "\nTop 50 Array Problems\n" }, { "code": null, "e": 22728, "s": 22703, "text": "\nTop 50 String Problems\n" }, { "code": null, "e": 22751, "s": 22728, "text": "\nTop 50 Tree Problems\n" }, { "code": null, "e": 22775, "s": 22751, "text": "\nTop 50 Graph Problems\n" }, { "code": null, "e": 22796, "s": 22775, "text": "\nTop 50 DP Problems\n" }, { "code": null, "e": 22834, "s": 22796, "text": "\nTutorials\n \n\n" }, { "code": null, "e": 22907, "s": 22834, "text": "\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n" }, { "code": null, "e": 22924, "s": 22907, "text": "\nApply for Jobs\n" }, { "code": null, "e": 22937, "s": 22924, "text": "\nPost a Job\n" }, { "code": null, "e": 22950, "s": 22937, "text": "\nJOB-A-THON\n" }, { "code": null, "e": 23136, "s": 22950, "text": "\nPractice\n \n\n\nAll DSA Problems\n\nProblem of the Day\n\nInterview Series: Weekly Contests\n\nBi-Wizard Coding: School Contests\n\nContests and Events\n\nPractice SDE Sheet\n" }, { "code": null, "e": 23155, "s": 23136, "text": "\nAll DSA Problems\n" }, { "code": null, "e": 23176, "s": 23155, "text": "\nProblem of the Day\n" }, { "code": null, "e": 23212, "s": 23176, "text": "\nInterview Series: Weekly Contests\n" }, { "code": null, "e": 23248, "s": 23212, "text": "\nBi-Wizard Coding: School Contests\n" }, { "code": null, "e": 23270, "s": 23248, "text": "\nContests and Events\n" }, { "code": null, "e": 23291, "s": 23270, "text": "\nPractice SDE Sheet\n" }, { "code": null, "e": 23297, "s": 23291, "text": "GBlog" }, { "code": null, "e": 23305, "s": 23297, "text": "Puzzles" }, { "code": null, "e": 23318, "s": 23305, "text": "What's New ?" }, { "code": null, "e": 23324, "s": 23318, "text": "Array" }, { "code": null, "e": 23331, "s": 23324, "text": "Matrix" }, { "code": null, "e": 23339, "s": 23331, "text": "Strings" }, { "code": null, "e": 23347, "s": 23339, "text": "Hashing" }, { "code": null, "e": 23359, "s": 23347, "text": "Linked List" }, { "code": null, "e": 23365, "s": 23359, "text": "Stack" }, { "code": null, "e": 23371, "s": 23365, "text": "Queue" }, { "code": null, "e": 23383, "s": 23371, "text": "Binary Tree" }, { "code": null, "e": 23402, "s": 23383, "text": "Binary Search Tree" }, { "code": null, "e": 23407, "s": 23402, "text": "Heap" }, { "code": null, "e": 23413, "s": 23407, "text": "Graph" }, { "code": null, "e": 23423, "s": 23413, "text": "Searching" }, { "code": null, "e": 23431, "s": 23423, "text": "Sorting" }, { "code": null, "e": 23448, "s": 23431, "text": "Divide & Conquer" }, { "code": null, "e": 23461, "s": 23448, "text": "Mathematical" }, { "code": null, "e": 23471, "s": 23461, "text": "Geometric" }, { "code": null, "e": 23479, "s": 23471, "text": "Bitwise" }, { "code": null, "e": 23486, "s": 23479, "text": "Greedy" }, { "code": null, "e": 23499, "s": 23486, "text": "Backtracking" }, { "code": null, "e": 23516, "s": 23499, "text": "Branch and Bound" }, { "code": null, "e": 23536, "s": 23516, "text": "Dynamic Programming" }, { "code": null, "e": 23554, "s": 23536, "text": "Pattern Searching" }, { "code": null, "e": 23565, "s": 23554, "text": "Randomized" }, { "code": null, "e": 23600, "s": 23565, "text": "Linked List | Set 1 (Introduction)" }, { "code": null, "e": 23639, "s": 23600, "text": "Linked List | Set 2 (Inserting a node)" }, { "code": null, "e": 23661, "s": 23639, "text": "Reverse a linked list" }, { "code": null, "e": 23709, "s": 23661, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 23747, "s": 23709, "text": "Linked List | Set 3 (Deleting a node)" }, { "code": null, "e": 23803, "s": 23747, "text": "Doubly Linked List | Set 1 (Introduction and Insertion)" }, { "code": null, "e": 23822, "s": 23803, "text": "LinkedList in Java" }, { "code": null, "e": 23851, "s": 23822, "text": "Detect loop in a linked list" }, { "code": null, "e": 23872, "s": 23851, "text": "Linked List vs Array" }, { "code": null, "e": 23911, "s": 23872, "text": "Find the middle of a given linked list" }, { "code": null, "e": 23941, "s": 23911, "text": "Merge two sorted linked lists" }, { "code": null, "e": 23984, "s": 23941, "text": "Implement a stack using singly linked list" }, { "code": null, "e": 24019, "s": 23984, "text": "Queue - Linked List Implementation" }, { "code": null, "e": 24065, "s": 24019, "text": "Delete a Linked List node at a given position" }, { "code": null, "e": 24093, "s": 24065, "text": "Merge Sort for Linked Lists" }, { "code": null, "e": 24140, "s": 24093, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 24196, "s": 24140, "text": "Function to check if a singly linked list is palindrome" }, { "code": null, "e": 24251, "s": 24196, "text": "Find Length of a Linked List (Iterative and Recursive)" }, { "code": null, "e": 24291, "s": 24251, "text": "Detect and Remove Loop in a Linked List" }, { "code": null, "e": 24352, "s": 24291, "text": "Circular Linked List | Set 1 (Introduction and Applications)" }, { "code": null, "e": 24406, "s": 24352, "text": "Reverse a Linked List in groups of given size | Set 1" }, { "code": null, "e": 24467, "s": 24406, "text": "Search an element in a Linked List (Iterative and Recursive)" }, { "code": null, "e": 24519, "s": 24467, "text": "Program for n'th node from the end of a Linked List" }, { "code": null, "e": 24560, "s": 24519, "text": "Write a function to delete a Linked List" }, { "code": null, "e": 24627, "s": 24560, "text": "Write a function to get the intersection point of two Linked Lists" }, { "code": null, "e": 24671, "s": 24627, "text": "Remove duplicates from a sorted linked list" }, { "code": null, "e": 24709, "s": 24671, "text": "Top 20 Linked List Interview Question" }, { "code": null, "e": 24761, "s": 24709, "text": "Add two numbers represented by linked lists | Set 1" }, { "code": null, "e": 24808, "s": 24761, "text": "Remove duplicates from an unsorted linked list" }, { "code": null, "e": 24858, "s": 24808, "text": "Write a function to get Nth node in a Linked List" }, { "code": null, "e": 24893, "s": 24858, "text": "Linked List | Set 1 (Introduction)" }, { "code": null, "e": 24932, "s": 24893, "text": "Linked List | Set 2 (Inserting a node)" }, { "code": null, "e": 24954, "s": 24932, "text": "Reverse a linked list" }, { "code": null, "e": 25002, "s": 24954, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 25040, "s": 25002, "text": "Linked List | Set 3 (Deleting a node)" }, { "code": null, "e": 25096, "s": 25040, "text": "Doubly Linked List | Set 1 (Introduction and Insertion)" }, { "code": null, "e": 25115, "s": 25096, "text": "LinkedList in Java" }, { "code": null, "e": 25144, "s": 25115, "text": "Detect loop in a linked list" }, { "code": null, "e": 25165, "s": 25144, "text": "Linked List vs Array" }, { "code": null, "e": 25204, "s": 25165, "text": "Find the middle of a given linked list" }, { "code": null, "e": 25234, "s": 25204, "text": "Merge two sorted linked lists" }, { "code": null, "e": 25277, "s": 25234, "text": "Implement a stack using singly linked list" }, { "code": null, "e": 25312, "s": 25277, "text": "Queue - Linked List Implementation" }, { "code": null, "e": 25358, "s": 25312, "text": "Delete a Linked List node at a given position" }, { "code": null, "e": 25386, "s": 25358, "text": "Merge Sort for Linked Lists" }, { "code": null, "e": 25433, "s": 25386, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 25489, "s": 25433, "text": "Function to check if a singly linked list is palindrome" }, { "code": null, "e": 25544, "s": 25489, "text": "Find Length of a Linked List (Iterative and Recursive)" }, { "code": null, "e": 25584, "s": 25544, "text": "Detect and Remove Loop in a Linked List" }, { "code": null, "e": 25645, "s": 25584, "text": "Circular Linked List | Set 1 (Introduction and Applications)" }, { "code": null, "e": 25699, "s": 25645, "text": "Reverse a Linked List in groups of given size | Set 1" }, { "code": null, "e": 25760, "s": 25699, "text": "Search an element in a Linked List (Iterative and Recursive)" }, { "code": null, "e": 25812, "s": 25760, "text": "Program for n'th node from the end of a Linked List" }, { "code": null, "e": 25853, "s": 25812, "text": "Write a function to delete a Linked List" }, { "code": null, "e": 25920, "s": 25853, "text": "Write a function to get the intersection point of two Linked Lists" }, { "code": null, "e": 25964, "s": 25920, "text": "Remove duplicates from a sorted linked list" }, { "code": null, "e": 26002, "s": 25964, "text": "Top 20 Linked List Interview Question" }, { "code": null, "e": 26054, "s": 26002, "text": "Add two numbers represented by linked lists | Set 1" }, { "code": null, "e": 26101, "s": 26054, "text": "Remove duplicates from an unsorted linked list" }, { "code": null, "e": 26151, "s": 26101, "text": "Write a function to get Nth node in a Linked List" }, { "code": null, "e": 26175, "s": 26151, "text": "Difficulty Level :\nHard" }, { "code": null, "e": 26290, "s": 26175, "text": "Given a linked list, check if the the linked list has loop or not. Below diagram shows a linked list with a loop. " }, { "code": null, "e": 26807, "s": 26290, "text": "We have discussed Floyd’s algorithm to detect cycle in linked list. Brent’s cycle detection algorithm is similar to floyd’s algorithm as it also uses two pointer technique. But there is some difference in their approaches. Here we make one pointer stationary till every iteration and teleport it to other pointer at every power of two. The start of the cycle is determined by the smallest power of two at which they meet. This improves upon the constant factor of Floyd’s algorithm by reducing the number of calls. " }, { "code": null, "e": 27353, "s": 26807, "text": "Move fast pointer (or second_pointer) in powers of 2 until we find a loop. After every power, we reset slow pointer (or first_pointer) to previous value of second pointer. Reset length to 0 after every every power.The condition for loop testing is first_pointer and second_pointer become same. And loop is not present if second_pointer becomes NULL.When we come out of loop, we have length of loop.We reset first_pointer to head and second_pointer to node at position head + length.Now we move both pointers one by one to find beginning of loop." }, { "code": null, "e": 27568, "s": 27353, "text": "Move fast pointer (or second_pointer) in powers of 2 until we find a loop. After every power, we reset slow pointer (or first_pointer) to previous value of second pointer. Reset length to 0 after every every power." }, { "code": null, "e": 27704, "s": 27568, "text": "The condition for loop testing is first_pointer and second_pointer become same. And loop is not present if second_pointer becomes NULL." }, { "code": null, "e": 27754, "s": 27704, "text": "When we come out of loop, we have length of loop." }, { "code": null, "e": 27839, "s": 27754, "text": "We reset first_pointer to head and second_pointer to node at position head + length." }, { "code": null, "e": 27903, "s": 27839, "text": "Now we move both pointers one by one to find beginning of loop." }, { "code": null, "e": 28183, "s": 27903, "text": "Comparison with Floyd’s Algorithm: 1) Finds the length of loop in first cycle detection loop itself. No extra work is required for this. 2) We only move second in every iteration and avoid moving first (which can be costly if moving to next node involves evaluating a function). " }, { "code": null, "e": 28187, "s": 28183, "text": "C++" }, { "code": null, "e": 28189, "s": 28187, "text": "C" }, { "code": null, "e": 28197, "s": 28189, "text": "Python3" }, { "code": "// CPP program to implement Brent's cycle// detection algorithm to detect cycle in// a linked list.#include <iostream>using namespace std; /* Link list node */struct Node { int data; struct Node* next;}; /* This function detects loop in the listIf loop was there in the list then it returns,the first node of loop otherwise returns NULL */struct Node* detectCycle(struct Node* head){ // if head is null then no loop if (head == NULL) return NULL; struct Node* first_pointer = head; struct Node* second_pointer = head->next; int power = 1; int length = 1; // This loop runs till we find the loop. // If there is no loop then second_pointer // ends at NULL . while (second_pointer != NULL && second_pointer != first_pointer) { // condition after which we will // update the power and length as // smallest power of two gives the // start of cycle. if (length == power) { // updating the power. power *= 2; // updating the length length = 0; first_pointer = second_pointer; } second_pointer = second_pointer->next; ++length; } // if it is null then no loop if (second_pointer == NULL) return NULL; // Otherwise length stores actual length // of loop. // If needed, we can also print length of // loop. // printf(\"Length of loop is %d\\n\", length); // Now set first_pointer to the beginning // and second_pointer to beginning plus // cycle length which is length. first_pointer = second_pointer = head; while (length > 0) { second_pointer = second_pointer->next; --length; } // Now move both pointers at same speed so // that they meet at the beginning of loop. while (second_pointer != first_pointer) { second_pointer = second_pointer->next; first_pointer = first_pointer->next; } // If needed, we can also print length of // loop. // printf(\"Length of loop is %d\", length); return first_pointer;} struct Node* newNode(int key){ struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); temp->data = key; temp->next = NULL; return temp;} // Driver program to test above functionint main(){ struct Node* head = newNode(50); head->next = newNode(20); head->next->next = newNode(15); head->next->next->next = newNode(4); head->next->next->next->next = newNode(10); // Create a loop for testing head->next->next->next->next->next = head->next->next; Node *res = detectCycle(head); if (res == NULL) cout <<\"No loop\"; else cout <<\"Loop is present at \"<< res->data; return 0;} // this code is contributed by shivanisinghss2110", "e": 30984, "s": 28197, "text": null }, { "code": "// CPP program to implement Brent's cycle// detection algorithm to detect cycle in// a linked list.#include <stdio.h>#include <stdlib.h> /* Link list node */struct Node { int data; struct Node* next;}; /* This function detects loop in the listIf loop was there in the list then it returns,the first node of loop otherwise returns NULL */struct Node* detectCycle(struct Node* head){ // if head is null then no loop if (head == NULL) return NULL; struct Node* first_pointer = head; struct Node* second_pointer = head->next; int power = 1; int length = 1; // This loop runs till we find the loop. // If there is no loop then second_pointer // ends at NULL . while (second_pointer != NULL && second_pointer != first_pointer) { // condition after which we will // update the power and length as // smallest power of two gives the // start of cycle. if (length == power) { // updating the power. power *= 2; // updating the length length = 0; first_pointer = second_pointer; } second_pointer = second_pointer->next; ++length; } // if it is null then no loop if (second_pointer == NULL) return NULL; // Otherwise length stores actual length // of loop. // If needed, we can also print length of // loop. // printf(\"Length of loop is %d\\n\", length); // Now set first_pointer to the beginning // and second_pointer to beginning plus // cycle length which is length. first_pointer = second_pointer = head; while (length > 0) { second_pointer = second_pointer->next; --length; } // Now move both pointers at same speed so // that they meet at the beginning of loop. while (second_pointer != first_pointer) { second_pointer = second_pointer->next; first_pointer = first_pointer->next; } // If needed, we can also print length of // loop. // printf(\"Length of loop is %d\", length); return first_pointer;} struct Node* newNode(int key){ struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); temp->data = key; temp->next = NULL; return temp;} // Driver program to test above functionint main(){ struct Node* head = newNode(50); head->next = newNode(20); head->next->next = newNode(15); head->next->next->next = newNode(4); head->next->next->next->next = newNode(10); // Create a loop for testing head->next->next->next->next->next = head->next->next; Node *res = detectCycle(head); if (res == NULL) printf(\"No loop\"); else printf(\"Loop is present at %d\", res->data); return 0;}", "e": 33735, "s": 30984, "text": null }, { "code": "# Python program to implement# Brent's cycle detection# algorithm to detect cycle# in a linked list. # Node classclass Node: # Constructor to initialize # the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to insert a new Node # at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Utility function to print # the linked LinkedList def printList(self): temp = self.head while(temp): print (temp.data,end=\" \") temp = temp.next def detectCycle(self): # if head is null # then no loop temp=self.head if not (temp): return False first_p=temp second_p=temp.next power = 1 length = 1 # This loop runs till we # find the loop. If there # is no loop then second # pointer ends at NULL while (second_p and second_p!= first_p): # condition after which # we will update the power # and length as smallest # power of two gives # the start of cycle. if (length == power): # updating the power. power *= 2 # updating the length length = 0 first_p = second_p second_p = second_p.next length=length+1 # if it is null then no loop if not (second_p) : return # Otherwise length stores # actual length of loop. # If needed, we can also # print length of loop. # print(\"Length of loop is \") # print (length) # Now set first_pointer # to the beginning and # second_pointer to # beginning plus cycle # length which is length. first_p = second_p = self.head while (length > 0): second_p = second_p.next length=length-1 # Now move both pointers # at same speed so that # they meet at the # beginning of loop. while (second_p!= first_p) : second_p = second_p.next first_p = first_p.next return first_p # Driver program for testingllist = LinkedList()llist.push(50)llist.push(20)llist.push(15)llist.push(4)llist.push(10) # Create a loop for testingllist.head.next.next.next.next.next = llist.head.next.next;res=llist.detectCycle()if( res.data): print (\"loop found at \",end=' ') print (res.data)else : print (\"No Loop \") # This code is contributed by Gitanjali", "e": 36526, "s": 33735, "text": null }, { "code": null, "e": 36536, "s": 36526, "text": "Output: " }, { "code": null, "e": 36558, "s": 36536, "text": "Loop is present at 15" }, { "code": null, "e": 36813, "s": 36558, "text": "Time Complexity: O(m + n) where m is the smallest index of the sequence which is the beginning of a cycle, and n is the cycle’s length. Auxiliary Space : – O(1) auxiliaryReferences : https://en.wikipedia.org/wiki/Cycle_detection#Brent’s_algorithm github " }, { "code": null, "e": 36825, "s": 36813, "text": "anikakapoor" }, { "code": null, "e": 36844, "s": 36825, "text": "shivanisinghss2110" }, { "code": null, "e": 36856, "s": 36844, "text": "Linked List" }, { "code": null, "e": 36868, "s": 36856, "text": "Linked List" }, { "code": null, "e": 36966, "s": 36868, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37007, "s": 36966, "text": "Circular Linked List | Set 2 (Traversal)" }, { "code": null, "e": 37057, "s": 37007, "text": "Swap nodes in a linked list without swapping data" }, { "code": null, "e": 37116, "s": 37057, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 37156, "s": 37116, "text": "Circular Singly Linked List | Insertion" }, { "code": null, "e": 37227, "s": 37156, "text": "Given a linked list which is sorted, how will you insert in sorted way" }, { "code": null, "e": 37265, "s": 37227, "text": "Delete a node in a Doubly Linked List" }, { "code": null, "e": 37306, "s": 37265, "text": "Real-time application of Data Structures" }, { "code": null, "e": 37339, "s": 37306, "text": "Linked List Implementation in C#" }, { "code": null, "e": 37393, "s": 37339, "text": "Insert a node at a specific position in a linked list" } ]
Collections unmodifiableCollection() method in Java with Examples - GeeksforGeeks
08 Oct, 2018 The unmodifiableCollection() method of java.util.Collections class is used to return an unmodifiable view of the specified collection. This method allows modules to provide users with “read-only” access to internal collections. Query operations on the returned collection “read through” to the specified collection, and attempts to modify the returned collection, whether direct or via its iterator, result in an UnsupportedOperationException. The returned collection does not pass the hashCode and equals operations through to the backing collection, but relies on Object’s equals and hashCode methods. This is necessary to preserve the contracts of these operations in the case that the backing collection is a set or a list. The returned collection will be serializable if the specified collection is serializable. Syntax: public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) Parameters: This method takes the collection as a parameter for which an unmodifiable view is to be returned. Return Value: This method returns an unmodifiable view of the specified collection. Below are the examples to illustrate the unmodifiableCollection() method Example 1: // Java program to demonstrate// unmodifiableCollection() method// for <Character> Value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of ArrayList<Character> List<Character> list = new ArrayList<Character>(); // populate the list list.add('X'); list.add('Y'); // printing the list System.out.println("Initial list: " + list); // getting unmodifiable list // using unmodifiableCollection() method Collection<Character> immutablelist = Collections .unmodifiableCollection(list); } catch (UnsupportedOperationException e) { System.out.println("Exception thrown : " + e); } }} Initial list: [X, Y] Example 2: For UnsupportedOperationException // Java program to demonstrate// unmodifiableCollection() method// for UnsupportedOperationException import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of ArrayList<Character> List<Character> list = new ArrayList<Character>(); // populate the list list.add('X'); list.add('Y'); // printing the list System.out.println("Initial list: " + list); // getting unmodifiable list // using unmodifiableCollection() method Collection<Character> immutablelist = Collections .unmodifiableCollection(list); // Adding element to new Collection System.out.println("\nTrying to modify" + " the unmodifiableCollection"); immutablelist.add('Z'); } catch (UnsupportedOperationException e) { System.out.println("Exception thrown : " + e); } }} Initial list: [X, Y] Trying to modify the unmodifiableCollection Exception thrown : java.lang.UnsupportedOperationException Java - util package Java-Collections Java-Functions Java Programs Java-Collections 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 Get Elements By Index from HashSet in Java? Java Program to Write into a File How to Replace a Element in Java ArrayList? Java Program to Find Sum of Array Elements Java Program to Read a File to String Tic-Tac-Toe Game in Java How to Write Data into Excel Sheet using Java? Removing last element from ArrayList in Java Java Program to Write an Array of Strings to the Output Console
[ { "code": null, "e": 26107, "s": 26079, "text": "\n08 Oct, 2018" }, { "code": null, "e": 26551, "s": 26107, "text": "The unmodifiableCollection() method of java.util.Collections class is used to return an unmodifiable view of the specified collection. This method allows modules to provide users with “read-only” access to internal collections. Query operations on the returned collection “read through” to the specified collection, and attempts to modify the returned collection, whether direct or via its iterator, result in an UnsupportedOperationException." }, { "code": null, "e": 26835, "s": 26551, "text": "The returned collection does not pass the hashCode and equals operations through to the backing collection, but relies on Object’s equals and hashCode methods. This is necessary to preserve the contracts of these operations in the case that the backing collection is a set or a list." }, { "code": null, "e": 26925, "s": 26835, "text": "The returned collection will be serializable if the specified collection is serializable." }, { "code": null, "e": 26933, "s": 26925, "text": "Syntax:" }, { "code": null, "e": 27020, "s": 26933, "text": "public static <T> Collection<T> \n unmodifiableCollection(Collection<? extends T> c)" }, { "code": null, "e": 27130, "s": 27020, "text": "Parameters: This method takes the collection as a parameter for which an unmodifiable view is to be returned." }, { "code": null, "e": 27214, "s": 27130, "text": "Return Value: This method returns an unmodifiable view of the specified collection." }, { "code": null, "e": 27287, "s": 27214, "text": "Below are the examples to illustrate the unmodifiableCollection() method" }, { "code": null, "e": 27298, "s": 27287, "text": "Example 1:" }, { "code": "// Java program to demonstrate// unmodifiableCollection() method// for <Character> Value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of ArrayList<Character> List<Character> list = new ArrayList<Character>(); // populate the list list.add('X'); list.add('Y'); // printing the list System.out.println(\"Initial list: \" + list); // getting unmodifiable list // using unmodifiableCollection() method Collection<Character> immutablelist = Collections .unmodifiableCollection(list); } catch (UnsupportedOperationException e) { System.out.println(\"Exception thrown : \" + e); } }}", "e": 28169, "s": 27298, "text": null }, { "code": null, "e": 28191, "s": 28169, "text": "Initial list: [X, Y]\n" }, { "code": null, "e": 28236, "s": 28191, "text": "Example 2: For UnsupportedOperationException" }, { "code": "// Java program to demonstrate// unmodifiableCollection() method// for UnsupportedOperationException import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of ArrayList<Character> List<Character> list = new ArrayList<Character>(); // populate the list list.add('X'); list.add('Y'); // printing the list System.out.println(\"Initial list: \" + list); // getting unmodifiable list // using unmodifiableCollection() method Collection<Character> immutablelist = Collections .unmodifiableCollection(list); // Adding element to new Collection System.out.println(\"\\nTrying to modify\" + \" the unmodifiableCollection\"); immutablelist.add('Z'); } catch (UnsupportedOperationException e) { System.out.println(\"Exception thrown : \" + e); } }}", "e": 29327, "s": 28236, "text": null }, { "code": null, "e": 29453, "s": 29327, "text": "Initial list: [X, Y]\n\nTrying to modify the unmodifiableCollection\nException thrown : java.lang.UnsupportedOperationException\n" }, { "code": null, "e": 29473, "s": 29453, "text": "Java - util package" }, { "code": null, "e": 29490, "s": 29473, "text": "Java-Collections" }, { "code": null, "e": 29505, "s": 29490, "text": "Java-Functions" }, { "code": null, "e": 29519, "s": 29505, "text": "Java Programs" }, { "code": null, "e": 29536, "s": 29519, "text": "Java-Collections" }, { "code": null, "e": 29634, "s": 29536, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29682, "s": 29634, "text": "Iterate Over the Characters of a String in Java" }, { "code": null, "e": 29733, "s": 29682, "text": "How to Get Elements By Index from HashSet in Java?" }, { "code": null, "e": 29767, "s": 29733, "text": "Java Program to Write into a File" }, { "code": null, "e": 29811, "s": 29767, "text": "How to Replace a Element in Java ArrayList?" }, { "code": null, "e": 29854, "s": 29811, "text": "Java Program to Find Sum of Array Elements" }, { "code": null, "e": 29892, "s": 29854, "text": "Java Program to Read a File to String" }, { "code": null, "e": 29917, "s": 29892, "text": "Tic-Tac-Toe Game in Java" }, { "code": null, "e": 29964, "s": 29917, "text": "How to Write Data into Excel Sheet using Java?" }, { "code": null, "e": 30009, "s": 29964, "text": "Removing last element from ArrayList in Java" } ]
Threaded Port Scanner using Sockets in Python - GeeksforGeeks
28 Aug, 2020 Port scanning can be really slow yet, in most cases, is not process intensive. Thus, we can use threading to improve our speed. There can be thousands of possible ports. If it takes 5-15 seconds per port to scan, then we might have a long wait ahead of us without the use of threading. Threading is a complex topic, but it can be broken down and conceptualized as a methodology where we can tell the computer to do another task if the processor is experiencing idle time. In the case of port scanning, we are spending a lot of time just waiting on the response from the server. While we are waiting, we can do something else. That is what threading is used for. Example: In this program, we can scan a number of ports in a certain range. Python3 import threadingfrom queue import Queueimport timeimport socket # a print_lock is used to prevent "double"# modification of shared variables this is# used so that while one thread is using a# variable others cannot access it Once it# is done, the thread releases the print_lock.# In order to use it, we want to specify a# print_lock per thing you wish to print_lock.print_lock = threading.Lock() # ip = socket.gethostbyname(target)target = 'localhost' def portscan(port): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: con = s.connect((target, port)) with print_lock: print('port is open', port) con.close() except: print('port is close', port) # The threader thread pulls a worker # from a queue and processes itdef threader(): while True: # gets a worker from the queue worker = q.get() # Run the example job with the available # worker in queue (thread) portscan(worker) # completed with the job q.task_done() # Creating the queue and threaderq = Queue() # number of threads are we going to allow forfor x in range(4): t = threading.Thread(target=threader) # classifying as a daemon, so they it will # die when the main dies t.daemon = True # begins, must come after daemon definition t.start() start = time.time() # 10 jobs assigned.for worker in range(1, 10): q.put(worker) # wait till the thread terminates.q.join() Output: port is close 2 port is close port is close 4 port is closeport is close 1 53 port is close 6port is close 7 port is close 8 port is close 9 Python-threading Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25555, "s": 25527, "text": "\n28 Aug, 2020" }, { "code": null, "e": 25841, "s": 25555, "text": "Port scanning can be really slow yet, in most cases, is not process intensive. Thus, we can use threading to improve our speed. There can be thousands of possible ports. If it takes 5-15 seconds per port to scan, then we might have a long wait ahead of us without the use of threading." }, { "code": null, "e": 26218, "s": 25841, "text": "Threading is a complex topic, but it can be broken down and conceptualized as a methodology where we can tell the computer to do another task if the processor is experiencing idle time. In the case of port scanning, we are spending a lot of time just waiting on the response from the server. While we are waiting, we can do something else. That is what threading is used for. " }, { "code": null, "e": 26294, "s": 26218, "text": "Example: In this program, we can scan a number of ports in a certain range." }, { "code": null, "e": 26302, "s": 26294, "text": "Python3" }, { "code": "import threadingfrom queue import Queueimport timeimport socket # a print_lock is used to prevent \"double\"# modification of shared variables this is# used so that while one thread is using a# variable others cannot access it Once it# is done, the thread releases the print_lock.# In order to use it, we want to specify a# print_lock per thing you wish to print_lock.print_lock = threading.Lock() # ip = socket.gethostbyname(target)target = 'localhost' def portscan(port): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: con = s.connect((target, port)) with print_lock: print('port is open', port) con.close() except: print('port is close', port) # The threader thread pulls a worker # from a queue and processes itdef threader(): while True: # gets a worker from the queue worker = q.get() # Run the example job with the available # worker in queue (thread) portscan(worker) # completed with the job q.task_done() # Creating the queue and threaderq = Queue() # number of threads are we going to allow forfor x in range(4): t = threading.Thread(target=threader) # classifying as a daemon, so they it will # die when the main dies t.daemon = True # begins, must come after daemon definition t.start() start = time.time() # 10 jobs assigned.for worker in range(1, 10): q.put(worker) # wait till the thread terminates.q.join()", "e": 27781, "s": 26302, "text": null }, { "code": null, "e": 27790, "s": 27781, "text": "Output: " }, { "code": null, "e": 27934, "s": 27790, "text": "port is close 2\nport is close port is close 4\nport is closeport is close 1\n 53\n\nport is close 6port is close\n 7\nport is close 8\nport is close 9" }, { "code": null, "e": 27951, "s": 27934, "text": "Python-threading" }, { "code": null, "e": 27958, "s": 27951, "text": "Python" }, { "code": null, "e": 28056, "s": 27958, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28088, "s": 28056, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28130, "s": 28088, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28172, "s": 28130, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28228, "s": 28172, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28255, "s": 28228, "text": "Python Classes and Objects" }, { "code": null, "e": 28286, "s": 28255, "text": "Python | os.path.join() method" }, { "code": null, "e": 28325, "s": 28286, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28354, "s": 28325, "text": "Create a directory in Python" }, { "code": null, "e": 28376, "s": 28354, "text": "Defaultdict in Python" } ]
How to use Redux with ReactNative? - GeeksforGeeks
20 Nov, 2020 First, we create a fresh ReactNative Project by running the command “npx react-native init reduxDemo”. You can also integrate Redux into your existing project. Go to the project folder by “cd {rootDirectory}/reduxDemo” and install dependencies. “npm install redux” which is an official redux dependency.“npm install react-redux” which is used to connect redux to react. “npm install redux” which is an official redux dependency. “npm install react-redux” which is used to connect redux to react. Directory Structure: This is the Directory structure I am using. You can create your own Directory structure which suits you best. MyAssets directory contains a Redux Directory which contains all of Redux code and a Screen directory which contains all the screen components. I am using Burger(food) as an example to show actions such as buying or creating a Burger which will result in a Decrease or Increase in the number of Burgers. We will create all the files in MyAssets directory one-by-one. Directory Structure Example Step by Step: We will create MyAssests Directory inside our reduxDemo project. MyAssets will contain all the files for the app screen component as well as for Redux. Inside MyAssets we will create a Directory named Redux which will contain all of our Redux code. Creating Actions: Inside Redux directory we will create a directory named Burger which will contain all of our actions and reducer for the Burger. For creating actions we will create two files bugerActionTypes.js and burgerAction.js inside the Burger directory. burgerActionTypes.js: In this file, we export all the string action_type property. This file is completely optional to create and without it we will have to manually write the string Action_type in action and reducer. Javascript // all action String Type will be exported from hereexport const INCREASE_BURGER='INCREASE_BURGER';export const DECREASE_BURGER='DECREASE_BURGER'; burgerAction.js: In this, we will create our action function which returns action_type and optional payload property to reducer. Javascript import {INCREASE_BURGER,DECREASE_BURGER} from './burgerActionTypes'; // Action functions which return action type and // optional payLoad to burgerReducer export const increaseBurgerAction=(parameter)=>{ return{ type:INCREASE_BURGER, payload:parameter }} export const decreaseBurgerAction=()=>{ return{ type:DECREASE_BURGER }} Creating Reducer: Inside Burger directory, we will create a file burgerReducer.js.In this file, we will create a burgerReducer() function which takes an initial state and action as a parameter and returns a new state of the store based on the action_type. Javascript import {INCREASE_BURGER,DECREASE_BURGER} from './burgerActionTypes'; //initializing state const initialState={ numberOfBurger:10} const burgerReducer=(state=initialState,action)=>{ switch(action.type){ case INCREASE_BURGER:return{ ...state, numberOfBurger:state.numberOfBurger+action.payload } case DECREASE_BURGER:return{ ...state, numberOfBurger:state.numberOfBurger-1 } default:return state }} export default burgerReducer; Creating Store: Inside our Redux directory, we will create two files store.js and index.js. Index.js: This file will be used to export all actions from a single file. This file is completely optional to create and you can import action from their respective JavaScript files also. Javascript // Single file for exporting all actionsexport {increaseBurgerAction} from './Burger/burgerAction';export {decreaseBurgerAction} from './Burger/burgerAction'; store.js: In this file, we will import all the reducers and then create a store and export it to App.js.We can also create a store in App.js also but to keep the code cleaner I have created a separate file. Javascript import {createStore} from 'redux'; import burgerReducer from './Burger/burgerReducer'; // Passing burgerReducer to createStoreconst store=createStore(burgerReducer); export default store; App.js: In App.js we import Provider component from ‘react-redux’ and store from store.js. Provider is used to pass store state to all its child components. Javascript import React from 'react';import {Provider} from 'react-redux'; import store from './MyAssets/Redux/store';import Screen from './MyAssets/Screens/screen' const App= () => { return ( <Provider store={store}> <Screen/> </Provider> );}; export default App; Creating our Screen Component: Now finally we will create our screen component to use and update the store state. Inside MyAssets directory we will create a directory named Screens which will contain all of our app screen components. Inside Screens directory we will create a file named screen.js. Javascript import React, { Component } from 'react'import { Text, View,Button } from 'react-native'import {connect} from 'react-redux'import {increaseBurgerAction,decreaseBurgerAction} from '../Redux/index' class Screen extends Component { render() { return ( <View style={{justifyContent:'center',alignItems:'center'}}> <View style={{marginVertical:50}}> <Text> Number Of Burger = {this.props.numberOfBurger} </Text> <Button title="Increase Burger" onPress={()=>{this.props.increaseBurger(5)}}/> </View> <View style={{marginVertical:50}}> <Button title="Decrease Burger" onPress={()=>{this.props.decreaseBurger()}}/> </View> </View> ) }} const mapStateToProps=(state)=>{ return{ numberOfBurger:state.numberOfBurger }} const mapDispatchToProps=(dispatch)=>{ return{ increaseBurger:(parameter)=>{dispatch(increaseBurgerAction(parameter))}, decreaseBurger:()=>{dispatch(decreaseBurgerAction())} }} export default connect(mapStateToProps,mapDispatchToProps)(Screen); Render: This is called when the state of the store changes. mapStateToProps: This function maps the store state to the screen component to be used as props. We can also rename this other than mapStateToProps. mapDispatchToProps: This function maps the actions to the screen component to be called using props. We can also rename this other than mapDispatchToProps. connect: This is a ‘react-redux’ inbuilt function used to connect screen component to mapStateToProps and mapDispatchToProps.Always pass mapStateToProps as a first parameter and mapDispatchToProps as the second parameter to connect() function otherwise it will generate an error. Output: First we call this.props.increaseBurger(5) in Button from our component.Notice how we pass number ‘5’ as an parameter ,this parameter will be supplied to increaseBurgerAction(parameter) function of mapDispatchToProps function.Then the increaseBurgerAction() of burgerActions.js file will be called which will return action_type and ‘5’ as a payload to reducer function.Then the burgerReducer() function will be called which will accept an initial state and action as a parameter and then increase the numberOfBurger from the initial value to +5. First we call this.props.increaseBurger(5) in Button from our component.Notice how we pass number ‘5’ as an parameter ,this parameter will be supplied to increaseBurgerAction(parameter) function of mapDispatchToProps function. Then the increaseBurgerAction() of burgerActions.js file will be called which will return action_type and ‘5’ as a payload to reducer function. Then the burgerReducer() function will be called which will accept an initial state and action as a parameter and then increase the numberOfBurger from the initial value to +5. this.props.decreaseBurger() in Button works the same as this.props.increaseBurger(). Notice we haven’t passed any parameter this time. Multiple Reducers: In most cases, we have to use multiple reducers in order to separate states and actions. To demonstrate this I have created another Directory named Pizza which contains code for pizzaReducer.js, pizzaActionsType.js, and pizzaActions.js. store.js: In this, we use combineReducers() which is an inbuilt function of ‘redux’ to combine our reducers. Javascript import {createStore,combineReducers} from 'redux'; import burgerReducer from './Burger/burgerReducer';import pizzaReducer from './Pizza/pizzareducer'; // Combining burgerReducer and pizzaReducer in rootReducerconst rootReducer=combineReducers({ burgerReducer:burgerReducer, pizzaReducer:pizzaReducer}) // Passing rootReducer to createStoreconst store=createStore(rootReducer); export default store; pizzaReducer.js: Javascript import {PIZZA_DECREASE,PIZZA_INCREASE} from './pizzaActionsType'; // Initializing state const initialState={ numberOfPizza:30} const pizzaReducer=(state=initialState,action)=>{ switch(action.type){ case PIZZA_INCREASE:return{ ...state, numberOfPizza:state.numberOfPizza+action.payload } case PIZZA_DECREASE:return{ ...state, numberOfPizza:state.numberOfPizza-1 } default:return state }} export default pizzaReducer; pizzaActionType.js: Javascript export const PIZZA_INCREASE='PIZZA_INCREASE';export const PIZZA_DECREASE='PIZZA_DECREASE'; pizzaActions.js: Javascript import {PIZZA_INCREASE,PIZZA_DECREASE} from './pizzaActionsType'; // Action functions which return action type // and optional payLoad to burgerReducer export const increasePizzaAction=(parameter)=>{ return{ type:PIZZA_INCREASE, payload:parameter }} export const decreasePizzaAction=()=>{ return{ type:PIZZA_DECREASE }} index.js: Javascript // Single file for exporting all actionsexport {increaseBurgerAction} from './Burger/burgerAction';export {decreaseBurgerAction} from './Burger/burgerAction'; export {increasePizzaAction} from './Pizza/pizzaActions';export {decreasePizzaAction} from './Pizza/pizzaActions'; screen.js – Modifying our screen component code to use pizza actions and state. Javascript import React, { Component } from 'react'import { Text, View,Button } from 'react-native'import {connect} from 'react-redux'import {increaseBurgerAction,decreaseBurgerAction,increasePizzaAction,decreasePizzaAction} from '../Redux/index' class Screen extends Component { render() { return ( <View style={{justifyContent:'center',alignItems:'center'}}> <View style={{marginVertical:50}}> <Text> Number Of Burger = {this.props.numberOfBurger} </Text> <Button title="Increase Burger" onPress={()=>{this.props.increaseBurger(5)}}/> <Button title="Decrease Burger" onPress={()=>{this.props.decreaseBurger()}}/> </View> <View style={{marginVertical:50}}> <Text> Number Of Pizza = {this.props.numberOfPizza} </Text> <Button title="Increase Burger" onPress={()=>{this.props.increasePizza(5)}}/> <Button title="Decrease Burger" onPress={()=>{this.props.decreasePizza()}}/> </View> </View> ) }} const mapStateToProps=(state)=>{ return{ numberOfBurger:state.burgerReducer.numberOfBurger, numberOfPizza:state.pizzaReducer.numberOfPizza }} const mapDispatchToProps=(dispatch)=>{ return{ increaseBurger:(parameter)=>{dispatch(increaseBurgerAction(parameter))}, decreaseBurger:()=>{dispatch(decreaseBurgerAction())}, increasePizza:(parameter)=>{dispatch(increasePizzaAction(parameter))}, decreasePizza:()=>{dispatch(decreasePizzaAction())} }} export default connect(mapStateToProps,mapDispatchToProps)(Screen); Output: react-js Redux Android JavaScript Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create and Add Data to SQLite Database in Android? Resource Raw Folder in Android Studio Broadcast Receiver in Android With Example Services in Android with Example Android RecyclerView in Kotlin Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript?
[ { "code": null, "e": 26009, "s": 25981, "text": "\n20 Nov, 2020" }, { "code": null, "e": 26169, "s": 26009, "text": "First, we create a fresh ReactNative Project by running the command “npx react-native init reduxDemo”. You can also integrate Redux into your existing project." }, { "code": null, "e": 26254, "s": 26169, "text": "Go to the project folder by “cd {rootDirectory}/reduxDemo” and install dependencies." }, { "code": null, "e": 26379, "s": 26254, "text": "“npm install redux” which is an official redux dependency.“npm install react-redux” which is used to connect redux to react." }, { "code": null, "e": 26438, "s": 26379, "text": "“npm install redux” which is an official redux dependency." }, { "code": null, "e": 26505, "s": 26438, "text": "“npm install react-redux” which is used to connect redux to react." }, { "code": null, "e": 26636, "s": 26505, "text": "Directory Structure: This is the Directory structure I am using. You can create your own Directory structure which suits you best." }, { "code": null, "e": 26780, "s": 26636, "text": "MyAssets directory contains a Redux Directory which contains all of Redux code and a Screen directory which contains all the screen components." }, { "code": null, "e": 26940, "s": 26780, "text": "I am using Burger(food) as an example to show actions such as buying or creating a Burger which will result in a Decrease or Increase in the number of Burgers." }, { "code": null, "e": 27003, "s": 26940, "text": "We will create all the files in MyAssets directory one-by-one." }, { "code": null, "e": 27023, "s": 27003, "text": "Directory Structure" }, { "code": null, "e": 27294, "s": 27023, "text": "Example Step by Step: We will create MyAssests Directory inside our reduxDemo project. MyAssets will contain all the files for the app screen component as well as for Redux. Inside MyAssets we will create a Directory named Redux which will contain all of our Redux code." }, { "code": null, "e": 27441, "s": 27294, "text": "Creating Actions: Inside Redux directory we will create a directory named Burger which will contain all of our actions and reducer for the Burger." }, { "code": null, "e": 27556, "s": 27441, "text": "For creating actions we will create two files bugerActionTypes.js and burgerAction.js inside the Burger directory." }, { "code": null, "e": 27774, "s": 27556, "text": "burgerActionTypes.js: In this file, we export all the string action_type property. This file is completely optional to create and without it we will have to manually write the string Action_type in action and reducer." }, { "code": null, "e": 27785, "s": 27774, "text": "Javascript" }, { "code": "// all action String Type will be exported from hereexport const INCREASE_BURGER='INCREASE_BURGER';export const DECREASE_BURGER='DECREASE_BURGER';", "e": 27932, "s": 27785, "text": null }, { "code": null, "e": 28061, "s": 27932, "text": "burgerAction.js: In this, we will create our action function which returns action_type and optional payload property to reducer." }, { "code": null, "e": 28072, "s": 28061, "text": "Javascript" }, { "code": "import {INCREASE_BURGER,DECREASE_BURGER} from './burgerActionTypes'; // Action functions which return action type and // optional payLoad to burgerReducer export const increaseBurgerAction=(parameter)=>{ return{ type:INCREASE_BURGER, payload:parameter }} export const decreaseBurgerAction=()=>{ return{ type:DECREASE_BURGER }}", "e": 28437, "s": 28072, "text": null }, { "code": null, "e": 28693, "s": 28437, "text": "Creating Reducer: Inside Burger directory, we will create a file burgerReducer.js.In this file, we will create a burgerReducer() function which takes an initial state and action as a parameter and returns a new state of the store based on the action_type." }, { "code": null, "e": 28704, "s": 28693, "text": "Javascript" }, { "code": "import {INCREASE_BURGER,DECREASE_BURGER} from './burgerActionTypes'; //initializing state const initialState={ numberOfBurger:10} const burgerReducer=(state=initialState,action)=>{ switch(action.type){ case INCREASE_BURGER:return{ ...state, numberOfBurger:state.numberOfBurger+action.payload } case DECREASE_BURGER:return{ ...state, numberOfBurger:state.numberOfBurger-1 } default:return state }} export default burgerReducer;", "e": 29222, "s": 28704, "text": null }, { "code": null, "e": 29314, "s": 29222, "text": "Creating Store: Inside our Redux directory, we will create two files store.js and index.js." }, { "code": null, "e": 29503, "s": 29314, "text": "Index.js: This file will be used to export all actions from a single file. This file is completely optional to create and you can import action from their respective JavaScript files also." }, { "code": null, "e": 29514, "s": 29503, "text": "Javascript" }, { "code": "// Single file for exporting all actionsexport {increaseBurgerAction} from './Burger/burgerAction';export {decreaseBurgerAction} from './Burger/burgerAction';", "e": 29673, "s": 29514, "text": null }, { "code": null, "e": 29880, "s": 29673, "text": "store.js: In this file, we will import all the reducers and then create a store and export it to App.js.We can also create a store in App.js also but to keep the code cleaner I have created a separate file." }, { "code": null, "e": 29891, "s": 29880, "text": "Javascript" }, { "code": "import {createStore} from 'redux'; import burgerReducer from './Burger/burgerReducer'; // Passing burgerReducer to createStoreconst store=createStore(burgerReducer); export default store;", "e": 30082, "s": 29891, "text": null }, { "code": null, "e": 30239, "s": 30082, "text": "App.js: In App.js we import Provider component from ‘react-redux’ and store from store.js. Provider is used to pass store state to all its child components." }, { "code": null, "e": 30250, "s": 30239, "text": "Javascript" }, { "code": "import React from 'react';import {Provider} from 'react-redux'; import store from './MyAssets/Redux/store';import Screen from './MyAssets/Screens/screen' const App= () => { return ( <Provider store={store}> <Screen/> </Provider> );}; export default App;", "e": 30526, "s": 30250, "text": null }, { "code": null, "e": 30824, "s": 30526, "text": "Creating our Screen Component: Now finally we will create our screen component to use and update the store state. Inside MyAssets directory we will create a directory named Screens which will contain all of our app screen components. Inside Screens directory we will create a file named screen.js." }, { "code": null, "e": 30835, "s": 30824, "text": "Javascript" }, { "code": "import React, { Component } from 'react'import { Text, View,Button } from 'react-native'import {connect} from 'react-redux'import {increaseBurgerAction,decreaseBurgerAction} from '../Redux/index' class Screen extends Component { render() { return ( <View style={{justifyContent:'center',alignItems:'center'}}> <View style={{marginVertical:50}}> <Text> Number Of Burger = {this.props.numberOfBurger} </Text> <Button title=\"Increase Burger\" onPress={()=>{this.props.increaseBurger(5)}}/> </View> <View style={{marginVertical:50}}> <Button title=\"Decrease Burger\" onPress={()=>{this.props.decreaseBurger()}}/> </View> </View> ) }} const mapStateToProps=(state)=>{ return{ numberOfBurger:state.numberOfBurger }} const mapDispatchToProps=(dispatch)=>{ return{ increaseBurger:(parameter)=>{dispatch(increaseBurgerAction(parameter))}, decreaseBurger:()=>{dispatch(decreaseBurgerAction())} }} export default connect(mapStateToProps,mapDispatchToProps)(Screen);", "e": 31989, "s": 30835, "text": null }, { "code": null, "e": 32049, "s": 31989, "text": "Render: This is called when the state of the store changes." }, { "code": null, "e": 32198, "s": 32049, "text": "mapStateToProps: This function maps the store state to the screen component to be used as props. We can also rename this other than mapStateToProps." }, { "code": null, "e": 32354, "s": 32198, "text": "mapDispatchToProps: This function maps the actions to the screen component to be called using props. We can also rename this other than mapDispatchToProps." }, { "code": null, "e": 32634, "s": 32354, "text": "connect: This is a ‘react-redux’ inbuilt function used to connect screen component to mapStateToProps and mapDispatchToProps.Always pass mapStateToProps as a first parameter and mapDispatchToProps as the second parameter to connect() function otherwise it will generate an error." }, { "code": null, "e": 32642, "s": 32634, "text": "Output:" }, { "code": null, "e": 33188, "s": 32642, "text": "First we call this.props.increaseBurger(5) in Button from our component.Notice how we pass number ‘5’ as an parameter ,this parameter will be supplied to increaseBurgerAction(parameter) function of mapDispatchToProps function.Then the increaseBurgerAction() of burgerActions.js file will be called which will return action_type and ‘5’ as a payload to reducer function.Then the burgerReducer() function will be called which will accept an initial state and action as a parameter and then increase the numberOfBurger from the initial value to +5." }, { "code": null, "e": 33415, "s": 33188, "text": "First we call this.props.increaseBurger(5) in Button from our component.Notice how we pass number ‘5’ as an parameter ,this parameter will be supplied to increaseBurgerAction(parameter) function of mapDispatchToProps function." }, { "code": null, "e": 33559, "s": 33415, "text": "Then the increaseBurgerAction() of burgerActions.js file will be called which will return action_type and ‘5’ as a payload to reducer function." }, { "code": null, "e": 33736, "s": 33559, "text": "Then the burgerReducer() function will be called which will accept an initial state and action as a parameter and then increase the numberOfBurger from the initial value to +5." }, { "code": null, "e": 33871, "s": 33736, "text": "this.props.decreaseBurger() in Button works the same as this.props.increaseBurger(). Notice we haven’t passed any parameter this time." }, { "code": null, "e": 34127, "s": 33871, "text": "Multiple Reducers: In most cases, we have to use multiple reducers in order to separate states and actions. To demonstrate this I have created another Directory named Pizza which contains code for pizzaReducer.js, pizzaActionsType.js, and pizzaActions.js." }, { "code": null, "e": 34236, "s": 34127, "text": "store.js: In this, we use combineReducers() which is an inbuilt function of ‘redux’ to combine our reducers." }, { "code": null, "e": 34247, "s": 34236, "text": "Javascript" }, { "code": "import {createStore,combineReducers} from 'redux'; import burgerReducer from './Burger/burgerReducer';import pizzaReducer from './Pizza/pizzareducer'; // Combining burgerReducer and pizzaReducer in rootReducerconst rootReducer=combineReducers({ burgerReducer:burgerReducer, pizzaReducer:pizzaReducer}) // Passing rootReducer to createStoreconst store=createStore(rootReducer); export default store;", "e": 34656, "s": 34247, "text": null }, { "code": null, "e": 34673, "s": 34656, "text": "pizzaReducer.js:" }, { "code": null, "e": 34684, "s": 34673, "text": "Javascript" }, { "code": "import {PIZZA_DECREASE,PIZZA_INCREASE} from './pizzaActionsType'; // Initializing state const initialState={ numberOfPizza:30} const pizzaReducer=(state=initialState,action)=>{ switch(action.type){ case PIZZA_INCREASE:return{ ...state, numberOfPizza:state.numberOfPizza+action.payload } case PIZZA_DECREASE:return{ ...state, numberOfPizza:state.numberOfPizza-1 } default:return state }} export default pizzaReducer;", "e": 35191, "s": 34684, "text": null }, { "code": null, "e": 35211, "s": 35191, "text": "pizzaActionType.js:" }, { "code": null, "e": 35222, "s": 35211, "text": "Javascript" }, { "code": "export const PIZZA_INCREASE='PIZZA_INCREASE';export const PIZZA_DECREASE='PIZZA_DECREASE';", "e": 35313, "s": 35222, "text": null }, { "code": null, "e": 35330, "s": 35313, "text": "pizzaActions.js:" }, { "code": null, "e": 35341, "s": 35330, "text": "Javascript" }, { "code": "import {PIZZA_INCREASE,PIZZA_DECREASE} from './pizzaActionsType'; // Action functions which return action type // and optional payLoad to burgerReducer export const increasePizzaAction=(parameter)=>{ return{ type:PIZZA_INCREASE, payload:parameter }} export const decreasePizzaAction=()=>{ return{ type:PIZZA_DECREASE }}", "e": 35699, "s": 35341, "text": null }, { "code": null, "e": 35709, "s": 35699, "text": "index.js:" }, { "code": null, "e": 35720, "s": 35709, "text": "Javascript" }, { "code": "// Single file for exporting all actionsexport {increaseBurgerAction} from './Burger/burgerAction';export {decreaseBurgerAction} from './Burger/burgerAction'; export {increasePizzaAction} from './Pizza/pizzaActions';export {decreasePizzaAction} from './Pizza/pizzaActions';", "e": 35995, "s": 35720, "text": null }, { "code": null, "e": 36075, "s": 35995, "text": "screen.js – Modifying our screen component code to use pizza actions and state." }, { "code": null, "e": 36086, "s": 36075, "text": "Javascript" }, { "code": "import React, { Component } from 'react'import { Text, View,Button } from 'react-native'import {connect} from 'react-redux'import {increaseBurgerAction,decreaseBurgerAction,increasePizzaAction,decreasePizzaAction} from '../Redux/index' class Screen extends Component { render() { return ( <View style={{justifyContent:'center',alignItems:'center'}}> <View style={{marginVertical:50}}> <Text> Number Of Burger = {this.props.numberOfBurger} </Text> <Button title=\"Increase Burger\" onPress={()=>{this.props.increaseBurger(5)}}/> <Button title=\"Decrease Burger\" onPress={()=>{this.props.decreaseBurger()}}/> </View> <View style={{marginVertical:50}}> <Text> Number Of Pizza = {this.props.numberOfPizza} </Text> <Button title=\"Increase Burger\" onPress={()=>{this.props.increasePizza(5)}}/> <Button title=\"Decrease Burger\" onPress={()=>{this.props.decreasePizza()}}/> </View> </View> ) }} const mapStateToProps=(state)=>{ return{ numberOfBurger:state.burgerReducer.numberOfBurger, numberOfPizza:state.pizzaReducer.numberOfPizza }} const mapDispatchToProps=(dispatch)=>{ return{ increaseBurger:(parameter)=>{dispatch(increaseBurgerAction(parameter))}, decreaseBurger:()=>{dispatch(decreaseBurgerAction())}, increasePizza:(parameter)=>{dispatch(increasePizzaAction(parameter))}, decreasePizza:()=>{dispatch(decreasePizzaAction())} }} export default connect(mapStateToProps,mapDispatchToProps)(Screen);", "e": 37757, "s": 36086, "text": null }, { "code": null, "e": 37765, "s": 37757, "text": "Output:" }, { "code": null, "e": 37774, "s": 37765, "text": "react-js" }, { "code": null, "e": 37780, "s": 37774, "text": "Redux" }, { "code": null, "e": 37788, "s": 37780, "text": "Android" }, { "code": null, "e": 37799, "s": 37788, "text": "JavaScript" }, { "code": null, "e": 37807, "s": 37799, "text": "Android" }, { "code": null, "e": 37905, "s": 37807, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37963, "s": 37905, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 38001, "s": 37963, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 38044, "s": 38001, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 38077, "s": 38044, "text": "Services in Android with Example" }, { "code": null, "e": 38108, "s": 38077, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 38148, "s": 38108, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 38193, "s": 38148, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 38254, "s": 38193, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 38326, "s": 38254, "text": "Differences between Functional Components and Class Components in React" } ]
Securing Routing Protocols - GeeksforGeeks
29 Oct, 2021 Prerequisite – Routing Information Protocol (RIP), EIGRP fundamentals, OSPF protocol fundamentals Routing is a process in which a layer 3 device (either router or layer 3 switch) finds the best path between the source and destination network. Dynamic routing protocols are used to decrease administrator overhead, i.e., administrator have to configure less but by default, all the routing information is visible to all interested parties as it is not encrypted therefore open to an attack. We can secure the routing protocols like RIP, EIGRP, and OSPF by putting an authentication to it through creating a key chain and applying it to the interface on which we are advertising the routes. Here, we will not talk about protocol instead we will put authentication on RIP, EIGRP, and OSPF. 1. Routing Information Protocol (RIP) – RIP is a distance-vector routing protocol which uses port number 520 and has Administrative Distance 120. It is an application layer protocol and has 3 versions from which only version supports authentication. Configuration – There are 3 routers having named router1 (IP address-192.168.1.1 on ethernet0/0), router2 (IP address-192.168.1.2 on ethernet0/0 and 192.168.2.1 on ethernet0/1), router3 (IP address-192.168.2.2 on ethernet0/0). The router1 will not able to ping router3 as it has no route to 192.168.2.0 network. For this, we will perform RIP routing on all the routers and then put authentication on them. First configuring router1 for RIP: router1(config)#router rip router1(config-router)#network 192.168.1.0 router1(config-router)#no auto-summary router1(config-router)#version 2 Now, configuring RIP for router2: router2(config)#router rip router2(config-router)#network 192.168.1.0 router2(config-router)#network 192.168.2.0 router2(config-router)#no auto-summary router2(config-router)#version 2 Now, configuring RIP for router3: router3(config)#router rip router3(config-router)#network 192.168.2.0 router3(config-router)#no auto-summary router3(config-router)#version 2 Here, we have enable version 2 of RIP as it supports authentication. Now, able to Ping router3 (192.168.2.2) from router1(192.168.1.1), put Authentication on all routers one by one. First, make a key chain and apply it to the interface: router1(config)#key chain cisco router1(config-keychain)#key 1 router1(config-keychain-key)#key-string cisco1 router1(config-keychain-key)#exit router1(config-keychain)#exit router1(config)#int ethernet0/0 router1(config-if)#ip rip authentication mode md5 router1(config-if)#ip rip authentication key-chain cisco Here, we have create a key chain named cisco having key I’d 1 and key-string cisco1 and apply it to the interface ethernet0/0 (at which we have advertise RIP). Now creating same key chain on router2: router2(config)#key chain cisco router2(config-keychain)#key 1 router2(config-keychain-key)#key-string cisco1 router2(config-keychain-key)#exit router2(config-keychain)#exit router2(config)#int ethernet0/0 router2(config-if)#ip rip authentication mode md5 router2(config-if)#ip rip authentication key-chain cisco Note – The configuration of key chain, its I’d and key-string should be the same on both the routers. 2. Enhanced Interior Gateway Routing Protocol – EIGRP is an advanced distance routing protocol which uses protocol number 88 and has Administrative Distance 90. It is a network layer protocol which supports clear text and md5 authentication. Configuration – Taking same topology, there are 3 routers having named router1 (IP address-192.168.1.1 on ethernet0/0), router2 (ip address-192.168.1.2 on ethernet0/0 and 192.168.2.1 on ethernet0/1), router3 (ip address-192.168.2.2 on ethernet0/0). Here also, the router1 will not able to ping router3 as it has no route to 192.168.2.0 network. For this we will perform EIGRP routing on all the routers and then put authentication on them. Configuring EIGRP on router 1: router1(config)#router eigrp 100 router1(config-router)#network 192.168.1.0 router1(config-router)#no auto-summary Here, Autonomous System Number 100 is used. Configuring EIGRP on router2: router2(config)#router EIGRP 100 router2(config-router)#network 192.168.1.0 router2(config-router)#network 192.168.2.0 router2(config-router)#no auto-summary Configuring EIGRP on router3: router3(config)#router eigrp 100 router3(config-router)#network 192.168.2.0 router3(config-router)#no auto-summary Now, putting authentication on routers using eigrp. router1(config)#key chain cisco router1(config-keychain)#key 1 router1(config-keychain-key)#key-string cisco1 router1(config-keychain-key)#exit router1(config-keychain)#exit router1(config)#int ethernet0/0 router1(config-if)#ip authentication mode eigrp 100 md5 router1(config-if)#ip authentication key-chain eigrp 100 cisco Configuring same on router2: router2(config)#key chain cisco router2(config-keychain)#key 1 router2(config-keychain-key)#key-string cisco1 router2(config-keychain-key)#exit router2(config-keychain)#exit router2(config)#int ethernet0/0 router2(config-if)#ip authentication mode eigrp 100 md5 router2(config-if)#ip authentication key-chain eigrp 100 cisco Note – The configuration of key chain, its I’d and key-string should be same on both the routers. 3. Open Shortest Path First (OSPF) – OSPF is a link-state routing protocol which uses protocol number 89 and Administrative Distance 110.It is a network layer protocol which supports clear text and md5 authentication. Configuration – Taking same topology, there are 3 routers having named router1 (ip address-192.168.1.1 on ethernet0/0), router2 (ip address-192.168.1.2 on ethernet0/0 and 192.168.2.1 on ethernet0/1), router3 (ip address-192.168.2.2 on ethernet0/0). For this we will perform OSPF routing on all the routers and then put authentication on them. Configuring OSPF on router1: router1(config)#router ospf 1 router1(config-router)#network 192.168.1.0 0.0.0.255 area 0 Configuring OSPF on router2: router2(config)#router ospf 1 router2(config-router)#network 192.168.1.0 0.0.0.255 area 0 router2(config-router)#network 192.168.2.0 0.0.0.255 area 0 Configuring ospf on router3: router3(config)#router OSPF 1 router2(config-router)#network 192.168.2.0 0.0.0.255 area 0 configuring Authentication on router1: router1(config)#key chain cisco router1(config-keychain)#key 1 router1(config-keychain-key)#key-string cisco1 router1(config-keychain-key)#exit router1(config-keychain)#exit router1(config)#int ethernet0/0 router1(config-if)#ip ospf Authentication message-digest router1(config-if)#ip ospf authentication-key cisco1 Configuring Authentication on router2: router2(config)#key chain cisco router2(config-keychain)#key 1 router2(config-keychain-key)#key-string cisco1 router2(config-keychain-key)#exit router2(config-keychain)#exit router2(config)#int ethernet0/0 router2(config-if)#ip ospf authentication message-digest router2(config-if)#ip ospf authentication-key cisco1 Note – The configuration of key chain, its I’d and key-string should be same on both the routers. Md5 is susceptible to brute-force attack therefore it is advised to use passwords containing numbers or special characters and should be long. Pushpender007 Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. RSA Algorithm in Cryptography Differences between TCP and UDP TCP Server-Client implementation in C Data encryption standard (DES) | Set 1 Differences between IPv4 and IPv6 Socket Programming in Python Types of Network Topology TCP 3-Way Handshake Process Implementation of Diffie-Hellman Algorithm Types of Transmission Media
[ { "code": null, "e": 25887, "s": 25859, "text": "\n29 Oct, 2021" }, { "code": null, "e": 26378, "s": 25887, "text": "Prerequisite – Routing Information Protocol (RIP), EIGRP fundamentals, OSPF protocol fundamentals Routing is a process in which a layer 3 device (either router or layer 3 switch) finds the best path between the source and destination network. Dynamic routing protocols are used to decrease administrator overhead, i.e., administrator have to configure less but by default, all the routing information is visible to all interested parties as it is not encrypted therefore open to an attack. " }, { "code": null, "e": 26676, "s": 26378, "text": "We can secure the routing protocols like RIP, EIGRP, and OSPF by putting an authentication to it through creating a key chain and applying it to the interface on which we are advertising the routes. Here, we will not talk about protocol instead we will put authentication on RIP, EIGRP, and OSPF. " }, { "code": null, "e": 26927, "s": 26676, "text": "1. Routing Information Protocol (RIP) – RIP is a distance-vector routing protocol which uses port number 520 and has Administrative Distance 120. It is an application layer protocol and has 3 versions from which only version supports authentication. " }, { "code": null, "e": 26944, "s": 26927, "text": "Configuration – " }, { "code": null, "e": 27337, "s": 26946, "text": "There are 3 routers having named router1 (IP address-192.168.1.1 on ethernet0/0), router2 (IP address-192.168.1.2 on ethernet0/0 and 192.168.2.1 on ethernet0/1), router3 (IP address-192.168.2.2 on ethernet0/0). The router1 will not able to ping router3 as it has no route to 192.168.2.0 network. For this, we will perform RIP routing on all the routers and then put authentication on them. " }, { "code": null, "e": 27373, "s": 27337, "text": "First configuring router1 for RIP: " }, { "code": null, "e": 27515, "s": 27373, "text": "router1(config)#router rip\nrouter1(config-router)#network 192.168.1.0\nrouter1(config-router)#no auto-summary\nrouter1(config-router)#version 2" }, { "code": null, "e": 27550, "s": 27515, "text": "Now, configuring RIP for router2: " }, { "code": null, "e": 27735, "s": 27550, "text": "router2(config)#router rip\nrouter2(config-router)#network 192.168.1.0\nrouter2(config-router)#network 192.168.2.0\nrouter2(config-router)#no auto-summary\nrouter2(config-router)#version 2" }, { "code": null, "e": 27770, "s": 27735, "text": "Now, configuring RIP for router3: " }, { "code": null, "e": 27913, "s": 27770, "text": "router3(config)#router rip\nrouter3(config-router)#network 192.168.2.0\nrouter3(config-router)#no auto-summary \nrouter3(config-router)#version 2" }, { "code": null, "e": 28152, "s": 27913, "text": "Here, we have enable version 2 of RIP as it supports authentication. Now, able to Ping router3 (192.168.2.2) from router1(192.168.1.1), put Authentication on all routers one by one. First, make a key chain and apply it to the interface: " }, { "code": null, "e": 28465, "s": 28152, "text": "router1(config)#key chain cisco\nrouter1(config-keychain)#key 1\nrouter1(config-keychain-key)#key-string cisco1\nrouter1(config-keychain-key)#exit\nrouter1(config-keychain)#exit\nrouter1(config)#int ethernet0/0\nrouter1(config-if)#ip rip authentication mode md5\nrouter1(config-if)#ip rip authentication key-chain cisco" }, { "code": null, "e": 28667, "s": 28465, "text": "Here, we have create a key chain named cisco having key I’d 1 and key-string cisco1 and apply it to the interface ethernet0/0 (at which we have advertise RIP). Now creating same key chain on router2: " }, { "code": null, "e": 28980, "s": 28667, "text": "router2(config)#key chain cisco\nrouter2(config-keychain)#key 1\nrouter2(config-keychain-key)#key-string cisco1\nrouter2(config-keychain-key)#exit\nrouter2(config-keychain)#exit\nrouter2(config)#int ethernet0/0\nrouter2(config-if)#ip rip authentication mode md5\nrouter2(config-if)#ip rip authentication key-chain cisco" }, { "code": null, "e": 29083, "s": 28980, "text": "Note – The configuration of key chain, its I’d and key-string should be the same on both the routers. " }, { "code": null, "e": 29326, "s": 29083, "text": "2. Enhanced Interior Gateway Routing Protocol – EIGRP is an advanced distance routing protocol which uses protocol number 88 and has Administrative Distance 90. It is a network layer protocol which supports clear text and md5 authentication. " }, { "code": null, "e": 29343, "s": 29326, "text": "Configuration – " }, { "code": null, "e": 29770, "s": 29345, "text": "Taking same topology, there are 3 routers having named router1 (IP address-192.168.1.1 on ethernet0/0), router2 (ip address-192.168.1.2 on ethernet0/0 and 192.168.2.1 on ethernet0/1), router3 (ip address-192.168.2.2 on ethernet0/0). Here also, the router1 will not able to ping router3 as it has no route to 192.168.2.0 network. For this we will perform EIGRP routing on all the routers and then put authentication on them. " }, { "code": null, "e": 29802, "s": 29770, "text": "Configuring EIGRP on router 1: " }, { "code": null, "e": 29917, "s": 29802, "text": "router1(config)#router eigrp 100\nrouter1(config-router)#network 192.168.1.0\nrouter1(config-router)#no auto-summary" }, { "code": null, "e": 29992, "s": 29917, "text": "Here, Autonomous System Number 100 is used. Configuring EIGRP on router2: " }, { "code": null, "e": 30150, "s": 29992, "text": "router2(config)#router EIGRP 100\nrouter2(config-router)#network 192.168.1.0\nrouter2(config-router)#network 192.168.2.0\nrouter2(config-router)#no auto-summary" }, { "code": null, "e": 30181, "s": 30150, "text": "Configuring EIGRP on router3: " }, { "code": null, "e": 30296, "s": 30181, "text": "router3(config)#router eigrp 100\nrouter3(config-router)#network 192.168.2.0\nrouter3(config-router)#no auto-summary" }, { "code": null, "e": 30349, "s": 30296, "text": "Now, putting authentication on routers using eigrp. " }, { "code": null, "e": 30674, "s": 30349, "text": "router1(config)#key chain cisco\nrouter1(config-keychain)#key 1\nrouter1(config-keychain-key)#key-string cisco1\nrouter1(config-keychain-key)#exit\nrouter1(config-keychain)#exit\nrouter1(config)#int ethernet0/0\nrouter1(config-if)#ip authentication mode eigrp 100 md5\nrouter1(config-if)#ip authentication key-chain eigrp 100 cisco" }, { "code": null, "e": 30704, "s": 30674, "text": "Configuring same on router2: " }, { "code": null, "e": 31029, "s": 30704, "text": "router2(config)#key chain cisco\nrouter2(config-keychain)#key 1\nrouter2(config-keychain-key)#key-string cisco1\nrouter2(config-keychain-key)#exit\nrouter2(config-keychain)#exit\nrouter2(config)#int ethernet0/0\nrouter2(config-if)#ip authentication mode eigrp 100 md5\nrouter2(config-if)#ip authentication key-chain eigrp 100 cisco" }, { "code": null, "e": 31128, "s": 31029, "text": "Note – The configuration of key chain, its I’d and key-string should be same on both the routers. " }, { "code": null, "e": 31347, "s": 31128, "text": "3. Open Shortest Path First (OSPF) – OSPF is a link-state routing protocol which uses protocol number 89 and Administrative Distance 110.It is a network layer protocol which supports clear text and md5 authentication. " }, { "code": null, "e": 31364, "s": 31347, "text": "Configuration – " }, { "code": null, "e": 31723, "s": 31366, "text": "Taking same topology, there are 3 routers having named router1 (ip address-192.168.1.1 on ethernet0/0), router2 (ip address-192.168.1.2 on ethernet0/0 and 192.168.2.1 on ethernet0/1), router3 (ip address-192.168.2.2 on ethernet0/0). For this we will perform OSPF routing on all the routers and then put authentication on them. Configuring OSPF on router1: " }, { "code": null, "e": 31813, "s": 31723, "text": "router1(config)#router ospf 1\nrouter1(config-router)#network 192.168.1.0 0.0.0.255 area 0" }, { "code": null, "e": 31843, "s": 31813, "text": "Configuring OSPF on router2: " }, { "code": null, "e": 31993, "s": 31843, "text": "router2(config)#router ospf 1\nrouter2(config-router)#network 192.168.1.0 0.0.0.255 area 0\nrouter2(config-router)#network 192.168.2.0 0.0.0.255 area 0" }, { "code": null, "e": 32023, "s": 31993, "text": "Configuring ospf on router3: " }, { "code": null, "e": 32113, "s": 32023, "text": "router3(config)#router OSPF 1\nrouter2(config-router)#network 192.168.2.0 0.0.0.255 area 0" }, { "code": null, "e": 32153, "s": 32113, "text": "configuring Authentication on router1: " }, { "code": null, "e": 32469, "s": 32153, "text": "router1(config)#key chain cisco\nrouter1(config-keychain)#key 1\nrouter1(config-keychain-key)#key-string cisco1\nrouter1(config-keychain-key)#exit\nrouter1(config-keychain)#exit\nrouter1(config)#int ethernet0/0\nrouter1(config-if)#ip ospf Authentication message-digest\nrouter1(config-if)#ip ospf authentication-key cisco1" }, { "code": null, "e": 32509, "s": 32469, "text": "Configuring Authentication on router2: " }, { "code": null, "e": 32825, "s": 32509, "text": "router2(config)#key chain cisco\nrouter2(config-keychain)#key 1\nrouter2(config-keychain-key)#key-string cisco1\nrouter2(config-keychain-key)#exit\nrouter2(config-keychain)#exit\nrouter2(config)#int ethernet0/0\nrouter2(config-if)#ip ospf authentication message-digest\nrouter2(config-if)#ip ospf authentication-key cisco1" }, { "code": null, "e": 32833, "s": 32825, "text": "Note – " }, { "code": null, "e": 32925, "s": 32833, "text": "The configuration of key chain, its I’d and key-string should be same on both the routers. " }, { "code": null, "e": 33069, "s": 32925, "text": "Md5 is susceptible to brute-force attack therefore it is advised to use passwords containing numbers or special characters and should be long. " }, { "code": null, "e": 33083, "s": 33069, "text": "Pushpender007" }, { "code": null, "e": 33101, "s": 33083, "text": "Computer Networks" }, { "code": null, "e": 33119, "s": 33101, "text": "Computer Networks" }, { "code": null, "e": 33217, "s": 33119, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33247, "s": 33217, "text": "RSA Algorithm in Cryptography" }, { "code": null, "e": 33279, "s": 33247, "text": "Differences between TCP and UDP" }, { "code": null, "e": 33317, "s": 33279, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 33356, "s": 33317, "text": "Data encryption standard (DES) | Set 1" }, { "code": null, "e": 33390, "s": 33356, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 33419, "s": 33390, "text": "Socket Programming in Python" }, { "code": null, "e": 33445, "s": 33419, "text": "Types of Network Topology" }, { "code": null, "e": 33473, "s": 33445, "text": "TCP 3-Way Handshake Process" }, { "code": null, "e": 33516, "s": 33473, "text": "Implementation of Diffie-Hellman Algorithm" } ]
Python - assertLessEqual() function in unittest - GeeksforGeeks
24 Oct, 2020 assertLessEqual() in Python is an unittest library function that is used in unit testing to check whether the first given value is less than or equal to the second value or not. This function will take three parameters as input and return a boolean value depending upon the assert condition. This function checks that if the first given value is less than or equal to the second value and returns true if it is so, else return false if the first value is not less than or equal to the second value. Syntax: assertLessEqual(first, second, message=None) Parameters: assertLessEqual() accept three parameters which are listed below with explanation: first: first input value (integer) second: second input value (integer) message: a string sentence as a message which got displayed when the test case got failed. Listed below is an example illustrating the positive and negative test case for given assert function: Example 1: Python3 # test suiteimport unittest class TestStringMethods(unittest.TestCase): # negative test function to test if values1 is less or equal than value2 def test_negativeForLessEqual(self): first = 6 second = 5 # error message in case if test case got failed message = "first value is not less than or equal to second value." # assert function() to check if values1 is less or equal than value2 self.assertLessEqual(first, second, message) if __name__ == '__main__': unittest.main() Output: F======================================================================FAIL: test_negativeForLessEqual (__main__.TestStringMethods)———————————————————————-Traceback (most recent call last): File “p1.py”, line 13, in test_negativeForLessEqual self.assertLessEqual(first, second, message)AssertionError: 6 not less than or equal to 5 : first value is not less than or equal to second value. ———————————————————————-Ran 1 test in 0.000s FAILED (failures=1) Example 2: Python # test suiteimport unittest class TestStringMethods(unittest.TestCase): # positive test function to test if value1 is less or equal than value2 def test_positiveForLessEqual(self): first = 4 second = 4 # error message in case if test case got failed message = "first value is not less than or equal to second value." # assert function() to check if values1 is less or equal than value2 self.assertLessEqual(first, second, message) if __name__ == '__main__': unittest.main() Output: .———————————————————————-Ran 1 test in 0.000s OK Python unittest-library Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25555, "s": 25527, "text": "\n24 Oct, 2020" }, { "code": null, "e": 25847, "s": 25555, "text": "assertLessEqual() in Python is an unittest library function that is used in unit testing to check whether the first given value is less than or equal to the second value or not. This function will take three parameters as input and return a boolean value depending upon the assert condition." }, { "code": null, "e": 26054, "s": 25847, "text": "This function checks that if the first given value is less than or equal to the second value and returns true if it is so, else return false if the first value is not less than or equal to the second value." }, { "code": null, "e": 26107, "s": 26054, "text": "Syntax: assertLessEqual(first, second, message=None)" }, { "code": null, "e": 26202, "s": 26107, "text": "Parameters: assertLessEqual() accept three parameters which are listed below with explanation:" }, { "code": null, "e": 26237, "s": 26202, "text": "first: first input value (integer)" }, { "code": null, "e": 26275, "s": 26237, "text": "second: second input value (integer)" }, { "code": null, "e": 26366, "s": 26275, "text": "message: a string sentence as a message which got displayed when the test case got failed." }, { "code": null, "e": 26469, "s": 26366, "text": "Listed below is an example illustrating the positive and negative test case for given assert function:" }, { "code": null, "e": 26480, "s": 26469, "text": "Example 1:" }, { "code": null, "e": 26488, "s": 26480, "text": "Python3" }, { "code": "# test suiteimport unittest class TestStringMethods(unittest.TestCase): # negative test function to test if values1 is less or equal than value2 def test_negativeForLessEqual(self): first = 6 second = 5 # error message in case if test case got failed message = \"first value is not less than or equal to second value.\" # assert function() to check if values1 is less or equal than value2 self.assertLessEqual(first, second, message) if __name__ == '__main__': unittest.main()", "e": 27040, "s": 26488, "text": null }, { "code": null, "e": 27048, "s": 27040, "text": "Output:" }, { "code": null, "e": 27439, "s": 27048, "text": "F======================================================================FAIL: test_negativeForLessEqual (__main__.TestStringMethods)———————————————————————-Traceback (most recent call last): File “p1.py”, line 13, in test_negativeForLessEqual self.assertLessEqual(first, second, message)AssertionError: 6 not less than or equal to 5 : first value is not less than or equal to second value." }, { "code": null, "e": 27484, "s": 27439, "text": "———————————————————————-Ran 1 test in 0.000s" }, { "code": null, "e": 27504, "s": 27484, "text": "FAILED (failures=1)" }, { "code": null, "e": 27515, "s": 27504, "text": "Example 2:" }, { "code": null, "e": 27522, "s": 27515, "text": "Python" }, { "code": "# test suiteimport unittest class TestStringMethods(unittest.TestCase): # positive test function to test if value1 is less or equal than value2 def test_positiveForLessEqual(self): first = 4 second = 4 # error message in case if test case got failed message = \"first value is not less than or equal to second value.\" # assert function() to check if values1 is less or equal than value2 self.assertLessEqual(first, second, message) if __name__ == '__main__': unittest.main()", "e": 28076, "s": 27522, "text": null }, { "code": null, "e": 28084, "s": 28076, "text": "Output:" }, { "code": null, "e": 28130, "s": 28084, "text": ".———————————————————————-Ran 1 test in 0.000s" }, { "code": null, "e": 28133, "s": 28130, "text": "OK" }, { "code": null, "e": 28157, "s": 28133, "text": "Python unittest-library" }, { "code": null, "e": 28164, "s": 28157, "text": "Python" }, { "code": null, "e": 28262, "s": 28164, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28294, "s": 28262, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28336, "s": 28294, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28378, "s": 28336, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28434, "s": 28378, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28461, "s": 28434, "text": "Python Classes and Objects" }, { "code": null, "e": 28492, "s": 28461, "text": "Python | os.path.join() method" }, { "code": null, "e": 28531, "s": 28492, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28560, "s": 28531, "text": "Create a directory in Python" }, { "code": null, "e": 28582, "s": 28560, "text": "Defaultdict in Python" } ]
English dictionary application using Python - GeeksforGeeks
21 Nov, 2019 Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair. Key value is provided in the dictionary to make it more optimized. Each key-value pair in a Dictionary is separated by a colon :, whereas each key is separated by a ‘comma’. A Dictionary in Python works similar to the Dictionary in a real world. Keys of a Dictionary must be unique and of immutable data type such as Strings, Integers, and tuples, but the key-values can be repeated and be of any type. Note – To know more about dictionary click here. json: It comes built-in with python, so there is no need to install it externally. To know more about JSON click here. difflib: This module provides classes and functions for comparing sequences. It also comes built-in with python so there is no need to install it externally. Steps: Download a JSON file containing English dictionary words in a python dictionaries data type format, or arrange the file content in that way.Create a folder and add the downloaded .json file and python script in that folder.In python editor, import the required modules. Download a JSON file containing English dictionary words in a python dictionaries data type format, or arrange the file content in that way. Create a folder and add the downloaded .json file and python script in that folder. In python editor, import the required modules. Below is the implementation. # Import the modules requiredimport jsonfrom difflib import get_close_matches # Loading data from json file# in python dictionarydata = json.load(open("dictionary.json")) def translate(w): # converts to lower case w = w.lower() if w in data: return data[w] # for getting close matches of word elif len(get_close_matches(w, data.keys())) > 0: yn = input("Did you mean % s instead? Enter Y if yes, or N if no: " % get_close_matches(w, data.keys())[0]) yn = yn.lower() if yn == "y": return data[get_close_matches(w, data.keys())[0]] elif yn == "n": return "The word doesn't exist. Please double check it." else: return "We didn't understand your entry." else: return "The word doesn't exist. Please double check it." # Driver codeword = input("Enter word: ")output = translate(word) if type(output) == list: for item in output: print(item)else: print(output)input('Press ENTER to exit') Important, the output should not vary with different cases such as upper case and lower case input of same text should be same i.e rain or Rain or RaIn should produce same output. Also if user mistakes with spelling of word it should return the close words related to the word input or print a user friendly message that word does not exist. Input: rain Output: For mixed cases –Input: RaIn Output: If spelling is wrong it gives the word holding closest meaning with word typed by the user as shown. Suppose if the input is “rane” and the user wanter to search “range”, then the output will be as follows.Input: rane Output: python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python How To Convert Python Dictionary To JSON? sum() function in Python
[ { "code": null, "e": 25483, "s": 25455, "text": "\n21 Nov, 2019" }, { "code": null, "e": 25865, "s": 25483, "text": "Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair. Key value is provided in the dictionary to make it more optimized. Each key-value pair in a Dictionary is separated by a colon :, whereas each key is separated by a ‘comma’." }, { "code": null, "e": 26094, "s": 25865, "text": "A Dictionary in Python works similar to the Dictionary in a real world. Keys of a Dictionary must be unique and of immutable data type such as Strings, Integers, and tuples, but the key-values can be repeated and be of any type." }, { "code": null, "e": 26143, "s": 26094, "text": "Note – To know more about dictionary click here." }, { "code": null, "e": 26262, "s": 26143, "text": "json: It comes built-in with python, so there is no need to install it externally. To know more about JSON click here." }, { "code": null, "e": 26420, "s": 26262, "text": "difflib: This module provides classes and functions for comparing sequences. It also comes built-in with python so there is no need to install it externally." }, { "code": null, "e": 26427, "s": 26420, "text": "Steps:" }, { "code": null, "e": 26697, "s": 26427, "text": "Download a JSON file containing English dictionary words in a python dictionaries data type format, or arrange the file content in that way.Create a folder and add the downloaded .json file and python script in that folder.In python editor, import the required modules." }, { "code": null, "e": 26838, "s": 26697, "text": "Download a JSON file containing English dictionary words in a python dictionaries data type format, or arrange the file content in that way." }, { "code": null, "e": 26922, "s": 26838, "text": "Create a folder and add the downloaded .json file and python script in that folder." }, { "code": null, "e": 26969, "s": 26922, "text": "In python editor, import the required modules." }, { "code": null, "e": 26998, "s": 26969, "text": "Below is the implementation." }, { "code": "# Import the modules requiredimport jsonfrom difflib import get_close_matches # Loading data from json file# in python dictionarydata = json.load(open(\"dictionary.json\")) def translate(w): # converts to lower case w = w.lower() if w in data: return data[w] # for getting close matches of word elif len(get_close_matches(w, data.keys())) > 0: yn = input(\"Did you mean % s instead? Enter Y if yes, or N if no: \" % get_close_matches(w, data.keys())[0]) yn = yn.lower() if yn == \"y\": return data[get_close_matches(w, data.keys())[0]] elif yn == \"n\": return \"The word doesn't exist. Please double check it.\" else: return \"We didn't understand your entry.\" else: return \"The word doesn't exist. Please double check it.\" # Driver codeword = input(\"Enter word: \")output = translate(word) if type(output) == list: for item in output: print(item)else: print(output)input('Press ENTER to exit') ", "e": 28015, "s": 26998, "text": null }, { "code": null, "e": 28357, "s": 28015, "text": "Important, the output should not vary with different cases such as upper case and lower case input of same text should be same i.e rain or Rain or RaIn should produce same output. Also if user mistakes with spelling of word it should return the close words related to the word input or print a user friendly message that word does not exist." }, { "code": null, "e": 28364, "s": 28357, "text": "Input:" }, { "code": null, "e": 28369, "s": 28364, "text": "rain" }, { "code": null, "e": 28377, "s": 28369, "text": "Output:" }, { "code": null, "e": 28401, "s": 28377, "text": "For mixed cases –Input:" }, { "code": null, "e": 28406, "s": 28401, "text": "RaIn" }, { "code": null, "e": 28414, "s": 28406, "text": "Output:" }, { "code": null, "e": 28627, "s": 28414, "text": "If spelling is wrong it gives the word holding closest meaning with word typed by the user as shown. Suppose if the input is “rane” and the user wanter to search “range”, then the output will be as follows.Input:" }, { "code": null, "e": 28632, "s": 28627, "text": "rane" }, { "code": null, "e": 28640, "s": 28632, "text": "Output:" }, { "code": null, "e": 28655, "s": 28640, "text": "python-utility" }, { "code": null, "e": 28662, "s": 28655, "text": "Python" }, { "code": null, "e": 28760, "s": 28662, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28792, "s": 28760, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28814, "s": 28792, "text": "Enumerate() in Python" }, { "code": null, "e": 28856, "s": 28814, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28882, "s": 28856, "text": "Python String | replace()" }, { "code": null, "e": 28911, "s": 28882, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28948, "s": 28911, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28984, "s": 28948, "text": "Convert integer to string in Python" }, { "code": null, "e": 29026, "s": 28984, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29068, "s": 29026, "text": "How To Convert Python Dictionary To JSON?" } ]
Program for distance between two points on earth - GeeksforGeeks
09 Apr, 2021 Given latitude and longitude in degrees find the distance between two points on the earth. Image Source : WikipediaExamples: Input : Latitude 1: 53.32055555555556 Latitude 2: 53.31861111111111 Longitude 1: -1.7297222222222221 Longitude 2: -1.6997222222222223 Output: Distance is: 2.0043678382716137 Kilometers Problem can be solved using Haversine formula: The great circle distance or the orthodromic distance is the shortest distance between two points on a sphere (or the surface of Earth). In order to use this method, we need to have the co-ordinates of point A and point B.The great circle method is chosen over other methods.First, convert the latitude and longitude values from decimal degrees to radians. For this divide the values of longitude and latitude of both the points by 180/pi. The value of pi is 22/7. The value of 180/pi is approximately 57.29577951. If we want to calculate the distance between two places in miles, use the value 3, 963, which is the radius of Earth. If we want to calculate the distance between two places in kilometers, use the value 6, 378.8, which is the radius of Earth. Find the value of the latitude in radians:Value of Latitude in Radians, lat = Latitude / (180/pi) ORValue of Latitude in Radians, lat = Latitude / 57.29577951Find the value of longitude in radians:Value of Longitude in Radians, long = Longitude / (180/pi) ORValue of Longitude in Radians, long = Longitude / 57.29577951 Get the co-ordinates of point A in terms of latitude and longitude. Use the above conversion method to convert the values of latitude and longitude in radians. I will call it as lat1 and long1. Do the same for the co-ordinates of Point B and get lat2 and long2.Now, to get the distance between point A and point B use the following formula: Distance, d = 3963.0 * arccos[(sin(lat1) * sin(lat2)) + cos(lat1) * cos(lat2) * cos(long2 – long1)] The obtained distance, d, is in miles. If you want your value to be in units of kilometers, multiple d by 1.609344.d in kilometers = 1.609344 * d in milesThus you can have the shortest distance between two places on Earth using the great circle distance approach. C++ Java Python3 C# PHP Javascript // C++ program to calculate Distance// Between Two Points on Earth#include <bits/stdc++.h>using namespace std; // Utility function for// converting degrees to radianslong double toRadians(const long double °ree){ // cmath library in C++ // defines the constant // M_PI as the value of // pi accurate to 1e-30 long double one_deg = (M_PI) / 180; return (one_deg * degree);} long double distance(long double lat1, long double long1, long double lat2, long double long2){ // Convert the latitudes // and longitudes // from degree to radians. lat1 = toRadians(lat1); long1 = toRadians(long1); lat2 = toRadians(lat2); long2 = toRadians(long2); // Haversine Formula long double dlong = long2 - long1; long double dlat = lat2 - lat1; long double ans = pow(sin(dlat / 2), 2) + cos(lat1) * cos(lat2) * pow(sin(dlong / 2), 2); ans = 2 * asin(sqrt(ans)); // Radius of Earth in // Kilometers, R = 6371 // Use R = 3956 for miles long double R = 6371; // Calculate the result ans = ans * R; return ans;} // Driver Codeint main(){ long double lat1 = 53.32055555555556; long double long1 = -1.7297222222222221; long double lat2 = 53.31861111111111; long double long2 = -1.6997222222222223; // call the distance function cout << setprecision(15) << fixed; cout << distance(lat1, long1, lat2, long2) << " K.M"; return 0;} // This code is contributed// by Aayush Chaturvedi // Java program to calculate Distance Between// Two Points on Earthimport java.util.*;import java.lang.*; class GFG { public static double distance(double lat1, double lat2, double lon1, double lon2) { // The math module contains a function // named toRadians which converts from // degrees to radians. lon1 = Math.toRadians(lon1); lon2 = Math.toRadians(lon2); lat1 = Math.toRadians(lat1); lat2 = Math.toRadians(lat2); // Haversine formula double dlon = lon2 - lon1; double dlat = lat2 - lat1; double a = Math.pow(Math.sin(dlat / 2), 2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(dlon / 2),2); double c = 2 * Math.asin(Math.sqrt(a)); // Radius of earth in kilometers. Use 3956 // for miles double r = 6371; // calculate the result return(c * r); } // driver code public static void main(String[] args) { double lat1 = 53.32055555555556; double lat2 = 53.31861111111111; double lon1 = -1.7297222222222221; double lon2 = -1.6997222222222223; System.out.println(distance(lat1, lat2, lon1, lon2) + " K.M"); }} // This code is contributed by Prasad Kshirsagar # Python 3 program to calculate Distance Between Two Points on Earthfrom math import radians, cos, sin, asin, sqrtdef distance(lat1, lat2, lon1, lon2): # The math module contains a function named # radians which converts from degrees to radians. lon1 = radians(lon1) lon2 = radians(lon2) lat1 = radians(lat1) lat2 = radians(lat2) # Haversine formula dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2 c = 2 * asin(sqrt(a)) # Radius of earth in kilometers. Use 3956 for miles r = 6371 # calculate the result return(c * r) # driver codelat1 = 53.32055555555556lat2 = 53.31861111111111lon1 = -1.7297222222222221lon2 = -1.6997222222222223print(distance(lat1, lat2, lon1, lon2), "K.M") // C# program to calculate// Distance Between Two// Points on Earthusing System; class GFG{ static double toRadians( double angleIn10thofaDegree) { // Angle in 10th // of a degree return (angleIn10thofaDegree * Math.PI) / 180; } static double distance(double lat1, double lat2, double lon1, double lon2) { // The math module contains // a function named toRadians // which converts from degrees // to radians. lon1 = toRadians(lon1); lon2 = toRadians(lon2); lat1 = toRadians(lat1); lat2 = toRadians(lat2); // Haversine formula double dlon = lon2 - lon1; double dlat = lat2 - lat1; double a = Math.Pow(Math.Sin(dlat / 2), 2) + Math.Cos(lat1) * Math.Cos(lat2) * Math.Pow(Math.Sin(dlon / 2),2); double c = 2 * Math.Asin(Math.Sqrt(a)); // Radius of earth in // kilometers. Use 3956 // for miles double r = 6371; // calculate the result return (c * r); } // Driver code static void Main() { double lat1 = 53.32055555555556; double lat2 = 53.31861111111111; double lon1 = -1.7297222222222221; double lon2 = -1.6997222222222223; Console.WriteLine(distance(lat1, lat2, lon1, lon2) + " K.M"); }} // This code is contributed by// Manish Shaw(manishshaw1) <?php function twopoints_on_earth($latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo) { $long1 = deg2rad($longitudeFrom); $long2 = deg2rad($longitudeTo); $lat1 = deg2rad($latitudeFrom); $lat2 = deg2rad($latitudeTo); //Haversine Formula $dlong = $long2 - $long1; $dlati = $lat2 - $lat1; $val = pow(sin($dlati/2),2)+cos($lat1)*cos($lat2)*pow(sin($dlong/2),2); $res = 2 * asin(sqrt($val)); $radius = 3958.756; return ($res*$radius); } // latitude and longitude of Two Points $latitudeFrom = 19.017656 ; $longitudeFrom = 72.856178; $latitudeTo = 40.7127; $longitudeTo = -74.0059; // Distance between Mumbai and New York print_r(twopoints_on_earth( $latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo).' '.'miles'); // This code is contributed by akash1295// https://auth.geeksforgeeks.org/user/akash1295/articles?> <script> // JavaScript program to calculate Distance Between// Two Points on Earth function distance(lat1, lat2, lon1, lon2) { // The math module contains a function // named toRadians which converts from // degrees to radians. lon1 = lon1 * Math.PI / 180; lon2 = lon2 * Math.PI / 180; lat1 = lat1 * Math.PI / 180; lat2 = lat2 * Math.PI / 180; // Haversine formula let dlon = lon2 - lon1; let dlat = lat2 - lat1; let a = Math.pow(Math.sin(dlat / 2), 2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(dlon / 2),2); let c = 2 * Math.asin(Math.sqrt(a)); // Radius of earth in kilometers. Use 3956 // for miles let r = 6371; // calculate the result return(c * r); } // Driver code let lat1 = 53.32055555555556; let lat2 = 53.31861111111111; let lon1 = -1.7297222222222221; let lon2 = -1.6997222222222223; document.write(distance(lat1, lat2, lon1, lon2) + " K.M"); </script> Output: 2.0043678382716137 K.M Reference: Wikipedia Prasad_Kshirsagar AayushChaturvedi manishshaw1 Akanksha_Rai splevel62 Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check whether a given point lies inside a triangle or not Optimum location of point to minimize total distance Given n line segments, find if any two segments intersect Convex Hull using Divide and Conquer Algorithm Polygon Clipping | Sutherland–Hodgman Algorithm 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": 26353, "s": 26325, "text": "\n09 Apr, 2021" }, { "code": null, "e": 26445, "s": 26353, "text": "Given latitude and longitude in degrees find the distance between two points on the earth. " }, { "code": null, "e": 26481, "s": 26445, "text": "Image Source : WikipediaExamples: " }, { "code": null, "e": 26690, "s": 26481, "text": "Input : Latitude 1: 53.32055555555556\n Latitude 2: 53.31861111111111\n Longitude 1: -1.7297222222222221\n Longitude 2: -1.6997222222222223\nOutput: Distance is: 2.0043678382716137 Kilometers" }, { "code": null, "e": 26741, "s": 26694, "text": "Problem can be solved using Haversine formula:" }, { "code": null, "e": 27500, "s": 26741, "text": "The great circle distance or the orthodromic distance is the shortest distance between two points on a sphere (or the surface of Earth). In order to use this method, we need to have the co-ordinates of point A and point B.The great circle method is chosen over other methods.First, convert the latitude and longitude values from decimal degrees to radians. For this divide the values of longitude and latitude of both the points by 180/pi. The value of pi is 22/7. The value of 180/pi is approximately 57.29577951. If we want to calculate the distance between two places in miles, use the value 3, 963, which is the radius of Earth. If we want to calculate the distance between two places in kilometers, use the value 6, 378.8, which is the radius of Earth. " }, { "code": null, "e": 27820, "s": 27500, "text": "Find the value of the latitude in radians:Value of Latitude in Radians, lat = Latitude / (180/pi) ORValue of Latitude in Radians, lat = Latitude / 57.29577951Find the value of longitude in radians:Value of Longitude in Radians, long = Longitude / (180/pi) ORValue of Longitude in Radians, long = Longitude / 57.29577951" }, { "code": null, "e": 28162, "s": 27820, "text": "Get the co-ordinates of point A in terms of latitude and longitude. Use the above conversion method to convert the values of latitude and longitude in radians. I will call it as lat1 and long1. Do the same for the co-ordinates of Point B and get lat2 and long2.Now, to get the distance between point A and point B use the following formula: " }, { "code": null, "e": 28262, "s": 28162, "text": "Distance, d = 3963.0 * arccos[(sin(lat1) * sin(lat2)) + cos(lat1) * cos(lat2) * cos(long2 – long1)]" }, { "code": null, "e": 28528, "s": 28262, "text": "The obtained distance, d, is in miles. If you want your value to be in units of kilometers, multiple d by 1.609344.d in kilometers = 1.609344 * d in milesThus you can have the shortest distance between two places on Earth using the great circle distance approach. " }, { "code": null, "e": 28532, "s": 28528, "text": "C++" }, { "code": null, "e": 28537, "s": 28532, "text": "Java" }, { "code": null, "e": 28545, "s": 28537, "text": "Python3" }, { "code": null, "e": 28548, "s": 28545, "text": "C#" }, { "code": null, "e": 28552, "s": 28548, "text": "PHP" }, { "code": null, "e": 28563, "s": 28552, "text": "Javascript" }, { "code": "// C++ program to calculate Distance// Between Two Points on Earth#include <bits/stdc++.h>using namespace std; // Utility function for// converting degrees to radianslong double toRadians(const long double °ree){ // cmath library in C++ // defines the constant // M_PI as the value of // pi accurate to 1e-30 long double one_deg = (M_PI) / 180; return (one_deg * degree);} long double distance(long double lat1, long double long1, long double lat2, long double long2){ // Convert the latitudes // and longitudes // from degree to radians. lat1 = toRadians(lat1); long1 = toRadians(long1); lat2 = toRadians(lat2); long2 = toRadians(long2); // Haversine Formula long double dlong = long2 - long1; long double dlat = lat2 - lat1; long double ans = pow(sin(dlat / 2), 2) + cos(lat1) * cos(lat2) * pow(sin(dlong / 2), 2); ans = 2 * asin(sqrt(ans)); // Radius of Earth in // Kilometers, R = 6371 // Use R = 3956 for miles long double R = 6371; // Calculate the result ans = ans * R; return ans;} // Driver Codeint main(){ long double lat1 = 53.32055555555556; long double long1 = -1.7297222222222221; long double lat2 = 53.31861111111111; long double long2 = -1.6997222222222223; // call the distance function cout << setprecision(15) << fixed; cout << distance(lat1, long1, lat2, long2) << \" K.M\"; return 0;} // This code is contributed// by Aayush Chaturvedi", "e": 30127, "s": 28563, "text": null }, { "code": "// Java program to calculate Distance Between// Two Points on Earthimport java.util.*;import java.lang.*; class GFG { public static double distance(double lat1, double lat2, double lon1, double lon2) { // The math module contains a function // named toRadians which converts from // degrees to radians. lon1 = Math.toRadians(lon1); lon2 = Math.toRadians(lon2); lat1 = Math.toRadians(lat1); lat2 = Math.toRadians(lat2); // Haversine formula double dlon = lon2 - lon1; double dlat = lat2 - lat1; double a = Math.pow(Math.sin(dlat / 2), 2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(dlon / 2),2); double c = 2 * Math.asin(Math.sqrt(a)); // Radius of earth in kilometers. Use 3956 // for miles double r = 6371; // calculate the result return(c * r); } // driver code public static void main(String[] args) { double lat1 = 53.32055555555556; double lat2 = 53.31861111111111; double lon1 = -1.7297222222222221; double lon2 = -1.6997222222222223; System.out.println(distance(lat1, lat2, lon1, lon2) + \" K.M\"); }} // This code is contributed by Prasad Kshirsagar", "e": 31498, "s": 30127, "text": null }, { "code": "# Python 3 program to calculate Distance Between Two Points on Earthfrom math import radians, cos, sin, asin, sqrtdef distance(lat1, lat2, lon1, lon2): # The math module contains a function named # radians which converts from degrees to radians. lon1 = radians(lon1) lon2 = radians(lon2) lat1 = radians(lat1) lat2 = radians(lat2) # Haversine formula dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2 c = 2 * asin(sqrt(a)) # Radius of earth in kilometers. Use 3956 for miles r = 6371 # calculate the result return(c * r) # driver codelat1 = 53.32055555555556lat2 = 53.31861111111111lon1 = -1.7297222222222221lon2 = -1.6997222222222223print(distance(lat1, lat2, lon1, lon2), \"K.M\")", "e": 32307, "s": 31498, "text": null }, { "code": "// C# program to calculate// Distance Between Two// Points on Earthusing System; class GFG{ static double toRadians( double angleIn10thofaDegree) { // Angle in 10th // of a degree return (angleIn10thofaDegree * Math.PI) / 180; } static double distance(double lat1, double lat2, double lon1, double lon2) { // The math module contains // a function named toRadians // which converts from degrees // to radians. lon1 = toRadians(lon1); lon2 = toRadians(lon2); lat1 = toRadians(lat1); lat2 = toRadians(lat2); // Haversine formula double dlon = lon2 - lon1; double dlat = lat2 - lat1; double a = Math.Pow(Math.Sin(dlat / 2), 2) + Math.Cos(lat1) * Math.Cos(lat2) * Math.Pow(Math.Sin(dlon / 2),2); double c = 2 * Math.Asin(Math.Sqrt(a)); // Radius of earth in // kilometers. Use 3956 // for miles double r = 6371; // calculate the result return (c * r); } // Driver code static void Main() { double lat1 = 53.32055555555556; double lat2 = 53.31861111111111; double lon1 = -1.7297222222222221; double lon2 = -1.6997222222222223; Console.WriteLine(distance(lat1, lat2, lon1, lon2) + \" K.M\"); }} // This code is contributed by// Manish Shaw(manishshaw1)", "e": 33861, "s": 32307, "text": null }, { "code": "<?php function twopoints_on_earth($latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo) { $long1 = deg2rad($longitudeFrom); $long2 = deg2rad($longitudeTo); $lat1 = deg2rad($latitudeFrom); $lat2 = deg2rad($latitudeTo); //Haversine Formula $dlong = $long2 - $long1; $dlati = $lat2 - $lat1; $val = pow(sin($dlati/2),2)+cos($lat1)*cos($lat2)*pow(sin($dlong/2),2); $res = 2 * asin(sqrt($val)); $radius = 3958.756; return ($res*$radius); } // latitude and longitude of Two Points $latitudeFrom = 19.017656 ; $longitudeFrom = 72.856178; $latitudeTo = 40.7127; $longitudeTo = -74.0059; // Distance between Mumbai and New York print_r(twopoints_on_earth( $latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo).' '.'miles'); // This code is contributed by akash1295// https://auth.geeksforgeeks.org/user/akash1295/articles?>", "e": 34981, "s": 33861, "text": null }, { "code": "<script> // JavaScript program to calculate Distance Between// Two Points on Earth function distance(lat1, lat2, lon1, lon2) { // The math module contains a function // named toRadians which converts from // degrees to radians. lon1 = lon1 * Math.PI / 180; lon2 = lon2 * Math.PI / 180; lat1 = lat1 * Math.PI / 180; lat2 = lat2 * Math.PI / 180; // Haversine formula let dlon = lon2 - lon1; let dlat = lat2 - lat1; let a = Math.pow(Math.sin(dlat / 2), 2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(dlon / 2),2); let c = 2 * Math.asin(Math.sqrt(a)); // Radius of earth in kilometers. Use 3956 // for miles let r = 6371; // calculate the result return(c * r); } // Driver code let lat1 = 53.32055555555556; let lat2 = 53.31861111111111; let lon1 = -1.7297222222222221; let lon2 = -1.6997222222222223; document.write(distance(lat1, lat2, lon1, lon2) + \" K.M\"); </script>", "e": 36153, "s": 34981, "text": null }, { "code": null, "e": 36162, "s": 36153, "text": "Output: " }, { "code": null, "e": 36185, "s": 36162, "text": "2.0043678382716137 K.M" }, { "code": null, "e": 36207, "s": 36185, "text": "Reference: Wikipedia " }, { "code": null, "e": 36225, "s": 36207, "text": "Prasad_Kshirsagar" }, { "code": null, "e": 36242, "s": 36225, "text": "AayushChaturvedi" }, { "code": null, "e": 36254, "s": 36242, "text": "manishshaw1" }, { "code": null, "e": 36267, "s": 36254, "text": "Akanksha_Rai" }, { "code": null, "e": 36277, "s": 36267, "text": "splevel62" }, { "code": null, "e": 36287, "s": 36277, "text": "Geometric" }, { "code": null, "e": 36300, "s": 36287, "text": "Mathematical" }, { "code": null, "e": 36313, "s": 36300, "text": "Mathematical" }, { "code": null, "e": 36323, "s": 36313, "text": "Geometric" }, { "code": null, "e": 36421, "s": 36323, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36479, "s": 36421, "text": "Check whether a given point lies inside a triangle or not" }, { "code": null, "e": 36532, "s": 36479, "text": "Optimum location of point to minimize total distance" }, { "code": null, "e": 36590, "s": 36532, "text": "Given n line segments, find if any two segments intersect" }, { "code": null, "e": 36637, "s": 36590, "text": "Convex Hull using Divide and Conquer Algorithm" }, { "code": null, "e": 36685, "s": 36637, "text": "Polygon Clipping | Sutherland–Hodgman Algorithm" }, { "code": null, "e": 36715, "s": 36685, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 36775, "s": 36715, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 36790, "s": 36775, "text": "C++ Data Types" }, { "code": null, "e": 36833, "s": 36790, "text": "Set in C++ Standard Template Library (STL)" } ]
Reverse the substrings of the given String according to the given Array of indices - GeeksforGeeks
31 May, 2021 Given a string S and an array of indices A[], the task is to reverse the substrings of the given string according to the given Array of indices.Note: A[i] ≤ length(S), for all i.Examples: Input: S = “abcdef”, A[] = {2, 5} Output: baedcf Explanation: Input: S = “abcdefghij”, A[] = {2, 5} Output: baedcjihgf Approach: The idea is to use the concept of reversing the substrings of the given string. Sort the Array of Indices. Extract the substring formed for each index in the given array as follows: For the first index in the array A, the substring formed will be from index 0 to A[0] (exclusive) of the given string, i.e. [0, A[0])For all other index in the array A (except for last), the substring formed will be from index A[i] to A[i+1] (exclusive) of the given string, i.e. [A[i], A[i+1])For the last index in the array A, the substring formed will be from index A[i] to L (inclusive) where L is the length of the string, i.e. [A[i], L] For the first index in the array A, the substring formed will be from index 0 to A[0] (exclusive) of the given string, i.e. [0, A[0]) For all other index in the array A (except for last), the substring formed will be from index A[i] to A[i+1] (exclusive) of the given string, i.e. [A[i], A[i+1]) For the last index in the array A, the substring formed will be from index A[i] to L (inclusive) where L is the length of the string, i.e. [A[i], L] Reverse each substring found in the given string Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ implementation to reverse// the substrings of the given String// according to the given Array of indices #include <bits/stdc++.h>using namespace std; // Function to reverse a stringvoid reverseStr(string& str, int l, int h){ int n = h - l; // Swap character starting // from two corners for (int i = 0; i < n / 2; i++) { swap(str[i + l], str[n - i - 1 + l]); }} // Function to reverse the string// with the given array of indicesvoid reverseString(string& s, int A[], int n){ // Reverse the string from 0 to A[0] reverseStr(s, 0, A[0]); // Reverse the string for A[i] to A[i+1] for (int i = 1; i < n; i++) reverseStr(s, A[i - 1], A[i]); // Reverse String for A[n-1] to length reverseStr(s, A[n - 1], s.length());} // Driver Codeint main(){ string s = "abcdefgh"; int A[] = { 2, 4, 6 }; int n = sizeof(A) / sizeof(A[0]); reverseString(s, A, n); cout << s; return 0;} // Java implementation to reverse// the subStrings of the given String// according to the given Array of indicesclass GFG{ static String s; // Function to reverse a Stringstatic void reverseStr(int l, int h){ int n = h - l; // Swap character starting // from two corners for (int i = 0; i < n / 2; i++) { s = swap(i + l, n - i - 1 + l); }} // Function to reverse the String// with the given array of indicesstatic void reverseString(int A[], int n){ // Reverse the String from 0 to A[0] reverseStr(0, A[0]); // Reverse the String for A[i] to A[i+1] for (int i = 1; i < n; i++) reverseStr(A[i - 1], A[i]); // Reverse String for A[n-1] to length reverseStr(A[n - 1], s.length());}static String swap(int i, int j){ char ch[] = s.toCharArray(); char temp = ch[i]; ch[i] = ch[j]; ch[j] = temp; return String.valueOf(ch);} // Driver Codepublic static void main(String[] args){ s = "abcdefgh"; int A[] = { 2, 4, 6 }; int n = A.length; reverseString(A, n); System.out.print(s);}} // This code is contributed by Rajput-Ji # Python3 implementation to reverse# the substrings of the given String# according to the given Array of indices # Function to reverse a stringdef reverseStr(str, l, h): n = h - l # Swap character starting # from two corners for i in range(n//2): str[i + l], str[n - i - 1 + l] = str[n - i - 1 + l], str[i + l] # Function to reverse the string# with the given array of indicesdef reverseString(s, A, n): # Reverse the from 0 to A[0] reverseStr(s, 0, A[0]) # Reverse the for A[i] to A[i+1] for i in range(1, n): reverseStr(s, A[i - 1], A[i]) # Reverse String for A[n-1] to length reverseStr(s, A[n - 1], len(s)) # Driver Codes = "abcdefgh"s = [i for i in s]A = [2, 4, 6]n = len(A) reverseString(s, A, n)print("".join(s)) # This code is contributed by mohit kumar 29 // C# implementation to reverse// the subStrings of the given String// according to the given Array of indicesusing System; class GFG{ static String s; // Function to reverse a Stringstatic void reverseStr(int l, int h){ int n = h - l; // Swap character starting // from two corners for (int i = 0; i < n / 2; i++) { s = swap(i + l, n - i - 1 + l); }} // Function to reverse the String// with the given array of indicesstatic void reverseString(int []A, int n){ // Reverse the String from 0 to A[0] reverseStr(0, A[0]); // Reverse the String for A[i] to A[i+1] for (int i = 1; i < n; i++) reverseStr(A[i - 1], A[i]); // Reverse String for A[n-1] to length reverseStr(A[n - 1], s.Length);} static String swap(int i, int j){ char []ch = s.ToCharArray(); char temp = ch[i]; ch[i] = ch[j]; ch[j] = temp; return String.Join("",ch);} // Driver Codepublic static void Main(String[] args){ s = "abcdefgh"; int []A = { 2, 4, 6 }; int n = A.Length; reverseString(A, n); Console.Write(s);}} // This code is contributed by 29AjayKumar <script> // JavaScript implementation to reverse// the substrings of the given String// according to the given Array of indices // Function to reverse a stringfunction reverseStr(str, l, h){ var n = h - l; // Swap character starting // from two corners for (var i = 0; i < n / 2; i++) { [str[i + l], str[n - i - 1 + l]] = [str[n - i - 1 + l], str[i + l]]; } return str;} // Function to reverse the string// with the given array of indicesfunction reverseString(s, A, n){ // Reverse the string from 0 to A[0] s = reverseStr(s, 0, A[0]); // Reverse the string for A[i] to A[i+1] for (var i = 1; i < n; i++) s = reverseStr(s, A[i - 1], A[i]); // Reverse String for A[n-1] to length s = reverseStr(s, A[n - 1], s.length); return s;} // Driver Codevar s = "abcdefgh";var A = [2, 4, 6];var n = A.length;s = reverseString(s.split(''), A, n);document.write( s.join('')); </script> badcfehg mohit kumar 29 Rajput-Ji 29AjayKumar famously substring Arrays Pattern Searching Strings Arrays Strings Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element KMP Algorithm for Pattern Searching Rabin-Karp Algorithm for Pattern Searching Check if a string is substring of another Naive algorithm for Pattern Searching Boyer Moore Algorithm for Pattern Searching
[ { "code": null, "e": 26066, "s": 26038, "text": "\n31 May, 2021" }, { "code": null, "e": 26256, "s": 26066, "text": "Given a string S and an array of indices A[], the task is to reverse the substrings of the given string according to the given Array of indices.Note: A[i] ≤ length(S), for all i.Examples: " }, { "code": null, "e": 26320, "s": 26256, "text": "Input: S = “abcdef”, A[] = {2, 5} Output: baedcf Explanation: " }, { "code": null, "e": 26379, "s": 26320, "text": "Input: S = “abcdefghij”, A[] = {2, 5} Output: baedcjihgf " }, { "code": null, "e": 26473, "s": 26381, "text": "Approach: The idea is to use the concept of reversing the substrings of the given string. " }, { "code": null, "e": 26500, "s": 26473, "text": "Sort the Array of Indices." }, { "code": null, "e": 27018, "s": 26500, "text": "Extract the substring formed for each index in the given array as follows: For the first index in the array A, the substring formed will be from index 0 to A[0] (exclusive) of the given string, i.e. [0, A[0])For all other index in the array A (except for last), the substring formed will be from index A[i] to A[i+1] (exclusive) of the given string, i.e. [A[i], A[i+1])For the last index in the array A, the substring formed will be from index A[i] to L (inclusive) where L is the length of the string, i.e. [A[i], L]" }, { "code": null, "e": 27152, "s": 27018, "text": "For the first index in the array A, the substring formed will be from index 0 to A[0] (exclusive) of the given string, i.e. [0, A[0])" }, { "code": null, "e": 27314, "s": 27152, "text": "For all other index in the array A (except for last), the substring formed will be from index A[i] to A[i+1] (exclusive) of the given string, i.e. [A[i], A[i+1])" }, { "code": null, "e": 27463, "s": 27314, "text": "For the last index in the array A, the substring formed will be from index A[i] to L (inclusive) where L is the length of the string, i.e. [A[i], L]" }, { "code": null, "e": 27512, "s": 27463, "text": "Reverse each substring found in the given string" }, { "code": null, "e": 27564, "s": 27512, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 27568, "s": 27564, "text": "C++" }, { "code": null, "e": 27573, "s": 27568, "text": "Java" }, { "code": null, "e": 27581, "s": 27573, "text": "Python3" }, { "code": null, "e": 27584, "s": 27581, "text": "C#" }, { "code": null, "e": 27595, "s": 27584, "text": "Javascript" }, { "code": "// C++ implementation to reverse// the substrings of the given String// according to the given Array of indices #include <bits/stdc++.h>using namespace std; // Function to reverse a stringvoid reverseStr(string& str, int l, int h){ int n = h - l; // Swap character starting // from two corners for (int i = 0; i < n / 2; i++) { swap(str[i + l], str[n - i - 1 + l]); }} // Function to reverse the string// with the given array of indicesvoid reverseString(string& s, int A[], int n){ // Reverse the string from 0 to A[0] reverseStr(s, 0, A[0]); // Reverse the string for A[i] to A[i+1] for (int i = 1; i < n; i++) reverseStr(s, A[i - 1], A[i]); // Reverse String for A[n-1] to length reverseStr(s, A[n - 1], s.length());} // Driver Codeint main(){ string s = \"abcdefgh\"; int A[] = { 2, 4, 6 }; int n = sizeof(A) / sizeof(A[0]); reverseString(s, A, n); cout << s; return 0;}", "e": 28554, "s": 27595, "text": null }, { "code": "// Java implementation to reverse// the subStrings of the given String// according to the given Array of indicesclass GFG{ static String s; // Function to reverse a Stringstatic void reverseStr(int l, int h){ int n = h - l; // Swap character starting // from two corners for (int i = 0; i < n / 2; i++) { s = swap(i + l, n - i - 1 + l); }} // Function to reverse the String// with the given array of indicesstatic void reverseString(int A[], int n){ // Reverse the String from 0 to A[0] reverseStr(0, A[0]); // Reverse the String for A[i] to A[i+1] for (int i = 1; i < n; i++) reverseStr(A[i - 1], A[i]); // Reverse String for A[n-1] to length reverseStr(A[n - 1], s.length());}static String swap(int i, int j){ char ch[] = s.toCharArray(); char temp = ch[i]; ch[i] = ch[j]; ch[j] = temp; return String.valueOf(ch);} // Driver Codepublic static void main(String[] args){ s = \"abcdefgh\"; int A[] = { 2, 4, 6 }; int n = A.length; reverseString(A, n); System.out.print(s);}} // This code is contributed by Rajput-Ji", "e": 29652, "s": 28554, "text": null }, { "code": "# Python3 implementation to reverse# the substrings of the given String# according to the given Array of indices # Function to reverse a stringdef reverseStr(str, l, h): n = h - l # Swap character starting # from two corners for i in range(n//2): str[i + l], str[n - i - 1 + l] = str[n - i - 1 + l], str[i + l] # Function to reverse the string# with the given array of indicesdef reverseString(s, A, n): # Reverse the from 0 to A[0] reverseStr(s, 0, A[0]) # Reverse the for A[i] to A[i+1] for i in range(1, n): reverseStr(s, A[i - 1], A[i]) # Reverse String for A[n-1] to length reverseStr(s, A[n - 1], len(s)) # Driver Codes = \"abcdefgh\"s = [i for i in s]A = [2, 4, 6]n = len(A) reverseString(s, A, n)print(\"\".join(s)) # This code is contributed by mohit kumar 29", "e": 30465, "s": 29652, "text": null }, { "code": "// C# implementation to reverse// the subStrings of the given String// according to the given Array of indicesusing System; class GFG{ static String s; // Function to reverse a Stringstatic void reverseStr(int l, int h){ int n = h - l; // Swap character starting // from two corners for (int i = 0; i < n / 2; i++) { s = swap(i + l, n - i - 1 + l); }} // Function to reverse the String// with the given array of indicesstatic void reverseString(int []A, int n){ // Reverse the String from 0 to A[0] reverseStr(0, A[0]); // Reverse the String for A[i] to A[i+1] for (int i = 1; i < n; i++) reverseStr(A[i - 1], A[i]); // Reverse String for A[n-1] to length reverseStr(A[n - 1], s.Length);} static String swap(int i, int j){ char []ch = s.ToCharArray(); char temp = ch[i]; ch[i] = ch[j]; ch[j] = temp; return String.Join(\"\",ch);} // Driver Codepublic static void Main(String[] args){ s = \"abcdefgh\"; int []A = { 2, 4, 6 }; int n = A.Length; reverseString(A, n); Console.Write(s);}} // This code is contributed by 29AjayKumar", "e": 31573, "s": 30465, "text": null }, { "code": "<script> // JavaScript implementation to reverse// the substrings of the given String// according to the given Array of indices // Function to reverse a stringfunction reverseStr(str, l, h){ var n = h - l; // Swap character starting // from two corners for (var i = 0; i < n / 2; i++) { [str[i + l], str[n - i - 1 + l]] = [str[n - i - 1 + l], str[i + l]]; } return str;} // Function to reverse the string// with the given array of indicesfunction reverseString(s, A, n){ // Reverse the string from 0 to A[0] s = reverseStr(s, 0, A[0]); // Reverse the string for A[i] to A[i+1] for (var i = 1; i < n; i++) s = reverseStr(s, A[i - 1], A[i]); // Reverse String for A[n-1] to length s = reverseStr(s, A[n - 1], s.length); return s;} // Driver Codevar s = \"abcdefgh\";var A = [2, 4, 6];var n = A.length;s = reverseString(s.split(''), A, n);document.write( s.join('')); </script>", "e": 32510, "s": 31573, "text": null }, { "code": null, "e": 32519, "s": 32510, "text": "badcfehg" }, { "code": null, "e": 32536, "s": 32521, "text": "mohit kumar 29" }, { "code": null, "e": 32546, "s": 32536, "text": "Rajput-Ji" }, { "code": null, "e": 32558, "s": 32546, "text": "29AjayKumar" }, { "code": null, "e": 32567, "s": 32558, "text": "famously" }, { "code": null, "e": 32577, "s": 32567, "text": "substring" }, { "code": null, "e": 32584, "s": 32577, "text": "Arrays" }, { "code": null, "e": 32602, "s": 32584, "text": "Pattern Searching" }, { "code": null, "e": 32610, "s": 32602, "text": "Strings" }, { "code": null, "e": 32617, "s": 32610, "text": "Arrays" }, { "code": null, "e": 32625, "s": 32617, "text": "Strings" }, { "code": null, "e": 32643, "s": 32625, "text": "Pattern Searching" }, { "code": null, "e": 32741, "s": 32643, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32768, "s": 32741, "text": "Count pairs with given sum" }, { "code": null, "e": 32799, "s": 32768, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 32824, "s": 32799, "text": "Window Sliding Technique" }, { "code": null, "e": 32862, "s": 32824, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 32883, "s": 32862, "text": "Next Greater Element" }, { "code": null, "e": 32919, "s": 32883, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 32962, "s": 32919, "text": "Rabin-Karp Algorithm for Pattern Searching" }, { "code": null, "e": 33004, "s": 32962, "text": "Check if a string is substring of another" }, { "code": null, "e": 33042, "s": 33004, "text": "Naive algorithm for Pattern Searching" } ]
Recursion - GeeksforGeeks
11 Oct, 2021 What is Recursion? The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called as recursive function. Using recursive algorithm, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc. A Mathematical Interpretation Let us consider a problem that a programmer have to determine the sum of first n natural numbers, there are several ways of doing that but the simplest approach is simply add the numbers starting from 1 to n. So the function simply looks like, approach(1) – Simply adding one by one f(n) = 1 + 2 + 3 +........+ n but there is another mathematical approach of representing this, approach(2) – Recursive adding f(n) = 1 n=1 f(n) = n + f(n-1) n>1 There is a simple difference between the approach (1) and approach(2) and that is in approach(2) the function “ f( ) ” itself is being called inside the function, so this phenomenon is named as recursion and the function containing recursion is called recursive function, at the end this is a great tool in the hand of the programmers to code some problems in a lot easier and efficient way. What is base condition in recursion? In the recursive program, the solution to the base case is provided and the solution of the bigger problem is expressed in terms of smaller problems. int fact(int n) { if (n < = 1) // base case return 1; else return n*fact(n-1); } In the above example, base case for n < = 1 is defined and larger value of number can be solved by converting to smaller one till base case is reached. How a particular problem is solved using recursion? The idea is to represent a problem in terms of one or more smaller problems, and add one or more base conditions that stop the recursion. For example, we compute factorial n if we know factorial of (n-1). The base case for factorial would be n = 0. We return 1 when n = 0. Why Stack Overflow error occurs in recursion? If the base case is not reached or not defined, then the stack overflow problem may arise. Let us take an example to understand this. int fact(int n) { // wrong base case (it may cause // stack overflow). if (n == 100) return 1; else return n*fact(n-1); } If fact(10) is called, it will call fact(9), fact(8), fact(7) and so on but the number will never reach 100. So, the base case is not reached. If the memory is exhausted by these functions on the stack, it will cause a stack overflow error. What is the difference between direct and indirect recursion? A function fun is called direct recursive if it calls the same function fun. A function fun is called indirect recursive if it calls another function say fun_new and fun_new calls fun directly or indirectly. Difference between direct and indirect recursion has been illustrated in Table 1. // An example of direct recursion void directRecFun() { // Some code.... directRecFun(); // Some code... } // An example of indirect recursion void indirectRecFun1() { // Some code... indirectRecFun2(); // Some code... } void indirectRecFun2() { // Some code... indirectRecFun1(); // Some code... } What is difference between tailed and non-tailed recursion? A recursive function is tail recursive when recursive call is the last thing executed by the function. Please refer tail recursion article for details. How memory is allocated to different function calls in recursion? When any function is called from main(), the memory is allocated to it on the stack. A recursive function calls itself, the memory for a called function is allocated on top of memory allocated to calling function and different copy of local variables is created for each function call. When the base case is reached, the function returns its value to the function by whom it is called and memory is de-allocated and the process continues.Let us take the example how recursion works by taking a simple function. CPP Java Python3 C# PHP Javascript // A C++ program to demonstrate working of// recursion#include <bits/stdc++.h>using namespace std; void printFun(int test){ if (test < 1) return; else { cout << test << " "; printFun(test - 1); // statement 2 cout << test << " "; return; }} // Driver Codeint main(){ int test = 3; printFun(test);} // A Java program to demonstrate working of// recursionclass GFG { static void printFun(int test) { if (test < 1) return; else { System.out.printf("%d ", test); printFun(test - 1); // statement 2 System.out.printf("%d ", test); return; } } // Driver Code public static void main(String[] args) { int test = 3; printFun(test); }} // This code is contributed by// Smitha Dinesh Semwal # A Python 3 program to# demonstrate working of# recursion def printFun(test): if (test < 1): return else: print(test, end=" ") printFun(test-1) # statement 2 print(test, end=" ") return # Driver Codetest = 3printFun(test) # This code is contributed by# Smitha Dinesh Semwal // A C# program to demonstrate// working of recursionusing System; class GFG { // function to demonstrate // working of recursion static void printFun(int test) { if (test < 1) return; else { Console.Write(test + " "); // statement 2 printFun(test - 1); Console.Write(test + " "); return; } } // Driver Code public static void Main(String[] args) { int test = 3; printFun(test); }} // This code is contributed by Anshul Aggarwal. <?php// PHP program to demonstrate// working of recursion // function to demonstrate// working of recursionfunction printFun($test){ if ($test < 1) return; else { echo("$test "); // statement 2 printFun($test-1); echo("$test "); return; }} // Driver Code$test = 3;printFun($test); // This code is contributed by// Smitha Dinesh Semwal.?> <script> // JavaScript program to demonstrate working of// recursion function printFun(test) { if (test < 1) return; else { document.write(test + " "); printFun(test - 1); // statement 2 document.write(test + " "); return; } } // Driver code let test = 3; printFun(test); </script> Output : 3 2 1 1 2 3 When printFun(3) is called from main(), memory is allocated to printFun(3) and a local variable test is initialized to 3 and statement 1 to 4 are pushed on the stack as shown in below diagram. It first prints ‘3’. In statement 2, printFun(2) is called and memory is allocated to printFun(2) and a local variable test is initialized to 2 and statement 1 to 4 are pushed in the stack. Similarly, printFun(2) calls printFun(1) and printFun(1) calls printFun(0). printFun(0) goes to if statement and it return to printFun(1). Remaining statements of printFun(1) are executed and it returns to printFun(2) and so on. In the output, value from 3 to 1 are printed and then 1 to 3 are printed. The memory stack has been shown in below diagram. Now, let’s discuss a few practical problems which can be solved by using recursion and understand its basic working. For basic understanding please read the following articles. Basic understanding of Recursion.Problem 1: Write a program and recurrence relation to find the Fibonacci series of n where n>2 . Mathematical Equation: n if n == 0, n == 1; fib(n) = fib(n-1) + fib(n-2) otherwise; Recurrence Relation: T(n) = T(n-1) + T(n-2) + O(1) Recursive program: Input: n = 5 Output: Fibonacci series of 5 numbers is : 0 1 1 2 3 Implementation: C++ C Java Python3 C# Javascript // C++ code to implement Fibonacci series#include <bits/stdc++.h>using namespace std; // Function for fibonacci int fib(int n){ // Stop condition if (n == 0) return 0; // Stop condition if (n == 1 || n == 2) return 1; // Recursion function else return (fib(n - 1) + fib(n - 2));} // Driver Codeint main(){ // Initialize variable n. int n = 5; cout<<"Fibonacci series of 5 numbers is: "; // for loop to print the fibonacci series. for (int i = 0; i < n; i++) { cout<<fib(i)<<" "; } return 0;} // C code to implement Fibonacci series#include <stdio.h> // Function for fibonacciint fib(int n){ // Stop condition if (n == 0) return 0; // Stop condition if (n == 1 || n == 2) return 1; // Recursion function else return (fib(n - 1) + fib(n - 2));} // Driver Codeint main(){ // Initialize variable n. int n = 5; printf("Fibonacci series " "of %d numbers is: ", n); // for loop to print the fibonacci series. for (int i = 0; i < n; i++) { printf("%d ", fib(i)); } return 0;} // Java code to implement Fibonacci seriesimport java.util.*; class GFG{ // Function for fibonaccistatic int fib(int n){ // Stop condition if (n == 0) return 0; // Stop condition if (n == 1 || n == 2) return 1; // Recursion function else return (fib(n - 1) + fib(n - 2));} // Driver Codepublic static void main(String []args){ // Initialize variable n. int n = 5; System.out.print("Fibonacci series of 5 numbers is: "); // for loop to print the fibonacci series. for (int i = 0; i < n; i++) { System.out.print(fib(i)+" "); }}} // This code is contributed by rutvik_56. # Python code to implement Fibonacci series # Function for fibonaccidef fib(n): # Stop condition if (n == 0): return 0 # Stop condition if (n == 1 or n == 2): return 1 # Recursion function else: return (fib(n - 1) + fib(n - 2)) # Driver Code # Initialize variable n.n = 5;print("Fibonacci series of 5 numbers is :",end=" ") # for loop to print the fibonacci series.for i in range(0,n): print(fib(i),end=" ") using System; public class GFG{ // Function for fibonacci static int fib(int n) { // Stop condition if (n == 0) return 0; // Stop condition if (n == 1 || n == 2) return 1; // Recursion function else return (fib(n - 1) + fib(n - 2)); } // Driver Code static public void Main () { // Initialize variable n. int n = 5; Console.Write("Fibonacci series of 5 numbers is: "); // for loop to print the fibonacci series. for (int i = 0; i < n; i++) { Console.Write(fib(i) + " "); } }} // This code is contributed by avanitrachhadiya2155 <script>// JavaScript code to implement Fibonacci series // Function for fibonaccifunction fib(n){ // Stop condition if(n == 0) return 0; // Stop condition if(n == 1 || n == 2) return 1; // Recursion function else return fib(n-1) + fib(n-2);} // Initialize variable n.let n = 5; document.write("Fibonacci series of 5 numbers is: "); // for loop to print the fibonacci series.for(let i = 0; i < n; i++){ document.write(fib(i) + " ");} </script> Fibonacci series of 5 numbers is: 0 1 1 2 3 Here is the recursive tree for input 5 which shows a clear picture of how a big problem can be solved into smaller ones. fib(n) is a Fibonacci function. The time complexity of the given program can depend on the function call. fib(n) -> level CBT (UB) -> 2^n-1 nodes -> 2^n function call -> 2^n*O(1) -> T(n) = O(2^n) For Best Case. T(n) = θ(2^n\2) Working: Problem 2: Write a program and recurrence relation to find the Factorial of n where n>2 . Mathematical Equation: 1 if n == 0 or n == 1; f(n) = n*f(n-1) if n> 1; Recurrence Relation: T(n) = 1 for n = 0 T(n) = 1 + T(n-1) for n > 0 Recursive Program: Input: n = 5 Output: factorial of 5 is: 120Implementation: C++ C Java Python3 C# Javascript // C++ code to implement factorial#include <bits/stdc++.h>using namespace std; // Factorial functionint f(int n){ // Stop condition if (n == 0 || n == 1) return 1; // Recursive condition else return n * f(n - 1);} // Driver codeint main(){ int n = 5; cout<<"factorial of "<<n<<" is: "<<f(n); return 0;} // C code to implement factorial#include <stdio.h> // Factorial functionint f(int n){ // Stop condition if (n == 0 || n == 1) return 1; // Recursive condition else return n * f(n - 1);} // Driver codeint main(){ int n = 5; printf("factorial of %d is: %d", n, f(n)); return 0;} // Java code to implement factorialpublic class GFG{ // Factorial function static int f(int n) { // Stop condition if (n == 0 || n == 1) return 1; // Recursive condition else return n * f(n - 1); } // Driver code public static void main(String[] args) { int n = 5; System.out.println("factorial of " + n + " is: " + f(n)); }} // This code is contributed by divyesh072019. # Python3 code to implement factorial # Factorial functiondef f(n): # Stop condition if (n == 0 or n == 1): return 1; # Recursive condition else: return n * f(n - 1); # Driver codeif __name__=='__main__': n = 5; print("factorial of",n,"is:",f(n)) # This code is contributed by pratham76. // C# code to implement factorialusing System;class GFG { // Factorial function static int f(int n) { // Stop condition if (n == 0 || n == 1) return 1; // Recursive condition else return n * f(n - 1); } // Driver code static void Main() { int n = 5; Console.WriteLine("factorial of " + n + " is: " + f(n)); }} // This code is contributed by divyeshrabadiya07. <script>// JavaScript code to implement factorial // Factorial functionfunction f(n){ // Stop condition if(n == 0 || n == 1) return 1; // Recursive condition else return n*f(n-1);} // Initialize variable n.let n = 5;document.write("factorial of "+ n +" is: " + f(n)); // This code is contributed by probinsah.</script> factorial of 5 is: 120 Working: Diagram of factorial Recursion function for user input 5. What are the disadvantages of recursive programming over iterative programming? Note that both recursive and iterative programs have the same problem-solving powers, i.e., every recursive program can be written iteratively and vice versa is also true. The recursive program has greater space requirements than iterative program as all functions will remain in the stack until the base case is reached. It also has greater time requirements because of function calls and returns overhead. What are the advantages of recursive programming over iterative programming? Recursion provides a clean and simple way to write code. Some problems are inherently recursive like tree traversals, Tower of Hanoi, etc. For such problems, it is preferred to write recursive code. We can write such codes also iteratively with the help of a stack data structure. For example refer Inorder Tree Traversal without Recursion, Iterative Tower of Hanoi. Output based practice problems for beginners: Practice Questions for Recursion | Set 1 Practice Questions for Recursion | Set 2 Practice Questions for Recursion | Set 3 Practice Questions for Recursion | Set 4 Practice Questions for Recursion | Set 5 Practice Questions for Recursion | Set 6 Practice Questions for Recursion | Set 7Quiz on Recursion Coding Practice on Recursion: All Articles on Recursion Recursive Practice Problems with SolutionsThis article is contributed by Sonal Tuteja. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Anshul_Aggarwal Kirti_Mangal Ashish_rana akashkumarsen4 iamartyayadav divyesh072019 divyeshrabadiya07 rutvik_56 avanitrachhadiya2155 pratham76 chinmoy1997pal probinsah sumitgumber28 abhishek0719kadiyan tail-recursion Algorithms Recursion Recursion Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar Understanding Time Complexity with Simple Examples Introduction to Algorithms How to Start Learning DSA? Write a program to print all permutations of a given string Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Program for Tower of Hanoi Backtracking | Introduction Print all possible combinations of r elements in a given array of size n
[ { "code": null, "e": 26025, "s": 25997, "text": "\n11 Oct, 2021" }, { "code": null, "e": 26384, "s": 26025, "text": "What is Recursion? The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called as recursive function. Using recursive algorithm, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc." }, { "code": null, "e": 26414, "s": 26384, "text": "A Mathematical Interpretation" }, { "code": null, "e": 26658, "s": 26414, "text": "Let us consider a problem that a programmer have to determine the sum of first n natural numbers, there are several ways of doing that but the simplest approach is simply add the numbers starting from 1 to n. So the function simply looks like," }, { "code": null, "e": 26697, "s": 26658, "text": "approach(1) – Simply adding one by one" }, { "code": null, "e": 26727, "s": 26697, "text": "f(n) = 1 + 2 + 3 +........+ n" }, { "code": null, "e": 26792, "s": 26727, "text": "but there is another mathematical approach of representing this," }, { "code": null, "e": 26824, "s": 26792, "text": "approach(2) – Recursive adding " }, { "code": null, "e": 26854, "s": 26824, "text": "f(n) = 1 n=1" }, { "code": null, "e": 26879, "s": 26854, "text": "f(n) = n + f(n-1) n>1" }, { "code": null, "e": 27271, "s": 26879, "text": "There is a simple difference between the approach (1) and approach(2) and that is in approach(2) the function “ f( ) ” itself is being called inside the function, so this phenomenon is named as recursion and the function containing recursion is called recursive function, at the end this is a great tool in the hand of the programmers to code some problems in a lot easier and efficient way." }, { "code": null, "e": 27460, "s": 27271, "text": "What is base condition in recursion? In the recursive program, the solution to the base case is provided and the solution of the bigger problem is expressed in terms of smaller problems. " }, { "code": null, "e": 27573, "s": 27460, "text": "int fact(int n)\n{\n if (n < = 1) // base case\n return 1;\n else \n return n*fact(n-1); \n}" }, { "code": null, "e": 27725, "s": 27573, "text": "In the above example, base case for n < = 1 is defined and larger value of number can be solved by converting to smaller one till base case is reached." }, { "code": null, "e": 28051, "s": 27725, "text": "How a particular problem is solved using recursion? The idea is to represent a problem in terms of one or more smaller problems, and add one or more base conditions that stop the recursion. For example, we compute factorial n if we know factorial of (n-1). The base case for factorial would be n = 0. We return 1 when n = 0. " }, { "code": null, "e": 28231, "s": 28051, "text": "Why Stack Overflow error occurs in recursion? If the base case is not reached or not defined, then the stack overflow problem may arise. Let us take an example to understand this." }, { "code": null, "e": 28387, "s": 28231, "text": "int fact(int n)\n{\n // wrong base case (it may cause\n // stack overflow).\n if (n == 100) \n return 1;\n\n else\n return n*fact(n-1);\n}" }, { "code": null, "e": 28629, "s": 28387, "text": "If fact(10) is called, it will call fact(9), fact(8), fact(7) and so on but the number will never reach 100. So, the base case is not reached. If the memory is exhausted by these functions on the stack, it will cause a stack overflow error. " }, { "code": null, "e": 28982, "s": 28629, "text": "What is the difference between direct and indirect recursion? A function fun is called direct recursive if it calls the same function fun. A function fun is called indirect recursive if it calls another function say fun_new and fun_new calls fun directly or indirectly. Difference between direct and indirect recursion has been illustrated in Table 1. " }, { "code": null, "e": 29324, "s": 28982, "text": "// An example of direct recursion\nvoid directRecFun()\n{\n // Some code....\n\n directRecFun();\n\n // Some code...\n}\n\n// An example of indirect recursion\nvoid indirectRecFun1()\n{\n // Some code...\n\n indirectRecFun2();\n\n // Some code...\n}\nvoid indirectRecFun2()\n{\n // Some code...\n\n indirectRecFun1();\n\n // Some code...\n}" }, { "code": null, "e": 29537, "s": 29324, "text": "What is difference between tailed and non-tailed recursion? A recursive function is tail recursive when recursive call is the last thing executed by the function. Please refer tail recursion article for details. " }, { "code": null, "e": 30115, "s": 29537, "text": "How memory is allocated to different function calls in recursion? When any function is called from main(), the memory is allocated to it on the stack. A recursive function calls itself, the memory for a called function is allocated on top of memory allocated to calling function and different copy of local variables is created for each function call. When the base case is reached, the function returns its value to the function by whom it is called and memory is de-allocated and the process continues.Let us take the example how recursion works by taking a simple function. " }, { "code": null, "e": 30119, "s": 30115, "text": "CPP" }, { "code": null, "e": 30124, "s": 30119, "text": "Java" }, { "code": null, "e": 30132, "s": 30124, "text": "Python3" }, { "code": null, "e": 30135, "s": 30132, "text": "C#" }, { "code": null, "e": 30139, "s": 30135, "text": "PHP" }, { "code": null, "e": 30150, "s": 30139, "text": "Javascript" }, { "code": "// A C++ program to demonstrate working of// recursion#include <bits/stdc++.h>using namespace std; void printFun(int test){ if (test < 1) return; else { cout << test << \" \"; printFun(test - 1); // statement 2 cout << test << \" \"; return; }} // Driver Codeint main(){ int test = 3; printFun(test);}", "e": 30498, "s": 30150, "text": null }, { "code": "// A Java program to demonstrate working of// recursionclass GFG { static void printFun(int test) { if (test < 1) return; else { System.out.printf(\"%d \", test); printFun(test - 1); // statement 2 System.out.printf(\"%d \", test); return; } } // Driver Code public static void main(String[] args) { int test = 3; printFun(test); }} // This code is contributed by// Smitha Dinesh Semwal", "e": 30993, "s": 30498, "text": null }, { "code": "# A Python 3 program to# demonstrate working of# recursion def printFun(test): if (test < 1): return else: print(test, end=\" \") printFun(test-1) # statement 2 print(test, end=\" \") return # Driver Codetest = 3printFun(test) # This code is contributed by# Smitha Dinesh Semwal", "e": 31313, "s": 30993, "text": null }, { "code": "// A C# program to demonstrate// working of recursionusing System; class GFG { // function to demonstrate // working of recursion static void printFun(int test) { if (test < 1) return; else { Console.Write(test + \" \"); // statement 2 printFun(test - 1); Console.Write(test + \" \"); return; } } // Driver Code public static void Main(String[] args) { int test = 3; printFun(test); }} // This code is contributed by Anshul Aggarwal.", "e": 31875, "s": 31313, "text": null }, { "code": "<?php// PHP program to demonstrate// working of recursion // function to demonstrate// working of recursionfunction printFun($test){ if ($test < 1) return; else { echo(\"$test \"); // statement 2 printFun($test-1); echo(\"$test \"); return; }} // Driver Code$test = 3;printFun($test); // This code is contributed by// Smitha Dinesh Semwal.?>", "e": 32285, "s": 31875, "text": null }, { "code": "<script> // JavaScript program to demonstrate working of// recursion function printFun(test) { if (test < 1) return; else { document.write(test + \" \"); printFun(test - 1); // statement 2 document.write(test + \" \"); return; } } // Driver code let test = 3; printFun(test); </script>", "e": 32655, "s": 32285, "text": null }, { "code": null, "e": 32665, "s": 32655, "text": "Output : " }, { "code": null, "e": 32677, "s": 32665, "text": "3 2 1 1 2 3" }, { "code": null, "e": 33413, "s": 32677, "text": "When printFun(3) is called from main(), memory is allocated to printFun(3) and a local variable test is initialized to 3 and statement 1 to 4 are pushed on the stack as shown in below diagram. It first prints ‘3’. In statement 2, printFun(2) is called and memory is allocated to printFun(2) and a local variable test is initialized to 2 and statement 1 to 4 are pushed in the stack. Similarly, printFun(2) calls printFun(1) and printFun(1) calls printFun(0). printFun(0) goes to if statement and it return to printFun(1). Remaining statements of printFun(1) are executed and it returns to printFun(2) and so on. In the output, value from 3 to 1 are printed and then 1 to 3 are printed. The memory stack has been shown in below diagram." }, { "code": null, "e": 33745, "s": 33413, "text": "Now, let’s discuss a few practical problems which can be solved by using recursion and understand its basic working. For basic understanding please read the following articles. Basic understanding of Recursion.Problem 1: Write a program and recurrence relation to find the Fibonacci series of n where n>2 . Mathematical Equation: " }, { "code": null, "e": 33812, "s": 33745, "text": "n if n == 0, n == 1; \nfib(n) = fib(n-1) + fib(n-2) otherwise;" }, { "code": null, "e": 33834, "s": 33812, "text": "Recurrence Relation: " }, { "code": null, "e": 33864, "s": 33834, "text": "T(n) = T(n-1) + T(n-2) + O(1)" }, { "code": null, "e": 33884, "s": 33864, "text": "Recursive program: " }, { "code": null, "e": 33951, "s": 33884, "text": "Input: n = 5 \nOutput:\nFibonacci series of 5 numbers is : 0 1 1 2 3" }, { "code": null, "e": 33968, "s": 33951, "text": "Implementation: " }, { "code": null, "e": 33972, "s": 33968, "text": "C++" }, { "code": null, "e": 33974, "s": 33972, "text": "C" }, { "code": null, "e": 33979, "s": 33974, "text": "Java" }, { "code": null, "e": 33987, "s": 33979, "text": "Python3" }, { "code": null, "e": 33990, "s": 33987, "text": "C#" }, { "code": null, "e": 34001, "s": 33990, "text": "Javascript" }, { "code": "// C++ code to implement Fibonacci series#include <bits/stdc++.h>using namespace std; // Function for fibonacci int fib(int n){ // Stop condition if (n == 0) return 0; // Stop condition if (n == 1 || n == 2) return 1; // Recursion function else return (fib(n - 1) + fib(n - 2));} // Driver Codeint main(){ // Initialize variable n. int n = 5; cout<<\"Fibonacci series of 5 numbers is: \"; // for loop to print the fibonacci series. for (int i = 0; i < n; i++) { cout<<fib(i)<<\" \"; } return 0;}", "e": 34566, "s": 34001, "text": null }, { "code": "// C code to implement Fibonacci series#include <stdio.h> // Function for fibonacciint fib(int n){ // Stop condition if (n == 0) return 0; // Stop condition if (n == 1 || n == 2) return 1; // Recursion function else return (fib(n - 1) + fib(n - 2));} // Driver Codeint main(){ // Initialize variable n. int n = 5; printf(\"Fibonacci series \" \"of %d numbers is: \", n); // for loop to print the fibonacci series. for (int i = 0; i < n; i++) { printf(\"%d \", fib(i)); } return 0;}", "e": 35132, "s": 34566, "text": null }, { "code": "// Java code to implement Fibonacci seriesimport java.util.*; class GFG{ // Function for fibonaccistatic int fib(int n){ // Stop condition if (n == 0) return 0; // Stop condition if (n == 1 || n == 2) return 1; // Recursion function else return (fib(n - 1) + fib(n - 2));} // Driver Codepublic static void main(String []args){ // Initialize variable n. int n = 5; System.out.print(\"Fibonacci series of 5 numbers is: \"); // for loop to print the fibonacci series. for (int i = 0; i < n; i++) { System.out.print(fib(i)+\" \"); }}} // This code is contributed by rutvik_56.", "e": 35774, "s": 35132, "text": null }, { "code": "# Python code to implement Fibonacci series # Function for fibonaccidef fib(n): # Stop condition if (n == 0): return 0 # Stop condition if (n == 1 or n == 2): return 1 # Recursion function else: return (fib(n - 1) + fib(n - 2)) # Driver Code # Initialize variable n.n = 5;print(\"Fibonacci series of 5 numbers is :\",end=\" \") # for loop to print the fibonacci series.for i in range(0,n): print(fib(i),end=\" \")", "e": 36228, "s": 35774, "text": null }, { "code": "using System; public class GFG{ // Function for fibonacci static int fib(int n) { // Stop condition if (n == 0) return 0; // Stop condition if (n == 1 || n == 2) return 1; // Recursion function else return (fib(n - 1) + fib(n - 2)); } // Driver Code static public void Main () { // Initialize variable n. int n = 5; Console.Write(\"Fibonacci series of 5 numbers is: \"); // for loop to print the fibonacci series. for (int i = 0; i < n; i++) { Console.Write(fib(i) + \" \"); } }} // This code is contributed by avanitrachhadiya2155", "e": 36830, "s": 36228, "text": null }, { "code": "<script>// JavaScript code to implement Fibonacci series // Function for fibonaccifunction fib(n){ // Stop condition if(n == 0) return 0; // Stop condition if(n == 1 || n == 2) return 1; // Recursion function else return fib(n-1) + fib(n-2);} // Initialize variable n.let n = 5; document.write(\"Fibonacci series of 5 numbers is: \"); // for loop to print the fibonacci series.for(let i = 0; i < n; i++){ document.write(fib(i) + \" \");} </script>", "e": 37307, "s": 36830, "text": null }, { "code": null, "e": 37352, "s": 37307, "text": "Fibonacci series of 5 numbers is: 0 1 1 2 3 " }, { "code": null, "e": 37580, "s": 37352, "text": "Here is the recursive tree for input 5 which shows a clear picture of how a big problem can be solved into smaller ones. fib(n) is a Fibonacci function. The time complexity of the given program can depend on the function call. " }, { "code": null, "e": 37672, "s": 37580, "text": "fib(n) -> level CBT (UB) -> 2^n-1 nodes -> 2^n function call -> 2^n*O(1) -> T(n) = O(2^n) " }, { "code": null, "e": 37688, "s": 37672, "text": "For Best Case. " }, { "code": null, "e": 37706, "s": 37688, "text": "T(n) = θ(2^n\\2)" }, { "code": null, "e": 37716, "s": 37706, "text": "Working: " }, { "code": null, "e": 37830, "s": 37716, "text": "Problem 2: Write a program and recurrence relation to find the Factorial of n where n>2 . Mathematical Equation: " }, { "code": null, "e": 37884, "s": 37830, "text": "1 if n == 0 or n == 1; \nf(n) = n*f(n-1) if n> 1;" }, { "code": null, "e": 37906, "s": 37884, "text": "Recurrence Relation: " }, { "code": null, "e": 37953, "s": 37906, "text": "T(n) = 1 for n = 0\nT(n) = 1 + T(n-1) for n > 0" }, { "code": null, "e": 38032, "s": 37953, "text": "Recursive Program: Input: n = 5 Output: factorial of 5 is: 120Implementation: " }, { "code": null, "e": 38036, "s": 38032, "text": "C++" }, { "code": null, "e": 38038, "s": 38036, "text": "C" }, { "code": null, "e": 38043, "s": 38038, "text": "Java" }, { "code": null, "e": 38051, "s": 38043, "text": "Python3" }, { "code": null, "e": 38054, "s": 38051, "text": "C#" }, { "code": null, "e": 38065, "s": 38054, "text": "Javascript" }, { "code": "// C++ code to implement factorial#include <bits/stdc++.h>using namespace std; // Factorial functionint f(int n){ // Stop condition if (n == 0 || n == 1) return 1; // Recursive condition else return n * f(n - 1);} // Driver codeint main(){ int n = 5; cout<<\"factorial of \"<<n<<\" is: \"<<f(n); return 0;}", "e": 38404, "s": 38065, "text": null }, { "code": "// C code to implement factorial#include <stdio.h> // Factorial functionint f(int n){ // Stop condition if (n == 0 || n == 1) return 1; // Recursive condition else return n * f(n - 1);} // Driver codeint main(){ int n = 5; printf(\"factorial of %d is: %d\", n, f(n)); return 0;}", "e": 38717, "s": 38404, "text": null }, { "code": "// Java code to implement factorialpublic class GFG{ // Factorial function static int f(int n) { // Stop condition if (n == 0 || n == 1) return 1; // Recursive condition else return n * f(n - 1); } // Driver code public static void main(String[] args) { int n = 5; System.out.println(\"factorial of \" + n + \" is: \" + f(n)); }} // This code is contributed by divyesh072019.", "e": 39129, "s": 38717, "text": null }, { "code": "# Python3 code to implement factorial # Factorial functiondef f(n): # Stop condition if (n == 0 or n == 1): return 1; # Recursive condition else: return n * f(n - 1); # Driver codeif __name__=='__main__': n = 5; print(\"factorial of\",n,\"is:\",f(n)) # This code is contributed by pratham76.", "e": 39461, "s": 39129, "text": null }, { "code": "// C# code to implement factorialusing System;class GFG { // Factorial function static int f(int n) { // Stop condition if (n == 0 || n == 1) return 1; // Recursive condition else return n * f(n - 1); } // Driver code static void Main() { int n = 5; Console.WriteLine(\"factorial of \" + n + \" is: \" + f(n)); }} // This code is contributed by divyeshrabadiya07.", "e": 39860, "s": 39461, "text": null }, { "code": "<script>// JavaScript code to implement factorial // Factorial functionfunction f(n){ // Stop condition if(n == 0 || n == 1) return 1; // Recursive condition else return n*f(n-1);} // Initialize variable n.let n = 5;document.write(\"factorial of \"+ n +\" is: \" + f(n)); // This code is contributed by probinsah.</script>", "e": 40202, "s": 39860, "text": null }, { "code": null, "e": 40225, "s": 40202, "text": "factorial of 5 is: 120" }, { "code": null, "e": 40236, "s": 40225, "text": "Working: " }, { "code": null, "e": 40294, "s": 40236, "text": "Diagram of factorial Recursion function for user input 5." }, { "code": null, "e": 40782, "s": 40294, "text": "What are the disadvantages of recursive programming over iterative programming? Note that both recursive and iterative programs have the same problem-solving powers, i.e., every recursive program can be written iteratively and vice versa is also true. The recursive program has greater space requirements than iterative program as all functions will remain in the stack until the base case is reached. It also has greater time requirements because of function calls and returns overhead." }, { "code": null, "e": 41226, "s": 40782, "text": "What are the advantages of recursive programming over iterative programming? Recursion provides a clean and simple way to write code. Some problems are inherently recursive like tree traversals, Tower of Hanoi, etc. For such problems, it is preferred to write recursive code. We can write such codes also iteratively with the help of a stack data structure. For example refer Inorder Tree Traversal without Recursion, Iterative Tower of Hanoi." }, { "code": null, "e": 42093, "s": 41226, "text": "Output based practice problems for beginners: Practice Questions for Recursion | Set 1 Practice Questions for Recursion | Set 2 Practice Questions for Recursion | Set 3 Practice Questions for Recursion | Set 4 Practice Questions for Recursion | Set 5 Practice Questions for Recursion | Set 6 Practice Questions for Recursion | Set 7Quiz on Recursion Coding Practice on Recursion: All Articles on Recursion Recursive Practice Problems with SolutionsThis article is contributed by Sonal Tuteja. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 42109, "s": 42093, "text": "Anshul_Aggarwal" }, { "code": null, "e": 42122, "s": 42109, "text": "Kirti_Mangal" }, { "code": null, "e": 42134, "s": 42122, "text": "Ashish_rana" }, { "code": null, "e": 42149, "s": 42134, "text": "akashkumarsen4" }, { "code": null, "e": 42163, "s": 42149, "text": "iamartyayadav" }, { "code": null, "e": 42177, "s": 42163, "text": "divyesh072019" }, { "code": null, "e": 42195, "s": 42177, "text": "divyeshrabadiya07" }, { "code": null, "e": 42205, "s": 42195, "text": "rutvik_56" }, { "code": null, "e": 42226, "s": 42205, "text": "avanitrachhadiya2155" }, { "code": null, "e": 42236, "s": 42226, "text": "pratham76" }, { "code": null, "e": 42251, "s": 42236, "text": "chinmoy1997pal" }, { "code": null, "e": 42261, "s": 42251, "text": "probinsah" }, { "code": null, "e": 42275, "s": 42261, "text": "sumitgumber28" }, { "code": null, "e": 42295, "s": 42275, "text": "abhishek0719kadiyan" }, { "code": null, "e": 42310, "s": 42295, "text": "tail-recursion" }, { "code": null, "e": 42321, "s": 42310, "text": "Algorithms" }, { "code": null, "e": 42331, "s": 42321, "text": "Recursion" }, { "code": null, "e": 42341, "s": 42331, "text": "Recursion" }, { "code": null, "e": 42352, "s": 42341, "text": "Algorithms" }, { "code": null, "e": 42450, "s": 42352, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42499, "s": 42450, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 42524, "s": 42499, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 42575, "s": 42524, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 42602, "s": 42575, "text": "Introduction to Algorithms" }, { "code": null, "e": 42629, "s": 42602, "text": "How to Start Learning DSA?" }, { "code": null, "e": 42689, "s": 42629, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 42774, "s": 42689, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 42801, "s": 42774, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 42829, "s": 42801, "text": "Backtracking | Introduction" } ]
Python | Pandas Dataframe.iat[ ] - GeeksforGeeks
16 Jul, 2021 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas iat[] method is used to return data in a dataframe at the passed location. The passed location is in the format [position in the row, position in the column]. This method works similarly to Pandas iloc[] but iat[] is used to return only a single value and hence works faster than it. Syntax: Dataframe.iat[row, column]Parameters: position: Position of element in column label: Position of element in rowReturn type: Single element at passed position To download the data set used in the following example, click here. In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below. Example #1: In this example, A dataframe is created by passing URL of csv to Pandas .read_csv() method. After that 3 is passed as column position and 7 as the position in row and value at that position is returned using .iat[ ] method. Python3 # importing pandas module import pandas as pd # reading csv file from url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # creating column and row variablescolumn = 7row = 3 # calling .iat[] methodoutput = data.iat[row, column] # displayprint(output) # df displaydata.head() Output: As shown in the output image, the output can be compared and it can be seen that the Value of the 3rd element in the 7th column was returned. Note: Unlike, .iloc[ ], This method only returns single value. Hence, dataframe.at[3:6, 4:2] will return an error Since this method only works for single values, it is faster than .iloc[] method debjyotidasadhikary surindertarika1234 Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe *args and **kwargs in Python Reading and Writing to text files in Python Convert integer to string in Python Create a Pandas DataFrame from Lists Check if element exists in list in Python sum() function in Python
[ { "code": null, "e": 26083, "s": 26055, "text": "\n16 Jul, 2021" }, { "code": null, "e": 26297, "s": 26083, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 26588, "s": 26297, "text": "Pandas iat[] method is used to return data in a dataframe at the passed location. The passed location is in the format [position in the row, position in the column]. This method works similarly to Pandas iloc[] but iat[] is used to return only a single value and hence works faster than it." }, { "code": null, "e": 26756, "s": 26588, "text": "Syntax: Dataframe.iat[row, column]Parameters: position: Position of element in column label: Position of element in rowReturn type: Single element at passed position " }, { "code": null, "e": 26824, "s": 26756, "text": "To download the data set used in the following example, click here." }, { "code": null, "e": 26971, "s": 26824, "text": "In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below." }, { "code": null, "e": 27208, "s": 26971, "text": "Example #1: In this example, A dataframe is created by passing URL of csv to Pandas .read_csv() method. After that 3 is passed as column position and 7 as the position in row and value at that position is returned using .iat[ ] method. " }, { "code": null, "e": 27216, "s": 27208, "text": "Python3" }, { "code": "# importing pandas module import pandas as pd # reading csv file from url data = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # creating column and row variablescolumn = 7row = 3 # calling .iat[] methodoutput = data.iat[row, column] # displayprint(output) # df displaydata.head()", "e": 27529, "s": 27216, "text": null }, { "code": null, "e": 27680, "s": 27529, "text": "Output: As shown in the output image, the output can be compared and it can be seen that the Value of the 3rd element in the 7th column was returned. " }, { "code": null, "e": 27688, "s": 27680, "text": "Note: " }, { "code": null, "e": 27796, "s": 27688, "text": "Unlike, .iloc[ ], This method only returns single value. Hence, dataframe.at[3:6, 4:2] will return an error" }, { "code": null, "e": 27877, "s": 27796, "text": "Since this method only works for single values, it is faster than .iloc[] method" }, { "code": null, "e": 27899, "s": 27879, "text": "debjyotidasadhikary" }, { "code": null, "e": 27918, "s": 27899, "text": "surindertarika1234" }, { "code": null, "e": 27942, "s": 27918, "text": "Python pandas-dataFrame" }, { "code": null, "e": 27974, "s": 27942, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 27988, "s": 27974, "text": "Python-pandas" }, { "code": null, "e": 27995, "s": 27988, "text": "Python" }, { "code": null, "e": 28093, "s": 27995, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28111, "s": 28093, "text": "Python Dictionary" }, { "code": null, "e": 28143, "s": 28111, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28165, "s": 28143, "text": "Enumerate() in Python" }, { "code": null, "e": 28207, "s": 28165, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28236, "s": 28207, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28280, "s": 28236, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28316, "s": 28280, "text": "Convert integer to string in Python" }, { "code": null, "e": 28353, "s": 28316, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28395, "s": 28353, "text": "Check if element exists in list in Python" } ]
Introduction to Swift Programming - GeeksforGeeks
07 Aug, 2018 Swift is a general-purpose, multi-paradigm, object-oriented, functional, imperative and block structured language. It is the result of the latest research on programming languages and is built using a modern approach to safety, software design patterns by Apple Inc.. It is the brand new programming language for iOS application, macOS application, watchOS application, tvOS application. Soon it became one of top 5 programming language and gained popularity among Apple developer community over the few years of time replacing the old school Objective C. Evolution of Swift Programming Language:Swift language was developed by ‘Chris Lattner‘ with an aim to resolve difficulties existed in Objective C. It was introduced at Apple’s 2014 Worldwide Developers Conference (WWDC) with version Swift 1.0. Soon, It underwent an upgrade to version 1.2 during 2014. Swift 2.0 was introduced at WWDC 2015. Initially, version 2.2 was made open-source software under the Apache License 2.0 on December 3, 2015, for Apple and Linux platforms. It is primarily designed to work with Apple’s Cocoa and Cocoa Touch frameworks and the large body of existing Objective-C code written for Apple products. Swift language has gone through major changes since its release from version names 1.0, 2.0, 3.0 and 4.0 and later. The current released version is Swift 4.2 with a beta version of Swift 4.3 and Xcode 10. Changes include the following areas: Syntax change Library and methods names change New features integration The newly added library like Core ML and AR kit and Vision frameworks Major and promising changes in the latest version i.e. Swift 4 and later includes the following: Faster, easier to use Strings that retain Unicode correctness and add support for creating, using and managing substrings. Smart key paths for type-safe, efficient, extensible key-value coding for Swift types. Enhancements to creating and manipulating Dictionary and Set types. Extends support of archival and serialization to struct and enum types and enables type-safety for serializing to external formats such as JSON and plist. Enforced exclusive access to memory. // Basic Swift Program import UIKit var str1 = "Hello geeks!" var str2 = "How are you?" print (str1) print (str2) Output: Hello geeks! How are you? Run: Code can be tested on Online IDE for Swift Note: Import statement is used to import any objective-C framework or library directly into Swift program. var keyword is used for variable and let keyword is used for constant. There is no need of ; for termination, in case programmer uses it compiler won’t show error. The Protocol-Oriented Programming Paradigm in Swift: Protocol-Oriented Programming is a new programming paradigm used from the release time of Swift 2.0. In this approach, design protocols are similar to classes but this serves better as compared to object-oriented programming. Since the concepts like structs and enums don’t work properly as a struct cannot inherit from another struct, neither can an enum inherit from another enum. So inheritance which is one of the fundamental object-oriented concepts cannot be applied to value types. On the other hand, value types can inherit from protocols. The concepts used in protocol-oriented paradigm are:Protocol extensionsProtocol inheritanceProtocol compositions Protocol extensionsProtocol inheritanceProtocol compositions Protocol extensions Protocol inheritance Protocol compositions Optional type variable in Swift: There is a rule in Swift that each declared variable must have a value associated with them while running the application. In case the variable’s value is found null or nil, the app crashes. So Apple’s engineer came up with a solution in a very smooth and intelligent manner with a concept what they called as optional. While declaring any variable. For Example:var number: Int?‘?‘ is a kind of notation and the variable associated with optional it is called an optional type variable. A variable declared with an option is basically a safe variable that value if found nil then, Xcode and app just ignore that variable and doesn’t crash. The concept of safe unwarping for optional is used to achieve this functionality. var number: Int? ‘?‘ is a kind of notation and the variable associated with optional it is called an optional type variable. A variable declared with an option is basically a safe variable that value if found nil then, Xcode and app just ignore that variable and doesn’t crash. The concept of safe unwarping for optional is used to achieve this functionality. Encodables, Decodables and Delegate methods: In most apps or rather say each and every day to day applications use data and, the data security is a major concern. The apps involve network connection, saving data to disk, or submitting data to APIs and services. These tasks data needed to be encoded and decoded to and from an intermediate format while the data is being transferred. Apple has made their own libraries to cope up with these issues i.e Encodable and Decodable. These are Swift standard library defined for a standardized approach to data encoding and decoding. Delegates methods are the part of Protocol-oriented approach and abstract class implementation in Swift. Advantages: Swift is open sourced and easy to learn. Swift is fast, safe and expressive. Swift is approachable and familiar (C and C++ code can be added by Swift programmers into Swift applications.) Swift is the future of Apple development. Swift is enterprise ready. Disadvantages: The language is still quite young and talent pool is limited. Swift is considered a “moving target” as it is a new language and number of swift programmers are few. Poor interoperability with third-party tools and IDEs Lack of support for earlier iOS versions. Programming Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Decorators with parameters in Python Top 10 Programming Languages to Learn in 2022 Shallow Copy and Deep Copy in C++ Kotlin Array C# | Data Types Difference between Shallow and Deep copy of a class Advantages and Disadvantages of OOP Java Swing | JComboBox with examples Top 10 Fastest Programming Languages Prolog | An Introduction
[ { "code": null, "e": 26441, "s": 26413, "text": "\n07 Aug, 2018" }, { "code": null, "e": 26997, "s": 26441, "text": "Swift is a general-purpose, multi-paradigm, object-oriented, functional, imperative and block structured language. It is the result of the latest research on programming languages and is built using a modern approach to safety, software design patterns by Apple Inc.. It is the brand new programming language for iOS application, macOS application, watchOS application, tvOS application. Soon it became one of top 5 programming language and gained popularity among Apple developer community over the few years of time replacing the old school Objective C." }, { "code": null, "e": 27833, "s": 26997, "text": "Evolution of Swift Programming Language:Swift language was developed by ‘Chris Lattner‘ with an aim to resolve difficulties existed in Objective C. It was introduced at Apple’s 2014 Worldwide Developers Conference (WWDC) with version Swift 1.0. Soon, It underwent an upgrade to version 1.2 during 2014. Swift 2.0 was introduced at WWDC 2015. Initially, version 2.2 was made open-source software under the Apache License 2.0 on December 3, 2015, for Apple and Linux platforms. It is primarily designed to work with Apple’s Cocoa and Cocoa Touch frameworks and the large body of existing Objective-C code written for Apple products. Swift language has gone through major changes since its release from version names 1.0, 2.0, 3.0 and 4.0 and later. The current released version is Swift 4.2 with a beta version of Swift 4.3 and Xcode 10." }, { "code": null, "e": 27870, "s": 27833, "text": "Changes include the following areas:" }, { "code": null, "e": 27884, "s": 27870, "text": "Syntax change" }, { "code": null, "e": 27917, "s": 27884, "text": "Library and methods names change" }, { "code": null, "e": 27942, "s": 27917, "text": "New features integration" }, { "code": null, "e": 28012, "s": 27942, "text": "The newly added library like Core ML and AR kit and Vision frameworks" }, { "code": null, "e": 28109, "s": 28012, "text": "Major and promising changes in the latest version i.e. Swift 4 and later includes the following:" }, { "code": null, "e": 28232, "s": 28109, "text": "Faster, easier to use Strings that retain Unicode correctness and add support for creating, using and managing substrings." }, { "code": null, "e": 28319, "s": 28232, "text": "Smart key paths for type-safe, efficient, extensible key-value coding for Swift types." }, { "code": null, "e": 28387, "s": 28319, "text": "Enhancements to creating and manipulating Dictionary and Set types." }, { "code": null, "e": 28542, "s": 28387, "text": "Extends support of archival and serialization to struct and enum types and enables type-safety for serializing to external formats such as JSON and plist." }, { "code": null, "e": 28579, "s": 28542, "text": "Enforced exclusive access to memory." }, { "code": null, "e": 28695, "s": 28579, "text": "// Basic Swift Program\nimport UIKit\n\nvar str1 = \"Hello geeks!\"\nvar str2 = \"How are you?\"\nprint (str1)\nprint (str2)\n" }, { "code": null, "e": 28703, "s": 28695, "text": "Output:" }, { "code": null, "e": 28730, "s": 28703, "text": "Hello geeks!\nHow are you?\n" }, { "code": null, "e": 28778, "s": 28730, "text": "Run: Code can be tested on Online IDE for Swift" }, { "code": null, "e": 29049, "s": 28778, "text": "Note: Import statement is used to import any objective-C framework or library directly into Swift program. var keyword is used for variable and let keyword is used for constant. There is no need of ; for termination, in case programmer uses it compiler won’t show error." }, { "code": null, "e": 29763, "s": 29049, "text": "The Protocol-Oriented Programming Paradigm in Swift: Protocol-Oriented Programming is a new programming paradigm used from the release time of Swift 2.0. In this approach, design protocols are similar to classes but this serves better as compared to object-oriented programming. Since the concepts like structs and enums don’t work properly as a struct cannot inherit from another struct, neither can an enum inherit from another enum. So inheritance which is one of the fundamental object-oriented concepts cannot be applied to value types. On the other hand, value types can inherit from protocols. The concepts used in protocol-oriented paradigm are:Protocol extensionsProtocol inheritanceProtocol compositions" }, { "code": null, "e": 29824, "s": 29763, "text": "Protocol extensionsProtocol inheritanceProtocol compositions" }, { "code": null, "e": 29844, "s": 29824, "text": "Protocol extensions" }, { "code": null, "e": 29865, "s": 29844, "text": "Protocol inheritance" }, { "code": null, "e": 29887, "s": 29865, "text": "Protocol compositions" }, { "code": null, "e": 30641, "s": 29887, "text": "Optional type variable in Swift: There is a rule in Swift that each declared variable must have a value associated with them while running the application. In case the variable’s value is found null or nil, the app crashes. So Apple’s engineer came up with a solution in a very smooth and intelligent manner with a concept what they called as optional. While declaring any variable. For Example:var number: Int?‘?‘ is a kind of notation and the variable associated with optional it is called an optional type variable. A variable declared with an option is basically a safe variable that value if found nil then, Xcode and app just ignore that variable and doesn’t crash. The concept of safe unwarping for optional is used to achieve this functionality." }, { "code": null, "e": 30658, "s": 30641, "text": "var number: Int?" }, { "code": null, "e": 31001, "s": 30658, "text": "‘?‘ is a kind of notation and the variable associated with optional it is called an optional type variable. A variable declared with an option is basically a safe variable that value if found nil then, Xcode and app just ignore that variable and doesn’t crash. The concept of safe unwarping for optional is used to achieve this functionality." }, { "code": null, "e": 31683, "s": 31001, "text": "Encodables, Decodables and Delegate methods: In most apps or rather say each and every day to day applications use data and, the data security is a major concern. The apps involve network connection, saving data to disk, or submitting data to APIs and services. These tasks data needed to be encoded and decoded to and from an intermediate format while the data is being transferred. Apple has made their own libraries to cope up with these issues i.e Encodable and Decodable. These are Swift standard library defined for a standardized approach to data encoding and decoding. Delegates methods are the part of Protocol-oriented approach and abstract class implementation in Swift." }, { "code": null, "e": 31695, "s": 31683, "text": "Advantages:" }, { "code": null, "e": 31736, "s": 31695, "text": "Swift is open sourced and easy to learn." }, { "code": null, "e": 31772, "s": 31736, "text": "Swift is fast, safe and expressive." }, { "code": null, "e": 31883, "s": 31772, "text": "Swift is approachable and familiar (C and C++ code can be added by Swift programmers into Swift applications.)" }, { "code": null, "e": 31925, "s": 31883, "text": "Swift is the future of Apple development." }, { "code": null, "e": 31952, "s": 31925, "text": "Swift is enterprise ready." }, { "code": null, "e": 31967, "s": 31952, "text": "Disadvantages:" }, { "code": null, "e": 32029, "s": 31967, "text": "The language is still quite young and talent pool is limited." }, { "code": null, "e": 32132, "s": 32029, "text": "Swift is considered a “moving target” as it is a new language and number of swift programmers are few." }, { "code": null, "e": 32186, "s": 32132, "text": "Poor interoperability with third-party tools and IDEs" }, { "code": null, "e": 32228, "s": 32186, "text": "Lack of support for earlier iOS versions." }, { "code": null, "e": 32249, "s": 32228, "text": "Programming Language" }, { "code": null, "e": 32347, "s": 32249, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32384, "s": 32347, "text": "Decorators with parameters in Python" }, { "code": null, "e": 32430, "s": 32384, "text": "Top 10 Programming Languages to Learn in 2022" }, { "code": null, "e": 32464, "s": 32430, "text": "Shallow Copy and Deep Copy in C++" }, { "code": null, "e": 32477, "s": 32464, "text": "Kotlin Array" }, { "code": null, "e": 32493, "s": 32477, "text": "C# | Data Types" }, { "code": null, "e": 32545, "s": 32493, "text": "Difference between Shallow and Deep copy of a class" }, { "code": null, "e": 32581, "s": 32545, "text": "Advantages and Disadvantages of OOP" }, { "code": null, "e": 32618, "s": 32581, "text": "Java Swing | JComboBox with examples" }, { "code": null, "e": 32655, "s": 32618, "text": "Top 10 Fastest Programming Languages" } ]
Introduction to Fragments | Android - GeeksforGeeks
04 Jul, 2020 A Fragment is a piece of an activity which enable more modular activity design. A fragment encapsulates functionality so that it is easier to reuse within activities and layouts.Android devices exists in a variety of screen sizes and densities. Fragments simplify the reuse of components in different layouts and their logic. You can build single-pane layouts for handsets (phones) and multi-pane layouts for tablets. You can also use fragments also to support different layout for landscape and portrait orientation on a smartphone. The below image shows how two UI modules defined by fragments can be combined into one activity for a tablet design but separated for a handset design. Fragment Life Cycle Android fragments have their own life cycle very similar to an android activity. onAttach() : The fragment instance is associated with an activity instance.The fragment and the activity is not fully initialized. Typically you get in this method a reference to the activity which uses the fragment for further initialization work. onCreate() : The system calls this method when creating the fragment. You should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed. onCreateView() : The system calls this callback when it’s time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View component from this method that is the root of your fragment’s layout. You can return null if the fragment does not provide a UI. onActivityCreated() : The onActivityCreated() is called after the onCreateView() method when the host activity is created. Activity and fragment instance have been created as well as the view hierarchy of the activity. At this point, view can be accessed with the findViewById() method. example. In this method you can instantiate objects which require a Context object onStart() : The onStart() method is called once the fragment gets visible. onResume() : Fragment becomes active. onPause() : The system calls this method as the first indication that the user is leaving the fragment. This is usually where you should commit any changes that should be persisted beyond the current user session. onStop() : Fragment going to be stopped by calling onStop() onDestroyView() : Fragment view will destroy after call this method onDestroy() :called to do final clean up of the fragment’s state but Not guaranteed to be called by the Android platform. Types of Fragments Single frame fragments : Single frame fragments are using for hand hold devices like mobiles, here we can show only one fragment as a view. List fragments : fragments having special list view is called as list fragment Fragments transaction : Using with fragment transaction. we can move one fragment to another fragment. Handling the Fragment Lifecycle A Fragment exist in three states : Resumed : The fragment is visible in the running activity. Paused : Another activity is in the foreground and has focus, but the activity in which this fragment lives is still visible (the foreground activity is partially transparent or doesn’t cover the entire screen). Stopped : The fragment is not visible. Either the host activity has been stopped or the fragment has been removed from the activity but added to the back stack. A stopped fragment is still alive (all state and member information is retained by the system). However, it is no longer visible to the user and will be killed if the activity is killed. The effect of the activity lifecycle on the fragment lifecycle : Defining and using fragments To define a new fragment we either extend the android.app.Fragment class or one of its subclasses. package com.saket.geeksforgeeks.demo; import android.app.Fragment;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView; public class DetailFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_rssitem_detail, container, false); return view; } public void setText(String text) { TextView view = (TextView) getView().findViewById(R.id.detailsText); view.setText(text); }} Fragment Transaction: While for an dynamic activity we are set buttons for an interactive UI. If we are set after clicking the button the fragment should appear then we have to get help from Fragment Manager. It handle all the fragment in an activity. We need to set fragment transaction with the help of fragment manager and and begin transaction, and then simply replace the layout of the fragment with desired place. /* this code is contributed by rohansadhukhan9 */Button B = findViewById(R.id.button);B.setOnClickListener(new View.OnClickListener) { @Override public void onClick(View v) { fragment f = new fragment(); FragmentTransaction t = getSupportFragmentManeger().beginTransaction(); t.replace(R.id.fragment_layout, f).commit(); }} This article is contributed by Saket 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. rohansadhukhan9 android GBlog Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar GET and POST requests using Python Top 10 Projects For Beginners To Practice HTML and CSS Skills Types of Software Testing Working with csv files in Python How to Start Learning DSA? Supervised and Unsupervised learning Differences between Procedural and Object Oriented Programming Introduction to Recurrent Neural Network 12 pip Commands For Python Developers
[ { "code": null, "e": 26011, "s": 25983, "text": "\n04 Jul, 2020" }, { "code": null, "e": 26545, "s": 26011, "text": "A Fragment is a piece of an activity which enable more modular activity design. A fragment encapsulates functionality so that it is easier to reuse within activities and layouts.Android devices exists in a variety of screen sizes and densities. Fragments simplify the reuse of components in different layouts and their logic. You can build single-pane layouts for handsets (phones) and multi-pane layouts for tablets. You can also use fragments also to support different layout for landscape and portrait orientation on a smartphone." }, { "code": null, "e": 26697, "s": 26545, "text": "The below image shows how two UI modules defined by fragments can be combined into one activity for a tablet design but separated for a handset design." }, { "code": null, "e": 26717, "s": 26697, "text": "Fragment Life Cycle" }, { "code": null, "e": 26798, "s": 26717, "text": "Android fragments have their own life cycle very similar to an android activity." }, { "code": null, "e": 27047, "s": 26798, "text": "onAttach() : The fragment instance is associated with an activity instance.The fragment and the activity is not fully initialized. Typically you get in this method a reference to the activity which uses the fragment for further initialization work." }, { "code": null, "e": 27254, "s": 27047, "text": "onCreate() : The system calls this method when creating the fragment. You should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed." }, { "code": null, "e": 27566, "s": 27254, "text": "onCreateView() : The system calls this callback when it’s time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View component from this method that is the root of your fragment’s layout. You can return null if the fragment does not provide a UI." }, { "code": null, "e": 27936, "s": 27566, "text": "onActivityCreated() : The onActivityCreated() is called after the onCreateView() method when the host activity is created. Activity and fragment instance have been created as well as the view hierarchy of the activity. At this point, view can be accessed with the findViewById() method. example. In this method you can instantiate objects which require a Context object" }, { "code": null, "e": 28011, "s": 27936, "text": "onStart() : The onStart() method is called once the fragment gets visible." }, { "code": null, "e": 28049, "s": 28011, "text": "onResume() : Fragment becomes active." }, { "code": null, "e": 28263, "s": 28049, "text": "onPause() : The system calls this method as the first indication that the user is leaving the fragment. This is usually where you should commit any changes that should be persisted beyond the current user session." }, { "code": null, "e": 28323, "s": 28263, "text": "onStop() : Fragment going to be stopped by calling onStop()" }, { "code": null, "e": 28391, "s": 28323, "text": "onDestroyView() : Fragment view will destroy after call this method" }, { "code": null, "e": 28513, "s": 28391, "text": "onDestroy() :called to do final clean up of the fragment’s state but Not guaranteed to be called by the Android platform." }, { "code": null, "e": 28532, "s": 28513, "text": "Types of Fragments" }, { "code": null, "e": 28672, "s": 28532, "text": "Single frame fragments : Single frame fragments are using for hand hold devices like mobiles, here we can show only one fragment as a view." }, { "code": null, "e": 28751, "s": 28672, "text": "List fragments : fragments having special list view is called as list fragment" }, { "code": null, "e": 28854, "s": 28751, "text": "Fragments transaction : Using with fragment transaction. we can move one fragment to another fragment." }, { "code": null, "e": 28886, "s": 28854, "text": "Handling the Fragment Lifecycle" }, { "code": null, "e": 28921, "s": 28886, "text": "A Fragment exist in three states :" }, { "code": null, "e": 28980, "s": 28921, "text": "Resumed : The fragment is visible in the running activity." }, { "code": null, "e": 29192, "s": 28980, "text": "Paused : Another activity is in the foreground and has focus, but the activity in which this fragment lives is still visible (the foreground activity is partially transparent or doesn’t cover the entire screen)." }, { "code": null, "e": 29540, "s": 29192, "text": "Stopped : The fragment is not visible. Either the host activity has been stopped or the fragment has been removed from the activity but added to the back stack. A stopped fragment is still alive (all state and member information is retained by the system). However, it is no longer visible to the user and will be killed if the activity is killed." }, { "code": null, "e": 29605, "s": 29540, "text": "The effect of the activity lifecycle on the fragment lifecycle :" }, { "code": null, "e": 29634, "s": 29605, "text": "Defining and using fragments" }, { "code": null, "e": 29733, "s": 29634, "text": "To define a new fragment we either extend the android.app.Fragment class or one of its subclasses." }, { "code": "package com.saket.geeksforgeeks.demo; import android.app.Fragment;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView; public class DetailFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_rssitem_detail, container, false); return view; } public void setText(String text) { TextView view = (TextView) getView().findViewById(R.id.detailsText); view.setText(text); }}", "e": 30478, "s": 29733, "text": null }, { "code": null, "e": 30898, "s": 30478, "text": "Fragment Transaction: While for an dynamic activity we are set buttons for an interactive UI. If we are set after clicking the button the fragment should appear then we have to get help from Fragment Manager. It handle all the fragment in an activity. We need to set fragment transaction with the help of fragment manager and and begin transaction, and then simply replace the layout of the fragment with desired place." }, { "code": "/* this code is contributed by rohansadhukhan9 */Button B = findViewById(R.id.button);B.setOnClickListener(new View.OnClickListener) { @Override public void onClick(View v) { fragment f = new fragment(); FragmentTransaction t = getSupportFragmentManeger().beginTransaction(); t.replace(R.id.fragment_layout, f).commit(); }}", "e": 31252, "s": 30898, "text": null }, { "code": null, "e": 31551, "s": 31252, "text": "This article is contributed by Saket 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 31676, "s": 31551, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 31692, "s": 31676, "text": "rohansadhukhan9" }, { "code": null, "e": 31700, "s": 31692, "text": "android" }, { "code": null, "e": 31706, "s": 31700, "text": "GBlog" }, { "code": null, "e": 31804, "s": 31706, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31829, "s": 31804, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 31864, "s": 31829, "text": "GET and POST requests using Python" }, { "code": null, "e": 31926, "s": 31864, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 31952, "s": 31926, "text": "Types of Software Testing" }, { "code": null, "e": 31985, "s": 31952, "text": "Working with csv files in Python" }, { "code": null, "e": 32012, "s": 31985, "text": "How to Start Learning DSA?" }, { "code": null, "e": 32049, "s": 32012, "text": "Supervised and Unsupervised learning" }, { "code": null, "e": 32112, "s": 32049, "text": "Differences between Procedural and Object Oriented Programming" }, { "code": null, "e": 32153, "s": 32112, "text": "Introduction to Recurrent Neural Network" } ]
Mathematics | Introduction to Proofs - GeeksforGeeks
10 Sep, 2021 Mathematical proof is an argument we give logically to validate a mathematical statement. In order to validate a statement, we consider two things: A statement and Logical operators. A statement is either true or false but not both. Logical operators are AND, OR, NOT, If then, and If and only if. Coupled with quantifiers like for all and there exists. We apply operators on the statement to check the correctness of it. Types of mathematical proofs: Proof by cases – In this method, we evaluate every case of the statement to conclude its truthiness. Example: For every integer x, the integer x(x + 1) is even Proof: If x is even, hence, x = 2k for some number k. now the statement becomes: Example: For every integer x, the integer x(x + 1) is even Proof: If x is even, hence, x = 2k for some number k. now the statement becomes: 2k(2k + 1) which is divisible by 2, hence it is even. If x is odd, hence x = 2k + 1 for some number k, now the statement becomes: (2k+1)(2k+1+1) = (2k + 1) 2(k + 1) which is again divisible by 2 and hence in both cases we proved that x(x+1) is even. Proof by contradiction – We assume the negation of the given statement and then proceed to conclude the proof. Example: Prove that sqrt(2) is irrational Suppose sqrt(2) is rational. Example: Prove that sqrt(2) is irrational Suppose sqrt(2) is rational. sqrt(2) = a/b for some integers a and b with b != 0. Let us choose integers a and b with sqrt(2) = a/b, such that b is positive and as small as possible. (Well-Ordering Principle) a^2 = 2b^2 Since a^2 is even, it follows that a is even. a = 2k for some integer k, so a^2 = 4k^2 b^2 = 2k^2. Since b^2 is even, it follows that b is even. Since a and b are both even, a/2 and b/2 are integers with b/2 > 0, and sqrt(2) = (a/2)/(b/2), because (a/2)/(b/2) = a/b. But it contradicts our assumption b is as small as possible. Therefore sqrt(2) cannot be rational. Proof by induction – The Principle of Mathematical Induction (PMI). Let P(n) be a statement about the positive integer n. If the following are true: 1. P(1), 2. (for all n there exists Z+) P(n) implies P(n + 1), then (for all n there exists Z+) P(n). Example: For every positive integer n, 1 + 2 +···+ n = n(n + 1)/ 2 Proof: Base case: If n = 1, 1 + ··· + n = 1 And n(n + 1)/2 = 11 Inductive step: Suppose that for a given n there exists Z+, 1 + 2 +···+ n = n(n + 1)/ 2 ---- (i) (inductive hypothesis) Our goal is to show that: 1 + 2 +···+ n + (n + 1) = [n + 1]([n + 1] + 1)/ 2 i.e. 1 + 2 +···+ n + (n + 1) = (n + 1)(n + 2) /2 Add n + 1 both sides to equation (i), we get, 1 + 2 +···+ n + (n + 1) = n(n + 1)/ 2 + (n + 1) = n(n + 1) /2 + 2(n + 1) /2 = (n + 2)(n + 1) /2 Direct Proof – when we want to prove a conditional statement p implies q, we assume that p is true, and follow implications to get to show that q is then true. It is Mostly an application of hypothetical syllogism, [(p → r) ∧ (r → q)] → (p → q)] We just have to find the propositions that lead us to q. Theorem: If m is even and n is odd, then their sum is odd Proof: Since m is even, there is an integer j such that m = 2j. Since n is odd, there is an integer k such that n = 2k+1. Then, Theorem: If m is even and n is odd, then their sum is odd Proof: Since m is even, there is an integer j such that m = 2j. Since n is odd, there is an integer k such that n = 2k+1. Then, m+n = (2j)+(2k+1) = 2(j+k)+1 Since j+k is an integer, we see that m+n is odd. anikaseth98 Discrete Mathematics Picked Engineering Mathematics GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inequalities in LaTeX Activation Functions Arrow Symbols in LaTeX Newton's Divided Difference Interpolation Formula Set Notations in LaTeX Layers of OSI Model ACID Properties in DBMS TCP/IP Model Types of Operating Systems Normal Forms in DBMS
[ { "code": null, "e": 31277, "s": 31249, "text": "\n10 Sep, 2021" }, { "code": null, "e": 31461, "s": 31277, "text": "Mathematical proof is an argument we give logically to validate a mathematical statement. In order to validate a statement, we consider two things: A statement and Logical operators. " }, { "code": null, "e": 31701, "s": 31461, "text": "A statement is either true or false but not both. Logical operators are AND, OR, NOT, If then, and If and only if. Coupled with quantifiers like for all and there exists. We apply operators on the statement to check the correctness of it. " }, { "code": null, "e": 31732, "s": 31701, "text": "Types of mathematical proofs: " }, { "code": null, "e": 31975, "s": 31732, "text": "Proof by cases – In this method, we evaluate every case of the statement to conclude its truthiness. Example: For every integer x, the integer x(x + 1) is even Proof: If x is even, hence, x = 2k for some number k. now the statement becomes: " }, { "code": null, "e": 32117, "s": 31975, "text": "Example: For every integer x, the integer x(x + 1) is even Proof: If x is even, hence, x = 2k for some number k. now the statement becomes: " }, { "code": null, "e": 32128, "s": 32117, "text": "2k(2k + 1)" }, { "code": null, "e": 32172, "s": 32128, "text": "which is divisible by 2, hence it is even. " }, { "code": null, "e": 32249, "s": 32172, "text": "If x is odd, hence x = 2k + 1 for some number k, now the statement becomes: " }, { "code": null, "e": 32285, "s": 32249, "text": "(2k+1)(2k+1+1) = (2k + 1) 2(k + 1)" }, { "code": null, "e": 32371, "s": 32285, "text": "which is again divisible by 2 and hence in both cases we proved that x(x+1) is even. " }, { "code": null, "e": 32554, "s": 32371, "text": "Proof by contradiction – We assume the negation of the given statement and then proceed to conclude the proof. Example: Prove that sqrt(2) is irrational Suppose sqrt(2) is rational. " }, { "code": null, "e": 32626, "s": 32554, "text": "Example: Prove that sqrt(2) is irrational Suppose sqrt(2) is rational. " }, { "code": null, "e": 32641, "s": 32626, "text": "sqrt(2) = a/b " }, { "code": null, "e": 32808, "s": 32641, "text": "for some integers a and b with b != 0. Let us choose integers a and b with sqrt(2) = a/b, such that b is positive and as small as possible. (Well-Ordering Principle) " }, { "code": null, "e": 32821, "s": 32808, "text": " a^2 = 2b^2 " }, { "code": null, "e": 33188, "s": 32821, "text": "Since a^2 is even, it follows that a is even. a = 2k for some integer k, so a^2 = 4k^2 b^2 = 2k^2. Since b^2 is even, it follows that b is even. Since a and b are both even, a/2 and b/2 are integers with b/2 > 0, and sqrt(2) = (a/2)/(b/2), because (a/2)/(b/2) = a/b. But it contradicts our assumption b is as small as possible. Therefore sqrt(2) cannot be rational. " }, { "code": null, "e": 33338, "s": 33188, "text": "Proof by induction – The Principle of Mathematical Induction (PMI). Let P(n) be a statement about the positive integer n. If the following are true: " }, { "code": null, "e": 33445, "s": 33338, "text": "1. P(1), \n2. (for all n there exists Z+) P(n) implies P(n + 1), \n then (for all n there exists Z+) P(n)." }, { "code": null, "e": 33485, "s": 33445, "text": "Example: For every positive integer n, " }, { "code": null, "e": 33514, "s": 33485, "text": "1 + 2 +···+ n = n(n + 1)/ 2 " }, { "code": null, "e": 33543, "s": 33514, "text": "Proof: Base case: If n = 1, " }, { "code": null, "e": 33561, "s": 33543, "text": "1 + ··· + n = 1 " }, { "code": null, "e": 33566, "s": 33561, "text": "And " }, { "code": null, "e": 33583, "s": 33566, "text": "n(n + 1)/2 = 11 " }, { "code": null, "e": 33644, "s": 33583, "text": "Inductive step: Suppose that for a given n there exists Z+, " }, { "code": null, "e": 33706, "s": 33644, "text": "1 + 2 +···+ n = n(n + 1)/ 2 ---- (i) (inductive hypothesis) " }, { "code": null, "e": 33733, "s": 33706, "text": "Our goal is to show that: " }, { "code": null, "e": 33833, "s": 33733, "text": "1 + 2 +···+ n + (n + 1) = [n + 1]([n + 1] + 1)/ 2\ni.e. 1 + 2 +···+ n + (n + 1) = (n + 1)(n + 2) /2 " }, { "code": null, "e": 33880, "s": 33833, "text": "Add n + 1 both sides to equation (i), we get, " }, { "code": null, "e": 33979, "s": 33880, "text": "1 + 2 +···+ n + (n + 1) \n= n(n + 1)/ 2 + (n + 1)\n= n(n + 1) /2 + 2(n + 1) /2\n= (n + 2)(n + 1) /2 " }, { "code": null, "e": 34470, "s": 33979, "text": "Direct Proof – when we want to prove a conditional statement p implies q, we assume that p is true, and follow implications to get to show that q is then true. It is Mostly an application of hypothetical syllogism, [(p → r) ∧ (r → q)] → (p → q)] We just have to find the propositions that lead us to q. Theorem: If m is even and n is odd, then their sum is odd Proof: Since m is even, there is an integer j such that m = 2j. Since n is odd, there is an integer k such that n = 2k+1. Then, " }, { "code": null, "e": 34658, "s": 34470, "text": "Theorem: If m is even and n is odd, then their sum is odd Proof: Since m is even, there is an integer j such that m = 2j. Since n is odd, there is an integer k such that n = 2k+1. Then, " }, { "code": null, "e": 34688, "s": 34658, "text": "m+n = (2j)+(2k+1) = 2(j+k)+1 " }, { "code": null, "e": 34738, "s": 34688, "text": "Since j+k is an integer, we see that m+n is odd. " }, { "code": null, "e": 34750, "s": 34738, "text": "anikaseth98" }, { "code": null, "e": 34771, "s": 34750, "text": "Discrete Mathematics" }, { "code": null, "e": 34778, "s": 34771, "text": "Picked" }, { "code": null, "e": 34802, "s": 34778, "text": "Engineering Mathematics" }, { "code": null, "e": 34810, "s": 34802, "text": "GATE CS" }, { "code": null, "e": 34908, "s": 34810, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34930, "s": 34908, "text": "Inequalities in LaTeX" }, { "code": null, "e": 34951, "s": 34930, "text": "Activation Functions" }, { "code": null, "e": 34974, "s": 34951, "text": "Arrow Symbols in LaTeX" }, { "code": null, "e": 35024, "s": 34974, "text": "Newton's Divided Difference Interpolation Formula" }, { "code": null, "e": 35047, "s": 35024, "text": "Set Notations in LaTeX" }, { "code": null, "e": 35067, "s": 35047, "text": "Layers of OSI Model" }, { "code": null, "e": 35091, "s": 35067, "text": "ACID Properties in DBMS" }, { "code": null, "e": 35104, "s": 35091, "text": "TCP/IP Model" }, { "code": null, "e": 35131, "s": 35104, "text": "Types of Operating Systems" } ]
numpy.unwrap() in Python - GeeksforGeeks
05 Jul, 2021 numpy.unwrap(p, discount=3.141592653589793, axis=-1) function helps user to unwrap a given array by changing deltas to values of 2*pi complement. It unwraps radian phase p by changing absolute jumps greater than discount to their 2*pi complement along the given axis. Result is an unwrapped array. Parameters:p : [array like] input array discount : [float, optional] Maximum discontinuity between values, default is pi axis : [int, optional] Axis along which unwrap will operate, default is last axisReturns: [ndarray] output array Note: If the discontinuity in p is smaller than pi, but larger than discount, no unwrapping is done because taking the 2*pi complement would only make the discontinuity larger.Code #1: Default Values Working Python3 import numpy as np l1 =[1, 2, 3, 4, 5]print("Result 1: ", np.unwrap(l1)) l2 =[0, 0.78, 5.49, 6.28]print("Result 2: ", np.unwrap(l2)) Output: Result 1: array([1., 2., 3., 4., 5.]) Result 2: array([ 0., 0.78, -0.79318531, -0.00318531]) In l2, discount > 2*pi (between 0.78 and 5.49), so array values are changed.Code #2: Custom Values Working Python3 import numpy as np l1 =[5, 7, 10, 14, 19, 25, 32]print("Result 1: ", np.unwrap(l1, discount = 4)) l2 =[0, 1.34237486723, 4.3453455, 8.134654756, 9.3465456542]print("Result 2: ", np.unwrap(l2, discount = 3.1)) Output: Result 1: [ 5., 7., 10., 7.71681469, 6.43362939, 6.15044408, 6.86725877] Result 2: [0., 1.34237487, 4.3453455, 1.85146945, 3.06336035] References: https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.unwrap.html singghakshay Picked Python numpy-arrayManipulation Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n05 Jul, 2021" }, { "code": null, "e": 25836, "s": 25537, "text": "numpy.unwrap(p, discount=3.141592653589793, axis=-1) function helps user to unwrap a given array by changing deltas to values of 2*pi complement. It unwraps radian phase p by changing absolute jumps greater than discount to their 2*pi complement along the given axis. Result is an unwrapped array. " }, { "code": null, "e": 26070, "s": 25836, "text": "Parameters:p : [array like] input array discount : [float, optional] Maximum discontinuity between values, default is pi axis : [int, optional] Axis along which unwrap will operate, default is last axisReturns: [ndarray] output array" }, { "code": null, "e": 26280, "s": 26070, "text": "Note: If the discontinuity in p is smaller than pi, but larger than discount, no unwrapping is done because taking the 2*pi complement would only make the discontinuity larger.Code #1: Default Values Working " }, { "code": null, "e": 26288, "s": 26280, "text": "Python3" }, { "code": "import numpy as np l1 =[1, 2, 3, 4, 5]print(\"Result 1: \", np.unwrap(l1)) l2 =[0, 0.78, 5.49, 6.28]print(\"Result 2: \", np.unwrap(l2))", "e": 26421, "s": 26288, "text": null }, { "code": null, "e": 26431, "s": 26421, "text": "Output: " }, { "code": null, "e": 26525, "s": 26431, "text": "Result 1: array([1., 2., 3., 4., 5.])\nResult 2: array([ 0., 0.78, -0.79318531, -0.00318531])" }, { "code": null, "e": 26634, "s": 26525, "text": "In l2, discount > 2*pi (between 0.78 and 5.49), so array values are changed.Code #2: Custom Values Working " }, { "code": null, "e": 26642, "s": 26634, "text": "Python3" }, { "code": "import numpy as np l1 =[5, 7, 10, 14, 19, 25, 32]print(\"Result 1: \", np.unwrap(l1, discount = 4)) l2 =[0, 1.34237486723, 4.3453455, 8.134654756, 9.3465456542]print(\"Result 2: \", np.unwrap(l2, discount = 3.1))", "e": 26851, "s": 26642, "text": null }, { "code": null, "e": 26861, "s": 26851, "text": "Output: " }, { "code": null, "e": 26996, "s": 26861, "text": "Result 1: [ 5., 7., 10., 7.71681469, 6.43362939, 6.15044408, 6.86725877] Result 2: [0., 1.34237487, 4.3453455, 1.85146945, 3.06336035]" }, { "code": null, "e": 27087, "s": 26996, "text": "References: https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.unwrap.html " }, { "code": null, "e": 27100, "s": 27087, "text": "singghakshay" }, { "code": null, "e": 27107, "s": 27100, "text": "Picked" }, { "code": null, "e": 27138, "s": 27107, "text": "Python numpy-arrayManipulation" }, { "code": null, "e": 27151, "s": 27138, "text": "Python-numpy" }, { "code": null, "e": 27158, "s": 27151, "text": "Python" }, { "code": null, "e": 27256, "s": 27158, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27288, "s": 27256, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27330, "s": 27288, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27372, "s": 27330, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27428, "s": 27372, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27455, "s": 27428, "text": "Python Classes and Objects" }, { "code": null, "e": 27494, "s": 27455, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27525, "s": 27494, "text": "Python | os.path.join() method" }, { "code": null, "e": 27554, "s": 27525, "text": "Create a directory in Python" }, { "code": null, "e": 27576, "s": 27554, "text": "Defaultdict in Python" } ]
Surface Area and Volume of Hexagonal Prism - GeeksforGeeks
17 Mar, 2021 Given a Base edge and Height of the Hexagonal prism, the task is to find the Surface Area and the Volume of hexagonal Prism. In mathematics, a hexagonal prism is a three-dimensional solid shape which have 8 faces, 18 edges, and 12 vertices. The two faces at either ends are hexagons, and the rest of the faces of the hexagonal prism are rectangular. where a is the base length and h is the height of the hexagonal prism. Surface Area = Volume = Examples: Input : a = 4, h = 3 Output : Surface Area: 155.138443 Volume: 124.707657 Input : a = 5, h = 10 Output : Surface Area: 429.904 Volume: 649.519 C++ Java Python3 C# PHP Javascript // C++ program to find the Surface Area// and Volume of Hexagonal Prism. #include <bits/stdc++.h>using namespace std; // Function to calculate Surface areavoid findSurfaceArea(float a, float h){ float Area; // Formula to calculate surface area Area = 6 * a * h + 3 * sqrt(3) * a * a; // Display surface area cout << "Surface Area: " << Area; cout << "\n";} // Function to calculate Volumevoid findVolume(float a, float h){ float Volume; // formula to calculate Volume Volume = 3 * sqrt(3) * a * a * h / 2; // Display Volume cout << "Volume: " << Volume;} // Driver Codeint main(){ float a = 5, h = 10; // surface area function call findSurfaceArea(a, h); // volume function call findVolume(a, h); return 0;} // Java program to find the Surface Area// and Volume of Hexagonal Prism. import java.io.*; class GFG { // Function to calculate Surface area static void findSurfaceArea(float a, float h) { float Area; // Formula to calculate surface area Area = 6 * a * h + 3 * (float)(Math.sqrt(3)) * a * a; // Display surface area System.out.println("Surface Area: " + Area); } // Function to calculate Volume static void findVolume(float a, float h) { float Volume; // formula to calculate Volume Volume = 3 * (float)(Math.sqrt(3)) * a * a * h / 2; // Display Volume System.out.println("Volume: " + Volume); } // Driver code public static void main (String[] args) { float a = 5, h = 10; // surface area function call findSurfaceArea(a, h); // volume function call findVolume(a, h); }} # Python3 program to find the# Surface Area and Volume# of Hexagonal Prism.import math # Function to calculate# Surface areadef findSurfaceArea(a, h): Area = 0; # Formula to calculate # surface area Area = (6 * a * h + 3 * math.sqrt(3) * a * a); # Display surface area print("Surface Area:", round(Area, 3)); # Function to# calculate Volumedef findVolume(a, h): Volume = 0; # formula to # calculate Volume Volume = (3 * math.sqrt(3) * a * a * h / 2); # Display Volume print("Volume:", round(Volume, 3)); # Driver Codea = 5;h = 10; # surface area# function callfindSurfaceArea(a, h); # volume function callfindVolume(a, h); # This code is contributed# by mits // C# program to find the// Surface Area and Volume// of Hexagonal Prism.using System; class GFG{ // Function to calculate // Surface area static void findSurfaceArea(float a, float h) { float Area; // Formula to calculate // surface area Area = 6 * a * h + 3 * (float)(Math.Sqrt(3)) * a * a; // Display surface area Console.WriteLine("Surface Area: " + Area); } // Function to // calculate Volume static void findVolume(float a, float h) { float Volume; // formula to calculate Volume Volume = 3 * (float)(Math.Sqrt(3)) * a * a * h / 2; // Display Volume Console.WriteLine("Volume: " + Volume); } // Driver code public static void Main () { float a = 5, h = 10; // surface area // function call findSurfaceArea(a, h); // volume function call findVolume(a, h); }} // This code is contributed// by anuj_67. <?php// PHP program to find the// Surface Area and Volume// of Hexagonal Prism. // Function to calculate// Surface areafunction findSurfaceArea($a, $h){ $Area; // Formula to calculate // surface area $Area = 6 * $a * $h + 3 * sqrt(3) * $a * $a; // Display surface area echo "Surface Area: " , $Area,"\n"; } // Function to// calculate Volumefunction findVolume($a, $h){ $Volume; // formula to // calculate Volume $Volume = 3 * sqrt(3) * $a * $a * $h / 2; // Display Volume echo "Volume: " , $Volume;} // Driver Code$a = 5; $h = 10; // surface area// function callfindSurfaceArea($a, $h); // volume function callfindVolume($a, $h); // This code is contributed// by anuj_67.?> <script>// javascript program to find the Surface Area// and Volume of Hexagonal Prism. // Function to calculate Surface areafunction findSurfaceArea( a, h){ let Area; // Formula to calculate surface area Area = 6 * a * h + 3 * Math.sqrt(3) * a * a; // Display surface area document.write( "Surface Area: " + Area.toFixed(3) + "<br/>");} // Function to calculate Volumefunction findVolume( a, h){ let Volume; // formula to calculate Volume Volume = 3 * Math.sqrt(3) * a * a * h / 2; // Display Volume document.write( "Volume: " + Volume.toFixed(3));} // Driver Code let a = 5, h = 10; // surface area function call findSurfaceArea(a, h); // volume function call findVolume(a, h); // This code is contributed by todaysgaurav </script> Surface Area: 429.904 Volume: 649.519 vt_m Mithun Kumar todaysgaurav Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 26117, "s": 26089, "text": "\n17 Mar, 2021" }, { "code": null, "e": 26469, "s": 26117, "text": "Given a Base edge and Height of the Hexagonal prism, the task is to find the Surface Area and the Volume of hexagonal Prism. In mathematics, a hexagonal prism is a three-dimensional solid shape which have 8 faces, 18 edges, and 12 vertices. The two faces at either ends are hexagons, and the rest of the faces of the hexagonal prism are rectangular. " }, { "code": null, "e": 26541, "s": 26469, "text": "where a is the base length and h is the height of the hexagonal prism. " }, { "code": null, "e": 26567, "s": 26541, "text": "Surface Area = Volume = " }, { "code": null, "e": 26579, "s": 26567, "text": "Examples: " }, { "code": null, "e": 26741, "s": 26579, "text": "Input : a = 4, h = 3\nOutput : Surface Area: 155.138443\n Volume: 124.707657\n\nInput : a = 5, h = 10\nOutput : Surface Area: 429.904\n Volume: 649.519" }, { "code": null, "e": 26747, "s": 26743, "text": "C++" }, { "code": null, "e": 26752, "s": 26747, "text": "Java" }, { "code": null, "e": 26760, "s": 26752, "text": "Python3" }, { "code": null, "e": 26763, "s": 26760, "text": "C#" }, { "code": null, "e": 26767, "s": 26763, "text": "PHP" }, { "code": null, "e": 26778, "s": 26767, "text": "Javascript" }, { "code": "// C++ program to find the Surface Area// and Volume of Hexagonal Prism. #include <bits/stdc++.h>using namespace std; // Function to calculate Surface areavoid findSurfaceArea(float a, float h){ float Area; // Formula to calculate surface area Area = 6 * a * h + 3 * sqrt(3) * a * a; // Display surface area cout << \"Surface Area: \" << Area; cout << \"\\n\";} // Function to calculate Volumevoid findVolume(float a, float h){ float Volume; // formula to calculate Volume Volume = 3 * sqrt(3) * a * a * h / 2; // Display Volume cout << \"Volume: \" << Volume;} // Driver Codeint main(){ float a = 5, h = 10; // surface area function call findSurfaceArea(a, h); // volume function call findVolume(a, h); return 0;}", "e": 27548, "s": 26778, "text": null }, { "code": "// Java program to find the Surface Area// and Volume of Hexagonal Prism. import java.io.*; class GFG { // Function to calculate Surface area static void findSurfaceArea(float a, float h) { float Area; // Formula to calculate surface area Area = 6 * a * h + 3 * (float)(Math.sqrt(3)) * a * a; // Display surface area System.out.println(\"Surface Area: \" + Area); } // Function to calculate Volume static void findVolume(float a, float h) { float Volume; // formula to calculate Volume Volume = 3 * (float)(Math.sqrt(3)) * a * a * h / 2; // Display Volume System.out.println(\"Volume: \" + Volume); } // Driver code public static void main (String[] args) { float a = 5, h = 10; // surface area function call findSurfaceArea(a, h); // volume function call findVolume(a, h); }}", "e": 28502, "s": 27548, "text": null }, { "code": "# Python3 program to find the# Surface Area and Volume# of Hexagonal Prism.import math # Function to calculate# Surface areadef findSurfaceArea(a, h): Area = 0; # Formula to calculate # surface area Area = (6 * a * h + 3 * math.sqrt(3) * a * a); # Display surface area print(\"Surface Area:\", round(Area, 3)); # Function to# calculate Volumedef findVolume(a, h): Volume = 0; # formula to # calculate Volume Volume = (3 * math.sqrt(3) * a * a * h / 2); # Display Volume print(\"Volume:\", round(Volume, 3)); # Driver Codea = 5;h = 10; # surface area# function callfindSurfaceArea(a, h); # volume function callfindVolume(a, h); # This code is contributed# by mits", "e": 29250, "s": 28502, "text": null }, { "code": "// C# program to find the// Surface Area and Volume// of Hexagonal Prism.using System; class GFG{ // Function to calculate // Surface area static void findSurfaceArea(float a, float h) { float Area; // Formula to calculate // surface area Area = 6 * a * h + 3 * (float)(Math.Sqrt(3)) * a * a; // Display surface area Console.WriteLine(\"Surface Area: \" + Area); } // Function to // calculate Volume static void findVolume(float a, float h) { float Volume; // formula to calculate Volume Volume = 3 * (float)(Math.Sqrt(3)) * a * a * h / 2; // Display Volume Console.WriteLine(\"Volume: \" + Volume); } // Driver code public static void Main () { float a = 5, h = 10; // surface area // function call findSurfaceArea(a, h); // volume function call findVolume(a, h); }} // This code is contributed// by anuj_67.", "e": 30424, "s": 29250, "text": null }, { "code": "<?php// PHP program to find the// Surface Area and Volume// of Hexagonal Prism. // Function to calculate// Surface areafunction findSurfaceArea($a, $h){ $Area; // Formula to calculate // surface area $Area = 6 * $a * $h + 3 * sqrt(3) * $a * $a; // Display surface area echo \"Surface Area: \" , $Area,\"\\n\"; } // Function to// calculate Volumefunction findVolume($a, $h){ $Volume; // formula to // calculate Volume $Volume = 3 * sqrt(3) * $a * $a * $h / 2; // Display Volume echo \"Volume: \" , $Volume;} // Driver Code$a = 5; $h = 10; // surface area// function callfindSurfaceArea($a, $h); // volume function callfindVolume($a, $h); // This code is contributed// by anuj_67.?>", "e": 31181, "s": 30424, "text": null }, { "code": "<script>// javascript program to find the Surface Area// and Volume of Hexagonal Prism. // Function to calculate Surface areafunction findSurfaceArea( a, h){ let Area; // Formula to calculate surface area Area = 6 * a * h + 3 * Math.sqrt(3) * a * a; // Display surface area document.write( \"Surface Area: \" + Area.toFixed(3) + \"<br/>\");} // Function to calculate Volumefunction findVolume( a, h){ let Volume; // formula to calculate Volume Volume = 3 * Math.sqrt(3) * a * a * h / 2; // Display Volume document.write( \"Volume: \" + Volume.toFixed(3));} // Driver Code let a = 5, h = 10; // surface area function call findSurfaceArea(a, h); // volume function call findVolume(a, h); // This code is contributed by todaysgaurav </script>", "e": 31976, "s": 31181, "text": null }, { "code": null, "e": 32014, "s": 31976, "text": "Surface Area: 429.904\nVolume: 649.519" }, { "code": null, "e": 32021, "s": 32016, "text": "vt_m" }, { "code": null, "e": 32034, "s": 32021, "text": "Mithun Kumar" }, { "code": null, "e": 32047, "s": 32034, "text": "todaysgaurav" }, { "code": null, "e": 32060, "s": 32047, "text": "Mathematical" }, { "code": null, "e": 32079, "s": 32060, "text": "School Programming" }, { "code": null, "e": 32092, "s": 32079, "text": "Mathematical" }, { "code": null, "e": 32190, "s": 32092, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32220, "s": 32190, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 32280, "s": 32220, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 32295, "s": 32280, "text": "C++ Data Types" }, { "code": null, "e": 32338, "s": 32295, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 32357, "s": 32338, "text": "Coin Change | DP-7" }, { "code": null, "e": 32375, "s": 32357, "text": "Python Dictionary" }, { "code": null, "e": 32391, "s": 32375, "text": "Arrays in C/C++" }, { "code": null, "e": 32410, "s": 32391, "text": "Inheritance in C++" }, { "code": null, "e": 32435, "s": 32410, "text": "Reverse a string in Java" } ]
Change Icon for Tkinter MessageBox - GeeksforGeeks
10 May, 2020 We know many modules and one of them is Tkinter. Tkinter is a module which is a standard interface of Python to the Tk GUI toolkit. This interface Tk and the Tkinter modules, both of them are available on most of the Unix platforms. it is also available on Windows OS and many others. But it is usually a shared library or DLL file, for some cases, it is statically linked with the Python interpreter. Whenever we create a message box using the Tkinter, we always see a similar icon in the message box. Let us see it again with an example. Example: import tkinter as tk win = tk.Tk() # as it does not have any mentions # of the icon we get a default icon.win.title("example") win.mainloop() Output : In the above example, within the circle that is the default icon we get, when it is not mentioned in the code. And yes, we can change it according to our wishes. Select the photo you want to keep it as an icon. Select and then [Right click–> Properties]. Type of File you see will be in the format of (.png). But we need it in the format of (.ico). There might be a question that why we need to convert .png to .ico? Why can’t we use it in the format of .png? For that, the answer will be the icon bitmap function (depending on the programming language) should be used to set a bitmap image to the window when the window is iconified. For that just search online for online icoconverter, go there, and simply convert the image you want to convert it to (.ico). So we got our image ready to the desired format, next get back to the coding part and let’s learn how to change the default icon to our selected icon follow the steps. Step 1: Add a line, defining the icon bitmap i.e. win.iconbitmap(r”) import tkinter as to win = tk.Tk() win.title("example") win.iconbitmap(r'') win.mainloop() Step 2: Mentioning the file path of the image we want as an icon. Copy the File location and paste it inside “win.iconbitmap(r”)”. win.iconbitmap(r'C:\Users\Madhusudan\Downloads\') Step 3: Mention the file name. Copy the file name and paste it after “\” where you mentioned the file location. win.iconbitmap(r'C:\Users\Madhusudan\Downloads\favicon(2).ico') Finally, we get the complete code for how we can change the icon. Let’s put it together. import tkinter as tk win = tk.Tk()win.title("example")win.iconbitmap(r'C:\Users\Madhusudan\Downloads\favicon(2).ico') win.mainloop() Output : Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25675, "s": 25647, "text": "\n10 May, 2020" }, { "code": null, "e": 26077, "s": 25675, "text": "We know many modules and one of them is Tkinter. Tkinter is a module which is a standard interface of Python to the Tk GUI toolkit. This interface Tk and the Tkinter modules, both of them are available on most of the Unix platforms. it is also available on Windows OS and many others. But it is usually a shared library or DLL file, for some cases, it is statically linked with the Python interpreter." }, { "code": null, "e": 26215, "s": 26077, "text": "Whenever we create a message box using the Tkinter, we always see a similar icon in the message box. Let us see it again with an example." }, { "code": null, "e": 26224, "s": 26215, "text": "Example:" }, { "code": "import tkinter as tk win = tk.Tk() # as it does not have any mentions # of the icon we get a default icon.win.title(\"example\") win.mainloop()", "e": 26370, "s": 26224, "text": null }, { "code": null, "e": 26379, "s": 26370, "text": "Output :" }, { "code": null, "e": 26688, "s": 26379, "text": "In the above example, within the circle that is the default icon we get, when it is not mentioned in the code. And yes, we can change it according to our wishes. Select the photo you want to keep it as an icon. Select and then [Right click–> Properties]. Type of File you see will be in the format of (.png)." }, { "code": null, "e": 27308, "s": 26688, "text": "But we need it in the format of (.ico). There might be a question that why we need to convert .png to .ico? Why can’t we use it in the format of .png? For that, the answer will be the icon bitmap function (depending on the programming language) should be used to set a bitmap image to the window when the window is iconified. For that just search online for online icoconverter, go there, and simply convert the image you want to convert it to (.ico). So we got our image ready to the desired format, next get back to the coding part and let’s learn how to change the default icon to our selected icon follow the steps." }, { "code": null, "e": 27377, "s": 27308, "text": "Step 1: Add a line, defining the icon bitmap i.e. win.iconbitmap(r”)" }, { "code": null, "e": 27470, "s": 27377, "text": "import tkinter as to\n\n\nwin = tk.Tk()\nwin.title(\"example\")\nwin.iconbitmap(r'')\nwin.mainloop()" }, { "code": null, "e": 27601, "s": 27470, "text": "Step 2: Mentioning the file path of the image we want as an icon. Copy the File location and paste it inside “win.iconbitmap(r”)”." }, { "code": null, "e": 27651, "s": 27601, "text": "win.iconbitmap(r'C:\\Users\\Madhusudan\\Downloads\\')" }, { "code": null, "e": 27763, "s": 27651, "text": "Step 3: Mention the file name. Copy the file name and paste it after “\\” where you mentioned the file location." }, { "code": null, "e": 27828, "s": 27763, "text": "win.iconbitmap(r'C:\\Users\\Madhusudan\\Downloads\\favicon(2).ico')\n" }, { "code": null, "e": 27917, "s": 27828, "text": "Finally, we get the complete code for how we can change the icon. Let’s put it together." }, { "code": "import tkinter as tk win = tk.Tk()win.title(\"example\")win.iconbitmap(r'C:\\Users\\Madhusudan\\Downloads\\favicon(2).ico') win.mainloop() ", "e": 28055, "s": 27917, "text": null }, { "code": null, "e": 28064, "s": 28055, "text": "Output :" }, { "code": null, "e": 28079, "s": 28064, "text": "Python-tkinter" }, { "code": null, "e": 28086, "s": 28079, "text": "Python" }, { "code": null, "e": 28184, "s": 28086, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28202, "s": 28184, "text": "Python Dictionary" }, { "code": null, "e": 28237, "s": 28202, "text": "Read a file line by line in Python" }, { "code": null, "e": 28269, "s": 28237, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28291, "s": 28269, "text": "Enumerate() in Python" }, { "code": null, "e": 28333, "s": 28291, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28363, "s": 28333, "text": "Iterate over a list in Python" }, { "code": null, "e": 28389, "s": 28363, "text": "Python String | replace()" }, { "code": null, "e": 28418, "s": 28389, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28462, "s": 28418, "text": "Reading and Writing to text files in Python" } ]
Perform Bubble Sort on strings in Java
To perform Bubble Sort, try the below given code. In this each each pair of adjacent elements is compared and the elements are swapped if they are not in order. The following is an example. Live Demo public class Demo { public static void main(String []args) { String str[] = { "s", "k", "r", "v", "n"}; String temp; System.out.println("Sorted string..."); for (int j = 0; j < str.length; j++) { for (int i = j + 1; i < str.length; i++) { // comparing strings if (str[i].compareTo(str[j]) < 0) { temp = str[j]; str[j] = str[i]; str[i] = temp; } } System.out.println(str[j]); } } } Sorted string... k n r s v
[ { "code": null, "e": 1223, "s": 1062, "text": "To perform Bubble Sort, try the below given code. In this each each pair of adjacent elements is compared and the elements are swapped if they are not in order." }, { "code": null, "e": 1252, "s": 1223, "text": "The following is an example." }, { "code": null, "e": 1263, "s": 1252, "text": " Live Demo" }, { "code": null, "e": 1788, "s": 1263, "text": "public class Demo {\n public static void main(String []args) {\n String str[] = { \"s\", \"k\", \"r\", \"v\", \"n\"};\n String temp;\n System.out.println(\"Sorted string...\");\n for (int j = 0; j < str.length; j++) {\n for (int i = j + 1; i < str.length; i++) {\n // comparing strings\n if (str[i].compareTo(str[j]) < 0) {\n temp = str[j];\n str[j] = str[i];\n str[i] = temp;\n }\n }\n System.out.println(str[j]);\n }\n }\n}" }, { "code": null, "e": 1815, "s": 1788, "text": "Sorted string...\nk\nn\nr\ns\nv" } ]
Find Last Digit Of a^b for Large Numbers | Practice | GeeksforGeeks
You are given two integer numbers, the base a and the index b. You have to find the last digit of ab. Example 1: Input: a = "3", b = "10" Output: 9 Explanation: 310 = 59049. Last digit is 9. Example 2: Input: a = "6", b = "2" Output: 6 Explanation: 62 = 36. Last digit is 6. Your Task: You don't need to read input or print anything. Your task is to complete the function getLastDigit() which takes two strings a,b as parameters and returns an integer denoting the last digit of ab. Expected Time Complexity: O(|b|) Expected Auxiliary Space: O(1) Constraints: 1 <= |a|,|b| <= 1000 Note:|a| = length of a and |b| = length of b. There will not be any test cases such that ab is undefined. 0 mayank20212 months ago C++int getLastDigit(string a, string b) { int zero_b=0; for(int i=0; i<b.length(); i++) { if(b[i] !='0') { zero_b=1; break; } } if(zero_b==0) return 1; int zero_a=0; for(int i=0; i<a.length(); i++) { if(a[i] !='0') { zero_a=1; break; } } if(zero_a==0) return 0; int last2; if(b.length()>=2) last2= (b[b.length()-2] -'0' ) *10 + (b[b.length()-1] -'0' ); else last2= (b[b.length()-1] -'0' ) ; //cout<<"--1--"<<last2<<endl; if(last2 %4==0) { last2=pow(a[a.length()-1]-'0', 4); } else { last2=last2%4; last2=pow(a[a.length()-1]-'0', last2); } return last2%10; } 0 rahulschauhan505 months ago int getLastDigit(string a, string b) { // code here if(b=="0"){ return 1; } int a1=a[a.size()-1]-'0'; int b1=b[b.size()-1]-'0'; if(b.size()>1){ string ss=""; ss+=b[b.size()-2]; ss+=b[b.size()-1]; b1=stoi(ss); } set<int>st; for(int i=1;i<=7;i++){ int j=pow(a1,i); j=j%10; st.insert(j); } // for(auto i=st.begin();i!=st.end();i++){ // cout<<*i<<" "; // } int rem=b1%st.size(); //cout<<endl<<rem<<endl; if(rem==0){ return ((int)pow(a1,st.size()))%10; } else{ return ((int)pow(a1,rem))%10; } } 0 ervishnu19945 months ago static int getLastDigit(String a, String b) { // code here char[] x=a.toCharArray(); char[] y=b.toCharArray(); int power=0; if(y.length<=2) for(int i=0;i<y.length;i++){ power+=y[i]-48; power*=10; } else for(int i=y.length-2;i<y.length;i++){//last 2 digit separated power+=y[i]-48; power*=10; } power/=10; // last two digit divided by 4 the number divide by 4 /* last digit repeated same values; greaterthan of 1: 1^0=1,1^1=1,1^2=1; 5^0=1,5^1=5,5^2=25; 6^0=1,6^1=6,6^2=36; power 4 after repeated same last values: 2^0=1,2^1=2,2^2=4,2^3=8,2^4=16,2^5=32; 3^0=1,3^1=3,3^2=9,3^3=27,3^4=81,3^5=243; 7^0=1,7^1=7,7^2=49,7^3=343,7^4=2401,7^5=16809; 8^0=1,8^1=8,8^2=64,8^3=512,8^4=4096,8^5,32768; */ if(x[x.length-1]-48==2||x[x.length-1]-48==3||x[x.length-1]-48==7||x[x.length-1]-48==8){ power%=4; if(power==0)power=4; }else if(x[x.length-1]-48==4||x[x.length-1]-48==9){ power%=2; if(power==0)power=4; }else if(x[x.length-1]-48==5||x[x.length-1]-48==6||x[x.length-1]-48==0||x[x.length-1]-48==1){ if(power>0) return x[x.length-1]-48; } int result=1; for(int i=0;i<power;i++){ result=(result*(x[x.length-1]-48))%10; } return result; } 0 tshivansh445 months ago Java solution class Solution { static int getLastDigit(String a, String b) { // code here // Return 1 if B is zero.. if(b.equals("0")) { return 1; } //creation of HashMap and storing repeating digits.. /*Using the concept that last digit repeats after every cycle of 4*/ HashMap<Integer,ArrayList<Integer>> mp=new HashMap<>(); for(int i=0;i<10;i++) { mp.put(i,new ArrayList<Integer>()); } for(int i=0;i<10;i++) { int k=i; for(int j=0;j<4;j++) { mp.get(i).add(k%10); k=k*i; } } /* After above for loop, Hash Map will be created which will contain value like 1:{1,1,1,1},2:{2,4,8,6},3:{3,9,7,1} */ /* if b's length is 1, we can apply below concept,because b will not be that much large*/ if(b.length()==1) { char lc=a.charAt(a.length()-1); int nlc=Character.getNumericValue(lc); int ltd=Integer.parseInt(b)-1; return mp.get(nlc).get(ltd%4); } /* if b's length is above 2, we can use the property of divisiblity by 4*/ char lc=a.charAt(a.length()-1); int nlc=Character.getNumericValue(lc); String lt=""; lt+=b.charAt(b.length()-2); lt+=b.charAt(b.length()-1); int ltd=Integer.parseInt(lt)-1; if(ltd%4==0) { return mp.get(nlc).get(0); } if(ltd%2==0) { return mp.get(nlc).get(2); } int f=4; int k=f; int count=1; while(ltd>k) { count++; k=f*count; } // System.out.println(k+" "+ltd); if((k-ltd)==3) { return mp.get(nlc).get(1); } else { return mp.get(nlc).get(3); } } }; +1 saurabhsharma295205 months ago Time Complexity: O(1)Space Complexity: O(1)int getLastDigit(string a, string b) { int n = b.size(); if(b == "0") return 1; int base = a.back()-48; int power = stoi((n == 1) ? b : b.substr(n-2, n)); power %= 4; unordered_map<int,vector<int>>mp; mp.insert({0, {0,0,0,0}}); mp.insert({1, {1,1,1,1}}); mp.insert({2, {2,4,8,6}}); mp.insert({3, {3,9,7,1}}); mp.insert({4, {4,6,4,6}}); mp.insert({5, {5,5,5,5}}); mp.insert({6, {6,6,6,6}}); mp.insert({7, {7,9,3,1}}); mp.insert({8, {8,4,2,6}}); mp.insert({9, {9,1,9,1}}); return mp[base][(power == 0) ? 3 : power-1]; } -1 fungkwe5 months ago O(1) with bit-wise operators and subtractions 0 atharvrustagi5 months ago O(1) Time and O(1) Space Solution (Math based) // last digits of powers of each number // (ex - powers of 3: 3 9 27 81 243 729...) // pattern repeats after 4 numbers in powers of 3 vector<vector<int>> mp = {{0}, {1}, {2, 4, 8, 6}, {3, 9, 7, 1}, {4, 6}, {5}, {6}, {7, 9, 3, 1}, {8, 4, 2, 6}, {9, 1}}; class Solution { public: int getLastDigit(string a, string b) { if (b == "0") return 1; int d = a.back() - '0'; auto it = b.rbegin(); // num = last 2 digits of b, or only last digit if |b|==1 int num = *it - '0' + 3; // 3 added due to mod adjustment ++it; if (it != b.rend()) num += (*it - '0') * 10; return mp[d][num % mp[d].size()]; } }; -4 aakashmehta8805 months ago O(1) Time Complexity O(1) Auxilliary space int getLastDigit(string a, string b) { int A=stoi(a),B=stoi(b); if(B==0) return 1; if(A==0) return 0; int last=A%10; int x=0,y=0; x=pow(last,4); if(B%4!=0){ y=pow(last,B%4); return (x*y)%10; } return x%10; } +2 mastermind_5 months ago ( C++) Solution ~ O(|b|) Time int getLastDigit(string a, string b) { int x = (a.back() - '0'), v = 0; if (b.size() == 1 && b[0] == '0')return 1; for (auto c : b)(v *= 10) %= 4, (v += (c - '0')) %= 4; return ((int)pow(x, (v == 0) ? 4 : v)) % 10; } +2 santoryuzoro05 months ago class Solution { public: int getLastDigit(string a, string b) { int last_digit = a[a.length() - 1u] - '0'; if(b.length() == 1u && b[0] == '0') return 1; vector<int> u(10); for(int i = 0; i <= 9; i ++) { int count = 0; int dig = i; do { dig = (dig * i) % 10; count ++; } while(dig != i); u[i] = count; } if(u[last_digit] == 1) return last_digit; int mod = 0; for(int i = 0; i < b.length(); i ++) { mod = (mod * 10 + (b[i] - '0')) % u[last_digit]; } // cout << mod << ' ' << u[last_digit] << '\n'; int answer = 1; if(mod == 0) mod = u[last_digit]; while(mod --) { answer = (answer * last_digit) % 10; } return answer; }}; 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": 340, "s": 238, "text": "You are given two integer numbers, the base a and the index b. You have to find the last digit of ab." }, { "code": null, "e": 353, "s": 342, "text": "Example 1:" }, { "code": null, "e": 431, "s": 353, "text": "Input:\na = \"3\", b = \"10\"\nOutput:\n9\nExplanation:\n310 = 59049. Last digit is 9." }, { "code": null, "e": 442, "s": 431, "text": "Example 2:" }, { "code": null, "e": 515, "s": 442, "text": "Input:\na = \"6\", b = \"2\"\nOutput:\n6\nExplanation:\n62 = 36. Last digit is 6." }, { "code": null, "e": 725, "s": 517, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function getLastDigit() which takes two strings a,b as parameters and returns an integer denoting the last digit of ab." }, { "code": null, "e": 791, "s": 727, "text": "Expected Time Complexity: O(|b|)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 827, "s": 793, "text": "Constraints:\n1 <= |a|,|b| <= 1000" }, { "code": null, "e": 933, "s": 827, "text": "Note:|a| = length of a and |b| = length of b. There will not be any test cases such that ab is undefined." }, { "code": null, "e": 935, "s": 933, "text": "0" }, { "code": null, "e": 958, "s": 935, "text": "mayank20212 months ago" }, { "code": null, "e": 1898, "s": 958, "text": "C++int getLastDigit(string a, string b) { int zero_b=0; for(int i=0; i<b.length(); i++) { if(b[i] !='0') { zero_b=1; break; } } if(zero_b==0) return 1; int zero_a=0; for(int i=0; i<a.length(); i++) { if(a[i] !='0') { zero_a=1; break; } } if(zero_a==0) return 0; int last2; if(b.length()>=2) last2= (b[b.length()-2] -'0' ) *10 + (b[b.length()-1] -'0' ); else last2= (b[b.length()-1] -'0' ) ; //cout<<\"--1--\"<<last2<<endl; if(last2 %4==0) { last2=pow(a[a.length()-1]-'0', 4); } else { last2=last2%4; last2=pow(a[a.length()-1]-'0', last2); } return last2%10; }" }, { "code": null, "e": 1900, "s": 1898, "text": "0" }, { "code": null, "e": 1928, "s": 1900, "text": "rahulschauhan505 months ago" }, { "code": null, "e": 2716, "s": 1928, "text": "int getLastDigit(string a, string b) {\n // code here\n if(b==\"0\"){\n return 1;\n }\n int a1=a[a.size()-1]-'0';\n int b1=b[b.size()-1]-'0';\n if(b.size()>1){\n string ss=\"\";\n ss+=b[b.size()-2];\n ss+=b[b.size()-1];\n b1=stoi(ss);\n }\n set<int>st;\n \n for(int i=1;i<=7;i++){\n int j=pow(a1,i);\n j=j%10;\n st.insert(j);\n }\n // for(auto i=st.begin();i!=st.end();i++){\n // cout<<*i<<\" \";\n // }\n int rem=b1%st.size();\n //cout<<endl<<rem<<endl;\n if(rem==0){\n return ((int)pow(a1,st.size()))%10;\n }\n else{\n return ((int)pow(a1,rem))%10;\n }\n \n }" }, { "code": null, "e": 2718, "s": 2716, "text": "0" }, { "code": null, "e": 2743, "s": 2718, "text": "ervishnu19945 months ago" }, { "code": null, "e": 4169, "s": 2743, "text": "static int getLastDigit(String a, String b) { // code here char[] x=a.toCharArray(); char[] y=b.toCharArray(); int power=0; if(y.length<=2) for(int i=0;i<y.length;i++){ power+=y[i]-48; power*=10; } else for(int i=y.length-2;i<y.length;i++){//last 2 digit separated power+=y[i]-48; power*=10; } power/=10; // last two digit divided by 4 the number divide by 4 /* last digit repeated same values; greaterthan of 1: 1^0=1,1^1=1,1^2=1; 5^0=1,5^1=5,5^2=25; 6^0=1,6^1=6,6^2=36; power 4 after repeated same last values: 2^0=1,2^1=2,2^2=4,2^3=8,2^4=16,2^5=32; 3^0=1,3^1=3,3^2=9,3^3=27,3^4=81,3^5=243; 7^0=1,7^1=7,7^2=49,7^3=343,7^4=2401,7^5=16809; 8^0=1,8^1=8,8^2=64,8^3=512,8^4=4096,8^5,32768; */ if(x[x.length-1]-48==2||x[x.length-1]-48==3||x[x.length-1]-48==7||x[x.length-1]-48==8){ power%=4; if(power==0)power=4; }else if(x[x.length-1]-48==4||x[x.length-1]-48==9){ power%=2; if(power==0)power=4; }else if(x[x.length-1]-48==5||x[x.length-1]-48==6||x[x.length-1]-48==0||x[x.length-1]-48==1){ if(power>0) return x[x.length-1]-48; } int result=1; for(int i=0;i<power;i++){ result=(result*(x[x.length-1]-48))%10; } return result; }" }, { "code": null, "e": 4171, "s": 4169, "text": "0" }, { "code": null, "e": 4195, "s": 4171, "text": "tshivansh445 months ago" }, { "code": null, "e": 4247, "s": 4195, "text": " Java solution" }, { "code": null, "e": 6230, "s": 4247, "text": "class Solution {\n static int getLastDigit(String a, String b) {\n // code here\n // Return 1 if B is zero..\n if(b.equals(\"0\"))\n {\n return 1;\n }\n //creation of HashMap and storing repeating digits..\n /*Using the concept that last digit repeats after every cycle\n of 4*/\n \n HashMap<Integer,ArrayList<Integer>> mp=new HashMap<>();\n for(int i=0;i<10;i++)\n {\n mp.put(i,new ArrayList<Integer>()); \n }\n for(int i=0;i<10;i++)\n {\n int k=i;\n for(int j=0;j<4;j++)\n {\n mp.get(i).add(k%10);\n k=k*i;\n }\n }\n /* After above for loop, Hash Map will be created which will contain value\n like 1:{1,1,1,1},2:{2,4,8,6},3:{3,9,7,1} */\n /* if b's length is 1, we can apply below concept,because\n b will not be that much large*/\n if(b.length()==1)\n {\n char lc=a.charAt(a.length()-1);\n int nlc=Character.getNumericValue(lc); \n int ltd=Integer.parseInt(b)-1;\n return mp.get(nlc).get(ltd%4);\n }\n /* if b's length is above 2, we can use the property of divisiblity by\n 4*/\n \n char lc=a.charAt(a.length()-1);\n int nlc=Character.getNumericValue(lc);\n String lt=\"\";\n lt+=b.charAt(b.length()-2);\n lt+=b.charAt(b.length()-1);\n int ltd=Integer.parseInt(lt)-1;\n if(ltd%4==0)\n {\n return mp.get(nlc).get(0);\n }\n if(ltd%2==0)\n {\n return mp.get(nlc).get(2);\n }\n int f=4;\n int k=f;\n int count=1;\n while(ltd>k)\n {\n count++;\n k=f*count;\n }\n // System.out.println(k+\" \"+ltd);\n if((k-ltd)==3)\n {\n return mp.get(nlc).get(1); \n }\n else\n {\n return mp.get(nlc).get(3);\n }\n \n }\n};" }, { "code": null, "e": 6233, "s": 6230, "text": "+1" }, { "code": null, "e": 6264, "s": 6233, "text": "saurabhsharma295205 months ago" }, { "code": null, "e": 6974, "s": 6264, "text": "Time Complexity: O(1)Space Complexity: O(1)int getLastDigit(string a, string b) { int n = b.size(); if(b == \"0\") return 1; int base = a.back()-48; int power = stoi((n == 1) ? b : b.substr(n-2, n)); power %= 4; unordered_map<int,vector<int>>mp; mp.insert({0, {0,0,0,0}}); mp.insert({1, {1,1,1,1}}); mp.insert({2, {2,4,8,6}}); mp.insert({3, {3,9,7,1}}); mp.insert({4, {4,6,4,6}}); mp.insert({5, {5,5,5,5}}); mp.insert({6, {6,6,6,6}}); mp.insert({7, {7,9,3,1}}); mp.insert({8, {8,4,2,6}}); mp.insert({9, {9,1,9,1}}); return mp[base][(power == 0) ? 3 : power-1]; } " }, { "code": null, "e": 6977, "s": 6974, "text": "-1" }, { "code": null, "e": 6997, "s": 6977, "text": "fungkwe5 months ago" }, { "code": null, "e": 7043, "s": 6997, "text": "O(1) with bit-wise operators and subtractions" }, { "code": null, "e": 7045, "s": 7043, "text": "0" }, { "code": null, "e": 7071, "s": 7045, "text": "atharvrustagi5 months ago" }, { "code": null, "e": 7118, "s": 7071, "text": "O(1) Time and O(1) Space Solution (Math based)" }, { "code": null, "e": 8040, "s": 7118, "text": "// last digits of powers of each number \n// (ex - powers of 3: 3 9 27 81 243 729...)\n// pattern repeats after 4 numbers in powers of 3\nvector<vector<int>> mp = {{0},\n {1}, \n {2, 4, 8, 6}, \n {3, 9, 7, 1}, \n {4, 6}, \n {5},\n {6},\n {7, 9, 3, 1},\n {8, 4, 2, 6},\n {9, 1}};\n\nclass Solution {\n public:\n int getLastDigit(string a, string b) {\n if (b == \"0\")\treturn 1;\n int d = a.back() - '0';\n auto it = b.rbegin();\n // num = last 2 digits of b, or only last digit if |b|==1\n int num = *it - '0' + 3; // 3 added due to mod adjustment\n ++it;\n if (it != b.rend())\n num += (*it - '0') * 10;\n return mp[d][num % mp[d].size()];\n }\n};" }, { "code": null, "e": 8043, "s": 8040, "text": "-4" }, { "code": null, "e": 8070, "s": 8043, "text": "aakashmehta8805 months ago" }, { "code": null, "e": 8430, "s": 8070, "text": "O(1) Time Complexity O(1) Auxilliary space\nint getLastDigit(string a, string b) {\n int A=stoi(a),B=stoi(b);\n if(B==0) return 1;\n if(A==0) return 0;\n int last=A%10;\n int x=0,y=0;\n \n x=pow(last,4);\n if(B%4!=0){\n y=pow(last,B%4);\n return (x*y)%10;\n }\n return x%10;\n }" }, { "code": null, "e": 8433, "s": 8430, "text": "+2" }, { "code": null, "e": 8457, "s": 8433, "text": "mastermind_5 months ago" }, { "code": null, "e": 8487, "s": 8457, "text": "( C++) Solution ~ O(|b|) Time" }, { "code": null, "e": 8720, "s": 8487, "text": "int getLastDigit(string a, string b) {\n int x = (a.back() - '0'), v = 0;\n if (b.size() == 1 && b[0] == '0')return 1;\n for (auto c : b)(v *= 10) %= 4, (v += (c - '0')) %= 4;\n return ((int)pow(x, (v == 0) ? 4 : v)) % 10;\n}" }, { "code": null, "e": 8723, "s": 8720, "text": "+2" }, { "code": null, "e": 8749, "s": 8723, "text": "santoryuzoro05 months ago" }, { "code": null, "e": 9562, "s": 8749, "text": "class Solution { public: int getLastDigit(string a, string b) { int last_digit = a[a.length() - 1u] - '0'; if(b.length() == 1u && b[0] == '0') return 1; vector<int> u(10); for(int i = 0; i <= 9; i ++) { int count = 0; int dig = i; do { dig = (dig * i) % 10; count ++; } while(dig != i); u[i] = count; } if(u[last_digit] == 1) return last_digit; int mod = 0; for(int i = 0; i < b.length(); i ++) { mod = (mod * 10 + (b[i] - '0')) % u[last_digit]; } // cout << mod << ' ' << u[last_digit] << '\\n'; int answer = 1; if(mod == 0) mod = u[last_digit]; while(mod --) { answer = (answer * last_digit) % 10; } return answer; }};" }, { "code": null, "e": 9708, "s": 9562, "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": 9744, "s": 9708, "text": " Login to access your submissions. " }, { "code": null, "e": 9754, "s": 9744, "text": "\nProblem\n" }, { "code": null, "e": 9764, "s": 9754, "text": "\nContest\n" }, { "code": null, "e": 9827, "s": 9764, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 9975, "s": 9827, "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": 10183, "s": 9975, "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": 10289, "s": 10183, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to specify values on Y-axis in Python Matplotlib?
To specify values on Y-axis in Python, we can take the following steps− Create x and y data points using numpy. To specify the value of axes, create a list of characters. Use xticks and yticks method to specify the ticks on the axes with x and y ticks data points respectively. Plot the line using x and y, color=red, using plot() method. Make x and y margin 0. To display the figure, use show() method. import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True x = np.array([0, 2, 4, 6]) y = np.array([1, 3, 5, 7]) ticks = ['a', 'b', 'c', 'd'] plt.xticks(x, ticks) plt.yticks(y, ticks) plt.plot(x, y, c='green') plt.margins(x=0, y=0) plt.show()
[ { "code": null, "e": 1134, "s": 1062, "text": "To specify values on Y-axis in Python, we can take the following steps−" }, { "code": null, "e": 1174, "s": 1134, "text": "Create x and y data points using numpy." }, { "code": null, "e": 1233, "s": 1174, "text": "To specify the value of axes, create a list of characters." }, { "code": null, "e": 1340, "s": 1233, "text": "Use xticks and yticks method to specify the ticks on the axes with x and y ticks data points respectively." }, { "code": null, "e": 1401, "s": 1340, "text": "Plot the line using x and y, color=red, using plot() method." }, { "code": null, "e": 1424, "s": 1401, "text": "Make x and y margin 0." }, { "code": null, "e": 1466, "s": 1424, "text": "To display the figure, use show() method." }, { "code": null, "e": 1793, "s": 1466, "text": "import numpy as np\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nx = np.array([0, 2, 4, 6])\ny = np.array([1, 3, 5, 7])\nticks = ['a', 'b', 'c', 'd']\nplt.xticks(x, ticks)\nplt.yticks(y, ticks)\nplt.plot(x, y, c='green')\nplt.margins(x=0, y=0)\nplt.show()" } ]
RecyclerView in Android with Example - GeeksforGeeks
05 Nov, 2020 RecyclerView is a ViewGroup added to the android studio as a successor of the GridView and ListView. It is an improvement on both of them and can be found in the latest v-7 support packages. It has been created to make possible construction of any lists with XML layouts as an item which can be customized vastly while improving on the efficiency of ListViews and GridViews. This improvement is achieved by recycling the views which are out of the visibility of the user. For example, if a user scrolled down to a position where items 4 and 5 are visible; items 1, 2, and 3 would be cleared from the memory to reduce memory consumption. Implementation: To implement a basic RecyclerView three sub-parts are needed to be constructed which offer the users the degree of control they require in making varying designs of their choice. The Card Layout: The card layout is an XML layout which will be treated as an item for the list created by the RecyclerView.The ViewHolder: The ViewHolder is a java class that stores the reference to the card layout views that have to be dynamically modified during the execution of the program by a list of data obtained either by online databases or added in some other way.The Data Class: The Data class is a custom java class that acts as a structure for holding the information for every item of the RecyclerView. The Card Layout: The card layout is an XML layout which will be treated as an item for the list created by the RecyclerView. The ViewHolder: The ViewHolder is a java class that stores the reference to the card layout views that have to be dynamically modified during the execution of the program by a list of data obtained either by online databases or added in some other way. The Data Class: The Data class is a custom java class that acts as a structure for holding the information for every item of the RecyclerView. Below is the implementation of the RecyclerView: exam_card.xml examViewHolder.java examData.java <!-- XML Code illustrating card layout usage. --><?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" android:layout_width="match_parent" android:layout_height="105dp"> <TextView android:layout_width="200dp" android:id="@+id/examName" android:textSize="16sp" android:layout_marginStart="20dp" android:text="First Exam" android:textColor="@color/black" android:layout_marginEnd="20dp" android:maxLines="1" android:layout_marginTop="15dp" android:layout_height="wrap_content"/> <ImageView android:id="@+id/examPic" android:layout_width="20dp" android:layout_height="20dp" android:layout_below="@+id/examName" android:tint="#808080" android:layout_marginStart="20dp" android:layout_marginTop="7dp" app:srcCompat="@drawable/baseline_schedule_black_36dp"/> <TextView android:id="@+id/examDate" android:layout_toEndOf="@+id/examPic" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/examName" android:layout_marginTop="5dp" android:layout_marginEnd="20dp" android:layout_marginStart="10dp" android:gravity="center" android:text="May 23, 2015" android:textSize="16sp"/> <ImageView android:id="@+id/examPic2" android:layout_width="20dp" android:layout_height="20dp" android:layout_below="@+id/examDate" android:tint="#808080" android:layout_marginStart="20dp" android:layout_marginTop="7dp" app:srcCompat="@drawable/baseline_school_black_36dp"/> <TextView android:id="@+id/examMessage" android:layout_toEndOf="@+id/examPic2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/examDate" android:layout_marginEnd="20dp" android:layout_marginTop="5dp" android:layout_marginStart="10dp" android:gravity="center" android:text="Best Of Luck" android:textSize="16sp"/> <TextView android:id="@+id/border2" android:layout_width="match_parent" android:layout_height="1dp" android:layout_marginStart="15dp" android:layout_marginEnd="15dp" android:layout_alignParentBottom="true" android:background="#808080"/> </RelativeLayout> // ViewHolder code for RecyclerViewpackage com.example.admin.example; import android.support.v7.widget.RecyclerView;import android.view.View;import android.widget.TextView; public class examViewHolder extends RecyclerView.ViewHolder { TextView examName; TextView examMessage; TextView examDate; View view; examViewHolder(View itemView) { super(itemView); examName = (TextView)itemView .findViewById(R.id.examName); examDate = (TextView)itemView .findViewById(R.id.examDate); examMessage = (TextView)itemView .findViewById(R.id.examMessage); view = itemView }} package com.prodigieux.admin.prodigieux; public class examData { String name; String date; String message; examData(String name, String date, String message) { this.name = name; this.date = date; this.message = message; }} To click on recycler item: To click on item of recycler view pass the instance of click interface in constructor of adapter public class ClickListiner{ // here index is index// of item clickedpublic click(int index); } The Adapter: The adapter is the main code responsible for RecyclerView. It holds all the important methods dealing with the implementation of RecylcerView. The basic methods for a successful implementation are: onCreateViewHolder: which deals with the inflation of the card layout as an item for the RecyclerView. onBindViewHolder: which deals with the setting of different data and methods related to clicks on particular items of the RecyclerView. getItemCount: which Returns the length of the RecyclerView. onAttachedToRecyclerView: which attaches the adapter to the RecyclerView. Below program illustrates an example of a custom adapter: ImageGalleryAdapter2.java private class ImageGalleryAdapter2 extends RecyclerView.Adapter<examViewHolder> { List<examData> list = Collections.emptyList(); Context context; ClickListiner listiner; public ImageGalleryAdapter2(List<examData> list, Context context,ClickListiner listiner) { this.list = list; this.context = context; this.listiner = listiner; } @Override public examViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { Context context = parent.getContext(); LayoutInflater inflater = LayoutInflater.from(context); // Inflate the layout View photoView = inflater .inflate(R.layout.card_exam, parent, false); examViewHolder viewHolder = new examViewHolder(photoView); return viewHolder; } @Override public void onBindViewHolder(final examViewHolder viewHolder, final int position) { final index = viewHolder.getAdapterPosition(); viewHolder.examName .setText(list.get(position).name); viewHolder.examDate .setText(list.get(position).date); viewHolder.examMessage .setText(list.get(position).message); viewHolder.view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { listiner.click(index); } }); } @Override public int getItemCount() { return list.size(); } @Override public void onAttachedToRecyclerView( RecyclerView recyclerView) { super.onAttachedToRecyclerView(recyclerView); } } RecyclerView Implementation in an activity: exam.java activity_exam.xml package com.example.admin.example; import android.content.Context;import android.content.Intent;import android.support.v7.app.ActionBarDrawerToggle;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.LinearLayoutManager;import android.support.v7.widget.RecyclerView;import android.support.v7.widget.Toolbar;import android.view.LayoutInflater;import android.view.MenuItem;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView; import com.prolificinteractive .materialcalendarview .MaterialCalendarView; import java.util.ArrayList;import java.util.Collections;import java.util.List; public class exam extends AppCompatActivity implements NavigationView .OnNavigationItemSelectedListener { ImageGalleryAdapter2 adapter; RecyclerView recyclerView; ClickListiner listiner; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_exam); Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar); toolbar.setTitle(""); setSupportActionBar(toolbar); List<examData> list = new ArrayList<>(); list = getData(); recyclerView = (RecyclerView)findViewById( R.id.recyclerView); listiner = new ClickListiner() { @Override public void click(int index){ Toast.makeTexT(this,"clicked item index is "+index,Toast.LENGTH_LONG).show(); } }; adapter = new ImageGalleryAdapter2( list, getApplication(),listiner); recyclerView.setAdapter(adapter); recyclerView.setLayoutManager( new LinearLayoutManager(exam.this)); } @Override public void onBackPressed() { super.onBackPressed(); } // Sample data for RecyclerView private List<examData> getData() { List<examData> list = new ArrayList<>(); list.add(new examData("First Exam", "May 23, 2015", "Best Of Luck")); list.add(new examData("Second Exam", "June 09, 2015", "b of l")); list.add(new examData("My Test Exam", "April 27, 2017", "This is testing exam ..")); return list; }} <?xml version="1.0" encoding="utf-8"?><ScrollView 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:layout_marginTop="56dp" android:background="#FFFFFF" tools:context=".exam" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > <android.support.v7.widget.RecyclerView android:nestedScrollingEnabled="false" android:id="@+id/recyclerView" android:layout_width="match_parent" android:overScrollMode="never" android:layout_height="wrap_content"/> </LinearLayout> </ScrollView> Keep in mind, that the drawable mentioned in the XML layouts have to be added to the drawable folder under res of the Android Studio Project and support package v7 should be added as an implementation in the Gradle file of the project for the code to run. The above code uses ScrollView as a parent to RecyclerView and disables the scrolling of the RecyclerView hence making the whole page scroll instead of just the RecyclerView contents. shad0w1947 android Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments HashMap in Java with Examples Initialize an ArrayList in Java Interfaces in Java ArrayList in Java Multidimensional Arrays in Java Singleton Class in Java Stack Class in Java Set in Java Multithreading in Java LinkedList in Java
[ { "code": null, "e": 25372, "s": 25344, "text": "\n05 Nov, 2020" }, { "code": null, "e": 26009, "s": 25372, "text": "RecyclerView is a ViewGroup added to the android studio as a successor of the GridView and ListView. It is an improvement on both of them and can be found in the latest v-7 support packages. It has been created to make possible construction of any lists with XML layouts as an item which can be customized vastly while improving on the efficiency of ListViews and GridViews. This improvement is achieved by recycling the views which are out of the visibility of the user. For example, if a user scrolled down to a position where items 4 and 5 are visible; items 1, 2, and 3 would be cleared from the memory to reduce memory consumption." }, { "code": null, "e": 26204, "s": 26009, "text": "Implementation: To implement a basic RecyclerView three sub-parts are needed to be constructed which offer the users the degree of control they require in making varying designs of their choice." }, { "code": null, "e": 26723, "s": 26204, "text": "The Card Layout: The card layout is an XML layout which will be treated as an item for the list created by the RecyclerView.The ViewHolder: The ViewHolder is a java class that stores the reference to the card layout views that have to be dynamically modified during the execution of the program by a list of data obtained either by online databases or added in some other way.The Data Class: The Data class is a custom java class that acts as a structure for holding the information for every item of the RecyclerView." }, { "code": null, "e": 26848, "s": 26723, "text": "The Card Layout: The card layout is an XML layout which will be treated as an item for the list created by the RecyclerView." }, { "code": null, "e": 27101, "s": 26848, "text": "The ViewHolder: The ViewHolder is a java class that stores the reference to the card layout views that have to be dynamically modified during the execution of the program by a list of data obtained either by online databases or added in some other way." }, { "code": null, "e": 27244, "s": 27101, "text": "The Data Class: The Data class is a custom java class that acts as a structure for holding the information for every item of the RecyclerView." }, { "code": null, "e": 27293, "s": 27244, "text": "Below is the implementation of the RecyclerView:" }, { "code": null, "e": 27307, "s": 27293, "text": "exam_card.xml" }, { "code": null, "e": 27327, "s": 27307, "text": "examViewHolder.java" }, { "code": null, "e": 27341, "s": 27327, "text": "examData.java" }, { "code": "<!-- XML Code illustrating card layout usage. --><?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\" android:layout_width=\"match_parent\" android:layout_height=\"105dp\"> <TextView android:layout_width=\"200dp\" android:id=\"@+id/examName\" android:textSize=\"16sp\" android:layout_marginStart=\"20dp\" android:text=\"First Exam\" android:textColor=\"@color/black\" android:layout_marginEnd=\"20dp\" android:maxLines=\"1\" android:layout_marginTop=\"15dp\" android:layout_height=\"wrap_content\"/> <ImageView android:id=\"@+id/examPic\" android:layout_width=\"20dp\" android:layout_height=\"20dp\" android:layout_below=\"@+id/examName\" android:tint=\"#808080\" android:layout_marginStart=\"20dp\" android:layout_marginTop=\"7dp\" app:srcCompat=\"@drawable/baseline_schedule_black_36dp\"/> <TextView android:id=\"@+id/examDate\" android:layout_toEndOf=\"@+id/examPic\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/examName\" android:layout_marginTop=\"5dp\" android:layout_marginEnd=\"20dp\" android:layout_marginStart=\"10dp\" android:gravity=\"center\" android:text=\"May 23, 2015\" android:textSize=\"16sp\"/> <ImageView android:id=\"@+id/examPic2\" android:layout_width=\"20dp\" android:layout_height=\"20dp\" android:layout_below=\"@+id/examDate\" android:tint=\"#808080\" android:layout_marginStart=\"20dp\" android:layout_marginTop=\"7dp\" app:srcCompat=\"@drawable/baseline_school_black_36dp\"/> <TextView android:id=\"@+id/examMessage\" android:layout_toEndOf=\"@+id/examPic2\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/examDate\" android:layout_marginEnd=\"20dp\" android:layout_marginTop=\"5dp\" android:layout_marginStart=\"10dp\" android:gravity=\"center\" android:text=\"Best Of Luck\" android:textSize=\"16sp\"/> <TextView android:id=\"@+id/border2\" android:layout_width=\"match_parent\" android:layout_height=\"1dp\" android:layout_marginStart=\"15dp\" android:layout_marginEnd=\"15dp\" android:layout_alignParentBottom=\"true\" android:background=\"#808080\"/> </RelativeLayout>", "e": 29895, "s": 27341, "text": null }, { "code": "// ViewHolder code for RecyclerViewpackage com.example.admin.example; import android.support.v7.widget.RecyclerView;import android.view.View;import android.widget.TextView; public class examViewHolder extends RecyclerView.ViewHolder { TextView examName; TextView examMessage; TextView examDate; View view; examViewHolder(View itemView) { super(itemView); examName = (TextView)itemView .findViewById(R.id.examName); examDate = (TextView)itemView .findViewById(R.id.examDate); examMessage = (TextView)itemView .findViewById(R.id.examMessage); view = itemView }}", "e": 30603, "s": 29895, "text": null }, { "code": "package com.prodigieux.admin.prodigieux; public class examData { String name; String date; String message; examData(String name, String date, String message) { this.name = name; this.date = date; this.message = message; }}", "e": 30892, "s": 30603, "text": null }, { "code": null, "e": 30919, "s": 30892, "text": "To click on recycler item:" }, { "code": null, "e": 31016, "s": 30919, "text": "To click on item of recycler view pass the instance of click interface in constructor of adapter" }, { "code": "public class ClickListiner{ // here index is index// of item clickedpublic click(int index); }", "e": 31113, "s": 31016, "text": null }, { "code": null, "e": 31324, "s": 31113, "text": "The Adapter: The adapter is the main code responsible for RecyclerView. It holds all the important methods dealing with the implementation of RecylcerView. The basic methods for a successful implementation are:" }, { "code": null, "e": 31427, "s": 31324, "text": "onCreateViewHolder: which deals with the inflation of the card layout as an item for the RecyclerView." }, { "code": null, "e": 31563, "s": 31427, "text": "onBindViewHolder: which deals with the setting of different data and methods related to clicks on particular items of the RecyclerView." }, { "code": null, "e": 31623, "s": 31563, "text": "getItemCount: which Returns the length of the RecyclerView." }, { "code": null, "e": 31697, "s": 31623, "text": "onAttachedToRecyclerView: which attaches the adapter to the RecyclerView." }, { "code": null, "e": 31755, "s": 31697, "text": "Below program illustrates an example of a custom adapter:" }, { "code": null, "e": 31781, "s": 31755, "text": "ImageGalleryAdapter2.java" }, { "code": "private class ImageGalleryAdapter2 extends RecyclerView.Adapter<examViewHolder> { List<examData> list = Collections.emptyList(); Context context; ClickListiner listiner; public ImageGalleryAdapter2(List<examData> list, Context context,ClickListiner listiner) { this.list = list; this.context = context; this.listiner = listiner; } @Override public examViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { Context context = parent.getContext(); LayoutInflater inflater = LayoutInflater.from(context); // Inflate the layout View photoView = inflater .inflate(R.layout.card_exam, parent, false); examViewHolder viewHolder = new examViewHolder(photoView); return viewHolder; } @Override public void onBindViewHolder(final examViewHolder viewHolder, final int position) { final index = viewHolder.getAdapterPosition(); viewHolder.examName .setText(list.get(position).name); viewHolder.examDate .setText(list.get(position).date); viewHolder.examMessage .setText(list.get(position).message); viewHolder.view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { listiner.click(index); } }); } @Override public int getItemCount() { return list.size(); } @Override public void onAttachedToRecyclerView( RecyclerView recyclerView) { super.onAttachedToRecyclerView(recyclerView); } }", "e": 33598, "s": 31781, "text": null }, { "code": null, "e": 33642, "s": 33598, "text": "RecyclerView Implementation in an activity:" }, { "code": null, "e": 33652, "s": 33642, "text": "exam.java" }, { "code": null, "e": 33670, "s": 33652, "text": "activity_exam.xml" }, { "code": "package com.example.admin.example; import android.content.Context;import android.content.Intent;import android.support.v7.app.ActionBarDrawerToggle;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.LinearLayoutManager;import android.support.v7.widget.RecyclerView;import android.support.v7.widget.Toolbar;import android.view.LayoutInflater;import android.view.MenuItem;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView; import com.prolificinteractive .materialcalendarview .MaterialCalendarView; import java.util.ArrayList;import java.util.Collections;import java.util.List; public class exam extends AppCompatActivity implements NavigationView .OnNavigationItemSelectedListener { ImageGalleryAdapter2 adapter; RecyclerView recyclerView; ClickListiner listiner; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_exam); Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar); toolbar.setTitle(\"\"); setSupportActionBar(toolbar); List<examData> list = new ArrayList<>(); list = getData(); recyclerView = (RecyclerView)findViewById( R.id.recyclerView); listiner = new ClickListiner() { @Override public void click(int index){ Toast.makeTexT(this,\"clicked item index is \"+index,Toast.LENGTH_LONG).show(); } }; adapter = new ImageGalleryAdapter2( list, getApplication(),listiner); recyclerView.setAdapter(adapter); recyclerView.setLayoutManager( new LinearLayoutManager(exam.this)); } @Override public void onBackPressed() { super.onBackPressed(); } // Sample data for RecyclerView private List<examData> getData() { List<examData> list = new ArrayList<>(); list.add(new examData(\"First Exam\", \"May 23, 2015\", \"Best Of Luck\")); list.add(new examData(\"Second Exam\", \"June 09, 2015\", \"b of l\")); list.add(new examData(\"My Test Exam\", \"April 27, 2017\", \"This is testing exam ..\")); return list; }}", "e": 36114, "s": 33670, "text": null }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><ScrollView 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:layout_marginTop=\"56dp\" android:background=\"#FFFFFF\" tools:context=\".exam\" > <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\" > <android.support.v7.widget.RecyclerView android:nestedScrollingEnabled=\"false\" android:id=\"@+id/recyclerView\" android:layout_width=\"match_parent\" android:overScrollMode=\"never\" android:layout_height=\"wrap_content\"/> </LinearLayout> </ScrollView>", "e": 36984, "s": 36114, "text": null }, { "code": null, "e": 37424, "s": 36984, "text": "Keep in mind, that the drawable mentioned in the XML layouts have to be added to the drawable folder under res of the Android Studio Project and support package v7 should be added as an implementation in the Gradle file of the project for the code to run. The above code uses ScrollView as a parent to RecyclerView and disables the scrolling of the RecyclerView hence making the whole page scroll instead of just the RecyclerView contents." }, { "code": null, "e": 37435, "s": 37424, "text": "shad0w1947" }, { "code": null, "e": 37443, "s": 37435, "text": "android" }, { "code": null, "e": 37448, "s": 37443, "text": "Java" }, { "code": null, "e": 37453, "s": 37448, "text": "Java" }, { "code": null, "e": 37551, "s": 37453, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37560, "s": 37551, "text": "Comments" }, { "code": null, "e": 37573, "s": 37560, "text": "Old Comments" }, { "code": null, "e": 37603, "s": 37573, "text": "HashMap in Java with Examples" }, { "code": null, "e": 37635, "s": 37603, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 37654, "s": 37635, "text": "Interfaces in Java" }, { "code": null, "e": 37672, "s": 37654, "text": "ArrayList in Java" }, { "code": null, "e": 37704, "s": 37672, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 37728, "s": 37704, "text": "Singleton Class in Java" }, { "code": null, "e": 37748, "s": 37728, "text": "Stack Class in Java" }, { "code": null, "e": 37760, "s": 37748, "text": "Set in Java" }, { "code": null, "e": 37783, "s": 37760, "text": "Multithreading in Java" } ]
Jackson Annotations - @JsonManagedReference
@JsonManagedReferences and JsonBackReferences are used to display objects with parent child relationship. @JsonManagedReferences is used to refer to parent object and @JsonBackReferences is used to mark child objects. import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonManagedReference; import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonTester { public static void main(String args[]) throws IOException, ParseException { ObjectMapper mapper = new ObjectMapper(); Student student = new Student(1, "Mark"); Book book1 = new Book(1,"Learn HTML", student); Book book2 = new Book(1,"Learn JAVA", student); student.addBook(book1); student.addBook(book2); String jsonString = mapper .writerWithDefaultPrettyPrinter() .writeValueAsString(book1); System.out.println(jsonString); } } class Student { public int rollNo; public String name; @JsonBackReference public List<Book> books; Student(int rollNo, String name){ this.rollNo = rollNo; this.name = name; this.books = new ArrayList<Book>(); } public void addBook(Book book){ books.add(book); } } class Book { public int id; public String name; Book(int id, String name, Student owner){ this.id = id; this.name = name; this.owner = owner; } @JsonManagedReference public Student owner; } { "id" : 1, "name" : "Learn HTML", "owner" : { "rollNo" : 1, "name" : "Mark" } } Print Add Notes Bookmark this page
[ { "code": null, "e": 2693, "s": 2475, "text": "@JsonManagedReferences and JsonBackReferences are used to display objects with parent child relationship. @JsonManagedReferences is used to refer to parent object and @JsonBackReferences is used to mark child objects." }, { "code": null, "e": 4059, "s": 2693, "text": "import java.io.IOException;\nimport java.text.ParseException;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport com.fasterxml.jackson.annotation.JsonBackReference;\nimport com.fasterxml.jackson.annotation.JsonManagedReference;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\npublic class JacksonTester {\n public static void main(String args[]) throws IOException, ParseException {\n ObjectMapper mapper = new ObjectMapper(); \n Student student = new Student(1, \"Mark\");\n Book book1 = new Book(1,\"Learn HTML\", student);\n Book book2 = new Book(1,\"Learn JAVA\", student);\n\n student.addBook(book1);\n student.addBook(book2);\n\n String jsonString = mapper \n .writerWithDefaultPrettyPrinter()\n .writeValueAsString(book1);\n System.out.println(jsonString);\n }\n}\nclass Student {\n public int rollNo;\n public String name;\n\n @JsonBackReference\n public List<Book> books;\n\n Student(int rollNo, String name){\n this.rollNo = rollNo;\n this.name = name;\n this.books = new ArrayList<Book>();\n }\n public void addBook(Book book){\n books.add(book);\n }\n}\nclass Book {\n public int id;\n public String name;\n\n Book(int id, String name, Student owner){\n this.id = id;\n this.name = name;\n this.owner = owner;\n }\n @JsonManagedReference\n public Student owner;\n}" }, { "code": null, "e": 4165, "s": 4059, "text": "{\n \"id\" : 1,\n \"name\" : \"Learn HTML\",\n \"owner\" : {\n \"rollNo\" : 1,\n \"name\" : \"Mark\"\n }\n}\n" }, { "code": null, "e": 4172, "s": 4165, "text": " Print" }, { "code": null, "e": 4183, "s": 4172, "text": " Add Notes" } ]
MySQL case statement inside a select statement?
For this, you can use CASE WHEN statement. Let us first create a table − mysql> create table DemoTable -> ( -> FirstName varchar(20), -> Score int -> ); Query OK, 0 rows affected (0.63 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values('John',46); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('John',78); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('John',69); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('Chris',78); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('Chris',89); Query OK, 1 row affected (0.17 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +-----------+-------+ | FirstName | Score | +-----------+-------+ | John | 46 | | John | 78 | | John | 69 | | Chris | 78 | | Chris | 89 | +-----------+-------+ 5 rows in set (0.00 sec) Following is the query to implement case statement inside a select statement − mysql> select FirstName,max(case when Score=69 then 1 else 0 end ) as isExistsOrNot -> from DemoTable -> group by FirstName; This will produce the following output − +-----------+---------------+ | FirstName | isExistsOrNot | +-----------+---------------+ | John | 1 | | Chris | 0 | +-----------+---------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1135, "s": 1062, "text": "For this, you can use CASE WHEN statement. Let us first create a table −" }, { "code": null, "e": 1264, "s": 1135, "text": "mysql> create table DemoTable\n -> (\n -> FirstName varchar(20),\n -> Score int\n -> );\nQuery OK, 0 rows affected (0.63 sec)" }, { "code": null, "e": 1320, "s": 1264, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1742, "s": 1320, "text": "mysql> insert into DemoTable values('John',46);\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable values('John',78);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values('John',69);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable values('Chris',78);\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable values('Chris',89);\nQuery OK, 1 row affected (0.17 sec)" }, { "code": null, "e": 1802, "s": 1742, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1833, "s": 1802, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1874, "s": 1833, "text": "This will produce the following output −" }, { "code": null, "e": 2097, "s": 1874, "text": "+-----------+-------+\n| FirstName | Score |\n+-----------+-------+\n| John | 46 |\n| John | 78 |\n| John | 69 |\n| Chris | 78 |\n| Chris | 89 |\n+-----------+-------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2176, "s": 2097, "text": "Following is the query to implement case statement inside a select statement −" }, { "code": null, "e": 2307, "s": 2176, "text": "mysql> select FirstName,max(case when Score=69 then 1 else 0 end ) as isExistsOrNot\n -> from DemoTable\n -> group by FirstName;" }, { "code": null, "e": 2348, "s": 2307, "text": "This will produce the following output −" }, { "code": null, "e": 2553, "s": 2348, "text": "+-----------+---------------+\n| FirstName | isExistsOrNot |\n+-----------+---------------+\n| John | 1 |\n| Chris | 0 |\n+-----------+---------------+\n2 rows in set (0.00 sec)" } ]
Difference between ArrayList and HashSet in Java
HashSet and ArrayList both are some of the most important classes of the Java Collection framework. The following are the important differences between ArrayList and HashSet. JavaTester.java Live Demo import java.io.*; import java.util.*; public class JavaTester { public static void main(String[] args) throws IOException{ int n = 5; List<Integer> al = new ArrayList<>(n); for (int i = 1; i <= n; i++) { al.add(i); } System.out.println(al); al.remove(3); System.out.println(al); for (int i = 0; i < al.size(); i++) { System.out.print(al.get(i) + " "); } } } [1, 2, 3, 4, 5] [1, 2, 3, 5] 1 2 3 5 JavaTester.java import java.util.HashSet; import java.util.Set; public class JavaTester { public static void main(String[] args){ Set<Integer> hs = new HashSet<>(); hs.add(1); hs.add(2); hs.add(3); hs.add(4); hs.add(4); for (Integer temp : hs) { System.out.print(temp + " "); } } } 1 2 3 4
[ { "code": null, "e": 1162, "s": 1062, "text": "HashSet and ArrayList both are some of the most important classes of the Java Collection framework." }, { "code": null, "e": 1237, "s": 1162, "text": "The following are the important differences between ArrayList and HashSet." }, { "code": null, "e": 1253, "s": 1237, "text": "JavaTester.java" }, { "code": null, "e": 1264, "s": 1253, "text": " Live Demo" }, { "code": null, "e": 1701, "s": 1264, "text": "import java.io.*;\nimport java.util.*;\npublic class JavaTester {\n public static void main(String[] args) throws IOException{\n int n = 5;\n List<Integer> al = new ArrayList<>(n);\n for (int i = 1; i <= n; i++) {\n al.add(i);\n }\n System.out.println(al);\n al.remove(3);\n System.out.println(al);\n for (int i = 0; i < al.size(); i++) {\n System.out.print(al.get(i) + \" \");\n }\n }\n}\n" }, { "code": null, "e": 1738, "s": 1701, "text": "[1, 2, 3, 4, 5]\n[1, 2, 3, 5]\n1 2 3 5" }, { "code": null, "e": 1754, "s": 1738, "text": "JavaTester.java" }, { "code": null, "e": 2084, "s": 1754, "text": "import java.util.HashSet;\nimport java.util.Set;\npublic class JavaTester {\n public static void main(String[] args){\n Set<Integer> hs = new HashSet<>();\n hs.add(1);\n hs.add(2);\n hs.add(3);\n hs.add(4);\n hs.add(4);\n for (Integer temp : hs) {\n System.out.print(temp + \" \");\n }\n }\n}\n" }, { "code": null, "e": 2092, "s": 2084, "text": "1 2 3 4" } ]
Character isDigit() method in Java with examples - GeeksforGeeks
17 May, 2020 The java.lang.Character.isDigit(char ch) is an inbuilt method in java which determines whether a specified character is a digit or not. There are few conditions that a character must accomplish to be accepted as a digit. That is if the general category type of a character, provided by Character.getType(ch), is DECIMAL_DIGIT_NUMBER, then the character is a digit.Some Unicode character ranges that contain digits:From ‘\u0030’ to ‘\u0039’ : ISO-LATIN-1 digits (‘0’ through ‘9’)From ‘\u0660’ to ‘\u0669’ : Arabic-Indic digitsFrom ‘\u06F0’ to ‘\u06F9’ : Extended Arabic-Indic digitsFrom ‘\u0966’ to ‘\u096F’ : Devanagari digitsFrom ‘\uFF10’ to ‘\uFF19’ : Fullwidth digitsApart from the above mentioned ranges, many other character ranges contain digits as well.Syntax:public static boolean isDigit(char ch) Parameter: This method accepts character parameter ch as an argument, which is to be tested.Return value:This method returns a boolean value. It returns True if ch is digit, else False.Note: This method cannot handle supplementary characters. To support all Unicode characters, including supplementary characters, use the isDigit(int) method.Below programs illustrate the above method:Program 1:// Java program to illustrate the// Character.isDigit() method import java.util.*;import java.lang.*; public class GFG { public static void main(String[] args) { // two characters char c1 = 'A', c2 = '4'; // Function to check if the character // is digit or not System.out.println( c1 + " is a digit -> " + Character.isDigit(c1)); System.out.println( c2 + " is a digit -> " + Character.isDigit(c2)); }}Output:A is a digit -> false 4 is a digit -> true Program 2:// Java program to illustrate the// Character.isDigit() method import java.util.*;import java.lang.*; public class GFG { public static int search_digit(String s) { // Function to check if is digit // is found or not for (int i = 0; i < s.length(); i++) { if (Character.isDigit( s.charAt(i)) == true) { // return position of digit return i + 1; } } // return 0 if digit not present return 0; } public static void main(String[] args) { // Array of strings String[] arr = { "ABC4DEF", "QWERTY" }; // To store the position of digit int index = 0; // Traverse the array arr[] to find digit // within it's elements for (String x : arr) { index = search_digit(x); if (index != 0) { System.out.println( "Digit found at : " + (index) + "th position."); } else { System.out.println( "Digit not present."); } } }}Output:Digit found at : 4th position. Digit not present. The java.lang.Character.isDigit(int codePoint) is an inbuilt method in java which determines whether the specified Unicode code point character of integer type is a digit or not.There are few conditions that a character must accomplish to be accepted as a digit. That is if the general category type of a character, provided by getType(codepoint), is a DECIMAL_DIGIT_NUMBER, then the character is a digit. Some Unicode character ranges that contain digits:From ‘\u0030’ to ‘\u0039’ : ISO-LATIN-1 digits (‘0’ through ‘9’)From ‘\u0660’ to ‘\u0669’ : Arabic-Indic digitsFrom ‘\u06F0’ to ‘\u06F9’ : Extended Arabic-Indic digitsFrom ‘\u0966’ to ‘\u096F’ : Devanagari digitsFrom ‘\uFF10’ to ‘\uFF19’ : Fullwidth digitsApart from the above mentioned ranges, many other character ranges contain digits as well.Syntax:public static boolean isDigit(int codePoint) Parameter: This method accepts unicode character parameter codePoint of integer type as an argument, which is to be tested.Return value: This method returns a boolean value. It returns True if the specified character is digit, else it returns False.Below programs illustrate the above method:Program 1:// This program demonstrates the use of// isDigit(int codePoint) method of Character class.import java.util.*; public class GFG { public static void main(String[] args) { // create codePoints int cp1 = 57; int cp2 = 84; // Check whether the codePoints // are digit or not. System.out.println( "The codePoint cp1 is a digit -> " + Character.isDigit(cp1)); System.out.println( "The codePoint cp2 is a digit -> " + Character.isDigit(cp2)); }}Output:The codePoint cp1 is a digit -> true The codePoint cp2 is a digit -> false Program 2:// This program demonstrates the use of// isDigit(int codePoint) method of// Character class.import java.util.*; public class Main { public static void main(String[] args) { // create codePoints int cp1 = 0x50; int cp2 = 0x06f8; // Check whether the codePoints // are digit or not. System.out.println( "The codePoint cp1 is a digit -> " + Character.isDigit(cp1)); System.out.println( "The codePoint cp2 is a digit -> " + Character.isDigit(cp2)); }}Output:The codePoint cp1 is a digit -> false The codePoint cp2 is a digit -> true Reference: https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html#isDigit-char- The java.lang.Character.isDigit(char ch) is an inbuilt method in java which determines whether a specified character is a digit or not. There are few conditions that a character must accomplish to be accepted as a digit. That is if the general category type of a character, provided by Character.getType(ch), is DECIMAL_DIGIT_NUMBER, then the character is a digit.Some Unicode character ranges that contain digits:From ‘\u0030’ to ‘\u0039’ : ISO-LATIN-1 digits (‘0’ through ‘9’)From ‘\u0660’ to ‘\u0669’ : Arabic-Indic digitsFrom ‘\u06F0’ to ‘\u06F9’ : Extended Arabic-Indic digitsFrom ‘\u0966’ to ‘\u096F’ : Devanagari digitsFrom ‘\uFF10’ to ‘\uFF19’ : Fullwidth digitsApart from the above mentioned ranges, many other character ranges contain digits as well.Syntax:public static boolean isDigit(char ch) Parameter: This method accepts character parameter ch as an argument, which is to be tested.Return value:This method returns a boolean value. It returns True if ch is digit, else False.Note: This method cannot handle supplementary characters. To support all Unicode characters, including supplementary characters, use the isDigit(int) method.Below programs illustrate the above method:Program 1:// Java program to illustrate the// Character.isDigit() method import java.util.*;import java.lang.*; public class GFG { public static void main(String[] args) { // two characters char c1 = 'A', c2 = '4'; // Function to check if the character // is digit or not System.out.println( c1 + " is a digit -> " + Character.isDigit(c1)); System.out.println( c2 + " is a digit -> " + Character.isDigit(c2)); }}Output:A is a digit -> false 4 is a digit -> true Program 2:// Java program to illustrate the// Character.isDigit() method import java.util.*;import java.lang.*; public class GFG { public static int search_digit(String s) { // Function to check if is digit // is found or not for (int i = 0; i < s.length(); i++) { if (Character.isDigit( s.charAt(i)) == true) { // return position of digit return i + 1; } } // return 0 if digit not present return 0; } public static void main(String[] args) { // Array of strings String[] arr = { "ABC4DEF", "QWERTY" }; // To store the position of digit int index = 0; // Traverse the array arr[] to find digit // within it's elements for (String x : arr) { index = search_digit(x); if (index != 0) { System.out.println( "Digit found at : " + (index) + "th position."); } else { System.out.println( "Digit not present."); } } }}Output:Digit found at : 4th position. Digit not present. From ‘\u0030’ to ‘\u0039’ : ISO-LATIN-1 digits (‘0’ through ‘9’)From ‘\u0660’ to ‘\u0669’ : Arabic-Indic digitsFrom ‘\u06F0’ to ‘\u06F9’ : Extended Arabic-Indic digitsFrom ‘\u0966’ to ‘\u096F’ : Devanagari digitsFrom ‘\uFF10’ to ‘\uFF19’ : Fullwidth digits Apart from the above mentioned ranges, many other character ranges contain digits as well. Syntax: public static boolean isDigit(char ch) Parameter: This method accepts character parameter ch as an argument, which is to be tested. Return value:This method returns a boolean value. It returns True if ch is digit, else False. Note: This method cannot handle supplementary characters. To support all Unicode characters, including supplementary characters, use the isDigit(int) method. Below programs illustrate the above method:Program 1: // Java program to illustrate the// Character.isDigit() method import java.util.*;import java.lang.*; public class GFG { public static void main(String[] args) { // two characters char c1 = 'A', c2 = '4'; // Function to check if the character // is digit or not System.out.println( c1 + " is a digit -> " + Character.isDigit(c1)); System.out.println( c2 + " is a digit -> " + Character.isDigit(c2)); }} A is a digit -> false 4 is a digit -> true Program 2: // Java program to illustrate the// Character.isDigit() method import java.util.*;import java.lang.*; public class GFG { public static int search_digit(String s) { // Function to check if is digit // is found or not for (int i = 0; i < s.length(); i++) { if (Character.isDigit( s.charAt(i)) == true) { // return position of digit return i + 1; } } // return 0 if digit not present return 0; } public static void main(String[] args) { // Array of strings String[] arr = { "ABC4DEF", "QWERTY" }; // To store the position of digit int index = 0; // Traverse the array arr[] to find digit // within it's elements for (String x : arr) { index = search_digit(x); if (index != 0) { System.out.println( "Digit found at : " + (index) + "th position."); } else { System.out.println( "Digit not present."); } } }} Digit found at : 4th position. Digit not present. The java.lang.Character.isDigit(int codePoint) is an inbuilt method in java which determines whether the specified Unicode code point character of integer type is a digit or not.There are few conditions that a character must accomplish to be accepted as a digit. That is if the general category type of a character, provided by getType(codepoint), is a DECIMAL_DIGIT_NUMBER, then the character is a digit. Some Unicode character ranges that contain digits:From ‘\u0030’ to ‘\u0039’ : ISO-LATIN-1 digits (‘0’ through ‘9’)From ‘\u0660’ to ‘\u0669’ : Arabic-Indic digitsFrom ‘\u06F0’ to ‘\u06F9’ : Extended Arabic-Indic digitsFrom ‘\u0966’ to ‘\u096F’ : Devanagari digitsFrom ‘\uFF10’ to ‘\uFF19’ : Fullwidth digitsApart from the above mentioned ranges, many other character ranges contain digits as well.Syntax:public static boolean isDigit(int codePoint) Parameter: This method accepts unicode character parameter codePoint of integer type as an argument, which is to be tested.Return value: This method returns a boolean value. It returns True if the specified character is digit, else it returns False.Below programs illustrate the above method:Program 1:// This program demonstrates the use of// isDigit(int codePoint) method of Character class.import java.util.*; public class GFG { public static void main(String[] args) { // create codePoints int cp1 = 57; int cp2 = 84; // Check whether the codePoints // are digit or not. System.out.println( "The codePoint cp1 is a digit -> " + Character.isDigit(cp1)); System.out.println( "The codePoint cp2 is a digit -> " + Character.isDigit(cp2)); }}Output:The codePoint cp1 is a digit -> true The codePoint cp2 is a digit -> false Program 2:// This program demonstrates the use of// isDigit(int codePoint) method of// Character class.import java.util.*; public class Main { public static void main(String[] args) { // create codePoints int cp1 = 0x50; int cp2 = 0x06f8; // Check whether the codePoints // are digit or not. System.out.println( "The codePoint cp1 is a digit -> " + Character.isDigit(cp1)); System.out.println( "The codePoint cp2 is a digit -> " + Character.isDigit(cp2)); }}Output:The codePoint cp1 is a digit -> false The codePoint cp2 is a digit -> true Reference: https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html#isDigit-char- From ‘\u0030’ to ‘\u0039’ : ISO-LATIN-1 digits (‘0’ through ‘9’)From ‘\u0660’ to ‘\u0669’ : Arabic-Indic digitsFrom ‘\u06F0’ to ‘\u06F9’ : Extended Arabic-Indic digitsFrom ‘\u0966’ to ‘\u096F’ : Devanagari digitsFrom ‘\uFF10’ to ‘\uFF19’ : Fullwidth digits Apart from the above mentioned ranges, many other character ranges contain digits as well. Syntax: public static boolean isDigit(int codePoint) Parameter: This method accepts unicode character parameter codePoint of integer type as an argument, which is to be tested. Return value: This method returns a boolean value. It returns True if the specified character is digit, else it returns False. Below programs illustrate the above method:Program 1: // This program demonstrates the use of// isDigit(int codePoint) method of Character class.import java.util.*; public class GFG { public static void main(String[] args) { // create codePoints int cp1 = 57; int cp2 = 84; // Check whether the codePoints // are digit or not. System.out.println( "The codePoint cp1 is a digit -> " + Character.isDigit(cp1)); System.out.println( "The codePoint cp2 is a digit -> " + Character.isDigit(cp2)); }} The codePoint cp1 is a digit -> true The codePoint cp2 is a digit -> false Program 2: // This program demonstrates the use of// isDigit(int codePoint) method of// Character class.import java.util.*; public class Main { public static void main(String[] args) { // create codePoints int cp1 = 0x50; int cp2 = 0x06f8; // Check whether the codePoints // are digit or not. System.out.println( "The codePoint cp1 is a digit -> " + Character.isDigit(cp1)); System.out.println( "The codePoint cp2 is a digit -> " + Character.isDigit(cp2)); }} The codePoint cp1 is a digit -> false The codePoint cp2 is a digit -> true Reference: https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html#isDigit-char- Java-Functions Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Initialize an ArrayList in Java HashMap in Java with Examples Interfaces in Java Object Oriented Programming (OOPs) Concept in Java ArrayList in Java How to iterate any Map in Java Multidimensional Arrays in Java LinkedList in Java Stack Class in Java Overriding in Java
[ { "code": null, "e": 25054, "s": 25026, "text": "\n17 May, 2020" }, { "code": null, "e": 30575, "s": 25054, "text": "The java.lang.Character.isDigit(char ch) is an inbuilt method in java which determines whether a specified character is a digit or not. There are few conditions that a character must accomplish to be accepted as a digit. That is if the general category type of a character, provided by Character.getType(ch), is DECIMAL_DIGIT_NUMBER, then the character is a digit.Some Unicode character ranges that contain digits:From ‘\\u0030’ to ‘\\u0039’ : ISO-LATIN-1 digits (‘0’ through ‘9’)From ‘\\u0660’ to ‘\\u0669’ : Arabic-Indic digitsFrom ‘\\u06F0’ to ‘\\u06F9’ : Extended Arabic-Indic digitsFrom ‘\\u0966’ to ‘\\u096F’ : Devanagari digitsFrom ‘\\uFF10’ to ‘\\uFF19’ : Fullwidth digitsApart from the above mentioned ranges, many other character ranges contain digits as well.Syntax:public static boolean isDigit(char ch)\nParameter: This method accepts character parameter ch as an argument, which is to be tested.Return value:This method returns a boolean value. It returns True if ch is digit, else False.Note: This method cannot handle supplementary characters. To support all Unicode characters, including supplementary characters, use the isDigit(int) method.Below programs illustrate the above method:Program 1:// Java program to illustrate the// Character.isDigit() method import java.util.*;import java.lang.*; public class GFG { public static void main(String[] args) { // two characters char c1 = 'A', c2 = '4'; // Function to check if the character // is digit or not System.out.println( c1 + \" is a digit -> \" + Character.isDigit(c1)); System.out.println( c2 + \" is a digit -> \" + Character.isDigit(c2)); }}Output:A is a digit -> false\n4 is a digit -> true\nProgram 2:// Java program to illustrate the// Character.isDigit() method import java.util.*;import java.lang.*; public class GFG { public static int search_digit(String s) { // Function to check if is digit // is found or not for (int i = 0; i < s.length(); i++) { if (Character.isDigit( s.charAt(i)) == true) { // return position of digit return i + 1; } } // return 0 if digit not present return 0; } public static void main(String[] args) { // Array of strings String[] arr = { \"ABC4DEF\", \"QWERTY\" }; // To store the position of digit int index = 0; // Traverse the array arr[] to find digit // within it's elements for (String x : arr) { index = search_digit(x); if (index != 0) { System.out.println( \"Digit found at : \" + (index) + \"th position.\"); } else { System.out.println( \"Digit not present.\"); } } }}Output:Digit found at : 4th position.\nDigit not present.\nThe java.lang.Character.isDigit(int codePoint) is an inbuilt method in java which determines whether the specified Unicode code point character of integer type is a digit or not.There are few conditions that a character must accomplish to be accepted as a digit. That is if the general category type of a character, provided by getType(codepoint), is a DECIMAL_DIGIT_NUMBER, then the character is a digit. Some Unicode character ranges that contain digits:From ‘\\u0030’ to ‘\\u0039’ : ISO-LATIN-1 digits (‘0’ through ‘9’)From ‘\\u0660’ to ‘\\u0669’ : Arabic-Indic digitsFrom ‘\\u06F0’ to ‘\\u06F9’ : Extended Arabic-Indic digitsFrom ‘\\u0966’ to ‘\\u096F’ : Devanagari digitsFrom ‘\\uFF10’ to ‘\\uFF19’ : Fullwidth digitsApart from the above mentioned ranges, many other character ranges contain digits as well.Syntax:public static boolean isDigit(int codePoint)\nParameter: This method accepts unicode character parameter codePoint of integer type as an argument, which is to be tested.Return value: This method returns a boolean value. It returns True if the specified character is digit, else it returns False.Below programs illustrate the above method:Program 1:// This program demonstrates the use of// isDigit(int codePoint) method of Character class.import java.util.*; public class GFG { public static void main(String[] args) { // create codePoints int cp1 = 57; int cp2 = 84; // Check whether the codePoints // are digit or not. System.out.println( \"The codePoint cp1 is a digit -> \" + Character.isDigit(cp1)); System.out.println( \"The codePoint cp2 is a digit -> \" + Character.isDigit(cp2)); }}Output:The codePoint cp1 is a digit -> true\nThe codePoint cp2 is a digit -> false\nProgram 2:// This program demonstrates the use of// isDigit(int codePoint) method of// Character class.import java.util.*; public class Main { public static void main(String[] args) { // create codePoints int cp1 = 0x50; int cp2 = 0x06f8; // Check whether the codePoints // are digit or not. System.out.println( \"The codePoint cp1 is a digit -> \" + Character.isDigit(cp1)); System.out.println( \"The codePoint cp2 is a digit -> \" + Character.isDigit(cp2)); }}Output:The codePoint cp1 is a digit -> false\nThe codePoint cp2 is a digit -> true\nReference: https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html#isDigit-char-" }, { "code": null, "e": 33578, "s": 30575, "text": "The java.lang.Character.isDigit(char ch) is an inbuilt method in java which determines whether a specified character is a digit or not. There are few conditions that a character must accomplish to be accepted as a digit. That is if the general category type of a character, provided by Character.getType(ch), is DECIMAL_DIGIT_NUMBER, then the character is a digit.Some Unicode character ranges that contain digits:From ‘\\u0030’ to ‘\\u0039’ : ISO-LATIN-1 digits (‘0’ through ‘9’)From ‘\\u0660’ to ‘\\u0669’ : Arabic-Indic digitsFrom ‘\\u06F0’ to ‘\\u06F9’ : Extended Arabic-Indic digitsFrom ‘\\u0966’ to ‘\\u096F’ : Devanagari digitsFrom ‘\\uFF10’ to ‘\\uFF19’ : Fullwidth digitsApart from the above mentioned ranges, many other character ranges contain digits as well.Syntax:public static boolean isDigit(char ch)\nParameter: This method accepts character parameter ch as an argument, which is to be tested.Return value:This method returns a boolean value. It returns True if ch is digit, else False.Note: This method cannot handle supplementary characters. To support all Unicode characters, including supplementary characters, use the isDigit(int) method.Below programs illustrate the above method:Program 1:// Java program to illustrate the// Character.isDigit() method import java.util.*;import java.lang.*; public class GFG { public static void main(String[] args) { // two characters char c1 = 'A', c2 = '4'; // Function to check if the character // is digit or not System.out.println( c1 + \" is a digit -> \" + Character.isDigit(c1)); System.out.println( c2 + \" is a digit -> \" + Character.isDigit(c2)); }}Output:A is a digit -> false\n4 is a digit -> true\nProgram 2:// Java program to illustrate the// Character.isDigit() method import java.util.*;import java.lang.*; public class GFG { public static int search_digit(String s) { // Function to check if is digit // is found or not for (int i = 0; i < s.length(); i++) { if (Character.isDigit( s.charAt(i)) == true) { // return position of digit return i + 1; } } // return 0 if digit not present return 0; } public static void main(String[] args) { // Array of strings String[] arr = { \"ABC4DEF\", \"QWERTY\" }; // To store the position of digit int index = 0; // Traverse the array arr[] to find digit // within it's elements for (String x : arr) { index = search_digit(x); if (index != 0) { System.out.println( \"Digit found at : \" + (index) + \"th position.\"); } else { System.out.println( \"Digit not present.\"); } } }}Output:Digit found at : 4th position.\nDigit not present.\n" }, { "code": null, "e": 33835, "s": 33578, "text": "From ‘\\u0030’ to ‘\\u0039’ : ISO-LATIN-1 digits (‘0’ through ‘9’)From ‘\\u0660’ to ‘\\u0669’ : Arabic-Indic digitsFrom ‘\\u06F0’ to ‘\\u06F9’ : Extended Arabic-Indic digitsFrom ‘\\u0966’ to ‘\\u096F’ : Devanagari digitsFrom ‘\\uFF10’ to ‘\\uFF19’ : Fullwidth digits" }, { "code": null, "e": 33926, "s": 33835, "text": "Apart from the above mentioned ranges, many other character ranges contain digits as well." }, { "code": null, "e": 33934, "s": 33926, "text": "Syntax:" }, { "code": null, "e": 33974, "s": 33934, "text": "public static boolean isDigit(char ch)\n" }, { "code": null, "e": 34067, "s": 33974, "text": "Parameter: This method accepts character parameter ch as an argument, which is to be tested." }, { "code": null, "e": 34161, "s": 34067, "text": "Return value:This method returns a boolean value. It returns True if ch is digit, else False." }, { "code": null, "e": 34319, "s": 34161, "text": "Note: This method cannot handle supplementary characters. To support all Unicode characters, including supplementary characters, use the isDigit(int) method." }, { "code": null, "e": 34373, "s": 34319, "text": "Below programs illustrate the above method:Program 1:" }, { "code": "// Java program to illustrate the// Character.isDigit() method import java.util.*;import java.lang.*; public class GFG { public static void main(String[] args) { // two characters char c1 = 'A', c2 = '4'; // Function to check if the character // is digit or not System.out.println( c1 + \" is a digit -> \" + Character.isDigit(c1)); System.out.println( c2 + \" is a digit -> \" + Character.isDigit(c2)); }}", "e": 34879, "s": 34373, "text": null }, { "code": null, "e": 34923, "s": 34879, "text": "A is a digit -> false\n4 is a digit -> true\n" }, { "code": null, "e": 34934, "s": 34923, "text": "Program 2:" }, { "code": "// Java program to illustrate the// Character.isDigit() method import java.util.*;import java.lang.*; public class GFG { public static int search_digit(String s) { // Function to check if is digit // is found or not for (int i = 0; i < s.length(); i++) { if (Character.isDigit( s.charAt(i)) == true) { // return position of digit return i + 1; } } // return 0 if digit not present return 0; } public static void main(String[] args) { // Array of strings String[] arr = { \"ABC4DEF\", \"QWERTY\" }; // To store the position of digit int index = 0; // Traverse the array arr[] to find digit // within it's elements for (String x : arr) { index = search_digit(x); if (index != 0) { System.out.println( \"Digit found at : \" + (index) + \"th position.\"); } else { System.out.println( \"Digit not present.\"); } } }}", "e": 36114, "s": 34934, "text": null }, { "code": null, "e": 36165, "s": 36114, "text": "Digit found at : 4th position.\nDigit not present.\n" }, { "code": null, "e": 38684, "s": 36165, "text": "The java.lang.Character.isDigit(int codePoint) is an inbuilt method in java which determines whether the specified Unicode code point character of integer type is a digit or not.There are few conditions that a character must accomplish to be accepted as a digit. That is if the general category type of a character, provided by getType(codepoint), is a DECIMAL_DIGIT_NUMBER, then the character is a digit. Some Unicode character ranges that contain digits:From ‘\\u0030’ to ‘\\u0039’ : ISO-LATIN-1 digits (‘0’ through ‘9’)From ‘\\u0660’ to ‘\\u0669’ : Arabic-Indic digitsFrom ‘\\u06F0’ to ‘\\u06F9’ : Extended Arabic-Indic digitsFrom ‘\\u0966’ to ‘\\u096F’ : Devanagari digitsFrom ‘\\uFF10’ to ‘\\uFF19’ : Fullwidth digitsApart from the above mentioned ranges, many other character ranges contain digits as well.Syntax:public static boolean isDigit(int codePoint)\nParameter: This method accepts unicode character parameter codePoint of integer type as an argument, which is to be tested.Return value: This method returns a boolean value. It returns True if the specified character is digit, else it returns False.Below programs illustrate the above method:Program 1:// This program demonstrates the use of// isDigit(int codePoint) method of Character class.import java.util.*; public class GFG { public static void main(String[] args) { // create codePoints int cp1 = 57; int cp2 = 84; // Check whether the codePoints // are digit or not. System.out.println( \"The codePoint cp1 is a digit -> \" + Character.isDigit(cp1)); System.out.println( \"The codePoint cp2 is a digit -> \" + Character.isDigit(cp2)); }}Output:The codePoint cp1 is a digit -> true\nThe codePoint cp2 is a digit -> false\nProgram 2:// This program demonstrates the use of// isDigit(int codePoint) method of// Character class.import java.util.*; public class Main { public static void main(String[] args) { // create codePoints int cp1 = 0x50; int cp2 = 0x06f8; // Check whether the codePoints // are digit or not. System.out.println( \"The codePoint cp1 is a digit -> \" + Character.isDigit(cp1)); System.out.println( \"The codePoint cp2 is a digit -> \" + Character.isDigit(cp2)); }}Output:The codePoint cp1 is a digit -> false\nThe codePoint cp2 is a digit -> true\nReference: https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html#isDigit-char-" }, { "code": null, "e": 38941, "s": 38684, "text": "From ‘\\u0030’ to ‘\\u0039’ : ISO-LATIN-1 digits (‘0’ through ‘9’)From ‘\\u0660’ to ‘\\u0669’ : Arabic-Indic digitsFrom ‘\\u06F0’ to ‘\\u06F9’ : Extended Arabic-Indic digitsFrom ‘\\u0966’ to ‘\\u096F’ : Devanagari digitsFrom ‘\\uFF10’ to ‘\\uFF19’ : Fullwidth digits" }, { "code": null, "e": 39032, "s": 38941, "text": "Apart from the above mentioned ranges, many other character ranges contain digits as well." }, { "code": null, "e": 39040, "s": 39032, "text": "Syntax:" }, { "code": null, "e": 39086, "s": 39040, "text": "public static boolean isDigit(int codePoint)\n" }, { "code": null, "e": 39210, "s": 39086, "text": "Parameter: This method accepts unicode character parameter codePoint of integer type as an argument, which is to be tested." }, { "code": null, "e": 39337, "s": 39210, "text": "Return value: This method returns a boolean value. It returns True if the specified character is digit, else it returns False." }, { "code": null, "e": 39391, "s": 39337, "text": "Below programs illustrate the above method:Program 1:" }, { "code": "// This program demonstrates the use of// isDigit(int codePoint) method of Character class.import java.util.*; public class GFG { public static void main(String[] args) { // create codePoints int cp1 = 57; int cp2 = 84; // Check whether the codePoints // are digit or not. System.out.println( \"The codePoint cp1 is a digit -> \" + Character.isDigit(cp1)); System.out.println( \"The codePoint cp2 is a digit -> \" + Character.isDigit(cp2)); }}", "e": 39936, "s": 39391, "text": null }, { "code": null, "e": 40012, "s": 39936, "text": "The codePoint cp1 is a digit -> true\nThe codePoint cp2 is a digit -> false\n" }, { "code": null, "e": 40023, "s": 40012, "text": "Program 2:" }, { "code": "// This program demonstrates the use of// isDigit(int codePoint) method of// Character class.import java.util.*; public class Main { public static void main(String[] args) { // create codePoints int cp1 = 0x50; int cp2 = 0x06f8; // Check whether the codePoints // are digit or not. System.out.println( \"The codePoint cp1 is a digit -> \" + Character.isDigit(cp1)); System.out.println( \"The codePoint cp2 is a digit -> \" + Character.isDigit(cp2)); }}", "e": 40577, "s": 40023, "text": null }, { "code": null, "e": 40653, "s": 40577, "text": "The codePoint cp1 is a digit -> false\nThe codePoint cp2 is a digit -> true\n" }, { "code": null, "e": 40745, "s": 40653, "text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html#isDigit-char-" }, { "code": null, "e": 40760, "s": 40745, "text": "Java-Functions" }, { "code": null, "e": 40765, "s": 40760, "text": "Java" }, { "code": null, "e": 40770, "s": 40765, "text": "Java" }, { "code": null, "e": 40868, "s": 40770, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40877, "s": 40868, "text": "Comments" }, { "code": null, "e": 40890, "s": 40877, "text": "Old Comments" }, { "code": null, "e": 40922, "s": 40890, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 40952, "s": 40922, "text": "HashMap in Java with Examples" }, { "code": null, "e": 40971, "s": 40952, "text": "Interfaces in Java" }, { "code": null, "e": 41022, "s": 40971, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 41040, "s": 41022, "text": "ArrayList in Java" }, { "code": null, "e": 41071, "s": 41040, "text": "How to iterate any Map in Java" }, { "code": null, "e": 41103, "s": 41071, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 41122, "s": 41103, "text": "LinkedList in Java" }, { "code": null, "e": 41142, "s": 41122, "text": "Stack Class in Java" } ]
C# | Remove all elements of a List that match the conditions defined by the predicate - GeeksforGeeks
01 Feb, 2019 List<T>.RemoveAll(Predicate<T>) Method is used to remove all the elements that match the conditions defined by the specified predicate. Properties of List: It is different from the arrays. A list can be resized dynamically but arrays cannot. List class can accept null as a valid value for reference types and it also allows duplicate elements. If the Count becomes equals to Capacity then the capacity of the List increases automatically by reallocating the internal array. The existing elements will be copied to the new array before the addition of the new element. Syntax: public int RemoveAll (Predicate<T> match); Parameter: match: It is the Predicate<T> delegate that defines the conditions of the elements which is to be removed. Return Value: This method returns the number of elements that to be remove from the List<T>. Exception: This method will give ArgumentNullException if the match is null. Below programs illustrate the use of List<T>.RemoveAll(Predicate<T>) Method: Example 1: // C# Program to remove all elements of// a List that match the conditions// defined by the predicateusing System;using System.Collections;using System.Collections.Generic; class Geeks { // function which checks whether an // element is even or not. Or you can // say it is the specified condition private static bool isEven(int i) { return ((i % 2) == 0); } // Main Method public static void Main(String[] args) { // Creating an List<T> of Integers List<int> firstlist = new List<int>(); // Adding elements to List for (int i = 1; i <= 10; i++) { firstlist.Add(i); } Console.WriteLine("Elements Present in List:\n"); // Displaying the elements of List foreach (int k in firstlist) { Console.WriteLine(k); } Console.WriteLine(" "); Console.Write("Number of Elements Removed: "); // Removing the elements which is even // This will return 5 as it removed 5 // even elements from the list Console.WriteLine(firstlist.RemoveAll(isEven)); Console.WriteLine(" "); Console.WriteLine("Remaining Elements in List:"); // Displaying the elements of List foreach (int k in firstlist) { Console.WriteLine(k); } }} Output: Elements Present in List: 1 2 3 4 5 6 7 8 9 10 Number of Elements Removed: 5 Remaining Elements in List: 1 3 5 7 9 Example 2: // C# Program to remove all elements of// a List that match the conditions// defined by the predicateusing System;using System.Collections;using System.Collections.Generic; class Geeks { // function which checks whether an // element is even or not. Or you can // say it is the specified condition private static bool isEven(int i) { return ((i % 2) == 0); } // Main Method public static void Main(String[] args) { // Creating an List<T> of Integers List<int> firstlist = new List<int>(); // Adding items to List firstlist.Add(13); firstlist.Add(17); firstlist.Add(19); firstlist.Add(11); Console.WriteLine("Elements Present in List:\n"); // Displaying the elements of List foreach(int k in firstlist) { Console.WriteLine(k); } Console.WriteLine(" "); Console.Write("Number of Elements Removed: "); // Removing the elements which is even // This will return 0 as it no elements // are even in List Console.WriteLine(firstlist.RemoveAll(isEven)); Console.WriteLine(" "); Console.WriteLine("Remaining Elements in List:"); // Displaying the elements of List foreach (int k in firstlist) { Console.WriteLine(k); } }} Output: Elements Present in List: 13 17 19 11 Number of Elements Removed: 0 Remaining Elements in List: 13 17 19 11 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.removeall?view=netframework-4.7.2 CSharp-Collections-Namespace CSharp-Generic-List CSharp-Generic-Namespace CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Method Overriding C# | Abstract Classes Difference between Ref and Out keywords in C# Extension Method in C# C# | Class and Object C# | Replace() Method C# | Constructors Introduction to .NET Framework
[ { "code": null, "e": 25989, "s": 25961, "text": "\n01 Feb, 2019" }, { "code": null, "e": 26125, "s": 25989, "text": "List<T>.RemoveAll(Predicate<T>) Method is used to remove all the elements that match the conditions defined by the specified predicate." }, { "code": null, "e": 26145, "s": 26125, "text": "Properties of List:" }, { "code": null, "e": 26231, "s": 26145, "text": "It is different from the arrays. A list can be resized dynamically but arrays cannot." }, { "code": null, "e": 26334, "s": 26231, "text": "List class can accept null as a valid value for reference types and it also allows duplicate elements." }, { "code": null, "e": 26558, "s": 26334, "text": "If the Count becomes equals to Capacity then the capacity of the List increases automatically by reallocating the internal array. The existing elements will be copied to the new array before the addition of the new element." }, { "code": null, "e": 26566, "s": 26558, "text": "Syntax:" }, { "code": null, "e": 26609, "s": 26566, "text": "public int RemoveAll (Predicate<T> match);" }, { "code": null, "e": 26620, "s": 26609, "text": "Parameter:" }, { "code": null, "e": 26727, "s": 26620, "text": "match: It is the Predicate<T> delegate that defines the conditions of the elements which is to be removed." }, { "code": null, "e": 26820, "s": 26727, "text": "Return Value: This method returns the number of elements that to be remove from the List<T>." }, { "code": null, "e": 26897, "s": 26820, "text": "Exception: This method will give ArgumentNullException if the match is null." }, { "code": null, "e": 26974, "s": 26897, "text": "Below programs illustrate the use of List<T>.RemoveAll(Predicate<T>) Method:" }, { "code": null, "e": 26985, "s": 26974, "text": "Example 1:" }, { "code": "// C# Program to remove all elements of// a List that match the conditions// defined by the predicateusing System;using System.Collections;using System.Collections.Generic; class Geeks { // function which checks whether an // element is even or not. Or you can // say it is the specified condition private static bool isEven(int i) { return ((i % 2) == 0); } // Main Method public static void Main(String[] args) { // Creating an List<T> of Integers List<int> firstlist = new List<int>(); // Adding elements to List for (int i = 1; i <= 10; i++) { firstlist.Add(i); } Console.WriteLine(\"Elements Present in List:\\n\"); // Displaying the elements of List foreach (int k in firstlist) { Console.WriteLine(k); } Console.WriteLine(\" \"); Console.Write(\"Number of Elements Removed: \"); // Removing the elements which is even // This will return 5 as it removed 5 // even elements from the list Console.WriteLine(firstlist.RemoveAll(isEven)); Console.WriteLine(\" \"); Console.WriteLine(\"Remaining Elements in List:\"); // Displaying the elements of List foreach (int k in firstlist) { Console.WriteLine(k); } }}", "e": 28336, "s": 26985, "text": null }, { "code": null, "e": 28344, "s": 28336, "text": "Output:" }, { "code": null, "e": 28465, "s": 28344, "text": "Elements Present in List:\n\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n \nNumber of Elements Removed: 5\n \nRemaining Elements in List:\n1\n3\n5\n7\n9\n" }, { "code": null, "e": 28476, "s": 28465, "text": "Example 2:" }, { "code": "// C# Program to remove all elements of// a List that match the conditions// defined by the predicateusing System;using System.Collections;using System.Collections.Generic; class Geeks { // function which checks whether an // element is even or not. Or you can // say it is the specified condition private static bool isEven(int i) { return ((i % 2) == 0); } // Main Method public static void Main(String[] args) { // Creating an List<T> of Integers List<int> firstlist = new List<int>(); // Adding items to List firstlist.Add(13); firstlist.Add(17); firstlist.Add(19); firstlist.Add(11); Console.WriteLine(\"Elements Present in List:\\n\"); // Displaying the elements of List foreach(int k in firstlist) { Console.WriteLine(k); } Console.WriteLine(\" \"); Console.Write(\"Number of Elements Removed: \"); // Removing the elements which is even // This will return 0 as it no elements // are even in List Console.WriteLine(firstlist.RemoveAll(isEven)); Console.WriteLine(\" \"); Console.WriteLine(\"Remaining Elements in List:\"); // Displaying the elements of List foreach (int k in firstlist) { Console.WriteLine(k); } }}", "e": 29841, "s": 28476, "text": null }, { "code": null, "e": 29849, "s": 29841, "text": "Output:" }, { "code": null, "e": 29963, "s": 29849, "text": "Elements Present in List:\n\n13\n17\n19\n11\n \nNumber of Elements Removed: 0\n \nRemaining Elements in List:\n13\n17\n19\n11\n" }, { "code": null, "e": 29974, "s": 29963, "text": "Reference:" }, { "code": null, "e": 30086, "s": 29974, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.removeall?view=netframework-4.7.2" }, { "code": null, "e": 30115, "s": 30086, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 30135, "s": 30115, "text": "CSharp-Generic-List" }, { "code": null, "e": 30160, "s": 30135, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 30174, "s": 30160, "text": "CSharp-method" }, { "code": null, "e": 30177, "s": 30174, "text": "C#" }, { "code": null, "e": 30275, "s": 30177, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30303, "s": 30275, "text": "C# Dictionary with examples" }, { "code": null, "e": 30318, "s": 30303, "text": "C# | Delegates" }, { "code": null, "e": 30341, "s": 30318, "text": "C# | Method Overriding" }, { "code": null, "e": 30363, "s": 30341, "text": "C# | Abstract Classes" }, { "code": null, "e": 30409, "s": 30363, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 30432, "s": 30409, "text": "Extension Method in C#" }, { "code": null, "e": 30454, "s": 30432, "text": "C# | Class and Object" }, { "code": null, "e": 30476, "s": 30454, "text": "C# | Replace() Method" }, { "code": null, "e": 30494, "s": 30476, "text": "C# | Constructors" } ]
Angular PrimeNG Dialog Component - GeeksforGeeks
07 Oct, 2021 Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Dialog component in Angular PrimeNG. We will also learn about the properties, events & styling along with their syntaxes that will be used in the code. Dialog component: It is used to make a component containing some content to display in an overlay window. Properties: header: It is the title text of the dialog. It is of string data type, the default value is null. draggable: It enables dragging to change the position using a header. It is of the boolean data type, the default value is true. keepInViewport: It is used to keeps dialog in the viewport. It is of boolean data type, the default value is true. resizable: It enables resizing of the content. It is of boolean data type, the default value is true. contentStyle: It is used to set the style of the content section. It is of object data type, the default value is null. visible: It specifies the visibility of the dialog. It is of the boolean data type, the default value is false. modal: It is used to defines if the background should be blocked when dialog is displayed. It is of the boolean data type, the default value is false. position: It is used to set the position of the dialog. It is of string data type, the default value is center. blockScroll: It is used to specify whether background scroll should be blocked when dialog is visible. It is of the boolean data type, the default value is false. closeOnEscape: It is used to specify if pressing the escape key should hide the dialog. It is of boolean data type, the default value is true. dismissableMask: It is used to specify if clicking the modal background should hide the dialog. It is of boolean data type, the default value is false. rtl: When the enabled dialog is displayed in the RTL direction. It is of boolean data type, the default value is false. closable: It is used to set the close icon to the header to hide the dialog. It is of boolean data type, the default value is true. appendTo: It is used to set the Target element to attach the dialog, valid values are “body” or a local ng-template variable of another element. It accepts any data type, the default value is null. style: It is used to set the inline style of the component. It is of object data type, the default value is null. styleClass: It is used to set the style class of the component. It is of string data type, the default value is null. maskStyleClass: It is used to set the style class of the mask. It is of string data type, the default value is null. contentStyle: It is used to set the Inline style of the content. It is of object data type, the default value is null. contentStyleClass: It is used to set the style class of the content. It is of string data type, the default value is null. showHeader: It is used to specify whether to show the header or not. It is of boolean datatype, the default value is true. baseZIndex: It is used to set the base zIndex value to use in layering. It is of number datatype, the default value is 0. autoZIndex: It is used to specify whether to automatically manage layering. It is of boolean datatype, the default value is true. minX: It is used to set the minimum value for the left coordinate of dialog in dragging. It is of number data type, the default value is 0. minY: It is used to set the minimum value for the top coordinate of dialog in dragging. It is of number data type, the default value is 0. focusOnShow: It is used to specify first button receives focus on show. It is of the boolean data type, the default value is true. focusTrap: It is used to specify whether elements can only focus on elements inside the dialog. It is of the boolean datatype, the default value is true. maximizable: It is used to specify whether the dialog can be displayed full screen. It is of the boolean data type, the default value is false. breakpoints: It is the object literal to define widths per screen size. It is of object data type, default Value is null. transitionOptions: It is used to set the transition options of the animation. It is of string data type, the default value is 150ms cubic-bezier(0, 0, 0.2, 1). closeIcon: It is used to set the name of the close icon. It is of string data type, the default value is null. minimizeIcon: It is used to set the name of the minimize icon. It is of string data type, the default value is pi pi-window-minimize. maximizeIcon: It is used to set the name of the maximize icon. It is of string data type, the default value is pi pi-window-maximize. Events: onShow: It is a callback that is fired when the dialog is shown. onHide: It is a callback that is fired when dialog is hidden. onResizeInit: It is a callback that is fired when dialog resizing is initiated. onResizeEnd: It is a callback that is fired when dialog resizing is completed. onDragEnd: It is a callback that is fired when dialog dragging is completed. onMaximize: It is a callback that is fired when dialog is maximized or unmaximized. Styling: p-dialog: It is the container element. p-dialog-titlebar: It is the container of the header. p-dialog-title: It is the header element. p-dialog-titlebar-icon: It is the icon container inside the header. p-dialog-titlebar-close: It is the close icon element. p-dialog-content: It is the content element. p-dialog-footer: It is the footer element. Creating Angular application & module installation: Step 1: Create an Angular application using the following command. ng new appname Step 2: After creating your project folder i.e. appname, move to it using the following command. cd appname Step 3: Install PrimeNG in your given directory. npm install primeng --save npm install primeicons --save Project Structure: It will look like the following: Example 1: This is the basic example that shows how to use the Dialog component. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG Dialog Component</h5><p-button (click)="gfg()" label="Click Here"></p-button><p-dialog header="GeeksforGeeks" [(visible)]="geeks"> <p>Angular PrimeNG Dialog Component</p> </p-dialog> app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { DialogModule } from "primeng/dialog";import { ButtonModule } from "primeng/button"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, DialogModule, ButtonModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} app.component.ts import { Component } from "@angular/core";import { PrimeNGConfig } from "primeng/api"; @Component({ selector: "my-app", templateUrl: "./app.component.html",})export class AppComponent { constructor(private primengConfig: PrimeNGConfig) {} ngOnInit() { this.primengConfig.ripple = true; } geeks: boolean; gfg() { this.geeks = true; }} Output: Example 2: In this example, we will know how to use the position property in the Dialog component. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG Dialog Component</h5><p-button (click)="gfg()" label="Click Here"></p-button><p-dialog position="top" header="GeeksforGeeks" [(visible)]="geeks"> <p>Angular PrimeNG Dialog Component</p> </p-dialog> app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { DialogModule } from "primeng/dialog";import { ButtonModule } from "primeng/button"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, DialogModule, ButtonModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} app.component.ts import { Component } from "@angular/core";import { PrimeNGConfig } from "primeng/api"; @Component({ selector: "my-app", templateUrl: "./app.component.html",})export class AppComponent { constructor(private primengConfig: PrimeNGConfig) {} ngOnInit() { this.primengConfig.ripple = true; } geeks: boolean; gfg() { this.geeks = true; }} Output: Example 3: In this example, we will know how to use the visible, modal, resizable & draggable properties in the Dialog component that will help to make the modal to drag & resize. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG Dialog Component</h5><h6>Modal</h6><p-button (click)="gfg()" icon="pi pi-external-link" label="View"> </p-button> <p-dialog header="About GeeksforGeeks" [(visible)]="geeks" [modal]="true" [draggable]="true" [resizable]="true"> <p class="p-m-0"> A Computer Science portal for geeks. It contains well written, well thought and well-explained computer science and programming articles. With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. </p> <ng-template pTemplate="footer"> <p-button icon="pi pi-check" (click)="geeks=false" label="OK" class="p-button-text"> </p-button> </ng-template></p-dialog> app.component.ts import { Component } from "@angular/core";import { PrimeNGConfig } from "primeng/api"; @Component({ selector: "my-app", templateUrl: "./app.component.html",})export class AppComponent { constructor(private primengConfig: PrimeNGConfig) {} ngOnInit() { this.primengConfig.ripple = true; } displayModal: boolean; displayModalDialog() { this.displayModal = true; }} app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { DialogModule } from "primeng/dialog";import { ButtonModule } from "primeng/button"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, DialogModule, ButtonModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} Output: Reference: https://primefaces.org/primeng/showcase/#/dialog Angular-PrimeNG AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular PrimeNG Messages Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26488, "s": 26460, "text": "\n07 Oct, 2021" }, { "code": null, "e": 26887, "s": 26488, "text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Dialog component in Angular PrimeNG. We will also learn about the properties, events & styling along with their syntaxes that will be used in the code. " }, { "code": null, "e": 26993, "s": 26887, "text": "Dialog component: It is used to make a component containing some content to display in an overlay window." }, { "code": null, "e": 27005, "s": 26993, "text": "Properties:" }, { "code": null, "e": 27103, "s": 27005, "text": "header: It is the title text of the dialog. It is of string data type, the default value is null." }, { "code": null, "e": 27232, "s": 27103, "text": "draggable: It enables dragging to change the position using a header. It is of the boolean data type, the default value is true." }, { "code": null, "e": 27347, "s": 27232, "text": "keepInViewport: It is used to keeps dialog in the viewport. It is of boolean data type, the default value is true." }, { "code": null, "e": 27449, "s": 27347, "text": "resizable: It enables resizing of the content. It is of boolean data type, the default value is true." }, { "code": null, "e": 27569, "s": 27449, "text": "contentStyle: It is used to set the style of the content section. It is of object data type, the default value is null." }, { "code": null, "e": 27681, "s": 27569, "text": "visible: It specifies the visibility of the dialog. It is of the boolean data type, the default value is false." }, { "code": null, "e": 27832, "s": 27681, "text": "modal: It is used to defines if the background should be blocked when dialog is displayed. It is of the boolean data type, the default value is false." }, { "code": null, "e": 27944, "s": 27832, "text": "position: It is used to set the position of the dialog. It is of string data type, the default value is center." }, { "code": null, "e": 28107, "s": 27944, "text": "blockScroll: It is used to specify whether background scroll should be blocked when dialog is visible. It is of the boolean data type, the default value is false." }, { "code": null, "e": 28250, "s": 28107, "text": "closeOnEscape: It is used to specify if pressing the escape key should hide the dialog. It is of boolean data type, the default value is true." }, { "code": null, "e": 28402, "s": 28250, "text": "dismissableMask: It is used to specify if clicking the modal background should hide the dialog. It is of boolean data type, the default value is false." }, { "code": null, "e": 28522, "s": 28402, "text": "rtl: When the enabled dialog is displayed in the RTL direction. It is of boolean data type, the default value is false." }, { "code": null, "e": 28654, "s": 28522, "text": "closable: It is used to set the close icon to the header to hide the dialog. It is of boolean data type, the default value is true." }, { "code": null, "e": 28852, "s": 28654, "text": "appendTo: It is used to set the Target element to attach the dialog, valid values are “body” or a local ng-template variable of another element. It accepts any data type, the default value is null." }, { "code": null, "e": 28966, "s": 28852, "text": "style: It is used to set the inline style of the component. It is of object data type, the default value is null." }, { "code": null, "e": 29084, "s": 28966, "text": "styleClass: It is used to set the style class of the component. It is of string data type, the default value is null." }, { "code": null, "e": 29201, "s": 29084, "text": "maskStyleClass: It is used to set the style class of the mask. It is of string data type, the default value is null." }, { "code": null, "e": 29320, "s": 29201, "text": "contentStyle: It is used to set the Inline style of the content. It is of object data type, the default value is null." }, { "code": null, "e": 29443, "s": 29320, "text": "contentStyleClass: It is used to set the style class of the content. It is of string data type, the default value is null." }, { "code": null, "e": 29566, "s": 29443, "text": "showHeader: It is used to specify whether to show the header or not. It is of boolean datatype, the default value is true." }, { "code": null, "e": 29688, "s": 29566, "text": "baseZIndex: It is used to set the base zIndex value to use in layering. It is of number datatype, the default value is 0." }, { "code": null, "e": 29818, "s": 29688, "text": "autoZIndex: It is used to specify whether to automatically manage layering. It is of boolean datatype, the default value is true." }, { "code": null, "e": 29958, "s": 29818, "text": "minX: It is used to set the minimum value for the left coordinate of dialog in dragging. It is of number data type, the default value is 0." }, { "code": null, "e": 30097, "s": 29958, "text": "minY: It is used to set the minimum value for the top coordinate of dialog in dragging. It is of number data type, the default value is 0." }, { "code": null, "e": 30228, "s": 30097, "text": "focusOnShow: It is used to specify first button receives focus on show. It is of the boolean data type, the default value is true." }, { "code": null, "e": 30382, "s": 30228, "text": "focusTrap: It is used to specify whether elements can only focus on elements inside the dialog. It is of the boolean datatype, the default value is true." }, { "code": null, "e": 30526, "s": 30382, "text": "maximizable: It is used to specify whether the dialog can be displayed full screen. It is of the boolean data type, the default value is false." }, { "code": null, "e": 30648, "s": 30526, "text": "breakpoints: It is the object literal to define widths per screen size. It is of object data type, default Value is null." }, { "code": null, "e": 30808, "s": 30648, "text": "transitionOptions: It is used to set the transition options of the animation. It is of string data type, the default value is 150ms cubic-bezier(0, 0, 0.2, 1)." }, { "code": null, "e": 30919, "s": 30808, "text": "closeIcon: It is used to set the name of the close icon. It is of string data type, the default value is null." }, { "code": null, "e": 31053, "s": 30919, "text": "minimizeIcon: It is used to set the name of the minimize icon. It is of string data type, the default value is pi pi-window-minimize." }, { "code": null, "e": 31187, "s": 31053, "text": "maximizeIcon: It is used to set the name of the maximize icon. It is of string data type, the default value is pi pi-window-maximize." }, { "code": null, "e": 31195, "s": 31187, "text": "Events:" }, { "code": null, "e": 31260, "s": 31195, "text": "onShow: It is a callback that is fired when the dialog is shown." }, { "code": null, "e": 31322, "s": 31260, "text": "onHide: It is a callback that is fired when dialog is hidden." }, { "code": null, "e": 31402, "s": 31322, "text": "onResizeInit: It is a callback that is fired when dialog resizing is initiated." }, { "code": null, "e": 31481, "s": 31402, "text": "onResizeEnd: It is a callback that is fired when dialog resizing is completed." }, { "code": null, "e": 31558, "s": 31481, "text": "onDragEnd: It is a callback that is fired when dialog dragging is completed." }, { "code": null, "e": 31642, "s": 31558, "text": "onMaximize: It is a callback that is fired when dialog is maximized or unmaximized." }, { "code": null, "e": 31653, "s": 31644, "text": "Styling:" }, { "code": null, "e": 31692, "s": 31653, "text": "p-dialog: It is the container element." }, { "code": null, "e": 31746, "s": 31692, "text": "p-dialog-titlebar: It is the container of the header." }, { "code": null, "e": 31788, "s": 31746, "text": "p-dialog-title: It is the header element." }, { "code": null, "e": 31856, "s": 31788, "text": "p-dialog-titlebar-icon: It is the icon container inside the header." }, { "code": null, "e": 31911, "s": 31856, "text": "p-dialog-titlebar-close: It is the close icon element." }, { "code": null, "e": 31956, "s": 31911, "text": "p-dialog-content: It is the content element." }, { "code": null, "e": 31999, "s": 31956, "text": "p-dialog-footer: It is the footer element." }, { "code": null, "e": 32051, "s": 31999, "text": "Creating Angular application & module installation:" }, { "code": null, "e": 32118, "s": 32051, "text": "Step 1: Create an Angular application using the following command." }, { "code": null, "e": 32133, "s": 32118, "text": "ng new appname" }, { "code": null, "e": 32230, "s": 32133, "text": "Step 2: After creating your project folder i.e. appname, move to it using the following command." }, { "code": null, "e": 32241, "s": 32230, "text": "cd appname" }, { "code": null, "e": 32290, "s": 32241, "text": "Step 3: Install PrimeNG in your given directory." }, { "code": null, "e": 32347, "s": 32290, "text": "npm install primeng --save\nnpm install primeicons --save" }, { "code": null, "e": 32399, "s": 32347, "text": "Project Structure: It will look like the following:" }, { "code": null, "e": 32481, "s": 32399, "text": "Example 1: This is the basic example that shows how to use the Dialog component. " }, { "code": null, "e": 32500, "s": 32481, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG Dialog Component</h5><p-button (click)=\"gfg()\" label=\"Click Here\"></p-button><p-dialog header=\"GeeksforGeeks\" [(visible)]=\"geeks\"> <p>Angular PrimeNG Dialog Component</p> </p-dialog>", "e": 32721, "s": 32500, "text": null }, { "code": null, "e": 32735, "s": 32721, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { DialogModule } from \"primeng/dialog\";import { ButtonModule } from \"primeng/button\"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, DialogModule, ButtonModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 33276, "s": 32735, "text": null }, { "code": null, "e": 33295, "s": 33278, "text": "app.component.ts" }, { "code": "import { Component } from \"@angular/core\";import { PrimeNGConfig } from \"primeng/api\"; @Component({ selector: \"my-app\", templateUrl: \"./app.component.html\",})export class AppComponent { constructor(private primengConfig: PrimeNGConfig) {} ngOnInit() { this.primengConfig.ripple = true; } geeks: boolean; gfg() { this.geeks = true; }}", "e": 33650, "s": 33295, "text": null }, { "code": null, "e": 33658, "s": 33650, "text": "Output:" }, { "code": null, "e": 33757, "s": 33658, "text": "Example 2: In this example, we will know how to use the position property in the Dialog component." }, { "code": null, "e": 33776, "s": 33757, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG Dialog Component</h5><p-button (click)=\"gfg()\" label=\"Click Here\"></p-button><p-dialog position=\"top\" header=\"GeeksforGeeks\" [(visible)]=\"geeks\"> <p>Angular PrimeNG Dialog Component</p> </p-dialog>", "e": 34012, "s": 33776, "text": null }, { "code": null, "e": 34026, "s": 34012, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { DialogModule } from \"primeng/dialog\";import { ButtonModule } from \"primeng/button\"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, DialogModule, ButtonModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 34555, "s": 34026, "text": null }, { "code": null, "e": 34572, "s": 34555, "text": "app.component.ts" }, { "code": "import { Component } from \"@angular/core\";import { PrimeNGConfig } from \"primeng/api\"; @Component({ selector: \"my-app\", templateUrl: \"./app.component.html\",})export class AppComponent { constructor(private primengConfig: PrimeNGConfig) {} ngOnInit() { this.primengConfig.ripple = true; } geeks: boolean; gfg() { this.geeks = true; }}", "e": 34925, "s": 34572, "text": null }, { "code": null, "e": 34933, "s": 34925, "text": "Output:" }, { "code": null, "e": 35113, "s": 34933, "text": "Example 3: In this example, we will know how to use the visible, modal, resizable & draggable properties in the Dialog component that will help to make the modal to drag & resize." }, { "code": null, "e": 35132, "s": 35113, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG Dialog Component</h5><h6>Modal</h6><p-button (click)=\"gfg()\" icon=\"pi pi-external-link\" label=\"View\"> </p-button> <p-dialog header=\"About GeeksforGeeks\" [(visible)]=\"geeks\" [modal]=\"true\" [draggable]=\"true\" [resizable]=\"true\"> <p class=\"p-m-0\"> A Computer Science portal for geeks. It contains well written, well thought and well-explained computer science and programming articles. With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. </p> <ng-template pTemplate=\"footer\"> <p-button icon=\"pi pi-check\" (click)=\"geeks=false\" label=\"OK\" class=\"p-button-text\"> </p-button> </ng-template></p-dialog>", "e": 36180, "s": 35132, "text": null }, { "code": null, "e": 36197, "s": 36180, "text": "app.component.ts" }, { "code": "import { Component } from \"@angular/core\";import { PrimeNGConfig } from \"primeng/api\"; @Component({ selector: \"my-app\", templateUrl: \"./app.component.html\",})export class AppComponent { constructor(private primengConfig: PrimeNGConfig) {} ngOnInit() { this.primengConfig.ripple = true; } displayModal: boolean; displayModalDialog() { this.displayModal = true; }}", "e": 36579, "s": 36197, "text": null }, { "code": null, "e": 36593, "s": 36579, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { DialogModule } from \"primeng/dialog\";import { ButtonModule } from \"primeng/button\"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, DialogModule, ButtonModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 37122, "s": 36593, "text": null }, { "code": null, "e": 37130, "s": 37122, "text": "Output:" }, { "code": null, "e": 37190, "s": 37130, "text": "Reference: https://primefaces.org/primeng/showcase/#/dialog" }, { "code": null, "e": 37206, "s": 37190, "text": "Angular-PrimeNG" }, { "code": null, "e": 37216, "s": 37206, "text": "AngularJS" }, { "code": null, "e": 37233, "s": 37216, "text": "Web Technologies" }, { "code": null, "e": 37331, "s": 37233, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37366, "s": 37331, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 37401, "s": 37366, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 37436, "s": 37401, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 37460, "s": 37436, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 37513, "s": 37460, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 37553, "s": 37513, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 37586, "s": 37553, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 37631, "s": 37586, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 37674, "s": 37631, "text": "How to fetch data from an API in ReactJS ?" } ]
Maximum amount of money that can be collected by a player in a game of coins - GeeksforGeeks
08 Jun, 2021 Given a 2D array Arr[][] consisting of N rows and two persons A and B playing a game of alternate turns based on the following rules: A row is chosen at random, where A can only take the leftmost remaining coin while B can only take the rightmost remaining coin in the chosen row. The game ends when there are no coins left. The task is to determine the maximum amount of money obtained by A. Examples: Input: N = 2, Arr[][] = {{ 5, 2, 3, 4 }, { 1, 6 }}Output: 8Explanation: Row 1: 5, 2, 3, 4Row 2: 1, 6Operations: A takes the coin with value 5B takes the coin with value 4A takes the coin with value 2B takes the coin with value 3A takes the coin with value 1B takes the coin with value 6 A takes the coin with value 5 B takes the coin with value 4 A takes the coin with value 2 B takes the coin with value 3 A takes the coin with value 1 B takes the coin with value 6 Optimally, money collected by A = 5 + 2 + 1 = 8 Money collected by B = 3 + 4 + 6 = 13 Input: N = 1, Arr[] = {{ 1, 2, 3 }}Output : 3 Approach: Follow the steps below to solve the problem In a game played with optimal strategyInitialize a variable, say amount, to store the money obtained by A.If N is even, A will collect the first half of the coinsOtherwise, first, (N / 2) coins would be collected by A and last (N / 2) would be collected by BIf N is odd, the coin at the middle can be collected by A or B, depending upon the sequence of moves.Store the coin at the middle of all odd sized rows in a variable, say mid_odd[].Sort the array mid_odd[] in descending order.Optimally, A would collect all coins at even indices of min_odd[]Finally, print the score of A. In a game played with optimal strategy Initialize a variable, say amount, to store the money obtained by A. If N is even, A will collect the first half of the coins Otherwise, first, (N / 2) coins would be collected by A and last (N / 2) would be collected by B If N is odd, the coin at the middle can be collected by A or B, depending upon the sequence of moves. Store the coin at the middle of all odd sized rows in a variable, say mid_odd[]. Sort the array mid_odd[] in descending order. Optimally, A would collect all coins at even indices of min_odd[] Finally, print the score of A. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // CPP Program to implement// the above approach#include<bits/stdc++.h>using namespace std; // Function to calculate the// maximum amount collected by Avoid find(int N, vector<vector<int>>Arr){ // Stores the money // obtained by A int amount = 0; // Stores mid elements // of odd sized rows vector<int> mid_odd; for(int i = 0; i < N; i++) { // Size of current row int siz = Arr[i].size(); // Increase money collected by A for (int j = 0; j < siz / 2; j++) amount = amount + Arr[i][j]; if(siz % 2 == 1) mid_odd.push_back(Arr[i][siz/2]); } // Add coins at even indices // to the amount collected by A sort(mid_odd.begin(),mid_odd.end()); for(int i = 0; i < mid_odd.size(); i++) if (i % 2 == 0) amount = amount + mid_odd[i]; // Print the amount cout<<amount<<endl; } // Driver Codeint main(){ int N = 2; vector<vector<int>>Arr{{5, 2, 3, 4}, {1, 6}}; // Function call to calculate the // amount of coins collected by A find(N, Arr);} // This code is contributed by ipg2016107. // Java program to implement// the above approachimport java.util.*;class GFG{ // Function to calculate the// maximum amount collected by Astatic void find(int N, int[][] Arr){ // Stores the money // obtained by A int amount = 0; // Stores mid elements // of odd sized rows ArrayList<Integer> mid_odd = new ArrayList<Integer>(); for(int i = 0; i < N; i++) { // Size of current row int siz = Arr[i].length; // Increase money collected by A for (int j = 0; j < siz / 2; j++) amount = amount + Arr[i][j]; if(siz % 2 == 1) mid_odd.add(Arr[i][siz/2]); } // Add coins at even indices // to the amount collected by A Collections.sort(mid_odd); for(int i = 0; i < mid_odd.size(); i++){ if (i % 2 == 0) amount = amount + mid_odd.get(i); } // Print the amount System.out.println(amount);} // Driver Codepublic static void main(String[] args){ int N = 2; int[][] Arr = {{5, 2, 3, 4}, {1, 6}}; // Function call to calculate the // amount of coins collected by A find(N, Arr);}} // This code is contributed by splevel62. # Python Program to implement# the above approach # Function to calculate the# maximum amount collected by A def find(N, Arr): # Stores the money # obtained by A amount = 0 # Stores mid elements # of odd sized rows mid_odd = [] for i in range(N): # Size of current row siz = len(Arr[i]) # Increase money collected by A for j in range(0, siz // 2): amount = amount + Arr[i][j] if(siz % 2 == 1): mid_odd.append(Arr[i][siz // 2]) # Add coins at even indices # to the amount collected by A mid_odd.sort(reverse=True) for i in range(len(mid_odd)): if i % 2 == 0: amount = amount + mid_odd[i] # Print the amount print(amount) # Driver Code N = 2Arr = [[5, 2, 3, 4], [1, 6]] # Function call to calculate the# amount of coins collected by Afind(N, Arr) // C# Program to implement// the above approachusing System;using System.Collections.Generic;class GFG { // Function to calculate the // maximum amount collected by A static void find(int N, List<List<int>> Arr) { // Stores the money // obtained by A int amount = 0; // Stores mid elements // of odd sized rows List<int> mid_odd = new List<int>(); for(int i = 0; i < N; i++) { // Size of current row int siz = Arr[i].Count; // Increase money collected by A for (int j = 0; j < siz / 2; j++) amount = amount + Arr[i][j]; if(siz % 2 == 1) mid_odd.Add(Arr[i][siz/2]); } // Add coins at even indices // to the amount collected by A mid_odd.Sort(); for(int i = 0; i < mid_odd.Count; i++) if (i % 2 == 0) amount = amount + mid_odd[i]; // Print the amount Console.WriteLine(amount); } // Driver code static void Main() { int N = 2; List<List<int>> Arr = new List<List<int>>(); Arr.Add(new List<int>()); Arr[0].Add(5); Arr[0].Add(2); Arr[0].Add(3); Arr[0].Add(4); Arr.Add(new List<int>()); Arr[1].Add(1); Arr[1].Add(6); // Function call to calculate the // amount of coins collected by A find(N, Arr); }} // This code is contributed by divyesh072019. <script> // Javascript Program to implement// the above approach // Function to calculate the// maximum amount collected by Afunction find(N, Arr){ // Stores the money // obtained by A var amount = 0; // Stores mid elements // of odd sized rows var mid_odd = []; for(var i = 0; i < N; i++) { // Size of current row var siz = Arr[i].length; // Increase money collected by A for (var j = 0; j < siz / 2; j++) amount = amount + Arr[i][j]; if(siz % 2 == 1) mid_odd.push(Arr[i][siz/2]); } // Add coins at even indices // to the amount collected by A mid_odd.sort((a,b)=>a-b) for(var i = 0; i < mid_odd.length; i++) if (i % 2 == 0) amount = amount + mid_odd[i]; // Print the amount document.write( amount + "<br>"); } // Driver Codevar N = 2;var Arr = [[5, 2, 3, 4], [1, 6]]; // Function call to calculate the// amount of coins collected by Afind(N, Arr); // This code is contributed by importantly.</script> 8 Time Complexity : O(N)Auxiliary Space : O(1) ipg2016107 splevel62 divyesh072019 importantly adnanirshad158 Arrays Mathematical Pattern Searching Arrays Mathematical Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Window Sliding Technique Program to find sum of elements in a given array Reversal algorithm for array rotation Find duplicates in O(n) time and O(1) extra space | Set 1 Trapping Rain Water Program for Fibonacci numbers C++ Data Types Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 24740, "s": 24712, "text": "\n08 Jun, 2021" }, { "code": null, "e": 24874, "s": 24740, "text": "Given a 2D array Arr[][] consisting of N rows and two persons A and B playing a game of alternate turns based on the following rules:" }, { "code": null, "e": 25021, "s": 24874, "text": "A row is chosen at random, where A can only take the leftmost remaining coin while B can only take the rightmost remaining coin in the chosen row." }, { "code": null, "e": 25065, "s": 25021, "text": "The game ends when there are no coins left." }, { "code": null, "e": 25133, "s": 25065, "text": "The task is to determine the maximum amount of money obtained by A." }, { "code": null, "e": 25144, "s": 25133, "text": " Examples:" }, { "code": null, "e": 25256, "s": 25144, "text": "Input: N = 2, Arr[][] = {{ 5, 2, 3, 4 }, { 1, 6 }}Output: 8Explanation: Row 1: 5, 2, 3, 4Row 2: 1, 6Operations:" }, { "code": null, "e": 25431, "s": 25256, "text": "A takes the coin with value 5B takes the coin with value 4A takes the coin with value 2B takes the coin with value 3A takes the coin with value 1B takes the coin with value 6" }, { "code": null, "e": 25461, "s": 25431, "text": "A takes the coin with value 5" }, { "code": null, "e": 25491, "s": 25461, "text": "B takes the coin with value 4" }, { "code": null, "e": 25521, "s": 25491, "text": "A takes the coin with value 2" }, { "code": null, "e": 25551, "s": 25521, "text": "B takes the coin with value 3" }, { "code": null, "e": 25581, "s": 25551, "text": "A takes the coin with value 1" }, { "code": null, "e": 25611, "s": 25581, "text": "B takes the coin with value 6" }, { "code": null, "e": 25697, "s": 25611, "text": "Optimally, money collected by A = 5 + 2 + 1 = 8 Money collected by B = 3 + 4 + 6 = 13" }, { "code": null, "e": 25743, "s": 25697, "text": "Input: N = 1, Arr[] = {{ 1, 2, 3 }}Output : 3" }, { "code": null, "e": 25799, "s": 25743, "text": " Approach: Follow the steps below to solve the problem" }, { "code": null, "e": 26379, "s": 25799, "text": "In a game played with optimal strategyInitialize a variable, say amount, to store the money obtained by A.If N is even, A will collect the first half of the coinsOtherwise, first, (N / 2) coins would be collected by A and last (N / 2) would be collected by BIf N is odd, the coin at the middle can be collected by A or B, depending upon the sequence of moves.Store the coin at the middle of all odd sized rows in a variable, say mid_odd[].Sort the array mid_odd[] in descending order.Optimally, A would collect all coins at even indices of min_odd[]Finally, print the score of A." }, { "code": null, "e": 26418, "s": 26379, "text": "In a game played with optimal strategy" }, { "code": null, "e": 26487, "s": 26418, "text": "Initialize a variable, say amount, to store the money obtained by A." }, { "code": null, "e": 26544, "s": 26487, "text": "If N is even, A will collect the first half of the coins" }, { "code": null, "e": 26641, "s": 26544, "text": "Otherwise, first, (N / 2) coins would be collected by A and last (N / 2) would be collected by B" }, { "code": null, "e": 26743, "s": 26641, "text": "If N is odd, the coin at the middle can be collected by A or B, depending upon the sequence of moves." }, { "code": null, "e": 26824, "s": 26743, "text": "Store the coin at the middle of all odd sized rows in a variable, say mid_odd[]." }, { "code": null, "e": 26870, "s": 26824, "text": "Sort the array mid_odd[] in descending order." }, { "code": null, "e": 26936, "s": 26870, "text": "Optimally, A would collect all coins at even indices of min_odd[]" }, { "code": null, "e": 26967, "s": 26936, "text": "Finally, print the score of A." }, { "code": null, "e": 27018, "s": 26967, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27022, "s": 27018, "text": "C++" }, { "code": null, "e": 27027, "s": 27022, "text": "Java" }, { "code": null, "e": 27035, "s": 27027, "text": "Python3" }, { "code": null, "e": 27038, "s": 27035, "text": "C#" }, { "code": null, "e": 27049, "s": 27038, "text": "Javascript" }, { "code": "// CPP Program to implement// the above approach#include<bits/stdc++.h>using namespace std; // Function to calculate the// maximum amount collected by Avoid find(int N, vector<vector<int>>Arr){ // Stores the money // obtained by A int amount = 0; // Stores mid elements // of odd sized rows vector<int> mid_odd; for(int i = 0; i < N; i++) { // Size of current row int siz = Arr[i].size(); // Increase money collected by A for (int j = 0; j < siz / 2; j++) amount = amount + Arr[i][j]; if(siz % 2 == 1) mid_odd.push_back(Arr[i][siz/2]); } // Add coins at even indices // to the amount collected by A sort(mid_odd.begin(),mid_odd.end()); for(int i = 0; i < mid_odd.size(); i++) if (i % 2 == 0) amount = amount + mid_odd[i]; // Print the amount cout<<amount<<endl; } // Driver Codeint main(){ int N = 2; vector<vector<int>>Arr{{5, 2, 3, 4}, {1, 6}}; // Function call to calculate the // amount of coins collected by A find(N, Arr);} // This code is contributed by ipg2016107.", "e": 28163, "s": 27049, "text": null }, { "code": "// Java program to implement// the above approachimport java.util.*;class GFG{ // Function to calculate the// maximum amount collected by Astatic void find(int N, int[][] Arr){ // Stores the money // obtained by A int amount = 0; // Stores mid elements // of odd sized rows ArrayList<Integer> mid_odd = new ArrayList<Integer>(); for(int i = 0; i < N; i++) { // Size of current row int siz = Arr[i].length; // Increase money collected by A for (int j = 0; j < siz / 2; j++) amount = amount + Arr[i][j]; if(siz % 2 == 1) mid_odd.add(Arr[i][siz/2]); } // Add coins at even indices // to the amount collected by A Collections.sort(mid_odd); for(int i = 0; i < mid_odd.size(); i++){ if (i % 2 == 0) amount = amount + mid_odd.get(i); } // Print the amount System.out.println(amount);} // Driver Codepublic static void main(String[] args){ int N = 2; int[][] Arr = {{5, 2, 3, 4}, {1, 6}}; // Function call to calculate the // amount of coins collected by A find(N, Arr);}} // This code is contributed by splevel62.", "e": 29332, "s": 28163, "text": null }, { "code": "# Python Program to implement# the above approach # Function to calculate the# maximum amount collected by A def find(N, Arr): # Stores the money # obtained by A amount = 0 # Stores mid elements # of odd sized rows mid_odd = [] for i in range(N): # Size of current row siz = len(Arr[i]) # Increase money collected by A for j in range(0, siz // 2): amount = amount + Arr[i][j] if(siz % 2 == 1): mid_odd.append(Arr[i][siz // 2]) # Add coins at even indices # to the amount collected by A mid_odd.sort(reverse=True) for i in range(len(mid_odd)): if i % 2 == 0: amount = amount + mid_odd[i] # Print the amount print(amount) # Driver Code N = 2Arr = [[5, 2, 3, 4], [1, 6]] # Function call to calculate the# amount of coins collected by Afind(N, Arr)", "e": 30202, "s": 29332, "text": null }, { "code": "// C# Program to implement// the above approachusing System;using System.Collections.Generic;class GFG { // Function to calculate the // maximum amount collected by A static void find(int N, List<List<int>> Arr) { // Stores the money // obtained by A int amount = 0; // Stores mid elements // of odd sized rows List<int> mid_odd = new List<int>(); for(int i = 0; i < N; i++) { // Size of current row int siz = Arr[i].Count; // Increase money collected by A for (int j = 0; j < siz / 2; j++) amount = amount + Arr[i][j]; if(siz % 2 == 1) mid_odd.Add(Arr[i][siz/2]); } // Add coins at even indices // to the amount collected by A mid_odd.Sort(); for(int i = 0; i < mid_odd.Count; i++) if (i % 2 == 0) amount = amount + mid_odd[i]; // Print the amount Console.WriteLine(amount); } // Driver code static void Main() { int N = 2; List<List<int>> Arr = new List<List<int>>(); Arr.Add(new List<int>()); Arr[0].Add(5); Arr[0].Add(2); Arr[0].Add(3); Arr[0].Add(4); Arr.Add(new List<int>()); Arr[1].Add(1); Arr[1].Add(6); // Function call to calculate the // amount of coins collected by A find(N, Arr); }} // This code is contributed by divyesh072019.", "e": 31501, "s": 30202, "text": null }, { "code": "<script> // Javascript Program to implement// the above approach // Function to calculate the// maximum amount collected by Afunction find(N, Arr){ // Stores the money // obtained by A var amount = 0; // Stores mid elements // of odd sized rows var mid_odd = []; for(var i = 0; i < N; i++) { // Size of current row var siz = Arr[i].length; // Increase money collected by A for (var j = 0; j < siz / 2; j++) amount = amount + Arr[i][j]; if(siz % 2 == 1) mid_odd.push(Arr[i][siz/2]); } // Add coins at even indices // to the amount collected by A mid_odd.sort((a,b)=>a-b) for(var i = 0; i < mid_odd.length; i++) if (i % 2 == 0) amount = amount + mid_odd[i]; // Print the amount document.write( amount + \"<br>\"); } // Driver Codevar N = 2;var Arr = [[5, 2, 3, 4], [1, 6]]; // Function call to calculate the// amount of coins collected by Afind(N, Arr); // This code is contributed by importantly.</script>", "e": 32534, "s": 31501, "text": null }, { "code": null, "e": 32536, "s": 32534, "text": "8" }, { "code": null, "e": 32583, "s": 32538, "text": "Time Complexity : O(N)Auxiliary Space : O(1)" }, { "code": null, "e": 32594, "s": 32583, "text": "ipg2016107" }, { "code": null, "e": 32604, "s": 32594, "text": "splevel62" }, { "code": null, "e": 32618, "s": 32604, "text": "divyesh072019" }, { "code": null, "e": 32630, "s": 32618, "text": "importantly" }, { "code": null, "e": 32645, "s": 32630, "text": "adnanirshad158" }, { "code": null, "e": 32652, "s": 32645, "text": "Arrays" }, { "code": null, "e": 32665, "s": 32652, "text": "Mathematical" }, { "code": null, "e": 32683, "s": 32665, "text": "Pattern Searching" }, { "code": null, "e": 32690, "s": 32683, "text": "Arrays" }, { "code": null, "e": 32703, "s": 32690, "text": "Mathematical" }, { "code": null, "e": 32721, "s": 32703, "text": "Pattern Searching" }, { "code": null, "e": 32819, "s": 32721, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32828, "s": 32819, "text": "Comments" }, { "code": null, "e": 32841, "s": 32828, "text": "Old Comments" }, { "code": null, "e": 32866, "s": 32841, "text": "Window Sliding Technique" }, { "code": null, "e": 32915, "s": 32866, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 32953, "s": 32915, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 33011, "s": 32953, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 33031, "s": 33011, "text": "Trapping Rain Water" }, { "code": null, "e": 33061, "s": 33031, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 33076, "s": 33061, "text": "C++ Data Types" }, { "code": null, "e": 33136, "s": 33076, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 33179, "s": 33136, "text": "Set in C++ Standard Template Library (STL)" } ]
html.escape() in Python
22 Apr, 2020 With the help of html.escape() method, we can convert the html script into a string by replacing special characters with the string with ascii characters by using html.escape() method. Syntax : html.escape(String) Return : Return a string of ascii character script from html. Example #1 :In this example we can see that by using html.escape() method, we are able to convert the html script to ascii string by using this method. # import htmlimport html s = '<html><head></head><body><h1>This is python</h1></body></html>'# Using html.escape() methodgfg = html.escape(s) print(gfg) Output : <html><head></head><body><h1>This is python</h1></body></html> Example #2 : # import htmlimport html s = '<html><head></head><body><h1>GeeksForGeeks</h1></body></html>'# Using html.escape() methodgfg = html.escape(s) print(gfg) Output : <html><head></head><body><h1>GeeksForGeeks</h1></body></html> Python html-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 Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 213, "s": 28, "text": "With the help of html.escape() method, we can convert the html script into a string by replacing special characters with the string with ascii characters by using html.escape() method." }, { "code": null, "e": 242, "s": 213, "text": "Syntax : html.escape(String)" }, { "code": null, "e": 304, "s": 242, "text": "Return : Return a string of ascii character script from html." }, { "code": null, "e": 456, "s": 304, "text": "Example #1 :In this example we can see that by using html.escape() method, we are able to convert the html script to ascii string by using this method." }, { "code": "# import htmlimport html s = '<html><head></head><body><h1>This is python</h1></body></html>'# Using html.escape() methodgfg = html.escape(s) print(gfg)", "e": 611, "s": 456, "text": null }, { "code": null, "e": 620, "s": 611, "text": "Output :" }, { "code": null, "e": 683, "s": 620, "text": "<html><head></head><body><h1>This is python</h1></body></html>" }, { "code": null, "e": 696, "s": 683, "text": "Example #2 :" }, { "code": "# import htmlimport html s = '<html><head></head><body><h1>GeeksForGeeks</h1></body></html>'# Using html.escape() methodgfg = html.escape(s) print(gfg)", "e": 850, "s": 696, "text": null }, { "code": null, "e": 859, "s": 850, "text": "Output :" }, { "code": null, "e": 921, "s": 859, "text": "<html><head></head><body><h1>GeeksForGeeks</h1></body></html>" }, { "code": null, "e": 940, "s": 921, "text": "Python html-module" }, { "code": null, "e": 947, "s": 940, "text": "Python" }, { "code": null, "e": 1045, "s": 947, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1063, "s": 1045, "text": "Python Dictionary" }, { "code": null, "e": 1105, "s": 1063, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1127, "s": 1105, "text": "Enumerate() in Python" }, { "code": null, "e": 1153, "s": 1127, "text": "Python String | replace()" }, { "code": null, "e": 1185, "s": 1153, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1214, "s": 1185, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1241, "s": 1214, "text": "Python Classes and Objects" }, { "code": null, "e": 1262, "s": 1241, "text": "Python OOPs Concepts" }, { "code": null, "e": 1285, "s": 1262, "text": "Introduction To PYTHON" } ]
time.After() Function in Golang With Examples
02 Apr, 2020 In Go language, time packages supplies functionality for determining as well as viewing time. The After() function in Go language is used to wait for the duration of time to pass and after that it delivers the actual time on the returned channel. Moreover, this function is defined under the time package. Here, you need to import “time” package in order to use these functions. Syntax: func After(d Duration) <-chan Time Here, d is the duration of time before time out, and chan is the channel where current time is sent. Return Value: It first waits for the stated time and then displays timeout. Example 1: // Golang program to illustrate the usage of// After() function in Golang // Including main packagepackage main // Importing fmt and timeimport ( "fmt" "time") // Creating a channel// Using var keywordvar ch chan int // Main functionfunc main() { // For loop for i := 1; i < 6; i++ { // Prints these util loop stops fmt.Println("****Welcome to GeeksforGeeks***") fmt.Println("A CS-Portal!") } // Select statement select { // Using case statement to receive // or send operation on channel and // calling After() method with its // parameter case <-time.After(3 * time.Second): // Printed when timed out fmt.Println("Time Out!") }} Output: ****Welcome to GeeksforGeeks*** A CS-Portal! ****Welcome to GeeksforGeeks*** A CS-Portal! ****Welcome to GeeksforGeeks*** A CS-Portal! ****Welcome to GeeksforGeeks*** A CS-Portal! ****Welcome to GeeksforGeeks*** A CS-Portal! Time Out! // Displayed after 3 seconds as mentioned in the above code In the above example, we have used the “case” statement under the select statement in order to send operation on the channel. Moreover, here time out will be displayed after 3 seconds of the execution of for loop. Example 2: // Golang program to illustrate the usage of// After() function in Golang // Including main packagepackage main // Importing fmt and timeimport ( "fmt" "time") // Main functionfunc main() { // Creating a channel // Using make keyword channel := make(chan string, 2) // Select statement select { // Using case statement to receive // or send operation on channel case output := <-channel: fmt.Println(output) // Calling After() method with its // parameter case <-time.After(5 * time.Second): // Printed after 5 seconds fmt.Println("Its timeout..") }} Output: Its timeout.. Here, we have used the “make” keyword in order to create a channel then like the above example here also case statement is used under a select statement but here it’s used twice. The first one is used to return output and the second one is used to call After() method on the channel. After this, the timeout is displayed in the stated time. GoLang-time Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. strings.Replace() Function in Golang With Examples fmt.Sprintf() Function in Golang With Examples Arrays in Go Golang Maps How to Split a String in Golang? Interfaces in Golang Slices in Golang Different Ways to Find the Type of Variable in Golang How to Parse JSON in Golang? How to Trim a String in Golang?
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Apr, 2020" }, { "code": null, "e": 407, "s": 28, "text": "In Go language, time packages supplies functionality for determining as well as viewing time. The After() function in Go language is used to wait for the duration of time to pass and after that it delivers the actual time on the returned channel. Moreover, this function is defined under the time package. Here, you need to import “time” package in order to use these functions." }, { "code": null, "e": 415, "s": 407, "text": "Syntax:" }, { "code": null, "e": 451, "s": 415, "text": "func After(d Duration) <-chan Time\n" }, { "code": null, "e": 552, "s": 451, "text": "Here, d is the duration of time before time out, and chan is the channel where current time is sent." }, { "code": null, "e": 628, "s": 552, "text": "Return Value: It first waits for the stated time and then displays timeout." }, { "code": null, "e": 639, "s": 628, "text": "Example 1:" }, { "code": "// Golang program to illustrate the usage of// After() function in Golang // Including main packagepackage main // Importing fmt and timeimport ( \"fmt\" \"time\") // Creating a channel// Using var keywordvar ch chan int // Main functionfunc main() { // For loop for i := 1; i < 6; i++ { // Prints these util loop stops fmt.Println(\"****Welcome to GeeksforGeeks***\") fmt.Println(\"A CS-Portal!\") } // Select statement select { // Using case statement to receive // or send operation on channel and // calling After() method with its // parameter case <-time.After(3 * time.Second): // Printed when timed out fmt.Println(\"Time Out!\") }}", "e": 1358, "s": 639, "text": null }, { "code": null, "e": 1366, "s": 1358, "text": "Output:" }, { "code": null, "e": 1665, "s": 1366, "text": "****Welcome to GeeksforGeeks***\nA CS-Portal!\n****Welcome to GeeksforGeeks***\nA CS-Portal!\n****Welcome to GeeksforGeeks***\nA CS-Portal!\n****Welcome to GeeksforGeeks***\nA CS-Portal!\n****Welcome to GeeksforGeeks***\nA CS-Portal!\nTime Out! // Displayed after 3 seconds as mentioned in the above code\n" }, { "code": null, "e": 1879, "s": 1665, "text": "In the above example, we have used the “case” statement under the select statement in order to send operation on the channel. Moreover, here time out will be displayed after 3 seconds of the execution of for loop." }, { "code": null, "e": 1890, "s": 1879, "text": "Example 2:" }, { "code": "// Golang program to illustrate the usage of// After() function in Golang // Including main packagepackage main // Importing fmt and timeimport ( \"fmt\" \"time\") // Main functionfunc main() { // Creating a channel // Using make keyword channel := make(chan string, 2) // Select statement select { // Using case statement to receive // or send operation on channel case output := <-channel: fmt.Println(output) // Calling After() method with its // parameter case <-time.After(5 * time.Second): // Printed after 5 seconds fmt.Println(\"Its timeout..\") }}", "e": 2517, "s": 1890, "text": null }, { "code": null, "e": 2525, "s": 2517, "text": "Output:" }, { "code": null, "e": 2540, "s": 2525, "text": "Its timeout..\n" }, { "code": null, "e": 2881, "s": 2540, "text": "Here, we have used the “make” keyword in order to create a channel then like the above example here also case statement is used under a select statement but here it’s used twice. The first one is used to return output and the second one is used to call After() method on the channel. After this, the timeout is displayed in the stated time." }, { "code": null, "e": 2893, "s": 2881, "text": "GoLang-time" }, { "code": null, "e": 2905, "s": 2893, "text": "Go Language" }, { "code": null, "e": 3003, "s": 2905, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3054, "s": 3003, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 3101, "s": 3054, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 3114, "s": 3101, "text": "Arrays in Go" }, { "code": null, "e": 3126, "s": 3114, "text": "Golang Maps" }, { "code": null, "e": 3159, "s": 3126, "text": "How to Split a String in Golang?" }, { "code": null, "e": 3180, "s": 3159, "text": "Interfaces in Golang" }, { "code": null, "e": 3197, "s": 3180, "text": "Slices in Golang" }, { "code": null, "e": 3251, "s": 3197, "text": "Different Ways to Find the Type of Variable in Golang" }, { "code": null, "e": 3280, "s": 3251, "text": "How to Parse JSON in Golang?" } ]
PHP program to check if a number is prime or not
To check if a number is prime or not, the code is as follows − Live Demo <?php function check_prime($num) { if ($num == 1) return 0; for ($i = 2; $i <= $num/2; $i++) { if ($num % $i == 0) return 0; } return 1; } $num = 47; $flag_val = check_prime($num); if ($flag_val == 1) echo "It is a prime number"; else echo "It is a non-prime number" ?> It is a prime number A function named ‘check_prime’ is used to check if the number is prime or not. A number that needs to be checked for being prime is passed as a parameter to the function. The number is defined and this function is called by passing the number as parameter. Relevant message is displayed on the console.
[ { "code": null, "e": 1250, "s": 1187, "text": "To check if a number is prime or not, the code is as follows −" }, { "code": null, "e": 1261, "s": 1250, "text": " Live Demo" }, { "code": null, "e": 1567, "s": 1261, "text": "<?php\nfunction check_prime($num)\n{\n if ($num == 1)\n return 0;\n for ($i = 2; $i <= $num/2; $i++)\n {\n if ($num % $i == 0)\n return 0;\n }\n return 1;\n}\n$num = 47;\n$flag_val = check_prime($num);\nif ($flag_val == 1)\n echo \"It is a prime number\";\nelse\n echo \"It is a non-prime number\"\n?>" }, { "code": null, "e": 1588, "s": 1567, "text": "It is a prime number" }, { "code": null, "e": 1891, "s": 1588, "text": "A function named ‘check_prime’ is used to check if the number is prime or not. A number that needs to be checked for being prime is passed as a parameter to the function. The number is defined and this function is called by passing the number as parameter. Relevant message is displayed on the console." } ]
GATE | GATE CS 2010 | Question 36
28 Jun, 2021 The following C function takes a simply-linked list as input argument. It modifies the list by moving the last element to the front of the list and returns the modified list. Some part of the code is left blank. typedef struct node { int value; struct node *next;}Node; Node *move_to_front(Node *head) { Node *p, *q; if ((head == NULL: || (head->next == NULL)) return head; q = NULL; p = head; while (p-> next !=NULL) { q = p; p = p->next; } _______________________________ return head;} Choose the correct alternative to replace the blank line.(A) q = NULL; p->next = head; head = p;(B) q->next = NULL; head = p; p->next = head;(C) head = p; p->next = q; q->next = NULL;(D) q->next = NULL; p->next = head; head = p;Answer: (D)Explanation: When the while loop ends, q contains address of second last node and p contains address of last node. So we need to do following things after while loop.i) Set next of q as NULL (q->next = NULL).ii) Set next of p as head (p->next = head).iii) Make head as p ( head = p)Step (ii) must be performed before step (iii). If we change head first, then we lose track of head node in the original linked list.See https://www.geeksforgeeks.org/move-last-element-to-front-of-a-given-linked-list/ for more details.Quiz of this Question GATE-CS-2010 GATE-GATE CS 2010 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jun, 2021" }, { "code": null, "e": 264, "s": 52, "text": "The following C function takes a simply-linked list as input argument. It modifies the list by moving the last element to the front of the list and returns the modified list. Some part of the code is left blank." }, { "code": "typedef struct node { int value; struct node *next;}Node; Node *move_to_front(Node *head) { Node *p, *q; if ((head == NULL: || (head->next == NULL)) return head; q = NULL; p = head; while (p-> next !=NULL) { q = p; p = p->next; } _______________________________ return head;}", "e": 563, "s": 264, "text": null }, { "code": null, "e": 1340, "s": 563, "text": "Choose the correct alternative to replace the blank line.(A) q = NULL; p->next = head; head = p;(B) q->next = NULL; head = p; p->next = head;(C) head = p; p->next = q; q->next = NULL;(D) q->next = NULL; p->next = head; head = p;Answer: (D)Explanation: When the while loop ends, q contains address of second last node and p contains address of last node. So we need to do following things after while loop.i) Set next of q as NULL (q->next = NULL).ii) Set next of p as head (p->next = head).iii) Make head as p ( head = p)Step (ii) must be performed before step (iii). If we change head first, then we lose track of head node in the original linked list.See https://www.geeksforgeeks.org/move-last-element-to-front-of-a-given-linked-list/ for more details.Quiz of this Question" }, { "code": null, "e": 1353, "s": 1340, "text": "GATE-CS-2010" }, { "code": null, "e": 1371, "s": 1353, "text": "GATE-GATE CS 2010" }, { "code": null, "e": 1376, "s": 1371, "text": "GATE" } ]
GATE | GATE CS 2010 | Question 19
21 Dec, 2021 A relational schema for a train reservation database is given below.Passenger (pid, pname, age)Reservation (pid, class, tid) Table: Passenger pid pname age ----------------- 0 Sachin 65 1 Rahul 66 2 Sourav 67 3 Anil 69 Table : Reservation pid class tid --------------- 0 AC 8200 1 AC 8201 2 SC 8201 5 AC 8203 1 SC 8204 3 AC 8202 What pids are returned by the following SQL query for the above instance of the tables? SELECT pid FROM Reservation , WHERE class ‘AC’ AND EXISTS (SELECT * FROM Passenger WHERE age > 65 AND Passenger. pid = Reservation.pid) (A) 1, 0(B) 1, 2(C) 1, 3(D) 1, 5Answer: (C)Explanation: When a subquery uses values from outer query, the subquery is called correlated subquery. The correlated subquery is evaluated once for each row processed by the outer query. The outer query selects 4 entries (with pids as 0, 1, 5, 3) from Reservation table. Out of these selected entries, the subquery returns Non-Null values only for 1 and 3.Quiz of this Question ManasChhabra2 GATE-CS-2010 GATE-GATE CS 2010 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-CS-2014-(Set-2) | Question 65 GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33 GATE | GATE-CS-2014-(Set-3) | Question 20 GATE | GATE CS 2008 | Question 40 GATE | GATE CS 2008 | Question 46 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE CS 2011 | Question 49 GATE | GATE CS 1996 | Question 38 GATE | GATE-CS-2004 | Question 31
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Dec, 2021" }, { "code": null, "e": 153, "s": 28, "text": "A relational schema for a train reservation database is given below.Passenger (pid, pname, age)Reservation (pid, class, tid)" }, { "code": null, "e": 427, "s": 153, "text": "Table: Passenger\npid pname age\n-----------------\n 0 Sachin 65\n 1 Rahul 66\n 2 Sourav 67\n 3 Anil 69\n\nTable : Reservation\npid class tid\n---------------\n 0 AC 8200\n 1 AC 8201\n 2 SC 8201\n 5 AC 8203\n 1 SC 8204\n 3 AC 8202" }, { "code": null, "e": 515, "s": 427, "text": "What pids are returned by the following SQL query for the above instance of the tables?" }, { "code": null, "e": 676, "s": 515, "text": "SELECT pid\nFROM Reservation ,\nWHERE class ‘AC’ AND\n EXISTS (SELECT *\n FROM Passenger\n WHERE age > 65 AND\n Passenger. pid = Reservation.pid)" }, { "code": null, "e": 907, "s": 676, "text": "(A) 1, 0(B) 1, 2(C) 1, 3(D) 1, 5Answer: (C)Explanation: When a subquery uses values from outer query, the subquery is called correlated subquery. The correlated subquery is evaluated once for each row processed by the outer query." }, { "code": null, "e": 1098, "s": 907, "text": "The outer query selects 4 entries (with pids as 0, 1, 5, 3) from Reservation table. Out of these selected entries, the subquery returns Non-Null values only for 1 and 3.Quiz of this Question" }, { "code": null, "e": 1112, "s": 1098, "text": "ManasChhabra2" }, { "code": null, "e": 1125, "s": 1112, "text": "GATE-CS-2010" }, { "code": null, "e": 1143, "s": 1125, "text": "GATE-GATE CS 2010" }, { "code": null, "e": 1148, "s": 1143, "text": "GATE" }, { "code": null, "e": 1246, "s": 1148, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1288, "s": 1246, "text": "GATE | GATE-CS-2014-(Set-2) | Question 65" }, { "code": null, "e": 1350, "s": 1288, "text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33" }, { "code": null, "e": 1392, "s": 1350, "text": "GATE | GATE-CS-2014-(Set-3) | Question 20" }, { "code": null, "e": 1426, "s": 1392, "text": "GATE | GATE CS 2008 | Question 40" }, { "code": null, "e": 1460, "s": 1426, "text": "GATE | GATE CS 2008 | Question 46" }, { "code": null, "e": 1502, "s": 1460, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 1544, "s": 1502, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 1578, "s": 1544, "text": "GATE | GATE CS 2011 | Question 49" }, { "code": null, "e": 1612, "s": 1578, "text": "GATE | GATE CS 1996 | Question 38" } ]
Highest power of two that divides a given number
22 Jun, 2022 Given a number n, find the highest power of 2 that divides n.Examples: Input : n = 48 Output : 16 Highest power of 2 that divides 48 is 16.Input : n = 5 Output : 1 Highest power of 2 that divides 5 is 1. A simple solution is to try all powers of 2 one by one starting from 1, then 2, then 4 and so on.An efficient solution is based on bit magic. If we take a closer look, we can notice that, we basically need to find the number that has rightmost bit set at same position as n and all other bits as 0. For example, for n = 5 (101), our output is 001. For n = 48 (110000), our output is 010000 How do we find a number that has same rightmost set bit and all other bits as 0? We follow below steps.Let n = 48 (00110000) Subtract one from n, i.e., we do n-1. We get 47(00101111) Do negation of (n-1), i.e., we do ~(n-1). We get (11010000). Do n & (~(n-1)), we get 00010000 which has value 16.Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript // CPP program to find highest power// of 2 that divides n.#include<iostream>using namespace std; int highestPowerOf2(int n){ return (n & (~(n - 1)));} int main(){ int n = 48; cout << highestPowerOf2(n); return 0;} // Java program to find highest power// of 2 that divides n. class GFG{ static int highestPowerOf2(int n){ return (n & (~(n - 1)));} public static void main(String []args){ int n = 48; System.out.println(highestPowerOf2(n));}} # Python3 program to find highest power# of 2 that divides n. def highestPowerOf2(n): return (n & (~(n - 1))) #Driver codeif __name__=='__main__': n = 48 print(highestPowerOf2(n)) # this code is contributed# by ash264 // C# program to find highest power// of 2 that divides n.using System; class GFG{ static int highestPowerOf2(int n){ return (n & (~(n - 1)));} public static void Main(){ int n = 48; Console.Write(highestPowerOf2(n));}} // This code is contributed// by Akanksha Rai(Abby_akku) <?php// PHP program to find highest power// of 2 that divides n. function highestPowerOf2($n){ return ($n & (~($n - 1)));} // Driver Code$n = 48;echo highestPowerOf2($n); // This code is contributed// by Sach_Code..?> <script> // javascript program to find highest power// of 2 that divides n. function highestPowerOf2(n){ return (n & (~(n - 1)));} var n = 48;document.write(highestPowerOf2(n)); // This code is contributed by 29AjayKumar </script> 16 Time Complexity: O(log2n)Space Complexity:- O(1). Approach – 2: This is also an efficient approach, where you can find the largest divisor of power two for a number ‘n’ using a predefined function in C for handling bits. Which is _builtin_ctz(n), this function helps you to find the trailing zeros of the number, and then you can see the bits-magic. Input : n = 48 ~= (110000)2 // num of trailing zeros are = 4, so number of trailing zeros = 4 Output : 1<<4 =16 // pow(2,4) = 16 Highest power of 2 that divides 48 is 16. Input : n = 21 ~= (10101)2 // no trailing zeros are present, so number of trailing zeros = 0 Output : 1<<0 =2 // pow(2,0)=1 Note: To know in the detail about such bits masking functions you can go through this article. C #include <stdio.h>int main(){ int n = 21; int m = 48; printf("for %d is %d ", n,(1<< __builtin_ctz(n))); printf("\nfor %d is %d ", m,(1<< __builtin_ctz(m))); return 0;} for 21 is 1 for 48 is 16 Time Complexity: O(log2n)Space Complexity: O(1) ash264 Sach_Code Akanksha_Rai ukasp 29AjayKumar madhav_mohan navihere divisibility Bit Magic Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Little and Big Endian Mystery Bits manipulation (Important tactics) Binary representation of a given number Divide two integers without using multiplication, division and mod operator Josephus problem | Set 1 (A O(n) Solution) Bit Fields in C Find the element that appears once Add two numbers without using arithmetic operators C++ bitset and its application Find the two non-repeating elements in an array of repeating elements/ Unique Numbers 2
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jun, 2022" }, { "code": null, "e": 100, "s": 28, "text": "Given a number n, find the highest power of 2 that divides n.Examples: " }, { "code": null, "e": 233, "s": 100, "text": "Input : n = 48 Output : 16 Highest power of 2 that divides 48 is 16.Input : n = 5 Output : 1 Highest power of 2 that divides 5 is 1." }, { "code": null, "e": 970, "s": 235, "text": "A simple solution is to try all powers of 2 one by one starting from 1, then 2, then 4 and so on.An efficient solution is based on bit magic. If we take a closer look, we can notice that, we basically need to find the number that has rightmost bit set at same position as n and all other bits as 0. For example, for n = 5 (101), our output is 001. For n = 48 (110000), our output is 010000 How do we find a number that has same rightmost set bit and all other bits as 0? We follow below steps.Let n = 48 (00110000) Subtract one from n, i.e., we do n-1. We get 47(00101111) Do negation of (n-1), i.e., we do ~(n-1). We get (11010000). Do n & (~(n-1)), we get 00010000 which has value 16.Below is the implementation of above approach: " }, { "code": null, "e": 974, "s": 970, "text": "C++" }, { "code": null, "e": 979, "s": 974, "text": "Java" }, { "code": null, "e": 987, "s": 979, "text": "Python3" }, { "code": null, "e": 990, "s": 987, "text": "C#" }, { "code": null, "e": 994, "s": 990, "text": "PHP" }, { "code": null, "e": 1005, "s": 994, "text": "Javascript" }, { "code": "// CPP program to find highest power// of 2 that divides n.#include<iostream>using namespace std; int highestPowerOf2(int n){ return (n & (~(n - 1)));} int main(){ int n = 48; cout << highestPowerOf2(n); return 0;}", "e": 1232, "s": 1005, "text": null }, { "code": "// Java program to find highest power// of 2 that divides n. class GFG{ static int highestPowerOf2(int n){ return (n & (~(n - 1)));} public static void main(String []args){ int n = 48; System.out.println(highestPowerOf2(n));}}", "e": 1475, "s": 1232, "text": null }, { "code": "# Python3 program to find highest power# of 2 that divides n. def highestPowerOf2(n): return (n & (~(n - 1))) #Driver codeif __name__=='__main__': n = 48 print(highestPowerOf2(n)) # this code is contributed# by ash264", "e": 1704, "s": 1475, "text": null }, { "code": "// C# program to find highest power// of 2 that divides n.using System; class GFG{ static int highestPowerOf2(int n){ return (n & (~(n - 1)));} public static void Main(){ int n = 48; Console.Write(highestPowerOf2(n));}} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 1994, "s": 1704, "text": null }, { "code": "<?php// PHP program to find highest power// of 2 that divides n. function highestPowerOf2($n){ return ($n & (~($n - 1)));} // Driver Code$n = 48;echo highestPowerOf2($n); // This code is contributed// by Sach_Code..?>", "e": 2215, "s": 1994, "text": null }, { "code": "<script> // javascript program to find highest power// of 2 that divides n. function highestPowerOf2(n){ return (n & (~(n - 1)));} var n = 48;document.write(highestPowerOf2(n)); // This code is contributed by 29AjayKumar </script>", "e": 2458, "s": 2215, "text": null }, { "code": null, "e": 2461, "s": 2458, "text": "16" }, { "code": null, "e": 2511, "s": 2461, "text": "Time Complexity: O(log2n)Space Complexity:- O(1)." }, { "code": null, "e": 2813, "s": 2511, "text": "Approach – 2: This is also an efficient approach, where you can find the largest divisor of power two for a number ‘n’ using a predefined function in C for handling bits. Which is _builtin_ctz(n), this function helps you to find the trailing zeros of the number, and then you can see the bits-magic." }, { "code": null, "e": 2913, "s": 2813, "text": "Input : n = 48 ~= (110000)2 // num of trailing zeros are = 4, so number of trailing zeros = 4" }, { "code": null, "e": 3001, "s": 2913, "text": "Output : 1<<4 =16 // pow(2,4) = 16 Highest power of 2 that divides 48 is 16." }, { "code": null, "e": 3101, "s": 3001, "text": "Input : n = 21 ~= (10101)2 // no trailing zeros are present, so number of trailing zeros = 0" }, { "code": null, "e": 3138, "s": 3101, "text": "Output : 1<<0 =2 // pow(2,0)=1" }, { "code": null, "e": 3233, "s": 3138, "text": "Note: To know in the detail about such bits masking functions you can go through this article." }, { "code": null, "e": 3235, "s": 3233, "text": "C" }, { "code": "#include <stdio.h>int main(){ int n = 21; int m = 48; printf(\"for %d is %d \", n,(1<< __builtin_ctz(n))); printf(\"\\nfor %d is %d \", m,(1<< __builtin_ctz(m))); return 0;}", "e": 3444, "s": 3235, "text": null }, { "code": null, "e": 3471, "s": 3444, "text": "for 21 is 1 \nfor 48 is 16 " }, { "code": null, "e": 3519, "s": 3471, "text": "Time Complexity: O(log2n)Space Complexity: O(1)" }, { "code": null, "e": 3526, "s": 3519, "text": "ash264" }, { "code": null, "e": 3536, "s": 3526, "text": "Sach_Code" }, { "code": null, "e": 3549, "s": 3536, "text": "Akanksha_Rai" }, { "code": null, "e": 3555, "s": 3549, "text": "ukasp" }, { "code": null, "e": 3567, "s": 3555, "text": "29AjayKumar" }, { "code": null, "e": 3580, "s": 3567, "text": "madhav_mohan" }, { "code": null, "e": 3589, "s": 3580, "text": "navihere" }, { "code": null, "e": 3602, "s": 3589, "text": "divisibility" }, { "code": null, "e": 3612, "s": 3602, "text": "Bit Magic" }, { "code": null, "e": 3622, "s": 3612, "text": "Bit Magic" }, { "code": null, "e": 3720, "s": 3622, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3750, "s": 3720, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 3788, "s": 3750, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 3828, "s": 3788, "text": "Binary representation of a given number" }, { "code": null, "e": 3904, "s": 3828, "text": "Divide two integers without using multiplication, division and mod operator" }, { "code": null, "e": 3947, "s": 3904, "text": "Josephus problem | Set 1 (A O(n) Solution)" }, { "code": null, "e": 3963, "s": 3947, "text": "Bit Fields in C" }, { "code": null, "e": 3998, "s": 3963, "text": "Find the element that appears once" }, { "code": null, "e": 4049, "s": 3998, "text": "Add two numbers without using arithmetic operators" }, { "code": null, "e": 4080, "s": 4049, "text": "C++ bitset and its application" } ]
Select variables (columns) in R using Dplyr
21 Jul, 2021 In this article, we are going to select variables or columns in R programming language using dplyr library. Dataset in use: Here we will use select() method to select column by its name Syntax: select(dataframe,column1,column2,.,column n) Here, data frame is the input dataframe and columns are the columns in the dataframe to be displayed Example 1: R program to select columns R # load the librarylibrary(dplyr) # create dataframe with 3 columns# id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby','gnanesh', 'rohith','pinkey','dhanush', 'sravan','gnanesh','ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada', 'guntur','hyd','tenali','hyd')) # select id column from the dataframe by # column nameprint(select(data1,id)) # select name column from the dataframe by# column nameprint(select(data1,name)) Output: Example 2: R program to select multiple columns R # load the librarylibrary(dplyr) # create dataframe with 3 columns # id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby','gnanesh', 'rohith','pinkey','dhanush', 'sravan','gnanesh','ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada', 'guntur','hyd','tenali','hyd')) # select multiple columns from the dataframe# by column nameprint(select(data1,id,name,address)) Output: We can also use the column position and get the column using select() method. Position starts with 1. Syntax: select(dataframe,column1_position,column2_position,.,column n_position) where, dataframe is the input dataframe and column position is an column number For selecting multiple columns we can use range operator “;” to select columns by their position Syntax: select(dataframe,start_position:end_position) where, dataframe is the input dataframe, start_position is a column number starting position and end_position is a column number ending position Example 1: R program to select particular column by column position R # load the librarylibrary(dplyr) # create dataframe with 3 columns# id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby','gnanesh', 'rohith','pinkey','dhanush', 'sravan','gnanesh','ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada', 'guntur','hyd','tenali','hyd')) # select first column by column positionprint(select(data1,1)) # select third column by column positionprint(select(data1,3)) Output: Example 2: R program to select multiple columns by positions R # load the librarylibrary(dplyr) # create dataframe with 3 columns # id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby','gnanesh', 'rohith','pinkey','dhanush','sravan', 'gnanesh','ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # select multiple column by column positionprint(select(data1,1,2)) Output: Example 3: R program to select multiple columns by position with range operator R # load the librarylibrary(dplyr) # create dataframe with 3 columns # id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby','gnanesh', 'rohith','pinkey','dhanush','sravan', 'gnanesh','ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # select multiple column by column # position with : operatorprint(select(data1,1:3)) Output: Here, we will display the column values based on values or pattern present in the column Display the column that contains the given sub string Syntax: select(dataframe,contains(‘sub_string’)) Here, dataframe is the input dataframe and sub_string is the string present in the column name Example: R program to select column based on substring R # load the librarylibrary(dplyr) # create dataframe with 3 columns # id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby','gnanesh', 'rohith','pinkey','dhanush','sravan', 'gnanesh','ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # select column that contains amprint(select(data1,contains('am'))) # select column that contains dprint(select(data1,contains('d'))) # select column that contains ddprint(select(data1,contains('dd'))) Output: It will check and display the column that contains the given sub string select(dataframe,matches(‘sub_string’)) Here, dataframe is the input dataframe and sub_string is the string present in the column name Example: R program to select column based on substring R # load the librarylibrary(dplyr) # create dataframe with 3 columns # id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby','gnanesh', 'rohith','pinkey','dhanush','sravan', 'gnanesh','ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # select column that matches with amprint(select(data1,matches('am'))) # select column that matches with dprint(select(data1,matches ('d'))) # select column that matches with ddprint(select(data1,matches ('dd'))) Output: Here we can also select columns based on starting and ending characters. starts_with() is used to return the column that starts with the given character. Syntax: select(dataframe,starts_with(‘substring’)) Where, dataframe is the input dataframe and substring is the character/string that starts with it ends_with() is used to return the column that ends with the given character. Syntax: select(dataframe,ends_with(‘substring’)) where, dataframe is the input dataframe and substring is the character/string that ends with it Example 1: R program to display columns that starts with a character/substring R # load the librarylibrary(dplyr) # create dataframe with 3 columns id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby','gnanesh', 'rohith','pinkey','dhanush','sravan', 'gnanesh','ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # select column that starts with nprint(select(data1,starts_with('n'))) # select column that starts with addprint(select(data1,starts_with('add'))) Output: Example 2: R program to select column that ends with a given string or character R # load the librarylibrary(dplyr) # create dataframe with 3 columns id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby','gnanesh', 'rohith','pinkey','dhanush','sravan', 'gnanesh','ojaswi'), address=c('hyd','hyd','ponnur','tenali','vijayawada', 'vijayawada','guntur','hyd','tenali','hyd')) # select column that ends with ssprint(select(data1,ends_with('ss'))) # select column that ends with dprint(select(data1,ends_with('d'))) Output: We can select all the columns in the data frame by using everything() method. Syntax: select(dataframe,everything()) Example: R program to select all columns R # load the librarylibrary(dplyr) # create dataframe with 3 columns# id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby','gnanesh', 'rohith','pinkey','dhanush','sravan', 'gnanesh','ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # select all columns using everything methodprint(select(data1,everything())) Output: Picked R Dplyr 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? R - if statement Logistic Regression in R Programming How to filter R DataFrame by values in a column? 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": "\n21 Jul, 2021" }, { "code": null, "e": 136, "s": 28, "text": "In this article, we are going to select variables or columns in R programming language using dplyr library." }, { "code": null, "e": 152, "s": 136, "text": "Dataset in use:" }, { "code": null, "e": 214, "s": 152, "text": "Here we will use select() method to select column by its name" }, { "code": null, "e": 222, "s": 214, "text": "Syntax:" }, { "code": null, "e": 267, "s": 222, "text": "select(dataframe,column1,column2,.,column n)" }, { "code": null, "e": 368, "s": 267, "text": "Here, data frame is the input dataframe and columns are the columns in the dataframe to be displayed" }, { "code": null, "e": 407, "s": 368, "text": "Example 1: R program to select columns" }, { "code": null, "e": 409, "s": 407, "text": "R" }, { "code": "# load the librarylibrary(dplyr) # create dataframe with 3 columns# id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby','gnanesh', 'rohith','pinkey','dhanush', 'sravan','gnanesh','ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada', 'guntur','hyd','tenali','hyd')) # select id column from the dataframe by # column nameprint(select(data1,id)) # select name column from the dataframe by# column nameprint(select(data1,name))", "e": 1075, "s": 409, "text": null }, { "code": null, "e": 1083, "s": 1075, "text": "Output:" }, { "code": null, "e": 1131, "s": 1083, "text": "Example 2: R program to select multiple columns" }, { "code": null, "e": 1133, "s": 1131, "text": "R" }, { "code": "# load the librarylibrary(dplyr) # create dataframe with 3 columns # id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby','gnanesh', 'rohith','pinkey','dhanush', 'sravan','gnanesh','ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada', 'guntur','hyd','tenali','hyd')) # select multiple columns from the dataframe# by column nameprint(select(data1,id,name,address))", "e": 1735, "s": 1133, "text": null }, { "code": null, "e": 1743, "s": 1735, "text": "Output:" }, { "code": null, "e": 1845, "s": 1743, "text": "We can also use the column position and get the column using select() method. Position starts with 1." }, { "code": null, "e": 1853, "s": 1845, "text": "Syntax:" }, { "code": null, "e": 1925, "s": 1853, "text": "select(dataframe,column1_position,column2_position,.,column n_position)" }, { "code": null, "e": 2005, "s": 1925, "text": "where, dataframe is the input dataframe and column position is an column number" }, { "code": null, "e": 2102, "s": 2005, "text": "For selecting multiple columns we can use range operator “;” to select columns by their position" }, { "code": null, "e": 2110, "s": 2102, "text": "Syntax:" }, { "code": null, "e": 2156, "s": 2110, "text": "select(dataframe,start_position:end_position)" }, { "code": null, "e": 2303, "s": 2156, "text": "where, dataframe is the input dataframe, start_position is a column number starting position and end_position is a column number ending position" }, { "code": null, "e": 2371, "s": 2303, "text": "Example 1: R program to select particular column by column position" }, { "code": null, "e": 2373, "s": 2371, "text": "R" }, { "code": "# load the librarylibrary(dplyr) # create dataframe with 3 columns# id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby','gnanesh', 'rohith','pinkey','dhanush', 'sravan','gnanesh','ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada', 'guntur','hyd','tenali','hyd')) # select first column by column positionprint(select(data1,1)) # select third column by column positionprint(select(data1,3)) ", "e": 3007, "s": 2373, "text": null }, { "code": null, "e": 3015, "s": 3007, "text": "Output:" }, { "code": null, "e": 3076, "s": 3015, "text": "Example 2: R program to select multiple columns by positions" }, { "code": null, "e": 3078, "s": 3076, "text": "R" }, { "code": "# load the librarylibrary(dplyr) # create dataframe with 3 columns # id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby','gnanesh', 'rohith','pinkey','dhanush','sravan', 'gnanesh','ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # select multiple column by column positionprint(select(data1,1,2))", "e": 3651, "s": 3078, "text": null }, { "code": null, "e": 3659, "s": 3651, "text": "Output:" }, { "code": null, "e": 3739, "s": 3659, "text": "Example 3: R program to select multiple columns by position with range operator" }, { "code": null, "e": 3741, "s": 3739, "text": "R" }, { "code": "# load the librarylibrary(dplyr) # create dataframe with 3 columns # id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby','gnanesh', 'rohith','pinkey','dhanush','sravan', 'gnanesh','ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # select multiple column by column # position with : operatorprint(select(data1,1:3))", "e": 4332, "s": 3741, "text": null }, { "code": null, "e": 4340, "s": 4332, "text": "Output:" }, { "code": null, "e": 4430, "s": 4340, "text": "Here, we will display the column values based on values or pattern present in the column " }, { "code": null, "e": 4484, "s": 4430, "text": "Display the column that contains the given sub string" }, { "code": null, "e": 4492, "s": 4484, "text": "Syntax:" }, { "code": null, "e": 4533, "s": 4492, "text": "select(dataframe,contains(‘sub_string’))" }, { "code": null, "e": 4628, "s": 4533, "text": "Here, dataframe is the input dataframe and sub_string is the string present in the column name" }, { "code": null, "e": 4683, "s": 4628, "text": "Example: R program to select column based on substring" }, { "code": null, "e": 4685, "s": 4683, "text": "R" }, { "code": "# load the librarylibrary(dplyr) # create dataframe with 3 columns # id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby','gnanesh', 'rohith','pinkey','dhanush','sravan', 'gnanesh','ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # select column that contains amprint(select(data1,contains('am'))) # select column that contains dprint(select(data1,contains('d'))) # select column that contains ddprint(select(data1,contains('dd')))", "e": 5394, "s": 4685, "text": null }, { "code": null, "e": 5402, "s": 5394, "text": "Output:" }, { "code": null, "e": 5474, "s": 5402, "text": "It will check and display the column that contains the given sub string" }, { "code": null, "e": 5514, "s": 5474, "text": "select(dataframe,matches(‘sub_string’))" }, { "code": null, "e": 5609, "s": 5514, "text": "Here, dataframe is the input dataframe and sub_string is the string present in the column name" }, { "code": null, "e": 5664, "s": 5609, "text": "Example: R program to select column based on substring" }, { "code": null, "e": 5666, "s": 5664, "text": "R" }, { "code": "# load the librarylibrary(dplyr) # create dataframe with 3 columns # id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby','gnanesh', 'rohith','pinkey','dhanush','sravan', 'gnanesh','ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # select column that matches with amprint(select(data1,matches('am'))) # select column that matches with dprint(select(data1,matches ('d'))) # select column that matches with ddprint(select(data1,matches ('dd')))", "e": 6388, "s": 5666, "text": null }, { "code": null, "e": 6396, "s": 6388, "text": "Output:" }, { "code": null, "e": 6469, "s": 6396, "text": "Here we can also select columns based on starting and ending characters." }, { "code": null, "e": 6550, "s": 6469, "text": "starts_with() is used to return the column that starts with the given character." }, { "code": null, "e": 6558, "s": 6550, "text": "Syntax:" }, { "code": null, "e": 6601, "s": 6558, "text": "select(dataframe,starts_with(‘substring’))" }, { "code": null, "e": 6699, "s": 6601, "text": "Where, dataframe is the input dataframe and substring is the character/string that starts with it" }, { "code": null, "e": 6776, "s": 6699, "text": "ends_with() is used to return the column that ends with the given character." }, { "code": null, "e": 6784, "s": 6776, "text": "Syntax:" }, { "code": null, "e": 6825, "s": 6784, "text": "select(dataframe,ends_with(‘substring’))" }, { "code": null, "e": 6921, "s": 6825, "text": "where, dataframe is the input dataframe and substring is the character/string that ends with it" }, { "code": null, "e": 7000, "s": 6921, "text": "Example 1: R program to display columns that starts with a character/substring" }, { "code": null, "e": 7002, "s": 7000, "text": "R" }, { "code": "# load the librarylibrary(dplyr) # create dataframe with 3 columns id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby','gnanesh', 'rohith','pinkey','dhanush','sravan', 'gnanesh','ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # select column that starts with nprint(select(data1,starts_with('n'))) # select column that starts with addprint(select(data1,starts_with('add')))", "e": 7654, "s": 7002, "text": null }, { "code": null, "e": 7662, "s": 7654, "text": "Output:" }, { "code": null, "e": 7743, "s": 7662, "text": "Example 2: R program to select column that ends with a given string or character" }, { "code": null, "e": 7745, "s": 7743, "text": "R" }, { "code": "# load the librarylibrary(dplyr) # create dataframe with 3 columns id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby','gnanesh', 'rohith','pinkey','dhanush','sravan', 'gnanesh','ojaswi'), address=c('hyd','hyd','ponnur','tenali','vijayawada', 'vijayawada','guntur','hyd','tenali','hyd')) # select column that ends with ssprint(select(data1,ends_with('ss'))) # select column that ends with dprint(select(data1,ends_with('d')))", "e": 8360, "s": 7745, "text": null }, { "code": null, "e": 8368, "s": 8360, "text": "Output:" }, { "code": null, "e": 8446, "s": 8368, "text": "We can select all the columns in the data frame by using everything() method." }, { "code": null, "e": 8454, "s": 8446, "text": "Syntax:" }, { "code": null, "e": 8485, "s": 8454, "text": "select(dataframe,everything())" }, { "code": null, "e": 8526, "s": 8485, "text": "Example: R program to select all columns" }, { "code": null, "e": 8528, "s": 8526, "text": "R" }, { "code": "# load the librarylibrary(dplyr) # create dataframe with 3 columns# id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby','gnanesh', 'rohith','pinkey','dhanush','sravan', 'gnanesh','ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # select all columns using everything methodprint(select(data1,everything()))", "e": 9110, "s": 8528, "text": null }, { "code": null, "e": 9118, "s": 9110, "text": "Output:" }, { "code": null, "e": 9125, "s": 9118, "text": "Picked" }, { "code": null, "e": 9133, "s": 9125, "text": "R Dplyr" }, { "code": null, "e": 9144, "s": 9133, "text": "R Language" }, { "code": null, "e": 9242, "s": 9144, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9294, "s": 9242, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 9352, "s": 9294, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 9387, "s": 9352, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 9425, "s": 9387, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 9442, "s": 9425, "text": "R - if statement" }, { "code": null, "e": 9479, "s": 9442, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 9528, "s": 9479, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 9571, "s": 9528, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 9608, "s": 9571, "text": "How to import an Excel File into R ?" } ]
numpy.tanh() in Python
04 Dec, 2020 The numpy.tanh()is a mathematical function that helps user to calculate hyperbolic tangent for all x(being the array elements). Equivalent to np.sinh(x) / np.cosh(x) or -1j * np.tan(1j*x). Syntax : numpy.tanh(x[, out]) = ufunc ‘tanh’)Parameters : array : [array_like] elements are in radians.2pi Radians = 36o degrees Return : An array with hyperbolic tangent of x for all x i.e. array elements Code #1 : Working # Python3 program explaining# tanh() function import numpy as npimport math in_array = [0, math.pi / 2, np.pi / 3, np.pi]print ("Input array : \n", in_array) tanh_Values = np.tanh(in_array)print ("\nTangent Hyperbolic values : \n", tanh_Values) Output : Input array : [0, 1.5707963267948966, 1.0471975511965976, 3.141592653589793] Tangent Hyperbolic values : [ 0. 0.91715234 0.78071444 0.99627208] Code #2 : Graphical representation # Python program showing Graphical# representation of tanh() functionimport numpy as npimport matplotlib.pyplot as plt in_array = np.linspace(-np.pi, np.pi, 12)out_array = np.tanh(in_array) print("in_array : ", in_array)print("\nout_array : ", out_array) # red for numpy.tanh()plt.plot(in_array, out_array, color = 'red', marker = "o")plt.title("numpy.tanh()")plt.xlabel("X")plt.ylabel("Y")plt.show() Output : in_array : [-3.14159265 -2.57039399 -1.99919533 -1.42799666 -0.856798 -0.28559933 0.28559933 0.856798 1.42799666 1.99919533 2.57039399 3.14159265] out_array : [-0.99627208 -0.98836197 -0.96397069 -0.89125532 -0.69460424 -0.27807943 0.27807943 0.69460424 0.89125532 0.96397069 0.98836197 0.99627208] References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.tanh.html#numpy.tanh. Python numpy-Mathematical Function Python-numpy 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 Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Dec, 2020" }, { "code": null, "e": 156, "s": 28, "text": "The numpy.tanh()is a mathematical function that helps user to calculate hyperbolic tangent for all x(being the array elements)." }, { "code": null, "e": 217, "s": 156, "text": "Equivalent to np.sinh(x) / np.cosh(x) or -1j * np.tan(1j*x)." }, { "code": null, "e": 275, "s": 217, "text": "Syntax : numpy.tanh(x[, out]) = ufunc ‘tanh’)Parameters :" }, { "code": null, "e": 346, "s": 275, "text": "array : [array_like] elements are in radians.2pi Radians = 36o degrees" }, { "code": null, "e": 423, "s": 346, "text": "Return : An array with hyperbolic tangent of x for all x i.e. array elements" }, { "code": null, "e": 442, "s": 423, "text": " Code #1 : Working" }, { "code": "# Python3 program explaining# tanh() function import numpy as npimport math in_array = [0, math.pi / 2, np.pi / 3, np.pi]print (\"Input array : \\n\", in_array) tanh_Values = np.tanh(in_array)print (\"\\nTangent Hyperbolic values : \\n\", tanh_Values)", "e": 690, "s": 442, "text": null }, { "code": null, "e": 699, "s": 690, "text": "Output :" }, { "code": null, "e": 860, "s": 699, "text": "Input array : \n [0, 1.5707963267948966, 1.0471975511965976, 3.141592653589793]\n\nTangent Hyperbolic values : \n [ 0. 0.91715234 0.78071444 0.99627208]\n" }, { "code": null, "e": 896, "s": 860, "text": " Code #2 : Graphical representation" }, { "code": "# Python program showing Graphical# representation of tanh() functionimport numpy as npimport matplotlib.pyplot as plt in_array = np.linspace(-np.pi, np.pi, 12)out_array = np.tanh(in_array) print(\"in_array : \", in_array)print(\"\\nout_array : \", out_array) # red for numpy.tanh()plt.plot(in_array, out_array, color = 'red', marker = \"o\")plt.title(\"numpy.tanh()\")plt.xlabel(\"X\")plt.ylabel(\"Y\")plt.show()", "e": 1300, "s": 896, "text": null }, { "code": null, "e": 1309, "s": 1300, "text": "Output :" }, { "code": null, "e": 1629, "s": 1309, "text": "in_array : [-3.14159265 -2.57039399 -1.99919533 -1.42799666 -0.856798 -0.28559933\n 0.28559933 0.856798 1.42799666 1.99919533 2.57039399 3.14159265]\n\nout_array : [-0.99627208 -0.98836197 -0.96397069 -0.89125532 -0.69460424 -0.27807943\n 0.27807943 0.69460424 0.89125532 0.96397069 0.98836197 0.99627208]" }, { "code": null, "e": 1728, "s": 1629, "text": " References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.tanh.html#numpy.tanh." }, { "code": null, "e": 1763, "s": 1728, "text": "Python numpy-Mathematical Function" }, { "code": null, "e": 1776, "s": 1763, "text": "Python-numpy" }, { "code": null, "e": 1783, "s": 1776, "text": "Python" }, { "code": null, "e": 1881, "s": 1783, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1899, "s": 1881, "text": "Python Dictionary" }, { "code": null, "e": 1941, "s": 1899, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1963, "s": 1941, "text": "Enumerate() in Python" }, { "code": null, "e": 1998, "s": 1963, "text": "Read a file line by line in Python" }, { "code": null, "e": 2024, "s": 1998, "text": "Python String | replace()" }, { "code": null, "e": 2056, "s": 2024, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2085, "s": 2056, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2112, "s": 2085, "text": "Python Classes and Objects" }, { "code": null, "e": 2142, "s": 2112, "text": "Iterate over a list in Python" } ]