title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Types of Network Address Translation (NAT)
25 Oct, 2021 Prerequisite – Network address translation (NAT) Network Address Translation (NAT) is a process in which one or more local IP address is translated into one or more Global IP address and vice versa in order to provide Internet access to the local hosts. NAT generally operates on a router or firewall. Network address translation (NAT) working – Generally, the border router is configured for NAT i.e the router which has one interface in the local (inside) network and one interface in the global (outside) network. When a packet traverse outside the local (inside) network, then NAT converts that local (private) IP address to a global (public) IP address. When a packet enters the local network, the global (public) IP address is converted to a local (private) IP address. If NAT runs out of addresses, i.e., no address is left in the pool configured then the packets will be dropped and an Internet Control Message Protocol (ICMP) host unreachable packet to the destination is sent. NAT types – There are 3 types of NAT: 1. Static NAT – In this, a single private IP address is mapped with a single Public IP address, i.e., a private IP address is translated to a public IP address. It is used in Web hosting. Configuration – Here is a small topology in which there is PC having IP address 192.168.1.1/24, Router R1 having IP address 192.168.1.2/24 on interface fa0/0, 12.1.1.1/24 on fa0/1, and server having IP address 73.1.1.2/24. Now, inside local and inside global are shown in the figure. Configuring the static NAT through command IP nat inside source static INSIDE_LOCAL_IP_ADDRESS INSIDE_GLOBAL_IP_ADDRESS. R1(config)# ip nat inside source static 192.168.1.1 12.1.1.1 Now, we have configured the router’s inside interface as IP NAT inside and outside interface as IP NAT outside. R1(config)# int fa0/0 R1(config-if)# ip nat inside R1(config)# int fa0/1 R1(config-if)# ip nat outside 2. Dynamic NAT – In this type of NAT, multiple private IP addresses are mapped to a pool of public IP addresses. It is used when we know the number of fixed users who want to access the Internet at a given point in time. Configuration – There is a PC having IP address 192.168.1.1/24, Router R1 having IP address 192.168.1.2/24 on interface fa0/0, 12.1.1.1/24 on fa0/1, and a server having IP address 73.1.1.2/24. Now, first configuring the access-list: R1(config)# access-list 1 permit 192.168.1.0 0.0.0.255 Configuring the nat pool from which a public IP will be selected. R1(config)# ip nat pool pool1 12.1.1.1 12.1.1.3 netmask 255.255.255.0 Now, enabling Dynamic NAT: R1(config)# ip nat inside source list 1 pool pool1 At last, we have to configure router interfaces as inside or outside. R1(config)# int fa0/0 R1(config-if)# ip nat inside R1(config)# int fa0/1 R1(config-if)# ip nat outside 3. Port Address Translation (PAT) – This is also known as NAT overload. In this, many local (private) IP addresses can be translated to a single public IP address. Port numbers are used to distinguish the traffic, i.e., which traffic belongs to which IP address. This is most frequently used as it is cost-effective as thousands of users can be connected to the Internet by using only one real global (public) IP address. Configuration – Taking the same topology, There is PC1 having IP address 192.168.1.1/24, Router R1 has IP address 192.168.1.2/24 on interface fa0/0, 12.1.1.1/24 on fa0/1, and the server has IP address 73.1.1.2/24. Now, first configuring the access-list: R1(config)# access-list 1 permit 192.168.1.0 0.0.0.255 Configuring the nat pool from which a public IP will be selected. R1(config)# ip nat pool pool1 12.1.1.1 12.1.1.1 netmask 255.255.255.0 Here, note that the nat pool is shrunk to one IP address only and the IP address used is the outside interface IP address of the router. If you have additional IP then you can use that also. Now, enabling Dynamic NAT overload (PAT): R1(config)# ip nat inside source list 1 pool pool1 overload Or we can also use R1(config)# ip nat inside source list 1 interface fastEthernet 0/1 overload At last, we have to configure router interfaces as inside or outside. R1(config)# int fa0/0 R1(config-if)# ip nat inside R1(config)# int fa0/1 R1(config-if)# ip nat outside How NAT protect you:- -It hides the IP address of any devices on your network from the outside world giving them all a single address. -It requires every incoming packet of information to have been asked for by a device. if a malicious data packet isn’t on the list of expected communications it gets rejected. -Some firewalls can use whitelisting to block unauthorized outgoing traffic so if you do contract a piece of malware your firewall may prevent it from communicating with your device. deep089 vaibhavsinghtanwar Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n25 Oct, 2021" }, { "code": null, "e": 357, "s": 54, "text": "Prerequisite – Network address translation (NAT) Network Address Translation (NAT) is a process in which one or more local IP address is translated into one or more Global IP address and vice versa in order to provide Internet access to the local hosts. NAT generally operates on a router or firewall. " }, { "code": null, "e": 832, "s": 357, "text": "Network address translation (NAT) working – Generally, the border router is configured for NAT i.e the router which has one interface in the local (inside) network and one interface in the global (outside) network. When a packet traverse outside the local (inside) network, then NAT converts that local (private) IP address to a global (public) IP address. When a packet enters the local network, the global (public) IP address is converted to a local (private) IP address. " }, { "code": null, "e": 1044, "s": 832, "text": "If NAT runs out of addresses, i.e., no address is left in the pool configured then the packets will be dropped and an Internet Control Message Protocol (ICMP) host unreachable packet to the destination is sent. " }, { "code": null, "e": 1083, "s": 1044, "text": "NAT types – There are 3 types of NAT: " }, { "code": null, "e": 1272, "s": 1083, "text": "1. Static NAT – In this, a single private IP address is mapped with a single Public IP address, i.e., a private IP address is translated to a public IP address. It is used in Web hosting. " }, { "code": null, "e": 1289, "s": 1272, "text": "Configuration – " }, { "code": null, "e": 1499, "s": 1291, "text": "Here is a small topology in which there is PC having IP address 192.168.1.1/24, Router R1 having IP address 192.168.1.2/24 on interface fa0/0, 12.1.1.1/24 on fa0/1, and server having IP address 73.1.1.2/24. " }, { "code": null, "e": 1683, "s": 1499, "text": "Now, inside local and inside global are shown in the figure. Configuring the static NAT through command IP nat inside source static INSIDE_LOCAL_IP_ADDRESS INSIDE_GLOBAL_IP_ADDRESS. " }, { "code": null, "e": 1745, "s": 1683, "text": "R1(config)# ip nat inside source static 192.168.1.1 12.1.1.1 " }, { "code": null, "e": 1859, "s": 1745, "text": "Now, we have configured the router’s inside interface as IP NAT inside and outside interface as IP NAT outside. " }, { "code": null, "e": 1964, "s": 1859, "text": "R1(config)# int fa0/0\nR1(config-if)# ip nat inside \nR1(config)# int fa0/1\nR1(config-if)# ip nat outside " }, { "code": null, "e": 2186, "s": 1964, "text": "2. Dynamic NAT – In this type of NAT, multiple private IP addresses are mapped to a pool of public IP addresses. It is used when we know the number of fixed users who want to access the Internet at a given point in time. " }, { "code": null, "e": 2203, "s": 2186, "text": "Configuration – " }, { "code": null, "e": 2424, "s": 2205, "text": "There is a PC having IP address 192.168.1.1/24, Router R1 having IP address 192.168.1.2/24 on interface fa0/0, 12.1.1.1/24 on fa0/1, and a server having IP address 73.1.1.2/24. Now, first configuring the access-list: " }, { "code": null, "e": 2480, "s": 2424, "text": "R1(config)# access-list 1 permit 192.168.1.0 0.0.0.255 " }, { "code": null, "e": 2548, "s": 2480, "text": "Configuring the nat pool from which a public IP will be selected. " }, { "code": null, "e": 2619, "s": 2548, "text": "R1(config)# ip nat pool pool1 12.1.1.1 12.1.1.3 netmask 255.255.255.0 " }, { "code": null, "e": 2648, "s": 2619, "text": "Now, enabling Dynamic NAT: " }, { "code": null, "e": 2699, "s": 2648, "text": "R1(config)# ip nat inside source list 1 pool pool1" }, { "code": null, "e": 2771, "s": 2699, "text": "At last, we have to configure router interfaces as inside or outside. " }, { "code": null, "e": 2874, "s": 2771, "text": "R1(config)# int fa0/0\nR1(config-if)# ip nat inside\nR1(config)# int fa0/1\nR1(config-if)# ip nat outside" }, { "code": null, "e": 3297, "s": 2874, "text": "3. Port Address Translation (PAT) – This is also known as NAT overload. In this, many local (private) IP addresses can be translated to a single public IP address. Port numbers are used to distinguish the traffic, i.e., which traffic belongs to which IP address. This is most frequently used as it is cost-effective as thousands of users can be connected to the Internet by using only one real global (public) IP address. " }, { "code": null, "e": 3314, "s": 3297, "text": "Configuration – " }, { "code": null, "e": 3556, "s": 3316, "text": "Taking the same topology, There is PC1 having IP address 192.168.1.1/24, Router R1 has IP address 192.168.1.2/24 on interface fa0/0, 12.1.1.1/24 on fa0/1, and the server has IP address 73.1.1.2/24. Now, first configuring the access-list: " }, { "code": null, "e": 3612, "s": 3556, "text": "R1(config)# access-list 1 permit 192.168.1.0 0.0.0.255 " }, { "code": null, "e": 3680, "s": 3612, "text": "Configuring the nat pool from which a public IP will be selected. " }, { "code": null, "e": 3750, "s": 3680, "text": "R1(config)# ip nat pool pool1 12.1.1.1 12.1.1.1 netmask 255.255.255.0" }, { "code": null, "e": 3985, "s": 3750, "text": "Here, note that the nat pool is shrunk to one IP address only and the IP address used is the outside interface IP address of the router. If you have additional IP then you can use that also. Now, enabling Dynamic NAT overload (PAT): " }, { "code": null, "e": 4045, "s": 3985, "text": "R1(config)# ip nat inside source list 1 pool pool1 overload" }, { "code": null, "e": 4066, "s": 4045, "text": "Or we can also use " }, { "code": null, "e": 4142, "s": 4066, "text": "R1(config)# ip nat inside source list 1 interface fastEthernet 0/1 overload" }, { "code": null, "e": 4214, "s": 4142, "text": "At last, we have to configure router interfaces as inside or outside. " }, { "code": null, "e": 4317, "s": 4214, "text": "R1(config)# int fa0/0\nR1(config-if)# ip nat inside\nR1(config)# int fa0/1\nR1(config-if)# ip nat outside" }, { "code": null, "e": 4339, "s": 4317, "text": "How NAT protect you:-" }, { "code": null, "e": 4452, "s": 4339, "text": "-It hides the IP address of any devices on your network from the outside world giving them all a single address." }, { "code": null, "e": 4628, "s": 4452, "text": "-It requires every incoming packet of information to have been asked for by a device. if a malicious data packet isn’t on the list of expected communications it gets rejected." }, { "code": null, "e": 4811, "s": 4628, "text": "-Some firewalls can use whitelisting to block unauthorized outgoing traffic so if you do contract a piece of malware your firewall may prevent it from communicating with your device." }, { "code": null, "e": 4819, "s": 4811, "text": "deep089" }, { "code": null, "e": 4838, "s": 4819, "text": "vaibhavsinghtanwar" }, { "code": null, "e": 4856, "s": 4838, "text": "Computer Networks" }, { "code": null, "e": 4874, "s": 4856, "text": "Computer Networks" } ]
Convert Matrix to Vector in R
06 Sep, 2021 In this article, we are going to convert the given matrix into the vector in R programming language. Simply passing the name of the matrix will do the job. Syntax: c(matrix_name) Where matrix_name is the name of the input matrix Example 1: R # create a matrix with 12 elements# with 4 rows and 3 columnsmatrix=matrix(1:12,nrow=4,ncol=3)print(matrix) # convert matrix to vector using c()# functiona=c(matrix) print(a) Output: Example 2: R # create a matrix with 16 elements# with 4 rows and 4 columnsmatrix=matrix(1:16,nrow=4,ncol=4)print(matrix) # convert matrix to vector using# c() functiona=c(matrix) print(a) Output: This function is used to convert matrix to vector so again simply passing the matrix name is enough. Syntax: as.vector(matrix) Example: R # create a matrix with 12 elements# with 4 rows and 3 columnsmatrix=matrix(1:12,nrow=4,ncol=3)print(matrix) # convert matrix to vector using# as.vector() functiona=as.vector(matrix) print(a) Output: Example 2: R # create a matrix with 16 elements with 4 rows and 4 columnsmatrix=matrix(1:16,nrow=4,ncol=4)print(matrix) # convert matrix to vector using as.vector() functiona=as.vector(matrix) print(a) Output t() function is used to transpose the given matrix. It will transpose rows as columns and columns as rows. Syntax: t(matrix) where the matrix is the input matrix After applying t() we can apply c() and as.vector() functions to convert the matrix to vector Syntax: c(t(matrix)) Example 1: R # create a matrix with 12 elements# with 4 rows and 3 columnsmatrix=matrix(1:12,nrow=4,ncol=3)print(matrix) # convert matrix to vector using# c() function along with t()a=c(t(matrix)) print(a) Output: Example 2: R # create a matrix with 12 elements# with 2 rows and 6 columnsmatrix=matrix(1:12,nrow=2,ncol=6)print(matrix) # convert matrix to vector using# c() function along with t()a=c(t(matrix)) print(a) Output: The work of t() is same as above. After the transpose has been taken, the matrix is converted to vector using as.vector(). Syntax: as.vector(t(matrix)) Example R # create a matrix with 12 elements# with 2 rows and 6 columnsmatrix=matrix(1:12,nrow=2,ncol=6)print(matrix) # convert matrix to vector using# as.vector() function along with t()a=as.vector(t(matrix)) print(a) Output: Example 2: R # create a matrix with 4 elements# with 2 rows and 2 columnsmatrix=matrix(1:4,nrow=2,ncol=2)print(matrix) # convert matrix to vector using# as.vector() function along with t()a=as.vector(t(matrix)) print(a) Output as5853535 sweetyty Picked R Matrix-Programs R Vector-Programs R-Matrix R-Vectors R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Sep, 2021" }, { "code": null, "e": 129, "s": 28, "text": "In this article, we are going to convert the given matrix into the vector in R programming language." }, { "code": null, "e": 184, "s": 129, "text": "Simply passing the name of the matrix will do the job." }, { "code": null, "e": 192, "s": 184, "text": "Syntax:" }, { "code": null, "e": 207, "s": 192, "text": "c(matrix_name)" }, { "code": null, "e": 257, "s": 207, "text": "Where matrix_name is the name of the input matrix" }, { "code": null, "e": 268, "s": 257, "text": "Example 1:" }, { "code": null, "e": 270, "s": 268, "text": "R" }, { "code": "# create a matrix with 12 elements# with 4 rows and 3 columnsmatrix=matrix(1:12,nrow=4,ncol=3)print(matrix) # convert matrix to vector using c()# functiona=c(matrix) print(a)", "e": 445, "s": 270, "text": null }, { "code": null, "e": 456, "s": 448, "text": "Output:" }, { "code": null, "e": 471, "s": 460, "text": "Example 2:" }, { "code": null, "e": 475, "s": 473, "text": "R" }, { "code": "# create a matrix with 16 elements# with 4 rows and 4 columnsmatrix=matrix(1:16,nrow=4,ncol=4)print(matrix) # convert matrix to vector using# c() functiona=c(matrix) print(a)", "e": 650, "s": 475, "text": null }, { "code": null, "e": 661, "s": 653, "text": "Output:" }, { "code": null, "e": 762, "s": 661, "text": "This function is used to convert matrix to vector so again simply passing the matrix name is enough." }, { "code": null, "e": 771, "s": 762, "text": "Syntax: " }, { "code": null, "e": 789, "s": 771, "text": "as.vector(matrix)" }, { "code": null, "e": 801, "s": 791, "text": "Example: " }, { "code": null, "e": 803, "s": 801, "text": "R" }, { "code": "# create a matrix with 12 elements# with 4 rows and 3 columnsmatrix=matrix(1:12,nrow=4,ncol=3)print(matrix) # convert matrix to vector using# as.vector() functiona=as.vector(matrix) print(a)", "e": 994, "s": 803, "text": null }, { "code": null, "e": 1005, "s": 997, "text": "Output:" }, { "code": null, "e": 1018, "s": 1007, "text": "Example 2:" }, { "code": null, "e": 1020, "s": 1018, "text": "R" }, { "code": "# create a matrix with 16 elements with 4 rows and 4 columnsmatrix=matrix(1:16,nrow=4,ncol=4)print(matrix) # convert matrix to vector using as.vector() functiona=as.vector(matrix) print(a)", "e": 1209, "s": 1020, "text": null }, { "code": null, "e": 1220, "s": 1212, "text": "Output " }, { "code": null, "e": 1329, "s": 1222, "text": "t() function is used to transpose the given matrix. It will transpose rows as columns and columns as rows." }, { "code": null, "e": 1337, "s": 1329, "text": "Syntax:" }, { "code": null, "e": 1347, "s": 1337, "text": "t(matrix)" }, { "code": null, "e": 1384, "s": 1347, "text": "where the matrix is the input matrix" }, { "code": null, "e": 1480, "s": 1386, "text": "After applying t() we can apply c() and as.vector() functions to convert the matrix to vector" }, { "code": null, "e": 1490, "s": 1482, "text": "Syntax:" }, { "code": null, "e": 1503, "s": 1490, "text": "c(t(matrix))" }, { "code": null, "e": 1516, "s": 1505, "text": "Example 1:" }, { "code": null, "e": 1518, "s": 1516, "text": "R" }, { "code": "# create a matrix with 12 elements# with 4 rows and 3 columnsmatrix=matrix(1:12,nrow=4,ncol=3)print(matrix) # convert matrix to vector using# c() function along with t()a=c(t(matrix)) print(a)", "e": 1711, "s": 1518, "text": null }, { "code": null, "e": 1722, "s": 1714, "text": "Output:" }, { "code": null, "e": 1735, "s": 1724, "text": "Example 2:" }, { "code": null, "e": 1737, "s": 1735, "text": "R" }, { "code": "# create a matrix with 12 elements# with 2 rows and 6 columnsmatrix=matrix(1:12,nrow=2,ncol=6)print(matrix) # convert matrix to vector using# c() function along with t()a=c(t(matrix)) print(a)", "e": 1930, "s": 1737, "text": null }, { "code": null, "e": 1941, "s": 1933, "text": "Output:" }, { "code": null, "e": 2066, "s": 1943, "text": "The work of t() is same as above. After the transpose has been taken, the matrix is converted to vector using as.vector()." }, { "code": null, "e": 2074, "s": 2066, "text": "Syntax:" }, { "code": null, "e": 2095, "s": 2074, "text": "as.vector(t(matrix))" }, { "code": null, "e": 2105, "s": 2097, "text": "Example" }, { "code": null, "e": 2107, "s": 2105, "text": "R" }, { "code": "# create a matrix with 12 elements# with 2 rows and 6 columnsmatrix=matrix(1:12,nrow=2,ncol=6)print(matrix) # convert matrix to vector using# as.vector() function along with t()a=as.vector(t(matrix)) print(a)", "e": 2316, "s": 2107, "text": null }, { "code": null, "e": 2327, "s": 2319, "text": "Output:" }, { "code": null, "e": 2340, "s": 2329, "text": "Example 2:" }, { "code": null, "e": 2342, "s": 2340, "text": "R" }, { "code": "# create a matrix with 4 elements# with 2 rows and 2 columnsmatrix=matrix(1:4,nrow=2,ncol=2)print(matrix) # convert matrix to vector using# as.vector() function along with t()a=as.vector(t(matrix)) print(a)", "e": 2549, "s": 2342, "text": null }, { "code": null, "e": 2556, "s": 2549, "text": "Output" }, { "code": null, "e": 2568, "s": 2558, "text": "as5853535" }, { "code": null, "e": 2577, "s": 2568, "text": "sweetyty" }, { "code": null, "e": 2584, "s": 2577, "text": "Picked" }, { "code": null, "e": 2602, "s": 2584, "text": "R Matrix-Programs" }, { "code": null, "e": 2620, "s": 2602, "text": "R Vector-Programs" }, { "code": null, "e": 2629, "s": 2620, "text": "R-Matrix" }, { "code": null, "e": 2639, "s": 2629, "text": "R-Vectors" }, { "code": null, "e": 2650, "s": 2639, "text": "R Language" }, { "code": null, "e": 2661, "s": 2650, "text": "R Programs" } ]
PostgreSQL – Interval Data Type
30 Sep, 2021 In PostgreSQL the interval data type is used to store and manipulate a time period. It holds 16 bytes of space and ranging from -178, 000, 000 years to 178, 000, 000 years. It also has additional attribute called “precision (denoted by p)” that can be used to set the level of precision in the query results. Syntax:interval [ Data_fields ] [ (p) ] Where, Data_fields: Time period p: precision PostgreSQL stores the interval type value in the integer form of days and months whereas for values in seconds, it can be fractions. Now let’s jump into a few examples for demonstration. Example 1: In this example we will query to know the time of 4 hours 25 minutes ago at the current time of last year using the below commands: SELECT now(), now() - INTERVAL '1 year 4 hours 25 minutes' AS "4 hours 25 minutes ago of last year"; Output: Example 2: In this example we will convert an interval value ta string format using the TO_CHAR() function.The TO_CHAR() function takes the first argument as an interval value, the second one as the format, and returns a string that represents the interval in the specified format. SELECT TO_CHAR( INTERVAL '15h 25m 12s', 'HH24:MI:SS' ); Output: kashishsoda postgreSQL postgreSQL-dataTypes PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Sep, 2021" }, { "code": null, "e": 338, "s": 28, "text": "In PostgreSQL the interval data type is used to store and manipulate a time period. It holds 16 bytes of space and ranging from -178, 000, 000 years to 178, 000, 000 years. It also has additional attribute called “precision (denoted by p)” that can be used to set the level of precision in the query results. " }, { "code": null, "e": 426, "s": 340, "text": "Syntax:interval [ Data_fields ] [ (p) ]\n\nWhere,\nData_fields: Time period\np: precision" }, { "code": null, "e": 758, "s": 426, "text": "PostgreSQL stores the interval type value in the integer form of days and months whereas for values in seconds, it can be fractions. Now let’s jump into a few examples for demonstration. Example 1: In this example we will query to know the time of 4 hours 25 minutes ago at the current time of last year using the below commands: " }, { "code": null, "e": 881, "s": 758, "text": "SELECT\n now(),\n now() - INTERVAL '1 year 4 hours 25 minutes' \n AS \"4 hours 25 minutes ago of last year\";" }, { "code": null, "e": 891, "s": 881, "text": "Output: " }, { "code": null, "e": 1175, "s": 891, "text": "Example 2: In this example we will convert an interval value ta string format using the TO_CHAR() function.The TO_CHAR() function takes the first argument as an interval value, the second one as the format, and returns a string that represents the interval in the specified format. " }, { "code": null, "e": 1255, "s": 1175, "text": "SELECT\n TO_CHAR(\n INTERVAL '15h 25m 12s',\n 'HH24:MI:SS'\n );" }, { "code": null, "e": 1265, "s": 1255, "text": "Output: " }, { "code": null, "e": 1279, "s": 1267, "text": "kashishsoda" }, { "code": null, "e": 1290, "s": 1279, "text": "postgreSQL" }, { "code": null, "e": 1311, "s": 1290, "text": "postgreSQL-dataTypes" }, { "code": null, "e": 1322, "s": 1311, "text": "PostgreSQL" } ]
Variable Shadowing in Python
04 Jan, 2022 In this article, we will understand the concept of variable shadowing in a Python programming language. To understand this concept, we need to be well versed with the scope of a lifetime of variables in python. When we define a function, we can create variables that are scoped only to that function and are not accessible outside of the function. These variables are referred to as local variables ( as they are local to the function ) Python3 def fn(): # local variable a a = 3 print(a) # Error, variable a referenced before # assignmentprint(a) Output: NameError: name 'a' is not defined Variables are defined outside of any function and are potentially accessible anywhere in the program. Python3 # global variablea = 3 def fn(): # print 3 print(a) # print 3print(a) Output: 3 Note: For more information, refer to our Global and Local Variables in Python Variable shadowing occurs when a variable defined in the inner scope has the same name as a variable in the outer scope. Consider the example below, here the variable inside the function has the same name as a global variable. In this program, there are two versions of variable a, one which is defined globally and the other which is defined within the context of the function. Python treats these variables as completely separate variables. The global variable a is said to be shadowed by the local variable a. The way outer and inner variables with the same name are handled depends upon the name resolution rules of the language. Python3 # global variablea = 3 def fn(): # local variable a = 5 print(a) # prints 5 fn()print(a) # prints 3 5 3 To modify a global variable, and avoid variable shadowing python provides global keyword which tells python to use the global version of the variable, instead of creating a new locally scoped variable. Python3 # global variablea = 3 def fn(): global a # global variable modified a = 5 print(a) # prints 5 print(a) # prints 5fn() Output: 3 5 To avoid variable shadowing at the function level, meaning if a variable in outer function has the same name as a variable in an inner function, python provides nonlocal keyword which tells python to use the variable defined in the outer function, instead of creating a new locally scoped variable Python3 def outer(): a = 5 def inner(): nonlocal a a = 3 print(a) # prints 3 inner() print(a) # prints 3 outer() Output: 3 3 python-basics Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Jan, 2022" }, { "code": null, "e": 240, "s": 28, "text": "In this article, we will understand the concept of variable shadowing in a Python programming language. To understand this concept, we need to be well versed with the scope of a lifetime of variables in python. " }, { "code": null, "e": 466, "s": 240, "text": "When we define a function, we can create variables that are scoped only to that function and are not accessible outside of the function. These variables are referred to as local variables ( as they are local to the function )" }, { "code": null, "e": 474, "s": 466, "text": "Python3" }, { "code": "def fn(): # local variable a a = 3 print(a) # Error, variable a referenced before # assignmentprint(a) ", "e": 596, "s": 474, "text": null }, { "code": null, "e": 604, "s": 596, "text": "Output:" }, { "code": null, "e": 639, "s": 604, "text": "NameError: name 'a' is not defined" }, { "code": null, "e": 741, "s": 639, "text": "Variables are defined outside of any function and are potentially accessible anywhere in the program." }, { "code": null, "e": 749, "s": 741, "text": "Python3" }, { "code": "# global variablea = 3 def fn(): # print 3 print(a) # print 3print(a) ", "e": 835, "s": 749, "text": null }, { "code": null, "e": 843, "s": 835, "text": "Output:" }, { "code": null, "e": 845, "s": 843, "text": "3" }, { "code": null, "e": 923, "s": 845, "text": "Note: For more information, refer to our Global and Local Variables in Python" }, { "code": null, "e": 1557, "s": 923, "text": "Variable shadowing occurs when a variable defined in the inner scope has the same name as a variable in the outer scope. Consider the example below, here the variable inside the function has the same name as a global variable. In this program, there are two versions of variable a, one which is defined globally and the other which is defined within the context of the function. Python treats these variables as completely separate variables. The global variable a is said to be shadowed by the local variable a. The way outer and inner variables with the same name are handled depends upon the name resolution rules of the language." }, { "code": null, "e": 1565, "s": 1557, "text": "Python3" }, { "code": "# global variablea = 3 def fn(): # local variable a = 5 print(a) # prints 5 fn()print(a) # prints 3", "e": 1674, "s": 1565, "text": null }, { "code": null, "e": 1679, "s": 1674, "text": "5\n3\n" }, { "code": null, "e": 1881, "s": 1679, "text": "To modify a global variable, and avoid variable shadowing python provides global keyword which tells python to use the global version of the variable, instead of creating a new locally scoped variable." }, { "code": null, "e": 1889, "s": 1881, "text": "Python3" }, { "code": "# global variablea = 3 def fn(): global a # global variable modified a = 5 print(a) # prints 5 print(a) # prints 5fn()", "e": 2020, "s": 1889, "text": null }, { "code": null, "e": 2028, "s": 2020, "text": "Output:" }, { "code": null, "e": 2032, "s": 2028, "text": "3\n5" }, { "code": null, "e": 2330, "s": 2032, "text": "To avoid variable shadowing at the function level, meaning if a variable in outer function has the same name as a variable in an inner function, python provides nonlocal keyword which tells python to use the variable defined in the outer function, instead of creating a new locally scoped variable" }, { "code": null, "e": 2338, "s": 2330, "text": "Python3" }, { "code": "def outer(): a = 5 def inner(): nonlocal a a = 3 print(a) # prints 3 inner() print(a) # prints 3 outer()", "e": 2465, "s": 2338, "text": null }, { "code": null, "e": 2473, "s": 2465, "text": "Output:" }, { "code": null, "e": 2477, "s": 2473, "text": "3\n3" }, { "code": null, "e": 2491, "s": 2477, "text": "python-basics" }, { "code": null, "e": 2498, "s": 2491, "text": "Python" } ]
BufferedReader close() method in Java with Examples
05 Jun, 2020 The close() method of BufferedReader class in Java is used to close the stream and release all the system resources associated with the stream operations. Syntax: public void close() throws IOException Parameters: This method does not accept any parameter. Return value: This method does not return any value. Exception: This method throws IOException if an I/O error occurs. Below programs illustrate close() method in BufferedReader class in IO package: Program 1: Assume the existence of the file “c:/demo.txt”. // Java program to illustrate// BufferedReader close() method import java.io.*;public class GFG { public static void main(String[] args) throws IOException { // Read stream file 'demo.txt' // containing text "GEEKSFORGEEKS" FileReader fileReader = new FileReader( "c:/demo.txt"); // Convert fileReader to // bufferedReader BufferedReader buffReader = new BufferedReader( fileReader); // Call read() method while (buffReader.ready()) { System.out.print( (char)buffReader.read()); } // Call close() method buffReader.close(); }} Program 2: Assume the existence of the file “c:/demo.txt”. // Java program to illustrate// BufferedReader close() method import java.io.*;public class GFG { public static void main(String[] args) throws IOException { try { // Read stream file 'demo.txt' // containing text "GEEKSFORGEEKS" FileReader fileReader = new FileReader( "c:/demo.txt"); // Convert fileReader to // bufferedReader BufferedReader buffReader = new BufferedReader( fileReader); // Call close() method buffReader.close(); // Call read() method System.out.print( (char)buffReader.read()); } catch (IOException e) { // Exception is thrown System.out.println( "BufferedReader is closed"); } }} Reference: https://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#close() Java-Functions Java-IO package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Collections in Java Multidimensional Arrays in Java Stream In Java Singleton Class in Java Set in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Jun, 2020" }, { "code": null, "e": 183, "s": 28, "text": "The close() method of BufferedReader class in Java is used to close the stream and release all the system resources associated with the stream operations." }, { "code": null, "e": 191, "s": 183, "text": "Syntax:" }, { "code": null, "e": 244, "s": 191, "text": "public void close() \n throws IOException\n" }, { "code": null, "e": 299, "s": 244, "text": "Parameters: This method does not accept any parameter." }, { "code": null, "e": 352, "s": 299, "text": "Return value: This method does not return any value." }, { "code": null, "e": 418, "s": 352, "text": "Exception: This method throws IOException if an I/O error occurs." }, { "code": null, "e": 498, "s": 418, "text": "Below programs illustrate close() method in BufferedReader class in IO package:" }, { "code": null, "e": 557, "s": 498, "text": "Program 1: Assume the existence of the file “c:/demo.txt”." }, { "code": "// Java program to illustrate// BufferedReader close() method import java.io.*;public class GFG { public static void main(String[] args) throws IOException { // Read stream file 'demo.txt' // containing text \"GEEKSFORGEEKS\" FileReader fileReader = new FileReader( \"c:/demo.txt\"); // Convert fileReader to // bufferedReader BufferedReader buffReader = new BufferedReader( fileReader); // Call read() method while (buffReader.ready()) { System.out.print( (char)buffReader.read()); } // Call close() method buffReader.close(); }}", "e": 1264, "s": 557, "text": null }, { "code": null, "e": 1323, "s": 1264, "text": "Program 2: Assume the existence of the file “c:/demo.txt”." }, { "code": "// Java program to illustrate// BufferedReader close() method import java.io.*;public class GFG { public static void main(String[] args) throws IOException { try { // Read stream file 'demo.txt' // containing text \"GEEKSFORGEEKS\" FileReader fileReader = new FileReader( \"c:/demo.txt\"); // Convert fileReader to // bufferedReader BufferedReader buffReader = new BufferedReader( fileReader); // Call close() method buffReader.close(); // Call read() method System.out.print( (char)buffReader.read()); } catch (IOException e) { // Exception is thrown System.out.println( \"BufferedReader is closed\"); } }}", "e": 2208, "s": 1323, "text": null }, { "code": null, "e": 2297, "s": 2208, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#close()" }, { "code": null, "e": 2312, "s": 2297, "text": "Java-Functions" }, { "code": null, "e": 2328, "s": 2312, "text": "Java-IO package" }, { "code": null, "e": 2333, "s": 2328, "text": "Java" }, { "code": null, "e": 2338, "s": 2333, "text": "Java" }, { "code": null, "e": 2436, "s": 2338, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2487, "s": 2436, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 2518, "s": 2487, "text": "How to iterate any Map in Java" }, { "code": null, "e": 2537, "s": 2518, "text": "Interfaces in Java" }, { "code": null, "e": 2567, "s": 2537, "text": "HashMap in Java with Examples" }, { "code": null, "e": 2585, "s": 2567, "text": "ArrayList in Java" }, { "code": null, "e": 2605, "s": 2585, "text": "Collections in Java" }, { "code": null, "e": 2637, "s": 2605, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 2652, "s": 2637, "text": "Stream In Java" }, { "code": null, "e": 2676, "s": 2652, "text": "Singleton Class in Java" } ]
How to save file with file name from user using Python?
13 Jan, 2021 Prerequisites: File Handling in Python Reading and Writing to text files in Python Saving a file with the user’s custom name can be achieved using python file handling concepts. Python provides inbuilt functions for working with files. The file can be saved with the user preferred name by creating a new file, renaming the existing file, making a copy of a file(Save As). Let’s discuss these in detail. Method 1: Using open() function We can create a new file using the open() function with one of the access modes listed below. Syntax: open( filepath , mode ) Access modes: Write Only (‘w’): Creates a new file for writing, if the file doesn’t exist otherwise truncates and over-write existing file. Write and Read (‘w+’): Creates a new file for reading & writing, if the file doesn’t exist otherwise truncates and over-write existing file. Append Only (‘a’): Creates a new file for writing, if the file doesn’t exist otherwise data being written will be inserted at the end of the file. Append and Read (‘a+’): Creates a new file for reading & writing, if the file doesn’t exist otherwise data being written will be inserted at the end of the file. Approach Get file name from the user Open a file with mentioned access mode Create this file with the entered name Example: Python3 # path of this scriptdirectory = "D:\gfg\\" # get fileName from userfilepath = directory + input("Enter filename: ") # Creates a new filewith open(filepath, 'w+') as fp: pass Output: Enter filename: newgfgfile.txt Method 2: Using pathlib library pathlib offers a set of classes to handle filesystem paths. We can use touch() method to create the file at a given path it updates the file modification time with the current time and marks exist_ok as True, otherwise, FileExistsError is raised. Syntax: Path.touch(mode=0o666, exist_ok=True) Approach Import module Get file name from the user Create a file with the entered name Example: Python3 # import pathlib moduleimport pathlib # path of this scriptdirectory = "D:\gfg\\" # get fileName from userfilepath = directory + input("Enter filename:") # To create a filepathlib.Path(filepath).touch() Output: Enter filename:gfgfile2.txt Method 1: Using the os module Python’s OS module includes functions to communicate with the operating system. Here, we can use rename() method to save a file with the name specified by the user. Syntax: rename(src, dest, *, src_dir_fd=None, dst_dir_fd=None) Approach: Import module Get source file name Get destination file name Rename the source file to destination file or directory If destination file already exists, the operation will fail with an OSError. Example: Python3 # import os libraryimport os # get source file namesrc = input("Enter src filename:") # get destination file namedest = input("Enter dest filename:") # rename source file name with destination file nameos.rename(src, dest) Output: Enter src filename:D:\gfg\newgfgfile.txt Enter dest filename:D:\gfg\renamedfile1.txt Method 2: Using pathlib library pathlib also provides rename() function to change the name of a file which more or less serves the same purpose as given above. syntax: Path(filepath).rename(target) Approach: Import module Get source file name Get destination file name Rename source file or directory to the destination specified Return a new instance of the Path to the destination. (On Unix, if the target exists and the user has permission, it will be replaced.) Example: Python3 # import pathlib moduleimport pathlib # get source file namesrc = input("Enter src filename:") # get destination file nametarget = input("Enter target filename:") # rename source file name with target file namepathlib.Path(src).rename(target) Output: Enter src filename:D:\gfg\gfgfile2.txt Enter target filename:D:\gfg\renamedfile2.txt Method 1: Using the os module We can use popen() method to make a copy of the source file to the target file with the name specified by the user. Syntax: popen( command, mode , buffersize ) os.popen() get command to be performed as the first argument, access mode as the second argument which can be read (‘r’) or write (‘w’) and finally buffer size. The default mode is read and 0 for no buffering, positive integers for buffer size. Approach: Import module Get source file name Get destination file name Copy source to destination Example: Python # import os moduleimport os # get source file namesrc = input("Enter src filename:") # get destination file namedestination = input("Enter target filename:") # copies source to destination fileos.popen(f"copy {src} {destination}") Output: Enter src filename:D:\gfg\renamedfile1.txt Enter target filename:D:\gfg\copied-renamedfile1.txt Method 2: Using the shutil module The shutil module offers several high-level operations on files and collections of files. Its copyfile() method is used to rename the file with the user preferred name. Syntax: shutil.copyfile(src_file, dest_file, *, follow_symlinks=True) Approach: Import module Get source file name Get destination file name Copy source file to a new destination file. If both file names specify the same file, SameFileError is raised and if destination file already exists, it will be replaced. Example: Python3 # import shutil moduleimport shutil # get source file namesrc = input("Enter src filename:") # get destination file namedest = input("Enter target filename:") # copies source file to a new destination fileshutil.copyfile(src, dest) Output: Enter src filename:D:\gfg\renamedfile2.txt Enter target filename:D:\gfg\copied-renamedfile2.txt Picked Python file-handling-programs python-file-handling 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": "\n13 Jan, 2021" }, { "code": null, "e": 43, "s": 28, "text": "Prerequisites:" }, { "code": null, "e": 67, "s": 43, "text": "File Handling in Python" }, { "code": null, "e": 111, "s": 67, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 434, "s": 111, "text": "Saving a file with the user’s custom name can be achieved using python file handling concepts. Python provides inbuilt functions for working with files. The file can be saved with the user preferred name by creating a new file, renaming the existing file, making a copy of a file(Save As). Let’s discuss these in detail. " }, { "code": null, "e": 466, "s": 434, "text": "Method 1: Using open() function" }, { "code": null, "e": 562, "s": 466, "text": "We can create a new file using the open() function with one of the access modes listed below. " }, { "code": null, "e": 572, "s": 562, "text": "Syntax: " }, { "code": null, "e": 596, "s": 572, "text": "open( filepath , mode )" }, { "code": null, "e": 610, "s": 596, "text": "Access modes:" }, { "code": null, "e": 736, "s": 610, "text": "Write Only (‘w’): Creates a new file for writing, if the file doesn’t exist otherwise truncates and over-write existing file." }, { "code": null, "e": 877, "s": 736, "text": "Write and Read (‘w+’): Creates a new file for reading & writing, if the file doesn’t exist otherwise truncates and over-write existing file." }, { "code": null, "e": 1024, "s": 877, "text": "Append Only (‘a’): Creates a new file for writing, if the file doesn’t exist otherwise data being written will be inserted at the end of the file." }, { "code": null, "e": 1186, "s": 1024, "text": "Append and Read (‘a+’): Creates a new file for reading & writing, if the file doesn’t exist otherwise data being written will be inserted at the end of the file." }, { "code": null, "e": 1195, "s": 1186, "text": "Approach" }, { "code": null, "e": 1223, "s": 1195, "text": "Get file name from the user" }, { "code": null, "e": 1262, "s": 1223, "text": "Open a file with mentioned access mode" }, { "code": null, "e": 1301, "s": 1262, "text": "Create this file with the entered name" }, { "code": null, "e": 1310, "s": 1301, "text": "Example:" }, { "code": null, "e": 1318, "s": 1310, "text": "Python3" }, { "code": "# path of this scriptdirectory = \"D:\\gfg\\\\\" # get fileName from userfilepath = directory + input(\"Enter filename: \") # Creates a new filewith open(filepath, 'w+') as fp: pass", "e": 1498, "s": 1318, "text": null }, { "code": null, "e": 1506, "s": 1498, "text": "Output:" }, { "code": null, "e": 1537, "s": 1506, "text": "Enter filename: newgfgfile.txt" }, { "code": null, "e": 1569, "s": 1537, "text": "Method 2: Using pathlib library" }, { "code": null, "e": 1816, "s": 1569, "text": "pathlib offers a set of classes to handle filesystem paths. We can use touch() method to create the file at a given path it updates the file modification time with the current time and marks exist_ok as True, otherwise, FileExistsError is raised." }, { "code": null, "e": 1825, "s": 1816, "text": "Syntax: " }, { "code": null, "e": 1863, "s": 1825, "text": "Path.touch(mode=0o666, exist_ok=True)" }, { "code": null, "e": 1872, "s": 1863, "text": "Approach" }, { "code": null, "e": 1886, "s": 1872, "text": "Import module" }, { "code": null, "e": 1914, "s": 1886, "text": "Get file name from the user" }, { "code": null, "e": 1950, "s": 1914, "text": "Create a file with the entered name" }, { "code": null, "e": 1959, "s": 1950, "text": "Example:" }, { "code": null, "e": 1967, "s": 1959, "text": "Python3" }, { "code": "# import pathlib moduleimport pathlib # path of this scriptdirectory = \"D:\\gfg\\\\\" # get fileName from userfilepath = directory + input(\"Enter filename:\") # To create a filepathlib.Path(filepath).touch()", "e": 2173, "s": 1967, "text": null }, { "code": null, "e": 2181, "s": 2173, "text": "Output:" }, { "code": null, "e": 2209, "s": 2181, "text": "Enter filename:gfgfile2.txt" }, { "code": null, "e": 2239, "s": 2209, "text": "Method 1: Using the os module" }, { "code": null, "e": 2404, "s": 2239, "text": "Python’s OS module includes functions to communicate with the operating system. Here, we can use rename() method to save a file with the name specified by the user." }, { "code": null, "e": 2413, "s": 2404, "text": "Syntax: " }, { "code": null, "e": 2468, "s": 2413, "text": "rename(src, dest, *, src_dir_fd=None, dst_dir_fd=None)" }, { "code": null, "e": 2478, "s": 2468, "text": "Approach:" }, { "code": null, "e": 2492, "s": 2478, "text": "Import module" }, { "code": null, "e": 2513, "s": 2492, "text": "Get source file name" }, { "code": null, "e": 2539, "s": 2513, "text": "Get destination file name" }, { "code": null, "e": 2595, "s": 2539, "text": "Rename the source file to destination file or directory" }, { "code": null, "e": 2672, "s": 2595, "text": "If destination file already exists, the operation will fail with an OSError." }, { "code": null, "e": 2681, "s": 2672, "text": "Example:" }, { "code": null, "e": 2689, "s": 2681, "text": "Python3" }, { "code": "# import os libraryimport os # get source file namesrc = input(\"Enter src filename:\") # get destination file namedest = input(\"Enter dest filename:\") # rename source file name with destination file nameos.rename(src, dest)", "e": 2915, "s": 2689, "text": null }, { "code": null, "e": 2923, "s": 2915, "text": "Output:" }, { "code": null, "e": 2965, "s": 2923, "text": "Enter src filename:D:\\gfg\\newgfgfile.txt " }, { "code": null, "e": 3009, "s": 2965, "text": "Enter dest filename:D:\\gfg\\renamedfile1.txt" }, { "code": null, "e": 3041, "s": 3009, "text": "Method 2: Using pathlib library" }, { "code": null, "e": 3170, "s": 3041, "text": "pathlib also provides rename() function to change the name of a file which more or less serves the same purpose as given above. " }, { "code": null, "e": 3178, "s": 3170, "text": "syntax:" }, { "code": null, "e": 3210, "s": 3178, "text": " Path(filepath).rename(target) " }, { "code": null, "e": 3220, "s": 3210, "text": "Approach:" }, { "code": null, "e": 3234, "s": 3220, "text": "Import module" }, { "code": null, "e": 3255, "s": 3234, "text": "Get source file name" }, { "code": null, "e": 3281, "s": 3255, "text": "Get destination file name" }, { "code": null, "e": 3342, "s": 3281, "text": "Rename source file or directory to the destination specified" }, { "code": null, "e": 3478, "s": 3342, "text": "Return a new instance of the Path to the destination. (On Unix, if the target exists and the user has permission, it will be replaced.)" }, { "code": null, "e": 3487, "s": 3478, "text": "Example:" }, { "code": null, "e": 3495, "s": 3487, "text": "Python3" }, { "code": "# import pathlib moduleimport pathlib # get source file namesrc = input(\"Enter src filename:\") # get destination file nametarget = input(\"Enter target filename:\") # rename source file name with target file namepathlib.Path(src).rename(target)", "e": 3741, "s": 3495, "text": null }, { "code": null, "e": 3749, "s": 3741, "text": "Output:" }, { "code": null, "e": 3789, "s": 3749, "text": "Enter src filename:D:\\gfg\\gfgfile2.txt " }, { "code": null, "e": 3835, "s": 3789, "text": "Enter target filename:D:\\gfg\\renamedfile2.txt" }, { "code": null, "e": 3866, "s": 3835, "text": "Method 1: Using the os module " }, { "code": null, "e": 3982, "s": 3866, "text": "We can use popen() method to make a copy of the source file to the target file with the name specified by the user." }, { "code": null, "e": 3990, "s": 3982, "text": "Syntax:" }, { "code": null, "e": 4027, "s": 3990, "text": " popen( command, mode , buffersize )" }, { "code": null, "e": 4272, "s": 4027, "text": "os.popen() get command to be performed as the first argument, access mode as the second argument which can be read (‘r’) or write (‘w’) and finally buffer size. The default mode is read and 0 for no buffering, positive integers for buffer size." }, { "code": null, "e": 4282, "s": 4272, "text": "Approach:" }, { "code": null, "e": 4296, "s": 4282, "text": "Import module" }, { "code": null, "e": 4317, "s": 4296, "text": "Get source file name" }, { "code": null, "e": 4343, "s": 4317, "text": "Get destination file name" }, { "code": null, "e": 4370, "s": 4343, "text": "Copy source to destination" }, { "code": null, "e": 4379, "s": 4370, "text": "Example:" }, { "code": null, "e": 4386, "s": 4379, "text": "Python" }, { "code": "# import os moduleimport os # get source file namesrc = input(\"Enter src filename:\") # get destination file namedestination = input(\"Enter target filename:\") # copies source to destination fileos.popen(f\"copy {src} {destination}\")", "e": 4620, "s": 4386, "text": null }, { "code": null, "e": 4628, "s": 4620, "text": "Output:" }, { "code": null, "e": 4672, "s": 4628, "text": "Enter src filename:D:\\gfg\\renamedfile1.txt " }, { "code": null, "e": 4725, "s": 4672, "text": "Enter target filename:D:\\gfg\\copied-renamedfile1.txt" }, { "code": null, "e": 4759, "s": 4725, "text": "Method 2: Using the shutil module" }, { "code": null, "e": 4928, "s": 4759, "text": "The shutil module offers several high-level operations on files and collections of files. Its copyfile() method is used to rename the file with the user preferred name." }, { "code": null, "e": 4937, "s": 4928, "text": "Syntax: " }, { "code": null, "e": 4999, "s": 4937, "text": "shutil.copyfile(src_file, dest_file, *, follow_symlinks=True)" }, { "code": null, "e": 5009, "s": 4999, "text": "Approach:" }, { "code": null, "e": 5023, "s": 5009, "text": "Import module" }, { "code": null, "e": 5044, "s": 5023, "text": "Get source file name" }, { "code": null, "e": 5070, "s": 5044, "text": "Get destination file name" }, { "code": null, "e": 5241, "s": 5070, "text": "Copy source file to a new destination file. If both file names specify the same file, SameFileError is raised and if destination file already exists, it will be replaced." }, { "code": null, "e": 5250, "s": 5241, "text": "Example:" }, { "code": null, "e": 5258, "s": 5250, "text": "Python3" }, { "code": "# import shutil moduleimport shutil # get source file namesrc = input(\"Enter src filename:\") # get destination file namedest = input(\"Enter target filename:\") # copies source file to a new destination fileshutil.copyfile(src, dest)", "e": 5493, "s": 5258, "text": null }, { "code": null, "e": 5501, "s": 5493, "text": "Output:" }, { "code": null, "e": 5545, "s": 5501, "text": "Enter src filename:D:\\gfg\\renamedfile2.txt " }, { "code": null, "e": 5598, "s": 5545, "text": "Enter target filename:D:\\gfg\\copied-renamedfile2.txt" }, { "code": null, "e": 5605, "s": 5598, "text": "Picked" }, { "code": null, "e": 5635, "s": 5605, "text": "Python file-handling-programs" }, { "code": null, "e": 5656, "s": 5635, "text": "python-file-handling" }, { "code": null, "e": 5680, "s": 5656, "text": "Technical Scripter 2020" }, { "code": null, "e": 5687, "s": 5680, "text": "Python" }, { "code": null, "e": 5706, "s": 5687, "text": "Technical Scripter" } ]
Convert Java Object to Json String using Jackson API
10 May, 2022 JSON stands for JavaScript Object Notation. It’s a standard text-based format that shows structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications. JSON is highly recommended to transmit data between a server and web application. In order to convert a Java object into JSON, the following two methods can be used that are as listed below as follows: GSON JACKSON API Java object is converted into JSON using Jackson API. Step 1: Add jar files of Jackson (in the case of the Maven project add Jackson dependencies in the pom.xml file) html <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.5.3</version></dependency> Now pom.xml file is depicted below as follows: Step 2: Create a POJO (Plain Old Java Object) to be converted into JSON Java // Java Program to Illustrate Organisation Class package com.Geeks; // Importing required classespublic class Organisation { // Class data members private String organisation_name; private String description; private int Employees; // Calling getters and setters // Getter public String getOrganisation_name() { return organisation_name; } // Setter public void setOrganisation_name(String organisation_name) { this.organisation_name = organisation_name; } // Getter public String getDescription() { return description; } // Setter public void setDescription(String description) { this.description = description; } // Getter public int getEmployees() { return Employees; } // Setter public void setEmployees(int employees) { Employees = employees; } // Method // Creating toString @Override public String toString() { // Returning attributes of organisation return "Organisation [organisation_name=" + organisation_name + ", description=" + description + ", Employees=" + Employees + "]"; }} Step 3: Create a Java class for converting the Organisation object into JSON. Convert the object into JSON using ObjectMapper class of Jackson API. Java // Java Program to Illustrate Object to JSON Conversion package com.Geeks; // Importing required classesimport com.Geeks.Organisation;import java.io.IOException;import org.codehaus.jackson.map.ObjectMapper; // Classpublic class ObjectToJson { // Main driver method public static void main(String[] a) { // Creating object of Organisation Organisation org = new Organisation(); // Insert the data into the object org = getObjectData(org); // Creating Object of ObjectMapper define in Jackson // Api ObjectMapper Obj = new ObjectMapper(); // Try block to check for exceptions try { // Getting organisation object as a json string String jsonStr = Obj.writeValueAsString(org); // Displaying JSON String on console System.out.println(jsonStr); } // Catch block to handle exceptions catch (IOException e) { // Display exception along with line number // using printStackTrace() method e.printStackTrace(); } } // Method // Getting the data to be inserted // into the object public static Organisation getObjectData(Organisation org) { // Insert the custom data org.setName("GeeksforGeeks"); org.setDescription( "A computer Science portal for Geeks"); org.setEmployees(2000); // Returning the object return org; } Step 3: Execute the process. The output in the JSON will be as below: Output: alfiskaria sweetyty solankimayank varshagumber28 Java-String-Programs JSON Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Multidimensional Arrays in Java Collections in Java Set in Java Initializing a List in Java Stream In Java
[ { "code": null, "e": 54, "s": 26, "text": "\n10 May, 2022" }, { "code": null, "e": 460, "s": 54, "text": "JSON stands for JavaScript Object Notation. It’s a standard text-based format that shows structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications. JSON is highly recommended to transmit data between a server and web application. In order to convert a Java object into JSON, the following two methods can be used that are as listed below as follows: " }, { "code": null, "e": 465, "s": 460, "text": "GSON" }, { "code": null, "e": 477, "s": 465, "text": "JACKSON API" }, { "code": null, "e": 531, "s": 477, "text": "Java object is converted into JSON using Jackson API." }, { "code": null, "e": 644, "s": 531, "text": "Step 1: Add jar files of Jackson (in the case of the Maven project add Jackson dependencies in the pom.xml file)" }, { "code": null, "e": 649, "s": 644, "text": "html" }, { "code": "<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.5.3</version></dependency>", "e": 809, "s": 649, "text": null }, { "code": null, "e": 857, "s": 809, "text": "Now pom.xml file is depicted below as follows: " }, { "code": null, "e": 930, "s": 857, "text": "Step 2: Create a POJO (Plain Old Java Object) to be converted into JSON " }, { "code": null, "e": 935, "s": 930, "text": "Java" }, { "code": "// Java Program to Illustrate Organisation Class package com.Geeks; // Importing required classespublic class Organisation { // Class data members private String organisation_name; private String description; private int Employees; // Calling getters and setters // Getter public String getOrganisation_name() { return organisation_name; } // Setter public void setOrganisation_name(String organisation_name) { this.organisation_name = organisation_name; } // Getter public String getDescription() { return description; } // Setter public void setDescription(String description) { this.description = description; } // Getter public int getEmployees() { return Employees; } // Setter public void setEmployees(int employees) { Employees = employees; } // Method // Creating toString @Override public String toString() { // Returning attributes of organisation return \"Organisation [organisation_name=\" + organisation_name + \", description=\" + description + \", Employees=\" + Employees + \"]\"; }}", "e": 2104, "s": 935, "text": null }, { "code": null, "e": 2183, "s": 2104, "text": "Step 3: Create a Java class for converting the Organisation object into JSON. " }, { "code": null, "e": 2253, "s": 2183, "text": "Convert the object into JSON using ObjectMapper class of Jackson API." }, { "code": null, "e": 2258, "s": 2253, "text": "Java" }, { "code": "// Java Program to Illustrate Object to JSON Conversion package com.Geeks; // Importing required classesimport com.Geeks.Organisation;import java.io.IOException;import org.codehaus.jackson.map.ObjectMapper; // Classpublic class ObjectToJson { // Main driver method public static void main(String[] a) { // Creating object of Organisation Organisation org = new Organisation(); // Insert the data into the object org = getObjectData(org); // Creating Object of ObjectMapper define in Jackson // Api ObjectMapper Obj = new ObjectMapper(); // Try block to check for exceptions try { // Getting organisation object as a json string String jsonStr = Obj.writeValueAsString(org); // Displaying JSON String on console System.out.println(jsonStr); } // Catch block to handle exceptions catch (IOException e) { // Display exception along with line number // using printStackTrace() method e.printStackTrace(); } } // Method // Getting the data to be inserted // into the object public static Organisation getObjectData(Organisation org) { // Insert the custom data org.setName(\"GeeksforGeeks\"); org.setDescription( \"A computer Science portal for Geeks\"); org.setEmployees(2000); // Returning the object return org; }", "e": 3731, "s": 2258, "text": null }, { "code": null, "e": 3760, "s": 3731, "text": "Step 3: Execute the process." }, { "code": null, "e": 3802, "s": 3760, "text": "The output in the JSON will be as below: " }, { "code": null, "e": 3812, "s": 3802, "text": "Output: " }, { "code": null, "e": 3823, "s": 3812, "text": "alfiskaria" }, { "code": null, "e": 3832, "s": 3823, "text": "sweetyty" }, { "code": null, "e": 3846, "s": 3832, "text": "solankimayank" }, { "code": null, "e": 3861, "s": 3846, "text": "varshagumber28" }, { "code": null, "e": 3882, "s": 3861, "text": "Java-String-Programs" }, { "code": null, "e": 3887, "s": 3882, "text": "JSON" }, { "code": null, "e": 3892, "s": 3887, "text": "Java" }, { "code": null, "e": 3897, "s": 3892, "text": "Java" }, { "code": null, "e": 3995, "s": 3897, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4046, "s": 3995, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 4077, "s": 4046, "text": "How to iterate any Map in Java" }, { "code": null, "e": 4096, "s": 4077, "text": "Interfaces in Java" }, { "code": null, "e": 4126, "s": 4096, "text": "HashMap in Java with Examples" }, { "code": null, "e": 4144, "s": 4126, "text": "ArrayList in Java" }, { "code": null, "e": 4176, "s": 4144, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 4196, "s": 4176, "text": "Collections in Java" }, { "code": null, "e": 4208, "s": 4196, "text": "Set in Java" }, { "code": null, "e": 4236, "s": 4208, "text": "Initializing a List in Java" } ]
How to Display Dynamic AlertDialog in Android using Firebase Firestore?
21 Jan, 2021 Dynamic AlertDialog is used in many different apps which are used to show different messages from dialog to the users. This type of dialog is also used for educating users with so many promotional banners. This type of alert dialog is generally dynamic and it displays images and texts which are dynamic in behavior and change after a certain interval. In this article, we will take a look at the implementation of the dynamic alert dialog box in Android. We will be building a simple alert dialog in Android. Inside that AlertDialog, we will be displaying our image and text from Firebase. The data inside our alert dialog can be changed according to our requirements. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Step 1: Create a new Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Connect your app to Firebase After creating a new project navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot. Inside that column Navigate to Firebase Cloud Firestore. Click on that option and you will get to see two options on Connect app to Firebase and Add Cloud Firestore to your app. Click on Connect now option and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase. After connecting your app to Firebase you will get to see the below screen. After that verify that dependency for the Firebase Firestore database has been added to our Gradle file. Navigate to the app > Gradle Scripts inside that file to check whether the below dependency is added or not. If the below dependency is not present in your build.gradle file. Add the below dependency in the dependencies section. implementation ‘com.google.firebase:firebase-firestore:22.0.1’ After adding this dependency sync your project and now we are ready for creating our app. If you want to know more about connecting your app to Firebase. Refer to this article to get in detail about How to add Firebase to Android App. Step 3: Working with the AndroidManifest.xml file For adding data to Firebase we should have to give permissions for accessing the internet. For adding these permissions navigate to the app > AndroidManifest.xml and Inside that file add the below permissions to it. XML <!--Permissions for internet--><uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> Step 4: Working with the activity_main.xml file As we are not displaying any UI inside our activity_main.xml file so we are not adding any UI component in our activity_main.xml because we are displaying the data in our custom layout file. Step 5: Creating a new layout file for our alert dialog As we are displaying one image and text inside our alert dialog. So we will be building a custom layout for our Alert Dialog. For creating a new layout file four our custom dialog box. Navigate to the app > res > layout > Right-click on it > Click on New > layout resource file and name it as custom_pop_up_layout and add below code to it. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="30dp" android:background="@color/purple_500"> <!--Image view inside our dialog box--> <ImageView android:id="@+id/idIVNotification" android:layout_width="300dp" android:layout_height="300dp" android:layout_below="@id/idTVNotification" android:layout_centerHorizontal="true" android:layout_margin="20dp" /> <!--Text view inside our dialog box--> <TextView android:id="@+id/idTVNotification" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="8dp" android:text="Notification Message" android:textAlignment="center" android:textColor="@color/white" android:textSize="18sp" /> </RelativeLayout> Step 6: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.app.AlertDialog;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.widget.ImageView;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity; import com.google.firebase.firestore.DocumentReference;import com.google.firebase.firestore.DocumentSnapshot;import com.google.firebase.firestore.EventListener;import com.google.firebase.firestore.FirebaseFirestore;import com.google.firebase.firestore.FirebaseFirestoreException;import com.squareup.picasso.Picasso; public class MainActivity extends AppCompatActivity { // initializing th variable for firebase firestore. FirebaseFirestore db = FirebaseFirestore.getInstance(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // creating a variable for our alert dialog builder. AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); // creating a layout inflater variable. LayoutInflater inflater = getLayoutInflater(); // below line is for inflating a custom pop up layout. View dialoglayout = inflater.inflate(R.layout.custom_pop_up_layout, null); // initializing the textview and imageview from our dialog box. TextView notificationTV = dialoglayout.findViewById(R.id.idTVNotification); ImageView notificationIV = dialoglayout.findViewById(R.id.idIVNotification); // creating a variable for document reference. DocumentReference documentReference = db.collection("MyData").document("Data"); // adding snapshot listener to our document reference. documentReference.addSnapshotListener(new EventListener<DocumentSnapshot>() { @Override public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) { // inside the on event method. if (error != null) { // this method is called when error is not null // and we gt any error // in this cas we are displaying an error message. Toast.makeText(MainActivity.this, "Error found is " + error, Toast.LENGTH_SHORT).show(); return; } if (value != null && value.exists()) { // if the value from firestore is not null then we are // getting our data and setting that data to our text view. // after getting the value from firebase firestore // we are setting it to our text view and image view. notificationTV.setText(value.getData().get("NotificationMessage").toString()); Picasso.get().load(value.getData().get("NotificationImage").toString()).into(notificationIV); } } }); // after setting the text to our text view. // we are displaying our alert dialog. builder.setView(dialoglayout); builder.show(); }} Step 7: Adding the data to Firebase Firestore Console in Android After adding this code go to this link to open Firebase. After clicking on this link you will get to see the below page and on this page Click on Go to Console option in the top right corner. After clicking on this screen you will get to see the below screen with your all project inside that select your project. Inside that screen click n Firebase Firestore Database in the left window. After clicking on Create Database option you will get to see the below screen. Inside this screen, we have to select the Start in test mode option. We are using test mode because we are not setting authentication inside our app. So we are selecting Start in test mode. After selecting on test mode click on the Next option and you will get to see the below screen. Inside this screen, we just have to click on Enable button to enable our Firebase Firestore database. After completing this process we just have to run our application and add data inside Firebase Console. For adding the data click on the Start Collection option and add your collection Name as “MyData“. After adding this we have to add our Document ID as “Data“. Inside the fields section, we have to add our field name as “NotificationImage” for displaying our image in the notification and enter the corresponding value of it (URL for the image). And create another file and name the field as “NotificationMessage” to display the message inside our notification. Also, enter the corresponding value of it. At last click on the Save button. After adding data the screen will look like the following. You can edit and delete those files. Now run the app and see the output of the app below : android Firebase Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Android SDK and it's Components Flutter - Custom Bottom Navigation Bar Retrofit with Kotlin Coroutine in Android How to Post Data to API using Retrofit in Android? Flutter - Stack Widget Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java For-each loop in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jan, 2021" }, { "code": null, "e": 485, "s": 28, "text": "Dynamic AlertDialog is used in many different apps which are used to show different messages from dialog to the users. This type of dialog is also used for educating users with so many promotional banners. This type of alert dialog is generally dynamic and it displays images and texts which are dynamic in behavior and change after a certain interval. In this article, we will take a look at the implementation of the dynamic alert dialog box in Android. " }, { "code": null, "e": 864, "s": 485, "text": "We will be building a simple alert dialog in Android. Inside that AlertDialog, we will be displaying our image and text from Firebase. The data inside our alert dialog can be changed according to our requirements. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 893, "s": 864, "text": "Step 1: Create a new Project" }, { "code": null, "e": 1057, "s": 893, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. " }, { "code": null, "e": 1094, "s": 1057, "text": "Step 2: Connect your app to Firebase" }, { "code": null, "e": 1298, "s": 1094, "text": "After creating a new project navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot." }, { "code": null, "e": 1707, "s": 1298, "text": "Inside that column Navigate to Firebase Cloud Firestore. Click on that option and you will get to see two options on Connect app to Firebase and Add Cloud Firestore to your app. Click on Connect now option and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase. After connecting your app to Firebase you will get to see the below screen. " }, { "code": null, "e": 2041, "s": 1707, "text": "After that verify that dependency for the Firebase Firestore database has been added to our Gradle file. Navigate to the app > Gradle Scripts inside that file to check whether the below dependency is added or not. If the below dependency is not present in your build.gradle file. Add the below dependency in the dependencies section." }, { "code": null, "e": 2104, "s": 2041, "text": "implementation ‘com.google.firebase:firebase-firestore:22.0.1’" }, { "code": null, "e": 2341, "s": 2104, "text": "After adding this dependency sync your project and now we are ready for creating our app. If you want to know more about connecting your app to Firebase. Refer to this article to get in detail about How to add Firebase to Android App. " }, { "code": null, "e": 2391, "s": 2341, "text": "Step 3: Working with the AndroidManifest.xml file" }, { "code": null, "e": 2609, "s": 2391, "text": "For adding data to Firebase we should have to give permissions for accessing the internet. For adding these permissions navigate to the app > AndroidManifest.xml and Inside that file add the below permissions to it. " }, { "code": null, "e": 2613, "s": 2609, "text": "XML" }, { "code": "<!--Permissions for internet--><uses-permission android:name=\"android.permission.INTERNET\" /><uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\" />", "e": 2781, "s": 2613, "text": null }, { "code": null, "e": 2829, "s": 2781, "text": "Step 4: Working with the activity_main.xml file" }, { "code": null, "e": 3021, "s": 2829, "text": "As we are not displaying any UI inside our activity_main.xml file so we are not adding any UI component in our activity_main.xml because we are displaying the data in our custom layout file. " }, { "code": null, "e": 3077, "s": 3021, "text": "Step 5: Creating a new layout file for our alert dialog" }, { "code": null, "e": 3418, "s": 3077, "text": "As we are displaying one image and text inside our alert dialog. So we will be building a custom layout for our Alert Dialog. For creating a new layout file four our custom dialog box. Navigate to the app > res > layout > Right-click on it > Click on New > layout resource file and name it as custom_pop_up_layout and add below code to it. " }, { "code": null, "e": 3422, "s": 3418, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"30dp\" android:background=\"@color/purple_500\"> <!--Image view inside our dialog box--> <ImageView android:id=\"@+id/idIVNotification\" android:layout_width=\"300dp\" android:layout_height=\"300dp\" android:layout_below=\"@id/idTVNotification\" android:layout_centerHorizontal=\"true\" android:layout_margin=\"20dp\" /> <!--Text view inside our dialog box--> <TextView android:id=\"@+id/idTVNotification\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"8dp\" android:text=\"Notification Message\" android:textAlignment=\"center\" android:textColor=\"@color/white\" android:textSize=\"18sp\" /> </RelativeLayout>", "e": 4402, "s": 3422, "text": null }, { "code": null, "e": 4450, "s": 4402, "text": "Step 6: Working with the MainActivity.java file" }, { "code": null, "e": 4640, "s": 4450, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 4645, "s": 4640, "text": "Java" }, { "code": "import android.app.AlertDialog;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.widget.ImageView;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity; import com.google.firebase.firestore.DocumentReference;import com.google.firebase.firestore.DocumentSnapshot;import com.google.firebase.firestore.EventListener;import com.google.firebase.firestore.FirebaseFirestore;import com.google.firebase.firestore.FirebaseFirestoreException;import com.squareup.picasso.Picasso; public class MainActivity extends AppCompatActivity { // initializing th variable for firebase firestore. FirebaseFirestore db = FirebaseFirestore.getInstance(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // creating a variable for our alert dialog builder. AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); // creating a layout inflater variable. LayoutInflater inflater = getLayoutInflater(); // below line is for inflating a custom pop up layout. View dialoglayout = inflater.inflate(R.layout.custom_pop_up_layout, null); // initializing the textview and imageview from our dialog box. TextView notificationTV = dialoglayout.findViewById(R.id.idTVNotification); ImageView notificationIV = dialoglayout.findViewById(R.id.idIVNotification); // creating a variable for document reference. DocumentReference documentReference = db.collection(\"MyData\").document(\"Data\"); // adding snapshot listener to our document reference. documentReference.addSnapshotListener(new EventListener<DocumentSnapshot>() { @Override public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) { // inside the on event method. if (error != null) { // this method is called when error is not null // and we gt any error // in this cas we are displaying an error message. Toast.makeText(MainActivity.this, \"Error found is \" + error, Toast.LENGTH_SHORT).show(); return; } if (value != null && value.exists()) { // if the value from firestore is not null then we are // getting our data and setting that data to our text view. // after getting the value from firebase firestore // we are setting it to our text view and image view. notificationTV.setText(value.getData().get(\"NotificationMessage\").toString()); Picasso.get().load(value.getData().get(\"NotificationImage\").toString()).into(notificationIV); } } }); // after setting the text to our text view. // we are displaying our alert dialog. builder.setView(dialoglayout); builder.show(); }}", "e": 7874, "s": 4645, "text": null }, { "code": null, "e": 7939, "s": 7874, "text": "Step 7: Adding the data to Firebase Firestore Console in Android" }, { "code": null, "e": 8133, "s": 7939, "text": "After adding this code go to this link to open Firebase. After clicking on this link you will get to see the below page and on this page Click on Go to Console option in the top right corner. " }, { "code": null, "e": 8257, "s": 8133, "text": "After clicking on this screen you will get to see the below screen with your all project inside that select your project. " }, { "code": null, "e": 8334, "s": 8257, "text": "Inside that screen click n Firebase Firestore Database in the left window. " }, { "code": null, "e": 8415, "s": 8334, "text": "After clicking on Create Database option you will get to see the below screen. " }, { "code": null, "e": 8703, "s": 8415, "text": "Inside this screen, we have to select the Start in test mode option. We are using test mode because we are not setting authentication inside our app. So we are selecting Start in test mode. After selecting on test mode click on the Next option and you will get to see the below screen. " }, { "code": null, "e": 9447, "s": 8703, "text": "Inside this screen, we just have to click on Enable button to enable our Firebase Firestore database. After completing this process we just have to run our application and add data inside Firebase Console. For adding the data click on the Start Collection option and add your collection Name as “MyData“. After adding this we have to add our Document ID as “Data“. Inside the fields section, we have to add our field name as “NotificationImage” for displaying our image in the notification and enter the corresponding value of it (URL for the image). And create another file and name the field as “NotificationMessage” to display the message inside our notification. Also, enter the corresponding value of it. At last click on the Save button." }, { "code": null, "e": 9543, "s": 9447, "text": "After adding data the screen will look like the following. You can edit and delete those files." }, { "code": null, "e": 9598, "s": 9543, "text": "Now run the app and see the output of the app below : " }, { "code": null, "e": 9606, "s": 9598, "text": "android" }, { "code": null, "e": 9615, "s": 9606, "text": "Firebase" }, { "code": null, "e": 9639, "s": 9615, "text": "Technical Scripter 2020" }, { "code": null, "e": 9647, "s": 9639, "text": "Android" }, { "code": null, "e": 9652, "s": 9647, "text": "Java" }, { "code": null, "e": 9671, "s": 9652, "text": "Technical Scripter" }, { "code": null, "e": 9676, "s": 9671, "text": "Java" }, { "code": null, "e": 9684, "s": 9676, "text": "Android" }, { "code": null, "e": 9782, "s": 9684, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9814, "s": 9782, "text": "Android SDK and it's Components" }, { "code": null, "e": 9853, "s": 9814, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 9895, "s": 9853, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 9946, "s": 9895, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 9969, "s": 9946, "text": "Flutter - Stack Widget" }, { "code": null, "e": 9984, "s": 9969, "text": "Arrays in Java" }, { "code": null, "e": 10028, "s": 9984, "text": "Split() String method in Java with examples" }, { "code": null, "e": 10064, "s": 10028, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 10089, "s": 10064, "text": "Reverse a string in Java" } ]
Python | Summation of dictionary list values
28 Aug, 2019 Sometimes, while working with Python dictionaries, we can have it’s values as lists. In this can we can have a problem that we just require the count of elements in those list as a whole. This can be a problem in Data Science in which we need to get total records in observations. Let’s discuss certain ways in which this task can be performed. Method #1 : Using sum() + list comprehensionThis task can be performed using sum function which can be used to get the summation and internal list comprehension can provide a mechanism to iterate this logic to all the keys of dictionary. # Python3 code to demonstrate working of# Summation of dictionary list values# using sum() + list comprehension # initialize dictionarytest_dict = {'gfg' : [5, 6, 7], 'is' : [10, 11], 'best' : [19, 31, 22]} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Summation of dictionary list values# using sum() + list comprehensionres = sum(len(sub) for sub in test_dict.values()) # printing resultprint("Summation of dictionary list values are : " + str(res)) The original dictionary is : {'best': [19, 31, 22], 'is': [10, 11], 'gfg': [5, 6, 7]} Summation of dictionary list values are : 8 Method #2 : Using sum() + map()This task can also be performed using map function in place of list comprehension to extend the logic of finding the length, rest all the functionality remaining same as the above method. # Python3 code to demonstrate working of# Summation of dictionary list values# using sum() + map() # initialize dictionarytest_dict = {'gfg' : [5, 6, 7], 'is' : [10, 11], 'best' : [19, 31, 22]} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Summation of dictionary list values# using sum() + map()res = sum(map(len, test_dict.values())) # printing resultprint("Summation of dictionary list values are : " + str(res)) The original dictionary is : {'best': [19, 31, 22], 'is': [10, 11], 'gfg': [5, 6, 7]} Summation of dictionary list values are : 8 Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Aug, 2019" }, { "code": null, "e": 373, "s": 28, "text": "Sometimes, while working with Python dictionaries, we can have it’s values as lists. In this can we can have a problem that we just require the count of elements in those list as a whole. This can be a problem in Data Science in which we need to get total records in observations. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 611, "s": 373, "text": "Method #1 : Using sum() + list comprehensionThis task can be performed using sum function which can be used to get the summation and internal list comprehension can provide a mechanism to iterate this logic to all the keys of dictionary." }, { "code": "# Python3 code to demonstrate working of# Summation of dictionary list values# using sum() + list comprehension # initialize dictionarytest_dict = {'gfg' : [5, 6, 7], 'is' : [10, 11], 'best' : [19, 31, 22]} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Summation of dictionary list values# using sum() + list comprehensionres = sum(len(sub) for sub in test_dict.values()) # printing resultprint(\"Summation of dictionary list values are : \" + str(res))", "e": 1109, "s": 611, "text": null }, { "code": null, "e": 1240, "s": 1109, "text": "The original dictionary is : {'best': [19, 31, 22], 'is': [10, 11], 'gfg': [5, 6, 7]}\nSummation of dictionary list values are : 8\n" }, { "code": null, "e": 1461, "s": 1242, "text": "Method #2 : Using sum() + map()This task can also be performed using map function in place of list comprehension to extend the logic of finding the length, rest all the functionality remaining same as the above method." }, { "code": "# Python3 code to demonstrate working of# Summation of dictionary list values# using sum() + map() # initialize dictionarytest_dict = {'gfg' : [5, 6, 7], 'is' : [10, 11], 'best' : [19, 31, 22]} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Summation of dictionary list values# using sum() + map()res = sum(map(len, test_dict.values())) # printing resultprint(\"Summation of dictionary list values are : \" + str(res))", "e": 1923, "s": 1461, "text": null }, { "code": null, "e": 2054, "s": 1923, "text": "The original dictionary is : {'best': [19, 31, 22], 'is': [10, 11], 'gfg': [5, 6, 7]}\nSummation of dictionary list values are : 8\n" }, { "code": null, "e": 2081, "s": 2054, "text": "Python dictionary-programs" }, { "code": null, "e": 2088, "s": 2081, "text": "Python" }, { "code": null, "e": 2104, "s": 2088, "text": "Python Programs" } ]
Basic Authentication - Django REST Framework - GeeksforGeeks
14 Sep, 2021 Authentication is a mechanism that provides access control based on the credentials associated with incoming requests. Django REST Framework provides several authentication schemes. In this section, let’s look at the Basic Authentication in Django rest framework, i.e., authenticated against a user’s username and password. Basic Authentication in Django REST Framework uses HTTP Basic Authentication. It is generally appropriate for testing. The REST framework will attempt to authenticate the Basic Authentication class and set the returned values to request.user and request.auth. If successfully authenticated, BasicAuthentication provides the following credentials. request.user will be a Django User instance. request.auth will be None. if not, the value of request.user will be set to as an instance of django.contrib.auth.models.AnonymousUser, and request.auth will be set to None. To make of BasicAuthentication scheme, we need to set it to the default authentication scheme. You can either set it globally or you can set the authentication scheme on a per-view basis. You can set the authentication globally by using the DEFAULT_AUTHENTICATION_CLASSES setting. Python3 REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', ]} Setting the authentication scheme on a per-view basis differs in function-based views and class-based views. We can make use of @authentication_classes and @permission_classes decorators to set the authentication scheme in function-based views that use @api_view decorator. The sample code is as follows: Python3 @api_view(['GET'])@authentication_classes([BasicAuthentication])@permission_classes([IsAuthenticated])def function_based_view(request, format=None): content = { # `django.contrib.auth.User` instance 'user': str(request.user), # None 'auth': str(request.auth), } return Response(content) By using the APIView class, we can set the authentication scheme in class-based views. The sample code is as follows: Python3 from rest_framework.authentication import SessionAuthentication, BasicAuthenticationfrom rest_framework.permissions import IsAuthenticatedfrom rest_framework.response import Responsefrom rest_framework.views import APIView class ClassBasedView(APIView): authentication_classes = [BasicAuthentication] permission_classes = [IsAuthenticated] def get(self, request, format=None): content = { # `django.contrib.auth.User` instance 'user': str(request.user), # None 'auth': str(request.auth), } return Response(content) Note: Here, we will use the simplest style of permission that allows access to any authenticated user, and deny access to any unauthenticated user. This corresponds to the ‘IsAuthenticated’ class in REST framework. If not set to ‘IsAuthenticated’ class, it uses the default class ‘AllowAny’, which allows unrestricted access. Let’s set the BasicAuthentication scheme globally. You can open the settings.py file of our restful web service and add the below code. Python3 REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES' 'rest_framework.authentication.BasicAuthentication', )} Note: You can refer The Browsable API section for Models, Serializers, and Views of Project used in the article Here we set the BasicAuthentication scheme globally, so we don’t need to set it for each view. But we need to set the permission class since, by default, the permission class is set to AllowAny, which allows unrestricted access. To make use IsAuthenticated class we need to import it from rest_framework.permissions. from rest_framework.permissions import IsAuthenticated Now, let’s set the permission class to ‘IsAuthenticated’ for RobotDetail and RobotList class. The code is as follows: Python3 class RobotDetail(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsAuthenticated] queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-detail' class RobotList(generics.ListCreateAPIView): permission_classes = [IsAuthenticated] queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-list' Let’s try to retrieve robots without providing any credentials. The HTTPie command is http :8000/robot/ Output Now we will create a superuser and provide the credentials to retrieve robots. You can follow How to create superuser in Django? to create a superuser. Let’s try the HTTPie command with credentials to retrieve the robots. http -a “admin”:”admin@123′′ :8000/robot/ Output Let’s try an HTTPie command that creates a new robot entry. http -a “admin”:”admin@123′′ POST :8000/robot/ name=”SR-3iA” robot_category=”SCARA Robots” currency=”USD” price=25000 manufacturer=”Fanuc” manufacturing_date=”2020-05-10 00:00:00+00:00′′ Output Note: If you use BasicAuthentication in production, you should ensure your API is available only for HTTPS and always re-request the credentials. If you are deploying to Apache using mod_wsgi, you need to explicitly configure mod_wsgi to pass the required headers through to the application by setting the WSGIPassAuthorization to ‘On’. Django-REST Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Pandas dataframe.groupby() Create a directory in Python Defaultdict in Python Python | Get unique values from a list
[ { "code": null, "e": 25647, "s": 25619, "text": "\n14 Sep, 2021" }, { "code": null, "e": 25971, "s": 25647, "text": "Authentication is a mechanism that provides access control based on the credentials associated with incoming requests. Django REST Framework provides several authentication schemes. In this section, let’s look at the Basic Authentication in Django rest framework, i.e., authenticated against a user’s username and password." }, { "code": null, "e": 26318, "s": 25971, "text": "Basic Authentication in Django REST Framework uses HTTP Basic Authentication. It is generally appropriate for testing. The REST framework will attempt to authenticate the Basic Authentication class and set the returned values to request.user and request.auth. If successfully authenticated, BasicAuthentication provides the following credentials." }, { "code": null, "e": 26363, "s": 26318, "text": "request.user will be a Django User instance." }, { "code": null, "e": 26390, "s": 26363, "text": "request.auth will be None." }, { "code": null, "e": 26725, "s": 26390, "text": "if not, the value of request.user will be set to as an instance of django.contrib.auth.models.AnonymousUser, and request.auth will be set to None. To make of BasicAuthentication scheme, we need to set it to the default authentication scheme. You can either set it globally or you can set the authentication scheme on a per-view basis." }, { "code": null, "e": 26818, "s": 26725, "text": "You can set the authentication globally by using the DEFAULT_AUTHENTICATION_CLASSES setting." }, { "code": null, "e": 26826, "s": 26818, "text": "Python3" }, { "code": "REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', ]}", "e": 26950, "s": 26826, "text": null }, { "code": null, "e": 27059, "s": 26950, "text": "Setting the authentication scheme on a per-view basis differs in function-based views and class-based views." }, { "code": null, "e": 27255, "s": 27059, "text": "We can make use of @authentication_classes and @permission_classes decorators to set the authentication scheme in function-based views that use @api_view decorator. The sample code is as follows:" }, { "code": null, "e": 27263, "s": 27255, "text": "Python3" }, { "code": "@api_view(['GET'])@authentication_classes([BasicAuthentication])@permission_classes([IsAuthenticated])def function_based_view(request, format=None): content = { # `django.contrib.auth.User` instance 'user': str(request.user), # None 'auth': str(request.auth), } return Response(content)", "e": 27603, "s": 27263, "text": null }, { "code": null, "e": 27721, "s": 27603, "text": "By using the APIView class, we can set the authentication scheme in class-based views. The sample code is as follows:" }, { "code": null, "e": 27729, "s": 27721, "text": "Python3" }, { "code": "from rest_framework.authentication import SessionAuthentication, BasicAuthenticationfrom rest_framework.permissions import IsAuthenticatedfrom rest_framework.response import Responsefrom rest_framework.views import APIView class ClassBasedView(APIView): authentication_classes = [BasicAuthentication] permission_classes = [IsAuthenticated] def get(self, request, format=None): content = { # `django.contrib.auth.User` instance 'user': str(request.user), # None 'auth': str(request.auth), } return Response(content)", "e": 28345, "s": 27729, "text": null }, { "code": null, "e": 28672, "s": 28345, "text": "Note: Here, we will use the simplest style of permission that allows access to any authenticated user, and deny access to any unauthenticated user. This corresponds to the ‘IsAuthenticated’ class in REST framework. If not set to ‘IsAuthenticated’ class, it uses the default class ‘AllowAny’, which allows unrestricted access. " }, { "code": null, "e": 28808, "s": 28672, "text": "Let’s set the BasicAuthentication scheme globally. You can open the settings.py file of our restful web service and add the below code." }, { "code": null, "e": 28816, "s": 28808, "text": "Python3" }, { "code": "REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES' 'rest_framework.authentication.BasicAuthentication', )}", "e": 28941, "s": 28816, "text": null }, { "code": null, "e": 29053, "s": 28941, "text": "Note: You can refer The Browsable API section for Models, Serializers, and Views of Project used in the article" }, { "code": null, "e": 29371, "s": 29053, "text": "Here we set the BasicAuthentication scheme globally, so we don’t need to set it for each view. But we need to set the permission class since, by default, the permission class is set to AllowAny, which allows unrestricted access. To make use IsAuthenticated class we need to import it from rest_framework.permissions." }, { "code": null, "e": 29426, "s": 29371, "text": "from rest_framework.permissions import IsAuthenticated" }, { "code": null, "e": 29544, "s": 29426, "text": "Now, let’s set the permission class to ‘IsAuthenticated’ for RobotDetail and RobotList class. The code is as follows:" }, { "code": null, "e": 29552, "s": 29544, "text": "Python3" }, { "code": "class RobotDetail(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsAuthenticated] queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-detail' class RobotList(generics.ListCreateAPIView): permission_classes = [IsAuthenticated] queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-list'", "e": 29934, "s": 29552, "text": null }, { "code": null, "e": 30020, "s": 29934, "text": "Let’s try to retrieve robots without providing any credentials. The HTTPie command is" }, { "code": null, "e": 30038, "s": 30020, "text": "http :8000/robot/" }, { "code": null, "e": 30045, "s": 30038, "text": "Output" }, { "code": null, "e": 30197, "s": 30045, "text": "Now we will create a superuser and provide the credentials to retrieve robots. You can follow How to create superuser in Django? to create a superuser." }, { "code": null, "e": 30267, "s": 30197, "text": "Let’s try the HTTPie command with credentials to retrieve the robots." }, { "code": null, "e": 30309, "s": 30267, "text": "http -a “admin”:”admin@123′′ :8000/robot/" }, { "code": null, "e": 30316, "s": 30309, "text": "Output" }, { "code": null, "e": 30376, "s": 30316, "text": "Let’s try an HTTPie command that creates a new robot entry." }, { "code": null, "e": 30563, "s": 30376, "text": "http -a “admin”:”admin@123′′ POST :8000/robot/ name=”SR-3iA” robot_category=”SCARA Robots” currency=”USD” price=25000 manufacturer=”Fanuc” manufacturing_date=”2020-05-10 00:00:00+00:00′′" }, { "code": null, "e": 30570, "s": 30563, "text": "Output" }, { "code": null, "e": 30907, "s": 30570, "text": "Note: If you use BasicAuthentication in production, you should ensure your API is available only for HTTPS and always re-request the credentials. If you are deploying to Apache using mod_wsgi, you need to explicitly configure mod_wsgi to pass the required headers through to the application by setting the WSGIPassAuthorization to ‘On’." }, { "code": null, "e": 30919, "s": 30907, "text": "Django-REST" }, { "code": null, "e": 30933, "s": 30919, "text": "Python Django" }, { "code": null, "e": 30940, "s": 30933, "text": "Python" }, { "code": null, "e": 31038, "s": 30940, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31070, "s": 31038, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 31112, "s": 31070, "text": "Check if element exists in list in Python" }, { "code": null, "e": 31154, "s": 31112, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 31210, "s": 31154, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 31237, "s": 31210, "text": "Python Classes and Objects" }, { "code": null, "e": 31268, "s": 31237, "text": "Python | os.path.join() method" }, { "code": null, "e": 31304, "s": 31268, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 31333, "s": 31304, "text": "Create a directory in Python" }, { "code": null, "e": 31355, "s": 31333, "text": "Defaultdict in Python" } ]
YOLO Object Detection with OpenCV and Python | by Arun Ponnusamy | Towards Data Science
If you have been keeping up with the advancements in the area of object detection, you might have got used to hearing this word ‘YOLO’. It has kind of become a buzzword. YOLO (You Only Look Once) is a method / way to do object detection. It is the algorithm /strategy behind how the code is going to detect objects in the image. The official implementation of this idea is available through DarkNet (neural net implementation from the ground up in C from the author). It is available on github for people to use. Earlier detection frameworks, looked at different parts of the image multiple times at different scales and repurposed image classification technique to detect objects. This approach is slow and inefficient. YOLO takes entirely different approach. It looks at the entire image only once and goes through the network once and detects objects. Hence the name. It is very fast. That’s the reason it has got so popular. There are other popular object detection frameworks like Faster R-CNN and SSD that are also widely used. In this post, we are going to look at how to use a pre-trained YOLO model with OpenCV and start detecting objects right away. DNN (Deep Neural Network) module was initially part of opencv_contrib repo. It has been moved to the master branch of opencv repo last year, giving users the ability to run inference on pre-trained deep learning models within OpenCV itself. (One thing to note here is, dnn module is not meant be used for training. It’s just for running inference on images/videos.) Initially only Caffe and Torch models were supported. Over the period support for different frameworks/libraries like TensorFlow is being added. Support for YOLO/DarkNet has been added recently. We are going to use the OpenCV dnn module with a pre-trained YOLO model for detecting common objects. Enough of talking. Let’s start writing code. (in Python obviously) Following things are needed to execute the code we will be writing. Python 3 Numpy OpenCV Python bindings If you are on Ubuntu, it’s most likely that Python 3 is already installed. Run python3 in terminal to check whether its installed. If its not installed use sudo apt-get install python3 For macOS please refer my earlier post on deep learning setup for macOS. I highly recommend using Python virtualenvironment. Have a look at my earlier post if you need a starting point. pip install numpy This should install numpy. Make sure pip is linked to Python 3.x ( pip -V will show this info) If needed use pip3. Use sudo apt-get install python3-pip to get pip3 if not already installed. You need to compile OpenCV from source from the master branch on github to get the Python bindings. (recommended) Adrian Rosebrock has written a good blog post on PyImageSearch on this. (Download the source from master branch instead of from archive) If you are overwhelmed by the instructions to get OpenCV Python bindings from source, you can get the unofficial Python package using pip install opencv-python This is not maintained officially by OpenCV.org. It’s a community maintained one. Thanks to the efforts of Olli-Pekka Heinisuo. The script requires four input arguments. input image YOLO config file pre-trained YOLO weights text file containing class names All of these files are available on the github repository I have put together. (link to download pre-trained weights is available in readme.) You can also download the pre-trained weights in Terminal by typing wget https://pjreddie.com/media/files/yolov3.weights This particular model is trained on COCO dataset (common objects in context) from Microsoft. It is capable of detecting 80 common objects. See the full list here. Input image can be of your choice. Sample input is available in the repo. Run the script by typing $ python yolo_opencv.py --image dog.jpg --config yolov3.cfg --weights yolov3.weights --classes yolov3.txt Read the input image and get its width and height. Read the text file containing class names in human readable form and extract the class names to a list. Generate different colors for different classes to draw bounding boxes. net = cv2.dnn.readNet(args.weights, args.config) Above line reads the weights and config file and creates the network. blob = cv2.dnn.blobFromImage(image, scale, (Width,Height), (0,0,0), True, crop=False)net.setInput(blob) Above lines prepares the input image to run through the deep neural network. Generally in a sequential CNN network there will be only one output layer at the end. In the YOLO v3 architecture we are using there are multiple output layers giving out predictions. get_output_layers() function gives the names of the output layers. An output layer is not connected to any next layer. draw_bounding_box() function draws rectangle over the given predicted region and writes class name over the box. If needed, we can write the confidence value too. outs = net.forward(get_output_layers(net)) Above line is where the exact feed forward through the network happens. Moment of truth. If we don’t specify the output layer names, by default, it will return the predictions only from final output layer. Any intermediate output layer will be ignored. We need go through each detection from each output layer to get the class id, confidence and bounding box corners and more importantly ignore the weak detections (detections with low confidence value). Even though we ignored weak detections, there will be lot of duplicate detections with overlapping bounding boxes. Non-max suppression removes boxes with high overlapping. Finally we look at the detections that are left and draw bounding boxes around them and display the output image. In this post, we looked at how to use OpenCV dnn module with pre-trained YOLO model to do object detection. We have only scratched the surface. There is lot more to object detection. We can also train a model to detect objects of our own interest that are not covered in the pre-trained one. I will be covering more on object detection in the future including other frameworks like Faster R-CNN and SSD. Be sure to subscribe to my blog to get notified when new posts are published. That’s all for now. Thanks for reading. I hope this post was useful to get started with object detection. Feel free to share your thoughts in the comments or you can reach out to me on twitter @ponnusamy_arun.
[ { "code": null, "e": 342, "s": 172, "text": "If you have been keeping up with the advancements in the area of object detection, you might have got used to hearing this word ‘YOLO’. It has kind of become a buzzword." }, { "code": null, "e": 501, "s": 342, "text": "YOLO (You Only Look Once) is a method / way to do object detection. It is the algorithm /strategy behind how the code is going to detect objects in the image." }, { "code": null, "e": 685, "s": 501, "text": "The official implementation of this idea is available through DarkNet (neural net implementation from the ground up in C from the author). It is available on github for people to use." }, { "code": null, "e": 893, "s": 685, "text": "Earlier detection frameworks, looked at different parts of the image multiple times at different scales and repurposed image classification technique to detect objects. This approach is slow and inefficient." }, { "code": null, "e": 1101, "s": 893, "text": "YOLO takes entirely different approach. It looks at the entire image only once and goes through the network once and detects objects. Hence the name. It is very fast. That’s the reason it has got so popular." }, { "code": null, "e": 1206, "s": 1101, "text": "There are other popular object detection frameworks like Faster R-CNN and SSD that are also widely used." }, { "code": null, "e": 1332, "s": 1206, "text": "In this post, we are going to look at how to use a pre-trained YOLO model with OpenCV and start detecting objects right away." }, { "code": null, "e": 1573, "s": 1332, "text": "DNN (Deep Neural Network) module was initially part of opencv_contrib repo. It has been moved to the master branch of opencv repo last year, giving users the ability to run inference on pre-trained deep learning models within OpenCV itself." }, { "code": null, "e": 1698, "s": 1573, "text": "(One thing to note here is, dnn module is not meant be used for training. It’s just for running inference on images/videos.)" }, { "code": null, "e": 1843, "s": 1698, "text": "Initially only Caffe and Torch models were supported. Over the period support for different frameworks/libraries like TensorFlow is being added." }, { "code": null, "e": 1995, "s": 1843, "text": "Support for YOLO/DarkNet has been added recently. We are going to use the OpenCV dnn module with a pre-trained YOLO model for detecting common objects." }, { "code": null, "e": 2062, "s": 1995, "text": "Enough of talking. Let’s start writing code. (in Python obviously)" }, { "code": null, "e": 2130, "s": 2062, "text": "Following things are needed to execute the code we will be writing." }, { "code": null, "e": 2139, "s": 2130, "text": "Python 3" }, { "code": null, "e": 2145, "s": 2139, "text": "Numpy" }, { "code": null, "e": 2168, "s": 2145, "text": "OpenCV Python bindings" }, { "code": null, "e": 2324, "s": 2168, "text": "If you are on Ubuntu, it’s most likely that Python 3 is already installed. Run python3 in terminal to check whether its installed. If its not installed use" }, { "code": null, "e": 2353, "s": 2324, "text": "sudo apt-get install python3" }, { "code": null, "e": 2426, "s": 2353, "text": "For macOS please refer my earlier post on deep learning setup for macOS." }, { "code": null, "e": 2539, "s": 2426, "text": "I highly recommend using Python virtualenvironment. Have a look at my earlier post if you need a starting point." }, { "code": null, "e": 2557, "s": 2539, "text": "pip install numpy" }, { "code": null, "e": 2652, "s": 2557, "text": "This should install numpy. Make sure pip is linked to Python 3.x ( pip -V will show this info)" }, { "code": null, "e": 2747, "s": 2652, "text": "If needed use pip3. Use sudo apt-get install python3-pip to get pip3 if not already installed." }, { "code": null, "e": 2861, "s": 2747, "text": "You need to compile OpenCV from source from the master branch on github to get the Python bindings. (recommended)" }, { "code": null, "e": 2998, "s": 2861, "text": "Adrian Rosebrock has written a good blog post on PyImageSearch on this. (Download the source from master branch instead of from archive)" }, { "code": null, "e": 3132, "s": 2998, "text": "If you are overwhelmed by the instructions to get OpenCV Python bindings from source, you can get the unofficial Python package using" }, { "code": null, "e": 3158, "s": 3132, "text": "pip install opencv-python" }, { "code": null, "e": 3286, "s": 3158, "text": "This is not maintained officially by OpenCV.org. It’s a community maintained one. Thanks to the efforts of Olli-Pekka Heinisuo." }, { "code": null, "e": 3328, "s": 3286, "text": "The script requires four input arguments." }, { "code": null, "e": 3340, "s": 3328, "text": "input image" }, { "code": null, "e": 3357, "s": 3340, "text": "YOLO config file" }, { "code": null, "e": 3382, "s": 3357, "text": "pre-trained YOLO weights" }, { "code": null, "e": 3415, "s": 3382, "text": "text file containing class names" }, { "code": null, "e": 3557, "s": 3415, "text": "All of these files are available on the github repository I have put together. (link to download pre-trained weights is available in readme.)" }, { "code": null, "e": 3625, "s": 3557, "text": "You can also download the pre-trained weights in Terminal by typing" }, { "code": null, "e": 3678, "s": 3625, "text": "wget https://pjreddie.com/media/files/yolov3.weights" }, { "code": null, "e": 3841, "s": 3678, "text": "This particular model is trained on COCO dataset (common objects in context) from Microsoft. It is capable of detecting 80 common objects. See the full list here." }, { "code": null, "e": 3915, "s": 3841, "text": "Input image can be of your choice. Sample input is available in the repo." }, { "code": null, "e": 3940, "s": 3915, "text": "Run the script by typing" }, { "code": null, "e": 4046, "s": 3940, "text": "$ python yolo_opencv.py --image dog.jpg --config yolov3.cfg --weights yolov3.weights --classes yolov3.txt" }, { "code": null, "e": 4097, "s": 4046, "text": "Read the input image and get its width and height." }, { "code": null, "e": 4201, "s": 4097, "text": "Read the text file containing class names in human readable form and extract the class names to a list." }, { "code": null, "e": 4273, "s": 4201, "text": "Generate different colors for different classes to draw bounding boxes." }, { "code": null, "e": 4322, "s": 4273, "text": "net = cv2.dnn.readNet(args.weights, args.config)" }, { "code": null, "e": 4392, "s": 4322, "text": "Above line reads the weights and config file and creates the network." }, { "code": null, "e": 4496, "s": 4392, "text": "blob = cv2.dnn.blobFromImage(image, scale, (Width,Height), (0,0,0), True, crop=False)net.setInput(blob)" }, { "code": null, "e": 4573, "s": 4496, "text": "Above lines prepares the input image to run through the deep neural network." }, { "code": null, "e": 4876, "s": 4573, "text": "Generally in a sequential CNN network there will be only one output layer at the end. In the YOLO v3 architecture we are using there are multiple output layers giving out predictions. get_output_layers() function gives the names of the output layers. An output layer is not connected to any next layer." }, { "code": null, "e": 5039, "s": 4876, "text": "draw_bounding_box() function draws rectangle over the given predicted region and writes class name over the box. If needed, we can write the confidence value too." }, { "code": null, "e": 5082, "s": 5039, "text": "outs = net.forward(get_output_layers(net))" }, { "code": null, "e": 5335, "s": 5082, "text": "Above line is where the exact feed forward through the network happens. Moment of truth. If we don’t specify the output layer names, by default, it will return the predictions only from final output layer. Any intermediate output layer will be ignored." }, { "code": null, "e": 5537, "s": 5335, "text": "We need go through each detection from each output layer to get the class id, confidence and bounding box corners and more importantly ignore the weak detections (detections with low confidence value)." }, { "code": null, "e": 5709, "s": 5537, "text": "Even though we ignored weak detections, there will be lot of duplicate detections with overlapping bounding boxes. Non-max suppression removes boxes with high overlapping." }, { "code": null, "e": 5823, "s": 5709, "text": "Finally we look at the detections that are left and draw bounding boxes around them and display the output image." }, { "code": null, "e": 6006, "s": 5823, "text": "In this post, we looked at how to use OpenCV dnn module with pre-trained YOLO model to do object detection. We have only scratched the surface. There is lot more to object detection." }, { "code": null, "e": 6305, "s": 6006, "text": "We can also train a model to detect objects of our own interest that are not covered in the pre-trained one. I will be covering more on object detection in the future including other frameworks like Faster R-CNN and SSD. Be sure to subscribe to my blog to get notified when new posts are published." } ]
Flutter - Tooltip Widget - GeeksforGeeks
22 Feb, 2022 Tooltip is a built-in widget in flutter based on material design, which displays a textual description of the widget in a floating label when a user long-pressed and or hover over the widget. Tooltip widget becomes very useful when the UI of the application is too dense to display all the information at once on the screen, in a way it simply makes the app more accessible. There are two ways to implement the Tooltip in a widget, the first one is by using the widget itself and the other way is limited to some widgets such as IconButton, FloatingActionButton, etc which provide tooltip as a property which in turn takes in a string as a parameter. One should remember that the Tooltip widget is customizable through its properties but the tooltip property isn’t. const Tooltip( {Key? key, required String message, double? height, EdgeInsetsGeometry? padding, EdgeInsetsGeometry? margin, double? verticalOffset, bool? preferBelow, bool? excludeFromSemantics, Decoration? decoration, TextStyle? textStyle, Duration? waitDuration, Duration? showDuration, Widget? child} ) child: This property determines the widget for which the tooltip has to be displayed. decoration: With the help of decoration property background color, border (Shape), of the tooltip can be controlled. excludeFormSemantics: This property takes in boolean as a parameter, and by default it is false. It controls whether the tooltip’s message should be added to the semantic tree or not. height: This property determined the height of the tooltip. It takes in double value as a parameter. margin: This property determines the empty space around the tooltip. It takes EdgeInsetsGeometry as the parameter. message: This property takes a string value as the parameter to display the text in tooltip. padding: This property also takes EdgeInsetsGeometry as the parameter to determine the empty space between the border and the main content of the tooltip. preferBelow: This property controls whether to display the tooltip on the widget or below that by taking a boolean as the parameter. By default, it is set to true. showDuration: This property determines the time in seconds for which the tooltip should be displayed. textStyle: This property takes care of the styling of the message in the tooltip such as font size or color. verticalOffset: This property controls the vertical distance between the tooltip and the widget. waitDuration: This property controls the time after which the tooltip will be made visible once the user hovers over the widget of presses it for more than one second. Example 1: Basic tooltips. main.dart Dart import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.greenAccent[400], leading: IconButton( icon: Icon(Icons.menu), tooltip: 'Menu', onPressed: () {}, ) //IconButton ), //AppBar body: Center( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Container( child: Padding( padding: const EdgeInsets.all(12.0), child: Tooltip( message: 'Text', child: Text( 'Flutter is an open-source UI software development kit created by Google. ', style: TextStyle( color: Colors.grey, fontSize: 25, ), //TextStyle ), //Text ), //Tooltip ), //Padding color: Colors.green[50], width: 300, height: 175, ), //Container ], //<Widget>[] ) //Row ), //Center ), //Scaffold debugShowCheckedModeBanner: false, )); //MaterialApp} Output: Explanation: Thus app is starting with a simple app bar created with the built-in flutter AppBar widget with a leading menu IconButton. The title of the app bar is Text widget taking a string value of ‘GeeksforGeeks’. The background color assigned to the app bar is greenAccent[400]. In the IconButton tooltip property is being employed, which is also taking a string parameter. One can notice that pressing the menu icon on the screen for more than one-second displays the tooltip with a text menu. This is one of the ways of using tooltip for the widgets, but this is all it has got, we cannot do anything else to change its looks. Another way is by using the Tooltip widget itself as we have done in the body of the app. In the body of the app, we have Center widget as the parent widget with Row as its child that aligns all its children widgets in the center. After that, we have created a Container with some padding and inside that, we have the widget Tooltip. Now, the Tooltip widget is taking Text as its child that prints a string on the screen. When we use Tooltip, the message property is a must provide, and in this case, it is ‘Test’. And similar to the menu icon when the text is hovered or long pressed the tooltip pops up. Both the tooltips in this app are bare basic built into the flutter. And we haven’t done anything to change their appears, In the second example, we will see how to modify the Tooltip widget. Example 2: Modified tooltip. This is the code snippet for the Tooltip widget. ... child: Tooltip( message: 'Text', waitDuration: Duration(seconds: 1), showDuration: Duration(seconds: 2), padding: EdgeInsets.all(12), height: 35, verticalOffset: 100, preferBelow: true, textStyle: TextStyle( fontSize: 15, color: Colors.white, fontWeight: FontWeight.normal), decoration: BoxDecoration( borderRadius: BorderRadius.only(topRight: Radius.circular(10)), boxShadow: [ new BoxShadow( color: Colors.grey, blurRadius: 10.0, offset: new Offset(6.0, 6.0), ), //BoxShadow ], color: Colors.greenAccent[400]), //BoxDecoration child: Text( 'Flutter is an open-source UI software development kit created by Google. ', style: TextStyle( color: Colors.grey, fontSize: 25, ), //TextStyle ), //Text ), //Tooltip ... Output: If the above properties are used then the output will look like this. Explanation: Flutter doesn’t give the option to modify the tooltip property as used in the menu icon. But if we want to tweak the looks of the tooltip we can always embed it in a Tooltip widget. But flutter provided multiple properties (mentioned above) to change the look and feel of tooltips. In this app, the first change we have made after the message property is the addition of the property waitDuration which takes in Duration as its child which in turn takes the amount of time in seconds to wait before showing tooltip after a user does the appropriate action. Then we have used the showDuration property which is similar to the waitDuration, it controls for how long the tooltip will be displayed. After that, we have the padding which is taking EdgeInsets.all(12) as the parameter to provide the gap between the border of the tooltip and the child widget. A height is 35 is given to tooltip using is height property. The verticalOffset is set to 100 to display the tooltip below the Text widget. Next is the preferBelow property which controls whether to display the tooltip on the widget itself or below it. The preferedBelow property is true by default. But we can see that in the above first example the tooltip is being displayed on the text itself. The reason for this is the size of the Text widget, it’s too big for tooltip it to crossover as it does in with the menu icon. So to change this behavior we have used the verticalOffset property. All this is followed by textStyle, decoration, and child properties. The child property is the same as the previous example which is taking the Text widget as a child. The testStyle property is adding style to the message property, in this property the font size is set to 15, text color to white, and font-weight to normal. The decoration property is in charge of the styling of the tooltip box, in this case, we have made one of the corners round, added a shadow to the tooltip, and gave green color to the tooltip. Flutter also offers some other ways of displaying the description of a widget in a more beautiful way. One of the ways is by using showcaseview package. And if you still want something different you can create your own custom widget to do the job. rajeev0719singh simranarora5sos arorakashish0911 android Flutter Flutter-widgets Android Dart Flutter Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Broadcast Receiver in Android With Example How to Create and Add Data to SQLite Database in Android? Services in Android with Example Content Providers in Android with Example Android RecyclerView in Kotlin Flutter - DropDownButton Widget Flutter - Asset Image Listview.builder in Flutter Dart - Standard Input Output Splash Screen in Flutter
[ { "code": null, "e": 24256, "s": 24228, "text": "\n22 Feb, 2022" }, { "code": null, "e": 25023, "s": 24256, "text": "Tooltip is a built-in widget in flutter based on material design, which displays a textual description of the widget in a floating label when a user long-pressed and or hover over the widget. Tooltip widget becomes very useful when the UI of the application is too dense to display all the information at once on the screen, in a way it simply makes the app more accessible. There are two ways to implement the Tooltip in a widget, the first one is by using the widget itself and the other way is limited to some widgets such as IconButton, FloatingActionButton, etc which provide tooltip as a property which in turn takes in a string as a parameter. One should remember that the Tooltip widget is customizable through its properties but the tooltip property isn’t. " }, { "code": null, "e": 25329, "s": 25023, "text": "const Tooltip(\n{Key? key,\nrequired String message,\ndouble? height,\nEdgeInsetsGeometry? padding,\nEdgeInsetsGeometry? margin,\ndouble? verticalOffset,\nbool? preferBelow,\nbool? excludeFromSemantics,\nDecoration? decoration,\nTextStyle? textStyle,\nDuration? waitDuration,\nDuration? showDuration,\nWidget? child}\n)" }, { "code": null, "e": 25415, "s": 25329, "text": "child: This property determines the widget for which the tooltip has to be displayed." }, { "code": null, "e": 25532, "s": 25415, "text": "decoration: With the help of decoration property background color, border (Shape), of the tooltip can be controlled." }, { "code": null, "e": 25716, "s": 25532, "text": "excludeFormSemantics: This property takes in boolean as a parameter, and by default it is false. It controls whether the tooltip’s message should be added to the semantic tree or not." }, { "code": null, "e": 25817, "s": 25716, "text": "height: This property determined the height of the tooltip. It takes in double value as a parameter." }, { "code": null, "e": 25932, "s": 25817, "text": "margin: This property determines the empty space around the tooltip. It takes EdgeInsetsGeometry as the parameter." }, { "code": null, "e": 26025, "s": 25932, "text": "message: This property takes a string value as the parameter to display the text in tooltip." }, { "code": null, "e": 26180, "s": 26025, "text": "padding: This property also takes EdgeInsetsGeometry as the parameter to determine the empty space between the border and the main content of the tooltip." }, { "code": null, "e": 26344, "s": 26180, "text": "preferBelow: This property controls whether to display the tooltip on the widget or below that by taking a boolean as the parameter. By default, it is set to true." }, { "code": null, "e": 26446, "s": 26344, "text": "showDuration: This property determines the time in seconds for which the tooltip should be displayed." }, { "code": null, "e": 26555, "s": 26446, "text": "textStyle: This property takes care of the styling of the message in the tooltip such as font size or color." }, { "code": null, "e": 26652, "s": 26555, "text": "verticalOffset: This property controls the vertical distance between the tooltip and the widget." }, { "code": null, "e": 26820, "s": 26652, "text": "waitDuration: This property controls the time after which the tooltip will be made visible once the user hovers over the widget of presses it for more than one second." }, { "code": null, "e": 26847, "s": 26820, "text": "Example 1: Basic tooltips." }, { "code": null, "e": 26857, "s": 26847, "text": "main.dart" }, { "code": null, "e": 26862, "s": 26857, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.greenAccent[400], leading: IconButton( icon: Icon(Icons.menu), tooltip: 'Menu', onPressed: () {}, ) //IconButton ), //AppBar body: Center( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Container( child: Padding( padding: const EdgeInsets.all(12.0), child: Tooltip( message: 'Text', child: Text( 'Flutter is an open-source UI software development kit created by Google. ', style: TextStyle( color: Colors.grey, fontSize: 25, ), //TextStyle ), //Text ), //Tooltip ), //Padding color: Colors.green[50], width: 300, height: 175, ), //Container ], //<Widget>[] ) //Row ), //Center ), //Scaffold debugShowCheckedModeBanner: false, )); //MaterialApp}", "e": 28081, "s": 26862, "text": null }, { "code": null, "e": 28090, "s": 28081, "text": "Output: " }, { "code": null, "e": 29331, "s": 28090, "text": "Explanation: Thus app is starting with a simple app bar created with the built-in flutter AppBar widget with a leading menu IconButton. The title of the app bar is Text widget taking a string value of ‘GeeksforGeeks’. The background color assigned to the app bar is greenAccent[400]. In the IconButton tooltip property is being employed, which is also taking a string parameter. One can notice that pressing the menu icon on the screen for more than one-second displays the tooltip with a text menu. This is one of the ways of using tooltip for the widgets, but this is all it has got, we cannot do anything else to change its looks. Another way is by using the Tooltip widget itself as we have done in the body of the app. In the body of the app, we have Center widget as the parent widget with Row as its child that aligns all its children widgets in the center. After that, we have created a Container with some padding and inside that, we have the widget Tooltip. Now, the Tooltip widget is taking Text as its child that prints a string on the screen. When we use Tooltip, the message property is a must provide, and in this case, it is ‘Test’. And similar to the menu icon when the text is hovered or long pressed the tooltip pops up." }, { "code": null, "e": 29523, "s": 29331, "text": "Both the tooltips in this app are bare basic built into the flutter. And we haven’t done anything to change their appears, In the second example, we will see how to modify the Tooltip widget." }, { "code": null, "e": 29552, "s": 29523, "text": "Example 2: Modified tooltip." }, { "code": null, "e": 29601, "s": 29552, "text": "This is the code snippet for the Tooltip widget." }, { "code": null, "e": 30898, "s": 29601, "text": "...\n child: Tooltip(\n message: 'Text',\n waitDuration: Duration(seconds: 1),\n showDuration: Duration(seconds: 2),\n padding: EdgeInsets.all(12),\n height: 35,\n verticalOffset: 100,\n preferBelow: true,\n textStyle: TextStyle(\n fontSize: 15,\n color: Colors.white,\n fontWeight: FontWeight.normal),\n decoration: BoxDecoration(\n borderRadius:\n BorderRadius.only(topRight: Radius.circular(10)),\n boxShadow: [\n new BoxShadow(\n color: Colors.grey,\n blurRadius: 10.0,\n offset: new Offset(6.0, 6.0),\n ), //BoxShadow\n ],\n color: Colors.greenAccent[400]), //BoxDecoration\n child: Text(\n 'Flutter is an open-source UI software development kit created by Google. ',\n style: TextStyle(\n color: Colors.grey,\n fontSize: 25,\n ), //TextStyle\n ), //Text\n ), //Tooltip\n..." }, { "code": null, "e": 30976, "s": 30898, "text": "Output: If the above properties are used then the output will look like this." }, { "code": null, "e": 32956, "s": 30976, "text": "Explanation: Flutter doesn’t give the option to modify the tooltip property as used in the menu icon. But if we want to tweak the looks of the tooltip we can always embed it in a Tooltip widget. But flutter provided multiple properties (mentioned above) to change the look and feel of tooltips. In this app, the first change we have made after the message property is the addition of the property waitDuration which takes in Duration as its child which in turn takes the amount of time in seconds to wait before showing tooltip after a user does the appropriate action. Then we have used the showDuration property which is similar to the waitDuration, it controls for how long the tooltip will be displayed. After that, we have the padding which is taking EdgeInsets.all(12) as the parameter to provide the gap between the border of the tooltip and the child widget. A height is 35 is given to tooltip using is height property. The verticalOffset is set to 100 to display the tooltip below the Text widget. Next is the preferBelow property which controls whether to display the tooltip on the widget itself or below it. The preferedBelow property is true by default. But we can see that in the above first example the tooltip is being displayed on the text itself. The reason for this is the size of the Text widget, it’s too big for tooltip it to crossover as it does in with the menu icon. So to change this behavior we have used the verticalOffset property. All this is followed by textStyle, decoration, and child properties. The child property is the same as the previous example which is taking the Text widget as a child. The testStyle property is adding style to the message property, in this property the font size is set to 15, text color to white, and font-weight to normal. The decoration property is in charge of the styling of the tooltip box, in this case, we have made one of the corners round, added a shadow to the tooltip, and gave green color to the tooltip." }, { "code": null, "e": 33204, "s": 32956, "text": "Flutter also offers some other ways of displaying the description of a widget in a more beautiful way. One of the ways is by using showcaseview package. And if you still want something different you can create your own custom widget to do the job." }, { "code": null, "e": 33220, "s": 33204, "text": "rajeev0719singh" }, { "code": null, "e": 33236, "s": 33220, "text": "simranarora5sos" }, { "code": null, "e": 33253, "s": 33236, "text": "arorakashish0911" }, { "code": null, "e": 33261, "s": 33253, "text": "android" }, { "code": null, "e": 33269, "s": 33261, "text": "Flutter" }, { "code": null, "e": 33285, "s": 33269, "text": "Flutter-widgets" }, { "code": null, "e": 33293, "s": 33285, "text": "Android" }, { "code": null, "e": 33298, "s": 33293, "text": "Dart" }, { "code": null, "e": 33306, "s": 33298, "text": "Flutter" }, { "code": null, "e": 33314, "s": 33306, "text": "Android" }, { "code": null, "e": 33412, "s": 33314, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33421, "s": 33412, "text": "Comments" }, { "code": null, "e": 33434, "s": 33421, "text": "Old Comments" }, { "code": null, "e": 33477, "s": 33434, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 33535, "s": 33477, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 33568, "s": 33535, "text": "Services in Android with Example" }, { "code": null, "e": 33610, "s": 33568, "text": "Content Providers in Android with Example" }, { "code": null, "e": 33641, "s": 33610, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 33673, "s": 33641, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 33695, "s": 33673, "text": "Flutter - Asset Image" }, { "code": null, "e": 33723, "s": 33695, "text": "Listview.builder in Flutter" }, { "code": null, "e": 33752, "s": 33723, "text": "Dart - Standard Input Output" } ]
Minimum rotations required to get the same string - GeeksforGeeks
21 Apr, 2022 Given a string, we need to find the minimum number of rotations required to get the same string.Examples: Input : s = "geeks" Output : 5 Input : s = "aaaa" Output : 1 The idea is based on below post.A Program to check if strings are rotations of each other or notStep 1 : Initialize result = 0 (Here result is count of rotations) Step 2 : Take a temporary string equals to original string concatenated with itself. Step 3 : Now take the substring of temporary string of size same as original string starting from second character (or index 1). Step 4 : Increase the count. Step 5 : Check whether the substring becomes equal to original string. If yes, then break the loop. Else go to step 2 and repeat it from the next index. C++ Java Python3 C# PHP Javascript // C++ program to determine minimum number// of rotations required to yield same// string.#include <iostream>using namespace std; // Returns count of rotations to get the// same string back.int findRotations(string str){ // tmp is the concatenated string. string tmp = str + str; int n = str.length(); for (int i = 1; i <= n; i++) { // substring from i index of original // string size. string substring = tmp.substr(i, str.size()); // if substring matches with original string // then we will come out of the loop. if (str == substring) return i; } return n;} // Driver codeint main(){ string str = "abc"; cout << findRotations(str) << endl; return 0;} // Java program to determine minimum number// of rotations required to yield same// string. import java.util.*; class GFG{ // Returns count of rotations to get the // same string back. static int findRotations(String str) { // tmp is the concatenated string. String tmp = str + str; int n = str.length(); for (int i = 1; i <= n; i++) { // substring from i index of original // string size. String substring = tmp.substring( i, i+str.length()); // if substring matches with original string // then we will come out of the loop. if (str.equals(substring)) return i; } return n; } // Driver Method public static void main(String[] args) { String str = "aaaa"; System.out.println(findRotations(str)); }}/* This code is contributed by Mr. Somesh Awasthi */ # Python 3 program to determine minimum# number of rotations required to yield# same string. # Returns count of rotations to get the# same string back.def findRotations(str): # tmp is the concatenated string. tmp = str + str n = len(str) for i in range(1, n + 1): # substring from i index of # original string size. substring = tmp[i: i+n] # if substring matches with # original string then we will # come out of the loop. if (str == substring): return i return n # Driver codeif __name__ == '__main__': str = "abc" print(findRotations(str)) # This code is contributed# by 29AjayKumar. // C# program to determine minimum number// of rotations required to yield same// string.using System; class GFG { // Returns count of rotations to get // the same string back. static int findRotations(String str) { // tmp is the concatenated string. String tmp = str + str; int n = str.Length; for (int i = 1; i <= n; i++) { // substring from i index of // original string size. String substring = tmp.Substring(i, str.Length); // if substring matches with // original string then we will // come out of the loop. if (str == substring) return i; } return n; } // Driver Method public static void Main() { String str = "abc"; Console.Write(findRotations(str)); }} // This code is contributed by nitin mittal. <?php// PHP program to determine minimum// number of rotations required to// yield same string. // Returns count of rotations// to get the same string back.function findRotations($str){ // tmp is the concatenated string. $tmp = ($str + $str); $n = strlen($str); for ( $i = 1; $i <= $n; $i++) { // substring from i index // of original string size. $substring = $tmp.substr($i, strlen($str)); // if substring matches with // original string then we will // come out of the loop. if ($str == $substring) return $i; } return $n;} // Driver code$str = "abc";echo findRotations($str), "\n"; // This code is contributed// by Sachin?> <script>// javascript program to determine minimum number// of rotations required to yield same// string. // Returns count of rotations to get the // same string back. function findRotations( str) { // tmp is the concatenated string. var tmp = str + str; var n = str.length; for (var i = 1; i <= n; i++) { // substring from i index of original // string size. var substring = tmp.substring(i ,str.length); // if substring matches with original string // then we will come out of the loop. if (str===(substring)) return i; } return n; } // Driver Method var str = "abc"; document.write(findRotations(str)); // This code contributed by gauravrajput1</script> Output: 3 Time Complexity: O(n2) Space Complexity : O(2n) ~ O(n) We can solve this problem without using any temporary variable as extra space . We will traverse the original string and at each position we partition it and concatenate the right substring and left substring and check weather it is equal to original string C++ Python3 Javascript // C++ program to determine minimum number// of rotations required to yield same// string.#include <iostream>using namespace std; // Returns count of rotations to get the// same string back.int findRotations(string str){ int ans = 0; //to store the answer int n = str.length(); //length of the string //All the length where we can partition for(int i=1;i<str.length()-1;i++) { //right part + left part = rotated string // we are checking weather the rotated string is equal to //original string if(str.substr(i,n-i) + str.substr(0,i) == str) { ans = i; break; } } if(ans == 0) return n; return ans;} // Driver codeint main(){ string str = "abc"; cout << findRotations(str) << endl; return 0;} # Python program to determine minimum number# of rotations required to yield same# string. # Returns count of rotations to get the# same string back.def findRotations(Str): ans = 0 # to store the answer n = len(Str) # length of the String # All the length where we can partition for i in range(1 , len(Str) - 1): # right part + left part = rotated String # we are checking weather the rotated String is equal to # original String if(Str[i: n] + Str[0: i] == Str): ans = i break if(ans == 0): return n return ans # Driver codeStr = "abc"print(findRotations(Str)) # This code is contributed by shinjanpatra <script> // JavaScript program to determine minimum number// of rotations required to yield same// string. // Returns count of rotations to get the// same string back.function findRotations(str){ let ans = 0; // to store the answer let n = str.length; // length of the string // All the length where we can partition for(let i = 1; i < str.length - 1; i++) { // right part + left part = rotated string // we are checking weather the rotated string is equal to // original string if(str.substr(i, n - i) + str.substr(0, i) == str) { ans = i; break; } } if(ans == 0) return n; return ans;} // Driver code let str = "abc";document.write(findRotations(str),"</br>"); // This code is contributed by shinjanpatra </script> 3 Time Complexity : O(n2) Space Complexity : O(1) Alternate Implementation in Python : Python3 # Python 3 program to determine minimum# number of rotations required to yield# same string. # inputstring = 'aaaa'check = '' for r in range(1, len(string)+1): # checking the input after each rotation check = string[r:] + string[:r] # following if statement checks if input is # equals to check , if yes it will print r and # break out of the loop if check == string: print(r) break # This code is contributed# by nagasowmyanarayanan. Output: 1 This article is contributed by Jatin Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal Sach_Code 29AjayKumar gp6 nagasowmyanarayanan GauravRajput1 kaivalyamanit rotation Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python program to check if a string is palindrome or not Different methods to reverse a string in C/C++ Check for Balanced Brackets in an expression (well-formedness) using Stack KMP Algorithm for Pattern Searching Longest Palindromic Substring | Set 1 Convert string to char array in C++ Caesar Cipher in Cryptography Reverse words in a given string Array of Strings in C++ (5 Different Ways to Create) Top 50 String Coding Problems for Interviews
[ { "code": null, "e": 25158, "s": 25130, "text": "\n21 Apr, 2022" }, { "code": null, "e": 25266, "s": 25158, "text": "Given a string, we need to find the minimum number of rotations required to get the same string.Examples: " }, { "code": null, "e": 25328, "s": 25266, "text": "Input : s = \"geeks\"\nOutput : 5\n\nInput : s = \"aaaa\"\nOutput : 1" }, { "code": null, "e": 25892, "s": 25330, "text": "The idea is based on below post.A Program to check if strings are rotations of each other or notStep 1 : Initialize result = 0 (Here result is count of rotations) Step 2 : Take a temporary string equals to original string concatenated with itself. Step 3 : Now take the substring of temporary string of size same as original string starting from second character (or index 1). Step 4 : Increase the count. Step 5 : Check whether the substring becomes equal to original string. If yes, then break the loop. Else go to step 2 and repeat it from the next index. " }, { "code": null, "e": 25896, "s": 25892, "text": "C++" }, { "code": null, "e": 25901, "s": 25896, "text": "Java" }, { "code": null, "e": 25909, "s": 25901, "text": "Python3" }, { "code": null, "e": 25912, "s": 25909, "text": "C#" }, { "code": null, "e": 25916, "s": 25912, "text": "PHP" }, { "code": null, "e": 25927, "s": 25916, "text": "Javascript" }, { "code": "// C++ program to determine minimum number// of rotations required to yield same// string.#include <iostream>using namespace std; // Returns count of rotations to get the// same string back.int findRotations(string str){ // tmp is the concatenated string. string tmp = str + str; int n = str.length(); for (int i = 1; i <= n; i++) { // substring from i index of original // string size. string substring = tmp.substr(i, str.size()); // if substring matches with original string // then we will come out of the loop. if (str == substring) return i; } return n;} // Driver codeint main(){ string str = \"abc\"; cout << findRotations(str) << endl; return 0;}", "e": 26664, "s": 25927, "text": null }, { "code": "// Java program to determine minimum number// of rotations required to yield same// string. import java.util.*; class GFG{ // Returns count of rotations to get the // same string back. static int findRotations(String str) { // tmp is the concatenated string. String tmp = str + str; int n = str.length(); for (int i = 1; i <= n; i++) { // substring from i index of original // string size. String substring = tmp.substring( i, i+str.length()); // if substring matches with original string // then we will come out of the loop. if (str.equals(substring)) return i; } return n; } // Driver Method public static void main(String[] args) { String str = \"aaaa\"; System.out.println(findRotations(str)); }}/* This code is contributed by Mr. Somesh Awasthi */", "e": 27641, "s": 26664, "text": null }, { "code": "# Python 3 program to determine minimum# number of rotations required to yield# same string. # Returns count of rotations to get the# same string back.def findRotations(str): # tmp is the concatenated string. tmp = str + str n = len(str) for i in range(1, n + 1): # substring from i index of # original string size. substring = tmp[i: i+n] # if substring matches with # original string then we will # come out of the loop. if (str == substring): return i return n # Driver codeif __name__ == '__main__': str = \"abc\" print(findRotations(str)) # This code is contributed# by 29AjayKumar.", "e": 28325, "s": 27641, "text": null }, { "code": "// C# program to determine minimum number// of rotations required to yield same// string.using System; class GFG { // Returns count of rotations to get // the same string back. static int findRotations(String str) { // tmp is the concatenated string. String tmp = str + str; int n = str.Length; for (int i = 1; i <= n; i++) { // substring from i index of // original string size. String substring = tmp.Substring(i, str.Length); // if substring matches with // original string then we will // come out of the loop. if (str == substring) return i; } return n; } // Driver Method public static void Main() { String str = \"abc\"; Console.Write(findRotations(str)); }} // This code is contributed by nitin mittal.", "e": 29293, "s": 28325, "text": null }, { "code": "<?php// PHP program to determine minimum// number of rotations required to// yield same string. // Returns count of rotations// to get the same string back.function findRotations($str){ // tmp is the concatenated string. $tmp = ($str + $str); $n = strlen($str); for ( $i = 1; $i <= $n; $i++) { // substring from i index // of original string size. $substring = $tmp.substr($i, strlen($str)); // if substring matches with // original string then we will // come out of the loop. if ($str == $substring) return $i; } return $n;} // Driver code$str = \"abc\";echo findRotations($str), \"\\n\"; // This code is contributed// by Sachin?>", "e": 30030, "s": 29293, "text": null }, { "code": "<script>// javascript program to determine minimum number// of rotations required to yield same// string. // Returns count of rotations to get the // same string back. function findRotations( str) { // tmp is the concatenated string. var tmp = str + str; var n = str.length; for (var i = 1; i <= n; i++) { // substring from i index of original // string size. var substring = tmp.substring(i ,str.length); // if substring matches with original string // then we will come out of the loop. if (str===(substring)) return i; } return n; } // Driver Method var str = \"abc\"; document.write(findRotations(str)); // This code contributed by gauravrajput1</script>", "e": 30850, "s": 30030, "text": null }, { "code": null, "e": 30860, "s": 30850, "text": "Output: " }, { "code": null, "e": 30862, "s": 30860, "text": "3" }, { "code": null, "e": 31083, "s": 30862, "text": " Time Complexity: O(n2) " }, { "code": null, "e": 31116, "s": 31083, "text": "Space Complexity : O(2n) ~ O(n)" }, { "code": null, "e": 31375, "s": 31116, "text": "We can solve this problem without using any temporary variable as extra space . We will traverse the original string and at each position we partition it and concatenate the right substring and left substring and check weather it is equal to original string" }, { "code": null, "e": 31379, "s": 31375, "text": "C++" }, { "code": null, "e": 31387, "s": 31379, "text": "Python3" }, { "code": null, "e": 31398, "s": 31387, "text": "Javascript" }, { "code": "// C++ program to determine minimum number// of rotations required to yield same// string.#include <iostream>using namespace std; // Returns count of rotations to get the// same string back.int findRotations(string str){ int ans = 0; //to store the answer int n = str.length(); //length of the string //All the length where we can partition for(int i=1;i<str.length()-1;i++) { //right part + left part = rotated string // we are checking weather the rotated string is equal to //original string if(str.substr(i,n-i) + str.substr(0,i) == str) { ans = i; break; } } if(ans == 0) return n; return ans;} // Driver codeint main(){ string str = \"abc\"; cout << findRotations(str) << endl; return 0;}", "e": 32220, "s": 31398, "text": null }, { "code": "# Python program to determine minimum number# of rotations required to yield same# string. # Returns count of rotations to get the# same string back.def findRotations(Str): ans = 0 # to store the answer n = len(Str) # length of the String # All the length where we can partition for i in range(1 , len(Str) - 1): # right part + left part = rotated String # we are checking weather the rotated String is equal to # original String if(Str[i: n] + Str[0: i] == Str): ans = i break if(ans == 0): return n return ans # Driver codeStr = \"abc\"print(findRotations(Str)) # This code is contributed by shinjanpatra", "e": 32911, "s": 32220, "text": null }, { "code": "<script> // JavaScript program to determine minimum number// of rotations required to yield same// string. // Returns count of rotations to get the// same string back.function findRotations(str){ let ans = 0; // to store the answer let n = str.length; // length of the string // All the length where we can partition for(let i = 1; i < str.length - 1; i++) { // right part + left part = rotated string // we are checking weather the rotated string is equal to // original string if(str.substr(i, n - i) + str.substr(0, i) == str) { ans = i; break; } } if(ans == 0) return n; return ans;} // Driver code let str = \"abc\";document.write(findRotations(str),\"</br>\"); // This code is contributed by shinjanpatra </script>", "e": 33743, "s": 32911, "text": null }, { "code": null, "e": 33745, "s": 33743, "text": "3" }, { "code": null, "e": 33962, "s": 33745, "text": " Time Complexity : O(n2) " }, { "code": null, "e": 33987, "s": 33962, "text": "Space Complexity : O(1) " }, { "code": null, "e": 34026, "s": 33987, "text": "Alternate Implementation in Python : " }, { "code": null, "e": 34034, "s": 34026, "text": "Python3" }, { "code": "# Python 3 program to determine minimum# number of rotations required to yield# same string. # inputstring = 'aaaa'check = '' for r in range(1, len(string)+1): # checking the input after each rotation check = string[r:] + string[:r] # following if statement checks if input is # equals to check , if yes it will print r and # break out of the loop if check == string: print(r) break # This code is contributed# by nagasowmyanarayanan.", "e": 34488, "s": 34034, "text": null }, { "code": null, "e": 34498, "s": 34488, "text": "Output: " }, { "code": null, "e": 34500, "s": 34498, "text": "1" }, { "code": null, "e": 34920, "s": 34500, "text": "This article is contributed by Jatin Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 34933, "s": 34920, "text": "nitin mittal" }, { "code": null, "e": 34943, "s": 34933, "text": "Sach_Code" }, { "code": null, "e": 34955, "s": 34943, "text": "29AjayKumar" }, { "code": null, "e": 34959, "s": 34955, "text": "gp6" }, { "code": null, "e": 34979, "s": 34959, "text": "nagasowmyanarayanan" }, { "code": null, "e": 34993, "s": 34979, "text": "GauravRajput1" }, { "code": null, "e": 35007, "s": 34993, "text": "kaivalyamanit" }, { "code": null, "e": 35016, "s": 35007, "text": "rotation" }, { "code": null, "e": 35024, "s": 35016, "text": "Strings" }, { "code": null, "e": 35032, "s": 35024, "text": "Strings" }, { "code": null, "e": 35130, "s": 35032, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35139, "s": 35130, "text": "Comments" }, { "code": null, "e": 35152, "s": 35139, "text": "Old Comments" }, { "code": null, "e": 35209, "s": 35152, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 35256, "s": 35209, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 35331, "s": 35256, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 35367, "s": 35331, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 35405, "s": 35367, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 35441, "s": 35405, "text": "Convert string to char array in C++" }, { "code": null, "e": 35471, "s": 35441, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 35503, "s": 35471, "text": "Reverse words in a given string" }, { "code": null, "e": 35556, "s": 35503, "text": "Array of Strings in C++ (5 Different Ways to Create)" } ]
Minimum Bitwise AND operations to make any two array elements equal - GeeksforGeeks
07 Sep, 2021 Given an array of integers of size ‘n’ and an integer ‘k’, We can perform the Bitwise AND operation between any array element and ‘k’ any number of times. The task is to print the minimum number of such operations required to make any two elements of the array equal. If it is not possible to make any two elements of the array equal after performing the above mentioned operation then print ‘-1’. Examples: Input : k = 6 ; Array : 1, 2, 1, 2 Output : 0 Explanation : There are already two equal elements in the array so the answer is 0.Input : k = 2 ; Array : 5, 6, 2, 4 Output : 1 Explanation : If we apply AND operation on element ‘6’, it will become 6&2 = 2 And the array will become 5 2 2 4, Now, the array has two equal elements, so the answer is 1.Input : k = 15 ; Array : 1, 2, 3 Output : -1 Explanation : No matter how many times we perform the above mentioned operation, this array will never have equal element pair. So the answer is -1 Approach: The key observation is that if it is possible to make the desired array then the answer will be either ‘0’, ‘1’, or ‘2’. It will never exceed ‘2’. Because, if (x&k) = y then, no matter how many times you perform (y&k) it’ll always give ‘y’ as the result. The answer will be ‘0’, if there are already equal elements in the array. For the answer to be ‘1’, we will create a new array b which holds b[i] = (a[i]&K), Now, for each a[i] we will check if there is any index ‘j’ such that i!=j and a[i]=b[j]. If yes, then the answer will be ‘1’. For the answer to be ‘2’, we will check for an index ‘i’ in the new array b, if there is any index ‘j’ such that i != j and b[i] = b[j]. If yes, then the answer will be ‘2’. If any of the above conditions are not satisfied then the answer will be ‘-1’. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to count the// minimum operations required.int minOperations(int a[], int n, int K){ unordered_map<int, bool> map; for (int i = 0; i < n; i++) { // check if the initial array // already contains an equal pair if (map[a[i]]) return 0; map[a[i]] = true; } // create new array with AND operations int b[n]; for (int i = 0; i < n; i++) b[i] = a[i] & K; // clear the map map.clear(); // Check if the solution // is a single operation for (int i = 0; i < n; i++) { // If Bitwise operation between //'k' and a[i] gives // a number other than a[i] if (a[i] != b[i]) map[b[i]] = true; } // Check if any of the a[i] // gets equal to any other element // of the array after the operation. for (int i = 0; i < n; i++) // Single operation // will be enough if (map[a[i]]) return 1; // clear the map map.clear(); // Check if the solution // is two operations for (int i = 0; i < n; i++) { // Check if the array 'b' // contains duplicates if (map[b[i]]) return 2; map[b[i]] = true; } // otherwise it is impossible to // create such an array with // Bitwise AND operations return -1;} // Driver codeint main(){ int K = 3; int a[] = { 1, 2, 3, 7 }; int n = sizeof(a)/sizeof(a[0]); // Function call to compute the result cout << minOperations(a, n, K); return 0;} // Java implementation of the approachimport java.util.*; class geeks{ // Function to count the // minimum operations required. public static int minOperations(int[] a, int n, int K) { HashMap<Integer, Boolean> map = new HashMap<>(); for (int i = 0; i < n; i++) { // check if the initial array // already contains an equal pair // try-catch is used so that // nullpointer exception can be handled try { if (map.get(a[i])) return 1; } catch (Exception e) { //TODO: handle exception } try { map.put(a[i], true); } catch (Exception e) {} } // create new array with AND operations int[] b = new int[n]; for (int i = 0; i < n; i++) b[i] = a[i] & K; // clear the map map.clear(); // Check if the solution // is a single operation for (int i = 0; i < n; i++) { // If Bitwise operation between // 'k' and a[i] gives // a number other than a[i] if (a[i] != b[i]) { try { map.put(b[i], true); } catch (Exception e) {} } } // Check if any of the a[i] // gets equal to any other element // of the array after the operation. for (int i = 0; i < n; i++) { // Single operation // will be enough try { if (map.get(a[i])) return 1; } catch (Exception e) { //TODO: handle exception } } // clear the map map.clear(); // Check if the solution // is two operations for (int i = 0; i < n; i++) { // Check if the array 'b' // contains duplicates try { if (map.get(b[i])) return 2; } catch (Exception e) { //TODO: handle exception } try { map.put(b[i], true); } catch (Exception e) { //TODO: handle exception } } // otherwise it is impossible to // create such an array with // Bitwise AND operations return -1; } // Driver Code public static void main(String[] args) { int K = 3; int[] a = { 1, 2, 3, 7 }; int n = a.length; // Function call to compute the result System.out.println(minOperations(a, n, K)); }} // This code is contributed by// sanjeev2552 # Python3 implementation of the approachfrom collections import defaultdict # Function to count the minimum# operations required.def minOperations(a, n, K): Map = defaultdict(lambda:False) for i in range(0, n): # check if the initial array # already contains an equal pair if Map[a[i]] == True: return 0 Map[a[i]] = True # create new array with AND operations b = [] for i in range(0, n): b.append(a[i] & K) # clear the map Map.clear() # Check if the solution # is a single operation for i in range(0, n): # If Bitwise operation between #'k' and a[i] gives # a number other than a[i] if a[i] != b[i]: Map[b[i]] = True # Check if any of the a[i] # gets equal to any other element # of the array after the operation. for i in range(0, n): # Single operation # will be enough if Map[a[i]] == True: return 1 # clear the map Map.clear() # Check if the solution # is two operations for i in range(0, n): # Check if the array 'b' # contains duplicates if Map[b[i]] == True: return 2 Map[b[i]] = True # otherwise it is impossible to # create such an array with # Bitwise AND operations return -1 # Driver codeif __name__ == "__main__": K = 3 a = [1, 2, 3, 7] n = len(a) # Function call to compute the result print(minOperations(a, n, K)) # This code is contributed by Rituraj Jain // C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function to return the count of // minimum operations required public static int minOperations(int[] a, int n, int K) { Dictionary<int, Boolean> map = new Dictionary<int, Boolean>(); for (int i = 0; i < n; i++) { // Check if the initial array // already contains an equal pair if (map.ContainsKey(a[i])) return 0; map.Add(a[i], true); } // Create new array with AND operations int[] b = new int[n]; for (int i = 0; i < n; i++) b[i] = a[i] & K; // Clear the map map.Clear(); // Check if the solution // is a single operation for (int i = 0; i < n; i++) { // If Bitwise OR operation between // 'k' and a[i] gives // a number other than a[i] if (a[i] != b[i]) map.Add(b[i], true); } // Check if any of the a[i] // gets equal to any other element // of the array after the operation for (int i = 0; i < n; i++) { // Single operation // will be enough if (map.ContainsKey(a[i])) return 1; } // Clear the map map.Clear(); // Check if the solution // is two operations for (int i = 0; i < n; i++) { // Check if the array 'b' // contains duplicates if (map.ContainsKey(b[i])) return 2; map.Add(b[i], true); } // Otherwise it is impossible to // create such an array with // Bitwise OR operations return -1; } // Driver code public static void Main(String[] args) { int K = 3; int[] a = { 1, 2, 3, 7 }; int n = a.Length; Console.WriteLine(minOperations(a, n, K)); }} // This code is contributed by Rajput-Ji <script> // JavaScript implementation of the approach // Function to count the// minimum operations required.function minOperations(a, n, K){ var map = new Map(); for (var i = 0; i < n; i++) { // check if the initial array // already contains an equal pair if (map[a[i]]) return 0; map.set(a[i], true); } // create new array with AND operations var b = Array(n); for (var i = 0; i < n; i++) b[i] = a[i] & K; // clear the map map = new Map(); // Check if the solution // is a single operation for (var i = 0; i < n; i++) { // If Bitwise operation between //'k' and a[i] gives // a number other than a[i] if (a[i] != b[i]) map.set(b[i], true); } // Check if any of the a[i] // gets equal to any other element // of the array after the operation. for (var i = 0; i < n; i++) // Single operation // will be enough if (map.get(a[i])) return 1; // clear the map map = new Map(); // Check if the solution // is two operations for (var i = 0; i < n; i++) { // Check if the array 'b' // contains duplicates if (map.get(b[i])) return 2; map.set(b[i], true); } // otherwise it is impossible to // create such an array with // Bitwise AND operations return -1;} // Driver code var K = 3;var a = [1, 2, 3, 7];var n = a.length; // Function call to compute the resultdocument.write( minOperations(a, n, K)); </script> 1 Complexity: O(n) rituraj_jain sanjeev2552 Rajput-Ji rutvik_56 anikaseth98 Bitwise-AND Arrays Hash Arrays Hash 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) Multidimensional Arrays in Java Queue | Set 1 (Introduction and Array Implementation) Linear Search Python | Using 2D arrays/lists the right way Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Count pairs with given sum Hashing | Set 3 (Open Addressing)
[ { "code": null, "e": 24975, "s": 24947, "text": "\n07 Sep, 2021" }, { "code": null, "e": 25374, "s": 24975, "text": "Given an array of integers of size ‘n’ and an integer ‘k’, We can perform the Bitwise AND operation between any array element and ‘k’ any number of times. The task is to print the minimum number of such operations required to make any two elements of the array equal. If it is not possible to make any two elements of the array equal after performing the above mentioned operation then print ‘-1’. " }, { "code": null, "e": 25385, "s": 25374, "text": "Examples: " }, { "code": null, "e": 25925, "s": 25385, "text": "Input : k = 6 ; Array : 1, 2, 1, 2 Output : 0 Explanation : There are already two equal elements in the array so the answer is 0.Input : k = 2 ; Array : 5, 6, 2, 4 Output : 1 Explanation : If we apply AND operation on element ‘6’, it will become 6&2 = 2 And the array will become 5 2 2 4, Now, the array has two equal elements, so the answer is 1.Input : k = 15 ; Array : 1, 2, 3 Output : -1 Explanation : No matter how many times we perform the above mentioned operation, this array will never have equal element pair. So the answer is -1" }, { "code": null, "e": 26082, "s": 25925, "text": "Approach: The key observation is that if it is possible to make the desired array then the answer will be either ‘0’, ‘1’, or ‘2’. It will never exceed ‘2’." }, { "code": null, "e": 26193, "s": 26082, "text": "Because, if (x&k) = y then, no matter how many times you perform (y&k) it’ll always give ‘y’ as the result. " }, { "code": null, "e": 26267, "s": 26193, "text": "The answer will be ‘0’, if there are already equal elements in the array." }, { "code": null, "e": 26477, "s": 26267, "text": "For the answer to be ‘1’, we will create a new array b which holds b[i] = (a[i]&K), Now, for each a[i] we will check if there is any index ‘j’ such that i!=j and a[i]=b[j]. If yes, then the answer will be ‘1’." }, { "code": null, "e": 26651, "s": 26477, "text": "For the answer to be ‘2’, we will check for an index ‘i’ in the new array b, if there is any index ‘j’ such that i != j and b[i] = b[j]. If yes, then the answer will be ‘2’." }, { "code": null, "e": 26730, "s": 26651, "text": "If any of the above conditions are not satisfied then the answer will be ‘-1’." }, { "code": null, "e": 26782, "s": 26730, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26786, "s": 26782, "text": "C++" }, { "code": null, "e": 26791, "s": 26786, "text": "Java" }, { "code": null, "e": 26799, "s": 26791, "text": "Python3" }, { "code": null, "e": 26802, "s": 26799, "text": "C#" }, { "code": null, "e": 26813, "s": 26802, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to count the// minimum operations required.int minOperations(int a[], int n, int K){ unordered_map<int, bool> map; for (int i = 0; i < n; i++) { // check if the initial array // already contains an equal pair if (map[a[i]]) return 0; map[a[i]] = true; } // create new array with AND operations int b[n]; for (int i = 0; i < n; i++) b[i] = a[i] & K; // clear the map map.clear(); // Check if the solution // is a single operation for (int i = 0; i < n; i++) { // If Bitwise operation between //'k' and a[i] gives // a number other than a[i] if (a[i] != b[i]) map[b[i]] = true; } // Check if any of the a[i] // gets equal to any other element // of the array after the operation. for (int i = 0; i < n; i++) // Single operation // will be enough if (map[a[i]]) return 1; // clear the map map.clear(); // Check if the solution // is two operations for (int i = 0; i < n; i++) { // Check if the array 'b' // contains duplicates if (map[b[i]]) return 2; map[b[i]] = true; } // otherwise it is impossible to // create such an array with // Bitwise AND operations return -1;} // Driver codeint main(){ int K = 3; int a[] = { 1, 2, 3, 7 }; int n = sizeof(a)/sizeof(a[0]); // Function call to compute the result cout << minOperations(a, n, K); return 0;}", "e": 28425, "s": 26813, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class geeks{ // Function to count the // minimum operations required. public static int minOperations(int[] a, int n, int K) { HashMap<Integer, Boolean> map = new HashMap<>(); for (int i = 0; i < n; i++) { // check if the initial array // already contains an equal pair // try-catch is used so that // nullpointer exception can be handled try { if (map.get(a[i])) return 1; } catch (Exception e) { //TODO: handle exception } try { map.put(a[i], true); } catch (Exception e) {} } // create new array with AND operations int[] b = new int[n]; for (int i = 0; i < n; i++) b[i] = a[i] & K; // clear the map map.clear(); // Check if the solution // is a single operation for (int i = 0; i < n; i++) { // If Bitwise operation between // 'k' and a[i] gives // a number other than a[i] if (a[i] != b[i]) { try { map.put(b[i], true); } catch (Exception e) {} } } // Check if any of the a[i] // gets equal to any other element // of the array after the operation. for (int i = 0; i < n; i++) { // Single operation // will be enough try { if (map.get(a[i])) return 1; } catch (Exception e) { //TODO: handle exception } } // clear the map map.clear(); // Check if the solution // is two operations for (int i = 0; i < n; i++) { // Check if the array 'b' // contains duplicates try { if (map.get(b[i])) return 2; } catch (Exception e) { //TODO: handle exception } try { map.put(b[i], true); } catch (Exception e) { //TODO: handle exception } } // otherwise it is impossible to // create such an array with // Bitwise AND operations return -1; } // Driver Code public static void main(String[] args) { int K = 3; int[] a = { 1, 2, 3, 7 }; int n = a.length; // Function call to compute the result System.out.println(minOperations(a, n, K)); }} // This code is contributed by// sanjeev2552", "e": 31306, "s": 28425, "text": null }, { "code": "# Python3 implementation of the approachfrom collections import defaultdict # Function to count the minimum# operations required.def minOperations(a, n, K): Map = defaultdict(lambda:False) for i in range(0, n): # check if the initial array # already contains an equal pair if Map[a[i]] == True: return 0 Map[a[i]] = True # create new array with AND operations b = [] for i in range(0, n): b.append(a[i] & K) # clear the map Map.clear() # Check if the solution # is a single operation for i in range(0, n): # If Bitwise operation between #'k' and a[i] gives # a number other than a[i] if a[i] != b[i]: Map[b[i]] = True # Check if any of the a[i] # gets equal to any other element # of the array after the operation. for i in range(0, n): # Single operation # will be enough if Map[a[i]] == True: return 1 # clear the map Map.clear() # Check if the solution # is two operations for i in range(0, n): # Check if the array 'b' # contains duplicates if Map[b[i]] == True: return 2 Map[b[i]] = True # otherwise it is impossible to # create such an array with # Bitwise AND operations return -1 # Driver codeif __name__ == \"__main__\": K = 3 a = [1, 2, 3, 7] n = len(a) # Function call to compute the result print(minOperations(a, n, K)) # This code is contributed by Rituraj Jain", "e": 32850, "s": 31306, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function to return the count of // minimum operations required public static int minOperations(int[] a, int n, int K) { Dictionary<int, Boolean> map = new Dictionary<int, Boolean>(); for (int i = 0; i < n; i++) { // Check if the initial array // already contains an equal pair if (map.ContainsKey(a[i])) return 0; map.Add(a[i], true); } // Create new array with AND operations int[] b = new int[n]; for (int i = 0; i < n; i++) b[i] = a[i] & K; // Clear the map map.Clear(); // Check if the solution // is a single operation for (int i = 0; i < n; i++) { // If Bitwise OR operation between // 'k' and a[i] gives // a number other than a[i] if (a[i] != b[i]) map.Add(b[i], true); } // Check if any of the a[i] // gets equal to any other element // of the array after the operation for (int i = 0; i < n; i++) { // Single operation // will be enough if (map.ContainsKey(a[i])) return 1; } // Clear the map map.Clear(); // Check if the solution // is two operations for (int i = 0; i < n; i++) { // Check if the array 'b' // contains duplicates if (map.ContainsKey(b[i])) return 2; map.Add(b[i], true); } // Otherwise it is impossible to // create such an array with // Bitwise OR operations return -1; } // Driver code public static void Main(String[] args) { int K = 3; int[] a = { 1, 2, 3, 7 }; int n = a.Length; Console.WriteLine(minOperations(a, n, K)); }} // This code is contributed by Rajput-Ji", "e": 34924, "s": 32850, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Function to count the// minimum operations required.function minOperations(a, n, K){ var map = new Map(); for (var i = 0; i < n; i++) { // check if the initial array // already contains an equal pair if (map[a[i]]) return 0; map.set(a[i], true); } // create new array with AND operations var b = Array(n); for (var i = 0; i < n; i++) b[i] = a[i] & K; // clear the map map = new Map(); // Check if the solution // is a single operation for (var i = 0; i < n; i++) { // If Bitwise operation between //'k' and a[i] gives // a number other than a[i] if (a[i] != b[i]) map.set(b[i], true); } // Check if any of the a[i] // gets equal to any other element // of the array after the operation. for (var i = 0; i < n; i++) // Single operation // will be enough if (map.get(a[i])) return 1; // clear the map map = new Map(); // Check if the solution // is two operations for (var i = 0; i < n; i++) { // Check if the array 'b' // contains duplicates if (map.get(b[i])) return 2; map.set(b[i], true); } // otherwise it is impossible to // create such an array with // Bitwise AND operations return -1;} // Driver code var K = 3;var a = [1, 2, 3, 7];var n = a.length; // Function call to compute the resultdocument.write( minOperations(a, n, K)); </script>", "e": 36479, "s": 34924, "text": null }, { "code": null, "e": 36481, "s": 36479, "text": "1" }, { "code": null, "e": 36500, "s": 36483, "text": "Complexity: O(n)" }, { "code": null, "e": 36513, "s": 36500, "text": "rituraj_jain" }, { "code": null, "e": 36525, "s": 36513, "text": "sanjeev2552" }, { "code": null, "e": 36535, "s": 36525, "text": "Rajput-Ji" }, { "code": null, "e": 36545, "s": 36535, "text": "rutvik_56" }, { "code": null, "e": 36557, "s": 36545, "text": "anikaseth98" }, { "code": null, "e": 36569, "s": 36557, "text": "Bitwise-AND" }, { "code": null, "e": 36576, "s": 36569, "text": "Arrays" }, { "code": null, "e": 36581, "s": 36576, "text": "Hash" }, { "code": null, "e": 36588, "s": 36581, "text": "Arrays" }, { "code": null, "e": 36593, "s": 36588, "text": "Hash" }, { "code": null, "e": 36691, "s": 36593, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36700, "s": 36691, "text": "Comments" }, { "code": null, "e": 36713, "s": 36700, "text": "Old Comments" }, { "code": null, "e": 36761, "s": 36713, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 36793, "s": 36761, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 36847, "s": 36793, "text": "Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 36861, "s": 36847, "text": "Linear Search" }, { "code": null, "e": 36906, "s": 36861, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 36991, "s": 36906, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 37027, "s": 36991, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 37058, "s": 37027, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 37085, "s": 37058, "text": "Count pairs with given sum" } ]
Client side validation with HTML and without JavaScript
To display HTML5 client-side validation error bubbles, use the required attribute. You do not need to have javascript for client side validations like empty text box would never be submitted because HTML5 introduced a new attribute called required which would be used as follows and would insist to have a value: <!DOCTYPE HTML> <html> <body> <form action = "/cgi-bin/html5.cgi" method = "get"> Enter email : <input type="text" name = "newinput" required/> <p>Try to submit using Submit button</p> <input type = "submit" value = "submit" /> </form> </body> </html>
[ { "code": null, "e": 1145, "s": 1062, "text": "To display HTML5 client-side validation error bubbles, use the required attribute." }, { "code": null, "e": 1375, "s": 1145, "text": "You do not need to have javascript for client side validations like empty text box would never be submitted because HTML5 introduced a new attribute called required which would be used as follows and would insist to have a value:" }, { "code": null, "e": 1672, "s": 1375, "text": "<!DOCTYPE HTML>\n<html>\n <body>\n <form action = \"/cgi-bin/html5.cgi\" method = \"get\">\n Enter email : <input type=\"text\" name = \"newinput\" required/>\n <p>Try to submit using Submit button</p>\n <input type = \"submit\" value = \"submit\" />\n </form>\n </body>\n</html>" } ]
SAP ABAP - Case Control Statement
The CASE control statement is used when you need to compare two or more fields. The syntax for CASE control statement is as follows − CASE <field>. WHEN <abc>. <statement block>. WHEN <def>. <tatement block>. WHEN <pqr>. <statement block>. ...... ...... ...... WHEN <xyz>. <statement block>. WHEN OTHERS. <statement block>. ENDCASE. The following rules apply to a CASE statement − No logical expressions can be used for the <field> field. No logical expressions can be used for the <field> field. The field strings used in the CASE statement are treated as type C variables. The field strings used in the CASE statement are treated as type C variables. The statement block following a WHEN clause is executed if the content of the fields shown in the <field> is similar to one of the fields <abc>, <def>, <ghi> up to <xyz>. The statement block following a WHEN clause is executed if the content of the fields shown in the <field> is similar to one of the fields <abc>, <def>, <ghi> up to <xyz>. After executing all the conditions specified in the WHEN statement, the program continues to process the remaining statements after the ENDCASE statement. After executing all the conditions specified in the WHEN statement, the program continues to process the remaining statements after the ENDCASE statement. The WHEN OTHERS clause is executed in a program when the value of the <field> does not match with any value specified in the <abc> up to <xyz> fields of the WHEN clause. The WHEN OTHERS clause is executed in a program when the value of the <field> does not match with any value specified in the <abc> up to <xyz> fields of the WHEN clause. If the WHEN OTHERS clause is omitted and the value of the <field> does not match with any value specified in the <abc> up to <xyz> fields of the WHEN clause, the program continues to process the remaining statements after the ENDCASE statement. If the WHEN OTHERS clause is omitted and the value of the <field> does not match with any value specified in the <abc> up to <xyz> fields of the WHEN clause, the program continues to process the remaining statements after the ENDCASE statement. Report YH_SEP_15. Data: Title_1(10) TYPE C, Title_2(15) TYPE C. Title_1 = 'ABAP'. Title_2 = 'Programming'. CASE Title_2. WHEN 'ABAP'. Write 'This is not the title'. WHEN 'Tutorials'. Write 'This is not the title'. WHEN 'Limited'. Write 'This is not the title'. WHEN 'Programming'. Write 'Yes, this is the title'. WHEN OTHERS. Write 'Sorry, Mismatch'. ENDCASE. The above code produces the following output − Yes, this is the title. 25 Lectures 6 hours Sanjo Thomas 26 Lectures 2 hours Neha Gupta 30 Lectures 2.5 hours Sumit Agarwal 30 Lectures 4 hours Sumit Agarwal 14 Lectures 1.5 hours Neha Malik 13 Lectures 1.5 hours Neha Malik Print Add Notes Bookmark this page
[ { "code": null, "e": 2978, "s": 2898, "text": "The CASE control statement is used when you need to compare two or more fields." }, { "code": null, "e": 3032, "s": 2978, "text": "The syntax for CASE control statement is as follows −" }, { "code": null, "e": 3274, "s": 3032, "text": "CASE <field>. \n \nWHEN <abc>. \n <statement block>.\n \nWHEN <def>. \n <tatement block>.\n \nWHEN <pqr>. \n <statement block>. \n...... \n...... \n...... \nWHEN <xyz>. \n <statement block>. \n \nWHEN OTHERS. \n <statement block>. \nENDCASE.\n" }, { "code": null, "e": 3322, "s": 3274, "text": "The following rules apply to a CASE statement −" }, { "code": null, "e": 3380, "s": 3322, "text": "No logical expressions can be used for the <field> field." }, { "code": null, "e": 3438, "s": 3380, "text": "No logical expressions can be used for the <field> field." }, { "code": null, "e": 3516, "s": 3438, "text": "The field strings used in the CASE statement are treated as type C variables." }, { "code": null, "e": 3594, "s": 3516, "text": "The field strings used in the CASE statement are treated as type C variables." }, { "code": null, "e": 3765, "s": 3594, "text": "The statement block following a WHEN clause is executed if the content of the fields shown in the <field> is similar to one of the fields <abc>, <def>, <ghi> up to <xyz>." }, { "code": null, "e": 3936, "s": 3765, "text": "The statement block following a WHEN clause is executed if the content of the fields shown in the <field> is similar to one of the fields <abc>, <def>, <ghi> up to <xyz>." }, { "code": null, "e": 4091, "s": 3936, "text": "After executing all the conditions specified in the WHEN statement, the program continues to process the remaining statements after the ENDCASE statement." }, { "code": null, "e": 4246, "s": 4091, "text": "After executing all the conditions specified in the WHEN statement, the program continues to process the remaining statements after the ENDCASE statement." }, { "code": null, "e": 4416, "s": 4246, "text": "The WHEN OTHERS clause is executed in a program when the value of the <field> does not match with any value specified in the <abc> up to <xyz> fields of the WHEN clause." }, { "code": null, "e": 4586, "s": 4416, "text": "The WHEN OTHERS clause is executed in a program when the value of the <field> does not match with any value specified in the <abc> up to <xyz> fields of the WHEN clause." }, { "code": null, "e": 4831, "s": 4586, "text": "If the WHEN OTHERS clause is omitted and the value of the <field> does not match with any value specified in the <abc> up to <xyz> fields of the WHEN clause, the program continues to process the remaining statements after the ENDCASE statement." }, { "code": null, "e": 5076, "s": 4831, "text": "If the WHEN OTHERS clause is omitted and the value of the <field> does not match with any value specified in the <abc> up to <xyz> fields of the WHEN clause, the program continues to process the remaining statements after the ENDCASE statement." }, { "code": null, "e": 5486, "s": 5076, "text": "Report YH_SEP_15.\n \nData: Title_1(10) TYPE C, \n Title_2(15) TYPE C. \n\t\nTitle_1 = 'ABAP'.\nTitle_2 = 'Programming'. \n\nCASE Title_2.\n \nWHEN 'ABAP'. \n Write 'This is not the title'. \n\t\nWHEN 'Tutorials'.\n Write 'This is not the title'. \n\t\nWHEN 'Limited'.\n Write 'This is not the title'.\n\t\nWHEN 'Programming'.\n Write 'Yes, this is the title'.\n\t\nWHEN OTHERS.\n Write 'Sorry, Mismatch'.\n\t \nENDCASE. " }, { "code": null, "e": 5533, "s": 5486, "text": "The above code produces the following output −" }, { "code": null, "e": 5558, "s": 5533, "text": "Yes, this is the title.\n" }, { "code": null, "e": 5591, "s": 5558, "text": "\n 25 Lectures \n 6 hours \n" }, { "code": null, "e": 5605, "s": 5591, "text": " Sanjo Thomas" }, { "code": null, "e": 5638, "s": 5605, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 5650, "s": 5638, "text": " Neha Gupta" }, { "code": null, "e": 5685, "s": 5650, "text": "\n 30 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5700, "s": 5685, "text": " Sumit Agarwal" }, { "code": null, "e": 5733, "s": 5700, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 5748, "s": 5733, "text": " Sumit Agarwal" }, { "code": null, "e": 5783, "s": 5748, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5795, "s": 5783, "text": " Neha Malik" }, { "code": null, "e": 5830, "s": 5795, "text": "\n 13 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5842, "s": 5830, "text": " Neha Malik" }, { "code": null, "e": 5849, "s": 5842, "text": " Print" }, { "code": null, "e": 5860, "s": 5849, "text": " Add Notes" } ]
Python program to cyclically rotate an array by one
Given a user input array. Our task is to rotate cyclically means clockwise rotate the value. Input: A=[1,2,3,4,5] Output=[5,1,2,3,4] Step 1: input array element. Step 2: Store the last element in a variable say x. Step 3: Shift all elements one position ahead. Step 4: Replace first element of array with x. # Python program to cyclically rotate #an array by one # Method for rotation def rotate(A, n): x = A[n - 1] for i in range(n - 1, 0, -1): A[i] = A[i - 1]; A[0] = x; # Driver function A=list() n=int(input("Enter the size of the List ::")) print("Enter the Element of List ::") for i in range(int(n)): k=int(input("")) A.append(k) print ("The array is ::>") for i in range(0, n): print (A[i], end = ' ') rotate(A, n) print ("\nRotated array is") for i in range(0, n): print (A[i], end = ' ') Enter the size of the List ::5 Enter the Element of List :: 8 7 90 67 56 The array is ::> 8 7 90 67 56 Rotated array is 56 8 7 90 67
[ { "code": null, "e": 1155, "s": 1062, "text": "Given a user input array. Our task is to rotate cyclically means clockwise rotate the value." }, { "code": null, "e": 1196, "s": 1155, "text": "Input: A=[1,2,3,4,5]\nOutput=[5,1,2,3,4]\n" }, { "code": null, "e": 1372, "s": 1196, "text": "Step 1: input array element.\nStep 2: Store the last element in a variable say x.\nStep 3: Shift all elements one position ahead.\nStep 4: Replace first element of array with x.\n" }, { "code": null, "e": 1890, "s": 1372, "text": "# Python program to cyclically rotate\n#an array by one\n# Method for rotation\ndef rotate(A, n):\n x = A[n - 1]\n for i in range(n - 1, 0, -1):\n A[i] = A[i - 1];\n A[0] = x;\n# Driver function\nA=list()\nn=int(input(\"Enter the size of the List ::\"))\nprint(\"Enter the Element of List ::\")\nfor i in range(int(n)):\n k=int(input(\"\"))\n A.append(k)\nprint (\"The array is ::>\")\nfor i in range(0, n):\n print (A[i], end = ' ')\nrotate(A, n)\nprint (\"\\nRotated array is\")\nfor i in range(0, n):\n print (A[i], end = ' ')" }, { "code": null, "e": 2028, "s": 1890, "text": "Enter the size of the List ::5\nEnter the Element of List ::\n8\n7\n90\n67\n56\nThe array is ::>\n8 7 90 67 56 \nRotated array is\n56 8 7 90 67 \n" } ]
jQuery | focus() with Examples - GeeksforGeeks
03 Aug, 2021 The focus() is an inbuilt method in jQuery which is used to focus on an element. The element get focused by the mouse click or by the tab-navigating button.Syntax: $(selector).focus(function) Here selector is the selected element.Parameter: It accepts an optional parameter “function” which specifies the function to run when the focus event occurs.Return Value: It returns the selected element which get focused. <html> <head> <style> span { display: none; } body { width: 35%; height: 50px; border: 2px solid green; padding: 35px; margin: 10px; } </style> <script src="https://code.jquery.com/jquery-1.10.2.js"> </script></head> <body> <!-- this paragraph element get focused --> <p> <input type="text"> <span>focused</span></p> <!-- jQuery cdee to show working of this method --> <script> $("input").focus(function() { $(this).next("span").css("display", "inline"); }); </script> </body> </html> Output:Before the mouse clicking inside of the input field- After the mouse clicking inside of the input field with text “GeeksforGeeks”- Code #2:In the below code, no parameter is passed to this method. <html> <head> <style> span { display: none; } body { width: 30%; height: 50px; border: 2px solid green; padding: 35px; margin: 10px; } </style> <script src="https://code.jquery.com/jquery-1.10.2.js"> </script></head> <body> <!-- this paragraph element get focused --> <p> <input type="text"> <span>focused</span></p> <!-- jQuery code to show working of this method --> <script> $("input").focus(); </script> </body> </html> Output:Before the mouse is clicked inside of the input field- After the mouse is clicked inside of the input field with text “GeeksforGeeks”- jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples. jQuery-Events JavaScript JQuery 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 Open URL in New Tab using JavaScript ? How to read a local text file using JavaScript? Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to change the background color after clicking the button in JavaScript ? How to add options to a select element using jQuery? How to fetch data from JSON file and display in HTML table using jQuery ?
[ { "code": null, "e": 25708, "s": 25680, "text": "\n03 Aug, 2021" }, { "code": null, "e": 25872, "s": 25708, "text": "The focus() is an inbuilt method in jQuery which is used to focus on an element. The element get focused by the mouse click or by the tab-navigating button.Syntax:" }, { "code": null, "e": 25901, "s": 25872, "text": "$(selector).focus(function)\n" }, { "code": null, "e": 26123, "s": 25901, "text": "Here selector is the selected element.Parameter: It accepts an optional parameter “function” which specifies the function to run when the focus event occurs.Return Value: It returns the selected element which get focused." }, { "code": "<html> <head> <style> span { display: none; } body { width: 35%; height: 50px; border: 2px solid green; padding: 35px; margin: 10px; } </style> <script src=\"https://code.jquery.com/jquery-1.10.2.js\"> </script></head> <body> <!-- this paragraph element get focused --> <p> <input type=\"text\"> <span>focused</span></p> <!-- jQuery cdee to show working of this method --> <script> $(\"input\").focus(function() { $(this).next(\"span\").css(\"display\", \"inline\"); }); </script> </body> </html>", "e": 26777, "s": 26123, "text": null }, { "code": null, "e": 26837, "s": 26777, "text": "Output:Before the mouse clicking inside of the input field-" }, { "code": null, "e": 26915, "s": 26837, "text": "After the mouse clicking inside of the input field with text “GeeksforGeeks”-" }, { "code": null, "e": 26981, "s": 26915, "text": "Code #2:In the below code, no parameter is passed to this method." }, { "code": "<html> <head> <style> span { display: none; } body { width: 30%; height: 50px; border: 2px solid green; padding: 35px; margin: 10px; } </style> <script src=\"https://code.jquery.com/jquery-1.10.2.js\"> </script></head> <body> <!-- this paragraph element get focused --> <p> <input type=\"text\"> <span>focused</span></p> <!-- jQuery code to show working of this method --> <script> $(\"input\").focus(); </script> </body> </html>", "e": 27556, "s": 26981, "text": null }, { "code": null, "e": 27618, "s": 27556, "text": "Output:Before the mouse is clicked inside of the input field-" }, { "code": null, "e": 27698, "s": 27618, "text": "After the mouse is clicked inside of the input field with text “GeeksforGeeks”-" }, { "code": null, "e": 27966, "s": 27698, "text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples." }, { "code": null, "e": 27980, "s": 27966, "text": "jQuery-Events" }, { "code": null, "e": 27991, "s": 27980, "text": "JavaScript" }, { "code": null, "e": 27998, "s": 27991, "text": "JQuery" }, { "code": null, "e": 28096, "s": 27998, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28105, "s": 28096, "text": "Comments" }, { "code": null, "e": 28118, "s": 28105, "text": "Old Comments" }, { "code": null, "e": 28179, "s": 28118, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28224, "s": 28179, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28296, "s": 28224, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28342, "s": 28296, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 28390, "s": 28342, "text": "How to read a local text file using JavaScript?" }, { "code": null, "e": 28419, "s": 28390, "text": "Form validation using jQuery" }, { "code": null, "e": 28482, "s": 28419, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 28559, "s": 28482, "text": "How to change the background color after clicking the button in JavaScript ?" }, { "code": null, "e": 28612, "s": 28559, "text": "How to add options to a select element using jQuery?" } ]
OpenCV Java example to scale an image.
The resize() method of the Imgproc class resizes the specified image. This method accepts − Two Mat objects representing the source and destination images. Two Mat objects representing the source and destination images. A Size object representing the size of the output image. A Size object representing the size of the output image. A double variable representing the scale factor along the horizontal axis. A double variable representing the scale factor along the horizontal axis. A double variable representing the scale factor along the vertical axis. A double variable representing the scale factor along the vertical axis. An integer variable representing the interpolation method to be used in the operation. An integer variable representing the interpolation method to be used in the operation. import java.awt.Image; import java.awt.image.BufferedImage; import java.io.IOException; import javafx.application.Application; import javafx.embed.swing.SwingFXUtils; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.image.ImageView; import javafx.scene.image.WritableImage; import javafx.stage.Stage; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.Size; import org.opencv.highgui.HighGui; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; public class ScalingAnImage extends Application { public void start(Stage stage) throws IOException { //Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); //Reading image data String file ="D:\\Images\\elephant.jpg"; Mat src = Imgcodecs.imread(file); //Creating destination matrix Mat dst = new Mat(src.rows(), src.cols(), src.type()); //Creating the Size object Size size = new Size(src.rows()*0.5, src.rows()*0.5); //Scaling the Image Imgproc.resize(src, dst, size, 0, 0, Imgproc.INTER_AREA); Imgcodecs.imwrite("D:\\Images\\scaling_example.jpg", dst); //Converting matrix to JavaFX writable image Image img = HighGui.toBufferedImage(dst); WritableImage writableImage= SwingFXUtils.toFXImage((BufferedImage) img, null); //Setting the image view ImageView imageView = new ImageView(writableImage); imageView.setX(10); imageView.setY(10); imageView.setPreserveRatio(true); //Setting the Scene object Group root = new Group(imageView); Scene scene = new Scene(root, 595, 400); stage.setTitle("Scaling Example"); stage.setScene(scene); stage.show(); } public static void main(String args[]) { launch(args); } } On executing, the above program generates the following output −
[ { "code": null, "e": 1154, "s": 1062, "text": "The resize() method of the Imgproc class resizes the specified image. This method accepts −" }, { "code": null, "e": 1218, "s": 1154, "text": "Two Mat objects representing the source and destination images." }, { "code": null, "e": 1282, "s": 1218, "text": "Two Mat objects representing the source and destination images." }, { "code": null, "e": 1339, "s": 1282, "text": "A Size object representing the size of the output image." }, { "code": null, "e": 1396, "s": 1339, "text": "A Size object representing the size of the output image." }, { "code": null, "e": 1471, "s": 1396, "text": "A double variable representing the scale factor along the horizontal axis." }, { "code": null, "e": 1546, "s": 1471, "text": "A double variable representing the scale factor along the horizontal axis." }, { "code": null, "e": 1619, "s": 1546, "text": "A double variable representing the scale factor along the vertical axis." }, { "code": null, "e": 1692, "s": 1619, "text": "A double variable representing the scale factor along the vertical axis." }, { "code": null, "e": 1779, "s": 1692, "text": "An integer variable representing the interpolation method to be used in the\noperation." }, { "code": null, "e": 1866, "s": 1779, "text": "An integer variable representing the interpolation method to be used in the\noperation." }, { "code": null, "e": 3698, "s": 1866, "text": "import java.awt.Image;\nimport java.awt.image.BufferedImage;\nimport java.io.IOException;\nimport javafx.application.Application;\nimport javafx.embed.swing.SwingFXUtils;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.image.ImageView;\nimport javafx.scene.image.WritableImage;\nimport javafx.stage.Stage;\nimport org.opencv.core.Core;\nimport org.opencv.core.Mat;\nimport org.opencv.core.Size;\nimport org.opencv.highgui.HighGui;\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\npublic class ScalingAnImage extends Application {\n public void start(Stage stage) throws IOException {\n //Loading the OpenCV core library\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n //Reading image data\n String file =\"D:\\\\Images\\\\elephant.jpg\";\n Mat src = Imgcodecs.imread(file);\n //Creating destination matrix\n Mat dst = new Mat(src.rows(), src.cols(), src.type());\n //Creating the Size object\n Size size = new Size(src.rows()*0.5, src.rows()*0.5);\n //Scaling the Image\n Imgproc.resize(src, dst, size, 0, 0, Imgproc.INTER_AREA);\n Imgcodecs.imwrite(\"D:\\\\Images\\\\scaling_example.jpg\", dst);\n //Converting matrix to JavaFX writable image\n Image img = HighGui.toBufferedImage(dst);\n WritableImage writableImage= SwingFXUtils.toFXImage((BufferedImage) img, null);\n //Setting the image view\n ImageView imageView = new ImageView(writableImage);\n imageView.setX(10);\n imageView.setY(10);\n imageView.setPreserveRatio(true);\n //Setting the Scene object\n Group root = new Group(imageView);\n Scene scene = new Scene(root, 595, 400);\n stage.setTitle(\"Scaling Example\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]) {\n launch(args);\n }\n}" }, { "code": null, "e": 3763, "s": 3698, "text": "On executing, the above program generates the following output −" } ]
Fraction module in Python - GeeksforGeeks
19 Nov, 2020 This module provides support for rational number arithmetic. It allows to create a Fraction instance from integers, floats, numbers, decimals and strings. Fraction Instances : A Fraction instance can be constructed from a pair of integers, from another rational number, or from a string. Fraction instances are hashable, and should be treated as immutable. class fractions.Fraction(numerator=0, denominator=1) : This requires that numerator and denominator are instances of numbers. Rational and a fraction instance with value = (numerator/denominator) is returned. A zerodivision error is raised if denominator = 0.from fractions import Fraction print (Fraction(11, 35))# returns Fraction(11, 35) print (Fraction(10, 18))# returns Fraction(5, 9) print (Fraction())# returns Fraction(0, 1)Output :11/35 5/9 0 class fractions.Fraction(other_fraction) : This requires that other_fraction is instance of numbers.Rational and a fraction instance with same value is returned.class fractions.Fraction(float) : This requires the float instance and a fraction instance with same value is returned.from fractions import Fraction print (Fraction(1.13))# returns Fraction(1272266894732165, 1125899906842624)Output :1272266894732165/1125899906842624 class fractions.Fraction(decimal) : This requires the decimal instance and a fraction instance with same value is returned.from fractions import Fraction print (Fraction('1.13'))# returns Fraction(113, 100)Output :113/100 class fractions.Fraction(string) : This requires the string or unicode instance instance and a fraction instance with same value is returned.Form for this instance : [sign] numerator [‘/’ denominator]Here, sign represents ‘+’ or ‘-’ and numerator and denominator are strings of single digits.from fractions import Fraction print (Fraction('8/25'))# returns Fraction(8, 25) print (Fraction('1.13'))# returns Fraction(113, 100) print (Fraction('3/7'))# returns Fraction(3, 7) print (Fraction('1.414213 \t\n'))# returns Fraction(1414213, 1000000)Output :8/25 113/100 3/7 1414213/1000000 limit_denominator(max_denominator=1000000) :This method is useful for finding rational approximations to a given floating-point number.This module finds and returns the closest Fraction to self that has denominator at most max_denominator.This module can also be used to return the numerator of a given fraction in the lowest term by using the numerator property and the denominator by using the denominator property.from fractions import Fraction print (Fraction('3.14159265358979323846'))# returns Fraction(157079632679489661923, 50000000000000000000) print (Fraction('3.14159265358979323846').limit_denominator(10000))# returns Fraction(355, 113) print (Fraction('3.14159265358979323846').limit_denominator(100))# returns Fraction(311, 99) print (Fraction('3.14159265358979323846').limit_denominator(10))# returns Fraction(22, 7) print (Fraction(125, 50).numerator)# returns 5 print (Fraction(125, 50).denominator)# returns 2Output :157079632679489661923/50000000000000000000 355/113 311/99 22/7 5 2 class fractions.Fraction(numerator=0, denominator=1) : This requires that numerator and denominator are instances of numbers. Rational and a fraction instance with value = (numerator/denominator) is returned. A zerodivision error is raised if denominator = 0.from fractions import Fraction print (Fraction(11, 35))# returns Fraction(11, 35) print (Fraction(10, 18))# returns Fraction(5, 9) print (Fraction())# returns Fraction(0, 1)Output :11/35 5/9 0 from fractions import Fraction print (Fraction(11, 35))# returns Fraction(11, 35) print (Fraction(10, 18))# returns Fraction(5, 9) print (Fraction())# returns Fraction(0, 1) Output : 11/35 5/9 0 class fractions.Fraction(other_fraction) : This requires that other_fraction is instance of numbers.Rational and a fraction instance with same value is returned. class fractions.Fraction(float) : This requires the float instance and a fraction instance with same value is returned.from fractions import Fraction print (Fraction(1.13))# returns Fraction(1272266894732165, 1125899906842624)Output :1272266894732165/1125899906842624 from fractions import Fraction print (Fraction(1.13))# returns Fraction(1272266894732165, 1125899906842624) Output : 1272266894732165/1125899906842624 class fractions.Fraction(decimal) : This requires the decimal instance and a fraction instance with same value is returned.from fractions import Fraction print (Fraction('1.13'))# returns Fraction(113, 100)Output :113/100 from fractions import Fraction print (Fraction('1.13'))# returns Fraction(113, 100) Output : 113/100 class fractions.Fraction(string) : This requires the string or unicode instance instance and a fraction instance with same value is returned.Form for this instance : [sign] numerator [‘/’ denominator]Here, sign represents ‘+’ or ‘-’ and numerator and denominator are strings of single digits.from fractions import Fraction print (Fraction('8/25'))# returns Fraction(8, 25) print (Fraction('1.13'))# returns Fraction(113, 100) print (Fraction('3/7'))# returns Fraction(3, 7) print (Fraction('1.414213 \t\n'))# returns Fraction(1414213, 1000000)Output :8/25 113/100 3/7 1414213/1000000 Form for this instance : [sign] numerator [‘/’ denominator]Here, sign represents ‘+’ or ‘-’ and numerator and denominator are strings of single digits. from fractions import Fraction print (Fraction('8/25'))# returns Fraction(8, 25) print (Fraction('1.13'))# returns Fraction(113, 100) print (Fraction('3/7'))# returns Fraction(3, 7) print (Fraction('1.414213 \t\n'))# returns Fraction(1414213, 1000000) Output : 8/25 113/100 3/7 1414213/1000000 limit_denominator(max_denominator=1000000) :This method is useful for finding rational approximations to a given floating-point number.This module finds and returns the closest Fraction to self that has denominator at most max_denominator.This module can also be used to return the numerator of a given fraction in the lowest term by using the numerator property and the denominator by using the denominator property.from fractions import Fraction print (Fraction('3.14159265358979323846'))# returns Fraction(157079632679489661923, 50000000000000000000) print (Fraction('3.14159265358979323846').limit_denominator(10000))# returns Fraction(355, 113) print (Fraction('3.14159265358979323846').limit_denominator(100))# returns Fraction(311, 99) print (Fraction('3.14159265358979323846').limit_denominator(10))# returns Fraction(22, 7) print (Fraction(125, 50).numerator)# returns 5 print (Fraction(125, 50).denominator)# returns 2Output :157079632679489661923/50000000000000000000 355/113 311/99 22/7 5 2 This method is useful for finding rational approximations to a given floating-point number. This module finds and returns the closest Fraction to self that has denominator at most max_denominator. This module can also be used to return the numerator of a given fraction in the lowest term by using the numerator property and the denominator by using the denominator property. from fractions import Fraction print (Fraction('3.14159265358979323846'))# returns Fraction(157079632679489661923, 50000000000000000000) print (Fraction('3.14159265358979323846').limit_denominator(10000))# returns Fraction(355, 113) print (Fraction('3.14159265358979323846').limit_denominator(100))# returns Fraction(311, 99) print (Fraction('3.14159265358979323846').limit_denominator(10))# returns Fraction(22, 7) print (Fraction(125, 50).numerator)# returns 5 print (Fraction(125, 50).denominator)# returns 2 Output : 157079632679489661923/50000000000000000000 355/113 311/99 22/7 5 2 Performing Mathematical operations on fractions from fractions import Fraction print (Fraction(113, 100) + Fraction(25, 18))# returns Fraction(2267, 900) print (Fraction(18, 5) / Fraction(18, 10))# returns Fraction(2, 1) print (Fraction(18, 5) * Fraction(16, 19))# returns Fraction(288, 95) print (Fraction(18, 5) * Fraction(15, 36))# returns Fraction(3, 2) print (Fraction(12, 5) ** Fraction(12, 10))# returns 2.8592589556010197 Output : 2267/900 2 288/95 3/2 2.8592589556 Fraction-based calculations using various functions of math module import mathfrom fractions import Fraction print (math.sqrt(Fraction(25, 4)))# returns 2.5 print (math.sqrt(Fraction(28,3)))# returns 3.0550504633038935 print (math.floor(Fraction(3558, 1213)))# returns 2 print (Fraction(math.sin(math.pi/3)))# returns Fraction(3900231685776981, 4503599627370496) print (Fraction(math.sin(math.pi/3)).limit_denominator(10))# returns Fraction(6, 7) Output : 2.5 3.0550504633 2.0 3900231685776981/4503599627370496 6/7 This article is contributed by Aditi Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Fraction Python-Library rational-numbers Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Reading and Writing to text files in Python *args and **kwargs in Python sum() function in Python How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 24576, "s": 24548, "text": "\n19 Nov, 2020" }, { "code": null, "e": 24731, "s": 24576, "text": "This module provides support for rational number arithmetic. It allows to create a Fraction instance from integers, floats, numbers, decimals and strings." }, { "code": null, "e": 24933, "s": 24731, "text": "Fraction Instances : A Fraction instance can be constructed from a pair of integers, from another rational number, or from a string. Fraction instances are hashable, and should be treated as immutable." }, { "code": null, "e": 27649, "s": 24933, "text": "class fractions.Fraction(numerator=0, denominator=1) : This requires that numerator and denominator are instances of numbers. Rational and a fraction instance with value = (numerator/denominator) is returned. A zerodivision error is raised if denominator = 0.from fractions import Fraction print (Fraction(11, 35))# returns Fraction(11, 35) print (Fraction(10, 18))# returns Fraction(5, 9) print (Fraction())# returns Fraction(0, 1)Output :11/35\n5/9\n0\nclass fractions.Fraction(other_fraction) : This requires that other_fraction is instance of numbers.Rational and a fraction instance with same value is returned.class fractions.Fraction(float) : This requires the float instance and a fraction instance with same value is returned.from fractions import Fraction print (Fraction(1.13))# returns Fraction(1272266894732165, 1125899906842624)Output :1272266894732165/1125899906842624\nclass fractions.Fraction(decimal) : This requires the decimal instance and a fraction instance with same value is returned.from fractions import Fraction print (Fraction('1.13'))# returns Fraction(113, 100)Output :113/100\nclass fractions.Fraction(string) : This requires the string or unicode instance instance and a fraction instance with same value is returned.Form for this instance : [sign] numerator [‘/’ denominator]Here, sign represents ‘+’ or ‘-’ and numerator and denominator are strings of single digits.from fractions import Fraction print (Fraction('8/25'))# returns Fraction(8, 25) print (Fraction('1.13'))# returns Fraction(113, 100) print (Fraction('3/7'))# returns Fraction(3, 7) print (Fraction('1.414213 \\t\\n'))# returns Fraction(1414213, 1000000)Output :8/25\n113/100\n3/7\n1414213/1000000\nlimit_denominator(max_denominator=1000000) :This method is useful for finding rational approximations to a given floating-point number.This module finds and returns the closest Fraction to self that has denominator at most max_denominator.This module can also be used to return the numerator of a given fraction in the lowest term by using the numerator property and the denominator by using the denominator property.from fractions import Fraction print (Fraction('3.14159265358979323846'))# returns Fraction(157079632679489661923, 50000000000000000000) print (Fraction('3.14159265358979323846').limit_denominator(10000))# returns Fraction(355, 113) print (Fraction('3.14159265358979323846').limit_denominator(100))# returns Fraction(311, 99) print (Fraction('3.14159265358979323846').limit_denominator(10))# returns Fraction(22, 7) print (Fraction(125, 50).numerator)# returns 5 print (Fraction(125, 50).denominator)# returns 2Output :157079632679489661923/50000000000000000000\n355/113\n311/99\n22/7\n5\n2\n" }, { "code": null, "e": 28107, "s": 27649, "text": "class fractions.Fraction(numerator=0, denominator=1) : This requires that numerator and denominator are instances of numbers. Rational and a fraction instance with value = (numerator/denominator) is returned. A zerodivision error is raised if denominator = 0.from fractions import Fraction print (Fraction(11, 35))# returns Fraction(11, 35) print (Fraction(10, 18))# returns Fraction(5, 9) print (Fraction())# returns Fraction(0, 1)Output :11/35\n5/9\n0\n" }, { "code": "from fractions import Fraction print (Fraction(11, 35))# returns Fraction(11, 35) print (Fraction(10, 18))# returns Fraction(5, 9) print (Fraction())# returns Fraction(0, 1)", "e": 28286, "s": 28107, "text": null }, { "code": null, "e": 28295, "s": 28286, "text": "Output :" }, { "code": null, "e": 28308, "s": 28295, "text": "11/35\n5/9\n0\n" }, { "code": null, "e": 28470, "s": 28308, "text": "class fractions.Fraction(other_fraction) : This requires that other_fraction is instance of numbers.Rational and a fraction instance with same value is returned." }, { "code": null, "e": 28740, "s": 28470, "text": "class fractions.Fraction(float) : This requires the float instance and a fraction instance with same value is returned.from fractions import Fraction print (Fraction(1.13))# returns Fraction(1272266894732165, 1125899906842624)Output :1272266894732165/1125899906842624\n" }, { "code": "from fractions import Fraction print (Fraction(1.13))# returns Fraction(1272266894732165, 1125899906842624)", "e": 28849, "s": 28740, "text": null }, { "code": null, "e": 28858, "s": 28849, "text": "Output :" }, { "code": null, "e": 28893, "s": 28858, "text": "1272266894732165/1125899906842624\n" }, { "code": null, "e": 29117, "s": 28893, "text": "class fractions.Fraction(decimal) : This requires the decimal instance and a fraction instance with same value is returned.from fractions import Fraction print (Fraction('1.13'))# returns Fraction(113, 100)Output :113/100\n" }, { "code": "from fractions import Fraction print (Fraction('1.13'))# returns Fraction(113, 100)", "e": 29202, "s": 29117, "text": null }, { "code": null, "e": 29211, "s": 29202, "text": "Output :" }, { "code": null, "e": 29220, "s": 29211, "text": "113/100\n" }, { "code": null, "e": 29811, "s": 29220, "text": "class fractions.Fraction(string) : This requires the string or unicode instance instance and a fraction instance with same value is returned.Form for this instance : [sign] numerator [‘/’ denominator]Here, sign represents ‘+’ or ‘-’ and numerator and denominator are strings of single digits.from fractions import Fraction print (Fraction('8/25'))# returns Fraction(8, 25) print (Fraction('1.13'))# returns Fraction(113, 100) print (Fraction('3/7'))# returns Fraction(3, 7) print (Fraction('1.414213 \\t\\n'))# returns Fraction(1414213, 1000000)Output :8/25\n113/100\n3/7\n1414213/1000000\n" }, { "code": null, "e": 29963, "s": 29811, "text": "Form for this instance : [sign] numerator [‘/’ denominator]Here, sign represents ‘+’ or ‘-’ and numerator and denominator are strings of single digits." }, { "code": "from fractions import Fraction print (Fraction('8/25'))# returns Fraction(8, 25) print (Fraction('1.13'))# returns Fraction(113, 100) print (Fraction('3/7'))# returns Fraction(3, 7) print (Fraction('1.414213 \\t\\n'))# returns Fraction(1414213, 1000000)", "e": 30221, "s": 29963, "text": null }, { "code": null, "e": 30230, "s": 30221, "text": "Output :" }, { "code": null, "e": 30264, "s": 30230, "text": "8/25\n113/100\n3/7\n1414213/1000000\n" }, { "code": null, "e": 31280, "s": 30264, "text": "limit_denominator(max_denominator=1000000) :This method is useful for finding rational approximations to a given floating-point number.This module finds and returns the closest Fraction to self that has denominator at most max_denominator.This module can also be used to return the numerator of a given fraction in the lowest term by using the numerator property and the denominator by using the denominator property.from fractions import Fraction print (Fraction('3.14159265358979323846'))# returns Fraction(157079632679489661923, 50000000000000000000) print (Fraction('3.14159265358979323846').limit_denominator(10000))# returns Fraction(355, 113) print (Fraction('3.14159265358979323846').limit_denominator(100))# returns Fraction(311, 99) print (Fraction('3.14159265358979323846').limit_denominator(10))# returns Fraction(22, 7) print (Fraction(125, 50).numerator)# returns 5 print (Fraction(125, 50).denominator)# returns 2Output :157079632679489661923/50000000000000000000\n355/113\n311/99\n22/7\n5\n2\n" }, { "code": null, "e": 31372, "s": 31280, "text": "This method is useful for finding rational approximations to a given floating-point number." }, { "code": null, "e": 31477, "s": 31372, "text": "This module finds and returns the closest Fraction to self that has denominator at most max_denominator." }, { "code": null, "e": 31656, "s": 31477, "text": "This module can also be used to return the numerator of a given fraction in the lowest term by using the numerator property and the denominator by using the denominator property." }, { "code": "from fractions import Fraction print (Fraction('3.14159265358979323846'))# returns Fraction(157079632679489661923, 50000000000000000000) print (Fraction('3.14159265358979323846').limit_denominator(10000))# returns Fraction(355, 113) print (Fraction('3.14159265358979323846').limit_denominator(100))# returns Fraction(311, 99) print (Fraction('3.14159265358979323846').limit_denominator(10))# returns Fraction(22, 7) print (Fraction(125, 50).numerator)# returns 5 print (Fraction(125, 50).denominator)# returns 2", "e": 32180, "s": 31656, "text": null }, { "code": null, "e": 32189, "s": 32180, "text": "Output :" }, { "code": null, "e": 32257, "s": 32189, "text": "157079632679489661923/50000000000000000000\n355/113\n311/99\n22/7\n5\n2\n" }, { "code": null, "e": 32305, "s": 32257, "text": "Performing Mathematical operations on fractions" }, { "code": "from fractions import Fraction print (Fraction(113, 100) + Fraction(25, 18))# returns Fraction(2267, 900) print (Fraction(18, 5) / Fraction(18, 10))# returns Fraction(2, 1) print (Fraction(18, 5) * Fraction(16, 19))# returns Fraction(288, 95) print (Fraction(18, 5) * Fraction(15, 36))# returns Fraction(3, 2) print (Fraction(12, 5) ** Fraction(12, 10))# returns 2.8592589556010197", "e": 32697, "s": 32305, "text": null }, { "code": null, "e": 32706, "s": 32697, "text": "Output :" }, { "code": null, "e": 32742, "s": 32706, "text": "2267/900\n2\n288/95\n3/2\n2.8592589556\n" }, { "code": null, "e": 32809, "s": 32742, "text": "Fraction-based calculations using various functions of math module" }, { "code": "import mathfrom fractions import Fraction print (math.sqrt(Fraction(25, 4)))# returns 2.5 print (math.sqrt(Fraction(28,3)))# returns 3.0550504633038935 print (math.floor(Fraction(3558, 1213)))# returns 2 print (Fraction(math.sin(math.pi/3)))# returns Fraction(3900231685776981, 4503599627370496) print (Fraction(math.sin(math.pi/3)).limit_denominator(10))# returns Fraction(6, 7)", "e": 33199, "s": 32809, "text": null }, { "code": null, "e": 33208, "s": 33199, "text": "Output :" }, { "code": null, "e": 33268, "s": 33208, "text": "2.5\n3.0550504633\n2.0\n3900231685776981/4503599627370496\n6/7\n" }, { "code": null, "e": 33567, "s": 33268, "text": "This article is contributed by Aditi Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 33692, "s": 33567, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 33701, "s": 33692, "text": "Fraction" }, { "code": null, "e": 33716, "s": 33701, "text": "Python-Library" }, { "code": null, "e": 33733, "s": 33716, "text": "rational-numbers" }, { "code": null, "e": 33740, "s": 33733, "text": "Python" }, { "code": null, "e": 33838, "s": 33740, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33856, "s": 33838, "text": "Python Dictionary" }, { "code": null, "e": 33878, "s": 33856, "text": "Enumerate() in Python" }, { "code": null, "e": 33910, "s": 33878, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 33952, "s": 33910, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 33978, "s": 33952, "text": "Python String | replace()" }, { "code": null, "e": 34015, "s": 33978, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 34059, "s": 34015, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 34088, "s": 34059, "text": "*args and **kwargs in Python" }, { "code": null, "e": 34113, "s": 34088, "text": "sum() function in Python" } ]
DSA using C - Recursion
Recursion refers to a technique in a programming language where a function calls itself. The function which calls itself is called a recursive method. A recursive function must posses the following two characteristics. Base Case(s) Base Case(s) Set of rules which leads to base case after reducing the cases. Set of rules which leads to base case after reducing the cases. Factorial is one of the classical example of recursion. Factorial is a non-negative number satisfying following conditions. 0! = 1 0! = 1 1! = 1 1! = 1 n! = n * n-1! n! = n * n-1! Factorial is represented by "!". Here Rule 1 and Rule 2 are base cases and Rule 3 are factorial rules. As an example, 3! = 3 x 2 x 1 = 6 int factorial(int n){ //base case if(n == 0){ return 1; } else { return n * factorial(n-1); } } Fibonacci Series is another classical example of recursion. Fibonacci series a series of integers satisfying following conditions. F0 = 0 F0 = 0 F1 = 1 F1 = 1 Fn = Fn-1 + Fn-2 Fn = Fn-1 + Fn-2 Fibonacci is represented by "F". Here Rule 1 and Rule 2 are base cases and Rule 3 are fibonnacci rules. As an example, F5 = 0 1 1 2 3 #include <stdio.h> int factorial(int n){ //base case if(n == 0){ return 1; } else { return n * factorial(n-1); } } int fibbonacci(int n){ if(n ==0){ return 0; } else if(n==1){ return 1; } else { return (fibbonacci(n-1) + fibbonacci(n-2)); } } main(){ int n = 5; int i; printf("Factorial of %d: %d\n" , n , factorial(n)); printf("Fibbonacci of %d: " , n); for(i=0;i<n;i++){ printf("%d ",fibbonacci(i)); } } If we compile and run the above program then it would produce following output − Factorial of 5: 120 Fibbonacci of 5: 0 1 1 2 3 Print Add Notes Bookmark this page
[ { "code": null, "e": 2242, "s": 2091, "text": "Recursion refers to a technique in a programming language where a function calls itself. The function which calls itself is called a recursive method." }, { "code": null, "e": 2310, "s": 2242, "text": "A recursive function must posses the following two characteristics." }, { "code": null, "e": 2323, "s": 2310, "text": "Base Case(s)" }, { "code": null, "e": 2336, "s": 2323, "text": "Base Case(s)" }, { "code": null, "e": 2400, "s": 2336, "text": "Set of rules which leads to base case after reducing the cases." }, { "code": null, "e": 2464, "s": 2400, "text": "Set of rules which leads to base case after reducing the cases." }, { "code": null, "e": 2588, "s": 2464, "text": "Factorial is one of the classical example of recursion. Factorial is a non-negative number satisfying following conditions." }, { "code": null, "e": 2595, "s": 2588, "text": "0! = 1" }, { "code": null, "e": 2602, "s": 2595, "text": "0! = 1" }, { "code": null, "e": 2609, "s": 2602, "text": "1! = 1" }, { "code": null, "e": 2616, "s": 2609, "text": "1! = 1" }, { "code": null, "e": 2630, "s": 2616, "text": "n! = n * n-1!" }, { "code": null, "e": 2644, "s": 2630, "text": "n! = n * n-1!" }, { "code": null, "e": 2747, "s": 2644, "text": "Factorial is represented by \"!\". Here Rule 1 and Rule 2 are base cases and Rule 3 are factorial rules." }, { "code": null, "e": 2781, "s": 2747, "text": "As an example, 3! = 3 x 2 x 1 = 6" }, { "code": null, "e": 2901, "s": 2781, "text": "int factorial(int n){\n //base case\n if(n == 0){\n return 1;\n } else {\n return n * factorial(n-1);\n }\n}" }, { "code": null, "e": 3032, "s": 2901, "text": "Fibonacci Series is another classical example of recursion. Fibonacci series a series of integers satisfying following conditions." }, { "code": null, "e": 3039, "s": 3032, "text": "F0 = 0" }, { "code": null, "e": 3046, "s": 3039, "text": "F0 = 0" }, { "code": null, "e": 3053, "s": 3046, "text": "F1 = 1" }, { "code": null, "e": 3060, "s": 3053, "text": "F1 = 1" }, { "code": null, "e": 3077, "s": 3060, "text": "Fn = Fn-1 + Fn-2" }, { "code": null, "e": 3094, "s": 3077, "text": "Fn = Fn-1 + Fn-2" }, { "code": null, "e": 3198, "s": 3094, "text": "Fibonacci is represented by \"F\". Here Rule 1 and Rule 2 are base cases and Rule 3 are fibonnacci rules." }, { "code": null, "e": 3228, "s": 3198, "text": "As an example, F5 = 0 1 1 2 3" }, { "code": null, "e": 3728, "s": 3228, "text": "#include <stdio.h>\n\nint factorial(int n){\n //base case\n if(n == 0){\n return 1;\n } else {\n return n * factorial(n-1);\n }\n}\nint fibbonacci(int n){\n if(n ==0){\n return 0;\n }\n else if(n==1){\n return 1;\n } else {\n return (fibbonacci(n-1) + fibbonacci(n-2));\n }\n}\nmain(){\n int n = 5;\n int i;\n printf(\"Factorial of %d: %d\\n\" , n , factorial(n));\n printf(\"Fibbonacci of %d: \" , n);\n for(i=0;i<n;i++){\n printf(\"%d \",fibbonacci(i)); \n }\n}" }, { "code": null, "e": 3809, "s": 3728, "text": "If we compile and run the above program then it would produce following output −" }, { "code": null, "e": 3857, "s": 3809, "text": "Factorial of 5: 120\nFibbonacci of 5: 0 1 1 2 3\n" }, { "code": null, "e": 3864, "s": 3857, "text": " Print" }, { "code": null, "e": 3875, "s": 3864, "text": " Add Notes" } ]
abstract keyword in java - GeeksforGeeks
12 Apr, 2022 abstract is a non-access modifier in java applicable for classes, methods but not variables. It is used to achieve abstraction which is one of the pillar of Object Oriented Programming(OOP). Following are different contexts where abstract can be used in Java. Abstract classes The class which is having partial implementation(i.e. not all methods present in the class have method definition). To declare a class abstract, use this general form : abstract class class-name{ //body of class } Due to their partial implementation, we cannot instantiate abstract classes.Any subclass of an abstract class must either implement all of the abstract methods in the super-class, or be declared abstract itself.Some of the predefined classes in java are abstract. They depend on their sub-classes to provide complete implementation. For example, java.lang.Number is a abstract class. For more on abstract classes, see abstract classes in java Abstract methods Sometimes, we require just method declaration in super-classes.This can be achieve by specifying the abstract type modifier. These methods are sometimes referred to as subclasser responsibility because they have no implementation specified in the super-class. Thus, a subclass must override them to provide method definition. To declare an abstract method, use this general form: abstract type method-name(parameter-list); As you can see, no method body is present.Any concrete class(i.e. class without abstract keyword) that extends an abstract class must overrides all the abstract methods of the class.Important rules for abstract methods: Any class that contains one or more abstract methods must also be declared abstract The following are various illegal combinations of other modifiers for methods with respect to abstract modifier : finalabstract nativeabstract synchronizedabstract staticabstract privateabstract strictfp finalabstract nativeabstract synchronizedabstract staticabstract privateabstract strictfp final abstract native abstract synchronized abstract static abstract private abstract strictfp Consider the following java program, that illustrate the use of abstract keyword with classes and methods. Java // A java program to demonstrate// use of abstract keyword. // abstract with classabstract class A{ // abstract with method // it has no body abstract void m1(); // concrete methods are still allowed in abstract classes void m2() { System.out.println("This is a concrete method."); }} // concrete class Bclass B extends A{ // class B must override m1() method // otherwise, compile-time exception will be thrown void m1() { System.out.println("B's implementation of m1."); } } // Driver classpublic class AbstractDemo{ public static void main(String args[]) { B b = new B(); b.m1(); b.m2(); }} Output: B's implementation of m1. This is a concrete method. Note : Although abstract classes cannot be used to instantiate objects, they can be used to create object references, because Java’s approach to run-time polymorphism is implemented through the use of super-class references. Thus, it must be possible to create a reference to an abstract class so that it can be used to point to a subclass object. abstract and final In java, you will never see a class or method declared with both final and abstract keywords. For classes, final is used to prevent inheritance whereas abstract classes depends upon their child classes for complete implementation. In cases of methods, final is used to prevent overriding whereas abstract methods needs to be overridden in sub-classes.This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. amanmalakar007 chaandharaghavcb19 Java-keyword Java-Object Oriented Java School Programming Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Split() String method in Java with examples Reverse a string in Java Arrays.sort() in Java with examples How to iterate any Map in Java Initialize an ArrayList in Java Python Dictionary Arrays in C/C++ Reverse a string in Java Inheritance in C++ Constructors in C++
[ { "code": null, "e": 28559, "s": 28531, "text": "\n12 Apr, 2022" }, { "code": null, "e": 28820, "s": 28559, "text": "abstract is a non-access modifier in java applicable for classes, methods but not variables. It is used to achieve abstraction which is one of the pillar of Object Oriented Programming(OOP). Following are different contexts where abstract can be used in Java. " }, { "code": null, "e": 28837, "s": 28820, "text": "Abstract classes" }, { "code": null, "e": 29008, "s": 28837, "text": "The class which is having partial implementation(i.e. not all methods present in the class have method definition). To declare a class abstract, use this general form : " }, { "code": null, "e": 29057, "s": 29008, "text": "abstract class class-name{\n //body of class\n}" }, { "code": null, "e": 29501, "s": 29057, "text": "Due to their partial implementation, we cannot instantiate abstract classes.Any subclass of an abstract class must either implement all of the abstract methods in the super-class, or be declared abstract itself.Some of the predefined classes in java are abstract. They depend on their sub-classes to provide complete implementation. For example, java.lang.Number is a abstract class. For more on abstract classes, see abstract classes in java " }, { "code": null, "e": 29518, "s": 29501, "text": "Abstract methods" }, { "code": null, "e": 29900, "s": 29518, "text": "Sometimes, we require just method declaration in super-classes.This can be achieve by specifying the abstract type modifier. These methods are sometimes referred to as subclasser responsibility because they have no implementation specified in the super-class. Thus, a subclass must override them to provide method definition. To declare an abstract method, use this general form: " }, { "code": null, "e": 29943, "s": 29900, "text": "abstract type method-name(parameter-list);" }, { "code": null, "e": 30165, "s": 29943, "text": "As you can see, no method body is present.Any concrete class(i.e. class without abstract keyword) that extends an abstract class must overrides all the abstract methods of the class.Important rules for abstract methods: " }, { "code": null, "e": 30249, "s": 30165, "text": "Any class that contains one or more abstract methods must also be declared abstract" }, { "code": null, "e": 30453, "s": 30249, "text": "The following are various illegal combinations of other modifiers for methods with respect to abstract modifier : finalabstract nativeabstract synchronizedabstract staticabstract privateabstract strictfp" }, { "code": null, "e": 30543, "s": 30453, "text": "finalabstract nativeabstract synchronizedabstract staticabstract privateabstract strictfp" }, { "code": null, "e": 30549, "s": 30543, "text": "final" }, { "code": null, "e": 30565, "s": 30549, "text": "abstract native" }, { "code": null, "e": 30587, "s": 30565, "text": "abstract synchronized" }, { "code": null, "e": 30603, "s": 30587, "text": "abstract static" }, { "code": null, "e": 30620, "s": 30603, "text": "abstract private" }, { "code": null, "e": 30638, "s": 30620, "text": "abstract strictfp" }, { "code": null, "e": 30747, "s": 30638, "text": "Consider the following java program, that illustrate the use of abstract keyword with classes and methods. " }, { "code": null, "e": 30752, "s": 30747, "text": "Java" }, { "code": "// A java program to demonstrate// use of abstract keyword. // abstract with classabstract class A{ // abstract with method // it has no body abstract void m1(); // concrete methods are still allowed in abstract classes void m2() { System.out.println(\"This is a concrete method.\"); }} // concrete class Bclass B extends A{ // class B must override m1() method // otherwise, compile-time exception will be thrown void m1() { System.out.println(\"B's implementation of m1.\"); } } // Driver classpublic class AbstractDemo{ public static void main(String args[]) { B b = new B(); b.m1(); b.m2(); }}", "e": 31437, "s": 30752, "text": null }, { "code": null, "e": 31447, "s": 31437, "text": "Output: " }, { "code": null, "e": 31500, "s": 31447, "text": "B's implementation of m1.\nThis is a concrete method." }, { "code": null, "e": 31849, "s": 31500, "text": "Note : Although abstract classes cannot be used to instantiate objects, they can be used to create object references, because Java’s approach to run-time polymorphism is implemented through the use of super-class references. Thus, it must be possible to create a reference to an abstract class so that it can be used to point to a subclass object. " }, { "code": null, "e": 31868, "s": 31849, "text": "abstract and final" }, { "code": null, "e": 32642, "s": 31868, "text": "In java, you will never see a class or method declared with both final and abstract keywords. For classes, final is used to prevent inheritance whereas abstract classes depends upon their child classes for complete implementation. In cases of methods, final is used to prevent overriding whereas abstract methods needs to be overridden in sub-classes.This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 32657, "s": 32642, "text": "amanmalakar007" }, { "code": null, "e": 32676, "s": 32657, "text": "chaandharaghavcb19" }, { "code": null, "e": 32689, "s": 32676, "text": "Java-keyword" }, { "code": null, "e": 32710, "s": 32689, "text": "Java-Object Oriented" }, { "code": null, "e": 32715, "s": 32710, "text": "Java" }, { "code": null, "e": 32734, "s": 32715, "text": "School Programming" }, { "code": null, "e": 32739, "s": 32734, "text": "Java" }, { "code": null, "e": 32837, "s": 32739, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32846, "s": 32837, "text": "Comments" }, { "code": null, "e": 32859, "s": 32846, "text": "Old Comments" }, { "code": null, "e": 32903, "s": 32859, "text": "Split() String method in Java with examples" }, { "code": null, "e": 32928, "s": 32903, "text": "Reverse a string in Java" }, { "code": null, "e": 32964, "s": 32928, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 32995, "s": 32964, "text": "How to iterate any Map in Java" }, { "code": null, "e": 33027, "s": 32995, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 33045, "s": 33027, "text": "Python Dictionary" }, { "code": null, "e": 33061, "s": 33045, "text": "Arrays in C/C++" }, { "code": null, "e": 33086, "s": 33061, "text": "Reverse a string in Java" }, { "code": null, "e": 33105, "s": 33086, "text": "Inheritance in C++" } ]
Meteor - Package.js
In this chapter, we will learn how to create our own meteor package. Let's add a new folder on the desktop, where the package will be created. We will use the command prompt window. C:\Users\username\Desktop\meteorApp> mkdir packages Now, we can create the package in the folder we have created above. Run the following command from the command prompt. Username is the Meteor Developer username and package-name is the name of the package. C:\Users\username\Desktop\meteorApp\packages>meteor create --package username:package-name To be able to add a local package to our app, we need to set the ENVIRONMENT VARIABLE that will tell Meteor to load the package from the local folder. Right-click the computer icon and choose properties/Advanced system settings/Environment Variables/NEW. Variable Name should be PACKAGE_DIRS. Variable Value should be the path to the folder we created. In our case, C:\Users\username\Desktop\meteorApp\packages. Don't forget to restart the command prompt after adding a new Environment Variable. We can now add the package to our app by running the following code − C:\Users\username\Desktop\meteorApp>meteor add username:package-name Following four files will be found in the package we created. package-name-test.js package-name.js package.js README.md Meteor offers tinytest package for testing. Let's install it first using the following command in the command prompt window. C:\Users\username\Desktop\meteorApp>meteor add tinytest If we open package-name-test.js, we will see the default test example. We will use this example to test the app. Note: It is always better to write our own tests when developing meteor packages. To test the package, let us run this code in the command prompt. C:\Users\username\Desktop>meteor test-packages packages/package-name We will get the following result. This is the file where we can write the code. Let's create some simple functionality for our package. Our package will log some text in the console. myPackageFunction = function() { console.log('This is simple package...'); } This is the file where we can set some package configuration. We will get back to it later, but for now we need to export myPackageFunction so we can use it in our app. We need to add this inside Package.onUse function. The file will look something like this. Package.describe({ name: 'username:package-name', version: '0.0.1', // Brief, one-line summary of the package. summary: '', // URL to the Git repository containing the source code for this package. git: '', // By default, Meteor will default to using README.md for documentation. // To avoid submitting documentation, set this field to null. documentation: 'README.md' }); Package.onUse(function(api) { api.versionsFrom('1.2.1'); api.use('ecmascript'); api.addFiles('mypackage.js'); api.export('myPackageFunction'); // We are exporting the function we created above... }); Package.onTest(function(api) { api.use('ecmascript'); api.use('tinytest'); api.use('username:package-name'); api.addFiles('package-name-tests.js'); }); Now we can finally call the myPackageFunction() from our meteorApp.js file. if(Meteor.isClient) { myPackageFunction(); } The console will log the text from our package. To better understand how the package.js file can be configured, we will use the example from Meteor official documentation. /* Information about this package */ Package.describe({ // Short two-sentence summary. summary: "What this does", // Version number. version: "1.0.0", // Optional. Default is package directory name. name: "username:package-name", // Optional github URL to your source repository. git: "https://github.com/something/something.git", }); /* This defines your actual package */ Package.onUse(function (api) { // If no version is specified for an 'api.use' dependency, use the // one defined in Meteor 0.9.0. api.versionsFrom('0.9.0'); // Use Underscore package, but only on the server. // Version not specified, so it will be as of Meteor 0.9.0. api.use('underscore', 'server'); // Use iron:router package, version 1.0.0 or newer. api.use('iron:router@1.0.0'); // Give users of this package access to the Templating package. api.imply('templating') // Export the object 'Email' to packages or apps that use this package. api.export('Email', 'server'); // Specify the source code for the package. api.addFiles('email.js', 'server'); }); /* This defines the tests for the package */ Package.onTest(function (api) { // Sets up a dependency on this package api.use('username:package-name'); // Allows you to use the 'tinytest' framework api.use('tinytest@1.0.0'); // Specify the source code for the package tests api.addFiles('email_tests.js', 'server'); }); /* This lets you use npm packages in your package*/ Npm.depends({ simplesmtp: "0.3.10", "stream-buffers": "0.2.5" }); 73 Lectures 4 hours Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2190, "s": 2121, "text": "In this chapter, we will learn how to create our own meteor package." }, { "code": null, "e": 2303, "s": 2190, "text": "Let's add a new folder on the desktop, where the package will be created. We will use the command prompt window." }, { "code": null, "e": 2356, "s": 2303, "text": "C:\\Users\\username\\Desktop\\meteorApp> mkdir packages\n" }, { "code": null, "e": 2562, "s": 2356, "text": "Now, we can create the package in the folder we have created above. Run the following command from the command prompt. Username is the Meteor Developer username and package-name is the name of the package." }, { "code": null, "e": 2654, "s": 2562, "text": "C:\\Users\\username\\Desktop\\meteorApp\\packages>meteor create --package username:package-name\n" }, { "code": null, "e": 2909, "s": 2654, "text": "To be able to add a local package to our app, we need to set the ENVIRONMENT VARIABLE that will tell Meteor to load the package from the local folder. Right-click the computer icon and choose properties/Advanced system settings/Environment Variables/NEW." }, { "code": null, "e": 3066, "s": 2909, "text": "Variable Name should be PACKAGE_DIRS. Variable Value should be the path to the folder we created. In our case, C:\\Users\\username\\Desktop\\meteorApp\\packages." }, { "code": null, "e": 3150, "s": 3066, "text": "Don't forget to restart the command prompt after adding a new Environment Variable." }, { "code": null, "e": 3220, "s": 3150, "text": "We can now add the package to our app by running the following code −" }, { "code": null, "e": 3290, "s": 3220, "text": "C:\\Users\\username\\Desktop\\meteorApp>meteor add username:package-name\n" }, { "code": null, "e": 3352, "s": 3290, "text": "Following four files will be found in the package we created." }, { "code": null, "e": 3373, "s": 3352, "text": "package-name-test.js" }, { "code": null, "e": 3389, "s": 3373, "text": "package-name.js" }, { "code": null, "e": 3400, "s": 3389, "text": "package.js" }, { "code": null, "e": 3410, "s": 3400, "text": "README.md" }, { "code": null, "e": 3535, "s": 3410, "text": "Meteor offers tinytest package for testing. Let's install it first using the following command in the command prompt window." }, { "code": null, "e": 3592, "s": 3535, "text": "C:\\Users\\username\\Desktop\\meteorApp>meteor add tinytest\n" }, { "code": null, "e": 3787, "s": 3592, "text": "If we open package-name-test.js, we will see the default test example. We will use this example to test the app. Note: It is always better to write our own tests when developing meteor packages." }, { "code": null, "e": 3852, "s": 3787, "text": "To test the package, let us run this code in the command prompt." }, { "code": null, "e": 3922, "s": 3852, "text": "C:\\Users\\username\\Desktop>meteor test-packages packages/package-name\n" }, { "code": null, "e": 3956, "s": 3922, "text": "We will get the following result." }, { "code": null, "e": 4105, "s": 3956, "text": "This is the file where we can write the code. Let's create some simple functionality for our package. Our package will log some text in the console." }, { "code": null, "e": 4185, "s": 4105, "text": "myPackageFunction = function() {\n console.log('This is simple package...');\n}" }, { "code": null, "e": 4445, "s": 4185, "text": "This is the file where we can set some package configuration. We will get back to it later, but for now we need to export myPackageFunction so we can use it in our app. We need to add this inside Package.onUse function. The file will look something like this." }, { "code": null, "e": 5239, "s": 4445, "text": "Package.describe({\n name: 'username:package-name',\n version: '0.0.1',\n \n // Brief, one-line summary of the package.\n summary: '',\n \n // URL to the Git repository containing the source code for this package.\n git: '',\n \n // By default, Meteor will default to using README.md for documentation.\n \n // To avoid submitting documentation, set this field to null.\n documentation: 'README.md'\n});\n\nPackage.onUse(function(api) {\n api.versionsFrom('1.2.1');\n api.use('ecmascript');\n api.addFiles('mypackage.js');\n api.export('myPackageFunction'); // We are exporting the function we created above...\n});\n\nPackage.onTest(function(api) {\n api.use('ecmascript');\n api.use('tinytest');\n api.use('username:package-name');\n api.addFiles('package-name-tests.js');\n});" }, { "code": null, "e": 5315, "s": 5239, "text": "Now we can finally call the myPackageFunction() from our meteorApp.js file." }, { "code": null, "e": 5363, "s": 5315, "text": "if(Meteor.isClient) {\n myPackageFunction();\n}" }, { "code": null, "e": 5411, "s": 5363, "text": "The console will log the text from our package." }, { "code": null, "e": 5535, "s": 5411, "text": "To better understand how the package.js file can be configured, we will use the example from Meteor official documentation." }, { "code": null, "e": 7114, "s": 5535, "text": "/* Information about this package */\nPackage.describe({\n \n // Short two-sentence summary.\n summary: \"What this does\",\n\n // Version number.\n version: \"1.0.0\",\n\n // Optional. Default is package directory name.\n name: \"username:package-name\",\n\n // Optional github URL to your source repository.\n git: \"https://github.com/something/something.git\",\n});\n\n/* This defines your actual package */\nPackage.onUse(function (api) {\n\n // If no version is specified for an 'api.use' dependency, use the\n // one defined in Meteor 0.9.0.\n api.versionsFrom('0.9.0');\n\n // Use Underscore package, but only on the server.\n // Version not specified, so it will be as of Meteor 0.9.0.\n api.use('underscore', 'server');\n\n // Use iron:router package, version 1.0.0 or newer.\n api.use('iron:router@1.0.0');\n\n // Give users of this package access to the Templating package.\n api.imply('templating')\n\n // Export the object 'Email' to packages or apps that use this package.\n api.export('Email', 'server');\n\n // Specify the source code for the package.\n api.addFiles('email.js', 'server');\n});\n\n/* This defines the tests for the package */\nPackage.onTest(function (api) {\n\n // Sets up a dependency on this package\n api.use('username:package-name');\n\n // Allows you to use the 'tinytest' framework\n api.use('tinytest@1.0.0');\n\n // Specify the source code for the package tests\n api.addFiles('email_tests.js', 'server');\n});\n\n/* This lets you use npm packages in your package*/\nNpm.depends({\n simplesmtp: \"0.3.10\",\n \"stream-buffers\": \"0.2.5\"\n});" }, { "code": null, "e": 7147, "s": 7114, "text": "\n 73 Lectures \n 4 hours \n" }, { "code": null, "e": 7167, "s": 7147, "text": " Skillbakerystudios" }, { "code": null, "e": 7174, "s": 7167, "text": " Print" }, { "code": null, "e": 7185, "s": 7174, "text": " Add Notes" } ]
Count distinct pairs with difference k | Practice | GeeksforGeeks
Given an integer array and a non-negative integer k, count all distinct pairs with difference equal to k, i.e., A[ i ] - A[ j ] = k Example 1: Input: array = {1, 5, 4, 1, 2}, k = 0 Output: 1 Explanation: There is only one pair (1, 1) whose difference equal to 0. Example 2; Input: array = {1, 5, 3}, k = 2 Output: 2 Explanation: There are two pairs (5, 3) and (1, 3) whose difference equal to 2. Your Task: You don't need to read or print anything. Your task is to complete the function TotalPairs() which takes array and k as input parameter and returns count of all distinct pairs. Expected Time Complexity: O(Max(Ai)) Expected Space Complexity: O(Max(Ai)) Constraints: 0 <= length of array, k <= 100000 1 <= elements of array <= 100000 0 mayank20212 days ago C++ : 1.22/2.51int TotalPairs(vector<int>nums, int k){ int count=0; unordered_map<int, int>mp; for(int i=0; i<nums.size(); i++) mp[nums[i]]++; for(int i=0; i<nums.size(); i++) { if(!k && mp[nums[i]]>1) count++; else if(k && mp[nums[i]] && mp[nums[i]+k]) count++; if(k && mp[nums[i]] && mp[nums[i]-k]) count++; mp.erase(nums[i]); } return count; } +2 shivanshpandey1573 weeks ago unordered_map<int,int>mp; int count=0; for(int i=0;i<arr.size();i++) { mp[arr[i]]++; } for(auto x:mp) { if(mp.find(x.first-k)!=mp.end()) { if((x.first-k)==x.first) { if(x.second>1) count++; } else count++; } } return count; 0 shadabarshad162 months ago time-o(n) space-o(n)class Solution{ public int TotalPairs(int[] a, int k) { int n = a.length; int c=0; HashMap<Integer,Integer>map=new HashMap<>(); for(int i=0;i<n;i++) { if(map.containsKey(a[i])) { map.put(a[i],map.get(a[i])+1); } else { map.put(a[i],1); } } for(int i=0;i<n;i++) { if(map.containsKey(a[i]-k)) { if(a[i] == a[i]-k && map.get(a[i]-k)==1) { continue; } else{ c++; map.remove(a[i]-k); } } } return c; }} 0 akkeshri140420012 months ago int TotalPairs(vector<int>nums, int k){ // Code here map<int,int>m; int count=0; for(int i=0;i<nums.size();i++){ m[nums[i]]++; } for(auto x:m){ if(k==0){ if(x.second>1){ count++; } } else{ if(m.find(x.first-k)!=m.end()){ count++; } } } return count; } 0 codertheta12 months ago TC O(nlogn) SC O(1) Arrays.sort(nums); int i = 0, j = 1,ans = 0; while(i < nums.length && j < nums.length){ if(i > 0 && i < nums.length && nums[i - 1] == nums[i]){i++; continue;} int diff = nums[j] - nums[i]; if(i == j){ if(target < 0) i++; else j++; continue; } if(diff == target){ ans++; i++; j++; } else if(diff < target) j++; else i++; } return ans; 0 independentanup2 months ago pls check my mistake int TotalPairs(vector<int>nums, int k){ // Code here sort(nums.begin(),nums.end()); int count=0; unordered_map<int,int>mp; for(int i=0;i<nums.size();i++){ mp[nums[i]]++; } for(auto i=mp.begin();i!=mp.end();i++){ auto it =mp.find((i->first)+k); if(it!=mp.end()){ count=count+(i->second) * (it->second); } } return count;} +2 avinav26113 months ago Easiest C++ Solution (working!) The idea is to distinguish all the duplicates elements and then count the pair-difference......and sorted in descending order so that all the sums of smaller elements are taken into consideration. 0 rathoredivya1503 months ago class sloution{public:int TotalPairs(vector<int>nums, int k){ unordered_map<int,int>mp; int count=0; typedef pair<int, int> pairs; set<pairs>s; for(int i=0;i<nums.size();i++) { mp[nums[i]]++; } if(k==0){ for(int i=0;i<nums.size();i++) { if(mp[nums[i]]>1) { count++; mp.erase(nums[i]); } }} else { for(int i=0;i<nums.size();i++) { if(mp.find(nums[i]+k)!=mp.end()) { count++; pairs x=make_pair(nums[i]+k,nums[i]); s.insert(x); } } count=s.size(); }return count; // Code here}}; 0 mhbhuiyan10023 This comment was deleted. 0 mhbhuiyan10023 This comment was deleted. We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 372, "s": 238, "text": "Given an integer array and a non-negative integer k, count all distinct pairs with difference equal to k, i.e., A[ i ] - A[ j ] = k\n " }, { "code": null, "e": 383, "s": 372, "text": "Example 1:" }, { "code": null, "e": 504, "s": 383, "text": "Input: array = {1, 5, 4, 1, 2}, k = 0\nOutput: 1\nExplanation: There is only one pair (1, 1)\nwhose difference equal to 0.\n" }, { "code": null, "e": 515, "s": 504, "text": "Example 2;" }, { "code": null, "e": 639, "s": 515, "text": "Input: array = {1, 5, 3}, k = 2\nOutput: 2\nExplanation: There are two pairs (5, 3) and \n(1, 3) whose difference equal to 2.\n" }, { "code": null, "e": 831, "s": 641, "text": "Your Task:\nYou don't need to read or print anything. Your task is to complete the function TotalPairs() which takes array and k as input parameter and returns count of all distinct pairs.\n " }, { "code": null, "e": 908, "s": 831, "text": "Expected Time Complexity: O(Max(Ai))\nExpected Space Complexity: O(Max(Ai))\n " }, { "code": null, "e": 988, "s": 908, "text": "Constraints:\n0 <= length of array, k <= 100000\n1 <= elements of array <= 100000" }, { "code": null, "e": 990, "s": 988, "text": "0" }, { "code": null, "e": 1011, "s": 990, "text": "mayank20212 days ago" }, { "code": null, "e": 1498, "s": 1011, "text": "C++ : 1.22/2.51int TotalPairs(vector<int>nums, int k){ int count=0; unordered_map<int, int>mp; for(int i=0; i<nums.size(); i++) mp[nums[i]]++; for(int i=0; i<nums.size(); i++) { if(!k && mp[nums[i]]>1) count++; else if(k && mp[nums[i]] && mp[nums[i]+k]) count++; if(k && mp[nums[i]] && mp[nums[i]-k]) count++; mp.erase(nums[i]); } return count; }" }, { "code": null, "e": 1501, "s": 1498, "text": "+2" }, { "code": null, "e": 1530, "s": 1501, "text": "shivanshpandey1573 weeks ago" }, { "code": null, "e": 1891, "s": 1530, "text": "unordered_map<int,int>mp; int count=0; for(int i=0;i<arr.size();i++) { mp[arr[i]]++; } for(auto x:mp) { if(mp.find(x.first-k)!=mp.end()) { if((x.first-k)==x.first) { if(x.second>1) count++; } else count++; } } return count;" }, { "code": null, "e": 1893, "s": 1891, "text": "0" }, { "code": null, "e": 1920, "s": 1893, "text": "shadabarshad162 months ago" }, { "code": null, "e": 1930, "s": 1920, "text": "time-o(n)" }, { "code": null, "e": 2720, "s": 1930, "text": "space-o(n)class Solution{ public int TotalPairs(int[] a, int k) { int n = a.length; int c=0; HashMap<Integer,Integer>map=new HashMap<>(); for(int i=0;i<n;i++) { if(map.containsKey(a[i])) { map.put(a[i],map.get(a[i])+1); } else { map.put(a[i],1); } } for(int i=0;i<n;i++) { if(map.containsKey(a[i]-k)) { if(a[i] == a[i]-k && map.get(a[i]-k)==1) { continue; } else{ c++; map.remove(a[i]-k); } } }" }, { "code": null, "e": 2742, "s": 2720, "text": " return c; }}" }, { "code": null, "e": 2744, "s": 2742, "text": "0" }, { "code": null, "e": 2773, "s": 2744, "text": "akkeshri140420012 months ago" }, { "code": null, "e": 3177, "s": 2773, "text": "int TotalPairs(vector<int>nums, int k){\n // Code here\n map<int,int>m;\n int count=0;\n for(int i=0;i<nums.size();i++){\n m[nums[i]]++;\n }\n for(auto x:m){\n if(k==0){\n if(x.second>1){\n count++;\n }\n }\n else{\n if(m.find(x.first-k)!=m.end()){\n count++;\n }\n }\n }\n return count;\n}" }, { "code": null, "e": 3179, "s": 3177, "text": "0" }, { "code": null, "e": 3203, "s": 3179, "text": "codertheta12 months ago" }, { "code": null, "e": 3890, "s": 3203, "text": "TC O(nlogn) SC O(1)\n Arrays.sort(nums);\n int i = 0, j = 1,ans = 0;\n while(i < nums.length && j < nums.length){\n \n if(i > 0 && i < nums.length && nums[i - 1] == nums[i]){i++; continue;}\n \n int diff = nums[j] - nums[i];\n \n if(i == j){\n if(target < 0)\n i++;\n else\n j++;\n continue;\n }\n \n if(diff == target){\n ans++;\n i++;\n j++;\n }\n else if(diff < target) j++;\n else\n i++;\n }\n return ans;" }, { "code": null, "e": 3892, "s": 3890, "text": "0" }, { "code": null, "e": 3920, "s": 3892, "text": "independentanup2 months ago" }, { "code": null, "e": 3941, "s": 3920, "text": "pls check my mistake" }, { "code": null, "e": 4327, "s": 3943, "text": "int TotalPairs(vector<int>nums, int k){ // Code here sort(nums.begin(),nums.end()); int count=0; unordered_map<int,int>mp; for(int i=0;i<nums.size();i++){ mp[nums[i]]++; } for(auto i=mp.begin();i!=mp.end();i++){ auto it =mp.find((i->first)+k); if(it!=mp.end()){ count=count+(i->second) * (it->second); } } return count;}" }, { "code": null, "e": 4332, "s": 4329, "text": "+2" }, { "code": null, "e": 4355, "s": 4332, "text": "avinav26113 months ago" }, { "code": null, "e": 4387, "s": 4355, "text": "Easiest C++ Solution (working!)" }, { "code": null, "e": 4588, "s": 4391, "text": "The idea is to distinguish all the duplicates elements and then count the pair-difference......and sorted in descending order so that all the sums of smaller elements are taken into consideration." }, { "code": null, "e": 4590, "s": 4588, "text": "0" }, { "code": null, "e": 4618, "s": 4590, "text": "rathoredivya1503 months ago" }, { "code": null, "e": 4758, "s": 4618, "text": "class sloution{public:int TotalPairs(vector<int>nums, int k){ unordered_map<int,int>mp; int count=0; typedef pair<int, int> pairs;" }, { "code": null, "e": 5353, "s": 4758, "text": "set<pairs>s; for(int i=0;i<nums.size();i++) { mp[nums[i]]++; } if(k==0){ for(int i=0;i<nums.size();i++) { if(mp[nums[i]]>1) { count++; mp.erase(nums[i]); } }} else { for(int i=0;i<nums.size();i++) { if(mp.find(nums[i]+k)!=mp.end()) { count++; pairs x=make_pair(nums[i]+k,nums[i]); s.insert(x); } } count=s.size(); }return count; // Code here}};" }, { "code": null, "e": 5359, "s": 5357, "text": "0" }, { "code": null, "e": 5374, "s": 5359, "text": "mhbhuiyan10023" }, { "code": null, "e": 5400, "s": 5374, "text": "This comment was deleted." }, { "code": null, "e": 5402, "s": 5400, "text": "0" }, { "code": null, "e": 5417, "s": 5402, "text": "mhbhuiyan10023" }, { "code": null, "e": 5443, "s": 5417, "text": "This comment was deleted." }, { "code": null, "e": 5589, "s": 5443, "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": 5625, "s": 5589, "text": " Login to access your submissions. " }, { "code": null, "e": 5635, "s": 5625, "text": "\nProblem\n" }, { "code": null, "e": 5645, "s": 5635, "text": "\nContest\n" }, { "code": null, "e": 5708, "s": 5645, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5856, "s": 5708, "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": 6064, "s": 5856, "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": 6170, "s": 6064, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Data Retention: Handling Data with Many Missing Values and Less Than 1000 Observations | by Asel Mendis | Towards Data Science
The data used in the current project contains a number of diagnostic measures of type 2 diabetes in women of the Pima Indian heritage, and whether or not the individual has type 2 diabetes. The dataset was obtained from Kaggle at (https://www.kaggle.com/uciml/pima-indians-diabetes-database). There is a total of 768 observations and 9 variables. The variables in the dataset are: Pregnancies Glucose — The blood plasma glucose concentration after a 2 hour oral glucose tolerance test. BloodPressure — Diastolic blood pressure (mm/HG). SkinThickness — Skinfold thickness of the triceps (mm). Insulin — 2 hour serum insulin (mu U/ml). BMI — Body mass index (kg/m squared) DiabetesPedigreeFunction — A function that determines the risk of type 2 diabetes based on family history, the larger the function, the higher the risk of type 2 diabetes. Age. Outcome — Whether the person is diagnosed with type 2 diabetes (1 = yes, 0 = no). library(readr) library(tidyverse) library(dplyr) library(knitr) glimpse(Diabetes)Observations: 768 Variables: 9 $ Pregnancies <int> 6, 1, 8, 1, 0, 5, 3, 10, 2, 8, 4... $ Glucose <int> 148, 85, 183, 89, 137, 116, 78, ... $ BloodPressure <int> 72, 66, 64, 66, 40, 74, 50, 0, 7... $ SkinThickness <int> 35, 29, 0, 23, 35, 0, 32, 0, 45,... $ Insulin <int> 0, 0, 0, 94, 168, 0, 88, 0, 543,... $ BMI <dbl> 33.6, 26.6, 23.3, 28.1, 43.1, 25... $ DiabetesPedigreeFunction <dbl> 0.627, 0.351, 0.672, 0.167, 2.28... $ Age <int> 50, 31, 32, 21, 33, 30, 26, 29, ... $ Outcome <int> 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0,... The outcome variable needs to be converted into a categorical variable. It will be ordered to accommodate analysis purposes in the near future. Diabetes$Outcome <- as.factor(unlist(Diabetes$Outcome)) Diabetes$Outcome <- factor(Diabetes$Outcome, levels=c("1", "0"), labels = c("Positive", "Negative")) summary(Diabetes$Outcome)Positive Negative 268 500 We can see that there are almost twice as many people wihtout diabetes than there are with diabetes. While there is no universal cutoff for the number of rows for your target variable, this should suffice. We just need to make sure that there is enough data for your model to learn how to differentiate between the two. The following variables: * Glucose * BloodPressure * SkinThickness * Insulin * BMI need to be converted into numeric variables from its current integer class. These variables have decimal values and its absence could potentially create misleading results and distort specified ranges of risk represented by those medical tests. Diabetes$Glucose <- as.numeric(Diabetes$Glucose) Diabetes$BloodPressure <- as.numeric(Diabetes$BloodPressure) Diabetes$SkinThickness <- as.numeric(Diabetes$SkinThickness) Diabetes$Insulin <- as.numeric(Diabetes$Insulin) Diabetes$BMI <- as.numeric(Diabetes$BMI) Diabetes$Age <- as.integer(Diabetes$Age) 6/9 variables in the dataset have a number of zero markers. It appears that after taking the sum of each column and row separately, there are 763 zero values in the dataset. Alarmingly, this represents almost 100% of our observations. list( Column = colSums(Diabetes==0), Row = sum(rowSums(Diabetes==0)) )$Column Pregnancies 111Glucose 5 BloodPressure 35 SkinThickness 227 Insulin 374 BMI 11 DiabetesPedigreeFunction 0Age 0 Outcome 0 $Row [1] 763 A value of ‘0’ does not necessarily mean it is a missing value. For example: A woman has a zero record of pregnancies because that woman has not been pregnant. This is one example on how careful you have to be when preprocessing your data for missing values. Zero does not mean it is missing. However in addition to that point, zero values could create problems when passing it to a machine learning model. Techniques like Regression can give you an estimate of the output when the variable is zero. Another method of dealing with zeros could be to bin the variable which will then create a categorical variable. Diabetes$Pregnancies <- ifelse(Diabetes$Pregnancies==0, "No", "Yes") %>% factor() summary(Diabetes$Pregnancies) No Yes 111 657 50% of the rows in Insulin have 0 values. Lets look at it in a practical sense. There are times when the body produces little to no insulin which is a sign on Type 1 Diabetes. But I doubt this is the case in this instance. Insulin is such an important variable concerning Diabetes, but when a variable is just rife with missing values you have to do something about it. You can just impute the values, but this is medical data and half of the values are missing. It would not be appropriate to just impute the rows with it mean in my opinion. That’s why no matter how important it is, it has to be REMOVED. This is one of those times where you need to make a tough call. Diabetes$Insulin <- NULL The same can be said for SkinThickness. 31% of its rows have 0 as a value. Practically how can a human have 0mm skinfold thickness. This variable is also not giving us much use. Therefore I will remove this variable as well. Diabetes$SkinThickness <- NULL BMI can be supplemented with its respective range of obesity criteria. BMI only has 11 0 values so it would not be expected to cause too much trouble. If it was substantially higher, binning would not really solve the problem because the allocated bin may not be its correct one. Diabetes$BMI <- ifelse(Diabetes$BMI<19,"Underweight", ifelse(Diabetes$BMI>=19 & Diabetes$BMI<=25, "Normal", ifelse(Diabetes$BMI>=25 & Diabetes$BMI<=30, "Overweight","Obese"))) %>% factor(levels=c("Underweight","Normal", "Overweight","Obese")) list(BMI = summary(Diabetes$BMI)) $BMI Underweight Normal Overweight Obese 15 108 180 465 So now I see that Underweight has 15 rows which means there were 15 rows that had a BMI less than 19 and knowing that BMI had 11 zero values, we know that most of the rows are zero. Because it is so little, I am choosing to keep it. Also, we have already removed two variables and I want to retain as much data as possible while making sure it can add value. With a 2 hour ‘Oral Glucose Tolerance Test’ (OGTT), people are considered to not have diabetes if after 2 hours of administering the test their levels are below 7.8 mmol/L. To categorize the levels of glucose tolerance, we will use the following criteria: * Hypoglycemia (Low Blood Sugar) - <2.2 mmol/L * Normal/No Diabetes - >=2.2 mmol/L - <=7.8mmol/L * Prediabetes (Hyperglycemia / High Blood Sugar) - >7.8 mmol/L - <=11.1 mmol/L * Diabetes - >11.1 mmol/L Although one of the levels says this person has diabetes, it is not a final diganosis. Other factors will have to be taken to account. To avoid misleads, ‘Diabetes’ in this circumstance REFERS TO THE TEST RESULT ANME AND NOT A FINAL DIAGNOSIS OF TYPE 2 DIABETES’ The unit of measurement for the 2-hour OGTT in this dataset is assumed to be in milligrams per deciliter (mg/dl). It can be converted to Milimoles per liter (mmol/l) so that we may apply a qualitative test result to the numeric results. Multiplying the current results by 0.0555 will convert them to be measured in mmol/l. Diabetes$Glucose <- Diabetes$Glucose*0.0555Diabetes$Glucose <- if_else(Diabetes$Glucose<2.2,"Hypoglycemia", if_else(Diabetes$Glucose>=2.2 & Diabetes$Glucose<=7.8,"Normal", if_else(Diabetes$Glucose>7.8 & Diabetes$Glucose<=11.1, "Hyperglycemia","Diabetes"))) %>% factor()list( `Test Result` = summary(Diabetes$Glucose) )$`Test Result` Hyperglycemia Hypoglycemia Normal 192 5 571 It appears that 74% of participants have Normal Glucose levels and 25% have Prediabetes/Hyperglycemia/High Blood Sugar.Only 1% have Hypoglycemia/Low Blood Sugar. My main concern with Hypoglycemia is that when I take it through a machine learning process, the level may not be present during k-fold cross validation. I cannot say for sure at this point but it is worth noting and keeping in mind for the future. When measuring Blood Pressure, two measures are used: * Systolic - Measures the pressure in blood vessels when the heart beats. * Diastolic - Measures the pressure in blood vessels when the heart rests between beats. In this dataset, only the diastolic blood Pressure is reported. This requires us to proceed with caution. As reported by the Centers for Disease Control and Prevention, blood pressure is measured using systolic and diastolic units. When they are reported we can make the following inferences: Normal Systolic <120mmHg, Diastolic <80mmHg Prehypertension Systolic >=120mmHg — <=139mmHg Diastolic >=80 — <=89mmHg High Systolic: >=140mmHg Diastolic: >=90mmHg BECAUSE SYSTOLIC PRESSURE IS NOT REPORTED, I DO NOT FEEL COMFORTABLE IN PROCEEDING WITH THIS VARIABALE. THIS IS A SUBJECTIVE DECISION OF MINE. Diabetes$BloodPressure <- NULL ggplot(Diabetes, aes(y=Age, x=Outcome)) + geom_boxplot() + geom_jitter()+ theme_bw() + xlab("Outcome") + ylab("Age") + stat_summary(fun.y=mode, colour="Orange", geom="point", shape=16, size=5) + stat_summary(fun.y=mean, colour="purple", geom="point", shape=16, size=5) + ggtitle(label="Age by Outcome", subtitle = "Orange=Most Frequent\nPurple=Average Age") + theme(axis.text.x = element_text(face="bold",size=12), axis.text.y = element_text(face="bold",size=12), title = element_text(face="bold",size=12), axis.title = element_text(face="bold",size=12)) + scale_y_continuous(breaks=seq(20,80,4)) It seems there is a lot of noise in this variable. There is no clear distinction in age with regards to having diabetes. ggplot(Diabetes, aes(y=DiabetesPedigreeFunction, x=Outcome)) + geom_boxplot() + geom_jitter()+ theme_bw() + xlab("Outcome") + ylab("DiabetesPedigreeFunction") + stat_summary(fun.y=mode, colour="orange", geom="point", shape=16, size=5) + stat_summary(fun.y=mean, colour="purple", geom="point", shape=16, size=5) + ggtitle(label="Diabetes Pedigree Function by Outcome", subtitle = "Orange=Most Frequent\nPurple=Average Age") + theme(axis.text.x = element_text(face="bold",size=12), axis.text.y = element_text(face="bold",size=12), title = element_text(face="bold",size=12), axis.title = element_text(face="bold",size=12)) + scale_y_continuous(breaks=seq(0,3,0.5)) Interestingly, the Diabetes Pedigree Function does not seem to give a clear picture of a diabetic outcome. This is supposed to be a score wherein the higher the score, the more likely you are to have diabetes. This is also a variable with a lot of noise. (pregnant <- table(Diabetes$Pregnancies, Diabetes$Outcome, dnn = c("Pregnant", "Outcome")) ) Outcome Pregnant Positive Negative No 38 73Yes 230 427pregnant %>% prop.table(2) %>% round(2) %>% kable(format = 'html') Positive Negative No 0.14 0.15 Yes 0.86 0.85 It seems that having a pregnancy does not necessarily increase your chances of having diabetes as the same proportion of women who had or didn’t have diabetes had at least one pregnancy. (bmi <- table(Diabetes$BMI, Diabetes$Outcome, dnn = c("BMI", "Outcome")) ) Outcome BMI Positive Negative Underweight 2 13 Normal 7 101 Overweight 44 136 Obese 215 250bmi %>% prop.table(2)%>% round(2) %>% kable(format = 'html') Positive Negative Underweight 0.01 0.03 Normal 0.03 0.20 Overweight 0.16 0.27 Obese 0.80 0.50 Unsurprisingly, 80% of Diabetic women were obese while 16% were overweight. Only 3% were reported to be of normal weight. Among the women that do not have diabetes, 50% were obese, 27% overweight and 20% normal. (glucose <- table(Diabetes$Glucose, Diabetes$Outcome, dnn = c("Glucose Level", "Outcome")) ) Outcome Glucose Level Positive Negative Hyperglycemia 132 60 Hypoglycemia 2 3 Normal 134 437glucose %>% prop.table(2) %>% round(2) %>% kable(format = 'html') Positive Negative Hyperglycemia 0.49 0.12 Hypoglycemia 0.01 0.01 Normal 0.50 0.87 49% of women who have diabetes were positive for Hyperglycemia and 50% had normal glucose levels. Surprisingly, the glucose levels do not seem to clearly differentiate between those who are diabetic. Obviously, people with Hyperglycemia are more likely to have diabetes but the magnitude is very low according to the above table. Unsurprisingly, 87% of women without diabetes had normal glucose levels. summary(Diabetes)Pregnancies No :111 Yes:657Glucose Hyperglycemia:192 Hypoglycemia : 5 Normal :571BMI Underweight: 15 Normal :108 Overweight :180 Obese :465 DiabetesPedigreeFunction Min. :0.0780 1st Qu.:0.2437 Median :0.3725 Mean :0.4719 3rd Qu.:0.6262 Max. :2.4200Age Min. :21.00 1st Qu.:24.00 Median :29.00 Mean :33.24 3rd Qu.:41.00 Max. :81.00Outcome Positive:268 Negative:500 In my following post, I use this dataset to create a Decision Tree Classifier. If you have any questions or concerns please comment for a discussion and I invite anyone who finds this interesting to join. Thank you The original post can be found here in my blog: Easy Data Science with R and Python
[ { "code": null, "e": 552, "s": 171, "text": "The data used in the current project contains a number of diagnostic measures of type 2 diabetes in women of the Pima Indian heritage, and whether or not the individual has type 2 diabetes. The dataset was obtained from Kaggle at (https://www.kaggle.com/uciml/pima-indians-diabetes-database). There is a total of 768 observations and 9 variables. The variables in the dataset are:" }, { "code": null, "e": 564, "s": 552, "text": "Pregnancies" }, { "code": null, "e": 657, "s": 564, "text": "Glucose — The blood plasma glucose concentration after a 2 hour oral glucose tolerance test." }, { "code": null, "e": 707, "s": 657, "text": "BloodPressure — Diastolic blood pressure (mm/HG)." }, { "code": null, "e": 763, "s": 707, "text": "SkinThickness — Skinfold thickness of the triceps (mm)." }, { "code": null, "e": 805, "s": 763, "text": "Insulin — 2 hour serum insulin (mu U/ml)." }, { "code": null, "e": 842, "s": 805, "text": "BMI — Body mass index (kg/m squared)" }, { "code": null, "e": 1014, "s": 842, "text": "DiabetesPedigreeFunction — A function that determines the risk of type 2 diabetes based on family history, the larger the function, the higher the risk of type 2 diabetes." }, { "code": null, "e": 1019, "s": 1014, "text": "Age." }, { "code": null, "e": 1101, "s": 1019, "text": "Outcome — Whether the person is diagnosed with type 2 diabetes (1 = yes, 0 = no)." }, { "code": null, "e": 1166, "s": 1101, "text": "library(readr) library(tidyverse) library(dplyr) library(knitr) " }, { "code": null, "e": 1707, "s": 1166, "text": "glimpse(Diabetes)Observations: 768 Variables: 9 $ Pregnancies <int> 6, 1, 8, 1, 0, 5, 3, 10, 2, 8, 4... $ Glucose <int> 148, 85, 183, 89, 137, 116, 78, ... $ BloodPressure <int> 72, 66, 64, 66, 40, 74, 50, 0, 7... $ SkinThickness <int> 35, 29, 0, 23, 35, 0, 32, 0, 45,... $ Insulin <int> 0, 0, 0, 94, 168, 0, 88, 0, 543,... $ BMI <dbl> 33.6, 26.6, 23.3, 28.1, 43.1, 25... $ DiabetesPedigreeFunction <dbl> 0.627, 0.351, 0.672, 0.167, 2.28... $ Age <int> 50, 31, 32, 21, 33, 30, 26, 29, ... $ Outcome <int> 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0,..." }, { "code": null, "e": 1851, "s": 1707, "text": "The outcome variable needs to be converted into a categorical variable. It will be ordered to accommodate analysis purposes in the near future." }, { "code": null, "e": 2069, "s": 1851, "text": "Diabetes$Outcome <- as.factor(unlist(Diabetes$Outcome)) Diabetes$Outcome <- factor(Diabetes$Outcome, levels=c(\"1\", \"0\"), labels = c(\"Positive\", \"Negative\")) summary(Diabetes$Outcome)Positive Negative 268 500" }, { "code": null, "e": 2275, "s": 2069, "text": "We can see that there are almost twice as many people wihtout diabetes than there are with diabetes. While there is no universal cutoff for the number of rows for your target variable, this should suffice." }, { "code": null, "e": 2389, "s": 2275, "text": "We just need to make sure that there is enough data for your model to learn how to differentiate between the two." }, { "code": null, "e": 2414, "s": 2389, "text": "The following variables:" }, { "code": null, "e": 2424, "s": 2414, "text": "* Glucose" }, { "code": null, "e": 2440, "s": 2424, "text": "* BloodPressure" }, { "code": null, "e": 2456, "s": 2440, "text": "* SkinThickness" }, { "code": null, "e": 2466, "s": 2456, "text": "* Insulin" }, { "code": null, "e": 2472, "s": 2466, "text": "* BMI" }, { "code": null, "e": 2717, "s": 2472, "text": "need to be converted into numeric variables from its current integer class. These variables have decimal values and its absence could potentially create misleading results and distort specified ranges of risk represented by those medical tests." }, { "code": null, "e": 3019, "s": 2717, "text": "Diabetes$Glucose <- as.numeric(Diabetes$Glucose) Diabetes$BloodPressure <- as.numeric(Diabetes$BloodPressure) Diabetes$SkinThickness <- as.numeric(Diabetes$SkinThickness) Diabetes$Insulin <- as.numeric(Diabetes$Insulin) Diabetes$BMI <- as.numeric(Diabetes$BMI) Diabetes$Age <- as.integer(Diabetes$Age)" }, { "code": null, "e": 3254, "s": 3019, "text": "6/9 variables in the dataset have a number of zero markers. It appears that after taking the sum of each column and row separately, there are 763 zero values in the dataset. Alarmingly, this represents almost 100% of our observations." }, { "code": null, "e": 3474, "s": 3254, "text": "list( Column = colSums(Diabetes==0), Row = sum(rowSums(Diabetes==0)) )$Column Pregnancies 111Glucose 5 BloodPressure 35 SkinThickness 227 Insulin 374 BMI 11 DiabetesPedigreeFunction 0Age 0 Outcome 0 $Row [1] 763" }, { "code": null, "e": 3634, "s": 3474, "text": "A value of ‘0’ does not necessarily mean it is a missing value. For example: A woman has a zero record of pregnancies because that woman has not been pregnant." }, { "code": null, "e": 4087, "s": 3634, "text": "This is one example on how careful you have to be when preprocessing your data for missing values. Zero does not mean it is missing. However in addition to that point, zero values could create problems when passing it to a machine learning model. Techniques like Regression can give you an estimate of the output when the variable is zero. Another method of dealing with zeros could be to bin the variable which will then create a categorical variable." }, { "code": null, "e": 4169, "s": 4087, "text": "Diabetes$Pregnancies <- ifelse(Diabetes$Pregnancies==0, \"No\", \"Yes\") %>% factor()" }, { "code": null, "e": 4199, "s": 4169, "text": "summary(Diabetes$Pregnancies)" }, { "code": null, "e": 4214, "s": 4199, "text": "No Yes 111 657" }, { "code": null, "e": 4885, "s": 4214, "text": "50% of the rows in Insulin have 0 values. Lets look at it in a practical sense. There are times when the body produces little to no insulin which is a sign on Type 1 Diabetes. But I doubt this is the case in this instance. Insulin is such an important variable concerning Diabetes, but when a variable is just rife with missing values you have to do something about it. You can just impute the values, but this is medical data and half of the values are missing. It would not be appropriate to just impute the rows with it mean in my opinion. That’s why no matter how important it is, it has to be REMOVED. This is one of those times where you need to make a tough call." }, { "code": null, "e": 4911, "s": 4885, "text": "Diabetes$Insulin <- NULL " }, { "code": null, "e": 5136, "s": 4911, "text": "The same can be said for SkinThickness. 31% of its rows have 0 as a value. Practically how can a human have 0mm skinfold thickness. This variable is also not giving us much use. Therefore I will remove this variable as well." }, { "code": null, "e": 5168, "s": 5136, "text": "Diabetes$SkinThickness <- NULL " }, { "code": null, "e": 5448, "s": 5168, "text": "BMI can be supplemented with its respective range of obesity criteria. BMI only has 11 0 values so it would not be expected to cause too much trouble. If it was substantially higher, binning would not really solve the problem because the allocated bin may not be its correct one." }, { "code": null, "e": 5691, "s": 5448, "text": "Diabetes$BMI <- ifelse(Diabetes$BMI<19,\"Underweight\", ifelse(Diabetes$BMI>=19 & Diabetes$BMI<=25, \"Normal\", ifelse(Diabetes$BMI>=25 & Diabetes$BMI<=30, \"Overweight\",\"Obese\"))) %>% factor(levels=c(\"Underweight\",\"Normal\", \"Overweight\",\"Obese\"))" }, { "code": null, "e": 5725, "s": 5691, "text": "list(BMI = summary(Diabetes$BMI))" }, { "code": null, "e": 5782, "s": 5725, "text": "$BMI Underweight Normal Overweight Obese 15 108 180 465" }, { "code": null, "e": 6141, "s": 5782, "text": "So now I see that Underweight has 15 rows which means there were 15 rows that had a BMI less than 19 and knowing that BMI had 11 zero values, we know that most of the rows are zero. Because it is so little, I am choosing to keep it. Also, we have already removed two variables and I want to retain as much data as possible while making sure it can add value." }, { "code": null, "e": 6397, "s": 6141, "text": "With a 2 hour ‘Oral Glucose Tolerance Test’ (OGTT), people are considered to not have diabetes if after 2 hours of administering the test their levels are below 7.8 mmol/L. To categorize the levels of glucose tolerance, we will use the following criteria:" }, { "code": null, "e": 6599, "s": 6397, "text": "* Hypoglycemia (Low Blood Sugar) - <2.2 mmol/L * Normal/No Diabetes - >=2.2 mmol/L - <=7.8mmol/L * Prediabetes (Hyperglycemia / High Blood Sugar) - >7.8 mmol/L - <=11.1 mmol/L * Diabetes - >11.1 mmol/L" }, { "code": null, "e": 6862, "s": 6599, "text": "Although one of the levels says this person has diabetes, it is not a final diganosis. Other factors will have to be taken to account. To avoid misleads, ‘Diabetes’ in this circumstance REFERS TO THE TEST RESULT ANME AND NOT A FINAL DIAGNOSIS OF TYPE 2 DIABETES’" }, { "code": null, "e": 7185, "s": 6862, "text": "The unit of measurement for the 2-hour OGTT in this dataset is assumed to be in milligrams per deciliter (mg/dl). It can be converted to Milimoles per liter (mmol/l) so that we may apply a qualitative test result to the numeric results. Multiplying the current results by 0.0555 will convert them to be measured in mmol/l." }, { "code": null, "e": 7584, "s": 7185, "text": "Diabetes$Glucose <- Diabetes$Glucose*0.0555Diabetes$Glucose <- if_else(Diabetes$Glucose<2.2,\"Hypoglycemia\", if_else(Diabetes$Glucose>=2.2 & Diabetes$Glucose<=7.8,\"Normal\", if_else(Diabetes$Glucose>7.8 & Diabetes$Glucose<=11.1, \"Hyperglycemia\",\"Diabetes\"))) %>% factor()list( `Test Result` = summary(Diabetes$Glucose) )$`Test Result` Hyperglycemia Hypoglycemia Normal 192 5 571" }, { "code": null, "e": 7746, "s": 7584, "text": "It appears that 74% of participants have Normal Glucose levels and 25% have Prediabetes/Hyperglycemia/High Blood Sugar.Only 1% have Hypoglycemia/Low Blood Sugar." }, { "code": null, "e": 7995, "s": 7746, "text": "My main concern with Hypoglycemia is that when I take it through a machine learning process, the level may not be present during k-fold cross validation. I cannot say for sure at this point but it is worth noting and keeping in mind for the future." }, { "code": null, "e": 8049, "s": 7995, "text": "When measuring Blood Pressure, two measures are used:" }, { "code": null, "e": 8212, "s": 8049, "text": "* Systolic - Measures the pressure in blood vessels when the heart beats. * Diastolic - Measures the pressure in blood vessels when the heart rests between beats." }, { "code": null, "e": 8318, "s": 8212, "text": "In this dataset, only the diastolic blood Pressure is reported. This requires us to proceed with caution." }, { "code": null, "e": 8505, "s": 8318, "text": "As reported by the Centers for Disease Control and Prevention, blood pressure is measured using systolic and diastolic units. When they are reported we can make the following inferences:" }, { "code": null, "e": 8512, "s": 8505, "text": "Normal" }, { "code": null, "e": 8531, "s": 8512, "text": "Systolic <120mmHg," }, { "code": null, "e": 8549, "s": 8531, "text": "Diastolic <80mmHg" }, { "code": null, "e": 8565, "s": 8549, "text": "Prehypertension" }, { "code": null, "e": 8596, "s": 8565, "text": "Systolic >=120mmHg — <=139mmHg" }, { "code": null, "e": 8622, "s": 8596, "text": "Diastolic >=80 — <=89mmHg" }, { "code": null, "e": 8627, "s": 8622, "text": "High" }, { "code": null, "e": 8647, "s": 8627, "text": "Systolic: >=140mmHg" }, { "code": null, "e": 8667, "s": 8647, "text": "Diastolic: >=90mmHg" }, { "code": null, "e": 8810, "s": 8667, "text": "BECAUSE SYSTOLIC PRESSURE IS NOT REPORTED, I DO NOT FEEL COMFORTABLE IN PROCEEDING WITH THIS VARIABALE. THIS IS A SUBJECTIVE DECISION OF MINE." }, { "code": null, "e": 8841, "s": 8810, "text": "Diabetes$BloodPressure <- NULL" }, { "code": null, "e": 9444, "s": 8841, "text": "ggplot(Diabetes, aes(y=Age, x=Outcome)) + geom_boxplot() + geom_jitter()+ theme_bw() + xlab(\"Outcome\") + ylab(\"Age\") + stat_summary(fun.y=mode, colour=\"Orange\", geom=\"point\", shape=16, size=5) + stat_summary(fun.y=mean, colour=\"purple\", geom=\"point\", shape=16, size=5) + ggtitle(label=\"Age by Outcome\", subtitle = \"Orange=Most Frequent\\nPurple=Average Age\") + theme(axis.text.x = element_text(face=\"bold\",size=12), axis.text.y = element_text(face=\"bold\",size=12), title = element_text(face=\"bold\",size=12), axis.title = element_text(face=\"bold\",size=12)) + scale_y_continuous(breaks=seq(20,80,4))" }, { "code": null, "e": 9565, "s": 9444, "text": "It seems there is a lot of noise in this variable. There is no clear distinction in age with regards to having diabetes." }, { "code": null, "e": 10227, "s": 9565, "text": "ggplot(Diabetes, aes(y=DiabetesPedigreeFunction, x=Outcome)) + geom_boxplot() + geom_jitter()+ theme_bw() + xlab(\"Outcome\") + ylab(\"DiabetesPedigreeFunction\") + stat_summary(fun.y=mode, colour=\"orange\", geom=\"point\", shape=16, size=5) + stat_summary(fun.y=mean, colour=\"purple\", geom=\"point\", shape=16, size=5) + ggtitle(label=\"Diabetes Pedigree Function by Outcome\", subtitle = \"Orange=Most Frequent\\nPurple=Average Age\") + theme(axis.text.x = element_text(face=\"bold\",size=12), axis.text.y = element_text(face=\"bold\",size=12), title = element_text(face=\"bold\",size=12), axis.title = element_text(face=\"bold\",size=12)) + scale_y_continuous(breaks=seq(0,3,0.5))" }, { "code": null, "e": 10482, "s": 10227, "text": "Interestingly, the Diabetes Pedigree Function does not seem to give a clear picture of a diabetic outcome. This is supposed to be a score wherein the higher the score, the more likely you are to have diabetes. This is also a variable with a lot of noise." }, { "code": null, "e": 10803, "s": 10482, "text": "(pregnant <- table(Diabetes$Pregnancies, Diabetes$Outcome, dnn = c(\"Pregnant\", \"Outcome\")) ) Outcome Pregnant Positive Negative No 38 73Yes 230 427pregnant %>% prop.table(2) %>% round(2) %>% kable(format = 'html') Positive Negative No 0.14 0.15 Yes 0.86 0.85" }, { "code": null, "e": 10990, "s": 10803, "text": "It seems that having a pregnancy does not necessarily increase your chances of having diabetes as the same proportion of women who had or didn’t have diabetes had at least one pregnancy." }, { "code": null, "e": 11458, "s": 10990, "text": "(bmi <- table(Diabetes$BMI, Diabetes$Outcome, dnn = c(\"BMI\", \"Outcome\")) ) Outcome BMI Positive Negative Underweight 2 13 Normal 7 101 Overweight 44 136 Obese 215 250bmi %>% prop.table(2)%>% round(2) %>% kable(format = 'html') Positive Negative Underweight 0.01 0.03 Normal 0.03 0.20 Overweight 0.16 0.27 Obese 0.80 0.50" }, { "code": null, "e": 11670, "s": 11458, "text": "Unsurprisingly, 80% of Diabetic women were obese while 16% were overweight. Only 3% were reported to be of normal weight. Among the women that do not have diabetes, 50% were obese, 27% overweight and 20% normal." }, { "code": null, "e": 12118, "s": 11670, "text": "(glucose <- table(Diabetes$Glucose, Diabetes$Outcome, dnn = c(\"Glucose Level\", \"Outcome\")) ) Outcome Glucose Level Positive Negative Hyperglycemia 132 60 Hypoglycemia 2 3 Normal 134 437glucose %>% prop.table(2) %>% round(2) %>% kable(format = 'html') Positive Negative Hyperglycemia 0.49 0.12 Hypoglycemia 0.01 0.01 Normal 0.50 0.87" }, { "code": null, "e": 12448, "s": 12118, "text": "49% of women who have diabetes were positive for Hyperglycemia and 50% had normal glucose levels. Surprisingly, the glucose levels do not seem to clearly differentiate between those who are diabetic. Obviously, people with Hyperglycemia are more likely to have diabetes but the magnitude is very low according to the above table." }, { "code": null, "e": 12521, "s": 12448, "text": "Unsurprisingly, 87% of women without diabetes had normal glucose levels." }, { "code": null, "e": 12908, "s": 12521, "text": "summary(Diabetes)Pregnancies No :111 Yes:657Glucose Hyperglycemia:192 Hypoglycemia : 5 Normal :571BMI Underweight: 15 Normal :108 Overweight :180 Obese :465 DiabetesPedigreeFunction Min. :0.0780 1st Qu.:0.2437 Median :0.3725 Mean :0.4719 3rd Qu.:0.6262 Max. :2.4200Age Min. :21.00 1st Qu.:24.00 Median :29.00 Mean :33.24 3rd Qu.:41.00 Max. :81.00Outcome Positive:268 Negative:500 " }, { "code": null, "e": 12987, "s": 12908, "text": "In my following post, I use this dataset to create a Decision Tree Classifier." }, { "code": null, "e": 13123, "s": 12987, "text": "If you have any questions or concerns please comment for a discussion and I invite anyone who finds this interesting to join. Thank you" } ]
Sentiment Analysis using Logistic Regression and Naive Bayes | by Atharva Mashalkar | Towards Data Science
In supervised machine learning, you usually have an input X, which goes into your prediction function to get your Y^. You can then compare your prediction with the true value Y. This gives you your cost which you use to update the parameters θ. Sentiment analysis (also known as opinion mining or emotion AI) refers to the use of natural language processing, text analysis, computational linguistics, and biometrics to systematically identify, extract, quantify, and study affective states and subjective information. So, let's start sentiment analysis using Logistic Regression We will be using the sample twitter data set for this exercise. Given a tweet, or some text, we can represent it as a vector of dimension V, where V corresponds to our vocabulary size. For example: If you had the tweet “I am learning sentiment analysis”, then you would put a 1 in the corresponding index for any word in the tweet, and a 0 otherwise. As we can see, as V gets larger, the vector becomes more sparse. Furthermore, we end up having many more features and end up training θ V parameters. This could result in larger training time and large prediction time. Hence, we will extract frequencies of every word and making a frequency dictionary. The idea here is to divide the training set into positive and negative tweets. Count all the words and make a python dictionary of their frequencies in positive and negative tweets. For every tweet make a vector of bias unit, sum of all the positive frequencies(words from positive tweets) of all the words and also their negative frequencies. We will go into detail regarding this in further paragraphs. When preprocessing, you have to perform the following: Eliminate handles and URLsTokenize the string into words.Remove stop words like “and, is, a, on, etc.”Stemming- or convert every word to its stem. Like a dancer, dancing, danced, becomes ‘danc’. You can use porter stemmer to take care of this.Convert all your words to lower case. Eliminate handles and URLs Tokenize the string into words. Remove stop words like “and, is, a, on, etc.” Stemming- or convert every word to its stem. Like a dancer, dancing, danced, becomes ‘danc’. You can use porter stemmer to take care of this. Convert all your words to lower case. In order to carry out the above steps follow the below-given code snippets: Import the libraries and sample twitter data set provided by nltk (Natural Language Toolkit) package, which contains 5000 positive and 5000 negative tweets. Also, let's import some additional libraries which will help us in carrying out Regular Expression in python. import reimport stringfrom nltk.corpus import stopwordsfrom nltk.stem import PorterStemmerfrom nltk.tokenize import TweetTokenizerimport numpy as np Here we remove stopwords (words which don’t and any value to the model, without these words the model will provide the same accuracy, ex: ‘the’, ‘is’, ‘are’, etc.) and carry out stemming (removing suffix of few words in order to reduce the vocabulary size). We also import English stopwords from nltk library Note: Here we are also tokenizing the string into a list of words after removing retweets, hashtags, URLs. #Preprocessing tweetsdef process_tweet(tweet): #Remove old style retweet text "RT" tweet2 = re.sub(r'^RT[\s]','', tweet) #Remove hyperlinks tweet2 = re.sub(r'https?:\/\/.*[\r\n]*','', tweet2) #Remove hastags #Only removing the hash # sign from the word tweet2 = re.sub(r'#','',tweet2) # instantiate tokenizer class tokenizer = TweetTokenizer(preserve_case=False, strip_handles=True, reduce_len=True) # tokenize tweets tweet_tokens = tokenizer.tokenize(tweet2) #Import the english stop words list from NLTK stopwords_english = stopwords.words('english') #Creating a list of words without stopwords tweets_clean = [] for word in tweet_tokens: if word not in stopwords_english and word not in string.punctuation: tweets_clean.append(word) #Instantiate stemming class stemmer = PorterStemmer() #Creating a list of stems of words in tweet tweets_stem = [] for word in tweets_clean: stem_word = stemmer.stem(word) tweets_stem.append(stem_word) return tweets_stem Now, we will create a function that will take tweets and their labels as input, go through every tweet, preprocess them, count the occurrence of every word in the data set and create a frequency dictionary. Note: The squeeze function is necessary or the list ends up with one element. #Frequency generating functiondef build_freqs(tweets, ys): yslist = np.squeeze(ys).tolist() freqs = {} for y, tweet in zip(yslist, tweets): for word in process_tweet(tweet): pair = (word, y) freqs[pair] = freqs.get(pair, 0) + 1 return freqs The required functions for processing tweets are ready, now let's build our logistic regression model. Logistic regression makes use of the sigmoid function which outputs a probability between 0 and 1. The sigmoid function with some weight parameter θ and some input x^{(i)}x(i) is defined as follows:- h(x^(i), θ) = 1/(1 + e^(-θ^T*x^(i)). The sigmoid function gives values between -1 and 1 hence we can classify the predictions depending on a particular cutoff. (say : 0.5) Note that as (θ^T)x(i) gets closer and closer to −∞ the denominator of the sigmoid function gets larger and larger and as a result, the sigmoid gets closer to 0. On the other hand, (θ^T)x(i) gets closer and closer to ∞ the denominator of the sigmoid function gets closer to 1 and as a result the sigmoid also gets closer to 1. As we have understood the sigmoid function now let's code it! Note: The function should work for a scalar as well as an array def sigmoid(z): ''' Input: z: is the input (can be a scalar or an array) Output: h: the sigmoid of z ''' # calculate the sigmoid of z h = 1/(1 + np.exp(-z)) return h The logistic regression cost function is defined as J(θ)=(−1/m)*​∑i=1 to m​[y(i)log(h(x(i),θ)+(1−y(i))log(1−h(x(i),θ))] We aim to reduce cost by improving the theta using the following equation: θj:=θj−α*∂J(θ)/θj Here, α is called the learning rate. The above process of making hypothesis (h) using the sigmoid function and changing the weights (θ) using the derivative of cost function and a specific learning rate is called the Gradient Descent Algorithm. Note: You initialize your parameter θ, that you can use in your sigmoid, you then compute the gradient that you will use to update θ, and then calculate the cost. You keep doing so until good enough. Let's code what we learned. def gradientDescent(x, y, theta, alpha, num_iters): ''' Input: x: matrix of features which is (m,n+1) y: corresponding labels of the input matrix x, dimensions (m,1) theta: weight vector of dimension (n+1,1) alpha: learning rate num_iters: number of iterations you want to train your model for Output: J: the final cost theta: your final weight vector Hint: you might want to print the cost to make sure that it is going down. ''' m = len(x) for i in range(0, num_iters): # get z, the dot product of x and theta z = np.dot(x,theta) # get the sigmoid of z h = sigmoid(z) # calculate the cost function J = (-1/m)*(np.dot(y.T,np.log(h)) + np.dot((1-y).T,np.log(1-h))) # update the weights theta theta = theta - (alpha/m)*np.dot(x.T, h-y) J = float(J) return J, theta Now, let's create a function that will extract features from a tweet using the ‘freqs’ dictionary and above defined preprocessing function (process_tweet). def extract_features(tweet, freqs): ''' Input: tweet: a list of words for one tweet freqs: a dictionary corresponding to the frequencies of each tuple (word, label) Output: x: a feature vector of dimension (1,3) ''' # process_tweet tokenizes, stems, and removes stopwords word_l = process_tweet(tweet) # 3 elements in the form of a 1 x 3 vector x = np.zeros((1, 3)) #bias term is set to 1 x[0,0] = 1 # loop through each word in the list of words for word in word_l: # increment the word count for the positive label 1 x[0,1] += freqs.get((word,1),0) # increment the word count for the negative label 0 x[0,2] += freqs.get((word,0),0) assert(x.shape == (1, 3)) return x Now, we will import the data set from nltk and break it into a training set and test set # split the data into two pieces, one for training and one for testing (validation set) test_pos = all_positive_tweets[4000:]train_pos = all_positive_tweets[:4000]test_neg = all_negative_tweets[4000:]train_neg = all_negative_tweets[:4000]train_x = train_pos + train_neg test_x = test_pos + test_neg# combine positive and negative labelstrain_y = np.append(np.ones((len(train_pos), 1)), np.zeros((len(train_neg), 1)), axis=0)test_y = np.append(np.ones((len(test_pos), 1)), np.zeros((len(test_neg), 1)), axis=0) As all the required functions are ready we can finally train our model using the training data set and test it on the test data set # collect the features 'x' and stack them into a matrix 'X'X = np.zeros((len(train_x), 3))for i in range(len(train_x)): X[i, :]= extract_features(train_x[i], freqs)# training labels corresponding to XY = train_y# Apply gradient descentJ, theta = gradientDescent(X, Y, np.zeros((3, 1)), 1e-9, 1500)print(f"The cost after training is {J:.8f}.")print(f"The resulting vector of weights is {[round(t, 8) for t in np.squeeze(theta)]}") J is the final cost and “theta” are the final weights after training the model. In order to check it before testing on the test data set. # Check your function# test 1# test on training datatmp1 = extract_features(train_x[0], freqs)print(tmp1)# #### Expected output# ```# [[1.00e+00 3.02e+03 6.10e+01]] Lets, write two more functions which given a tweet will predict the result using the ‘freqs’ dictionary and theta. The second function will use the predict function and provide the accuracy of the model on the given testing data set. def predict_tweet(tweet, freqs, theta): ''' Input: tweet: a string freqs: a dictionary corresponding to the frequencies of each tuple (word, label) theta: (3,1) vector of weights Output: y_pred: the probability of a tweet being positive or negative ''' # extract the features of the tweet and store it into x x = extract_features(tweet, freqs) # make the prediction using x and theta z = np.dot(x,theta) y_pred = sigmoid(z) return y_preddef test_logistic_regression(test_x, test_y, freqs, theta): """ Input: test_x: a list of tweets test_y: (m, 1) vector with the corresponding labels for the list of tweets freqs: a dictionary with the frequency of each pair (or tuple) theta: weight vector of dimension (3, 1) Output: accuracy: (# of tweets classified correctly) / (total # of tweets) """ # the list for storing predictions y_hat = [] for tweet in test_x: # get the label prediction for the tweet y_pred = predict_tweet(tweet, freqs, theta) if y_pred > 0.5: # append 1.0 to the list y_hat.append(1) else: # append 0 to the list y_hat.append(0)# With the above implementation, y_hat is a list, but test_y is (m,1) array # convert both to one-dimensional arrays in order to compare them using the '==' operator y_hat = np.array(y_hat) test_y = test_y.reshape(-1) accuracy = np.sum((test_y == y_hat).astype(int))/len(test_x) return accuracy On testing the model using the test data set we get an accuracy of 99.5% Naive Bayes algorithm is based on the Bayes rule, which can be represented as follows: P(X∣Y)=P(Y)P(Y∣X)P(X)​ Here, the process up to creating a dictionary of frequencies (importing libraries, preprocessing, etc.) is the same. The way the algorithm works is as follows:- Find the log of the ratio of the number of positive tweets and negative sentiment tweets. i.e. Find the log of the ratio of the number of positive tweets and negative sentiment tweets. i.e. logprior :- log(P(Dpos))−log(P(Dneg))=log(Dpos)−log(Dneg) 2. Instead of keeping the frequencies of each word with the positive and negative labels we take the ratio of their frequency in that label by the total number of frequencies in that label. This will give the probability of occurrence of that word given the tweet is positive/negative. 3. Then we make another property called loglikelihood. It is the log of the ratio of Positive probability to that of the negative probability of a particular word. But what if the probability of the word is zero ( frequency is zero in either positive or negative case) the log may become +/- infinity. Hence to overcome this we use additive smoothing. This wiki article explains more about additive smoothing. Therefore, to compute the positive probability and the negative probability for a specific word in the vocabulary, we’ll use the following inputs: freqpos and freqneg are the frequencies of that specific word in the positive or negative class. In other words, the positive frequency of a word is the number of times the word is counted with the label of 1. Npos and Nneg are the total numbers of positive and negative words for all documents (for all tweets), respectively. V is the number of unique words in the entire set of documents, for all classes, whether positive or negative. We’ll use these to compute the positive and negative probability for a specific word using this formula: P(Wpos)= (freqpos+1)/(Npos+V) P(Wneg)= (freqneg+1)/(Nneg+V) Notice that we add the “+1” in the numerator for additive smoothing. And the loglikelihood can be represented as:- loglikelihood=log(P(Wpos)/P(Wneg)) That's it! We just need to code the above written in order to train our Naive Bayes function. So, first, let's write a function that does all the above work. def train_naive_bayes(freqs, train_x, train_y): ''' Input: freqs: dictionary from (word, label) to how often the word appears train_x: a list of tweets train_y: a list of labels correponding to the tweets (0,1) Output: logprior: the log prior. (equation 3 above) loglikelihood: the log likelihood of you Naive bayes equation. (equation 6 above) ''' loglikelihood = {} logprior = 0 # calculate V, the number of unique words in the vocabulary vocab = set([pair[0] for pair in freqs.keys()]) V = len(vocab) # calculate N_pos and N_neg N_pos = N_neg = 0 for pair in freqs.keys(): # if the label is positive (greater than zero) if pair[1] > 0: # Increment the number of positive words by the count for this (word, label) pair N_pos += freqs.get(pair, 1) # else, the label is negative else: # increment the number of negative words by the count for this (word,label) pair N_neg += freqs.get(pair, 1) # Calculate D, the number of documents D = len(train_y) # Calculate D_pos, the number of positive documents (*hint: use sum(<np_array>)) D_pos = sum(train_y) # Calculate D_neg, the number of negative documents (*hint: compute using D and D_pos) D_neg = D-D_pos # Calculate logprior logprior = np.log(D_pos) - np.log(D_neg) # For each word in the vocabulary... for word in vocab: # get the positive and negative frequency of the word freq_pos = freqs.get((word, 1),0) freq_neg = freqs.get((word, 0),0) # calculate the probability that each word is positive, and negative p_w_pos = (freq_pos + 1)/(N_pos + V) p_w_neg = (freq_neg + 1)/(N_neg + V) # calculate the log likelihood of the word loglikelihood[word] = np.log(p_w_pos/p_w_neg) return logprior, loglikelihoodlogprior, loglikelihood = train_naive_bayes(freqs, train_x, train_y) In order to predict the sentiment of a tweet we simply have to sum up the loglikelihood of the words in the tweet along with the logprior. If the value is positive then the tweet shows positive sentiment but if the value is negative then the tweet shows negative sentiment. So let's write the predicting ( takes in a tweet, loglikelihood, and logprior and returns the prediction) and a testing function ( to test the model using the test data set). def naive_bayes_predict(tweet, logprior, loglikelihood): ''' Input: tweet: a string logprior: a number loglikelihood: a dictionary of words mapping to numbers Output: p: the sum of all the logliklihoods of each word in the tweet (if found in the dictionary) + logprior (a number)''' # process the tweet to get a list of words word_l = process_tweet(tweet)# initialize probability to zero p = 0# add the logprior p += logpriorfor word in word_l:# check if the word exists in the loglikelihood dictionary if word in loglikelihood: # add the log likelihood of that word to the probability p += loglikelihood[word]return pdef test_naive_bayes(test_x, test_y, logprior, loglikelihood): """ Input: test_x: A list of tweets test_y: the corresponding labels for the list of tweets logprior: the logprior loglikelihood: a dictionary with the loglikelihoods for each word Output: accuracy: (# of tweets classified correctly)/(total # of tweets) """ accuracy = 0 # return this properlyy_hats = [] for tweet in test_x: # if the prediction is > 0 if naive_bayes_predict(tweet, logprior, loglikelihood) > 0: # the predicted class is 1 y_hat_i = 1 else: # otherwise the predicted class is 0 y_hat_i = 0# append the predicted class to the list y_hats y_hats.append(y_hat_i) # error is the average of the absolute values of the differences between y_hats and test_y error = np.mean(np.absolute(y_hats - test_y))# Accuracy is 1 minus the error accuracy = 1 - errorreturn accuracy On testing the model on the test data set we get an accuracy of 99.4%. which is slightly less may be due to the assumptions that the Naive Bayes algorithm makes. In fact, it called “Naive” due to its assumptions. The assumptions are as follows:- Independence assumption Independence assumption In the first image, you can see the word sunny and hot tend to depend on each other and are correlated to a certain extent with the word “desert”. Naive Bayes assumes independence throughout. Furthermore, if you were to fill in the sentence on the right, this naive model will assign equal weight to the words “spring, summer, fall, winter”. 2. Relative frequencies On Twitter, there are usually more positive tweets than negative ones. However, some “clean” datasets you may find are artificially balanced to have the same amount of positive and negative tweets. Just keep in mind, that in the real world, the data could be much noisier. From the above results, we can see that the Logistic Regression algorithm has performed relatively well as compared to the Naive Bayes algorithm. This can be due to the fact that the Logistic Regression algorithm doesn’t make as many assumptions as that of the Naive Bayes algorithm.
[ { "code": null, "e": 417, "s": 172, "text": "In supervised machine learning, you usually have an input X, which goes into your prediction function to get your Y^. You can then compare your prediction with the true value Y. This gives you your cost which you use to update the parameters θ." }, { "code": null, "e": 690, "s": 417, "text": "Sentiment analysis (also known as opinion mining or emotion AI) refers to the use of natural language processing, text analysis, computational linguistics, and biometrics to systematically identify, extract, quantify, and study affective states and subjective information." }, { "code": null, "e": 751, "s": 690, "text": "So, let's start sentiment analysis using Logistic Regression" }, { "code": null, "e": 815, "s": 751, "text": "We will be using the sample twitter data set for this exercise." }, { "code": null, "e": 1405, "s": 815, "text": "Given a tweet, or some text, we can represent it as a vector of dimension V, where V corresponds to our vocabulary size. For example: If you had the tweet “I am learning sentiment analysis”, then you would put a 1 in the corresponding index for any word in the tweet, and a 0 otherwise. As we can see, as V gets larger, the vector becomes more sparse. Furthermore, we end up having many more features and end up training θ V parameters. This could result in larger training time and large prediction time. Hence, we will extract frequencies of every word and making a frequency dictionary." }, { "code": null, "e": 1587, "s": 1405, "text": "The idea here is to divide the training set into positive and negative tweets. Count all the words and make a python dictionary of their frequencies in positive and negative tweets." }, { "code": null, "e": 1810, "s": 1587, "text": "For every tweet make a vector of bias unit, sum of all the positive frequencies(words from positive tweets) of all the words and also their negative frequencies. We will go into detail regarding this in further paragraphs." }, { "code": null, "e": 1865, "s": 1810, "text": "When preprocessing, you have to perform the following:" }, { "code": null, "e": 2146, "s": 1865, "text": "Eliminate handles and URLsTokenize the string into words.Remove stop words like “and, is, a, on, etc.”Stemming- or convert every word to its stem. Like a dancer, dancing, danced, becomes ‘danc’. You can use porter stemmer to take care of this.Convert all your words to lower case." }, { "code": null, "e": 2173, "s": 2146, "text": "Eliminate handles and URLs" }, { "code": null, "e": 2205, "s": 2173, "text": "Tokenize the string into words." }, { "code": null, "e": 2251, "s": 2205, "text": "Remove stop words like “and, is, a, on, etc.”" }, { "code": null, "e": 2393, "s": 2251, "text": "Stemming- or convert every word to its stem. Like a dancer, dancing, danced, becomes ‘danc’. You can use porter stemmer to take care of this." }, { "code": null, "e": 2431, "s": 2393, "text": "Convert all your words to lower case." }, { "code": null, "e": 2507, "s": 2431, "text": "In order to carry out the above steps follow the below-given code snippets:" }, { "code": null, "e": 2774, "s": 2507, "text": "Import the libraries and sample twitter data set provided by nltk (Natural Language Toolkit) package, which contains 5000 positive and 5000 negative tweets. Also, let's import some additional libraries which will help us in carrying out Regular Expression in python." }, { "code": null, "e": 2923, "s": 2774, "text": "import reimport stringfrom nltk.corpus import stopwordsfrom nltk.stem import PorterStemmerfrom nltk.tokenize import TweetTokenizerimport numpy as np" }, { "code": null, "e": 3232, "s": 2923, "text": "Here we remove stopwords (words which don’t and any value to the model, without these words the model will provide the same accuracy, ex: ‘the’, ‘is’, ‘are’, etc.) and carry out stemming (removing suffix of few words in order to reduce the vocabulary size). We also import English stopwords from nltk library" }, { "code": null, "e": 3339, "s": 3232, "text": "Note: Here we are also tokenizing the string into a list of words after removing retweets, hashtags, URLs." }, { "code": null, "e": 4454, "s": 3339, "text": "#Preprocessing tweetsdef process_tweet(tweet): #Remove old style retweet text \"RT\" tweet2 = re.sub(r'^RT[\\s]','', tweet) #Remove hyperlinks tweet2 = re.sub(r'https?:\\/\\/.*[\\r\\n]*','', tweet2) #Remove hastags #Only removing the hash # sign from the word tweet2 = re.sub(r'#','',tweet2) # instantiate tokenizer class tokenizer = TweetTokenizer(preserve_case=False, strip_handles=True, reduce_len=True) # tokenize tweets tweet_tokens = tokenizer.tokenize(tweet2) #Import the english stop words list from NLTK stopwords_english = stopwords.words('english') #Creating a list of words without stopwords tweets_clean = [] for word in tweet_tokens: if word not in stopwords_english and word not in string.punctuation: tweets_clean.append(word) #Instantiate stemming class stemmer = PorterStemmer() #Creating a list of stems of words in tweet tweets_stem = [] for word in tweets_clean: stem_word = stemmer.stem(word) tweets_stem.append(stem_word) return tweets_stem" }, { "code": null, "e": 4661, "s": 4454, "text": "Now, we will create a function that will take tweets and their labels as input, go through every tweet, preprocess them, count the occurrence of every word in the data set and create a frequency dictionary." }, { "code": null, "e": 4739, "s": 4661, "text": "Note: The squeeze function is necessary or the list ends up with one element." }, { "code": null, "e": 5037, "s": 4739, "text": "#Frequency generating functiondef build_freqs(tweets, ys): yslist = np.squeeze(ys).tolist() freqs = {} for y, tweet in zip(yslist, tweets): for word in process_tweet(tweet): pair = (word, y) freqs[pair] = freqs.get(pair, 0) + 1 return freqs" }, { "code": null, "e": 5140, "s": 5037, "text": "The required functions for processing tweets are ready, now let's build our logistic regression model." }, { "code": null, "e": 5340, "s": 5140, "text": "Logistic regression makes use of the sigmoid function which outputs a probability between 0 and 1. The sigmoid function with some weight parameter θ and some input x^{(i)}x(i) is defined as follows:-" }, { "code": null, "e": 5377, "s": 5340, "text": "h(x^(i), θ) = 1/(1 + e^(-θ^T*x^(i))." }, { "code": null, "e": 5512, "s": 5377, "text": "The sigmoid function gives values between -1 and 1 hence we can classify the predictions depending on a particular cutoff. (say : 0.5)" }, { "code": null, "e": 5839, "s": 5512, "text": "Note that as (θ^T)x(i) gets closer and closer to −∞ the denominator of the sigmoid function gets larger and larger and as a result, the sigmoid gets closer to 0. On the other hand, (θ^T)x(i) gets closer and closer to ∞ the denominator of the sigmoid function gets closer to 1 and as a result the sigmoid also gets closer to 1." }, { "code": null, "e": 5901, "s": 5839, "text": "As we have understood the sigmoid function now let's code it!" }, { "code": null, "e": 5965, "s": 5901, "text": "Note: The function should work for a scalar as well as an array" }, { "code": null, "e": 6171, "s": 5965, "text": "def sigmoid(z): ''' Input: z: is the input (can be a scalar or an array) Output: h: the sigmoid of z ''' # calculate the sigmoid of z h = 1/(1 + np.exp(-z)) return h" }, { "code": null, "e": 6223, "s": 6171, "text": "The logistic regression cost function is defined as" }, { "code": null, "e": 6291, "s": 6223, "text": "J(θ)=(−1/m)*​∑i=1 to m​[y(i)log(h(x(i),θ)+(1−y(i))log(1−h(x(i),θ))]" }, { "code": null, "e": 6366, "s": 6291, "text": "We aim to reduce cost by improving the theta using the following equation:" }, { "code": null, "e": 6384, "s": 6366, "text": "θj:=θj−α*∂J(θ)/θj" }, { "code": null, "e": 6629, "s": 6384, "text": "Here, α is called the learning rate. The above process of making hypothesis (h) using the sigmoid function and changing the weights (θ) using the derivative of cost function and a specific learning rate is called the Gradient Descent Algorithm." }, { "code": null, "e": 6829, "s": 6629, "text": "Note: You initialize your parameter θ, that you can use in your sigmoid, you then compute the gradient that you will use to update θ, and then calculate the cost. You keep doing so until good enough." }, { "code": null, "e": 6857, "s": 6829, "text": "Let's code what we learned." }, { "code": null, "e": 7799, "s": 6857, "text": "def gradientDescent(x, y, theta, alpha, num_iters): ''' Input: x: matrix of features which is (m,n+1) y: corresponding labels of the input matrix x, dimensions (m,1) theta: weight vector of dimension (n+1,1) alpha: learning rate num_iters: number of iterations you want to train your model for Output: J: the final cost theta: your final weight vector Hint: you might want to print the cost to make sure that it is going down. ''' m = len(x) for i in range(0, num_iters): # get z, the dot product of x and theta z = np.dot(x,theta) # get the sigmoid of z h = sigmoid(z) # calculate the cost function J = (-1/m)*(np.dot(y.T,np.log(h)) + np.dot((1-y).T,np.log(1-h))) # update the weights theta theta = theta - (alpha/m)*np.dot(x.T, h-y) J = float(J) return J, theta" }, { "code": null, "e": 7955, "s": 7799, "text": "Now, let's create a function that will extract features from a tweet using the ‘freqs’ dictionary and above defined preprocessing function (process_tweet)." }, { "code": null, "e": 8759, "s": 7955, "text": "def extract_features(tweet, freqs): ''' Input: tweet: a list of words for one tweet freqs: a dictionary corresponding to the frequencies of each tuple (word, label) Output: x: a feature vector of dimension (1,3) ''' # process_tweet tokenizes, stems, and removes stopwords word_l = process_tweet(tweet) # 3 elements in the form of a 1 x 3 vector x = np.zeros((1, 3)) #bias term is set to 1 x[0,0] = 1 # loop through each word in the list of words for word in word_l: # increment the word count for the positive label 1 x[0,1] += freqs.get((word,1),0) # increment the word count for the negative label 0 x[0,2] += freqs.get((word,0),0) assert(x.shape == (1, 3)) return x" }, { "code": null, "e": 8848, "s": 8759, "text": "Now, we will import the data set from nltk and break it into a training set and test set" }, { "code": null, "e": 9358, "s": 8848, "text": "# split the data into two pieces, one for training and one for testing (validation set) test_pos = all_positive_tweets[4000:]train_pos = all_positive_tweets[:4000]test_neg = all_negative_tweets[4000:]train_neg = all_negative_tweets[:4000]train_x = train_pos + train_neg test_x = test_pos + test_neg# combine positive and negative labelstrain_y = np.append(np.ones((len(train_pos), 1)), np.zeros((len(train_neg), 1)), axis=0)test_y = np.append(np.ones((len(test_pos), 1)), np.zeros((len(test_neg), 1)), axis=0)" }, { "code": null, "e": 9490, "s": 9358, "text": "As all the required functions are ready we can finally train our model using the training data set and test it on the test data set" }, { "code": null, "e": 9923, "s": 9490, "text": "# collect the features 'x' and stack them into a matrix 'X'X = np.zeros((len(train_x), 3))for i in range(len(train_x)): X[i, :]= extract_features(train_x[i], freqs)# training labels corresponding to XY = train_y# Apply gradient descentJ, theta = gradientDescent(X, Y, np.zeros((3, 1)), 1e-9, 1500)print(f\"The cost after training is {J:.8f}.\")print(f\"The resulting vector of weights is {[round(t, 8) for t in np.squeeze(theta)]}\")" }, { "code": null, "e": 10003, "s": 9923, "text": "J is the final cost and “theta” are the final weights after training the model." }, { "code": null, "e": 10061, "s": 10003, "text": "In order to check it before testing on the test data set." }, { "code": null, "e": 10226, "s": 10061, "text": "# Check your function# test 1# test on training datatmp1 = extract_features(train_x[0], freqs)print(tmp1)# #### Expected output# ```# [[1.00e+00 3.02e+03 6.10e+01]]" }, { "code": null, "e": 10460, "s": 10226, "text": "Lets, write two more functions which given a tweet will predict the result using the ‘freqs’ dictionary and theta. The second function will use the predict function and provide the accuracy of the model on the given testing data set." }, { "code": null, "e": 12045, "s": 10460, "text": "def predict_tweet(tweet, freqs, theta): ''' Input: tweet: a string freqs: a dictionary corresponding to the frequencies of each tuple (word, label) theta: (3,1) vector of weights Output: y_pred: the probability of a tweet being positive or negative ''' # extract the features of the tweet and store it into x x = extract_features(tweet, freqs) # make the prediction using x and theta z = np.dot(x,theta) y_pred = sigmoid(z) return y_preddef test_logistic_regression(test_x, test_y, freqs, theta): \"\"\" Input: test_x: a list of tweets test_y: (m, 1) vector with the corresponding labels for the list of tweets freqs: a dictionary with the frequency of each pair (or tuple) theta: weight vector of dimension (3, 1) Output: accuracy: (# of tweets classified correctly) / (total # of tweets) \"\"\" # the list for storing predictions y_hat = [] for tweet in test_x: # get the label prediction for the tweet y_pred = predict_tweet(tweet, freqs, theta) if y_pred > 0.5: # append 1.0 to the list y_hat.append(1) else: # append 0 to the list y_hat.append(0)# With the above implementation, y_hat is a list, but test_y is (m,1) array # convert both to one-dimensional arrays in order to compare them using the '==' operator y_hat = np.array(y_hat) test_y = test_y.reshape(-1) accuracy = np.sum((test_y == y_hat).astype(int))/len(test_x) return accuracy" }, { "code": null, "e": 12118, "s": 12045, "text": "On testing the model using the test data set we get an accuracy of 99.5%" }, { "code": null, "e": 12205, "s": 12118, "text": "Naive Bayes algorithm is based on the Bayes rule, which can be represented as follows:" }, { "code": null, "e": 12228, "s": 12205, "text": "P(X∣Y)=P(Y)P(Y∣X)P(X)​" }, { "code": null, "e": 12389, "s": 12228, "text": "Here, the process up to creating a dictionary of frequencies (importing libraries, preprocessing, etc.) is the same. The way the algorithm works is as follows:-" }, { "code": null, "e": 12484, "s": 12389, "text": "Find the log of the ratio of the number of positive tweets and negative sentiment tweets. i.e." }, { "code": null, "e": 12579, "s": 12484, "text": "Find the log of the ratio of the number of positive tweets and negative sentiment tweets. i.e." }, { "code": null, "e": 12637, "s": 12579, "text": "logprior :- log(P(Dpos))−log(P(Dneg))=log(Dpos)−log(Dneg)" }, { "code": null, "e": 12923, "s": 12637, "text": "2. Instead of keeping the frequencies of each word with the positive and negative labels we take the ratio of their frequency in that label by the total number of frequencies in that label. This will give the probability of occurrence of that word given the tweet is positive/negative." }, { "code": null, "e": 13333, "s": 12923, "text": "3. Then we make another property called loglikelihood. It is the log of the ratio of Positive probability to that of the negative probability of a particular word. But what if the probability of the word is zero ( frequency is zero in either positive or negative case) the log may become +/- infinity. Hence to overcome this we use additive smoothing. This wiki article explains more about additive smoothing." }, { "code": null, "e": 13480, "s": 13333, "text": "Therefore, to compute the positive probability and the negative probability for a specific word in the vocabulary, we’ll use the following inputs:" }, { "code": null, "e": 13690, "s": 13480, "text": "freqpos and freqneg are the frequencies of that specific word in the positive or negative class. In other words, the positive frequency of a word is the number of times the word is counted with the label of 1." }, { "code": null, "e": 13807, "s": 13690, "text": "Npos and Nneg are the total numbers of positive and negative words for all documents (for all tweets), respectively." }, { "code": null, "e": 13918, "s": 13807, "text": "V is the number of unique words in the entire set of documents, for all classes, whether positive or negative." }, { "code": null, "e": 14023, "s": 13918, "text": "We’ll use these to compute the positive and negative probability for a specific word using this formula:" }, { "code": null, "e": 14053, "s": 14023, "text": "P(Wpos)= (freqpos+1)/(Npos+V)" }, { "code": null, "e": 14083, "s": 14053, "text": "P(Wneg)= (freqneg+1)/(Nneg+V)" }, { "code": null, "e": 14152, "s": 14083, "text": "Notice that we add the “+1” in the numerator for additive smoothing." }, { "code": null, "e": 14198, "s": 14152, "text": "And the loglikelihood can be represented as:-" }, { "code": null, "e": 14233, "s": 14198, "text": "loglikelihood=log(P(Wpos)/P(Wneg))" }, { "code": null, "e": 14391, "s": 14233, "text": "That's it! We just need to code the above written in order to train our Naive Bayes function. So, first, let's write a function that does all the above work." }, { "code": null, "e": 16349, "s": 14391, "text": "def train_naive_bayes(freqs, train_x, train_y): ''' Input: freqs: dictionary from (word, label) to how often the word appears train_x: a list of tweets train_y: a list of labels correponding to the tweets (0,1) Output: logprior: the log prior. (equation 3 above) loglikelihood: the log likelihood of you Naive bayes equation. (equation 6 above) ''' loglikelihood = {} logprior = 0 # calculate V, the number of unique words in the vocabulary vocab = set([pair[0] for pair in freqs.keys()]) V = len(vocab) # calculate N_pos and N_neg N_pos = N_neg = 0 for pair in freqs.keys(): # if the label is positive (greater than zero) if pair[1] > 0: # Increment the number of positive words by the count for this (word, label) pair N_pos += freqs.get(pair, 1) # else, the label is negative else: # increment the number of negative words by the count for this (word,label) pair N_neg += freqs.get(pair, 1) # Calculate D, the number of documents D = len(train_y) # Calculate D_pos, the number of positive documents (*hint: use sum(<np_array>)) D_pos = sum(train_y) # Calculate D_neg, the number of negative documents (*hint: compute using D and D_pos) D_neg = D-D_pos # Calculate logprior logprior = np.log(D_pos) - np.log(D_neg) # For each word in the vocabulary... for word in vocab: # get the positive and negative frequency of the word freq_pos = freqs.get((word, 1),0) freq_neg = freqs.get((word, 0),0) # calculate the probability that each word is positive, and negative p_w_pos = (freq_pos + 1)/(N_pos + V) p_w_neg = (freq_neg + 1)/(N_neg + V) # calculate the log likelihood of the word loglikelihood[word] = np.log(p_w_pos/p_w_neg) return logprior, loglikelihoodlogprior, loglikelihood = train_naive_bayes(freqs, train_x, train_y)" }, { "code": null, "e": 16623, "s": 16349, "text": "In order to predict the sentiment of a tweet we simply have to sum up the loglikelihood of the words in the tweet along with the logprior. If the value is positive then the tweet shows positive sentiment but if the value is negative then the tweet shows negative sentiment." }, { "code": null, "e": 16798, "s": 16623, "text": "So let's write the predicting ( takes in a tweet, loglikelihood, and logprior and returns the prediction) and a testing function ( to test the model using the test data set)." }, { "code": null, "e": 18477, "s": 16798, "text": "def naive_bayes_predict(tweet, logprior, loglikelihood): ''' Input: tweet: a string logprior: a number loglikelihood: a dictionary of words mapping to numbers Output: p: the sum of all the logliklihoods of each word in the tweet (if found in the dictionary) + logprior (a number)''' # process the tweet to get a list of words word_l = process_tweet(tweet)# initialize probability to zero p = 0# add the logprior p += logpriorfor word in word_l:# check if the word exists in the loglikelihood dictionary if word in loglikelihood: # add the log likelihood of that word to the probability p += loglikelihood[word]return pdef test_naive_bayes(test_x, test_y, logprior, loglikelihood): \"\"\" Input: test_x: A list of tweets test_y: the corresponding labels for the list of tweets logprior: the logprior loglikelihood: a dictionary with the loglikelihoods for each word Output: accuracy: (# of tweets classified correctly)/(total # of tweets) \"\"\" accuracy = 0 # return this properlyy_hats = [] for tweet in test_x: # if the prediction is > 0 if naive_bayes_predict(tweet, logprior, loglikelihood) > 0: # the predicted class is 1 y_hat_i = 1 else: # otherwise the predicted class is 0 y_hat_i = 0# append the predicted class to the list y_hats y_hats.append(y_hat_i) # error is the average of the absolute values of the differences between y_hats and test_y error = np.mean(np.absolute(y_hats - test_y))# Accuracy is 1 minus the error accuracy = 1 - errorreturn accuracy" }, { "code": null, "e": 18690, "s": 18477, "text": "On testing the model on the test data set we get an accuracy of 99.4%. which is slightly less may be due to the assumptions that the Naive Bayes algorithm makes. In fact, it called “Naive” due to its assumptions." }, { "code": null, "e": 18723, "s": 18690, "text": "The assumptions are as follows:-" }, { "code": null, "e": 18747, "s": 18723, "text": "Independence assumption" }, { "code": null, "e": 18771, "s": 18747, "text": "Independence assumption" }, { "code": null, "e": 19113, "s": 18771, "text": "In the first image, you can see the word sunny and hot tend to depend on each other and are correlated to a certain extent with the word “desert”. Naive Bayes assumes independence throughout. Furthermore, if you were to fill in the sentence on the right, this naive model will assign equal weight to the words “spring, summer, fall, winter”." }, { "code": null, "e": 19137, "s": 19113, "text": "2. Relative frequencies" }, { "code": null, "e": 19410, "s": 19137, "text": "On Twitter, there are usually more positive tweets than negative ones. However, some “clean” datasets you may find are artificially balanced to have the same amount of positive and negative tweets. Just keep in mind, that in the real world, the data could be much noisier." } ]
How to convert InputStream to byte array in Java?
The InputStream class in Java provides read() method. This method accepts a byte array and it reads the contents of the input stream to the given byte array. Live Demo import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; public class StreamToByteArray { public static void main(String args[]) throws IOException { InputStream is = new BufferedInputStream(System.in); byte [] byteArray = new byte[1024]; System.out.println("Enter some data"); is.read(byteArray); String s = new String(byteArray); System.out.println("Contents of the byte stream are :: "+ s); } } Enter some data hello how are you Contents of the byte stream are :: hello how are you
[ { "code": null, "e": 1220, "s": 1062, "text": "The InputStream class in Java provides read() method. This method accepts a byte array and it reads the contents of the input stream to the given byte array." }, { "code": null, "e": 1231, "s": 1220, "text": " Live Demo" }, { "code": null, "e": 1706, "s": 1231, "text": "import java.io.BufferedInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\npublic class StreamToByteArray {\n public static void main(String args[]) throws IOException {\n InputStream is = new BufferedInputStream(System.in);\n byte [] byteArray = new byte[1024];\n System.out.println(\"Enter some data\");\n is.read(byteArray);\n String s = new String(byteArray);\n System.out.println(\"Contents of the byte stream are :: \"+ s);\n }\n}" }, { "code": null, "e": 1793, "s": 1706, "text": "Enter some data\nhello how are you\nContents of the byte stream are :: hello how are you" } ]
Apache Arrow: Read DataFrame With Zero Memory | Towards Data Science
Last week I saw a tweet from Wes McKinney, probably best known as the creator of the awesome pandas package: So, when I saw him quoting William Gibson, I thought there must be something amazing going on. I was not disappointed. The tweet at the start of the chain was about Hugging Face, a natural-language processing library. The project collects datasets that can be used for training & benchmarking of models. And some of these datasets are huge. In the initial tweet, Thomas Wolf points out that with a special file format, he and Quentin Lhoest are now able to iterate through 17GB of data in less than a minute with a RAM footprint of 9MB 🤯 The first question that came to my mind: How? What magic is going on here? So that was the future Wes McKinney was talking about. Since there aren’t many practical examples online, I decided to write an introductory blog post with hands-on example about what I’ve learned so far. I’m not affiliated with the Hugging Face or PyArrow project. At the end of this article, you will find links to all sources. Any sufficiently advanced technology is indistinguishable from magic. — Arthur C. Clarke, 3rd law The first clue was Thomas Wolf referring to Apache Arrow. Apache Arrow is a project started by Wes McKinney, intending to create an interface for data exchange: Apache Arrow is a cross-language development platform for in-memory data. It specifies a standardized language-independent columnar memory format for flat and hierarchical data, organized for efficient analytic operations on modern hardware. It also provides computational libraries and zero-copy streaming messaging and interprocess communication. [1] What does this mean? Before Arrow, the standard way of exchanging data between any application or library was to store it to disk in one way or the other. So if a .NET Core library wants to pass the data to Python for data analysis, chances were that someone would write out a file (e.g. csv, json, Parquet, ...) and then read it in again with Python. Both steps, the writing (serialization) and reading (deserialization) are costly and slow — and the bigger the dataset, the longer it takes to complete each of them. What if there was a way to exchange the data directly via handshake and zero copying? It could look like this: .NET would start chatting with Python, point to a pile of data in memory and be like: Hey pal, this is yours now. And Python could directly jump onto it without carting it from one place to another. Wouldn’t that be fantastic? That’s what Apache Arrow is all about. That left me wondering — how can I use Arrow? By looking at the source code of Hugging Face, I learned that the project uses PyArrow to read the data. Until then, I associated PyArrow with Parquet, a highly compressed, columnar storage format. So, is Parquet the way how Arrow exchanges data? (Spoiler: It’s not) Traditionally, data is stored on disk in a row-by-row manner. Columnar storage was born out of the necessity to analyze large datasets and aggregate them efficiently. Data analytics is less interested in rows of data (e.g. one customer transaction, one call log, ...) but on aggregations thereof (e.g. total amount spent by customer, total call minutes by region, ...). This gave rise to changing the orientation: Instead of storing it row by row, columnar storage arranges data column by column. Parquet is a columnar file format which has two major benefits [4]: Highly compressible: While .json or .csv files are by default uncompressed, Parquet compresses data and hence saves a lot of disk space. Tables have usually a mix of columns with large number of unique values (high cardinality; think of unique user ID) and columns with only few unique values (low cardinality; think of country). The lower the cardinality, the better compression (may) work — more on that in the next sectionFile querying/filter pushdown: Prune unnecessary data before reading it in. This improves loading times and optimizes resource consumption. If you only need two columns from a thousand-column table, you don’t need to scan all rows to get the two attributes — you directly fetch the column in its entirety Highly compressible: While .json or .csv files are by default uncompressed, Parquet compresses data and hence saves a lot of disk space. Tables have usually a mix of columns with large number of unique values (high cardinality; think of unique user ID) and columns with only few unique values (low cardinality; think of country). The lower the cardinality, the better compression (may) work — more on that in the next section File querying/filter pushdown: Prune unnecessary data before reading it in. This improves loading times and optimizes resource consumption. If you only need two columns from a thousand-column table, you don’t need to scan all rows to get the two attributes — you directly fetch the column in its entirety To better understand the difference between Parquet and Arrow, we will need to make a detour and get some intuition for compression. File compression is a huge subject on its own right. The following is a simplified narrative, filtered through my own understanding of the topic. This digression will help answer these two questions: How does Parquet get file down to such small sizes? Where does Parquet differ from Arrow? Imagine you flip a coin ten times and record the result: [Head, Head, Head, Head, Tail, Tail, Tail, Head, Tail, Tail] Now, try to say the result out loud? Likely, you’ll shorten it and say something like “4 times head, 3 times tail, head and 2 times tail”: [4 x Head, 3 x Tail, Head, 2 x Tail] That’s compression in action (the described algorithm is called Run-length encoding [8]). We tend to naturally see a pattern and abbreviate. A compression algorithm does that too — just with more raw computational power and sophisticated rules. But this example should be sufficient to help us understand a key difference: While .csv takes the literal approach and spells out each single record, Parquet abbreviates (without losing any information). This simple example is sufficient to also get an intuition on why the compression ratio can widely differ. For instance, if the sort order doesn’t matter and you are simply interested in the total occurrence count of head vs tail, you could sort the list first and then the compressed version would look like this: [5 x Head, 5 x Tail] By implication, if we sort a dataset by all columns first before we save it to Parquet, the file size will be smaller compared to an unsorted one. The compression ratio will be higher the lower the cardinality. The compression ratio for each column is expected to shrink the further down it is in the sort order. With this, we gained some intuition of why Parquet files are so small compared to uncompressed .csv files. But how is that related to Arrow? It turns out that this is exactly one of the key differences. Parquet is stored in a highly efficient way on disk. And with filter pushdown you can reduce the volume of data read in (i.e. by selecting only the columns you actually need). But when you want to perform operations on the data, your computer still needs to unpack the compressed information and bring it into memory. [2] Arrow on the other hand is a memory-mapped format. In a blog-post Wes McKinney summarizes it as following: “Arrow serialization design provides a ‘data header’ which describes the exact locations and sizes of all the memory buffers for all the columns in a table. This means you can memory map huge, bigger-than-RAM datasets and evaluate pandas-style algorithms on them in-place without loading them into memory like you have to with pandas now. You could read 1 megabyte from the middle of a 1 terabyte table, and you only pay the cost of performing those random reads totalling 1 megabyte.” [6] In short, applications can directly operate on a dataset stored on disk without the need to fully load it into memory. If you recall the initial Tweet — that’s exactly what was going on there. Now let’s explore these data formats. As a sample dataset I’m using the Palmer Station Penguin dataset. Since it only contains 350 rows, I’ll resample it to 1 million so that the performance difference becomes more apparent: As a next step I write the files to disk in three formats: csv (DataFrame with missing values) Parquet (DataFrame with missing values) Arrow (DataFrame with & without missing values) Note that Arrow can only be converted to pandas without allocating memory (= zero-copy) under certain conditions. One of them: There must be no NaN values. To compare the performance between with & without zero-copying, I write the Arrow file once with and without missing numeric values. The resulting file sizes are: Parquet is as expected the smallest file — despite the random sequence (no sorting took place before writing the file out), it shines with a compression ratio of 80%. Arrow is only slightly smaller than csv. Reason is that csv stores even numeric values as strings which consumes more disk space. In all cases the size difference between files with missing values and without is insignificant (<0.5 MB). Now the key part: Reading performance. How long does it take to calculate average flipper length? csv Parquet Arrow with file API (OSFile(...)) Arrow as memory-map API (memory_map(...)) with missing values/NaN Arrow as memory-map API (memory_map(...)) without missing values Timing each of the three functions, the following results arise: Unsurprisingly, csv is the slowest option. It requires reading 200MB, parse the text, discard all columns except flipper length and then calculate the mean. Parquet is ~60 times faster since there is no need to parse the entire file — only the required columns is read in. Arrow with missing values is ~3 times faster than Parquet and almost ~200 times faster than csv. Like Parquet, Arrow can limit itself to reading only the specified column. What makes it faster is that there is no need to decompress the column. Note that the difference between reading memory-mapped Arrow files with and without zero-copying meant another ~3 times performance improvement (i.e. zero-copy is in total ~600 times faster than csv and ~9 times faster than Parquet). What’s surprising: Arrow with the file API is even slower than Parquet. What’s going on? To answer that let’s look at the memory consumption. How much RAM is each file consuming if we read a single column? Here are the results: Most notable: Arrow with file API consumes 189 MB — which is pretty much the entire file size (even though we only read a single column?!). The answer lies in the documentation: “[...] OSFile allocates new memory on each read, like Python file objects.” [3] By using OSFile the entire file was read into memory first. Now it's obvious why this operation was slower than Parquet and consumes the most memory! However, by using the memory-mapping function and with filled NaN values, the pandas DataFrame was created directly on top of the stored Arrow file. No copying: 0 MB of RAM! No surprise this was the fastest option. You can find the entire Jupyter Notebook here 📝 For me, there is lot to learn about Arrow. What I have learnt so far is: You can’t have your cake and eat it, too. There is a trade-off between [7]: Optimize for disk space/long-term storage on disk → Parquet Optimize for data exchange and fast retrieval → Arrow The performance gains of both Parquet and Arrow are significant compared to csv. When storing Arrow to disk, it consumes more storage than Parquet. However, Arrow beats Parquet in terms of reading performance — both in terms of time and memory consumption. The presented examples (calculate mean of one column/read column) are only scratching on the surface — my expectation is that with more complicated queries & bigger datasets Arrow would shine even more. As long as Arrow is read with the memory-mapping function, the reading performance is incredible. The best case is when the dataset has no missing values/NaNs. Then PyArrow can do its magic and allow you to operate on the table, barely consuming any memory. The future is indeed already here — and it’s amazing! I will keep writing about Python, data and technology —I’d be happy to meet you on Twitter ✨ Big thanks to Yingying for the thorough review and great feedback! 👏 [1] Apache Arrow, Landing Page (2020), Apache Arrow Website [2] Apache Arrow, FAQ (2020), Apache Arrow Website [3] Apache Arrow, On-Disk and Memory Mapped Files (2020), Apache Arrow Python Bindings Documentation [4] J. LeDem, Apache Arrow and Apache Parquet: Why We Needed Different Projects for Columnar Data, On Disk and In-Memory (2017), KDnuggets [5] J. LeDem, The Columnar Roadmap: Apache Parquet and Apache Arrow (2017), Dremio [6] W. McKinney, Apache Arrow and the “10 Things I Hate About pandas” (2017), Blog [7] W. McKinney, Some comments to Daniel Abadi’s blog about Apache Arrow (2017), Blog [8] Wikipedia, Run-length encoding (2020), Wikipedia
[ { "code": null, "e": 281, "s": 172, "text": "Last week I saw a tweet from Wes McKinney, probably best known as the creator of the awesome pandas package:" }, { "code": null, "e": 400, "s": 281, "text": "So, when I saw him quoting William Gibson, I thought there must be something amazing going on. I was not disappointed." }, { "code": null, "e": 819, "s": 400, "text": "The tweet at the start of the chain was about Hugging Face, a natural-language processing library. The project collects datasets that can be used for training & benchmarking of models. And some of these datasets are huge. In the initial tweet, Thomas Wolf points out that with a special file format, he and Quentin Lhoest are now able to iterate through 17GB of data in less than a minute with a RAM footprint of 9MB 🤯" }, { "code": null, "e": 894, "s": 819, "text": "The first question that came to my mind: How? What magic is going on here?" }, { "code": null, "e": 949, "s": 894, "text": "So that was the future Wes McKinney was talking about." }, { "code": null, "e": 1224, "s": 949, "text": "Since there aren’t many practical examples online, I decided to write an introductory blog post with hands-on example about what I’ve learned so far. I’m not affiliated with the Hugging Face or PyArrow project. At the end of this article, you will find links to all sources." }, { "code": null, "e": 1322, "s": 1224, "text": "Any sufficiently advanced technology is indistinguishable from magic. — Arthur C. Clarke, 3rd law" }, { "code": null, "e": 1483, "s": 1322, "text": "The first clue was Thomas Wolf referring to Apache Arrow. Apache Arrow is a project started by Wes McKinney, intending to create an interface for data exchange:" }, { "code": null, "e": 1836, "s": 1483, "text": "Apache Arrow is a cross-language development platform for in-memory data. It specifies a standardized language-independent columnar memory format for flat and hierarchical data, organized for efficient analytic operations on modern hardware. It also provides computational libraries and zero-copy streaming messaging and interprocess communication. [1]" }, { "code": null, "e": 1857, "s": 1836, "text": "What does this mean?" }, { "code": null, "e": 2354, "s": 1857, "text": "Before Arrow, the standard way of exchanging data between any application or library was to store it to disk in one way or the other. So if a .NET Core library wants to pass the data to Python for data analysis, chances were that someone would write out a file (e.g. csv, json, Parquet, ...) and then read it in again with Python. Both steps, the writing (serialization) and reading (deserialization) are costly and slow — and the bigger the dataset, the longer it takes to complete each of them." }, { "code": null, "e": 2692, "s": 2354, "text": "What if there was a way to exchange the data directly via handshake and zero copying? It could look like this: .NET would start chatting with Python, point to a pile of data in memory and be like: Hey pal, this is yours now. And Python could directly jump onto it without carting it from one place to another. Wouldn’t that be fantastic?" }, { "code": null, "e": 2731, "s": 2692, "text": "That’s what Apache Arrow is all about." }, { "code": null, "e": 3044, "s": 2731, "text": "That left me wondering — how can I use Arrow? By looking at the source code of Hugging Face, I learned that the project uses PyArrow to read the data. Until then, I associated PyArrow with Parquet, a highly compressed, columnar storage format. So, is Parquet the way how Arrow exchanges data? (Spoiler: It’s not)" }, { "code": null, "e": 3414, "s": 3044, "text": "Traditionally, data is stored on disk in a row-by-row manner. Columnar storage was born out of the necessity to analyze large datasets and aggregate them efficiently. Data analytics is less interested in rows of data (e.g. one customer transaction, one call log, ...) but on aggregations thereof (e.g. total amount spent by customer, total call minutes by region, ...)." }, { "code": null, "e": 3541, "s": 3414, "text": "This gave rise to changing the orientation: Instead of storing it row by row, columnar storage arranges data column by column." }, { "code": null, "e": 3609, "s": 3541, "text": "Parquet is a columnar file format which has two major benefits [4]:" }, { "code": null, "e": 4339, "s": 3609, "text": "Highly compressible: While .json or .csv files are by default uncompressed, Parquet compresses data and hence saves a lot of disk space. Tables have usually a mix of columns with large number of unique values (high cardinality; think of unique user ID) and columns with only few unique values (low cardinality; think of country). The lower the cardinality, the better compression (may) work — more on that in the next sectionFile querying/filter pushdown: Prune unnecessary data before reading it in. This improves loading times and optimizes resource consumption. If you only need two columns from a thousand-column table, you don’t need to scan all rows to get the two attributes — you directly fetch the column in its entirety" }, { "code": null, "e": 4765, "s": 4339, "text": "Highly compressible: While .json or .csv files are by default uncompressed, Parquet compresses data and hence saves a lot of disk space. Tables have usually a mix of columns with large number of unique values (high cardinality; think of unique user ID) and columns with only few unique values (low cardinality; think of country). The lower the cardinality, the better compression (may) work — more on that in the next section" }, { "code": null, "e": 5070, "s": 4765, "text": "File querying/filter pushdown: Prune unnecessary data before reading it in. This improves loading times and optimizes resource consumption. If you only need two columns from a thousand-column table, you don’t need to scan all rows to get the two attributes — you directly fetch the column in its entirety" }, { "code": null, "e": 5403, "s": 5070, "text": "To better understand the difference between Parquet and Arrow, we will need to make a detour and get some intuition for compression. File compression is a huge subject on its own right. The following is a simplified narrative, filtered through my own understanding of the topic. This digression will help answer these two questions:" }, { "code": null, "e": 5455, "s": 5403, "text": "How does Parquet get file down to such small sizes?" }, { "code": null, "e": 5493, "s": 5455, "text": "Where does Parquet differ from Arrow?" }, { "code": null, "e": 5550, "s": 5493, "text": "Imagine you flip a coin ten times and record the result:" }, { "code": null, "e": 5611, "s": 5550, "text": "[Head, Head, Head, Head, Tail, Tail, Tail, Head, Tail, Tail]" }, { "code": null, "e": 5750, "s": 5611, "text": "Now, try to say the result out loud? Likely, you’ll shorten it and say something like “4 times head, 3 times tail, head and 2 times tail”:" }, { "code": null, "e": 5787, "s": 5750, "text": "[4 x Head, 3 x Tail, Head, 2 x Tail]" }, { "code": null, "e": 6237, "s": 5787, "text": "That’s compression in action (the described algorithm is called Run-length encoding [8]). We tend to naturally see a pattern and abbreviate. A compression algorithm does that too — just with more raw computational power and sophisticated rules. But this example should be sufficient to help us understand a key difference: While .csv takes the literal approach and spells out each single record, Parquet abbreviates (without losing any information)." }, { "code": null, "e": 6552, "s": 6237, "text": "This simple example is sufficient to also get an intuition on why the compression ratio can widely differ. For instance, if the sort order doesn’t matter and you are simply interested in the total occurrence count of head vs tail, you could sort the list first and then the compressed version would look like this:" }, { "code": null, "e": 6573, "s": 6552, "text": "[5 x Head, 5 x Tail]" }, { "code": null, "e": 6886, "s": 6573, "text": "By implication, if we sort a dataset by all columns first before we save it to Parquet, the file size will be smaller compared to an unsorted one. The compression ratio will be higher the lower the cardinality. The compression ratio for each column is expected to shrink the further down it is in the sort order." }, { "code": null, "e": 7027, "s": 6886, "text": "With this, we gained some intuition of why Parquet files are so small compared to uncompressed .csv files. But how is that related to Arrow?" }, { "code": null, "e": 7411, "s": 7027, "text": "It turns out that this is exactly one of the key differences. Parquet is stored in a highly efficient way on disk. And with filter pushdown you can reduce the volume of data read in (i.e. by selecting only the columns you actually need). But when you want to perform operations on the data, your computer still needs to unpack the compressed information and bring it into memory. [2]" }, { "code": null, "e": 7518, "s": 7411, "text": "Arrow on the other hand is a memory-mapped format. In a blog-post Wes McKinney summarizes it as following:" }, { "code": null, "e": 8008, "s": 7518, "text": "“Arrow serialization design provides a ‘data header’ which describes the exact locations and sizes of all the memory buffers for all the columns in a table. This means you can memory map huge, bigger-than-RAM datasets and evaluate pandas-style algorithms on them in-place without loading them into memory like you have to with pandas now. You could read 1 megabyte from the middle of a 1 terabyte table, and you only pay the cost of performing those random reads totalling 1 megabyte.” [6]" }, { "code": null, "e": 8201, "s": 8008, "text": "In short, applications can directly operate on a dataset stored on disk without the need to fully load it into memory. If you recall the initial Tweet — that’s exactly what was going on there." }, { "code": null, "e": 8426, "s": 8201, "text": "Now let’s explore these data formats. As a sample dataset I’m using the Palmer Station Penguin dataset. Since it only contains 350 rows, I’ll resample it to 1 million so that the performance difference becomes more apparent:" }, { "code": null, "e": 8485, "s": 8426, "text": "As a next step I write the files to disk in three formats:" }, { "code": null, "e": 8521, "s": 8485, "text": "csv (DataFrame with missing values)" }, { "code": null, "e": 8561, "s": 8521, "text": "Parquet (DataFrame with missing values)" }, { "code": null, "e": 8609, "s": 8561, "text": "Arrow (DataFrame with & without missing values)" }, { "code": null, "e": 8898, "s": 8609, "text": "Note that Arrow can only be converted to pandas without allocating memory (= zero-copy) under certain conditions. One of them: There must be no NaN values. To compare the performance between with & without zero-copying, I write the Arrow file once with and without missing numeric values." }, { "code": null, "e": 8928, "s": 8898, "text": "The resulting file sizes are:" }, { "code": null, "e": 9332, "s": 8928, "text": "Parquet is as expected the smallest file — despite the random sequence (no sorting took place before writing the file out), it shines with a compression ratio of 80%. Arrow is only slightly smaller than csv. Reason is that csv stores even numeric values as strings which consumes more disk space. In all cases the size difference between files with missing values and without is insignificant (<0.5 MB)." }, { "code": null, "e": 9430, "s": 9332, "text": "Now the key part: Reading performance. How long does it take to calculate average flipper length?" }, { "code": null, "e": 9434, "s": 9430, "text": "csv" }, { "code": null, "e": 9442, "s": 9434, "text": "Parquet" }, { "code": null, "e": 9476, "s": 9442, "text": "Arrow with file API (OSFile(...))" }, { "code": null, "e": 9542, "s": 9476, "text": "Arrow as memory-map API (memory_map(...)) with missing values/NaN" }, { "code": null, "e": 9607, "s": 9542, "text": "Arrow as memory-map API (memory_map(...)) without missing values" }, { "code": null, "e": 9672, "s": 9607, "text": "Timing each of the three functions, the following results arise:" }, { "code": null, "e": 9829, "s": 9672, "text": "Unsurprisingly, csv is the slowest option. It requires reading 200MB, parse the text, discard all columns except flipper length and then calculate the mean." }, { "code": null, "e": 9945, "s": 9829, "text": "Parquet is ~60 times faster since there is no need to parse the entire file — only the required columns is read in." }, { "code": null, "e": 10189, "s": 9945, "text": "Arrow with missing values is ~3 times faster than Parquet and almost ~200 times faster than csv. Like Parquet, Arrow can limit itself to reading only the specified column. What makes it faster is that there is no need to decompress the column." }, { "code": null, "e": 10423, "s": 10189, "text": "Note that the difference between reading memory-mapped Arrow files with and without zero-copying meant another ~3 times performance improvement (i.e. zero-copy is in total ~600 times faster than csv and ~9 times faster than Parquet)." }, { "code": null, "e": 10512, "s": 10423, "text": "What’s surprising: Arrow with the file API is even slower than Parquet. What’s going on?" }, { "code": null, "e": 10629, "s": 10512, "text": "To answer that let’s look at the memory consumption. How much RAM is each file consuming if we read a single column?" }, { "code": null, "e": 10651, "s": 10629, "text": "Here are the results:" }, { "code": null, "e": 10829, "s": 10651, "text": "Most notable: Arrow with file API consumes 189 MB — which is pretty much the entire file size (even though we only read a single column?!). The answer lies in the documentation:" }, { "code": null, "e": 10909, "s": 10829, "text": "“[...] OSFile allocates new memory on each read, like Python file objects.” [3]" }, { "code": null, "e": 11059, "s": 10909, "text": "By using OSFile the entire file was read into memory first. Now it's obvious why this operation was slower than Parquet and consumes the most memory!" }, { "code": null, "e": 11274, "s": 11059, "text": "However, by using the memory-mapping function and with filled NaN values, the pandas DataFrame was created directly on top of the stored Arrow file. No copying: 0 MB of RAM! No surprise this was the fastest option." }, { "code": null, "e": 11322, "s": 11274, "text": "You can find the entire Jupyter Notebook here 📝" }, { "code": null, "e": 11471, "s": 11322, "text": "For me, there is lot to learn about Arrow. What I have learnt so far is: You can’t have your cake and eat it, too. There is a trade-off between [7]:" }, { "code": null, "e": 11531, "s": 11471, "text": "Optimize for disk space/long-term storage on disk → Parquet" }, { "code": null, "e": 11585, "s": 11531, "text": "Optimize for data exchange and fast retrieval → Arrow" }, { "code": null, "e": 12045, "s": 11585, "text": "The performance gains of both Parquet and Arrow are significant compared to csv. When storing Arrow to disk, it consumes more storage than Parquet. However, Arrow beats Parquet in terms of reading performance — both in terms of time and memory consumption. The presented examples (calculate mean of one column/read column) are only scratching on the surface — my expectation is that with more complicated queries & bigger datasets Arrow would shine even more." }, { "code": null, "e": 12303, "s": 12045, "text": "As long as Arrow is read with the memory-mapping function, the reading performance is incredible. The best case is when the dataset has no missing values/NaNs. Then PyArrow can do its magic and allow you to operate on the table, barely consuming any memory." }, { "code": null, "e": 12357, "s": 12303, "text": "The future is indeed already here — and it’s amazing!" }, { "code": null, "e": 12450, "s": 12357, "text": "I will keep writing about Python, data and technology —I’d be happy to meet you on Twitter ✨" }, { "code": null, "e": 12519, "s": 12450, "text": "Big thanks to Yingying for the thorough review and great feedback! 👏" }, { "code": null, "e": 12579, "s": 12519, "text": "[1] Apache Arrow, Landing Page (2020), Apache Arrow Website" }, { "code": null, "e": 12630, "s": 12579, "text": "[2] Apache Arrow, FAQ (2020), Apache Arrow Website" }, { "code": null, "e": 12731, "s": 12630, "text": "[3] Apache Arrow, On-Disk and Memory Mapped Files (2020), Apache Arrow Python Bindings Documentation" }, { "code": null, "e": 12870, "s": 12731, "text": "[4] J. LeDem, Apache Arrow and Apache Parquet: Why We Needed Different Projects for Columnar Data, On Disk and In-Memory (2017), KDnuggets" }, { "code": null, "e": 12953, "s": 12870, "text": "[5] J. LeDem, The Columnar Roadmap: Apache Parquet and Apache Arrow (2017), Dremio" }, { "code": null, "e": 13036, "s": 12953, "text": "[6] W. McKinney, Apache Arrow and the “10 Things I Hate About pandas” (2017), Blog" }, { "code": null, "e": 13122, "s": 13036, "text": "[7] W. McKinney, Some comments to Daniel Abadi’s blog about Apache Arrow (2017), Blog" } ]
How to remove underline from a link in HTML?
To remove underline from a link in HTML, use the CSS property text-decoration. Use it with the style attribute. The style attribute specifies an inline style for an element. Use the style attribute with the CSS property text-decoration to remove underline from a link in HTML. Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet. You can try the following code to remove underline from a link in HTML Live Demo <!DOCTYPE html> <html> <head> <title>HTML Text Decoration</title> </head> <body> <h2>About</h2> <p> Our <a href="/about/about_team.htm" style="text-decoration: none;">Team</a> comprises of programmers, writers, and analysts. </p> </body> </html>
[ { "code": null, "e": 1236, "s": 1062, "text": "To remove underline from a link in HTML, use the CSS property text-decoration. Use it with the style attribute. The style attribute specifies an inline style for an element." }, { "code": null, "e": 1501, "s": 1236, "text": "Use the style attribute with the CSS property text-decoration to remove underline from a link in HTML. Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet." }, { "code": null, "e": 1572, "s": 1501, "text": "You can try the following code to remove underline from a link in HTML" }, { "code": null, "e": 1582, "s": 1572, "text": "Live Demo" }, { "code": null, "e": 1853, "s": 1582, "text": "<!DOCTYPE html>\n<html>\n<head>\n <title>HTML Text Decoration</title>\n</head>\n\n<body>\n <h2>About</h2>\n <p>\n Our <a href=\"/about/about_team.htm\" style=\"text-decoration: none;\">Team</a>\n comprises of programmers, writers, and analysts.\n </p>\n</body>\n</html>" } ]
Bootstrap 4 - Borders
Border utility provides style, color and radius of an element's border. The element's border can be added or removed by using additive and subtractive utilities of border as shown below − <html lang = "en"> <head> <!-- Meta tags --> <meta charset = "utf-8"> <meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no"> <!-- Bootstrap CSS --> <link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <title>Bootstrap 4 Example</title> </head> <body> <div class = "container"> <br> <div class = "text-white bg-secondary"> <h2>Additive</h2> <span class = "border">border</span> <span class = "border-top">border-top</span> <span class = "border-right">border-right</span> <span class = "border-bottom">border-bottom</span> <span class = "border-left">border-left</span> <br> <br> </div> <div class = "text-white bg-secondary"> <h2>Subtractive</h2> <span class = "border border-0">border-0</span> <span class = "border border-top-0">border-top-0</span> <span class = "border border-right-0">border-right-0</span> <span class = "border border-bottom-0">border-bottom-0</span> <span class = "border border-left-0">border-left-0</span> </div> </div> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src = "https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity = "sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin = "anonymous"> </script> <!-- Popper --> <script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity = "sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin = "anonymous"> </script> <!-- Latest compiled and minified Bootstrap JavaScript --> <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity = "sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin = "anonymous"> </script> </body> </html> It will produce the following result − You can set the color for an element's border by using the theme colors as shown in the below example − <html lang = "en"> <head> <!-- Meta tags --> <meta charset="utf-8"> <meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no"> <!-- Bootstrap CSS --> <link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <title>Bootstrap 4 Example</title> </head> <body> <div class = "container"> <h2>Border Color</h2> <div class = "bordercolor"> <p>border-primary, border-secondary, border-success</p> <span class = ""> <img src = "https://www.tutorialspoint.com/bootstrap/images/download.png" alt = "..." class = "border border-primary" > </span> <span class = ""> <img src = "https://www.tutorialspoint.com/bootstrap/images/download.png" alt = "..." class = "border border-secondary" > </span> <span> <img src = "https://www.tutorialspoint.com/bootstrap/images/download.png" alt = "..." class = "border border-success"> </span> <br> <br> <p>border-danger, border-warning, border-info</p> <span> <img src = "https://www.tutorialspoint.com/bootstrap/images/download.png" alt = "..." class = "border border-danger"> </span> <span> <img src = "https://www.tutorialspoint.com/bootstrap/images/download.png" alt = "..." class = "border border-warning"> </span> <span> <img src = "https://www.tutorialspoint.com/bootstrap/images/download.png" alt = "..." class = "border border-info"> </span> <br> <br> <p>border-light, border-dark, border-white</p> <span> <img src = "https://www.tutorialspoint.com/bootstrap/images/download.png" alt = "..." class = "border border-light"> </span> <span> <img src = "https://www.tutorialspoint.com/bootstrap/images/download.png" alt = "..." class = "border border-dark"> </span> <span> <img src = "https://www.tutorialspoint.com/bootstrap/images/download.png" alt = "..." class = "border border-white"> </span> <br> </div> </div> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src = "https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity = "sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin = "anonymous"> </script> <!-- Popper --> <script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity = "sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin = "anonymous"> </script> <!-- Latest compiled and minified Bootstrap JavaScript --> <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity = "sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin = "anonymous"> </script> </body> </html> It will produce the following result − border-primary, border-secondary, border-success border-danger, border-warning, border-info border-light, border-dark, border-white You can add the rounded corners to an element by using the classes (rounded-top, rounded-right etc) as shown in the below example − <html lang = "en"> <head> <!-- Meta tags --> <meta charset = "utf-8"> <meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no"> <!-- Bootstrap CSS --> <link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <title>Bootstrap 4 Example</title> </head> <body> <div class = "container-fluid bg-secondary"> <br> <h2>Border Radius</h2> <img src = "https://www.tutorialspoint.com/bootstrap/images/download.png" alt = "..." class = "rounded "> <img src = "https://www.tutorialspoint.com/bootstrap/images/download.png" alt = "..." class = "rounded-top"> <img src = "https://www.tutorialspoint.com/bootstrap/images/download.png" alt = "..." class = "rounded-right"> <img src = "https://www.tutorialspoint.com/bootstrap/images/download.png" alt = "..." class = "rounded-bottom"> <img src = "https://www.tutorialspoint.com/bootstrap/images/download.png" alt = "..." class = "rounded-left"> <img src = "https://www.tutorialspoint.com/bootstrap/images/download.png" alt = "..." class = "rounded-circle"> <img src = "https://www.tutorialspoint.com/bootstrap/images/download.png" alt = "..." class = "rounded-0"> <br> <br> <br> </div> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src = "https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity = "sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin = "anonymous"> </script> <!-- Popper --> <script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity = "sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin = "anonymous"> </script> <!-- Latest compiled and minified Bootstrap JavaScript --> <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity = "sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin = "anonymous"> </script> </body> </html> It will produce the following result − 26 Lectures 2 hours Anadi Sharma 54 Lectures 4.5 hours Frahaan Hussain 161 Lectures 14.5 hours Eduonix Learning Solutions 20 Lectures 4 hours Azaz Patel 15 Lectures 1.5 hours Muhammad Ismail 62 Lectures 8 hours Yossef Ayman Zedan Print Add Notes Bookmark this page
[ { "code": null, "e": 1888, "s": 1816, "text": "Border utility provides style, color and radius of an element's border." }, { "code": null, "e": 2004, "s": 1888, "text": "The element's border can be added or removed by using additive and subtractive utilities of border as shown below −" }, { "code": null, "e": 4335, "s": 2004, "text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"container\">\n <br>\n <div class = \"text-white bg-secondary\">\n <h2>Additive</h2>\n <span class = \"border\">border</span>\n <span class = \"border-top\">border-top</span>\n <span class = \"border-right\">border-right</span>\n <span class = \"border-bottom\">border-bottom</span>\n <span class = \"border-left\">border-left</span>\n <br>\n <br>\n </div>\n \n <div class = \"text-white bg-secondary\">\n <h2>Subtractive</h2>\n <span class = \"border border-0\">border-0</span>\n <span class = \"border border-top-0\">border-top-0</span>\n <span class = \"border border-right-0\">border-right-0</span>\n <span class = \"border border-bottom-0\">border-bottom-0</span>\n <span class = \"border border-left-0\">border-left-0</span>\n </div>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.2.1.slim.min.js\" \n integrity = \"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" \n crossorigin = \"anonymous\">\n </script>\n \n <!-- Popper -->\n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" \n integrity = \"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" \n crossorigin = \"anonymous\">\n \n </script>\n <!-- Latest compiled and minified Bootstrap JavaScript -->\n <script src = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" \n integrity = \"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>" }, { "code": null, "e": 4374, "s": 4335, "text": "It will produce the following result −" }, { "code": null, "e": 4478, "s": 4374, "text": "You can set the color for an element's border by using the theme colors as shown in the below example −" }, { "code": null, "e": 8030, "s": 4478, "text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset=\"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"container\">\n <h2>Border Color</h2>\n <div class = \"bordercolor\">\n <p>border-primary, border-secondary, border-success</p>\n <span class = \"\">\n <img src = \"https://www.tutorialspoint.com/bootstrap/images/download.png\" \n alt = \"...\" class = \"border border-primary\" >\n </span>\n <span class = \"\">\n <img src = \"https://www.tutorialspoint.com/bootstrap/images/download.png\" \n alt = \"...\" class = \"border border-secondary\" >\n </span>\n <span>\n <img src = \"https://www.tutorialspoint.com/bootstrap/images/download.png\" \n alt = \"...\" class = \"border border-success\">\n </span>\n <br>\n <br>\n \n <p>border-danger, border-warning, border-info</p>\n <span>\n <img src = \"https://www.tutorialspoint.com/bootstrap/images/download.png\" \n alt = \"...\" class = \"border border-danger\">\n </span>\n <span>\n <img src = \"https://www.tutorialspoint.com/bootstrap/images/download.png\" \n alt = \"...\" class = \"border border-warning\">\n </span>\n <span>\n <img src = \"https://www.tutorialspoint.com/bootstrap/images/download.png\" \n alt = \"...\" class = \"border border-info\">\n </span>\n <br>\n <br>\n \n <p>border-light, border-dark, border-white</p>\n <span>\n <img src = \"https://www.tutorialspoint.com/bootstrap/images/download.png\" \n alt = \"...\" class = \"border border-light\">\n </span>\n <span>\n <img src = \"https://www.tutorialspoint.com/bootstrap/images/download.png\" \n alt = \"...\" class = \"border border-dark\">\n </span>\n <span>\n <img src = \"https://www.tutorialspoint.com/bootstrap/images/download.png\" \n alt = \"...\" class = \"border border-white\">\n </span>\n <br>\n </div>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.2.1.slim.min.js\" \n integrity = \"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" \n crossorigin = \"anonymous\">\n </script>\n \n <!-- Popper -->\n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" \n integrity = \"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" \n crossorigin = \"anonymous\">\n </script>\n \n <!-- Latest compiled and minified Bootstrap JavaScript -->\n <script src = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" \n integrity = \"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>" }, { "code": null, "e": 8069, "s": 8030, "text": "It will produce the following result −" }, { "code": null, "e": 8118, "s": 8069, "text": "border-primary, border-secondary, border-success" }, { "code": null, "e": 8161, "s": 8118, "text": "border-danger, border-warning, border-info" }, { "code": null, "e": 8201, "s": 8161, "text": "border-light, border-dark, border-white" }, { "code": null, "e": 8333, "s": 8201, "text": "You can add the rounded corners to an element by using the classes (rounded-top, rounded-right etc) as shown in the below example −" }, { "code": null, "e": 10778, "s": 8333, "text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\">\n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"container-fluid bg-secondary\">\n <br>\n <h2>Border Radius</h2>\n <img src = \"https://www.tutorialspoint.com/bootstrap/images/download.png\" \n alt = \"...\" class = \"rounded \">\n \n <img src = \"https://www.tutorialspoint.com/bootstrap/images/download.png\" \n alt = \"...\" class = \"rounded-top\">\n \n <img src = \"https://www.tutorialspoint.com/bootstrap/images/download.png\" \n alt = \"...\" class = \"rounded-right\">\n \n <img src = \"https://www.tutorialspoint.com/bootstrap/images/download.png\" \n alt = \"...\" class = \"rounded-bottom\">\n \n <img src = \"https://www.tutorialspoint.com/bootstrap/images/download.png\" \n alt = \"...\" class = \"rounded-left\">\n \n <img src = \"https://www.tutorialspoint.com/bootstrap/images/download.png\" \n alt = \"...\" class = \"rounded-circle\">\n \n <img src = \"https://www.tutorialspoint.com/bootstrap/images/download.png\" \n alt = \"...\" class = \"rounded-0\">\n <br>\n <br>\n <br>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.2.1.slim.min.js\" \n integrity = \"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" \n crossorigin = \"anonymous\">\n </script>\n \n <!-- Popper -->\n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" \n integrity = \"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" \n crossorigin = \"anonymous\">\n </script>\n \n <!-- Latest compiled and minified Bootstrap JavaScript -->\n <script src = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" \n integrity = \"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>" }, { "code": null, "e": 10817, "s": 10778, "text": "It will produce the following result −" }, { "code": null, "e": 10850, "s": 10817, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 10864, "s": 10850, "text": " Anadi Sharma" }, { "code": null, "e": 10899, "s": 10864, "text": "\n 54 Lectures \n 4.5 hours \n" }, { "code": null, "e": 10916, "s": 10899, "text": " Frahaan Hussain" }, { "code": null, "e": 10953, "s": 10916, "text": "\n 161 Lectures \n 14.5 hours \n" }, { "code": null, "e": 10981, "s": 10953, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 11014, "s": 10981, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 11026, "s": 11014, "text": " Azaz Patel" }, { "code": null, "e": 11061, "s": 11026, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 11078, "s": 11061, "text": " Muhammad Ismail" }, { "code": null, "e": 11111, "s": 11078, "text": "\n 62 Lectures \n 8 hours \n" }, { "code": null, "e": 11131, "s": 11111, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 11138, "s": 11131, "text": " Print" }, { "code": null, "e": 11149, "s": 11138, "text": " Add Notes" } ]
Python | Animated Banner showing 'GeeksForGeeks' - GeeksforGeeks
14 Jul, 2019 Want to be fancy and create an animated banner? This program is going to print a cool animated banner to the Python console. Initially, it is suitable just for showing ‘GeeksForGeeks’. Consider it as a challenge by adding more characters yourself. IMPORTANT NOTE:- For this to work, you have to open the file in the console, and not through the editor/IDLE. Python implementation: import osimport time #You can change the width of the display according to your wish.WIDTH = 250 # Written below currently is GeeksForGeeks. If you wish to get more# written, you have to add each alphabet manually.message = "geeksforgeeks".upper() #The message will get printed here.printedMessage = [ "","","","","","","","","","","","","","", ] """What we have done here is a dictionary mapping the letters to their line.These mapped indexes identify itself to each letter in the dictionary and also for each line in the display."""characters = { " " : [ " ", " ", " ", " ", " ", " ", " " ], "E" : [ "*****", "* ", "* ", "*****", "* ", "* ", "*****" ], "O" : [ "*****", "* *", "* *", "* *", "* *", "* *", "*****" ], "K" : [ " * *", " * * ", " * * ", " ** ", " * * ", " * * ", " * *" ], "S" : [" **** ", " * ", " * ", " *** ", " * ", " * ", " **** " ], "G" : [" *** ", "* * ", "* ", "* *** ", "* * ", "* * ", " *** " ], "F" : ["***** ", "* ", "* ", "**** ", "* ", "* ", "* " ], "R" : [" **** ", " * * ", " * * ", " **** ", " * * ", " * * ", " * * " ] } for row in range(7): for char in message: printedMessage[row] += (str(characters[char][row]) + " ") offset = WIDTHwhile True: os.system("cls") for row in range(7): print(" " * offset + printedMessage[row][max(0,offset*-1):WIDTH - offset]) offset -=1 if offset <= ((len(message)+2)*6) * -1: offset = WIDTH #Use this to change the speed of the animation that you wish to keep. time.sleep(0.10) Output (The original output will be moving from right to left. Basically, it’s an animation.): Python list-programs Python-gui Web technologies Python Python Programs Python-Quizzes Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25555, "s": 25527, "text": "\n14 Jul, 2019" }, { "code": null, "e": 25803, "s": 25555, "text": "Want to be fancy and create an animated banner? This program is going to print a cool animated banner to the Python console. Initially, it is suitable just for showing ‘GeeksForGeeks’. Consider it as a challenge by adding more characters yourself." }, { "code": null, "e": 25913, "s": 25803, "text": "IMPORTANT NOTE:- For this to work, you have to open the file in the console, and not through the editor/IDLE." }, { "code": null, "e": 25936, "s": 25913, "text": "Python implementation:" }, { "code": "import osimport time #You can change the width of the display according to your wish.WIDTH = 250 # Written below currently is GeeksForGeeks. If you wish to get more# written, you have to add each alphabet manually.message = \"geeksforgeeks\".upper() #The message will get printed here.printedMessage = [ \"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\", ] \"\"\"What we have done here is a dictionary mapping the letters to their line.These mapped indexes identify itself to each letter in the dictionary and also for each line in the display.\"\"\"characters = { \" \" : [ \" \", \" \", \" \", \" \", \" \", \" \", \" \" ], \"E\" : [ \"*****\", \"* \", \"* \", \"*****\", \"* \", \"* \", \"*****\" ], \"O\" : [ \"*****\", \"* *\", \"* *\", \"* *\", \"* *\", \"* *\", \"*****\" ], \"K\" : [ \" * *\", \" * * \", \" * * \", \" ** \", \" * * \", \" * * \", \" * *\" ], \"S\" : [\" **** \", \" * \", \" * \", \" *** \", \" * \", \" * \", \" **** \" ], \"G\" : [\" *** \", \"* * \", \"* \", \"* *** \", \"* * \", \"* * \", \" *** \" ], \"F\" : [\"***** \", \"* \", \"* \", \"**** \", \"* \", \"* \", \"* \" ], \"R\" : [\" **** \", \" * * \", \" * * \", \" **** \", \" * * \", \" * * \", \" * * \" ] } for row in range(7): for char in message: printedMessage[row] += (str(characters[char][row]) + \" \") offset = WIDTHwhile True: os.system(\"cls\") for row in range(7): print(\" \" * offset + printedMessage[row][max(0,offset*-1):WIDTH - offset]) offset -=1 if offset <= ((len(message)+2)*6) * -1: offset = WIDTH #Use this to change the speed of the animation that you wish to keep. time.sleep(0.10)", "e": 28885, "s": 25936, "text": null }, { "code": null, "e": 28980, "s": 28885, "text": "Output (The original output will be moving from right to left. Basically, it’s an animation.):" }, { "code": null, "e": 29001, "s": 28980, "text": "Python list-programs" }, { "code": null, "e": 29012, "s": 29001, "text": "Python-gui" }, { "code": null, "e": 29029, "s": 29012, "text": "Web technologies" }, { "code": null, "e": 29036, "s": 29029, "text": "Python" }, { "code": null, "e": 29052, "s": 29036, "text": "Python Programs" }, { "code": null, "e": 29067, "s": 29052, "text": "Python-Quizzes" }, { "code": null, "e": 29165, "s": 29067, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29197, "s": 29165, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29239, "s": 29197, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29281, "s": 29239, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29337, "s": 29281, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29364, "s": 29337, "text": "Python Classes and Objects" }, { "code": null, "e": 29386, "s": 29364, "text": "Defaultdict in Python" }, { "code": null, "e": 29425, "s": 29386, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 29471, "s": 29425, "text": "Python | Split string into list of characters" }, { "code": null, "e": 29509, "s": 29471, "text": "Python | Convert a list to dictionary" } ]
Python SQLAlchemy - Group_by and return max date - GeeksforGeeks
22 Nov, 2021 In this article, we are going to see how to use Group_by and return max date SQLAlchemy in Python. SQLAlchemy is available via pip install package. pip install sqlalchemy However, if you are using flask you can make use of its own implementation of SQLAlchemy. It can be installed using – pip install flask-sqlalchemy Before we move ahead, we need to have a database and a table to work with. For this example, we are using mySQL database and have created a users table. The table has 6 columns and 7 records as shown below. Users Table – mySQL In the above table, we can see that there are 3 distinct users namely, John, Emma, and Liam. We will GROUP BY on the basis of their first_name and last_name. The table has a created_on field which is a TIMESTAMP data type. It will be used to pick the maximum date for a distinct user. First, we import the sqlalchemy library as db for simplicity. All the sqlalchemy objects, methods, etc will be imported using db prefix for better clarity.We then create the engine which will serve as a connection to the database to perform all the database operations.Create the metadata object. The metadata object `metadata` contains all the information about our database.Use the metadata information to fetch the users table from database.We can now write an SQLAlchemy query to fetch the required records. We perform GROUP BY operation on first_name and last_name fields and in the SELECT query retrieve the maximum date using the SQLalchemy’s `func.max()` function.Print all the fetched records. In the output we can view that we have only 3 distinct users and the corresponding updated_on field for all of the users is the maximum date that we have in the table entries. First, we import the sqlalchemy library as db for simplicity. All the sqlalchemy objects, methods, etc will be imported using db prefix for better clarity. We then create the engine which will serve as a connection to the database to perform all the database operations. Create the metadata object. The metadata object `metadata` contains all the information about our database. Use the metadata information to fetch the users table from database. We can now write an SQLAlchemy query to fetch the required records. We perform GROUP BY operation on first_name and last_name fields and in the SELECT query retrieve the maximum date using the SQLalchemy’s `func.max()` function. Print all the fetched records. In the output we can view that we have only 3 distinct users and the corresponding updated_on field for all of the users is the maximum date that we have in the table entries. Python import sqlalchemy as dbfrom sqlalchemy.engine import result # Define the Engine (Connection Object)engine = db.create_engine( "mysql+pymysql://root:password@localhost/Geeks4Geeks") # Create the Metadata Objectmeta_data = db.MetaData(bind=engine)db.MetaData.reflect(meta_data) # Get the `users` table from the Metadata objectUSERS = meta_data.tables['users'] # SQLAlchemy Query to GROUP BY and fetch MAX datequery = db.select([ USERS.c.email, USERS.c.first_name, USERS.c.last_name, db.func.max(USERS.c.created_on)]).group_by(USERS.c.first_name, USERS.c.last_name) # Fetch all the recordsresult = engine.execute(query).fetchall() # View the recordsfor record in result: print("\n", record) Output: Picked Python-SQLAlchemy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n22 Nov, 2021" }, { "code": null, "e": 25636, "s": 25537, "text": "In this article, we are going to see how to use Group_by and return max date SQLAlchemy in Python." }, { "code": null, "e": 25685, "s": 25636, "text": "SQLAlchemy is available via pip install package." }, { "code": null, "e": 25708, "s": 25685, "text": "pip install sqlalchemy" }, { "code": null, "e": 25826, "s": 25708, "text": "However, if you are using flask you can make use of its own implementation of SQLAlchemy. It can be installed using –" }, { "code": null, "e": 25855, "s": 25826, "text": "pip install flask-sqlalchemy" }, { "code": null, "e": 26062, "s": 25855, "text": "Before we move ahead, we need to have a database and a table to work with. For this example, we are using mySQL database and have created a users table. The table has 6 columns and 7 records as shown below." }, { "code": null, "e": 26082, "s": 26062, "text": "Users Table – mySQL" }, { "code": null, "e": 26367, "s": 26082, "text": "In the above table, we can see that there are 3 distinct users namely, John, Emma, and Liam. We will GROUP BY on the basis of their first_name and last_name. The table has a created_on field which is a TIMESTAMP data type. It will be used to pick the maximum date for a distinct user." }, { "code": null, "e": 27246, "s": 26367, "text": "First, we import the sqlalchemy library as db for simplicity. All the sqlalchemy objects, methods, etc will be imported using db prefix for better clarity.We then create the engine which will serve as a connection to the database to perform all the database operations.Create the metadata object. The metadata object `metadata` contains all the information about our database.Use the metadata information to fetch the users table from database.We can now write an SQLAlchemy query to fetch the required records. We perform GROUP BY operation on first_name and last_name fields and in the SELECT query retrieve the maximum date using the SQLalchemy’s `func.max()` function.Print all the fetched records. In the output we can view that we have only 3 distinct users and the corresponding updated_on field for all of the users is the maximum date that we have in the table entries." }, { "code": null, "e": 27402, "s": 27246, "text": "First, we import the sqlalchemy library as db for simplicity. All the sqlalchemy objects, methods, etc will be imported using db prefix for better clarity." }, { "code": null, "e": 27517, "s": 27402, "text": "We then create the engine which will serve as a connection to the database to perform all the database operations." }, { "code": null, "e": 27625, "s": 27517, "text": "Create the metadata object. The metadata object `metadata` contains all the information about our database." }, { "code": null, "e": 27694, "s": 27625, "text": "Use the metadata information to fetch the users table from database." }, { "code": null, "e": 27923, "s": 27694, "text": "We can now write an SQLAlchemy query to fetch the required records. We perform GROUP BY operation on first_name and last_name fields and in the SELECT query retrieve the maximum date using the SQLalchemy’s `func.max()` function." }, { "code": null, "e": 28130, "s": 27923, "text": "Print all the fetched records. In the output we can view that we have only 3 distinct users and the corresponding updated_on field for all of the users is the maximum date that we have in the table entries." }, { "code": null, "e": 28137, "s": 28130, "text": "Python" }, { "code": "import sqlalchemy as dbfrom sqlalchemy.engine import result # Define the Engine (Connection Object)engine = db.create_engine( \"mysql+pymysql://root:password@localhost/Geeks4Geeks\") # Create the Metadata Objectmeta_data = db.MetaData(bind=engine)db.MetaData.reflect(meta_data) # Get the `users` table from the Metadata objectUSERS = meta_data.tables['users'] # SQLAlchemy Query to GROUP BY and fetch MAX datequery = db.select([ USERS.c.email, USERS.c.first_name, USERS.c.last_name, db.func.max(USERS.c.created_on)]).group_by(USERS.c.first_name, USERS.c.last_name) # Fetch all the recordsresult = engine.execute(query).fetchall() # View the recordsfor record in result: print(\"\\n\", record)", "e": 28849, "s": 28137, "text": null }, { "code": null, "e": 28857, "s": 28849, "text": "Output:" }, { "code": null, "e": 28864, "s": 28857, "text": "Picked" }, { "code": null, "e": 28882, "s": 28864, "text": "Python-SQLAlchemy" }, { "code": null, "e": 28889, "s": 28882, "text": "Python" }, { "code": null, "e": 28987, "s": 28889, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29019, "s": 28987, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29061, "s": 29019, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29103, "s": 29061, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29159, "s": 29103, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29186, "s": 29159, "text": "Python Classes and Objects" }, { "code": null, "e": 29217, "s": 29186, "text": "Python | os.path.join() method" }, { "code": null, "e": 29256, "s": 29217, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29285, "s": 29256, "text": "Create a directory in Python" }, { "code": null, "e": 29307, "s": 29285, "text": "Defaultdict in Python" } ]
How to parse local HTML file in Python? - GeeksforGeeks
16 Mar, 2021 Prerequisites: Beautifulsoup Parsing means dividing a file or input into pieces of information/data that can be stored for our personal use in the future. Sometimes, we need data from an existing file stored on our computers, parsing technique can be used in such cases. The parsing includes multiple techniques used to extract data from a file. The following includes Modifying the file, Removing something from the file, Printing data, using the recursive child generator method to traverse data from the file, finding the children of tags, web scraping from a link to extract useful information, etc. Using the prettify method to modify the HTML code from- https://festive-knuth-1279a2.netlify.app/, look better. Prettify makes the code look in the standard form like the one used in VS Code. Example: Python3 # Importing BeautifulSoup class from the bs4 modulefrom bs4 import BeautifulSoup # Importing the HTTP libraryimport requests as req # Requesting for the websiteWeb = req.get('https://festive-knuth-1279a2.netlify.app/') # Creating a BeautifulSoup object and specifying the parserS = BeautifulSoup(Web.text, 'lxml') # Using the prettify methodprint(S.prettify()) Output: A tag can be removed by using the decompose method and the select_one method with the CSS selectors to select and then remove the second element from the li tag and then using the prettify method to modify the HTML code from the index.html file. Example: File Used: Python3 # Importing BeautifulSoup class from the bs4 modulefrom bs4 import BeautifulSoup # Opening the html fileHTMLFile = open("index.html", "r") # Reading the fileindex = HTMLFile.read() # Creating a BeautifulSoup object and specifying the parserS = BeautifulSoup(index, 'lxml') # Using the select-one method to find the second element from the li tagTag = S.select_one('li:nth-of-type(2)') # Using the decompose methodTag.decompose() # Using the prettify method to modify the codeprint(S.body.prettify()) Output: Tags can be found normally and printed normally using print(). Example: Python3 # Importing BeautifulSoup class from the bs4 modulefrom bs4 import BeautifulSoup # Opening the html fileHTMLFile = open("index.html", "r") # Reading the fileindex = HTMLFile.read() # Creating a BeautifulSoup object and specifying the parserParse = BeautifulSoup(index, 'lxml') # Printing html code of some tagsprint(Parse.head)print(Parse.h1)print(Parse.h2)print(Parse.h3)print(Parse.li) Output: The recursiveChildGenerator method is used to traverse tags, which recursively finds all the tags within tags from the file. Example: Python3 # Importing BeautifulSoup class from the bs4 modulefrom bs4 import BeautifulSoup # Opening the html fileHTMLFile = open("index.html", "r") # Reading the fileindex = HTMLFile.read() # Creating a BeautifulSoup object and specifying the parserS = BeautifulSoup(index, 'lxml') # Using the recursiveChildGenerator method to traverse the html filefor TraverseTags in S.recursiveChildGenerator(): # Traversing the names of the tags if TraverseTags.name: # Printing the names of the tags print(TraverseTags.name) Output: Using the name attribute of the tag to print its name and the text attribute to print its text along with the code of the tag- ul from the file. Example: Python3 # Importing BeautifulSoup class from the bs4 modulefrom bs4 import BeautifulSoup # Opening the html fileHTMLFile = open("index.html", "r") # Reading the fileindex = HTMLFile.read() # Creating a BeautifulSoup object and specifying the parserS = BeautifulSoup(index, 'lxml') # Printing the Code, name, and text of a tagprint(f'HTML: {S.ul}, name: {S.ul.name}, text: {S.ul.text}') Output: The Children attribute is used to get the children of a tag. The Children attribute returns ‘tags with spaces’ between them, we’re adding a condition- e. name is not None to print only names of the tags from the file. Example: Python3 # Importing BeautifulSoup class from the bs4 modulefrom bs4 import BeautifulSoup # Opening the html fileHTMLFile = open("index.html", "r") # Reading the fileindex = HTMLFile.read() # Creating a BeautifulSoup object and specifying the parserS = BeautifulSoup(index, 'lxml') # Providing the sourceAttr = S.html # Using the Children attribute to get the children of a tag# Only contain tag names and not the spacesAttr_Tag = [e.name for e in Attr.children if e.name is not None] # Printing the childrenprint(Attr_Tag) Output: Finding Children at all levels of a tag: The Descendants attribute is used to get all the descendants (Children at all levels) of a tag from the file. Example: Python3 # Importing BeautifulSoup class from the bs4 modulefrom bs4 import BeautifulSoup # Opening the html fileHTMLFile = open("index.html", "r") # Reading the fileindex = HTMLFile.read() # Creating a BeautifulSoup object and specifying the parserS = BeautifulSoup(index, 'lxml') # Providing the sourceDes = S.body # Using the descendants attributeAttr_Tag = [e.name for e in Des.descendants if e.name is not None] # Printing the childrenprint(Attr_Tag) Output: Using find_all(): The find_all method is used to find all the elements (name and text) inside the p tag from the file. Example: Python3 # Importing BeautifulSoup class from the bs4 modulefrom bs4 import BeautifulSoup # Opening the html fileHTMLFile = open("index.html", "r") # Reading the fileindex = HTMLFile.read() # Creating a BeautifulSoup object and specifying the parserS = BeautifulSoup(index, 'lxml') # Using the find_all method to find all elements of a tagfor tag in S.find_all('p'): # Printing the name, and text of p tag print(f'{tag.name}: {tag.text}') Output: CSS selectors to find elements: Using the select method to use the CSS selectors to find the second element from the li tag from the file. Example: Python3 # Importing BeautifulSoup class from the bs4 modulefrom bs4 import BeautifulSoup # Opening the html fileHTMLFile = open("index.html", "r") # Reading the fileindex = HTMLFile.read() # Creating a BeautifulSoup object and specifying the parserS = BeautifulSoup(index, 'lxml') # Using the select method# Prints the second element from the li tagprint(S.select('li:nth-of-type(2)')) Output: Picked Python BeautifulSoup Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n16 Mar, 2021" }, { "code": null, "e": 25566, "s": 25537, "text": "Prerequisites: Beautifulsoup" }, { "code": null, "e": 26141, "s": 25566, "text": "Parsing means dividing a file or input into pieces of information/data that can be stored for our personal use in the future. Sometimes, we need data from an existing file stored on our computers, parsing technique can be used in such cases. The parsing includes multiple techniques used to extract data from a file. The following includes Modifying the file, Removing something from the file, Printing data, using the recursive child generator method to traverse data from the file, finding the children of tags, web scraping from a link to extract useful information, etc." }, { "code": null, "e": 26333, "s": 26141, "text": "Using the prettify method to modify the HTML code from- https://festive-knuth-1279a2.netlify.app/, look better. Prettify makes the code look in the standard form like the one used in VS Code." }, { "code": null, "e": 26342, "s": 26333, "text": "Example:" }, { "code": null, "e": 26350, "s": 26342, "text": "Python3" }, { "code": "# Importing BeautifulSoup class from the bs4 modulefrom bs4 import BeautifulSoup # Importing the HTTP libraryimport requests as req # Requesting for the websiteWeb = req.get('https://festive-knuth-1279a2.netlify.app/') # Creating a BeautifulSoup object and specifying the parserS = BeautifulSoup(Web.text, 'lxml') # Using the prettify methodprint(S.prettify())", "e": 26715, "s": 26350, "text": null }, { "code": null, "e": 26723, "s": 26715, "text": "Output:" }, { "code": null, "e": 26969, "s": 26723, "text": "A tag can be removed by using the decompose method and the select_one method with the CSS selectors to select and then remove the second element from the li tag and then using the prettify method to modify the HTML code from the index.html file." }, { "code": null, "e": 26978, "s": 26969, "text": "Example:" }, { "code": null, "e": 26989, "s": 26978, "text": "File Used:" }, { "code": null, "e": 26997, "s": 26989, "text": "Python3" }, { "code": "# Importing BeautifulSoup class from the bs4 modulefrom bs4 import BeautifulSoup # Opening the html fileHTMLFile = open(\"index.html\", \"r\") # Reading the fileindex = HTMLFile.read() # Creating a BeautifulSoup object and specifying the parserS = BeautifulSoup(index, 'lxml') # Using the select-one method to find the second element from the li tagTag = S.select_one('li:nth-of-type(2)') # Using the decompose methodTag.decompose() # Using the prettify method to modify the codeprint(S.body.prettify())", "e": 27503, "s": 26997, "text": null }, { "code": null, "e": 27511, "s": 27503, "text": "Output:" }, { "code": null, "e": 27574, "s": 27511, "text": "Tags can be found normally and printed normally using print()." }, { "code": null, "e": 27583, "s": 27574, "text": "Example:" }, { "code": null, "e": 27591, "s": 27583, "text": "Python3" }, { "code": "# Importing BeautifulSoup class from the bs4 modulefrom bs4 import BeautifulSoup # Opening the html fileHTMLFile = open(\"index.html\", \"r\") # Reading the fileindex = HTMLFile.read() # Creating a BeautifulSoup object and specifying the parserParse = BeautifulSoup(index, 'lxml') # Printing html code of some tagsprint(Parse.head)print(Parse.h1)print(Parse.h2)print(Parse.h3)print(Parse.li)", "e": 27983, "s": 27591, "text": null }, { "code": null, "e": 27991, "s": 27983, "text": "Output:" }, { "code": null, "e": 28116, "s": 27991, "text": "The recursiveChildGenerator method is used to traverse tags, which recursively finds all the tags within tags from the file." }, { "code": null, "e": 28125, "s": 28116, "text": "Example:" }, { "code": null, "e": 28133, "s": 28125, "text": "Python3" }, { "code": "# Importing BeautifulSoup class from the bs4 modulefrom bs4 import BeautifulSoup # Opening the html fileHTMLFile = open(\"index.html\", \"r\") # Reading the fileindex = HTMLFile.read() # Creating a BeautifulSoup object and specifying the parserS = BeautifulSoup(index, 'lxml') # Using the recursiveChildGenerator method to traverse the html filefor TraverseTags in S.recursiveChildGenerator(): # Traversing the names of the tags if TraverseTags.name: # Printing the names of the tags print(TraverseTags.name)", "e": 28658, "s": 28133, "text": null }, { "code": null, "e": 28666, "s": 28658, "text": "Output:" }, { "code": null, "e": 28811, "s": 28666, "text": "Using the name attribute of the tag to print its name and the text attribute to print its text along with the code of the tag- ul from the file." }, { "code": null, "e": 28820, "s": 28811, "text": "Example:" }, { "code": null, "e": 28828, "s": 28820, "text": "Python3" }, { "code": "# Importing BeautifulSoup class from the bs4 modulefrom bs4 import BeautifulSoup # Opening the html fileHTMLFile = open(\"index.html\", \"r\") # Reading the fileindex = HTMLFile.read() # Creating a BeautifulSoup object and specifying the parserS = BeautifulSoup(index, 'lxml') # Printing the Code, name, and text of a tagprint(f'HTML: {S.ul}, name: {S.ul.name}, text: {S.ul.text}')", "e": 29210, "s": 28828, "text": null }, { "code": null, "e": 29218, "s": 29210, "text": "Output:" }, { "code": null, "e": 29436, "s": 29218, "text": "The Children attribute is used to get the children of a tag. The Children attribute returns ‘tags with spaces’ between them, we’re adding a condition- e. name is not None to print only names of the tags from the file." }, { "code": null, "e": 29445, "s": 29436, "text": "Example:" }, { "code": null, "e": 29453, "s": 29445, "text": "Python3" }, { "code": "# Importing BeautifulSoup class from the bs4 modulefrom bs4 import BeautifulSoup # Opening the html fileHTMLFile = open(\"index.html\", \"r\") # Reading the fileindex = HTMLFile.read() # Creating a BeautifulSoup object and specifying the parserS = BeautifulSoup(index, 'lxml') # Providing the sourceAttr = S.html # Using the Children attribute to get the children of a tag# Only contain tag names and not the spacesAttr_Tag = [e.name for e in Attr.children if e.name is not None] # Printing the childrenprint(Attr_Tag)", "e": 29974, "s": 29453, "text": null }, { "code": null, "e": 29982, "s": 29974, "text": "Output:" }, { "code": null, "e": 30023, "s": 29982, "text": "Finding Children at all levels of a tag:" }, { "code": null, "e": 30133, "s": 30023, "text": "The Descendants attribute is used to get all the descendants (Children at all levels) of a tag from the file." }, { "code": null, "e": 30142, "s": 30133, "text": "Example:" }, { "code": null, "e": 30150, "s": 30142, "text": "Python3" }, { "code": "# Importing BeautifulSoup class from the bs4 modulefrom bs4 import BeautifulSoup # Opening the html fileHTMLFile = open(\"index.html\", \"r\") # Reading the fileindex = HTMLFile.read() # Creating a BeautifulSoup object and specifying the parserS = BeautifulSoup(index, 'lxml') # Providing the sourceDes = S.body # Using the descendants attributeAttr_Tag = [e.name for e in Des.descendants if e.name is not None] # Printing the childrenprint(Attr_Tag)", "e": 30603, "s": 30150, "text": null }, { "code": null, "e": 30611, "s": 30603, "text": "Output:" }, { "code": null, "e": 30629, "s": 30611, "text": "Using find_all():" }, { "code": null, "e": 30730, "s": 30629, "text": "The find_all method is used to find all the elements (name and text) inside the p tag from the file." }, { "code": null, "e": 30739, "s": 30730, "text": "Example:" }, { "code": null, "e": 30747, "s": 30739, "text": "Python3" }, { "code": "# Importing BeautifulSoup class from the bs4 modulefrom bs4 import BeautifulSoup # Opening the html fileHTMLFile = open(\"index.html\", \"r\") # Reading the fileindex = HTMLFile.read() # Creating a BeautifulSoup object and specifying the parserS = BeautifulSoup(index, 'lxml') # Using the find_all method to find all elements of a tagfor tag in S.find_all('p'): # Printing the name, and text of p tag print(f'{tag.name}: {tag.text}')", "e": 31187, "s": 30747, "text": null }, { "code": null, "e": 31195, "s": 31187, "text": "Output:" }, { "code": null, "e": 31228, "s": 31195, "text": "CSS selectors to find elements: " }, { "code": null, "e": 31335, "s": 31228, "text": "Using the select method to use the CSS selectors to find the second element from the li tag from the file." }, { "code": null, "e": 31344, "s": 31335, "text": "Example:" }, { "code": null, "e": 31352, "s": 31344, "text": "Python3" }, { "code": "# Importing BeautifulSoup class from the bs4 modulefrom bs4 import BeautifulSoup # Opening the html fileHTMLFile = open(\"index.html\", \"r\") # Reading the fileindex = HTMLFile.read() # Creating a BeautifulSoup object and specifying the parserS = BeautifulSoup(index, 'lxml') # Using the select method# Prints the second element from the li tagprint(S.select('li:nth-of-type(2)'))", "e": 31734, "s": 31352, "text": null }, { "code": null, "e": 31742, "s": 31734, "text": "Output:" }, { "code": null, "e": 31749, "s": 31742, "text": "Picked" }, { "code": null, "e": 31770, "s": 31749, "text": "Python BeautifulSoup" }, { "code": null, "e": 31777, "s": 31770, "text": "Python" }, { "code": null, "e": 31875, "s": 31777, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31907, "s": 31875, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 31949, "s": 31907, "text": "Check if element exists in list in Python" }, { "code": null, "e": 31991, "s": 31949, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 32047, "s": 31991, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 32074, "s": 32047, "text": "Python Classes and Objects" }, { "code": null, "e": 32105, "s": 32074, "text": "Python | os.path.join() method" }, { "code": null, "e": 32144, "s": 32105, "text": "Python | Get unique values from a list" }, { "code": null, "e": 32173, "s": 32144, "text": "Create a directory in Python" }, { "code": null, "e": 32195, "s": 32173, "text": "Defaultdict in Python" } ]
Columnar Transposition Cipher - GeeksforGeeks
30 Aug, 2019 Given a plain-text message and a numeric key, cipher/de-cipher the given text using Columnar Transposition Cipher The Columnar Transposition Cipher is a form of transposition cipher just like Rail Fence Cipher. Columnar Transposition involves writing the plaintext out in rows, and then reading the ciphertext off in columns one by one. Examples: Encryption Input : Geeks for Geeks Key = HACK Output : e kefGsGsrekoe_ Decryption Input : e kefGsGsrekoe_ Key = HACK Output : Geeks for Geeks Encryption Input : Geeks on work Key = HACK Output : e w_eoo_Gs kknr_ Decryption Input : e w_eoo_Gs kknr_ Key = HACK Output : Geeks on work Encryption In a transposition cipher, the order of the alphabets is re-arranged to obtain the cipher-text. The message is written out in rows of a fixed length, and then read out again column by column, and the columns are chosen in some scrambled order.Width of the rows and the permutation of the columns are usually defined by a keyword.For example, the word HACK is of length 4 (so the rows are of length 4), and the permutation is defined by the alphabetical order of the letters in the keyword. In this case, the order would be “3 1 2 4”.Any spare spaces are filled with nulls or left blank or placed by a character (Example: _).Finally, the message is read off in columns, in the order specified by the keyword. The message is written out in rows of a fixed length, and then read out again column by column, and the columns are chosen in some scrambled order. Width of the rows and the permutation of the columns are usually defined by a keyword. For example, the word HACK is of length 4 (so the rows are of length 4), and the permutation is defined by the alphabetical order of the letters in the keyword. In this case, the order would be “3 1 2 4”. Any spare spaces are filled with nulls or left blank or placed by a character (Example: _). Finally, the message is read off in columns, in the order specified by the keyword. Decryption To decipher it, the recipient has to work out the column lengths by dividing the message length by the key length.Then, write the message out in columns again, then re-order the columns by reforming the key word.C++Python3C++// CPP program for illustrating// Columnar Transposition Cipher#include<bits/stdc++.h>using namespace std; // Key for Columnar Transpositionstring const key = "HACK"; map<int,int> keyMap; void setPermutationOrder(){ // Add the permutation order into map for(int i=0; i < key.length(); i++) { keyMap[key[i]] = i; }} // Encryption string encryptMessage(string msg){ int row,col,j; string cipher = ""; /* calculate column of the matrix*/ col = key.length(); /* calculate Maximum row of the matrix*/ row = msg.length()/col; if (msg.length() % col) row += 1; char matrix[row][col]; for (int i=0,k=0; i < row; i++) { for (int j=0; j<col; ) { if(msg[k] == '\0') { /* Adding the padding character '_' */ matrix[i][j] = '_'; j++; } if( isalpha(msg[k]) || msg[k]==' ') { /* Adding only space and alphabet into matrix*/ matrix[i][j] = msg[k]; j++; } k++; } } for (map<int,int>::iterator ii = keyMap.begin(); ii!=keyMap.end(); ++ii) { j=ii->second; // getting cipher text from matrix column wise using permuted key for (int i=0; i<row; i++) { if( isalpha(matrix[i][j]) || matrix[i][j]==' ' || matrix[i][j]=='_') cipher += matrix[i][j]; } } return cipher;} // Decryption string decryptMessage(string cipher){ /* calculate row and column for cipher Matrix */ int col = key.length(); int row = cipher.length()/col; char cipherMat[row][col]; /* add character into matrix column wise */ for (int j=0,k=0; j<col; j++) for (int i=0; i<row; i++) cipherMat[i][j] = cipher[k++]; /* update the order of key for decryption */ int index = 0; for( map<int,int>::iterator ii=keyMap.begin(); ii!=keyMap.end(); ++ii) ii->second = index++; /* Arrange the matrix column wise according to permutation order by adding into new matrix */ char decCipher[row][col]; map<int,int>::iterator ii=keyMap.begin(); int k = 0; for (int l=0,j; key[l]!='\0'; k++) { j = keyMap[key[l++]]; for (int i=0; i<row; i++) { decCipher[i][k]=cipherMat[i][j]; } } /* getting Message using matrix */ string msg = ""; for (int i=0; i<row; i++) { for(int j=0; j<col; j++) { if(decCipher[i][j] != '_') msg += decCipher[i][j]; } } return msg;} // Driver Programint main(void){ /* message */ string msg = "Geeks for Geeks"; setPermutationOrder(); // Calling encryption function string cipher = encryptMessage(msg); cout << "Encrypted Message: " << cipher << endl; // Calling Decryption function cout << "Decrypted Message: " << decryptMessage(cipher) << endl; return 0;}Python3# Python3 implementation of # Columnar Transpositionimport math key = "HACK" # Encryptiondef encryptMessage(msg): cipher = "" # track key indices k_indx = 0 msg_len = float(len(msg)) msg_lst = list(msg) key_lst = sorted(list(key)) # calculate column of the matrix col = len(key) # calculate maximum row of the matrix row = int(math.ceil(msg_len / col)) # add the padding character '_' in empty # the empty cell of the matix fill_null = int((row * col) - msg_len) msg_lst.extend('_' * fill_null) # create Matrix and insert message and # padding characters row-wise matrix = [msg_lst[i: i + col] for i in range(0, len(msg_lst), col)] # read matrix column-wise using key for _ in range(col): curr_idx = key.index(key_lst[k_indx]) cipher += ''.join([row[curr_idx] for row in matrix]) k_indx += 1 return cipher # Decryptiondef decryptMessage(cipher): msg = "" # track key indices k_indx = 0 # track msg indices msg_indx = 0 msg_len = float(len(cipher)) msg_lst = list(cipher) # calculate column of the matrix col = len(key) # calculate maximum row of the matrix row = int(math.ceil(msg_len / col)) # convert key into list and sort # alphabetically so we can access # each character by its alphabetical position. key_lst = sorted(list(key)) # create an empty matrix to # store deciphered message dec_cipher = [] for _ in range(row): dec_cipher += [[None] * col] # Arrange the matrix column wise according # to permutation order by adding into new matrix for _ in range(col): curr_idx = key.index(key_lst[k_indx]) for j in range(row): dec_cipher[j][curr_idx] = msg_lst[msg_indx] msg_indx += 1 k_indx += 1 # convert decrypted msg matrix into a string try: msg = ''.join(sum(dec_cipher, [])) except TypeError: raise TypeError("This program cannot", "handle repeating words.") null_count = msg.count('_') if null_count > 0: return msg[: -null_count] return msg # Driver Codemsg = "Geeks for Geeks" cipher = encryptMessage(msg)print("Encrypted Message: {}". format(cipher)) print("Decryped Message: {}". format(decryptMessage(cipher))) # This code is contributed by Aditya KOutput:Encrypted Message: e kefGsGsrekoe_ Decrypted Message: Geeks for Geeks Try it yourself: A double columnar transposition( It was used by the U.S. Army in World War I, and it is just a columnar transposition followed by another columnar transposition).This article is contributed by Yasin Zafar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes arrow_drop_upSave To decipher it, the recipient has to work out the column lengths by dividing the message length by the key length. Then, write the message out in columns again, then re-order the columns by reforming the key word.C++Python3C++// CPP program for illustrating// Columnar Transposition Cipher#include<bits/stdc++.h>using namespace std; // Key for Columnar Transpositionstring const key = "HACK"; map<int,int> keyMap; void setPermutationOrder(){ // Add the permutation order into map for(int i=0; i < key.length(); i++) { keyMap[key[i]] = i; }} // Encryption string encryptMessage(string msg){ int row,col,j; string cipher = ""; /* calculate column of the matrix*/ col = key.length(); /* calculate Maximum row of the matrix*/ row = msg.length()/col; if (msg.length() % col) row += 1; char matrix[row][col]; for (int i=0,k=0; i < row; i++) { for (int j=0; j<col; ) { if(msg[k] == '\0') { /* Adding the padding character '_' */ matrix[i][j] = '_'; j++; } if( isalpha(msg[k]) || msg[k]==' ') { /* Adding only space and alphabet into matrix*/ matrix[i][j] = msg[k]; j++; } k++; } } for (map<int,int>::iterator ii = keyMap.begin(); ii!=keyMap.end(); ++ii) { j=ii->second; // getting cipher text from matrix column wise using permuted key for (int i=0; i<row; i++) { if( isalpha(matrix[i][j]) || matrix[i][j]==' ' || matrix[i][j]=='_') cipher += matrix[i][j]; } } return cipher;} // Decryption string decryptMessage(string cipher){ /* calculate row and column for cipher Matrix */ int col = key.length(); int row = cipher.length()/col; char cipherMat[row][col]; /* add character into matrix column wise */ for (int j=0,k=0; j<col; j++) for (int i=0; i<row; i++) cipherMat[i][j] = cipher[k++]; /* update the order of key for decryption */ int index = 0; for( map<int,int>::iterator ii=keyMap.begin(); ii!=keyMap.end(); ++ii) ii->second = index++; /* Arrange the matrix column wise according to permutation order by adding into new matrix */ char decCipher[row][col]; map<int,int>::iterator ii=keyMap.begin(); int k = 0; for (int l=0,j; key[l]!='\0'; k++) { j = keyMap[key[l++]]; for (int i=0; i<row; i++) { decCipher[i][k]=cipherMat[i][j]; } } /* getting Message using matrix */ string msg = ""; for (int i=0; i<row; i++) { for(int j=0; j<col; j++) { if(decCipher[i][j] != '_') msg += decCipher[i][j]; } } return msg;} // Driver Programint main(void){ /* message */ string msg = "Geeks for Geeks"; setPermutationOrder(); // Calling encryption function string cipher = encryptMessage(msg); cout << "Encrypted Message: " << cipher << endl; // Calling Decryption function cout << "Decrypted Message: " << decryptMessage(cipher) << endl; return 0;}Python3# Python3 implementation of # Columnar Transpositionimport math key = "HACK" # Encryptiondef encryptMessage(msg): cipher = "" # track key indices k_indx = 0 msg_len = float(len(msg)) msg_lst = list(msg) key_lst = sorted(list(key)) # calculate column of the matrix col = len(key) # calculate maximum row of the matrix row = int(math.ceil(msg_len / col)) # add the padding character '_' in empty # the empty cell of the matix fill_null = int((row * col) - msg_len) msg_lst.extend('_' * fill_null) # create Matrix and insert message and # padding characters row-wise matrix = [msg_lst[i: i + col] for i in range(0, len(msg_lst), col)] # read matrix column-wise using key for _ in range(col): curr_idx = key.index(key_lst[k_indx]) cipher += ''.join([row[curr_idx] for row in matrix]) k_indx += 1 return cipher # Decryptiondef decryptMessage(cipher): msg = "" # track key indices k_indx = 0 # track msg indices msg_indx = 0 msg_len = float(len(cipher)) msg_lst = list(cipher) # calculate column of the matrix col = len(key) # calculate maximum row of the matrix row = int(math.ceil(msg_len / col)) # convert key into list and sort # alphabetically so we can access # each character by its alphabetical position. key_lst = sorted(list(key)) # create an empty matrix to # store deciphered message dec_cipher = [] for _ in range(row): dec_cipher += [[None] * col] # Arrange the matrix column wise according # to permutation order by adding into new matrix for _ in range(col): curr_idx = key.index(key_lst[k_indx]) for j in range(row): dec_cipher[j][curr_idx] = msg_lst[msg_indx] msg_indx += 1 k_indx += 1 # convert decrypted msg matrix into a string try: msg = ''.join(sum(dec_cipher, [])) except TypeError: raise TypeError("This program cannot", "handle repeating words.") null_count = msg.count('_') if null_count > 0: return msg[: -null_count] return msg # Driver Codemsg = "Geeks for Geeks" cipher = encryptMessage(msg)print("Encrypted Message: {}". format(cipher)) print("Decryped Message: {}". format(decryptMessage(cipher))) # This code is contributed by Aditya KOutput:Encrypted Message: e kefGsGsrekoe_ Decrypted Message: Geeks for Geeks Try it yourself: A double columnar transposition( It was used by the U.S. Army in World War I, and it is just a columnar transposition followed by another columnar transposition).This article is contributed by Yasin Zafar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes arrow_drop_upSave C++ Python3 // CPP program for illustrating// Columnar Transposition Cipher#include<bits/stdc++.h>using namespace std; // Key for Columnar Transpositionstring const key = "HACK"; map<int,int> keyMap; void setPermutationOrder(){ // Add the permutation order into map for(int i=0; i < key.length(); i++) { keyMap[key[i]] = i; }} // Encryption string encryptMessage(string msg){ int row,col,j; string cipher = ""; /* calculate column of the matrix*/ col = key.length(); /* calculate Maximum row of the matrix*/ row = msg.length()/col; if (msg.length() % col) row += 1; char matrix[row][col]; for (int i=0,k=0; i < row; i++) { for (int j=0; j<col; ) { if(msg[k] == '\0') { /* Adding the padding character '_' */ matrix[i][j] = '_'; j++; } if( isalpha(msg[k]) || msg[k]==' ') { /* Adding only space and alphabet into matrix*/ matrix[i][j] = msg[k]; j++; } k++; } } for (map<int,int>::iterator ii = keyMap.begin(); ii!=keyMap.end(); ++ii) { j=ii->second; // getting cipher text from matrix column wise using permuted key for (int i=0; i<row; i++) { if( isalpha(matrix[i][j]) || matrix[i][j]==' ' || matrix[i][j]=='_') cipher += matrix[i][j]; } } return cipher;} // Decryption string decryptMessage(string cipher){ /* calculate row and column for cipher Matrix */ int col = key.length(); int row = cipher.length()/col; char cipherMat[row][col]; /* add character into matrix column wise */ for (int j=0,k=0; j<col; j++) for (int i=0; i<row; i++) cipherMat[i][j] = cipher[k++]; /* update the order of key for decryption */ int index = 0; for( map<int,int>::iterator ii=keyMap.begin(); ii!=keyMap.end(); ++ii) ii->second = index++; /* Arrange the matrix column wise according to permutation order by adding into new matrix */ char decCipher[row][col]; map<int,int>::iterator ii=keyMap.begin(); int k = 0; for (int l=0,j; key[l]!='\0'; k++) { j = keyMap[key[l++]]; for (int i=0; i<row; i++) { decCipher[i][k]=cipherMat[i][j]; } } /* getting Message using matrix */ string msg = ""; for (int i=0; i<row; i++) { for(int j=0; j<col; j++) { if(decCipher[i][j] != '_') msg += decCipher[i][j]; } } return msg;} // Driver Programint main(void){ /* message */ string msg = "Geeks for Geeks"; setPermutationOrder(); // Calling encryption function string cipher = encryptMessage(msg); cout << "Encrypted Message: " << cipher << endl; // Calling Decryption function cout << "Decrypted Message: " << decryptMessage(cipher) << endl; return 0;} # Python3 implementation of # Columnar Transpositionimport math key = "HACK" # Encryptiondef encryptMessage(msg): cipher = "" # track key indices k_indx = 0 msg_len = float(len(msg)) msg_lst = list(msg) key_lst = sorted(list(key)) # calculate column of the matrix col = len(key) # calculate maximum row of the matrix row = int(math.ceil(msg_len / col)) # add the padding character '_' in empty # the empty cell of the matix fill_null = int((row * col) - msg_len) msg_lst.extend('_' * fill_null) # create Matrix and insert message and # padding characters row-wise matrix = [msg_lst[i: i + col] for i in range(0, len(msg_lst), col)] # read matrix column-wise using key for _ in range(col): curr_idx = key.index(key_lst[k_indx]) cipher += ''.join([row[curr_idx] for row in matrix]) k_indx += 1 return cipher # Decryptiondef decryptMessage(cipher): msg = "" # track key indices k_indx = 0 # track msg indices msg_indx = 0 msg_len = float(len(cipher)) msg_lst = list(cipher) # calculate column of the matrix col = len(key) # calculate maximum row of the matrix row = int(math.ceil(msg_len / col)) # convert key into list and sort # alphabetically so we can access # each character by its alphabetical position. key_lst = sorted(list(key)) # create an empty matrix to # store deciphered message dec_cipher = [] for _ in range(row): dec_cipher += [[None] * col] # Arrange the matrix column wise according # to permutation order by adding into new matrix for _ in range(col): curr_idx = key.index(key_lst[k_indx]) for j in range(row): dec_cipher[j][curr_idx] = msg_lst[msg_indx] msg_indx += 1 k_indx += 1 # convert decrypted msg matrix into a string try: msg = ''.join(sum(dec_cipher, [])) except TypeError: raise TypeError("This program cannot", "handle repeating words.") null_count = msg.count('_') if null_count > 0: return msg[: -null_count] return msg # Driver Codemsg = "Geeks for Geeks" cipher = encryptMessage(msg)print("Encrypted Message: {}". format(cipher)) print("Decryped Message: {}". format(decryptMessage(cipher))) # This code is contributed by Aditya K Encrypted Message: e kefGsGsrekoe_ Decrypted Message: Geeks for Geeks Try it yourself: A double columnar transposition( It was used by the U.S. Army in World War I, and it is just a columnar transposition followed by another columnar transposition). This article is contributed by Yasin Zafar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. lakshaygupta2807 AdiK cryptography Algorithms cryptography Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar Introduction to Algorithms How to Start Learning DSA? Recursive Practice Problems with Solutions Difference between NP hard and NP complete problem Converting Roman Numerals to Decimal lying between 1 to 3999 Quick Sort vs Merge Sort Difference between Algorithm, Pseudocode and Program Generate all permutation of a set in Python
[ { "code": null, "e": 25751, "s": 25723, "text": "\n30 Aug, 2019" }, { "code": null, "e": 25865, "s": 25751, "text": "Given a plain-text message and a numeric key, cipher/de-cipher the given text using Columnar Transposition Cipher" }, { "code": null, "e": 26088, "s": 25865, "text": "The Columnar Transposition Cipher is a form of transposition cipher just like Rail Fence Cipher. Columnar Transposition involves writing the plaintext out in rows, and then reading the ciphertext off in columns one by one." }, { "code": null, "e": 26098, "s": 26088, "text": "Examples:" }, { "code": null, "e": 26386, "s": 26098, "text": "Encryption\nInput : Geeks for Geeks\nKey = HACK\nOutput : e kefGsGsrekoe_\nDecryption\nInput : e kefGsGsrekoe_\nKey = HACK\nOutput : Geeks for Geeks \n\nEncryption\nInput : Geeks on work\nKey = HACK\nOutput : e w_eoo_Gs kknr_\nDecryption\nInput : e w_eoo_Gs kknr_\nKey = HACK\nOutput : Geeks on work\n" }, { "code": null, "e": 26397, "s": 26386, "text": "Encryption" }, { "code": null, "e": 26493, "s": 26397, "text": "In a transposition cipher, the order of the alphabets is re-arranged to obtain the cipher-text." }, { "code": null, "e": 27105, "s": 26493, "text": "The message is written out in rows of a fixed length, and then read out again column by column, and the columns are chosen in some scrambled order.Width of the rows and the permutation of the columns are usually defined by a keyword.For example, the word HACK is of length 4 (so the rows are of length 4), and the permutation is defined by the alphabetical order of the letters in the keyword. In this case, the order would be “3 1 2 4”.Any spare spaces are filled with nulls or left blank or placed by a character (Example: _).Finally, the message is read off in columns, in the order specified by the keyword." }, { "code": null, "e": 27253, "s": 27105, "text": "The message is written out in rows of a fixed length, and then read out again column by column, and the columns are chosen in some scrambled order." }, { "code": null, "e": 27340, "s": 27253, "text": "Width of the rows and the permutation of the columns are usually defined by a keyword." }, { "code": null, "e": 27545, "s": 27340, "text": "For example, the word HACK is of length 4 (so the rows are of length 4), and the permutation is defined by the alphabetical order of the letters in the keyword. In this case, the order would be “3 1 2 4”." }, { "code": null, "e": 27637, "s": 27545, "text": "Any spare spaces are filled with nulls or left blank or placed by a character (Example: _)." }, { "code": null, "e": 27721, "s": 27637, "text": "Finally, the message is read off in columns, in the order specified by the keyword." }, { "code": null, "e": 27732, "s": 27721, "text": "Decryption" }, { "code": null, "e": 34162, "s": 27732, "text": "To decipher it, the recipient has to work out the column lengths by dividing the message length by the key length.Then, write the message out in columns again, then re-order the columns by reforming the key word.C++Python3C++// CPP program for illustrating// Columnar Transposition Cipher#include<bits/stdc++.h>using namespace std; // Key for Columnar Transpositionstring const key = \"HACK\"; map<int,int> keyMap; void setPermutationOrder(){ // Add the permutation order into map for(int i=0; i < key.length(); i++) { keyMap[key[i]] = i; }} // Encryption string encryptMessage(string msg){ int row,col,j; string cipher = \"\"; /* calculate column of the matrix*/ col = key.length(); /* calculate Maximum row of the matrix*/ row = msg.length()/col; if (msg.length() % col) row += 1; char matrix[row][col]; for (int i=0,k=0; i < row; i++) { for (int j=0; j<col; ) { if(msg[k] == '\\0') { /* Adding the padding character '_' */ matrix[i][j] = '_'; j++; } if( isalpha(msg[k]) || msg[k]==' ') { /* Adding only space and alphabet into matrix*/ matrix[i][j] = msg[k]; j++; } k++; } } for (map<int,int>::iterator ii = keyMap.begin(); ii!=keyMap.end(); ++ii) { j=ii->second; // getting cipher text from matrix column wise using permuted key for (int i=0; i<row; i++) { if( isalpha(matrix[i][j]) || matrix[i][j]==' ' || matrix[i][j]=='_') cipher += matrix[i][j]; } } return cipher;} // Decryption string decryptMessage(string cipher){ /* calculate row and column for cipher Matrix */ int col = key.length(); int row = cipher.length()/col; char cipherMat[row][col]; /* add character into matrix column wise */ for (int j=0,k=0; j<col; j++) for (int i=0; i<row; i++) cipherMat[i][j] = cipher[k++]; /* update the order of key for decryption */ int index = 0; for( map<int,int>::iterator ii=keyMap.begin(); ii!=keyMap.end(); ++ii) ii->second = index++; /* Arrange the matrix column wise according to permutation order by adding into new matrix */ char decCipher[row][col]; map<int,int>::iterator ii=keyMap.begin(); int k = 0; for (int l=0,j; key[l]!='\\0'; k++) { j = keyMap[key[l++]]; for (int i=0; i<row; i++) { decCipher[i][k]=cipherMat[i][j]; } } /* getting Message using matrix */ string msg = \"\"; for (int i=0; i<row; i++) { for(int j=0; j<col; j++) { if(decCipher[i][j] != '_') msg += decCipher[i][j]; } } return msg;} // Driver Programint main(void){ /* message */ string msg = \"Geeks for Geeks\"; setPermutationOrder(); // Calling encryption function string cipher = encryptMessage(msg); cout << \"Encrypted Message: \" << cipher << endl; // Calling Decryption function cout << \"Decrypted Message: \" << decryptMessage(cipher) << endl; return 0;}Python3# Python3 implementation of # Columnar Transpositionimport math key = \"HACK\" # Encryptiondef encryptMessage(msg): cipher = \"\" # track key indices k_indx = 0 msg_len = float(len(msg)) msg_lst = list(msg) key_lst = sorted(list(key)) # calculate column of the matrix col = len(key) # calculate maximum row of the matrix row = int(math.ceil(msg_len / col)) # add the padding character '_' in empty # the empty cell of the matix fill_null = int((row * col) - msg_len) msg_lst.extend('_' * fill_null) # create Matrix and insert message and # padding characters row-wise matrix = [msg_lst[i: i + col] for i in range(0, len(msg_lst), col)] # read matrix column-wise using key for _ in range(col): curr_idx = key.index(key_lst[k_indx]) cipher += ''.join([row[curr_idx] for row in matrix]) k_indx += 1 return cipher # Decryptiondef decryptMessage(cipher): msg = \"\" # track key indices k_indx = 0 # track msg indices msg_indx = 0 msg_len = float(len(cipher)) msg_lst = list(cipher) # calculate column of the matrix col = len(key) # calculate maximum row of the matrix row = int(math.ceil(msg_len / col)) # convert key into list and sort # alphabetically so we can access # each character by its alphabetical position. key_lst = sorted(list(key)) # create an empty matrix to # store deciphered message dec_cipher = [] for _ in range(row): dec_cipher += [[None] * col] # Arrange the matrix column wise according # to permutation order by adding into new matrix for _ in range(col): curr_idx = key.index(key_lst[k_indx]) for j in range(row): dec_cipher[j][curr_idx] = msg_lst[msg_indx] msg_indx += 1 k_indx += 1 # convert decrypted msg matrix into a string try: msg = ''.join(sum(dec_cipher, [])) except TypeError: raise TypeError(\"This program cannot\", \"handle repeating words.\") null_count = msg.count('_') if null_count > 0: return msg[: -null_count] return msg # Driver Codemsg = \"Geeks for Geeks\" cipher = encryptMessage(msg)print(\"Encrypted Message: {}\". format(cipher)) print(\"Decryped Message: {}\". format(decryptMessage(cipher))) # This code is contributed by Aditya KOutput:Encrypted Message: e kefGsGsrekoe_\nDecrypted Message: Geeks for Geeks\nTry it yourself: A double columnar transposition( It was used by the U.S. Army in World War I, and it is just a columnar transposition followed by another columnar transposition).This article is contributed by Yasin Zafar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 34277, "s": 34162, "text": "To decipher it, the recipient has to work out the column lengths by dividing the message length by the key length." }, { "code": null, "e": 40593, "s": 34277, "text": "Then, write the message out in columns again, then re-order the columns by reforming the key word.C++Python3C++// CPP program for illustrating// Columnar Transposition Cipher#include<bits/stdc++.h>using namespace std; // Key for Columnar Transpositionstring const key = \"HACK\"; map<int,int> keyMap; void setPermutationOrder(){ // Add the permutation order into map for(int i=0; i < key.length(); i++) { keyMap[key[i]] = i; }} // Encryption string encryptMessage(string msg){ int row,col,j; string cipher = \"\"; /* calculate column of the matrix*/ col = key.length(); /* calculate Maximum row of the matrix*/ row = msg.length()/col; if (msg.length() % col) row += 1; char matrix[row][col]; for (int i=0,k=0; i < row; i++) { for (int j=0; j<col; ) { if(msg[k] == '\\0') { /* Adding the padding character '_' */ matrix[i][j] = '_'; j++; } if( isalpha(msg[k]) || msg[k]==' ') { /* Adding only space and alphabet into matrix*/ matrix[i][j] = msg[k]; j++; } k++; } } for (map<int,int>::iterator ii = keyMap.begin(); ii!=keyMap.end(); ++ii) { j=ii->second; // getting cipher text from matrix column wise using permuted key for (int i=0; i<row; i++) { if( isalpha(matrix[i][j]) || matrix[i][j]==' ' || matrix[i][j]=='_') cipher += matrix[i][j]; } } return cipher;} // Decryption string decryptMessage(string cipher){ /* calculate row and column for cipher Matrix */ int col = key.length(); int row = cipher.length()/col; char cipherMat[row][col]; /* add character into matrix column wise */ for (int j=0,k=0; j<col; j++) for (int i=0; i<row; i++) cipherMat[i][j] = cipher[k++]; /* update the order of key for decryption */ int index = 0; for( map<int,int>::iterator ii=keyMap.begin(); ii!=keyMap.end(); ++ii) ii->second = index++; /* Arrange the matrix column wise according to permutation order by adding into new matrix */ char decCipher[row][col]; map<int,int>::iterator ii=keyMap.begin(); int k = 0; for (int l=0,j; key[l]!='\\0'; k++) { j = keyMap[key[l++]]; for (int i=0; i<row; i++) { decCipher[i][k]=cipherMat[i][j]; } } /* getting Message using matrix */ string msg = \"\"; for (int i=0; i<row; i++) { for(int j=0; j<col; j++) { if(decCipher[i][j] != '_') msg += decCipher[i][j]; } } return msg;} // Driver Programint main(void){ /* message */ string msg = \"Geeks for Geeks\"; setPermutationOrder(); // Calling encryption function string cipher = encryptMessage(msg); cout << \"Encrypted Message: \" << cipher << endl; // Calling Decryption function cout << \"Decrypted Message: \" << decryptMessage(cipher) << endl; return 0;}Python3# Python3 implementation of # Columnar Transpositionimport math key = \"HACK\" # Encryptiondef encryptMessage(msg): cipher = \"\" # track key indices k_indx = 0 msg_len = float(len(msg)) msg_lst = list(msg) key_lst = sorted(list(key)) # calculate column of the matrix col = len(key) # calculate maximum row of the matrix row = int(math.ceil(msg_len / col)) # add the padding character '_' in empty # the empty cell of the matix fill_null = int((row * col) - msg_len) msg_lst.extend('_' * fill_null) # create Matrix and insert message and # padding characters row-wise matrix = [msg_lst[i: i + col] for i in range(0, len(msg_lst), col)] # read matrix column-wise using key for _ in range(col): curr_idx = key.index(key_lst[k_indx]) cipher += ''.join([row[curr_idx] for row in matrix]) k_indx += 1 return cipher # Decryptiondef decryptMessage(cipher): msg = \"\" # track key indices k_indx = 0 # track msg indices msg_indx = 0 msg_len = float(len(cipher)) msg_lst = list(cipher) # calculate column of the matrix col = len(key) # calculate maximum row of the matrix row = int(math.ceil(msg_len / col)) # convert key into list and sort # alphabetically so we can access # each character by its alphabetical position. key_lst = sorted(list(key)) # create an empty matrix to # store deciphered message dec_cipher = [] for _ in range(row): dec_cipher += [[None] * col] # Arrange the matrix column wise according # to permutation order by adding into new matrix for _ in range(col): curr_idx = key.index(key_lst[k_indx]) for j in range(row): dec_cipher[j][curr_idx] = msg_lst[msg_indx] msg_indx += 1 k_indx += 1 # convert decrypted msg matrix into a string try: msg = ''.join(sum(dec_cipher, [])) except TypeError: raise TypeError(\"This program cannot\", \"handle repeating words.\") null_count = msg.count('_') if null_count > 0: return msg[: -null_count] return msg # Driver Codemsg = \"Geeks for Geeks\" cipher = encryptMessage(msg)print(\"Encrypted Message: {}\". format(cipher)) print(\"Decryped Message: {}\". format(decryptMessage(cipher))) # This code is contributed by Aditya KOutput:Encrypted Message: e kefGsGsrekoe_\nDecrypted Message: Geeks for Geeks\nTry it yourself: A double columnar transposition( It was used by the U.S. Army in World War I, and it is just a columnar transposition followed by another columnar transposition).This article is contributed by Yasin Zafar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 40597, "s": 40593, "text": "C++" }, { "code": null, "e": 40605, "s": 40597, "text": "Python3" }, { "code": "// CPP program for illustrating// Columnar Transposition Cipher#include<bits/stdc++.h>using namespace std; // Key for Columnar Transpositionstring const key = \"HACK\"; map<int,int> keyMap; void setPermutationOrder(){ // Add the permutation order into map for(int i=0; i < key.length(); i++) { keyMap[key[i]] = i; }} // Encryption string encryptMessage(string msg){ int row,col,j; string cipher = \"\"; /* calculate column of the matrix*/ col = key.length(); /* calculate Maximum row of the matrix*/ row = msg.length()/col; if (msg.length() % col) row += 1; char matrix[row][col]; for (int i=0,k=0; i < row; i++) { for (int j=0; j<col; ) { if(msg[k] == '\\0') { /* Adding the padding character '_' */ matrix[i][j] = '_'; j++; } if( isalpha(msg[k]) || msg[k]==' ') { /* Adding only space and alphabet into matrix*/ matrix[i][j] = msg[k]; j++; } k++; } } for (map<int,int>::iterator ii = keyMap.begin(); ii!=keyMap.end(); ++ii) { j=ii->second; // getting cipher text from matrix column wise using permuted key for (int i=0; i<row; i++) { if( isalpha(matrix[i][j]) || matrix[i][j]==' ' || matrix[i][j]=='_') cipher += matrix[i][j]; } } return cipher;} // Decryption string decryptMessage(string cipher){ /* calculate row and column for cipher Matrix */ int col = key.length(); int row = cipher.length()/col; char cipherMat[row][col]; /* add character into matrix column wise */ for (int j=0,k=0; j<col; j++) for (int i=0; i<row; i++) cipherMat[i][j] = cipher[k++]; /* update the order of key for decryption */ int index = 0; for( map<int,int>::iterator ii=keyMap.begin(); ii!=keyMap.end(); ++ii) ii->second = index++; /* Arrange the matrix column wise according to permutation order by adding into new matrix */ char decCipher[row][col]; map<int,int>::iterator ii=keyMap.begin(); int k = 0; for (int l=0,j; key[l]!='\\0'; k++) { j = keyMap[key[l++]]; for (int i=0; i<row; i++) { decCipher[i][k]=cipherMat[i][j]; } } /* getting Message using matrix */ string msg = \"\"; for (int i=0; i<row; i++) { for(int j=0; j<col; j++) { if(decCipher[i][j] != '_') msg += decCipher[i][j]; } } return msg;} // Driver Programint main(void){ /* message */ string msg = \"Geeks for Geeks\"; setPermutationOrder(); // Calling encryption function string cipher = encryptMessage(msg); cout << \"Encrypted Message: \" << cipher << endl; // Calling Decryption function cout << \"Decrypted Message: \" << decryptMessage(cipher) << endl; return 0;}", "e": 43645, "s": 40605, "text": null }, { "code": "# Python3 implementation of # Columnar Transpositionimport math key = \"HACK\" # Encryptiondef encryptMessage(msg): cipher = \"\" # track key indices k_indx = 0 msg_len = float(len(msg)) msg_lst = list(msg) key_lst = sorted(list(key)) # calculate column of the matrix col = len(key) # calculate maximum row of the matrix row = int(math.ceil(msg_len / col)) # add the padding character '_' in empty # the empty cell of the matix fill_null = int((row * col) - msg_len) msg_lst.extend('_' * fill_null) # create Matrix and insert message and # padding characters row-wise matrix = [msg_lst[i: i + col] for i in range(0, len(msg_lst), col)] # read matrix column-wise using key for _ in range(col): curr_idx = key.index(key_lst[k_indx]) cipher += ''.join([row[curr_idx] for row in matrix]) k_indx += 1 return cipher # Decryptiondef decryptMessage(cipher): msg = \"\" # track key indices k_indx = 0 # track msg indices msg_indx = 0 msg_len = float(len(cipher)) msg_lst = list(cipher) # calculate column of the matrix col = len(key) # calculate maximum row of the matrix row = int(math.ceil(msg_len / col)) # convert key into list and sort # alphabetically so we can access # each character by its alphabetical position. key_lst = sorted(list(key)) # create an empty matrix to # store deciphered message dec_cipher = [] for _ in range(row): dec_cipher += [[None] * col] # Arrange the matrix column wise according # to permutation order by adding into new matrix for _ in range(col): curr_idx = key.index(key_lst[k_indx]) for j in range(row): dec_cipher[j][curr_idx] = msg_lst[msg_indx] msg_indx += 1 k_indx += 1 # convert decrypted msg matrix into a string try: msg = ''.join(sum(dec_cipher, [])) except TypeError: raise TypeError(\"This program cannot\", \"handle repeating words.\") null_count = msg.count('_') if null_count > 0: return msg[: -null_count] return msg # Driver Codemsg = \"Geeks for Geeks\" cipher = encryptMessage(msg)print(\"Encrypted Message: {}\". format(cipher)) print(\"Decryped Message: {}\". format(decryptMessage(cipher))) # This code is contributed by Aditya K", "e": 46090, "s": 43645, "text": null }, { "code": null, "e": 46162, "s": 46090, "text": "Encrypted Message: e kefGsGsrekoe_\nDecrypted Message: Geeks for Geeks\n" }, { "code": null, "e": 46342, "s": 46162, "text": "Try it yourself: A double columnar transposition( It was used by the U.S. Army in World War I, and it is just a columnar transposition followed by another columnar transposition)." }, { "code": null, "e": 46641, "s": 46342, "text": "This article is contributed by Yasin Zafar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 46766, "s": 46641, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 46783, "s": 46766, "text": "lakshaygupta2807" }, { "code": null, "e": 46788, "s": 46783, "text": "AdiK" }, { "code": null, "e": 46801, "s": 46788, "text": "cryptography" }, { "code": null, "e": 46812, "s": 46801, "text": "Algorithms" }, { "code": null, "e": 46825, "s": 46812, "text": "cryptography" }, { "code": null, "e": 46836, "s": 46825, "text": "Algorithms" }, { "code": null, "e": 46934, "s": 46836, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46983, "s": 46934, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 47008, "s": 46983, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 47035, "s": 47008, "text": "Introduction to Algorithms" }, { "code": null, "e": 47062, "s": 47035, "text": "How to Start Learning DSA?" }, { "code": null, "e": 47105, "s": 47062, "text": "Recursive Practice Problems with Solutions" }, { "code": null, "e": 47156, "s": 47105, "text": "Difference between NP hard and NP complete problem" }, { "code": null, "e": 47217, "s": 47156, "text": "Converting Roman Numerals to Decimal lying between 1 to 3999" }, { "code": null, "e": 47242, "s": 47217, "text": "Quick Sort vs Merge Sort" }, { "code": null, "e": 47295, "s": 47242, "text": "Difference between Algorithm, Pseudocode and Program" } ]
Finding a Non Transitive Co-prime Triplet in a Range - GeeksforGeeks
05 May, 2021 Given L and R, find a possible non-transitive triplet (a, b, c) such that pair (a, b) is co-prime and pair (b, c) is co-prime but (a, c) is not co-prime. Eg: (2, 5, 6) is a non-transitive triplet as pair (2, 5) is co-prime and pair (5, 6) is co-prime but pair (2, 6) is not co-prime. Examples: Input : L = 2, R = 10 Output : a = 4, b = 7, c = 8 is one such triplet Explanation (4, 7, 8) is a possible triplet (while there are other such triplets present in this range), Here, pair (4, 7) is co-prime and pair (7, 8) is co-prime but the pair (4, 8) is not co-primeInput : L = 21, R = 47 Output : a = 23, b = 25, c = 46 is one such triplet Explanation (23, 25, 46) is a possible triplet (while there are other such triplets present in this range), Here, pair (23, 25) is co-prime and pair (25, 46) is co-prime but the pair (23, 46) is not co-prime Method 1 (Brute Force) : We generate all possible Triplets between L and R and check if the property holds true that pair (a, b) is co-prime and pair (b, c) is co-prime but pair (a, c) isn’t. C++ Java Python3 C# PHP Javascript // C++ program to find possible non transitive triplets btw L and R#include <bits/stdc++.h>using namespace std; // Function to return gcd of a and bint gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // function to check for gcdbool coprime(int a, int b){ // a and b are coprime if their gcd is 1. return (gcd(a, b) == 1);} /* Checks if any possible triplet (a, b, c) satisfying the condition that (a, b) is coprime, (b, c) is coprime but (a, c) isnt */void possibleTripletInRange(int L, int R){ bool flag = false; int possibleA, possibleB, possibleC; // Generate and check for all possible triplets // between L and R for (int a = L; a <= R; a++) { for (int b = a + 1; b <= R; b++) { for (int c = b + 1; c <= R; c++) { // if we find any such triplets set flag to true if (coprime(a, b) && coprime(b, c) && !coprime(a, c)) { flag = true; possibleA = a; possibleB = b; possibleC = c; break; } } } } // flag = True indicates that a pair exists // between L and R if (flag == true) { cout << "(" << possibleA << ", " << possibleB << ", " << possibleC << ")" << " is one such possible triplet between " << L << " and " << R << "\n"; } else { cout << "No Such Triplet exists between " << L << " and " << R << "\n"; }} // Driver codeint main(){ int L, R; // finding possible Triplet between 2 and 10 L = 2; R = 10; possibleTripletInRange(L, R); // finding possible Triplet between 23 and 46 L = 23; R = 46; possibleTripletInRange(L, R); return 0;} // Java program to find possible non// transitive triplets btw L and Rclass GFG { // Function to return gcd of a and b static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // function to check for gcd static boolean coprime(int a, int b) { // a and b are coprime if their // gcd is 1. return (gcd(a, b) == 1); } // Checks if any possible triplet // (a, b, c) satifying the condition // that (a, b) is coprime, (b, c) is // coprime but (a, c) isnt */ static void possibleTripletInRange(int L, int R) { boolean flag = false; int possibleA = 0, possibleB = 0, possibleC = 0; // Generate and check for all possible // triplets between L and R for (int a = L; a <= R; a++) { for (int b = a + 1; b <= R; b++) { for (int c = b + 1; c <= R; c++) { // if we find any such triplets // set flag to true if (coprime(a, b) && coprime(b, c) && !coprime(a, c)) { flag = true; possibleA = a; possibleB = b; possibleC = c; break; } } } } // flag = True indicates that a pair exists // between L and R if (flag == true) { System.out.println("(" + possibleA + ", " + possibleB + ", " + possibleC + ")" + " is one such possible triplet " + "between " + L + " and " + R); } else { System.out.println("No Such Triplet exists" + "between " + L + " and " + R); } } // Driver code public static void main(String[] args) { int L, R; // finding possible Triplet between // 2 and 10 L = 2; R = 10; possibleTripletInRange(L, R); // finding possible Triplet between // 23 and 46 L = 23; R = 46; possibleTripletInRange(L, R); }} // This code is contributed by// Smitha DInesh Semwal # Python3 program to find possible non# transitive triplets btw L and R # Function to return gcd of a and bdef gcd(a, b): if (a == 0): return b; return gcd(b % a, a); # function to check for gcddef coprime(a, b): # a and b are coprime if # their gcd is 1. return (gcd(a, b) == 1); # Checks if any possible triplet# (a, b, c) satifying the condition# that (a, b) is coprime, (b, c)# is coprime but (a, c) isntdef possibleTripletInRange(L, R): flag = False; possibleA = 0; possibleB = 0; possibleC = 0; # Generate and check for all # possible triplets between L and R for a in range(L, R + 1): for b in range(a + 1, R + 1): for c in range(b + 1, R + 1): # if we find any such triplets # set flag to true if (coprime(a, b) and coprime(b, c) and coprime(a, c) == False): flag = True; possibleA = a; possibleB = b; possibleC = c; break; # flag = True indicates that a # pair exists between L and R if (flag == True): print("(", possibleA, ",", possibleB, ",", possibleC, ") is one such", "possible triplet between", L, "and", R); else: print("No Such Triplet exists between", L, "and", R); # Driver Code # finding possible Triplet# between 2 and 10L = 2;R = 10;possibleTripletInRange(L, R); # finding possible Triplet# between 23 and 46L = 23;R = 46;possibleTripletInRange(L, R); # This code is contributed by mits // C# program to find possible// non transitive triplets// btw L and Rusing System;class GFG{ // Function to return // gcd of a and b static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // function to // check for gcd static bool coprime(int a, int b) { // a and b are coprime // if their gcd is 1. return (gcd(a, b) == 1); } // Checks if any possible // triplet (a, b, c) satifying // the condition that (a, b) // is coprime, (b, c) is // coprime but (a, c) isnt */ static void possibleTripletInRange(int L, int R) { bool flag = false; int possibleA = 0, possibleB = 0, possibleC = 0; // Generate and check for // all possible triplets // between L and R for (int a = L; a <= R; a++) { for (int b = a + 1; b <= R; b++) { for (int c = b + 1; c <= R; c++) { // if we find any // such triplets // set flag to true if (coprime(a, b) && coprime(b, c) && !coprime(a, c)) { flag = true; possibleA = a; possibleB = b; possibleC = c; break; } } } } // flag = True indicates // that a pair exists // between L and R if (flag == true) { Console.WriteLine("(" + possibleA + ", " + possibleB + ", " + possibleC + ")" + " is one such possible triplet " + "between " + L + " and " + R); } else { Console.WriteLine("No Such Triplet exists" + "between " + L + " and " + R); } } // Driver code public static void Main() { int L, R; // finding possible // Triplet between // 2 and 10 L = 2; R = 10; possibleTripletInRange(L, R); // finding possible // Triplet between // 23 and 46 L = 23; R = 46; possibleTripletInRange(L, R); }} // This code is contributed// by anuj_67. <?php// PHP program to find possible non// transitive triplets btw L and R // Function to return gcd of a and bfunction gcd($a, $b){ if ($a == 0) return $b; return gcd($b % $a, $a);} // function to check for gcdfunction coprime($a, $b){ // a and b are coprime if // their gcd is 1. return (gcd($a, $b) == 1);} /* Checks if any possible triplet (a, b, c) satifying the condition that (a, b) is coprime, (b, c) is coprime but (a, c) isnt */function possibleTripletInRange($L, $R){ $flag = false; $possibleA; $possibleB; $possibleC; // Generate and check for all // possible triplets between L and R for ($a = $L; $a <= $R; $a++) { for ($b = $a + 1; $b <= $R; $b++) { for ( $c = $b + 1; $c <= $R; $c++) { // if we find any such triplets // set flag to true if (coprime($a, $b) && coprime($b, $c) && !coprime($a, $c)) { $flag = true; $possibleA = $a; $possibleB = $b; $possibleC = $c; break; } } } } // flag = True indicates that a // pair exists between L and R if ($flag == true) { echo "(" ,$possibleA , ", " , $possibleB, ", " , $possibleC , ")", " is one such possible triplet between ", $L , " and " , $R , "\n"; } else { echo "No Such Triplet exists between ", $L , " and " , $R , "\n"; }} // Driver Code$L;$R; // finding possible Triplet// between 2 and 10$L = 2;$R = 10;possibleTripletInRange($L, $R); // finding possible Triplet// between 23 and 46$L = 23;$R = 46;possibleTripletInRange($L, $R); // This code is contributed by jit_t?> <script> // Javascript program to find possible // non transitive triplets // btw L and R // Function to return // gcd of a and b function gcd(a, b) { if (a == 0) return b; return gcd(b % a, a); } // function to // check for gcd function coprime(a, b) { // a and b are coprime // if their gcd is 1. return (gcd(a, b) == 1); } // Checks if any possible // triplet (a, b, c) satifying // the condition that (a, b) // is coprime, (b, c) is // coprime but (a, c) isnt */ function possibleTripletInRange(L, R) { let flag = false; let possibleA = 0, possibleB = 0, possibleC = 0; // Generate and check for // all possible triplets // between L and R for (let a = L; a <= R; a++) { for (let b = a + 1; b <= R; b++) { for (let c = b + 1; c <= R; c++) { // if we find any // such triplets // set flag to true if (coprime(a, b) && coprime(b, c) && !coprime(a, c)) { flag = true; possibleA = a; possibleB = b; possibleC = c; break; } } } } // flag = True indicates // that a pair exists // between L and R if (flag == true) { document.write("(" + possibleA + ", " + possibleB + ", " + possibleC + ")" + " is one such possible triplet " + "between " + L + " and " + R + "</br>"); } else { document.write("No Such Triplet exists" + "between " + L + " and " + R + "</br>"); } } let L, R; // finding possible // Triplet between // 2 and 10 L = 2; R = 10; possibleTripletInRange(L, R); // finding possible // Triplet between // 23 and 46 L = 23; R = 46; possibleTripletInRange(L, R); </script> Output: (8, 9, 10) is one such possible triplet between 2 and 10 (44, 45, 46) is one such possible triplet between 23 and 46 The time Complexity of the Brute Force Solution is O(n3log(A)) where A is the smallest number of the triplet. Note: The log factor of the complexity is that of computing the GCD for a pair of numbers. Method 2 (efficient): Since we need only one such possible pair, we can use this to break down our complexity further.We just need to identify some cases and look to solve those to solve this problem.Case 1: There are less than 3 numbers between L and R. This Case is easy, we can’t form any triplets, so the answer is this case would always be ‘Not Possible’Case 2: There are more than three numbers between L and R. Now, It’s well-known proof that consecutive numbers are always co-prime. We can even prove this easily. Proof: Given that N and N + 1 are two consecutive integers. Now suppose gcd(n, n + 1) = X, ? X divides n and X also divides (n + 1). Which implies that X divides ((n + 1) - n) or X divides 1. But, There is no number which divides 1 except 1. ? X = 1, or we can also say that gcd(n, n + 1) = 1 Thus, n and n + 1 are coprime. So, if we take three consecutive numbers of the form 2k, 2k + 1, 2k + 2 we would always end up having a possible triplet because as proved above, pairs (2k, 2k + 1) and (2k + 1, 2k + 2) being pairs of consecutive numbers are co-prime and the pair (2k, 2k+2) have their gcd as 2 (since they are even).Case 3: When there are exactly 3 numbers between L and R This is an extension of case 3, now this case can have 2 cases,Case 3.1 When the three numbers are of the form 2k, 2k + 1, 2k + 2 We have already looked at this case in case 2. So this is the only triplet and also is a valid triplet between L and R.Case 3.2 When the three numbers are of the form 2k – 1, 2k, 2k + 1 We have already seen that (2k – 1, 2k) and (2k, 2k + 1) being a pair of consecutive numbers are co-prime pairs, so we need to check if the pair (2k – 1, 2k + 1) is co-prime or not It can be proved that the pair (2k – 1, 2k + 1) is always co-prime as shown below Proof: Given that 2k - 1 and 2k + 1 are two numbers Now suppose gcd((2k - 1), (2k + 1)) = X, ? X divides (2k - 1) and X also divides (2k + 1). Which implies that X divides ((2k + 1) - (2k - 1)) or X divides 2. 2 being a prime is only divisible by 1 and 2 itself. But, 2k - 1 and 2k + 1 are odd numbers so X can never be equal to 2. ? X = 1, or we can also say that gcd((2k -1), (2k + 1)) = 1 Thus, 2k - 1 and 2k + 1 are coprime. Thus, in this case, we won’t be able to find any possible valid triplet.Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript /* C++ program to find a non transitive co-prime triplets between L and R */#include <bits/stdc++.h>using namespace std; /* Checks if any possible triplet (a, b, c) satisfying the condition that (a, b) is coprime, (b, c) is coprime but (a, c) isnt */ void possibleTripletInRange(int L, int R){ bool flag = false; int possibleA, possibleB, possibleC; int numbersInRange = (R - L + 1); /* Case 1 : Less than 3 numbers between L and R */ if (numbersInRange < 3) { flag = false; } /* Case 2: More than 3 numbers between L and R */ else if (numbersInRange > 3) { flag = true; // triplets should always be of form (2k, 2k + 1, 2k + 2) if (L % 2) { L++; } possibleA = L; possibleB = L + 1; possibleC = L + 2; } else { /* Case 3.1: Exactly 3 numbers in range of form (2k, 2k + 1, 2k + 2) */ if (!(L % 2)) { flag = true; possibleA = L; possibleB = L + 1; possibleC = L + 2; } else { /* Case 3.2: Exactly 3 numbers in range of form (2k - 1, 2k, 2k + 1) */ flag = false; } } // flag = True indicates that a pair exists between L and R if (flag == true) { cout << "(" << possibleA << ", " << possibleB << ", " << possibleC << ")" << " is one such possible triplet between " << L << " and " << R << "\n"; } else { cout << "No Such Triplet exists between " << L << " and " << R << "\n"; }} // Driver codeint main(){ int L, R; // finding possible Triplet between 2 and 10 L = 2; R = 10; possibleTripletInRange(L, R); // finding possible Triplet between 23 and 46 L = 23; R = 46; possibleTripletInRange(L, R); return 0;} // Java program to find a// non transitive co-prime// triplets between L and Rimport java.io.*; class GFG{ // Checks if any possible triplet// (a, b, c) satifying the condition// that (a, b) is coprime, (b, c)// is coprime but (a, c) isntstatic void possibleTripletInRange(int L, int R){ boolean flag = false; int possibleA = 0, possibleB = 0, possibleC = 0; int numbersInRange = (R - L + 1); // Case 1 : Less than 3 // numbers between L and R if (numbersInRange < 3) { flag = false; } // Case 2: More than 3 // numbers between L and R else if (numbersInRange > 3) { flag = true; // triplets should always // be of form (2k, 2k + 1, // 2k + 2) if (L % 2 > 0) { L++; } possibleA = L; possibleB = L + 1; possibleC = L + 2; } else { /* Case 3.1: Exactly 3 numbers in range of form (2k, 2k + 1, 2k + 2) */ if (!(L % 2 > 0)) { flag = true; possibleA = L; possibleB = L + 1; possibleC = L + 2; } else { /* Case 3.2: Exactly 3 numbers in range of form (2k - 1, 2k, 2k + 1) */ flag = false; } } // flag = True indicates // that a pair exists // between L and R if (flag == true) { System.out.println("(" + possibleA + ", " + possibleB + ", " + possibleC + ")" + " is one such possible" + " triplet between " + L + " and " + R ); } else { System.out.println("No Such Triplet" + " exists between " + L + " and " + R); }} // Driver codepublic static void main (String[] args){int L, R; // finding possible Triplet// between 2 and 10L = 2;R = 10;possibleTripletInRange(L, R); // finding possible Triplet// between 23 and 46L = 23;R = 46;possibleTripletInRange(L, R);}} // This code is contributed// by anuj_67. # Python3 program to find a non transitive# co-prime triplets between L and R # Checks if any possible triplet (a, b, c)# satifying the condition that (a, b) is# coprime, (b, c) is coprime but (a, c) isntdef possibleTripletInRange(L, R): flag = False; possibleA = 0; possibleB = 0; possibleC = 0; numbersInRange = (R - L + 1); # Case 1 : Less than 3 numbers # between L and R if (numbersInRange < 3): flag = False; # Case 2: More than 3 numbers # between L and R elif (numbersInRange > 3): flag = True; # triplets should always be of # form (2k, 2k + 1, 2k + 2) if ((L % 2) > 0): L += 1; possibleA = L; possibleB = L + 1; possibleC = L + 2; else: # Case 3.1: Exactly 3 numbers in range # of form (2k, 2k + 1, 2k + 2) if ((L % 2) == 0): flag = True; possibleA = L; possibleB = L + 1; possibleC = L + 2; else: # Case 3.2: Exactly 3 numbers in range # of form (2k - 1, 2k, 2k + 1) flag = False; # flag = True indicates that a pair # exists between L and R if (flag == True): print("(", possibleA, ",", possibleB, ",", possibleC, ") is one such", "possible triplet between", L, "and", R); else: print("No Such Triplet exists between", L, "and", R); # Driver code # finding possible Triplet# between 2 and 10L = 2;R = 10;possibleTripletInRange(L, R); # finding possible Triplet# between 23 and 46L = 23;R = 46;possibleTripletInRange(L, R); # This code is contributed by mits // C# program to find a// non transitive co-prime// triplets between L and Rusing System; public class GFG{ // Checks if any possible triplet// (a, b, c) satifying the condition// that (a, b) is coprime, (b, c)// is coprime but (a, c) isntstatic void possibleTripletInRange(int L, int R){ bool flag = false; int possibleA = 0, possibleB = 0, possibleC = 0; int numbersInRange = (R - L + 1); // Case 1 : Less than 3 // numbers between L and R if (numbersInRange < 3) { flag = false; } // Case 2: More than 3 // numbers between L and R else if (numbersInRange > 3) { flag = true; // triplets should always // be of form (2k, 2k + 1, // 2k + 2) if (L % 2 > 0) { L++; } possibleA = L; possibleB = L + 1; possibleC = L + 2; } else { /* Case 3.1: Exactly 3 numbers in range of form (2k, 2k + 1, 2k + 2) */ if (!(L % 2 > 0)) { flag = true; possibleA = L; possibleB = L + 1; possibleC = L + 2; } else { /* Case 3.2: Exactly 3 numbers in range of form (2k - 1, 2k, 2k + 1) */ flag = false; } } // flag = True indicates // that a pair exists // between L and R if (flag == true) { Console.WriteLine("(" + possibleA + ", " + possibleB + ", " + possibleC + ")" + " is one such possible" + " triplet between " + L + " and " + R ); } else { Console.WriteLine("No Such Triplet" + " exists between " + L + " and " + R); }} // Driver code static public void Main (){ int L, R; // finding possible Triplet // between 2 and 10 L = 2; R = 10; possibleTripletInRange(L, R); // finding possible Triplet // between 23 and 46 L = 23; R = 46; possibleTripletInRange(L, R); }}// This code is contributed by ajit <?php// PHP program to find possible// non transitive triplets// btw L and Rfunction gcd($a, $b){ if ($a == 0) return $b; return gcd($b % $a, $a);} // function to check for gcdfunction coprime($a, $b){ // a and b are coprime // if their gcd is 1. return (gcd($a, $b) == 1);} /* Checks if any possible triplet(a, b, c) satifying the conditionthat (a, b) is coprime, (b, c) iscoprime but (a, c) isnt */function possibleTripletInRange($L, $R){ $flag = false; $possibleA; $possibleB; $possibleC; // Generate and check for // all possible triplets // between L and R for ($a = $L; $a <= $R; $a++) { for ($b = $a + 1; $b <= $R; $b++) { for ($c = $b + 1; $c <= $R; $c++) { // if we find any such // triplets set flag to true if (coprime($a, $b) && coprime($b, $c) && !coprime($a, $c)) { $flag = true; $possibleA = $a; $possibleB = $b; $possibleC = $c; break; } } } } // flag = True indicates // that a pair exists // between L and R if ($flag == true) { echo "(" , $possibleA , ", " , $possibleB , ", " , $possibleC , ")" , " is one such possible ", "triplet between " , $L , " and " , $R , "\n"; } else { echo "No Such Triplet exists between ", $L , " and " , $R , "\n"; }} // Driver code // finding possible Triplet// between 2 and 10$L = 2;$R = 10;possibleTripletInRange($L, $R); // finding possible Triplet// between 23 and 46$L = 23;$R = 46;possibleTripletInRange($L, $R); // This code is contributed// by Akanksha Rai(Abby_akku) <script> /* Javascript program to find a non transitive co-prime triplets between L and R */ /* Checks if any possible triplet (a, b, c) satisfying the condition that (a, b) is coprime, (b, c) is coprime but (a, c) isnt */ function possibleTripletInRange(L, R) { let flag = false; let possibleA, possibleB, possibleC; let numbersInRange = (R - L + 1); /* Case 1 : Less than 3 numbers between L and R */ if (numbersInRange < 3) { flag = false; } /* Case 2: More than 3 numbers between L and R */ else if (numbersInRange > 3) { flag = true; // triplets should always be of form (2k, 2k + 1, 2k + 2) if (L % 2) { L++; } possibleA = L; possibleB = L + 1; possibleC = L + 2; } else { /* Case 3.1: Exactly 3 numbers in range of form (2k, 2k + 1, 2k + 2) */ if (!(L % 2)) { flag = true; possibleA = L; possibleB = L + 1; possibleC = L + 2; } else { /* Case 3.2: Exactly 3 numbers in range of form (2k - 1, 2k, 2k + 1) */ flag = false; } } // flag = True indicates that a pair exists between L and R if (flag == true) { document.write("(" + possibleA + ", " + possibleB + ", " + possibleC + ")" + " is one such possible triplet between " + L + " and " + R + "</br>"); } else { document.write("No Such Triplet exists between " + L + " and " + R + "</br>"); } } let L, R; // finding possible Triplet between 2 and 10 L = 2; R = 10; possibleTripletInRange(L, R); // finding possible Triplet between 23 and 46 L = 23; R = 46; possibleTripletInRange(L, R); </script> Output: (2, 3, 4) is one such possible triplet between 2 and 10 (24, 25, 26) is one such possible triplet between 24 and 46 The time complexity of this method is O(1). Smitha Dinesh Semwal vt_m Akanksha_Rai jit_t Mithun Kumar ManasChhabra2 mukesh07 divyeshrabadiya07 GCD-LCM number-theory Prime Number Mathematical Technical Scripter number-theory Mathematical Prime Number Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Segment Tree | Set 1 (Sum of given range) Product of Array except itself Program to multiply two matrices Singular Value Decomposition (SVD) Generate all permutation of a set in Python Fizz Buzz Implementation Program to print prime numbers from 1 to N. Shortest path in a Binary Maze Expression Evaluation Josephus problem | Set 1 (A O(n) Solution)
[ { "code": null, "e": 25963, "s": 25935, "text": "\n05 May, 2021" }, { "code": null, "e": 26247, "s": 25963, "text": "Given L and R, find a possible non-transitive triplet (a, b, c) such that pair (a, b) is co-prime and pair (b, c) is co-prime but (a, c) is not co-prime. Eg: (2, 5, 6) is a non-transitive triplet as pair (2, 5) is co-prime and pair (5, 6) is co-prime but pair (2, 6) is not co-prime." }, { "code": null, "e": 26259, "s": 26247, "text": "Examples: " }, { "code": null, "e": 26812, "s": 26259, "text": "Input : L = 2, R = 10 Output : a = 4, b = 7, c = 8 is one such triplet Explanation (4, 7, 8) is a possible triplet (while there are other such triplets present in this range), Here, pair (4, 7) is co-prime and pair (7, 8) is co-prime but the pair (4, 8) is not co-primeInput : L = 21, R = 47 Output : a = 23, b = 25, c = 46 is one such triplet Explanation (23, 25, 46) is a possible triplet (while there are other such triplets present in this range), Here, pair (23, 25) is co-prime and pair (25, 46) is co-prime but the pair (23, 46) is not co-prime " }, { "code": null, "e": 26907, "s": 26812, "text": " Method 1 (Brute Force) :" }, { "code": null, "e": 27076, "s": 26907, "text": "We generate all possible Triplets between L and R and check if the property holds true that pair (a, b) is co-prime and pair (b, c) is co-prime but pair (a, c) isn’t. " }, { "code": null, "e": 27080, "s": 27076, "text": "C++" }, { "code": null, "e": 27085, "s": 27080, "text": "Java" }, { "code": null, "e": 27093, "s": 27085, "text": "Python3" }, { "code": null, "e": 27096, "s": 27093, "text": "C#" }, { "code": null, "e": 27100, "s": 27096, "text": "PHP" }, { "code": null, "e": 27111, "s": 27100, "text": "Javascript" }, { "code": "// C++ program to find possible non transitive triplets btw L and R#include <bits/stdc++.h>using namespace std; // Function to return gcd of a and bint gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // function to check for gcdbool coprime(int a, int b){ // a and b are coprime if their gcd is 1. return (gcd(a, b) == 1);} /* Checks if any possible triplet (a, b, c) satisfying the condition that (a, b) is coprime, (b, c) is coprime but (a, c) isnt */void possibleTripletInRange(int L, int R){ bool flag = false; int possibleA, possibleB, possibleC; // Generate and check for all possible triplets // between L and R for (int a = L; a <= R; a++) { for (int b = a + 1; b <= R; b++) { for (int c = b + 1; c <= R; c++) { // if we find any such triplets set flag to true if (coprime(a, b) && coprime(b, c) && !coprime(a, c)) { flag = true; possibleA = a; possibleB = b; possibleC = c; break; } } } } // flag = True indicates that a pair exists // between L and R if (flag == true) { cout << \"(\" << possibleA << \", \" << possibleB << \", \" << possibleC << \")\" << \" is one such possible triplet between \" << L << \" and \" << R << \"\\n\"; } else { cout << \"No Such Triplet exists between \" << L << \" and \" << R << \"\\n\"; }} // Driver codeint main(){ int L, R; // finding possible Triplet between 2 and 10 L = 2; R = 10; possibleTripletInRange(L, R); // finding possible Triplet between 23 and 46 L = 23; R = 46; possibleTripletInRange(L, R); return 0;}", "e": 28901, "s": 27111, "text": null }, { "code": "// Java program to find possible non// transitive triplets btw L and Rclass GFG { // Function to return gcd of a and b static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // function to check for gcd static boolean coprime(int a, int b) { // a and b are coprime if their // gcd is 1. return (gcd(a, b) == 1); } // Checks if any possible triplet // (a, b, c) satifying the condition // that (a, b) is coprime, (b, c) is // coprime but (a, c) isnt */ static void possibleTripletInRange(int L, int R) { boolean flag = false; int possibleA = 0, possibleB = 0, possibleC = 0; // Generate and check for all possible // triplets between L and R for (int a = L; a <= R; a++) { for (int b = a + 1; b <= R; b++) { for (int c = b + 1; c <= R; c++) { // if we find any such triplets // set flag to true if (coprime(a, b) && coprime(b, c) && !coprime(a, c)) { flag = true; possibleA = a; possibleB = b; possibleC = c; break; } } } } // flag = True indicates that a pair exists // between L and R if (flag == true) { System.out.println(\"(\" + possibleA + \", \" + possibleB + \", \" + possibleC + \")\" + \" is one such possible triplet \" + \"between \" + L + \" and \" + R); } else { System.out.println(\"No Such Triplet exists\" + \"between \" + L + \" and \" + R); } } // Driver code public static void main(String[] args) { int L, R; // finding possible Triplet between // 2 and 10 L = 2; R = 10; possibleTripletInRange(L, R); // finding possible Triplet between // 23 and 46 L = 23; R = 46; possibleTripletInRange(L, R); }} // This code is contributed by// Smitha DInesh Semwal", "e": 31224, "s": 28901, "text": null }, { "code": "# Python3 program to find possible non# transitive triplets btw L and R # Function to return gcd of a and bdef gcd(a, b): if (a == 0): return b; return gcd(b % a, a); # function to check for gcddef coprime(a, b): # a and b are coprime if # their gcd is 1. return (gcd(a, b) == 1); # Checks if any possible triplet# (a, b, c) satifying the condition# that (a, b) is coprime, (b, c)# is coprime but (a, c) isntdef possibleTripletInRange(L, R): flag = False; possibleA = 0; possibleB = 0; possibleC = 0; # Generate and check for all # possible triplets between L and R for a in range(L, R + 1): for b in range(a + 1, R + 1): for c in range(b + 1, R + 1): # if we find any such triplets # set flag to true if (coprime(a, b) and coprime(b, c) and coprime(a, c) == False): flag = True; possibleA = a; possibleB = b; possibleC = c; break; # flag = True indicates that a # pair exists between L and R if (flag == True): print(\"(\", possibleA, \",\", possibleB, \",\", possibleC, \") is one such\", \"possible triplet between\", L, \"and\", R); else: print(\"No Such Triplet exists between\", L, \"and\", R); # Driver Code # finding possible Triplet# between 2 and 10L = 2;R = 10;possibleTripletInRange(L, R); # finding possible Triplet# between 23 and 46L = 23;R = 46;possibleTripletInRange(L, R); # This code is contributed by mits", "e": 32883, "s": 31224, "text": null }, { "code": "// C# program to find possible// non transitive triplets// btw L and Rusing System;class GFG{ // Function to return // gcd of a and b static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // function to // check for gcd static bool coprime(int a, int b) { // a and b are coprime // if their gcd is 1. return (gcd(a, b) == 1); } // Checks if any possible // triplet (a, b, c) satifying // the condition that (a, b) // is coprime, (b, c) is // coprime but (a, c) isnt */ static void possibleTripletInRange(int L, int R) { bool flag = false; int possibleA = 0, possibleB = 0, possibleC = 0; // Generate and check for // all possible triplets // between L and R for (int a = L; a <= R; a++) { for (int b = a + 1; b <= R; b++) { for (int c = b + 1; c <= R; c++) { // if we find any // such triplets // set flag to true if (coprime(a, b) && coprime(b, c) && !coprime(a, c)) { flag = true; possibleA = a; possibleB = b; possibleC = c; break; } } } } // flag = True indicates // that a pair exists // between L and R if (flag == true) { Console.WriteLine(\"(\" + possibleA + \", \" + possibleB + \", \" + possibleC + \")\" + \" is one such possible triplet \" + \"between \" + L + \" and \" + R); } else { Console.WriteLine(\"No Such Triplet exists\" + \"between \" + L + \" and \" + R); } } // Driver code public static void Main() { int L, R; // finding possible // Triplet between // 2 and 10 L = 2; R = 10; possibleTripletInRange(L, R); // finding possible // Triplet between // 23 and 46 L = 23; R = 46; possibleTripletInRange(L, R); }} // This code is contributed// by anuj_67.", "e": 35471, "s": 32883, "text": null }, { "code": "<?php// PHP program to find possible non// transitive triplets btw L and R // Function to return gcd of a and bfunction gcd($a, $b){ if ($a == 0) return $b; return gcd($b % $a, $a);} // function to check for gcdfunction coprime($a, $b){ // a and b are coprime if // their gcd is 1. return (gcd($a, $b) == 1);} /* Checks if any possible triplet (a, b, c) satifying the condition that (a, b) is coprime, (b, c) is coprime but (a, c) isnt */function possibleTripletInRange($L, $R){ $flag = false; $possibleA; $possibleB; $possibleC; // Generate and check for all // possible triplets between L and R for ($a = $L; $a <= $R; $a++) { for ($b = $a + 1; $b <= $R; $b++) { for ( $c = $b + 1; $c <= $R; $c++) { // if we find any such triplets // set flag to true if (coprime($a, $b) && coprime($b, $c) && !coprime($a, $c)) { $flag = true; $possibleA = $a; $possibleB = $b; $possibleC = $c; break; } } } } // flag = True indicates that a // pair exists between L and R if ($flag == true) { echo \"(\" ,$possibleA , \", \" , $possibleB, \", \" , $possibleC , \")\", \" is one such possible triplet between \", $L , \" and \" , $R , \"\\n\"; } else { echo \"No Such Triplet exists between \", $L , \" and \" , $R , \"\\n\"; }} // Driver Code$L;$R; // finding possible Triplet// between 2 and 10$L = 2;$R = 10;possibleTripletInRange($L, $R); // finding possible Triplet// between 23 and 46$L = 23;$R = 46;possibleTripletInRange($L, $R); // This code is contributed by jit_t?>", "e": 37340, "s": 35471, "text": null }, { "code": "<script> // Javascript program to find possible // non transitive triplets // btw L and R // Function to return // gcd of a and b function gcd(a, b) { if (a == 0) return b; return gcd(b % a, a); } // function to // check for gcd function coprime(a, b) { // a and b are coprime // if their gcd is 1. return (gcd(a, b) == 1); } // Checks if any possible // triplet (a, b, c) satifying // the condition that (a, b) // is coprime, (b, c) is // coprime but (a, c) isnt */ function possibleTripletInRange(L, R) { let flag = false; let possibleA = 0, possibleB = 0, possibleC = 0; // Generate and check for // all possible triplets // between L and R for (let a = L; a <= R; a++) { for (let b = a + 1; b <= R; b++) { for (let c = b + 1; c <= R; c++) { // if we find any // such triplets // set flag to true if (coprime(a, b) && coprime(b, c) && !coprime(a, c)) { flag = true; possibleA = a; possibleB = b; possibleC = c; break; } } } } // flag = True indicates // that a pair exists // between L and R if (flag == true) { document.write(\"(\" + possibleA + \", \" + possibleB + \", \" + possibleC + \")\" + \" is one such possible triplet \" + \"between \" + L + \" and \" + R + \"</br>\"); } else { document.write(\"No Such Triplet exists\" + \"between \" + L + \" and \" + R + \"</br>\"); } } let L, R; // finding possible // Triplet between // 2 and 10 L = 2; R = 10; possibleTripletInRange(L, R); // finding possible // Triplet between // 23 and 46 L = 23; R = 46; possibleTripletInRange(L, R); </script>", "e": 39678, "s": 37340, "text": null }, { "code": null, "e": 39688, "s": 39678, "text": "Output: " }, { "code": null, "e": 39805, "s": 39688, "text": "(8, 9, 10) is one such possible triplet between 2 and 10\n(44, 45, 46) is one such possible triplet between 23 and 46" }, { "code": null, "e": 40007, "s": 39805, "text": "The time Complexity of the Brute Force Solution is O(n3log(A)) where A is the smallest number of the triplet. Note: The log factor of the complexity is that of computing the GCD for a pair of numbers. " }, { "code": null, "e": 40091, "s": 40007, "text": " Method 2 (efficient):" }, { "code": null, "e": 40592, "s": 40091, "text": "Since we need only one such possible pair, we can use this to break down our complexity further.We just need to identify some cases and look to solve those to solve this problem.Case 1: There are less than 3 numbers between L and R. This Case is easy, we can’t form any triplets, so the answer is this case would always be ‘Not Possible’Case 2: There are more than three numbers between L and R. Now, It’s well-known proof that consecutive numbers are always co-prime. We can even prove this easily. " }, { "code": null, "e": 40920, "s": 40592, "text": "Proof:\nGiven that N and N + 1 are two consecutive integers. \nNow suppose gcd(n, n + 1) = X,\n? X divides n and X also divides (n + 1). \nWhich implies that X divides ((n + 1) - n) or X divides 1.\nBut, There is no number which divides 1 except 1.\n? X = 1, or we can also say that gcd(n, n + 1) = 1 \n\nThus, n and n + 1 are coprime." }, { "code": null, "e": 41856, "s": 40920, "text": "So, if we take three consecutive numbers of the form 2k, 2k + 1, 2k + 2 we would always end up having a possible triplet because as proved above, pairs (2k, 2k + 1) and (2k + 1, 2k + 2) being pairs of consecutive numbers are co-prime and the pair (2k, 2k+2) have their gcd as 2 (since they are even).Case 3: When there are exactly 3 numbers between L and R This is an extension of case 3, now this case can have 2 cases,Case 3.1 When the three numbers are of the form 2k, 2k + 1, 2k + 2 We have already looked at this case in case 2. So this is the only triplet and also is a valid triplet between L and R.Case 3.2 When the three numbers are of the form 2k – 1, 2k, 2k + 1 We have already seen that (2k – 1, 2k) and (2k, 2k + 1) being a pair of consecutive numbers are co-prime pairs, so we need to check if the pair (2k – 1, 2k + 1) is co-prime or not It can be proved that the pair (2k – 1, 2k + 1) is always co-prime as shown below " }, { "code": null, "e": 42290, "s": 41856, "text": "Proof:\nGiven that 2k - 1 and 2k + 1 are two numbers \nNow suppose gcd((2k - 1), (2k + 1)) = X,\n? X divides (2k - 1) and X also divides (2k + 1). \nWhich implies that X divides ((2k + 1) - (2k - 1)) or X divides 2.\n2 being a prime is only divisible by 1 and 2 itself. \nBut, 2k - 1 and 2k + 1 are odd numbers so X can never be equal to 2.\n? X = 1, or we can also say that gcd((2k -1), (2k + 1)) = 1 \n\nThus, 2k - 1 and 2k + 1 are coprime." }, { "code": null, "e": 42415, "s": 42290, "text": "Thus, in this case, we won’t be able to find any possible valid triplet.Below is the implementation of the above approach: " }, { "code": null, "e": 42419, "s": 42415, "text": "C++" }, { "code": null, "e": 42424, "s": 42419, "text": "Java" }, { "code": null, "e": 42432, "s": 42424, "text": "Python3" }, { "code": null, "e": 42435, "s": 42432, "text": "C#" }, { "code": null, "e": 42439, "s": 42435, "text": "PHP" }, { "code": null, "e": 42450, "s": 42439, "text": "Javascript" }, { "code": "/* C++ program to find a non transitive co-prime triplets between L and R */#include <bits/stdc++.h>using namespace std; /* Checks if any possible triplet (a, b, c) satisfying the condition that (a, b) is coprime, (b, c) is coprime but (a, c) isnt */ void possibleTripletInRange(int L, int R){ bool flag = false; int possibleA, possibleB, possibleC; int numbersInRange = (R - L + 1); /* Case 1 : Less than 3 numbers between L and R */ if (numbersInRange < 3) { flag = false; } /* Case 2: More than 3 numbers between L and R */ else if (numbersInRange > 3) { flag = true; // triplets should always be of form (2k, 2k + 1, 2k + 2) if (L % 2) { L++; } possibleA = L; possibleB = L + 1; possibleC = L + 2; } else { /* Case 3.1: Exactly 3 numbers in range of form (2k, 2k + 1, 2k + 2) */ if (!(L % 2)) { flag = true; possibleA = L; possibleB = L + 1; possibleC = L + 2; } else { /* Case 3.2: Exactly 3 numbers in range of form (2k - 1, 2k, 2k + 1) */ flag = false; } } // flag = True indicates that a pair exists between L and R if (flag == true) { cout << \"(\" << possibleA << \", \" << possibleB << \", \" << possibleC << \")\" << \" is one such possible triplet between \" << L << \" and \" << R << \"\\n\"; } else { cout << \"No Such Triplet exists between \" << L << \" and \" << R << \"\\n\"; }} // Driver codeint main(){ int L, R; // finding possible Triplet between 2 and 10 L = 2; R = 10; possibleTripletInRange(L, R); // finding possible Triplet between 23 and 46 L = 23; R = 46; possibleTripletInRange(L, R); return 0;}", "e": 44322, "s": 42450, "text": null }, { "code": "// Java program to find a// non transitive co-prime// triplets between L and Rimport java.io.*; class GFG{ // Checks if any possible triplet// (a, b, c) satifying the condition// that (a, b) is coprime, (b, c)// is coprime but (a, c) isntstatic void possibleTripletInRange(int L, int R){ boolean flag = false; int possibleA = 0, possibleB = 0, possibleC = 0; int numbersInRange = (R - L + 1); // Case 1 : Less than 3 // numbers between L and R if (numbersInRange < 3) { flag = false; } // Case 2: More than 3 // numbers between L and R else if (numbersInRange > 3) { flag = true; // triplets should always // be of form (2k, 2k + 1, // 2k + 2) if (L % 2 > 0) { L++; } possibleA = L; possibleB = L + 1; possibleC = L + 2; } else { /* Case 3.1: Exactly 3 numbers in range of form (2k, 2k + 1, 2k + 2) */ if (!(L % 2 > 0)) { flag = true; possibleA = L; possibleB = L + 1; possibleC = L + 2; } else { /* Case 3.2: Exactly 3 numbers in range of form (2k - 1, 2k, 2k + 1) */ flag = false; } } // flag = True indicates // that a pair exists // between L and R if (flag == true) { System.out.println(\"(\" + possibleA + \", \" + possibleB + \", \" + possibleC + \")\" + \" is one such possible\" + \" triplet between \" + L + \" and \" + R ); } else { System.out.println(\"No Such Triplet\" + \" exists between \" + L + \" and \" + R); }} // Driver codepublic static void main (String[] args){int L, R; // finding possible Triplet// between 2 and 10L = 2;R = 10;possibleTripletInRange(L, R); // finding possible Triplet// between 23 and 46L = 23;R = 46;possibleTripletInRange(L, R);}} // This code is contributed// by anuj_67.", "e": 46517, "s": 44322, "text": null }, { "code": "# Python3 program to find a non transitive# co-prime triplets between L and R # Checks if any possible triplet (a, b, c)# satifying the condition that (a, b) is# coprime, (b, c) is coprime but (a, c) isntdef possibleTripletInRange(L, R): flag = False; possibleA = 0; possibleB = 0; possibleC = 0; numbersInRange = (R - L + 1); # Case 1 : Less than 3 numbers # between L and R if (numbersInRange < 3): flag = False; # Case 2: More than 3 numbers # between L and R elif (numbersInRange > 3): flag = True; # triplets should always be of # form (2k, 2k + 1, 2k + 2) if ((L % 2) > 0): L += 1; possibleA = L; possibleB = L + 1; possibleC = L + 2; else: # Case 3.1: Exactly 3 numbers in range # of form (2k, 2k + 1, 2k + 2) if ((L % 2) == 0): flag = True; possibleA = L; possibleB = L + 1; possibleC = L + 2; else: # Case 3.2: Exactly 3 numbers in range # of form (2k - 1, 2k, 2k + 1) flag = False; # flag = True indicates that a pair # exists between L and R if (flag == True): print(\"(\", possibleA, \",\", possibleB, \",\", possibleC, \") is one such\", \"possible triplet between\", L, \"and\", R); else: print(\"No Such Triplet exists between\", L, \"and\", R); # Driver code # finding possible Triplet# between 2 and 10L = 2;R = 10;possibleTripletInRange(L, R); # finding possible Triplet# between 23 and 46L = 23;R = 46;possibleTripletInRange(L, R); # This code is contributed by mits", "e": 48232, "s": 46517, "text": null }, { "code": "// C# program to find a// non transitive co-prime// triplets between L and Rusing System; public class GFG{ // Checks if any possible triplet// (a, b, c) satifying the condition// that (a, b) is coprime, (b, c)// is coprime but (a, c) isntstatic void possibleTripletInRange(int L, int R){ bool flag = false; int possibleA = 0, possibleB = 0, possibleC = 0; int numbersInRange = (R - L + 1); // Case 1 : Less than 3 // numbers between L and R if (numbersInRange < 3) { flag = false; } // Case 2: More than 3 // numbers between L and R else if (numbersInRange > 3) { flag = true; // triplets should always // be of form (2k, 2k + 1, // 2k + 2) if (L % 2 > 0) { L++; } possibleA = L; possibleB = L + 1; possibleC = L + 2; } else { /* Case 3.1: Exactly 3 numbers in range of form (2k, 2k + 1, 2k + 2) */ if (!(L % 2 > 0)) { flag = true; possibleA = L; possibleB = L + 1; possibleC = L + 2; } else { /* Case 3.2: Exactly 3 numbers in range of form (2k - 1, 2k, 2k + 1) */ flag = false; } } // flag = True indicates // that a pair exists // between L and R if (flag == true) { Console.WriteLine(\"(\" + possibleA + \", \" + possibleB + \", \" + possibleC + \")\" + \" is one such possible\" + \" triplet between \" + L + \" and \" + R ); } else { Console.WriteLine(\"No Such Triplet\" + \" exists between \" + L + \" and \" + R); }} // Driver code static public void Main (){ int L, R; // finding possible Triplet // between 2 and 10 L = 2; R = 10; possibleTripletInRange(L, R); // finding possible Triplet // between 23 and 46 L = 23; R = 46; possibleTripletInRange(L, R); }}// This code is contributed by ajit", "e": 50451, "s": 48232, "text": null }, { "code": "<?php// PHP program to find possible// non transitive triplets// btw L and Rfunction gcd($a, $b){ if ($a == 0) return $b; return gcd($b % $a, $a);} // function to check for gcdfunction coprime($a, $b){ // a and b are coprime // if their gcd is 1. return (gcd($a, $b) == 1);} /* Checks if any possible triplet(a, b, c) satifying the conditionthat (a, b) is coprime, (b, c) iscoprime but (a, c) isnt */function possibleTripletInRange($L, $R){ $flag = false; $possibleA; $possibleB; $possibleC; // Generate and check for // all possible triplets // between L and R for ($a = $L; $a <= $R; $a++) { for ($b = $a + 1; $b <= $R; $b++) { for ($c = $b + 1; $c <= $R; $c++) { // if we find any such // triplets set flag to true if (coprime($a, $b) && coprime($b, $c) && !coprime($a, $c)) { $flag = true; $possibleA = $a; $possibleB = $b; $possibleC = $c; break; } } } } // flag = True indicates // that a pair exists // between L and R if ($flag == true) { echo \"(\" , $possibleA , \", \" , $possibleB , \", \" , $possibleC , \")\" , \" is one such possible \", \"triplet between \" , $L , \" and \" , $R , \"\\n\"; } else { echo \"No Such Triplet exists between \", $L , \" and \" , $R , \"\\n\"; }} // Driver code // finding possible Triplet// between 2 and 10$L = 2;$R = 10;possibleTripletInRange($L, $R); // finding possible Triplet// between 23 and 46$L = 23;$R = 46;possibleTripletInRange($L, $R); // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 52331, "s": 50451, "text": null }, { "code": "<script> /* Javascript program to find a non transitive co-prime triplets between L and R */ /* Checks if any possible triplet (a, b, c) satisfying the condition that (a, b) is coprime, (b, c) is coprime but (a, c) isnt */ function possibleTripletInRange(L, R) { let flag = false; let possibleA, possibleB, possibleC; let numbersInRange = (R - L + 1); /* Case 1 : Less than 3 numbers between L and R */ if (numbersInRange < 3) { flag = false; } /* Case 2: More than 3 numbers between L and R */ else if (numbersInRange > 3) { flag = true; // triplets should always be of form (2k, 2k + 1, 2k + 2) if (L % 2) { L++; } possibleA = L; possibleB = L + 1; possibleC = L + 2; } else { /* Case 3.1: Exactly 3 numbers in range of form (2k, 2k + 1, 2k + 2) */ if (!(L % 2)) { flag = true; possibleA = L; possibleB = L + 1; possibleC = L + 2; } else { /* Case 3.2: Exactly 3 numbers in range of form (2k - 1, 2k, 2k + 1) */ flag = false; } } // flag = True indicates that a pair exists between L and R if (flag == true) { document.write(\"(\" + possibleA + \", \" + possibleB + \", \" + possibleC + \")\" + \" is one such possible triplet between \" + L + \" and \" + R + \"</br>\"); } else { document.write(\"No Such Triplet exists between \" + L + \" and \" + R + \"</br>\"); } } let L, R; // finding possible Triplet between 2 and 10 L = 2; R = 10; possibleTripletInRange(L, R); // finding possible Triplet between 23 and 46 L = 23; R = 46; possibleTripletInRange(L, R); </script>", "e": 54072, "s": 52331, "text": null }, { "code": null, "e": 54082, "s": 54072, "text": "Output: " }, { "code": null, "e": 54198, "s": 54082, "text": "(2, 3, 4) is one such possible triplet between 2 and 10\n(24, 25, 26) is one such possible triplet between 24 and 46" }, { "code": null, "e": 54243, "s": 54198, "text": "The time complexity of this method is O(1). " }, { "code": null, "e": 54264, "s": 54243, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 54269, "s": 54264, "text": "vt_m" }, { "code": null, "e": 54282, "s": 54269, "text": "Akanksha_Rai" }, { "code": null, "e": 54288, "s": 54282, "text": "jit_t" }, { "code": null, "e": 54301, "s": 54288, "text": "Mithun Kumar" }, { "code": null, "e": 54315, "s": 54301, "text": "ManasChhabra2" }, { "code": null, "e": 54324, "s": 54315, "text": "mukesh07" }, { "code": null, "e": 54342, "s": 54324, "text": "divyeshrabadiya07" }, { "code": null, "e": 54350, "s": 54342, "text": "GCD-LCM" }, { "code": null, "e": 54364, "s": 54350, "text": "number-theory" }, { "code": null, "e": 54377, "s": 54364, "text": "Prime Number" }, { "code": null, "e": 54390, "s": 54377, "text": "Mathematical" }, { "code": null, "e": 54409, "s": 54390, "text": "Technical Scripter" }, { "code": null, "e": 54423, "s": 54409, "text": "number-theory" }, { "code": null, "e": 54436, "s": 54423, "text": "Mathematical" }, { "code": null, "e": 54449, "s": 54436, "text": "Prime Number" }, { "code": null, "e": 54547, "s": 54449, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 54589, "s": 54547, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 54620, "s": 54589, "text": "Product of Array except itself" }, { "code": null, "e": 54653, "s": 54620, "text": "Program to multiply two matrices" }, { "code": null, "e": 54688, "s": 54653, "text": "Singular Value Decomposition (SVD)" }, { "code": null, "e": 54732, "s": 54688, "text": "Generate all permutation of a set in Python" }, { "code": null, "e": 54757, "s": 54732, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 54801, "s": 54757, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 54832, "s": 54801, "text": "Shortest path in a Binary Maze" }, { "code": null, "e": 54854, "s": 54832, "text": "Expression Evaluation" } ]
Python string | strip() - GeeksforGeeks
11 Aug, 2021 strip() is an inbuilt function in Python programming language that returns a copy of the string with both leading and trailing characters removed (based on the string argument passed). Syntax: string.strip([chars]) Parameter: There is only one optional parameter in it: 1)chars - a string specifying the set of characters to be removed. If the optional chars parameter is not given, all leading and trailing whitespaces are removed from the string. Return Value: Returns a copy of the string with both leading and trailing characters removed. Python3 # Python3 program to demonstrate the use of# strip() method string = """ geeks for geeks """ # prints the string without strippingprint(string) # prints the string by removing leading and trailing whitespacesprint(string.strip()) # prints the string by removing geeksprint(string.strip(' geeks')) geeks for geeks geeks for geeks for Python3 # Python Program to demonstrate use of strip() method str1 = 'geeks for geeks'# Print the string without stripping.print(str1) # String whose set of characters are to be# remove from original string at both its ends.str2 = 'ekgs' # Print string after stripping str2 from str1 at both its end.print(str1.strip(str2)) geeks for geeks for Working of above code : We first construct a string str1 = ‘geeks for geeks’ Now we call strip method over str1 and pass str2 = ‘ekgs’ as argument. Now python interpreter trace str1 from left.It remove the character of str1 if it is present in str2. Otherwise it stops tracing. Now python interpreter trace str1 from right. It remove the character of str1 if it is present in str2. Otherwise it stop tracing. Now at last it returns the resultant string.When we call strip() without argument, it removes leading and trailing spaces. Python3 # Python Program to demonstrate use of strip() method without any argumentstr1 = """ geeks for geeks """ # Print the string without stripping.print(str1) # Print string after removing all leading# and trailing whitespaces.print(str1.strip()) geeks for geeks Output: geeks for geeks Practical application: Given a string remove occurrence of word “the” from the beginning and the end. Python # Python3 program to demonstrate the practical application# strip() string = " the King has the largest army in the entire world the" # prints the string after removing the from beginning and endprint(string.strip(" the")) the King has the largest army in the entire world the Output: King has the largest army in the entire world Vishalmast akkucoder123 preetishneema312 simranarora5sos gabaa406 python-string Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Taking input in Python Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe
[ { "code": null, "e": 24619, "s": 24591, "text": "\n11 Aug, 2021" }, { "code": null, "e": 24813, "s": 24619, "text": "strip() is an inbuilt function in Python programming language that returns a copy of the string with both leading and trailing characters removed (based on the string argument passed). Syntax: " }, { "code": null, "e": 25168, "s": 24813, "text": "string.strip([chars])\nParameter: \nThere is only one optional parameter in it:\n1)chars - a string specifying \nthe set of characters to be removed. \n\nIf the optional chars parameter is not given, all leading \nand trailing whitespaces are removed from the string.\nReturn Value:\nReturns a copy of the string with both leading and trailing characters removed." }, { "code": null, "e": 25176, "s": 25168, "text": "Python3" }, { "code": "# Python3 program to demonstrate the use of# strip() method string = \"\"\" geeks for geeks \"\"\" # prints the string without strippingprint(string) # prints the string by removing leading and trailing whitespacesprint(string.strip()) # prints the string by removing geeksprint(string.strip(' geeks'))", "e": 25482, "s": 25176, "text": null }, { "code": null, "e": 25527, "s": 25482, "text": " geeks for geeks \ngeeks for geeks\nfor" }, { "code": null, "e": 25537, "s": 25529, "text": "Python3" }, { "code": "# Python Program to demonstrate use of strip() method str1 = 'geeks for geeks'# Print the string without stripping.print(str1) # String whose set of characters are to be# remove from original string at both its ends.str2 = 'ekgs' # Print string after stripping str2 from str1 at both its end.print(str1.strip(str2))", "e": 25853, "s": 25537, "text": null }, { "code": null, "e": 25874, "s": 25853, "text": "geeks for geeks\n for" }, { "code": null, "e": 26410, "s": 25876, "text": "Working of above code : We first construct a string str1 = ‘geeks for geeks’ Now we call strip method over str1 and pass str2 = ‘ekgs’ as argument. Now python interpreter trace str1 from left.It remove the character of str1 if it is present in str2. Otherwise it stops tracing. Now python interpreter trace str1 from right. It remove the character of str1 if it is present in str2. Otherwise it stop tracing. Now at last it returns the resultant string.When we call strip() without argument, it removes leading and trailing spaces. " }, { "code": null, "e": 26418, "s": 26410, "text": "Python3" }, { "code": "# Python Program to demonstrate use of strip() method without any argumentstr1 = \"\"\" geeks for geeks \"\"\" # Print the string without stripping.print(str1) # Print string after removing all leading# and trailing whitespaces.print(str1.strip())", "e": 26666, "s": 26418, "text": null }, { "code": null, "e": 26691, "s": 26666, "text": " geeks for geeks " }, { "code": null, "e": 26702, "s": 26693, "text": "Output: " }, { "code": null, "e": 26718, "s": 26702, "text": "geeks for geeks" }, { "code": null, "e": 26822, "s": 26718, "text": "Practical application: Given a string remove occurrence of word “the” from the beginning and the end. " }, { "code": null, "e": 26829, "s": 26822, "text": "Python" }, { "code": "# Python3 program to demonstrate the practical application# strip() string = \" the King has the largest army in the entire world the\" # prints the string after removing the from beginning and endprint(string.strip(\" the\"))", "e": 27053, "s": 26829, "text": null }, { "code": null, "e": 27107, "s": 27053, "text": "the King has the largest army in the entire world the" }, { "code": null, "e": 27118, "s": 27109, "text": "Output: " }, { "code": null, "e": 27164, "s": 27118, "text": "King has the largest army in the entire world" }, { "code": null, "e": 27177, "s": 27166, "text": "Vishalmast" }, { "code": null, "e": 27190, "s": 27177, "text": "akkucoder123" }, { "code": null, "e": 27207, "s": 27190, "text": "preetishneema312" }, { "code": null, "e": 27223, "s": 27207, "text": "simranarora5sos" }, { "code": null, "e": 27232, "s": 27223, "text": "gabaa406" }, { "code": null, "e": 27246, "s": 27232, "text": "python-string" }, { "code": null, "e": 27253, "s": 27246, "text": "Python" }, { "code": null, "e": 27351, "s": 27253, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27379, "s": 27351, "text": "Read JSON file using Python" }, { "code": null, "e": 27429, "s": 27379, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 27451, "s": 27429, "text": "Python map() function" }, { "code": null, "e": 27495, "s": 27451, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 27513, "s": 27495, "text": "Python Dictionary" }, { "code": null, "e": 27536, "s": 27513, "text": "Taking input in Python" }, { "code": null, "e": 27571, "s": 27536, "text": "Read a file line by line in Python" }, { "code": null, "e": 27603, "s": 27571, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27625, "s": 27603, "text": "Enumerate() in Python" } ]
jQuery UI Datepicker minDate Option - GeeksforGeeks
19 Mar, 2021 jQuery UI consists of GUI widgets, visual effects, and themes implemented using jQuery, CSS, and HTML. jQuery UI is great for building UI interfaces for the webpages. The jQuery UI Datepicker minDate option is used to set the minimum selectable date. If we set it to null, there is no minimum date. Syntax: $( ".selector" ).datepicker({ minDate: new Date(2007, 1 - 1, 1) }); CDN Link: First, add jQuery UI scripts needed for your project. <link rel=”stylesheet” href=”//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css”><script src=”//code.jquery.com/jquery-1.12.4.js”></script><script src=”//code.jquery.com/ui/1.12.1/jquery-ui.js”></script> Example: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <link href= "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet" /> <script src="https://code.jquery.com/jquery-1.10.2.js"> </script> <script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"> </script> <!-- Javascript --> <script> $(function () { $("#gfg").datepicker({ minDate: new Date(2021, 1 - 1, 1) }); }); </script></head> <body> <h1>GeeksforGeeks</h1> <h3>jQuery UI Datepicker minDate Option</h3> <div>Enter Date: <input type="text" id="gfg" /></div></body> </html> Output: minDate option Reference: https://api.jqueryui.com/datepicker/#option-minDate HTML-Tags jQuery-Methods jQuery-UI JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show and Hide div elements using radio buttons? How to prevent Body from scrolling when a modal is opened using jQuery ? jQuery | ajax() Method jQuery | removeAttr() with Examples How to get the value in an input text box using jQuery ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 27144, "s": 27116, "text": "\n19 Mar, 2021" }, { "code": null, "e": 27443, "s": 27144, "text": "jQuery UI consists of GUI widgets, visual effects, and themes implemented using jQuery, CSS, and HTML. jQuery UI is great for building UI interfaces for the webpages. The jQuery UI Datepicker minDate option is used to set the minimum selectable date. If we set it to null, there is no minimum date." }, { "code": null, "e": 27451, "s": 27443, "text": "Syntax:" }, { "code": null, "e": 27521, "s": 27451, "text": "$( \".selector\" ).datepicker({\n minDate: new Date(2007, 1 - 1, 1)\n});" }, { "code": null, "e": 27585, "s": 27521, "text": "CDN Link: First, add jQuery UI scripts needed for your project." }, { "code": null, "e": 27798, "s": 27585, "text": "<link rel=”stylesheet” href=”//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css”><script src=”//code.jquery.com/jquery-1.12.4.js”></script><script src=”//code.jquery.com/ui/1.12.1/jquery-ui.js”></script>" }, { "code": null, "e": 27807, "s": 27798, "text": "Example:" }, { "code": null, "e": 27812, "s": 27807, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <link href= \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\" rel=\"stylesheet\" /> <script src=\"https://code.jquery.com/jquery-1.10.2.js\"> </script> <script src=\"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"> </script> <!-- Javascript --> <script> $(function () { $(\"#gfg\").datepicker({ minDate: new Date(2021, 1 - 1, 1) }); }); </script></head> <body> <h1>GeeksforGeeks</h1> <h3>jQuery UI Datepicker minDate Option</h3> <div>Enter Date: <input type=\"text\" id=\"gfg\" /></div></body> </html>", "e": 28491, "s": 27812, "text": null }, { "code": null, "e": 28499, "s": 28491, "text": "Output:" }, { "code": null, "e": 28514, "s": 28499, "text": "minDate option" }, { "code": null, "e": 28577, "s": 28514, "text": "Reference: https://api.jqueryui.com/datepicker/#option-minDate" }, { "code": null, "e": 28587, "s": 28577, "text": "HTML-Tags" }, { "code": null, "e": 28602, "s": 28587, "text": "jQuery-Methods" }, { "code": null, "e": 28612, "s": 28602, "text": "jQuery-UI" }, { "code": null, "e": 28619, "s": 28612, "text": "JQuery" }, { "code": null, "e": 28636, "s": 28619, "text": "Web Technologies" }, { "code": null, "e": 28734, "s": 28636, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28789, "s": 28734, "text": "How to Show and Hide div elements using radio buttons?" }, { "code": null, "e": 28862, "s": 28789, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 28885, "s": 28862, "text": "jQuery | ajax() Method" }, { "code": null, "e": 28921, "s": 28885, "text": "jQuery | removeAttr() with Examples" }, { "code": null, "e": 28978, "s": 28921, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 29018, "s": 28978, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29051, "s": 29018, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29096, "s": 29051, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29139, "s": 29096, "text": "How to fetch data from an API in ReactJS ?" } ]
How to use AvatarGroup Component in ReactJS? - GeeksforGeeks
05 Mar, 2021 AvatarGroup Component is used to group multiples of Avatars together. It renders its children as a stack. Material UI for React has this component available for us, and it is very easy to integrate. We can use the AvatarGroup Component in ReactJS using the following approach. Creating React Application And Installing Module: Step 1: Create a React application using the following command. npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command. cd foldername Step 3: After creating the ReactJS application, Install the material-ui modules using the following command. npm install @material-ui/core npm install @material-ui/lab Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from "react";import AvatarGroup from "@material-ui/lab/AvatarGroup";import Avatar from "@material-ui/core/Avatar"; export default function App() { return ( <div style={{ display: "block" }}> <h4>How to use AvatarGroup Component in ReactJS?</h4> <AvatarGroup max={4}> <Avatar alt="Geeksforgeeks" src="YourPicturePath" /> <Avatar alt="Random Name" src="YourPicturePath" /> <Avatar alt="Unknow" src="YourPicturePath" /> <Avatar alt="Gourav" src="YourPicturePath" /> <Avatar alt="Harrier" src="YourPicturePath" /> </AvatarGroup> </div> );} Step to Run Application: Run the application using the following command from the root directory of the project. npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output. Reference: https://material-ui.com/components/avatars/#grouped Material-UI React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ReactJS useNavigate() Hook How to set background images in ReactJS ? Axios in React: A Guide for Beginners How to create a table in ReactJS ? How to navigate on path by button click in react router ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26071, "s": 26043, "text": "\n05 Mar, 2021" }, { "code": null, "e": 26348, "s": 26071, "text": "AvatarGroup Component is used to group multiples of Avatars together. It renders its children as a stack. Material UI for React has this component available for us, and it is very easy to integrate. We can use the AvatarGroup Component in ReactJS using the following approach." }, { "code": null, "e": 26398, "s": 26348, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 26462, "s": 26398, "text": "Step 1: Create a React application using the following command." }, { "code": null, "e": 26494, "s": 26462, "text": "npx create-react-app foldername" }, { "code": null, "e": 26594, "s": 26494, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command." }, { "code": null, "e": 26608, "s": 26594, "text": "cd foldername" }, { "code": null, "e": 26717, "s": 26608, "text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command." }, { "code": null, "e": 26776, "s": 26717, "text": "npm install @material-ui/core\nnpm install @material-ui/lab" }, { "code": null, "e": 26828, "s": 26776, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 26846, "s": 26828, "text": "Project Structure" }, { "code": null, "e": 26976, "s": 26846, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 26983, "s": 26976, "text": "App.js" }, { "code": "import React from \"react\";import AvatarGroup from \"@material-ui/lab/AvatarGroup\";import Avatar from \"@material-ui/core/Avatar\"; export default function App() { return ( <div style={{ display: \"block\" }}> <h4>How to use AvatarGroup Component in ReactJS?</h4> <AvatarGroup max={4}> <Avatar alt=\"Geeksforgeeks\" src=\"YourPicturePath\" /> <Avatar alt=\"Random Name\" src=\"YourPicturePath\" /> <Avatar alt=\"Unknow\" src=\"YourPicturePath\" /> <Avatar alt=\"Gourav\" src=\"YourPicturePath\" /> <Avatar alt=\"Harrier\" src=\"YourPicturePath\" /> </AvatarGroup> </div> );}", "e": 27591, "s": 26983, "text": null }, { "code": null, "e": 27704, "s": 27591, "text": "Step to Run Application: Run the application using the following command from the root directory of the project." }, { "code": null, "e": 27714, "s": 27704, "text": "npm start" }, { "code": null, "e": 27813, "s": 27714, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output." }, { "code": null, "e": 27876, "s": 27813, "text": "Reference: https://material-ui.com/components/avatars/#grouped" }, { "code": null, "e": 27888, "s": 27876, "text": "Material-UI" }, { "code": null, "e": 27904, "s": 27888, "text": "React-Questions" }, { "code": null, "e": 27912, "s": 27904, "text": "ReactJS" }, { "code": null, "e": 27929, "s": 27912, "text": "Web Technologies" }, { "code": null, "e": 28027, "s": 27929, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28054, "s": 28027, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 28096, "s": 28054, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 28134, "s": 28096, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 28169, "s": 28134, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 28227, "s": 28169, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 28267, "s": 28227, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28300, "s": 28267, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28345, "s": 28300, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28395, "s": 28345, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python | Pandas DataFrame.ix[ ] - GeeksforGeeks
28 Dec, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas DataFrame.ix[ ] is both Label and Integer based slicing technique. Besides pure label based and integer based, Pandas provides a hybrid method for selections and subsetting the object using the ix[] operator. ix[] is the most general indexer and will support any of the inputs in loc[] and iloc[]. Syntax: DataFrame.ix[ ] Parameters:Index Position: Index position of rows in integer or list of integer.Index label: String or list of string of index label of rows Returns: Data frame or Series depending on parameters # importing pandas package import pandas as geek # making data frame from csv filedata = geek.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # Integer slicingprint("Slicing only rows(till index 4):")x1 = data.ix[:4, ]print(x1, "\n") print("Slicing rows and columns(rows=4, col 1-4, excluding 4):")x2 = data.ix[:4, 1:4]print(x2) Output : Code #2: # importing pandas package import pandas as geek # making data frame from csv filedata = geek.read_csv("nba.csv") # Index slicing on Height columnprint("After index slicing:")x1 = data.ix[10:20, 'Height']print(x1, "\n") # Index slicing on Salary columnx2 = data.ix[10:20, 'Salary']print(x2) Output: Code #3: # importing pandas and numpyimport pandas as pdimport numpy as np df = pd.DataFrame(np.random.randn(10, 4), columns = ['A', 'B', 'C', 'D']) print("Original DataFrame: \n" , df) # Integer slicingprint("\n Slicing only rows:")print("--------------------------")x1 = df.ix[:4, ]print(x1) print("\n Slicing rows and columns:")print("----------------------------")x2 = df.ix[:4, 1:3]print(x2) Output : Code #4: # importing pandas and numpyimport pandas as pdimport numpy as np df = pd.DataFrame(np.random.randn(10, 4), columns = ['A', 'B', 'C', 'D']) print("Original DataFrame: \n" , df) # Integer slicing (printing all the rows of column 'A')print("\n After index slicing (On 'A'):")print("--------------------------")x = df.ix[:, 'A'] print(x) Output : Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Read a file line by line in Python Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Reading and Writing to text files in Python *args and **kwargs in Python Convert integer to string in Python Check if element exists in list in Python
[ { "code": null, "e": 26142, "s": 26114, "text": "\n28 Dec, 2018" }, { "code": null, "e": 26356, "s": 26142, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 26661, "s": 26356, "text": "Pandas DataFrame.ix[ ] is both Label and Integer based slicing technique. Besides pure label based and integer based, Pandas provides a hybrid method for selections and subsetting the object using the ix[] operator. ix[] is the most general indexer and will support any of the inputs in loc[] and iloc[]." }, { "code": null, "e": 26685, "s": 26661, "text": "Syntax: DataFrame.ix[ ]" }, { "code": null, "e": 26826, "s": 26685, "text": "Parameters:Index Position: Index position of rows in integer or list of integer.Index label: String or list of string of index label of rows" }, { "code": null, "e": 26880, "s": 26826, "text": "Returns: Data frame or Series depending on parameters" }, { "code": "# importing pandas package import pandas as geek # making data frame from csv filedata = geek.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # Integer slicingprint(\"Slicing only rows(till index 4):\")x1 = data.ix[:4, ]print(x1, \"\\n\") print(\"Slicing rows and columns(rows=4, col 1-4, excluding 4):\")x2 = data.ix[:4, 1:4]print(x2)", "e": 27242, "s": 26880, "text": null }, { "code": null, "e": 27260, "s": 27242, "text": "Output : Code #2:" }, { "code": "# importing pandas package import pandas as geek # making data frame from csv filedata = geek.read_csv(\"nba.csv\") # Index slicing on Height columnprint(\"After index slicing:\")x1 = data.ix[10:20, 'Height']print(x1, \"\\n\") # Index slicing on Salary columnx2 = data.ix[10:20, 'Salary']print(x2)", "e": 27560, "s": 27260, "text": null }, { "code": null, "e": 27568, "s": 27560, "text": "Output:" }, { "code": null, "e": 27579, "s": 27570, "text": "Code #3:" }, { "code": "# importing pandas and numpyimport pandas as pdimport numpy as np df = pd.DataFrame(np.random.randn(10, 4), columns = ['A', 'B', 'C', 'D']) print(\"Original DataFrame: \\n\" , df) # Integer slicingprint(\"\\n Slicing only rows:\")print(\"--------------------------\")x1 = df.ix[:4, ]print(x1) print(\"\\n Slicing rows and columns:\")print(\"----------------------------\")x2 = df.ix[:4, 1:3]print(x2)", "e": 27983, "s": 27579, "text": null }, { "code": null, "e": 28001, "s": 27983, "text": "Output : Code #4:" }, { "code": "# importing pandas and numpyimport pandas as pdimport numpy as np df = pd.DataFrame(np.random.randn(10, 4), columns = ['A', 'B', 'C', 'D']) print(\"Original DataFrame: \\n\" , df) # Integer slicing (printing all the rows of column 'A')print(\"\\n After index slicing (On 'A'):\")print(\"--------------------------\")x = df.ix[:, 'A'] print(x)", "e": 28351, "s": 28001, "text": null }, { "code": null, "e": 28360, "s": 28351, "text": "Output :" }, { "code": null, "e": 28384, "s": 28360, "text": "Python pandas-dataFrame" }, { "code": null, "e": 28416, "s": 28384, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 28430, "s": 28416, "text": "Python-pandas" }, { "code": null, "e": 28437, "s": 28430, "text": "Python" }, { "code": null, "e": 28535, "s": 28437, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28553, "s": 28535, "text": "Python Dictionary" }, { "code": null, "e": 28585, "s": 28553, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28620, "s": 28585, "text": "Read a file line by line in Python" }, { "code": null, "e": 28642, "s": 28620, "text": "Enumerate() in Python" }, { "code": null, "e": 28684, "s": 28642, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28714, "s": 28684, "text": "Iterate over a list in Python" }, { "code": null, "e": 28758, "s": 28714, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28787, "s": 28758, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28823, "s": 28787, "text": "Convert integer to string in Python" } ]
Python | Ways to split strings on Uppercase characters - GeeksforGeeks
20 Aug, 2020 Given a string, write a Python program to split strings on Uppercase characters. Let’s discuss a few methods to solve the problem.Method #1: Using re.findall() method Python3 # Python code to demonstrate# to split strings# on uppercase letter import re # Initialising stringini_str = 'GeeksForGeeks' # Printing Initial stringprint ("Initial String", ini_str) # Splitting on UpperCase using reres_list = []res_list = re.findall('[A-Z][^A-Z]*', ini_str) # Printing resultprint("Resultant prefix", str(res_list)) Initial String GeeksForGeeks Resultant prefix ['Geeks', 'For', 'Geeks'] Method #2: Using re.split() Python3 # Python code to demonstrate# to split strings# on uppercase letter import re # Initialising stringini_str = 'GeeksForGeeks' # Printing Initial stringprint ("Initial String", ini_str) # Splitting on UpperCase using reres_list = [s for s in re.split("([A-Z][^A-Z]*)", ini_str) if s] # Printing resultprint("Resultant prefix", str(res_list)) Initial String GeeksForGeeks Resultant prefix ['Geeks', 'For', 'Geeks'] Method #3: Using enumerate Python3 # Python code to demonstrate# to split strings# on uppercase letter # Initialising stringini_str = 'GeeksForGeeks' # Printing Initial stringprint ("Initial String", ini_str) # Splitting on UpperCaseres_pos = [i for i, e in enumerate(ini_str+'A') if e.isupper()]res_list = [ini_str[res_pos[j]:res_pos[j + 1]] for j in range(len(res_pos)-1)] # Printing resultprint("Resultant prefix", str(res_list)) Initial String GeeksForGeeks Resultant prefix ['Geeks', 'For', 'Geeks'] nayeemulhkhan Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 26139, "s": 26111, "text": "\n20 Aug, 2020" }, { "code": null, "e": 26308, "s": 26139, "text": "Given a string, write a Python program to split strings on Uppercase characters. Let’s discuss a few methods to solve the problem.Method #1: Using re.findall() method " }, { "code": null, "e": 26316, "s": 26308, "text": "Python3" }, { "code": "# Python code to demonstrate# to split strings# on uppercase letter import re # Initialising stringini_str = 'GeeksForGeeks' # Printing Initial stringprint (\"Initial String\", ini_str) # Splitting on UpperCase using reres_list = []res_list = re.findall('[A-Z][^A-Z]*', ini_str) # Printing resultprint(\"Resultant prefix\", str(res_list))", "e": 26651, "s": 26316, "text": null }, { "code": null, "e": 26728, "s": 26653, "text": "Initial String GeeksForGeeks\nResultant prefix ['Geeks', 'For', 'Geeks']\n\n\n" }, { "code": null, "e": 26762, "s": 26732, "text": "Method #2: Using re.split() " }, { "code": null, "e": 26770, "s": 26762, "text": "Python3" }, { "code": "# Python code to demonstrate# to split strings# on uppercase letter import re # Initialising stringini_str = 'GeeksForGeeks' # Printing Initial stringprint (\"Initial String\", ini_str) # Splitting on UpperCase using reres_list = [s for s in re.split(\"([A-Z][^A-Z]*)\", ini_str) if s] # Printing resultprint(\"Resultant prefix\", str(res_list))", "e": 27110, "s": 26770, "text": null }, { "code": null, "e": 27185, "s": 27110, "text": "Initial String GeeksForGeeks\nResultant prefix ['Geeks', 'For', 'Geeks']\n\n\n" }, { "code": null, "e": 27220, "s": 27189, "text": " Method #3: Using enumerate " }, { "code": null, "e": 27228, "s": 27220, "text": "Python3" }, { "code": "# Python code to demonstrate# to split strings# on uppercase letter # Initialising stringini_str = 'GeeksForGeeks' # Printing Initial stringprint (\"Initial String\", ini_str) # Splitting on UpperCaseres_pos = [i for i, e in enumerate(ini_str+'A') if e.isupper()]res_list = [ini_str[res_pos[j]:res_pos[j + 1]] for j in range(len(res_pos)-1)] # Printing resultprint(\"Resultant prefix\", str(res_list))", "e": 27637, "s": 27228, "text": null }, { "code": null, "e": 27714, "s": 27639, "text": "Initial String GeeksForGeeks\nResultant prefix ['Geeks', 'For', 'Geeks']\n\n\n" }, { "code": null, "e": 27732, "s": 27718, "text": "nayeemulhkhan" }, { "code": null, "e": 27755, "s": 27732, "text": "Python string-programs" }, { "code": null, "e": 27762, "s": 27755, "text": "Python" }, { "code": null, "e": 27778, "s": 27762, "text": "Python Programs" }, { "code": null, "e": 27876, "s": 27778, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27894, "s": 27876, "text": "Python Dictionary" }, { "code": null, "e": 27926, "s": 27894, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27948, "s": 27926, "text": "Enumerate() in Python" }, { "code": null, "e": 27990, "s": 27948, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28016, "s": 27990, "text": "Python String | replace()" }, { "code": null, "e": 28038, "s": 28016, "text": "Defaultdict in Python" }, { "code": null, "e": 28077, "s": 28038, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28123, "s": 28077, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28161, "s": 28123, "text": "Python | Convert a list to dictionary" } ]
Jacobsthal and Jacobsthal-Lucas numbers - GeeksforGeeks
26 May, 2021 The Jacobsthal sequence is an additive sequence similar to the Fibonacci sequence, defined by the recurrence relation Jn = Jn-1 + 2Jn-2, with initial terms J0 = 0 and J1 = 1. A number in the sequence is called a Jacobsthal number. They are a specific type of Lucas sequence Un(P, Q) for which P = 1 and Q = -2. The first Jacobsthal numbers are: 0, 1, 1, 3, 5, 11, 21, 43, 85, 171, 341, 683, 1365, 2731, 5461, 10923, 21845, 43691, ......Jacobsthal numbers are defined by the recurrence relation: Jacobsthal-Lucas numbers Jacobsthal-Lucas numbers represent the complementary Lucas sequence Vn(1, -2). They satisfy the same recurrence relation as Jacobsthal numbers but have different initial values:Given a positive integer n. The task is to find nth Jacobsthal and Jacobsthal-Lucas numbers. Examples : Input : n = 5 Output : Jacobsthal number: 11 Jacobsthal-Lucas number: 31 Input : n = 4 Output : Jacobsthal number: 5 Jacobsthal-Lucas number: 17 Below is the implementation of finding nth Jacobsthal and Jacobsthal-Lucas numbers using recursion. C++ Java Python3 C# PHP Javascript // A simple C++ recursive solution to find// Jacobsthal and Jacobsthal-Lucas numbers#include <bits/stdc++.h>using namespace std; // Return nth Jacobsthal number.int Jacobsthal(int n){ // base case if (n == 0) return 0; // base case if (n == 1) return 1; // recursive step. return Jacobsthal(n - 1) + 2 * Jacobsthal(n - 2);} // Return nth Jacobsthal-Lucas number.int Jacobsthal_Lucas(int n){ // base case if (n == 0) return 2; // base case if (n == 1) return 1; // recursive step. return Jacobsthal_Lucas(n - 1) + 2 * Jacobsthal_Lucas(n - 2);} // Driven Programint main(){ int n = 5; cout << "Jacobsthal number: " << Jacobsthal(n) << endl; cout << "Jacobsthal-Lucas number: " << Jacobsthal_Lucas(n) << endl; return 0;} // A simple recursive solution// to find Jacobsthal and// Jacobsthal-Lucas numbersimport java.util.*;import java.lang.*; public class GfG{ // Return nth Jacobsthal number. public static int Jacobsthal(int n) { // base case if (n == 0) return 0; // base case if (n == 1) return 1; // recursive step. return Jacobsthal(n - 1) + 2 * Jacobsthal(n - 2); } // Return nth Jacobsthal-Lucas number. public static int Jacobsthal_Lucas(int n) { // base case if (n == 0) return 2; // base case if (n == 1) return 1; // recursive step. return Jacobsthal_Lucas(n - 1) + 2 * Jacobsthal_Lucas(n - 2); } // Driver function public static void main(String argc[]){ int n = 5; System.out.println("Jacobsthal number: " + Jacobsthal(n)); System.out.println("Jacobsthal-Lucas number: " + Jacobsthal_Lucas(n)); }} /* This code is contributed Sagar Shukla */ # A simple Python3 recursive solution to # find Jacobsthal and Jacobsthal-Lucas# numbers # Return nth Jacobsthal number.def Jacobsthal(n): # base case if (n == 0): return 0 # base case if (n == 1): return 1 # recursive step. return Jacobsthal(n - 1) + 2 * Jacobsthal(n - 2) # Return nth Jacobsthal-Lucas number.def Jacobsthal_Lucas(n): # base case if (n == 0): return 2 # base case if (n == 1): return 1 # recursive step. return Jacobsthal_Lucas(n - 1) + 2 * Jacobsthal_Lucas(n - 2) # Driven Programn = 5print("Jacobsthal number:", Jacobsthal(n))print("Jacobsthal-Lucas number:", Jacobsthal_Lucas(n)) # This code is contributed by Smitha Dinesh Semwal // A simple recursive solution// to find Jacobsthal and// Jacobsthal-Lucas numbersusing System; public class GfG { // Return nth Jacobsthal number. public static int Jacobsthal(int n) { // base case if (n == 0) return 0; // base case if (n == 1) return 1; // recursive step. return Jacobsthal(n - 1) + 2 * Jacobsthal(n - 2); } // Return nth Jacobsthal-Lucas number. public static int Jacobsthal_Lucas(int n) { // base case if (n == 0) return 2; // base case if (n == 1) return 1; // recursive step return Jacobsthal_Lucas(n - 1) + 2 * Jacobsthal_Lucas(n - 2); } // Driver function public static void Main() { int n = 5; Console.WriteLine("Jacobsthal number: " + Jacobsthal(n)); Console.WriteLine("Jacobsthal-Lucas number: " + Jacobsthal_Lucas(n)); }} // This code is contributed vt_m <?php// A simple PHP recursive solution// to find Jacobsthal and// Jacobsthal-Lucas numbers // Return nth Jacobsthal number.function Jacobsthal($n){ // base case if ($n == 0) return 0; // base case if ($n == 1) return 1; // recursive step. return Jacobsthal($n - 1) + 2 * Jacobsthal($n - 2);} // Return nth Jacobsthal-// Lucas number.function Jacobsthal_Lucas($n){ // base case if ($n == 0) return 2; // base case if ($n == 1) return 1; // recursive step. return Jacobsthal_Lucas($n - 1) + 2 * Jacobsthal_Lucas($n - 2);} // Driven Code$n = 5;echo "Jacobsthal number: " , Jacobsthal($n) , "\n";echo "Jacobsthal-Lucas number: ", Jacobsthal_Lucas($n), "\n"; // This code is contributed by aj_36?> <script> // JavaScript program to find max xor sum// of 1 to n using atmost k numbers // Return nth Jacobsthal number. function Jacobsthal(n) { let dp = []; // base case dp[0] = 0; dp[1] = 1; for (let i = 2; i <= n; i++) dp[i] = dp[i - 1] + 2 * dp[i - 2]; return dp[n]; } // Return nth Jacobsthal-Lucas number. function Jacobsthal_Lucas(n) { let dp = []; // base case dp[0] = 2; dp[1] = 1; for (let i = 2; i <= n; i++) dp[i] = dp[i - 1] + 2 * dp[i - 2]; return dp[n]; } // Driver code let n = 5; document.write("Jacobsthal number: " + Jacobsthal(n) + "<br/>"); document.write("Jacobsthal-Lucas number: " + Jacobsthal_Lucas(n)); </script> Output : Jacobsthal number: 11 Jacobsthal-Lucas number: 31 Below is the implementation of finding nth Jacobsthal and Jacobsthal-Lucas numbers using Dynamic Programming. C++ Java Python3 C# PHP Javascript // A DP based solution to find Jacobsthal// and Jacobsthal-Lucas numbers#include <bits/stdc++.h>using namespace std; // Return nth Jacobsthal number.int Jacobsthal(int n){ int dp[n + 1]; // base case dp[0] = 0; dp[1] = 1; for (int i = 2; i <= n; i++) dp[i] = dp[i - 1] + 2 * dp[i - 2]; return dp[n];} // Return nth Jacobsthal-Lucas number.int Jacobsthal_Lucas(int n){ int dp[n + 1]; // base case dp[0] = 2; dp[1] = 1; for (int i = 2; i <= n; i++) dp[i] = dp[i - 1] + 2 * dp[i - 2]; return dp[n];}// Driven Programint main(){ int n = 5; cout << "Jacobsthal number: " << Jacobsthal(n) << endl; cout << "Jacobsthal-Lucas number: " << Jacobsthal_Lucas(n) << endl; return 0;} // A DP based solution// to find Jacobsthal and// Jacobsthal-Lucas numbersimport java.util.*;import java.lang.*; public class GfG{ // Return nth Jacobsthal number. public static int Jacobsthal(int n) { int[] dp = new int[n + 1]; // base case dp[0] = 0; dp[1] = 1; for (int i = 2; i <= n; i++) dp[i] = dp[i - 1] + 2 * dp[i - 2]; return dp[n]; } // Return nth Jacobsthal-Lucas number. public static int Jacobsthal_Lucas(int n) { int[] dp = new int[n + 1]; // base case dp[0] = 2; dp[1] = 1; for (int i = 2; i <= n; i++) dp[i] = dp[i - 1] + 2 * dp[i - 2]; return dp[n]; } // Driver function public static void main(String argc[]){ int n = 5; System.out.println("Jacobsthal number: " + Jacobsthal(n)); System.out.println("Jacobsthal-Lucas number: " + Jacobsthal_Lucas(n)); } } /* This code is contributed Sagar Shukla */ # A DP based solution to find# Jacobsthal and Jacobsthal-# Lucas numbers # Return nth Jacobsthal number.def Jacobsthal(n): dp = [0] * (n + 1) # base case dp[0] = 0 dp[1] = 1 for i in range(2, n+1): dp[i] = dp[i - 1] + 2 * dp[i - 2] return dp[n] # Return nth Jacobsthal-# Lucas number.def Jacobsthal_Lucas(n): dp=[0] * (n + 1) # base case dp[0] = 2 dp[1] = 1 for i in range(2, n+1): dp[i] = dp[i - 1] + 2 * dp[i - 2]; return dp[n] # Driven Programn = 5 print("Jacobsthal number:",Jacobsthal(n))print("Jacobsthal-Lucas number:",Jacobsthal_Lucas(n)) # This code is contributed by Smitha Dinesh Semwal // A DP based solution// to find Jacobsthal and// Jacobsthal-Lucas numbersusing System; public class GfG { // Return nth Jacobsthal number. public static int Jacobsthal(int n) { int[] dp = new int[n + 1]; // base case dp[0] = 0; dp[1] = 1; for (int i = 2; i <= n; i++) dp[i] = dp[i - 1] + 2 * dp[i - 2]; return dp[n]; } // Return nth Jacobsthal-Lucas number. public static int Jacobsthal_Lucas(int n) { int[] dp = new int[n + 1]; // base case dp[0] = 2; dp[1] = 1; for (int i = 2; i <= n; i++) dp[i] = dp[i - 1] + 2 * dp[i - 2]; return dp[n]; } // Driver Code public static void Main() { int n = 5; Console.WriteLine("Jacobsthal number: " + Jacobsthal(n)); Console.WriteLine("Jacobsthal-Lucas number: " + Jacobsthal_Lucas(n)); } } // This code is contributed vt_m <?php// A DP based solution to// find Jacobsthal and// Jacobsthal-Lucas numbers // Return nth Jacobsthal number.function Jacobsthal($n){ //$dp[$n + 1]; // base case $dp[0] = 0; $dp[1] = 1; for ($i = 2; $i <= $n; $i++) $dp[$i] = $dp[$i - 1] + 2 * $dp[$i - 2]; return $dp[$n];} // Return nth Jacobsthal-// Lucas number.function Jacobsthal_Lucas($n){ // $dp[$n + 1]; // base case $dp[0] = 2; $dp[1] = 1; for ($i = 2; $i <= $n; $i++) $dp[$i] = $dp[$i - 1] + 2 * $dp[$i - 2]; return $dp[$n];} // Driver Code$n = 5;echo "Jacobsthal number: " , Jacobsthal($n), "\n";echo "Jacobsthal-Lucas number: " , Jacobsthal_Lucas($n), "\n"; // This code is contributed by ajit?> <script> // A DP based solution// to find Jacobsthal and// Jacobsthal-Lucas numbers // Return nth Jacobsthal number.function Jacobsthal(n){ let dp = new Array(n + 1); // Base case dp[0] = 0; dp[1] = 1; for(let i = 2; i <= n; i++) dp[i] = dp[i - 1] + 2 * dp[i - 2]; return dp[n];} // Return nth Jacobsthal-Lucas number.function Jacobsthal_Lucas(n){ let dp = new Array(n + 1); // Base case dp[0] = 2; dp[1] = 1; for(let i = 2; i <= n; i++) dp[i] = dp[i - 1] + 2 * dp[i - 2]; return dp[n];} // Driver codelet n = 5;document.write("Jacobsthal number: " + Jacobsthal(n) + "<br>");document.write("Jacobsthal-Lucas number: " + Jacobsthal_Lucas(n)); // This code is contributed by rameshtravel07 </script> Output: Jacobsthal number: 11 Jacobsthal-Lucas number: 31 jit_t PSinha splevel62 rameshtravel07 surinderdawra388 series Dynamic Programming Dynamic Programming series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Subset Sum Problem | DP-25 Matrix Chain Multiplication | DP-8 Longest Palindromic Substring | Set 1 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Edit Distance | DP-5 Sieve of Eratosthenes Overlapping Subproblems Property in Dynamic Programming | DP-1 Maximum size square sub-matrix with all 1s
[ { "code": null, "e": 25948, "s": 25920, "text": "\n26 May, 2021" }, { "code": null, "e": 26260, "s": 25948, "text": "The Jacobsthal sequence is an additive sequence similar to the Fibonacci sequence, defined by the recurrence relation Jn = Jn-1 + 2Jn-2, with initial terms J0 = 0 and J1 = 1. A number in the sequence is called a Jacobsthal number. They are a specific type of Lucas sequence Un(P, Q) for which P = 1 and Q = -2. " }, { "code": null, "e": 26445, "s": 26260, "text": "The first Jacobsthal numbers are: 0, 1, 1, 3, 5, 11, 21, 43, 85, 171, 341, 683, 1365, 2731, 5461, 10923, 21845, 43691, ......Jacobsthal numbers are defined by the recurrence relation: " }, { "code": null, "e": 26740, "s": 26445, "text": "Jacobsthal-Lucas numbers Jacobsthal-Lucas numbers represent the complementary Lucas sequence Vn(1, -2). They satisfy the same recurrence relation as Jacobsthal numbers but have different initial values:Given a positive integer n. The task is to find nth Jacobsthal and Jacobsthal-Lucas numbers." }, { "code": null, "e": 26752, "s": 26740, "text": "Examples : " }, { "code": null, "e": 26898, "s": 26752, "text": "Input : n = 5\nOutput :\nJacobsthal number: 11\nJacobsthal-Lucas number: 31\n\nInput : n = 4\nOutput :\nJacobsthal number: 5\nJacobsthal-Lucas number: 17" }, { "code": null, "e": 26999, "s": 26898, "text": "Below is the implementation of finding nth Jacobsthal and Jacobsthal-Lucas numbers using recursion. " }, { "code": null, "e": 27003, "s": 26999, "text": "C++" }, { "code": null, "e": 27008, "s": 27003, "text": "Java" }, { "code": null, "e": 27016, "s": 27008, "text": "Python3" }, { "code": null, "e": 27019, "s": 27016, "text": "C#" }, { "code": null, "e": 27023, "s": 27019, "text": "PHP" }, { "code": null, "e": 27034, "s": 27023, "text": "Javascript" }, { "code": "// A simple C++ recursive solution to find// Jacobsthal and Jacobsthal-Lucas numbers#include <bits/stdc++.h>using namespace std; // Return nth Jacobsthal number.int Jacobsthal(int n){ // base case if (n == 0) return 0; // base case if (n == 1) return 1; // recursive step. return Jacobsthal(n - 1) + 2 * Jacobsthal(n - 2);} // Return nth Jacobsthal-Lucas number.int Jacobsthal_Lucas(int n){ // base case if (n == 0) return 2; // base case if (n == 1) return 1; // recursive step. return Jacobsthal_Lucas(n - 1) + 2 * Jacobsthal_Lucas(n - 2);} // Driven Programint main(){ int n = 5; cout << \"Jacobsthal number: \" << Jacobsthal(n) << endl; cout << \"Jacobsthal-Lucas number: \" << Jacobsthal_Lucas(n) << endl; return 0;}", "e": 27842, "s": 27034, "text": null }, { "code": "// A simple recursive solution// to find Jacobsthal and// Jacobsthal-Lucas numbersimport java.util.*;import java.lang.*; public class GfG{ // Return nth Jacobsthal number. public static int Jacobsthal(int n) { // base case if (n == 0) return 0; // base case if (n == 1) return 1; // recursive step. return Jacobsthal(n - 1) + 2 * Jacobsthal(n - 2); } // Return nth Jacobsthal-Lucas number. public static int Jacobsthal_Lucas(int n) { // base case if (n == 0) return 2; // base case if (n == 1) return 1; // recursive step. return Jacobsthal_Lucas(n - 1) + 2 * Jacobsthal_Lucas(n - 2); } // Driver function public static void main(String argc[]){ int n = 5; System.out.println(\"Jacobsthal number: \" + Jacobsthal(n)); System.out.println(\"Jacobsthal-Lucas number: \" + Jacobsthal_Lucas(n)); }} /* This code is contributed Sagar Shukla */", "e": 28933, "s": 27842, "text": null }, { "code": "# A simple Python3 recursive solution to # find Jacobsthal and Jacobsthal-Lucas# numbers # Return nth Jacobsthal number.def Jacobsthal(n): # base case if (n == 0): return 0 # base case if (n == 1): return 1 # recursive step. return Jacobsthal(n - 1) + 2 * Jacobsthal(n - 2) # Return nth Jacobsthal-Lucas number.def Jacobsthal_Lucas(n): # base case if (n == 0): return 2 # base case if (n == 1): return 1 # recursive step. return Jacobsthal_Lucas(n - 1) + 2 * Jacobsthal_Lucas(n - 2) # Driven Programn = 5print(\"Jacobsthal number:\", Jacobsthal(n))print(\"Jacobsthal-Lucas number:\", Jacobsthal_Lucas(n)) # This code is contributed by Smitha Dinesh Semwal", "e": 29661, "s": 28933, "text": null }, { "code": "// A simple recursive solution// to find Jacobsthal and// Jacobsthal-Lucas numbersusing System; public class GfG { // Return nth Jacobsthal number. public static int Jacobsthal(int n) { // base case if (n == 0) return 0; // base case if (n == 1) return 1; // recursive step. return Jacobsthal(n - 1) + 2 * Jacobsthal(n - 2); } // Return nth Jacobsthal-Lucas number. public static int Jacobsthal_Lucas(int n) { // base case if (n == 0) return 2; // base case if (n == 1) return 1; // recursive step return Jacobsthal_Lucas(n - 1) + 2 * Jacobsthal_Lucas(n - 2); } // Driver function public static void Main() { int n = 5; Console.WriteLine(\"Jacobsthal number: \" + Jacobsthal(n)); Console.WriteLine(\"Jacobsthal-Lucas number: \" + Jacobsthal_Lucas(n)); }} // This code is contributed vt_m", "e": 30681, "s": 29661, "text": null }, { "code": "<?php// A simple PHP recursive solution// to find Jacobsthal and// Jacobsthal-Lucas numbers // Return nth Jacobsthal number.function Jacobsthal($n){ // base case if ($n == 0) return 0; // base case if ($n == 1) return 1; // recursive step. return Jacobsthal($n - 1) + 2 * Jacobsthal($n - 2);} // Return nth Jacobsthal-// Lucas number.function Jacobsthal_Lucas($n){ // base case if ($n == 0) return 2; // base case if ($n == 1) return 1; // recursive step. return Jacobsthal_Lucas($n - 1) + 2 * Jacobsthal_Lucas($n - 2);} // Driven Code$n = 5;echo \"Jacobsthal number: \" , Jacobsthal($n) , \"\\n\";echo \"Jacobsthal-Lucas number: \", Jacobsthal_Lucas($n), \"\\n\"; // This code is contributed by aj_36?>", "e": 31467, "s": 30681, "text": null }, { "code": "<script> // JavaScript program to find max xor sum// of 1 to n using atmost k numbers // Return nth Jacobsthal number. function Jacobsthal(n) { let dp = []; // base case dp[0] = 0; dp[1] = 1; for (let i = 2; i <= n; i++) dp[i] = dp[i - 1] + 2 * dp[i - 2]; return dp[n]; } // Return nth Jacobsthal-Lucas number. function Jacobsthal_Lucas(n) { let dp = []; // base case dp[0] = 2; dp[1] = 1; for (let i = 2; i <= n; i++) dp[i] = dp[i - 1] + 2 * dp[i - 2]; return dp[n]; } // Driver code let n = 5; document.write(\"Jacobsthal number: \" + Jacobsthal(n) + \"<br/>\"); document.write(\"Jacobsthal-Lucas number: \" + Jacobsthal_Lucas(n)); </script>", "e": 32348, "s": 31467, "text": null }, { "code": null, "e": 32358, "s": 32348, "text": "Output : " }, { "code": null, "e": 32408, "s": 32358, "text": "Jacobsthal number: 11\nJacobsthal-Lucas number: 31" }, { "code": null, "e": 32518, "s": 32408, "text": "Below is the implementation of finding nth Jacobsthal and Jacobsthal-Lucas numbers using Dynamic Programming." }, { "code": null, "e": 32522, "s": 32518, "text": "C++" }, { "code": null, "e": 32527, "s": 32522, "text": "Java" }, { "code": null, "e": 32535, "s": 32527, "text": "Python3" }, { "code": null, "e": 32538, "s": 32535, "text": "C#" }, { "code": null, "e": 32542, "s": 32538, "text": "PHP" }, { "code": null, "e": 32553, "s": 32542, "text": "Javascript" }, { "code": "// A DP based solution to find Jacobsthal// and Jacobsthal-Lucas numbers#include <bits/stdc++.h>using namespace std; // Return nth Jacobsthal number.int Jacobsthal(int n){ int dp[n + 1]; // base case dp[0] = 0; dp[1] = 1; for (int i = 2; i <= n; i++) dp[i] = dp[i - 1] + 2 * dp[i - 2]; return dp[n];} // Return nth Jacobsthal-Lucas number.int Jacobsthal_Lucas(int n){ int dp[n + 1]; // base case dp[0] = 2; dp[1] = 1; for (int i = 2; i <= n; i++) dp[i] = dp[i - 1] + 2 * dp[i - 2]; return dp[n];}// Driven Programint main(){ int n = 5; cout << \"Jacobsthal number: \" << Jacobsthal(n) << endl; cout << \"Jacobsthal-Lucas number: \" << Jacobsthal_Lucas(n) << endl; return 0;}", "e": 33292, "s": 32553, "text": null }, { "code": "// A DP based solution// to find Jacobsthal and// Jacobsthal-Lucas numbersimport java.util.*;import java.lang.*; public class GfG{ // Return nth Jacobsthal number. public static int Jacobsthal(int n) { int[] dp = new int[n + 1]; // base case dp[0] = 0; dp[1] = 1; for (int i = 2; i <= n; i++) dp[i] = dp[i - 1] + 2 * dp[i - 2]; return dp[n]; } // Return nth Jacobsthal-Lucas number. public static int Jacobsthal_Lucas(int n) { int[] dp = new int[n + 1]; // base case dp[0] = 2; dp[1] = 1; for (int i = 2; i <= n; i++) dp[i] = dp[i - 1] + 2 * dp[i - 2]; return dp[n]; } // Driver function public static void main(String argc[]){ int n = 5; System.out.println(\"Jacobsthal number: \" + Jacobsthal(n)); System.out.println(\"Jacobsthal-Lucas number: \" + Jacobsthal_Lucas(n)); } } /* This code is contributed Sagar Shukla */", "e": 34336, "s": 33292, "text": null }, { "code": "# A DP based solution to find# Jacobsthal and Jacobsthal-# Lucas numbers # Return nth Jacobsthal number.def Jacobsthal(n): dp = [0] * (n + 1) # base case dp[0] = 0 dp[1] = 1 for i in range(2, n+1): dp[i] = dp[i - 1] + 2 * dp[i - 2] return dp[n] # Return nth Jacobsthal-# Lucas number.def Jacobsthal_Lucas(n): dp=[0] * (n + 1) # base case dp[0] = 2 dp[1] = 1 for i in range(2, n+1): dp[i] = dp[i - 1] + 2 * dp[i - 2]; return dp[n] # Driven Programn = 5 print(\"Jacobsthal number:\",Jacobsthal(n))print(\"Jacobsthal-Lucas number:\",Jacobsthal_Lucas(n)) # This code is contributed by Smitha Dinesh Semwal", "e": 35008, "s": 34336, "text": null }, { "code": "// A DP based solution// to find Jacobsthal and// Jacobsthal-Lucas numbersusing System; public class GfG { // Return nth Jacobsthal number. public static int Jacobsthal(int n) { int[] dp = new int[n + 1]; // base case dp[0] = 0; dp[1] = 1; for (int i = 2; i <= n; i++) dp[i] = dp[i - 1] + 2 * dp[i - 2]; return dp[n]; } // Return nth Jacobsthal-Lucas number. public static int Jacobsthal_Lucas(int n) { int[] dp = new int[n + 1]; // base case dp[0] = 2; dp[1] = 1; for (int i = 2; i <= n; i++) dp[i] = dp[i - 1] + 2 * dp[i - 2]; return dp[n]; } // Driver Code public static void Main() { int n = 5; Console.WriteLine(\"Jacobsthal number: \" + Jacobsthal(n)); Console.WriteLine(\"Jacobsthal-Lucas number: \" + Jacobsthal_Lucas(n)); } } // This code is contributed vt_m", "e": 36007, "s": 35008, "text": null }, { "code": "<?php// A DP based solution to// find Jacobsthal and// Jacobsthal-Lucas numbers // Return nth Jacobsthal number.function Jacobsthal($n){ //$dp[$n + 1]; // base case $dp[0] = 0; $dp[1] = 1; for ($i = 2; $i <= $n; $i++) $dp[$i] = $dp[$i - 1] + 2 * $dp[$i - 2]; return $dp[$n];} // Return nth Jacobsthal-// Lucas number.function Jacobsthal_Lucas($n){ // $dp[$n + 1]; // base case $dp[0] = 2; $dp[1] = 1; for ($i = 2; $i <= $n; $i++) $dp[$i] = $dp[$i - 1] + 2 * $dp[$i - 2]; return $dp[$n];} // Driver Code$n = 5;echo \"Jacobsthal number: \" , Jacobsthal($n), \"\\n\";echo \"Jacobsthal-Lucas number: \" , Jacobsthal_Lucas($n), \"\\n\"; // This code is contributed by ajit?>", "e": 36777, "s": 36007, "text": null }, { "code": "<script> // A DP based solution// to find Jacobsthal and// Jacobsthal-Lucas numbers // Return nth Jacobsthal number.function Jacobsthal(n){ let dp = new Array(n + 1); // Base case dp[0] = 0; dp[1] = 1; for(let i = 2; i <= n; i++) dp[i] = dp[i - 1] + 2 * dp[i - 2]; return dp[n];} // Return nth Jacobsthal-Lucas number.function Jacobsthal_Lucas(n){ let dp = new Array(n + 1); // Base case dp[0] = 2; dp[1] = 1; for(let i = 2; i <= n; i++) dp[i] = dp[i - 1] + 2 * dp[i - 2]; return dp[n];} // Driver codelet n = 5;document.write(\"Jacobsthal number: \" + Jacobsthal(n) + \"<br>\");document.write(\"Jacobsthal-Lucas number: \" + Jacobsthal_Lucas(n)); // This code is contributed by rameshtravel07 </script>", "e": 37559, "s": 36777, "text": null }, { "code": null, "e": 37568, "s": 37559, "text": "Output: " }, { "code": null, "e": 37618, "s": 37568, "text": "Jacobsthal number: 11\nJacobsthal-Lucas number: 31" }, { "code": null, "e": 37626, "s": 37620, "text": "jit_t" }, { "code": null, "e": 37633, "s": 37626, "text": "PSinha" }, { "code": null, "e": 37643, "s": 37633, "text": "splevel62" }, { "code": null, "e": 37658, "s": 37643, "text": "rameshtravel07" }, { "code": null, "e": 37675, "s": 37658, "text": "surinderdawra388" }, { "code": null, "e": 37682, "s": 37675, "text": "series" }, { "code": null, "e": 37702, "s": 37682, "text": "Dynamic Programming" }, { "code": null, "e": 37722, "s": 37702, "text": "Dynamic Programming" }, { "code": null, "e": 37729, "s": 37722, "text": "series" }, { "code": null, "e": 37827, "s": 37729, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37858, "s": 37827, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 37891, "s": 37858, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 37918, "s": 37891, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 37953, "s": 37918, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 37991, "s": 37953, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 38059, "s": 37991, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 38080, "s": 38059, "text": "Edit Distance | DP-5" }, { "code": null, "e": 38102, "s": 38080, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 38165, "s": 38102, "text": "Overlapping Subproblems Property in Dynamic Programming | DP-1" } ]
p5.js | style() Function - GeeksforGeeks
21 Aug, 2019 The style() function is used to set the style property of an element with the given value. If this function contains single parameter then use .style() function to return the value of the given property. Note: This function requires the p5.dom library. So add the following line in the head section of the index.html file. <script language=”javascript” type=”text/javascript” src=”path/to/p5.dom.js”></script> Syntax: style( property ) or style( property, value ) Parameters: property: This parameter holds the CSS property name. value: This parameter holds the value of CSS property. Return Value: This function returns the value of property. Example 1: function setup() { // Create canvas of size 400*200 createCanvas(400, 200); // Set background color background('green'); // Create an input element var input_val = createInput(''); // Set the attribute and its value input_val.attribute('value', 'Welcome to GeeksforGeeks'); // Set the position of div element input_val.position(60, 80); // Set width of input field input_val.style('width', '250px'); // Set font-size of input text input_val.style('font-size', '20px'); } Output: Example 2: function setup() { // Create canvas of size 400*200 createCanvas(400, 200); // Set background color background('green'); // Create an input element var div_cont = createDiv('Welcome to GeeksforGeeks'); // Set the position of div element div_cont.position(60, 80); // Set the font color div_cont.style('color', '#ffffff'); // Set width of input field div_cont.style('width', '250px'); // Set font-size of input text div_cont.style('font-size', '20px'); } Output: JavaScript-p5.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 25497, "s": 25469, "text": "\n21 Aug, 2019" }, { "code": null, "e": 25701, "s": 25497, "text": "The style() function is used to set the style property of an element with the given value. If this function contains single parameter then use .style() function to return the value of the given property." }, { "code": null, "e": 25820, "s": 25701, "text": "Note: This function requires the p5.dom library. So add the following line in the head section of the index.html file." }, { "code": null, "e": 25907, "s": 25820, "text": "<script language=”javascript” type=”text/javascript” src=”path/to/p5.dom.js”></script>" }, { "code": null, "e": 25915, "s": 25907, "text": "Syntax:" }, { "code": null, "e": 25933, "s": 25915, "text": "style( property )" }, { "code": null, "e": 25936, "s": 25933, "text": "or" }, { "code": null, "e": 25961, "s": 25936, "text": "style( property, value )" }, { "code": null, "e": 25973, "s": 25961, "text": "Parameters:" }, { "code": null, "e": 26027, "s": 25973, "text": "property: This parameter holds the CSS property name." }, { "code": null, "e": 26082, "s": 26027, "text": "value: This parameter holds the value of CSS property." }, { "code": null, "e": 26141, "s": 26082, "text": "Return Value: This function returns the value of property." }, { "code": null, "e": 26152, "s": 26141, "text": "Example 1:" }, { "code": "function setup() { // Create canvas of size 400*200 createCanvas(400, 200); // Set background color background('green'); // Create an input element var input_val = createInput(''); // Set the attribute and its value input_val.attribute('value', 'Welcome to GeeksforGeeks'); // Set the position of div element input_val.position(60, 80); // Set width of input field input_val.style('width', '250px'); // Set font-size of input text input_val.style('font-size', '20px'); } ", "e": 26715, "s": 26152, "text": null }, { "code": null, "e": 26723, "s": 26715, "text": "Output:" }, { "code": null, "e": 26734, "s": 26723, "text": "Example 2:" }, { "code": "function setup() { // Create canvas of size 400*200 createCanvas(400, 200); // Set background color background('green'); // Create an input element var div_cont = createDiv('Welcome to GeeksforGeeks'); // Set the position of div element div_cont.position(60, 80); // Set the font color div_cont.style('color', '#ffffff'); // Set width of input field div_cont.style('width', '250px'); // Set font-size of input text div_cont.style('font-size', '20px'); } ", "e": 27272, "s": 26734, "text": null }, { "code": null, "e": 27280, "s": 27272, "text": "Output:" }, { "code": null, "e": 27297, "s": 27280, "text": "JavaScript-p5.js" }, { "code": null, "e": 27308, "s": 27297, "text": "JavaScript" }, { "code": null, "e": 27325, "s": 27308, "text": "Web Technologies" }, { "code": null, "e": 27423, "s": 27325, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27463, "s": 27423, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27508, "s": 27463, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27569, "s": 27508, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27641, "s": 27569, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27693, "s": 27641, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 27733, "s": 27693, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27766, "s": 27733, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27811, "s": 27766, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27854, "s": 27811, "text": "How to fetch data from an API in ReactJS ?" } ]
Python | os.set_blocking() method - GeeksforGeeks
18 Jun, 2019 OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.set_blocking() method in Python is used to set the blocking mode of the specified file descriptor. This method modifies the os.O_NONBLOCK flag. It sets the os.O_NONBLOCK flag for non-blocking mode and clears the os.O_NONBLOCK flag for blocking mode. A file descriptor in blocking mode means that I/O system calls like read, write, or connect can be blocked by the system.For example: If we call read system call on stdin then our program will get blocked (the kernel will put the process into the sleeping state) until data to be read is actually available on stdin. Note: os.set_blocking() method is available on Unix platforms only. Syntax: os.set_blocking(fd, blocking) Parameter:fd: A file descriptor whose blocking mode is to be set.blocking: A Boolean value. True if the file descriptor is to be put into blocking mode and false if the file descriptor is to be put into non-blocking mode. Return Type: This method does not return any value. # Python program to explain os.set_blocking() method # importing os module import os # File path path = "/home/ihritik/Documents/file.txt" # Open the file and get# the file descriptor associated# with it using os.open() methodfd = os.open(path, os.O_RDWR) # Get the current blocking mode# of the file descriptor# using os.get_blocking() methodprint("Blocking Mode:", os.get_blocking(fd)) # Change the blocking modeblocking = Falseos.set_blocking(fd, blocking)print("Blocking mode changed") # Get the blocking mode# of the file descriptor# using os.get_blocking() methodprint("Blocking Mode:", os.get_blocking(fd)) # close the file descriptoros.close(fd) # A False value for blocking# mode denotes that the file# descriptor has been put into# Non-Blocking mode while True# denotes that file descriptor# is in blocking mode. Blocking Mode: True Blocking mode changed Blocking Mode: False Reference: https://docs.python.org/3/library/os.html#os.set_blocking python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n18 Jun, 2019" }, { "code": null, "e": 25756, "s": 25537, "text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality." }, { "code": null, "e": 26009, "s": 25756, "text": "os.set_blocking() method in Python is used to set the blocking mode of the specified file descriptor. This method modifies the os.O_NONBLOCK flag. It sets the os.O_NONBLOCK flag for non-blocking mode and clears the os.O_NONBLOCK flag for blocking mode." }, { "code": null, "e": 26326, "s": 26009, "text": "A file descriptor in blocking mode means that I/O system calls like read, write, or connect can be blocked by the system.For example: If we call read system call on stdin then our program will get blocked (the kernel will put the process into the sleeping state) until data to be read is actually available on stdin." }, { "code": null, "e": 26394, "s": 26326, "text": "Note: os.set_blocking() method is available on Unix platforms only." }, { "code": null, "e": 26432, "s": 26394, "text": "Syntax: os.set_blocking(fd, blocking)" }, { "code": null, "e": 26654, "s": 26432, "text": "Parameter:fd: A file descriptor whose blocking mode is to be set.blocking: A Boolean value. True if the file descriptor is to be put into blocking mode and false if the file descriptor is to be put into non-blocking mode." }, { "code": null, "e": 26706, "s": 26654, "text": "Return Type: This method does not return any value." }, { "code": "# Python program to explain os.set_blocking() method # importing os module import os # File path path = \"/home/ihritik/Documents/file.txt\" # Open the file and get# the file descriptor associated# with it using os.open() methodfd = os.open(path, os.O_RDWR) # Get the current blocking mode# of the file descriptor# using os.get_blocking() methodprint(\"Blocking Mode:\", os.get_blocking(fd)) # Change the blocking modeblocking = Falseos.set_blocking(fd, blocking)print(\"Blocking mode changed\") # Get the blocking mode# of the file descriptor# using os.get_blocking() methodprint(\"Blocking Mode:\", os.get_blocking(fd)) # close the file descriptoros.close(fd) # A False value for blocking# mode denotes that the file# descriptor has been put into# Non-Blocking mode while True# denotes that file descriptor# is in blocking mode.", "e": 27552, "s": 26706, "text": null }, { "code": null, "e": 27616, "s": 27552, "text": "Blocking Mode: True\nBlocking mode changed\nBlocking Mode: False\n" }, { "code": null, "e": 27685, "s": 27616, "text": "Reference: https://docs.python.org/3/library/os.html#os.set_blocking" }, { "code": null, "e": 27702, "s": 27685, "text": "python-os-module" }, { "code": null, "e": 27709, "s": 27702, "text": "Python" }, { "code": null, "e": 27807, "s": 27709, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27839, "s": 27807, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27881, "s": 27839, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27923, "s": 27881, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27979, "s": 27923, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28006, "s": 27979, "text": "Python Classes and Objects" }, { "code": null, "e": 28045, "s": 28006, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28076, "s": 28045, "text": "Python | os.path.join() method" }, { "code": null, "e": 28098, "s": 28076, "text": "Defaultdict in Python" }, { "code": null, "e": 28127, "s": 28098, "text": "Create a directory in Python" } ]
How to debug PHP scripts ? - GeeksforGeeks
25 Jun, 2019 When we write huge lines of code in PHP and then some error occurs then removing that error might be a heck of the task. Some basic errors that programmer do while programming in PHP which are: Missing Semicolon “;” and closing brackets “}”.To debug the above errors, using a good PHP ide will be very helpful as it will suggest the closing bracket “}” and end of statement by “;”. Misspelling a variable name. Remember $var != $Var as we know, PHP is a case sensitive language. Using “=” instead of “==” (Assignment operator and Equal operator)Example:if($a = $b) { // Statement }This will always result in True as it is never an error to assign one variable to another. if($a = $b) { // Statement } This will always result in True as it is never an error to assign one variable to another. Missing quotes in SQL queries like ‘ ‘ and ” “. This is a very common and frequent error that occurs while PHP programming. To debug this kind of error always use mysqli_error($con) command with echo to see what error you are doing in SQL statements where $con is the connection variable that you are using.Example:if (!mysqli_query($conn, $sql)) { echo "Error: " . $sql . "" . mysqli_error($con); } if (!mysqli_query($conn, $sql)) { echo "Error: " . $sql . "" . mysqli_error($con); } If your PHP script produces no output while running then make sure that “display_errors” is set to on in php.ini file. “Parse Error” – This error occurs when your code is not understood by PHP. This error generally occurs with a syntax error. “Misunderstanding isset() behavior” – Despite its name, isset() not only returns false if an item does not exist but also returns false for null values. This behavior is more problematic than it might appear at first and is a common source of problems.Example:$data = fetchRecordFromStorage($storage, $identifier); if (!isset($data['keyShouldBeSet']) { // do something here if 'keyShouldBeSet' is not set } The author of this code presumably wanted to check if keyShouldBeSet was set in $data. But, as discussed, isset($data[‘keyShouldBeSet’]) will also return false if $data[‘keyShouldBeSet’] was set, but was set to null. So the above logic is flawed. $data = fetchRecordFromStorage($storage, $identifier); if (!isset($data['keyShouldBeSet']) { // do something here if 'keyShouldBeSet' is not set } The author of this code presumably wanted to check if keyShouldBeSet was set in $data. But, as discussed, isset($data[‘keyShouldBeSet’]) will also return false if $data[‘keyShouldBeSet’] was set, but was set to null. So the above logic is flawed. One common error is missing PHP closing before using HTML commands. So always close PHP with “?>”and then write HTML code and after ending HTML code use “<?php” to again start php coding. PHP debugging tools: PHP code can be debug using one of many debugging tools to attach a debugger client. PhpStorm works with debug utilities like Xdebug and ZendDebugger.Being a polyglot (knowing or using several languages), we need an IDE that supports multiple languages. The Xdebug with Visual Studio is used in the past, so let’s see how to set it up with the VS Code.The debug server setup is the same, but each client (IDE or CLI) will have a slightly different setup. See the debug server (a Zend extension) opens a port, and the client communicates with the server through that port. It is just a matter of configuration and installing the right components.Here are the steps to doing PHP programming:Check for PHP extensions in VS Code.Install the PHP Debug extension.Click “reload” to reload VS Code.Install Xdebug. The PHP Debug extension for VS Code is only integration to Xdebug. If we install PHP 7.0 then it must get the right version of Xdebug from the download page.Now when you have the right version, put it in the PHP/ext directory.Next, you need to configure PHP to use the extension and allow remote debugging. Add the following configuration to the php.ini file that’s listed in PHP Info:; set the extension path zend_extension="C:/Program Files (x86)/PHP/v7.0/ext/php_xdebug-2.6.1-7.0-vc14-nts.dll" ; allow remote debugging [XDebug] xdebug.remote_enable = 1 xdebug.remote_autostart = 1 It will set up the PHP server to use XDebug. The steps here are the same no matter what IDE you use.Xdebug opens an HTTP port so that your debugger can attach. The client still needs to be configured to attach and use the debugging protocol.Finally, configure VS Code to connect to Xdebug. There are a few simple steps and then attaching is automatic. Being a polyglot (knowing or using several languages), we need an IDE that supports multiple languages. The Xdebug with Visual Studio is used in the past, so let’s see how to set it up with the VS Code. The debug server setup is the same, but each client (IDE or CLI) will have a slightly different setup. See the debug server (a Zend extension) opens a port, and the client communicates with the server through that port. It is just a matter of configuration and installing the right components. Here are the steps to doing PHP programming: Check for PHP extensions in VS Code. Install the PHP Debug extension. Click “reload” to reload VS Code. Install Xdebug. The PHP Debug extension for VS Code is only integration to Xdebug. If we install PHP 7.0 then it must get the right version of Xdebug from the download page. Now when you have the right version, put it in the PHP/ext directory. Next, you need to configure PHP to use the extension and allow remote debugging. Add the following configuration to the php.ini file that’s listed in PHP Info:; set the extension path zend_extension="C:/Program Files (x86)/PHP/v7.0/ext/php_xdebug-2.6.1-7.0-vc14-nts.dll" ; allow remote debugging [XDebug] xdebug.remote_enable = 1 xdebug.remote_autostart = 1 It will set up the PHP server to use XDebug. The steps here are the same no matter what IDE you use. ; set the extension path zend_extension="C:/Program Files (x86)/PHP/v7.0/ext/php_xdebug-2.6.1-7.0-vc14-nts.dll" ; allow remote debugging [XDebug] xdebug.remote_enable = 1 xdebug.remote_autostart = 1 It will set up the PHP server to use XDebug. The steps here are the same no matter what IDE you use. Xdebug opens an HTTP port so that your debugger can attach. The client still needs to be configured to attach and use the debugging protocol. Finally, configure VS Code to connect to Xdebug. There are a few simple steps and then attaching is automatic. Configuring your IDE: After installing Xdebug, you need to configure IDE to attach to the debugger. In VS Code, this means adding a debug configuration. Fortunately, it is automatic at this point. It’s just a few simple steps:Switch to the debug view.Click the gear to bring up the languages menu.Select PHP. Visual Studio Code will generate the default configuration.Reload the PHP server. We have to install another extension called “PHP Server” that makes this simple. Use the context menu (right-click) to control the PHP server.It puts the IDE in a state which is ready to attach to Xdebug. Communications with the debugger happen through a TCP port on the debug server. Xdebug uses the DBGp protocol through port 9000 by default. Switch to the debug view. Click the gear to bring up the languages menu. Select PHP. Visual Studio Code will generate the default configuration. Reload the PHP server. We have to install another extension called “PHP Server” that makes this simple. Use the context menu (right-click) to control the PHP server. It puts the IDE in a state which is ready to attach to Xdebug. Communications with the debugger happen through a TCP port on the debug server. Xdebug uses the DBGp protocol through port 9000 by default. Attaching a debugger: The PHP Debug extension for VS Code generated a launch.json file. That file goes into a .vscode directory in the root of the project.{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Listen for XDebug", "type": "php", "request": "launch", "port": 9000 }, { "name": "Launch currently open script", "type": "php", "request": "launch", "program": "${file}", "cwd": "${fileDirname}", "port": 9000 } ] } It’s adding two launch configurations. Those are available in the debug view. We can either attach to a running server or launch a new one with the current script. Since I have phpinfo running already, I will start there by choosing Listen for XDebug to attach to that server. Once you are attached, you will see the debug toolbar. Most debuggers have a similar control mechanism which allows to start, stop, step, and restart debugger. { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Listen for XDebug", "type": "php", "request": "launch", "port": 9000 }, { "name": "Launch currently open script", "type": "php", "request": "launch", "program": "${file}", "cwd": "${fileDirname}", "port": 9000 } ] } It’s adding two launch configurations. Those are available in the debug view. We can either attach to a running server or launch a new one with the current script. Since I have phpinfo running already, I will start there by choosing Listen for XDebug to attach to that server. Once you are attached, you will see the debug toolbar. Most debuggers have a similar control mechanism which allows to start, stop, step, and restart debugger. Switching error reporting level: PHP has a few ways to configure error reporting. You can use the php.ini file and you have to access it. Otherwise, you might use the htaccess configuration. If you can’t use configuration files, you have the option of changing the values via a script. A combination of settings will get the right levels of error logging. You want to consider the following settings:error_reporting sets the level of logging.E_NOTICE is useful during development since it will tell about defects such as unassigned variables.display_errors is used to display the error messages.display_startup_errors should only be used when debugging.log_errors and error_log work together to send errors to a log file. Do this in production rather than displaying them to end users.The PHP manual spells out these settings in more detail and provides more information. error_reporting sets the level of logging. E_NOTICE is useful during development since it will tell about defects such as unassigned variables. display_errors is used to display the error messages. display_startup_errors should only be used when debugging. log_errors and error_log work together to send errors to a log file. Do this in production rather than displaying them to end users. The PHP manual spells out these settings in more detail and provides more information. Picked PHP Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? PHP | Converting string to Date and DateTime Comparing two dates in PHP How to pass JavaScript variables to PHP ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 26039, "s": 26011, "text": "\n25 Jun, 2019" }, { "code": null, "e": 26233, "s": 26039, "text": "When we write huge lines of code in PHP and then some error occurs then removing that error might be a heck of the task. Some basic errors that programmer do while programming in PHP which are:" }, { "code": null, "e": 26421, "s": 26233, "text": "Missing Semicolon “;” and closing brackets “}”.To debug the above errors, using a good PHP ide will be very helpful as it will suggest the closing bracket “}” and end of statement by “;”." }, { "code": null, "e": 26518, "s": 26421, "text": "Misspelling a variable name. Remember $var != $Var as we know, PHP is a case sensitive language." }, { "code": null, "e": 26715, "s": 26518, "text": "Using “=” instead of “==” (Assignment operator and Equal operator)Example:if($a = $b) {\n // Statement\n}This will always result in True as it is never an error to assign one variable to another." }, { "code": null, "e": 26748, "s": 26715, "text": "if($a = $b) {\n // Statement\n}" }, { "code": null, "e": 26839, "s": 26748, "text": "This will always result in True as it is never an error to assign one variable to another." }, { "code": null, "e": 27244, "s": 26839, "text": "Missing quotes in SQL queries like ‘ ‘ and ” “. This is a very common and frequent error that occurs while PHP programming. To debug this kind of error always use mysqli_error($con) command with echo to see what error you are doing in SQL statements where $con is the connection variable that you are using.Example:if (!mysqli_query($conn, $sql)) {\n echo \"Error: \" . $sql . \"\" . mysqli_error($con);\n}\n" }, { "code": null, "e": 27334, "s": 27244, "text": "if (!mysqli_query($conn, $sql)) {\n echo \"Error: \" . $sql . \"\" . mysqli_error($con);\n}\n" }, { "code": null, "e": 27453, "s": 27334, "text": "If your PHP script produces no output while running then make sure that “display_errors” is set to on in php.ini file." }, { "code": null, "e": 27577, "s": 27453, "text": "“Parse Error” – This error occurs when your code is not understood by PHP. This error generally occurs with a syntax error." }, { "code": null, "e": 28235, "s": 27577, "text": "“Misunderstanding isset() behavior” – Despite its name, isset() not only returns false if an item does not exist but also returns false for null values. This behavior is more problematic than it might appear at first and is a common source of problems.Example:$data = fetchRecordFromStorage($storage, $identifier);\nif (!isset($data['keyShouldBeSet']) {\n // do something here if 'keyShouldBeSet' is not set\n}\nThe author of this code presumably wanted to check if keyShouldBeSet was set in $data. But, as discussed, isset($data[‘keyShouldBeSet’]) will also return false if $data[‘keyShouldBeSet’] was set, but was set to null. So the above logic is flawed." }, { "code": null, "e": 28387, "s": 28235, "text": "$data = fetchRecordFromStorage($storage, $identifier);\nif (!isset($data['keyShouldBeSet']) {\n // do something here if 'keyShouldBeSet' is not set\n}\n" }, { "code": null, "e": 28634, "s": 28387, "text": "The author of this code presumably wanted to check if keyShouldBeSet was set in $data. But, as discussed, isset($data[‘keyShouldBeSet’]) will also return false if $data[‘keyShouldBeSet’] was set, but was set to null. So the above logic is flawed." }, { "code": null, "e": 28822, "s": 28634, "text": "One common error is missing PHP closing before using HTML commands. So always close PHP with “?>”and then write HTML code and after ending HTML code use “<?php” to again start php coding." }, { "code": null, "e": 30586, "s": 28822, "text": "PHP debugging tools: PHP code can be debug using one of many debugging tools to attach a debugger client. PhpStorm works with debug utilities like Xdebug and ZendDebugger.Being a polyglot (knowing or using several languages), we need an IDE that supports multiple languages. The Xdebug with Visual Studio is used in the past, so let’s see how to set it up with the VS Code.The debug server setup is the same, but each client (IDE or CLI) will have a slightly different setup. See the debug server (a Zend extension) opens a port, and the client communicates with the server through that port. It is just a matter of configuration and installing the right components.Here are the steps to doing PHP programming:Check for PHP extensions in VS Code.Install the PHP Debug extension.Click “reload” to reload VS Code.Install Xdebug. The PHP Debug extension for VS Code is only integration to Xdebug. If we install PHP 7.0 then it must get the right version of Xdebug from the download page.Now when you have the right version, put it in the PHP/ext directory.Next, you need to configure PHP to use the extension and allow remote debugging. Add the following configuration to the php.ini file that’s listed in PHP Info:; set the extension path\nzend_extension=\"C:/Program Files \n(x86)/PHP/v7.0/ext/php_xdebug-2.6.1-7.0-vc14-nts.dll\"\n; allow remote debugging\n[XDebug]\nxdebug.remote_enable = 1\nxdebug.remote_autostart = 1\nIt will set up the PHP server to use XDebug. The steps here are the same no matter what IDE you use.Xdebug opens an HTTP port so that your debugger can attach. The client still needs to be configured to attach and use the debugging protocol.Finally, configure VS Code to connect to Xdebug. There are a few simple steps and then attaching is automatic." }, { "code": null, "e": 30789, "s": 30586, "text": "Being a polyglot (knowing or using several languages), we need an IDE that supports multiple languages. The Xdebug with Visual Studio is used in the past, so let’s see how to set it up with the VS Code." }, { "code": null, "e": 31083, "s": 30789, "text": "The debug server setup is the same, but each client (IDE or CLI) will have a slightly different setup. See the debug server (a Zend extension) opens a port, and the client communicates with the server through that port. It is just a matter of configuration and installing the right components." }, { "code": null, "e": 31128, "s": 31083, "text": "Here are the steps to doing PHP programming:" }, { "code": null, "e": 31165, "s": 31128, "text": "Check for PHP extensions in VS Code." }, { "code": null, "e": 31198, "s": 31165, "text": "Install the PHP Debug extension." }, { "code": null, "e": 31232, "s": 31198, "text": "Click “reload” to reload VS Code." }, { "code": null, "e": 31406, "s": 31232, "text": "Install Xdebug. The PHP Debug extension for VS Code is only integration to Xdebug. If we install PHP 7.0 then it must get the right version of Xdebug from the download page." }, { "code": null, "e": 31476, "s": 31406, "text": "Now when you have the right version, put it in the PHP/ext directory." }, { "code": null, "e": 31936, "s": 31476, "text": "Next, you need to configure PHP to use the extension and allow remote debugging. Add the following configuration to the php.ini file that’s listed in PHP Info:; set the extension path\nzend_extension=\"C:/Program Files \n(x86)/PHP/v7.0/ext/php_xdebug-2.6.1-7.0-vc14-nts.dll\"\n; allow remote debugging\n[XDebug]\nxdebug.remote_enable = 1\nxdebug.remote_autostart = 1\nIt will set up the PHP server to use XDebug. The steps here are the same no matter what IDE you use." }, { "code": null, "e": 32137, "s": 31936, "text": "; set the extension path\nzend_extension=\"C:/Program Files \n(x86)/PHP/v7.0/ext/php_xdebug-2.6.1-7.0-vc14-nts.dll\"\n; allow remote debugging\n[XDebug]\nxdebug.remote_enable = 1\nxdebug.remote_autostart = 1\n" }, { "code": null, "e": 32238, "s": 32137, "text": "It will set up the PHP server to use XDebug. The steps here are the same no matter what IDE you use." }, { "code": null, "e": 32380, "s": 32238, "text": "Xdebug opens an HTTP port so that your debugger can attach. The client still needs to be configured to attach and use the debugging protocol." }, { "code": null, "e": 32491, "s": 32380, "text": "Finally, configure VS Code to connect to Xdebug. There are a few simple steps and then attaching is automatic." }, { "code": null, "e": 33227, "s": 32491, "text": "Configuring your IDE: After installing Xdebug, you need to configure IDE to attach to the debugger. In VS Code, this means adding a debug configuration. Fortunately, it is automatic at this point. It’s just a few simple steps:Switch to the debug view.Click the gear to bring up the languages menu.Select PHP. Visual Studio Code will generate the default configuration.Reload the PHP server. We have to install another extension called “PHP Server” that makes this simple. Use the context menu (right-click) to control the PHP server.It puts the IDE in a state which is ready to attach to Xdebug. Communications with the debugger happen through a TCP port on the debug server. Xdebug uses the DBGp protocol through port 9000 by default." }, { "code": null, "e": 33253, "s": 33227, "text": "Switch to the debug view." }, { "code": null, "e": 33300, "s": 33253, "text": "Click the gear to bring up the languages menu." }, { "code": null, "e": 33372, "s": 33300, "text": "Select PHP. Visual Studio Code will generate the default configuration." }, { "code": null, "e": 33538, "s": 33372, "text": "Reload the PHP server. We have to install another extension called “PHP Server” that makes this simple. Use the context menu (right-click) to control the PHP server." }, { "code": null, "e": 33741, "s": 33538, "text": "It puts the IDE in a state which is ready to attach to Xdebug. Communications with the debugger happen through a TCP port on the debug server. Xdebug uses the DBGp protocol through port 9000 by default." }, { "code": null, "e": 34968, "s": 33741, "text": "Attaching a debugger: The PHP Debug extension for VS Code generated a launch.json file. That file goes into a .vscode directory in the root of the project.{\n // Use IntelliSense to learn about possible attributes.\n // Hover to view descriptions of existing attributes.\n // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387\n\n \"version\": \"0.2.0\",\n \"configurations\": [\n {\n \"name\": \"Listen for XDebug\",\n \"type\": \"php\",\n \"request\": \"launch\",\n \"port\": 9000\n },\n {\n \"name\": \"Launch currently open script\",\n \"type\": \"php\",\n \"request\": \"launch\",\n \"program\": \"${file}\",\n \"cwd\": \"${fileDirname}\",\n \"port\": 9000\n }\n ]\n}\nIt’s adding two launch configurations. Those are available in the debug view. We can either attach to a running server or launch a new one with the current script. Since I have phpinfo running already, I will start there by choosing Listen for XDebug to attach to that server. Once you are attached, you will see the debug toolbar. Most debuggers have a similar control mechanism which allows to start, stop, step, and restart debugger." }, { "code": null, "e": 35604, "s": 34968, "text": "{\n // Use IntelliSense to learn about possible attributes.\n // Hover to view descriptions of existing attributes.\n // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387\n\n \"version\": \"0.2.0\",\n \"configurations\": [\n {\n \"name\": \"Listen for XDebug\",\n \"type\": \"php\",\n \"request\": \"launch\",\n \"port\": 9000\n },\n {\n \"name\": \"Launch currently open script\",\n \"type\": \"php\",\n \"request\": \"launch\",\n \"program\": \"${file}\",\n \"cwd\": \"${fileDirname}\",\n \"port\": 9000\n }\n ]\n}\n" }, { "code": null, "e": 36041, "s": 35604, "text": "It’s adding two launch configurations. Those are available in the debug view. We can either attach to a running server or launch a new one with the current script. Since I have phpinfo running already, I will start there by choosing Listen for XDebug to attach to that server. Once you are attached, you will see the debug toolbar. Most debuggers have a similar control mechanism which allows to start, stop, step, and restart debugger." }, { "code": null, "e": 36913, "s": 36041, "text": "Switching error reporting level: PHP has a few ways to configure error reporting. You can use the php.ini file and you have to access it. Otherwise, you might use the htaccess configuration. If you can’t use configuration files, you have the option of changing the values via a script. A combination of settings will get the right levels of error logging. You want to consider the following settings:error_reporting sets the level of logging.E_NOTICE is useful during development since it will tell about defects such as unassigned variables.display_errors is used to display the error messages.display_startup_errors should only be used when debugging.log_errors and error_log work together to send errors to a log file. Do this in production rather than displaying them to end users.The PHP manual spells out these settings in more detail and provides more information." }, { "code": null, "e": 36956, "s": 36913, "text": "error_reporting sets the level of logging." }, { "code": null, "e": 37057, "s": 36956, "text": "E_NOTICE is useful during development since it will tell about defects such as unassigned variables." }, { "code": null, "e": 37111, "s": 37057, "text": "display_errors is used to display the error messages." }, { "code": null, "e": 37170, "s": 37111, "text": "display_startup_errors should only be used when debugging." }, { "code": null, "e": 37303, "s": 37170, "text": "log_errors and error_log work together to send errors to a log file. Do this in production rather than displaying them to end users." }, { "code": null, "e": 37390, "s": 37303, "text": "The PHP manual spells out these settings in more detail and provides more information." }, { "code": null, "e": 37397, "s": 37390, "text": "Picked" }, { "code": null, "e": 37401, "s": 37397, "text": "PHP" }, { "code": null, "e": 37418, "s": 37401, "text": "Web Technologies" }, { "code": null, "e": 37445, "s": 37418, "text": "Web technologies Questions" }, { "code": null, "e": 37449, "s": 37445, "text": "PHP" }, { "code": null, "e": 37547, "s": 37449, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37597, "s": 37547, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 37637, "s": 37597, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 37682, "s": 37637, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 37709, "s": 37682, "text": "Comparing two dates in PHP" }, { "code": null, "e": 37751, "s": 37709, "text": "How to pass JavaScript variables to PHP ?" }, { "code": null, "e": 37791, "s": 37751, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 37824, "s": 37791, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 37869, "s": 37824, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 37912, "s": 37869, "text": "How to fetch data from an API in ReactJS ?" } ]
Java - ByteArrayOutputStream
The ByteArrayOutputStream class stream creates a buffer in memory and all the data sent to the stream is stored in the buffer. Following is the list of the constructors to be provided by ByteArrayOutputStream class. ByteArrayOutputStream() This constructor creates a ByteArrayOutputStream having buffer of 32 byte. ByteArrayOutputStream(int a) This constructor creates a ByteArrayOutputStream having buffer of the given size. Once you have ByteArrayOutputStream object in hand, then there is a list of helper methods which can be used to write the stream or to do other operations on the stream. public void reset() This method resets the number of valid bytes of the byte array output stream to zero, so all the accumulated output in the stream will be discarded. public byte[] toByteArray() This method creates a newly allocated Byte array. Its size would be the current size of the output stream and the contents of the buffer will be copied into it. Returns the current contents of the output stream as a byte array. public String toString() Converts the buffer content into a string. Translation will be done according to the default character encoding. Returns the String translated from the buffer's content. public void write(int w) Writes the specified array to the output stream. public void write(byte []b, int of, int len) Writes len number of bytes starting from offset off to the stream. public void writeTo(OutputStream outSt) Writes the entire content of this Stream to the specified stream argument. Following is an example to demonstrate ByteArrayOutputStream and ByteArrayInputStream. import java.io.*; public class ByteStreamTest { public static void main(String args[])throws IOException { ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12); while( bOutput.size()!= 10 ) { // Gets the inputs from the user bOutput.write("hello".getBytes()); } byte b [] = bOutput.toByteArray(); System.out.println("Print the content"); for(int x = 0; x < b.length; x++) { // printing the characters System.out.print((char)b[x] + " "); } System.out.println(" "); int c; ByteArrayInputStream bInput = new ByteArrayInputStream(b); System.out.println("Converting characters to Upper case " ); for(int y = 0 ; y < 1; y++ ) { while(( c = bInput.read())!= -1) { System.out.println(Character.toUpperCase((char)c)); } bInput.reset(); } } } Here is the sample run of the above program − Print the content h e l l o h e l l o Converting characters to Upper case H E L L O H E L L O 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2504, "s": 2377, "text": "The ByteArrayOutputStream class stream creates a buffer in memory and all the data sent to the stream is stored in the buffer." }, { "code": null, "e": 2593, "s": 2504, "text": "Following is the list of the constructors to be provided by ByteArrayOutputStream class." }, { "code": null, "e": 2617, "s": 2593, "text": "ByteArrayOutputStream()" }, { "code": null, "e": 2692, "s": 2617, "text": "This constructor creates a ByteArrayOutputStream having buffer of 32 byte." }, { "code": null, "e": 2721, "s": 2692, "text": "ByteArrayOutputStream(int a)" }, { "code": null, "e": 2803, "s": 2721, "text": "This constructor creates a ByteArrayOutputStream having buffer of the given size." }, { "code": null, "e": 2973, "s": 2803, "text": "Once you have ByteArrayOutputStream object in hand, then there is a list of helper methods which can be used to write the stream or to do other operations on the stream." }, { "code": null, "e": 2993, "s": 2973, "text": "public void reset()" }, { "code": null, "e": 3142, "s": 2993, "text": "This method resets the number of valid bytes of the byte array output stream to zero, so all the accumulated output in the stream will be discarded." }, { "code": null, "e": 3170, "s": 3142, "text": "public byte[] toByteArray()" }, { "code": null, "e": 3398, "s": 3170, "text": "This method creates a newly allocated Byte array. Its size would be the current size of the output stream and the contents of the buffer will be copied into it. Returns the current contents of the output stream as a byte array." }, { "code": null, "e": 3423, "s": 3398, "text": "public String toString()" }, { "code": null, "e": 3593, "s": 3423, "text": "Converts the buffer content into a string. Translation will be done according to the default character encoding. Returns the String translated from the buffer's content." }, { "code": null, "e": 3618, "s": 3593, "text": "public void write(int w)" }, { "code": null, "e": 3667, "s": 3618, "text": "Writes the specified array to the output stream." }, { "code": null, "e": 3712, "s": 3667, "text": "public void write(byte []b, int of, int len)" }, { "code": null, "e": 3779, "s": 3712, "text": "Writes len number of bytes starting from offset off to the stream." }, { "code": null, "e": 3819, "s": 3779, "text": "public void writeTo(OutputStream outSt)" }, { "code": null, "e": 3894, "s": 3819, "text": "Writes the entire content of this Stream to the specified stream argument." }, { "code": null, "e": 3981, "s": 3894, "text": "Following is an example to demonstrate ByteArrayOutputStream and ByteArrayInputStream." }, { "code": null, "e": 4908, "s": 3981, "text": "import java.io.*;\npublic class ByteStreamTest {\n\n public static void main(String args[])throws IOException {\n ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12);\n\n while( bOutput.size()!= 10 ) {\n // Gets the inputs from the user\n bOutput.write(\"hello\".getBytes()); \n }\n byte b [] = bOutput.toByteArray();\n System.out.println(\"Print the content\");\n \n for(int x = 0; x < b.length; x++) {\n // printing the characters\n System.out.print((char)b[x] + \" \"); \n }\n System.out.println(\" \");\n\n int c;\n ByteArrayInputStream bInput = new ByteArrayInputStream(b);\n System.out.println(\"Converting characters to Upper case \" );\n \n for(int y = 0 ; y < 1; y++ ) {\n while(( c = bInput.read())!= -1) {\n System.out.println(Character.toUpperCase((char)c));\n }\n bInput.reset(); \n }\n }\n}" }, { "code": null, "e": 4954, "s": 4908, "text": "Here is the sample run of the above program −" }, { "code": null, "e": 5074, "s": 4954, "text": "Print the content\nh e l l o h e l l o \nConverting characters to Upper case \nH\nE\nL\nL\nO\nH\nE\nL\nL\nO\n" }, { "code": null, "e": 5107, "s": 5074, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 5123, "s": 5107, "text": " Malhar Lathkar" }, { "code": null, "e": 5156, "s": 5123, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 5172, "s": 5156, "text": " Malhar Lathkar" }, { "code": null, "e": 5207, "s": 5172, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5221, "s": 5207, "text": " Anadi Sharma" }, { "code": null, "e": 5255, "s": 5221, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 5269, "s": 5255, "text": " Tushar Kale" }, { "code": null, "e": 5306, "s": 5269, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 5321, "s": 5306, "text": " Monica Mittal" }, { "code": null, "e": 5354, "s": 5321, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 5373, "s": 5354, "text": " Arnab Chakraborty" }, { "code": null, "e": 5380, "s": 5373, "text": " Print" }, { "code": null, "e": 5391, "s": 5380, "text": " Add Notes" } ]
Understanding for-loop in Python - GeeksforGeeks
29 Dec, 2019 A Pythonic for-loop is very different from for-loops of other programming language. A for-loop in Python is used to loop over an iterator however in other languages, it is used to loop over a condition. In this article, we will take a deeper dive into Pythonic for-loop and witness the reason behind this dissimilarity. Let’s begin by familiarizing ourselves with the looping gotchas: If one doesn’t know what “gotcha” means: a “gotcha” in coding is a term used for a feature of a programming language (say for-loop, function, return statement, etc) that is likely to play tricks by showing a behavior which doesn’t match the expected outcome. Here are two infamous for-loop gotchas: Consider this example: numList = [0, 1, 2, 3, 4]squares = (n**2 for n in numList) Here, the variable squares contains an iterable of squares of the elements of numList. If we check whether 16 is in squares, we get True but if we check it again, we get False. sum of a for-loop : Take a look at this: numList = [0, 2, 4, 6, 8]doubles = (n * 2 for n in numList) We can make this doubles into a list or tuple to look at its elements. Let’s calculate the sum of the elements in doubles. The result should be 40 as per expectation.But, we get 0 instead. To understand this anomaly, let’s first see “under-the-hood” working of for-loops. As stated earlier, for-loops of other programming languages, such as C, C++, Java, loop over a condition. For example: let numList = [0, 1, 2, 3, 4];for (let i = 0; i < numList.length; i += 1) { print(numList[i])} The above code is written in Javascript. As seen the for-loop is quite different from what we see in Python. This is because what we call a for-loop in Python is actually a “foreach” loop. A foreach loop doesn’t maintain a counter like a for loop. A for loop works on indices of the elements of the iterable rather than the element itself. But a foreach loop works straight on the elements rather than their indices and thus have no conditions, no initializations and no incrementation of index. numList = [0, 1, 2, 3, 4] # for loop in Pythonfor n in numList: print(n) Hence, it won’t be wrong to say that we don’t have for-loops in Python but we have foreach loops which are implemented as for-loops!One might think that Python uses indices under the hood to loop over in a for loop. But the answer is no. Let’s look at an example to prove this:We will take the help of while loop for using indices. games = { 'tennis', 'baseball', 'rugby', 'soccer' } i = 0 while i < len(games): print(games[i]) i += 1 Output: This proves that Python doesn’t make use of indices for looping and so we can’t loop over everything using indices. A simple question now arises, what does Python use for looping? The answer is, iterators! We know what iterables are(lists, strings, tuples, etc). An iterator can be considered as the power supply of iterables. An iterable is made up of iterator and this is the fact which helps Python to loop over an iterable. To extractor iterator from an iterable, we use Python’s iter function. Let’s look at an example: games = ['tennis', 'baseball', 'rugby', 'soccer']iterator = iter(games) # we use the next() function to # print the next item of iterableprint(next(iterator)) print(next(iterator))print(next(iterator)) If we keep on using the next() function even after we reach the last item, we will get a StopIteration Error. Note: Once an item in an iterator is all used up(iterated over), it is deleted from the memory! Now that we know how loops work, let’s try and make our own loop using the power of iterators. # Python program to demonstrate# power of iterators # creating our own loopdef newForLoop(iterable): # extracting iterator out of iterable iterator = iter(iterable) # condition to check if looping is done loopingFinished = False while not loopingFinished: try: nextItem = next(iterator) except StopIteration: loopingFinished = True else: print(nextItem) # Driver's codenewForLoop([1, 2, 3, 4]) Output: 1 2 3 4 We need to learn about iterators because we work with iterators almost every time with even knowing about it. The most common example is a generator. A generator is an iterator. We can apply each and every function of an iterator to a generator. numList = [0, 2, 4] # creating a generator named "squares"squares = (n**2 for n in numList) print(next(squares))print(next(squares))print(next(squares)) Output: 0 4 16 Now that we know what exactly are for-loops and how do they work in Python, we will end this article from where we began, that is, by trying to reason out looping gotchas as seen earlier. Exhausting an iterator partially : When we did : numList = [0, 1, 2, 3, 4]squares = (n**2 for n in numList) and asked if 9 is in the squares, we got True. But asking again gives returns a False. This is because when we first asked if 9 is there, it iterates over the iterator(generator) to find 9 and we know that as soon as the next item in an iterator is reached, the previous item is deleted. This is why once we find 9, all the numbers before 9 get deleted and asking again returns False. Hence we have exhausted the iterator partially. Exhausting an iterator completely : In this code: numList = [0, 2, 4, 6, 8]doubles = (n * 2 for n in numList) When we convert doubles to list, we are already iterating over each item in the iterator by doing so. Therefore, the iterator gets completely exhausted and finally, no items remain in it. This is why the function sum() on the tuple returns zero. If we do the sum without converting it into a list, it will return the correct output. Python loop-programs Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n29 Dec, 2019" }, { "code": null, "e": 25922, "s": 25537, "text": "A Pythonic for-loop is very different from for-loops of other programming language. A for-loop in Python is used to loop over an iterator however in other languages, it is used to loop over a condition. In this article, we will take a deeper dive into Pythonic for-loop and witness the reason behind this dissimilarity. Let’s begin by familiarizing ourselves with the looping gotchas:" }, { "code": null, "e": 26221, "s": 25922, "text": "If one doesn’t know what “gotcha” means: a “gotcha” in coding is a term used for a feature of a programming language (say for-loop, function, return statement, etc) that is likely to play tricks by showing a behavior which doesn’t match the expected outcome. Here are two infamous for-loop gotchas:" }, { "code": null, "e": 26244, "s": 26221, "text": "Consider this example:" }, { "code": "numList = [0, 1, 2, 3, 4]squares = (n**2 for n in numList)", "e": 26303, "s": 26244, "text": null }, { "code": null, "e": 26480, "s": 26303, "text": "Here, the variable squares contains an iterable of squares of the elements of numList. If we check whether 16 is in squares, we get True but if we check it again, we get False." }, { "code": null, "e": 26500, "s": 26480, "text": "sum of a for-loop :" }, { "code": null, "e": 26521, "s": 26500, "text": "Take a look at this:" }, { "code": "numList = [0, 2, 4, 6, 8]doubles = (n * 2 for n in numList)", "e": 26581, "s": 26521, "text": null }, { "code": null, "e": 26770, "s": 26581, "text": "We can make this doubles into a list or tuple to look at its elements. Let’s calculate the sum of the elements in doubles. The result should be 40 as per expectation.But, we get 0 instead." }, { "code": null, "e": 26853, "s": 26770, "text": "To understand this anomaly, let’s first see “under-the-hood” working of for-loops." }, { "code": null, "e": 26972, "s": 26853, "text": "As stated earlier, for-loops of other programming languages, such as C, C++, Java, loop over a condition. For example:" }, { "code": "let numList = [0, 1, 2, 3, 4];for (let i = 0; i < numList.length; i += 1) { print(numList[i])}", "e": 27070, "s": 26972, "text": null }, { "code": null, "e": 27566, "s": 27070, "text": "The above code is written in Javascript. As seen the for-loop is quite different from what we see in Python. This is because what we call a for-loop in Python is actually a “foreach” loop. A foreach loop doesn’t maintain a counter like a for loop. A for loop works on indices of the elements of the iterable rather than the element itself. But a foreach loop works straight on the elements rather than their indices and thus have no conditions, no initializations and no incrementation of index." }, { "code": "numList = [0, 1, 2, 3, 4] # for loop in Pythonfor n in numList: print(n)", "e": 27644, "s": 27566, "text": null }, { "code": null, "e": 27976, "s": 27644, "text": "Hence, it won’t be wrong to say that we don’t have for-loops in Python but we have foreach loops which are implemented as for-loops!One might think that Python uses indices under the hood to loop over in a for loop. But the answer is no. Let’s look at an example to prove this:We will take the help of while loop for using indices." }, { "code": "games = { 'tennis', 'baseball', 'rugby', 'soccer' } i = 0 while i < len(games): print(games[i]) i += 1", "e": 28086, "s": 27976, "text": null }, { "code": null, "e": 28094, "s": 28086, "text": "Output:" }, { "code": null, "e": 28300, "s": 28094, "text": "This proves that Python doesn’t make use of indices for looping and so we can’t loop over everything using indices. A simple question now arises, what does Python use for looping? The answer is, iterators!" }, { "code": null, "e": 28593, "s": 28300, "text": "We know what iterables are(lists, strings, tuples, etc). An iterator can be considered as the power supply of iterables. An iterable is made up of iterator and this is the fact which helps Python to loop over an iterable. To extractor iterator from an iterable, we use Python’s iter function." }, { "code": null, "e": 28619, "s": 28593, "text": "Let’s look at an example:" }, { "code": "games = ['tennis', 'baseball', 'rugby', 'soccer']iterator = iter(games) # we use the next() function to # print the next item of iterableprint(next(iterator)) print(next(iterator))print(next(iterator))", "e": 28822, "s": 28619, "text": null }, { "code": null, "e": 28932, "s": 28822, "text": "If we keep on using the next() function even after we reach the last item, we will get a StopIteration Error." }, { "code": null, "e": 29028, "s": 28932, "text": "Note: Once an item in an iterator is all used up(iterated over), it is deleted from the memory!" }, { "code": null, "e": 29123, "s": 29028, "text": "Now that we know how loops work, let’s try and make our own loop using the power of iterators." }, { "code": "# Python program to demonstrate# power of iterators # creating our own loopdef newForLoop(iterable): # extracting iterator out of iterable iterator = iter(iterable) # condition to check if looping is done loopingFinished = False while not loopingFinished: try: nextItem = next(iterator) except StopIteration: loopingFinished = True else: print(nextItem) # Driver's codenewForLoop([1, 2, 3, 4])", "e": 29611, "s": 29123, "text": null }, { "code": null, "e": 29619, "s": 29611, "text": "Output:" }, { "code": null, "e": 29628, "s": 29619, "text": "1\n2\n3\n4\n" }, { "code": null, "e": 29874, "s": 29628, "text": "We need to learn about iterators because we work with iterators almost every time with even knowing about it. The most common example is a generator. A generator is an iterator. We can apply each and every function of an iterator to a generator." }, { "code": "numList = [0, 2, 4] # creating a generator named \"squares\"squares = (n**2 for n in numList) print(next(squares))print(next(squares))print(next(squares))", "e": 30030, "s": 29874, "text": null }, { "code": null, "e": 30038, "s": 30030, "text": "Output:" }, { "code": null, "e": 30048, "s": 30038, "text": "0 \n4 \n16\n" }, { "code": null, "e": 30236, "s": 30048, "text": "Now that we know what exactly are for-loops and how do they work in Python, we will end this article from where we began, that is, by trying to reason out looping gotchas as seen earlier." }, { "code": null, "e": 30271, "s": 30236, "text": "Exhausting an iterator partially :" }, { "code": null, "e": 30285, "s": 30271, "text": "When we did :" }, { "code": "numList = [0, 1, 2, 3, 4]squares = (n**2 for n in numList)", "e": 30344, "s": 30285, "text": null }, { "code": null, "e": 30777, "s": 30344, "text": "and asked if 9 is in the squares, we got True. But asking again gives returns a False. This is because when we first asked if 9 is there, it iterates over the iterator(generator) to find 9 and we know that as soon as the next item in an iterator is reached, the previous item is deleted. This is why once we find 9, all the numbers before 9 get deleted and asking again returns False. Hence we have exhausted the iterator partially." }, { "code": null, "e": 30813, "s": 30777, "text": "Exhausting an iterator completely :" }, { "code": null, "e": 30827, "s": 30813, "text": "In this code:" }, { "code": "numList = [0, 2, 4, 6, 8]doubles = (n * 2 for n in numList)", "e": 30887, "s": 30827, "text": null }, { "code": null, "e": 31220, "s": 30887, "text": "When we convert doubles to list, we are already iterating over each item in the iterator by doing so. Therefore, the iterator gets completely exhausted and finally, no items remain in it. This is why the function sum() on the tuple returns zero. If we do the sum without converting it into a list, it will return the correct output." }, { "code": null, "e": 31241, "s": 31220, "text": "Python loop-programs" }, { "code": null, "e": 31248, "s": 31241, "text": "Python" }, { "code": null, "e": 31346, "s": 31248, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31378, "s": 31346, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 31420, "s": 31378, "text": "Check if element exists in list in Python" }, { "code": null, "e": 31462, "s": 31420, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 31489, "s": 31462, "text": "Python Classes and Objects" }, { "code": null, "e": 31545, "s": 31489, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 31567, "s": 31545, "text": "Defaultdict in Python" }, { "code": null, "e": 31606, "s": 31567, "text": "Python | Get unique values from a list" }, { "code": null, "e": 31637, "s": 31606, "text": "Python | os.path.join() method" }, { "code": null, "e": 31666, "s": 31637, "text": "Create a directory in Python" } ]
Output of Java Program | Set 7 - GeeksforGeeks
28 Jun, 2021 Difficulty level : Intermediate Predict the output of following Java Programs. Program 1 : public class Calculator{ int num = 100; public void calc(int num) { this.num = num * 10; } public void printNum() { System.out.println(num); } public static void main(String[] args) { Calculator obj = new Calculator(); obj.calc(2); obj.printNum(); }} Options :A) 20B) 100C) 1000D) 2Answer : A) 20Explanation : Here the class instance variable name(num) is same as calc() method local variable name(num). So for referencing class instance variable from calc() method, this keyword is used. So in statement this.num = num * 10, num represents local variable of the method whose value is 2 and this.num represents class instance variable whose initial value is 100. Now in printNum() method, as it has no local variable whose name is same as class instance variable, so we can directly use num to reference instance variable, although this.num can be used. Program 2 : public class MyStuff{ String name; MyStuff(String n) { name = n; } public static void main(String[] args) { MyStuff m1 = new MyStuff("guitar"); MyStuff m2 = new MyStuff("tv"); System.out.println(m2.equals(m1)); } @Override public boolean equals(Object obj) { MyStuff m = (MyStuff) obj; if (m.name != null) { return true; } return false; }} Options :A) The output is true and MyStuff fulfills the Object.equals() contract.B) The output is false and MyStuff fulfills the Object.equals() contract.C) The output is true and MyStuff does NOT fulfill the Object.equals() contract.D) The output is false and MyStuff does NOT fulfill the Object.equals() contract. Answer : C) The output is true and MyStuff does NOT fulfill the Object.equals() contract.Explanation : As equals(Object obj) method in Object class, compares two objects on the basis of equivalence relation. But here we are just confirming that the object is null or not, So it doesn’t fulfill Object.equals() contract. As m1 is not null, true will be printed. Program 3 : class Alpha{ public String type = "a "; public Alpha() { System.out.print("alpha "); }} public class Beta extends Alpha{ public Beta() { System.out.print("beta "); } void go() { type = "b "; System.out.print(this.type + super.type); } public static void main(String[] args) { new Beta().go(); }} Options :A) alpha beta b bB) alpha beta a bC) beta alpha b bD) beta alpha a b Answer : A) alpha beta b bExplanation : The statement new Beta().go() executes in two phases. In first phase Beta class constructor is called. There is no instance member present in Beta class. So now Beta class constructor is executed. As Beta class extends Alpha class, so call goes to Alpha class constructor as first statement by default(Put by the compiler) is super() in the Beta class constructor. Now as one instance variable(type) is present in Alpha class, so it will get memory and now Alpha class constructor is executed, then call return to Beta class constructor next statement. So alpha beta is printed.In second phase go() method is called on this object. As there is only one variable(type) in the object whose value is a. So it will be changed to b and printed two times. The super keyword here is of no use. Program 4 : public class Test{ public static void main(String[] args) { StringBuilder s1 = new StringBuilder("Java"); String s2 = "Love"; s1.append(s2); s1.substring(4); int foundAt = s1.indexOf(s2); System.out.println(foundAt); }} Options :A) -1B) 3C) 4D) A StringIndexOutOfBoundsException is thrown at runtime.Answer : C) 4Explanation : append(String str) method,concatenate the str to s1. The substring(int index) method return the String from the given index to the end. But as there is no any String variable to store the returned string,so it will be destroyed.Now indexOf(String s2) method return the index of first occurrence of s2. So 4 is printed as s1=”JavaLove”. Program 5 : class Writer{ public static void write() { System.out.println("Writing..."); }}class Author extends Writer{ public static void write() { System.out.println("Writing book"); }} public class Programmer extends Author{ public static void write() { System.out.println("Writing code"); } public static void main(String[] args) { Author a = new Programmer(); a.write(); }} Options :A) Writing...B) Writing bookC) Writing codeD) Compilation fails Answer : B) Writing bookExplanation : Since static methods can’t be overridden, it doesn’t matter which class object is created. As a is a Author referenced type, so always Author class method is called. If we remove write() method from Author class then Writer class method is called, as Author class extends Writer class. This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jacob341 Java-Output Java Program Output Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Interfaces in Java ArrayList in Java Stack Class in Java Singleton Class in Java Arrow operator -> in C/C++ with Examples Output of Java Program | Set 1 delete keyword in C++ Output of C Programs | Set 1 Output of C++ programs | Set 34 (File Handling)
[ { "code": null, "e": 25695, "s": 25667, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25727, "s": 25695, "text": "Difficulty level : Intermediate" }, { "code": null, "e": 25774, "s": 25727, "text": "Predict the output of following Java Programs." }, { "code": null, "e": 25786, "s": 25774, "text": "Program 1 :" }, { "code": "public class Calculator{ int num = 100; public void calc(int num) { this.num = num * 10; } public void printNum() { System.out.println(num); } public static void main(String[] args) { Calculator obj = new Calculator(); obj.calc(2); obj.printNum(); }}", "e": 26084, "s": 25786, "text": null }, { "code": null, "e": 26687, "s": 26084, "text": "Options :A) 20B) 100C) 1000D) 2Answer : A) 20Explanation : Here the class instance variable name(num) is same as calc() method local variable name(num). So for referencing class instance variable from calc() method, this keyword is used. So in statement this.num = num * 10, num represents local variable of the method whose value is 2 and this.num represents class instance variable whose initial value is 100. Now in printNum() method, as it has no local variable whose name is same as class instance variable, so we can directly use num to reference instance variable, although this.num can be used." }, { "code": null, "e": 26701, "s": 26689, "text": "Program 2 :" }, { "code": "public class MyStuff{ String name; MyStuff(String n) { name = n; } public static void main(String[] args) { MyStuff m1 = new MyStuff(\"guitar\"); MyStuff m2 = new MyStuff(\"tv\"); System.out.println(m2.equals(m1)); } @Override public boolean equals(Object obj) { MyStuff m = (MyStuff) obj; if (m.name != null) { return true; } return false; }}", "e": 27120, "s": 26701, "text": null }, { "code": null, "e": 27436, "s": 27120, "text": "Options :A) The output is true and MyStuff fulfills the Object.equals() contract.B) The output is false and MyStuff fulfills the Object.equals() contract.C) The output is true and MyStuff does NOT fulfill the Object.equals() contract.D) The output is false and MyStuff does NOT fulfill the Object.equals() contract." }, { "code": null, "e": 27797, "s": 27436, "text": "Answer : C) The output is true and MyStuff does NOT fulfill the Object.equals() contract.Explanation : As equals(Object obj) method in Object class, compares two objects on the basis of equivalence relation. But here we are just confirming that the object is null or not, So it doesn’t fulfill Object.equals() contract. As m1 is not null, true will be printed." }, { "code": null, "e": 27811, "s": 27799, "text": "Program 3 :" }, { "code": "class Alpha{ public String type = \"a \"; public Alpha() { System.out.print(\"alpha \"); }} public class Beta extends Alpha{ public Beta() { System.out.print(\"beta \"); } void go() { type = \"b \"; System.out.print(this.type + super.type); } public static void main(String[] args) { new Beta().go(); }}", "e": 28164, "s": 27811, "text": null }, { "code": null, "e": 28242, "s": 28164, "text": "Options :A) alpha beta b bB) alpha beta a bC) beta alpha b bD) beta alpha a b" }, { "code": null, "e": 29069, "s": 28242, "text": "Answer : A) alpha beta b bExplanation : The statement new Beta().go() executes in two phases. In first phase Beta class constructor is called. There is no instance member present in Beta class. So now Beta class constructor is executed. As Beta class extends Alpha class, so call goes to Alpha class constructor as first statement by default(Put by the compiler) is super() in the Beta class constructor. Now as one instance variable(type) is present in Alpha class, so it will get memory and now Alpha class constructor is executed, then call return to Beta class constructor next statement. So alpha beta is printed.In second phase go() method is called on this object. As there is only one variable(type) in the object whose value is a. So it will be changed to b and printed two times. The super keyword here is of no use." }, { "code": null, "e": 29083, "s": 29071, "text": "Program 4 :" }, { "code": "public class Test{ public static void main(String[] args) { StringBuilder s1 = new StringBuilder(\"Java\"); String s2 = \"Love\"; s1.append(s2); s1.substring(4); int foundAt = s1.indexOf(s2); System.out.println(foundAt); }}", "e": 29354, "s": 29083, "text": null }, { "code": null, "e": 29797, "s": 29354, "text": "Options :A) -1B) 3C) 4D) A StringIndexOutOfBoundsException is thrown at runtime.Answer : C) 4Explanation : append(String str) method,concatenate the str to s1. The substring(int index) method return the String from the given index to the end. But as there is no any String variable to store the returned string,so it will be destroyed.Now indexOf(String s2) method return the index of first occurrence of s2. So 4 is printed as s1=”JavaLove”." }, { "code": null, "e": 29811, "s": 29799, "text": "Program 5 :" }, { "code": "class Writer{ public static void write() { System.out.println(\"Writing...\"); }}class Author extends Writer{ public static void write() { System.out.println(\"Writing book\"); }} public class Programmer extends Author{ public static void write() { System.out.println(\"Writing code\"); } public static void main(String[] args) { Author a = new Programmer(); a.write(); }}", "e": 30255, "s": 29811, "text": null }, { "code": null, "e": 30328, "s": 30255, "text": "Options :A) Writing...B) Writing bookC) Writing codeD) Compilation fails" }, { "code": null, "e": 30652, "s": 30328, "text": "Answer : B) Writing bookExplanation : Since static methods can’t be overridden, it doesn’t matter which class object is created. As a is a Author referenced type, so always Author class method is called. If we remove write() method from Author class then Writer class method is called, as Author class extends Writer class." }, { "code": null, "e": 30950, "s": 30652, "text": "This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 31075, "s": 30950, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 31084, "s": 31075, "text": "jacob341" }, { "code": null, "e": 31096, "s": 31084, "text": "Java-Output" }, { "code": null, "e": 31101, "s": 31096, "text": "Java" }, { "code": null, "e": 31116, "s": 31101, "text": "Program Output" }, { "code": null, "e": 31121, "s": 31116, "text": "Java" }, { "code": null, "e": 31219, "s": 31121, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31234, "s": 31219, "text": "Stream In Java" }, { "code": null, "e": 31253, "s": 31234, "text": "Interfaces in Java" }, { "code": null, "e": 31271, "s": 31253, "text": "ArrayList in Java" }, { "code": null, "e": 31291, "s": 31271, "text": "Stack Class in Java" }, { "code": null, "e": 31315, "s": 31291, "text": "Singleton Class in Java" }, { "code": null, "e": 31356, "s": 31315, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 31387, "s": 31356, "text": "Output of Java Program | Set 1" }, { "code": null, "e": 31409, "s": 31387, "text": "delete keyword in C++" }, { "code": null, "e": 31438, "s": 31409, "text": "Output of C Programs | Set 1" } ]
Send Message on Instagram Using Instabot module in Python - GeeksforGeeks
31 Oct, 2021 In this article, we are going to see how to send messages on Instagram using the Instabot module in Python. Instagram is a nice platform for chatting but when it comes to sending the same message to all friends this is a really boring and time-consuming task especially if you have a large number of followers. To make this easy we make a bot using Python to send messages on Instagram. So without further delay, let’s jump right in. Instabot library: It is a script of promotion and API Python wrapper for Instagram. pip install instabot Step 1: First we import the Bot from the Instabot library and make a variable bot. Python3 # importing Bot form instabot library.from instabot import Bot bot = Bot() Step 2: Now we need to login into our account using the bot. Python3 # Login using botbot.login(username="Your_username", password="Your_password") Step 3: It’s time to make a list of friends/followers to whom messages will be sent. Don’t forget any name because everyone is important. Python3 # Make a list of followers/friendsurer_ids = ["username1", "username2", "....."] Step 4: Write a message Python3 # Messagetext = "I like GFG" Step 5: It’s time to send the message. To send messages to more person use the “send_messages” function and to send messages to a single person “send_message” function also can be used. Python3 # Sending messages to one or more friendsbot.send_messages(text, urer_ids) Below is the full implementation: Python3 # Program to send message# on Instagram using Python. # importing Bot form instabot library.from instabot import Bot # Creating bot variable.bot = Bot() # Login using bot.bot.login(username="Your_username", password="Your_password") # Make a list of followers/friendsurer_ids = ["username1", "username2", "....."] # Messagetext = "I like GFG" # Sending messagesbot.send_messages(text, urer_ids) Output: Note: Sometimes it’s difficult to rerun the program because of login errors to avoid this you need to delete a config folder that is auto-created after running the program once. anikakapoor python-modules python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Defaultdict in Python How to Install PIP on Windows ? Deque in Python Bar Plot in Matplotlib Check if element exists in list in Python Python math function | sqrt() Python | Output Formatting Python - Pandas dataframe.append() How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects
[ { "code": null, "e": 25562, "s": 25534, "text": "\n31 Oct, 2021" }, { "code": null, "e": 25670, "s": 25562, "text": "In this article, we are going to see how to send messages on Instagram using the Instabot module in Python." }, { "code": null, "e": 25996, "s": 25670, "text": "Instagram is a nice platform for chatting but when it comes to sending the same message to all friends this is a really boring and time-consuming task especially if you have a large number of followers. To make this easy we make a bot using Python to send messages on Instagram. So without further delay, let’s jump right in." }, { "code": null, "e": 26080, "s": 25996, "text": "Instabot library: It is a script of promotion and API Python wrapper for Instagram." }, { "code": null, "e": 26101, "s": 26080, "text": "pip install instabot" }, { "code": null, "e": 26184, "s": 26101, "text": "Step 1: First we import the Bot from the Instabot library and make a variable bot." }, { "code": null, "e": 26192, "s": 26184, "text": "Python3" }, { "code": "# importing Bot form instabot library.from instabot import Bot bot = Bot()", "e": 26267, "s": 26192, "text": null }, { "code": null, "e": 26328, "s": 26267, "text": "Step 2: Now we need to login into our account using the bot." }, { "code": null, "e": 26336, "s": 26328, "text": "Python3" }, { "code": "# Login using botbot.login(username=\"Your_username\", password=\"Your_password\")", "e": 26424, "s": 26336, "text": null }, { "code": null, "e": 26563, "s": 26424, "text": "Step 3: It’s time to make a list of friends/followers to whom messages will be sent. Don’t forget any name because everyone is important. " }, { "code": null, "e": 26571, "s": 26563, "text": "Python3" }, { "code": "# Make a list of followers/friendsurer_ids = [\"username1\", \"username2\", \".....\"]", "e": 26652, "s": 26571, "text": null }, { "code": null, "e": 26677, "s": 26652, "text": "Step 4: Write a message" }, { "code": null, "e": 26685, "s": 26677, "text": "Python3" }, { "code": "# Messagetext = \"I like GFG\"", "e": 26714, "s": 26685, "text": null }, { "code": null, "e": 26900, "s": 26714, "text": "Step 5: It’s time to send the message. To send messages to more person use the “send_messages” function and to send messages to a single person “send_message” function also can be used." }, { "code": null, "e": 26908, "s": 26900, "text": "Python3" }, { "code": "# Sending messages to one or more friendsbot.send_messages(text, urer_ids)", "e": 26983, "s": 26908, "text": null }, { "code": null, "e": 27017, "s": 26983, "text": "Below is the full implementation:" }, { "code": null, "e": 27025, "s": 27017, "text": "Python3" }, { "code": "# Program to send message# on Instagram using Python. # importing Bot form instabot library.from instabot import Bot # Creating bot variable.bot = Bot() # Login using bot.bot.login(username=\"Your_username\", password=\"Your_password\") # Make a list of followers/friendsurer_ids = [\"username1\", \"username2\", \".....\"] # Messagetext = \"I like GFG\" # Sending messagesbot.send_messages(text, urer_ids)", "e": 27429, "s": 27025, "text": null }, { "code": null, "e": 27437, "s": 27429, "text": "Output:" }, { "code": null, "e": 27616, "s": 27437, "text": "Note: Sometimes it’s difficult to rerun the program because of login errors to avoid this you need to delete a config folder that is auto-created after running the program once. " }, { "code": null, "e": 27628, "s": 27616, "text": "anikakapoor" }, { "code": null, "e": 27643, "s": 27628, "text": "python-modules" }, { "code": null, "e": 27658, "s": 27643, "text": "python-utility" }, { "code": null, "e": 27665, "s": 27658, "text": "Python" }, { "code": null, "e": 27763, "s": 27665, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27785, "s": 27763, "text": "Defaultdict in Python" }, { "code": null, "e": 27817, "s": 27785, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27833, "s": 27817, "text": "Deque in Python" }, { "code": null, "e": 27856, "s": 27833, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 27898, "s": 27856, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27928, "s": 27898, "text": "Python math function | sqrt()" }, { "code": null, "e": 27955, "s": 27928, "text": "Python | Output Formatting" }, { "code": null, "e": 27990, "s": 27955, "text": "Python - Pandas dataframe.append()" }, { "code": null, "e": 28046, "s": 27990, "text": "How to drop one or multiple columns in Pandas Dataframe" } ]
PHP | Check if a number is armstrong number - GeeksforGeeks
30 Apr, 2021 Given a number, we need to check whether it is an armstrong number or not in PHP. An Armstrong number is the one whose value is equal to the sum of the cubes of its digits.Examples: Input : 407 Output : Yes 407 = (4*4*4) + (0*0*0) + (7*7*7) = 64 + 0 + 343 = 407 Input : 303 Output : No Approach: For every digit r in input number x, compute r3. If sum of all such values is equal to n, then print “Yes”, else “No”. Php <?php// PHP code to check whether a number is// armstrong number or not // function to check whether the number is// armstrong number or notfunction armstrongCheck($number){ $sum = 0; $x = $number; while($x != 0) { $rem = $x % 10; $sum = $sum + $rem*$rem*$rem; $x = $x / 10; } // if true then armstrong number if ($number == $sum) return 1; // not an armstrong number return 0; } // Driver Code$number = 407;$flag = armstrongCheck($number);if ($flag == 1) echo "Yes";else echo "No"?> Output: Yes Time Complexity: O(num), where num is the number of digits in the given number. hritikbhatnagar2182 PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26213, "s": 26185, "text": "\n30 Apr, 2021" }, { "code": null, "e": 26397, "s": 26213, "text": "Given a number, we need to check whether it is an armstrong number or not in PHP. An Armstrong number is the one whose value is equal to the sum of the cubes of its digits.Examples: " }, { "code": null, "e": 26516, "s": 26397, "text": "Input : 407\nOutput : Yes\n407 = (4*4*4) + (0*0*0) + (7*7*7) \n = 64 + 0 + 343 \n = 407 \n\nInput : 303\nOutput : No" }, { "code": null, "e": 26648, "s": 26518, "text": "Approach: For every digit r in input number x, compute r3. If sum of all such values is equal to n, then print “Yes”, else “No”. " }, { "code": null, "e": 26652, "s": 26648, "text": "Php" }, { "code": "<?php// PHP code to check whether a number is// armstrong number or not // function to check whether the number is// armstrong number or notfunction armstrongCheck($number){ $sum = 0; $x = $number; while($x != 0) { $rem = $x % 10; $sum = $sum + $rem*$rem*$rem; $x = $x / 10; } // if true then armstrong number if ($number == $sum) return 1; // not an armstrong number return 0; } // Driver Code$number = 407;$flag = armstrongCheck($number);if ($flag == 1) echo \"Yes\";else echo \"No\"?>", "e": 27220, "s": 26652, "text": null }, { "code": null, "e": 27230, "s": 27220, "text": "Output: " }, { "code": null, "e": 27234, "s": 27230, "text": "Yes" }, { "code": null, "e": 27315, "s": 27234, "text": "Time Complexity: O(num), where num is the number of digits in the given number. " }, { "code": null, "e": 27335, "s": 27315, "text": "hritikbhatnagar2182" }, { "code": null, "e": 27339, "s": 27335, "text": "PHP" }, { "code": null, "e": 27356, "s": 27339, "text": "Web Technologies" }, { "code": null, "e": 27360, "s": 27356, "text": "PHP" }, { "code": null, "e": 27458, "s": 27360, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27508, "s": 27458, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27548, "s": 27508, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 27609, "s": 27548, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 27659, "s": 27609, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 27704, "s": 27659, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 27744, "s": 27704, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27777, "s": 27744, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27822, "s": 27777, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27865, "s": 27822, "text": "How to fetch data from an API in ReactJS ?" } ]
Check if binary representation of a number is palindrome - GeeksforGeeks
02 Nov, 2021 Given an integer ‘x’, write a C function that returns true if binary representation of x is palindrome else return false.For example a numbers with binary representation as 10..01 is palindrome and number with binary representation as 10..00 is not palindrome.The idea is similar to checking a string is palindrome or not. We start from leftmost and rightmost bits and compare bits one by one. If we find a mismatch, then return false. Algorithm: isPalindrome(x) 1) Find number of bits in x using sizeof() operator. 2) Initialize left and right positions as 1 and n respectively. 3) Do following while left ‘l’ is smaller than right ‘r’. .......a) If bit at position ‘l’ is not same as bit at position ‘r’, then return false. .......b) Increment ‘l’ and decrement ‘r’, i.e., do l++ and r–-. 4) If we reach here, it means we didn’t find a mismatching bit.To find the bit at a given position, we can use the idea similar to this post. The expression “x & (1 << (k-1))” gives us non-zero value if bit at k’th position from right is set and gives a zero value if if k’th bit is not set. Following is the implementation of the above algorithm. C++ Java Python3 C# PHP Javascript // C++ Program to Check if binary representation// of a number is palindrome#include<iostream>using namespace std; // This function returns true if k'th bit in x// is set (or 1). For example if x (0010) is 2// and k is 2, then it returns truebool isKthBitSet(unsigned int x, unsigned int k){ return (x & (1 << (k - 1))) ? true : false;} // This function returns true if binary// representation of x is palindrome.// For example (1000...001) is palindromebool isPalindrome(unsigned int x){ int l = 1; // Initialize left position int r = sizeof(unsigned int) * 8; // initialize right position // One by one compare bits while (l < r) { if (isKthBitSet(x, l) != isKthBitSet(x, r)) return false; l++; r--; } return true;} // Driver Codeint main(){ unsigned int x = 1 << 15 + 1 << 16; cout << isPalindrome(x) << endl; x = 1 << 31 + 1; cout << isPalindrome(x) << endl; return 0;} // Java Program to Check if binary representation// of a number is palindromeclass GFG{ // This function returns true if k'th bit in x // is set (or 1). For example if x (0010) is 2 // and k is 2, then it returns true static int isKthBitSet(long x, long k) { int rslt = ((x & (1 << (k - 1))) != 0) ? 1 : 0; return rslt; } // This function returns true if binary // representation of x is palindrome. // For example (1000...001) is palindrome static int isPalindrome( long x) { long l = 1; // Initialize left position long r = (Integer.SIZE/8 )* 8; // initialize right position // One by one compare bits while (l < r) { if (isKthBitSet(x, l) != isKthBitSet(x, r)) { return 0; } l++; r--; } return 1; } // Driver Code public static void main (String[] args) { long x = 1 << 15 + 1 << 16 ; System.out.println(isPalindrome(x)); x = (1 << 31) + 1 ; System.out.println(isPalindrome(x)); }} // This code is contributed by AnkitRai01 # python 3 Program to Check if binary representation# of a number is palindromeimport sys# This function returns true if k'th bit in x# is set (or 1). For example if x (0010) is 2# and k is 2, then it returns truedef isKthBitSet(x, k): if ((x & (1 << (k - 1))) !=0): return True else: return False # This function returns true if binary# representation of x is palindrome.# For example (1000...001) is palindromedef isPalindrome(x): l = 1 # Initialize left position r = 2 * 8 # initialize right position # One by one compare bits while (l < r): if (isKthBitSet(x, l) != isKthBitSet(x, r)): return False l += 1 r -= 1 return True # Driver Codeif __name__ =='__main__': x = 1 << 15 + 1 << 16 print(int(isPalindrome(x))) x = 1 << 31 + 1 print(int(isPalindrome(x))) # This code is contributed by# Surendra_Gangwar // C# Program to Check if binary representation// of a number is palindromeusing System; class GFG{ // This function returns true if k'th bit in x // is set (or 1). For example if x (0010) is 2 // and k is 2, then it returns true static int isKthBitSet(long x, long k) { int rslt = ((x & (1 << (int)(k - 1))) != 0) ? 1 : 0; return rslt; } // This function returns true if binary // representation of x is palindrome. // For example (1000...001) is palindrome static int isPalindrome( long x) { long l = 1; // Initialize left position long r = 4 * 8; // initialize right position // One by one compare bits while (l < r) { if (isKthBitSet(x, l) != isKthBitSet(x, r)) { return 0; } l++; r--; } return 1; } // Driver Code public static void Main () { long x = 1 << 15 + 1 << 16 ; Console.WriteLine(isPalindrome(x)); x = (1 << 31) + 1 ; Console.WriteLine(isPalindrome(x)); }} // This code is contributed by AnkitRai01 <?php// PHP Program to Check if binary representation// of a number is palindrome // This function returns true if k'th bit in x// is set (or 1). For example if x (0010) is 2// and k is 2, then it returns truefunction isKthBitSet($x, $k){ return ($x & (1 << ($k - 1))) ? true : false;} // This function returns true if binary// representation of x is palindrome.// For example (1000...001) is palindromefunction isPalindrome($x){ $l = 1; // Initialize left position $r = sizeof(4) * 8; // initialize right position // One by one compare bits while ($l < $r) { if (isKthBitSet($x, $l) != isKthBitSet($x, $r)) return false; $l++; $r--; } return true;} // Driver Code$x = 1 << 15 + 1 << 16;echo isPalindrome($x), "\n";$x = 1 << 31 + 1;echo isPalindrome($x), "\n"; // This code is contributed by ajit.?> <script> // Javascript program to Check if binary// representation of a number is palindrome // This function returns true if k'th bit in x// is set (or 1). For example if x (0010) is 2// and k is 2, then it returns truefunction isKthBitSet(x, k){ let rslt = ((x & (1 << (k - 1))) != 0) ? 1 : 0; return rslt;} // This function returns true if binary// representation of x is palindrome.// For example (1000...001) is palindromefunction isPalindrome(x){ // Initialize left position let l = 1; // initialize right position let r = 4 * 8; // One by one compare bits while (l < r) { if (isKthBitSet(x, l) != isKthBitSet(x, r)) { return 0; } l++; r--; } return 1;} // Driver codelet x = 1 << 15 + 1 << 16;document.write(isPalindrome(x) + "</br>"); x = (1 << 31) + 1;document.write(isPalindrome(x)); // This code is contributed by divyesh072019 </script> Output: 1 1 Time Complexity: O(x) Auxiliary Space: O(1) This article is contributed by Saurabh Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t SURENDRA_GANGWAR ankthon divyesh072019 simranarora5sos subhammahato348 Amazon binary-representation Microsoft Bit Magic Mathematical Amazon Microsoft Mathematical Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Little and Big Endian Mystery Cyclic Redundancy Check and Modulo-2 Division Binary representation of a given number Add two numbers without using arithmetic operators Josephus problem | Set 1 (A O(n) Solution) 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": 26125, "s": 26097, "text": "\n02 Nov, 2021" }, { "code": null, "e": 26562, "s": 26125, "text": "Given an integer ‘x’, write a C function that returns true if binary representation of x is palindrome else return false.For example a numbers with binary representation as 10..01 is palindrome and number with binary representation as 10..00 is not palindrome.The idea is similar to checking a string is palindrome or not. We start from leftmost and rightmost bits and compare bits one by one. If we find a mismatch, then return false. " }, { "code": null, "e": 27209, "s": 26562, "text": "Algorithm: isPalindrome(x) 1) Find number of bits in x using sizeof() operator. 2) Initialize left and right positions as 1 and n respectively. 3) Do following while left ‘l’ is smaller than right ‘r’. .......a) If bit at position ‘l’ is not same as bit at position ‘r’, then return false. .......b) Increment ‘l’ and decrement ‘r’, i.e., do l++ and r–-. 4) If we reach here, it means we didn’t find a mismatching bit.To find the bit at a given position, we can use the idea similar to this post. The expression “x & (1 << (k-1))” gives us non-zero value if bit at k’th position from right is set and gives a zero value if if k’th bit is not set." }, { "code": null, "e": 27266, "s": 27209, "text": "Following is the implementation of the above algorithm. " }, { "code": null, "e": 27270, "s": 27266, "text": "C++" }, { "code": null, "e": 27275, "s": 27270, "text": "Java" }, { "code": null, "e": 27283, "s": 27275, "text": "Python3" }, { "code": null, "e": 27286, "s": 27283, "text": "C#" }, { "code": null, "e": 27290, "s": 27286, "text": "PHP" }, { "code": null, "e": 27301, "s": 27290, "text": "Javascript" }, { "code": "// C++ Program to Check if binary representation// of a number is palindrome#include<iostream>using namespace std; // This function returns true if k'th bit in x// is set (or 1). For example if x (0010) is 2// and k is 2, then it returns truebool isKthBitSet(unsigned int x, unsigned int k){ return (x & (1 << (k - 1))) ? true : false;} // This function returns true if binary// representation of x is palindrome.// For example (1000...001) is palindromebool isPalindrome(unsigned int x){ int l = 1; // Initialize left position int r = sizeof(unsigned int) * 8; // initialize right position // One by one compare bits while (l < r) { if (isKthBitSet(x, l) != isKthBitSet(x, r)) return false; l++; r--; } return true;} // Driver Codeint main(){ unsigned int x = 1 << 15 + 1 << 16; cout << isPalindrome(x) << endl; x = 1 << 31 + 1; cout << isPalindrome(x) << endl; return 0;}", "e": 28240, "s": 27301, "text": null }, { "code": "// Java Program to Check if binary representation// of a number is palindromeclass GFG{ // This function returns true if k'th bit in x // is set (or 1). For example if x (0010) is 2 // and k is 2, then it returns true static int isKthBitSet(long x, long k) { int rslt = ((x & (1 << (k - 1))) != 0) ? 1 : 0; return rslt; } // This function returns true if binary // representation of x is palindrome. // For example (1000...001) is palindrome static int isPalindrome( long x) { long l = 1; // Initialize left position long r = (Integer.SIZE/8 )* 8; // initialize right position // One by one compare bits while (l < r) { if (isKthBitSet(x, l) != isKthBitSet(x, r)) { return 0; } l++; r--; } return 1; } // Driver Code public static void main (String[] args) { long x = 1 << 15 + 1 << 16 ; System.out.println(isPalindrome(x)); x = (1 << 31) + 1 ; System.out.println(isPalindrome(x)); }} // This code is contributed by AnkitRai01", "e": 29390, "s": 28240, "text": null }, { "code": "# python 3 Program to Check if binary representation# of a number is palindromeimport sys# This function returns true if k'th bit in x# is set (or 1). For example if x (0010) is 2# and k is 2, then it returns truedef isKthBitSet(x, k): if ((x & (1 << (k - 1))) !=0): return True else: return False # This function returns true if binary# representation of x is palindrome.# For example (1000...001) is palindromedef isPalindrome(x): l = 1 # Initialize left position r = 2 * 8 # initialize right position # One by one compare bits while (l < r): if (isKthBitSet(x, l) != isKthBitSet(x, r)): return False l += 1 r -= 1 return True # Driver Codeif __name__ =='__main__': x = 1 << 15 + 1 << 16 print(int(isPalindrome(x))) x = 1 << 31 + 1 print(int(isPalindrome(x))) # This code is contributed by# Surendra_Gangwar", "e": 30285, "s": 29390, "text": null }, { "code": "// C# Program to Check if binary representation// of a number is palindromeusing System; class GFG{ // This function returns true if k'th bit in x // is set (or 1). For example if x (0010) is 2 // and k is 2, then it returns true static int isKthBitSet(long x, long k) { int rslt = ((x & (1 << (int)(k - 1))) != 0) ? 1 : 0; return rslt; } // This function returns true if binary // representation of x is palindrome. // For example (1000...001) is palindrome static int isPalindrome( long x) { long l = 1; // Initialize left position long r = 4 * 8; // initialize right position // One by one compare bits while (l < r) { if (isKthBitSet(x, l) != isKthBitSet(x, r)) { return 0; } l++; r--; } return 1; } // Driver Code public static void Main () { long x = 1 << 15 + 1 << 16 ; Console.WriteLine(isPalindrome(x)); x = (1 << 31) + 1 ; Console.WriteLine(isPalindrome(x)); }} // This code is contributed by AnkitRai01", "e": 31422, "s": 30285, "text": null }, { "code": "<?php// PHP Program to Check if binary representation// of a number is palindrome // This function returns true if k'th bit in x// is set (or 1). For example if x (0010) is 2// and k is 2, then it returns truefunction isKthBitSet($x, $k){ return ($x & (1 << ($k - 1))) ? true : false;} // This function returns true if binary// representation of x is palindrome.// For example (1000...001) is palindromefunction isPalindrome($x){ $l = 1; // Initialize left position $r = sizeof(4) * 8; // initialize right position // One by one compare bits while ($l < $r) { if (isKthBitSet($x, $l) != isKthBitSet($x, $r)) return false; $l++; $r--; } return true;} // Driver Code$x = 1 << 15 + 1 << 16;echo isPalindrome($x), \"\\n\";$x = 1 << 31 + 1;echo isPalindrome($x), \"\\n\"; // This code is contributed by ajit.?>", "e": 32279, "s": 31422, "text": null }, { "code": "<script> // Javascript program to Check if binary// representation of a number is palindrome // This function returns true if k'th bit in x// is set (or 1). For example if x (0010) is 2// and k is 2, then it returns truefunction isKthBitSet(x, k){ let rslt = ((x & (1 << (k - 1))) != 0) ? 1 : 0; return rslt;} // This function returns true if binary// representation of x is palindrome.// For example (1000...001) is palindromefunction isPalindrome(x){ // Initialize left position let l = 1; // initialize right position let r = 4 * 8; // One by one compare bits while (l < r) { if (isKthBitSet(x, l) != isKthBitSet(x, r)) { return 0; } l++; r--; } return 1;} // Driver codelet x = 1 << 15 + 1 << 16;document.write(isPalindrome(x) + \"</br>\"); x = (1 << 31) + 1;document.write(isPalindrome(x)); // This code is contributed by divyesh072019 </script>", "e": 33226, "s": 32279, "text": null }, { "code": null, "e": 33235, "s": 33226, "text": "Output: " }, { "code": null, "e": 33239, "s": 33235, "text": "1\n1" }, { "code": null, "e": 33261, "s": 33239, "text": "Time Complexity: O(x)" }, { "code": null, "e": 33283, "s": 33261, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 33455, "s": 33283, "text": "This article is contributed by Saurabh Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 33461, "s": 33455, "text": "jit_t" }, { "code": null, "e": 33478, "s": 33461, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 33486, "s": 33478, "text": "ankthon" }, { "code": null, "e": 33500, "s": 33486, "text": "divyesh072019" }, { "code": null, "e": 33516, "s": 33500, "text": "simranarora5sos" }, { "code": null, "e": 33532, "s": 33516, "text": "subhammahato348" }, { "code": null, "e": 33539, "s": 33532, "text": "Amazon" }, { "code": null, "e": 33561, "s": 33539, "text": "binary-representation" }, { "code": null, "e": 33571, "s": 33561, "text": "Microsoft" }, { "code": null, "e": 33581, "s": 33571, "text": "Bit Magic" }, { "code": null, "e": 33594, "s": 33581, "text": "Mathematical" }, { "code": null, "e": 33601, "s": 33594, "text": "Amazon" }, { "code": null, "e": 33611, "s": 33601, "text": "Microsoft" }, { "code": null, "e": 33624, "s": 33611, "text": "Mathematical" }, { "code": null, "e": 33634, "s": 33624, "text": "Bit Magic" }, { "code": null, "e": 33732, "s": 33634, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33762, "s": 33732, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 33808, "s": 33762, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 33848, "s": 33808, "text": "Binary representation of a given number" }, { "code": null, "e": 33899, "s": 33848, "text": "Add two numbers without using arithmetic operators" }, { "code": null, "e": 33942, "s": 33899, "text": "Josephus problem | Set 1 (A O(n) Solution)" }, { "code": null, "e": 33972, "s": 33942, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 34032, "s": 33972, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 34047, "s": 34032, "text": "C++ Data Types" }, { "code": null, "e": 34090, "s": 34047, "text": "Set in C++ Standard Template Library (STL)" } ]
Set containsAll() method in Java with Examples - GeeksforGeeks
31 Dec, 2018 The containsAll() method of Java Set is used to check whether two sets contain the same elements or not. It takes one set as a parameter and returns True if all of the elements of this set is present in the other set. Syntax: public boolean containsAll(Collection C) Parameters: The parameter C is a Collection. This parameter refers to the set whose elements occurrence is needed to be checked in this set. Return Value: The method returns True if this set contains all the elements of other set otherwise it returns False. Below programs illustrate the Set.containsAll() method: Program 1: // Java code to illustrate// Set containsAll() import java.util.*; class SetDemo { public static void main(String args[]) { // Creating an empty set Set<String> set = new HashSet<String>(); // Use add() method to // add elements in the set set.add("Geeks"); set.add("for"); set.add("Geeks"); set.add("10"); set.add("20"); // prints the set System.out.println("Set 1: " + set); // Creating another empty set Set<String> set2 = new HashSet<String>(); // Use add() method to // add elements in the set set2.add("Geeks"); set2.add("for"); set2.add("Geeks"); set2.add("10"); set2.add("20"); // prints the set System.out.println("Set 2: " + set2); // Check if the set // contains same elements System.out.println("\nDoes set 1 contains set 2?: " + set.containsAll(set2)); }} Set 1: [Geeks, for, 20, 10] Set 2: [Geeks, for, 20, 10] Does set 1 contains set 2?: true Program 2: // Java code to illustrate boolean containsAll() import java.util.*; class SetDemo { public static void main(String args[]) { // Creating an empty set Set<String> set = new HashSet<String>(); // Use add() method to // add elements in the set set.add("Geeks"); set.add("for"); set.add("Geeks"); // prints the set System.out.println("Set 1: " + set); // Creating another empty set Set<String> set2 = new HashSet<String>(); // Use add() method to // add elements in the set set2.add("10"); set2.add("20"); // prints the set System.out.println("Set 2: " + set2); // Check if the set // contains same elements System.out.println("\nDoes set 1 contains set 2: " + set.containsAll(set2)); }} Set 1: [Geeks, for] Set 2: [20, 10] Does set 1 contains set 2: false Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#containsAll(java.util.Collection) Java-Collections Java-Functions java-set Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. HashMap in Java with Examples Interfaces in Java Stream In Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java Set in Java Multithreading in Java
[ { "code": null, "e": 26129, "s": 26101, "text": "\n31 Dec, 2018" }, { "code": null, "e": 26347, "s": 26129, "text": "The containsAll() method of Java Set is used to check whether two sets contain the same elements or not. It takes one set as a parameter and returns True if all of the elements of this set is present in the other set." }, { "code": null, "e": 26355, "s": 26347, "text": "Syntax:" }, { "code": null, "e": 26396, "s": 26355, "text": "public boolean containsAll(Collection C)" }, { "code": null, "e": 26537, "s": 26396, "text": "Parameters: The parameter C is a Collection. This parameter refers to the set whose elements occurrence is needed to be checked in this set." }, { "code": null, "e": 26654, "s": 26537, "text": "Return Value: The method returns True if this set contains all the elements of other set otherwise it returns False." }, { "code": null, "e": 26710, "s": 26654, "text": "Below programs illustrate the Set.containsAll() method:" }, { "code": null, "e": 26721, "s": 26710, "text": "Program 1:" }, { "code": "// Java code to illustrate// Set containsAll() import java.util.*; class SetDemo { public static void main(String args[]) { // Creating an empty set Set<String> set = new HashSet<String>(); // Use add() method to // add elements in the set set.add(\"Geeks\"); set.add(\"for\"); set.add(\"Geeks\"); set.add(\"10\"); set.add(\"20\"); // prints the set System.out.println(\"Set 1: \" + set); // Creating another empty set Set<String> set2 = new HashSet<String>(); // Use add() method to // add elements in the set set2.add(\"Geeks\"); set2.add(\"for\"); set2.add(\"Geeks\"); set2.add(\"10\"); set2.add(\"20\"); // prints the set System.out.println(\"Set 2: \" + set2); // Check if the set // contains same elements System.out.println(\"\\nDoes set 1 contains set 2?: \" + set.containsAll(set2)); }}", "e": 27790, "s": 26721, "text": null }, { "code": null, "e": 27881, "s": 27790, "text": "Set 1: [Geeks, for, 20, 10]\nSet 2: [Geeks, for, 20, 10]\n\nDoes set 1 contains set 2?: true\n" }, { "code": null, "e": 27892, "s": 27881, "text": "Program 2:" }, { "code": "// Java code to illustrate boolean containsAll() import java.util.*; class SetDemo { public static void main(String args[]) { // Creating an empty set Set<String> set = new HashSet<String>(); // Use add() method to // add elements in the set set.add(\"Geeks\"); set.add(\"for\"); set.add(\"Geeks\"); // prints the set System.out.println(\"Set 1: \" + set); // Creating another empty set Set<String> set2 = new HashSet<String>(); // Use add() method to // add elements in the set set2.add(\"10\"); set2.add(\"20\"); // prints the set System.out.println(\"Set 2: \" + set2); // Check if the set // contains same elements System.out.println(\"\\nDoes set 1 contains set 2: \" + set.containsAll(set2)); }}", "e": 28842, "s": 27892, "text": null }, { "code": null, "e": 28913, "s": 28842, "text": "Set 1: [Geeks, for]\nSet 2: [20, 10]\n\nDoes set 1 contains set 2: false\n" }, { "code": null, "e": 29019, "s": 28913, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#containsAll(java.util.Collection)" }, { "code": null, "e": 29036, "s": 29019, "text": "Java-Collections" }, { "code": null, "e": 29051, "s": 29036, "text": "Java-Functions" }, { "code": null, "e": 29060, "s": 29051, "text": "java-set" }, { "code": null, "e": 29065, "s": 29060, "text": "Java" }, { "code": null, "e": 29070, "s": 29065, "text": "Java" }, { "code": null, "e": 29087, "s": 29070, "text": "Java-Collections" }, { "code": null, "e": 29185, "s": 29087, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29215, "s": 29185, "text": "HashMap in Java with Examples" }, { "code": null, "e": 29234, "s": 29215, "text": "Interfaces in Java" }, { "code": null, "e": 29249, "s": 29234, "text": "Stream In Java" }, { "code": null, "e": 29267, "s": 29249, "text": "ArrayList in Java" }, { "code": null, "e": 29299, "s": 29267, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 29319, "s": 29299, "text": "Stack Class in Java" }, { "code": null, "e": 29351, "s": 29319, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 29375, "s": 29351, "text": "Singleton Class in Java" }, { "code": null, "e": 29387, "s": 29375, "text": "Set in Java" } ]
CURRENT_USER() Function in SQL Server - GeeksforGeeks
15 Feb, 2021 CURRENT_USER() function :This function in SQL Server is used to return the current user’s name in the database of SQL Server in use. Features : This function is used to find the current user’s name. This function comes under Advanced Functions. This function doesn’t accept any parameter. Syntax : CURRENT_USER Parameter : This method does not accept any parameter. Returns : It returns the current user’s name in the database of SQL Server which is in use. Example-1 :Using CURRENT_USER () function and getting the current user’s name. SELECT CURRENT_USER; Output : nidhi Example-2 :Using CURRENT_USER as a default value in the below example and getting the output. CREATE TABLE user01 ( user_id int IDENTITY(100, 2) NOT NULL, customer_id int NOT NULL, user_name char(50) NOT NULL DEFAULT CURRENT_USER ); Inserting values in the table – INSERT user01(customer_id) VALUES (101), (102); Displaying the contents of the table – SELECT * FROM user01; Output : Here, firstly you need to create a table then insert values into it then generate the required output using CURRENT_USER function as a default value. Note: For running above code use SQL server compiler, you can also use an online compiler. Example-3 :Using CURRENT_USER () function and impersonating user ‘Geek’. SELECT CURRENT_USER; EXECUTE AS USER = 'Geek'; SELECT CURRENT_USER; Output : nidhi Geek Here, we are impersonating user as ‘Geek’, then calling CURRENT_USER function to get the current user’s name. Example-4 :Using CURRENT_USER () function for impersonating user ‘Geek’ then again reverting the code to get the previous current user. SELECT CURRENT_USER; EXECUTE AS USER = 'Geek'; SELECT CURRENT_USER; REVERT; SELECT CURRENT_USER; Output : nidhi Geek nidhi Application : This function is used to find the current user’s name in the database of the SQL server. SQL-Server DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Deadlock in DBMS Types of Functional dependencies in DBMS KDD Process in Data Mining What is Temporary Table in SQL? Conflict Serializability in DBMS SQL | DDL, DQL, DML, DCL and TCL Commands How to find Nth highest salary from a table SQL | ALTER (RENAME) How to Update Multiple Columns in Single Update Statement in SQL? MySQL | Group_CONCAT() Function
[ { "code": null, "e": 25549, "s": 25521, "text": "\n15 Feb, 2021" }, { "code": null, "e": 25682, "s": 25549, "text": "CURRENT_USER() function :This function in SQL Server is used to return the current user’s name in the database of SQL Server in use." }, { "code": null, "e": 25693, "s": 25682, "text": "Features :" }, { "code": null, "e": 25748, "s": 25693, "text": "This function is used to find the current user’s name." }, { "code": null, "e": 25794, "s": 25748, "text": "This function comes under Advanced Functions." }, { "code": null, "e": 25838, "s": 25794, "text": "This function doesn’t accept any parameter." }, { "code": null, "e": 25847, "s": 25838, "text": "Syntax :" }, { "code": null, "e": 25860, "s": 25847, "text": "CURRENT_USER" }, { "code": null, "e": 25915, "s": 25860, "text": "Parameter : This method does not accept any parameter." }, { "code": null, "e": 26007, "s": 25915, "text": "Returns : It returns the current user’s name in the database of SQL Server which is in use." }, { "code": null, "e": 26086, "s": 26007, "text": "Example-1 :Using CURRENT_USER () function and getting the current user’s name." }, { "code": null, "e": 26107, "s": 26086, "text": "SELECT CURRENT_USER;" }, { "code": null, "e": 26116, "s": 26107, "text": "Output :" }, { "code": null, "e": 26122, "s": 26116, "text": "nidhi" }, { "code": null, "e": 26216, "s": 26122, "text": "Example-2 :Using CURRENT_USER as a default value in the below example and getting the output." }, { "code": null, "e": 26358, "s": 26216, "text": "CREATE TABLE user01 ( \nuser_id int IDENTITY(100, 2) NOT NULL,\ncustomer_id int NOT NULL,\nuser_name char(50) NOT NULL DEFAULT CURRENT_USER\n); " }, { "code": null, "e": 26391, "s": 26358, "text": " Inserting values in the table –" }, { "code": null, "e": 26441, "s": 26391, "text": "INSERT user01(customer_id) \nVALUES (101), (102);" }, { "code": null, "e": 26480, "s": 26441, "text": "Displaying the contents of the table –" }, { "code": null, "e": 26505, "s": 26480, "text": "SELECT * \nFROM user01; " }, { "code": null, "e": 26514, "s": 26505, "text": "Output :" }, { "code": null, "e": 26664, "s": 26514, "text": "Here, firstly you need to create a table then insert values into it then generate the required output using CURRENT_USER function as a default value." }, { "code": null, "e": 26755, "s": 26664, "text": "Note: For running above code use SQL server compiler, you can also use an online compiler." }, { "code": null, "e": 26828, "s": 26755, "text": "Example-3 :Using CURRENT_USER () function and impersonating user ‘Geek’." }, { "code": null, "e": 26903, "s": 26828, "text": "SELECT CURRENT_USER; \nEXECUTE AS USER = 'Geek'; \nSELECT CURRENT_USER; " }, { "code": null, "e": 26912, "s": 26903, "text": "Output :" }, { "code": null, "e": 26923, "s": 26912, "text": "nidhi\nGeek" }, { "code": null, "e": 27033, "s": 26923, "text": "Here, we are impersonating user as ‘Geek’, then calling CURRENT_USER function to get the current user’s name." }, { "code": null, "e": 27169, "s": 27033, "text": "Example-4 :Using CURRENT_USER () function for impersonating user ‘Geek’ then again reverting the code to get the previous current user." }, { "code": null, "e": 27273, "s": 27169, "text": "SELECT CURRENT_USER; \nEXECUTE AS USER = 'Geek'; \nSELECT CURRENT_USER; \nREVERT;\nSELECT CURRENT_USER;" }, { "code": null, "e": 27282, "s": 27273, "text": "Output :" }, { "code": null, "e": 27299, "s": 27282, "text": "nidhi\nGeek\nnidhi" }, { "code": null, "e": 27313, "s": 27299, "text": "Application :" }, { "code": null, "e": 27402, "s": 27313, "text": "This function is used to find the current user’s name in the database of the SQL server." }, { "code": null, "e": 27413, "s": 27402, "text": "SQL-Server" }, { "code": null, "e": 27418, "s": 27413, "text": "DBMS" }, { "code": null, "e": 27422, "s": 27418, "text": "SQL" }, { "code": null, "e": 27427, "s": 27422, "text": "DBMS" }, { "code": null, "e": 27431, "s": 27427, "text": "SQL" }, { "code": null, "e": 27529, "s": 27431, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27546, "s": 27529, "text": "Deadlock in DBMS" }, { "code": null, "e": 27587, "s": 27546, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 27614, "s": 27587, "text": "KDD Process in Data Mining" }, { "code": null, "e": 27646, "s": 27614, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 27679, "s": 27646, "text": "Conflict Serializability in DBMS" }, { "code": null, "e": 27721, "s": 27679, "text": "SQL | DDL, DQL, DML, DCL and TCL Commands" }, { "code": null, "e": 27765, "s": 27721, "text": "How to find Nth highest salary from a table" }, { "code": null, "e": 27786, "s": 27765, "text": "SQL | ALTER (RENAME)" }, { "code": null, "e": 27852, "s": 27786, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" } ]
How to write the output to HTML file with Python BeautifulSoup? - GeeksforGeeks
08 Apr, 2021 In this article, we are going to write the output to an HTML file with Python BeautifulSoup. BeautifulSoup is a python library majorly used for web scraping but in this article, we will discuss how to write the output to an HTML file. Modules needed and installation: pip install bs4 Approach: We will first import all the required libraries. Make a get request to the desired URL and extract its page content. Using the file data type of python write the output in a new file. Steps to be followed: Step 1: Import the required libraries. Python3 # Import librariesfrom bs4 import BeautifulSoupimport requests Step 2: We will perform a get request to the Google search engine home page and extract its page content and make a soup object out of it by passing it to beautiful soup, and we will set the markup as html.parser. Note: if you are extracting a xml page set the markup as xml.parser Python3 # set the url to perform the get requestURL = 'https://www.geeksforgeeks.org/how-to-scrape-all-pdf-files-in-a-website/'page = requests.get(URL) # load the page contenttext = page.content # make a soup object by using beautiful# soup and set the markup as html parsersoup = BeautifulSoup(text, "html.parser") Step 3: We use the file data type of python and write the soup object in the output file. We will set the encoding to UTF-8. We will use .prettify() function on soup object that will make it easier to read. We will convert the soup object to a string before writing it. We will store the output file in the same directory with the name output.html Python3 # open the file in w mode# set encoding to UTF-8with open("output.html", "w", encoding = 'utf-8') as file: # prettify the soup object and convert it into a string file.write(str(soup.prettify())) Below is the full implementation: Python3 # Import librariesfrom bs4 import BeautifulSoupimport requests # set the url to perform the get requestURL = 'https://www.geeksforgeeks.org/how-to-scrape-all-pdf-files-in-a-website/'page = requests.get(URL) # load the page contenttext = page.content # make a soup object by using# beautiful soup and set the markup as html parsersoup = BeautifulSoup(text, "html.parser") # open the file in w mode# set encoding to UTF-8with open("output.html", "w", encoding = 'utf-8') as file: # prettify the soup object and convert it into a string file.write(str(soup.prettify())) Output: Picked Python BeautifulSoup Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n08 Apr, 2021" }, { "code": null, "e": 25773, "s": 25537, "text": "In this article, we are going to write the output to an HTML file with Python BeautifulSoup. BeautifulSoup is a python library majorly used for web scraping but in this article, we will discuss how to write the output to an HTML file." }, { "code": null, "e": 25806, "s": 25773, "text": "Modules needed and installation:" }, { "code": null, "e": 25822, "s": 25806, "text": "pip install bs4" }, { "code": null, "e": 25832, "s": 25822, "text": "Approach:" }, { "code": null, "e": 25881, "s": 25832, "text": "We will first import all the required libraries." }, { "code": null, "e": 25949, "s": 25881, "text": "Make a get request to the desired URL and extract its page content." }, { "code": null, "e": 26016, "s": 25949, "text": "Using the file data type of python write the output in a new file." }, { "code": null, "e": 26038, "s": 26016, "text": "Steps to be followed:" }, { "code": null, "e": 26077, "s": 26038, "text": "Step 1: Import the required libraries." }, { "code": null, "e": 26085, "s": 26077, "text": "Python3" }, { "code": "# Import librariesfrom bs4 import BeautifulSoupimport requests", "e": 26148, "s": 26085, "text": null }, { "code": null, "e": 26362, "s": 26148, "text": "Step 2: We will perform a get request to the Google search engine home page and extract its page content and make a soup object out of it by passing it to beautiful soup, and we will set the markup as html.parser." }, { "code": null, "e": 26430, "s": 26362, "text": "Note: if you are extracting a xml page set the markup as xml.parser" }, { "code": null, "e": 26438, "s": 26430, "text": "Python3" }, { "code": "# set the url to perform the get requestURL = 'https://www.geeksforgeeks.org/how-to-scrape-all-pdf-files-in-a-website/'page = requests.get(URL) # load the page contenttext = page.content # make a soup object by using beautiful# soup and set the markup as html parsersoup = BeautifulSoup(text, \"html.parser\")", "e": 26748, "s": 26438, "text": null }, { "code": null, "e": 27018, "s": 26748, "text": "Step 3: We use the file data type of python and write the soup object in the output file. We will set the encoding to UTF-8. We will use .prettify() function on soup object that will make it easier to read. We will convert the soup object to a string before writing it." }, { "code": null, "e": 27096, "s": 27018, "text": "We will store the output file in the same directory with the name output.html" }, { "code": null, "e": 27104, "s": 27096, "text": "Python3" }, { "code": "# open the file in w mode# set encoding to UTF-8with open(\"output.html\", \"w\", encoding = 'utf-8') as file: # prettify the soup object and convert it into a string file.write(str(soup.prettify()))", "e": 27312, "s": 27104, "text": null }, { "code": null, "e": 27346, "s": 27312, "text": "Below is the full implementation:" }, { "code": null, "e": 27354, "s": 27346, "text": "Python3" }, { "code": "# Import librariesfrom bs4 import BeautifulSoupimport requests # set the url to perform the get requestURL = 'https://www.geeksforgeeks.org/how-to-scrape-all-pdf-files-in-a-website/'page = requests.get(URL) # load the page contenttext = page.content # make a soup object by using# beautiful soup and set the markup as html parsersoup = BeautifulSoup(text, \"html.parser\") # open the file in w mode# set encoding to UTF-8with open(\"output.html\", \"w\", encoding = 'utf-8') as file: # prettify the soup object and convert it into a string file.write(str(soup.prettify()))", "e": 27935, "s": 27354, "text": null }, { "code": null, "e": 27943, "s": 27935, "text": "Output:" }, { "code": null, "e": 27950, "s": 27943, "text": "Picked" }, { "code": null, "e": 27971, "s": 27950, "text": "Python BeautifulSoup" }, { "code": null, "e": 27978, "s": 27971, "text": "Python" }, { "code": null, "e": 28076, "s": 27978, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28108, "s": 28076, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28150, "s": 28108, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28192, "s": 28150, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28219, "s": 28192, "text": "Python Classes and Objects" }, { "code": null, "e": 28275, "s": 28219, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28297, "s": 28275, "text": "Defaultdict in Python" }, { "code": null, "e": 28336, "s": 28297, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28367, "s": 28336, "text": "Python | os.path.join() method" }, { "code": null, "e": 28396, "s": 28367, "text": "Create a directory in Python" } ]
Explain Description Lists in HTML - GeeksforGeeks
04 Jan, 2022 A description list is a list of terms, with a description of each term. Lists in HTML are used for specifying particular information in list form. There are various types of Lists in Html such as Ordered Lists, Unordered Lists, and description Lists. Description Lists are used for: To give definitions to particular terms that we have defined in our lists. To have a dictionary type of format(term and definition of term) Format of description Lists: Description Lists are used with description list tag <dl> tag in html. In <dl> tag we have description terms it is represented as <dt> tag Here we do not use li tag as Other Lists. In <dt> write terms of the data. We can have different terms with the help of <dl>tag. In this we use data description tag <dd> we use this tag for defining the term that we have stated. for eg. If we declare term as Pizza then we can have description as Pizza is a food item. Syntax: <dl> Contents of the list </dl> Example 1: HTML <!DOCTYPE html><html> <head> <title> Description lists in html </title></head> <body> <h1>GeeksForGeeks Courses</h1> <h2> Live courses at GeeksForGeeks and their Description </h2> <dl> <dt> Full Stack Development with React & Node JS - Live: </dt> <dd> Learn how to develop Single Page Web Applications. </dd> <dt>System Design - Live:</dt> <dd> For individuals looking to crack SDE job interviews. </dd> <dt>JAVA Backend Development - Live:</dt> <dd>Learn backend development with Java</dd> <dt>DSA Live for Working Professionals:</dt> <dd> A LIVE classroom program designed for Working Professionals </dd> </dl></body> </html> Output: Example 2: HTML <!DOCTYPE html><html> <head> <title>Description lists in html</title></head> <body> <h1>GeeksForGeeks problem difficulties</h1> <h2> This is Type and description of problem difficulty levels <br>at Practice platform of GeeksForGeeks. </h2> <dl> <dt>School:</dt> <dd>Basic/school level problems</dd> <dt>Basic:</dt> <dd>Simple logical problems</dd> <dt>Easy:</dt> <dd> Problems based on simple data structures and logic </dd> <dt>Medium:</dt> <dd>Medium level problems based on dsa</dd> <dt>Hard:</dt> <dd>High level logical thinking problems</dd> </dl></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. nnr223442 HTML-Questions HTML-Tags Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML Design a web page using HTML and CSS Form validation using jQuery Angular File Upload Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26139, "s": 26111, "text": "\n04 Jan, 2022" }, { "code": null, "e": 26390, "s": 26139, "text": "A description list is a list of terms, with a description of each term. Lists in HTML are used for specifying particular information in list form. There are various types of Lists in Html such as Ordered Lists, Unordered Lists, and description Lists." }, { "code": null, "e": 26422, "s": 26390, "text": "Description Lists are used for:" }, { "code": null, "e": 26497, "s": 26422, "text": "To give definitions to particular terms that we have defined in our lists." }, { "code": null, "e": 26562, "s": 26497, "text": "To have a dictionary type of format(term and definition of term)" }, { "code": null, "e": 26591, "s": 26562, "text": "Format of description Lists:" }, { "code": null, "e": 26662, "s": 26591, "text": "Description Lists are used with description list tag <dl> tag in html." }, { "code": null, "e": 26859, "s": 26662, "text": "In <dl> tag we have description terms it is represented as <dt> tag Here we do not use li tag as Other Lists. In <dt> write terms of the data. We can have different terms with the help of <dl>tag." }, { "code": null, "e": 27049, "s": 26859, "text": "In this we use data description tag <dd> we use this tag for defining the term that we have stated. for eg. If we declare term as Pizza then we can have description as Pizza is a food item." }, { "code": null, "e": 27057, "s": 27049, "text": "Syntax:" }, { "code": null, "e": 27089, "s": 27057, "text": "<dl> Contents of the list </dl>" }, { "code": null, "e": 27100, "s": 27089, "text": "Example 1:" }, { "code": null, "e": 27105, "s": 27100, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> Description lists in html </title></head> <body> <h1>GeeksForGeeks Courses</h1> <h2> Live courses at GeeksForGeeks and their Description </h2> <dl> <dt> Full Stack Development with React & Node JS - Live: </dt> <dd> Learn how to develop Single Page Web Applications. </dd> <dt>System Design - Live:</dt> <dd> For individuals looking to crack SDE job interviews. </dd> <dt>JAVA Backend Development - Live:</dt> <dd>Learn backend development with Java</dd> <dt>DSA Live for Working Professionals:</dt> <dd> A LIVE classroom program designed for Working Professionals </dd> </dl></body> </html>", "e": 27954, "s": 27105, "text": null }, { "code": null, "e": 27962, "s": 27954, "text": "Output:" }, { "code": null, "e": 27973, "s": 27962, "text": "Example 2:" }, { "code": null, "e": 27978, "s": 27973, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Description lists in html</title></head> <body> <h1>GeeksForGeeks problem difficulties</h1> <h2> This is Type and description of problem difficulty levels <br>at Practice platform of GeeksForGeeks. </h2> <dl> <dt>School:</dt> <dd>Basic/school level problems</dd> <dt>Basic:</dt> <dd>Simple logical problems</dd> <dt>Easy:</dt> <dd> Problems based on simple data structures and logic </dd> <dt>Medium:</dt> <dd>Medium level problems based on dsa</dd> <dt>Hard:</dt> <dd>High level logical thinking problems</dd> </dl></body> </html>", "e": 28686, "s": 27978, "text": null }, { "code": null, "e": 28694, "s": 28686, "text": "Output:" }, { "code": null, "e": 28831, "s": 28694, "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": 28841, "s": 28831, "text": "nnr223442" }, { "code": null, "e": 28856, "s": 28841, "text": "HTML-Questions" }, { "code": null, "e": 28866, "s": 28856, "text": "HTML-Tags" }, { "code": null, "e": 28873, "s": 28866, "text": "Picked" }, { "code": null, "e": 28878, "s": 28873, "text": "HTML" }, { "code": null, "e": 28895, "s": 28878, "text": "Web Technologies" }, { "code": null, "e": 28900, "s": 28895, "text": "HTML" }, { "code": null, "e": 28998, "s": 28900, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29022, "s": 28998, "text": "REST API (Introduction)" }, { "code": null, "e": 29063, "s": 29022, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 29100, "s": 29063, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 29129, "s": 29100, "text": "Form validation using jQuery" }, { "code": null, "e": 29149, "s": 29129, "text": "Angular File Upload" }, { "code": null, "e": 29189, "s": 29149, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29222, "s": 29189, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29267, "s": 29222, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29310, "s": 29267, "text": "How to fetch data from an API in ReactJS ?" } ]
LCA for n-ary Tree | Constant Query O(1) - GeeksforGeeks
16 Dec, 2021 We have seen various methods with different Time Complexities to calculate LCA in n-ary tree:-Method 1 : Naive Method ( by calculating root to node path) | O(n) per query Method 2 :Using Sqrt Decomposition | O(sqrt H) Method 3 : Using Sparse Matrix DP approach | O(logn) Lets study another method that has faster query time than all the above methods. So, our aim will be to calculate LCA in constant time ~ O(1). Let’s see how we can achieve it. Method 4 : Using Range Minimum Query We have discussed LCA and RMQ for binary tree. Here we discuss LCA problem to RMQ problem conversion for n-ary tree. Pre-requisites:- LCA in Binary Tree using RMQ RMQ using sparse table Key Concept : In this method, we will be reducing our LCA problem to RMQ(Range Minimum Query) problem over a static array. Once, we do that then we will relate the Range minimum queries to the required LCA queries. The first step will be to decompose the tree into a flat linear array. To do this we can apply the Euler walk. The Euler walk will give the pre-order traversal of the graph. So we will perform a Euler Walk on the tree and store the nodes in an array as we visit them. This process reduces the tree data-structure to a simple linear array. Consider the below tree and the euler walk over it:- Now lets think in general terms : Consider any two nodes on the tree. There will be exactly one path connecting both the nodes and the node that has the smallest depth value in the path will be the LCA of the two given nodes.Now take any two distinct node say u and v in the Euler walk array. Now all the elements in the path from u to v will lie in between the index of nodes u and v in the Euler walk array. Therefore, we just need to calculate the node with the minimum depth between the index of node u and node v in the euler array. For this we will maintain another array that will contain the depth of all the nodes corresponding to their position in the Euler walk array so that we can Apply our RMQ algorithm on it. Given below is the euler walk array parallel to its depth track array. Example :- Consider two nodes node 6 and node 7 in the euler array. To calculate the LCA of node 6 and node 7 we look the smallest depth value for all the nodes in between node 6 and node 7 . Therefore, node 1 has the smallest depth value = 0 and hence, it is the LCA for node 6 and node 7. Implementation:- We will be maintaining three arrays 1)Euler Path 2)Depth array 3)First Appearance Index Euler Path and Depth array are the same as described above First Appearance Index FAI[] : The First Appearance index Array will store the index for the first position of every node in the Euler Path array. FAI[i] = First appearance of ith node in Euler Walk array. The Implementation for the above method is given below:- C++ Java // C++ program to demonstrate LCA of n-ary tree// in constant time.#include "bits/stdc++.h"using namespace std;#define sz 101 vector < int > adj[sz]; // stores the treevector < int > euler; // tracks the eulerwalkvector < int > depthArr; // depth for each node corresponding // to eulerwalk int FAI[sz]; // stores first appearance index of every nodeint level[sz]; // stores depth for all nodes in the treeint ptr; // pointer to euler walkint dp[sz][18]; // sparse tableint logn[sz]; // stores log valuesint p2[20]; // stores power of 2 void buildSparseTable(int n){ // initializing sparse table memset(dp,-1,sizeof(dp)); // filling base case values for (int i=1; i<n; i++) dp[i-1][0] = (depthArr[i]>depthArr[i-1])?i-1:i; // dp to fill sparse table for (int l=1; l<15; l++) for (int i=0; i<n; i++) if (dp[i][l-1]!=-1 and dp[i+p2[l-1]][l-1]!=-1) dp[i][l] = (depthArr[dp[i][l-1]]>depthArr[dp[i+p2[l-1]][l-1]])? dp[i+p2[l-1]][l-1] : dp[i][l-1]; else break;} int query(int l,int r){ int d = r-l; int dx = logn[d]; if (l==r) return l; if (depthArr[dp[l][dx]] > depthArr[dp[r-p2[dx]][dx]]) return dp[r-p2[dx]][dx]; else return dp[l][dx];} void preprocess(){ // memorizing powers of 2 p2[0] = 1; for (int i=1; i<18; i++) p2[i] = p2[i-1]*2; // memorizing all log(n) values int val = 1,ptr=0; for (int i=1; i<sz; i++) { logn[i] = ptr-1; if (val==i) { val*=2; logn[i] = ptr; ptr++; } }} /** * Euler Walk ( preorder traversal) * converting tree to linear depthArray * Time Complexity : O(n) * */void dfs(int cur,int prev,int dep){ // marking FAI for cur node if (FAI[cur]==-1) FAI[cur] = ptr; level[cur] = dep; // pushing root to euler walk euler.push_back(cur); // incrementing euler walk pointer ptr++; for (auto x:adj[cur]) { if (x != prev) { dfs(x,cur,dep+1); // pushing cur again in backtrack // of euler walk euler.push_back(cur); // increment euler walk pointer ptr++; } }} // Create Level depthArray corresponding// to the Euler walk Arrayvoid makeArr(){ for (auto x : euler) depthArr.push_back(level[x]);} int LCA(int u,int v){ // trivial case if (u==v) return u; if (FAI[u] > FAI[v]) swap(u,v); // doing RMQ in the required range return euler[query(FAI[u], FAI[v])];} void addEdge(int u,int v){ adj[u].push_back(v); adj[v].push_back(u);} int main(int argc, char const *argv[]){ // constructing the described tree int numberOfNodes = 8; addEdge(1,2); addEdge(1,3); addEdge(2,4); addEdge(2,5); addEdge(2,6); addEdge(3,7); addEdge(3,8); // performing required precalculations preprocess(); // doing the Euler walk ptr = 0; memset(FAI,-1,sizeof(FAI)); dfs(1,0,0); // creating depthArray corresponding to euler[] makeArr(); // building sparse table buildSparseTable(depthArr.size()); cout << "LCA(6,7) : " << LCA(6,7) << "\n"; cout << "LCA(6,4) : " << LCA(6,4) << "\n"; return 0;} // Java program to demonstrate LCA of n-ary// tree in constant time.import java.util.ArrayList;import java.util.Arrays; class GFG{ static int sz = 101; @SuppressWarnings("unchecked")// Stores the treestatic ArrayList<Integer>[] adj = new ArrayList[sz]; // Tracks the eulerwalkstatic ArrayList<Integer> euler = new ArrayList<>(); // Depth for each node correspondingstatic ArrayList<Integer> depthArr = new ArrayList<>();// to eulerwalk // Stores first appearance index of every nodestatic int[] FAI = new int[sz]; // Stores depth for all nodes in the treestatic int[] level = new int[sz]; // Pointer to euler walkstatic int ptr; // Sparse tablestatic int[][] dp = new int[sz][18]; // Stores log valuesstatic int[] logn = new int[sz]; // Stores power of 2static int[] p2 = new int[20]; static void buildSparseTable(int n){ // Initializing sparse table for(int i = 0; i < sz; i++) { for(int j = 0; j < 18; j++) { dp[i][j] = -1; } } // Filling base case values for(int i = 1; i < n; i++) dp[i - 1][0] = (depthArr.get(i) > depthArr.get(i - 1)) ? i - 1 : i; // dp to fill sparse table for(int l = 1; l < 15; l++) for(int i = 0; i < n; i++) if (dp[i][l - 1] != -1 && dp[i + p2[l - 1]][l - 1] != -1) dp[i][l] = (depthArr.get(dp[i][l - 1]) > depthArr.get( dp[i + p2[l - 1]][l - 1])) ? dp[i + p2[l - 1]][l - 1] : dp[i][l - 1]; else break;} static int query(int l, int r){ int d = r - l; int dx = logn[d]; if (l == r) return l; if (depthArr.get(dp[l][dx]) > depthArr.get(dp[r - p2[dx]][dx])) return dp[r - p2[dx]][dx]; else return dp[l][dx];} static void preprocess(){ // Memorizing powers of 2 p2[0] = 1; for(int i = 1; i < 18; i++) p2[i] = p2[i - 1] * 2; // Memorizing all log(n) values int val = 1, ptr = 0; for(int i = 1; i < sz; i++) { logn[i] = ptr - 1; if (val == i) { val *= 2; logn[i] = ptr; ptr++; } }} // Euler Walk ( preorder traversal) converting// tree to linear depthArray// Time Complexity : O(n)static void dfs(int cur, int prev, int dep){ // Marking FAI for cur node if (FAI[cur] == -1) FAI[cur] = ptr; level[cur] = dep; // Pushing root to euler walk euler.add(cur); // Incrementing euler walk pointer ptr++; for(Integer x : adj[cur]) { if (x != prev) { dfs(x, cur, dep + 1); // Pushing cur again in backtrack // of euler walk euler.add(cur); // Increment euler walk pointer ptr++; } }} // Create Level depthArray corresponding// to the Euler walk Arraystatic void makeArr(){ for(Integer x : euler) depthArr.add(level[x]);} static int LCA(int u, int v){ // Trivial case if (u == v) return u; if (FAI[u] > FAI[v]) { int temp = u; u = v; v = temp; } // Doing RMQ in the required range return euler.get(query(FAI[u], FAI[v]));} static void addEdge(int u, int v){ adj[u].add(v); adj[v].add(u);} // Driver codepublic static void main(String[] args){ for(int i = 0; i < sz; i++) { adj[i] = new ArrayList<>(); } // Constructing the described tree int numberOfNodes = 8; addEdge(1, 2); addEdge(1, 3); addEdge(2, 4); addEdge(2, 5); addEdge(2, 6); addEdge(3, 7); addEdge(3, 8); // Performing required precalculations preprocess(); // Doing the Euler walk ptr = 0; Arrays.fill(FAI, -1); dfs(1, 0, 0); // Creating depthArray corresponding to euler[] makeArr(); // Building sparse table buildSparseTable(depthArr.size()); System.out.println("LCA(6,7) : " + LCA(6, 7)); System.out.println("LCA(6,4) : " + LCA(6, 4));}} // This code is contributed by sanjeev2552 Output: LCA(6,7) : 1 LCA(6,4) : 2 Note : We are precalculating all the required power of 2’s and also precalculating the all the required log values to ensure constant time complexity per query. Else if we did log calculation for every query operation our Time complexity would have not been constant. Time Complexity: The Conversion process from LCA to RMQ is done by Euler Walk that takes O(n) time. Pre-processing for the sparse table in RMQ takes O(nlogn) time and answering each Query is a Constant time process. Therefore, overall Time Complexity is O(nlogn) – preprocessing and O(1) for each query. This article is contributed by Nitish Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Akanksha_Rai sanjeev2552 clintra sumitgumber28 anikakapoor array-range-queries n-ary-tree Advanced Data Structure Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Ordered Set and GNU C++ PBDS 2-3 Trees | (Search, Insert and Deletion) Extendible Hashing (Dynamic approach to DBMS) Suffix Array | Set 1 (Introduction) Quad Tree Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal Binary Tree | Set 3 (Types of Binary Tree) Inorder Tree Traversal without Recursion
[ { "code": null, "e": 25731, "s": 25703, "text": "\n16 Dec, 2021" }, { "code": null, "e": 26003, "s": 25731, "text": "We have seen various methods with different Time Complexities to calculate LCA in n-ary tree:-Method 1 : Naive Method ( by calculating root to node path) | O(n) per query Method 2 :Using Sqrt Decomposition | O(sqrt H) Method 3 : Using Sparse Matrix DP approach | O(logn) " }, { "code": null, "e": 26180, "s": 26003, "text": "Lets study another method that has faster query time than all the above methods. So, our aim will be to calculate LCA in constant time ~ O(1). Let’s see how we can achieve it. " }, { "code": null, "e": 26218, "s": 26180, "text": "Method 4 : Using Range Minimum Query " }, { "code": null, "e": 26336, "s": 26218, "text": "We have discussed LCA and RMQ for binary tree. Here we discuss LCA problem to RMQ problem conversion for n-ary tree. " }, { "code": null, "e": 26422, "s": 26336, "text": "Pre-requisites:- LCA in Binary Tree using RMQ\n RMQ using sparse table" }, { "code": null, "e": 26639, "s": 26422, "text": "Key Concept : In this method, we will be reducing our LCA problem to RMQ(Range Minimum Query) problem over a static array. Once, we do that then we will relate the Range minimum queries to the required LCA queries. " }, { "code": null, "e": 26979, "s": 26639, "text": "The first step will be to decompose the tree into a flat linear array. To do this we can apply the Euler walk. The Euler walk will give the pre-order traversal of the graph. So we will perform a Euler Walk on the tree and store the nodes in an array as we visit them. This process reduces the tree data-structure to a simple linear array. " }, { "code": null, "e": 27033, "s": 26979, "text": "Consider the below tree and the euler walk over it:- " }, { "code": null, "e": 27572, "s": 27033, "text": "Now lets think in general terms : Consider any two nodes on the tree. There will be exactly one path connecting both the nodes and the node that has the smallest depth value in the path will be the LCA of the two given nodes.Now take any two distinct node say u and v in the Euler walk array. Now all the elements in the path from u to v will lie in between the index of nodes u and v in the Euler walk array. Therefore, we just need to calculate the node with the minimum depth between the index of node u and node v in the euler array. " }, { "code": null, "e": 27759, "s": 27572, "text": "For this we will maintain another array that will contain the depth of all the nodes corresponding to their position in the Euler walk array so that we can Apply our RMQ algorithm on it." }, { "code": null, "e": 27831, "s": 27759, "text": "Given below is the euler walk array parallel to its depth track array. " }, { "code": null, "e": 28122, "s": 27831, "text": "Example :- Consider two nodes node 6 and node 7 in the euler array. To calculate the LCA of node 6 and node 7 we look the smallest depth value for all the nodes in between node 6 and node 7 . Therefore, node 1 has the smallest depth value = 0 and hence, it is the LCA for node 6 and node 7." }, { "code": null, "e": 28140, "s": 28122, "text": "Implementation:- " }, { "code": null, "e": 28306, "s": 28140, "text": "We will be maintaining three arrays 1)Euler Path \n 2)Depth array \n 3)First Appearance Index" }, { "code": null, "e": 28365, "s": 28306, "text": "Euler Path and Depth array are the same as described above" }, { "code": null, "e": 28572, "s": 28365, "text": "First Appearance Index FAI[] : The First Appearance index Array will store the index for the first position of every node in the Euler Path array. FAI[i] = First appearance of ith node in Euler Walk array. " }, { "code": null, "e": 28629, "s": 28572, "text": "The Implementation for the above method is given below:-" }, { "code": null, "e": 28633, "s": 28629, "text": "C++" }, { "code": null, "e": 28638, "s": 28633, "text": "Java" }, { "code": "// C++ program to demonstrate LCA of n-ary tree// in constant time.#include \"bits/stdc++.h\"using namespace std;#define sz 101 vector < int > adj[sz]; // stores the treevector < int > euler; // tracks the eulerwalkvector < int > depthArr; // depth for each node corresponding // to eulerwalk int FAI[sz]; // stores first appearance index of every nodeint level[sz]; // stores depth for all nodes in the treeint ptr; // pointer to euler walkint dp[sz][18]; // sparse tableint logn[sz]; // stores log valuesint p2[20]; // stores power of 2 void buildSparseTable(int n){ // initializing sparse table memset(dp,-1,sizeof(dp)); // filling base case values for (int i=1; i<n; i++) dp[i-1][0] = (depthArr[i]>depthArr[i-1])?i-1:i; // dp to fill sparse table for (int l=1; l<15; l++) for (int i=0; i<n; i++) if (dp[i][l-1]!=-1 and dp[i+p2[l-1]][l-1]!=-1) dp[i][l] = (depthArr[dp[i][l-1]]>depthArr[dp[i+p2[l-1]][l-1]])? dp[i+p2[l-1]][l-1] : dp[i][l-1]; else break;} int query(int l,int r){ int d = r-l; int dx = logn[d]; if (l==r) return l; if (depthArr[dp[l][dx]] > depthArr[dp[r-p2[dx]][dx]]) return dp[r-p2[dx]][dx]; else return dp[l][dx];} void preprocess(){ // memorizing powers of 2 p2[0] = 1; for (int i=1; i<18; i++) p2[i] = p2[i-1]*2; // memorizing all log(n) values int val = 1,ptr=0; for (int i=1; i<sz; i++) { logn[i] = ptr-1; if (val==i) { val*=2; logn[i] = ptr; ptr++; } }} /** * Euler Walk ( preorder traversal) * converting tree to linear depthArray * Time Complexity : O(n) * */void dfs(int cur,int prev,int dep){ // marking FAI for cur node if (FAI[cur]==-1) FAI[cur] = ptr; level[cur] = dep; // pushing root to euler walk euler.push_back(cur); // incrementing euler walk pointer ptr++; for (auto x:adj[cur]) { if (x != prev) { dfs(x,cur,dep+1); // pushing cur again in backtrack // of euler walk euler.push_back(cur); // increment euler walk pointer ptr++; } }} // Create Level depthArray corresponding// to the Euler walk Arrayvoid makeArr(){ for (auto x : euler) depthArr.push_back(level[x]);} int LCA(int u,int v){ // trivial case if (u==v) return u; if (FAI[u] > FAI[v]) swap(u,v); // doing RMQ in the required range return euler[query(FAI[u], FAI[v])];} void addEdge(int u,int v){ adj[u].push_back(v); adj[v].push_back(u);} int main(int argc, char const *argv[]){ // constructing the described tree int numberOfNodes = 8; addEdge(1,2); addEdge(1,3); addEdge(2,4); addEdge(2,5); addEdge(2,6); addEdge(3,7); addEdge(3,8); // performing required precalculations preprocess(); // doing the Euler walk ptr = 0; memset(FAI,-1,sizeof(FAI)); dfs(1,0,0); // creating depthArray corresponding to euler[] makeArr(); // building sparse table buildSparseTable(depthArr.size()); cout << \"LCA(6,7) : \" << LCA(6,7) << \"\\n\"; cout << \"LCA(6,4) : \" << LCA(6,4) << \"\\n\"; return 0;}", "e": 31931, "s": 28638, "text": null }, { "code": "// Java program to demonstrate LCA of n-ary// tree in constant time.import java.util.ArrayList;import java.util.Arrays; class GFG{ static int sz = 101; @SuppressWarnings(\"unchecked\")// Stores the treestatic ArrayList<Integer>[] adj = new ArrayList[sz]; // Tracks the eulerwalkstatic ArrayList<Integer> euler = new ArrayList<>(); // Depth for each node correspondingstatic ArrayList<Integer> depthArr = new ArrayList<>();// to eulerwalk // Stores first appearance index of every nodestatic int[] FAI = new int[sz]; // Stores depth for all nodes in the treestatic int[] level = new int[sz]; // Pointer to euler walkstatic int ptr; // Sparse tablestatic int[][] dp = new int[sz][18]; // Stores log valuesstatic int[] logn = new int[sz]; // Stores power of 2static int[] p2 = new int[20]; static void buildSparseTable(int n){ // Initializing sparse table for(int i = 0; i < sz; i++) { for(int j = 0; j < 18; j++) { dp[i][j] = -1; } } // Filling base case values for(int i = 1; i < n; i++) dp[i - 1][0] = (depthArr.get(i) > depthArr.get(i - 1)) ? i - 1 : i; // dp to fill sparse table for(int l = 1; l < 15; l++) for(int i = 0; i < n; i++) if (dp[i][l - 1] != -1 && dp[i + p2[l - 1]][l - 1] != -1) dp[i][l] = (depthArr.get(dp[i][l - 1]) > depthArr.get( dp[i + p2[l - 1]][l - 1])) ? dp[i + p2[l - 1]][l - 1] : dp[i][l - 1]; else break;} static int query(int l, int r){ int d = r - l; int dx = logn[d]; if (l == r) return l; if (depthArr.get(dp[l][dx]) > depthArr.get(dp[r - p2[dx]][dx])) return dp[r - p2[dx]][dx]; else return dp[l][dx];} static void preprocess(){ // Memorizing powers of 2 p2[0] = 1; for(int i = 1; i < 18; i++) p2[i] = p2[i - 1] * 2; // Memorizing all log(n) values int val = 1, ptr = 0; for(int i = 1; i < sz; i++) { logn[i] = ptr - 1; if (val == i) { val *= 2; logn[i] = ptr; ptr++; } }} // Euler Walk ( preorder traversal) converting// tree to linear depthArray// Time Complexity : O(n)static void dfs(int cur, int prev, int dep){ // Marking FAI for cur node if (FAI[cur] == -1) FAI[cur] = ptr; level[cur] = dep; // Pushing root to euler walk euler.add(cur); // Incrementing euler walk pointer ptr++; for(Integer x : adj[cur]) { if (x != prev) { dfs(x, cur, dep + 1); // Pushing cur again in backtrack // of euler walk euler.add(cur); // Increment euler walk pointer ptr++; } }} // Create Level depthArray corresponding// to the Euler walk Arraystatic void makeArr(){ for(Integer x : euler) depthArr.add(level[x]);} static int LCA(int u, int v){ // Trivial case if (u == v) return u; if (FAI[u] > FAI[v]) { int temp = u; u = v; v = temp; } // Doing RMQ in the required range return euler.get(query(FAI[u], FAI[v]));} static void addEdge(int u, int v){ adj[u].add(v); adj[v].add(u);} // Driver codepublic static void main(String[] args){ for(int i = 0; i < sz; i++) { adj[i] = new ArrayList<>(); } // Constructing the described tree int numberOfNodes = 8; addEdge(1, 2); addEdge(1, 3); addEdge(2, 4); addEdge(2, 5); addEdge(2, 6); addEdge(3, 7); addEdge(3, 8); // Performing required precalculations preprocess(); // Doing the Euler walk ptr = 0; Arrays.fill(FAI, -1); dfs(1, 0, 0); // Creating depthArray corresponding to euler[] makeArr(); // Building sparse table buildSparseTable(depthArr.size()); System.out.println(\"LCA(6,7) : \" + LCA(6, 7)); System.out.println(\"LCA(6,4) : \" + LCA(6, 4));}} // This code is contributed by sanjeev2552", "e": 36064, "s": 31931, "text": null }, { "code": null, "e": 36073, "s": 36064, "text": "Output: " }, { "code": null, "e": 36099, "s": 36073, "text": "LCA(6,7) : 1\nLCA(6,4) : 2" }, { "code": null, "e": 36367, "s": 36099, "text": "Note : We are precalculating all the required power of 2’s and also precalculating the all the required log values to ensure constant time complexity per query. Else if we did log calculation for every query operation our Time complexity would have not been constant." }, { "code": null, "e": 36671, "s": 36367, "text": "Time Complexity: The Conversion process from LCA to RMQ is done by Euler Walk that takes O(n) time. Pre-processing for the sparse table in RMQ takes O(nlogn) time and answering each Query is a Constant time process. Therefore, overall Time Complexity is O(nlogn) – preprocessing and O(1) for each query." }, { "code": null, "e": 37092, "s": 36671, "text": "This article is contributed by Nitish Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 37105, "s": 37092, "text": "Akanksha_Rai" }, { "code": null, "e": 37117, "s": 37105, "text": "sanjeev2552" }, { "code": null, "e": 37125, "s": 37117, "text": "clintra" }, { "code": null, "e": 37139, "s": 37125, "text": "sumitgumber28" }, { "code": null, "e": 37151, "s": 37139, "text": "anikakapoor" }, { "code": null, "e": 37171, "s": 37151, "text": "array-range-queries" }, { "code": null, "e": 37182, "s": 37171, "text": "n-ary-tree" }, { "code": null, "e": 37206, "s": 37182, "text": "Advanced Data Structure" }, { "code": null, "e": 37211, "s": 37206, "text": "Tree" }, { "code": null, "e": 37216, "s": 37211, "text": "Tree" }, { "code": null, "e": 37314, "s": 37216, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37343, "s": 37314, "text": "Ordered Set and GNU C++ PBDS" }, { "code": null, "e": 37385, "s": 37343, "text": "2-3 Trees | (Search, Insert and Deletion)" }, { "code": null, "e": 37431, "s": 37385, "text": "Extendible Hashing (Dynamic approach to DBMS)" }, { "code": null, "e": 37467, "s": 37431, "text": "Suffix Array | Set 1 (Introduction)" }, { "code": null, "e": 37477, "s": 37467, "text": "Quad Tree" }, { "code": null, "e": 37527, "s": 37477, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 37562, "s": 37527, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 37596, "s": 37562, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 37639, "s": 37596, "text": "Binary Tree | Set 3 (Types of Binary Tree)" } ]
Find smallest positive number Y such that Bitwise AND of X and Y is Zero - GeeksforGeeks
09 Aug, 2021 Given an integer X. The task is to find the smallest positive number Y(> 0) such that X AND Y is zero.Examples: Input : X = 3 Output : 4 4 is the smallest positive number whose bitwise AND with 3 is zero Input : X = 10 Output : 1 Approach : There are 2 cases : If the binary representation of X contains all 1s, in that case, all the bits of Y should be 0 to make the result of AND operation is zero. Then X+1 is our answer which is the first positive integer. If the binary representation of X doesn’t contain all 1s, in that case, find the first position in X at which bit is 0. Then our answer will be power(2, position) Below is the implementation of the above approach : C++ Java Python3 C# Javascript // C++ program to find smallest number Y for// a given value of X such that X AND Y is zero#include <bits/stdc++.h>#define mod 1000000007using namespace std; // Method to find smallest number Y for// a given value of X such that X AND Y is zeroint findSmallestNonZeroY(int A_num){ // Convert the number into its binary form string A_binary = bitset<8>(A_num).to_string(); int B = 1; int length = A_binary.size(); int no_ones = __builtin_popcount(A_num); // Case 1 : If all bits are ones, // then return the next number if (length == no_ones ) return A_num + 1; // Case 2 : find the first 0-bit // index and return the Y for (int i=0;i<length;i++) { char ch = A_binary[length - i - 1]; if (ch == '0') { B = pow(2.0, i); break; } } return B;} // Driver Codeint main(){ int X = findSmallestNonZeroY(10); cout << X;} // This code is contributed by mohit kumar 29 // Java program to find smallest number Y for// a given value of X such that X AND Y is zeroimport java.lang.*; public class Main { // Method to find smallest number Y for // a given value of X such that X AND Y is zero static long findSmallestNonZeroY(long A_num) { // Convert the number into its binary form String A_binary = Long.toBinaryString(A_num); long B = 1; int len = A_binary.length(); int no_ones = Long.bitCount(A_num); // Case 1 : If all bits are ones, // then return the next number if (len == no_ones) { return A_num + 1; } // Case 2 : find the first 0-bit // index and return the Y for (int i = 0; i < len; i++) { char ch = A_binary.charAt(len - i - 1); if (ch == '0') { B = (long)Math.pow(2.0, (double)i); break; } } return B; } // Driver code public static void main(String[] args) { long X = findSmallestNonZeroY(10); System.out.println(X); }} # Python3 program to find smallest number Y for# a given value of X such that X AND Y is zero # Method to find smallest number Y for# a given value of X such that X AND Y is zerodef findSmallestNonZeroY(A_num) : # Convert the number into its binary form A_binary = bin(A_num) B = 1 length = len(A_binary); no_ones = (A_binary).count('1'); # Case 1 : If all bits are ones, # then return the next number if length == no_ones : return A_num + 1; # Case 2 : find the first 0-bit # index and return the Y for i in range(length) : ch = A_binary[length - i - 1]; if (ch == '0') : B = pow(2.0, i); break; return B; # Driver Codeif __name__ == "__main__" : X = findSmallestNonZeroY(10); print(X) # This code is contributed by AnkitRai01 // C# program to find smallest number Y for// a given value of X such that X AND Y is zerousing System; class GFG{ // Method to find smallest number Y for // a given value of X such that X AND Y is zero static long findSmallestNonZeroY(long A_num) { // Convert the number into its binary form String A_binary = Convert.ToString(A_num, 2); long B = 1; int len = A_binary.Length; int no_ones = bitCount(A_num); // Case 1 : If all bits are ones, // then return the next number if (len == no_ones) { return A_num + 1; } // Case 2 : find the first 0-bit // index and return the Y for (int i = 0; i < len; i++) { char ch = A_binary[len - i - 1]; if (ch == '0') { B = (long)Math.Pow(2.0, (double)i); break; } } return B; } static int bitCount(long x) { // To store the count // of set bits int setBits = 0; while (x != 0) { x = x & (x - 1); setBits++; } return setBits; } // Driver code public static void Main(String[] args) { long X = findSmallestNonZeroY(10); Console.WriteLine(X); }} // This code is contributed by 29AjayKumar <script>// Javascript program to find smallest number Y for// a given value of X such that X AND Y is zero // Method to find smallest number Y for // a given value of X such that X AND Y is zerofunction findSmallestNonZeroY(A_num){ // Convert the number into its binary form let A_binary = (A_num >>> 0).toString(2); let B = 1; let len = A_binary.length; let no_ones = bitCount(A_num); // Case 1 : If all bits are ones, // then return the next number if (len == no_ones) { return A_num + 1; } // Case 2 : find the first 0-bit // index and return the Y for (let i = 0; i < len; i++) { let ch = A_binary[len - i - 1]; if (ch == '0') { B = Math.floor(Math.pow(2.0, i)); break; } } return B;}function bitCount(x){ // To store the count // of set bits let setBits = 0; while (x != 0) { x = x & (x - 1); setBits++; } return setBits;} // Driver codelet X = findSmallestNonZeroY(10);document.write(X); // This code is contributed by unknown2108</script> 1 Time Complexity: O(1)Auxiliary Space: O(1) ankthon 29AjayKumar Akanksha_Rai mohit kumar 29 unknown2108 pankajsharmagfg sumitgumber28 Bitwise-AND Algorithms Mathematical Mathematical Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar How to write a Pseudo Code? Understanding Time Complexity with Simple Examples Introduction to Algorithms 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": 26225, "s": 26197, "text": "\n09 Aug, 2021" }, { "code": null, "e": 26339, "s": 26225, "text": "Given an integer X. The task is to find the smallest positive number Y(> 0) such that X AND Y is zero.Examples: " }, { "code": null, "e": 26459, "s": 26339, "text": "Input : X = 3 Output : 4 4 is the smallest positive number whose bitwise AND with 3 is zero Input : X = 10 Output : 1 " }, { "code": null, "e": 26492, "s": 26459, "text": "Approach : There are 2 cases : " }, { "code": null, "e": 26694, "s": 26492, "text": "If the binary representation of X contains all 1s, in that case, all the bits of Y should be 0 to make the result of AND operation is zero. Then X+1 is our answer which is the first positive integer. " }, { "code": null, "e": 26859, "s": 26694, "text": "If the binary representation of X doesn’t contain all 1s, in that case, find the first position in X at which bit is 0. Then our answer will be power(2, position) " }, { "code": null, "e": 26912, "s": 26859, "text": "Below is the implementation of the above approach : " }, { "code": null, "e": 26916, "s": 26912, "text": "C++" }, { "code": null, "e": 26921, "s": 26916, "text": "Java" }, { "code": null, "e": 26929, "s": 26921, "text": "Python3" }, { "code": null, "e": 26932, "s": 26929, "text": "C#" }, { "code": null, "e": 26943, "s": 26932, "text": "Javascript" }, { "code": "// C++ program to find smallest number Y for// a given value of X such that X AND Y is zero#include <bits/stdc++.h>#define mod 1000000007using namespace std; // Method to find smallest number Y for// a given value of X such that X AND Y is zeroint findSmallestNonZeroY(int A_num){ // Convert the number into its binary form string A_binary = bitset<8>(A_num).to_string(); int B = 1; int length = A_binary.size(); int no_ones = __builtin_popcount(A_num); // Case 1 : If all bits are ones, // then return the next number if (length == no_ones ) return A_num + 1; // Case 2 : find the first 0-bit // index and return the Y for (int i=0;i<length;i++) { char ch = A_binary[length - i - 1]; if (ch == '0') { B = pow(2.0, i); break; } } return B;} // Driver Codeint main(){ int X = findSmallestNonZeroY(10); cout << X;} // This code is contributed by mohit kumar 29", "e": 27939, "s": 26943, "text": null }, { "code": "// Java program to find smallest number Y for// a given value of X such that X AND Y is zeroimport java.lang.*; public class Main { // Method to find smallest number Y for // a given value of X such that X AND Y is zero static long findSmallestNonZeroY(long A_num) { // Convert the number into its binary form String A_binary = Long.toBinaryString(A_num); long B = 1; int len = A_binary.length(); int no_ones = Long.bitCount(A_num); // Case 1 : If all bits are ones, // then return the next number if (len == no_ones) { return A_num + 1; } // Case 2 : find the first 0-bit // index and return the Y for (int i = 0; i < len; i++) { char ch = A_binary.charAt(len - i - 1); if (ch == '0') { B = (long)Math.pow(2.0, (double)i); break; } } return B; } // Driver code public static void main(String[] args) { long X = findSmallestNonZeroY(10); System.out.println(X); }}", "e": 29028, "s": 27939, "text": null }, { "code": "# Python3 program to find smallest number Y for# a given value of X such that X AND Y is zero # Method to find smallest number Y for# a given value of X such that X AND Y is zerodef findSmallestNonZeroY(A_num) : # Convert the number into its binary form A_binary = bin(A_num) B = 1 length = len(A_binary); no_ones = (A_binary).count('1'); # Case 1 : If all bits are ones, # then return the next number if length == no_ones : return A_num + 1; # Case 2 : find the first 0-bit # index and return the Y for i in range(length) : ch = A_binary[length - i - 1]; if (ch == '0') : B = pow(2.0, i); break; return B; # Driver Codeif __name__ == \"__main__\" : X = findSmallestNonZeroY(10); print(X) # This code is contributed by AnkitRai01", "e": 29910, "s": 29028, "text": null }, { "code": "// C# program to find smallest number Y for// a given value of X such that X AND Y is zerousing System; class GFG{ // Method to find smallest number Y for // a given value of X such that X AND Y is zero static long findSmallestNonZeroY(long A_num) { // Convert the number into its binary form String A_binary = Convert.ToString(A_num, 2); long B = 1; int len = A_binary.Length; int no_ones = bitCount(A_num); // Case 1 : If all bits are ones, // then return the next number if (len == no_ones) { return A_num + 1; } // Case 2 : find the first 0-bit // index and return the Y for (int i = 0; i < len; i++) { char ch = A_binary[len - i - 1]; if (ch == '0') { B = (long)Math.Pow(2.0, (double)i); break; } } return B; } static int bitCount(long x) { // To store the count // of set bits int setBits = 0; while (x != 0) { x = x & (x - 1); setBits++; } return setBits; } // Driver code public static void Main(String[] args) { long X = findSmallestNonZeroY(10); Console.WriteLine(X); }} // This code is contributed by 29AjayKumar", "e": 31273, "s": 29910, "text": null }, { "code": "<script>// Javascript program to find smallest number Y for// a given value of X such that X AND Y is zero // Method to find smallest number Y for // a given value of X such that X AND Y is zerofunction findSmallestNonZeroY(A_num){ // Convert the number into its binary form let A_binary = (A_num >>> 0).toString(2); let B = 1; let len = A_binary.length; let no_ones = bitCount(A_num); // Case 1 : If all bits are ones, // then return the next number if (len == no_ones) { return A_num + 1; } // Case 2 : find the first 0-bit // index and return the Y for (let i = 0; i < len; i++) { let ch = A_binary[len - i - 1]; if (ch == '0') { B = Math.floor(Math.pow(2.0, i)); break; } } return B;}function bitCount(x){ // To store the count // of set bits let setBits = 0; while (x != 0) { x = x & (x - 1); setBits++; } return setBits;} // Driver codelet X = findSmallestNonZeroY(10);document.write(X); // This code is contributed by unknown2108</script>", "e": 32464, "s": 31273, "text": null }, { "code": null, "e": 32466, "s": 32464, "text": "1" }, { "code": null, "e": 32511, "s": 32468, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 32519, "s": 32511, "text": "ankthon" }, { "code": null, "e": 32531, "s": 32519, "text": "29AjayKumar" }, { "code": null, "e": 32544, "s": 32531, "text": "Akanksha_Rai" }, { "code": null, "e": 32559, "s": 32544, "text": "mohit kumar 29" }, { "code": null, "e": 32571, "s": 32559, "text": "unknown2108" }, { "code": null, "e": 32587, "s": 32571, "text": "pankajsharmagfg" }, { "code": null, "e": 32601, "s": 32587, "text": "sumitgumber28" }, { "code": null, "e": 32613, "s": 32601, "text": "Bitwise-AND" }, { "code": null, "e": 32624, "s": 32613, "text": "Algorithms" }, { "code": null, "e": 32637, "s": 32624, "text": "Mathematical" }, { "code": null, "e": 32650, "s": 32637, "text": "Mathematical" }, { "code": null, "e": 32661, "s": 32650, "text": "Algorithms" }, { "code": null, "e": 32759, "s": 32661, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32808, "s": 32759, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 32833, "s": 32808, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 32861, "s": 32833, "text": "How to write a Pseudo Code?" }, { "code": null, "e": 32912, "s": 32861, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 32939, "s": 32912, "text": "Introduction to Algorithms" }, { "code": null, "e": 32969, "s": 32939, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 33029, "s": 32969, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 33044, "s": 33029, "text": "C++ Data Types" }, { "code": null, "e": 33087, "s": 33044, "text": "Set in C++ Standard Template Library (STL)" } ]
Compact Strings in Java 9 with Examples - GeeksforGeeks
07 Feb, 2020 Prerequisites: String Compact String is one of the performance enhancements introduced in the JVM as part of JDK 9. Till JDK 8, whenever we create one String object then internally it is represented as char[], which consist the characters of the String object. What is the need of Compact String? Till JDK 8, Java represent String object as char[] because every character in java is of 2 bytes because Java internally uses UTF-16. If any String contains a word in the English language then the character can be represented using a single byte only, we don’t need 2 bytes for each character. Many characters require 2 bytes to represent them but most of the characters require only 1 byte, which falls under LATIN-1 character set. So, there is a scope to improve memory consumption and performance. Java 9 introduced the concept of compact Strings. The main purpose of the compact string is whenever we create a string object and the characters inside the object can be represented using 1 byte, which is nothing but LATIN-1 representation, then internally java will create one byte[]. In other cases, if any character requires more than 1 byte to represent it then each character is stored using 2 bytes i.e. UTF-16 representation. Thats how Java developers changed the internal implementation of String i.e. known as Compact String, which will improve the memory consumption and performance of String. String class internal implementation before Java 9: Java 8 or before import java.io.Serializable; public final class String implements Serializable, Comparable<String>, CharSequence { // The value is used // for character storage. private final char value[];} Note: In the above program, we can see that before Java 9, Java represent String object as a char[] only. Suppose we create one String object and object contains the characters which can be represented using 1 byte. Instead of representing the object as byte[] it will create char[] only, which will consume more memory. JDK developers analyzed that most of the strings can be represented only using Latin-1 characters set. A Latin-1 char can be stored in one byte, which is exactly half of the size of char. This will improve the performance of String. String class internal implementation from Java 9 Java 9 and after import java.io.Serializable; public final class String implements Serializable, Comparable<String>, CharSequence { private final byte[] value; private final byte coder;} Note: Now the question is how will it distinguish between the LATIN-1 and UTF-16 representations? Java developers introduced one final byte variable coder that preserves the information about characters representation. The value of coder value can be: static final byte LATIN1 = 0; static final byte UTF16 = 1; Thus, the new String implementation known as Compact String in Java 9 is better than String before Java 9 in terms of performance because Compact String uses approximately the half area as compared with String in the heap from JDK 9. Let’s see the difference of the memory used by a String object before Java 9 and from Java 9: // Program to illustrate the memory// used by String before Java 9 public class Geeks { public static void main(String[] args) { String s = new String("Geeksforgeeks"); }} Key points to note when we are running on Java 8 or earlier: Here, we created a String object with 13 characters and characters inside the object can be represented using 1 byte, which is nothing but LATIN-1 representation. If we run the above program with JDK version 8 or earlier then As JDK 8 uses UTF-16 as default, Internally String will be represented as char[]. Here we don’t need char[], we can represent each character with 1 byte only. Instead of creating byte[], char[] will be created and for each character, 2 bytes are assigned in the heap memory. This is nothing but wastage of heap memory. // Program to illustrate the memory// used by String from Java 9 public class Geeks { public static void main(String[] args) { String s1 = new String("Geeksforgeeks"); String s2 = new String("Geeksforgeeks€"); }} Key points to note when we are running on Java 9: From Java 9 as per need char[] or byte[] will be created for String objects. Here as we can see we created String object s1 with 13 characters and object s2 with 14 characters. Each character present inside object s1 can be represented using 1 byte only. That’s why for object s1, one byte[] will be created. Now for s2, we have one additional character apart from the characters present in object s1 i.e. €. We cant represent € character using LATIN-1 character set. Here we need 2 bytes to represent €. That’s why here Java will use UTF-16 to present the characters represent inside s2. For object s2, Internally char[] will be created. This is how the new String implementation known as Compact String in Java 9 is better than String before Java 9 in terms of memory consumption and performance. Java-Strings Technical Scripter 2019 Java Technical Scripter Java-Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n07 Feb, 2020" }, { "code": null, "e": 25247, "s": 25225, "text": "Prerequisites: String" }, { "code": null, "e": 25486, "s": 25247, "text": "Compact String is one of the performance enhancements introduced in the JVM as part of JDK 9. Till JDK 8, whenever we create one String object then internally it is represented as char[], which consist the characters of the String object." }, { "code": null, "e": 25522, "s": 25486, "text": "What is the need of Compact String?" }, { "code": null, "e": 25656, "s": 25522, "text": "Till JDK 8, Java represent String object as char[] because every character in java is of 2 bytes because Java internally uses UTF-16." }, { "code": null, "e": 26023, "s": 25656, "text": "If any String contains a word in the English language then the character can be represented using a single byte only, we don’t need 2 bytes for each character. Many characters require 2 bytes to represent them but most of the characters require only 1 byte, which falls under LATIN-1 character set. So, there is a scope to improve memory consumption and performance." }, { "code": null, "e": 26457, "s": 26023, "text": "Java 9 introduced the concept of compact Strings. The main purpose of the compact string is whenever we create a string object and the characters inside the object can be represented using 1 byte, which is nothing but LATIN-1 representation, then internally java will create one byte[]. In other cases, if any character requires more than 1 byte to represent it then each character is stored using 2 bytes i.e. UTF-16 representation." }, { "code": null, "e": 26628, "s": 26457, "text": "Thats how Java developers changed the internal implementation of String i.e. known as Compact String, which will improve the memory consumption and performance of String." }, { "code": null, "e": 26680, "s": 26628, "text": "String class internal implementation before Java 9:" }, { "code": null, "e": 26697, "s": 26680, "text": "Java 8 or before" }, { "code": "import java.io.Serializable; public final class String implements Serializable, Comparable<String>, CharSequence { // The value is used // for character storage. private final char value[];}", "e": 26931, "s": 26697, "text": null }, { "code": null, "e": 27252, "s": 26931, "text": "Note: In the above program, we can see that before Java 9, Java represent String object as a char[] only. Suppose we create one String object and object contains the characters which can be represented using 1 byte. Instead of representing the object as byte[] it will create char[] only, which will consume more memory." }, { "code": null, "e": 27485, "s": 27252, "text": "JDK developers analyzed that most of the strings can be represented only using Latin-1 characters set. A Latin-1 char can be stored in one byte, which is exactly half of the size of char. This will improve the performance of String." }, { "code": null, "e": 27534, "s": 27485, "text": "String class internal implementation from Java 9" }, { "code": null, "e": 27551, "s": 27534, "text": "Java 9 and after" }, { "code": "import java.io.Serializable; public final class String implements Serializable, Comparable<String>, CharSequence { private final byte[] value; private final byte coder;}", "e": 27763, "s": 27551, "text": null }, { "code": null, "e": 28015, "s": 27763, "text": "Note: Now the question is how will it distinguish between the LATIN-1 and UTF-16 representations? Java developers introduced one final byte variable coder that preserves the information about characters representation. The value of coder value can be:" }, { "code": null, "e": 28075, "s": 28015, "text": "static final byte LATIN1 = 0;\nstatic final byte UTF16 = 1;\n" }, { "code": null, "e": 28309, "s": 28075, "text": "Thus, the new String implementation known as Compact String in Java 9 is better than String before Java 9 in terms of performance because Compact String uses approximately the half area as compared with String in the heap from JDK 9." }, { "code": null, "e": 28403, "s": 28309, "text": "Let’s see the difference of the memory used by a String object before Java 9 and from Java 9:" }, { "code": "// Program to illustrate the memory// used by String before Java 9 public class Geeks { public static void main(String[] args) { String s = new String(\"Geeksforgeeks\"); }}", "e": 28603, "s": 28403, "text": null }, { "code": null, "e": 28664, "s": 28603, "text": "Key points to note when we are running on Java 8 or earlier:" }, { "code": null, "e": 28827, "s": 28664, "text": "Here, we created a String object with 13 characters and characters inside the object can be represented using 1 byte, which is nothing but LATIN-1 representation." }, { "code": null, "e": 28972, "s": 28827, "text": "If we run the above program with JDK version 8 or earlier then As JDK 8 uses UTF-16 as default, Internally String will be represented as char[]." }, { "code": null, "e": 29209, "s": 28972, "text": "Here we don’t need char[], we can represent each character with 1 byte only. Instead of creating byte[], char[] will be created and for each character, 2 bytes are assigned in the heap memory. This is nothing but wastage of heap memory." }, { "code": "// Program to illustrate the memory// used by String from Java 9 public class Geeks { public static void main(String[] args) { String s1 = new String(\"Geeksforgeeks\"); String s2 = new String(\"Geeksforgeeks€\"); }}", "e": 29448, "s": 29209, "text": null }, { "code": null, "e": 29498, "s": 29448, "text": "Key points to note when we are running on Java 9:" }, { "code": null, "e": 29675, "s": 29498, "text": "From Java 9 as per need char[] or byte[] will be created for String objects. Here as we can see we created String object s1 with 13 characters and object s2 with 14 characters." }, { "code": null, "e": 29807, "s": 29675, "text": "Each character present inside object s1 can be represented using 1 byte only. That’s why for object s1, one byte[] will be created." }, { "code": null, "e": 30087, "s": 29807, "text": "Now for s2, we have one additional character apart from the characters present in object s1 i.e. €. We cant represent € character using LATIN-1 character set. Here we need 2 bytes to represent €. That’s why here Java will use UTF-16 to present the characters represent inside s2." }, { "code": null, "e": 30137, "s": 30087, "text": "For object s2, Internally char[] will be created." }, { "code": null, "e": 30297, "s": 30137, "text": "This is how the new String implementation known as Compact String in Java 9 is better than String before Java 9 in terms of memory consumption and performance." }, { "code": null, "e": 30310, "s": 30297, "text": "Java-Strings" }, { "code": null, "e": 30334, "s": 30310, "text": "Technical Scripter 2019" }, { "code": null, "e": 30339, "s": 30334, "text": "Java" }, { "code": null, "e": 30358, "s": 30339, "text": "Technical Scripter" }, { "code": null, "e": 30371, "s": 30358, "text": "Java-Strings" }, { "code": null, "e": 30376, "s": 30371, "text": "Java" }, { "code": null, "e": 30474, "s": 30376, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30489, "s": 30474, "text": "Stream In Java" }, { "code": null, "e": 30510, "s": 30489, "text": "Constructors in Java" }, { "code": null, "e": 30529, "s": 30510, "text": "Exceptions in Java" }, { "code": null, "e": 30559, "s": 30529, "text": "Functional Interfaces in Java" }, { "code": null, "e": 30605, "s": 30559, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 30622, "s": 30605, "text": "Generics in Java" }, { "code": null, "e": 30643, "s": 30622, "text": "Introduction to Java" }, { "code": null, "e": 30686, "s": 30643, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 30722, "s": 30686, "text": "Internal Working of HashMap in Java" } ]
JavaScript | Focus() - GeeksforGeeks
01 Apr, 2022 JavaScript focus method is used to give focus to a html element. It sets the element as the active element in the current document. It can be applied to one html element at a single time in a current document. The element can either be a button or a text field or a window etc. It is supported by all the browsers.Syntax: HTMLElementObject.focus() Parameters: It does not accept any parameters.Return Value: This method does not return any value. <html> <head> <script type="text/javascript"> function myFunction() { document.getElementById("focus").focus(); } </script></head> <body> <form action="#"> <br> <br> <label> Hover me: </label> <input type="text" onmousemove=myFunction() id="focus"> <!-- onmousemove is an event which occurs when somenone hovers the mouse on that particular element and calls the function of javascript --> <br> <br> <label>Without Focus: </label> <input type="text"> <br> <br> <input type="button" value="submit"> </form></body></html> Output:Focus field can be removed with the help of blur() method in javascript.Syntax: HTMLElementObject.blur() Parameters: This method does not accept any parameter.Illustration of blur method on clicking a field:Code: <html> <head> <script type="text/javascript"> function setFocus() { document.getElementById("focus").focus(); } function removeFocus() { document.getElementById("focus").blur(); } </script></head> <body> <input type="button" onclick="setFocus()" value="set focus"> <input type="button" onclick="removeFocus()" value="remove focus"> <br> <br> <input type="text" id="focus"></body> </html> Output:After clicking on set focus-After clicking on remove focus- javascript-functions JavaScript-Misc 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 Open URL in New Tab using JavaScript ? Difference Between PUT and PATCH Request How to read a local text file using JavaScript? Node.js | fs.writeFileSync() Method How to Use the JavaScript Fetch API to Get Data? How do you run JavaScript script through the Terminal?
[ { "code": null, "e": 27281, "s": 27253, "text": "\n01 Apr, 2022" }, { "code": null, "e": 27603, "s": 27281, "text": "JavaScript focus method is used to give focus to a html element. It sets the element as the active element in the current document. It can be applied to one html element at a single time in a current document. The element can either be a button or a text field or a window etc. It is supported by all the browsers.Syntax:" }, { "code": null, "e": 27629, "s": 27603, "text": "HTMLElementObject.focus()" }, { "code": null, "e": 27728, "s": 27629, "text": "Parameters: It does not accept any parameters.Return Value: This method does not return any value." }, { "code": "<html> <head> <script type=\"text/javascript\"> function myFunction() { document.getElementById(\"focus\").focus(); } </script></head> <body> <form action=\"#\"> <br> <br> <label> Hover me: </label> <input type=\"text\" onmousemove=myFunction() id=\"focus\"> <!-- onmousemove is an event which occurs when somenone hovers the mouse on that particular element and calls the function of javascript --> <br> <br> <label>Without Focus: </label> <input type=\"text\"> <br> <br> <input type=\"button\" value=\"submit\"> </form></body></html>", "e": 28406, "s": 27728, "text": null }, { "code": null, "e": 28493, "s": 28406, "text": "Output:Focus field can be removed with the help of blur() method in javascript.Syntax:" }, { "code": null, "e": 28518, "s": 28493, "text": "HTMLElementObject.blur()" }, { "code": null, "e": 28626, "s": 28518, "text": "Parameters: This method does not accept any parameter.Illustration of blur method on clicking a field:Code:" }, { "code": "<html> <head> <script type=\"text/javascript\"> function setFocus() { document.getElementById(\"focus\").focus(); } function removeFocus() { document.getElementById(\"focus\").blur(); } </script></head> <body> <input type=\"button\" onclick=\"setFocus()\" value=\"set focus\"> <input type=\"button\" onclick=\"removeFocus()\" value=\"remove focus\"> <br> <br> <input type=\"text\" id=\"focus\"></body> </html>", "e": 29090, "s": 28626, "text": null }, { "code": null, "e": 29157, "s": 29090, "text": "Output:After clicking on set focus-After clicking on remove focus-" }, { "code": null, "e": 29178, "s": 29157, "text": "javascript-functions" }, { "code": null, "e": 29194, "s": 29178, "text": "JavaScript-Misc" }, { "code": null, "e": 29205, "s": 29194, "text": "JavaScript" }, { "code": null, "e": 29303, "s": 29205, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29343, "s": 29303, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29388, "s": 29343, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29449, "s": 29388, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29521, "s": 29449, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 29567, "s": 29521, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 29608, "s": 29567, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29656, "s": 29608, "text": "How to read a local text file using JavaScript?" }, { "code": null, "e": 29692, "s": 29656, "text": "Node.js | fs.writeFileSync() Method" }, { "code": null, "e": 29741, "s": 29692, "text": "How to Use the JavaScript Fetch API to Get Data?" } ]
Inception V2 and V3 - Inception Network Versions - GeeksforGeeks
02 Aug, 2021 Inception V1 (or GoogLeNet) was the state-of-the-art architecture at ILSRVRC 2014. It has produced the record lowest error at ImageNet classification dataset but there are some points on which improvement can be made to improve the accuracy and decrease the complexity of the model. Problems of Inception V1 architecture: Inception V1 have sometimes use convolutions such as 5*5 that causes the input dimensions to decrease by a large margin. This causes the neural network to uses some accuracy decrease. The reason behind that the neural network is susceptible to information loss if the input dimension decreases too drastically. Furthermore, there is also a complexity decrease when we use bigger convolutions like 5×5 as compared to 3×3. We can go further in terms of factorization i.e. that we can divide a 3×3 convolution into an asymmetric convolution of 1×3 then followed by a 3×1 convolution. This is equivalent to sliding a two-layer network with the same receptive field as in a 3×3 convolution but 33% cheaper than 3×3. This factorization does not work well for early layers when input dimensions are big but only when the input size mxm (m is between 12 and 20). According to the Inception V1 architecture, the auxiliary classifier improves the convergence of the network. They argue that it can help reduce the effect of the vanishing gradient problem in the deep networks by pushing the useful gradient to earlier layers (to reduce the loss). But, the authors of this paper found that this classifier didn’t improve the convergence very much early in the training.Architectural Changes in Inception V2: In the Inception V2 architecture. The 5×5 convolution is replaced by the two 3×3 convolutions. This also decreases computational time and thus increases computational speed because a 5×5 convolution is 2.78 more expensive than a 3×3 convolution. So, Using two 3×3 layers instead of 5×5 increases the performance of architecture. Figure 1 This architecture also converts nXn factorization into 1xn and nx1 factorization. As we discussed above that a 3×3 convolution can be converted into 1×3 then followed by 3×1 convolution which is 33% cheaper in terms of computational complexity as compared to 3×3. Figure 2 To deal with the problem of the representational bottleneck, the feature banks of the module were expanded instead of making it deeper. This would prevent the loss of information that causes when we make it deeper. Figure 3 Architectural Changes in Inception V3: Inception V3 is similar to and contains all the features of Inception V2 with following changes/additions: Use of RMSprop optimizer. Batch Normalization in the fully connected layer of Auxiliary classifier. Use of 7×7 factorized Convolution Label Smoothing Regularization: It is a method to regularize the classifier by estimating the effect of label-dropout during training. It prevents the classifier to predict a class too confidently. The addition of label smoothing gives 0.2% improvement from the error rate. Architecture: Below is the layer-by-layer details of Inception V2: Inception V2 architecture The above architecture takes image input of size (299,299,3). Notice in the above architecture figures 5, 6, 7 refers to figure 1, 2, 3 in this article. Implementation: In this section we will look into the implementation of Inception V3. We will using Keras applications API to load the module We are using Cats vs Dogs dataset for this implementation. Code: Importing the required module. python3 import osimport zipfileimport tensorflow as tffrom tensorflow.keras.optimizers import RMSpropfrom tensorflow.keras.preprocessing.image import ImageDataGeneratorfrom tensorflow.keras import layersfrom tensorflow.keras import Modelfrom tensorflow.keras.applications.inception_v3 import InceptionV3from tensorflow.keras.optimizers import RMSprop Code: Creating directories in order to prepare for the dataset python3 local_zip = '/dataset/cats_and_dogs_filtered.zip'zip_ref = zipfile.ZipFile(local_zip, 'r')zip_ref.extractall('/tmp')zip_ref.close() base_dataset_dir = '/tmp/cats_and_dogs_filtered'train_dir = os.path.join(base_dataset_dir, 'train')validation_dir = os.path.join(base_dataset_dir, 'validation') # Directory with our training cat picturestrain_cats = os.path.join(train_dir, 'cats') # Directory with our training dog picturestrain_dogs = os.path.join(train_dir, 'dogs') # Directory with our validation cat picturesvalidation_cats = os.path.join(validation_dir, 'cats') # Directory with our validation dog picturesvalidation_dogs = os.path.join(validation_dir, 'dogs') Code: Storing the dataset in the directories created above and plot some sample images. python3 # Set up matplotlib fig, and size it to fit 4x4 picsimport matplotlib.image as mpimgnrows = 4ncols = 4 fig = plt.gcf()fig.set_size_inches(ncols*4, nrows*4)pic_index = 100train_cat_files = os.listdir( train_cats )train_dog_files = os.listdir( train_dogs ) next_cat_img = [os.path.join(train_cats, fname) for fname in train_cat_files[ pic_index-8:pic_index] ] next_dog_img = [os.path.join(train_dogs, fname) for fname in train_dog_files[ pic_index-8:pic_index] ] for i, img_path in enumerate(next_cat_img+next_dog_img): # Set up subplot; subplot indices start at 1 sp = plt.subplot(nrows, ncols, i + 1) sp.axis('Off') # Don't show axes (or gridlines) img = mpimg.imread(img_path) plt.imshow(img) plt.show() Code: Data augmentation to increase the data samples in dataset. python3 train_datagen = ImageDataGenerator(rescale = 1./255., rotation_range = 50, width_shift_range = 0.2, height_shift_range = 0.2, zoom_range = 0.2, horizontal_flip = True) test_datagen = ImageDataGenerator( rescale = 1.0/255. ) train_generator = train_datagen.flow_from_directory(train_dir, batch_size = 20, class_mode = 'binary', target_size = (150, 150)) validation_generator = test_datagen.flow_from_directory( validation_dir, batch_size = 20, class_mode = 'binary', target_size = (150, 150)) Code: Define the base model using Inception API we imported above and callback function to train the model. python3 base_model = InceptionV3(input_shape = (150, 150, 3), include_top = False, weights = 'imagenet')for layer in base_model.layers: layer.trainable = False #stop training is model accuracy reached 99%class myCallback(tf.keras.callbacks.Callback): def on_epoch_end(self, epoch, logs={}): if(logs.get('acc')>0.99): self.model.stop_training = True In this step, we train our model but before training, we need to change the last layer so that it can predict only one output and use the optimizer function for training. Here we used RMSprop with a learning rate of 0.0001. We also add a dropout 0.2 after the last fully connected layer. After that, we train the model up to 100 epochs. Code: python3 # codex = layers.Flatten()(base_model.output)x = layers.Dense(1024, activation='relu')(x)x = layers.Dropout(0.2)(x) x = layers.Dense (1, activation='sigmoid')(x) model = Model( base_model.input, x) model.compile(optimizer = RMSprop(lr=0.0001),loss = 'binary_crossentropy',metrics = ['acc'])callbacks = myCallback() history = model.fit_generator( train_generator, validation_data = validation_generator, steps_per_epoch = 100, epochs = 100, validation_steps = 50, verbose = 2, callbacks=[callbacks]) Code: Plot the training and validation accuracy along with training and validation loss. python3 acc = history.history['acc']val_acc = history.history['val_acc']loss = history.history['loss']val_loss = history.history['val_loss'] epochs = range(len(acc)) plt.plot(epochs, acc, 'r', label='Training accuracy')plt.plot(epochs, val_acc, 'b', label='Validation accuracy')plt.title('Training and validation accuracy') plt.figure() plt.plot(epochs, loss, 'r', label='Training Loss')plt.plot(epochs, val_loss, 'b', label='Validation Loss')plt.title('Training and validation loss')plt.legend() Results: The best performing Inception V3 architecture reported top-5 error of just 5.6% and top-1 error of 21.2% for a single crop on ILSVRC 2012 classification challenge which is the new state-of-the-art. On multiple crops(144 crops) it reported top-5 and top-1 error rate rate of 4.2% and 18.77% on ILSVRC 2012 classification benchmark. Inception V3 Performance An ensemble of Inception V3 architecture reported a top-5 error rate of 3.46% ILSVRC 2012 validation set (3.58% on ILSVRC 2012 test set). Ensemble Results of Inception V3 References: Rethinking the Inception Architecture for Computer Vision paper akashpunagin Neural Network Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Reinforcement learning Decision Tree Decision Tree Introduction with example Support Vector Machine Algorithm Python | Decision tree implementation ML | Underfitting and Overfitting Search Algorithms in AI Clustering in Machine Learning Intuition of Adam Optimizer
[ { "code": null, "e": 26005, "s": 25977, "text": "\n02 Aug, 2021" }, { "code": null, "e": 27954, "s": 26005, "text": "Inception V1 (or GoogLeNet) was the state-of-the-art architecture at ILSRVRC 2014. It has produced the record lowest error at ImageNet classification dataset but there are some points on which improvement can be made to improve the accuracy and decrease the complexity of the model. Problems of Inception V1 architecture: Inception V1 have sometimes use convolutions such as 5*5 that causes the input dimensions to decrease by a large margin. This causes the neural network to uses some accuracy decrease. The reason behind that the neural network is susceptible to information loss if the input dimension decreases too drastically. Furthermore, there is also a complexity decrease when we use bigger convolutions like 5×5 as compared to 3×3. We can go further in terms of factorization i.e. that we can divide a 3×3 convolution into an asymmetric convolution of 1×3 then followed by a 3×1 convolution. This is equivalent to sliding a two-layer network with the same receptive field as in a 3×3 convolution but 33% cheaper than 3×3. This factorization does not work well for early layers when input dimensions are big but only when the input size mxm (m is between 12 and 20). According to the Inception V1 architecture, the auxiliary classifier improves the convergence of the network. They argue that it can help reduce the effect of the vanishing gradient problem in the deep networks by pushing the useful gradient to earlier layers (to reduce the loss). But, the authors of this paper found that this classifier didn’t improve the convergence very much early in the training.Architectural Changes in Inception V2: In the Inception V2 architecture. The 5×5 convolution is replaced by the two 3×3 convolutions. This also decreases computational time and thus increases computational speed because a 5×5 convolution is 2.78 more expensive than a 3×3 convolution. So, Using two 3×3 layers instead of 5×5 increases the performance of architecture. " }, { "code": null, "e": 27963, "s": 27954, "text": "Figure 1" }, { "code": null, "e": 28228, "s": 27963, "text": "This architecture also converts nXn factorization into 1xn and nx1 factorization. As we discussed above that a 3×3 convolution can be converted into 1×3 then followed by 3×1 convolution which is 33% cheaper in terms of computational complexity as compared to 3×3. " }, { "code": null, "e": 28237, "s": 28228, "text": "Figure 2" }, { "code": null, "e": 28454, "s": 28237, "text": "To deal with the problem of the representational bottleneck, the feature banks of the module were expanded instead of making it deeper. This would prevent the loss of information that causes when we make it deeper. " }, { "code": null, "e": 28463, "s": 28454, "text": "Figure 3" }, { "code": null, "e": 28611, "s": 28463, "text": "Architectural Changes in Inception V3: Inception V3 is similar to and contains all the features of Inception V2 with following changes/additions: " }, { "code": null, "e": 28637, "s": 28611, "text": "Use of RMSprop optimizer." }, { "code": null, "e": 28711, "s": 28637, "text": "Batch Normalization in the fully connected layer of Auxiliary classifier." }, { "code": null, "e": 28745, "s": 28711, "text": "Use of 7×7 factorized Convolution" }, { "code": null, "e": 29019, "s": 28745, "text": "Label Smoothing Regularization: It is a method to regularize the classifier by estimating the effect of label-dropout during training. It prevents the classifier to predict a class too confidently. The addition of label smoothing gives 0.2% improvement from the error rate." }, { "code": null, "e": 29088, "s": 29019, "text": "Architecture: Below is the layer-by-layer details of Inception V2: " }, { "code": null, "e": 29114, "s": 29088, "text": "Inception V2 architecture" }, { "code": null, "e": 29507, "s": 29114, "text": "The above architecture takes image input of size (299,299,3). Notice in the above architecture figures 5, 6, 7 refers to figure 1, 2, 3 in this article. Implementation: In this section we will look into the implementation of Inception V3. We will using Keras applications API to load the module We are using Cats vs Dogs dataset for this implementation. Code: Importing the required module. " }, { "code": null, "e": 29515, "s": 29507, "text": "python3" }, { "code": "import osimport zipfileimport tensorflow as tffrom tensorflow.keras.optimizers import RMSpropfrom tensorflow.keras.preprocessing.image import ImageDataGeneratorfrom tensorflow.keras import layersfrom tensorflow.keras import Modelfrom tensorflow.keras.applications.inception_v3 import InceptionV3from tensorflow.keras.optimizers import RMSprop", "e": 29858, "s": 29515, "text": null }, { "code": null, "e": 29923, "s": 29858, "text": "Code: Creating directories in order to prepare for the dataset " }, { "code": null, "e": 29931, "s": 29923, "text": "python3" }, { "code": "local_zip = '/dataset/cats_and_dogs_filtered.zip'zip_ref = zipfile.ZipFile(local_zip, 'r')zip_ref.extractall('/tmp')zip_ref.close() base_dataset_dir = '/tmp/cats_and_dogs_filtered'train_dir = os.path.join(base_dataset_dir, 'train')validation_dir = os.path.join(base_dataset_dir, 'validation') # Directory with our training cat picturestrain_cats = os.path.join(train_dir, 'cats') # Directory with our training dog picturestrain_dogs = os.path.join(train_dir, 'dogs') # Directory with our validation cat picturesvalidation_cats = os.path.join(validation_dir, 'cats') # Directory with our validation dog picturesvalidation_dogs = os.path.join(validation_dir, 'dogs')", "e": 30596, "s": 29931, "text": null }, { "code": null, "e": 30686, "s": 30596, "text": "Code: Storing the dataset in the directories created above and plot some sample images. " }, { "code": null, "e": 30694, "s": 30686, "text": "python3" }, { "code": "# Set up matplotlib fig, and size it to fit 4x4 picsimport matplotlib.image as mpimgnrows = 4ncols = 4 fig = plt.gcf()fig.set_size_inches(ncols*4, nrows*4)pic_index = 100train_cat_files = os.listdir( train_cats )train_dog_files = os.listdir( train_dogs ) next_cat_img = [os.path.join(train_cats, fname) for fname in train_cat_files[ pic_index-8:pic_index] ] next_dog_img = [os.path.join(train_dogs, fname) for fname in train_dog_files[ pic_index-8:pic_index] ] for i, img_path in enumerate(next_cat_img+next_dog_img): # Set up subplot; subplot indices start at 1 sp = plt.subplot(nrows, ncols, i + 1) sp.axis('Off') # Don't show axes (or gridlines) img = mpimg.imread(img_path) plt.imshow(img) plt.show()", "e": 31464, "s": 30694, "text": null }, { "code": null, "e": 31531, "s": 31464, "text": "Code: Data augmentation to increase the data samples in dataset. " }, { "code": null, "e": 31539, "s": 31531, "text": "python3" }, { "code": "train_datagen = ImageDataGenerator(rescale = 1./255., rotation_range = 50, width_shift_range = 0.2, height_shift_range = 0.2, zoom_range = 0.2, horizontal_flip = True) test_datagen = ImageDataGenerator( rescale = 1.0/255. ) train_generator = train_datagen.flow_from_directory(train_dir, batch_size = 20, class_mode = 'binary', target_size = (150, 150)) validation_generator = test_datagen.flow_from_directory( validation_dir, batch_size = 20, class_mode = 'binary', target_size = (150, 150))", "e": 32532, "s": 31539, "text": null }, { "code": null, "e": 32642, "s": 32532, "text": "Code: Define the base model using Inception API we imported above and callback function to train the model. " }, { "code": null, "e": 32650, "s": 32642, "text": "python3" }, { "code": "base_model = InceptionV3(input_shape = (150, 150, 3), include_top = False, weights = 'imagenet')for layer in base_model.layers: layer.trainable = False #stop training is model accuracy reached 99%class myCallback(tf.keras.callbacks.Callback): def on_epoch_end(self, epoch, logs={}): if(logs.get('acc')>0.99): self.model.stop_training = True", "e": 33063, "s": 32650, "text": null }, { "code": null, "e": 33408, "s": 33063, "text": "In this step, we train our model but before training, we need to change the last layer so that it can predict only one output and use the optimizer function for training. Here we used RMSprop with a learning rate of 0.0001. We also add a dropout 0.2 after the last fully connected layer. After that, we train the model up to 100 epochs. Code: " }, { "code": null, "e": 33416, "s": 33408, "text": "python3" }, { "code": "# codex = layers.Flatten()(base_model.output)x = layers.Dense(1024, activation='relu')(x)x = layers.Dropout(0.2)(x) x = layers.Dense (1, activation='sigmoid')(x) model = Model( base_model.input, x) model.compile(optimizer = RMSprop(lr=0.0001),loss = 'binary_crossentropy',metrics = ['acc'])callbacks = myCallback() history = model.fit_generator( train_generator, validation_data = validation_generator, steps_per_epoch = 100, epochs = 100, validation_steps = 50, verbose = 2, callbacks=[callbacks])", "e": 34019, "s": 33416, "text": null }, { "code": null, "e": 34110, "s": 34019, "text": "Code: Plot the training and validation accuracy along with training and validation loss. " }, { "code": null, "e": 34118, "s": 34110, "text": "python3" }, { "code": "acc = history.history['acc']val_acc = history.history['val_acc']loss = history.history['loss']val_loss = history.history['val_loss'] epochs = range(len(acc)) plt.plot(epochs, acc, 'r', label='Training accuracy')plt.plot(epochs, val_acc, 'b', label='Validation accuracy')plt.title('Training and validation accuracy') plt.figure() plt.plot(epochs, loss, 'r', label='Training Loss')plt.plot(epochs, val_loss, 'b', label='Validation Loss')plt.title('Training and validation loss')plt.legend()", "e": 34607, "s": 34118, "text": null }, { "code": null, "e": 34948, "s": 34607, "text": "Results: The best performing Inception V3 architecture reported top-5 error of just 5.6% and top-1 error of 21.2% for a single crop on ILSVRC 2012 classification challenge which is the new state-of-the-art. On multiple crops(144 crops) it reported top-5 and top-1 error rate rate of 4.2% and 18.77% on ILSVRC 2012 classification benchmark. " }, { "code": null, "e": 34975, "s": 34950, "text": "Inception V3 Performance" }, { "code": null, "e": 35114, "s": 34975, "text": "An ensemble of Inception V3 architecture reported a top-5 error rate of 3.46% ILSVRC 2012 validation set (3.58% on ILSVRC 2012 test set). " }, { "code": null, "e": 35149, "s": 35116, "text": "Ensemble Results of Inception V3" }, { "code": null, "e": 35163, "s": 35149, "text": "References: " }, { "code": null, "e": 35227, "s": 35163, "text": "Rethinking the Inception Architecture for Computer Vision paper" }, { "code": null, "e": 35242, "s": 35229, "text": "akashpunagin" }, { "code": null, "e": 35257, "s": 35242, "text": "Neural Network" }, { "code": null, "e": 35274, "s": 35257, "text": "Machine Learning" }, { "code": null, "e": 35291, "s": 35274, "text": "Machine Learning" }, { "code": null, "e": 35389, "s": 35291, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35412, "s": 35389, "text": "ML | Linear Regression" }, { "code": null, "e": 35435, "s": 35412, "text": "Reinforcement learning" }, { "code": null, "e": 35449, "s": 35435, "text": "Decision Tree" }, { "code": null, "e": 35489, "s": 35449, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 35522, "s": 35489, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 35560, "s": 35522, "text": "Python | Decision tree implementation" }, { "code": null, "e": 35594, "s": 35560, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 35618, "s": 35594, "text": "Search Algorithms in AI" }, { "code": null, "e": 35649, "s": 35618, "text": "Clustering in Machine Learning" } ]
Check if the given string is K-periodic - GeeksforGeeks
02 Aug, 2021 Given a string str and an integer K, the task is to check whether the given string is K-periodic. A string is k-periodic if the string is a repetition of the sub-string str[0 ... k-1] i.e. the string “ababab” is 2-periodic. Print Yes if the given string is k-periodic, else print No. Examples: Input: str = “geeksgeeks”, k = 5 Output: Yes Given string can be generated by repeating the prefix of length k i.e. “geeks” Input: str = “geeksforgeeks”, k = 3 Output: No Approach: Starting with the sub-string str[k, 2k-1], str[2k, 3k-1] and so on, check whether all of these sub-strings are equal to the prefix of the string of length k i.e. str[0, k-1]. If the condition is true for all such sub-strings, then print Yes else print No.Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // CPP implementation of the approach#include<bits/stdc++.h>using namespace std; // Function that return true if sub-string // of length k starting at index i is also // a prefix of the string bool isPrefix(string str, int len, int i, int k) { // k length sub-string cannot start at index i if (i + k > len) return false; for (int j = 0; j < k; j++) { // Character mismatch between the prefix // and the sub-string starting at index i if (str[i] != str[j]) return false; i++; } return true; } // Function that returns true if str is K-periodic bool isKPeriodic(string str, int len, int k) { // Check whether all the sub-strings // str[0, k-1], str[k, 2k-1] ... are equal // to the k length prefix of the string for (int i = k; i < len; i += k) if (!isPrefix(str, len, i, k)) return false; return true; } // Driver code int main() { string str = "geeksgeeks"; int len = str.length(); int k = 5; if (isKPeriodic(str, len, k)) cout << ("Yes"); else cout << ("No"); } // This code is contributed by// Surendra_Gangwar // Java implementation of the approachclass GFG { // Function that return true if sub-string // of length k starting at index i is also // a prefix of the string static boolean isPrefix(String str, int len, int i, int k) { // k length sub-string cannot start at index i if (i + k > len) return false; for (int j = 0; j < k; j++) { // Character mismatch between the prefix // and the sub-string starting at index i if (str.charAt(i) != str.charAt(j)) return false; i++; } return true; } // Function that returns true if str is K-periodic static boolean isKPeriodic(String str, int len, int k) { // Check whether all the sub-strings // str[0, k-1], str[k, 2k-1] ... are equal // to the k length prefix of the string for (int i = k; i < len; i += k) if (!isPrefix(str, len, i, k)) return false; return true; } // Driver code public static void main(String[] args) { String str = "geeksgeeks"; int len = str.length(); int k = 5; if (isKPeriodic(str, len, k)) System.out.print("Yes"); else System.out.print("No"); }} # Python3 implementation of the approach # Function that returns true if sub-string# of length k starting at index i# is also a prefix of the stringdef isPrefix(string, length, i, k): # k length sub-string cannot # start at index i if i + k > length: return False for j in range(0, k): # Character mismatch between the prefix # and the sub-string starting at index i if string[i] != string[j]: return False i += 1 return True # Function that returns true if# str is K-periodicdef isKPeriodic(string, length, k): # Check whether all the sub-strings # str[0, k-1], str[k, 2k-1] ... are equal # to the k length prefix of the string for i in range(k, length, k): if isPrefix(string, length, i, k) == False: return False return True # Driver codeif __name__ == "__main__": string = "geeksgeeks" length = len(string) k = 5 if isKPeriodic(string, length, k) == True: print("Yes") else: print("No") # This code is contributed# by Rituraj Jain // C# implementation of the approachusing System; class GFG{ // Function that return true if sub-string // of length k starting at index i is also // a prefix of the string static bool isPrefix(String str, int len, int i, int k) { // k length sub-string cannot start at index i if (i + k > len) return false; for (int j = 0; j < k; j++) { // Character mismatch between the prefix // and the sub-string starting at index i if (str[i] != str[j]) return false; i++; } return true; } // Function that returns true if str is K-periodic static bool isKPeriodic(String str, int len, int k) { // Check whether all the sub-strings // str[0, k-1], str[k, 2k-1] ... are equal // to the k length prefix of the string for (int i = k; i < len; i += k) if (!isPrefix(str, len, i, k)) return false; return true; } // Driver code public static void Main() { String str = "geeksgeeks"; int len = str.Length; int k = 5; if (isKPeriodic(str, len, k)) Console.Write("Yes"); else Console.Write("No"); }} /* This code contributed by PrinciRaj1992 */ <?php// PHP implementation of the approach // Function that return true if sub-// of length $k starting at index $i// is also a prefix of the stringfunction isPrefix($str, $len, $i, $k){ // $k length sub- cannot start at index $i if ($i + $k > $len) return false; for ( $j = 0; $j < $k; $j++) { // Character mismatch between the prefix // and the sub- starting at index $i if ($str[$i] != $str[$j]) return false; $i++; } return true;} // Function that returns true if $str is K-periodicfunction isKPeriodic($str, $len, $k){ // Check whether all the sub-strings // $str[0, $k-1], $str[$k, 2k-1] ... are equal // to the $k length prefix of the for ($i = $k; $i < $len; $i += $k) if (!isPrefix($str, $len, $i, $k)) return false; return true;} // Driver code$str = "geeksgeeks";$len = strlen($str);$k = 5; if (isKPeriodic($str, $len, $k)) echo ("Yes");else echo ("No"); // This code is contributed by ihritik?> <script> // js implementation of the approach // Function that return true if sub-string// of length k starting at index i is also// a prefix of the stringfunction isPrefix(str, len, i, k){ // k length sub-string cannot start at index i if (i + k > len) return false; for (let j = 0; j < k; j++) { // Character mismatch between the prefix // and the sub-string starting at index i if (str[i] != str[j]) return false; i++; } return true;} // Function that returns true if str is K-periodicfunction isKPeriodic(str, len, k){ // Check whether all the sub-strings // str[0, k-1], str[k, 2k-1] ... are equal // to the k length prefix of the string for (let i = k; i < len; i += k) if (!isPrefix(str, len, i, k)) return false; return true;} // Driver code let str = "geeksgeeks";let len = str.length;let k = 5; if (isKPeriodic(str, len, k)) document.write("Yes");else document.write("No"); </script> Yes Time Complexity: O(K * log(len))Auxiliary Space: O(1) rituraj_jain princiraj1992 SURENDRA_GANGWAR ihritik mohit kumar 29 pankajsharmagfg Constructive Algorithms Marketing substring Algorithms Strings Strings Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar How to Start Learning DSA? Introduction to Algorithms Playfair Cipher with Examples Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Longest Common Subsequence | DP-4
[ { "code": null, "e": 26451, "s": 26423, "text": "\n02 Aug, 2021" }, { "code": null, "e": 26735, "s": 26451, "text": "Given a string str and an integer K, the task is to check whether the given string is K-periodic. A string is k-periodic if the string is a repetition of the sub-string str[0 ... k-1] i.e. the string “ababab” is 2-periodic. Print Yes if the given string is k-periodic, else print No." }, { "code": null, "e": 26747, "s": 26735, "text": "Examples: " }, { "code": null, "e": 26871, "s": 26747, "text": "Input: str = “geeksgeeks”, k = 5 Output: Yes Given string can be generated by repeating the prefix of length k i.e. “geeks”" }, { "code": null, "e": 26920, "s": 26871, "text": "Input: str = “geeksforgeeks”, k = 3 Output: No " }, { "code": null, "e": 27238, "s": 26920, "text": "Approach: Starting with the sub-string str[k, 2k-1], str[2k, 3k-1] and so on, check whether all of these sub-strings are equal to the prefix of the string of length k i.e. str[0, k-1]. If the condition is true for all such sub-strings, then print Yes else print No.Below is the implementation of the above approach: " }, { "code": null, "e": 27242, "s": 27238, "text": "C++" }, { "code": null, "e": 27247, "s": 27242, "text": "Java" }, { "code": null, "e": 27255, "s": 27247, "text": "Python3" }, { "code": null, "e": 27258, "s": 27255, "text": "C#" }, { "code": null, "e": 27262, "s": 27258, "text": "PHP" }, { "code": null, "e": 27273, "s": 27262, "text": "Javascript" }, { "code": "// CPP implementation of the approach#include<bits/stdc++.h>using namespace std; // Function that return true if sub-string // of length k starting at index i is also // a prefix of the string bool isPrefix(string str, int len, int i, int k) { // k length sub-string cannot start at index i if (i + k > len) return false; for (int j = 0; j < k; j++) { // Character mismatch between the prefix // and the sub-string starting at index i if (str[i] != str[j]) return false; i++; } return true; } // Function that returns true if str is K-periodic bool isKPeriodic(string str, int len, int k) { // Check whether all the sub-strings // str[0, k-1], str[k, 2k-1] ... are equal // to the k length prefix of the string for (int i = k; i < len; i += k) if (!isPrefix(str, len, i, k)) return false; return true; } // Driver code int main() { string str = \"geeksgeeks\"; int len = str.length(); int k = 5; if (isKPeriodic(str, len, k)) cout << (\"Yes\"); else cout << (\"No\"); } // This code is contributed by// Surendra_Gangwar", "e": 28556, "s": 27273, "text": null }, { "code": "// Java implementation of the approachclass GFG { // Function that return true if sub-string // of length k starting at index i is also // a prefix of the string static boolean isPrefix(String str, int len, int i, int k) { // k length sub-string cannot start at index i if (i + k > len) return false; for (int j = 0; j < k; j++) { // Character mismatch between the prefix // and the sub-string starting at index i if (str.charAt(i) != str.charAt(j)) return false; i++; } return true; } // Function that returns true if str is K-periodic static boolean isKPeriodic(String str, int len, int k) { // Check whether all the sub-strings // str[0, k-1], str[k, 2k-1] ... are equal // to the k length prefix of the string for (int i = k; i < len; i += k) if (!isPrefix(str, len, i, k)) return false; return true; } // Driver code public static void main(String[] args) { String str = \"geeksgeeks\"; int len = str.length(); int k = 5; if (isKPeriodic(str, len, k)) System.out.print(\"Yes\"); else System.out.print(\"No\"); }}", "e": 29838, "s": 28556, "text": null }, { "code": "# Python3 implementation of the approach # Function that returns true if sub-string# of length k starting at index i# is also a prefix of the stringdef isPrefix(string, length, i, k): # k length sub-string cannot # start at index i if i + k > length: return False for j in range(0, k): # Character mismatch between the prefix # and the sub-string starting at index i if string[i] != string[j]: return False i += 1 return True # Function that returns true if# str is K-periodicdef isKPeriodic(string, length, k): # Check whether all the sub-strings # str[0, k-1], str[k, 2k-1] ... are equal # to the k length prefix of the string for i in range(k, length, k): if isPrefix(string, length, i, k) == False: return False return True # Driver codeif __name__ == \"__main__\": string = \"geeksgeeks\" length = len(string) k = 5 if isKPeriodic(string, length, k) == True: print(\"Yes\") else: print(\"No\") # This code is contributed# by Rituraj Jain", "e": 30935, "s": 29838, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function that return true if sub-string // of length k starting at index i is also // a prefix of the string static bool isPrefix(String str, int len, int i, int k) { // k length sub-string cannot start at index i if (i + k > len) return false; for (int j = 0; j < k; j++) { // Character mismatch between the prefix // and the sub-string starting at index i if (str[i] != str[j]) return false; i++; } return true; } // Function that returns true if str is K-periodic static bool isKPeriodic(String str, int len, int k) { // Check whether all the sub-strings // str[0, k-1], str[k, 2k-1] ... are equal // to the k length prefix of the string for (int i = k; i < len; i += k) if (!isPrefix(str, len, i, k)) return false; return true; } // Driver code public static void Main() { String str = \"geeksgeeks\"; int len = str.Length; int k = 5; if (isKPeriodic(str, len, k)) Console.Write(\"Yes\"); else Console.Write(\"No\"); }} /* This code contributed by PrinciRaj1992 */", "e": 32243, "s": 30935, "text": null }, { "code": "<?php// PHP implementation of the approach // Function that return true if sub-// of length $k starting at index $i// is also a prefix of the stringfunction isPrefix($str, $len, $i, $k){ // $k length sub- cannot start at index $i if ($i + $k > $len) return false; for ( $j = 0; $j < $k; $j++) { // Character mismatch between the prefix // and the sub- starting at index $i if ($str[$i] != $str[$j]) return false; $i++; } return true;} // Function that returns true if $str is K-periodicfunction isKPeriodic($str, $len, $k){ // Check whether all the sub-strings // $str[0, $k-1], $str[$k, 2k-1] ... are equal // to the $k length prefix of the for ($i = $k; $i < $len; $i += $k) if (!isPrefix($str, $len, $i, $k)) return false; return true;} // Driver code$str = \"geeksgeeks\";$len = strlen($str);$k = 5; if (isKPeriodic($str, $len, $k)) echo (\"Yes\");else echo (\"No\"); // This code is contributed by ihritik?>", "e": 33259, "s": 32243, "text": null }, { "code": "<script> // js implementation of the approach // Function that return true if sub-string// of length k starting at index i is also// a prefix of the stringfunction isPrefix(str, len, i, k){ // k length sub-string cannot start at index i if (i + k > len) return false; for (let j = 0; j < k; j++) { // Character mismatch between the prefix // and the sub-string starting at index i if (str[i] != str[j]) return false; i++; } return true;} // Function that returns true if str is K-periodicfunction isKPeriodic(str, len, k){ // Check whether all the sub-strings // str[0, k-1], str[k, 2k-1] ... are equal // to the k length prefix of the string for (let i = k; i < len; i += k) if (!isPrefix(str, len, i, k)) return false; return true;} // Driver code let str = \"geeksgeeks\";let len = str.length;let k = 5; if (isKPeriodic(str, len, k)) document.write(\"Yes\");else document.write(\"No\"); </script>", "e": 34261, "s": 33259, "text": null }, { "code": null, "e": 34265, "s": 34261, "text": "Yes" }, { "code": null, "e": 34321, "s": 34267, "text": "Time Complexity: O(K * log(len))Auxiliary Space: O(1)" }, { "code": null, "e": 34334, "s": 34321, "text": "rituraj_jain" }, { "code": null, "e": 34348, "s": 34334, "text": "princiraj1992" }, { "code": null, "e": 34365, "s": 34348, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 34373, "s": 34365, "text": "ihritik" }, { "code": null, "e": 34388, "s": 34373, "text": "mohit kumar 29" }, { "code": null, "e": 34404, "s": 34388, "text": "pankajsharmagfg" }, { "code": null, "e": 34428, "s": 34404, "text": "Constructive Algorithms" }, { "code": null, "e": 34438, "s": 34428, "text": "Marketing" }, { "code": null, "e": 34448, "s": 34438, "text": "substring" }, { "code": null, "e": 34459, "s": 34448, "text": "Algorithms" }, { "code": null, "e": 34467, "s": 34459, "text": "Strings" }, { "code": null, "e": 34475, "s": 34467, "text": "Strings" }, { "code": null, "e": 34486, "s": 34475, "text": "Algorithms" }, { "code": null, "e": 34584, "s": 34486, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34633, "s": 34584, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 34658, "s": 34633, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 34685, "s": 34658, "text": "How to Start Learning DSA?" }, { "code": null, "e": 34712, "s": 34685, "text": "Introduction to Algorithms" }, { "code": null, "e": 34742, "s": 34712, "text": "Playfair Cipher with Examples" }, { "code": null, "e": 34788, "s": 34742, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 34813, "s": 34788, "text": "Reverse a string in Java" }, { "code": null, "e": 34873, "s": 34813, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 34888, "s": 34873, "text": "C++ Data Types" } ]
Python | Append at front and remove from rear - GeeksforGeeks
31 Dec, 2020 Being familiar with the concept of queue, which follows FIFO rule, i.e first in first out, that suggests a front removal and rear insertion. This has been discussed many times. But sometimes we need to perform the exact opposite of this and we need to perform the append at front and remove element from the rear. Let’s discuss certain ways in which this can be done. Method #1 : Using + operator and list slicingThese operators can be used to perform this particular task. The append operation can be done with the help of + operator and the removal of rear can be done using the conventional list slicing. # Python3 code to demonstrate# append from front and remove from rear# using + operator and list slicing # initializing listtest_list = [4, 5, 7, 3, 10] # printing original list print("The original list : " + str(test_list)) # using + operator and list slicing# append from front and remove from rearres = [13] + test_list[:-1] # printing resultprint("The list after append and removal : " + str(res)) The original list : [4, 5, 7, 3, 10] The list after append and removal : [13, 4, 5, 7, 3] Method #2 : Using collections.deque()The doubly ended queue can be used to perform this particular task in which is supported by python using the collection library, the appendleft and pop methods of queue function can be used to perform this job. # Python3 code to demonstrate# append from front and remove from rear# using collections.dequefrom collections import deque # initializing listtest_list = [4, 5, 7, 3, 10] # printing original list print("The original list : " + str(test_list)) # using collections.deque# append from front and remove from rearres = deque(test_list)res.appendleft(13)res.pop()res = list(res) # printing resultprint("The list after append and removal : " + str(res)) The original list : [4, 5, 7, 3, 10] The list after append and removal : [13, 4, 5, 7, 3] Python DSA-exercises Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() 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": 25761, "s": 25733, "text": "\n31 Dec, 2020" }, { "code": null, "e": 26129, "s": 25761, "text": "Being familiar with the concept of queue, which follows FIFO rule, i.e first in first out, that suggests a front removal and rear insertion. This has been discussed many times. But sometimes we need to perform the exact opposite of this and we need to perform the append at front and remove element from the rear. Let’s discuss certain ways in which this can be done." }, { "code": null, "e": 26369, "s": 26129, "text": "Method #1 : Using + operator and list slicingThese operators can be used to perform this particular task. The append operation can be done with the help of + operator and the removal of rear can be done using the conventional list slicing." }, { "code": "# Python3 code to demonstrate# append from front and remove from rear# using + operator and list slicing # initializing listtest_list = [4, 5, 7, 3, 10] # printing original list print(\"The original list : \" + str(test_list)) # using + operator and list slicing# append from front and remove from rearres = [13] + test_list[:-1] # printing resultprint(\"The list after append and removal : \" + str(res))", "e": 26775, "s": 26369, "text": null }, { "code": null, "e": 26866, "s": 26775, "text": "The original list : [4, 5, 7, 3, 10]\nThe list after append and removal : [13, 4, 5, 7, 3]\n" }, { "code": null, "e": 27116, "s": 26868, "text": "Method #2 : Using collections.deque()The doubly ended queue can be used to perform this particular task in which is supported by python using the collection library, the appendleft and pop methods of queue function can be used to perform this job." }, { "code": "# Python3 code to demonstrate# append from front and remove from rear# using collections.dequefrom collections import deque # initializing listtest_list = [4, 5, 7, 3, 10] # printing original list print(\"The original list : \" + str(test_list)) # using collections.deque# append from front and remove from rearres = deque(test_list)res.appendleft(13)res.pop()res = list(res) # printing resultprint(\"The list after append and removal : \" + str(res))", "e": 27568, "s": 27116, "text": null }, { "code": null, "e": 27659, "s": 27568, "text": "The original list : [4, 5, 7, 3, 10]\nThe list after append and removal : [13, 4, 5, 7, 3]\n" }, { "code": null, "e": 27680, "s": 27659, "text": "Python DSA-exercises" }, { "code": null, "e": 27701, "s": 27680, "text": "Python list-programs" }, { "code": null, "e": 27708, "s": 27701, "text": "Python" }, { "code": null, "e": 27724, "s": 27708, "text": "Python Programs" }, { "code": null, "e": 27822, "s": 27724, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27840, "s": 27822, "text": "Python Dictionary" }, { "code": null, "e": 27875, "s": 27840, "text": "Read a file line by line in Python" }, { "code": null, "e": 27907, "s": 27875, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27949, "s": 27907, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27975, "s": 27949, "text": "Python String | replace()" }, { "code": null, "e": 28018, "s": 27975, "text": "Python program to convert a list to string" }, { "code": null, "e": 28040, "s": 28018, "text": "Defaultdict in Python" }, { "code": null, "e": 28079, "s": 28040, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28125, "s": 28079, "text": "Python | Split string into list of characters" } ]
Python - First K consecutive digits in String - GeeksforGeeks
01 Aug, 2020 Given a String and number K, extract first K consecutive digits making number. Input : test_str = “geeks5geeks43best”, K = 2Output : 43Explanation : 43 is first 2 consecutive digits. Input : test_str = “geeks5gee2ks439best”, K = 3Output : 439Explanation : 439 is first 3 consecutive digits. Method #1 : Using loop This is brute way in which this task can be performed. In this, we run a loop through the list and check if valid N consecutive elements are present for current digit, if yes, we return those N elements. Python3 # Python3 code to demonstrate working of # First K consecutive digits in String# Using loop # initializing stringtest_str = "geeks5geeks43isbest" # printing original stringprint("The original string is : " + str(test_str)) # initializing K K = 2 # using loop to run through characters res = ""for idx in range(len(test_str) - K + 1): is_num = True # check for valid number of consecutives for j in range(K): is_num = is_num & test_str[idx + j].isdigit() # extracting numbers if is_num : res = "" for j in range(K): res += test_str[idx + j] # printing result print("Required character digits : " + str(res)) The original string is : geeks5geeks43isbest Required character digits : 43 Method #2 : Using regex() This is yet another way in which this task can be performed. In this, we apply valid regex expression and after processing, the result is returned as occurrences, the first one is returned. Python3 # Python3 code to demonstrate working of # First K consecutive digits in String# Using regex()import re # initializing stringtest_str = "geeks5geeks43isbest" # printing original stringprint("The original string is : " + str(test_str)) # initializing K K = 2 # using regex() to solve problemtemp = re.search('\d{% s}'% K, test_str)res = (temp.group(0) if temp else '') # printing result print("Required character digits : " + str(res)) The original string is : geeks5geeks43isbest Required character digits : 43 Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 26081, "s": 26053, "text": "\n01 Aug, 2020" }, { "code": null, "e": 26160, "s": 26081, "text": "Given a String and number K, extract first K consecutive digits making number." }, { "code": null, "e": 26264, "s": 26160, "text": "Input : test_str = “geeks5geeks43best”, K = 2Output : 43Explanation : 43 is first 2 consecutive digits." }, { "code": null, "e": 26372, "s": 26264, "text": "Input : test_str = “geeks5gee2ks439best”, K = 3Output : 439Explanation : 439 is first 3 consecutive digits." }, { "code": null, "e": 26395, "s": 26372, "text": "Method #1 : Using loop" }, { "code": null, "e": 26599, "s": 26395, "text": "This is brute way in which this task can be performed. In this, we run a loop through the list and check if valid N consecutive elements are present for current digit, if yes, we return those N elements." }, { "code": null, "e": 26607, "s": 26599, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # First K consecutive digits in String# Using loop # initializing stringtest_str = \"geeks5geeks43isbest\" # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing K K = 2 # using loop to run through characters res = \"\"for idx in range(len(test_str) - K + 1): is_num = True # check for valid number of consecutives for j in range(K): is_num = is_num & test_str[idx + j].isdigit() # extracting numbers if is_num : res = \"\" for j in range(K): res += test_str[idx + j] # printing result print(\"Required character digits : \" + str(res)) ", "e": 27328, "s": 26607, "text": null }, { "code": null, "e": 27405, "s": 27328, "text": "The original string is : geeks5geeks43isbest\nRequired character digits : 43\n" }, { "code": null, "e": 27431, "s": 27405, "text": "Method #2 : Using regex()" }, { "code": null, "e": 27621, "s": 27431, "text": "This is yet another way in which this task can be performed. In this, we apply valid regex expression and after processing, the result is returned as occurrences, the first one is returned." }, { "code": null, "e": 27629, "s": 27621, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # First K consecutive digits in String# Using regex()import re # initializing stringtest_str = \"geeks5geeks43isbest\" # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing K K = 2 # using regex() to solve problemtemp = re.search('\\d{% s}'% K, test_str)res = (temp.group(0) if temp else '') # printing result print(\"Required character digits : \" + str(res)) ", "e": 28070, "s": 27629, "text": null }, { "code": null, "e": 28147, "s": 28070, "text": "The original string is : geeks5geeks43isbest\nRequired character digits : 43\n" }, { "code": null, "e": 28170, "s": 28147, "text": "Python string-programs" }, { "code": null, "e": 28177, "s": 28170, "text": "Python" }, { "code": null, "e": 28193, "s": 28177, "text": "Python Programs" }, { "code": null, "e": 28291, "s": 28193, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28309, "s": 28291, "text": "Python Dictionary" }, { "code": null, "e": 28344, "s": 28309, "text": "Read a file line by line in Python" }, { "code": null, "e": 28376, "s": 28344, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28398, "s": 28376, "text": "Enumerate() in Python" }, { "code": null, "e": 28440, "s": 28398, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28483, "s": 28440, "text": "Python program to convert a list to string" }, { "code": null, "e": 28505, "s": 28483, "text": "Defaultdict in Python" }, { "code": null, "e": 28544, "s": 28505, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28590, "s": 28544, "text": "Python | Split string into list of characters" } ]
Check if a large number is divisibility by 15 - GeeksforGeeks
14 Apr, 2021 Given a very large number. Check its divisibility by 15.Examples: Input: 31 Output: No Input : num = "156457463274623847239840239 402394085458848462385346236 482374823647643742374523747 264723762374620" Output: Yes Given number is divisible by 15 A number is divisible by 15 if it is divisible by 5 (if the last digit is 5 or 0), and it is divisible by 3 (if sum of digits is divisible by 3).Here, used accumulate function to sum up all the numbers. C++ Java Python3 C# PHP Javascript // CPP program to check if a large// number is divisible by 15#include <bits/stdc++.h> using namespace std; // function to check if a large number// is divisible by 15bool isDivisible(string s){ // length of string int n = s.length(); // check divisibility by 5 if (s[n - 1] != '5' and s[n - 1] != '0') return false; // Sum of digits int sum = accumulate(begin(s), end(s), 0) - '0' * n; // if divisible by 3 return (sum % 3 == 0);} // driver programint main(){ string s = "15645746327462384723984023940239"; isDivisible(s)? cout << "Yes\n": cout << "No\n"; string s1 = "15645746327462384723984023940235"; isDivisible(s1)? cout << "Yes\n": cout << "No\n"; return 0;} // Java program to check if a large// number is divisible by 15import java.util.*; class GFG{ // function to check if a large// number is divisible by 15public static boolean isDivisible(String S){ // length of string int n = S.length(); // check divisibility by 5 if (S.charAt(n - 1) != '5' && S.charAt(n - 1) != '0') return false; // Sum of digits int sum = 0; for(int i = 0; i < S.length(); i++) sum += (int)S.charAt(i); // if divisible by 3 if(sum % 3 == 0) return true; else return false;} // Driver codepublic static void main (String[] args){ String S = "15645746327462384723984023940239"; if(isDivisible(S) == true) System.out.println("Yes"); else System.out.println("No"); String S1 = "15645746327462384723984023940235"; if(isDivisible(S1) == true) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed// by Akanksha Rai(Abby_akku) # Python3 program to check if# a large number is# divisible by 15 # to find sumdef accumulate(s): acc = 0; for i in range(len(s)): acc += ord(s[i]) - 48; return acc; # function to check# if a large number# is divisible by 15def isDivisible(s): # length of string n = len(s); # check divisibility by 5 if (s[n - 1] != '5' and s[n - 1] != '0'): return False; # Sum of digits sum = accumulate(s); # if divisible by 3 return (sum % 3 == 0); # Driver Codes = "15645746327462384723984023940239";if isDivisible(s): print("Yes");else: print("No"); s = "15645746327462384723984023940235";if isDivisible(s): print("Yes");else: print("No"); # This code is contributed by mits // C# program to check if a large// number is divisible by 15using System; class GFG{// function to check if a large// number is divisible by 15public static bool isDivisible(String S){ // length of string int n = S.Length; // check divisibility by 5 if (S[n - 1] != '5' && S[n - 1] != '0') return false; // Sum of digits int sum = 0; for(int i = 0; i < S.Length; i++) sum += (int)S[i]; // if divisible by 3 if(sum % 3 == 0) return true; else return false;} // Driver codepublic static void Main(){ String S = "15645746327462384723984023940239"; if(isDivisible(S) == true) Console.WriteLine("Yes"); else Console.WriteLine("No"); String S1 = "15645746327462384723984023940235"; if(isDivisible(S1) == true) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed// by mits <?php// PHP program to check if// a large number is// divisible by 15 // to find sumfunction accumulate($s){ $acc = 0; for($i = 0; $i < strlen($s); $i++) { $acc += $s[$i] - '0'; } return $acc;} // function to check// if a large number// is divisible by 15function isDivisible($s){ // length of string $n = strlen($s); // check divisibility by 5 if ($s[$n - 1] != '5' && $s[$n - 1] != '0') return false; // Sum of digits $sum = accumulate($s); // if divisible by 3 return ($sum % 3 == 0);} // Driver Code$s = "15645746327462384723984023940239";isDivisible($s) ?print("Yes\n") : print("No\n"); $s = "15645746327462384723984023940235";isDivisible($s) ?print("Yes\n") : print("No\n"); // This code is contributed by mits?> <script>// Javascript program to check if// a large number is// divisible by 15// to find sum function accumulate(s){ let acc = 0; for(let i = 0; i < s.length; i++) { acc += s[i] - '0'; } return acc;} // function to check// if a large number// is divisible by 15function isDivisible(s){ // length of string let n = s.length; // check divisibility by 5 if (s[n - 1] != '5' && s[n - 1] != '0') return false; // Sum of digits let sum = accumulate(s); // if divisible by 3 return (sum % 3 == 0);} // Driver Codelet s = "15645746327462384723984023940239";isDivisible(s) ?document.write("Yes<br>") : document.write("No<br>"); s = "15645746327462384723984023940235";isDivisible(s) ?document.write("Yes<br>") : document.write("No<br>"); // This code is contributed by _saurabh_jaiswal</script> Output: No Yes Time complexity: O(number of digits)This article is contributed by Striver. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Mithun Kumar Akanksha_Rai _saurabh_jaiswal divisibility large-numbers Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Segment Tree | Set 1 (Sum of given range) Modular multiplicative inverse Count all possible paths from top left to bottom right of a mXn matrix Fizz Buzz Implementation Check if a number is Palindrome Program to multiply two matrices Merge two sorted arrays with O(1) extra space Generate all permutation of a set in Python Count ways to reach the n'th stair
[ { "code": null, "e": 25961, "s": 25933, "text": "\n14 Apr, 2021" }, { "code": null, "e": 26029, "s": 25961, "text": "Given a very large number. Check its divisibility by 15.Examples: " }, { "code": null, "e": 26256, "s": 26029, "text": "Input: 31\nOutput: No\n\nInput : num = \"156457463274623847239840239\n 402394085458848462385346236\n 482374823647643742374523747\n 264723762374620\"\nOutput: Yes\nGiven number is divisible by 15" }, { "code": null, "e": 26463, "s": 26258, "text": "A number is divisible by 15 if it is divisible by 5 (if the last digit is 5 or 0), and it is divisible by 3 (if sum of digits is divisible by 3).Here, used accumulate function to sum up all the numbers. " }, { "code": null, "e": 26467, "s": 26463, "text": "C++" }, { "code": null, "e": 26472, "s": 26467, "text": "Java" }, { "code": null, "e": 26480, "s": 26472, "text": "Python3" }, { "code": null, "e": 26483, "s": 26480, "text": "C#" }, { "code": null, "e": 26487, "s": 26483, "text": "PHP" }, { "code": null, "e": 26498, "s": 26487, "text": "Javascript" }, { "code": "// CPP program to check if a large// number is divisible by 15#include <bits/stdc++.h> using namespace std; // function to check if a large number// is divisible by 15bool isDivisible(string s){ // length of string int n = s.length(); // check divisibility by 5 if (s[n - 1] != '5' and s[n - 1] != '0') return false; // Sum of digits int sum = accumulate(begin(s), end(s), 0) - '0' * n; // if divisible by 3 return (sum % 3 == 0);} // driver programint main(){ string s = \"15645746327462384723984023940239\"; isDivisible(s)? cout << \"Yes\\n\": cout << \"No\\n\"; string s1 = \"15645746327462384723984023940235\"; isDivisible(s1)? cout << \"Yes\\n\": cout << \"No\\n\"; return 0;}", "e": 27213, "s": 26498, "text": null }, { "code": "// Java program to check if a large// number is divisible by 15import java.util.*; class GFG{ // function to check if a large// number is divisible by 15public static boolean isDivisible(String S){ // length of string int n = S.length(); // check divisibility by 5 if (S.charAt(n - 1) != '5' && S.charAt(n - 1) != '0') return false; // Sum of digits int sum = 0; for(int i = 0; i < S.length(); i++) sum += (int)S.charAt(i); // if divisible by 3 if(sum % 3 == 0) return true; else return false;} // Driver codepublic static void main (String[] args){ String S = \"15645746327462384723984023940239\"; if(isDivisible(S) == true) System.out.println(\"Yes\"); else System.out.println(\"No\"); String S1 = \"15645746327462384723984023940235\"; if(isDivisible(S1) == true) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 28272, "s": 27213, "text": null }, { "code": "# Python3 program to check if# a large number is# divisible by 15 # to find sumdef accumulate(s): acc = 0; for i in range(len(s)): acc += ord(s[i]) - 48; return acc; # function to check# if a large number# is divisible by 15def isDivisible(s): # length of string n = len(s); # check divisibility by 5 if (s[n - 1] != '5' and s[n - 1] != '0'): return False; # Sum of digits sum = accumulate(s); # if divisible by 3 return (sum % 3 == 0); # Driver Codes = \"15645746327462384723984023940239\";if isDivisible(s): print(\"Yes\");else: print(\"No\"); s = \"15645746327462384723984023940235\";if isDivisible(s): print(\"Yes\");else: print(\"No\"); # This code is contributed by mits", "e": 29004, "s": 28272, "text": null }, { "code": "// C# program to check if a large// number is divisible by 15using System; class GFG{// function to check if a large// number is divisible by 15public static bool isDivisible(String S){ // length of string int n = S.Length; // check divisibility by 5 if (S[n - 1] != '5' && S[n - 1] != '0') return false; // Sum of digits int sum = 0; for(int i = 0; i < S.Length; i++) sum += (int)S[i]; // if divisible by 3 if(sum % 3 == 0) return true; else return false;} // Driver codepublic static void Main(){ String S = \"15645746327462384723984023940239\"; if(isDivisible(S) == true) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); String S1 = \"15645746327462384723984023940235\"; if(isDivisible(S1) == true) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed// by mits", "e": 29984, "s": 29004, "text": null }, { "code": "<?php// PHP program to check if// a large number is// divisible by 15 // to find sumfunction accumulate($s){ $acc = 0; for($i = 0; $i < strlen($s); $i++) { $acc += $s[$i] - '0'; } return $acc;} // function to check// if a large number// is divisible by 15function isDivisible($s){ // length of string $n = strlen($s); // check divisibility by 5 if ($s[$n - 1] != '5' && $s[$n - 1] != '0') return false; // Sum of digits $sum = accumulate($s); // if divisible by 3 return ($sum % 3 == 0);} // Driver Code$s = \"15645746327462384723984023940239\";isDivisible($s) ?print(\"Yes\\n\") : print(\"No\\n\"); $s = \"15645746327462384723984023940235\";isDivisible($s) ?print(\"Yes\\n\") : print(\"No\\n\"); // This code is contributed by mits?>", "e": 30777, "s": 29984, "text": null }, { "code": "<script>// Javascript program to check if// a large number is// divisible by 15// to find sum function accumulate(s){ let acc = 0; for(let i = 0; i < s.length; i++) { acc += s[i] - '0'; } return acc;} // function to check// if a large number// is divisible by 15function isDivisible(s){ // length of string let n = s.length; // check divisibility by 5 if (s[n - 1] != '5' && s[n - 1] != '0') return false; // Sum of digits let sum = accumulate(s); // if divisible by 3 return (sum % 3 == 0);} // Driver Codelet s = \"15645746327462384723984023940239\";isDivisible(s) ?document.write(\"Yes<br>\") : document.write(\"No<br>\"); s = \"15645746327462384723984023940235\";isDivisible(s) ?document.write(\"Yes<br>\") : document.write(\"No<br>\"); // This code is contributed by _saurabh_jaiswal</script>", "e": 31638, "s": 30777, "text": null }, { "code": null, "e": 31648, "s": 31638, "text": "Output: " }, { "code": null, "e": 31655, "s": 31648, "text": "No\nYes" }, { "code": null, "e": 32111, "s": 31655, "text": "Time complexity: O(number of digits)This article is contributed by Striver. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 32124, "s": 32111, "text": "Mithun Kumar" }, { "code": null, "e": 32137, "s": 32124, "text": "Akanksha_Rai" }, { "code": null, "e": 32154, "s": 32137, "text": "_saurabh_jaiswal" }, { "code": null, "e": 32167, "s": 32154, "text": "divisibility" }, { "code": null, "e": 32181, "s": 32167, "text": "large-numbers" }, { "code": null, "e": 32194, "s": 32181, "text": "Mathematical" }, { "code": null, "e": 32207, "s": 32194, "text": "Mathematical" }, { "code": null, "e": 32305, "s": 32207, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32349, "s": 32305, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 32391, "s": 32349, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 32422, "s": 32391, "text": "Modular multiplicative inverse" }, { "code": null, "e": 32493, "s": 32422, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 32518, "s": 32493, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 32550, "s": 32518, "text": "Check if a number is Palindrome" }, { "code": null, "e": 32583, "s": 32550, "text": "Program to multiply two matrices" }, { "code": null, "e": 32629, "s": 32583, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 32673, "s": 32629, "text": "Generate all permutation of a set in Python" } ]
Tcl-Tk - Quick Guide
Tcl is shortened form of Tool Command Language. John Ousterhout of the University of California, Berkeley, designed it. It is a combination of a scripting language and its own interpreter that gets embedded to the application, we develop with it. Tcl was developed initially for Unix. It was then ported to Windows, DOS, OS/2, and Mac OSX. Tcl is much similar to other unix shell languages like Bourne Shell (Sh), the C Shell (csh), the Korn Shell (sh), and Perl. It aims at providing ability for programs to interact with other programs and also for acting as an embeddable interpreter. Even though, the original aim was to enable programs to interact, you can find full-fledged applications written in Tcl/Tk. The features of Tcl are as follows − Reduced development time. Reduced development time. Powerful and simple user interface kit with integration of TK. Powerful and simple user interface kit with integration of TK. Write once, run anywhere. It runs on Windows, Mac OS X, and almost on every Unix platform. Write once, run anywhere. It runs on Windows, Mac OS X, and almost on every Unix platform. Quite easy to get started for experienced programmers; since, the language is so simple that they can learn Tcl in a few hours or days. Quite easy to get started for experienced programmers; since, the language is so simple that they can learn Tcl in a few hours or days. You can easily extend existing applications with Tcl. Also, it is possible to include Tcl in C, C++, or Java to Tcl or vice versa. You can easily extend existing applications with Tcl. Also, it is possible to include Tcl in C, C++, or Java to Tcl or vice versa. Have a powerful set of networking functions. Have a powerful set of networking functions. Finally, it's an open source, free, and can be used for commercial applications without any limit. Finally, it's an open source, free, and can be used for commercial applications without any limit. Tcl is a general-purpose language and you can find Tcl everywhere. It includes, Scalable websites that are often backed by databases. High performance web servers build with TclHttpd. Tcl with CGI based websites. Desktop GUI applications. Embedded applications. If you are willing to set up your environment for Tcl, you need the following two software applications available on your computer − Text Editor Tcl Interpreter. This will be used to type your program. Examples of a few text editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi. Name and version of a text editor can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on windows as well as Linux or UNIX. The files you create with your text editor are called source files and contain program source code. The source files for Tcl programs are named with the extension ".tcl". Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, build it, and finally execute it. It is just a small program that enables you to type Tcl commands and have them executed line by line. It stops execution of a tcl file, in case, it encounters an error unlike a compiler that executes fully. Let's have a helloWorld.tcl file as follows. We will use this as a first program, we run on a platform you choose. #!/usr/bin/tclsh puts "Hello World!" Download the latest version for windows installer from the list of Active Tcl binaries available. The active Tcl community edition is free for personal use. Run the downloaded executable to install the Tcl, which can be done by following the on screen instructions. Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using 'cd' command and then execute the program using the following steps C:\Tcl> tclsh helloWorld.tcl We can see the following output. C:\Tcl> helloWorld C:\Tcl is the folder, I am using to save my samples. You can change it to the folder in which you have saved Tcl programs. Most of the Linux operating systems come with Tcl inbuilt and you can get started right away in those systems. In case, it's not available, you can use the following command to download and install Tcl-Tk. $ yum install tcl tk Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using 'cd' command and then execute the program using the following steps − $ tclsh helloWorld.tcl We can see the following output − $ hello world In case, it's not available in your OS, you can use the following command to download and install Tcl-Tk − $ sudo apt-get install tcl tk Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using 'cd' command and then execute the program using the following steps − $ tclsh helloWorld.tcl We can see the following output − $ hello world Download the latest version for Mac OS X package from the list of Active Tcl binaries available. The active Tcl community edition is free for personal use. Run the downloaded executable to install the Active Tcl, which can be done by following the on screen instructions. Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using 'cd' and then execute the program using the following steps − $ tclsh helloWorld.tcl We can see the following output − $ hello world You can use the option of installing from source files when a binary package is not available. It is generally preferred to use Tcl binaries for Windows and Mac OS X, so only compilation of sources on unix based system is shown below. Download the source files. Download the source files. Now, use the following commands to extract, compile, and build after switching to the downloaded folder. Now, use the following commands to extract, compile, and build after switching to the downloaded folder. $ tar zxf tcl8.6.1-src.tar.gz $ cd tcl8.6.1 $ cd unix $ ./configure —prefix=/opt —enable-gcc $ make $ sudo make install Note − Make sure, you change the file name to the version you downloaded on commands 1 and 2 given above. In Tcl, we classify some of the variables as special variables and they have a predefined usage/functionality. The list of specials variables is listed below. argc Refers to a number of command-line arguments. argv Refers to the list containing the command-line arguments. argv0 Refers to the file name of the file being interpreted or the name by which we invoke the script. env Used for representing the array of elements that are environmental variables. errorCode Provides the error code for last Tcl error. errorInfo Provides the stack trace for last Tcl error. tcl_interactive Used to switch between interactive and non-interactive modes by setting this to 1 and 0 respectively. tcl_library Used for setting the location of standard Tcl libraries. tcl_pkgPath Provides the list of directories where packages are generally installed. tcl_patchLevel Refers to the current patch level of the Tcl interpreter. tcl_platform Used for representing the array of elements with objects including byteOrder, machine, osVersion, platform, and os. tcl_precision Refers to the precision i.e. number of digits to retain when converting to floating-point numbers to strings. The default value is 12. tcl_prompt1 Refers to the primary prompt. tcl_prompt2 Refers to the secondary prompt with invalid commands. tcl_rcFileName Provides the user specific startup file. tcl_traceCompile Used for controlling the tracing of bytecode compilation. Use 0 for no output, 1 for summary, and 2 for detailed. tcl_traceExec Used for controlling the tracing of bytecode execution. Use 0 for no output, 1 for summary, and 2 for detailed. tcl_version Returns the current version of the Tcl interpreter. The above special variables have their special meanings for the Tcl interpreter. Let's see some examples for special variables. #!/usr/bin/tclsh puts $tcl_version When you run the program, you will get a similar output as shown below − 8.6 #!/usr/bin/tclsh puts $env(PATH) When you run the program, you will get a similar output as shown below − /home/cg/root/GNUstep/Tools:/usr/GNUstep/Local/Tools:/usr/GNUstep/ System/Tools:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/webmaster/.local/bin:/ home/webmaster/bin:/usr/local/scriba/bin:/usr/local/smlnj/ bin:/usr/local/bin/std:/usr/local/bin/extra:/usr/local/fantom/bin:/usr/ local/dart/bin:/usr/bin:/usr/local/bin:/usr/local/sbin:/usr/sbin:/opt/mono/ bin:/opt/mono/lib/mono/4.5:/usr/local/bin:.:/usr/libexec/sdcc:/usr/local/ icon-v950/bin:/usr/local/mozart/bin:/opt/Pawn/bin:/opt/jdk1.7.0_75/bin:/ opt/jdk1.7.0_75/jre/bin:/opt/pash/Source/PashConsole/bin/Debug/ #!/usr/bin/tclsh puts $tcl_pkgPath When you run the program, you will get a similar output as shown below − /usr/lib64/tcl8.6 /usr/share/tcl8.6 /usr/lib64/tk8.6 /usr/share/tk8.6 #!/usr/bin/tclsh puts $tcl_library When you run the program, you will get a similar output as shown below − /usr/share/tcl8.6 #!/usr/bin/tclsh puts $tcl_patchLevel When you run the program, you will get a similar output as shown below − 8.6.6 #!/usr/bin/tclsh puts $tcl_precision When you run the program, you will get a similar output as shown below − 0 #!/usr/bin/tclsh puts $tcl_rcFileName When you run the program, you will get a similar output as shown below − ~/.tclshrc Tcl is quite simple to learn and let's start creating our first Tcl program! Let us write a simple Tcl program. All Tcl files will have an extension, i.e., .tcl. So, put the following source code in a test.tcl file. #!/usr/bin/tclsh puts "Hello, World!" Assuming, Tcl environment is setup correctly; let's run the program after switching to file's directory and then execute the program using − $ tclsh test.tcl We will get the following output − Hello, World! Let us now see the basic structure of Tcl program, so that it will be easy for you to understand basic building blocks of the Tcl language. In Tcl, we use new line or semicolon to terminate the previous line of code. But semicolon is not necessary, if you are using newline for each command. Comments are like helping text in your Tcl program and the interpreter ignores them. Comments can be written using a hash_(#) sign in the beginning. #!/usr/bin/tclsh # my first program in Tcl puts "Hello World!" When the above code is executed, it produces the following result − Hello World! Multiline or block comment is written using 'if' with condition '0'. An example is shown below. #!/usr/bin/tclsh if 0 { my first program in Tcl program Its very simple } puts "Hello World!" When the above code is executed, it produces the following result − Hello World! Inline comments use ;#. An example is given below. #!/usr/bin/tclsh puts "Hello World!" ;# my first print in Tcl program When the above code is executed, it produces the following result − Hello World! A Tcl identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores, dollars ($) , and digits (0 to 9). Tcl does not allow punctuation characters such as @, and % within identifiers. Tcl is a case sensitive_ language. Thus Manpower and manpower are two different identifiers in Tcl. Here are some of the examples of acceptable identifiers − mohd zara abc move_name a_123 myname50 _temp j a23b9 retVal A line containing only whitespace, possibly with a comment, is known as a blank line, and a Tcl interpreter totally ignores it. Whitespace is the term used in Tcl to describe blanks, tabs, newline characters, and comments. Whitespace separates one part of a statement from another and enables the interpreter to identify where one element in a statement, such as puts, ends and the next element begins. Therefore, in the following statement − #!/usr/bin/tclsh puts "Hello World!" There must be at least one whitespace character (usually a space) between “puts” and "Hello World!" for the interpreter to be able to distinguish them. On the other hand, in the following statement − #!/usr/bin/tclsh puts [expr 3 + 2] ;# print sum of the 3 and 2 When the above code is executed, it produces the following result − 5 No whitespace characters are necessary between 3 and +, or between + and 2; although, you are free to include some if you wish for the readability purpose. As you know, Tcl is a Tool command language, commands are the most vital part of the language. Tcl commands are built in-to the language with each having its own predefined function. These commands form the reserved words of the language and cannot be used for other variable naming. The advantage with these Tcl commands is that, you can define your own implementation for any of these commands to replace the original built-in functionality. Each of the Tcl commands validates the input and it reduces the work of the interpreter. Tcl command is actually a list of words, with the first word representing the command to be executed. The next words represent the arguments. In order to group the words into a single argument, we enclose multiple words with "" or {}. The syntax of Tcl command is as follows − commandName argument1 argument2 ... argumentN Let's see a simple example of Tcl command − #!/usr/bin/tclsh puts "Hello, world!" When the above code is executed, it produces the following result − Hello, world! In the above code, ‘puts’ is the Tcl command and "Hello World" is the argument1. As said before, we have used "" to group two words. Let's see another example of Tcl command with two arguments − #!/usr/bin/tclsh puts stdout "Hello, world!" When the above code is executed, it produces the following result − Hello, world! In the above code, ‘puts’ is the Tcl command, ‘stdout’ is argument1, and "Hello World" is argument2. Here, stdout makes the program to print in the standard output device. In command substitutions, square brackets are used to evaluate the scripts inside the square brackets. A simple example to add two numbers is shown below − #!/usr/bin/tclsh puts [expr 1 + 6 + 9] When the above code is executed, it produces following result − 16 In variable substitutions, $ is used before the variable name and this returns the contents of the variable. A simple example to set a value to a variable and print it is shown below. #!/usr/bin/tclsh set a 3 puts $a When the above code is executed, it produces the following result − 3 These are commonly called escape sequences; with each backslash, followed by a letter having its own meaning. A simple example for newline substitution is shown below − #!/usr/bin/tclsh puts "Hello\nWorld" When the above code is executed, it produces the following result − Hello World The primitive data-type of Tcl is string and often we can find quotes on Tcl as string only language. These primitive data-types in turn create composite data-types for list and associative array. In Tcl, data-types can represent not only the simple Tcl objects, but also can represent complex objects such as handles, graphic objects (mostly widgets), and I/O channels. Let's look into the details about each of the above. In Tcl, whether it is an integer number, boolean, floating point number, or a string. When you want to use a variable, you can directly assign a value to it, there is no step of declaration in Tcl. There can be internal representations for these different types of objects. It can transform one data-type to another when required. The syntax for assigning value to variable is as follows − #!/usr/bin/tclsh set myVariable 18 puts $myVariable When the above code is executed, it produces the following result − 18 The above statement will create a variable name myVariable and stores it as a string even though, we have not used double quotations. Now, if we try to make an arithmetic on the variable, it is automatically turned to an integer. A simple example is shown below − #!/usr/bin/tclsh set myVariable 18 puts [expr $myVariable + 6 + 9] When the above code is executed, it produces the following result − 33 One important thing to note is that, these variables don't have any default values and must be assigned value before they are used. If we try to print using puts, the number is transformed into proper string. Having two representations, internal and external, help Tcl to create complex data structures easily compared to other languages. Also, Tcl is more efficient due to its dynamic object nature. Unlike other languages, in Tcl, you need not include double quotes when it's only a single word. An example can be − #!/usr/bin/tclsh set myVariable hello puts $myVariable When the above code is executed, it produces the following result − hello When we want to represent multiple strings, we can use either double quotes or curly braces. It is shown below − #!/usr/bin/tclsh set myVariable "hello world" puts $myVariable set myVariable {hello world} puts $myVariable When the above code is executed, it produces the following result − hello world hello world List is nothing but a group of elements. A group of words either using double quotes or curly braces can be used to represent a simple list. A simple list is shown below − #!/usr/bin/tclsh set myVariable {red green blue} puts [lindex $myVariable 2] set myVariable "red green blue" puts [lindex $myVariable 1] When the above code is executed, it produces the following result − blue green Associative arrays have an index (key) that is not necessarily an integer. It is generally a string that acts like key value pairs. A simple example is shown below − #!/usr/bin/tclsh set marks(english) 80 puts $marks(english) set marks(mathematics) 90 puts $marks(mathematics) When the above code is executed, it produces the following result − 80 90 Tcl handles are commonly used to represent files and graphics objects. These can include handles to network requests and also other channels like serial port communication, sockets, or I/O devices. The following is an example where a file handle is created. set myfile [open "filename" r] You will see more detail on files in the Tcl file I/O chapter. In Tcl, there is no concept of variable declaration. Once, a new variable name is encountered, Tcl will define a new variable. The name of variables can contain any characters and length. You can even have white spaces by enclosing the variable in curly braces, but it is not preferred. The set command is used for assigning value to a variable. The syntax for set command is, set variableName value A few examples of variables are shown below − #!/usr/bin/tclsh set variableA 10 set {variable B} test puts $variableA puts ${variable B} When the above code is executed, it produces the following result − 10 test As you can see in the above program, the $variableName is used to get the value of the variable. Tcl is a dynamically typed language. The value of the variable can be dynamically converted to the required type when required. For example, a number 5 that is stored as string will be converted to number when doing an arithmetic operation. It is shown below − #!/usr/bin/tclsh set variableA "10" puts $variableA set sum [expr $variableA +20]; puts $sum When the above code is executed, it produces the following result − 10 30 As you can see in the above example, expr is used for representing mathematical expression. The default precision of Tcl is 12 digits. In order to get floating point results, we should add at least a single decimal digit. A simple example explains the above. #!/usr/bin/tclsh set variableA "10" set result [expr $variableA / 9]; puts $result set result [expr $variableA / 9.0]; puts $result set variableA "10.0" set result [expr $variableA / 9]; puts $result When the above code is executed, it produces the following result − 1 1.1111111111111112 1.1111111111111112 In the above example, you can see three cases. In the first case, the dividend and the divisor are whole numbers and we get a whole number as result. In the second case, the divisor alone is a decimal number and in the third case, the dividend is a decimal number. In both second and third cases, we get a decimal number as result. In the above code, you can change the precision by using tcl_precision special variable. It is shown below − #!/usr/bin/tclsh set variableA "10" set tcl_precision 5 set result [expr $variableA / 9.0]; puts $result When the above code is executed, it produces the following result − 1.1111 An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Tcl language is rich in built-in operators and provides the following types of operators − Arithmetic Operators Relational Operators Logical Operators Bitwise Operators Ternary Operator This chapter will explain the arithmetic, relational, logical, bitwise, and ternary operators one by one. Following table shows all the arithmetic operators supported by Tcl language. Assume variable ‘A’ holds 10 and variable ‘B’ holds 20, then − Show Examples Following table shows all the relational operators supported by Tcl language. Assume variable A holds 10 and variable B holds 20, then − Show Examples Following table shows all the logical operators supported by Tcl language. Assume variable A holds 1 and variable B holds 0, then − Show Examples Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows − Assume if A = 60; and B = 13; now in binary format they will be as follows − A = 0011 1100 B = 0000 1101 ---------------------- A&B = 0000 1100 A|B = 0011 1101 A^B = 0011 0001 The Bitwise operators supported by Tcl language are listed in the following table. Assume variable A holds 60 and variable B holds 13, then − Show Examples Show Examples Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator. For example : x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3 * 2 and then adds into 7. Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first. Show Examples Decision making structures require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Following is the general form of a typical decision making structure found in most of the programming languages − Tcl language uses the expr command internally and hence it’s not required for us to use expr statement explicitly. Tcl language provides following types of decision making statements − An 'if' statement consists of a Boolean expression followed by one or more statements. An 'if' statement can be followed by an optional 'else' statement, which executes when the Boolean expression is false. You can use one 'if' or 'else if' statement inside another 'if' or 'else if' statement(s). A switch statement allows a variable to be tested for equality against a list of values. You can use one switch statement inside another switch statement(s). We have covered conditional operator ? : in previous chapter, which can be used to replace if...else statements. It has the following general form − Exp1 ? Exp2 : Exp3; Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon. The value of a '? expression' is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire '? expression.' If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression. An example is shown below. #!/usr/bin/tclsh set a 10; set b [expr $a == 1 ? 20: 30] puts "Value of b is $b\n" set b [expr $a == 10 ? 20: 30] puts "Value of b is $b\n" When you compile and execute the above program, it produces the following result − Value of b is 30 Value of b is 20 There may be a situation, where you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages − Tcl language provides the following types of loops to handle looping requirements. Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. You can use one or more loop inside any another while, for or do..while loop. Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Tcl supports the following control statements. Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch. Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. A loop becomes infinite loop if a condition never becomes false. The while loop is traditionally used for this purpose. You can make an endless loop by leaving the conditional expression as 1. while {1} { puts "This loop will run forever." } When the conditional expression is absent, it is assumed to be true. Tcl programmers more commonly use the while {1} construct to signify an infinite loop. NOTE − You can terminate an infinite loop by pressing Ctrl + C keys. An array is a systematic arrangement of a group of elements using indices. The syntax for the conventional array is shown below. set ArrayName(Index) value An example for creating simple array is shown below. #!/usr/bin/tclsh set languages(0) Tcl set languages(1) "C Language" puts $languages(0) puts $languages(1) When the above code is executed, it produces the following result − Tcl C Language The syntax for calculating size array is shown below. [array size variablename] An example for printing the size is shown below. #!/usr/bin/tclsh set languages(0) Tcl set languages(1) "C Language" puts [array size languages] When the above code is executed, it produces the following result − 2 Though, array indices can be non-continuous like values specified for index 1 then index 10 and so on. But, in case they are continuous, we can use array iteration to access elements of the array. A simple array iteration for printing elements of the array is shown below. #!/usr/bin/tclsh set languages(0) Tcl set languages(1) "C Language" for { set index 0 } { $index < [array size languages] } { incr index } { puts "languages($index) : $languages($index)" } When the above code is executed, it produces the following result − languages(0) : Tcl languages(1) : C Language In Tcl, all arrays by nature are associative. Arrays are stored and retrieved without any specific order. Associative arrays have an index that is not necessarily a number, and can be sparsely populated. A simple example for associative array with non-number indices is shown below. #!/usr/bin/tclsh set personA(Name) "Dave" set personA(Age) 14 puts $personA(Name) puts $personA(Age) When the above code is executed, it produces the following result − Dave 14 The syntax for retrieving indices of array is shown below. [array names variablename] An example for printing the size is shown below. #!/usr/bin/tclsh set personA(Name) "Dave" set personA(Age) 14 puts [array names personA] When the above code is executed, it produces the following result − Age Name You can use the indices of array to iterate through the associative array. An example is shown below. #!/usr/bin/tclsh set personA(Name) "Dave" set personA(Age) 14 foreach index [array names personA] { puts "personA($index): $personA($index)" } When the above code is executed, it produces the following result − personA(Age): 14 personA(Name): Dave The primitive data-type of Tcl is string and often we can find quotes on Tcl as string only language. These strings can contain alphanumeric character, just numbers, Boolean, or even binary data. Tcl uses 16 bit unicode characters and alphanumeric characters can contain letters including non-Latin characters, number or punctuation. Boolean value can be represented as 1, yes or true for true and 0, no, or false for false. Unlike other languages, in Tcl, you need not include double quotes when it's only a single word. An example can be − #!/usr/bin/tclsh set myVariable hello puts $myVariable When the above code is executed, it produces the following result − hello When we want to represent multiple strings, we can use either double quotes or curly braces. It is shown below − #!/usr/bin/tclsh set myVariable "hello world" puts $myVariable set myVariable {hello world} puts $myVariable When the above code is executed, it produces the following result − hello world hello world A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal character (e.g., '\u02C0'). There are certain characters in Tcl when they are preceded by a backslash they will have special meaning and they are used to represent like newline (\n) or tab (\t). Here, you have a list of some of such escape sequence codes − Following is the example to show a few escape sequence characters − #!/usr/bin/tclsh puts "Hello\tWorld\n\nTutorialspoint"; When the above code is compiled and executed, it produces the following result − Hello World Tutorialspoint The list of subcommands for string command is listed in the following table − compare string1 string2 Compares string1 and string2 lexographically. Returns 0 if equal, -1 if string1 comes before string2, else 1. first string1 string2 Returns the index first occurrence of string1 in string2. If not found, returns -1. index string index Returns the character at index. last string1 string2 Returns the index last occurrence of string1 in string2. If not found, returns -1. length string Returns the length of string. match pattern string Returns 1 if the string matches the pattern. range string index1 index2 Return the range of characters in string from index1 to index2. tolower string Returns the lowercase string. toupper string Returns the uppercase string. trim string ?trimcharacters? Removes trimcharacters in both ends of string. The default trimcharacters is whitespace. trimleft string ?trimcharacters? Removes trimcharacters in left beginning of string. The default trimcharacters is whitespace. trimright string ?trimcharacters? Removes trimcharacters in left end of string. The default trimcharacters is whitespace. wordend findstring index Return the index in findstring of the character after the word containing the character at index. wordstart findstring index Return the index in findstring of the first character in the word containing the character at index. Examples of some commonly used Tcl string sub commands are given below. #!/usr/bin/tclsh set s1 "Hello" set s2 "World" set s3 "World" puts [string compare $s1 $s2] if {[string compare $s2 $s3] == 0} { puts "String \'s1\' and \'s2\' are same."; } if {[string compare $s1 $s2] == -1} { puts "String \'s1\' comes before \'s2\'."; } if {[string compare $s2 $s1] == 1} { puts "String \'s2\' comes after \'s1\'."; } When the above code is compiled and executed, it produces the following result − -1 String 's1' and 's2' are same. String 's1' comes before 's2'. String 's2' comes after 's1'. #!/usr/bin/tclsh set s1 "Hello World" set s2 "o" puts "First occurrence of $s2 in s1" puts [string first $s2 $s1] puts "Character at index 0 in s1" puts [string index $s1 0] puts "Last occurrence of $s2 in s1" puts [string last $s2 $s1] puts "Word end index in s1" puts [string wordend $s1 20] puts "Word start index in s1" puts [string wordstart $s1 20] When the above code is compiled and executed, it produces the following result − First occurrence of o in s1 4 Character at index 0 in s1 H Last occurrence of o in s1 7 Word end index in s1 11 Word start index in s1 6 #!/usr/bin/tclsh set s1 "Hello World" puts "Length of string s1" puts [string length $s1] When the above code is compiled and executed, it produces the following result − Length of string s1 11 #!/usr/bin/tclsh set s1 "Hello World" puts "Uppercase string of s1" puts [string toupper $s1] puts "Lowercase string of s1" puts [string tolower $s1] When the above code is compiled and executed, it produces the following result − Uppercase string of s1 HELLO WORLD Lowercase string of s1 hello world #!/usr/bin/tclsh set s1 "Hello World" set s2 "World" puts "Trim right $s2 in $s1" puts [string trimright $s1 $s2] set s2 "Hello" puts "Trim left $s2 in $s1" puts [string trimleft $s1 $s2] set s1 " Hello World " set s2 " " puts "Trim characters s1 on both sides of s2" puts [string trim $s1 $s2] When the above code is compiled and executed, it produces the following result − Trim right World in Hello World Hello Trim left Hello in Hello World World Trim characters s1 on both sides of s2 Hello World #!/usr/bin/tclsh set s1 "test@test.com" set s2 "*@*.com" puts "Matching pattern s2 in s1" puts [string match "*@*.com" $s1 ] puts "Matching pattern tcl in s1" puts [string match {tcl} $s1] When the above code is compiled and executed, it produces the following result − Matching pattern s2 in s1 1 Matching pattern tcl in s1 0 #!/usr/bin/tclsh set s1 "Hello" append s1 " World" puts $s1 When the above code is compiled and executed, it produces the following result − Hello World The following table shows the list of format specifiers available in Tcl − Some simple examples are given below − #!/usr/bin/tclsh puts [format "%f" 43.5] puts [format "%e" 43.5] puts [format "%d %s" 4 tuts] puts [format "%s" "Tcl Language"] puts [format "%x" 40] When the above code is compiled and executed, it produces the following result − 43.500000 4.350000e+01 4 tuts Tcl Language 28 Scan command is used for parsing a string based to the format specifier. Some examples are shown below. #!/usr/bin/tclsh puts [scan "90" {%[0-9]} m] puts [scan "abc" {%[a-z]} m] puts [scan "abc" {%[A-Z]} m] puts [scan "ABC" {%[A-Z]} m] When the above code is compiled and executed, it produces the following result − 1 1 0 1 List is one of the basic data-type available in Tcl. It is used for representing an ordered collection of items. It can include different types of items in the same list. Further, a list can contain another list. An important thing that needs to be noted is that these lists are represented as strings completely and processed to form individual items when required. So, avoid large lists and in such cases; use array. The general syntax for list is given below − set listName { item1 item2 item3 .. itemn } # or set listName [list item1 item2 item3] # or set listName [split "items separated by a character" split_character] Some examples are given below − #!/usr/bin/tclsh set colorList1 {red green blue} set colorList2 [list red green blue] set colorList3 [split "red_green_blue" _] puts $colorList1 puts $colorList2 puts $colorList3 When the above code is executed, it produces the following result − red green blue red green blue red green blue The syntax for appending item to a list is given below − append listName split_character value # or lappend listName value Some examples are given below − #!/usr/bin/tclsh set var orange append var " " "blue" lappend var "red" lappend var "green" puts $var When the above code is executed, it produces the following result − orange blue red green The syntax for length of list is given below − llength listName Example for length of list is given below − #!/usr/bin/tclsh set var {orange blue red green} puts [llength $var] When the above code is executed, it produces the following result − 4 The syntax for selecting list item at specific index is given below − lindex listname index Example for list item at index is given below − #!/usr/bin/tclsh set var {orange blue red green} puts [lindex $var 1] When the above code is executed, it produces the following result − blue The syntax for inserting list items at specific index is given below. linsert listname index value1 value2..valuen Example for inserting list item at specific index is given below. #!/usr/bin/tclsh set var {orange blue red green} set var [linsert $var 3 black white] puts $var When the above code is executed, it produces the following result − orange blue red black white green The syntax for replacing list items at specific indices is given below − lreplace listname firstindex lastindex value1 value2..valuen Example for replacing list items at specific indices is given below. #!/usr/bin/tclsh set var {orange blue red green} set var [lreplace $var 2 3 black white] puts $var When the above code is executed, it produces the following result − orange blue black white The syntax for setting list item at specific index is given below − lset listname index value Example for setting list item at specific index is given below − #!/usr/bin/tclsh set var {orange blue red green} lset var 0 black puts $var When the above code is executed, it produces the following result − black blue red green The syntax for copying values to variables is given below − lassign listname variable1 variable2.. variablen Example for transforming list into variables is given below − #!/usr/bin/tclsh set var {orange blue red green} lassign $var colour1 colour2 puts $colour1 puts $colour2 When the above code is executed, it produces the following result − orange blue The syntax for sorting a list is given below − lsort listname An example for sorting a list is given below − #!/usr/bin/tclsh set var {orange blue red green} set var [lsort $var] puts $var When the above code is executed, it produces the following result − blue green orange red A dictionary is an arrangement for mapping values to keys. The syntax for the conventional dictionary is shown below − dict set dictname key value # or dict create dictname key1 value1 key2 value2 .. keyn valuen Some examples for creating a dictionary are shown below − #!/usr/bin/tclsh dict set colours colour1 red puts $colours dict set colours colour2 green puts $colours set colours [dict create colour1 "black" colour2 "white"] puts $colours When the above code is executed, it produces the following result − colour1 red colour1 red colour2 green colour1 black colour2 white The syntax for getting size of dict is shown below − [dict size dictname] An example for printing the size is shown below − #!/usr/bin/tclsh set colours [dict create colour1 "black" colour2 "white"] puts [dict size $colours] When the above code is executed, it produces the following result − 2 A simple dictionary iteration for printing keys and valued of the dictionary is shown below − #!/usr/bin/tclsh set colours [dict create colour1 "black" colour2 "white"] foreach item [dict keys $colours] { set value [dict get $colours $item] puts $value } When the above code is executed, it produces the following result − black white The syntax for retrieving value for key in dict is shown below − [dict get $dictname $keyname] An example for retrieving value for key is given below − #!/usr/bin/tclsh set colours [dict create colour1 "black" colour2 "white"] set value [dict get $colours colour1] puts $value When the above code is executed, it produces the following result − black The syntax for retrieving all keys in dict is shown below − [dict keys $dictname] An example for printing all keys is shown below − #!/usr/bin/tclsh set colours [dict create colour1 "black" colour2 "white"] set keys [dict keys $colours] puts $keys When the above code is executed, it produces the following result − colour1 colour2 The syntax for retrieving all values in dict is shown below − [dict values $dictname] An example for printing all values is shown below − #!/usr/bin/tclsh set colours [dict create colour1 "black" colour2 "white"] set values [dict values $colours] puts $values When the above code is executed, it produces the following result − black white The syntax for checking if a key exists in dict is shown below − [dict exists $dictname $key] An example for checking if a key exists in dict is shown below − #!/usr/bin/tclsh set colours [dict create colour1 "black" colour2 "white"] set result [dict exists $colours colour1] puts $result When the above code is executed, it produces the following result − 1 Procedures are nothing but code blocks with series of commands that provide a specific reusable functionality. It is used to avoid same code being repeated in multiple locations. Procedures are equivalent to the functions used in many programming languages and are made available in Tcl with the help of proc command. The syntax of creating a simple procedure is shown below − proc procedureName {arguments} { body } A simple example for procedure is given below − #!/usr/bin/tclsh proc helloWorld {} { puts "Hello, World!" } helloWorld When the above code is executed, it produces the following result − Hello, World! An example for procedure with arguments is shown below − #!/usr/bin/tclsh proc add {a b} { return [expr $a+$b] } puts [add 10 30] When the above code is executed, it produces the following result − 40 An example for procedure with arguments is shown below − #!/usr/bin/tclsh proc avg {numbers} { set sum 0 foreach number $numbers { set sum [expr $sum + $number] } set average [expr $sum/[llength $numbers]] return $average } puts [avg {70 80 50 60}] puts [avg {70 80 50 }] When the above code is executed, it produces the following result − 65 66 Default arguments are used to provide default values that can be used if no value is provided. An example for procedure with default arguments, which is sometimes referred as implicit arguments is shown below − #!/usr/bin/tclsh proc add {a {b 100} } { return [expr $a+$b] } puts [add 10 30] puts [add 10] When the above code is executed, it produces the following result − 40 110 An example for recursive procedures is shown below − #!/usr/bin/tclsh proc factorial {number} { if {$number <= 1} { return 1 } return [expr $number * [factorial [expr $number - 1]]] } puts [factorial 3] puts [factorial 5] When the above code is executed, it produces the following result − 6 120 Packages are used for creating reusable units of code. A package consists of a collection of files that provide specific functionality. This collection of files is identified by a package name and can have multiple versions of same files. The package can be a collection of Tcl scripts, binary library, or a combination of both. Package uses the concept of namespace to avoid collision of variable names and procedure names. Check out more in our next 'namespace' tutorial. A package can be created with the help of minimum two files. One file contains the package code. Other file contains the index package file for declaring your package. The list of steps for creating and using package is given below. Create code for package inside a folder say HelloWorld. Let the file be named HelloWorld.tcl with the code as shown below − # /Users/rajkumar/Desktop/helloworld/HelloWorld.tcl # Create the namespace namespace eval ::HelloWorld { # Export MyProcedure namespace export MyProcedure # My Variables set version 1.0 set MyDescription "HelloWorld" # Variable for the path of the script variable home [file join [pwd] [file dirname [info script]]] } # Definition of the procedure MyProcedure proc ::HelloWorld::MyProcedure {} { puts $HelloWorld::MyDescription } package provide HelloWorld $HelloWorld::version package require Tcl 8.0 Open tclsh. Switch to HelloWorld directory and use the pkg_mkIndex command to create the index file as shown below − % cd /Users/rajkumar/Desktop/helloworld % pkg_mkIndex . *.tcl Use the lappend command to add the package to the global list as shown below − % lappend auto_path "/Users/rajkumar/Desktop/helloworld" Next add package to program using package require statement as shown below − % package require HelloWorld 1.0 Now, everything being setup, we can invoke our procedure as shown below − % puts [HelloWorld::MyProcedure] You will get the following result − HelloWorld First two steps create the package. Once package is created, you can use it in any Tcl file by adding the last three statements as shown below − lappend auto_path "/Users/rajkumar/Desktop/helloworld" package require HelloWorld 1.0 puts [HelloWorld::MyProcedure] You will get the following result − HelloWorld Namespace is a container for set of identifiers that is used to group variables and procedures. Namespaces are available from Tcl version 8.0. Before the introduction of the namespaces, there was single global scope. Now with namespaces, we have additional partitions of global scope. Namespaces are created using the namespace command. A simple example for creating namespace is shown below − #!/usr/bin/tclsh namespace eval MyMath { # Create a variable inside the namespace variable myResult } # Create procedures inside the namespace proc MyMath::Add {a b } { set ::MyMath::myResult [expr $a + $b] } MyMath::Add 10 23 puts $::MyMath::myResult When the above code is executed, it produces the following result − 33 In the above program, you can see there is a namespace with a variable myResult and a procedure Add. This makes it possible to create variables and procedures with the same names under different namespaces. Tcl allows nesting of namespaces. A simple example for nesting namespaces is given below − #!/usr/bin/tclsh namespace eval MyMath { # Create a variable inside the namespace variable myResult } namespace eval extendedMath { # Create a variable inside the namespace namespace eval MyMath { # Create a variable inside the namespace variable myResult } } set ::MyMath::myResult "test1" puts $::MyMath::myResult set ::extendedMath::MyMath::myResult "test2" puts $::extendedMath::MyMath::myResult When the above code is executed, it produces the following result − test1 test2 You can see in the previous namespace examples, we use a lot of scope resolution operator and it's more complex to use. We can avoid this by importing and exporting namespaces. An example is given below − #!/usr/bin/tclsh namespace eval MyMath { # Create a variable inside the namespace variable myResult namespace export Add } # Create procedures inside the namespace proc MyMath::Add {a b } { return [expr $a + $b] } namespace import MyMath::* puts [Add 10 30] When the above code is executed, it produces the following result − 40 You can remove an imported namespace by using forget subcommand. A simple example is shown below − #!/usr/bin/tclsh namespace eval MyMath { # Create a variable inside the namespace variable myResult namespace export Add } # Create procedures inside the namespace proc MyMath::Add {a b } { return [expr $a + $b] } namespace import MyMath::* puts [Add 10 30] namespace forget MyMath::* When the above code is executed, it produces the following result − 40 Tcl supports file handling with the help of the built in commands open, read, puts, gets, and close. A file represents a sequence of bytes, does not matter if it is a text file or binary file. Tcl uses the open command to open files in Tcl. The syntax for opening a file is as follows − open fileName accessMode Here, filename is string literal, which you will use to name your file and accessMode can have one of the following values − r Opens an existing text file for reading purpose and the file must exist. This is the default mode used when no accessMode is specified. w Opens a text file for writing, if it does not exist, then a new file is created else existing file is truncated. a Opens a text file for writing in appending mode and file must exist. Here, your program will start appending content in the existing file content. r+ Opens a text file for reading and writing both. File must exist already. w+ Opens a text file for reading and writing both. It first truncate the file to zero length if it exists otherwise create the file if it does not exist. a+ Opens a text file for reading and writing both. It creates the file if it does not exist. The reading will start from the beginning, but writing can only be appended. To close a file, use the close command. The syntax for close is as follows − close fileName Any file that has been opened by a program must be closed when the program finishes using that file. In most cases, the files need not be closed explicitly; they are closed automatically when File objects are terminated automatically. Puts command is used to write to an open file. puts $filename "text to write" A simple example for writing to a file is shown below. #!/usr/bin/tclsh set fp [open "input.txt" w+] puts $fp "test" close $fp When the above code is compiled and executed, it creates a new file input.txt in the directory that it has been started under (in the program's working directory). Following is the simple command to read from a file − set file_data [read $fp] A complete example of read and write is shown below − #!/usr/bin/tclsh set fp [open "input.txt" w+] puts $fp "test" close $fp set fp [open "input.txt" r] set file_data [read $fp] puts $file_data close $fp When the above code is compiled and executed, it reads the file created in previous section and produces the following result − test Here is another example for reading file till end of file line by line − #!/usr/bin/tclsh set fp [open "input.txt" w+] puts $fp "test\ntest" close $fp set fp [open "input.txt" r] while { [gets $fp data] >= 0 } { puts $data } close $fp When the above code is compiled and executed, it reads the file created in previous section and produces the following result − test test Error handling in Tcl is provided with the help of error and catch commands. The syntax for each of these commands is shown below. error message info code In the above error command syntax, message is the error message, info is set in the global variable errorInfo and code is set in the global variable errorCode. catch script resultVarName In the above catch command syntax, script is the code to be executed, resultVarName is variable that holds the error or the result. The catch command returns 0 if there is no error, and 1 if there is an error. An example for simple error handling is shown below − #!/usr/bin/tclsh proc Div {a b} { if {$b == 0} { error "Error generated by error" "Info String for error" 401 } else { return [expr $a/$b] } } if {[catch {puts "Result = [Div 10 0]"} errmsg]} { puts "ErrorMsg: $errmsg" puts "ErrorCode: $errorCode" puts "ErrorInfo:\n$errorInfo\n" } if {[catch {puts "Result = [Div 10 2]"} errmsg]} { puts "ErrorMsg: $errmsg" puts "ErrorCode: $errorCode" puts "ErrorInfo:\n$errorInfo\n" } When the above code is executed, it produces the following result − ErrorMsg: Error generated by error ErrorCode: 401 ErrorInfo: Info String for error (procedure "Div" line 1) invoked from within "Div 10 0" Result = 5 As you can see in the above example, we can create our own custom error messages. Similarly, it is possible to catch the error generated by Tcl. An example is shown below − #!/usr/bin/tclsh catch {set file [open myNonexistingfile.txt]} result puts "ErrorMsg: $result" puts "ErrorCode: $errorCode" puts "ErrorInfo:\n$errorInfo\n" When the above code is executed, it produces the following result − ErrorMsg: couldn't open "myNonexistingfile.txt": no such file or directory ErrorCode: POSIX ENOENT {no such file or directory} ErrorInfo: couldn't open "myNonexistingfile.txt": no such file or directory while executing "open myNonexistingfile.txt" Tcl provides a number of built-in functions (procedures) for various operations. This includes − Functions for list handling. Functions for list handling. Functions for string handling. Functions for string handling. Functions for array handling. Functions for array handling. Functions for dictionary handling. Functions for dictionary handling. Functions for File I/O handling. Functions for File I/O handling. Functions for creating namespaces and packages. Functions for creating namespaces and packages. Functions for Math operations. Functions for Math operations. Functions for System operations. Functions for System operations. Each of the above except for math and system functions are covered in earlier chapters. Math and system built-in functions are explained below. The math functions available in Tcl are listed in the following table − abs arg Calculates the absolute value of arg. acos arg Calculates the arccosine of arg. asin arg Calculates the arcsine of arg. atan arg Calculates the arctangent of arg. atan2 y x Calculates the arctangent of the quotient of its arguments(y/x). ceil arg Calculates the smallest integer greater than or equal to a number. cos arg Calculates the cosine of arg. cosh arg Calculates the hyperbolic cosine of arg. double arg Calculates if arg is a floating-point value, returns arg, otherwise converts arg to floating-point and returns the converted value. exp arg Calculates an exponential function (e raised to the power of arg). floor arg Calculates the largest integer less than or equal to arg. fmod x y Calculates the floating-point remainder of the division of x by y. If y is 0, an error is returned. hypot x y Calculates the length of the hypotenuse of a right-angled triangle sqrt(x*x+y*y). int arg Calculates if arg is an integer value of the same width as the machine word, returns arg, otherwise converts arg to an integer. log arg Calculates the natural logarithm of arg. log10 arg Calculates the base 10 logarithm of arg. pow x y Calculates the value of x raised to the power y. If x is negative, y must be an integer value. rand Calculates a pseudo-random number between 0 and 1. round arg Calculates the value of arg rounded to the nearest integer. sin arg Calculates the sine of arg. sinh arg Calculates the hyperbolic sine of arg. sqrt arg Calculates the square root of arg. arg must be positive. srand arg Calculates a pseudo-random number between 0 and 1. The arg, which must be an integer, is used to reset the seed for the random number generator of rand. tan arg Calculates the tangent of arg. tanh arg Calculates the hyperbolic tangent of arg. wide arg Calculates integer value at least 64-bits wide (by sign-extension if arg is a 32-bit number) for arg if it is not one already. Some examples using math functions are given below − #!/usr/bin/tclsh namespace import ::tcl::mathfunc::* puts [tan 10] puts [pow 10 2] puts [ceil 10.34] puts [hypot 10 20] puts [srand 45] puts [log 10] puts [srand 45] When the above code is executed, it produces the following result − 0.6483608274590866 100.0 11.0 22.360679774997898 0.0003521866166741525 2.302585092994046 0.0003521866166741525 The important system functions in Tcl includes, clock − seconds function, which returns current time in seconds. clock − seconds function, which returns current time in seconds. clock − format function, which formats the seconds into date and time. clock − format function, which formats the seconds into date and time. clock − scan function, which scans the input string and converts it into seconds. clock − scan function, which scans the input string and converts it into seconds. open − function, which is used to open a file. open − function, which is used to open a file. exec − function, which is used to execute a system command. exec − function, which is used to execute a system command. close − function, which is used to close a file. close − function, which is used to close a file. Some examples for the above functions are listed below − #!/usr/bin/tclsh #get seconds set currentTime [clock seconds] puts $currentTime #get format puts "The time is: [clock format $currentTime -format %H:%M:%S]" puts "The date is: [clock format $currentTime -format %D]" set date "Jun 15, 2014" puts [clock scan $date -format {%b %d, %Y}] puts [exec ls] puts [exec dir] set a [open input.txt] puts [read $a]; puts $a close $a When the above code is executed, it produces the following result − 1402819756 The time is: 03:09:16 The date is: 06/15/2014 1402808400 input.txt main.tcl input.txt main.tcl This is the file you can use to provide input to your program and later on open it inside your program to process the input. file3 The following table provides the list strings that can be used to format the date and time. %a Day in short form, eg:Sun. %A Day in full form eg:Sunday. %b Month in short form. %B Month in full form. %d Day of month. %j Julian day of year. %m Month in number. %y Year in two digits. %Y Year in four digits. %H Hour in 24 hour clock. %I Hour in 12 hour clock. %M Minutes. %S Seconds. %p AM or PM. %D Date in number, mm /dd/yy. %r Time in 12 hour clock. %R Time in 24 hour clock without seconds. %T Time in 24 hour clock with seconds. %Z Time Zone Name like GMT, IST, EST and so on. The "regexp" command is used to match a regular expression in Tcl. A regular expression is a sequence of characters that contains a search pattern. It consists of multiple rules and the following table explains these rules and corresponding use. x Exact match. [a-z] Any lowercase letter from a-z. . Any character. ^ Beginning string should match. $ Ending string should match. \^ Backlash sequence to match special character ^.Similarly you can use for other characters. () Add the above sequences inside parenthesis to make a regular expression. x* Should match 0 or more occurrences of the preceding x. x+ Should match 1 or more occurrences of the preceding x. [a-z]? Should match 0 or 1 occurrence of the preceding x. {digit} Matches exactly digit occurrences of previous regex expression. Digit that contains 0-9. {digit,} Matches 3 or more digit occurrences of previous regex expression. Digit that contains 0-9. {digit1,digit2} Occurrences matches the range between digit1 and digit2 occurrences of previous regex expression. The syntax for regex is given below − regexp optionalSwitches patterns searchString fullMatch subMatch1 ... subMatchn Here, regex is the command. We will see about optional switches later. Patterns are the rules as mentioned earlier. Search string is the actual string on which the regex is performed. Full match is any variable to hold the result of matched regex result. Submatch1 to SubMatchn are optional subMatch variable that holds the result of sub match patterns. Let's look at some simple examples before diving into complex ones. A simple example for a string with any alphabets. When any other character is encountered the regex, search will be stopped and returned. #!/usr/bin/tclsh regexp {([A-Za-z]*)} "Tcl Tutorial" a b puts "Full Match: $a" puts "Sub Match1: $b" When the above code is executed, it produces the following result − Full Match: Tcl Sub Match1: Tcl The following example shows how to search for multiple patterns. This is example pattern for any alphabets followed by any character followed by any alphabets. #!/usr/bin/tclsh regexp {([A-Za-z]*).([A-Za-z]*)} "Tcl Tutorial" a b c puts "Full Match: $a" puts "Sub Match1: $b" puts "Sub Match2: $c" When the above code is executed, it produces the following result − Full Match: Tcl Tutorial Sub Match1: Tcl Sub Match2: Tutorial A modified version of the above code to show that a sub pattern can contain multiple patterns is shown below − #!/usr/bin/tclsh regexp {([A-Za-z]*.([A-Za-z]*))} "Tcl Tutorial" a b c puts "Full Match: $a" puts "Sub Match1: $b" puts "Sub Match2: $c" When the above code is executed, it produces the following result − Full Match: Tcl Tutorial Sub Match1: Tcl Tutorial Sub Match2: Tutorial The list of switches available in Tcl are, nocase − Used to ignore case. nocase − Used to ignore case. indices − Store location of matched sub patterns instead of matched characters. indices − Store location of matched sub patterns instead of matched characters. line − New line sensitive matching. Ignores the characters after newline. line − New line sensitive matching. Ignores the characters after newline. start index − Sets the offset of start of search pattern. start index − Sets the offset of start of search pattern. Marks the end of switches Marks the end of switches In the above examples, I have deliberately used [A-Z, a-z] for all alphabets, you can easily use -nocase instead of as shown below − #!/usr/bin/tclsh regexp -nocase {([A-Z]*.([A-Z]*))} "Tcl Tutorial" a b c puts "Full Match: $a" puts "Sub Match1: $b" puts "Sub Match2: $c" When the above code is executed, it produces the following result − Full Match: Tcl Tutorial Sub Match1: Tcl Tutorial Sub Match2: Tutorial Another example using switches is shown below − #!/usr/bin/tclsh regexp -nocase -line -- {([A-Z]*.([A-Z]*))} "Tcl \nTutorial" a b puts "Full Match: $a" puts "Sub Match1: $b" regexp -nocase -start 4 -line -- {([A-Z]*.([A-Z]*))} "Tcl \nTutorial" a b puts "Full Match: $a" puts "Sub Match1: $b" When the above code is executed, it produces the following result − Full Match: Tcl Sub Match1: Tcl Full Match: Tutorial Sub Match1: Tutorial Tk refers to Toolkit and it provides cross platform GUI widgets, which helps you in building a Graphical User Interface. It was developed as an extension to Tcl scripting language by John Ousterhout. Tk remained in development independently from Tcl with version being different to each other, before, it was made in sync with Tcl in v8.0. It is cross platform with support for Linux, Mac OS, Unix, and Microsoft Windows operating systems. It is an open source. It provides high level of extendibility. It is customizable. It is configurable. It provides a large number of widgets. It can be used with other dynamic languages and not just Tcl. GUI looks identical across platforms. Large successful applications have been built in Tcl/Tk. Dashboard Soft User Interface Forms GUI for Relational DB Ad Hoc GUI for Relational DB Software/Hardware System Design Xtask - Task Management Musicology with Tcl and Tk Calender app Tk mail Tk Debugger Generally, all Mac and Linux mac come with Tk pre-installed. In case, it's not available or you need the latest version, then you may need to install it. Windows don't come with Tcl/Tk and you may need to use its specific binary to install it. It is just a small program that enables you to type Tk commands and have them executed line by line. It stops execution of a tcl file in case, it encounters an error unlike a compiler that executes fully. Let's have a helloWorld.tcl file as follows. We will use this as first program, we run on the platform you choose. #!/usr/bin/wish grid [ttk::button .mybutton -text "Hello World"] The following section explains only how to install Tcl/Tk on each of the available platforms. Download the latest version for windows installer from the list of Active Tcl/Tk binaries available. Active Tcl/Tk community edition is free for personal use. Run the downloaded executable to install the Tcl and Tk, which can be done by following the on screen instructions. Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using cd and then using the following step − C:\Tcl> wish helloWorld.tcl Press enter and we will see an output as shown below − Most Linux operating systems comes with Tk inbuilt and you can get started right away in those systems. In case, it's not available, you can use the following command to download and install Tcl-Tk. $ yum install tcl tk Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using cd command and then using the following step − $ wish helloWorld.tcl Press enter and we will see an output similar to the following − In case, it's not available prebuilt in your OS, you can use the following command to download and install Tcl-Tk − $ sudo apt-get install tcl tk Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using cd command and then using the following steps − $ wish helloWorld.tcl Press enter and we will see an output similar to the following − Download the latest version for Mac OS X package from the list of Active Tcl/Tk binaries available. Active Tcl community edition is free for personal use. Run the downloaded executable to install the Active Tcl, which can be done by following the on screen instructions. Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using cd command and then using the following step − $ wish helloWorld.tcl Press enter and we will see an output as shown below − You can use the option of installing from source files when a binary package is not available. It is generally preferred to use Tk binaries for Windows and Mac OS X, so only compilation of sources on unix based system is shown below − Download the source files. Download the source files. Now, use the following commands to extract, compile and build after switching to the downloaded folder. Now, use the following commands to extract, compile and build after switching to the downloaded folder. $ tar zxf tk8.6.1-src.tar.gz $ cd tcl8.6.1 $ cd unix $ ./configure —with-tcl=../../tcl8.6.1/unix —prefix=/opt —enable-gcc $ make $ sudo make install Note − Make sure, you change the file name to the version you downloaded on commands 1 and 2 in the above. In Tk, we classify some of the variables as special variables and they have a predefined usage/functionality. The list of special variables is listed below. tk_library Used for setting the location of standard Tk libraries. tk_patchLevel Refers to the current patch level of the Tk interpreter. tk_strictMotif When non-zero, Tk tries to adhere to Motif look-and-feel as closely as possible. tk_version Displays the Tk version. The above special variables have their special meanings for the Tk interpreter. Lets see the examples for special variables. #!/usr/bin/wish puts $tk_version When you run the program, you will get a similar output as shown below. 8.5 #!/usr/bin/wish puts $tk_library When you run the program, you will get a similar output as shown below. /Library/Frameworks/Tk.framework/Versions/8.6/Resources/Scripts #!/usr/bin/wish puts $tk_patchLevel When you run the program, you will get a similar output as shown below. 8.6.1 #!/usr/bin/wish puts $tk_strictMotif When you run the program, you will get a similar output as shown below. 0 The basic component of a Tk-based application is called a widget. A component is also sometimes called a window, since, in Tk, "window" and "widget" are often used interchangeably. Tk is a package that provides a rich set of graphical components for creating graphical applications with Tcl. Tk provides a range of widgets ranging from basic GUI widgets like buttons and menus to data display widgets. The widgets are very configurable as they have default configurations making them easy to use. Tk applications follow a widget hierarchy where any number of widgets may be placed within another widget, and those widgets within another widget. The main widget in a Tk program is referred to as the root widget and can be created by making a new instance of the TkRoot class. The syntax for creating a widget is given below. type variableName arguments options The type here refers to the widget type like button, label, and so on. Arguments can be optional and required based on individual syntax of each widget. The options range from size to formatting of each component. Widget uses a structure similar to naming packages. In Tk, the root window is named with a period (.) and an element in window, for example button is named .myButton1. The variable name should start with a lowercase letter, digit, or punctuation mark (except a period). After the first character, other characters may be uppercase or lowercase letters, numbers, or punctuation marks (except periods). It is recommended to use a lowercase letter to start the label. The colors can be declared using name like red, green, and so on. It can also use hexadecimal representing with #. The number of hexadecimal digits can be 3, 6, 9, or 12. The default unit is pixels and it is used when we specify no dimension. The other dimensions are i for inches, m for millimeters, c for centimeters and p for points. There are so many common options available to all widgets and they are listed below in the following table − -background color Used to set background color for widget. -borderwidth width Used to draw with border in 3D effects. -font fontDescriptor Used to set font for widget. -foreground color Used to set foreground color for widget. -height number Used to set height for widget. -highlightbackground color Used to set the color rectangle to draw around a widget when the widget does not have input focus. -highlightcolor color Used to set the color rectangle to draw around a widget when the widget has input focus. -padx number Sets the padx for the widget. -pady number Sets the pady for the widget. -relief condition Sets the 3D relief for this widget. The condition may be raised, sunken, flat, ridge, solid, or groove. -text text Sets the text for the widget. -textvariable varName Variable associated with the widget. When the text of widget changes, the variable is set with text of widget. -width number Sets the width for widget. A simple example for options is shown below. #!/usr/bin/wish grid [label .myLabel -background red -text "Hello World" -relief ridge -borderwidth 3] -padx 100 -pady 100 When we run the above program, we will get the following output. The list of available widgets are categorized below − Label Widget for displaying single line of text. Button Widget that is clickable and triggers an action. Entry Widget used to accept a single line of text as input. Message Widget for displaying multiple lines of text. Text Widget for displaying and optionally edit multiple lines of text. Toplevel Window with all borders and decorations provided by the Window manager. Frame Container widget to hold other widgets. Place Widget to hold other widgets in specific place with coordinates of its origin and an exact size. Pack Simple widget to organize widgets in blocks before placing them in the parent widget. Grid Widget to nest widgets packing in different directions. Radiobutton Widget that has a set of on/off buttons and labels, one of which may be selected. Checkbutton Widget that has a set of on/off buttons and labels, many of which may be selected.. Menu Widget that acts as holder for menu items. Listbox Widget that displays a list of cells, one or more of which may be selected. Dialog Widget for displaying dialog boxes. Spinbox Widget that allows users to choose numbers. Combobox Widget that combines an entry with a list of choices available to the use. Notebook Tabbed widget that helps to switch between one of several pages, using an index tab. Progressbar Widget to provide visual feedback to the progress of a long operation like file upload. Treeview Widget to display and allow browsing through a hierarchy of items more in form of tree. Scrollbar Scrolling widgets without a text or canvas widgets. Scale Scale widget to choose a numeric value through sliders. Canvas Drawing widget for displaying graphics and images.. We will cover each of these widgets in the upcoming chapters. Basic widgets are common widgets available in almost all Tk applications. The list of available basic widgets is given below − Widget for displaying single line of text. Widget that is clickable and triggers an action. Widget used to accept a single line of text as input. Widget for displaying multiple lines of text. Widget for displaying and optionally edit multiple lines of text. Widget used to create a frame that is a new top level window. A simple Tk example is shown below using basic widgets − #!/usr/bin/wish grid [label .myLabel -text "Label Widget" -textvariable labelText] grid [text .myText -width 20 -height 5] .myText insert 1.0 "Text\nWidget\n" grid [entry .myEntry -text "Entry Widget"] grid [message .myMessage -background red -foreground white -text "Message\nWidget"] grid [button .myButton1 -text "Button" -command "set labelText clicked"] When we run the above program, we will get the following output − Layout widgets are used to handle layouts for the Tk application. Frame widget is used group other widgets and place, pack, and grid are layout manager to give you total control over your adding to windows. The list of available layout widgets are as shown below − Container widget to hold other widgets. Widget to hold other widgets in specific place with coordinates of its origin and an exact size. Simple widget to organize widgets in blocks before placing them in the parent widget. Widget to nest widgets packing in different directions. A simple Tk example is shown below for layout widgets − #!/usr/bin/wish frame .myFrame1 -background red -relief ridge -borderwidth 8 -padx 10 -pady 10 -height 100 -width 100 frame .myFrame2 -background blue -relief ridge -borderwidth 8 -padx 10 -pady 10 -height 100 -width 50 pack .myFrame1 pack .myFrame2 When we run the above program, we will get the following output − Selection widgets are used to select different options in a Tk application. The list of available selection widgets are as shown below. Widget that has a set of on/off buttons and labels, one of which may be selected. Widget that has a set of on/off buttons and labels, many of which may be selected. Widget that acts as holder for menu items. Widget that displays a list of cells, one or more of which may be selected. A simple Tk example is shown below using selection widgets − #!/usr/bin/wish grid [frame .gender ] grid [label .label1 -text "Male" -textvariable myLabel1 ] grid [radiobutton .gender.maleBtn -text "Male" -variable gender -value "Male" -command "set myLabel1 Male"] -row 1 -column 2 grid [radiobutton .gender.femaleBtn -text "Female" -variable gender -value "Female" -command "set myLabel1 Female"] -row 1 -column 3 .gender.maleBtn select grid [label .myLabel2 -text "Range 1 not selected" -textvariable myLabelValue2 ] grid [checkbutton .chk1 -text "Range 1" -variable occupied1 -command {if {$occupied1 } { set myLabelValue2 {Range 1 selected} } else { set myLabelValue2 {Range 1 not selected} } }] proc setLabel {text} { .label configure -text $text } When we run the above program, we will get the following output − Canvas is used for providing drawing areas. The syntax for canvas widget is shown below − canvas canvasName options The options available for the canvas widget are listed below in the following table − -background color Used to set background color for widget. -closeenough distance Sets the closeness of mouse cursor to a displayable item. The default is 1.0 pixel. This value may be a fraction and must be positive. -scrollregion boundingBox The bounding box for the total area of this canvas. -height number Used to set height for widget. -width number Sets the width for widget. -xscrollincrement size The amount to scroll horizontally when scrolling is requested. -yscrollincrement size The amount to scroll vertically when scrolling is requested. A simple example for canvas widget is shown below − #!/usr/bin/wish canvas .myCanvas -background red -width 100 -height 100 pack .myCanvas When we run the above program, we will get the following output − The list of the available widgets for drawing in canvas is listed below − Draws a line. Draws an arc. Draws a rectangle. Draws an oval. Draws a polygon. Draws a text. Draws a bitmap. Draws an image. An example using different canvas widgets is shown below − #!/usr/bin/wish canvas .myCanvas -background red -width 200 -height 200 pack .myCanvas .myCanvas create arc 10 10 50 50 -fill yellow .myCanvas create line 10 30 50 50 100 10 -arrow both -fill yellow -smooth true -splinesteps 2 .myCanvas create oval 50 50 100 80 -fill yellow .myCanvas create polygon 50 150 100 80 120 120 100 190 -fill yellow -outline green .myCanvas create rectangle 150 150 170 170 -fill yellow .myCanvas create text 170 20 -fill yellow -text "Hello" -font {Helvetica -18 bold} .myCanvas create bitmap 180 50 -bitmap info When we run the above program, we will get the following output − Mega widgets include many complex widgets which is often required in some large scale Tk applications. The list of available mega widgets are as shown below − Widget for displaying dialog boxes. Widget that allows users to choose numbers. Widget that combines an entry with a list of choices available to the use. Tabbed widget that helps to switch between one of several pages, using an index tab. Widget to provide visual feedback to the progress of a long operation like file upload. Widget to display and allow browsing through a hierarchy of items more in form of tree. Scrolling widgets without a text or canvas widgets. Scale widget to choose a numeric value through sliders. A simple Tk example is shown below using some mega widgets. #!/usr/bin/wish ttk::treeview .tree -columns "Creator Year" -displaycolumns "Year Creator" .tree heading Creator -text "Creator" -anchor center .tree heading Year -text "Year" -anchor center pack .tree .tree insert {} end -id Languages -text "Languages" .tree insert Languages end -text C -values [list "Dennis Ritchie" "1990"] proc scaleMe {mywidget scaleValue} { $mywidget configure -length $scaleValue } pack [scale .s2 -from 100.0 -to 200.0 -length 100 -background yellow -borderwidth 5 -font{Helvetica -18 bold} -foreground red -width 40 -relief ridge -orien horizontal -variable a -command "scaleMe .s2" ] pack [ttk::progressbar .p1 -orient horizontal -length 200 -mode indeterminate -value 90] pack [ttk::progressbar .p2 -orient horizontal -length 200 -mode determinate -variable a -maximum 75 -value 20] When we run the above program, we will get the following output − There are a number of widgets that supports displaying text. Most of these provides the option of font attribute. The syntax for creating a font is shown below − font create fontName options The options available for the font create are listed below in the following table − -family familyName The name of font family. -size number The size of font. -weight level The weight for font. A simple example for a font creation is shown below − #!/usr/bin/wish font create myFont -family Helvetica -size 18 -weight bold pack [label .myLabel -font myFont -text "Hello World"] When we run the above program, we will get the following output − To get all the fonts available, we can use the following command − #!/usr/bin/wish puts [font families] When we run the above command, we will get the following output − {Abadi MT Condensed Extra Bold} {Abadi MT Condensed Light} {Al Bayan} {Al Nile} {Al Tarikh} {American Typewriter} {Andale Mono} Arial {Arial Black} {Arial Hebrew} {Arial Narrow} {Arial Rounded MT Bold} {Arial Unicode MS} Athelas Avenir {Avenir Next} {Avenir Next Condensed} Ayuthaya Baghdad {Bangla MN} {Bangla Sangam MN} {Baoli SC} Baskerville {Baskerville Old Face} Batang {Bauhaus 93} Beirut {Bell MT} {Bernard MT Condensed} BiauKai {Big Caslon} {Book Antiqua} {Bookman Old Style} {Bookshelf Symbol 7} Braggadocio {Britannic Bold} {Brush Script MT} Calibri {Calisto MT} Cambria {Cambria Math} Candara Century {Century Gothic} {Century Schoolbook} Chalkboard {Chalkboard SE} Chalkduster {Charcoal CY} Charter Cochin {Colonna MT} {Comic Sans MS} Consolas Constantia {Cooper Black} Copperplate {Copperplate Gothic Bold} {Copperplate Gothic Light} Corbel {Corsiva Hebrew} Courier {Courier New} {Curlz MT} Damascus {DecoType Naskh} Desdemona {Devanagari MT} {Devanagari Sangam MN} Didot {DIN Alternate} {DIN Condensed} {Diwan Kufi} {Diwan Thuluth} {Edwardian Script ITC} {Engravers MT} {Euphemia UCAS} Eurostile Farah Farisi {Footlight MT Light} {Franklin Gothic Book} {Franklin Gothic Medium} Futura Gabriola Garamond {GB18030 Bitmap} {Geeza Pro} Geneva {Geneva CY} Georgia {Gill Sans} {Gill Sans MT} {Gloucester MT Extra Condensed} {Goudy Old Style} {Gujarati MT} {Gujarati Sangam MN} Gulim GungSeo {Gurmukhi MN} {Gurmukhi MT} {Gurmukhi Sangam MN} Haettenschweiler {Hannotate SC} {Hannotate TC} {HanziPen SC} {HanziPen TC} Harrington HeadLineA Hei {Heiti SC} {Heiti TC} Helvetica {Helvetica CY} {Helvetica Neue} Herculanum {Hiragino Kaku Gothic Pro} {Hiragino Kaku Gothic ProN} {Hiragino Kaku Gothic Std} {Hiragino Kaku Gothic StdN} {Hiragino Maru Gothic Pro} {Hiragino Maru Gothic ProN} {Hiragino Mincho Pro} {Hiragino Mincho ProN} {Hiragino Sans GB} {Hoefler Text} Impact {Imprint MT Shadow} InaiMathi {Iowan Old Style} Kai Kailasa {Kaiti SC} {Kaiti TC} {Kannada MN} {Kannada Sangam MN} Kefa {Khmer MN} {Khmer Sangam MN} {Kino MT} Kokonor Krungthep KufiStandardGK {Lantinghei SC} {Lantinghei TC} {Lao MN} {Lao Sangam MN} {Libian SC} {LiHei Pro} {LiSong Pro} {Lucida Blackletter} {Lucida Bright} {Lucida Calligraphy} {Lucida Console} {Lucida Fax} {Lucida Grande} {Lucida Handwriting} {Lucida Sans} {Lucida Sans Typewriter} {Lucida Sans Unicode} {Malayalam MN} {Malayalam Sangam MN} Marion {Marker Felt} Marlett {Matura MT Script Capitals} Meiryo Menlo {Microsoft Sans Serif} Mishafi Mistral {Modern No. 20} Monaco {MS Gothic} {MS Mincho} {MS PGothic} {MS PMincho} {MS Reference Sans Serif} {MS Reference Specialty} Mshtakan {MT Extra} Muna {Myanmar MN} {Myanmar Sangam MN} Nadeem {Nanum Brush Script} {Nanum Gothic} {Nanum Myeongjo} {Nanum Pen Script} {New Peninim MT} {News Gothic MT} Noteworthy Onyx Optima {Oriya MN} {Oriya Sangam MN} Osaka Palatino {Palatino Linotype} Papyrus PCMyungjo Perpetua {Perpetua Titling MT} PilGi {Plantagenet Cherokee} Playbill PMingLiU {PT Mono} {PT Sans} {PT Sans Caption} {PT Sans Narrow} {PT Serif} {PT Serif Caption} Raanana Rockwell {Rockwell Extra Bold} Sana Sathu {Savoye LET} Seravek Silom SimSun {Sinhala MN} {Sinhala Sangam MN} Skia {Snell Roundhand} {Songti SC} {Songti TC} Stencil STFangsong STHeiti STIXGeneral STIXIntegralsD STIXIntegralsSm STIXIntegralsUp STIXIntegralsUpD STIXIntegralsUpSm STIXNonUnicode STIXSizeFiveSym STIXSizeFourSym STIXSizeOneSym STIXSizeThreeSym STIXSizeTwoSym STIXVariants STKaiti STSong Superclarendon Symbol Tahoma {Tamil MN} {Tamil Sangam MN} TeamViewer8 {Telugu MN} {Telugu Sangam MN} Thonburi Times {Times New Roman} {Trebuchet MS} {Tw Cen MT} Verdana Waseem {Wawati SC} {Wawati TC} Webdings {Weibei SC} {Weibei TC} {Wide Latin} Wingdings {Wingdings 2} {Wingdings 3} {Xingkai SC} {Yuanti SC} YuGothic YuMincho {Yuppy SC} {Yuppy TC} {Zapf Dingbats} Zapfino {Apple Braille} {Apple Chancery} {Apple Color Emoji} {Apple LiGothic} {Apple LiSung} {Apple SD Gothic Neo} {Apple Symbols} AppleGothic AppleMyungjo {Monotype Corsiva} {Monotype Sorts} The image widget is used to create and manipulate images. The syntax for creating image is as follows − image create type name options In the above syntax type is photo or bitmap and name is the image identifier. The options available for image create are listed below in the following table − -file fileName The name of the image file name. -height number Used to set height for widget. -width number Sets the width for widget. -data string Image in base 64 encoded string. A simple example for image widget is shown below − #!/usr/bin/wish image create photo imgobj -file "/Users/rajkumar/Desktop/F Drive/pictur/vb/Forests/ 680049.png" -width 400 -height 400 pack [label .myLabel] .myLabel configure -image imgobj When we run the above program, we will get the following output − The available function for image are listed below in the following table − image delete imageName Deletes the image from memory and related widgets visually. image height imageName Returns the height for image. image width imageName Returns the width for image. image type imageName Returns the type for image. image names Returns the list of images live in memory. A simple example for using the above image widget commands is shown below − #!/usr/bin/wish image create photo imgobj -file "/Users/rajkumar/images/680049.png" -width 400 -height 400 pack [label .myLabel] .myLabel configure -image imgobj puts [image height imgobj] puts [image width imgobj] puts [image type imgobj] puts [image names] image delete imgobj The image will be deleted visually and from memory once "image delete imgobj" command executes. In console, the output will be like the following − 400 400 photo imgobj ::tk::icons::information ::tk::icons::error ::tk::icons:: warning ::tk::icons::question Events in its simplest form is handled with the help of commands. A simple example for event handling is event handling with button and is shown below − #!/usr/bin/wish proc myEvent { } { puts "Event triggered" } pack [button .myButton1 -text "Button 1" -command myEvent] When we run the above program, we will get the following output − A simple program to show delay text animation event is shown below − #!/usr/bin/wish proc delay {} { for {set j 0} {$j < 100000} {incr j} {} } label .myLabel -text "Hello................" -width 25 pack .myLabel set str "Hello................" for {set i [string length $str]} {$i > -2} {set i [expr $i-1]} { .myLabel configure -text [string range $str 0 $i] update delay } When we run the program, we will get the following output in animated way − The syntax for event after delay is shown below − after milliseconds number command A simple program to show after delay event is shown below − #!/usr/bin/wish proc addText {} { label .myLabel -text "Hello................" -width 25 pack .myLabel } after 1000 addText When we run the program, we will get the following output after one second − You can cancel an event using the after cancel command as shown below − #!/usr/bin/wish proc addText {} { label .myLabel -text "Hello................" -width 25 pack .myLabel } after 1000 addText after cancel addText The syntax for event binding is as shown below − bind arguments #!/usr/bin/wish bind . {puts "Key Pressed: %K "} When we run the program and press a letter X, we will get the following output − Key Pressed: X #!/usr/bin/wish bind . {puts "Button %b Pressed : %x %y "} When we run the program and press the left mouse button, we will get an output similar to the following − Button 1 Pressed : 89 90 #!/usr/bin/wish proc myEvent { } { puts "Event triggered" } pack [button .myButton1 -text "Button 1" -command myEvent] bind . ".myButton1 invoke" When we run the program and press enter, we will get the following output − Event triggered Window manager is used to handle the top level window. It helps in controlling the size, position, and other attributes of the window. In Tk, . is used to refer the main window. The syntax for window command is shown below − wm option window arguments The list of options available for Tk wm command is shown in the following table − aspect windowName a b c d Tries to maintain the ratio of width/height to be between a/b and c/d. geometry windowName geometryParams Use to set geometry for window. grid windowName w h dx dy Sets the grid size. group windowName leaderName leaderName gives the leader of a group of related windows. deiconify windowName Brings the screen to normal if minimized. iconify windowName Minimizes the window. state windowName Returns the current state of window. withdraw windowName Unmaps the window and removes its details in memory. iconbitmap windowName image Sets or returns the icon bitmap. iconPhoto windowName image Sets or returns the icon photo. command windowName commandString Records the startup command in the WM_COMMAND property. protocol windowName arguments Register a command to handle the protocol request name, which can be WM_DELETE_WINDOW, WM_SAVE_YOURSELF, WM_TAKE_FOCUS. Eg: wm protocol. WM_DELETE_WINDOW Quit. minsize windowName size Determines the minimum window size. maxsize windowName size Determines the maximum window size. title windowName titleText Determines the title for window. attributes subOptions There are lots of attributes available like alpha, full screen and so on. Some of the above commands are used in the following example − #!/usr/bin/wish wm maxsize . 800 800 wm minsize . 300 300 wm title . "Hello" wm attributes . -alpha ".90" wm geometry . 300x200+100+100 When we run the above program, we will get the following output − As you can see alpha is one of the attributes available. The list of commonly used subcommands are listed below − -alpha number Sets the alpha for window. -fullscreen number Number can be 0 for normal screen or 1 for full screen. -topmost number Sets or returns whether window is topmost.Value can be 0 or 1. We can use toplevel command to create window and an example is shown below − #!/usr/bin/wish toplevel .t When we run the above program, we will get the following output − We can use destroy command to destroy window and an example is shown below − #!/usr/bin/wish destroy .t The above command will destroy window named .t. The geometry manager is used to manage the geometry of the window and other frames. We can use it to handle the position and size of the window and frames. The layout widgets are used for this purpose. The syntax for positioning and sizing window is shown below − wm geometry . wxh+/-x+/-y Here, w refers to width and h refers to height. It is followed by a '+' or '-' sign with number next referring to the x position on screen. Similarly the following '+' or '-' sign with number refers to the y position on screen A simple example is shown below for the above Statement −. #!/usr/bin/wish wm geometry . 300x200+100+100 When we run the above program, we will get the following output − The syntax for grid geometry is shown below − grid gridName -column number -row number -columnspan number -rowspan number The column, row, columnspan, or rowspan helps in providing the grid geometry. A simple example is shown below for the above statement − #!/usr/bin/wish frame .myFrame1 -background red -height 100 -width 100 frame .myFrame2 -background blue -height 100 -width 50 grid .myFrame1 -columnspan 10 -rowspan 10 -sticky w grid .myFrame2 -column 10 -row 2 When we run the above program, we will get the following output − Print Add Notes Bookmark this page
[ { "code": null, "e": 2448, "s": 2201, "text": "Tcl is shortened form of Tool Command Language. John Ousterhout of the University of California, Berkeley, designed it. It is a combination of a scripting language and its own interpreter that gets embedded to the application, we develop with it." }, { "code": null, "e": 2665, "s": 2448, "text": "Tcl was developed initially for Unix. It was then ported to Windows, DOS, OS/2, and Mac OSX. Tcl is much similar to other unix shell languages like Bourne Shell (Sh), the C Shell (csh), the Korn Shell (sh), and Perl." }, { "code": null, "e": 2913, "s": 2665, "text": "It aims at providing ability for programs to interact with other programs and also for acting as an embeddable interpreter. Even though, the original aim was to enable programs to interact, you can find full-fledged applications written in Tcl/Tk." }, { "code": null, "e": 2950, "s": 2913, "text": "The features of Tcl are as follows −" }, { "code": null, "e": 2976, "s": 2950, "text": "Reduced development time." }, { "code": null, "e": 3002, "s": 2976, "text": "Reduced development time." }, { "code": null, "e": 3065, "s": 3002, "text": "Powerful and simple user interface kit with integration of TK." }, { "code": null, "e": 3128, "s": 3065, "text": "Powerful and simple user interface kit with integration of TK." }, { "code": null, "e": 3219, "s": 3128, "text": "Write once, run anywhere. It runs on Windows, Mac OS X, and almost on every Unix platform." }, { "code": null, "e": 3310, "s": 3219, "text": "Write once, run anywhere. It runs on Windows, Mac OS X, and almost on every Unix platform." }, { "code": null, "e": 3446, "s": 3310, "text": "Quite easy to get started for experienced programmers; since, the language is so simple that they can learn Tcl in a few hours or days." }, { "code": null, "e": 3582, "s": 3446, "text": "Quite easy to get started for experienced programmers; since, the language is so simple that they can learn Tcl in a few hours or days." }, { "code": null, "e": 3713, "s": 3582, "text": "You can easily extend existing applications with Tcl. Also, it is possible to include Tcl in C, C++, or Java to Tcl or vice versa." }, { "code": null, "e": 3844, "s": 3713, "text": "You can easily extend existing applications with Tcl. Also, it is possible to include Tcl in C, C++, or Java to Tcl or vice versa." }, { "code": null, "e": 3889, "s": 3844, "text": "Have a powerful set of networking functions." }, { "code": null, "e": 3934, "s": 3889, "text": "Have a powerful set of networking functions." }, { "code": null, "e": 4033, "s": 3934, "text": "Finally, it's an open source, free, and can be used for commercial applications without any limit." }, { "code": null, "e": 4132, "s": 4033, "text": "Finally, it's an open source, free, and can be used for commercial applications without any limit." }, { "code": null, "e": 4212, "s": 4132, "text": "Tcl is a general-purpose language and you can find Tcl everywhere. It includes," }, { "code": null, "e": 4266, "s": 4212, "text": "Scalable websites that are often backed by databases." }, { "code": null, "e": 4316, "s": 4266, "text": "High performance web servers build with TclHttpd." }, { "code": null, "e": 4345, "s": 4316, "text": "Tcl with CGI based websites." }, { "code": null, "e": 4371, "s": 4345, "text": "Desktop GUI applications." }, { "code": null, "e": 4394, "s": 4371, "text": "Embedded applications." }, { "code": null, "e": 4527, "s": 4394, "text": "If you are willing to set up your environment for Tcl, you need the following two software applications available on your computer −" }, { "code": null, "e": 4539, "s": 4527, "text": "Text Editor" }, { "code": null, "e": 4556, "s": 4539, "text": "Tcl Interpreter." }, { "code": null, "e": 4707, "s": 4556, "text": "This will be used to type your program. Examples of a few text editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi." }, { "code": null, "e": 4891, "s": 4707, "text": "Name and version of a text editor can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on windows as well as Linux or UNIX." }, { "code": null, "e": 5062, "s": 4891, "text": "The files you create with your text editor are called source files and contain program source code. The source files for Tcl programs are named with the extension \".tcl\"." }, { "code": null, "e": 5253, "s": 5062, "text": "Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, build it, and finally execute it." }, { "code": null, "e": 5460, "s": 5253, "text": "It is just a small program that enables you to type Tcl commands and have them executed line by line. It stops execution of a tcl file, in case, it encounters an error unlike a compiler that executes fully." }, { "code": null, "e": 5575, "s": 5460, "text": "Let's have a helloWorld.tcl file as follows. We will use this as a first program, we run on a platform you choose." }, { "code": null, "e": 5614, "s": 5575, "text": "#!/usr/bin/tclsh\n\nputs \"Hello World!\" " }, { "code": null, "e": 5771, "s": 5614, "text": "Download the latest version for windows installer from the list of Active Tcl binaries available. The active Tcl community edition is free for personal use." }, { "code": null, "e": 5880, "s": 5771, "text": "Run the downloaded executable to install the Tcl, which can be done by following the on screen instructions." }, { "code": null, "e": 6053, "s": 5880, "text": "Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using 'cd' command and then execute the program using the following steps" }, { "code": null, "e": 6083, "s": 6053, "text": "C:\\Tcl> tclsh helloWorld.tcl\n" }, { "code": null, "e": 6116, "s": 6083, "text": "We can see the following output." }, { "code": null, "e": 6136, "s": 6116, "text": "C:\\Tcl> helloWorld\n" }, { "code": null, "e": 6259, "s": 6136, "text": "C:\\Tcl is the folder, I am using to save my samples. You can change it to the folder in which you have saved Tcl programs." }, { "code": null, "e": 6465, "s": 6259, "text": "Most of the Linux operating systems come with Tcl inbuilt and you can get started right away in those systems. In case, it's not available, you can use the following command to download and install Tcl-Tk." }, { "code": null, "e": 6487, "s": 6465, "text": "$ yum install tcl tk\n" }, { "code": null, "e": 6662, "s": 6487, "text": "Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using 'cd' command and then execute the program using the following steps −" }, { "code": null, "e": 6686, "s": 6662, "text": "$ tclsh helloWorld.tcl\n" }, { "code": null, "e": 6720, "s": 6686, "text": "We can see the following output −" }, { "code": null, "e": 6735, "s": 6720, "text": "$ hello world\n" }, { "code": null, "e": 6842, "s": 6735, "text": "In case, it's not available in your OS, you can use the following command to download and install Tcl-Tk −" }, { "code": null, "e": 6873, "s": 6842, "text": "$ sudo apt-get install tcl tk\n" }, { "code": null, "e": 7048, "s": 6873, "text": "Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using 'cd' command and then execute the program using the following steps −" }, { "code": null, "e": 7072, "s": 7048, "text": "$ tclsh helloWorld.tcl\n" }, { "code": null, "e": 7106, "s": 7072, "text": "We can see the following output −" }, { "code": null, "e": 7121, "s": 7106, "text": "$ hello world\n" }, { "code": null, "e": 7277, "s": 7121, "text": "Download the latest version for Mac OS X package from the list of Active Tcl binaries available. The active Tcl community edition is free for personal use." }, { "code": null, "e": 7393, "s": 7277, "text": "Run the downloaded executable to install the Active Tcl, which can be done by following the on screen instructions." }, { "code": null, "e": 7560, "s": 7393, "text": "Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using 'cd' and then execute the program using the following steps −" }, { "code": null, "e": 7583, "s": 7560, "text": "$ tclsh helloWorld.tcl" }, { "code": null, "e": 7617, "s": 7583, "text": "We can see the following output −" }, { "code": null, "e": 7632, "s": 7617, "text": "$ hello world\n" }, { "code": null, "e": 7867, "s": 7632, "text": "You can use the option of installing from source files when a binary package is not available. It is generally preferred to use Tcl binaries for Windows and Mac OS X, so only compilation of sources on unix based system is shown below." }, { "code": null, "e": 7894, "s": 7867, "text": "Download the source files." }, { "code": null, "e": 7921, "s": 7894, "text": "Download the source files." }, { "code": null, "e": 8026, "s": 7921, "text": "Now, use the following commands to extract, compile, and build after switching to the downloaded folder." }, { "code": null, "e": 8131, "s": 8026, "text": "Now, use the following commands to extract, compile, and build after switching to the downloaded folder." }, { "code": null, "e": 8252, "s": 8131, "text": "$ tar zxf tcl8.6.1-src.tar.gz\n$ cd tcl8.6.1\n$ cd unix\n$ ./configure —prefix=/opt —enable-gcc\n$ make\n$ sudo make install\n" }, { "code": null, "e": 8358, "s": 8252, "text": "Note − Make sure, you change the file name to the version you downloaded on commands 1 and 2 given above." }, { "code": null, "e": 8517, "s": 8358, "text": "In Tcl, we classify some of the variables as special variables and they have a predefined usage/functionality. The list of specials variables is listed below." }, { "code": null, "e": 8522, "s": 8517, "text": "argc" }, { "code": null, "e": 8568, "s": 8522, "text": "Refers to a number of command-line arguments." }, { "code": null, "e": 8573, "s": 8568, "text": "argv" }, { "code": null, "e": 8631, "s": 8573, "text": "Refers to the list containing the command-line arguments." }, { "code": null, "e": 8637, "s": 8631, "text": "argv0" }, { "code": null, "e": 8734, "s": 8637, "text": "Refers to the file name of the file being interpreted or the name by which we invoke the script." }, { "code": null, "e": 8738, "s": 8734, "text": "env" }, { "code": null, "e": 8816, "s": 8738, "text": "Used for representing the array of elements that are environmental variables." }, { "code": null, "e": 8826, "s": 8816, "text": "errorCode" }, { "code": null, "e": 8870, "s": 8826, "text": "Provides the error code for last Tcl error." }, { "code": null, "e": 8880, "s": 8870, "text": "errorInfo" }, { "code": null, "e": 8925, "s": 8880, "text": "Provides the stack trace for last Tcl error." }, { "code": null, "e": 8941, "s": 8925, "text": "tcl_interactive" }, { "code": null, "e": 9043, "s": 8941, "text": "Used to switch between interactive and non-interactive modes by setting this to 1 and 0 respectively." }, { "code": null, "e": 9055, "s": 9043, "text": "tcl_library" }, { "code": null, "e": 9112, "s": 9055, "text": "Used for setting the location of standard Tcl libraries." }, { "code": null, "e": 9124, "s": 9112, "text": "tcl_pkgPath" }, { "code": null, "e": 9197, "s": 9124, "text": "Provides the list of directories where packages are generally installed." }, { "code": null, "e": 9212, "s": 9197, "text": "tcl_patchLevel" }, { "code": null, "e": 9270, "s": 9212, "text": "Refers to the current patch level of the Tcl interpreter." }, { "code": null, "e": 9283, "s": 9270, "text": "tcl_platform" }, { "code": null, "e": 9399, "s": 9283, "text": "Used for representing the array of elements with objects including byteOrder, machine, osVersion, platform, and os." }, { "code": null, "e": 9413, "s": 9399, "text": "tcl_precision" }, { "code": null, "e": 9548, "s": 9413, "text": "Refers to the precision i.e. number of digits to retain when converting to floating-point numbers to strings. The default value is 12." }, { "code": null, "e": 9560, "s": 9548, "text": "tcl_prompt1" }, { "code": null, "e": 9590, "s": 9560, "text": "Refers to the primary prompt." }, { "code": null, "e": 9602, "s": 9590, "text": "tcl_prompt2" }, { "code": null, "e": 9656, "s": 9602, "text": "Refers to the secondary prompt with invalid commands." }, { "code": null, "e": 9671, "s": 9656, "text": "tcl_rcFileName" }, { "code": null, "e": 9712, "s": 9671, "text": "Provides the user specific startup file." }, { "code": null, "e": 9729, "s": 9712, "text": "tcl_traceCompile" }, { "code": null, "e": 9843, "s": 9729, "text": "Used for controlling the tracing of bytecode compilation. Use 0 for no output, 1 for summary, and 2 for detailed." }, { "code": null, "e": 9857, "s": 9843, "text": "tcl_traceExec" }, { "code": null, "e": 9969, "s": 9857, "text": "Used for controlling the tracing of bytecode execution. Use 0 for no output, 1 for summary, and 2 for detailed." }, { "code": null, "e": 9981, "s": 9969, "text": "tcl_version" }, { "code": null, "e": 10033, "s": 9981, "text": "Returns the current version of the Tcl interpreter." }, { "code": null, "e": 10114, "s": 10033, "text": "The above special variables have their special meanings for the Tcl interpreter." }, { "code": null, "e": 10161, "s": 10114, "text": "Let's see some examples for special variables." }, { "code": null, "e": 10197, "s": 10161, "text": "#!/usr/bin/tclsh\n\nputs $tcl_version" }, { "code": null, "e": 10270, "s": 10197, "text": "When you run the program, you will get a similar output as shown below −" }, { "code": null, "e": 10275, "s": 10270, "text": "8.6\n" }, { "code": null, "e": 10309, "s": 10275, "text": "#!/usr/bin/tclsh\n\nputs $env(PATH)" }, { "code": null, "e": 10382, "s": 10309, "text": "When you run the program, you will get a similar output as shown below −" }, { "code": null, "e": 10960, "s": 10382, "text": "/home/cg/root/GNUstep/Tools:/usr/GNUstep/Local/Tools:/usr/GNUstep/\nSystem/Tools:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/webmaster/.local/bin:/\nhome/webmaster/bin:/usr/local/scriba/bin:/usr/local/smlnj/\nbin:/usr/local/bin/std:/usr/local/bin/extra:/usr/local/fantom/bin:/usr/\nlocal/dart/bin:/usr/bin:/usr/local/bin:/usr/local/sbin:/usr/sbin:/opt/mono/\nbin:/opt/mono/lib/mono/4.5:/usr/local/bin:.:/usr/libexec/sdcc:/usr/local/\nicon-v950/bin:/usr/local/mozart/bin:/opt/Pawn/bin:/opt/jdk1.7.0_75/bin:/\nopt/jdk1.7.0_75/jre/bin:/opt/pash/Source/PashConsole/bin/Debug/\n" }, { "code": null, "e": 10996, "s": 10960, "text": "#!/usr/bin/tclsh\n\nputs $tcl_pkgPath" }, { "code": null, "e": 11069, "s": 10996, "text": "When you run the program, you will get a similar output as shown below −" }, { "code": null, "e": 11140, "s": 11069, "text": "/usr/lib64/tcl8.6 /usr/share/tcl8.6 /usr/lib64/tk8.6 /usr/share/tk8.6\n" }, { "code": null, "e": 11176, "s": 11140, "text": "#!/usr/bin/tclsh\n\nputs $tcl_library" }, { "code": null, "e": 11249, "s": 11176, "text": "When you run the program, you will get a similar output as shown below −" }, { "code": null, "e": 11268, "s": 11249, "text": "/usr/share/tcl8.6\n" }, { "code": null, "e": 11307, "s": 11268, "text": "#!/usr/bin/tclsh\n\nputs $tcl_patchLevel" }, { "code": null, "e": 11380, "s": 11307, "text": "When you run the program, you will get a similar output as shown below −" }, { "code": null, "e": 11387, "s": 11380, "text": "8.6.6\n" }, { "code": null, "e": 11425, "s": 11387, "text": "#!/usr/bin/tclsh\n\nputs $tcl_precision" }, { "code": null, "e": 11498, "s": 11425, "text": "When you run the program, you will get a similar output as shown below −" }, { "code": null, "e": 11501, "s": 11498, "text": "0\n" }, { "code": null, "e": 11540, "s": 11501, "text": "#!/usr/bin/tclsh\n\nputs $tcl_rcFileName" }, { "code": null, "e": 11613, "s": 11540, "text": "When you run the program, you will get a similar output as shown below −" }, { "code": null, "e": 11625, "s": 11613, "text": "~/.tclshrc\n" }, { "code": null, "e": 11702, "s": 11625, "text": "Tcl is quite simple to learn and let's start creating our first Tcl program!" }, { "code": null, "e": 11841, "s": 11702, "text": "Let us write a simple Tcl program. All Tcl files will have an extension, i.e., .tcl. So, put the following source code in a test.tcl file." }, { "code": null, "e": 11881, "s": 11841, "text": "#!/usr/bin/tclsh\n\nputs \"Hello, World!\" " }, { "code": null, "e": 12022, "s": 11881, "text": "Assuming, Tcl environment is setup correctly; let's run the program after switching to file's directory and then execute the program using −" }, { "code": null, "e": 12040, "s": 12022, "text": "$ tclsh test.tcl\n" }, { "code": null, "e": 12075, "s": 12040, "text": "We will get the following output −" }, { "code": null, "e": 12090, "s": 12075, "text": "Hello, World!\n" }, { "code": null, "e": 12382, "s": 12090, "text": "Let us now see the basic structure of Tcl program, so that it will be easy for you to understand basic building blocks of the Tcl language. In Tcl, we use new line or semicolon to terminate the previous line of code. But semicolon is not necessary, if you are using newline for each command." }, { "code": null, "e": 12531, "s": 12382, "text": "Comments are like helping text in your Tcl program and the interpreter ignores them. Comments can be written using a hash_(#) sign in the beginning." }, { "code": null, "e": 12596, "s": 12531, "text": "#!/usr/bin/tclsh\n\n# my first program in Tcl\nputs \"Hello World!\" " }, { "code": null, "e": 12664, "s": 12596, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 12678, "s": 12664, "text": "Hello World!\n" }, { "code": null, "e": 12774, "s": 12678, "text": "Multiline or block comment is written using 'if' with condition '0'. An example is shown below." }, { "code": null, "e": 12876, "s": 12774, "text": "#!/usr/bin/tclsh\n\nif 0 {\n my first program in Tcl program\n Its very simple\n}\nputs \"Hello World!\" " }, { "code": null, "e": 12944, "s": 12876, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 12958, "s": 12944, "text": "Hello World!\n" }, { "code": null, "e": 13009, "s": 12958, "text": "Inline comments use ;#. An example is given below." }, { "code": null, "e": 13080, "s": 13009, "text": "#!/usr/bin/tclsh\n\nputs \"Hello World!\" ;# my first print in Tcl program" }, { "code": null, "e": 13148, "s": 13080, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 13162, "s": 13148, "text": "Hello World!\n" }, { "code": null, "e": 13415, "s": 13162, "text": "A Tcl identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores, dollars ($) , and digits (0 to 9)." }, { "code": null, "e": 13652, "s": 13415, "text": "Tcl does not allow punctuation characters such as @, and % within identifiers. Tcl is a case sensitive_ language. Thus Manpower and manpower are two different identifiers in Tcl. Here are some of the examples of acceptable identifiers −" }, { "code": null, "e": 13738, "s": 13652, "text": "mohd zara abc move_name a_123\nmyname50 _temp j a23b9 retVal\n" }, { "code": null, "e": 13866, "s": 13738, "text": "A line containing only whitespace, possibly with a comment, is known as a blank line, and a Tcl interpreter totally ignores it." }, { "code": null, "e": 14181, "s": 13866, "text": "Whitespace is the term used in Tcl to describe blanks, tabs, newline characters, and comments. Whitespace separates one part of a statement from another and enables the interpreter to identify where one element in a statement, such as puts, ends and the next element begins. Therefore, in the following statement −" }, { "code": null, "e": 14220, "s": 14181, "text": "#!/usr/bin/tclsh\n\nputs \"Hello World!\" " }, { "code": null, "e": 14420, "s": 14220, "text": "There must be at least one whitespace character (usually a space) between “puts” and \"Hello World!\" for the interpreter to be able to distinguish them. On the other hand, in the following statement −" }, { "code": null, "e": 14484, "s": 14420, "text": "#!/usr/bin/tclsh\n\nputs [expr 3 + 2] ;# print sum of the 3 and 2" }, { "code": null, "e": 14552, "s": 14484, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 14555, "s": 14552, "text": "5\n" }, { "code": null, "e": 14711, "s": 14555, "text": "No whitespace characters are necessary between 3 and +, or between + and 2; although, you are free to include some if you wish for the readability purpose." }, { "code": null, "e": 15155, "s": 14711, "text": "As you know, Tcl is a Tool command language, commands are the most vital part of the language. Tcl commands are built in-to the language with each having its own predefined function. These commands form the reserved words of the language and cannot be used for other variable naming. The advantage with these Tcl commands is that, you can define your own implementation for any of these commands to replace the original built-in functionality." }, { "code": null, "e": 15244, "s": 15155, "text": "Each of the Tcl commands validates the input and it reduces the work of the interpreter." }, { "code": null, "e": 15479, "s": 15244, "text": "Tcl command is actually a list of words, with the first word representing the command to be executed. The next words represent the arguments. In order to group the words into a single argument, we enclose multiple words with \"\" or {}." }, { "code": null, "e": 15521, "s": 15479, "text": "The syntax of Tcl command is as follows −" }, { "code": null, "e": 15567, "s": 15521, "text": "commandName argument1 argument2 ... argumentN" }, { "code": null, "e": 15611, "s": 15567, "text": "Let's see a simple example of Tcl command −" }, { "code": null, "e": 15650, "s": 15611, "text": "#!/usr/bin/tclsh\n\nputs \"Hello, world!\"" }, { "code": null, "e": 15718, "s": 15650, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 15733, "s": 15718, "text": "Hello, world!\n" }, { "code": null, "e": 15866, "s": 15733, "text": "In the above code, ‘puts’ is the Tcl command and \"Hello World\" is the argument1. As said before, we have used \"\" to group two words." }, { "code": null, "e": 15928, "s": 15866, "text": "Let's see another example of Tcl command with two arguments −" }, { "code": null, "e": 15974, "s": 15928, "text": "#!/usr/bin/tclsh\n\nputs stdout \"Hello, world!\"" }, { "code": null, "e": 16042, "s": 15974, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 16057, "s": 16042, "text": "Hello, world!\n" }, { "code": null, "e": 16229, "s": 16057, "text": "In the above code, ‘puts’ is the Tcl command, ‘stdout’ is argument1, and \"Hello World\" is argument2. Here, stdout makes the program to print in the standard output device." }, { "code": null, "e": 16385, "s": 16229, "text": "In command substitutions, square brackets are used to evaluate the scripts inside the square brackets. A simple example to add two numbers is shown below −" }, { "code": null, "e": 16425, "s": 16385, "text": "#!/usr/bin/tclsh\n\nputs [expr 1 + 6 + 9]" }, { "code": null, "e": 16489, "s": 16425, "text": "When the above code is executed, it produces following result −" }, { "code": null, "e": 16493, "s": 16489, "text": "16\n" }, { "code": null, "e": 16677, "s": 16493, "text": "In variable substitutions, $ is used before the variable name and this returns the contents of the variable. A simple example to set a value to a variable and print it is shown below." }, { "code": null, "e": 16711, "s": 16677, "text": "#!/usr/bin/tclsh\n\nset a 3\nputs $a" }, { "code": null, "e": 16779, "s": 16711, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 16782, "s": 16779, "text": "3\n" }, { "code": null, "e": 16951, "s": 16782, "text": "These are commonly called escape sequences; with each backslash, followed by a letter having its own meaning. A simple example for newline substitution is shown below −" }, { "code": null, "e": 16989, "s": 16951, "text": "#!/usr/bin/tclsh\n\nputs \"Hello\\nWorld\"" }, { "code": null, "e": 17057, "s": 16989, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 17070, "s": 17057, "text": "Hello\nWorld\n" }, { "code": null, "e": 17494, "s": 17070, "text": "The primitive data-type of Tcl is string and often we can find quotes on Tcl as string only language. These primitive data-types in turn create composite data-types for list and associative array. In Tcl, data-types can represent not only the simple Tcl objects, but also can represent complex objects such as handles, graphic objects (mostly widgets), and I/O channels. Let's look into the details about each of the above." }, { "code": null, "e": 17884, "s": 17494, "text": "In Tcl, whether it is an integer number, boolean, floating point number, or a string. When you want to use a variable, you can directly assign a value to it, there is no step of declaration in Tcl. There can be internal representations for these different types of objects. It can transform one data-type to another when required. The syntax for assigning value to variable is as follows −" }, { "code": null, "e": 17937, "s": 17884, "text": "#!/usr/bin/tclsh\n\nset myVariable 18\nputs $myVariable" }, { "code": null, "e": 18005, "s": 17937, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 18009, "s": 18005, "text": "18\n" }, { "code": null, "e": 18273, "s": 18009, "text": "The above statement will create a variable name myVariable and stores it as a string even though, we have not used double quotations. Now, if we try to make an arithmetic on the variable, it is automatically turned to an integer. A simple example is shown below −" }, { "code": null, "e": 18341, "s": 18273, "text": "#!/usr/bin/tclsh\n\nset myVariable 18\nputs [expr $myVariable + 6 + 9]" }, { "code": null, "e": 18409, "s": 18341, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 18413, "s": 18409, "text": "33\n" }, { "code": null, "e": 18545, "s": 18413, "text": "One important thing to note is that, these variables don't have any default values and must be assigned value before they are used." }, { "code": null, "e": 18814, "s": 18545, "text": "If we try to print using puts, the number is transformed into proper string. Having two representations, internal and external, help Tcl to create complex data structures easily compared to other languages. Also, Tcl is more efficient due to its dynamic object nature." }, { "code": null, "e": 18931, "s": 18814, "text": "Unlike other languages, in Tcl, you need not include double quotes when it's only a single word. An example can be −" }, { "code": null, "e": 18987, "s": 18931, "text": "#!/usr/bin/tclsh\n\nset myVariable hello\nputs $myVariable" }, { "code": null, "e": 19055, "s": 18987, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 19062, "s": 19055, "text": "hello\n" }, { "code": null, "e": 19175, "s": 19062, "text": "When we want to represent multiple strings, we can use either double quotes or curly braces. It is shown below −" }, { "code": null, "e": 19285, "s": 19175, "text": "#!/usr/bin/tclsh\n\nset myVariable \"hello world\"\nputs $myVariable\nset myVariable {hello world}\nputs $myVariable" }, { "code": null, "e": 19353, "s": 19285, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 19378, "s": 19353, "text": "hello world\nhello world\n" }, { "code": null, "e": 19550, "s": 19378, "text": "List is nothing but a group of elements. A group of words either using double quotes or curly braces can be used to represent a simple list. A simple list is shown below −" }, { "code": null, "e": 19688, "s": 19550, "text": "#!/usr/bin/tclsh\n\nset myVariable {red green blue}\nputs [lindex $myVariable 2]\nset myVariable \"red green blue\"\nputs [lindex $myVariable 1]" }, { "code": null, "e": 19756, "s": 19688, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 19768, "s": 19756, "text": "blue\ngreen\n" }, { "code": null, "e": 19934, "s": 19768, "text": "Associative arrays have an index (key) that is not necessarily an integer. It is generally a string that acts like key value pairs. A simple example is shown below −" }, { "code": null, "e": 20048, "s": 19934, "text": "#!/usr/bin/tclsh\n\nset marks(english) 80\nputs $marks(english)\nset marks(mathematics) 90\nputs $marks(mathematics)" }, { "code": null, "e": 20116, "s": 20048, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 20123, "s": 20116, "text": "80\n90\n" }, { "code": null, "e": 20381, "s": 20123, "text": "Tcl handles are commonly used to represent files and graphics objects. These can include handles to network requests and also other channels like serial port communication, sockets, or I/O devices. The following is an example where a file handle is created." }, { "code": null, "e": 20413, "s": 20381, "text": "set myfile [open \"filename\" r]\n" }, { "code": null, "e": 20476, "s": 20413, "text": "You will see more detail on files in the Tcl file I/O chapter." }, { "code": null, "e": 20603, "s": 20476, "text": "In Tcl, there is no concept of variable declaration. Once, a new variable name is encountered, Tcl will define a new variable." }, { "code": null, "e": 20763, "s": 20603, "text": "The name of variables can contain any characters and length. You can even have white spaces by enclosing the variable in curly braces, but it is not preferred." }, { "code": null, "e": 20853, "s": 20763, "text": "The set command is used for assigning value to a variable. The syntax for set command is," }, { "code": null, "e": 20877, "s": 20853, "text": "set variableName value\n" }, { "code": null, "e": 20923, "s": 20877, "text": "A few examples of variables are shown below −" }, { "code": null, "e": 21015, "s": 20923, "text": "#!/usr/bin/tclsh\n\nset variableA 10\nset {variable B} test\nputs $variableA\nputs ${variable B}" }, { "code": null, "e": 21083, "s": 21015, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 21092, "s": 21083, "text": "10\ntest\n" }, { "code": null, "e": 21189, "s": 21092, "text": "As you can see in the above program, the $variableName is used to get the value of the variable." }, { "code": null, "e": 21450, "s": 21189, "text": "Tcl is a dynamically typed language. The value of the variable can be dynamically converted to the required type when required. For example, a number 5 that is stored as string will be converted to number when doing an arithmetic operation. It is shown below −" }, { "code": null, "e": 21544, "s": 21450, "text": "#!/usr/bin/tclsh\n\nset variableA \"10\"\nputs $variableA\nset sum [expr $variableA +20];\nputs $sum" }, { "code": null, "e": 21612, "s": 21544, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 21619, "s": 21612, "text": "10\n30\n" }, { "code": null, "e": 21878, "s": 21619, "text": "As you can see in the above example, expr is used for representing mathematical expression. The default precision of Tcl is 12 digits. In order to get floating point results, we should add at least a single decimal digit. A simple example explains the above." }, { "code": null, "e": 22079, "s": 21878, "text": "#!/usr/bin/tclsh\n\nset variableA \"10\"\nset result [expr $variableA / 9];\nputs $result\nset result [expr $variableA / 9.0];\nputs $result\nset variableA \"10.0\"\nset result [expr $variableA / 9];\nputs $result" }, { "code": null, "e": 22147, "s": 22079, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 22188, "s": 22147, "text": "1\n1.1111111111111112\n1.1111111111111112\n" }, { "code": null, "e": 22520, "s": 22188, "text": "In the above example, you can see three cases. In the first case, the dividend and the divisor are whole numbers and we get a whole number as result. In the second case, the divisor alone is a decimal number and in the third case, the dividend is a decimal number. In both second and third cases, we get a decimal number as result." }, { "code": null, "e": 22629, "s": 22520, "text": "In the above code, you can change the precision by using tcl_precision special variable. It is shown below −" }, { "code": null, "e": 22735, "s": 22629, "text": "#!/usr/bin/tclsh\n\nset variableA \"10\"\nset tcl_precision 5\nset result [expr $variableA / 9.0];\nputs $result" }, { "code": null, "e": 22803, "s": 22735, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 22811, "s": 22803, "text": "1.1111\n" }, { "code": null, "e": 23009, "s": 22811, "text": "An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Tcl language is rich in built-in operators and provides the following types of operators −" }, { "code": null, "e": 23030, "s": 23009, "text": "Arithmetic Operators" }, { "code": null, "e": 23051, "s": 23030, "text": "Relational Operators" }, { "code": null, "e": 23069, "s": 23051, "text": "Logical Operators" }, { "code": null, "e": 23087, "s": 23069, "text": "Bitwise Operators" }, { "code": null, "e": 23104, "s": 23087, "text": "Ternary Operator" }, { "code": null, "e": 23210, "s": 23104, "text": "This chapter will explain the arithmetic, relational, logical, bitwise, and ternary operators one by one." }, { "code": null, "e": 23351, "s": 23210, "text": "Following table shows all the arithmetic operators supported by Tcl language. Assume variable ‘A’ holds 10 and variable ‘B’ holds 20, then −" }, { "code": null, "e": 23365, "s": 23351, "text": "Show Examples" }, { "code": null, "e": 23502, "s": 23365, "text": "Following table shows all the relational operators supported by Tcl language. Assume variable A holds 10 and variable B holds 20, then −" }, { "code": null, "e": 23516, "s": 23502, "text": "Show Examples" }, { "code": null, "e": 23648, "s": 23516, "text": "Following table shows all the logical operators supported by Tcl language. Assume variable A holds 1 and variable B holds 0, then −" }, { "code": null, "e": 23662, "s": 23648, "text": "Show Examples" }, { "code": null, "e": 23777, "s": 23662, "text": "Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows −" }, { "code": null, "e": 23854, "s": 23777, "text": "Assume if A = 60; and B = 13; now in binary format they will be as follows −" }, { "code": null, "e": 23868, "s": 23854, "text": "A = 0011 1100" }, { "code": null, "e": 23882, "s": 23868, "text": "B = 0000 1101" }, { "code": null, "e": 23905, "s": 23882, "text": "----------------------" }, { "code": null, "e": 23921, "s": 23905, "text": "A&B = 0000 1100" }, { "code": null, "e": 23937, "s": 23921, "text": "A|B = 0011 1101" }, { "code": null, "e": 23953, "s": 23937, "text": "A^B = 0011 0001" }, { "code": null, "e": 24095, "s": 23953, "text": "The Bitwise operators supported by Tcl language are listed in the following table. Assume variable A holds 60 and variable B holds 13, then −" }, { "code": null, "e": 24109, "s": 24095, "text": "Show Examples" }, { "code": null, "e": 24123, "s": 24109, "text": "Show Examples" }, { "code": null, "e": 24384, "s": 24123, "text": "Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator." }, { "code": null, "e": 24554, "s": 24384, "text": "For example : x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3 * 2 and then adds into 7." }, { "code": null, "e": 24749, "s": 24554, "text": "Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first." }, { "code": null, "e": 24763, "s": 24749, "text": "Show Examples" }, { "code": null, "e": 25080, "s": 24763, "text": "Decision making structures require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false." }, { "code": null, "e": 25194, "s": 25080, "text": "Following is the general form of a typical decision making structure found in most of the programming languages −" }, { "code": null, "e": 25309, "s": 25194, "text": "Tcl language uses the expr command internally and hence it’s not required for us to use expr statement explicitly." }, { "code": null, "e": 25379, "s": 25309, "text": "Tcl language provides following types of decision making statements −" }, { "code": null, "e": 25466, "s": 25379, "text": "An 'if' statement consists of a Boolean expression followed by one or more statements." }, { "code": null, "e": 25586, "s": 25466, "text": "An 'if' statement can be followed by an optional 'else' statement, which executes when the Boolean expression is false." }, { "code": null, "e": 25677, "s": 25586, "text": "You can use one 'if' or 'else if' statement inside another 'if' or 'else if' statement(s)." }, { "code": null, "e": 25766, "s": 25677, "text": "A switch statement allows a variable to be tested for equality against a list of values." }, { "code": null, "e": 25835, "s": 25766, "text": "You can use one switch statement inside another switch statement(s)." }, { "code": null, "e": 25984, "s": 25835, "text": "We have covered conditional operator ? : in previous chapter, which can be used to replace if...else statements. It has the following general form −" }, { "code": null, "e": 26005, "s": 25984, "text": "Exp1 ? Exp2 : Exp3;\n" }, { "code": null, "e": 26092, "s": 26005, "text": "Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon." }, { "code": null, "e": 26375, "s": 26092, "text": "The value of a '? expression' is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire '? expression.' If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression. An example is shown below." }, { "code": null, "e": 26517, "s": 26375, "text": "#!/usr/bin/tclsh\n\nset a 10;\nset b [expr $a == 1 ? 20: 30]\nputs \"Value of b is $b\\n\"\nset b [expr $a == 10 ? 20: 30]\nputs \"Value of b is $b\\n\" " }, { "code": null, "e": 26600, "s": 26517, "text": "When you compile and execute the above program, it produces the following result −" }, { "code": null, "e": 26635, "s": 26600, "text": "Value of b is 30\nValue of b is 20\n" }, { "code": null, "e": 26866, "s": 26635, "text": "There may be a situation, where you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on." }, { "code": null, "e": 26972, "s": 26866, "text": "Programming languages provide various control structures that allow for more complicated execution paths." }, { "code": null, "e": 27153, "s": 26972, "text": "A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages −" }, { "code": null, "e": 27236, "s": 27153, "text": "Tcl language provides the following types of loops to handle looping requirements." }, { "code": null, "e": 27367, "s": 27236, "text": "Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body." }, { "code": null, "e": 27473, "s": 27367, "text": "Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable." }, { "code": null, "e": 27551, "s": 27473, "text": "You can use one or more loop inside any another while, for or do..while loop." }, { "code": null, "e": 27718, "s": 27551, "text": "Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed." }, { "code": null, "e": 27765, "s": 27718, "text": "Tcl supports the following control statements." }, { "code": null, "e": 27888, "s": 27765, "text": "Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch." }, { "code": null, "e": 27997, "s": 27888, "text": "Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating." }, { "code": null, "e": 28190, "s": 27997, "text": "A loop becomes infinite loop if a condition never becomes false. The while loop is traditionally used for this purpose. You can make an endless loop by leaving the conditional expression as 1." }, { "code": null, "e": 28243, "s": 28190, "text": "while {1} {\n puts \"This loop will run forever.\"\n}\n" }, { "code": null, "e": 28399, "s": 28243, "text": "When the conditional expression is absent, it is assumed to be true. Tcl programmers more commonly use the while {1} construct to signify an infinite loop." }, { "code": null, "e": 28468, "s": 28399, "text": "NOTE − You can terminate an infinite loop by pressing Ctrl + C keys." }, { "code": null, "e": 28597, "s": 28468, "text": "An array is a systematic arrangement of a group of elements using indices. The syntax for the conventional array is shown below." }, { "code": null, "e": 28625, "s": 28597, "text": "set ArrayName(Index) value\n" }, { "code": null, "e": 28678, "s": 28625, "text": "An example for creating simple array is shown below." }, { "code": null, "e": 28785, "s": 28678, "text": "#!/usr/bin/tclsh\n\nset languages(0) Tcl\nset languages(1) \"C Language\"\nputs $languages(0)\nputs $languages(1)" }, { "code": null, "e": 28853, "s": 28785, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 28869, "s": 28853, "text": "Tcl\nC Language\n" }, { "code": null, "e": 28923, "s": 28869, "text": "The syntax for calculating size array is shown below." }, { "code": null, "e": 28950, "s": 28923, "text": "[array size variablename]\n" }, { "code": null, "e": 28999, "s": 28950, "text": "An example for printing the size is shown below." }, { "code": null, "e": 29097, "s": 28999, "text": "#!/usr/bin/tclsh\n\nset languages(0) Tcl\nset languages(1) \"C Language\"\nputs [array size languages]" }, { "code": null, "e": 29165, "s": 29097, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 29168, "s": 29165, "text": "2\n" }, { "code": null, "e": 29441, "s": 29168, "text": "Though, array indices can be non-continuous like values specified for index 1 then index 10 and so on. But, in case they are continuous, we can use array iteration to access elements of the array. A simple array iteration for printing elements of the array is shown below." }, { "code": null, "e": 29636, "s": 29441, "text": "#!/usr/bin/tclsh\n\nset languages(0) Tcl\nset languages(1) \"C Language\"\nfor { set index 0 } { $index < [array size languages] } { incr index } {\n puts \"languages($index) : $languages($index)\"\n}" }, { "code": null, "e": 29704, "s": 29636, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 29750, "s": 29704, "text": "languages(0) : Tcl\nlanguages(1) : C Language\n" }, { "code": null, "e": 30033, "s": 29750, "text": "In Tcl, all arrays by nature are associative. Arrays are stored and retrieved without any specific order. Associative arrays have an index that is not necessarily a number, and can be sparsely populated. A simple example for associative array with non-number indices is shown below." }, { "code": null, "e": 30137, "s": 30033, "text": "#!/usr/bin/tclsh\n\nset personA(Name) \"Dave\"\nset personA(Age) 14\nputs $personA(Name)\nputs $personA(Age)" }, { "code": null, "e": 30205, "s": 30137, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 30214, "s": 30205, "text": "Dave\n14\n" }, { "code": null, "e": 30273, "s": 30214, "text": "The syntax for retrieving indices of array is shown below." }, { "code": null, "e": 30300, "s": 30273, "text": "[array names variablename]" }, { "code": null, "e": 30349, "s": 30300, "text": "An example for printing the size is shown below." }, { "code": null, "e": 30439, "s": 30349, "text": "#!/usr/bin/tclsh\n\nset personA(Name) \"Dave\"\nset personA(Age) 14\nputs [array names personA]" }, { "code": null, "e": 30507, "s": 30439, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 30517, "s": 30507, "text": "Age Name\n" }, { "code": null, "e": 30619, "s": 30517, "text": "You can use the indices of array to iterate through the associative array. An example is shown below." }, { "code": null, "e": 30766, "s": 30619, "text": "#!/usr/bin/tclsh\n\nset personA(Name) \"Dave\"\nset personA(Age) 14\nforeach index [array names personA] {\n puts \"personA($index): $personA($index)\"\n}" }, { "code": null, "e": 30834, "s": 30766, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 30872, "s": 30834, "text": "personA(Age): 14\npersonA(Name): Dave\n" }, { "code": null, "e": 31206, "s": 30872, "text": "The primitive data-type of Tcl is string and often we can find quotes on Tcl as string only language. These strings can contain alphanumeric character, just numbers, Boolean, or even binary data. Tcl uses 16 bit unicode characters and alphanumeric characters can contain letters including non-Latin characters, number or punctuation." }, { "code": null, "e": 31297, "s": 31206, "text": "Boolean value can be represented as 1, yes or true for true and 0, no, or false for false." }, { "code": null, "e": 31414, "s": 31297, "text": "Unlike other languages, in Tcl, you need not include double quotes when it's only a single word. An example can be −" }, { "code": null, "e": 31470, "s": 31414, "text": "#!/usr/bin/tclsh\n\nset myVariable hello\nputs $myVariable" }, { "code": null, "e": 31538, "s": 31470, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 31545, "s": 31538, "text": "hello\n" }, { "code": null, "e": 31658, "s": 31545, "text": "When we want to represent multiple strings, we can use either double quotes or curly braces. It is shown below −" }, { "code": null, "e": 31768, "s": 31658, "text": "#!/usr/bin/tclsh\n\nset myVariable \"hello world\"\nputs $myVariable\nset myVariable {hello world}\nputs $myVariable" }, { "code": null, "e": 31836, "s": 31768, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 31861, "s": 31836, "text": "hello world\nhello world\n" }, { "code": null, "e": 31995, "s": 31861, "text": "A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\\t'), or a universal character (e.g., '\\u02C0')." }, { "code": null, "e": 32224, "s": 31995, "text": "There are certain characters in Tcl when they are preceded by a backslash they will have special meaning and they are used to represent like newline (\\n) or tab (\\t). Here, you have a list of some of such escape sequence codes −" }, { "code": null, "e": 32292, "s": 32224, "text": "Following is the example to show a few escape sequence characters −" }, { "code": null, "e": 32349, "s": 32292, "text": "#!/usr/bin/tclsh\n\nputs \"Hello\\tWorld\\n\\nTutorialspoint\";" }, { "code": null, "e": 32430, "s": 32349, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 32461, "s": 32430, "text": "Hello World\n\nTutorialspoint\n" }, { "code": null, "e": 32539, "s": 32461, "text": "The list of subcommands for string command is listed in the following table −" }, { "code": null, "e": 32563, "s": 32539, "text": "compare string1 string2" }, { "code": null, "e": 32673, "s": 32563, "text": "Compares string1 and string2 lexographically. Returns 0 if equal, -1 if string1 comes before string2, else 1." }, { "code": null, "e": 32695, "s": 32673, "text": "first string1 string2" }, { "code": null, "e": 32779, "s": 32695, "text": "Returns the index first occurrence of string1 in string2. If not found, returns -1." }, { "code": null, "e": 32798, "s": 32779, "text": "index string index" }, { "code": null, "e": 32830, "s": 32798, "text": "Returns the character at index." }, { "code": null, "e": 32851, "s": 32830, "text": "last string1 string2" }, { "code": null, "e": 32934, "s": 32851, "text": "Returns the index last occurrence of string1 in string2. If not found, returns -1." }, { "code": null, "e": 32948, "s": 32934, "text": "length string" }, { "code": null, "e": 32978, "s": 32948, "text": "Returns the length of string." }, { "code": null, "e": 32999, "s": 32978, "text": "match pattern string" }, { "code": null, "e": 33044, "s": 32999, "text": "Returns 1 if the string matches the pattern." }, { "code": null, "e": 33071, "s": 33044, "text": "range string index1 index2" }, { "code": null, "e": 33135, "s": 33071, "text": "Return the range of characters in string from index1 to index2." }, { "code": null, "e": 33150, "s": 33135, "text": "tolower string" }, { "code": null, "e": 33180, "s": 33150, "text": "Returns the lowercase string." }, { "code": null, "e": 33195, "s": 33180, "text": "toupper string" }, { "code": null, "e": 33225, "s": 33195, "text": "Returns the uppercase string." }, { "code": null, "e": 33254, "s": 33225, "text": "trim string ?trimcharacters?" }, { "code": null, "e": 33343, "s": 33254, "text": "Removes trimcharacters in both ends of string. The default trimcharacters is whitespace." }, { "code": null, "e": 33376, "s": 33343, "text": "trimleft string ?trimcharacters?" }, { "code": null, "e": 33470, "s": 33376, "text": "Removes trimcharacters in left beginning of string. The default trimcharacters is whitespace." }, { "code": null, "e": 33504, "s": 33470, "text": "trimright string ?trimcharacters?" }, { "code": null, "e": 33592, "s": 33504, "text": "Removes trimcharacters in left end of string. The default trimcharacters is whitespace." }, { "code": null, "e": 33617, "s": 33592, "text": "wordend findstring index" }, { "code": null, "e": 33715, "s": 33617, "text": "Return the index in findstring of the character after the word containing the character at index." }, { "code": null, "e": 33742, "s": 33715, "text": "wordstart findstring index" }, { "code": null, "e": 33843, "s": 33742, "text": "Return the index in findstring of the first character in the word containing the character at index." }, { "code": null, "e": 33915, "s": 33843, "text": "Examples of some commonly used Tcl string sub commands are given below." }, { "code": null, "e": 34265, "s": 33915, "text": "#!/usr/bin/tclsh\n\nset s1 \"Hello\"\nset s2 \"World\"\nset s3 \"World\"\nputs [string compare $s1 $s2]\nif {[string compare $s2 $s3] == 0} {\n puts \"String \\'s1\\' and \\'s2\\' are same.\";\n}\n\nif {[string compare $s1 $s2] == -1} {\n puts \"String \\'s1\\' comes before \\'s2\\'.\";\n}\n\nif {[string compare $s2 $s1] == 1} {\n puts \"String \\'s2\\' comes after \\'s1\\'.\";\n}" }, { "code": null, "e": 34346, "s": 34265, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 34442, "s": 34346, "text": "-1\nString 's1' and 's2' are same.\nString 's1' comes before 's2'.\nString 's2' comes after 's1'.\n" }, { "code": null, "e": 34798, "s": 34442, "text": "#!/usr/bin/tclsh\n\nset s1 \"Hello World\"\nset s2 \"o\"\nputs \"First occurrence of $s2 in s1\"\nputs [string first $s2 $s1]\nputs \"Character at index 0 in s1\"\nputs [string index $s1 0]\nputs \"Last occurrence of $s2 in s1\"\nputs [string last $s2 $s1]\nputs \"Word end index in s1\"\nputs [string wordend $s1 20]\nputs \"Word start index in s1\"\nputs [string wordstart $s1 20]" }, { "code": null, "e": 34879, "s": 34798, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 35017, "s": 34879, "text": "First occurrence of o in s1\n4\nCharacter at index 0 in s1\nH\nLast occurrence of o in s1\n7\nWord end index in s1\n11\nWord start index in s1\n6\n" }, { "code": null, "e": 35108, "s": 35017, "text": "#!/usr/bin/tclsh\n\nset s1 \"Hello World\"\nputs \"Length of string s1\"\nputs [string length $s1]" }, { "code": null, "e": 35189, "s": 35108, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 35213, "s": 35189, "text": "Length of string s1\n11\n" }, { "code": null, "e": 35364, "s": 35213, "text": "#!/usr/bin/tclsh\n\nset s1 \"Hello World\"\nputs \"Uppercase string of s1\"\nputs [string toupper $s1]\nputs \"Lowercase string of s1\"\nputs [string tolower $s1]" }, { "code": null, "e": 35445, "s": 35364, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 35516, "s": 35445, "text": "Uppercase string of s1\nHELLO WORLD\nLowercase string of s1\nhello world\n" }, { "code": null, "e": 35814, "s": 35516, "text": "#!/usr/bin/tclsh\n\nset s1 \"Hello World\"\nset s2 \"World\"\nputs \"Trim right $s2 in $s1\"\nputs [string trimright $s1 $s2]\n\nset s2 \"Hello\"\nputs \"Trim left $s2 in $s1\"\nputs [string trimleft $s1 $s2]\n\nset s1 \" Hello World \"\nset s2 \" \"\nputs \"Trim characters s1 on both sides of s2\"\nputs [string trim $s1 $s2]" }, { "code": null, "e": 35895, "s": 35814, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 36024, "s": 35895, "text": "Trim right World in Hello World\nHello \nTrim left Hello in Hello World\n World\nTrim characters s1 on both sides of s2\nHello World\n" }, { "code": null, "e": 36215, "s": 36024, "text": "#!/usr/bin/tclsh\n\nset s1 \"test@test.com\" \nset s2 \"*@*.com\"\nputs \"Matching pattern s2 in s1\"\nputs [string match \"*@*.com\" $s1 ]\nputs \"Matching pattern tcl in s1\"\nputs [string match {tcl} $s1]" }, { "code": null, "e": 36296, "s": 36215, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 36354, "s": 36296, "text": "Matching pattern s2 in s1\n1\nMatching pattern tcl in s1\n0\n" }, { "code": null, "e": 36416, "s": 36354, "text": "#!/usr/bin/tclsh\n\nset s1 \"Hello\" \nappend s1 \" World\"\nputs $s1" }, { "code": null, "e": 36497, "s": 36416, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 36510, "s": 36497, "text": "Hello World\n" }, { "code": null, "e": 36585, "s": 36510, "text": "The following table shows the list of format specifiers available in Tcl −" }, { "code": null, "e": 36624, "s": 36585, "text": "Some simple examples are given below −" }, { "code": null, "e": 36775, "s": 36624, "text": "#!/usr/bin/tclsh\n\nputs [format \"%f\" 43.5]\nputs [format \"%e\" 43.5]\nputs [format \"%d %s\" 4 tuts]\nputs [format \"%s\" \"Tcl Language\"]\nputs [format \"%x\" 40]" }, { "code": null, "e": 36856, "s": 36775, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 36903, "s": 36856, "text": "43.500000\n4.350000e+01\n4 tuts\nTcl Language\n28\n" }, { "code": null, "e": 37007, "s": 36903, "text": "Scan command is used for parsing a string based to the format specifier. Some examples are shown below." }, { "code": null, "e": 37140, "s": 37007, "text": "#!/usr/bin/tclsh\n\nputs [scan \"90\" {%[0-9]} m]\nputs [scan \"abc\" {%[a-z]} m]\nputs [scan \"abc\" {%[A-Z]} m]\nputs [scan \"ABC\" {%[A-Z]} m]" }, { "code": null, "e": 37221, "s": 37140, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 37230, "s": 37221, "text": "1\n1\n0\n1\n" }, { "code": null, "e": 37443, "s": 37230, "text": "List is one of the basic data-type available in Tcl. It is used for representing an ordered collection of items. It can include different types of items in the same list. Further, a list can contain another list." }, { "code": null, "e": 37649, "s": 37443, "text": "An important thing that needs to be noted is that these lists are represented as strings completely and processed to form individual items when required. So, avoid large lists and in such cases; use array." }, { "code": null, "e": 37694, "s": 37649, "text": "The general syntax for list is given below −" }, { "code": null, "e": 37858, "s": 37694, "text": "set listName { item1 item2 item3 .. itemn }\n# or\nset listName [list item1 item2 item3]\n# or \nset listName [split \"items separated by a character\" split_character]\n" }, { "code": null, "e": 37890, "s": 37858, "text": "Some examples are given below −" }, { "code": null, "e": 38070, "s": 37890, "text": "#!/usr/bin/tclsh\n\nset colorList1 {red green blue}\nset colorList2 [list red green blue]\nset colorList3 [split \"red_green_blue\" _]\nputs $colorList1\nputs $colorList2\nputs $colorList3" }, { "code": null, "e": 38138, "s": 38070, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 38184, "s": 38138, "text": "red green blue\nred green blue\nred green blue\n" }, { "code": null, "e": 38241, "s": 38184, "text": "The syntax for appending item to a list is given below −" }, { "code": null, "e": 38308, "s": 38241, "text": "append listName split_character value\n# or\nlappend listName value\n" }, { "code": null, "e": 38340, "s": 38308, "text": "Some examples are given below −" }, { "code": null, "e": 38445, "s": 38340, "text": "#!/usr/bin/tclsh\n\nset var orange\nappend var \" \" \"blue\"\nlappend var \"red\" \nlappend var \"green\" \nputs $var" }, { "code": null, "e": 38513, "s": 38445, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 38536, "s": 38513, "text": "orange blue red green\n" }, { "code": null, "e": 38583, "s": 38536, "text": "The syntax for length of list is given below −" }, { "code": null, "e": 38601, "s": 38583, "text": "llength listName\n" }, { "code": null, "e": 38645, "s": 38601, "text": "Example for length of list is given below −" }, { "code": null, "e": 38716, "s": 38645, "text": "#!/usr/bin/tclsh\n\nset var {orange blue red green}\nputs [llength $var] " }, { "code": null, "e": 38784, "s": 38716, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 38787, "s": 38784, "text": "4\n" }, { "code": null, "e": 38857, "s": 38787, "text": "The syntax for selecting list item at specific index is given below −" }, { "code": null, "e": 38880, "s": 38857, "text": "lindex listname index\n" }, { "code": null, "e": 38928, "s": 38880, "text": "Example for list item at index is given below −" }, { "code": null, "e": 39000, "s": 38928, "text": "#!/usr/bin/tclsh\n\nset var {orange blue red green}\nputs [lindex $var 1]" }, { "code": null, "e": 39068, "s": 39000, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 39074, "s": 39068, "text": "blue\n" }, { "code": null, "e": 39144, "s": 39074, "text": "The syntax for inserting list items at specific index is given below." }, { "code": null, "e": 39190, "s": 39144, "text": "linsert listname index value1 value2..valuen\n" }, { "code": null, "e": 39256, "s": 39190, "text": "Example for inserting list item at specific index is given below." }, { "code": null, "e": 39354, "s": 39256, "text": "#!/usr/bin/tclsh\n\nset var {orange blue red green}\nset var [linsert $var 3 black white]\nputs $var" }, { "code": null, "e": 39422, "s": 39354, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 39457, "s": 39422, "text": "orange blue red black white green\n" }, { "code": null, "e": 39530, "s": 39457, "text": "The syntax for replacing list items at specific indices is given below −" }, { "code": null, "e": 39592, "s": 39530, "text": "lreplace listname firstindex lastindex value1 value2..valuen\n" }, { "code": null, "e": 39661, "s": 39592, "text": "Example for replacing list items at specific indices is given below." }, { "code": null, "e": 39761, "s": 39661, "text": "#!/usr/bin/tclsh\n\nset var {orange blue red green}\nset var [lreplace $var 2 3 black white]\nputs $var" }, { "code": null, "e": 39829, "s": 39761, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 39854, "s": 39829, "text": "orange blue black white\n" }, { "code": null, "e": 39922, "s": 39854, "text": "The syntax for setting list item at specific index is given below −" }, { "code": null, "e": 39950, "s": 39922, "text": "lset listname index value \n" }, { "code": null, "e": 40015, "s": 39950, "text": "Example for setting list item at specific index is given below −" }, { "code": null, "e": 40093, "s": 40015, "text": "#!/usr/bin/tclsh\n\nset var {orange blue red green}\nlset var 0 black \nputs $var" }, { "code": null, "e": 40161, "s": 40093, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 40183, "s": 40161, "text": "black blue red green\n" }, { "code": null, "e": 40243, "s": 40183, "text": "The syntax for copying values to variables is given below −" }, { "code": null, "e": 40293, "s": 40243, "text": "lassign listname variable1 variable2.. variablen\n" }, { "code": null, "e": 40355, "s": 40293, "text": "Example for transforming list into variables is given below −" }, { "code": null, "e": 40462, "s": 40355, "text": "#!/usr/bin/tclsh\n\nset var {orange blue red green}\nlassign $var colour1 colour2\nputs $colour1\nputs $colour2" }, { "code": null, "e": 40530, "s": 40462, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 40543, "s": 40530, "text": "orange\nblue\n" }, { "code": null, "e": 40590, "s": 40543, "text": "The syntax for sorting a list is given below −" }, { "code": null, "e": 40606, "s": 40590, "text": "lsort listname\n" }, { "code": null, "e": 40653, "s": 40606, "text": "An example for sorting a list is given below −" }, { "code": null, "e": 40734, "s": 40653, "text": "#!/usr/bin/tclsh\n\nset var {orange blue red green}\nset var [lsort $var]\nputs $var" }, { "code": null, "e": 40802, "s": 40734, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 40825, "s": 40802, "text": "blue green orange red\n" }, { "code": null, "e": 40944, "s": 40825, "text": "A dictionary is an arrangement for mapping values to keys. The syntax for the conventional dictionary is shown below −" }, { "code": null, "e": 41039, "s": 40944, "text": "dict set dictname key value\n# or \ndict create dictname key1 value1 key2 value2 .. keyn valuen\n" }, { "code": null, "e": 41097, "s": 41039, "text": "Some examples for creating a dictionary are shown below −" }, { "code": null, "e": 41279, "s": 41097, "text": "#!/usr/bin/tclsh\n\ndict set colours colour1 red \nputs $colours\ndict set colours colour2 green\nputs $colours\n\nset colours [dict create colour1 \"black\" colour2 \"white\"]\nputs $colours" }, { "code": null, "e": 41347, "s": 41279, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 41414, "s": 41347, "text": "colour1 red\ncolour1 red colour2 green\ncolour1 black colour2 white\n" }, { "code": null, "e": 41467, "s": 41414, "text": "The syntax for getting size of dict is shown below −" }, { "code": null, "e": 41489, "s": 41467, "text": "[dict size dictname]\n" }, { "code": null, "e": 41539, "s": 41489, "text": "An example for printing the size is shown below −" }, { "code": null, "e": 41641, "s": 41539, "text": "#!/usr/bin/tclsh\n\nset colours [dict create colour1 \"black\" colour2 \"white\"]\nputs [dict size $colours]" }, { "code": null, "e": 41709, "s": 41641, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 41712, "s": 41709, "text": "2\n" }, { "code": null, "e": 41806, "s": 41712, "text": "A simple dictionary iteration for printing keys and valued of the dictionary is shown below −" }, { "code": null, "e": 41974, "s": 41806, "text": "#!/usr/bin/tclsh\n\nset colours [dict create colour1 \"black\" colour2 \"white\"]\nforeach item [dict keys $colours] {\n set value [dict get $colours $item]\n puts $value\n}" }, { "code": null, "e": 42042, "s": 41974, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 42055, "s": 42042, "text": "black\nwhite\n" }, { "code": null, "e": 42120, "s": 42055, "text": "The syntax for retrieving value for key in dict is shown below −" }, { "code": null, "e": 42151, "s": 42120, "text": "[dict get $dictname $keyname]\n" }, { "code": null, "e": 42208, "s": 42151, "text": "An example for retrieving value for key is given below −" }, { "code": null, "e": 42334, "s": 42208, "text": "#!/usr/bin/tclsh\n\nset colours [dict create colour1 \"black\" colour2 \"white\"]\nset value [dict get $colours colour1]\nputs $value" }, { "code": null, "e": 42402, "s": 42334, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 42409, "s": 42402, "text": "black\n" }, { "code": null, "e": 42469, "s": 42409, "text": "The syntax for retrieving all keys in dict is shown below −" }, { "code": null, "e": 42492, "s": 42469, "text": "[dict keys $dictname]\n" }, { "code": null, "e": 42542, "s": 42492, "text": "An example for printing all keys is shown below −" }, { "code": null, "e": 42659, "s": 42542, "text": "#!/usr/bin/tclsh\n\nset colours [dict create colour1 \"black\" colour2 \"white\"]\nset keys [dict keys $colours]\nputs $keys" }, { "code": null, "e": 42727, "s": 42659, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 42744, "s": 42727, "text": "colour1 colour2\n" }, { "code": null, "e": 42806, "s": 42744, "text": "The syntax for retrieving all values in dict is shown below −" }, { "code": null, "e": 42831, "s": 42806, "text": "[dict values $dictname]\n" }, { "code": null, "e": 42883, "s": 42831, "text": "An example for printing all values is shown below −" }, { "code": null, "e": 43006, "s": 42883, "text": "#!/usr/bin/tclsh\n\nset colours [dict create colour1 \"black\" colour2 \"white\"]\nset values [dict values $colours]\nputs $values" }, { "code": null, "e": 43074, "s": 43006, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 43087, "s": 43074, "text": "black white\n" }, { "code": null, "e": 43152, "s": 43087, "text": "The syntax for checking if a key exists in dict is shown below −" }, { "code": null, "e": 43182, "s": 43152, "text": "[dict exists $dictname $key]\n" }, { "code": null, "e": 43247, "s": 43182, "text": "An example for checking if a key exists in dict is shown below −" }, { "code": null, "e": 43378, "s": 43247, "text": "#!/usr/bin/tclsh\n\nset colours [dict create colour1 \"black\" colour2 \"white\"]\nset result [dict exists $colours colour1]\nputs $result" }, { "code": null, "e": 43446, "s": 43378, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 43449, "s": 43446, "text": "1\n" }, { "code": null, "e": 43767, "s": 43449, "text": "Procedures are nothing but code blocks with series of commands that provide a specific reusable functionality. It is used to avoid same code being repeated in multiple locations. Procedures are equivalent to the functions used in many programming languages and are made available in Tcl with the help of proc command." }, { "code": null, "e": 43826, "s": 43767, "text": "The syntax of creating a simple procedure is shown below −" }, { "code": null, "e": 43870, "s": 43826, "text": "proc procedureName {arguments} {\n body\n}\n" }, { "code": null, "e": 43918, "s": 43870, "text": "A simple example for procedure is given below −" }, { "code": null, "e": 43994, "s": 43918, "text": "#!/usr/bin/tclsh\n\nproc helloWorld {} {\n puts \"Hello, World!\"\n}\nhelloWorld" }, { "code": null, "e": 44062, "s": 43994, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 44077, "s": 44062, "text": "Hello, World!\n" }, { "code": null, "e": 44134, "s": 44077, "text": "An example for procedure with arguments is shown below −" }, { "code": null, "e": 44211, "s": 44134, "text": "#!/usr/bin/tclsh\n\nproc add {a b} {\n return [expr $a+$b]\n}\nputs [add 10 30]" }, { "code": null, "e": 44279, "s": 44211, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 44283, "s": 44279, "text": "40\n" }, { "code": null, "e": 44340, "s": 44283, "text": "An example for procedure with arguments is shown below −" }, { "code": null, "e": 44578, "s": 44340, "text": "#!/usr/bin/tclsh\n\nproc avg {numbers} {\n set sum 0\n foreach number $numbers {\n set sum [expr $sum + $number]\n }\n set average [expr $sum/[llength $numbers]]\n return $average\n}\nputs [avg {70 80 50 60}]\nputs [avg {70 80 50 }]" }, { "code": null, "e": 44646, "s": 44578, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 44653, "s": 44646, "text": "65\n66\n" }, { "code": null, "e": 44864, "s": 44653, "text": "Default arguments are used to provide default values that can be used if no value is provided. An example for procedure with default arguments, which is sometimes referred as implicit arguments is shown below −" }, { "code": null, "e": 44962, "s": 44864, "text": "#!/usr/bin/tclsh\n\nproc add {a {b 100} } {\n return [expr $a+$b]\n}\nputs [add 10 30]\nputs [add 10]" }, { "code": null, "e": 45030, "s": 44962, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 45038, "s": 45030, "text": "40\n110\n" }, { "code": null, "e": 45091, "s": 45038, "text": "An example for recursive procedures is shown below −" }, { "code": null, "e": 45278, "s": 45091, "text": "#!/usr/bin/tclsh\n\nproc factorial {number} {\n if {$number <= 1} {\n return 1\n } \n return [expr $number * [factorial [expr $number - 1]]]\n\n}\nputs [factorial 3]\nputs [factorial 5]" }, { "code": null, "e": 45346, "s": 45278, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 45353, "s": 45346, "text": "6\n120\n" }, { "code": null, "e": 45682, "s": 45353, "text": "Packages are used for creating reusable units of code. A package consists of a collection of files that provide specific functionality. This collection of files is identified by a package name and can have multiple versions of same files. The package can be a collection of Tcl scripts, binary library, or a combination of both." }, { "code": null, "e": 45827, "s": 45682, "text": "Package uses the concept of namespace to avoid collision of variable names and procedure names. Check out more in our next 'namespace' tutorial." }, { "code": null, "e": 45995, "s": 45827, "text": "A package can be created with the help of minimum two files. One file contains the package code. Other file contains the index package file for declaring your package." }, { "code": null, "e": 46060, "s": 45995, "text": "The list of steps for creating and using package is given below." }, { "code": null, "e": 46184, "s": 46060, "text": "Create code for package inside a folder say HelloWorld. Let the file be named HelloWorld.tcl with the code as shown below −" }, { "code": null, "e": 46718, "s": 46184, "text": "# /Users/rajkumar/Desktop/helloworld/HelloWorld.tcl \n# Create the namespace\nnamespace eval ::HelloWorld {\n \n # Export MyProcedure\n namespace export MyProcedure\n \n # My Variables\n set version 1.0\n set MyDescription \"HelloWorld\"\n \n # Variable for the path of the script\n variable home [file join [pwd] [file dirname [info script]]]\n \n}\n \n# Definition of the procedure MyProcedure\nproc ::HelloWorld::MyProcedure {} {\n puts $HelloWorld::MyDescription\n}\n\npackage provide HelloWorld $HelloWorld::version\npackage require Tcl 8.0" }, { "code": null, "e": 46835, "s": 46718, "text": "Open tclsh. Switch to HelloWorld directory and use the pkg_mkIndex command to create the index file as shown below −" }, { "code": null, "e": 46899, "s": 46835, "text": "% cd /Users/rajkumar/Desktop/helloworld \n% pkg_mkIndex . *.tcl\n" }, { "code": null, "e": 46978, "s": 46899, "text": "Use the lappend command to add the package to the global list as shown below −" }, { "code": null, "e": 47036, "s": 46978, "text": "% lappend auto_path \"/Users/rajkumar/Desktop/helloworld\"\n" }, { "code": null, "e": 47113, "s": 47036, "text": "Next add package to program using package require statement as shown below −" }, { "code": null, "e": 47147, "s": 47113, "text": "% package require HelloWorld 1.0\n" }, { "code": null, "e": 47221, "s": 47147, "text": "Now, everything being setup, we can invoke our procedure as shown below −" }, { "code": null, "e": 47255, "s": 47221, "text": "% puts [HelloWorld::MyProcedure]\n" }, { "code": null, "e": 47291, "s": 47255, "text": "You will get the following result −" }, { "code": null, "e": 47303, "s": 47291, "text": "HelloWorld\n" }, { "code": null, "e": 47448, "s": 47303, "text": "First two steps create the package. Once package is created, you can use it in any Tcl file by adding the last three statements as shown below −" }, { "code": null, "e": 47566, "s": 47448, "text": "lappend auto_path \"/Users/rajkumar/Desktop/helloworld\"\npackage require HelloWorld 1.0\nputs [HelloWorld::MyProcedure]\n" }, { "code": null, "e": 47602, "s": 47566, "text": "You will get the following result −" }, { "code": null, "e": 47614, "s": 47602, "text": "HelloWorld\n" }, { "code": null, "e": 47899, "s": 47614, "text": "Namespace is a container for set of identifiers that is used to group variables and procedures. Namespaces are available from Tcl version 8.0. Before the introduction of the namespaces, there was single global scope. Now with namespaces, we have additional partitions of global scope." }, { "code": null, "e": 48008, "s": 47899, "text": "Namespaces are created using the namespace command. A simple example for creating namespace is shown below −" }, { "code": null, "e": 48271, "s": 48008, "text": "#!/usr/bin/tclsh\n\nnamespace eval MyMath {\n # Create a variable inside the namespace\n variable myResult\n}\n\n# Create procedures inside the namespace\nproc MyMath::Add {a b } { \n set ::MyMath::myResult [expr $a + $b]\n}\nMyMath::Add 10 23\n\nputs $::MyMath::myResult" }, { "code": null, "e": 48339, "s": 48271, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 48343, "s": 48339, "text": "33\n" }, { "code": null, "e": 48550, "s": 48343, "text": "In the above program, you can see there is a namespace with a variable myResult and a procedure Add. This makes it possible to create variables and procedures with the same names under different namespaces." }, { "code": null, "e": 48641, "s": 48550, "text": "Tcl allows nesting of namespaces. A simple example for nesting namespaces is given below −" }, { "code": null, "e": 49070, "s": 48641, "text": "#!/usr/bin/tclsh\n\nnamespace eval MyMath {\n # Create a variable inside the namespace\n variable myResult\n}\n\nnamespace eval extendedMath {\n # Create a variable inside the namespace\n namespace eval MyMath {\n # Create a variable inside the namespace\n variable myResult\n }\n}\nset ::MyMath::myResult \"test1\"\nputs $::MyMath::myResult\nset ::extendedMath::MyMath::myResult \"test2\"\nputs $::extendedMath::MyMath::myResult" }, { "code": null, "e": 49138, "s": 49070, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 49151, "s": 49138, "text": "test1\ntest2\n" }, { "code": null, "e": 49356, "s": 49151, "text": "You can see in the previous namespace examples, we use a lot of scope resolution operator and it's more complex to use. We can avoid this by importing and exporting namespaces. An example is given below −" }, { "code": null, "e": 49631, "s": 49356, "text": "#!/usr/bin/tclsh\n\nnamespace eval MyMath {\n # Create a variable inside the namespace\n variable myResult\n namespace export Add\n}\n\n# Create procedures inside the namespace\nproc MyMath::Add {a b } { \n return [expr $a + $b]\n}\n\nnamespace import MyMath::*\nputs [Add 10 30]" }, { "code": null, "e": 49699, "s": 49631, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 49703, "s": 49699, "text": "40\n" }, { "code": null, "e": 49802, "s": 49703, "text": "You can remove an imported namespace by using forget subcommand. A simple example is shown below −" }, { "code": null, "e": 50103, "s": 49802, "text": "#!/usr/bin/tclsh\n\nnamespace eval MyMath {\n # Create a variable inside the namespace\n variable myResult\n namespace export Add\n}\n\n# Create procedures inside the namespace\nproc MyMath::Add {a b } { \n return [expr $a + $b]\n}\nnamespace import MyMath::*\nputs [Add 10 30]\nnamespace forget MyMath::*" }, { "code": null, "e": 50171, "s": 50103, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 50175, "s": 50171, "text": "40\n" }, { "code": null, "e": 50276, "s": 50175, "text": "Tcl supports file handling with the help of the built in commands open, read, puts, gets, and close." }, { "code": null, "e": 50368, "s": 50276, "text": "A file represents a sequence of bytes, does not matter if it is a text file or binary file." }, { "code": null, "e": 50462, "s": 50368, "text": "Tcl uses the open command to open files in Tcl. The syntax for opening a file is as follows −" }, { "code": null, "e": 50488, "s": 50462, "text": "open fileName accessMode\n" }, { "code": null, "e": 50613, "s": 50488, "text": "Here, filename is string literal, which you will use to name your file and accessMode can have one of the following values −" }, { "code": null, "e": 50615, "s": 50613, "text": "r" }, { "code": null, "e": 50751, "s": 50615, "text": "Opens an existing text file for reading purpose and the file must exist. This is the default mode used when no accessMode is specified." }, { "code": null, "e": 50753, "s": 50751, "text": "w" }, { "code": null, "e": 50866, "s": 50753, "text": "Opens a text file for writing, if it does not exist, then a new file is created else existing file is truncated." }, { "code": null, "e": 50868, "s": 50866, "text": "a" }, { "code": null, "e": 51015, "s": 50868, "text": "Opens a text file for writing in appending mode and file must exist. Here, your program will start appending content in the existing file content." }, { "code": null, "e": 51018, "s": 51015, "text": "r+" }, { "code": null, "e": 51091, "s": 51018, "text": "Opens a text file for reading and writing both. File must exist already." }, { "code": null, "e": 51094, "s": 51091, "text": "w+" }, { "code": null, "e": 51245, "s": 51094, "text": "Opens a text file for reading and writing both. It first truncate the file to zero length if it exists otherwise create the file if it does not exist." }, { "code": null, "e": 51248, "s": 51245, "text": "a+" }, { "code": null, "e": 51415, "s": 51248, "text": "Opens a text file for reading and writing both. It creates the file if it does not exist. The reading will start from the beginning, but writing can only be appended." }, { "code": null, "e": 51492, "s": 51415, "text": "To close a file, use the close command. The syntax for close is as follows −" }, { "code": null, "e": 51509, "s": 51492, "text": "close fileName \n" }, { "code": null, "e": 51744, "s": 51509, "text": "Any file that has been opened by a program must be closed when the program finishes using that file. In most cases, the files need not be closed explicitly; they are closed automatically when File objects are terminated automatically." }, { "code": null, "e": 51791, "s": 51744, "text": "Puts command is used to write to an open file." }, { "code": null, "e": 51823, "s": 51791, "text": "puts $filename \"text to write\"\n" }, { "code": null, "e": 51878, "s": 51823, "text": "A simple example for writing to a file is shown below." }, { "code": null, "e": 51951, "s": 51878, "text": "#!/usr/bin/tclsh\n\nset fp [open \"input.txt\" w+]\nputs $fp \"test\"\nclose $fp" }, { "code": null, "e": 52115, "s": 51951, "text": "When the above code is compiled and executed, it creates a new file input.txt in the directory that it has been started under (in the program's working directory)." }, { "code": null, "e": 52169, "s": 52115, "text": "Following is the simple command to read from a file −" }, { "code": null, "e": 52195, "s": 52169, "text": "set file_data [read $fp]\n" }, { "code": null, "e": 52249, "s": 52195, "text": "A complete example of read and write is shown below −" }, { "code": null, "e": 52401, "s": 52249, "text": "#!/usr/bin/tclsh\n\nset fp [open \"input.txt\" w+]\nputs $fp \"test\"\nclose $fp\nset fp [open \"input.txt\" r]\nset file_data [read $fp]\nputs $file_data\nclose $fp" }, { "code": null, "e": 52529, "s": 52401, "text": "When the above code is compiled and executed, it reads the file created in previous section and produces the following result −" }, { "code": null, "e": 52535, "s": 52529, "text": "test\n" }, { "code": null, "e": 52608, "s": 52535, "text": "Here is another example for reading file till end of file line by line −" }, { "code": null, "e": 52775, "s": 52608, "text": "#!/usr/bin/tclsh\n\nset fp [open \"input.txt\" w+]\nputs $fp \"test\\ntest\"\nclose $fp\nset fp [open \"input.txt\" r]\n\nwhile { [gets $fp data] >= 0 } {\n puts $data\n}\nclose $fp" }, { "code": null, "e": 52903, "s": 52775, "text": "When the above code is compiled and executed, it reads the file created in previous section and produces the following result −" }, { "code": null, "e": 52914, "s": 52903, "text": "test\ntest\n" }, { "code": null, "e": 53045, "s": 52914, "text": "Error handling in Tcl is provided with the help of error and catch commands. The syntax for each of these commands is shown below." }, { "code": null, "e": 53070, "s": 53045, "text": "error message info code\n" }, { "code": null, "e": 53230, "s": 53070, "text": "In the above error command syntax, message is the error message, info is set in the global variable errorInfo and code is set in the global variable errorCode." }, { "code": null, "e": 53258, "s": 53230, "text": "catch script resultVarName\n" }, { "code": null, "e": 53468, "s": 53258, "text": "In the above catch command syntax, script is the code to be executed, resultVarName is variable that holds the error or the result. The catch command returns 0 if there is no error, and 1 if there is an error." }, { "code": null, "e": 53522, "s": 53468, "text": "An example for simple error handling is shown below −" }, { "code": null, "e": 53985, "s": 53522, "text": "#!/usr/bin/tclsh\n\nproc Div {a b} {\n if {$b == 0} {\n error \"Error generated by error\" \"Info String for error\" 401\n } else {\n return [expr $a/$b]\n }\n}\n\nif {[catch {puts \"Result = [Div 10 0]\"} errmsg]} {\n puts \"ErrorMsg: $errmsg\"\n puts \"ErrorCode: $errorCode\"\n puts \"ErrorInfo:\\n$errorInfo\\n\"\n}\n\nif {[catch {puts \"Result = [Div 10 2]\"} errmsg]} {\n puts \"ErrorMsg: $errmsg\"\n puts \"ErrorCode: $errorCode\"\n puts \"ErrorInfo:\\n$errorInfo\\n\"\n}" }, { "code": null, "e": 54053, "s": 53985, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 54211, "s": 54053, "text": "ErrorMsg: Error generated by error\nErrorCode: 401\nErrorInfo:\nInfo String for error\n (procedure \"Div\" line 1)\n invoked from within\n\"Div 10 0\"\n\nResult = 5\n" }, { "code": null, "e": 54384, "s": 54211, "text": "As you can see in the above example, we can create our own custom error messages. Similarly, it is possible to catch the error generated by Tcl. An example is shown below −" }, { "code": null, "e": 54541, "s": 54384, "text": "#!/usr/bin/tclsh\n\ncatch {set file [open myNonexistingfile.txt]} result\nputs \"ErrorMsg: $result\"\nputs \"ErrorCode: $errorCode\"\nputs \"ErrorInfo:\\n$errorInfo\\n\"" }, { "code": null, "e": 54609, "s": 54541, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 54861, "s": 54609, "text": "ErrorMsg: couldn't open \"myNonexistingfile.txt\": no such file or directory\nErrorCode: POSIX ENOENT {no such file or directory}\nErrorInfo:\ncouldn't open \"myNonexistingfile.txt\": no such file or directory\n while executing\n\"open myNonexistingfile.txt\"\n" }, { "code": null, "e": 54958, "s": 54861, "text": "Tcl provides a number of built-in functions (procedures) for various operations. This includes −" }, { "code": null, "e": 54987, "s": 54958, "text": "Functions for list handling." }, { "code": null, "e": 55016, "s": 54987, "text": "Functions for list handling." }, { "code": null, "e": 55047, "s": 55016, "text": "Functions for string handling." }, { "code": null, "e": 55078, "s": 55047, "text": "Functions for string handling." }, { "code": null, "e": 55108, "s": 55078, "text": "Functions for array handling." }, { "code": null, "e": 55138, "s": 55108, "text": "Functions for array handling." }, { "code": null, "e": 55173, "s": 55138, "text": "Functions for dictionary handling." }, { "code": null, "e": 55208, "s": 55173, "text": "Functions for dictionary handling." }, { "code": null, "e": 55241, "s": 55208, "text": "Functions for File I/O handling." }, { "code": null, "e": 55274, "s": 55241, "text": "Functions for File I/O handling." }, { "code": null, "e": 55322, "s": 55274, "text": "Functions for creating namespaces and packages." }, { "code": null, "e": 55370, "s": 55322, "text": "Functions for creating namespaces and packages." }, { "code": null, "e": 55401, "s": 55370, "text": "Functions for Math operations." }, { "code": null, "e": 55432, "s": 55401, "text": "Functions for Math operations." }, { "code": null, "e": 55465, "s": 55432, "text": "Functions for System operations." }, { "code": null, "e": 55498, "s": 55465, "text": "Functions for System operations." }, { "code": null, "e": 55642, "s": 55498, "text": "Each of the above except for math and system functions are covered in earlier chapters. Math and system built-in functions are explained below." }, { "code": null, "e": 55714, "s": 55642, "text": "The math functions available in Tcl are listed in the following table −" }, { "code": null, "e": 55722, "s": 55714, "text": "abs arg" }, { "code": null, "e": 55760, "s": 55722, "text": "Calculates the absolute value of arg." }, { "code": null, "e": 55769, "s": 55760, "text": "acos arg" }, { "code": null, "e": 55802, "s": 55769, "text": "Calculates the arccosine of arg." }, { "code": null, "e": 55811, "s": 55802, "text": "asin arg" }, { "code": null, "e": 55842, "s": 55811, "text": "Calculates the arcsine of arg." }, { "code": null, "e": 55851, "s": 55842, "text": "atan arg" }, { "code": null, "e": 55885, "s": 55851, "text": "Calculates the arctangent of arg." }, { "code": null, "e": 55895, "s": 55885, "text": "atan2 y x" }, { "code": null, "e": 55960, "s": 55895, "text": "Calculates the arctangent of the quotient of its arguments(y/x)." }, { "code": null, "e": 55969, "s": 55960, "text": "ceil arg" }, { "code": null, "e": 56036, "s": 55969, "text": "Calculates the smallest integer greater than or equal to a number." }, { "code": null, "e": 56044, "s": 56036, "text": "cos arg" }, { "code": null, "e": 56074, "s": 56044, "text": "Calculates the cosine of arg." }, { "code": null, "e": 56083, "s": 56074, "text": "cosh arg" }, { "code": null, "e": 56124, "s": 56083, "text": "Calculates the hyperbolic cosine of arg." }, { "code": null, "e": 56135, "s": 56124, "text": "double arg" }, { "code": null, "e": 56267, "s": 56135, "text": "Calculates if arg is a floating-point value, returns arg, otherwise converts arg to floating-point and returns the converted value." }, { "code": null, "e": 56275, "s": 56267, "text": "exp arg" }, { "code": null, "e": 56342, "s": 56275, "text": "Calculates an exponential function (e raised to the power of arg)." }, { "code": null, "e": 56352, "s": 56342, "text": "floor arg" }, { "code": null, "e": 56410, "s": 56352, "text": "Calculates the largest integer less than or equal to arg." }, { "code": null, "e": 56419, "s": 56410, "text": "fmod x y" }, { "code": null, "e": 56519, "s": 56419, "text": "Calculates the floating-point remainder of the division of x by y. If y is 0, an error is returned." }, { "code": null, "e": 56529, "s": 56519, "text": "hypot x y" }, { "code": null, "e": 56611, "s": 56529, "text": "Calculates the length of the hypotenuse of a right-angled triangle sqrt(x*x+y*y)." }, { "code": null, "e": 56619, "s": 56611, "text": "int arg" }, { "code": null, "e": 56747, "s": 56619, "text": "Calculates if arg is an integer value of the same width as the machine word, returns arg, otherwise converts arg to an integer." }, { "code": null, "e": 56755, "s": 56747, "text": "log arg" }, { "code": null, "e": 56796, "s": 56755, "text": "Calculates the natural logarithm of arg." }, { "code": null, "e": 56806, "s": 56796, "text": "log10 arg" }, { "code": null, "e": 56847, "s": 56806, "text": "Calculates the base 10 logarithm of arg." }, { "code": null, "e": 56855, "s": 56847, "text": "pow x y" }, { "code": null, "e": 56950, "s": 56855, "text": "Calculates the value of x raised to the power y. If x is negative, y must be an integer value." }, { "code": null, "e": 56955, "s": 56950, "text": "rand" }, { "code": null, "e": 57006, "s": 56955, "text": "Calculates a pseudo-random number between 0 and 1." }, { "code": null, "e": 57016, "s": 57006, "text": "round arg" }, { "code": null, "e": 57076, "s": 57016, "text": "Calculates the value of arg rounded to the nearest integer." }, { "code": null, "e": 57084, "s": 57076, "text": "sin arg" }, { "code": null, "e": 57112, "s": 57084, "text": "Calculates the sine of arg." }, { "code": null, "e": 57121, "s": 57112, "text": "sinh arg" }, { "code": null, "e": 57160, "s": 57121, "text": "Calculates the hyperbolic sine of arg." }, { "code": null, "e": 57169, "s": 57160, "text": "sqrt arg" }, { "code": null, "e": 57226, "s": 57169, "text": "Calculates the square root of arg. arg must be positive." }, { "code": null, "e": 57236, "s": 57226, "text": "srand arg" }, { "code": null, "e": 57389, "s": 57236, "text": "Calculates a pseudo-random number between 0 and 1. The arg, which must be an integer, is used to reset the seed for the random number generator of rand." }, { "code": null, "e": 57397, "s": 57389, "text": "tan arg" }, { "code": null, "e": 57428, "s": 57397, "text": "Calculates the tangent of arg." }, { "code": null, "e": 57437, "s": 57428, "text": "tanh arg" }, { "code": null, "e": 57479, "s": 57437, "text": "Calculates the hyperbolic tangent of arg." }, { "code": null, "e": 57488, "s": 57479, "text": "wide arg" }, { "code": null, "e": 57615, "s": 57488, "text": "Calculates integer value at least 64-bits wide (by sign-extension if arg is a 32-bit number) for arg if it is not one already." }, { "code": null, "e": 57668, "s": 57615, "text": "Some examples using math functions are given below −" }, { "code": null, "e": 57835, "s": 57668, "text": "#!/usr/bin/tclsh\n\nnamespace import ::tcl::mathfunc::*\nputs [tan 10]\nputs [pow 10 2]\nputs [ceil 10.34]\nputs [hypot 10 20]\nputs [srand 45]\nputs [log 10]\nputs [srand 45]" }, { "code": null, "e": 57903, "s": 57835, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 58015, "s": 57903, "text": "0.6483608274590866\n100.0\n11.0\n22.360679774997898\n0.0003521866166741525\n2.302585092994046\n0.0003521866166741525\n" }, { "code": null, "e": 58063, "s": 58015, "text": "The important system functions in Tcl includes," }, { "code": null, "e": 58128, "s": 58063, "text": "clock − seconds function, which returns current time in seconds." }, { "code": null, "e": 58193, "s": 58128, "text": "clock − seconds function, which returns current time in seconds." }, { "code": null, "e": 58264, "s": 58193, "text": "clock − format function, which formats the seconds into date and time." }, { "code": null, "e": 58335, "s": 58264, "text": "clock − format function, which formats the seconds into date and time." }, { "code": null, "e": 58417, "s": 58335, "text": "clock − scan function, which scans the input string and converts it into seconds." }, { "code": null, "e": 58499, "s": 58417, "text": "clock − scan function, which scans the input string and converts it into seconds." }, { "code": null, "e": 58546, "s": 58499, "text": "open − function, which is used to open a file." }, { "code": null, "e": 58593, "s": 58546, "text": "open − function, which is used to open a file." }, { "code": null, "e": 58653, "s": 58593, "text": "exec − function, which is used to execute a system command." }, { "code": null, "e": 58713, "s": 58653, "text": "exec − function, which is used to execute a system command." }, { "code": null, "e": 58762, "s": 58713, "text": "close − function, which is used to close a file." }, { "code": null, "e": 58811, "s": 58762, "text": "close − function, which is used to close a file." }, { "code": null, "e": 58868, "s": 58811, "text": "Some examples for the above functions are listed below −" }, { "code": null, "e": 59245, "s": 58868, "text": "#!/usr/bin/tclsh\n\n#get seconds\nset currentTime [clock seconds]\nputs $currentTime\n#get format \nputs \"The time is: [clock format $currentTime -format %H:%M:%S]\"\nputs \"The date is: [clock format $currentTime -format %D]\"\n\nset date \"Jun 15, 2014\"\nputs [clock scan $date -format {%b %d, %Y}]\n\nputs [exec ls]\nputs [exec dir]\n\nset a [open input.txt]\nputs [read $a];\nputs $a\nclose $a" }, { "code": null, "e": 59313, "s": 59245, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 59556, "s": 59313, "text": "1402819756\nThe time is: 03:09:16\nThe date is: 06/15/2014\n1402808400\ninput.txt\nmain.tcl\ninput.txt main.tcl\nThis is the file you can use to provide input to your program and later on open\n it inside your program to process the input.\n\nfile3\n" }, { "code": null, "e": 59648, "s": 59556, "text": "The following table provides the list strings that can be used to format the date and time." }, { "code": null, "e": 59651, "s": 59648, "text": "%a" }, { "code": null, "e": 59678, "s": 59651, "text": "Day in short form, eg:Sun." }, { "code": null, "e": 59681, "s": 59678, "text": "%A" }, { "code": null, "e": 59709, "s": 59681, "text": "Day in full form eg:Sunday." }, { "code": null, "e": 59712, "s": 59709, "text": "%b" }, { "code": null, "e": 59733, "s": 59712, "text": "Month in short form." }, { "code": null, "e": 59736, "s": 59733, "text": "%B" }, { "code": null, "e": 59756, "s": 59736, "text": "Month in full form." }, { "code": null, "e": 59759, "s": 59756, "text": "%d" }, { "code": null, "e": 59773, "s": 59759, "text": "Day of month." }, { "code": null, "e": 59776, "s": 59773, "text": "%j" }, { "code": null, "e": 59796, "s": 59776, "text": "Julian day of year." }, { "code": null, "e": 59799, "s": 59796, "text": "%m" }, { "code": null, "e": 59816, "s": 59799, "text": "Month in number." }, { "code": null, "e": 59819, "s": 59816, "text": "%y" }, { "code": null, "e": 59839, "s": 59819, "text": "Year in two digits." }, { "code": null, "e": 59842, "s": 59839, "text": "%Y" }, { "code": null, "e": 59863, "s": 59842, "text": "Year in four digits." }, { "code": null, "e": 59866, "s": 59863, "text": "%H" }, { "code": null, "e": 59889, "s": 59866, "text": "Hour in 24 hour clock." }, { "code": null, "e": 59892, "s": 59889, "text": "%I" }, { "code": null, "e": 59915, "s": 59892, "text": "Hour in 12 hour clock." }, { "code": null, "e": 59918, "s": 59915, "text": "%M" }, { "code": null, "e": 59927, "s": 59918, "text": "Minutes." }, { "code": null, "e": 59930, "s": 59927, "text": "%S" }, { "code": null, "e": 59939, "s": 59930, "text": "Seconds." }, { "code": null, "e": 59942, "s": 59939, "text": "%p" }, { "code": null, "e": 59952, "s": 59942, "text": "AM or PM." }, { "code": null, "e": 59955, "s": 59952, "text": "%D" }, { "code": null, "e": 59982, "s": 59955, "text": "Date in number, mm /dd/yy." }, { "code": null, "e": 59985, "s": 59982, "text": "%r" }, { "code": null, "e": 60008, "s": 59985, "text": "Time in 12 hour clock." }, { "code": null, "e": 60012, "s": 60008, "text": "%R " }, { "code": null, "e": 60051, "s": 60012, "text": "Time in 24 hour clock without seconds." }, { "code": null, "e": 60054, "s": 60051, "text": "%T" }, { "code": null, "e": 60090, "s": 60054, "text": "Time in 24 hour clock with seconds." }, { "code": null, "e": 60093, "s": 60090, "text": "%Z" }, { "code": null, "e": 60138, "s": 60093, "text": "Time Zone Name like GMT, IST, EST and so on." }, { "code": null, "e": 60384, "s": 60138, "text": "The \"regexp\" command is used to match a regular expression in Tcl. A regular expression is a sequence of characters that contains a search pattern. It consists of multiple rules and the following table explains these rules and corresponding use." }, { "code": null, "e": 60386, "s": 60384, "text": "x" }, { "code": null, "e": 60399, "s": 60386, "text": "Exact match." }, { "code": null, "e": 60405, "s": 60399, "text": "[a-z]" }, { "code": null, "e": 60436, "s": 60405, "text": "Any lowercase letter from a-z." }, { "code": null, "e": 60438, "s": 60436, "text": "." }, { "code": null, "e": 60453, "s": 60438, "text": "Any character." }, { "code": null, "e": 60455, "s": 60453, "text": "^" }, { "code": null, "e": 60486, "s": 60455, "text": "Beginning string should match." }, { "code": null, "e": 60488, "s": 60486, "text": "$" }, { "code": null, "e": 60516, "s": 60488, "text": "Ending string should match." }, { "code": null, "e": 60519, "s": 60516, "text": "\\^" }, { "code": null, "e": 60610, "s": 60519, "text": "Backlash sequence to match special character ^.Similarly you can use for other characters." }, { "code": null, "e": 60613, "s": 60610, "text": "()" }, { "code": null, "e": 60686, "s": 60613, "text": "Add the above sequences inside parenthesis to make a regular expression." }, { "code": null, "e": 60689, "s": 60686, "text": "x*" }, { "code": null, "e": 60744, "s": 60689, "text": "Should match 0 or more occurrences of the preceding x." }, { "code": null, "e": 60747, "s": 60744, "text": "x+" }, { "code": null, "e": 60802, "s": 60747, "text": "Should match 1 or more occurrences of the preceding x." }, { "code": null, "e": 60809, "s": 60802, "text": "[a-z]?" }, { "code": null, "e": 60860, "s": 60809, "text": "Should match 0 or 1 occurrence of the preceding x." }, { "code": null, "e": 60868, "s": 60860, "text": "{digit}" }, { "code": null, "e": 60957, "s": 60868, "text": "Matches exactly digit occurrences of previous regex expression. Digit that contains 0-9." }, { "code": null, "e": 60966, "s": 60957, "text": "{digit,}" }, { "code": null, "e": 61057, "s": 60966, "text": "Matches 3 or more digit occurrences of previous regex expression. Digit that contains 0-9." }, { "code": null, "e": 61073, "s": 61057, "text": "{digit1,digit2}" }, { "code": null, "e": 61171, "s": 61073, "text": "Occurrences matches the range between digit1 and digit2 occurrences of previous regex expression." }, { "code": null, "e": 61209, "s": 61171, "text": "The syntax for regex is given below −" }, { "code": null, "e": 61290, "s": 61209, "text": "regexp optionalSwitches patterns searchString fullMatch subMatch1 ... subMatchn\n" }, { "code": null, "e": 61644, "s": 61290, "text": "Here, regex is the command. We will see about optional switches later. Patterns are the rules as mentioned earlier. Search string is the actual string on which the regex is performed. Full match is any variable to hold the result of matched regex result. Submatch1 to SubMatchn are optional subMatch variable that holds the result of sub match patterns." }, { "code": null, "e": 61850, "s": 61644, "text": "Let's look at some simple examples before diving into complex ones. A simple example for a string with any alphabets. When any other character is encountered the regex, search will be stopped and returned." }, { "code": null, "e": 61953, "s": 61850, "text": "#!/usr/bin/tclsh\n\nregexp {([A-Za-z]*)} \"Tcl Tutorial\" a b \nputs \"Full Match: $a\"\nputs \"Sub Match1: $b\"" }, { "code": null, "e": 62021, "s": 61953, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 62054, "s": 62021, "text": "Full Match: Tcl\nSub Match1: Tcl\n" }, { "code": null, "e": 62214, "s": 62054, "text": "The following example shows how to search for multiple patterns. This is example pattern for any alphabets followed by any character followed by any alphabets." }, { "code": null, "e": 62354, "s": 62214, "text": "#!/usr/bin/tclsh\n\nregexp {([A-Za-z]*).([A-Za-z]*)} \"Tcl Tutorial\" a b c \nputs \"Full Match: $a\"\nputs \"Sub Match1: $b\"\nputs \"Sub Match2: $c\"" }, { "code": null, "e": 62422, "s": 62354, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 62485, "s": 62422, "text": "Full Match: Tcl Tutorial\nSub Match1: Tcl\nSub Match2: Tutorial\n" }, { "code": null, "e": 62596, "s": 62485, "text": "A modified version of the above code to show that a sub pattern can contain multiple patterns is shown below −" }, { "code": null, "e": 62736, "s": 62596, "text": "#!/usr/bin/tclsh\n\nregexp {([A-Za-z]*.([A-Za-z]*))} \"Tcl Tutorial\" a b c \nputs \"Full Match: $a\"\nputs \"Sub Match1: $b\"\nputs \"Sub Match2: $c\"" }, { "code": null, "e": 62804, "s": 62736, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 62876, "s": 62804, "text": "Full Match: Tcl Tutorial\nSub Match1: Tcl Tutorial\nSub Match2: Tutorial\n" }, { "code": null, "e": 62919, "s": 62876, "text": "The list of switches available in Tcl are," }, { "code": null, "e": 62949, "s": 62919, "text": "nocase − Used to ignore case." }, { "code": null, "e": 62979, "s": 62949, "text": "nocase − Used to ignore case." }, { "code": null, "e": 63059, "s": 62979, "text": "indices − Store location of matched sub patterns instead of matched characters." }, { "code": null, "e": 63139, "s": 63059, "text": "indices − Store location of matched sub patterns instead of matched characters." }, { "code": null, "e": 63213, "s": 63139, "text": "line − New line sensitive matching. Ignores the characters after newline." }, { "code": null, "e": 63287, "s": 63213, "text": "line − New line sensitive matching. Ignores the characters after newline." }, { "code": null, "e": 63345, "s": 63287, "text": "start index − Sets the offset of start of search pattern." }, { "code": null, "e": 63403, "s": 63345, "text": "start index − Sets the offset of start of search pattern." }, { "code": null, "e": 63429, "s": 63403, "text": "Marks the end of switches" }, { "code": null, "e": 63455, "s": 63429, "text": "Marks the end of switches" }, { "code": null, "e": 63588, "s": 63455, "text": "In the above examples, I have deliberately used [A-Z, a-z] for all alphabets, you can easily use -nocase instead of as shown below −" }, { "code": null, "e": 63730, "s": 63588, "text": "#!/usr/bin/tclsh\n\nregexp -nocase {([A-Z]*.([A-Z]*))} \"Tcl Tutorial\" a b c \nputs \"Full Match: $a\"\nputs \"Sub Match1: $b\"\nputs \"Sub Match2: $c\"" }, { "code": null, "e": 63798, "s": 63730, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 63870, "s": 63798, "text": "Full Match: Tcl Tutorial\nSub Match1: Tcl Tutorial\nSub Match2: Tutorial\n" }, { "code": null, "e": 63918, "s": 63870, "text": "Another example using switches is shown below −" }, { "code": null, "e": 64166, "s": 63918, "text": "#!/usr/bin/tclsh\n\nregexp -nocase -line -- {([A-Z]*.([A-Z]*))} \"Tcl \\nTutorial\" a b \nputs \"Full Match: $a\"\nputs \"Sub Match1: $b\"\nregexp -nocase -start 4 -line -- {([A-Z]*.([A-Z]*))} \"Tcl \\nTutorial\" a b \nputs \"Full Match: $a\"\nputs \"Sub Match1: $b\"" }, { "code": null, "e": 64234, "s": 64166, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 64311, "s": 64234, "text": "Full Match: Tcl \nSub Match1: Tcl \nFull Match: Tutorial\nSub Match1: Tutorial\n" }, { "code": null, "e": 64651, "s": 64311, "text": "Tk refers to Toolkit and it provides cross platform GUI widgets, which helps you in building a Graphical User Interface. It was developed as an extension to Tcl scripting language by John Ousterhout. Tk remained in development independently from Tcl with version being different to each other, before, it was made in sync with Tcl in v8.0." }, { "code": null, "e": 64751, "s": 64651, "text": "It is cross platform with support for Linux, Mac OS, Unix, and Microsoft Windows operating systems." }, { "code": null, "e": 64773, "s": 64751, "text": "It is an open source." }, { "code": null, "e": 64814, "s": 64773, "text": "It provides high level of extendibility." }, { "code": null, "e": 64834, "s": 64814, "text": "It is customizable." }, { "code": null, "e": 64854, "s": 64834, "text": "It is configurable." }, { "code": null, "e": 64893, "s": 64854, "text": "It provides a large number of widgets." }, { "code": null, "e": 64955, "s": 64893, "text": "It can be used with other dynamic languages and not just Tcl." }, { "code": null, "e": 64993, "s": 64955, "text": "GUI looks identical across platforms." }, { "code": null, "e": 65050, "s": 64993, "text": "Large successful applications have been built in Tcl/Tk." }, { "code": null, "e": 65080, "s": 65050, "text": "Dashboard Soft User Interface" }, { "code": null, "e": 65108, "s": 65080, "text": "Forms GUI for Relational DB" }, { "code": null, "e": 65137, "s": 65108, "text": "Ad Hoc GUI for Relational DB" }, { "code": null, "e": 65169, "s": 65137, "text": "Software/Hardware System Design" }, { "code": null, "e": 65193, "s": 65169, "text": "Xtask - Task Management" }, { "code": null, "e": 65220, "s": 65193, "text": "Musicology with Tcl and Tk" }, { "code": null, "e": 65233, "s": 65220, "text": "Calender app" }, { "code": null, "e": 65241, "s": 65233, "text": "Tk mail" }, { "code": null, "e": 65253, "s": 65241, "text": "Tk Debugger" }, { "code": null, "e": 65497, "s": 65253, "text": "Generally, all Mac and Linux mac come with Tk pre-installed. In case, it's not available or you need the latest version, then you may need to install it. Windows don't come with Tcl/Tk and you may need to use its specific binary to install it." }, { "code": null, "e": 65702, "s": 65497, "text": "It is just a small program that enables you to type Tk commands and have them executed line by line. It stops execution of a tcl file in case, it encounters an error unlike a compiler that executes fully." }, { "code": null, "e": 65817, "s": 65702, "text": "Let's have a helloWorld.tcl file as follows. We will use this as first program, we run on the platform you choose." }, { "code": null, "e": 65884, "s": 65817, "text": "#!/usr/bin/wish\n\ngrid [ttk::button .mybutton -text \"Hello World\"] " }, { "code": null, "e": 65978, "s": 65884, "text": "The following section explains only how to install Tcl/Tk on each of the available platforms." }, { "code": null, "e": 66138, "s": 65978, "text": "Download the latest version for windows installer from the list of Active Tcl/Tk binaries available. Active Tcl/Tk community edition is free for personal use." }, { "code": null, "e": 66254, "s": 66138, "text": "Run the downloaded executable to install the Tcl and Tk, which can be done by following the on screen instructions." }, { "code": null, "e": 66398, "s": 66254, "text": "Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using cd and then using the following step −" }, { "code": null, "e": 66427, "s": 66398, "text": "C:\\Tcl> wish helloWorld.tcl\n" }, { "code": null, "e": 66482, "s": 66427, "text": "Press enter and we will see an output as shown below −" }, { "code": null, "e": 66681, "s": 66482, "text": "Most Linux operating systems comes with Tk inbuilt and you can get started right away in those systems. In case, it's not available, you can use the following command to download and install Tcl-Tk." }, { "code": null, "e": 66703, "s": 66681, "text": "$ yum install tcl tk\n" }, { "code": null, "e": 66855, "s": 66703, "text": "Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using cd command and then using the following step −" }, { "code": null, "e": 66878, "s": 66855, "text": "$ wish helloWorld.tcl\n" }, { "code": null, "e": 66943, "s": 66878, "text": "Press enter and we will see an output similar to the following −" }, { "code": null, "e": 67059, "s": 66943, "text": "In case, it's not available prebuilt in your OS, you can use the following command to download and install Tcl-Tk −" }, { "code": null, "e": 67090, "s": 67059, "text": "$ sudo apt-get install tcl tk\n" }, { "code": null, "e": 67243, "s": 67090, "text": "Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using cd command and then using the following steps −" }, { "code": null, "e": 67266, "s": 67243, "text": "$ wish helloWorld.tcl\n" }, { "code": null, "e": 67331, "s": 67266, "text": "Press enter and we will see an output similar to the following −" }, { "code": null, "e": 67487, "s": 67331, "text": "Download the latest version for Mac OS X package from the list of Active Tcl/Tk binaries available. Active Tcl community edition is free for personal use." }, { "code": null, "e": 67603, "s": 67487, "text": "Run the downloaded executable to install the Active Tcl, which can be done by following the on screen instructions." }, { "code": null, "e": 67755, "s": 67603, "text": "Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using cd command and then using the following step −" }, { "code": null, "e": 67778, "s": 67755, "text": "$ wish helloWorld.tcl\n" }, { "code": null, "e": 67833, "s": 67778, "text": "Press enter and we will see an output as shown below −" }, { "code": null, "e": 68068, "s": 67833, "text": "You can use the option of installing from source files when a binary package is not available. It is generally preferred to use Tk binaries for Windows and Mac OS X, so only compilation of sources on unix based system is shown below −" }, { "code": null, "e": 68095, "s": 68068, "text": "Download the source files." }, { "code": null, "e": 68122, "s": 68095, "text": "Download the source files." }, { "code": null, "e": 68226, "s": 68122, "text": "Now, use the following commands to extract, compile and build after switching to the downloaded folder." }, { "code": null, "e": 68330, "s": 68226, "text": "Now, use the following commands to extract, compile and build after switching to the downloaded folder." }, { "code": null, "e": 68479, "s": 68330, "text": "$ tar zxf tk8.6.1-src.tar.gz\n$ cd tcl8.6.1\n$ cd unix\n$ ./configure —with-tcl=../../tcl8.6.1/unix —prefix=/opt —enable-gcc\n$ make\n$ sudo make install" }, { "code": null, "e": 68586, "s": 68479, "text": "Note − Make sure, you change the file name to the version you downloaded on commands 1 and 2 in the above." }, { "code": null, "e": 68743, "s": 68586, "text": "In Tk, we classify some of the variables as special variables and they have a predefined usage/functionality. The list of special variables is listed below." }, { "code": null, "e": 68754, "s": 68743, "text": "tk_library" }, { "code": null, "e": 68810, "s": 68754, "text": "Used for setting the location of standard Tk libraries." }, { "code": null, "e": 68824, "s": 68810, "text": "tk_patchLevel" }, { "code": null, "e": 68881, "s": 68824, "text": "Refers to the current patch level of the Tk interpreter." }, { "code": null, "e": 68896, "s": 68881, "text": "tk_strictMotif" }, { "code": null, "e": 68977, "s": 68896, "text": "When non-zero, Tk tries to adhere to Motif look-and-feel as closely as possible." }, { "code": null, "e": 68988, "s": 68977, "text": "tk_version" }, { "code": null, "e": 69013, "s": 68988, "text": "Displays the Tk version." }, { "code": null, "e": 69093, "s": 69013, "text": "The above special variables have their special meanings for the Tk interpreter." }, { "code": null, "e": 69138, "s": 69093, "text": "Lets see the examples for special variables." }, { "code": null, "e": 69172, "s": 69138, "text": "#!/usr/bin/wish\n\nputs $tk_version" }, { "code": null, "e": 69244, "s": 69172, "text": "When you run the program, you will get a similar output as shown below." }, { "code": null, "e": 69249, "s": 69244, "text": "8.5\n" }, { "code": null, "e": 69283, "s": 69249, "text": "#!/usr/bin/wish\n\nputs $tk_library" }, { "code": null, "e": 69355, "s": 69283, "text": "When you run the program, you will get a similar output as shown below." }, { "code": null, "e": 69420, "s": 69355, "text": "/Library/Frameworks/Tk.framework/Versions/8.6/Resources/Scripts\n" }, { "code": null, "e": 69457, "s": 69420, "text": "#!/usr/bin/wish\n\nputs $tk_patchLevel" }, { "code": null, "e": 69529, "s": 69457, "text": "When you run the program, you will get a similar output as shown below." }, { "code": null, "e": 69536, "s": 69529, "text": "8.6.1\n" }, { "code": null, "e": 69574, "s": 69536, "text": "#!/usr/bin/wish\n\nputs $tk_strictMotif" }, { "code": null, "e": 69646, "s": 69574, "text": "When you run the program, you will get a similar output as shown below." }, { "code": null, "e": 69649, "s": 69646, "text": "0\n" }, { "code": null, "e": 69941, "s": 69649, "text": "The basic component of a Tk-based application is called a widget. A component is also sometimes called a window, since, in Tk, \"window\" and \"widget\" are often used interchangeably. Tk is a package that provides a rich set of graphical components for creating graphical applications with Tcl." }, { "code": null, "e": 70146, "s": 69941, "text": "Tk provides a range of widgets ranging from basic GUI widgets like buttons and menus to data display widgets. The widgets are very configurable as they have default configurations making them easy to use." }, { "code": null, "e": 70425, "s": 70146, "text": "Tk applications follow a widget hierarchy where any number of widgets may be placed within another widget, and those widgets within another widget. The main widget in a Tk program is referred to as the root widget and can be created by making a new instance of the TkRoot class." }, { "code": null, "e": 70474, "s": 70425, "text": "The syntax for creating a widget is given below." }, { "code": null, "e": 70510, "s": 70474, "text": "type variableName arguments options" }, { "code": null, "e": 70724, "s": 70510, "text": "The type here refers to the widget type like button, label, and so on. Arguments can be optional and required based on individual syntax of each widget. The options range from size to formatting of each component." }, { "code": null, "e": 71189, "s": 70724, "text": "Widget uses a structure similar to naming packages. In Tk, the root window is named with a period (.) and an element in window, for example button is named .myButton1. The variable name should start with a lowercase letter, digit, or punctuation mark (except a period). After the first character, other characters may be uppercase or lowercase letters, numbers, or punctuation marks (except periods). It is recommended to use a lowercase letter to start the label." }, { "code": null, "e": 71360, "s": 71189, "text": "The colors can be declared using name like red, green, and so on. It can also use hexadecimal representing with #. The number of hexadecimal digits can be 3, 6, 9, or 12." }, { "code": null, "e": 71526, "s": 71360, "text": "The default unit is pixels and it is used when we specify no dimension. The other dimensions are i for inches, m for millimeters, c for centimeters and p for points." }, { "code": null, "e": 71635, "s": 71526, "text": "There are so many common options available to all widgets and they are listed below in the following table −" }, { "code": null, "e": 71653, "s": 71635, "text": "-background color" }, { "code": null, "e": 71694, "s": 71653, "text": "Used to set background color for widget." }, { "code": null, "e": 71713, "s": 71694, "text": "-borderwidth width" }, { "code": null, "e": 71753, "s": 71713, "text": "Used to draw with border in 3D effects." }, { "code": null, "e": 71774, "s": 71753, "text": "-font fontDescriptor" }, { "code": null, "e": 71803, "s": 71774, "text": "Used to set font for widget." }, { "code": null, "e": 71821, "s": 71803, "text": "-foreground color" }, { "code": null, "e": 71862, "s": 71821, "text": "Used to set foreground color for widget." }, { "code": null, "e": 71877, "s": 71862, "text": "-height number" }, { "code": null, "e": 71908, "s": 71877, "text": "Used to set height for widget." }, { "code": null, "e": 71935, "s": 71908, "text": "-highlightbackground color" }, { "code": null, "e": 72034, "s": 71935, "text": "Used to set the color rectangle to draw around a widget when the widget does not have input focus." }, { "code": null, "e": 72056, "s": 72034, "text": "-highlightcolor color" }, { "code": null, "e": 72145, "s": 72056, "text": "Used to set the color rectangle to draw around a widget when the widget has input focus." }, { "code": null, "e": 72158, "s": 72145, "text": "-padx number" }, { "code": null, "e": 72188, "s": 72158, "text": "Sets the padx for the widget." }, { "code": null, "e": 72201, "s": 72188, "text": "-pady number" }, { "code": null, "e": 72231, "s": 72201, "text": "Sets the pady for the widget." }, { "code": null, "e": 72249, "s": 72231, "text": "-relief condition" }, { "code": null, "e": 72353, "s": 72249, "text": "Sets the 3D relief for this widget. The condition may be raised, sunken, flat, ridge, solid, or groove." }, { "code": null, "e": 72364, "s": 72353, "text": "-text text" }, { "code": null, "e": 72394, "s": 72364, "text": "Sets the text for the widget." }, { "code": null, "e": 72416, "s": 72394, "text": "-textvariable varName" }, { "code": null, "e": 72527, "s": 72416, "text": "Variable associated with the widget. When the text of widget changes, the variable is set with text of widget." }, { "code": null, "e": 72541, "s": 72527, "text": "-width number" }, { "code": null, "e": 72568, "s": 72541, "text": "Sets the width for widget." }, { "code": null, "e": 72613, "s": 72568, "text": "A simple example for options is shown below." }, { "code": null, "e": 72740, "s": 72613, "text": "#!/usr/bin/wish\n\ngrid [label .myLabel -background red -text \"Hello World\" -relief ridge -borderwidth 3]\n -padx 100 -pady 100" }, { "code": null, "e": 72805, "s": 72740, "text": "When we run the above program, we will get the following output." }, { "code": null, "e": 72859, "s": 72805, "text": "The list of available widgets are categorized below −" }, { "code": null, "e": 72865, "s": 72859, "text": "Label" }, { "code": null, "e": 72908, "s": 72865, "text": "Widget for displaying single line of text." }, { "code": null, "e": 72915, "s": 72908, "text": "Button" }, { "code": null, "e": 72964, "s": 72915, "text": "Widget that is clickable and triggers an action." }, { "code": null, "e": 72970, "s": 72964, "text": "Entry" }, { "code": null, "e": 73024, "s": 72970, "text": "Widget used to accept a single line of text as input." }, { "code": null, "e": 73032, "s": 73024, "text": "Message" }, { "code": null, "e": 73078, "s": 73032, "text": "Widget for displaying multiple lines of text." }, { "code": null, "e": 73083, "s": 73078, "text": "Text" }, { "code": null, "e": 73149, "s": 73083, "text": "Widget for displaying and optionally edit multiple lines of text." }, { "code": null, "e": 73158, "s": 73149, "text": "Toplevel" }, { "code": null, "e": 73230, "s": 73158, "text": "Window with all borders and decorations provided by the Window manager." }, { "code": null, "e": 73236, "s": 73230, "text": "Frame" }, { "code": null, "e": 73276, "s": 73236, "text": "Container widget to hold other widgets." }, { "code": null, "e": 73282, "s": 73276, "text": "Place" }, { "code": null, "e": 73379, "s": 73282, "text": "Widget to hold other widgets in specific place with coordinates of its origin and an exact size." }, { "code": null, "e": 73384, "s": 73379, "text": "Pack" }, { "code": null, "e": 73470, "s": 73384, "text": "Simple widget to organize widgets in blocks before placing them in the parent widget." }, { "code": null, "e": 73475, "s": 73470, "text": "Grid" }, { "code": null, "e": 73531, "s": 73475, "text": "Widget to nest widgets packing in different directions." }, { "code": null, "e": 73543, "s": 73531, "text": "Radiobutton" }, { "code": null, "e": 73625, "s": 73543, "text": "Widget that has a set of on/off buttons and labels, one of which may be selected." }, { "code": null, "e": 73637, "s": 73625, "text": "Checkbutton" }, { "code": null, "e": 73721, "s": 73637, "text": "Widget that has a set of on/off buttons and labels, many of which may be selected.." }, { "code": null, "e": 73726, "s": 73721, "text": "Menu" }, { "code": null, "e": 73769, "s": 73726, "text": "Widget that acts as holder for menu items." }, { "code": null, "e": 73777, "s": 73769, "text": "Listbox" }, { "code": null, "e": 73853, "s": 73777, "text": "Widget that displays a list of cells, one or more of which may be selected." }, { "code": null, "e": 73860, "s": 73853, "text": "Dialog" }, { "code": null, "e": 73896, "s": 73860, "text": "Widget for displaying dialog boxes." }, { "code": null, "e": 73904, "s": 73896, "text": "Spinbox" }, { "code": null, "e": 73948, "s": 73904, "text": "Widget that allows users to choose numbers." }, { "code": null, "e": 73957, "s": 73948, "text": "Combobox" }, { "code": null, "e": 74032, "s": 73957, "text": "Widget that combines an entry with a list of choices available to the use." }, { "code": null, "e": 74041, "s": 74032, "text": "Notebook" }, { "code": null, "e": 74126, "s": 74041, "text": "Tabbed widget that helps to switch between one of several pages, using an index tab." }, { "code": null, "e": 74138, "s": 74126, "text": "Progressbar" }, { "code": null, "e": 74227, "s": 74138, "text": "Widget to provide visual feedback to the progress of a long operation like file upload." }, { "code": null, "e": 74236, "s": 74227, "text": "Treeview" }, { "code": null, "e": 74324, "s": 74236, "text": "Widget to display and allow browsing through a hierarchy of items more in form of tree." }, { "code": null, "e": 74334, "s": 74324, "text": "Scrollbar" }, { "code": null, "e": 74386, "s": 74334, "text": "Scrolling widgets without a text or canvas widgets." }, { "code": null, "e": 74392, "s": 74386, "text": "Scale" }, { "code": null, "e": 74448, "s": 74392, "text": "Scale widget to choose a numeric value through sliders." }, { "code": null, "e": 74455, "s": 74448, "text": "Canvas" }, { "code": null, "e": 74507, "s": 74455, "text": "Drawing widget for displaying graphics and images.." }, { "code": null, "e": 74569, "s": 74507, "text": "We will cover each of these widgets in the upcoming chapters." }, { "code": null, "e": 74696, "s": 74569, "text": "Basic widgets are common widgets available in almost all Tk applications. The list of available basic widgets is given below −" }, { "code": null, "e": 74739, "s": 74696, "text": "Widget for displaying single line of text." }, { "code": null, "e": 74788, "s": 74739, "text": "Widget that is clickable and triggers an action." }, { "code": null, "e": 74842, "s": 74788, "text": "Widget used to accept a single line of text as input." }, { "code": null, "e": 74888, "s": 74842, "text": "Widget for displaying multiple lines of text." }, { "code": null, "e": 74954, "s": 74888, "text": "Widget for displaying and optionally edit multiple lines of text." }, { "code": null, "e": 75016, "s": 74954, "text": "Widget used to create a frame that is a new top level window." }, { "code": null, "e": 75073, "s": 75016, "text": "A simple Tk example is shown below using basic widgets −" }, { "code": null, "e": 75435, "s": 75073, "text": "#!/usr/bin/wish\n\ngrid [label .myLabel -text \"Label Widget\" -textvariable labelText] \ngrid [text .myText -width 20 -height 5]\n.myText insert 1.0 \"Text\\nWidget\\n\"\ngrid [entry .myEntry -text \"Entry Widget\"]\ngrid [message .myMessage -background red -foreground white -text \"Message\\nWidget\"]\ngrid [button .myButton1 -text \"Button\" -command \"set labelText clicked\"]" }, { "code": null, "e": 75501, "s": 75435, "text": "When we run the above program, we will get the following output −" }, { "code": null, "e": 75766, "s": 75501, "text": "Layout widgets are used to handle layouts for the Tk application. Frame widget is used group other widgets and place, pack, and grid are layout manager to give you total control over your adding to windows. The list of available layout widgets are as shown below −" }, { "code": null, "e": 75806, "s": 75766, "text": "Container widget to hold other widgets." }, { "code": null, "e": 75903, "s": 75806, "text": "Widget to hold other widgets in specific place with coordinates of its origin and an exact size." }, { "code": null, "e": 75989, "s": 75903, "text": "Simple widget to organize widgets in blocks before placing them in the parent widget." }, { "code": null, "e": 76045, "s": 75989, "text": "Widget to nest widgets packing in different directions." }, { "code": null, "e": 76101, "s": 76045, "text": "A simple Tk example is shown below for layout widgets −" }, { "code": null, "e": 76361, "s": 76101, "text": "#!/usr/bin/wish\n\nframe .myFrame1 -background red -relief ridge -borderwidth 8 -padx 10 -pady 10\n -height 100 -width 100\nframe .myFrame2 -background blue -relief ridge -borderwidth 8 -padx 10 -pady 10\n -height 100 -width 50\npack .myFrame1 \npack .myFrame2" }, { "code": null, "e": 76427, "s": 76361, "text": "When we run the above program, we will get the following output −" }, { "code": null, "e": 76563, "s": 76427, "text": "Selection widgets are used to select different options in a Tk application. The list of available selection widgets are as shown below." }, { "code": null, "e": 76645, "s": 76563, "text": "Widget that has a set of on/off buttons and labels, one of which may be selected." }, { "code": null, "e": 76728, "s": 76645, "text": "Widget that has a set of on/off buttons and labels, many of which may be selected." }, { "code": null, "e": 76771, "s": 76728, "text": "Widget that acts as holder for menu items." }, { "code": null, "e": 76847, "s": 76771, "text": "Widget that displays a list of cells, one or more of which may be selected." }, { "code": null, "e": 76908, "s": 76847, "text": "A simple Tk example is shown below using selection widgets −" }, { "code": null, "e": 77626, "s": 76908, "text": "#!/usr/bin/wish\n\ngrid [frame .gender ]\ngrid [label .label1 -text \"Male\" -textvariable myLabel1 ] \ngrid [radiobutton .gender.maleBtn -text \"Male\" -variable gender -value \"Male\"\n -command \"set myLabel1 Male\"] -row 1 -column 2\ngrid [radiobutton .gender.femaleBtn -text \"Female\" -variable gender -value \"Female\"\n -command \"set myLabel1 Female\"] -row 1 -column 3\n.gender.maleBtn select\ngrid [label .myLabel2 -text \"Range 1 not selected\" -textvariable myLabelValue2 ] \ngrid [checkbutton .chk1 -text \"Range 1\" -variable occupied1 -command {if {$occupied1 } {\n set myLabelValue2 {Range 1 selected}\n} else {\n set myLabelValue2 {Range 1 not selected}\n} }]\nproc setLabel {text} {\n .label configure -text $text \n}" }, { "code": null, "e": 77692, "s": 77626, "text": "When we run the above program, we will get the following output −" }, { "code": null, "e": 77782, "s": 77692, "text": "Canvas is used for providing drawing areas. The syntax for canvas widget is shown below −" }, { "code": null, "e": 77809, "s": 77782, "text": "canvas canvasName options\n" }, { "code": null, "e": 77895, "s": 77809, "text": "The options available for the canvas widget are listed below in the following table −" }, { "code": null, "e": 77913, "s": 77895, "text": "-background color" }, { "code": null, "e": 77954, "s": 77913, "text": "Used to set background color for widget." }, { "code": null, "e": 77976, "s": 77954, "text": "-closeenough distance" }, { "code": null, "e": 78111, "s": 77976, "text": "Sets the closeness of mouse cursor to a displayable item. The default is 1.0 pixel. This value may be a fraction and must be positive." }, { "code": null, "e": 78137, "s": 78111, "text": "-scrollregion boundingBox" }, { "code": null, "e": 78189, "s": 78137, "text": "The bounding box for the total area of this canvas." }, { "code": null, "e": 78204, "s": 78189, "text": "-height number" }, { "code": null, "e": 78235, "s": 78204, "text": "Used to set height for widget." }, { "code": null, "e": 78249, "s": 78235, "text": "-width number" }, { "code": null, "e": 78276, "s": 78249, "text": "Sets the width for widget." }, { "code": null, "e": 78299, "s": 78276, "text": "-xscrollincrement size" }, { "code": null, "e": 78363, "s": 78299, "text": "The amount to scroll horizontally when scrolling is requested." }, { "code": null, "e": 78386, "s": 78363, "text": "-yscrollincrement size" }, { "code": null, "e": 78447, "s": 78386, "text": "The amount to scroll vertically when scrolling is requested." }, { "code": null, "e": 78499, "s": 78447, "text": "A simple example for canvas widget is shown below −" }, { "code": null, "e": 78588, "s": 78499, "text": "#!/usr/bin/wish\n\ncanvas .myCanvas -background red -width 100 -height 100 \npack .myCanvas" }, { "code": null, "e": 78654, "s": 78588, "text": "When we run the above program, we will get the following output −" }, { "code": null, "e": 78728, "s": 78654, "text": "The list of the available widgets for drawing in canvas is listed below −" }, { "code": null, "e": 78742, "s": 78728, "text": "Draws a line." }, { "code": null, "e": 78756, "s": 78742, "text": "Draws an arc." }, { "code": null, "e": 78775, "s": 78756, "text": "Draws a rectangle." }, { "code": null, "e": 78790, "s": 78775, "text": "Draws an oval." }, { "code": null, "e": 78807, "s": 78790, "text": "Draws a polygon." }, { "code": null, "e": 78821, "s": 78807, "text": "Draws a text." }, { "code": null, "e": 78837, "s": 78821, "text": "Draws a bitmap." }, { "code": null, "e": 78853, "s": 78837, "text": "Draws an image." }, { "code": null, "e": 78912, "s": 78853, "text": "An example using different canvas widgets is shown below −" }, { "code": null, "e": 79459, "s": 78912, "text": "#!/usr/bin/wish\n\ncanvas .myCanvas -background red -width 200 -height 200 \npack .myCanvas\n.myCanvas create arc 10 10 50 50 -fill yellow\n.myCanvas create line 10 30 50 50 100 10 -arrow both -fill yellow -smooth true\n -splinesteps 2\n.myCanvas create oval 50 50 100 80 -fill yellow\n.myCanvas create polygon 50 150 100 80 120 120 100 190 -fill yellow -outline green\n.myCanvas create rectangle 150 150 170 170 -fill yellow\n.myCanvas create text 170 20 -fill yellow -text \"Hello\" -font {Helvetica -18 bold}\n.myCanvas create bitmap 180 50 -bitmap info" }, { "code": null, "e": 79525, "s": 79459, "text": "When we run the above program, we will get the following output −" }, { "code": null, "e": 79684, "s": 79525, "text": "Mega widgets include many complex widgets which is often required in some large scale Tk applications. The list of available mega widgets are as shown below −" }, { "code": null, "e": 79720, "s": 79684, "text": "Widget for displaying dialog boxes." }, { "code": null, "e": 79764, "s": 79720, "text": "Widget that allows users to choose numbers." }, { "code": null, "e": 79839, "s": 79764, "text": "Widget that combines an entry with a list of choices available to the use." }, { "code": null, "e": 79924, "s": 79839, "text": "Tabbed widget that helps to switch between one of several pages, using an index tab." }, { "code": null, "e": 80013, "s": 79924, "text": "Widget to provide visual feedback to the progress of a long operation like file upload." }, { "code": null, "e": 80101, "s": 80013, "text": "Widget to display and allow browsing through a hierarchy of items more in form of tree." }, { "code": null, "e": 80153, "s": 80101, "text": "Scrolling widgets without a text or canvas widgets." }, { "code": null, "e": 80209, "s": 80153, "text": "Scale widget to choose a numeric value through sliders." }, { "code": null, "e": 80269, "s": 80209, "text": "A simple Tk example is shown below using some mega widgets." }, { "code": null, "e": 81095, "s": 80269, "text": "#!/usr/bin/wish\n\nttk::treeview .tree -columns \"Creator Year\" -displaycolumns \"Year Creator\" \n.tree heading Creator -text \"Creator\" -anchor center\n.tree heading Year -text \"Year\" -anchor center\npack .tree\n.tree insert {} end -id Languages -text \"Languages\"\n.tree insert Languages end -text C -values [list \"Dennis Ritchie\" \"1990\"]\nproc scaleMe {mywidget scaleValue} {\n\t$mywidget configure -length $scaleValue\n} \npack [scale .s2 -from 100.0 -to 200.0 -length 100 -background yellow -borderwidth 5\n -font{Helvetica -18 bold} -foreground red -width 40 -relief ridge -orien horizontal\n -variable a -command \"scaleMe .s2\" ]\npack [ttk::progressbar .p1 -orient horizontal -length 200 -mode indeterminate -value 90]\npack [ttk::progressbar .p2 -orient horizontal -length 200 -mode determinate -variable a\n -maximum 75 -value 20]" }, { "code": null, "e": 81161, "s": 81095, "text": "When we run the above program, we will get the following output −" }, { "code": null, "e": 81323, "s": 81161, "text": "There are a number of widgets that supports displaying text. Most of these provides the option of font attribute. The syntax for creating a font is shown below −" }, { "code": null, "e": 81353, "s": 81323, "text": "font create fontName options\n" }, { "code": null, "e": 81437, "s": 81353, "text": "The options available for the font create are listed below in the following table −" }, { "code": null, "e": 81456, "s": 81437, "text": "-family familyName" }, { "code": null, "e": 81481, "s": 81456, "text": "The name of font family." }, { "code": null, "e": 81494, "s": 81481, "text": "-size number" }, { "code": null, "e": 81512, "s": 81494, "text": "The size of font." }, { "code": null, "e": 81526, "s": 81512, "text": "-weight level" }, { "code": null, "e": 81547, "s": 81526, "text": "The weight for font." }, { "code": null, "e": 81601, "s": 81547, "text": "A simple example for a font creation is shown below −" }, { "code": null, "e": 81733, "s": 81601, "text": "#!/usr/bin/wish\n\nfont create myFont -family Helvetica -size 18 -weight bold \npack [label .myLabel -font myFont -text \"Hello World\"]" }, { "code": null, "e": 81799, "s": 81733, "text": "When we run the above program, we will get the following output −" }, { "code": null, "e": 81866, "s": 81799, "text": "To get all the fonts available, we can use the following command −" }, { "code": null, "e": 81904, "s": 81866, "text": "#!/usr/bin/wish\n\nputs [font families]" }, { "code": null, "e": 81970, "s": 81904, "text": "When we run the above command, we will get the following output −" }, { "code": null, "e": 85990, "s": 81970, "text": "{Abadi MT Condensed Extra Bold} {Abadi MT Condensed Light} {Al Bayan} {Al Nile}\n{Al Tarikh} {American Typewriter} {Andale Mono} Arial {Arial Black}\n{Arial Hebrew} {Arial Narrow} {Arial Rounded MT Bold} {Arial Unicode MS}\nAthelas Avenir {Avenir Next} {Avenir Next Condensed} Ayuthaya Baghdad {Bangla MN}\n{Bangla Sangam MN} {Baoli SC} Baskerville {Baskerville Old Face} Batang {Bauhaus 93}\nBeirut {Bell MT} {Bernard MT Condensed} BiauKai {Big Caslon} {Book Antiqua}\n{Bookman Old Style} {Bookshelf Symbol 7} Braggadocio {Britannic Bold} {Brush Script MT}\nCalibri {Calisto MT} Cambria {Cambria Math} Candara Century {Century Gothic}\n{Century Schoolbook} Chalkboard {Chalkboard SE} Chalkduster {Charcoal CY} Charter\nCochin {Colonna MT} {Comic Sans MS} Consolas Constantia {Cooper Black} Copperplate\n{Copperplate Gothic Bold} {Copperplate Gothic Light} Corbel {Corsiva Hebrew} Courier\n{Courier New} {Curlz MT} Damascus {DecoType Naskh} Desdemona {Devanagari MT}\n{Devanagari Sangam MN} Didot {DIN Alternate} {DIN Condensed} {Diwan Kufi} {Diwan Thuluth}\n{Edwardian Script ITC} {Engravers MT} {Euphemia UCAS} Eurostile Farah Farisi\n{Footlight MT Light} {Franklin Gothic Book} {Franklin Gothic Medium}\nFutura Gabriola Garamond {GB18030 Bitmap} {Geeza Pro} Geneva {Geneva CY}\nGeorgia {Gill Sans} {Gill Sans MT} {Gloucester MT Extra Condensed}\n{Goudy Old Style} {Gujarati MT} {Gujarati Sangam MN} Gulim GungSeo {Gurmukhi MN}\n{Gurmukhi MT} {Gurmukhi Sangam MN} Haettenschweiler {Hannotate SC} {Hannotate TC}\n{HanziPen SC} {HanziPen TC} Harrington HeadLineA Hei {Heiti SC} {Heiti TC}\nHelvetica {Helvetica CY} {Helvetica Neue} Herculanum {Hiragino Kaku Gothic Pro}\n{Hiragino Kaku Gothic ProN} {Hiragino Kaku Gothic Std} {Hiragino Kaku Gothic StdN}\n{Hiragino Maru Gothic Pro} {Hiragino Maru Gothic ProN}\n{Hiragino Mincho Pro} {Hiragino Mincho ProN} {Hiragino Sans GB}\n{Hoefler Text} Impact {Imprint MT Shadow} InaiMathi {Iowan Old Style} Kai Kailasa\n{Kaiti SC} {Kaiti TC} {Kannada MN} {Kannada Sangam MN} Kefa {Khmer MN} {Khmer Sangam MN}\n{Kino MT} Kokonor Krungthep KufiStandardGK {Lantinghei SC} {Lantinghei TC} {Lao MN}\n{Lao Sangam MN} {Libian SC} {LiHei Pro} {LiSong Pro} {Lucida Blackletter} {Lucida Bright}\n{Lucida Calligraphy} {Lucida Console} {Lucida Fax} {Lucida Grande} {Lucida Handwriting}\n{Lucida Sans} {Lucida Sans Typewriter} {Lucida Sans Unicode} {Malayalam MN}\n{Malayalam Sangam MN} Marion {Marker Felt} Marlett {Matura MT Script Capitals}\nMeiryo Menlo {Microsoft Sans Serif} Mishafi Mistral {Modern No. 20} Monaco {MS Gothic}\n{MS Mincho} {MS PGothic} {MS PMincho} {MS Reference Sans Serif} {MS Reference Specialty}\nMshtakan {MT Extra} Muna {Myanmar MN} {Myanmar Sangam MN} Nadeem {Nanum Brush Script}\n{Nanum Gothic} {Nanum Myeongjo} {Nanum Pen Script} {New Peninim MT} {News Gothic MT}\nNoteworthy Onyx Optima {Oriya MN} {Oriya Sangam MN} Osaka Palatino {Palatino Linotype}\nPapyrus PCMyungjo Perpetua {Perpetua Titling MT} PilGi {Plantagenet Cherokee}\nPlaybill PMingLiU {PT Mono} {PT Sans} {PT Sans Caption} {PT Sans Narrow} {PT Serif}\n{PT Serif Caption} Raanana Rockwell {Rockwell Extra Bold} Sana Sathu {Savoye LET}\nSeravek Silom SimSun {Sinhala MN} {Sinhala Sangam MN} Skia {Snell Roundhand} {Songti SC}\n{Songti TC} Stencil STFangsong STHeiti STIXGeneral STIXIntegralsD STIXIntegralsSm\nSTIXIntegralsUp STIXIntegralsUpD STIXIntegralsUpSm STIXNonUnicode STIXSizeFiveSym\nSTIXSizeFourSym STIXSizeOneSym STIXSizeThreeSym STIXSizeTwoSym STIXVariants STKaiti\nSTSong Superclarendon Symbol Tahoma {Tamil MN} {Tamil Sangam MN} TeamViewer8 {Telugu MN}\n{Telugu Sangam MN} Thonburi Times {Times New Roman} {Trebuchet MS} {Tw Cen MT} Verdana\nWaseem {Wawati SC} {Wawati TC} Webdings {Weibei SC} {Weibei TC} {Wide Latin} Wingdings\n{Wingdings 2} {Wingdings 3} {Xingkai SC} {Yuanti SC} YuGothic YuMincho {Yuppy SC}\n{Yuppy TC} {Zapf Dingbats} Zapfino {Apple Braille} {Apple Chancery} {Apple Color Emoji}\n{Apple LiGothic} {Apple LiSung} {Apple SD Gothic Neo} {Apple Symbols}\nAppleGothic AppleMyungjo {Monotype Corsiva} {Monotype Sorts}\n" }, { "code": null, "e": 86094, "s": 85990, "text": "The image widget is used to create and manipulate images. The syntax for creating image is as follows −" }, { "code": null, "e": 86126, "s": 86094, "text": "image create type name options\n" }, { "code": null, "e": 86204, "s": 86126, "text": "In the above syntax type is photo or bitmap and name is the image identifier." }, { "code": null, "e": 86285, "s": 86204, "text": "The options available for image create are listed below in the following table −" }, { "code": null, "e": 86300, "s": 86285, "text": "-file fileName" }, { "code": null, "e": 86333, "s": 86300, "text": "The name of the image file name." }, { "code": null, "e": 86348, "s": 86333, "text": "-height number" }, { "code": null, "e": 86379, "s": 86348, "text": "Used to set height for widget." }, { "code": null, "e": 86393, "s": 86379, "text": "-width number" }, { "code": null, "e": 86420, "s": 86393, "text": "Sets the width for widget." }, { "code": null, "e": 86433, "s": 86420, "text": "-data string" }, { "code": null, "e": 86466, "s": 86433, "text": "Image in base 64 encoded string." }, { "code": null, "e": 86517, "s": 86466, "text": "A simple example for image widget is shown below −" }, { "code": null, "e": 86713, "s": 86517, "text": "#!/usr/bin/wish\n\nimage create photo imgobj -file \"/Users/rajkumar/Desktop/F Drive/pictur/vb/Forests/\n 680049.png\" -width 400 -height 400 \npack [label .myLabel]\n.myLabel configure -image imgobj " }, { "code": null, "e": 86779, "s": 86713, "text": "When we run the above program, we will get the following output −" }, { "code": null, "e": 86854, "s": 86779, "text": "The available function for image are listed below in the following table −" }, { "code": null, "e": 86877, "s": 86854, "text": "image delete imageName" }, { "code": null, "e": 86937, "s": 86877, "text": "Deletes the image from memory and related widgets visually." }, { "code": null, "e": 86960, "s": 86937, "text": "image height imageName" }, { "code": null, "e": 86990, "s": 86960, "text": "Returns the height for image." }, { "code": null, "e": 87012, "s": 86990, "text": "image width imageName" }, { "code": null, "e": 87041, "s": 87012, "text": "Returns the width for image." }, { "code": null, "e": 87062, "s": 87041, "text": "image type imageName" }, { "code": null, "e": 87090, "s": 87062, "text": "Returns the type for image." }, { "code": null, "e": 87102, "s": 87090, "text": "image names" }, { "code": null, "e": 87145, "s": 87102, "text": "Returns the list of images live in memory." }, { "code": null, "e": 87221, "s": 87145, "text": "A simple example for using the above image widget commands is shown below −" }, { "code": null, "e": 87505, "s": 87221, "text": "#!/usr/bin/wish\n\nimage create photo imgobj -file \"/Users/rajkumar/images/680049.png\"\n -width 400 -height 400 \npack [label .myLabel]\n.myLabel configure -image imgobj\nputs [image height imgobj]\nputs [image width imgobj]\nputs [image type imgobj]\nputs [image names]\nimage delete imgobj" }, { "code": null, "e": 87653, "s": 87505, "text": "The image will be deleted visually and from memory once \"image delete imgobj\" command executes. In console, the output will be like the following −" }, { "code": null, "e": 87763, "s": 87653, "text": "400\n400\nphoto\nimgobj ::tk::icons::information ::tk::icons::error ::tk::icons::\nwarning ::tk::icons::question\n" }, { "code": null, "e": 87916, "s": 87763, "text": "Events in its simplest form is handled with the help of commands. A simple example for event handling is event handling with button and is shown below −" }, { "code": null, "e": 88042, "s": 87916, "text": "#!/usr/bin/wish\n\nproc myEvent { } {\n puts \"Event triggered\"\n}\npack [button .myButton1 -text \"Button 1\" -command myEvent]" }, { "code": null, "e": 88108, "s": 88042, "text": "When we run the above program, we will get the following output −" }, { "code": null, "e": 88177, "s": 88108, "text": "A simple program to show delay text animation event is shown below −" }, { "code": null, "e": 88497, "s": 88177, "text": "#!/usr/bin/wish\n\nproc delay {} {\n for {set j 0} {$j < 100000} {incr j} {} \n}\n\nlabel .myLabel -text \"Hello................\" -width 25\npack .myLabel\nset str \"Hello................\"\nfor {set i [string length $str]} {$i > -2} {set i [expr $i-1]} {\n .myLabel configure -text [string range $str 0 $i]\n update\n delay\n}" }, { "code": null, "e": 88573, "s": 88497, "text": "When we run the program, we will get the following output in animated way −" }, { "code": null, "e": 88623, "s": 88573, "text": "The syntax for event after delay is shown below −" }, { "code": null, "e": 88658, "s": 88623, "text": "after milliseconds number command\n" }, { "code": null, "e": 88718, "s": 88658, "text": "A simple program to show after delay event is shown below −" }, { "code": null, "e": 88849, "s": 88718, "text": "#!/usr/bin/wish\n\nproc addText {} {\n label .myLabel -text \"Hello................\" -width 25\n pack .myLabel\n}\nafter 1000 addText" }, { "code": null, "e": 88926, "s": 88849, "text": "When we run the program, we will get the following output after one second −" }, { "code": null, "e": 88998, "s": 88926, "text": "You can cancel an event using the after cancel command as shown below −" }, { "code": null, "e": 89150, "s": 88998, "text": "#!/usr/bin/wish\n\nproc addText {} {\n label .myLabel -text \"Hello................\" -width 25\n pack .myLabel\n}\nafter 1000 addText\nafter cancel addText" }, { "code": null, "e": 89199, "s": 89150, "text": "The syntax for event binding is as shown below −" }, { "code": null, "e": 89216, "s": 89199, "text": "bind arguments \n" }, { "code": null, "e": 89267, "s": 89216, "text": "#!/usr/bin/wish\n\nbind . {puts \"Key Pressed: %K \"}" }, { "code": null, "e": 89348, "s": 89267, "text": "When we run the program and press a letter X, we will get the following output −" }, { "code": null, "e": 89365, "s": 89348, "text": "Key Pressed: X \n" }, { "code": null, "e": 89426, "s": 89365, "text": "#!/usr/bin/wish\n\nbind . {puts \"Button %b Pressed : %x %y \"}" }, { "code": null, "e": 89532, "s": 89426, "text": "When we run the program and press the left mouse button, we will get an output similar to the following −" }, { "code": null, "e": 89559, "s": 89532, "text": "Button 1 Pressed : 89 90 \n" }, { "code": null, "e": 89713, "s": 89559, "text": "#!/usr/bin/wish\n\nproc myEvent { } {\n puts \"Event triggered\"\n}\npack [button .myButton1 -text \"Button 1\" -command myEvent]\nbind . \".myButton1 invoke\"" }, { "code": null, "e": 89789, "s": 89713, "text": "When we run the program and press enter, we will get the following output −" }, { "code": null, "e": 89806, "s": 89789, "text": "Event triggered\n" }, { "code": null, "e": 90031, "s": 89806, "text": "Window manager is used to handle the top level window. It helps in controlling the size, position, and other attributes of the window. In Tk, . is used to refer the main window. The syntax for window command is shown below −" }, { "code": null, "e": 90059, "s": 90031, "text": "wm option window arguments\n" }, { "code": null, "e": 90141, "s": 90059, "text": "The list of options available for Tk wm command is shown in the following table −" }, { "code": null, "e": 90167, "s": 90141, "text": "aspect windowName a b c d" }, { "code": null, "e": 90238, "s": 90167, "text": "Tries to maintain the ratio of width/height to be between a/b and c/d." }, { "code": null, "e": 90273, "s": 90238, "text": "geometry windowName geometryParams" }, { "code": null, "e": 90305, "s": 90273, "text": "Use to set geometry for window." }, { "code": null, "e": 90331, "s": 90305, "text": "grid windowName w h dx dy" }, { "code": null, "e": 90351, "s": 90331, "text": "Sets the grid size." }, { "code": null, "e": 90379, "s": 90351, "text": "group windowName leaderName" }, { "code": null, "e": 90438, "s": 90379, "text": "leaderName gives the leader of a group of related windows." }, { "code": null, "e": 90459, "s": 90438, "text": "deiconify windowName" }, { "code": null, "e": 90501, "s": 90459, "text": "Brings the screen to normal if minimized." }, { "code": null, "e": 90520, "s": 90501, "text": "iconify windowName" }, { "code": null, "e": 90542, "s": 90520, "text": "Minimizes the window." }, { "code": null, "e": 90559, "s": 90542, "text": "state windowName" }, { "code": null, "e": 90596, "s": 90559, "text": "Returns the current state of window." }, { "code": null, "e": 90616, "s": 90596, "text": "withdraw windowName" }, { "code": null, "e": 90669, "s": 90616, "text": "Unmaps the window and removes its details in memory." }, { "code": null, "e": 90697, "s": 90669, "text": "iconbitmap windowName image" }, { "code": null, "e": 90730, "s": 90697, "text": "Sets or returns the icon bitmap." }, { "code": null, "e": 90757, "s": 90730, "text": "iconPhoto windowName image" }, { "code": null, "e": 90789, "s": 90757, "text": "Sets or returns the icon photo." }, { "code": null, "e": 90822, "s": 90789, "text": "command windowName commandString" }, { "code": null, "e": 90878, "s": 90822, "text": "Records the startup command in the WM_COMMAND property." }, { "code": null, "e": 90908, "s": 90878, "text": "protocol windowName arguments" }, { "code": null, "e": 90995, "s": 90908, "text": "Register a command to handle the protocol request name, which can be WM_DELETE_WINDOW," }, { "code": null, "e": 91013, "s": 90995, "text": "WM_SAVE_YOURSELF," }, { "code": null, "e": 91045, "s": 91013, "text": "WM_TAKE_FOCUS. Eg: wm protocol." }, { "code": null, "e": 91068, "s": 91045, "text": "WM_DELETE_WINDOW Quit." }, { "code": null, "e": 91092, "s": 91068, "text": "minsize windowName size" }, { "code": null, "e": 91128, "s": 91092, "text": "Determines the minimum window size." }, { "code": null, "e": 91152, "s": 91128, "text": "maxsize windowName size" }, { "code": null, "e": 91188, "s": 91152, "text": "Determines the maximum window size." }, { "code": null, "e": 91215, "s": 91188, "text": "title windowName titleText" }, { "code": null, "e": 91248, "s": 91215, "text": "Determines the title for window." }, { "code": null, "e": 91270, "s": 91248, "text": "attributes subOptions" }, { "code": null, "e": 91344, "s": 91270, "text": "There are lots of attributes available like alpha, full screen and so on." }, { "code": null, "e": 91407, "s": 91344, "text": "Some of the above commands are used in the following example −" }, { "code": null, "e": 91545, "s": 91407, "text": "#!/usr/bin/wish\n\nwm maxsize . 800 800\nwm minsize . 300 300\nwm title . \"Hello\"\nwm attributes . -alpha \".90\" \nwm geometry . 300x200+100+100" }, { "code": null, "e": 91611, "s": 91545, "text": "When we run the above program, we will get the following output −" }, { "code": null, "e": 91725, "s": 91611, "text": "As you can see alpha is one of the attributes available. The list of commonly used subcommands are listed below −" }, { "code": null, "e": 91739, "s": 91725, "text": "-alpha number" }, { "code": null, "e": 91766, "s": 91739, "text": "Sets the alpha for window." }, { "code": null, "e": 91785, "s": 91766, "text": "-fullscreen number" }, { "code": null, "e": 91841, "s": 91785, "text": "Number can be 0 for normal screen or 1 for full screen." }, { "code": null, "e": 91857, "s": 91841, "text": "-topmost number" }, { "code": null, "e": 91920, "s": 91857, "text": "Sets or returns whether window is topmost.Value can be 0 or 1." }, { "code": null, "e": 91997, "s": 91920, "text": "We can use toplevel command to create window and an example is shown below −" }, { "code": null, "e": 92026, "s": 91997, "text": "#!/usr/bin/wish\n\ntoplevel .t" }, { "code": null, "e": 92092, "s": 92026, "text": "When we run the above program, we will get the following output −" }, { "code": null, "e": 92169, "s": 92092, "text": "We can use destroy command to destroy window and an example is shown below −" }, { "code": null, "e": 92197, "s": 92169, "text": "#!/usr/bin/wish\n\ndestroy .t" }, { "code": null, "e": 92245, "s": 92197, "text": "The above command will destroy window named .t." }, { "code": null, "e": 92447, "s": 92245, "text": "The geometry manager is used to manage the geometry of the window and other frames. We can use it to handle the position and size of the window and frames. The layout widgets are used for this purpose." }, { "code": null, "e": 92509, "s": 92447, "text": "The syntax for positioning and sizing window is shown below −" }, { "code": null, "e": 92536, "s": 92509, "text": "wm geometry . wxh+/-x+/-y\n" }, { "code": null, "e": 92763, "s": 92536, "text": "Here, w refers to width and h refers to height. It is followed by a '+' or '-' sign with number next referring to the x position on screen. Similarly the following '+' or '-' sign with number refers to the y position on screen" }, { "code": null, "e": 92822, "s": 92763, "text": "A simple example is shown below for the above Statement −." }, { "code": null, "e": 92869, "s": 92822, "text": "#!/usr/bin/wish\n\nwm geometry . 300x200+100+100" }, { "code": null, "e": 92935, "s": 92869, "text": "When we run the above program, we will get the following output −" }, { "code": null, "e": 92981, "s": 92935, "text": "The syntax for grid geometry is shown below −" }, { "code": null, "e": 93058, "s": 92981, "text": "grid gridName -column number -row number -columnspan number -rowspan number\n" }, { "code": null, "e": 93136, "s": 93058, "text": "The column, row, columnspan, or rowspan helps in providing the grid geometry." }, { "code": null, "e": 93194, "s": 93136, "text": "A simple example is shown below for the above statement −" }, { "code": null, "e": 93407, "s": 93194, "text": "#!/usr/bin/wish\n\nframe .myFrame1 -background red -height 100 -width 100\nframe .myFrame2 -background blue -height 100 -width 50\ngrid .myFrame1 -columnspan 10 -rowspan 10 -sticky w\ngrid .myFrame2 -column 10 -row 2" }, { "code": null, "e": 93473, "s": 93407, "text": "When we run the above program, we will get the following output −" }, { "code": null, "e": 93480, "s": 93473, "text": " Print" }, { "code": null, "e": 93491, "s": 93480, "text": " Add Notes" } ]
How to align text to the left in Tkinter Label?
Tkinter Label widget can be aligned using the anchor attributes. In order to calculate the accommodate spacing and alignment of the widget, anchor would help in a better way. Anchor provides several options such as N, W, S, E, NW, NE. SW, SE which can be defined in the pack manager itself. In the following example, we will align the Label text of an application to the left by adding the anchor attribute towards “w” direction. #Import the required library from tkinter import* #Create an instance of tkinter frame win= Tk() #Set the geometry win.geometry("750x250") #Create a Label Widget Label(win, text= "New Line Text", font= ('Helvetica 15 underline'), background="gray74").pack(pady=20, side= TOP, anchor="w") win.mainloop() Running the above code will align the text label widget towards Left direction.
[ { "code": null, "e": 1353, "s": 1062, "text": "Tkinter Label widget can be aligned using the anchor attributes. In order to calculate the accommodate spacing and alignment of the widget, anchor would help in a better way. Anchor provides several options such as N, W, S, E, NW, NE. SW, SE which can be defined in the pack manager itself." }, { "code": null, "e": 1492, "s": 1353, "text": "In the following example, we will align the Label text of an application to the left by adding the anchor attribute towards “w” direction." }, { "code": null, "e": 1795, "s": 1492, "text": "#Import the required library\nfrom tkinter import*\n#Create an instance of tkinter frame\nwin= Tk()\n#Set the geometry\nwin.geometry(\"750x250\")\n#Create a Label Widget\nLabel(win, text= \"New Line Text\", font= ('Helvetica 15 underline'),\nbackground=\"gray74\").pack(pady=20, side= TOP, anchor=\"w\")\nwin.mainloop()" }, { "code": null, "e": 1875, "s": 1795, "text": "Running the above code will align the text label widget towards Left direction." } ]
Program to count number of islands in a given matrix in Python
Suppose we have a binary matrix, we have to find number of islands in the matrix. Here 1 is for land and 0 is for water, so an island is a group of 1s that are neighboring and whose perimeter is surrounded by water. Here we are considering neighbors can only be horizontal or vertical, not diagonal. So, if the input is like then the output will be 4. To solve this, we will follow these steps − Define a function explore() . This will take row, col, matrix if row and col are not in range of matrix or matrix[row, col] is 0, thenreturn return matrix[row, col] := 0 explore(row + 1, col, matrix) explore(row - 1, col, matrix) explore(row, col + 1, matrix) explore(row, col - 1, matrix) From the main method, do the following − if matrix is null, thenreturn 0 return 0 islands := 0 for row in range 0 to row count of matrix, dofor col in range 0 to column count of matrix, doif matrix[row, col] is same as 1, thenislands := islands + 1explore(row, col, matrix) for col in range 0 to column count of matrix, doif matrix[row, col] is same as 1, thenislands := islands + 1explore(row, col, matrix) if matrix[row, col] is same as 1, thenislands := islands + 1explore(row, col, matrix) islands := islands + 1 explore(row, col, matrix) return islands Let us see the following implementation to get better understanding − Live Demo class Solution: def explore(self, row, col, matrix): if ( row < 0 or col < 0 or row > len(matrix) - 1 or col > len (matrix[0]) - 1 or matrix[row][col] == 0): return matrix[row][col] = 0 self.explore(row + 1, col, matrix) self.explore(row - 1, col, matrix) self.explore(row, col + 1, matrix) self.explore(row, col - 1, matrix) def solve(self, matrix): if not matrix: return 0 islands = 0 for row in range(len(matrix)): for col in range(len(matrix[0])): if matrix[row][col] == 1: islands += 1 self.explore(row, col, matrix) return islands ob = Solution() matrix = [ [1, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 1, 1, 0, 0], [0, 0, 0, 0, 0], [1, 1, 0, 1, 1], [1, 1, 1, 0, 1] ] print(ob.solve(matrix)) [ [1, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 1, 1, 0, 0], [0, 0, 0, 0, 0], [1, 1, 0, 1, 1], [1, 1, 1, 0, 1] ] 4
[ { "code": null, "e": 1362, "s": 1062, "text": "Suppose we have a binary matrix, we have to find number of islands in the matrix. Here 1 is for land and 0 is for water, so an island is a group of 1s that are neighboring and whose perimeter is surrounded by water. Here we are considering neighbors can only be horizontal or vertical, not diagonal." }, { "code": null, "e": 1387, "s": 1362, "text": "So, if the input is like" }, { "code": null, "e": 1414, "s": 1387, "text": "then the output will be 4." }, { "code": null, "e": 1458, "s": 1414, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1520, "s": 1458, "text": "Define a function explore() . This will take row, col, matrix" }, { "code": null, "e": 1599, "s": 1520, "text": "if row and col are not in range of matrix or matrix[row, col] is 0, thenreturn" }, { "code": null, "e": 1606, "s": 1599, "text": "return" }, { "code": null, "e": 1628, "s": 1606, "text": "matrix[row, col] := 0" }, { "code": null, "e": 1658, "s": 1628, "text": "explore(row + 1, col, matrix)" }, { "code": null, "e": 1688, "s": 1658, "text": "explore(row - 1, col, matrix)" }, { "code": null, "e": 1718, "s": 1688, "text": "explore(row, col + 1, matrix)" }, { "code": null, "e": 1748, "s": 1718, "text": "explore(row, col - 1, matrix)" }, { "code": null, "e": 1789, "s": 1748, "text": "From the main method, do the following −" }, { "code": null, "e": 1821, "s": 1789, "text": "if matrix is null, thenreturn 0" }, { "code": null, "e": 1830, "s": 1821, "text": "return 0" }, { "code": null, "e": 1843, "s": 1830, "text": "islands := 0" }, { "code": null, "e": 2022, "s": 1843, "text": "for row in range 0 to row count of matrix, dofor col in range 0 to column count of matrix, doif matrix[row, col] is same as 1, thenislands := islands + 1explore(row, col, matrix)" }, { "code": null, "e": 2156, "s": 2022, "text": "for col in range 0 to column count of matrix, doif matrix[row, col] is same as 1, thenislands := islands + 1explore(row, col, matrix)" }, { "code": null, "e": 2242, "s": 2156, "text": "if matrix[row, col] is same as 1, thenislands := islands + 1explore(row, col, matrix)" }, { "code": null, "e": 2265, "s": 2242, "text": "islands := islands + 1" }, { "code": null, "e": 2291, "s": 2265, "text": "explore(row, col, matrix)" }, { "code": null, "e": 2306, "s": 2291, "text": "return islands" }, { "code": null, "e": 2376, "s": 2306, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2387, "s": 2376, "text": " Live Demo" }, { "code": null, "e": 3276, "s": 2387, "text": "class Solution:\n def explore(self, row, col, matrix):\n if (\n row < 0 or col < 0 or row > len(matrix) - 1 or col > len (matrix[0]) - 1 or matrix[row][col] == 0):\n return\n matrix[row][col] = 0\n self.explore(row + 1, col, matrix)\n self.explore(row - 1, col, matrix)\n self.explore(row, col + 1, matrix)\n self.explore(row, col - 1, matrix)\n def solve(self, matrix):\n if not matrix:\n return 0\n islands = 0\n for row in range(len(matrix)):\n for col in range(len(matrix[0])):\n if matrix[row][col] == 1:\n islands += 1\n self.explore(row, col, matrix)\n return islands\nob = Solution() matrix = [\n [1, 0, 1, 0, 0],\n [0, 0, 1, 0, 0],\n [0, 1, 1, 0, 0],\n [0, 0, 0, 0, 0],\n [1, 1, 0, 1, 1],\n [1, 1, 1, 0, 1]\n]\nprint(ob.solve(matrix))" }, { "code": null, "e": 3399, "s": 3276, "text": "[\n [1, 0, 1, 0, 0],\n [0, 0, 1, 0, 0],\n [0, 1, 1, 0, 0],\n [0, 0, 0, 0, 0],\n [1, 1, 0, 1, 1],\n [1, 1, 1, 0, 1]\n]" }, { "code": null, "e": 3401, "s": 3399, "text": "4" } ]
Boyer Moore Algorithm
It is another approach of Boyer Moore Algorithm. Sometimes it is called the Good Suffix Heuristic method. For this case, a preprocessing table is created as suffix table. In this procedure, the substring or pattern is searched from the last character of the pattern. When a substring of main string matches with a substring of the pattern, it moves to find other occurrences of the matched substring. It can also move to find a prefix of the pattern which is a suffix of main string. Otherwise, it moves the whole length of the pattern. Input: Main String: “ABAAABCDBBABCDDEBCABC”, Pattern: “ABC” Output: Pattern found at position: 4 Pattern found at position: 10 Pattern found at position: 18 fullSuffixMatch(shiftArray, borderArray, pattern) Input − Array to store shift locations, the border array and the pattern to search. Output − Fill the shift array and the border array. Begin n := pattern length j := n j := n+1 borderArray[i] := j while i > 0, do while j <= n AND pattern[i-1] ≠ pattern[j-1], do if shiftArray[j] = 0, then shiftArray[j] := j-i; j := borderArray[j]; done decrease i and j by 1 borderArray[i] := j done End partialSuffixMatch(shiftArray, borderArray, pattern) Input− Array to store shift locations, the border array and the pattern to search. Output − Fill the shift array and the border array. Begin n := pattern length j := borderArray[0] for index of all characters ‘i’ of pattern, do if shiftArray[i] = 0, then shiftArray[i] := j if i = j then j := borderArray[j] done End searchPattern(text, pattern) Output − The indexes where the pattern is found Begin patLen := pattern length strLen := text size for all entries of shiftArray, do set all entries to 0 done call fullSuffixMatch(shiftArray, borderArray, pattern) call partialSuffixMatch(shiftArray, borderArray, pattern) shift := 0 while shift <= (strLen - patLen), do j := patLen -1 while j >= 0 and pattern[j] = text[shift + j], do decrease j by 1 done if j < 0, then print the shift as, there is a match shift := shift + shiftArray[0] else shift := shift + shiftArray[j+1] done End #include<iostream> using namespace std; void fullSuffixMatch(int shiftArr[], int borderArr[], string pattern) { int n = pattern.size(); //find length of pattern int i = n; int j = n+1; borderArr[i] = j; while(i > 0) { //search right when (i-1)th and (j-1)th item are not same while(j <= n && pattern[i-1] != pattern[j-1] ) { if(shiftArr[j] == 0) shiftArr[j] = j-i; //shift pattern from i to j j = borderArr[j]; //update border } i--; j--; borderArr[i] = j; } } void partialSuffixMatch(int shiftArr[], int borderArr[], string pattern) { int n = pattern.size(); //find length of pattern int j; j = borderArr[0]; for(int i = 0; i<n; i++) { if(shiftArr[i] == 0) shiftArr[i] = j; //when shift is 0, set shift to border value if(i == j) j = borderArr[j]; //update border value } } void searchPattern(string mainString, string pattern, int array[], int *index) { int patLen = pattern.size(); int strLen = mainString.size(); int borderArray[patLen+1]; int shiftArray[patLen + 1]; for(int i = 0; i<=patLen; i++) { shiftArray[i] = 0; //set all shift array to 0 } fullSuffixMatch(shiftArray, borderArray, pattern); partialSuffixMatch(shiftArray, borderArray, pattern); int shift = 0; while(shift <= (strLen - patLen)) { int j = patLen - 1; while(j >= 0 && pattern[j] == mainString[shift+j]) { j--; //reduce j when pattern and main string character is matching } if(j < 0) { (*index)++; array[(*index)] = shift; shift += shiftArray[0]; }else { shift += shiftArray[j+1]; } } } int main() { string mainString = "ABAAABCDBBABCDDEBCABC"; string pattern = "ABC"; int locArray[mainString.size()]; int index = -1; searchPattern(mainString, pattern, locArray, &index); for(int i = 0; i <= index; i++) { cout << "Pattern found at position: " << locArray[i]<<endl; } } Pattern found at position: 4 Pattern found at position: 10 Pattern found at position: 18
[ { "code": null, "e": 1599, "s": 1062, "text": "It is another approach of Boyer Moore Algorithm. Sometimes it is called the Good Suffix Heuristic method. For this case, a preprocessing table is created as suffix table. In this procedure, the substring or pattern is searched from the last character of the pattern. When a substring of main string matches with a substring of the pattern, it moves to find other occurrences of the matched substring. It can also move to find a prefix of the pattern which is a suffix of main string. Otherwise, it moves the whole length of the pattern." }, { "code": null, "e": 1756, "s": 1599, "text": "Input:\nMain String: “ABAAABCDBBABCDDEBCABC”, Pattern: “ABC”\nOutput:\nPattern found at position: 4\nPattern found at position: 10\nPattern found at position: 18" }, { "code": null, "e": 1806, "s": 1756, "text": "fullSuffixMatch(shiftArray, borderArray, pattern)" }, { "code": null, "e": 1890, "s": 1806, "text": "Input − Array to store shift locations, the border array and the pattern to search." }, { "code": null, "e": 1942, "s": 1890, "text": "Output − Fill the shift array and the border array." }, { "code": null, "e": 2270, "s": 1942, "text": "Begin\n n := pattern length\n j := n\n j := n+1\n borderArray[i] := j\n\n while i > 0, do\n while j <= n AND pattern[i-1] ≠ pattern[j-1], do\n if shiftArray[j] = 0, then\n shiftArray[j] := j-i;\n j := borderArray[j];\n done\n\n decrease i and j by 1\n borderArray[i] := j\n done\nEnd" }, { "code": null, "e": 2324, "s": 2270, "text": " partialSuffixMatch(shiftArray, borderArray, pattern)" }, { "code": null, "e": 2407, "s": 2324, "text": "Input− Array to store shift locations, the border array and the pattern to search." }, { "code": null, "e": 2459, "s": 2407, "text": "Output − Fill the shift array and the border array." }, { "code": null, "e": 2684, "s": 2459, "text": "Begin\n n := pattern length\n j := borderArray[0]\n\n for index of all characters ‘i’ of pattern, do\n if shiftArray[i] = 0, then\n shiftArray[i] := j\n if i = j then\n j := borderArray[j]\n done\nEnd" }, { "code": null, "e": 2713, "s": 2684, "text": "searchPattern(text, pattern)" }, { "code": null, "e": 2761, "s": 2713, "text": "Output − The indexes where the pattern is found" }, { "code": null, "e": 3352, "s": 2761, "text": "Begin\n patLen := pattern length\n strLen := text size\n\n for all entries of shiftArray, do\n set all entries to 0\n done\n\n call fullSuffixMatch(shiftArray, borderArray, pattern)\n call partialSuffixMatch(shiftArray, borderArray, pattern)\n shift := 0\n\n while shift <= (strLen - patLen), do\n j := patLen -1\n while j >= 0 and pattern[j] = text[shift + j], do\n decrease j by 1\n done\n\n if j < 0, then\n print the shift as, there is a match\n shift := shift + shiftArray[0]\n else\n shift := shift + shiftArray[j+1]\n done\nEnd" }, { "code": null, "e": 5437, "s": 3352, "text": "#include<iostream>\nusing namespace std;\n\nvoid fullSuffixMatch(int shiftArr[], int borderArr[], string pattern) {\n int n = pattern.size(); //find length of pattern\n int i = n;\n int j = n+1;\n borderArr[i] = j;\n\n while(i > 0) {\n //search right when (i-1)th and (j-1)th item are not same\n while(j <= n && pattern[i-1] != pattern[j-1] ) {\n if(shiftArr[j] == 0)\n shiftArr[j] = j-i; //shift pattern from i to j\n j = borderArr[j]; //update border\n }\n i--;\n j--;\n borderArr[i] = j;\n } \n}\n\nvoid partialSuffixMatch(int shiftArr[], int borderArr[], string pattern) {\n int n = pattern.size(); //find length of pattern\n int j;\n j = borderArr[0];\n\n for(int i = 0; i<n; i++) {\n if(shiftArr[i] == 0)\n shiftArr[i] = j; //when shift is 0, set shift to border value\n if(i == j)\n j = borderArr[j]; //update border value\n }\n}\n\nvoid searchPattern(string mainString, string pattern, int array[], int *index) {\n int patLen = pattern.size();\n int strLen = mainString.size();\n int borderArray[patLen+1];\n int shiftArray[patLen + 1];\n\n for(int i = 0; i<=patLen; i++) {\n shiftArray[i] = 0; //set all shift array to 0\n }\n\n fullSuffixMatch(shiftArray, borderArray, pattern);\n partialSuffixMatch(shiftArray, borderArray, pattern);\n int shift = 0;\n\n while(shift <= (strLen - patLen)) {\n int j = patLen - 1;\n while(j >= 0 && pattern[j] == mainString[shift+j]) {\n j--; //reduce j when pattern and main string character is matching\n }\n\n if(j < 0) {\n (*index)++;\n array[(*index)] = shift;\n shift += shiftArray[0];\n }else {\n shift += shiftArray[j+1];\n }\n }\n}\n\nint main() {\n string mainString = \"ABAAABCDBBABCDDEBCABC\";\n string pattern = \"ABC\";\n int locArray[mainString.size()];\n int index = -1;\n searchPattern(mainString, pattern, locArray, &index);\n\n for(int i = 0; i <= index; i++) {\n cout << \"Pattern found at position: \" << locArray[i]<<endl;\n }\n}" }, { "code": null, "e": 5526, "s": 5437, "text": "Pattern found at position: 4\nPattern found at position: 10\nPattern found at position: 18" } ]
Full-text search with Node.js and ElasticSearch on Docker | by Michele Riva | Towards Data Science
Full-text search can be both scary and exciting. Some popular databases such as MySql and Postgres are an amazing solution for storing data... but when it comes to full-text search performances, there’s no competition with ElasticSearch. For those who don’t know, ElasticSearch is a search engine server built on top of Lucene with amazing distributed architecture support. According to db-engines.com, it is currently the most used search engine out there. In this post, we will build a simple REST application called The Quotes Database which will allow us to store and search as many quotes as we want! I’ve prepared a JSON file containing 5000+ quotes with their authors; we’ll be using it as our starting data for populating ElasticSearch. You can find the repository for this project here. First of all, we don’t want to install ElasticSearch on our machine. We’ll be using Docker for orchestrating both the Node.js server and the ES instance on a container, which will allow us to deploy a production-ready application with all the dependencies that it needs! Let’s create a Dockerfile inside our project root folder: As you can see, we’re telling Docker that we’ll run a Node.js 10.15.3-alpine runtime. We’ll also create a new working directory under /usr/src/app, where we’ll copy both the package.json and the package-lock.json files. That way, Docker will be able to run npm install inside our WORKDIR, installing our needed dependencies. We’ll also install PM2 globally by running RUN npm install -g pm2. The Node.js runtime is single-threaded, so if a process crashes, the entire app needs to be restarted... PM2 checks the Node.js process status and restarts it when the app goes down for any reason. After installing PM2, we’ll copy our codebase inside our WORKDIR (COPY . ./), and we tell Docker to expose two ports: 3000, which will expose our RESTful service, and 9200, which exposes the ElasticSearch service (EXPOSE 3000 and EXPOSE 9200). Last but not least, we tell Docker which command will start the Node.js app: npm run start. Now you may be wondering, “_great, I get it! But how do I handle the ElasticSearch instance inside Docker? I can’t find it in my Dockerfile!_”... you’re right! That’s where docker-compose becomes useful. It allows us to orchestrate multiple Docker containers and to create a connection between them. So, let’s write down the docker-compose.yml file, which will be stored inside our project root directory: This is a bit more complex than our Dockerfile, but let’s analyze it: We declare which version of docker-compose.yml the file we’re using (3.6) We declare our services:apiWhich is our Node.js app. Just like in our Dockerfile, it requires the node:10.15.3-alpine image. We also assign a name to this container: tqd-nodeAnd here, we call the previously created Dockerfile using the build . command. We need then to expose the 3000 port: as you can see, we write these statements as follows: 3000:3000. It means that we’re mapping from the port 3000 (inside our container) to the port 3000 (accessible from our machine). Then we’ll set some environment variables. The value elasticsearch is a variable that refers to the elasticsearch service inside our docker-compose.yml file. We also want to mount a volume: /usr/src/app/quotes. That way, once we’ll restart our container, we’ll maintain our data without losing it. Once more, we tell Docker which command we need to execute once the container starts up, then we set a link to the elasticsearch service. We also tell Docker to start the api service after the elasticsearch service has booted (using the depends_on directive). Last but not least, we tell Docker to connect the api service under the esnet network. That’s because every container has its own network: that way, we say that api and elasticsearch services share the same network, so they will be able to call each other with the same ports.elasticsearchWhich is (as you may have guessed) our ES service. Its configuration is pretty similar to the api service. We’ll just cut off its verbose logs setting the logging directive to driver: none . We declare our volumes, where we store the ES data We declare our network, esnet Now we need to create our Node.js application, so let’s get started setting up our package.json file: npm init -y now we need to install some dependencies: npm i -s @elastic/elasticsearch body-parser cors dotenv express Great! Our package.json the file should look like this: Let’s implement our ElasticSearch connector in Node.js. First, we need to create a new /src/elastic.js file: As you can see, here we set some constants that will be incredibly useful. First of all, we create a new connection to ElasticSearch using its official Node.js SDK; then, we define an index ("quotes" ) and an index type ("quotes" again, we’ll see later what they mean). Now we need to create an index on ElasticSearch. You can think of “indexes” as a SQL “database” equivalent. ElasticSearch is a NoSQL database, which means that it has no tables — it just stores JSON documents. An index is a logical namespace that maps to one or more primary shards and can have zero or more replica shards. You can read more about ElasticSearch indices here. Let’s now define a function that will create our index: Now we need another function that creates the mapping for our quotes. The mapping defines the schema and types of our document: As you can see, we’re defining the schema for our documents, and we’re inserting it inside our index. Now let’s consider that ElasticSearch is a huge system and can take some seconds to boot up. We can’t connect to ES until it is ready, so we need a function that checks when the ES server is ready: As you can see, we’re returning a promise. That’s because by using, async/await we’re able to stop the entire Node.js process until this promise resolves, and it won’t do it until it connects to ES. That way, we force our Node.js to wait for ES before booting up. We’re done with ElasticSearch! Now, let’s export our functions: Great! Let’s see the entire elastic.js file: Now we need to populate our ES instance with our quotes. That may sound easy, but believe me, it can be a tricky part of our app! Let’s create a new file in /src/data/index.js: As you can see, we’re importing the elastic module we just created and our quotes from a JSON file stored in /src/data/quotes.json. We’re also creating an object called esAction, which will tell ES how to index a document once we insert it. Now we need a script to populate our database. We also need to create an array of Object with the following structure: So as you can see, for each quote we’re gonna insert, we need to set its mapping to ElasticSeaech. So that’s what we’ll do: Great! Now let’s create our main file /src/main.js and see how we’ll structure everything we’ve written so far: Let’s analyze the code above. We create a self-executing main function that will check for the ES connection. The code execution won’t proceed until ES is connected. When ES is ready, we’ll check if the quotes index exists: if it doesn’t, we’ll create it, we’ll set its mapping, and will populate the database. Obviously, we’ll do so only the first time we start up our server! Now we need to create our RESTful server. We’ll be using Express.js, which is the most popular Node.js framework out there for building servers. We’ll start with the /src/server/index.js file: As you can see, it is just a standard Express.js server; we won’t spend much time on that. Let’s see our /src/server/routes/index.js file: We create two endpoints: GET /Will return a list of quotes matching our query string parameters. POST /new/Will allow us to post a new quote storing it inside ElasticSearch. So now let’s see our /src/server/controllers/index.js file: Here we’re basically defining two functions: getQuotes, which requires at least one query string parameter: text addQuote, which require two parameters: author and quote The ElasticSearch interface is delegated to our /src/server/models/index.js. This structure helps us maintain an MVC-ish architecture. Let’s see our model: As you can see, we’re composing our ElasticSearch query by selecting every quote that includes a given word or phrase. Then, we spawn the query, setting both page and limit values: we can pass them in a query string, for instance: http://localhost:3000/quotes?text=love&page=1&limit=100. If these values are not passed via the query string, we’ll fall back to their default values. ElasticSearch returns a huge amount of data, but we need four things: Quote ID The quote itself Quote author Score The score represents how close the quote is to our search term; once we have these values, we return them with the total results number, which may be useful when paginating the results on the front end. Now we need to create the last function for our model: insertNewQuote: This function is straightforward: we post the quote and the author to our index and return the query result to the controller. Now the complete /src/server/models/index.js file should look like this: And we’re done! We need to set up our start script inside out package.json file and we’re ready to go: We also need to update our /src/main.js script to start up our Express.js server once ElasticSearch has been connected: We’re now ready to start our application using docker-compose! Just run the following command: $ docker-compose up You’ll need to wait until Docker downloads both the ElasticSearch and Node.js images, then it will boot up your server, and you’ll be ready to query against your REST endpoints! Let’s test with a couple of cURL calls: $ curl localhost:3000/quotes?text=love&limit=3{ "success": true, "data": { "results": 716, "values": [ { "id": "JDE3kGwBuLHMiUvv1itT", "quote": "There is only one happiness in life, to love and be loved.", "author": "George Sand", "score": 6.7102118 }, { "id": "JjE3kGwBuLHMiUvv1itT", "quote": "Live through feeling and you will live through love. For feeling is the language of the soul, and feeling is truth.", "author": "Matt Zotti", "score": 6.2868223 }, { "id": "NTE3kGwBuLHMiUvv1iFO", "quote": "Genuine love should first be directed at oneself if we do not love ourselves, how can we love others?", "author": "Dalai Lama", "score": 5.236455 } ] }} So as you can see, we decided to limit our results to 3, but there are other 713 quotes! We can easily get the next three quotes by calling: $ curl localhost:3000/quotes?text=love&limit=3&page=2{ "success": true, "data": { "results": 716, "values": [ { "id": "SsyHkGwBrOFNsaVmePwE", "quote": "Forgiveness is choosing to love. It is the first skill of self-giving love.", "author": "Mohandas Gandhi", "score": 4.93597 }, { "id": "rDE3kGwBuLHMiUvv1idS", "quote": "Neither a lofty degree of intelligence nor imagination nor both together go to the making of genius. Love, love, love, that is the soul of genius.", "author": "Wolfgang Amadeus Mozart", "score": 4.7821507 }, { "id": "TjE3kGwBuLHMiUvv1h9K", "quote": "Speak low, if you speak love.", "author": "William Shakespeare", "score": 4.6697206 } ] }} And what if you need to insert a new quote? Just call the /quotes/new endpoint! $ curl --request POST \ --url http://localhost:3000/quotes/new \ --header 'content-type: application/json' \ --data '{ "author": "Michele Riva", "quote": "Using Docker and ElasticSearch is challenging, but totally worth it."}' and the response will be: { "success": true, "data": { "id": "is2QkGwBrOFNsaVmFAi8", "author": "Michele Riva", "quote": "Using Docker and ElasticSearch is challenging, but totally worth it." }} Docker makes it incredibly easy to manage our dependencies and their deployment. From that point, we could host our application on Heroku, AWS ECS, Google Cloud Container, or any other Docker-based service with ease, without struggling to set up our server with their super-complex configurations. Next steps? Learn how to use Kubernetes to scale your container and orchestrate more ElasticSearch Instances! Create a new endpoint that will allow you to update an existing quote. Mistakes can happen! And what about deleting a quote? How would you implement that endpoint? It would be great to save your quotes with tags (for instances, quotes about love, health, art)... try to update your quotes index! Software development is fun. With Docker, Node, and ElasticSearch, it’s even better!
[ { "code": null, "e": 410, "s": 172, "text": "Full-text search can be both scary and exciting. Some popular databases such as MySql and Postgres are an amazing solution for storing data... but when it comes to full-text search performances, there’s no competition with ElasticSearch." }, { "code": null, "e": 630, "s": 410, "text": "For those who don’t know, ElasticSearch is a search engine server built on top of Lucene with amazing distributed architecture support. According to db-engines.com, it is currently the most used search engine out there." }, { "code": null, "e": 778, "s": 630, "text": "In this post, we will build a simple REST application called The Quotes Database which will allow us to store and search as many quotes as we want!" }, { "code": null, "e": 917, "s": 778, "text": "I’ve prepared a JSON file containing 5000+ quotes with their authors; we’ll be using it as our starting data for populating ElasticSearch." }, { "code": null, "e": 968, "s": 917, "text": "You can find the repository for this project here." }, { "code": null, "e": 1239, "s": 968, "text": "First of all, we don’t want to install ElasticSearch on our machine. We’ll be using Docker for orchestrating both the Node.js server and the ES instance on a container, which will allow us to deploy a production-ready application with all the dependencies that it needs!" }, { "code": null, "e": 1297, "s": 1239, "text": "Let’s create a Dockerfile inside our project root folder:" }, { "code": null, "e": 1622, "s": 1297, "text": "As you can see, we’re telling Docker that we’ll run a Node.js 10.15.3-alpine runtime. We’ll also create a new working directory under /usr/src/app, where we’ll copy both the package.json and the package-lock.json files. That way, Docker will be able to run npm install inside our WORKDIR, installing our needed dependencies." }, { "code": null, "e": 1887, "s": 1622, "text": "We’ll also install PM2 globally by running RUN npm install -g pm2. The Node.js runtime is single-threaded, so if a process crashes, the entire app needs to be restarted... PM2 checks the Node.js process status and restarts it when the app goes down for any reason." }, { "code": null, "e": 2131, "s": 1887, "text": "After installing PM2, we’ll copy our codebase inside our WORKDIR (COPY . ./), and we tell Docker to expose two ports: 3000, which will expose our RESTful service, and 9200, which exposes the ElasticSearch service (EXPOSE 3000 and EXPOSE 9200)." }, { "code": null, "e": 2223, "s": 2131, "text": "Last but not least, we tell Docker which command will start the Node.js app: npm run start." }, { "code": null, "e": 2629, "s": 2223, "text": "Now you may be wondering, “_great, I get it! But how do I handle the ElasticSearch instance inside Docker? I can’t find it in my Dockerfile!_”... you’re right! That’s where docker-compose becomes useful. It allows us to orchestrate multiple Docker containers and to create a connection between them. So, let’s write down the docker-compose.yml file, which will be stored inside our project root directory:" }, { "code": null, "e": 2699, "s": 2629, "text": "This is a bit more complex than our Dockerfile, but let’s analyze it:" }, { "code": null, "e": 2773, "s": 2699, "text": "We declare which version of docker-compose.yml the file we’re using (3.6)" }, { "code": null, "e": 4285, "s": 2773, "text": "We declare our services:apiWhich is our Node.js app. Just like in our Dockerfile, it requires the node:10.15.3-alpine image. We also assign a name to this container: tqd-nodeAnd here, we call the previously created Dockerfile using the build . command. We need then to expose the 3000 port: as you can see, we write these statements as follows: 3000:3000. It means that we’re mapping from the port 3000 (inside our container) to the port 3000 (accessible from our machine). Then we’ll set some environment variables. The value elasticsearch is a variable that refers to the elasticsearch service inside our docker-compose.yml file. We also want to mount a volume: /usr/src/app/quotes. That way, once we’ll restart our container, we’ll maintain our data without losing it. Once more, we tell Docker which command we need to execute once the container starts up, then we set a link to the elasticsearch service. We also tell Docker to start the api service after the elasticsearch service has booted (using the depends_on directive). Last but not least, we tell Docker to connect the api service under the esnet network. That’s because every container has its own network: that way, we say that api and elasticsearch services share the same network, so they will be able to call each other with the same ports.elasticsearchWhich is (as you may have guessed) our ES service. Its configuration is pretty similar to the api service. We’ll just cut off its verbose logs setting the logging directive to driver: none ." }, { "code": null, "e": 4336, "s": 4285, "text": "We declare our volumes, where we store the ES data" }, { "code": null, "e": 4366, "s": 4336, "text": "We declare our network, esnet" }, { "code": null, "e": 4468, "s": 4366, "text": "Now we need to create our Node.js application, so let’s get started setting up our package.json file:" }, { "code": null, "e": 4480, "s": 4468, "text": "npm init -y" }, { "code": null, "e": 4522, "s": 4480, "text": "now we need to install some dependencies:" }, { "code": null, "e": 4586, "s": 4522, "text": "npm i -s @elastic/elasticsearch body-parser cors dotenv express" }, { "code": null, "e": 4642, "s": 4586, "text": "Great! Our package.json the file should look like this:" }, { "code": null, "e": 4751, "s": 4642, "text": "Let’s implement our ElasticSearch connector in Node.js. First, we need to create a new /src/elastic.js file:" }, { "code": null, "e": 5021, "s": 4751, "text": "As you can see, here we set some constants that will be incredibly useful. First of all, we create a new connection to ElasticSearch using its official Node.js SDK; then, we define an index (\"quotes\" ) and an index type (\"quotes\" again, we’ll see later what they mean)." }, { "code": null, "e": 5397, "s": 5021, "text": "Now we need to create an index on ElasticSearch. You can think of “indexes” as a SQL “database” equivalent. ElasticSearch is a NoSQL database, which means that it has no tables — it just stores JSON documents. An index is a logical namespace that maps to one or more primary shards and can have zero or more replica shards. You can read more about ElasticSearch indices here." }, { "code": null, "e": 5453, "s": 5397, "text": "Let’s now define a function that will create our index:" }, { "code": null, "e": 5581, "s": 5453, "text": "Now we need another function that creates the mapping for our quotes. The mapping defines the schema and types of our document:" }, { "code": null, "e": 5683, "s": 5581, "text": "As you can see, we’re defining the schema for our documents, and we’re inserting it inside our index." }, { "code": null, "e": 5881, "s": 5683, "text": "Now let’s consider that ElasticSearch is a huge system and can take some seconds to boot up. We can’t connect to ES until it is ready, so we need a function that checks when the ES server is ready:" }, { "code": null, "e": 6145, "s": 5881, "text": "As you can see, we’re returning a promise. That’s because by using, async/await we’re able to stop the entire Node.js process until this promise resolves, and it won’t do it until it connects to ES. That way, we force our Node.js to wait for ES before booting up." }, { "code": null, "e": 6209, "s": 6145, "text": "We’re done with ElasticSearch! Now, let’s export our functions:" }, { "code": null, "e": 6254, "s": 6209, "text": "Great! Let’s see the entire elastic.js file:" }, { "code": null, "e": 6384, "s": 6254, "text": "Now we need to populate our ES instance with our quotes. That may sound easy, but believe me, it can be a tricky part of our app!" }, { "code": null, "e": 6431, "s": 6384, "text": "Let’s create a new file in /src/data/index.js:" }, { "code": null, "e": 6672, "s": 6431, "text": "As you can see, we’re importing the elastic module we just created and our quotes from a JSON file stored in /src/data/quotes.json. We’re also creating an object called esAction, which will tell ES how to index a document once we insert it." }, { "code": null, "e": 6791, "s": 6672, "text": "Now we need a script to populate our database. We also need to create an array of Object with the following structure:" }, { "code": null, "e": 6915, "s": 6791, "text": "So as you can see, for each quote we’re gonna insert, we need to set its mapping to ElasticSeaech. So that’s what we’ll do:" }, { "code": null, "e": 7027, "s": 6915, "text": "Great! Now let’s create our main file /src/main.js and see how we’ll structure everything we’ve written so far:" }, { "code": null, "e": 7405, "s": 7027, "text": "Let’s analyze the code above. We create a self-executing main function that will check for the ES connection. The code execution won’t proceed until ES is connected. When ES is ready, we’ll check if the quotes index exists: if it doesn’t, we’ll create it, we’ll set its mapping, and will populate the database. Obviously, we’ll do so only the first time we start up our server!" }, { "code": null, "e": 7550, "s": 7405, "text": "Now we need to create our RESTful server. We’ll be using Express.js, which is the most popular Node.js framework out there for building servers." }, { "code": null, "e": 7598, "s": 7550, "text": "We’ll start with the /src/server/index.js file:" }, { "code": null, "e": 7737, "s": 7598, "text": "As you can see, it is just a standard Express.js server; we won’t spend much time on that. Let’s see our /src/server/routes/index.js file:" }, { "code": null, "e": 7762, "s": 7737, "text": "We create two endpoints:" }, { "code": null, "e": 7834, "s": 7762, "text": "GET /Will return a list of quotes matching our query string parameters." }, { "code": null, "e": 7911, "s": 7834, "text": "POST /new/Will allow us to post a new quote storing it inside ElasticSearch." }, { "code": null, "e": 7971, "s": 7911, "text": "So now let’s see our /src/server/controllers/index.js file:" }, { "code": null, "e": 8016, "s": 7971, "text": "Here we’re basically defining two functions:" }, { "code": null, "e": 8084, "s": 8016, "text": "getQuotes, which requires at least one query string parameter: text" }, { "code": null, "e": 8141, "s": 8084, "text": "addQuote, which require two parameters: author and quote" }, { "code": null, "e": 8297, "s": 8141, "text": "The ElasticSearch interface is delegated to our /src/server/models/index.js. This structure helps us maintain an MVC-ish architecture. Let’s see our model:" }, { "code": null, "e": 8679, "s": 8297, "text": "As you can see, we’re composing our ElasticSearch query by selecting every quote that includes a given word or phrase. Then, we spawn the query, setting both page and limit values: we can pass them in a query string, for instance: http://localhost:3000/quotes?text=love&page=1&limit=100. If these values are not passed via the query string, we’ll fall back to their default values." }, { "code": null, "e": 8749, "s": 8679, "text": "ElasticSearch returns a huge amount of data, but we need four things:" }, { "code": null, "e": 8758, "s": 8749, "text": "Quote ID" }, { "code": null, "e": 8775, "s": 8758, "text": "The quote itself" }, { "code": null, "e": 8788, "s": 8775, "text": "Quote author" }, { "code": null, "e": 8794, "s": 8788, "text": "Score" }, { "code": null, "e": 8997, "s": 8794, "text": "The score represents how close the quote is to our search term; once we have these values, we return them with the total results number, which may be useful when paginating the results on the front end." }, { "code": null, "e": 9068, "s": 8997, "text": "Now we need to create the last function for our model: insertNewQuote:" }, { "code": null, "e": 9268, "s": 9068, "text": "This function is straightforward: we post the quote and the author to our index and return the query result to the controller. Now the complete /src/server/models/index.js file should look like this:" }, { "code": null, "e": 9371, "s": 9268, "text": "And we’re done! We need to set up our start script inside out package.json file and we’re ready to go:" }, { "code": null, "e": 9491, "s": 9371, "text": "We also need to update our /src/main.js script to start up our Express.js server once ElasticSearch has been connected:" }, { "code": null, "e": 9586, "s": 9491, "text": "We’re now ready to start our application using docker-compose! Just run the following command:" }, { "code": null, "e": 9606, "s": 9586, "text": "$ docker-compose up" }, { "code": null, "e": 9784, "s": 9606, "text": "You’ll need to wait until Docker downloads both the ElasticSearch and Node.js images, then it will boot up your server, and you’ll be ready to query against your REST endpoints!" }, { "code": null, "e": 9824, "s": 9784, "text": "Let’s test with a couple of cURL calls:" }, { "code": null, "e": 10604, "s": 9824, "text": "$ curl localhost:3000/quotes?text=love&limit=3{ \"success\": true, \"data\": { \"results\": 716, \"values\": [ { \"id\": \"JDE3kGwBuLHMiUvv1itT\", \"quote\": \"There is only one happiness in life, to love and be loved.\", \"author\": \"George Sand\", \"score\": 6.7102118 }, { \"id\": \"JjE3kGwBuLHMiUvv1itT\", \"quote\": \"Live through feeling and you will live through love. For feeling is the language of the soul, and feeling is truth.\", \"author\": \"Matt Zotti\", \"score\": 6.2868223 }, { \"id\": \"NTE3kGwBuLHMiUvv1iFO\", \"quote\": \"Genuine love should first be directed at oneself if we do not love ourselves, how can we love others?\", \"author\": \"Dalai Lama\", \"score\": 5.236455 } ] }}" }, { "code": null, "e": 10745, "s": 10604, "text": "So as you can see, we decided to limit our results to 3, but there are other 713 quotes! We can easily get the next three quotes by calling:" }, { "code": null, "e": 11533, "s": 10745, "text": "$ curl localhost:3000/quotes?text=love&limit=3&page=2{ \"success\": true, \"data\": { \"results\": 716, \"values\": [ { \"id\": \"SsyHkGwBrOFNsaVmePwE\", \"quote\": \"Forgiveness is choosing to love. It is the first skill of self-giving love.\", \"author\": \"Mohandas Gandhi\", \"score\": 4.93597 }, { \"id\": \"rDE3kGwBuLHMiUvv1idS\", \"quote\": \"Neither a lofty degree of intelligence nor imagination nor both together go to the making of genius. Love, love, love, that is the soul of genius.\", \"author\": \"Wolfgang Amadeus Mozart\", \"score\": 4.7821507 }, { \"id\": \"TjE3kGwBuLHMiUvv1h9K\", \"quote\": \"Speak low, if you speak love.\", \"author\": \"William Shakespeare\", \"score\": 4.6697206 } ] }}" }, { "code": null, "e": 11613, "s": 11533, "text": "And what if you need to insert a new quote? Just call the /quotes/new endpoint!" }, { "code": null, "e": 11866, "s": 11613, "text": "$ curl --request POST \\ --url http://localhost:3000/quotes/new \\ --header 'content-type: application/json' \\ --data '{ \"author\": \"Michele Riva\", \"quote\": \"Using Docker and ElasticSearch is challenging, but totally worth it.\"}'" }, { "code": null, "e": 11892, "s": 11866, "text": "and the response will be:" }, { "code": null, "e": 12072, "s": 11892, "text": "{ \"success\": true, \"data\": { \"id\": \"is2QkGwBrOFNsaVmFAi8\", \"author\": \"Michele Riva\", \"quote\": \"Using Docker and ElasticSearch is challenging, but totally worth it.\" }}" }, { "code": null, "e": 12370, "s": 12072, "text": "Docker makes it incredibly easy to manage our dependencies and their deployment. From that point, we could host our application on Heroku, AWS ECS, Google Cloud Container, or any other Docker-based service with ease, without struggling to set up our server with their super-complex configurations." }, { "code": null, "e": 12382, "s": 12370, "text": "Next steps?" }, { "code": null, "e": 12480, "s": 12382, "text": "Learn how to use Kubernetes to scale your container and orchestrate more ElasticSearch Instances!" }, { "code": null, "e": 12572, "s": 12480, "text": "Create a new endpoint that will allow you to update an existing quote. Mistakes can happen!" }, { "code": null, "e": 12644, "s": 12572, "text": "And what about deleting a quote? How would you implement that endpoint?" }, { "code": null, "e": 12776, "s": 12644, "text": "It would be great to save your quotes with tags (for instances, quotes about love, health, art)... try to update your quotes index!" } ]
Matching Pair | Practice | GeeksforGeeks
Given a set of numbers from 1 to N, each number is exactly present twice so there are N pairs. In the worst-case scenario, how many numbers X should be picked and removed from the set until we find a matching pair? Example 1: Input: N = 1 Output: 2 Explanation: When N=1 Then there is one pair and a matching pair can be extracted in 2 Draws. Example 2: Input: N = 2 Output: 3 Explanation: When N=2 then there are 2 pairs, let them be {1,2,1,2} and a matching pair will be made in 3 draws. Your Task: You don't need to read input or print anything. Your task is to complete the function find() which takes an integer N as input parameter and returns an integer, the number of x must be picked and removed from set to find a matching pair. Expected Time Complexity: O(1) Expected Space Complexity: O(1) Constraints: 0 <= N <= 105 0 hashimshafeequem2 months ago class Solution: def find (self, N): return N+1 0 prateekkasaudhan1232 months ago class Solution{ static long find(int N){ // code here return (N+1); }} 0 jatinbitthal13193 months ago Java solution 0.1 sec class Solution{ static long find(int N){ // code here return N + 1; }} 0 thatsiddharth3 months ago class Solution{ static long find(int N){ // code here return N+1; }} 0 shambhavijha9913 months ago def find (self, N): return(N+1) +1 ayushnautiyal11104 months ago int find(int N){ return N+1; } -6 gyanaranjansahoo5094 months ago its's like pigeon hole principle in mathematics +9 rohithk4224 months ago How N+1? Lets say there are numbers [ 1, 2, 3, 4, 1, 2, 3, 4 ] with 1 - 4 in pairs... lets pick up 4 numbers(worst case - all diff nums) from the list 1,2,3,4(we have) now the remaining item in list is [1, 2, 3, 4] Now - which ever number(1 or 2 or 3 or 4) I choose I will make a pair because, I already have 1, 2, 3, 4 The point 1 is N and point 2 is the +1 so the result is N+1 -4 mayank20214 months ago #python3 def find (self, N): return N+1 -10 naraindragokul4 months ago Print("Hello world") 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": 453, "s": 238, "text": "Given a set of numbers from 1 to N, each number is exactly present twice so there are N pairs. In the worst-case scenario, how many numbers X should be picked and removed from the set until we find a matching pair?" }, { "code": null, "e": 464, "s": 453, "text": "Example 1:" }, { "code": null, "e": 585, "s": 464, "text": "Input:\nN = 1\nOutput:\n2\nExplanation:\nWhen N=1 Then there is \none pair and a matching \npair can be extracted in \n2 Draws.\n" }, { "code": null, "e": 596, "s": 585, "text": "Example 2:" }, { "code": null, "e": 735, "s": 596, "text": "Input:\nN = 2\nOutput:\n3\nExplanation:\nWhen N=2 then there are \n2 pairs, let them be {1,2,1,2}\nand a matching pair will \nbe made in 3 draws.\n" }, { "code": null, "e": 987, "s": 735, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function find() which takes an integer N as input parameter and returns an integer, the number of x must be picked and removed from set to find a matching pair.\n " }, { "code": null, "e": 1052, "s": 987, "text": "Expected Time Complexity: O(1)\nExpected Space Complexity: O(1)\n " }, { "code": null, "e": 1079, "s": 1052, "text": "Constraints:\n0 <= N <= 105" }, { "code": null, "e": 1081, "s": 1079, "text": "0" }, { "code": null, "e": 1110, "s": 1081, "text": "hashimshafeequem2 months ago" }, { "code": null, "e": 1165, "s": 1110, "text": "class Solution: def find (self, N): return N+1" }, { "code": null, "e": 1167, "s": 1165, "text": "0" }, { "code": null, "e": 1199, "s": 1167, "text": "prateekkasaudhan1232 months ago" }, { "code": null, "e": 1286, "s": 1199, "text": "class Solution{ static long find(int N){ // code here return (N+1); }}" }, { "code": null, "e": 1288, "s": 1286, "text": "0" }, { "code": null, "e": 1317, "s": 1288, "text": "jatinbitthal13193 months ago" }, { "code": null, "e": 1339, "s": 1317, "text": "Java solution 0.1 sec" }, { "code": null, "e": 1426, "s": 1339, "text": "class Solution{ static long find(int N){ // code here return N + 1; }}" }, { "code": null, "e": 1428, "s": 1426, "text": "0" }, { "code": null, "e": 1454, "s": 1428, "text": "thatsiddharth3 months ago" }, { "code": null, "e": 1556, "s": 1454, "text": "class Solution{ static long find(int N){ // code here return N+1; }}" }, { "code": null, "e": 1558, "s": 1556, "text": "0" }, { "code": null, "e": 1586, "s": 1558, "text": "shambhavijha9913 months ago" }, { "code": null, "e": 1624, "s": 1586, "text": "def find (self, N): return(N+1)" }, { "code": null, "e": 1627, "s": 1624, "text": "+1" }, { "code": null, "e": 1657, "s": 1627, "text": "ayushnautiyal11104 months ago" }, { "code": null, "e": 1697, "s": 1657, "text": "int find(int N){ return N+1; }" }, { "code": null, "e": 1700, "s": 1697, "text": "-6" }, { "code": null, "e": 1732, "s": 1700, "text": "gyanaranjansahoo5094 months ago" }, { "code": null, "e": 1780, "s": 1732, "text": "its's like pigeon hole principle in mathematics" }, { "code": null, "e": 1783, "s": 1780, "text": "+9" }, { "code": null, "e": 1806, "s": 1783, "text": "rohithk4224 months ago" }, { "code": null, "e": 1815, "s": 1806, "text": "How N+1?" }, { "code": null, "e": 2021, "s": 1815, "text": "Lets say there are numbers [ 1, 2, 3, 4, 1, 2, 3, 4 ] with 1 - 4 in pairs... lets pick up 4 numbers(worst case - all diff nums) from the list 1,2,3,4(we have) now the remaining item in list is [1, 2, 3, 4]" }, { "code": null, "e": 2126, "s": 2021, "text": "Now - which ever number(1 or 2 or 3 or 4) I choose I will make a pair because, I already have 1, 2, 3, 4" }, { "code": null, "e": 2186, "s": 2126, "text": "The point 1 is N and point 2 is the +1 so the result is N+1" }, { "code": null, "e": 2189, "s": 2186, "text": "-4" }, { "code": null, "e": 2212, "s": 2189, "text": "mayank20214 months ago" }, { "code": null, "e": 2261, "s": 2212, "text": "#python3 def find (self, N): return N+1" }, { "code": null, "e": 2265, "s": 2261, "text": "-10" }, { "code": null, "e": 2292, "s": 2265, "text": "naraindragokul4 months ago" }, { "code": null, "e": 2314, "s": 2292, "text": "Print(\"Hello world\") " }, { "code": null, "e": 2460, "s": 2314, "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": 2496, "s": 2460, "text": " Login to access your submissions. " }, { "code": null, "e": 2506, "s": 2496, "text": "\nProblem\n" }, { "code": null, "e": 2516, "s": 2506, "text": "\nContest\n" }, { "code": null, "e": 2579, "s": 2516, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 2727, "s": 2579, "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": 2935, "s": 2727, "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": 3041, "s": 2935, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Monte Carlo Methods and Simulations explained in real-life: modeling insomnia | by Carolina Bento | Towards Data Science
Monte Carlo Methods is a group of algorithms that simulate the behavior of a complex system, or probabilistic phenomena, using inferential statistics. They simulate physical processes that are typically time-consuming, or too expensive to setup and run for a large number times. Since it is a tool to model probabilistic real-world processes, Monte Carlo Methods are widely used in areas ranging from particle Physics and Biochemistry to Engineering. So, if you can model it, you can use Monte Carlo Methods and run simulations! Monte Carlo simulations are great methodology when you want to: Simulate processes that are time consuming, i.e., they take a lot of time to setup the right conditions or take a long time to run before you can observe meaningful results. Run a large number of experiments in a short time-frame. With enough computing power, you can run thousands, even millions, of experiments in a relative short time and in parallel. Quickly adjust and repeat experiments. Simulations can run much faster than performing the experiment by hand or waiting for the optimal conditions to observe the phenomena. So you can run the simulation a few times, quickly make adjustments, fix bugs and get the experiment back up again. For instance, in a computer simulation, changing the concentration of a molecule means updating a number in your code, while in real life it would mean you’d have to create the compound from scratch, be precise in your measurements and get all the lab equipment running again. Sometimes that’s not an easy feat! At the end of the day, simulations help find the optimal trade-off between time to run your experiments, having faster cycles of iteration and achieving a volume of experiments that could be much difficult to manage and maintain if they were not computer simulations. One of the earliest Monte Carlo simulations was conducted by mathematician and naturalist Buffon, in 1777. He tossed a coin 2,048 times and recorded the results, to study the distribution of the possible outcomes[1]. But Buffon’s coin toss experiment is easy to setup, run and obtain results. Other experiments may have constraints that are difficult to overcome. For instance, in Biochemistry, Monte Carlo simulations are used to determine the parameters of metabolic processes. These processes are usually complex and simulations are used to create parallel virtual worlds, creating multiple what if scenarios. With well known parameters, they can also use simulations to create pseudo-real samples from the results of a biochemical process for further studies[2]. Not to mention the project that actually gave a name to this methodology. Stanislaw Ulam was working on the Manhattan project when he proposed a way to use random experiments to solve deterministic problems, such as neutron diffusion in fissionable material. And because they were working on a secret project, they needed a code name. Another colleague, Nicholas Metropolis, suggested the Monte Carlo, which was where Ulam’s uncle used to borrow money to gamble. But instead of doing everything by hand like everyone else before them, John Von Neumann helped program the ENIAC, the first programmable computer, to run those simulations. There are many Monte Carlo methods, ranging different levels of complexity. But simpler methods include the one used by Buffon, where you have Bernoulli trials and record the probability associated with success and failure, success being heads and failure tails, or vice-versa. Another one is to calculate the expected value of a random variable. In this case, the output of the random variable is defined by a function[3], and this function can be anything. If your random variable represents the toss of a fair coin, that function returns heads or tails with a probability of 1/2. But you have control over the random variable, and it can be anything that makes sense in the context of your problem. To calculate the expected value of the random variable, you repeat the following process multiple times: Pick a value from the set of possible values the random variable accepts,Plug the value into the function that generates the output of the random variable,Record the output. Pick a value from the set of possible values the random variable accepts, Plug the value into the function that generates the output of the random variable, Record the output. Take the average of all outputs, and you’ve just simulated the expected value of that random variable! This only works if you run a big enough number of simulations, and so, the Law of Large Numbers can be applied. The Law of Large Numbers states something like this: The results obtained from performing a large number of trials should be close to the expected value. And it will become closer to the true expected value, the more trials you perform. If you check this criteria, you can trust the result of your simulations. Regardless of the method you’re using, Monte Carlo simulations share a framework. Model the process or phenomenon you want to simulate.Define the inputs and outputs.Run the experiment, i.e., run the inputs through the model, and aggregate results. Model the process or phenomenon you want to simulate. Define the inputs and outputs. Run the experiment, i.e., run the inputs through the model, and aggregate results. To run Monte Carlo Simulations you need a model, a way to represent the conditions of your experiment and how the different elements in the experiment interact (or not) to achieve a result or output. In a simplistic way, a model transforms inputs into an output. The model represents a probabilistic system, something that takes inputs and returns an output with a given probability. Everything depends on the model. If you don’t have a good model, you’ll have consistently poor results, Garbage in, Garbage Out. What’s particular about Monte Carlo simulations, is that the inputs are randomly generated. Continuous inputs are generated based on a probability density function, and discrete inputs based on a probability mass function. Probability Density Functions (PDFs) describe the probability of each output of a continuous random variable. They give you a relative likelihood that the random variable will be equal to any given value. The interesting part is that it’s the relative probability, not an absolute one. Since we are dealing with continuous random variables, it’s hard to isolate the probability of a single value. It’s difficult to say, for example, what is the probability that all cats in my neighborhood have a tail with exactly 12 inches? Tail length is continuous, so we tend to look at the probabilities of continuous random variables as intervals. You might ask instead, What’s the probability that all cats in my neighborhood have a tail with length between 10 and 12 inches? Visually, you’d be interested in the following areas under the PDF curve. For inputs that can be described using discrete random variables, you can only get results from a preset list of outcomes. So you use a Probability Mass Function (PMF) to get the probability of a particular outcome. It’s the equivalent of a PDF, but for discrete random variables. When it’s your turn to play Risk and you choose to attack an enemy, you roll the dice. In 6-sided fair dice, you know you can only get a value between 1 and 6 for each die. You can’t get 2.3 on a die roll. With discrete random variables, you can ask questions about absolute probabilities, like what’s the probability that I get a 4 in the next roll? Or, if your opponent rolls the die, and gets a 3 and it’s your turn to attack, you might wonder what’s the probability of getting a value higher than 3? To run the experiment you plug the inputs in your model, or function, and record the results. But what do you do with the result of 100,000 simulations? Even though you run multiple simulations, the goal is to have an aggregated output that explains the phenomenon you’ve modeled. This aggregated output, can be the mean value for what you’ve modeled, like when you’re modeling temperatures, or the probability of a success/failure scenario, such as the likelihood of a team winning the Super Bowl. Running these simulations is a way to get all the pieces in place to use inferential statistics. The idea is to get lots outputs from the simulations, very much like you take random samples to study a population, and then use inferential statistics to draw conclusions about the actual phenomenon. But again, the key is to run a big number of simulations. If you run your simulation just a handful of times you might get just one-off, extreme outcomes. Try tossing a coin 5 times in a row. Maybe you’ll get all heads, or all tails. How sure are you that the probability of getting heads/tails is 1? Based on your 5 tosses it is, but we know that if they are truly independent tosses the probability would be close to 0.5. So there’s a lot of variance in the result from those 5 tosses. When you’re studying a population, the way to reduce variance it to increase the sample size. With Monte Carlo methods, you simply run more simulations. Let’s put this all together! You’ve noticed that since starting to work from home, you’ve had a harder time falling asleep at night, and even some episodes of insomnia. Although there may be several other factors, you quickly realize that you’ve just been having too much coffee altogether. Usually the day starts with a fresh brew that used to sit there half empty until the next day. But recently that is all gone by the end of the day! You start getting a sense that, on most days, you go over 5 cups of coffee. And for you, that’s a recipe for insomnia. To grab a hold of the situation and control the insomnia episodes, you start thinking about what may be leading you to drink more coffee: Working from couch On days when you spend most of time working from the couch instead of from your desk, you’re slouching more so you feel kind of sleepy all the time. On those days, you drink a cup of coffee every couple of hours. Pajama pants some days you don’t feel like changing from your pajama pants. Besides making you feel more comfy, you actually feel like you haven’t really woken up. So on those days, you end up drinking an extra cup in the morning, just in case. There are some exceptions, though. There are days when you’re so tired, you’ll fall asleep as soon as you get to bed. With these clues about what makes you drink more coffee, you want to know how likely are you to get a good night’s sleep. To do that, you can model your insomnia patterns with Monte Carlo methods, and run some simulations. To prepare the inputs of the simulations you took note, during the course of a few weeks, how many times you worked from the couch, wore pajama pants and the days you felt so tired that you quickly fell asleep. Then you turned that into probabilities: Probability of working from the couch: 0.7, Probability of wearing pajama pants: 0.35, Probability of being so tired, you quickly fall asleep: 0.05. You can think of each of these as the probability of success/failure event, meaning, you either wore pajama pants or not. This helps in deciding that the best distribution to model these probabilities is the Bernoulli distribution. There are also a couple of constants in your model, which you can also tweak: Number of working hours in a day, Number of cups that you can drink without getting insomnia. Here’s the model in Python. import randomdef insomnia_model(working_hours, coffee_threshold, p_couch, p_pajamas, p_tired):''' The model, i.e., how the different inputs interact to generate the outputModel constants (not picked at random):param working_hours: number of working hours in a day:param coffee_threshold: amount of coffee you need that will for sure result in insomniaModel inputs (picked at random):param p_couch: probability of working from the couch on any given day:param p_pajamas: probability of wearing pajama pants on any given day:param p_tired: probability of ending the day so tired that you'll fall asleep regardless of how many cups of coffee you have:return: The result of the model is either insomnia or sleep.'''# taking 1 sample from the bernoulli distribution with a given probability of success.# a binomial distribution with just 1 trial is equivalent to the bernoulli distribution. that's done by setting size = 1 if bool(np.random.binomial(1, p_tired, 1)[0]): # you're too tired today, you'll fall asleep regardless return False # starting your day, picking the outfit and deciding if you're going to work from the couch day_start = True pajamas = bool(np.random.binomial(1, p_pajamas, 1)[0]) work_from_couch = bool(np.random.binomial(1, p_couch, 1)[0]) while working_hours > 0 and coffee_threshold > 0: if pajamas and day_start: # starting the day with an extra cup of coffee coffee_threshold -= 2 day_start = False if work_from_couch and working_hours % 2 == 0: # if you're working from the couch, you get a cup of coffee every couple of hours coffee_threshold -= 1 working_hours -= 1return coffee_threshold == 0 Then you just need to run the model multiple times, aggregate and plot the results. Here, by default, you’ll be running 10,000 simulations. import pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltdef run_insomnia_simulations(runs=10000, working_hours=8, coffee_threshold=6, p_couch=0.7, p_pajamas=0.35, p_tired=0.05):''' Running 10,000 simulations (default) and plotting the resultsOnly highlighting here the parameters not mentioned in the model function:param runs: number of times the model will run:return:''' results = [] sim_count = 0 while sim_count < runs: results.append(insomnia_model(working_hours, coffee_threshold, p_couch, p_pajamas, p_tired)) sim_count += 1 # making the output easier to interpret results = list(map(lambda x: 'insomnia' if x else 'sleep', results)) results_pd = pd.DataFrame(data=results) results_pd.columns = ['type'] p_insomnia = round((results_pd[results_pd['type'] == 'insomnia'].count().values[0])/float(runs), 2) p_sleep = round((results_pd[results_pd['type'] == 'sleep'].count().values[0]) / float(runs), 2) print('Probability of having insomnia = ' + str(p_insomnia) + ' || Probability of a good night\'s sleep = ' + str(p_sleep)) # plotting the output of all model runs fig, ax = plt.subplots(figsize=(12, 7), constrained_layout=True) # removing to and right border ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) # setting the color palette sns.set_palette("Set2") sns.histplot(data=results_pd, x='type', hue='type', legend=False, linewidth=0) ax.xaxis.label.set_visible(False) plt.show() Running the simulations with the default values. # running simulations with all the default valuesrun_insomnia_simulations() With these probabilities, you’re actually getting a good night’s sleep 77% of the days! This is a simulation, so you can refine your model any time you want 😀 All you need to do is change the inputs, in this case, the probabilities of the events that lead you to drink more coffee. Maybe a more realist model is one where you’ll always be working from the couch and roughly 60% of the days you’re wearing your pajama pants. To see that in action, you just need to change the probability of working from the couch to be equal to 1 and probability of wearing pajama pants to 0.6. run_insomnia_simulations(p_couch=1, p_pajamas=0.6) With this model, you’re likely to have insomnia. In fact, 57% of the days you’re going to have insomnia if you always work from the couch and wear pajama pants 3 out of 5 days of the week. Creating this model opens up a lot of interesting investigations! For instance, you can continue to play around with the inputs and try to find the sweet-spot where you have as few insomnia episodes as possible! Hope you enjoyed this article, and got a better idea about how Monte Carlo methods and simulations can help you understand different phenomena. Thanks for reading! [1] Sawilowsky, Shlomo S. (2003). “You think you’ve got trivials?”. Journal of Modern Applied Statistical Methods. 2 (1): 218–225. [2] Tenekedjiev KI, Nikolova ND, Kolev K. Applications of Monte Carlo Simulation in Modelling of Biochemical Processes. In: Mode CJ, editor. Applications of Monte Carlo Methods in Biology, Medicine and Other Fields of Science [Internet]. Rijeka (HR): InTech; 2011 Feb 28. Chapter 4. PMID: 28045483. [3] Claus Beisbart & John D. Norton (2012): Why Monte Carlo Simulations Are Inferences and Not Experiments, International Studies in the Philosophy of Science, 26:4, 403–422
[ { "code": null, "e": 326, "s": 47, "text": "Monte Carlo Methods is a group of algorithms that simulate the behavior of a complex system, or probabilistic phenomena, using inferential statistics. They simulate physical processes that are typically time-consuming, or too expensive to setup and run for a large number times." }, { "code": null, "e": 576, "s": 326, "text": "Since it is a tool to model probabilistic real-world processes, Monte Carlo Methods are widely used in areas ranging from particle Physics and Biochemistry to Engineering. So, if you can model it, you can use Monte Carlo Methods and run simulations!" }, { "code": null, "e": 640, "s": 576, "text": "Monte Carlo simulations are great methodology when you want to:" }, { "code": null, "e": 814, "s": 640, "text": "Simulate processes that are time consuming, i.e., they take a lot of time to setup the right conditions or take a long time to run before you can observe meaningful results." }, { "code": null, "e": 995, "s": 814, "text": "Run a large number of experiments in a short time-frame. With enough computing power, you can run thousands, even millions, of experiments in a relative short time and in parallel." }, { "code": null, "e": 1597, "s": 995, "text": "Quickly adjust and repeat experiments. Simulations can run much faster than performing the experiment by hand or waiting for the optimal conditions to observe the phenomena. So you can run the simulation a few times, quickly make adjustments, fix bugs and get the experiment back up again. For instance, in a computer simulation, changing the concentration of a molecule means updating a number in your code, while in real life it would mean you’d have to create the compound from scratch, be precise in your measurements and get all the lab equipment running again. Sometimes that’s not an easy feat!" }, { "code": null, "e": 1865, "s": 1597, "text": "At the end of the day, simulations help find the optimal trade-off between time to run your experiments, having faster cycles of iteration and achieving a volume of experiments that could be much difficult to manage and maintain if they were not computer simulations." }, { "code": null, "e": 2082, "s": 1865, "text": "One of the earliest Monte Carlo simulations was conducted by mathematician and naturalist Buffon, in 1777. He tossed a coin 2,048 times and recorded the results, to study the distribution of the possible outcomes[1]." }, { "code": null, "e": 2229, "s": 2082, "text": "But Buffon’s coin toss experiment is easy to setup, run and obtain results. Other experiments may have constraints that are difficult to overcome." }, { "code": null, "e": 2632, "s": 2229, "text": "For instance, in Biochemistry, Monte Carlo simulations are used to determine the parameters of metabolic processes. These processes are usually complex and simulations are used to create parallel virtual worlds, creating multiple what if scenarios. With well known parameters, they can also use simulations to create pseudo-real samples from the results of a biochemical process for further studies[2]." }, { "code": null, "e": 2706, "s": 2632, "text": "Not to mention the project that actually gave a name to this methodology." }, { "code": null, "e": 3095, "s": 2706, "text": "Stanislaw Ulam was working on the Manhattan project when he proposed a way to use random experiments to solve deterministic problems, such as neutron diffusion in fissionable material. And because they were working on a secret project, they needed a code name. Another colleague, Nicholas Metropolis, suggested the Monte Carlo, which was where Ulam’s uncle used to borrow money to gamble." }, { "code": null, "e": 3269, "s": 3095, "text": "But instead of doing everything by hand like everyone else before them, John Von Neumann helped program the ENIAC, the first programmable computer, to run those simulations." }, { "code": null, "e": 3345, "s": 3269, "text": "There are many Monte Carlo methods, ranging different levels of complexity." }, { "code": null, "e": 3547, "s": 3345, "text": "But simpler methods include the one used by Buffon, where you have Bernoulli trials and record the probability associated with success and failure, success being heads and failure tails, or vice-versa." }, { "code": null, "e": 3616, "s": 3547, "text": "Another one is to calculate the expected value of a random variable." }, { "code": null, "e": 3728, "s": 3616, "text": "In this case, the output of the random variable is defined by a function[3], and this function can be anything." }, { "code": null, "e": 3971, "s": 3728, "text": "If your random variable represents the toss of a fair coin, that function returns heads or tails with a probability of 1/2. But you have control over the random variable, and it can be anything that makes sense in the context of your problem." }, { "code": null, "e": 4076, "s": 3971, "text": "To calculate the expected value of the random variable, you repeat the following process multiple times:" }, { "code": null, "e": 4250, "s": 4076, "text": "Pick a value from the set of possible values the random variable accepts,Plug the value into the function that generates the output of the random variable,Record the output." }, { "code": null, "e": 4324, "s": 4250, "text": "Pick a value from the set of possible values the random variable accepts," }, { "code": null, "e": 4407, "s": 4324, "text": "Plug the value into the function that generates the output of the random variable," }, { "code": null, "e": 4426, "s": 4407, "text": "Record the output." }, { "code": null, "e": 4529, "s": 4426, "text": "Take the average of all outputs, and you’ve just simulated the expected value of that random variable!" }, { "code": null, "e": 4641, "s": 4529, "text": "This only works if you run a big enough number of simulations, and so, the Law of Large Numbers can be applied." }, { "code": null, "e": 4694, "s": 4641, "text": "The Law of Large Numbers states something like this:" }, { "code": null, "e": 4878, "s": 4694, "text": "The results obtained from performing a large number of trials should be close to the expected value. And it will become closer to the true expected value, the more trials you perform." }, { "code": null, "e": 4952, "s": 4878, "text": "If you check this criteria, you can trust the result of your simulations." }, { "code": null, "e": 5034, "s": 4952, "text": "Regardless of the method you’re using, Monte Carlo simulations share a framework." }, { "code": null, "e": 5200, "s": 5034, "text": "Model the process or phenomenon you want to simulate.Define the inputs and outputs.Run the experiment, i.e., run the inputs through the model, and aggregate results." }, { "code": null, "e": 5254, "s": 5200, "text": "Model the process or phenomenon you want to simulate." }, { "code": null, "e": 5285, "s": 5254, "text": "Define the inputs and outputs." }, { "code": null, "e": 5368, "s": 5285, "text": "Run the experiment, i.e., run the inputs through the model, and aggregate results." }, { "code": null, "e": 5568, "s": 5368, "text": "To run Monte Carlo Simulations you need a model, a way to represent the conditions of your experiment and how the different elements in the experiment interact (or not) to achieve a result or output." }, { "code": null, "e": 5631, "s": 5568, "text": "In a simplistic way, a model transforms inputs into an output." }, { "code": null, "e": 5881, "s": 5631, "text": "The model represents a probabilistic system, something that takes inputs and returns an output with a given probability. Everything depends on the model. If you don’t have a good model, you’ll have consistently poor results, Garbage in, Garbage Out." }, { "code": null, "e": 6104, "s": 5881, "text": "What’s particular about Monte Carlo simulations, is that the inputs are randomly generated. Continuous inputs are generated based on a probability density function, and discrete inputs based on a probability mass function." }, { "code": null, "e": 6390, "s": 6104, "text": "Probability Density Functions (PDFs) describe the probability of each output of a continuous random variable. They give you a relative likelihood that the random variable will be equal to any given value. The interesting part is that it’s the relative probability, not an absolute one." }, { "code": null, "e": 6501, "s": 6390, "text": "Since we are dealing with continuous random variables, it’s hard to isolate the probability of a single value." }, { "code": null, "e": 6630, "s": 6501, "text": "It’s difficult to say, for example, what is the probability that all cats in my neighborhood have a tail with exactly 12 inches?" }, { "code": null, "e": 6742, "s": 6630, "text": "Tail length is continuous, so we tend to look at the probabilities of continuous random variables as intervals." }, { "code": null, "e": 6871, "s": 6742, "text": "You might ask instead, What’s the probability that all cats in my neighborhood have a tail with length between 10 and 12 inches?" }, { "code": null, "e": 6945, "s": 6871, "text": "Visually, you’d be interested in the following areas under the PDF curve." }, { "code": null, "e": 7226, "s": 6945, "text": "For inputs that can be described using discrete random variables, you can only get results from a preset list of outcomes. So you use a Probability Mass Function (PMF) to get the probability of a particular outcome. It’s the equivalent of a PDF, but for discrete random variables." }, { "code": null, "e": 7432, "s": 7226, "text": "When it’s your turn to play Risk and you choose to attack an enemy, you roll the dice. In 6-sided fair dice, you know you can only get a value between 1 and 6 for each die. You can’t get 2.3 on a die roll." }, { "code": null, "e": 7730, "s": 7432, "text": "With discrete random variables, you can ask questions about absolute probabilities, like what’s the probability that I get a 4 in the next roll? Or, if your opponent rolls the die, and gets a 3 and it’s your turn to attack, you might wonder what’s the probability of getting a value higher than 3?" }, { "code": null, "e": 7824, "s": 7730, "text": "To run the experiment you plug the inputs in your model, or function, and record the results." }, { "code": null, "e": 7883, "s": 7824, "text": "But what do you do with the result of 100,000 simulations?" }, { "code": null, "e": 8011, "s": 7883, "text": "Even though you run multiple simulations, the goal is to have an aggregated output that explains the phenomenon you’ve modeled." }, { "code": null, "e": 8229, "s": 8011, "text": "This aggregated output, can be the mean value for what you’ve modeled, like when you’re modeling temperatures, or the probability of a success/failure scenario, such as the likelihood of a team winning the Super Bowl." }, { "code": null, "e": 8527, "s": 8229, "text": "Running these simulations is a way to get all the pieces in place to use inferential statistics. The idea is to get lots outputs from the simulations, very much like you take random samples to study a population, and then use inferential statistics to draw conclusions about the actual phenomenon." }, { "code": null, "e": 8682, "s": 8527, "text": "But again, the key is to run a big number of simulations. If you run your simulation just a handful of times you might get just one-off, extreme outcomes." }, { "code": null, "e": 9015, "s": 8682, "text": "Try tossing a coin 5 times in a row. Maybe you’ll get all heads, or all tails. How sure are you that the probability of getting heads/tails is 1? Based on your 5 tosses it is, but we know that if they are truly independent tosses the probability would be close to 0.5. So there’s a lot of variance in the result from those 5 tosses." }, { "code": null, "e": 9168, "s": 9015, "text": "When you’re studying a population, the way to reduce variance it to increase the sample size. With Monte Carlo methods, you simply run more simulations." }, { "code": null, "e": 9197, "s": 9168, "text": "Let’s put this all together!" }, { "code": null, "e": 9459, "s": 9197, "text": "You’ve noticed that since starting to work from home, you’ve had a harder time falling asleep at night, and even some episodes of insomnia. Although there may be several other factors, you quickly realize that you’ve just been having too much coffee altogether." }, { "code": null, "e": 9726, "s": 9459, "text": "Usually the day starts with a fresh brew that used to sit there half empty until the next day. But recently that is all gone by the end of the day! You start getting a sense that, on most days, you go over 5 cups of coffee. And for you, that’s a recipe for insomnia." }, { "code": null, "e": 9864, "s": 9726, "text": "To grab a hold of the situation and control the insomnia episodes, you start thinking about what may be leading you to drink more coffee:" }, { "code": null, "e": 10096, "s": 9864, "text": "Working from couch On days when you spend most of time working from the couch instead of from your desk, you’re slouching more so you feel kind of sleepy all the time. On those days, you drink a cup of coffee every couple of hours." }, { "code": null, "e": 10341, "s": 10096, "text": "Pajama pants some days you don’t feel like changing from your pajama pants. Besides making you feel more comfy, you actually feel like you haven’t really woken up. So on those days, you end up drinking an extra cup in the morning, just in case." }, { "code": null, "e": 10459, "s": 10341, "text": "There are some exceptions, though. There are days when you’re so tired, you’ll fall asleep as soon as you get to bed." }, { "code": null, "e": 10581, "s": 10459, "text": "With these clues about what makes you drink more coffee, you want to know how likely are you to get a good night’s sleep." }, { "code": null, "e": 10682, "s": 10581, "text": "To do that, you can model your insomnia patterns with Monte Carlo methods, and run some simulations." }, { "code": null, "e": 10934, "s": 10682, "text": "To prepare the inputs of the simulations you took note, during the course of a few weeks, how many times you worked from the couch, wore pajama pants and the days you felt so tired that you quickly fell asleep. Then you turned that into probabilities:" }, { "code": null, "e": 10978, "s": 10934, "text": "Probability of working from the couch: 0.7," }, { "code": null, "e": 11021, "s": 10978, "text": "Probability of wearing pajama pants: 0.35," }, { "code": null, "e": 11083, "s": 11021, "text": "Probability of being so tired, you quickly fall asleep: 0.05." }, { "code": null, "e": 11315, "s": 11083, "text": "You can think of each of these as the probability of success/failure event, meaning, you either wore pajama pants or not. This helps in deciding that the best distribution to model these probabilities is the Bernoulli distribution." }, { "code": null, "e": 11393, "s": 11315, "text": "There are also a couple of constants in your model, which you can also tweak:" }, { "code": null, "e": 11427, "s": 11393, "text": "Number of working hours in a day," }, { "code": null, "e": 11487, "s": 11427, "text": "Number of cups that you can drink without getting insomnia." }, { "code": null, "e": 11515, "s": 11487, "text": "Here’s the model in Python." }, { "code": null, "e": 13189, "s": 11515, "text": "import randomdef insomnia_model(working_hours, coffee_threshold, p_couch, p_pajamas, p_tired):''' The model, i.e., how the different inputs interact to generate the outputModel constants (not picked at random):param working_hours: number of working hours in a day:param coffee_threshold: amount of coffee you need that will for sure result in insomniaModel inputs (picked at random):param p_couch: probability of working from the couch on any given day:param p_pajamas: probability of wearing pajama pants on any given day:param p_tired: probability of ending the day so tired that you'll fall asleep regardless of how many cups of coffee you have:return: The result of the model is either insomnia or sleep.'''# taking 1 sample from the bernoulli distribution with a given probability of success.# a binomial distribution with just 1 trial is equivalent to the bernoulli distribution. that's done by setting size = 1 if bool(np.random.binomial(1, p_tired, 1)[0]): # you're too tired today, you'll fall asleep regardless return False # starting your day, picking the outfit and deciding if you're going to work from the couch day_start = True pajamas = bool(np.random.binomial(1, p_pajamas, 1)[0]) work_from_couch = bool(np.random.binomial(1, p_couch, 1)[0]) while working_hours > 0 and coffee_threshold > 0: if pajamas and day_start: # starting the day with an extra cup of coffee coffee_threshold -= 2 day_start = False if work_from_couch and working_hours % 2 == 0: # if you're working from the couch, you get a cup of coffee every couple of hours coffee_threshold -= 1 working_hours -= 1return coffee_threshold == 0" }, { "code": null, "e": 13329, "s": 13189, "text": "Then you just need to run the model multiple times, aggregate and plot the results. Here, by default, you’ll be running 10,000 simulations." }, { "code": null, "e": 14788, "s": 13329, "text": "import pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltdef run_insomnia_simulations(runs=10000, working_hours=8, coffee_threshold=6, p_couch=0.7, p_pajamas=0.35, p_tired=0.05):''' Running 10,000 simulations (default) and plotting the resultsOnly highlighting here the parameters not mentioned in the model function:param runs: number of times the model will run:return:''' results = [] sim_count = 0 while sim_count < runs: results.append(insomnia_model(working_hours, coffee_threshold, p_couch, p_pajamas, p_tired)) sim_count += 1 # making the output easier to interpret results = list(map(lambda x: 'insomnia' if x else 'sleep', results)) results_pd = pd.DataFrame(data=results) results_pd.columns = ['type'] p_insomnia = round((results_pd[results_pd['type'] == 'insomnia'].count().values[0])/float(runs), 2) p_sleep = round((results_pd[results_pd['type'] == 'sleep'].count().values[0]) / float(runs), 2) print('Probability of having insomnia = ' + str(p_insomnia) + ' || Probability of a good night\\'s sleep = ' + str(p_sleep)) # plotting the output of all model runs fig, ax = plt.subplots(figsize=(12, 7), constrained_layout=True) # removing to and right border ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) # setting the color palette sns.set_palette(\"Set2\") sns.histplot(data=results_pd, x='type', hue='type', legend=False, linewidth=0) ax.xaxis.label.set_visible(False) plt.show()" }, { "code": null, "e": 14837, "s": 14788, "text": "Running the simulations with the default values." }, { "code": null, "e": 14913, "s": 14837, "text": "# running simulations with all the default valuesrun_insomnia_simulations()" }, { "code": null, "e": 15001, "s": 14913, "text": "With these probabilities, you’re actually getting a good night’s sleep 77% of the days!" }, { "code": null, "e": 15195, "s": 15001, "text": "This is a simulation, so you can refine your model any time you want 😀 All you need to do is change the inputs, in this case, the probabilities of the events that lead you to drink more coffee." }, { "code": null, "e": 15337, "s": 15195, "text": "Maybe a more realist model is one where you’ll always be working from the couch and roughly 60% of the days you’re wearing your pajama pants." }, { "code": null, "e": 15491, "s": 15337, "text": "To see that in action, you just need to change the probability of working from the couch to be equal to 1 and probability of wearing pajama pants to 0.6." }, { "code": null, "e": 15542, "s": 15491, "text": "run_insomnia_simulations(p_couch=1, p_pajamas=0.6)" }, { "code": null, "e": 15731, "s": 15542, "text": "With this model, you’re likely to have insomnia. In fact, 57% of the days you’re going to have insomnia if you always work from the couch and wear pajama pants 3 out of 5 days of the week." }, { "code": null, "e": 15943, "s": 15731, "text": "Creating this model opens up a lot of interesting investigations! For instance, you can continue to play around with the inputs and try to find the sweet-spot where you have as few insomnia episodes as possible!" }, { "code": null, "e": 16087, "s": 15943, "text": "Hope you enjoyed this article, and got a better idea about how Monte Carlo methods and simulations can help you understand different phenomena." }, { "code": null, "e": 16107, "s": 16087, "text": "Thanks for reading!" }, { "code": null, "e": 16238, "s": 16107, "text": "[1] Sawilowsky, Shlomo S. (2003). “You think you’ve got trivials?”. Journal of Modern Applied Statistical Methods. 2 (1): 218–225." }, { "code": null, "e": 16537, "s": 16238, "text": "[2] Tenekedjiev KI, Nikolova ND, Kolev K. Applications of Monte Carlo Simulation in Modelling of Biochemical Processes. In: Mode CJ, editor. Applications of Monte Carlo Methods in Biology, Medicine and Other Fields of Science [Internet]. Rijeka (HR): InTech; 2011 Feb 28. Chapter 4. PMID: 28045483." } ]
How to filter some fields in objects and fetch a specific subject name value in MongoDB?
To filter and fetch, use projection along with MongoDB $filter and $match. Let us create a collection with documents − > db.demo507.insertOne( ... { ... ... "Information": ... [ ... {"Name":"John","SubjectName":"MySQL"}, ... {"Name":"Bob","SubjectName":"MongoDB"}, ... {"Name":"Chris","SubjectName":"MySQL"}, ... {"Name":"David","SubjectName":"C++"} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e8836d3987b6e0e9d18f577") } Display all documents from a collection with the help of find() method − > db.demo507.find().pretty(); This will produce the following output − { "_id" : ObjectId("5e8836d3987b6e0e9d18f577"), "Information" : [ { "Name" : "John", "SubjectName" : "MySQL" }, { "Name" : "Bob", "SubjectName" : "MongoDB" }, { "Name" : "Chris", "SubjectName" : "MySQL" }, { "Name" : "David", "SubjectName" : "C++" } ] } Following is the query to filter some fields in objects − > db.demo507.aggregate([ ... {$match: {"Information.SubjectName" : "MySQL" } }, ... {$project: { ... _id:0, ... Information: { ... $filter: { ... input: '$Information', ... as: 'result', ... cond: {$eq: ['$$result.SubjectName', 'MySQL']} ... } ... } ... } ... },{$project: {Information: { SubjectName:1}}} ... ]); This will produce the following output − { "Information" : [ { "SubjectName" : "MySQL" }, { "SubjectName" : "MySQL" } ] }
[ { "code": null, "e": 1181, "s": 1062, "text": "To filter and fetch, use projection along with MongoDB $filter and $match. Let us create a collection with documents −" }, { "code": null, "e": 1549, "s": 1181, "text": "> db.demo507.insertOne(\n... {\n...\n... \"Information\":\n... [\n... {\"Name\":\"John\",\"SubjectName\":\"MySQL\"},\n... {\"Name\":\"Bob\",\"SubjectName\":\"MongoDB\"},\n... {\"Name\":\"Chris\",\"SubjectName\":\"MySQL\"},\n... {\"Name\":\"David\",\"SubjectName\":\"C++\"}\n... ]\n... }\n... );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e8836d3987b6e0e9d18f577\")\n}" }, { "code": null, "e": 1622, "s": 1549, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1652, "s": 1622, "text": "> db.demo507.find().pretty();" }, { "code": null, "e": 1693, "s": 1652, "text": "This will produce the following output −" }, { "code": null, "e": 2076, "s": 1693, "text": "{\n \"_id\" : ObjectId(\"5e8836d3987b6e0e9d18f577\"),\n \"Information\" : [\n {\n \"Name\" : \"John\",\n \"SubjectName\" : \"MySQL\"\n },\n {\n \"Name\" : \"Bob\",\n \"SubjectName\" : \"MongoDB\"\n },\n {\n \"Name\" : \"Chris\",\n \"SubjectName\" : \"MySQL\"\n },\n {\n \"Name\" : \"David\",\n \"SubjectName\" : \"C++\"\n }\n ]\n}" }, { "code": null, "e": 2134, "s": 2076, "text": "Following is the query to filter some fields in objects −" }, { "code": null, "e": 2529, "s": 2134, "text": "> db.demo507.aggregate([\n... {$match: {\"Information.SubjectName\" : \"MySQL\" } },\n... {$project: {\n... _id:0,\n... Information: {\n... $filter: {\n... input: '$Information',\n... as: 'result',\n... cond: {$eq: ['$$result.SubjectName', 'MySQL']}\n... }\n... }\n... }\n... },{$project: {Information: { SubjectName:1}}}\n... ]);" }, { "code": null, "e": 2570, "s": 2529, "text": "This will produce the following output −" }, { "code": null, "e": 2651, "s": 2570, "text": "{ \"Information\" : [ { \"SubjectName\" : \"MySQL\" }, { \"SubjectName\" : \"MySQL\" } ] }" } ]
CSS Interview Questions
Dear readers, these CSS Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of CSS Language. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer: Cascading Style Sheets, fondly referred to as CSS, is a simple design language intended to simplify the process of making web pages presentable. Following are the advantages of using CSS − CSS saves time − You can write CSS once and then reuse same sheet in multiple HTML pages. You can define a style for each HTML element and apply it to as many Web pages as you want. CSS saves time − You can write CSS once and then reuse same sheet in multiple HTML pages. You can define a style for each HTML element and apply it to as many Web pages as you want. Pages load faster − If you are using CSS, you do not need to write HTML tag attributes every time. Just write one CSS rule of a tag and apply it to all the occurrences of that tag. So less code means faster download times. Pages load faster − If you are using CSS, you do not need to write HTML tag attributes every time. Just write one CSS rule of a tag and apply it to all the occurrences of that tag. So less code means faster download times. Easy maintenance − To make a global change, simply change the style, and all elements in all the web pages will be updated automatically. Easy maintenance − To make a global change, simply change the style, and all elements in all the web pages will be updated automatically. Superior styles to HTML − CSS has a much wider array of attributes than HTML, so you can give a far better look to your HTML page in comparison to HTML attributes. Superior styles to HTML − CSS has a much wider array of attributes than HTML, so you can give a far better look to your HTML page in comparison to HTML attributes. Multiple Device Compatibility − Style sheets allow content to be optimized for more than one type of device. By using the same HTML document, different versions of a website can be presented for handheld devices such as PDAs and cell phones or for printing. Multiple Device Compatibility − Style sheets allow content to be optimized for more than one type of device. By using the same HTML document, different versions of a website can be presented for handheld devices such as PDAs and cell phones or for printing. Global web standards − Now HTML attributes are being deprecated and it is being recommended to use CSS. So its a good idea to start using CSS in all the HTML pages to make them compatible to future browsers. Global web standards − Now HTML attributes are being deprecated and it is being recommended to use CSS. So its a good idea to start using CSS in all the HTML pages to make them compatible to future browsers. Offline Browsing − CSS can store web applications locally with the help of an offline catche.Using of this, we can view offline websites.The cache also ensures faster loading and better overall performance of the website. Offline Browsing − CSS can store web applications locally with the help of an offline catche.Using of this, we can view offline websites.The cache also ensures faster loading and better overall performance of the website. Platform Independence − The Script offer consistent platform independence and can support latest browsers as well. Platform Independence − The Script offer consistent platform independence and can support latest browsers as well. A style rule is made of three parts − Selector − A selector is an HTML tag at which a style will be applied. This could be any tag like <h1> or <table> etc. Selector − A selector is an HTML tag at which a style will be applied. This could be any tag like <h1> or <table> etc. Property − A property is a type of attribute of HTML tag. Put simply, all the HTML attributes are converted into CSS properties. They could be color, border etc. Property − A property is a type of attribute of HTML tag. Put simply, all the HTML attributes are converted into CSS properties. They could be color, border etc. Value − Values are assigned to properties. For example, color property can have value either red or #F1F1F1 etc. Value − Values are assigned to properties. For example, color property can have value either red or #F1F1F1 etc. Type selector quite simply matches the name of an element type. To give a color to all level 1 headings − h1 { color: #36CFFF; } Rather than selecting elements of a specific type, the universal selector quite simply matches the name of any element type − * { color: #000000; } This rule renders the content of every element in our document in black. Suppose you want to apply a style rule to a particular element only when it lies inside a particular element. As given in the following example, style rule will apply to <em> element only when it lies inside <ul> tag. ul em { color: #000000; } You can define style rules based on the class attribute of the elements. All the elements having that class will be formatted according to the defined rule. .black { color: #000000; } This rule renders the content in black for every element with class attribute set to black in our document. You can make it a bit more particular. For example − h1.black { color: #000000; } This rule renders the content in black for only <h1> elements with class attribute set to black. You can define style rules based on the id attribute of the elements. All the elements having that id will be formatted according to the defined rule. #black { color: #000000; } This rule renders the content in black for every element with id attribute set to black in our document. ou can make it a bit more particular. For example − h1#black { color: #000000; } This rule renders the content in black for only <h1> elements with id attribute set to black. Consider the following example − body > p { color: #000000; } This rule will render all the paragraphs in black if they are direct child of <body> element. Other paragraphs put inside other elements like <div> or <td> would not have any effect of this rule. You can also apply styles to HTML elements with particular attributes. The style rule below will match all the input elements having a type attribute with a value of text − input[type = "text"] { color: #000000; } The advantage to this method is that the <input type = "submit" /> element is unaffected, and the color applied only to the desired text fields. p[lang] : Selects all paragraph elements with a lang attribute. p[lang="fr"] - Selects all paragraph elements whose lang attribute has a value of exactly "fr". p[lang~="fr"] - Selects all paragraph elements whose lang attribute contains the word "fr". p[lang|="en"] - Selects all paragraph elements whose lang attribute contains values that are exactly "en", or begin with "en-". There are four ways to associate styles with your HTML document. Most commonly used methods are inline CSS and External CSS. Embedded CSS − The <style> Element: You can put your CSS rules into an HTML document using the <style> element. Embedded CSS − The <style> Element: You can put your CSS rules into an HTML document using the <style> element. Inline CSS − The style Attribute: You can use style attribute of any HTML element to define style rules. Inline CSS − The style Attribute: You can use style attribute of any HTML element to define style rules. External CSS − The <link> Element: The <link> element can be used to include an external stylesheet file in your HTML document. External CSS − The <link> Element: The <link> element can be used to include an external stylesheet file in your HTML document. Imported CSS − @import Rule: @import is used to import an external stylesheet in a manner similar to the <link> element. Imported CSS − @import Rule: @import is used to import an external stylesheet in a manner similar to the <link> element. Following is the rule to override any Style Sheet Rule − Any inline style sheet takes highest priority. So, it will override any rule defined in <style>...</style> tags or rules defined in any external style sheet file. Any inline style sheet takes highest priority. So, it will override any rule defined in <style>...</style> tags or rules defined in any external style sheet file. Any rule defined in <style>...</style> tags will override rules defined in any external style sheet file. Any rule defined in <style>...</style> tags will override rules defined in any external style sheet file. Any rule defined in external style sheet file takes lowest priority, and rules defined in this file will be applied only when above two rules are not applicable. Any rule defined in external style sheet file takes lowest priority, and rules defined in this file will be applied only when above two rules are not applicable. % - Defines a measurement as a percentage relative to another value, typically an enclosing element. p {font-size: 16pt; line-height: 125%;} cm − Defines a measurement in centimeters. div {margin-bottom: 2cm;} em − A relative measurement for the height of a font in em spaces. Because an em unit is equivalent to the size of a given font, if you assign a font to 12pt, each "em" unit would be 12pt; thus, 2em would be 24pt. p {letter-spacing: 7em;} ex − This value defines a measurement relative to a font's x-height. The x-height is determined by the height of the font's lowercase letter. p {font-size: 24pt; line-height: 3ex;} in − Defines a measurement in inches. p {word-spacing: .15in;} mm − Defines a measurement in millimeters. p {word-spacing: 15mm;} pc − Defines a measurement in picas. A pica is equivalent to 12 points; thus, there are 6 picas per inch. p {font-size: 20pc;} pt − Defines a measurement in points. A point is defined as 1/72nd of an inch. body {font-size: 18pt;} px − Defines a measurement in screen pixels. p {padding: 25px;} vh − 1% of viewport height. h2 { font-size: 3.0vh; } vw − 1% of viewport width. h1 { font-size: 5.9vw; } vmin 1vw or 1vh, whichever is smaller. p { font-size: 2vmin;} You can specify your color values in various formats. Following table lists all the possible formats − There is the list of 216 colors which are supposed to be most safe and computer independent colors. These colors vary from hexa code 000000 to FFFFFF. These colors are safe to use because they ensure that all computers would display the colors correctly when running a 256 color palette. The background-color property is used to set the background color of an element. The background-image property is used to set the background image of an element. The background-repeat property is used to control the repetition of an image in the background. The background-position property is used to control the position of an image in the background. The background-attachment property is used to control the scrolling of an image in the background. The background property is used as a shorthand to specify a number of other background properties. The font-family property is used to change the face of a font. The font-style property is used to make a font italic or oblique. The font-variant property is used to create a small-caps effect. The font-weight property is used to increase or decrease how bold or light a font appears. The font-size property is used to increase or decrease the size of a font. The font property is used as shorthand to specify a number of other font properties. The color property is used to set the color of a text. The direction property is used to set the text direction. The letter-spacing property is used to add or subtract space between the letters that make up a word. The word-spacing property is used to add or subtract space between the words of a sentence. The text-indent property is used to indent the text of a paragraph. The text-align property is used to align the text of a document. The text-decoration property is used to underline, overline, and strikethrough text. The text-transform property is used to capitalize text or convert text to uppercase or lowercase letters. The white-space property is used to control the flow and formatting of text. The text-shadow property is used to set the text shadow around a text. The border property is used to set the width of an image border. The height property is used to set the height of an image. The width property is used to set the width of an image. The -moz-opacity property is used to set the opacity of an image. The :link signifies unvisited hyperlinks. The :visited signifies visited hyperlinks. The :hover signifies an element that currently has the user's mouse pointer hovering over it. The :active signifies an element on which the user is currently clicking. The border-collapse specifies whether the browser should control the appearance of the adjacent borders that touch each other or whether each cell should maintain its style. The border-spacing specifies the width that should appear between table cells. The caption-side captions are presented in the <caption> element. By default, these are rendered above the table in the document. You use the caption-side property to control the placement of the table caption. The empty-cells specifies whether the border should be shown if a cell is empty. The table-layout allows browsers to speed up layout of a table by using the first width properties it comes across for the rest of a column rather than having to load the whole table before rendering it. The border-color specifies the color of a border. The border-style specifies whether a border should be solid, dashed line, double line, or one of the other possible values. The border-width specifies the width of a border. The margin specifies a shorthand property for setting the margin properties in one declaration. The margin-bottom specifies the bottom margin of an element. The margin-top specifies the top margin of an element. The margin-left specifies the left margin of an element. The margin-right specifies the right margin of an element. The list-style-type allows you to control the shape or appearance of the marker. The list-style-position specifies whether a long point that wraps to a second line should align with the first line or start underneath the start of the marker. The list-style-image specifies an image for the marker rather than a bullet point or number. The list-style serves as shorthand for the styling properties. The marker-offset specifies the distance between a marker and the text in the list. The padding-bottom specifies the bottom padding of an element. The padding-top specifies the top padding of an element. The padding-left specifies the left padding of an element. The padding-right specifies the right padding of an element. The padding serves as shorthand for the all the padding properties. The cursor property of CSS allows you to specify the type of cursor that should be displayed to the user. auto − Shape of the cursor depends on the context area it is over. For example, an 'I' over text, a 'hand' over a link, and so on. crosshair − A crosshair or plus sign. default − An arrow. pointer − A pointing hand (in IE 4 this value is hand). move or text − The 'I' bar. wait − An hour glass. help − A question mark or balloon, ideal for use over help buttons. Yes! set the url as the source of a cursor image file. The outline-width property is used to set the width of the outline. The outline-style property is used to set the line style for the outline. The outline-color property is used to set the color of the outline. The outline property is used to set all the outlining properties in a single statement. The height property is used to set the height of a box. The width property is used to set the width of a box. Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong. Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-) 33 Lectures 2.5 hours Anadi Sharma 26 Lectures 2.5 hours Frahaan Hussain 44 Lectures 4.5 hours DigiFisk (Programming Is Fun) 21 Lectures 2.5 hours DigiFisk (Programming Is Fun) 51 Lectures 7.5 hours DigiFisk (Programming Is Fun) 52 Lectures 4 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 3065, "s": 2626, "text": "Dear readers, these CSS Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of CSS Language. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer:" }, { "code": null, "e": 3211, "s": 3065, "text": " Cascading Style Sheets, fondly referred to as CSS, is a simple design language intended to simplify the process of making web pages presentable." }, { "code": null, "e": 3255, "s": 3211, "text": "Following are the advantages of using CSS −" }, { "code": null, "e": 3437, "s": 3255, "text": "CSS saves time − You can write CSS once and then reuse same sheet in multiple HTML pages. You can define a style for each HTML element and apply it to as many Web pages as you want." }, { "code": null, "e": 3619, "s": 3437, "text": "CSS saves time − You can write CSS once and then reuse same sheet in multiple HTML pages. You can define a style for each HTML element and apply it to as many Web pages as you want." }, { "code": null, "e": 3842, "s": 3619, "text": "Pages load faster − If you are using CSS, you do not need to write HTML tag attributes every time. Just write one CSS rule of a tag and apply it to all the occurrences of that tag. So less code means faster download times." }, { "code": null, "e": 4065, "s": 3842, "text": "Pages load faster − If you are using CSS, you do not need to write HTML tag attributes every time. Just write one CSS rule of a tag and apply it to all the occurrences of that tag. So less code means faster download times." }, { "code": null, "e": 4203, "s": 4065, "text": "Easy maintenance − To make a global change, simply change the style, and all elements in all the web pages will be updated automatically." }, { "code": null, "e": 4341, "s": 4203, "text": "Easy maintenance − To make a global change, simply change the style, and all elements in all the web pages will be updated automatically." }, { "code": null, "e": 4505, "s": 4341, "text": "Superior styles to HTML − CSS has a much wider array of attributes than HTML, so you can give a far better look to your HTML page in comparison to HTML attributes." }, { "code": null, "e": 4669, "s": 4505, "text": "Superior styles to HTML − CSS has a much wider array of attributes than HTML, so you can give a far better look to your HTML page in comparison to HTML attributes." }, { "code": null, "e": 4927, "s": 4669, "text": "Multiple Device Compatibility − Style sheets allow content to be optimized for more than one type of device. By using the same HTML document, different versions of a website can be presented for handheld devices such as PDAs and cell phones or for printing." }, { "code": null, "e": 5185, "s": 4927, "text": "Multiple Device Compatibility − Style sheets allow content to be optimized for more than one type of device. By using the same HTML document, different versions of a website can be presented for handheld devices such as PDAs and cell phones or for printing." }, { "code": null, "e": 5393, "s": 5185, "text": "Global web standards − Now HTML attributes are being deprecated and it is being recommended to use CSS. So its a good idea to start using CSS in all the HTML pages to make them compatible to future browsers." }, { "code": null, "e": 5601, "s": 5393, "text": "Global web standards − Now HTML attributes are being deprecated and it is being recommended to use CSS. So its a good idea to start using CSS in all the HTML pages to make them compatible to future browsers." }, { "code": null, "e": 5823, "s": 5601, "text": "Offline Browsing − CSS can store web applications locally with the help of an offline catche.Using of this, we can view offline websites.The cache also ensures faster loading and better overall performance of the website." }, { "code": null, "e": 6045, "s": 5823, "text": "Offline Browsing − CSS can store web applications locally with the help of an offline catche.Using of this, we can view offline websites.The cache also ensures faster loading and better overall performance of the website." }, { "code": null, "e": 6160, "s": 6045, "text": "Platform Independence − The Script offer consistent platform independence and can support latest browsers as well." }, { "code": null, "e": 6275, "s": 6160, "text": "Platform Independence − The Script offer consistent platform independence and can support latest browsers as well." }, { "code": null, "e": 6314, "s": 6275, "text": " A style rule is made of three parts −" }, { "code": null, "e": 6433, "s": 6314, "text": "Selector − A selector is an HTML tag at which a style will be applied. This could be any tag like <h1> or <table> etc." }, { "code": null, "e": 6552, "s": 6433, "text": "Selector − A selector is an HTML tag at which a style will be applied. This could be any tag like <h1> or <table> etc." }, { "code": null, "e": 6714, "s": 6552, "text": "Property − A property is a type of attribute of HTML tag. Put simply, all the HTML attributes are converted into CSS properties. They could be color, border etc." }, { "code": null, "e": 6876, "s": 6714, "text": "Property − A property is a type of attribute of HTML tag. Put simply, all the HTML attributes are converted into CSS properties. They could be color, border etc." }, { "code": null, "e": 6989, "s": 6876, "text": "Value − Values are assigned to properties. For example, color property can have value either red or #F1F1F1 etc." }, { "code": null, "e": 7102, "s": 6989, "text": "Value − Values are assigned to properties. For example, color property can have value either red or #F1F1F1 etc." }, { "code": null, "e": 7209, "s": 7102, "text": " Type selector quite simply matches the name of an element type. To give a color to all level 1 headings −" }, { "code": null, "e": 7236, "s": 7209, "text": "h1 {\n color: #36CFFF; \n}" }, { "code": null, "e": 7363, "s": 7236, "text": " Rather than selecting elements of a specific type, the universal selector quite simply matches the name of any element type −" }, { "code": null, "e": 7390, "s": 7363, "text": "* { \n color: #000000; \n}" }, { "code": null, "e": 7463, "s": 7390, "text": "This rule renders the content of every element in our document in black." }, { "code": null, "e": 7682, "s": 7463, "text": " Suppose you want to apply a style rule to a particular element only when it lies inside a particular element. As given in the following example, style rule will apply to <em> element only when it lies inside <ul> tag." }, { "code": null, "e": 7712, "s": 7682, "text": "ul em {\n color: #000000; \n}" }, { "code": null, "e": 7870, "s": 7712, "text": " You can define style rules based on the class attribute of the elements. All the elements having that class will be formatted according to the defined rule." }, { "code": null, "e": 7901, "s": 7870, "text": ".black {\n color: #000000; \n}" }, { "code": null, "e": 8010, "s": 7901, "text": "This rule renders the content in black for every element with class attribute set to black in our document. " }, { "code": null, "e": 8064, "s": 8010, "text": " You can make it a bit more particular. For example −" }, { "code": null, "e": 8097, "s": 8064, "text": "h1.black {\n color: #000000; \n}" }, { "code": null, "e": 8194, "s": 8097, "text": "This rule renders the content in black for only <h1> elements with class attribute set to black." }, { "code": null, "e": 8346, "s": 8194, "text": " You can define style rules based on the id attribute of the elements. All the elements having that id will be formatted according to the defined rule." }, { "code": null, "e": 8377, "s": 8346, "text": "#black {\n color: #000000; \n}" }, { "code": null, "e": 8483, "s": 8377, "text": "This rule renders the content in black for every element with id attribute set to black in our document. " }, { "code": null, "e": 8536, "s": 8483, "text": " ou can make it a bit more particular. For example −" }, { "code": null, "e": 8569, "s": 8536, "text": "h1#black {\n color: #000000; \n}" }, { "code": null, "e": 8663, "s": 8569, "text": "This rule renders the content in black for only <h1> elements with id attribute set to black." }, { "code": null, "e": 8697, "s": 8663, "text": " Consider the following example −" }, { "code": null, "e": 8730, "s": 8697, "text": "body > p {\n color: #000000; \n}" }, { "code": null, "e": 8926, "s": 8730, "text": "This rule will render all the paragraphs in black if they are direct child of <body> element. Other paragraphs put inside other elements like <div> or <td> would not have any effect of this rule." }, { "code": null, "e": 9100, "s": 8926, "text": " You can also apply styles to HTML elements with particular attributes. The style rule below will match all the input elements having a type attribute with a value of text −" }, { "code": null, "e": 9145, "s": 9100, "text": "input[type = \"text\"] {\n color: #000000; \n}" }, { "code": null, "e": 9290, "s": 9145, "text": "The advantage to this method is that the <input type = \"submit\" /> element is unaffected, and the color applied only to the desired text fields." }, { "code": null, "e": 9355, "s": 9290, "text": " p[lang] : Selects all paragraph elements with a lang attribute." }, { "code": null, "e": 9452, "s": 9355, "text": " p[lang=\"fr\"] - Selects all paragraph elements whose lang attribute has a value of exactly \"fr\"." }, { "code": null, "e": 9545, "s": 9452, "text": " p[lang~=\"fr\"] - Selects all paragraph elements whose lang attribute contains the word \"fr\"." }, { "code": null, "e": 9674, "s": 9545, "text": " p[lang|=\"en\"] - Selects all paragraph elements whose lang attribute contains values that are exactly \"en\", or begin with \"en-\"." }, { "code": null, "e": 9800, "s": 9674, "text": " There are four ways to associate styles with your HTML document. Most commonly used methods are inline CSS and External CSS." }, { "code": null, "e": 9912, "s": 9800, "text": "Embedded CSS − The <style> Element: You can put your CSS rules into an HTML document using the <style> element." }, { "code": null, "e": 10024, "s": 9912, "text": "Embedded CSS − The <style> Element: You can put your CSS rules into an HTML document using the <style> element." }, { "code": null, "e": 10129, "s": 10024, "text": "Inline CSS − The style Attribute: You can use style attribute of any HTML element to define style rules." }, { "code": null, "e": 10234, "s": 10129, "text": "Inline CSS − The style Attribute: You can use style attribute of any HTML element to define style rules." }, { "code": null, "e": 10362, "s": 10234, "text": "External CSS − The <link> Element: The <link> element can be used to include an external stylesheet file in your HTML document." }, { "code": null, "e": 10490, "s": 10362, "text": "External CSS − The <link> Element: The <link> element can be used to include an external stylesheet file in your HTML document." }, { "code": null, "e": 10612, "s": 10490, "text": "Imported CSS − @import Rule: @import is used to import an external stylesheet in a manner similar to the <link> element. " }, { "code": null, "e": 10734, "s": 10612, "text": "Imported CSS − @import Rule: @import is used to import an external stylesheet in a manner similar to the <link> element. " }, { "code": null, "e": 10792, "s": 10734, "text": " Following is the rule to override any Style Sheet Rule −" }, { "code": null, "e": 10955, "s": 10792, "text": "Any inline style sheet takes highest priority. So, it will override any rule defined in <style>...</style> tags or rules defined in any external style sheet file." }, { "code": null, "e": 11118, "s": 10955, "text": "Any inline style sheet takes highest priority. So, it will override any rule defined in <style>...</style> tags or rules defined in any external style sheet file." }, { "code": null, "e": 11224, "s": 11118, "text": "Any rule defined in <style>...</style> tags will override rules defined in any external style sheet file." }, { "code": null, "e": 11330, "s": 11224, "text": "Any rule defined in <style>...</style> tags will override rules defined in any external style sheet file." }, { "code": null, "e": 11492, "s": 11330, "text": "Any rule defined in external style sheet file takes lowest priority, and rules defined in this file will be applied only when above two rules are not applicable." }, { "code": null, "e": 11654, "s": 11492, "text": "Any rule defined in external style sheet file takes lowest priority, and rules defined in this file will be applied only when above two rules are not applicable." }, { "code": null, "e": 11756, "s": 11654, "text": " % - Defines a measurement as a percentage relative to another value, typically an enclosing element." }, { "code": null, "e": 11796, "s": 11756, "text": "p {font-size: 16pt; line-height: 125%;}" }, { "code": null, "e": 11841, "s": 11796, "text": " cm − Defines a measurement in centimeters. " }, { "code": null, "e": 11867, "s": 11841, "text": "div {margin-bottom: 2cm;}" }, { "code": null, "e": 12083, "s": 11867, "text": " em − A relative measurement for the height of a font in em spaces. Because an em unit is equivalent to the size of a given font, if you assign a font to 12pt, each \"em\" unit would be 12pt; thus, 2em would be 24pt. " }, { "code": null, "e": 12108, "s": 12083, "text": "p {letter-spacing: 7em;}" }, { "code": null, "e": 12251, "s": 12108, "text": " ex − This value defines a measurement relative to a font's x-height. The x-height is determined by the height of the font's lowercase letter." }, { "code": null, "e": 12290, "s": 12251, "text": "p {font-size: 24pt; line-height: 3ex;}" }, { "code": null, "e": 12330, "s": 12290, "text": " in − Defines a measurement in inches. " }, { "code": null, "e": 12355, "s": 12330, "text": "p {word-spacing: .15in;}" }, { "code": null, "e": 12400, "s": 12355, "text": " mm − Defines a measurement in millimeters. " }, { "code": null, "e": 12424, "s": 12400, "text": "p {word-spacing: 15mm;}" }, { "code": null, "e": 12532, "s": 12424, "text": " pc − Defines a measurement in picas. A pica is equivalent to 12 points; thus, there are 6 picas per inch. " }, { "code": null, "e": 12553, "s": 12532, "text": "p {font-size: 20pc;}" }, { "code": null, "e": 12634, "s": 12553, "text": " pt − Defines a measurement in points. A point is defined as 1/72nd of an inch. " }, { "code": null, "e": 12658, "s": 12634, "text": "body {font-size: 18pt;}" }, { "code": null, "e": 12705, "s": 12658, "text": " px − Defines a measurement in screen pixels. " }, { "code": null, "e": 12724, "s": 12705, "text": "p {padding: 25px;}" }, { "code": null, "e": 12754, "s": 12724, "text": " vh − 1% of viewport height. " }, { "code": null, "e": 12779, "s": 12754, "text": "h2 { font-size: 3.0vh; }" }, { "code": null, "e": 12808, "s": 12779, "text": " vw − 1% of viewport width. " }, { "code": null, "e": 12834, "s": 12808, "text": "h1 { font-size: 5.9vw; } " }, { "code": null, "e": 12874, "s": 12834, "text": " vmin 1vw or 1vh, whichever is smaller." }, { "code": null, "e": 12897, "s": 12874, "text": "p { font-size: 2vmin;}" }, { "code": null, "e": 13001, "s": 12897, "text": " You can specify your color values in various formats. Following table lists all the possible formats −" }, { "code": null, "e": 13290, "s": 13001, "text": " There is the list of 216 colors which are supposed to be most safe and computer independent colors. These colors vary from hexa code 000000 to FFFFFF. These colors are safe to use because they ensure that all computers would display the colors correctly when running a 256 color palette." }, { "code": null, "e": 13372, "s": 13290, "text": " The background-color property is used to set the background color of an element." }, { "code": null, "e": 13454, "s": 13372, "text": " The background-image property is used to set the background image of an element." }, { "code": null, "e": 13551, "s": 13454, "text": " The background-repeat property is used to control the repetition of an image in the background." }, { "code": null, "e": 13648, "s": 13551, "text": " The background-position property is used to control the position of an image in the background." }, { "code": null, "e": 13748, "s": 13648, "text": " The background-attachment property is used to control the scrolling of an image in the background." }, { "code": null, "e": 13848, "s": 13748, "text": " The background property is used as a shorthand to specify a number of other background properties." }, { "code": null, "e": 13912, "s": 13848, "text": " The font-family property is used to change the face of a font." }, { "code": null, "e": 13979, "s": 13912, "text": " The font-style property is used to make a font italic or oblique." }, { "code": null, "e": 14045, "s": 13979, "text": " The font-variant property is used to create a small-caps effect." }, { "code": null, "e": 14137, "s": 14045, "text": " The font-weight property is used to increase or decrease how bold or light a font appears." }, { "code": null, "e": 14213, "s": 14137, "text": " The font-size property is used to increase or decrease the size of a font." }, { "code": null, "e": 14299, "s": 14213, "text": " The font property is used as shorthand to specify a number of other font properties." }, { "code": null, "e": 14355, "s": 14299, "text": " The color property is used to set the color of a text." }, { "code": null, "e": 14414, "s": 14355, "text": " The direction property is used to set the text direction." }, { "code": null, "e": 14517, "s": 14414, "text": " The letter-spacing property is used to add or subtract space between the letters that make up a word." }, { "code": null, "e": 14610, "s": 14517, "text": " The word-spacing property is used to add or subtract space between the words of a sentence." }, { "code": null, "e": 14679, "s": 14610, "text": " The text-indent property is used to indent the text of a paragraph." }, { "code": null, "e": 14745, "s": 14679, "text": " The text-align property is used to align the text of a document." }, { "code": null, "e": 14831, "s": 14745, "text": " The text-decoration property is used to underline, overline, and strikethrough text." }, { "code": null, "e": 14938, "s": 14831, "text": " The text-transform property is used to capitalize text or convert text to uppercase or lowercase letters." }, { "code": null, "e": 15016, "s": 14938, "text": " The white-space property is used to control the flow and formatting of text." }, { "code": null, "e": 15088, "s": 15016, "text": " The text-shadow property is used to set the text shadow around a text." }, { "code": null, "e": 15154, "s": 15088, "text": " The border property is used to set the width of an image border." }, { "code": null, "e": 15214, "s": 15154, "text": " The height property is used to set the height of an image." }, { "code": null, "e": 15272, "s": 15214, "text": " The width property is used to set the width of an image." }, { "code": null, "e": 15339, "s": 15272, "text": " The -moz-opacity property is used to set the opacity of an image." }, { "code": null, "e": 15382, "s": 15339, "text": " The :link signifies unvisited hyperlinks." }, { "code": null, "e": 15426, "s": 15382, "text": " The :visited signifies visited hyperlinks." }, { "code": null, "e": 15521, "s": 15426, "text": " The :hover signifies an element that currently has the user's mouse pointer hovering over it." }, { "code": null, "e": 15596, "s": 15521, "text": " The :active signifies an element on which the user is currently clicking." }, { "code": null, "e": 15771, "s": 15596, "text": " The border-collapse specifies whether the browser should control the appearance of the adjacent borders that touch each other or whether each cell should maintain its style." }, { "code": null, "e": 15851, "s": 15771, "text": " The border-spacing specifies the width that should appear between table cells." }, { "code": null, "e": 16063, "s": 15851, "text": " The caption-side captions are presented in the <caption> element. By default, these are rendered above the table in the document. You use the caption-side property to control the placement of the table caption." }, { "code": null, "e": 16145, "s": 16063, "text": " The empty-cells specifies whether the border should be shown if a cell is empty." }, { "code": null, "e": 16350, "s": 16145, "text": " The table-layout allows browsers to speed up layout of a table by using the first width properties it comes across for the rest of a column rather than having to load the whole table before rendering it." }, { "code": null, "e": 16401, "s": 16350, "text": " The border-color specifies the color of a border." }, { "code": null, "e": 16526, "s": 16401, "text": " The border-style specifies whether a border should be solid, dashed line, double line, or one of the other possible values." }, { "code": null, "e": 16577, "s": 16526, "text": " The border-width specifies the width of a border." }, { "code": null, "e": 16674, "s": 16577, "text": " The margin specifies a shorthand property for setting the margin properties in one declaration." }, { "code": null, "e": 16736, "s": 16674, "text": " The margin-bottom specifies the bottom margin of an element." }, { "code": null, "e": 16792, "s": 16736, "text": " The margin-top specifies the top margin of an element." }, { "code": null, "e": 16850, "s": 16792, "text": " The margin-left specifies the left margin of an element." }, { "code": null, "e": 16910, "s": 16850, "text": " The margin-right specifies the right margin of an element." }, { "code": null, "e": 16992, "s": 16910, "text": " The list-style-type allows you to control the shape or appearance of the marker." }, { "code": null, "e": 17154, "s": 16992, "text": " The list-style-position specifies whether a long point that wraps to a second line should align with the first line or start underneath the start of the marker." }, { "code": null, "e": 17248, "s": 17154, "text": " The list-style-image specifies an image for the marker rather than a bullet point or number." }, { "code": null, "e": 17312, "s": 17248, "text": " The list-style serves as shorthand for the styling properties." }, { "code": null, "e": 17397, "s": 17312, "text": " The marker-offset specifies the distance between a marker and the text in the list." }, { "code": null, "e": 17461, "s": 17397, "text": " The padding-bottom specifies the bottom padding of an element." }, { "code": null, "e": 17519, "s": 17461, "text": " The padding-top specifies the top padding of an element." }, { "code": null, "e": 17579, "s": 17519, "text": " The padding-left specifies the left padding of an element." }, { "code": null, "e": 17641, "s": 17579, "text": " The padding-right specifies the right padding of an element." }, { "code": null, "e": 17710, "s": 17641, "text": " The padding serves as shorthand for the all the padding properties." }, { "code": null, "e": 17817, "s": 17710, "text": " The cursor property of CSS allows you to specify the type of cursor that should be displayed to the user." }, { "code": null, "e": 17949, "s": 17817, "text": " auto − Shape of the cursor depends on the context area it is over. For example, an 'I' over text, a 'hand' over a link, and so on." }, { "code": null, "e": 17988, "s": 17949, "text": " crosshair − A crosshair or plus sign." }, { "code": null, "e": 18009, "s": 17988, "text": " default − An arrow." }, { "code": null, "e": 18066, "s": 18009, "text": " pointer − A pointing hand (in IE 4 this value is hand)." }, { "code": null, "e": 18095, "s": 18066, "text": " move or text − The 'I' bar." }, { "code": null, "e": 18118, "s": 18095, "text": " wait − An hour glass." }, { "code": null, "e": 18187, "s": 18118, "text": " help − A question mark or balloon, ideal for use over help buttons." }, { "code": null, "e": 18243, "s": 18187, "text": " Yes! set the url as the source of a cursor image file." }, { "code": null, "e": 18312, "s": 18243, "text": " The outline-width property is used to set the width of the outline." }, { "code": null, "e": 18387, "s": 18312, "text": " The outline-style property is used to set the line style for the outline." }, { "code": null, "e": 18456, "s": 18387, "text": " The outline-color property is used to set the color of the outline." }, { "code": null, "e": 18545, "s": 18456, "text": " The outline property is used to set all the outlining properties in a single statement." }, { "code": null, "e": 18602, "s": 18545, "text": " The height property is used to set the height of a box." }, { "code": null, "e": 18657, "s": 18602, "text": " The width property is used to set the width of a box." }, { "code": null, "e": 18944, "s": 18657, "text": "Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong." }, { "code": null, "e": 19274, "s": 18944, "text": "Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)" }, { "code": null, "e": 19309, "s": 19274, "text": "\n 33 Lectures \n 2.5 hours \n" }, { "code": null, "e": 19323, "s": 19309, "text": " Anadi Sharma" }, { "code": null, "e": 19358, "s": 19323, "text": "\n 26 Lectures \n 2.5 hours \n" }, { "code": null, "e": 19375, "s": 19358, "text": " Frahaan Hussain" }, { "code": null, "e": 19410, "s": 19375, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 19441, "s": 19410, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 19476, "s": 19441, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 19507, "s": 19476, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 19542, "s": 19507, "text": "\n 51 Lectures \n 7.5 hours \n" }, { "code": null, "e": 19573, "s": 19542, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 19606, "s": 19573, "text": "\n 52 Lectures \n 4 hours \n" }, { "code": null, "e": 19637, "s": 19606, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 19644, "s": 19637, "text": " Print" }, { "code": null, "e": 19655, "s": 19644, "text": " Add Notes" } ]
Generating Test Cases (generate() and generate_n() in C++
In this section we will see how we can use C++ STL function to generate test cases. Sometimes generating test cases for array programs can be very complicated and inefficient process. C++ provides two methods to generate test cases. These methods are as follows − The C++ function std::algorithm::generate() assigns the value returned by successive calls to gen to the elements in the range of first to last. It takes three parameters first, last and gen, these are forward iterator to the initial position, backward iterator to the final position and generator function that is called with no argument, and return values. Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; int create_random() { return (rand() % 1000); } int main () { srand(time(NULL)); vector<int> data(15); generate(data.begin(), data.end(), create_random); for (int i=0; i<data.size(); i++) cout << data[i] << " " ; } 449 180 785 629 547 912 581 520 534 778 670 302 345 965 107 The C++ function std::algorithm::generate_n() assigns the value returned by successive calls to gen for first n elements. It takes three parameters first, n and gen, these are forward iterator to the initial position, number of calls will be there and generator function that is called with no argument, and return values. Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; int create_random() { return (rand() % 1000); } int main () { srand(time(NULL)); vector<int> data(15); generate_n(data.begin(), 6, create_random); for (int i=0; i<data.size(); i++) cout << data[i] << " " ; } 540 744 814 771 254 913 0 0 0 0 0 0 0 0 0
[ { "code": null, "e": 1326, "s": 1062, "text": "In this section we will see how we can use C++ STL function to generate test cases. Sometimes generating test cases for array programs can be very complicated and inefficient process. C++ provides two methods to generate test cases. These methods are as follows −" }, { "code": null, "e": 1685, "s": 1326, "text": "The C++ function std::algorithm::generate() assigns the value returned by successive calls to gen to the elements in the range of first to last. It takes three parameters first, last and gen, these are forward iterator to the initial position, backward iterator to the final position and generator function that is called with no argument, and return values." }, { "code": null, "e": 1755, "s": 1685, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1766, "s": 1755, "text": " Live Demo" }, { "code": null, "e": 2048, "s": 1766, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint create_random() {\n return (rand() % 1000);\n}\nint main () {\n srand(time(NULL));\n vector<int> data(15);\n generate(data.begin(), data.end(), create_random);\n for (int i=0; i<data.size(); i++)\n cout << data[i] << \" \" ;\n}" }, { "code": null, "e": 2108, "s": 2048, "text": "449 180 785 629 547 912 581 520 534 778 670 302 345 965 107" }, { "code": null, "e": 2431, "s": 2108, "text": "The C++ function std::algorithm::generate_n() assigns the value returned by successive calls to gen for first n elements. It takes three parameters first, n and gen, these are forward iterator to the initial position, number of calls will be there and generator function that is called with no argument, and return values." }, { "code": null, "e": 2501, "s": 2431, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2512, "s": 2501, "text": " Live Demo" }, { "code": null, "e": 2787, "s": 2512, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint create_random() {\n return (rand() % 1000);\n}\nint main () {\n srand(time(NULL));\n vector<int> data(15);\n generate_n(data.begin(), 6, create_random);\n for (int i=0; i<data.size(); i++)\n cout << data[i] << \" \" ;\n}" }, { "code": null, "e": 2829, "s": 2787, "text": "540 744 814 771 254 913 0 0 0 0 0 0 0 0 0" } ]
Hide Your Secret Keys Using Environment Variables | by AnBento | Towards Data Science
A course I would strongly recommend to my readers: Command Line Automation In Python (DataCamp) → Learn to automate many common file system tasks and be able to manage and communicate with processes. Suppose you were working on a data science project and you decided to pull data from the company database by establishing a connection using Python. What if there was a need to share your script via GitHub for the wider team to review? Well, in that case, better your secret details were hidden in order to avoid other people misusing them. In this article I will show how to use environment variables through the command line to keep username, password and database name safe, avoiding undesired information leakage. towardsdatascience.com Environment variables are KEY=value pairs that like Shell variables can be created through the command line, but more powerful as, once declared, they can be used by any programming language since they are linked to your environment/operating system. In the command line environment: the variable KEY has to be written in capital letters and can be a mix of characters, numbers and underscores. on the other hand, any VALUE data type can be assigned to them and quotes are optional when using strings in Bash, unless the string contains a space. This is because Bash is sensitive to spaces, so strings that have them won’t work properly unless surrounded with quotes. Lastly, no space should be left before and after the “=” symbol as shown below: MY_VARIABLE=”my_value” --> works(capital, no space, quotes)MY_VARIABLE=my_value --> works(capital, no space, no quotes but underscore)MY_VARIABLE=my value --> fails(capital, no space, space in value)MY_VARIABLE = ”my_value” --> fails(capital, space between equal sign, quotes) towardsdatascience.com An easy way to permanently declare an environment variable while using Mac OS, is to add it to the .bash_profile that is an hidden file defined in your home directory used to configure the Bash Shell in your system. To access the file, first run your terminal, navigate to the home directory with cd ~, then open the file editor with open .bash_profile command: $ cd ~$ open .bash_profile In the file editor type the KEY=value pairs for the secret info you want to hide, preceded by the export command that indicates that you wish for these variables to be also available outside the shell: export USERNAME=”Insert Your User Name”export DBPW=”Insert Your PW"export DBNAME=”Insert Your DB Name" Once all the variables have been added, save the text file and refresh the bash profile with the source .bash_profile command: $ source .bash_profile If you omit running the command above, you will not be able to immediately see the environment variables just created and you will need to exit and log back in the command line. Now, before attempting a database connection, let’s make sure that the variables can actually be used in Python by opening the interactive Python console in the command line and importing the os module. Among other things, the os module enables Python to use your operating system environment variables. You can list them with os.environ, a method that returns a Python dictionary including all the variables that are currently available in your system or select each key as shown below: $ ipythonIn [1]: import osIn [2]: os.environ['USERNAME']Out[2]: 'Insert Your User Name'In [3]: os.environ['DBPW']Out[3]: 'Insert Your PW'In [4]: os.environ['DBNAME']Out[4]: 'Insert Your DB Name' Terrific! It seems that you can now replace secret info strings with environment variables KEYS in the database connection settings. If you like me use psycopg2.connect() and pd.read_sql() methods to connect to Redshift, you will end up with something like this: In this tutorial, I have tried to solve a practical problem that I faced a few times in the recent past: hiding secret keys while working on shared Python scripts and I hope you will find environment variables as useful for your workflow as they are for me. Please note that this is only an introductory guide and there is a lot more to learn about environment variables. For instance, a course that I found particularly enlightening is Command Line Automation In Python by DataCamp. Disclaimer: This post includes affiliate links for which I may make a small commission at no extra cost to you should, you make a purchase.
[ { "code": null, "e": 222, "s": 171, "text": "A course I would strongly recommend to my readers:" }, { "code": null, "e": 371, "s": 222, "text": "Command Line Automation In Python (DataCamp) → Learn to automate many common file system tasks and be able to manage and communicate with processes." }, { "code": null, "e": 712, "s": 371, "text": "Suppose you were working on a data science project and you decided to pull data from the company database by establishing a connection using Python. What if there was a need to share your script via GitHub for the wider team to review? Well, in that case, better your secret details were hidden in order to avoid other people misusing them." }, { "code": null, "e": 889, "s": 712, "text": "In this article I will show how to use environment variables through the command line to keep username, password and database name safe, avoiding undesired information leakage." }, { "code": null, "e": 912, "s": 889, "text": "towardsdatascience.com" }, { "code": null, "e": 1163, "s": 912, "text": "Environment variables are KEY=value pairs that like Shell variables can be created through the command line, but more powerful as, once declared, they can be used by any programming language since they are linked to your environment/operating system." }, { "code": null, "e": 1196, "s": 1163, "text": "In the command line environment:" }, { "code": null, "e": 1307, "s": 1196, "text": "the variable KEY has to be written in capital letters and can be a mix of characters, numbers and underscores." }, { "code": null, "e": 1580, "s": 1307, "text": "on the other hand, any VALUE data type can be assigned to them and quotes are optional when using strings in Bash, unless the string contains a space. This is because Bash is sensitive to spaces, so strings that have them won’t work properly unless surrounded with quotes." }, { "code": null, "e": 1660, "s": 1580, "text": "Lastly, no space should be left before and after the “=” symbol as shown below:" }, { "code": null, "e": 1937, "s": 1660, "text": "MY_VARIABLE=”my_value” --> works(capital, no space, quotes)MY_VARIABLE=my_value --> works(capital, no space, no quotes but underscore)MY_VARIABLE=my value --> fails(capital, no space, space in value)MY_VARIABLE = ”my_value” --> fails(capital, space between equal sign, quotes)" }, { "code": null, "e": 1960, "s": 1937, "text": "towardsdatascience.com" }, { "code": null, "e": 2322, "s": 1960, "text": "An easy way to permanently declare an environment variable while using Mac OS, is to add it to the .bash_profile that is an hidden file defined in your home directory used to configure the Bash Shell in your system. To access the file, first run your terminal, navigate to the home directory with cd ~, then open the file editor with open .bash_profile command:" }, { "code": null, "e": 2349, "s": 2322, "text": "$ cd ~$ open .bash_profile" }, { "code": null, "e": 2551, "s": 2349, "text": "In the file editor type the KEY=value pairs for the secret info you want to hide, preceded by the export command that indicates that you wish for these variables to be also available outside the shell:" }, { "code": null, "e": 2654, "s": 2551, "text": "export USERNAME=”Insert Your User Name”export DBPW=”Insert Your PW\"export DBNAME=”Insert Your DB Name\"" }, { "code": null, "e": 2781, "s": 2654, "text": "Once all the variables have been added, save the text file and refresh the bash profile with the source .bash_profile command:" }, { "code": null, "e": 2804, "s": 2781, "text": "$ source .bash_profile" }, { "code": null, "e": 2982, "s": 2804, "text": "If you omit running the command above, you will not be able to immediately see the environment variables just created and you will need to exit and log back in the command line." }, { "code": null, "e": 3470, "s": 2982, "text": "Now, before attempting a database connection, let’s make sure that the variables can actually be used in Python by opening the interactive Python console in the command line and importing the os module. Among other things, the os module enables Python to use your operating system environment variables. You can list them with os.environ, a method that returns a Python dictionary including all the variables that are currently available in your system or select each key as shown below:" }, { "code": null, "e": 3665, "s": 3470, "text": "$ ipythonIn [1]: import osIn [2]: os.environ['USERNAME']Out[2]: 'Insert Your User Name'In [3]: os.environ['DBPW']Out[3]: 'Insert Your PW'In [4]: os.environ['DBNAME']Out[4]: 'Insert Your DB Name'" }, { "code": null, "e": 3928, "s": 3665, "text": "Terrific! It seems that you can now replace secret info strings with environment variables KEYS in the database connection settings. If you like me use psycopg2.connect() and pd.read_sql() methods to connect to Redshift, you will end up with something like this:" }, { "code": null, "e": 4412, "s": 3928, "text": "In this tutorial, I have tried to solve a practical problem that I faced a few times in the recent past: hiding secret keys while working on shared Python scripts and I hope you will find environment variables as useful for your workflow as they are for me. Please note that this is only an introductory guide and there is a lot more to learn about environment variables. For instance, a course that I found particularly enlightening is Command Line Automation In Python by DataCamp." } ]
Cassandra - Create Keyspace
A keyspace in Cassandra is a namespace that defines data replication on nodes. A cluster contains one keyspace per node. Given below is the syntax for creating a keyspace using the statement CREATE KEYSPACE. CREATE KEYSPACE <identifier> WITH <properties> i.e. CREATE KEYSPACE “KeySpace Name” WITH replication = {'class': ‘Strategy name’, 'replication_factor' : ‘No.Of replicas’}; CREATE KEYSPACE “KeySpace Name” WITH replication = {'class': ‘Strategy name’, 'replication_factor' : ‘No.Of replicas’} AND durable_writes = ‘Boolean value’; The CREATE KEYSPACE statement has two properties: replication and durable_writes. The replication option is to specify the Replica Placement strategy and the number of replicas wanted. The following table lists all the replica placement strategies. Using this option, you can instruct Cassandra whether to use commitlog for updates on the current KeySpace. This option is not mandatory and by default, it is set to true. Given below is an example of creating a KeySpace. Here we are creating a KeySpace named TutorialsPoint. Here we are creating a KeySpace named TutorialsPoint. We are using the first replica placement strategy, i.e.., Simple Strategy. We are using the first replica placement strategy, i.e.., Simple Strategy. And we are choosing the replication factor to 1 replica. And we are choosing the replication factor to 1 replica. cqlsh.> CREATE KEYSPACE tutorialspoint WITH replication = {'class':'SimpleStrategy', 'replication_factor' : 3}; You can verify whether the table is created or not using the command Describe. If you use this command over keyspaces, it will display all the keyspaces created as shown below. cqlsh> DESCRIBE keyspaces; tutorialspoint system system_traces Here you can observe the newly created KeySpace tutorialspoint. By default, the durable_writes properties of a table is set to true, however it can be set to false. You cannot set this property to simplex strategy. Given below is the example demonstrating the usage of durable writes property. cqlsh> CREATE KEYSPACE test ... WITH REPLICATION = { 'class' : 'NetworkTopologyStrategy', 'datacenter1' : 3 } ... AND DURABLE_WRITES = false; You can verify whether the durable_writes property of test KeySpace was set to false by querying the System Keyspace. This query gives you all the KeySpaces along with their properties. cqlsh> SELECT * FROM system_schema.keyspaces; keyspace_name | durable_writes | strategy_class | strategy_options ----------------+----------------+------------------------------------------------------+---------------------------- test | False | org.apache.cassandra.locator.NetworkTopologyStrategy | {"datacenter1" : "3"} tutorialspoint | True | org.apache.cassandra.locator.SimpleStrategy | {"replication_factor" : "4"} system | True | org.apache.cassandra.locator.LocalStrategy | { } system_traces | True | org.apache.cassandra.locator.SimpleStrategy | {"replication_factor" : "2"} (4 rows) Here you can observe the durable_writes property of test KeySpace was set to false. You can use a created KeySpace using the keyword USE. Its syntax is as follows − Syntax:USE <identifier> In the following example, we are using the KeySpace tutorialspoint. cqlsh> USE tutorialspoint; cqlsh:tutorialspoint> You can create a Keyspace using the execute() method of Session class. Follow the steps given below to create a keyspace using Java API. First of all, create an instance of Cluster.builder class of com.datastax.driver.core package as shown below. //Creating Cluster.Builder object Cluster.Builder builder1 = Cluster.builder(); Add a contact point (IP address of the node) using addContactPoint() method of Cluster.Builder object. This method returns Cluster.Builder. //Adding contact point to the Cluster.Builder object Cluster.Builder builder2 = build.addContactPoint( "127.0.0.1" ); Using the new builder object, create a cluster object. To do so, you have a method called build() in the Cluster.Builder class. The following code shows how to create a cluster object. //Building a cluster Cluster cluster = builder.build(); You can build a cluster object in a single line of code as shown below. Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build(); Create an instance of Session object using the connect() method of Cluster class as shown below. Session session = cluster.connect( ); This method creates a new session and initializes it. If you already have a keyspace, you can set it to the existing one by passing the keyspace name in string format to this method as shown below. Session session = cluster.connect(“ Your keyspace name ” ); You can execute CQL queries using the execute() method of Session class. Pass the query either in string format or as a Statement class object to the execute() method. Whatever you pass to this method in string format will be executed on the cqlsh. In this example, we are creating a KeySpace named tp. We are using the first replica placement strategy, i.e., Simple Strategy, and we are choosing the replication factor to 1 replica. You have to store the query in a string variable and pass it to the execute() method as shown below. String query = "CREATE KEYSPACE tp WITH replication " + "= {'class':'SimpleStrategy', 'replication_factor':1}; "; session.execute(query); You can use a created KeySpace using the execute() method as shown below. execute(“ USE tp ” ); Given below is the complete program to create and use a keyspace in Cassandra using Java API. import com.datastax.driver.core.Cluster; import com.datastax.driver.core.Session; public class Create_KeySpace { public static void main(String args[]){ //Query String query = "CREATE KEYSPACE tp WITH replication " + "= {'class':'SimpleStrategy', 'replication_factor':1};"; //creating Cluster object Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build(); //Creating Session object Session session = cluster.connect(); //Executing the query session.execute(query); //using the KeySpace session.execute("USE tp"); System.out.println("Keyspace created"); } } Save the above program with the class name followed by .java, browse to the location where it is saved. Compile and execute the program as shown below. $javac Create_KeySpace.java $java Create_KeySpace Under normal conditions, it will produce the following output − Keyspace created 27 Lectures 2 hours Navdeep Kaur 34 Lectures 1.5 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2495, "s": 2287, "text": "A keyspace in Cassandra is a namespace that defines data replication on nodes. A cluster contains one keyspace per node. Given below is the syntax for creating a keyspace using the statement CREATE KEYSPACE." }, { "code": null, "e": 2543, "s": 2495, "text": "CREATE KEYSPACE <identifier> WITH <properties>\n" }, { "code": null, "e": 2548, "s": 2543, "text": "i.e." }, { "code": null, "e": 2831, "s": 2548, "text": "CREATE KEYSPACE “KeySpace Name”\nWITH replication = {'class': ‘Strategy name’, 'replication_factor' : ‘No.Of replicas’};\n\nCREATE KEYSPACE “KeySpace Name”\nWITH replication = {'class': ‘Strategy name’, 'replication_factor' : ‘No.Of replicas’}\n\nAND durable_writes = ‘Boolean value’;\n" }, { "code": null, "e": 2914, "s": 2831, "text": "The CREATE KEYSPACE statement has two properties: replication and durable_writes." }, { "code": null, "e": 3081, "s": 2914, "text": "The replication option is to specify the Replica Placement strategy and the number of replicas wanted. The following table lists all the replica placement strategies." }, { "code": null, "e": 3253, "s": 3081, "text": "Using this option, you can instruct Cassandra whether to use commitlog for updates on the current KeySpace. This option is not mandatory and by default, it is set to true." }, { "code": null, "e": 3303, "s": 3253, "text": "Given below is an example of creating a KeySpace." }, { "code": null, "e": 3357, "s": 3303, "text": "Here we are creating a KeySpace named TutorialsPoint." }, { "code": null, "e": 3411, "s": 3357, "text": "Here we are creating a KeySpace named TutorialsPoint." }, { "code": null, "e": 3486, "s": 3411, "text": "We are using the first replica placement strategy, i.e.., Simple Strategy." }, { "code": null, "e": 3561, "s": 3486, "text": "We are using the first replica placement strategy, i.e.., Simple Strategy." }, { "code": null, "e": 3618, "s": 3561, "text": "And we are choosing the replication factor to 1 replica." }, { "code": null, "e": 3675, "s": 3618, "text": "And we are choosing the replication factor to 1 replica." }, { "code": null, "e": 3788, "s": 3675, "text": "cqlsh.> CREATE KEYSPACE tutorialspoint\nWITH replication = {'class':'SimpleStrategy', 'replication_factor' : 3};\n" }, { "code": null, "e": 3965, "s": 3788, "text": "You can verify whether the table is created or not using the command Describe. If you use this command over keyspaces, it will display all the keyspaces created as shown below." }, { "code": null, "e": 4031, "s": 3965, "text": "cqlsh> DESCRIBE keyspaces;\n\ntutorialspoint system system_traces \n" }, { "code": null, "e": 4095, "s": 4031, "text": "Here you can observe the newly created KeySpace tutorialspoint." }, { "code": null, "e": 4246, "s": 4095, "text": "By default, the durable_writes properties of a table is set to true, however it can be set to false. You cannot set this property to simplex strategy." }, { "code": null, "e": 4325, "s": 4246, "text": "Given below is the example demonstrating the usage of durable writes property." }, { "code": null, "e": 4468, "s": 4325, "text": "cqlsh> CREATE KEYSPACE test\n... WITH REPLICATION = { 'class' : 'NetworkTopologyStrategy', 'datacenter1' : 3 }\n... AND DURABLE_WRITES = false;\n" }, { "code": null, "e": 4654, "s": 4468, "text": "You can verify whether the durable_writes property of test KeySpace was set to false by querying the System Keyspace. This query gives you all the KeySpaces along with their properties." }, { "code": null, "e": 5385, "s": 4654, "text": "cqlsh> SELECT * FROM system_schema.keyspaces;\n\n keyspace_name | durable_writes | strategy_class | strategy_options\n----------------+----------------+------------------------------------------------------+----------------------------\n\n test | False | org.apache.cassandra.locator.NetworkTopologyStrategy | {\"datacenter1\" : \"3\"}\n\n tutorialspoint | True | org.apache.cassandra.locator.SimpleStrategy | {\"replication_factor\" : \"4\"}\n\n system | True | org.apache.cassandra.locator.LocalStrategy | { }\n\n system_traces | True | org.apache.cassandra.locator.SimpleStrategy | {\"replication_factor\" : \"2\"}\n\n(4 rows)\n" }, { "code": null, "e": 5469, "s": 5385, "text": "Here you can observe the durable_writes property of test KeySpace was set to false." }, { "code": null, "e": 5550, "s": 5469, "text": "You can use a created KeySpace using the keyword USE. Its syntax is as follows −" }, { "code": null, "e": 5575, "s": 5550, "text": "Syntax:USE <identifier>\n" }, { "code": null, "e": 5643, "s": 5575, "text": "In the following example, we are using the KeySpace tutorialspoint." }, { "code": null, "e": 5693, "s": 5643, "text": "cqlsh> USE tutorialspoint;\ncqlsh:tutorialspoint>\n" }, { "code": null, "e": 5830, "s": 5693, "text": "You can create a Keyspace using the execute() method of Session class. Follow the steps given below to create a keyspace using Java API." }, { "code": null, "e": 5940, "s": 5830, "text": "First of all, create an instance of Cluster.builder class of com.datastax.driver.core package as shown below." }, { "code": null, "e": 6022, "s": 5940, "text": "//Creating Cluster.Builder object\n\nCluster.Builder builder1 = Cluster.builder();\n" }, { "code": null, "e": 6162, "s": 6022, "text": "Add a contact point (IP address of the node) using addContactPoint() method of Cluster.Builder object. This method returns Cluster.Builder." }, { "code": null, "e": 6282, "s": 6162, "text": "//Adding contact point to the Cluster.Builder object\n\nCluster.Builder builder2 = build.addContactPoint( \"127.0.0.1\" );\n" }, { "code": null, "e": 6467, "s": 6282, "text": "Using the new builder object, create a cluster object. To do so, you have a method called build() in the Cluster.Builder class. The following code shows how to create a cluster object." }, { "code": null, "e": 6524, "s": 6467, "text": "//Building a cluster\nCluster cluster = builder.build();\n" }, { "code": null, "e": 6596, "s": 6524, "text": "You can build a cluster object in a single line of code as shown below." }, { "code": null, "e": 6671, "s": 6596, "text": "Cluster cluster = Cluster.builder().addContactPoint(\"127.0.0.1\").build();\n" }, { "code": null, "e": 6768, "s": 6671, "text": "Create an instance of Session object using the connect() method of Cluster class as shown below." }, { "code": null, "e": 6807, "s": 6768, "text": "Session session = cluster.connect( );\n" }, { "code": null, "e": 7005, "s": 6807, "text": "This method creates a new session and initializes it. If you already have a keyspace, you can set it to the existing one by passing the keyspace name in string format to this method as shown below." }, { "code": null, "e": 7066, "s": 7005, "text": "Session session = cluster.connect(“ Your keyspace name ” );\n" }, { "code": null, "e": 7315, "s": 7066, "text": "You can execute CQL queries using the execute() method of Session class. Pass the query either in string format or as a Statement class object to the execute() method. Whatever you pass to this method in string format will be executed on the cqlsh." }, { "code": null, "e": 7500, "s": 7315, "text": "In this example, we are creating a KeySpace named tp. We are using the first replica placement strategy, i.e., Simple Strategy, and we are choosing the replication factor to 1 replica." }, { "code": null, "e": 7601, "s": 7500, "text": "You have to store the query in a string variable and pass it to the execute() method as shown below." }, { "code": null, "e": 7743, "s": 7601, "text": "String query = \"CREATE KEYSPACE tp WITH replication \"\n + \"= {'class':'SimpleStrategy', 'replication_factor':1}; \";\nsession.execute(query);\n" }, { "code": null, "e": 7817, "s": 7743, "text": "You can use a created KeySpace using the execute() method as shown below." }, { "code": null, "e": 7840, "s": 7817, "text": "execute(“ USE tp ” );\n" }, { "code": null, "e": 7934, "s": 7840, "text": "Given below is the complete program to create and use a keyspace in Cassandra using Java API." }, { "code": null, "e": 8632, "s": 7934, "text": "import com.datastax.driver.core.Cluster;\nimport com.datastax.driver.core.Session;\n\npublic class Create_KeySpace {\n\n public static void main(String args[]){\n\n //Query\n String query = \"CREATE KEYSPACE tp WITH replication \"\n + \"= {'class':'SimpleStrategy', 'replication_factor':1};\";\n \n //creating Cluster object\n Cluster cluster = Cluster.builder().addContactPoint(\"127.0.0.1\").build();\n \n //Creating Session object\n Session session = cluster.connect();\n \n //Executing the query\n session.execute(query);\n \n //using the KeySpace\n session.execute(\"USE tp\");\n System.out.println(\"Keyspace created\"); \n }\n}" }, { "code": null, "e": 8784, "s": 8632, "text": "Save the above program with the class name followed by .java, browse to the location where it is saved. Compile and execute the program as shown below." }, { "code": null, "e": 8835, "s": 8784, "text": "$javac Create_KeySpace.java\n$java Create_KeySpace\n" }, { "code": null, "e": 8899, "s": 8835, "text": "Under normal conditions, it will produce the following output −" }, { "code": null, "e": 8917, "s": 8899, "text": "Keyspace created\n" }, { "code": null, "e": 8950, "s": 8917, "text": "\n 27 Lectures \n 2 hours \n" }, { "code": null, "e": 8964, "s": 8950, "text": " Navdeep Kaur" }, { "code": null, "e": 8999, "s": 8964, "text": "\n 34 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9017, "s": 8999, "text": " Bigdata Engineer" }, { "code": null, "e": 9024, "s": 9017, "text": " Print" }, { "code": null, "e": 9035, "s": 9024, "text": " Add Notes" } ]
TypeScript - String split()
This method splits a String object into an array of strings by separating the string into substrings. string.split([separator][, limit]); separator − Specifies the character to use for separating the string. If separator is omitted, the array returned contains one element consisting of the entire string. separator − Specifies the character to use for separating the string. If separator is omitted, the array returned contains one element consisting of the entire string. limit − Integer specifying a limit on the number of splits to be found. limit − Integer specifying a limit on the number of splits to be found. The split method returns the new array. Also, when the string is empty, split returns an array containing one empty string, rather than an empty array. var str = "Apples are round, and apples are juicy."; var splitted = str.split(" ", 3); console.log(splitted) On compiling, it will generate the same code in JavaScript. Its output is as follows − [ 'Apples', 'are', 'round,' ] 45 Lectures 4 hours Antonio Papa 41 Lectures 7 hours Haider Malik 60 Lectures 2.5 hours Skillbakerystudios 77 Lectures 8 hours Sean Bradley 77 Lectures 3.5 hours TELCOMA Global 19 Lectures 3 hours Christopher Frewin Print Add Notes Bookmark this page
[ { "code": null, "e": 2150, "s": 2048, "text": "This method splits a String object into an array of strings by separating the string into substrings." }, { "code": null, "e": 2187, "s": 2150, "text": "string.split([separator][, limit]);\n" }, { "code": null, "e": 2355, "s": 2187, "text": "separator − Specifies the character to use for separating the string. If separator is omitted, the array returned contains one element consisting of the entire string." }, { "code": null, "e": 2523, "s": 2355, "text": "separator − Specifies the character to use for separating the string. If separator is omitted, the array returned contains one element consisting of the entire string." }, { "code": null, "e": 2595, "s": 2523, "text": "limit − Integer specifying a limit on the number of splits to be found." }, { "code": null, "e": 2667, "s": 2595, "text": "limit − Integer specifying a limit on the number of splits to be found." }, { "code": null, "e": 2819, "s": 2667, "text": "The split method returns the new array. Also, when the string is empty, split returns an array containing one empty string, rather than an empty array." }, { "code": null, "e": 2931, "s": 2819, "text": "var str = \"Apples are round, and apples are juicy.\"; \nvar splitted = str.split(\" \", 3); \nconsole.log(splitted)\n" }, { "code": null, "e": 2991, "s": 2931, "text": "On compiling, it will generate the same code in JavaScript." }, { "code": null, "e": 3018, "s": 2991, "text": "Its output is as follows −" }, { "code": null, "e": 3049, "s": 3018, "text": "[ 'Apples', 'are', 'round,' ]\n" }, { "code": null, "e": 3082, "s": 3049, "text": "\n 45 Lectures \n 4 hours \n" }, { "code": null, "e": 3096, "s": 3082, "text": " Antonio Papa" }, { "code": null, "e": 3129, "s": 3096, "text": "\n 41 Lectures \n 7 hours \n" }, { "code": null, "e": 3143, "s": 3129, "text": " Haider Malik" }, { "code": null, "e": 3178, "s": 3143, "text": "\n 60 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3198, "s": 3178, "text": " Skillbakerystudios" }, { "code": null, "e": 3231, "s": 3198, "text": "\n 77 Lectures \n 8 hours \n" }, { "code": null, "e": 3245, "s": 3231, "text": " Sean Bradley" }, { "code": null, "e": 3280, "s": 3245, "text": "\n 77 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3296, "s": 3280, "text": " TELCOMA Global" }, { "code": null, "e": 3329, "s": 3296, "text": "\n 19 Lectures \n 3 hours \n" }, { "code": null, "e": 3349, "s": 3329, "text": " Christopher Frewin" }, { "code": null, "e": 3356, "s": 3349, "text": " Print" }, { "code": null, "e": 3367, "s": 3356, "text": " Add Notes" } ]
Importance of the accumulate() method of JSONObject in Java?
A JSONObject is an unordered collection of a name and value pairs. A few important methods of JSONArray are accumulate(), put(), opt(), append(), write() and etc. The accumulate() method accumulates the values under a key and this method similar to the put() method except if there is an existing object stored under a key then a JSONArray can be stored under a key to hold all of the accumulated values. If there is an existing JSONArray then a new value can be added. public JSONObject accumulate(java.lang.String key, java.lang.Object value) throws JSONException import org.json.*; public class JSONAccumulateMethodTest { public static void main(String[] args) throws JSONException { JSONObject jsonObj = new JSONObject(); jsonObj.accumulate("Technology", "Java"); jsonObj.accumulate("Technology", "Python"); jsonObj.accumulate("Technology", "Spark"); jsonObj.accumulate("Technology", "Selenium"); jsonObj.accumulate("Technology", ".Net"); System.out.println(jsonObj.toString(3)); } } {"Technology": [ "Java", "Python", "Spark", "Selenium", ".Net" ]}
[ { "code": null, "e": 1532, "s": 1062, "text": "A JSONObject is an unordered collection of a name and value pairs. A few important methods of JSONArray are accumulate(), put(), opt(), append(), write() and etc. The accumulate() method accumulates the values under a key and this method similar to the put() method except if there is an existing object stored under a key then a JSONArray can be stored under a key to hold all of the accumulated values. If there is an existing JSONArray then a new value can be added." }, { "code": null, "e": 1628, "s": 1532, "text": "public JSONObject accumulate(java.lang.String key, java.lang.Object value) throws JSONException" }, { "code": null, "e": 2098, "s": 1628, "text": "import org.json.*;\npublic class JSONAccumulateMethodTest {\n public static void main(String[] args) throws JSONException {\n JSONObject jsonObj = new JSONObject();\n jsonObj.accumulate(\"Technology\", \"Java\");\n jsonObj.accumulate(\"Technology\", \"Python\");\n jsonObj.accumulate(\"Technology\", \"Spark\");\n jsonObj.accumulate(\"Technology\", \"Selenium\");\n jsonObj.accumulate(\"Technology\", \".Net\");\n System.out.println(jsonObj.toString(3));\n }\n}" }, { "code": null, "e": 2179, "s": 2098, "text": "{\"Technology\": [\n \"Java\",\n \"Python\",\n \"Spark\",\n \"Selenium\",\n \".Net\"\n]}" } ]
3 Basic Steps of Stock Market Analysis in Python | by Roman Orac | Towards Data Science
Analyze Tesla stock in Python, calculate Trading Indicators and plot the OHLC chart. Includes a Jupyter Notebook with code examples. I recently started reading Stan Weinstein's Secrets For Profiting in Bull and Bear Markets. In his book, Stan reveals his successful methods for timing investments to produce consistently profitable results. Many investors say “This is the only investing book you will ever need to read” Stan Weinstein is a professional stock market technical analysis. He became famous in 1987 when he predicted a 31% crash in the stock market where he used his chart reading skills. My other articles about this topic: romanorac.medium.com Here are few links that might interest you: - Complete your Python analyses 10x faster with Mito [Product]- Free skill tests for Data Scientists & ML Engineers [Test]- All New Self-Driving Car Engineer Nanodegree [Course] Would you like to read more such articles? If so, you can support me by clicking on any links above. Some of them are affiliate links, but you don’t need to buy anything. This is the first article in a series of Stock Market Analysis in Python in which I will try to describe and implement successful techniques to profit in the stock market. Let’s start with the basics. In this article you will learn: the easiest way to get the stock data in Python what are trading indicators and how to calculate them how to plot the stock data with OHLC chart Note I am not a professional investor and I’m not responsible for your losses. This is educational content. The easiest way to download the stock’s historical data in Python is with yfinance package. To install the package, simply run: pip install yfinance To download the daily stock prices for Tesla (TSLA) to a pandas DataFrame with yfinance is as simply as: df = yf.download("TSLA", start="2018-11-01", end="2020-10-18", interval="1d")df.head() yfinance download function has many arguments: Instead of setting the interval to 1d, you can use 1m, 2m, 5m,15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo, 3mo. you can define multiple tickers in a list or string: “SPY AAPL MSFT”. instead of start and end date, you can use the period “ytd” to download the data for one year from today. Other valid periods are 1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max. see yfinance for more. yfinance has many other useful functions, like the dividends function. Let’s say we would like to list dividends for AT&T (T). t = yf.Ticker("T")t.dividends t.dividends.plot(figsize=(14, 7)) Trading indicators are mathematical calculations, which are plotted as lines on a price chart and can help traders identify certain signals and trends within the market. TA-LIB is one of the most used libraries in Python when it comes to technical analysis. To use it, you first need to install TA-LIB dependency: # Mac OS Xbrew install ta-lib# see https://github.com/mrjbq7/ta-lib for other platforms Then you need to install python API: pip install TA-Lib The moving average (MA) is used to identify the direction of a current price trend, without the interference of shorter-term price spikes. The MA indicator combines price points of a stock over a specified time frame and divides it by the number of data points to present a single trend line. Let’s calculate 20 days (short term) and 200 days (long term) MA on TSLA Closing prices (we can calculate MA directly with pandas): df.loc[:, 'ma20'] = df.Close.rolling(20).mean()df.loc[:, 'ma200'] = df.Close.rolling(200).mean() Moving averages are used to identify significant support and resistance levels. Traders watch for crossovers of longer-term moving averages by shorter-term moving averages as possible indicators of trend changes to enter long and short positions. According to Stan Weinstein: The price must be above the short term MA in order to buy a stock. The relative strength index (RSI) is a momentum indicator used in technical analysis that measures the magnitude of recent price changes to evaluate overbought or oversold conditions in the price of a stock or other asset. The RSI is displayed as an oscillator (a line graph that moves between two extremes) and can have a reading from 0 to 100. It is most typically used on a 14-day timeframe. If you are reading Stan Weinstein’s Secrets For Profiting in Bull and Bear Markets, Stan mentions relative strength, but don’t confuse it with RSI. The relative strength tells about the value of a stock in comparison to another stock, index or benchmark, while the RSI tells about the performance of a stock in comparison to the recent performance of the same stock. import talibdf.loc[:, "rsi"] = talib.RSI(df.Close, 14) Now, let’s plot RSI with a line on 30 for oversold and 70 for overbought: import matplotlib.pyplot as pltfig, ax = plt.subplots(1, 2, figsize=(21, 7))ax0 = df[["rsi"]].plot(ax=ax[0])ax0.axhline(30, color="black")ax0.axhline(70, color="black")df[["Close"]].plot(ax=ax[1]) An asset with RSI ≥70 is often considered overbought, while an asset with RSI ≤ 30 is often considered oversold: an overbought signal suggests that assets may be in for a price correction. an oversold signal could mean that short-term declines are reaching maturity and assets may be in for a rally. In the plot above, we can observe a pattern that the TSLA price moves as the RSI suggests. When it is overbought (RSI ≥70) the price is in for correction and vise versa. In this section, we are going to see how to plot an OHLC chart — a chart with bars Open, High, Low, Close prices, that we are used to seeing on trading platforms. We are going to use the Plotly library for the OHLC chart. To install it: pip install plotly If you are using JupyterLab, you also need to install a Plotly extension, so that JupyterLab can render Plotly charts: jupyter labextension install jupyterlab-plotly To plot OHLC with Plotly, we simply need to set the prices on the correct inputs. import plotly.graph_objects as gofig = go.Figure( data=go.Ohlc( x=df.index, open=df["Open"], high=df["High"], low=df["Low"], close=df["Close"], ))fig.show() As usual, you can download this Jupyter Notebook to try examples on your machine. Follow me on Twitter, where I regularly tweet about Data Science and Machine Learning.
[ { "code": null, "e": 180, "s": 47, "text": "Analyze Tesla stock in Python, calculate Trading Indicators and plot the OHLC chart. Includes a Jupyter Notebook with code examples." }, { "code": null, "e": 388, "s": 180, "text": "I recently started reading Stan Weinstein's Secrets For Profiting in Bull and Bear Markets. In his book, Stan reveals his successful methods for timing investments to produce consistently profitable results." }, { "code": null, "e": 468, "s": 388, "text": "Many investors say “This is the only investing book you will ever need to read”" }, { "code": null, "e": 649, "s": 468, "text": "Stan Weinstein is a professional stock market technical analysis. He became famous in 1987 when he predicted a 31% crash in the stock market where he used his chart reading skills." }, { "code": null, "e": 685, "s": 649, "text": "My other articles about this topic:" }, { "code": null, "e": 706, "s": 685, "text": "romanorac.medium.com" }, { "code": null, "e": 750, "s": 706, "text": "Here are few links that might interest you:" }, { "code": null, "e": 928, "s": 750, "text": "- Complete your Python analyses 10x faster with Mito [Product]- Free skill tests for Data Scientists & ML Engineers [Test]- All New Self-Driving Car Engineer Nanodegree [Course]" }, { "code": null, "e": 1099, "s": 928, "text": "Would you like to read more such articles? If so, you can support me by clicking on any links above. Some of them are affiliate links, but you don’t need to buy anything." }, { "code": null, "e": 1271, "s": 1099, "text": "This is the first article in a series of Stock Market Analysis in Python in which I will try to describe and implement successful techniques to profit in the stock market." }, { "code": null, "e": 1332, "s": 1271, "text": "Let’s start with the basics. In this article you will learn:" }, { "code": null, "e": 1380, "s": 1332, "text": "the easiest way to get the stock data in Python" }, { "code": null, "e": 1434, "s": 1380, "text": "what are trading indicators and how to calculate them" }, { "code": null, "e": 1477, "s": 1434, "text": "how to plot the stock data with OHLC chart" }, { "code": null, "e": 1585, "s": 1477, "text": "Note I am not a professional investor and I’m not responsible for your losses. This is educational content." }, { "code": null, "e": 1713, "s": 1585, "text": "The easiest way to download the stock’s historical data in Python is with yfinance package. To install the package, simply run:" }, { "code": null, "e": 1734, "s": 1713, "text": "pip install yfinance" }, { "code": null, "e": 1839, "s": 1734, "text": "To download the daily stock prices for Tesla (TSLA) to a pandas DataFrame with yfinance is as simply as:" }, { "code": null, "e": 1926, "s": 1839, "text": "df = yf.download(\"TSLA\", start=\"2018-11-01\", end=\"2020-10-18\", interval=\"1d\")df.head()" }, { "code": null, "e": 1973, "s": 1926, "text": "yfinance download function has many arguments:" }, { "code": null, "e": 2082, "s": 1973, "text": "Instead of setting the interval to 1d, you can use 1m, 2m, 5m,15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo, 3mo." }, { "code": null, "e": 2152, "s": 2082, "text": "you can define multiple tickers in a list or string: “SPY AAPL MSFT”." }, { "code": null, "e": 2332, "s": 2152, "text": "instead of start and end date, you can use the period “ytd” to download the data for one year from today. Other valid periods are 1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max." }, { "code": null, "e": 2355, "s": 2332, "text": "see yfinance for more." }, { "code": null, "e": 2482, "s": 2355, "text": "yfinance has many other useful functions, like the dividends function. Let’s say we would like to list dividends for AT&T (T)." }, { "code": null, "e": 2512, "s": 2482, "text": "t = yf.Ticker(\"T\")t.dividends" }, { "code": null, "e": 2546, "s": 2512, "text": "t.dividends.plot(figsize=(14, 7))" }, { "code": null, "e": 2716, "s": 2546, "text": "Trading indicators are mathematical calculations, which are plotted as lines on a price chart and can help traders identify certain signals and trends within the market." }, { "code": null, "e": 2804, "s": 2716, "text": "TA-LIB is one of the most used libraries in Python when it comes to technical analysis." }, { "code": null, "e": 2860, "s": 2804, "text": "To use it, you first need to install TA-LIB dependency:" }, { "code": null, "e": 2948, "s": 2860, "text": "# Mac OS Xbrew install ta-lib# see https://github.com/mrjbq7/ta-lib for other platforms" }, { "code": null, "e": 2985, "s": 2948, "text": "Then you need to install python API:" }, { "code": null, "e": 3004, "s": 2985, "text": "pip install TA-Lib" }, { "code": null, "e": 3143, "s": 3004, "text": "The moving average (MA) is used to identify the direction of a current price trend, without the interference of shorter-term price spikes." }, { "code": null, "e": 3297, "s": 3143, "text": "The MA indicator combines price points of a stock over a specified time frame and divides it by the number of data points to present a single trend line." }, { "code": null, "e": 3429, "s": 3297, "text": "Let’s calculate 20 days (short term) and 200 days (long term) MA on TSLA Closing prices (we can calculate MA directly with pandas):" }, { "code": null, "e": 3526, "s": 3429, "text": "df.loc[:, 'ma20'] = df.Close.rolling(20).mean()df.loc[:, 'ma200'] = df.Close.rolling(200).mean()" }, { "code": null, "e": 3606, "s": 3526, "text": "Moving averages are used to identify significant support and resistance levels." }, { "code": null, "e": 3773, "s": 3606, "text": "Traders watch for crossovers of longer-term moving averages by shorter-term moving averages as possible indicators of trend changes to enter long and short positions." }, { "code": null, "e": 3869, "s": 3773, "text": "According to Stan Weinstein: The price must be above the short term MA in order to buy a stock." }, { "code": null, "e": 4092, "s": 3869, "text": "The relative strength index (RSI) is a momentum indicator used in technical analysis that measures the magnitude of recent price changes to evaluate overbought or oversold conditions in the price of a stock or other asset." }, { "code": null, "e": 4264, "s": 4092, "text": "The RSI is displayed as an oscillator (a line graph that moves between two extremes) and can have a reading from 0 to 100. It is most typically used on a 14-day timeframe." }, { "code": null, "e": 4412, "s": 4264, "text": "If you are reading Stan Weinstein’s Secrets For Profiting in Bull and Bear Markets, Stan mentions relative strength, but don’t confuse it with RSI." }, { "code": null, "e": 4631, "s": 4412, "text": "The relative strength tells about the value of a stock in comparison to another stock, index or benchmark, while the RSI tells about the performance of a stock in comparison to the recent performance of the same stock." }, { "code": null, "e": 4686, "s": 4631, "text": "import talibdf.loc[:, \"rsi\"] = talib.RSI(df.Close, 14)" }, { "code": null, "e": 4760, "s": 4686, "text": "Now, let’s plot RSI with a line on 30 for oversold and 70 for overbought:" }, { "code": null, "e": 4957, "s": 4760, "text": "import matplotlib.pyplot as pltfig, ax = plt.subplots(1, 2, figsize=(21, 7))ax0 = df[[\"rsi\"]].plot(ax=ax[0])ax0.axhline(30, color=\"black\")ax0.axhline(70, color=\"black\")df[[\"Close\"]].plot(ax=ax[1])" }, { "code": null, "e": 5070, "s": 4957, "text": "An asset with RSI ≥70 is often considered overbought, while an asset with RSI ≤ 30 is often considered oversold:" }, { "code": null, "e": 5146, "s": 5070, "text": "an overbought signal suggests that assets may be in for a price correction." }, { "code": null, "e": 5257, "s": 5146, "text": "an oversold signal could mean that short-term declines are reaching maturity and assets may be in for a rally." }, { "code": null, "e": 5427, "s": 5257, "text": "In the plot above, we can observe a pattern that the TSLA price moves as the RSI suggests. When it is overbought (RSI ≥70) the price is in for correction and vise versa." }, { "code": null, "e": 5590, "s": 5427, "text": "In this section, we are going to see how to plot an OHLC chart — a chart with bars Open, High, Low, Close prices, that we are used to seeing on trading platforms." }, { "code": null, "e": 5664, "s": 5590, "text": "We are going to use the Plotly library for the OHLC chart. To install it:" }, { "code": null, "e": 5683, "s": 5664, "text": "pip install plotly" }, { "code": null, "e": 5802, "s": 5683, "text": "If you are using JupyterLab, you also need to install a Plotly extension, so that JupyterLab can render Plotly charts:" }, { "code": null, "e": 5849, "s": 5802, "text": "jupyter labextension install jupyterlab-plotly" }, { "code": null, "e": 5931, "s": 5849, "text": "To plot OHLC with Plotly, we simply need to set the prices on the correct inputs." }, { "code": null, "e": 6129, "s": 5931, "text": "import plotly.graph_objects as gofig = go.Figure( data=go.Ohlc( x=df.index, open=df[\"Open\"], high=df[\"High\"], low=df[\"Low\"], close=df[\"Close\"], ))fig.show()" }, { "code": null, "e": 6211, "s": 6129, "text": "As usual, you can download this Jupyter Notebook to try examples on your machine." } ]
Apache IVY - Cachepath Task
cachepath task is used to create an ANT classpath with resolved artifacts present in the cache. As ANT needs jars to be classpath to compile java files, Ivy cachepath builds the classpath. Let's create Tester.java, build.xml and ivy.xml as described in IVY - Resolve Task chapter. Update the build.xml to use the ivy retrieve task. build.xml <project name="test" default="resolve" xmlns:ivy="antlib:org.apache.ivy.ant"> <target name="resolve" description="resolve dependencies"> <ivy:resolve /> <ivy:cachepath pathid="new.classpath" /> </target> <target name="compile" depends="resolve" description="Compile"> <mkdir dir="build/classes" /> <javac srcdir="src" destdir="build/classes"> <classpath refid="new.classpath" /> </javac> </target> </project> Following are the important terms. pathid − id of the classpath where cached jars are present. pathid − id of the classpath where cached jars are present. retrieve tasks copies the resolved dependencies in the lib directory of the project by default and can be changed using pattern attribute. As we've all the files ready. Just go the console. Navigate to E: > ivy folder and run the ant command. E:\ivy > ant compile Ivy will come into action, resolving the dependencies, you will see the following result. Buildfile: E:\ivy\build.xml resolve: [ivy:resolve] :: Apache Ivy 2.5.0 - 20191020104435 :: https://ant.apache.org/ivy / :: [ivy:resolve] :: loading settings :: url = jar:file:/E:/Apache/apache-ant-1.9.14 /lib/ivy-2.5.0.jar!/org/apache/ivy/core/settings/ivysettings.xml [ivy:resolve] :: resolving dependencies :: com.tutorialspoint#test;working@Acer- PC [ivy:resolve] confs: [default] [ivy:resolve] found commons-lang#commons-lang;2.6 in public [ivy:resolve] found junit#junit;3.8.1 in public [ivy:resolve] :: resolution report :: resolve 2314ms :: artifacts dl 15ms --------------------------------------------------------------------- | | modules || artifacts | | conf | number| search|dwnlded|evicted|| number|dwnlded| --------------------------------------------------------------------- | default | 2 | 2 | 0 | 0 || 4 | 0 | --------------------------------------------------------------------- compile: [javac] E:\ivy\build.xml:13: warning: 'includeantruntime' was not set, defau lting to build.sysclasspath=last; set to false for repeatable builds [javac] Compiling 1 source file to E:\ivy\build\classes BUILD SUCCESSFUL Total time: 3 seconds You can verify the compiled class file in project build directory. 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2193, "s": 2004, "text": "cachepath task is used to create an ANT classpath with resolved artifacts present in the cache. As ANT needs jars to be classpath to compile java files, Ivy cachepath builds the classpath." }, { "code": null, "e": 2285, "s": 2193, "text": "Let's create Tester.java, build.xml and ivy.xml as described in IVY - Resolve Task chapter." }, { "code": null, "e": 2336, "s": 2285, "text": "Update the build.xml to use the ivy retrieve task." }, { "code": null, "e": 2346, "s": 2336, "text": "build.xml" }, { "code": null, "e": 2806, "s": 2346, "text": "<project name=\"test\" default=\"resolve\" xmlns:ivy=\"antlib:org.apache.ivy.ant\">\n <target name=\"resolve\" description=\"resolve dependencies\">\n <ivy:resolve />\n <ivy:cachepath pathid=\"new.classpath\" />\n </target>\n <target name=\"compile\" depends=\"resolve\" description=\"Compile\">\n <mkdir dir=\"build/classes\" />\n <javac srcdir=\"src\" destdir=\"build/classes\">\n <classpath refid=\"new.classpath\" />\n </javac>\n </target>\n</project>" }, { "code": null, "e": 2841, "s": 2806, "text": "Following are the important terms." }, { "code": null, "e": 2901, "s": 2841, "text": "pathid − id of the classpath where cached jars are present." }, { "code": null, "e": 2961, "s": 2901, "text": "pathid − id of the classpath where cached jars are present." }, { "code": null, "e": 3100, "s": 2961, "text": "retrieve tasks copies the resolved dependencies in the lib directory of the project by default and can be changed using pattern attribute." }, { "code": null, "e": 3205, "s": 3100, "text": "As we've all the files ready. Just go the console. Navigate to E: > ivy folder and run the ant command." }, { "code": null, "e": 3227, "s": 3205, "text": "E:\\ivy > ant compile\n" }, { "code": null, "e": 3317, "s": 3227, "text": "Ivy will come into action, resolving the dependencies, you will see the following result." }, { "code": null, "e": 4605, "s": 3317, "text": "Buildfile: E:\\ivy\\build.xml\n\nresolve:\n[ivy:resolve] :: Apache Ivy 2.5.0 - 20191020104435 :: https://ant.apache.org/ivy\n/ ::\n[ivy:resolve] :: loading settings :: url = jar:file:/E:/Apache/apache-ant-1.9.14\n/lib/ivy-2.5.0.jar!/org/apache/ivy/core/settings/ivysettings.xml\n[ivy:resolve] :: resolving dependencies :: com.tutorialspoint#test;working@Acer-\nPC\n[ivy:resolve] confs: [default]\n[ivy:resolve] found commons-lang#commons-lang;2.6 in public\n[ivy:resolve] found junit#junit;3.8.1 in public\n[ivy:resolve] :: resolution report :: resolve 2314ms :: artifacts dl 15ms\n ---------------------------------------------------------------------\n | | modules || artifacts |\n | conf | number| search|dwnlded|evicted|| number|dwnlded|\n ---------------------------------------------------------------------\n | default | 2 | 2 | 0 | 0 || 4 | 0 |\n ---------------------------------------------------------------------\n\ncompile:\n [javac] E:\\ivy\\build.xml:13: warning: 'includeantruntime' was not set, defau\nlting to build.sysclasspath=last; set to false for repeatable builds\n [javac] Compiling 1 source file to E:\\ivy\\build\\classes\n\nBUILD SUCCESSFUL\nTotal time: 3 seconds\n" }, { "code": null, "e": 4672, "s": 4605, "text": "You can verify the compiled class file in project build directory." }, { "code": null, "e": 4707, "s": 4672, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4726, "s": 4707, "text": " Arnab Chakraborty" }, { "code": null, "e": 4761, "s": 4726, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4782, "s": 4761, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 4815, "s": 4782, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 4828, "s": 4815, "text": " Nilay Mehta" }, { "code": null, "e": 4863, "s": 4828, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4881, "s": 4863, "text": " Bigdata Engineer" }, { "code": null, "e": 4914, "s": 4881, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 4932, "s": 4914, "text": " Bigdata Engineer" }, { "code": null, "e": 4965, "s": 4932, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 4983, "s": 4965, "text": " Bigdata Engineer" }, { "code": null, "e": 4990, "s": 4983, "text": " Print" }, { "code": null, "e": 5001, "s": 4990, "text": " Add Notes" } ]
How to make a Tkinter canvas rectangle transparent?
The canvas widget is one of the most versatile widgets in Tkinter Library. Generally, it is used to draw shapes, animate objects, and create complex graphics in any application. To create shapes like Rectangle, we use the create_rectangle(x,y, x+ width, y+ height, **options) method. We can configure the item on the canvas by adding properties such as width, height, fill and bg, border width, etc. The alpha property in canvas defines the transparency of the canvas item. However, the property is not available in the Tkinter library; thus, we must define a function to provide the transparency attribute in shape. The steps to create the function for transparency attribute are, Define an inbuilt function create_rectangle(x,y,a,b, **options). Calculate the alpha for each color (RGB) that must be provided to the shape. Remove the predefined alpha (if applicable) from the shape using pop(). Calculate the shape color in the region using winfo_rgb() and add the alpha to the shape. Since a newly created shape will have different color and background, thus it must be needed to use this as an image. The Image can be displayed in the canvas easily. # Import the required libraries from tkinter import * from PIL import Image, ImageTk # Create an instance of tkinter frame win= Tk() # Set the size of the tkinter window win.geometry("700x350") # Store newly created image images=[] # Define a function to make the transparent rectangle def create_rectangle(x,y,a,b,**options): if 'alpha' in options: # Calculate the alpha transparency for every color(RGB) alpha = int(options.pop('alpha') * 255) # Use the fill variable to fill the shape with transparent color fill = options.pop('fill') fill = win.winfo_rgb(fill) + (alpha,) image = Image.new('RGBA', (a-x, b-y), fill) images.append(ImageTk.PhotoImage(image)) canvas.create_image(x, y, image=images[-1], anchor='nw') canvas.create_rectangle(x, y,a,b, **options) # Add a Canvas widget canvas= Canvas(win) # Create a rectangle in canvas create_rectangle(50, 110,300,280, fill= "blue", alpha=.3) create_rectangle(40, 90, 420, 250, fill= "red", alpha= .1) canvas.pack() win.mainloop() Running the above code will display multiple transparent rectangles in the canvas.
[ { "code": null, "e": 1462, "s": 1062, "text": "The canvas widget is one of the most versatile widgets in Tkinter Library. Generally, it is used to draw shapes, animate objects, and create complex graphics in any application. To create shapes like Rectangle, we use the create_rectangle(x,y, x+ width, y+ height, **options) method. We can configure the item on the canvas by adding properties such as width, height, fill and bg, border width, etc." }, { "code": null, "e": 1744, "s": 1462, "text": "The alpha property in canvas defines the transparency of the canvas item. However, the property is not available in the Tkinter library; thus, we must define a function to provide the transparency attribute in shape. The steps to create the function for transparency attribute are," }, { "code": null, "e": 1809, "s": 1744, "text": "Define an inbuilt function create_rectangle(x,y,a,b, **options)." }, { "code": null, "e": 1886, "s": 1809, "text": "Calculate the alpha for each color (RGB) that must be provided to the shape." }, { "code": null, "e": 1958, "s": 1886, "text": "Remove the predefined alpha (if applicable) from the shape using pop()." }, { "code": null, "e": 2048, "s": 1958, "text": "Calculate the shape color in the region using winfo_rgb() and add the alpha to the shape." }, { "code": null, "e": 2166, "s": 2048, "text": "Since a newly created shape will have different color and background, thus it must be needed to use this as an image." }, { "code": null, "e": 2215, "s": 2166, "text": "The Image can be displayed in the canvas easily." }, { "code": null, "e": 3260, "s": 2215, "text": "# Import the required libraries\nfrom tkinter import *\nfrom PIL import Image, ImageTk\n\n# Create an instance of tkinter frame\nwin= Tk()\n\n# Set the size of the tkinter window\nwin.geometry(\"700x350\")\n\n# Store newly created image\nimages=[]\n\n# Define a function to make the transparent rectangle\ndef create_rectangle(x,y,a,b,**options):\n if 'alpha' in options:\n # Calculate the alpha transparency for every color(RGB)\n alpha = int(options.pop('alpha') * 255)\n # Use the fill variable to fill the shape with transparent color\n fill = options.pop('fill')\n fill = win.winfo_rgb(fill) + (alpha,)\n image = Image.new('RGBA', (a-x, b-y), fill)\n images.append(ImageTk.PhotoImage(image))\n canvas.create_image(x, y, image=images[-1], anchor='nw')\n canvas.create_rectangle(x, y,a,b, **options)\n# Add a Canvas widget\ncanvas= Canvas(win)\n\n# Create a rectangle in canvas\ncreate_rectangle(50, 110,300,280, fill= \"blue\", alpha=.3)\ncreate_rectangle(40, 90, 420, 250, fill= \"red\", alpha= .1)\ncanvas.pack()\n\nwin.mainloop()" }, { "code": null, "e": 3343, "s": 3260, "text": "Running the above code will display multiple transparent rectangles in the canvas." } ]
10 Python Pandas tips to make data analysis faster | by Shiu-Tang Li | Towards Data Science
Have you ever complained about the table output looks boring when you do .head() in Jupyter notebooks? Is there a way not to display indexes (especially when there is already an ID column)? There’re ways to fix these issues. A. Highlight all negative values in a dataframe. (example revised from https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html) import pandas as pddef color_negative_red(val): color = 'red' if val < 0 else 'black' return 'color: %s' % colordf = pd.DataFrame(dict(col_1=[1.53,-2.5,3.53], col_2=[-4.1,5.9,0]) )df.style.applymap(color_negative_red) B. Hide the index. Try df.head().style.hide_index()!C. Add hovering effects. (example revised from https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.io.formats.style.Styler.set_table_styles.html) df = pd.DataFrame(np.random.randn(5, 3))df.style.set_table_styles([{'selector': 'tr:hover', 'props': [('background-color', 'yellow')]}]) D. More CSS styles. You can use CSS to change the appearance of the table. df = pd.DataFrame(dict(departure=['SFO', 'SFO', 'LAX', 'LAX', 'JFK', 'SFO'], arrival=['ORD', 'DFW', 'DFW', 'ATL', 'ATL', 'ORD'], airlines=['Delta','JetBlue','Delta',’AA','SouthWest', 'Delta']),columns=['airlines', 'departure','arrival'])df.style.set_table_styles([{'selector': 'tr:nth-of-type(odd)', 'props': [('background', '#eee')]}, {'selector': 'tr:nth-of-type(even)', 'props': [('background', 'white')]}, {'selector': 'th', 'props': [('background', '#606060'), ('color', 'white'), ('font-family', 'verdana')]}, {'selector': 'td', 'props': [('font-family', 'verdana')]},]).hide_index() The reader may have experienced the following issues when using .head(n) to check the dataframe:(1) There’re too many columns / rows in the dataframe and some columns / rows in the middle are omitted.(2) Columns containing long texts get truncated. (3) Columns containing floats display too many / too few digits. One can set import pandas as pd pd.options.display.max_columns = 50 # None -> No Restrictionspd.options.display.max_rows = 200 # None -> Be careful with this pd.options.display.max_colwidth = 100pd.options.display.precision = 3 to solve these issues. In SQL we can do aggregations like SELECT A, B, max(A), avg(A), sum(B), min(B), count(*)FROM tableGROUP BY A, B In Pandas it can be done with .groupby() and .agg(): import pandas as pdimport numpy as np df = pd.DataFrame(dict(A=['coke', 'sprite', 'coke', 'sprite', 'sprite', 'coke', 'coke'], B=['alpha','gamma', 'alpha', 'beta', 'gamma', 'beta', 'beta'], col_1=[1,2,3,4,5,6,7], col_2=[1,6,2,4,7,9,3]))tbl = df.groupby(['A','B']).agg({'col_1': ['max', np.mean], 'col_2': ['sum','min','count']})# 'count' will always be the count for number of rows in each group. And the result will look like this: Both the rows and columns are multi-indexed. A quick solution to change it to a dataframe without multi-indices is tbl = tbl.reset_index()tbl.columns = ['A', 'B', 'col_1_max', 'col_2_sum', 'col_2_min', 'count'] If you would like to have the column renaming process automated, you can do tbl.columns.get_level_values(0) and tbl.columns.get_level_values(1) to extract the indices in each level and combine them. Some of you might be familiar with this already, but I still find it very useful when handling a dataframe with a ton of columns. df.iloc[:,2:5].head() # select the 2nd to the 4th columndf.loc[:,'column_x':].head() # select all columns starting from 'column_x' To add a row ID / random row ID for each group by A, B, one can first append an ID / random ID to all rows: import numpy as np# df: target dataframe np.random.seed(0) # set random seeddf['random_ID_all'] = np.random.permutation(df.shape[0])df['ID_all'] = [i for i in range(1, df.shape[0]+1)] To add a random ID to each group (by A, B), one can then do df['ID'] = df.groupby(['A', 'B'])['ID_all'].rank(method='first', ascending=True).astype(int)df['random_ID'] = df.groupby(['A', 'B'])['random_ID_all'].rank(method='first', ascending=True).astype(int) to get Sometimes after we performed group by, we’d like to aggregate the values in the target column as a list of unique values instead of max, min, ...etc. This is how it’s done. df = pd.DataFrame(dict(A=['A','A','A','A','A','B','B','B','B'], B=[1,1,1,2,2,1,1,1,2], C=['CA','NY','CA','FL','FL', 'WA','FL','NY','WA']))tbl = df[['A', 'B', 'C']].drop_duplicates()\ .groupby(['A','B'])['C']\ .apply(list)\ .reset_index()# list to string (separated by commas) tbl['C'] = tbl.apply(lambda x: (','.join([str(s) for s in x['C']])), axis = 1) If you’d like to save the result, don’t forget to change the separator to anything other than commas. This is another common data manipulation. All you need is .apply(). df = pd.DataFrame(dict(A=[2,6,3], B=[2,2,6], C=[3,2,3]))df['col_total'] = df.apply(lambda x: x.sum(), axis=1)df.loc['row_total'] = df.apply(lambda x: x.sum()) .memory_usage(deep=True) can be used on Pandas dataframes to see the amount of memory used (in bytes) for each column. It’s useful when building machine learning models which may require a lot memory in training. From time to time, cumulative sum is required when you generate some statistical outcomes. Simply do df['cumulative_sum'] = df['target_column'].cumsum() . When you need to count the frequencies for groups formed by 3+ features, pd.crosstab() can make your life easier. Thanks for reading! Comment below if you find bugs / better solutions.
[ { "code": null, "e": 397, "s": 172, "text": "Have you ever complained about the table output looks boring when you do .head() in Jupyter notebooks? Is there a way not to display indexes (especially when there is already an ID column)? There’re ways to fix these issues." }, { "code": null, "e": 536, "s": 397, "text": "A. Highlight all negative values in a dataframe. (example revised from https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html)" }, { "code": null, "e": 796, "s": 536, "text": "import pandas as pddef color_negative_red(val): color = 'red' if val < 0 else 'black' return 'color: %s' % colordf = pd.DataFrame(dict(col_1=[1.53,-2.5,3.53], col_2=[-4.1,5.9,0]) )df.style.applymap(color_negative_red)" }, { "code": null, "e": 1008, "s": 796, "text": "B. Hide the index. Try df.head().style.hide_index()!C. Add hovering effects. (example revised from https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.io.formats.style.Styler.set_table_styles.html)" }, { "code": null, "e": 1146, "s": 1008, "text": "df = pd.DataFrame(np.random.randn(5, 3))df.style.set_table_styles([{'selector': 'tr:hover', 'props': [('background-color', 'yellow')]}])" }, { "code": null, "e": 1221, "s": 1146, "text": "D. More CSS styles. You can use CSS to change the appearance of the table." }, { "code": null, "e": 1863, "s": 1221, "text": "df = pd.DataFrame(dict(departure=['SFO', 'SFO', 'LAX', 'LAX', 'JFK', 'SFO'], arrival=['ORD', 'DFW', 'DFW', 'ATL', 'ATL', 'ORD'], airlines=['Delta','JetBlue','Delta',’AA','SouthWest', 'Delta']),columns=['airlines', 'departure','arrival'])df.style.set_table_styles([{'selector': 'tr:nth-of-type(odd)', 'props': [('background', '#eee')]}, {'selector': 'tr:nth-of-type(even)', 'props': [('background', 'white')]}, {'selector': 'th', 'props': [('background', '#606060'), ('color', 'white'), ('font-family', 'verdana')]}, {'selector': 'td', 'props': [('font-family', 'verdana')]},]).hide_index()" }, { "code": null, "e": 2177, "s": 1863, "text": "The reader may have experienced the following issues when using .head(n) to check the dataframe:(1) There’re too many columns / rows in the dataframe and some columns / rows in the middle are omitted.(2) Columns containing long texts get truncated. (3) Columns containing floats display too many / too few digits." }, { "code": null, "e": 2189, "s": 2177, "text": "One can set" }, { "code": null, "e": 2409, "s": 2189, "text": "import pandas as pd pd.options.display.max_columns = 50 # None -> No Restrictionspd.options.display.max_rows = 200 # None -> Be careful with this pd.options.display.max_colwidth = 100pd.options.display.precision = 3" }, { "code": null, "e": 2432, "s": 2409, "text": "to solve these issues." }, { "code": null, "e": 2467, "s": 2432, "text": "In SQL we can do aggregations like" }, { "code": null, "e": 2544, "s": 2467, "text": "SELECT A, B, max(A), avg(A), sum(B), min(B), count(*)FROM tableGROUP BY A, B" }, { "code": null, "e": 2597, "s": 2544, "text": "In Pandas it can be done with .groupby() and .agg():" }, { "code": null, "e": 3142, "s": 2597, "text": "import pandas as pdimport numpy as np df = pd.DataFrame(dict(A=['coke', 'sprite', 'coke', 'sprite', 'sprite', 'coke', 'coke'], B=['alpha','gamma', 'alpha', 'beta', 'gamma', 'beta', 'beta'], col_1=[1,2,3,4,5,6,7], col_2=[1,6,2,4,7,9,3]))tbl = df.groupby(['A','B']).agg({'col_1': ['max', np.mean], 'col_2': ['sum','min','count']})# 'count' will always be the count for number of rows in each group." }, { "code": null, "e": 3178, "s": 3142, "text": "And the result will look like this:" }, { "code": null, "e": 3293, "s": 3178, "text": "Both the rows and columns are multi-indexed. A quick solution to change it to a dataframe without multi-indices is" }, { "code": null, "e": 3389, "s": 3293, "text": "tbl = tbl.reset_index()tbl.columns = ['A', 'B', 'col_1_max', 'col_2_sum', 'col_2_min', 'count']" }, { "code": null, "e": 3588, "s": 3389, "text": "If you would like to have the column renaming process automated, you can do tbl.columns.get_level_values(0) and tbl.columns.get_level_values(1) to extract the indices in each level and combine them." }, { "code": null, "e": 3718, "s": 3588, "text": "Some of you might be familiar with this already, but I still find it very useful when handling a dataframe with a ton of columns." }, { "code": null, "e": 3863, "s": 3718, "text": "df.iloc[:,2:5].head() # select the 2nd to the 4th columndf.loc[:,'column_x':].head() # select all columns starting from 'column_x'" }, { "code": null, "e": 3971, "s": 3863, "text": "To add a row ID / random row ID for each group by A, B, one can first append an ID / random ID to all rows:" }, { "code": null, "e": 4157, "s": 3971, "text": "import numpy as np# df: target dataframe np.random.seed(0) # set random seeddf['random_ID_all'] = np.random.permutation(df.shape[0])df['ID_all'] = [i for i in range(1, df.shape[0]+1)]" }, { "code": null, "e": 4217, "s": 4157, "text": "To add a random ID to each group (by A, B), one can then do" }, { "code": null, "e": 4416, "s": 4217, "text": "df['ID'] = df.groupby(['A', 'B'])['ID_all'].rank(method='first', ascending=True).astype(int)df['random_ID'] = df.groupby(['A', 'B'])['random_ID_all'].rank(method='first', ascending=True).astype(int)" }, { "code": null, "e": 4423, "s": 4416, "text": "to get" }, { "code": null, "e": 4596, "s": 4423, "text": "Sometimes after we performed group by, we’d like to aggregate the values in the target column as a list of unique values instead of max, min, ...etc. This is how it’s done." }, { "code": null, "e": 5097, "s": 4596, "text": "df = pd.DataFrame(dict(A=['A','A','A','A','A','B','B','B','B'], B=[1,1,1,2,2,1,1,1,2], C=['CA','NY','CA','FL','FL', 'WA','FL','NY','WA']))tbl = df[['A', 'B', 'C']].drop_duplicates()\\ .groupby(['A','B'])['C']\\ .apply(list)\\ .reset_index()# list to string (separated by commas) tbl['C'] = tbl.apply(lambda x: (','.join([str(s) for s in x['C']])), axis = 1)" }, { "code": null, "e": 5199, "s": 5097, "text": "If you’d like to save the result, don’t forget to change the separator to anything other than commas." }, { "code": null, "e": 5267, "s": 5199, "text": "This is another common data manipulation. All you need is .apply()." }, { "code": null, "e": 5475, "s": 5267, "text": "df = pd.DataFrame(dict(A=[2,6,3], B=[2,2,6], C=[3,2,3]))df['col_total'] = df.apply(lambda x: x.sum(), axis=1)df.loc['row_total'] = df.apply(lambda x: x.sum())" }, { "code": null, "e": 5688, "s": 5475, "text": ".memory_usage(deep=True) can be used on Pandas dataframes to see the amount of memory used (in bytes) for each column. It’s useful when building machine learning models which may require a lot memory in training." }, { "code": null, "e": 5843, "s": 5688, "text": "From time to time, cumulative sum is required when you generate some statistical outcomes. Simply do df['cumulative_sum'] = df['target_column'].cumsum() ." }, { "code": null, "e": 5957, "s": 5843, "text": "When you need to count the frequencies for groups formed by 3+ features, pd.crosstab() can make your life easier." } ]
C++ program to Solve Tower of Hanoi Problem using Binary Value
This C++ program displays the solution to the Tower of Hanoi problem using binary value. There is one binary digit for each disk. The most significant bit represents the largest disk. A value of 0 indicates that the largest disk is on the initial peg, while a 1 indicates that it’s on the final peg. The bitstring is read from left to right, and each bit can be used to determine the location of the corresponding disk. The corresponding disk is stacked on top the previous disk on the same peg if a bit has the same value as the previous one. If it is different that means that the corresponding disk is one position to the left or right of the previous one. Begin Take the number of disk n as input. Declare n and a. Make a for loop a = 1 to (1<<n) – 1 // Here, (a & a – 1) = bitwise AND with a and a – 1. (a | a – 1) = bitwise OR with a and a – 1. Here % means modulus operator. // Print the result indicating that moving disks from peg number (a & a – 1) % 3 to peg number ((a | a – 1) + 1) % 3 End #include<iostream> using namespace std; int main() { int n, a; cout<<"\nEnter the no of Disks: "; cin>>n; for (a = 1; a < (1 << n); a++) { cout<<"\nDisk Move from Peg "<<(a&a-1)%3 <<" to Peg "<<((a|a-1)+1)%3; } cout<<"\n"; } Enter the no of Disks: 3 Disk Move from Peg 0 to Peg 2 Disk Move from Peg 0 to Peg 1 Disk Move from Peg 2 to Peg 1 Disk Move from Peg 0 to Peg 2 Disk Move from Peg 1 to Peg 0 Disk Move from Peg 1 to Peg 2 Disk Move from Peg 0 to Peg 2
[ { "code": null, "e": 1151, "s": 1062, "text": "This C++ program displays the solution to the Tower of Hanoi problem using binary value." }, { "code": null, "e": 1192, "s": 1151, "text": "There is one binary digit for each disk." }, { "code": null, "e": 1362, "s": 1192, "text": "The most significant bit represents the largest disk. A value of 0 indicates that the largest disk is on the initial peg, while a 1 indicates that it’s on the final peg." }, { "code": null, "e": 1482, "s": 1362, "text": "The bitstring is read from left to right, and each bit can be used to determine the location of the corresponding disk." }, { "code": null, "e": 1606, "s": 1482, "text": "The corresponding disk is stacked on top the previous disk on the same peg if a bit has the same value as the previous one." }, { "code": null, "e": 1722, "s": 1606, "text": "If it is different that means that the corresponding disk is one position to the left or right of the previous one." }, { "code": null, "e": 2101, "s": 1722, "text": "Begin\n Take the number of disk n as input.\n Declare n and a.\n Make a for loop a = 1 to (1<<n) – 1\n //\n Here, (a & a – 1) = bitwise AND with a and a – 1.\n (a | a – 1) = bitwise OR with a and a – 1.\n Here % means modulus operator.\n //\n Print the result indicating that moving disks from peg number (a & a – 1) % 3 to peg number ((a | a – 1) + 1) % 3\nEnd" }, { "code": null, "e": 2350, "s": 2101, "text": "#include<iostream>\nusing namespace std;\nint main() {\n int n, a;\n cout<<\"\\nEnter the no of Disks: \";\n cin>>n;\n for (a = 1; a < (1 << n); a++) {\n cout<<\"\\nDisk Move from Peg \"<<(a&a-1)%3 <<\" to Peg \"<<((a|a-1)+1)%3;\n }\n cout<<\"\\n\";\n}" }, { "code": null, "e": 2585, "s": 2350, "text": "Enter the no of Disks: 3\nDisk Move from Peg 0 to Peg 2\nDisk Move from Peg 0 to Peg 1\nDisk Move from Peg 2 to Peg 1\nDisk Move from Peg 0 to Peg 2\nDisk Move from Peg 1 to Peg 0\nDisk Move from Peg 1 to Peg 2\nDisk Move from Peg 0 to Peg 2" } ]
Rod Cutting
A rod is given of length n. Another table is also provided, which contains different size and price for each size. Determine the maximum price by cutting the rod and selling them in the market. To get the best price by making a cut at different positions and comparing the prices after cutting the rod. Let the f(n) will return the max possible price after cutting a row with length n. We can simply write the function f(n) like this. f(n) := maximum value from price[i]+f(n – i – 1), where i is in range 0 to (n – 1). Input: The price of different lengths, and the length of rod. Here the length is 8. Output: Maximum profit after selling is 22. Cut the rod in length 2 and 6. The profit is 5 + 17 = 22 rodCutting(price, n) Input: Price list, number of different prices on the list. Output: Maximum profit by cutting rods. Begin define profit array of size n + 1 profit[0] := 0 for i := 1 to n, do maxProfit := - ∞ for j := 0 to i-1, do maxProfit := maximum of maxProfit and (price[j] + profit[i-j-1]) done profit[i] := maxProfit done return maxProfit End #include <iostream> using namespace std; int max(int a, int b) { return (a > b)? a : b; } int rodCutting(int price[], int n) { //from price and length of n, find max profit int profit[n+1]; profit[0] = 0; int maxProfit; for (int i = 1; i<=n; i++) { maxProfit = INT_MIN; //initially set as -ve infinity for (int j = 0; j < i; j++) maxProfit = max(maxProfit, price[j] + profit[i-j-1]); profit[i] = maxProfit; } return maxProfit; } int main() { int priceList[] = {1, 5, 8, 9, 10, 17, 17, 20}; int rodLength = 8; cout << "Maximum Price: "<< rodCutting(priceList, rodLength); } Maximum Price: 22
[ { "code": null, "e": 1256, "s": 1062, "text": "A rod is given of length n. Another table is also provided, which contains different size and price for each size. Determine the maximum price by cutting the rod and selling them in the market." }, { "code": null, "e": 1365, "s": 1256, "text": "To get the best price by making a cut at different positions and comparing the prices after cutting the rod." }, { "code": null, "e": 1497, "s": 1365, "text": "Let the f(n) will return the max possible price after cutting a row with length n. We can simply write the function f(n) like this." }, { "code": null, "e": 1581, "s": 1497, "text": "f(n) := maximum value from price[i]+f(n – i – 1), where i is in range 0 to (n – 1)." }, { "code": null, "e": 1588, "s": 1581, "text": "Input:" }, { "code": null, "e": 1665, "s": 1588, "text": "The price of different lengths, and the length of rod. Here the length is 8." }, { "code": null, "e": 1673, "s": 1665, "text": "Output:" }, { "code": null, "e": 1709, "s": 1673, "text": "Maximum profit after selling is 22." }, { "code": null, "e": 1766, "s": 1709, "text": "Cut the rod in length 2 and 6. The profit is 5 + 17 = 22" }, { "code": null, "e": 1787, "s": 1766, "text": "rodCutting(price, n)" }, { "code": null, "e": 1846, "s": 1787, "text": "Input: Price list, number of different prices on the list." }, { "code": null, "e": 1886, "s": 1846, "text": "Output: Maximum profit by cutting rods." }, { "code": null, "e": 2168, "s": 1886, "text": "Begin\n define profit array of size n + 1\n profit[0] := 0\n for i := 1 to n, do\n maxProfit := - ∞\n for j := 0 to i-1, do\n maxProfit := maximum of maxProfit and (price[j] + profit[i-j-1])\n done\n\n profit[i] := maxProfit\n done\n return maxProfit\nEnd" }, { "code": null, "e": 2808, "s": 2168, "text": "#include <iostream>\nusing namespace std;\n\nint max(int a, int b) {\n return (a > b)? a : b;\n}\n\nint rodCutting(int price[], int n) { //from price and length of n, find max profit\n int profit[n+1];\n profit[0] = 0;\n int maxProfit;\n\n for (int i = 1; i<=n; i++) {\n maxProfit = INT_MIN; //initially set as -ve infinity\n for (int j = 0; j < i; j++)\n maxProfit = max(maxProfit, price[j] + profit[i-j-1]);\n profit[i] = maxProfit;\n }\n return maxProfit;\n}\n\nint main() {\n int priceList[] = {1, 5, 8, 9, 10, 17, 17, 20};\n int rodLength = 8;\n cout << \"Maximum Price: \"<< rodCutting(priceList, rodLength);\n}" }, { "code": null, "e": 2826, "s": 2808, "text": "Maximum Price: 22" } ]
Visualizing Decision Trees with Python (Scikit-learn, Graphviz, Matplotlib) | by Michael Galarnyk | Towards Data Science
Decision trees are a popular supervised learning method for a variety of reasons. Benefits of decision trees include that they can be used for both regression and classification, they don’t require feature scaling, and they are relatively easy to interpret as you can visualize decision trees. This is not only a powerful way to understand your model, but also to communicate how your model works. Consequently, it would help to know how to make a visualization based on your model. This tutorial covers: How to Fit a Decision Tree Model using Scikit-Learn How to Visualize Decision Trees using Matplotlib How to Visualize Decision Trees using Graphviz (what is Graphviz, how to install it on Mac and Windows, and how to use it to visualize decision trees) How to Visualize Individual Decision Trees from Bagged Trees or Random Forests As always, the code used in this tutorial is available on my GitHub. With that, let’s get started! In order to visualize decision trees, we need first need to fit a decision tree model using scikit-learn. If this section is not clear, I encourage you to read my Understanding Decision Trees for Classification (Python) tutorial as I go into a lot of detail on how decision trees work and how to use them. The following import statements are what we will use for this section of the tutorial. import matplotlib.pyplot as pltfrom sklearn.datasets import load_irisfrom sklearn.datasets import load_breast_cancerfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import train_test_splitimport pandas as pdimport numpy as npfrom sklearn import tree The Iris dataset is one of datasets scikit-learn comes with that do not require the downloading of any file from some external website. The code below loads the iris dataset. import pandas as pdfrom sklearn.datasets import load_irisdata = load_iris()df = pd.DataFrame(data.data, columns=data.feature_names)df['target'] = data.target The code below puts 75% of the data into a training set and 25% of the data into a test set. X_train, X_test, Y_train, Y_test = train_test_split(df[data.feature_names], df['target'], random_state=0) # Step 1: Import the model you want to use# This was already imported earlier in the notebook so commenting out#from sklearn.tree import DecisionTreeClassifier# Step 2: Make an instance of the Modelclf = DecisionTreeClassifier(max_depth = 2, random_state = 0)# Step 3: Train the model on the dataclf.fit(X_train, Y_train)# Step 4: Predict labels of unseen (test) data# Not doing this step in the tutorial# clf.predict(X_test) As of scikit-learn version 21.0 (roughly May 2019), Decision Trees can now be plotted with matplotlib using scikit-learn’s tree.plot_tree without relying on the dot library which is a hard-to-install dependency which we will cover later on in the blog post. The code below plots a decision tree using scikit-learn. tree.plot_tree(clf); In addition to adding the code to allow you to save your image, the code below tries to make the decision tree more interpretable by adding in feature and class names (as well as setting filled = True). fn=['sepal length (cm)','sepal width (cm)','petal length (cm)','petal width (cm)']cn=['setosa', 'versicolor', 'virginica']fig, axes = plt.subplots(nrows = 1,ncols = 1,figsize = (4,4), dpi=300)tree.plot_tree(clf, feature_names = fn, class_names=cn, filled = True);fig.savefig('imagename.png') Graphviz is open source graph visualization software. Graph visualization is a way of representing structural information as diagrams of abstract graphs and networks. In data science, one use of Graphviz is to visualize decision trees. I should note that the reason why I am going over Graphviz after covering Matplotlib is that getting this to work can be difficult. The first part of this process involves creating a dot file. A dot file is a Graphviz representation of a decision tree. The problem is that using Graphviz to convert the dot file into an image file (png, jpg, etc) can be difficult. There are a couple ways to do this including: installing python-graphviz though Anaconda, installing Graphviz through Homebrew (Mac), installing Graphviz executables from the official site (Windows), and using an online converter on the contents of your dot file to convert it into an image. The code below code will work on any operating system as python generates the dot file and exports it as a file named tree.dot. tree.export_graphviz(clf, out_file="tree.dot", feature_names = fn, class_names=cn, filled = True) Converting the dot file into an image file (png, jpg, etc) typically requires the installation of Graphviz which depends on your operating system and a host of other things. The goal of this section is to help people try and solve the common issue of getting the following error. dot: command not found. How to Install and Use on Mac through Anaconda To be able to install Graphviz on your Mac through this method, you first need to have Anaconda installed (If you don’t have Anaconda installed, you can learn how to install it here). Open a terminal. You can do this by clicking on the Spotlight magnifying glass at the top right of the screen, type terminal and then click on the Terminal icon. Type the command below to install Graphviz. conda install python-graphviz After that, you should be able to use the dot command below to convert the dot file into a png file. dot -Tpng tree.dot -o tree.png How to Install and Use on Mac through Homebrew If you don’t have Anaconda or just want another way of installing Graphviz on your Mac, you can use Homebrew. I previously wrote an article on how to install Homebrew and use it to convert a dot file into an image file here (see the Homebrew to Help Visualize Decision Trees section of the tutorial). How to Install and Use on Windows through Anaconda This is the method I prefer on Windows. To be able to install Graphviz on your Windows through this method, you first need to have Anaconda installed (If you don’t have Anaconda installed, you can learn how to install it here). Open a terminal/command prompt and enter the command below to install Graphviz. conda install python-graphviz After that, you should be able to use the dot command below to convert the dot file into a png file. dot -Tpng tree.dot -o tree.png How to Install and Use on Windows through Graphviz Executable If you don’t have Anaconda or just want another way of installing Graphviz on your Windows, you can use the following link to download and install it. If all else fails or you simply don’t want to install anything, you can use an online converter. In the image below, I opened the file with Sublime Text (though there are many different programs that can open/read a dot file) and copied the content of the file. In the image below, I pasted the content from the dot file onto the left side of the online converter. You can then choose what format you want and then save the image on the right side of the screen. Keep in mind that there are other online converters that can help accomplish the same task. A weakness of decision trees is that they don’t tend to have the best predictive accuracy. This is partially because of high variance, meaning that different splits in the training data can lead to very different trees. The video above covers Bagged Trees which is an ensemble model. This means using multiple learning algorithms to obtain a better predictive performance than could be obtained from any of the constituent learning algorithms alone. In this case, many trees protect each other from their individual errors. The interesting thing is that the thumbnail from the video above could be a diagram for either Bagged Trees or Random Forests (another ensemble model). The differences between how Bagged Trees and Random Forests models work is a subject for another blog, but what is important to note is that for both models we grow N trees where N is the number of decision trees a user specifies. Consequently after you fit a model, it would be nice to look at the individual decision trees that make up your model. In order to visualize individual decision trees, we need first need to fit a Bagged Trees or Random Forest model using scikit-learn (the code below fits a Random Forest model). # Load the Breast Cancer (Diagnostic) Datasetdata = load_breast_cancer()df = pd.DataFrame(data.data, columns=data.feature_names)df['target'] = data.target# Arrange Data into Features Matrix and Target VectorX = df.loc[:, df.columns != 'target']y = df.loc[:, 'target'].values# Split the data into training and testing setsX_train, X_test, Y_train, Y_test = train_test_split(X, y, random_state=0)# Random Forests in `scikit-learn` (with N = 100)rf = RandomForestClassifier(n_estimators=100, random_state=0)rf.fit(X_train, Y_train) You can now view all the individual trees from the fitted model. In this section, I will visualize all the decision trees using matplotlib. rf.estimators_ You can now visualize individual trees. The code below visualizes the first decision tree. fn=data.feature_namescn=data.target_namesfig, axes = plt.subplots(nrows = 1,ncols = 1,figsize = (4,4), dpi=800)tree.plot_tree(rf.estimators_[0], feature_names = fn, class_names=cn, filled = True);fig.savefig('rf_individualtree.png') You can try to use matplotlib subplots to visualize as many of the trees as you like. The code below visualizes the first 5 decision trees. I personally don’t prefer this method as it is even harder to read. # This may not the best way to view each estimator as it is smallfn=data.feature_namescn=data.target_namesfig, axes = plt.subplots(nrows = 1,ncols = 5,figsize = (10,2), dpi=3000)for index in range(0, 5): tree.plot_tree(rf.estimators_[index], feature_names = fn, class_names=cn, filled = True, ax = axes[index]); axes[index].set_title('Estimator: ' + str(index), fontsize = 11)fig.savefig('rf_5trees.png') Keep in mind that if for some reason you want images for all your estimators (decision trees), you can do so using the code on my GitHub. If you just want to see each of the 100 estimators for the Random Forest model fit in this tutorial without running the code, you can look at the video below. This tutorial covered how to visualize decision trees using Graphviz and Matplotlib. Note that the way to visualize decision trees using Matplotlib is a newer method so it might change or be improved upon in the future. Graphviz is currently more flexible as you can always modify your dot files to make them more visually appealing like I did using the dot language or even just alter the orientation of your decision tree. One thing we didn’t cover was how to use dtreeviz which is another library that can visualize decision trees. There is an excellent post on it here. My next machine learning tutorial goes over How to Speed up Scikit-Learn Model Training. If you have any questions or thoughts on the tutorial, feel free to reach out in the comments below or through Twitter.
[ { "code": null, "e": 654, "s": 171, "text": "Decision trees are a popular supervised learning method for a variety of reasons. Benefits of decision trees include that they can be used for both regression and classification, they don’t require feature scaling, and they are relatively easy to interpret as you can visualize decision trees. This is not only a powerful way to understand your model, but also to communicate how your model works. Consequently, it would help to know how to make a visualization based on your model." }, { "code": null, "e": 676, "s": 654, "text": "This tutorial covers:" }, { "code": null, "e": 728, "s": 676, "text": "How to Fit a Decision Tree Model using Scikit-Learn" }, { "code": null, "e": 777, "s": 728, "text": "How to Visualize Decision Trees using Matplotlib" }, { "code": null, "e": 928, "s": 777, "text": "How to Visualize Decision Trees using Graphviz (what is Graphviz, how to install it on Mac and Windows, and how to use it to visualize decision trees)" }, { "code": null, "e": 1007, "s": 928, "text": "How to Visualize Individual Decision Trees from Bagged Trees or Random Forests" }, { "code": null, "e": 1106, "s": 1007, "text": "As always, the code used in this tutorial is available on my GitHub. With that, let’s get started!" }, { "code": null, "e": 1412, "s": 1106, "text": "In order to visualize decision trees, we need first need to fit a decision tree model using scikit-learn. If this section is not clear, I encourage you to read my Understanding Decision Trees for Classification (Python) tutorial as I go into a lot of detail on how decision trees work and how to use them." }, { "code": null, "e": 1499, "s": 1412, "text": "The following import statements are what we will use for this section of the tutorial." }, { "code": null, "e": 1827, "s": 1499, "text": "import matplotlib.pyplot as pltfrom sklearn.datasets import load_irisfrom sklearn.datasets import load_breast_cancerfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import train_test_splitimport pandas as pdimport numpy as npfrom sklearn import tree" }, { "code": null, "e": 2002, "s": 1827, "text": "The Iris dataset is one of datasets scikit-learn comes with that do not require the downloading of any file from some external website. The code below loads the iris dataset." }, { "code": null, "e": 2160, "s": 2002, "text": "import pandas as pdfrom sklearn.datasets import load_irisdata = load_iris()df = pd.DataFrame(data.data, columns=data.feature_names)df['target'] = data.target" }, { "code": null, "e": 2253, "s": 2160, "text": "The code below puts 75% of the data into a training set and 25% of the data into a test set." }, { "code": null, "e": 2359, "s": 2253, "text": "X_train, X_test, Y_train, Y_test = train_test_split(df[data.feature_names], df['target'], random_state=0)" }, { "code": null, "e": 2814, "s": 2359, "text": "# Step 1: Import the model you want to use# This was already imported earlier in the notebook so commenting out#from sklearn.tree import DecisionTreeClassifier# Step 2: Make an instance of the Modelclf = DecisionTreeClassifier(max_depth = 2, random_state = 0)# Step 3: Train the model on the dataclf.fit(X_train, Y_train)# Step 4: Predict labels of unseen (test) data# Not doing this step in the tutorial# clf.predict(X_test)" }, { "code": null, "e": 3072, "s": 2814, "text": "As of scikit-learn version 21.0 (roughly May 2019), Decision Trees can now be plotted with matplotlib using scikit-learn’s tree.plot_tree without relying on the dot library which is a hard-to-install dependency which we will cover later on in the blog post." }, { "code": null, "e": 3129, "s": 3072, "text": "The code below plots a decision tree using scikit-learn." }, { "code": null, "e": 3150, "s": 3129, "text": "tree.plot_tree(clf);" }, { "code": null, "e": 3353, "s": 3150, "text": "In addition to adding the code to allow you to save your image, the code below tries to make the decision tree more interpretable by adding in feature and class names (as well as setting filled = True)." }, { "code": null, "e": 3688, "s": 3353, "text": "fn=['sepal length (cm)','sepal width (cm)','petal length (cm)','petal width (cm)']cn=['setosa', 'versicolor', 'virginica']fig, axes = plt.subplots(nrows = 1,ncols = 1,figsize = (4,4), dpi=300)tree.plot_tree(clf, feature_names = fn, class_names=cn, filled = True);fig.savefig('imagename.png')" }, { "code": null, "e": 4581, "s": 3688, "text": "Graphviz is open source graph visualization software. Graph visualization is a way of representing structural information as diagrams of abstract graphs and networks. In data science, one use of Graphviz is to visualize decision trees. I should note that the reason why I am going over Graphviz after covering Matplotlib is that getting this to work can be difficult. The first part of this process involves creating a dot file. A dot file is a Graphviz representation of a decision tree. The problem is that using Graphviz to convert the dot file into an image file (png, jpg, etc) can be difficult. There are a couple ways to do this including: installing python-graphviz though Anaconda, installing Graphviz through Homebrew (Mac), installing Graphviz executables from the official site (Windows), and using an online converter on the contents of your dot file to convert it into an image." }, { "code": null, "e": 4709, "s": 4581, "text": "The code below code will work on any operating system as python generates the dot file and exports it as a file named tree.dot." }, { "code": null, "e": 4888, "s": 4709, "text": "tree.export_graphviz(clf, out_file=\"tree.dot\", feature_names = fn, class_names=cn, filled = True)" }, { "code": null, "e": 5192, "s": 4888, "text": "Converting the dot file into an image file (png, jpg, etc) typically requires the installation of Graphviz which depends on your operating system and a host of other things. The goal of this section is to help people try and solve the common issue of getting the following error. dot: command not found." }, { "code": null, "e": 5239, "s": 5192, "text": "How to Install and Use on Mac through Anaconda" }, { "code": null, "e": 5423, "s": 5239, "text": "To be able to install Graphviz on your Mac through this method, you first need to have Anaconda installed (If you don’t have Anaconda installed, you can learn how to install it here)." }, { "code": null, "e": 5585, "s": 5423, "text": "Open a terminal. You can do this by clicking on the Spotlight magnifying glass at the top right of the screen, type terminal and then click on the Terminal icon." }, { "code": null, "e": 5629, "s": 5585, "text": "Type the command below to install Graphviz." }, { "code": null, "e": 5659, "s": 5629, "text": "conda install python-graphviz" }, { "code": null, "e": 5760, "s": 5659, "text": "After that, you should be able to use the dot command below to convert the dot file into a png file." }, { "code": null, "e": 5791, "s": 5760, "text": "dot -Tpng tree.dot -o tree.png" }, { "code": null, "e": 5838, "s": 5791, "text": "How to Install and Use on Mac through Homebrew" }, { "code": null, "e": 6139, "s": 5838, "text": "If you don’t have Anaconda or just want another way of installing Graphviz on your Mac, you can use Homebrew. I previously wrote an article on how to install Homebrew and use it to convert a dot file into an image file here (see the Homebrew to Help Visualize Decision Trees section of the tutorial)." }, { "code": null, "e": 6190, "s": 6139, "text": "How to Install and Use on Windows through Anaconda" }, { "code": null, "e": 6418, "s": 6190, "text": "This is the method I prefer on Windows. To be able to install Graphviz on your Windows through this method, you first need to have Anaconda installed (If you don’t have Anaconda installed, you can learn how to install it here)." }, { "code": null, "e": 6498, "s": 6418, "text": "Open a terminal/command prompt and enter the command below to install Graphviz." }, { "code": null, "e": 6528, "s": 6498, "text": "conda install python-graphviz" }, { "code": null, "e": 6629, "s": 6528, "text": "After that, you should be able to use the dot command below to convert the dot file into a png file." }, { "code": null, "e": 6660, "s": 6629, "text": "dot -Tpng tree.dot -o tree.png" }, { "code": null, "e": 6722, "s": 6660, "text": "How to Install and Use on Windows through Graphviz Executable" }, { "code": null, "e": 6873, "s": 6722, "text": "If you don’t have Anaconda or just want another way of installing Graphviz on your Windows, you can use the following link to download and install it." }, { "code": null, "e": 6970, "s": 6873, "text": "If all else fails or you simply don’t want to install anything, you can use an online converter." }, { "code": null, "e": 7135, "s": 6970, "text": "In the image below, I opened the file with Sublime Text (though there are many different programs that can open/read a dot file) and copied the content of the file." }, { "code": null, "e": 7336, "s": 7135, "text": "In the image below, I pasted the content from the dot file onto the left side of the online converter. You can then choose what format you want and then save the image on the right side of the screen." }, { "code": null, "e": 7428, "s": 7336, "text": "Keep in mind that there are other online converters that can help accomplish the same task." }, { "code": null, "e": 8454, "s": 7428, "text": "A weakness of decision trees is that they don’t tend to have the best predictive accuracy. This is partially because of high variance, meaning that different splits in the training data can lead to very different trees. The video above covers Bagged Trees which is an ensemble model. This means using multiple learning algorithms to obtain a better predictive performance than could be obtained from any of the constituent learning algorithms alone. In this case, many trees protect each other from their individual errors. The interesting thing is that the thumbnail from the video above could be a diagram for either Bagged Trees or Random Forests (another ensemble model). The differences between how Bagged Trees and Random Forests models work is a subject for another blog, but what is important to note is that for both models we grow N trees where N is the number of decision trees a user specifies. Consequently after you fit a model, it would be nice to look at the individual decision trees that make up your model." }, { "code": null, "e": 8631, "s": 8454, "text": "In order to visualize individual decision trees, we need first need to fit a Bagged Trees or Random Forest model using scikit-learn (the code below fits a Random Forest model)." }, { "code": null, "e": 9187, "s": 8631, "text": "# Load the Breast Cancer (Diagnostic) Datasetdata = load_breast_cancer()df = pd.DataFrame(data.data, columns=data.feature_names)df['target'] = data.target# Arrange Data into Features Matrix and Target VectorX = df.loc[:, df.columns != 'target']y = df.loc[:, 'target'].values# Split the data into training and testing setsX_train, X_test, Y_train, Y_test = train_test_split(X, y, random_state=0)# Random Forests in `scikit-learn` (with N = 100)rf = RandomForestClassifier(n_estimators=100, random_state=0)rf.fit(X_train, Y_train)" }, { "code": null, "e": 9327, "s": 9187, "text": "You can now view all the individual trees from the fitted model. In this section, I will visualize all the decision trees using matplotlib." }, { "code": null, "e": 9342, "s": 9327, "text": "rf.estimators_" }, { "code": null, "e": 9433, "s": 9342, "text": "You can now visualize individual trees. The code below visualizes the first decision tree." }, { "code": null, "e": 9709, "s": 9433, "text": "fn=data.feature_namescn=data.target_namesfig, axes = plt.subplots(nrows = 1,ncols = 1,figsize = (4,4), dpi=800)tree.plot_tree(rf.estimators_[0], feature_names = fn, class_names=cn, filled = True);fig.savefig('rf_individualtree.png')" }, { "code": null, "e": 9917, "s": 9709, "text": "You can try to use matplotlib subplots to visualize as many of the trees as you like. The code below visualizes the first 5 decision trees. I personally don’t prefer this method as it is even harder to read." }, { "code": null, "e": 10405, "s": 9917, "text": "# This may not the best way to view each estimator as it is smallfn=data.feature_namescn=data.target_namesfig, axes = plt.subplots(nrows = 1,ncols = 5,figsize = (10,2), dpi=3000)for index in range(0, 5): tree.plot_tree(rf.estimators_[index], feature_names = fn, class_names=cn, filled = True, ax = axes[index]); axes[index].set_title('Estimator: ' + str(index), fontsize = 11)fig.savefig('rf_5trees.png')" }, { "code": null, "e": 10702, "s": 10405, "text": "Keep in mind that if for some reason you want images for all your estimators (decision trees), you can do so using the code on my GitHub. If you just want to see each of the 100 estimators for the Random Forest model fit in this tutorial without running the code, you can look at the video below." }, { "code": null, "e": 11276, "s": 10702, "text": "This tutorial covered how to visualize decision trees using Graphviz and Matplotlib. Note that the way to visualize decision trees using Matplotlib is a newer method so it might change or be improved upon in the future. Graphviz is currently more flexible as you can always modify your dot files to make them more visually appealing like I did using the dot language or even just alter the orientation of your decision tree. One thing we didn’t cover was how to use dtreeviz which is another library that can visualize decision trees. There is an excellent post on it here." } ]
Differences between Interface and class in Java
A class is a blueprint from which individual objects are created. A class can contain any of the following variable types. Local variables − Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed. Local variables − Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed. Instance variables − Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class. Instance variables − Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class. Class variables − Class variables are variables declared within a class, outside any method, with the static keyword. Class variables − Class variables are variables declared within a class, outside any method, with the static keyword. An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. Along with abstract methods, an interface may also contain constants, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods. Writing an interface is similar to writing a class. But a class describes the attributes and behaviors of an object. And an interface contains behaviors that a class implements. Following are the important differences between Class and an Interface. public class JavaTester { public static void main(String args[]) { Animal tiger = new Tiger(); tiger.eat(); Tiger tiger1 = new Tiger(); tiger1.eat(); } } interface Animal { public void eat(); } class Tiger implements Animal { public void eat(){ System.out.println("Tiger eats"); } } Tiger eats Tiger eats
[ { "code": null, "e": 1185, "s": 1062, "text": "A class is a blueprint from which individual objects are created. A class can contain any of the following variable types." }, { "code": null, "e": 1418, "s": 1185, "text": "Local variables − Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed." }, { "code": null, "e": 1651, "s": 1418, "text": "Local variables − Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed." }, { "code": null, "e": 1915, "s": 1651, "text": "Instance variables − Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class." }, { "code": null, "e": 2179, "s": 1915, "text": "Instance variables − Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class." }, { "code": null, "e": 2297, "s": 2179, "text": "Class variables − Class variables are variables declared within a class, outside any method, with the static keyword." }, { "code": null, "e": 2415, "s": 2297, "text": "Class variables − Class variables are variables declared within a class, outside any method, with the static keyword." }, { "code": null, "e": 2612, "s": 2415, "text": "An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface." }, { "code": null, "e": 2798, "s": 2612, "text": "Along with abstract methods, an interface may also contain constants, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods." }, { "code": null, "e": 2976, "s": 2798, "text": "Writing an interface is similar to writing a class. But a class describes the attributes and behaviors of an object. And an interface contains behaviors that a class implements." }, { "code": null, "e": 3048, "s": 2976, "text": "Following are the important differences between Class and an Interface." }, { "code": null, "e": 3376, "s": 3048, "text": "public class JavaTester {\n public static void main(String args[]) {\n Animal tiger = new Tiger();\n tiger.eat();\n Tiger tiger1 = new Tiger();\n tiger1.eat();\n }\n}\ninterface Animal {\n public void eat();\n}\nclass Tiger implements Animal {\n public void eat(){\n System.out.println(\"Tiger eats\");\n }\n}" }, { "code": null, "e": 3398, "s": 3376, "text": "Tiger eats\nTiger eats" } ]
Tryit Editor v3.7
CSS Grid Container Tryit: Using justify-content: end
[ { "code": null, "e": 28, "s": 9, "text": "CSS Grid Container" } ]
How to display a pdf document into an Android Webview?
This example demonstrate about How to lock the Android device programmatically. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml <? xml version= "1.0" encoding= "utf-8" ?> <RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android :layout_width= "match_parent" android :layout_height= "match_parent" android :layout_margin= "16dp" tools :context= ".MainActivity" > <Button android :onClick= "loadPage" android :layout_width= "match_parent" android :layout_height= "wrap_content" android :text= "Load web Page" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity package app.tutorialspoint.com.sample ; import android.os.Bundle ; import android.support.v7.app.AppCompatActivity ; import android.view.View ; import android.webkit.WebView ; public class MainActivity extends AppCompatActivity { @Override protected void onCreate (Bundle savedInstanceState) { super .onCreate(savedInstanceState) ; setContentView(R.layout. activity_main ) ; } public void loadPage (View view) { WebView webview = new WebView( this ) ; webview.getSettings().setJavaScriptEnabled( true ) ; setContentView(webview) ; String pdf = "http://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf" ; webview.loadUrl( "http://drive.google.com/viewerng/viewer?embedded=true&url=" + pdf) ; } } 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.tutorialspoint.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> <receiver android :name= ".DeviceAdmin" android :description= "@string/app_description" android :label= "@string/app_name" android :permission= "android.permission.BIND_DEVICE_ADMIN" > <meta-data android :name= "android.app.device_admin" android :resource= "@xml/policies" /> <intent-filter> <action android :name= "android.app.action.DEVICE_ADMIN_ENABLED" /> </intent-filter> </receiver> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default.
[ { "code": null, "e": 1142, "s": 1062, "text": "This example demonstrate about How to lock the Android device programmatically." }, { "code": null, "e": 1271, "s": 1142, "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": 1335, "s": 1271, "text": "Step 2 − Add the following code to res/layout/activity_main.xml" }, { "code": null, "e": 1856, "s": 1335, "text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<RelativeLayout xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: tools = \"http://schemas.android.com/tools\"\n android :layout_width= \"match_parent\"\n android :layout_height= \"match_parent\"\n android :layout_margin= \"16dp\"\n tools :context= \".MainActivity\" >\n <Button\n android :onClick= \"loadPage\"\n android :layout_width= \"match_parent\"\n android :layout_height= \"wrap_content\"\n android :text= \"Load web Page\" />\n</RelativeLayout>" }, { "code": null, "e": 1908, "s": 1856, "text": "Step 3 − Add the following code to src/MainActivity" }, { "code": null, "e": 2678, "s": 1908, "text": "package app.tutorialspoint.com.sample ;\nimport android.os.Bundle ;\nimport android.support.v7.app.AppCompatActivity ;\nimport android.view.View ;\nimport android.webkit.WebView ;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState) ;\n setContentView(R.layout. activity_main ) ;\n }\n public void loadPage (View view) {\n WebView webview = new WebView( this ) ;\n webview.getSettings().setJavaScriptEnabled( true ) ;\n setContentView(webview) ;\n String pdf =\n \"http://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf\" ;\n webview.loadUrl( \"http://drive.google.com/viewerng/viewer?embedded=true&url=\" + pdf) ;\n }\n}" }, { "code": null, "e": 2733, "s": 2678, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3950, "s": 2733, "text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package= \"app.tutorialspoint.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 <receiver\n android :name= \".DeviceAdmin\"\n android :description= \"@string/app_description\"\n android :label= \"@string/app_name\"\n android :permission= \"android.permission.BIND_DEVICE_ADMIN\" >\n <meta-data\n android :name= \"android.app.device_admin\"\n android :resource= \"@xml/policies\" />\n <intent-filter>\n <action android :name= \"android.app.action.DEVICE_ADMIN_ENABLED\" />\n </intent-filter>\n </receiver>\n </application>\n</manifest>" }, { "code": null, "e": 4290, "s": 3950, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default. " } ]
TensorFlow Performance Analysis. How to Get the Most Value from Your... | by Chaim Rand | Towards Data Science
In previous posts (here and here), I told you about how our team uses the Amazon SageMaker and Amazon s3 services to train our deep neural networks on large quantities of data. In this blog, I would like to discuss how to profile the performance of a DNN training session running in TensorFlow. When speaking of the “performance” of a DNN training session, one may be referring to a number of different things. In the context of this blog, “performance” profiling will refer to analysis of the speed at which the training is performed (as measured, for example, by the training throughput in iterations per second), and the manner in which the session utilizes the system resources to achieve this speed. We will not be referring to the performance of the model being trained, often measured by the loss or metric evaluation on a test set. An additional measure of performance is the number of batches required until the training converges. This is also out of the scope of this blog. In short, if you are trying to figure out why your training is running slowly, you have come to the right place. If you are searching for ways to improve the accuracy of your mnist model, or are searching for what optimizer settings to use to accelerate convergence, you have not. The examples we will review were written in TensorFlow and run in the cloud using the Amazon SageMaker service, but the discussion we will have is equally applicable to any other training environment. Any discussion on performance profiling your training requires that we be clear about what the goal is, or, what utility function we are trying to optimize. Your utility function will likely depend on a number of factors, including, the number of training instances at your disposal, the cost of those instances, the number of models you need to train, project scheduling constraints and more. In order to have a meaningful discussion, we will make some simplifying assumptions. Our goal will be to maximize the throughput of a training session, given a fixed training environment, without harming the quality of the resultant model, or increasing the number of training samples required for convergence. The goal, as stated, includes some ambiguities that we will promptly explain. Our first simplifying assumptions are that the training is being performed on a single instance/machine and that the instance type is fixed. Naturally, different models perform differently on different types of machines. In an ideal situation, we would always be able to choose a machine that is optimal for the model being trained, that is, a machine on which all resources would be fully utilized. That way, we would avoid the cost of resources than are not being used. Unfortunately, in the real world, we are usually faced with a fixed number of instance types to choose from. For example, Amazon SageMaker offers a wide variety of instance types to choose from, that differ in the types and number of GPUs, the number of CPUs, the network properties, memory size and more. On the other hand, one does not have the ability to freely choose (based on the properties of their model) a machine with a specific number of CPUs, a specific GPU and specific network bandwidth. In order to choose the most appropriate training instance, one must carefully weigh how well a model is suited to different training instances, versus considerations such as the cost and availability of those instances, as well as scheduling requirements. This requires a comprehensive analysis of the maximum achievable performance of training the model on each of the different instances types, as we describe in this post. We will limit our discussion to instance types with a single GPU. Specifically, we will work on machines with an NVIDIA® V100 Tensor Core GPU. If you are using the Amazon SageMaker service for training, this is the ml.p3.2xlarge instance type. There are many different libraries and frameworks available for training DNN models. As before, the training performance of a fixed model, fixed training algorithm and fixed HW, will vary across different SW solutions. As highlighted in the title of the post, our focus will be on the TensorFlow training environment. Even within this training environment, performance may depend on a number of factors such as the framework version, whether you choose a high level API, such as tf.estimator or tf.keras.model.fit, or implement a custom training loop, and the manner in which you feed your training data into the training pipeline. Our assumptions in this post will be that the training will be performed in TensorFlow 2.2, using the tf.keras.model.fit() API, and that the data will be fed using the tf.dataset APIs. Where there no constraints, speeding up the training throughput would be a piece of cake. For example, we could simply reduce the size of our model architecture and training would fly. Of course, this is likely to kill the ability of the training to converge and the resultant model predictions may be useless. Obviously, we must ensure that any actions we take to accelerate the training does not harm the quality of the resultant model. For our discussion, we introduce an additional constraint, which is, that we do not want to impact the overall time required for training convergence, as measured by the overall number of training samples fed into the network until convergence. In other words, we make the simplifying assumption that our model requires a fixed number of training samples to converge and that the options we have to optimize will not change that fixed number. Based on that assumption, and given a fixed instance and SW environment, our goal is to optimize the overall amount of time (in seconds) that the training takes, or, alternatively, the training throughput, measured in the number of samples being processed by the training loop per second. We emphasize that this is an artificial constraint we introduce to simplify the discussion. There certainly may be situations where a change to the model architecture would increase the number of samples required for convergence, while reducing the overall time to convergence. For example, reducing the bit precision of some of the variables is likely to increase the throughput, but also might require more steps to converge. If the overall time to train is reduced, and the resultant model predicts just as well, then this would be a great optimization. Another important example is increasing the batch size. Increasing the training batch size is one of the basic ways to increase throughput. However, there are some models for which the training quality may be sensitive to the batch size. We make the simplifying assumption that such an impact is negligible and can be overcome by tuning other hyper-parameters (such as the learning rate). The units we will use to measure the throughput are the average number of samples processed by the training loop, per second. An, alternative, more common unit measurement for throughput is the average number of training iterations per second, steps per second, or batches per second. However, since this measurement is based on the chosen (global) batch size, it makes it hard to compare between runs that use different batch sizes. To extract this measurement, you can either rely on the logs that are printed by TensorFlow (at the end of every epoch), or implement the measurement on your own (e.g. with a custom TensorFlow callback). Our main method for increasing training throughput is by increasing the utilization of the resources on our training instance. In theory, any underutilized resource is a potential opportunity to increase throughput. However, practically speaking, once the GPU, the most expensive and important system resource, is fully utilized, and assuming we are satisfied with the performance of our GPU operations, we will consider our mission accomplished. We could, in theory, consider offloading some of the training to the CPU, but the performance gain would likely be negligible (if there is any at all) — certainly not worth the headache. Underutilization could be a result of the pipeline not reaching its maximum capacity (e.g. all of the resources are under-utilized). In this case, increasing the throughput is fairly easy, (e.g. simply increase the batch size). If the pipeline is at maximum capacity, under-utilization of a system resource is typically the result of a bottleneck in the pipeline. For example, the GPU might be idle while it waits for training data to be prepared by the CPU. In such cases, we will attempt to increase the throughput by removing the bottleneck. For example, we might introduce parallelization between the CPU and GPU so that the GPU never has to wait for data. The general strategy is to perform the following two steps iteratively until we are satisfied with the throughput, or until the GPU is fully utilized: 1. Profile the training performance to identify bottlenecks in the pipeline and under-utilized resources 2. Address bottlenecks and increase resource utilization Note that, at any given time, there may be more than one bottleneck in the pipeline. The CPU might be idle as it waits to receive data from the network, and the GPU might be idle as it waits for the CPU to prepare the data for training. Additionally, different bottlenecks might pop up at different stages of the training. For example, the GPU might be fully utilized but idle only during iterations when we save a checkpoint. Such bottlenecks, even if only periodic, could still potentially have a significant impact on the average throughput and should be addressed. This should be abundantly clear by now, but sometimes the obvious requires stating. All too often, I have encountered developers who are perfectly content with 40% GPU utilization. It makes me want to scream. The GPU is (usually) the most expensive resource you are using; if you are happy with any less than 90% utilization, you are wasting your (your company’s) money. Not to mention that you could probably be delivering your product much sooner. It’s all about the money. Training resources are expensive, and if you are not maximizing their utilization, you are committing a crime against humanity. I hope you are convinced of the importance of profiling your training performance and maximizing resource utilization. In the next section we will review some of the potential bottlenecks in a typical training pipeline. We will then survey some of the tools at our disposal for identifying these bottlenecks. In order to facilitate the discussion on the possible bottlenecks within a training session, we present the following diagram of a typical training pipeline. The training is broken down into eight steps, each of which can potentially impede the training flow. Note that while in this diagram training is performed on multiple GPUs, in this post, as mentioned above, we will assume that there is just one GPU. Unless you are auto-generating your training data, you are likely loading it from storage. This might be from local disk or it might be over the network, from a remote storage location. In either case, you are using system resources that could potentially block the pipeline. If the amount of raw data per training sample is particularly large, if your IO interface has high latency, or if the network bandwidth of your training instance is low, you may find your CPU sitting idly as it waits for the raw data to come in. A classic example of this is if you train with Amazon SageMaker using “filemode”. In “filemode” all of the training data is downloaded to local disk before the training even starts. If you have a lot of data, you could be waiting a while. The alternative Amazon Sagemaker option is to use “pipemode”. This allows you to stream data directly from s3 into your input data pipeline, thus avoiding the huge bottleneck to training startup. But even in the case of “pipemode” you can easily run up on resource limitations. For example, if your instance type supports network IO of up to 10 Gigabits per second, and each sample requires 100 Megabits of raw data, you will have an upper limit of 100 training samples per second, no matter how fast your GPU is. The way to overcome such issues is to reduce your raw data, compress some of the data or to choose an instance type with a higher network IO bandwidth. In the example we gave, the limitation came from the network IO bandwidth of the instance, but it could also come from a bandwidth on the amount of data that you can pull from s3, or from somewhere else along the line. (Side note: if you are pulling data from s3 without using pipe mode, make sure to choose an instance type with Elastic Network Adapter enabled.) The next step in the training pipeline is the data pre-processing. In this stage, typically performed on the CPU, the raw data is prepared for entry to the training loop. This might include applying augmentations to input data, inserting masking elements, batching, filtering and more. The tensorflow.dataset functions include built-in functionality for parallelizing the processing operations within the CPU (e.g. the num_parallel_calls argument in the tf.dataset.map routine), and also for running the CPU in parallel with the GPU (e.g. tf.dataset.prefetch). However, if you are running heavy, or memory intensive computation in this stage, you might still find yourself with your GPU idle as it waits for data input. Update: Be sure to check out my recent post, on the topic of performance bottlenecks in the data preprocessing pipeline. In most cases, your CPU and GPU use different memory, and the training samples need to be copied from CPU memory to GPU memory before the training loop can run. This too could potentially result in a bottleneck, depending on the size of your data samples and the interface bandwidth. One thing you should consider, wherever possible, is to hold off on casting to higher bit representation (tf.cast()) or decompressing bit masks (tf.one_hot), until after the data is copied to GPU memory. The heart of the training pipeline is the forward and backward pipeline. This step is performed on the GPU. Being that the GPU is the most expensive resource, we want the GPU to constantly be active and at peak performance. In most cases, the average throughput, in number of samples trained per second, increases as we increase the batch size, so we will try to increase the batch size up to the GPU’s memory capacity. Obviously, the throughput of this step is a function of your model architecture and your loss function. There are quite a number of common methods for reducing the computation. Here is a very small sample of them: · prefer conv layers over dense layers · replace large convolutions with a series of smaller ones with the same receptive field · use low precision or mixed precision variable types · consider using TensorFlow native functions instead of tf.py_func · prefer tf.where over tf.cond · research how your model and layer settings, such as memory layout (channels first or last), and memory alignment (layer input and output size, number of channels, shapes of convolutional filters, etc) impact your GPU performance and design your model accordingly · customize the graph optimization One additional thing to look out for are graph operations, that are not supported by the GPU, and, therefore, offloaded back on to the CPU. Occasionally, you might find that in the middle of your train step, the GPU will send data back to the CPU for processing, and wait until the processed data is returned before resuming computation. Needless to say that this will kill your throughput. In this case, you should use profiling tools to pinpoint the problematic operations and make the necessary adjustments so that they run on the GPU. This step is only performed when training running distributed training on multiple GPUs, either on a single training instance or on multiple instances. We leave the discussion on distributed training for a future post, but will note that this step can also potentially introduce a bottleneck. During distributed training, each GPU must collect the gradients from all other GPUs. Depending on the distribution strategy, the number and size of the gradients, and the bandwidth of the communication channel between GPUs, a GPU may find itself idle while it collects the gradients. To solve such issues, one might reduce the bit precision of the gradients, tune the communication channel or consider other distribution strategies. During training, the GPU will return data to the CPU. Typically, this will include the loss and metric results, but may, periodically, also include more memory intensive output tensors or model weights. As before, this data transfer can potentially introduce a bottleneck at certain phases of the training, depending on the size of the data and the interface bandwidth. The CPU might perform some processing on the output data received from the GPU. This processing typically occurs within TensorFlow callbacks. These can be used to evaluate tensors, create image summaries, collect statistics, update the learning rate and more. There are different ways in which this could reduce the training throughput: · If the processing is computation or memory intensive, this may become a performance bottleneck. If the processing is independent of the model GPU state, you might want to try running in a separate (non-blocking) thread. · Running a large number of callbacks could also bottleneck the pipeline. You might want to consider combining them into a small number. · If your callbacks are processing output on every iteration, you are also likely to be slowing down the throughput. Consider reducing the frequency of the processing, or adding the processing to the GPU model graph (e.g. using custom TensorFlow metrics). During the training the CPU might periodically transfer event files, log files, or model checkpoints to storage. As before, a large quantity of data combined with a limited IO bandwidth could potentially lead to latency in the training pipeline. Even if you are careful to make the data transfer non-blocking (e.g. using dedicated CPU threads) you might be using network input and output channels that share the same limited bandwidth (as on Amazon SageMaker instances). In this case, the amount of raw training data being fed on the network input could drop. One way this could happen is if we collect all of our TensorFlow summaries in a single event file which grows and grows during the course of the training. Each time the event file is uploaded to s3, the amount of data passing on the network increases. When the file becomes very large, the data upload can interfere with the training. Now that we have an understanding of some of the bottlenecks we might face in a training pipeline, let’s review some of the tools and techniques at your disposal for identifying and analyzing them. A good place to start is to assess how the resources of the training instance are being utilized. In Amazon SageMaker these are provided as “Instance Metrics” which are displayed in the “Monitor” section of the training job page, as well as in Amazon SageMaker Studio. Here is an example of how this appears on the training job page: The Instance Metrics include graphs of the memory utilization, CPU utilization, network in, network out, GPU memory utilization, GPU utilization, and disk utilization, where measurements are displayed at five minute intervals. You can use this to make sure things are running as expected and to get a high level indication of what can be improved. (We refer to this as “high level” because of the relatively infrequent measurements.) For example, you can verify that you are, in fact, running on the GPU, and assess how well you are using it. In addition, you can identify anomalies in the different metrics such as: · dips in the CPU/GPU utilization which could indicate a bottleneck · rising CPU memory which could indicate a memory leak · a choppy network-in could indicate an issue with how we are pulling data from s3 · if the network-in is at maximum capacity (when compared to the training instance properties) this could indicate a bottleneck on the input pipeline · a rising network-out could indicate that we are uploading a single file that keeps growing instead of uploading small files · a delay in GPU start time could indicate a lengthy model compilation period One thing worth noting is that the default behavior of TensorFlow is to take up all of the GPU memory. So don’t be overly alarmed (or happy) that the GPU memory utilization shows 100%. To configure TensorFlow to use only the memory it actually needs, you need to apply the lines of code below. gpus = tf.config.experimental.list_physical_devices('GPU')for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, True) Pressing on the “View Instance Metrics” link will take you to the CloudWatch Management Console, where you can play around a bit with the measurements and graphs. For example, you can zoom in to specific intervals of the training, decrease the measurement intervals (to one minute), and display multiple metrics on a single graph. SageMaker allows you to include your own, custom, metrics in this window as well. These are referred to as “Algorithm Metrics”. For details, see the SageMaker documentation. For example, you can define the training throughput as a metric and have it displayed in this window as well. This method of performance analysis leaves much to be desired. Aside from the infrequency of the measurements, we receive little information regarding which parts of code require improvement. An underutilized GPU could stem from a low batch size or from a bottleneck. A highly utilized GPU may be a result of an inefficient loss function. Getting more information will require some heavier artillery. If you are running on your own training instance and not within the SageMaker service, you will need to collect the “instance metrics” yourself using common, off-the-shelf system profilers. In a linux environment you can use command line tools such as nmon, perf, strace, top and iotop. If you are using an NVIDIA® GPU you can use nvidia-smi (with the -l flag). To get a more in depth picture of how the different stages of your training session are performing, you should use a performance profiler. Different profilers are available for different development frameworks. TenorFlow offers the TensorFlow Profiler for profiling tf models. Your first encounter with a performance profiler can be a bit intimidating. There are often multiple graphs, that might appear overloaded and seem, at first, confusing. It is not always immediately clear how to interpret the wealth of data that is reported. But once you get the hang of it, profilers can be very useful in evaluating resource utilization, identifying bottlenecks and improving model performance. TensorFlow Profiler Check out the TensorFlow Profiler Guide and the TensorBoard Profiler Tutorial for instructions on how to use the profiler. When training with tf.keras.model.fit(), the easiest way to integrate profiling is by using the TensorBoard Keras Callback as follows: tbc = tf.keras.callbacks.TensorBoard(log_dir='/tmp/tb', profile_batch='20, 24') This will capture statistics on iterations 20 to 24 and save them to a file that can be opened and analyzed in TensorBoard. (The size of the interval impacts the amount of data captured.) Note that the TensorFlow Profiler callback is limited in that it runs on a range of iterations, not on the whole training session. This means that to evaluate specific iterations (e.g. iterations where you save checkpoints) or to get a sense of how performance changes over time, you will need to run different profiling sessions and compare between them. Alternatively, you could use the more advanced profiling APIs that will allow you to collect statistics more freely. Sometimes that best way to get a good feel for how your training performs is by playing around with your program to see how different changes impact the performance. Here is a small sample of things you can try: · You can train with different batch sizes to test the maximum GPU memory capacity and assess the impact on GPU utilization. · You can loop on the training dataset without performing training as described here to measure the maximum throughput of the input pipeline. · You can train with generated data to assess the maximum GPU throughput. · You can add and remove different parts of the pre-processing pipeline to evaluate their impact on throughput. · You can train with different, simple and complex loss functions to evaluate the impact of the loss function on throughput. · You can train with and without callbacks. · If you want to evaluate the impact of specific functions, replace them with simple dummy functions to assess impact. Another useful programming technique is to simply add prints (e.g. using tf.print()) and timers (e.g. tf.timestamp()) to evaluate the performance of different blocks of code. The information-interference trade-off refers to the simple observation that the more we change the original pipeline in order to extract meaningful performance data, the less meaningful that data actually is. The more we increase the frequency at which we poll the system for utilization metrics, the more the activity of the actual profiling begins to overshadow the activity of the training loop, essentially deeming the captured data useless. Finding the right balance is not always so easy. A complete performance analysis strategy should include profiling at different levels of invasion in order to get as clear a picture as possible of what is going on. In this section we will demonstrate some of the potential performance issues we have discussed in action. Note, that many of the examples we will show were inspired by true events; real issues we encountered during our training on AWS. For each example, we will demonstrate how to identify the performance issues by selecting and analyzing some of the profiling measurements. The model we will use is deep convolutional network that learns to perform pixel level segmentation on an input image. Our base model parallelizes the CPU and GPU processing and runs with a batch size of 64. In this case the training throughput is roughly 100 samples per second. The SageMaker dashboard reports GPU memory utilization of 98% and GPU utilization of between 95% and 100%. The efficiency of the GPU utilization can also be seen from the trace_viewer of the tf profiler where we can see that the GPU is almost always active. Recall that the tf profile was configured to run for five steps, steps 20–24. For the sake of comparison, we will also note that the Instance Metrics reports network-in of 14.9 GBytes per minute, and network-out of under 100 MBytes per minute. To evaluate the impact of the batch size on the performance, we reduce the batch size to 2, leaving all other model properties unchanged. The throughput drops all the way down to 40 samples per second. The effect on GPU utilization and GPU memory utilization is immediately noticeable from the “instance metrics” where we see a significant drop, down to around 60% and 23%, respectively. Naturally, each iteration takes a lot less time, but the percentage of the time during which the GPU is active is much lower. The tf profiler step time graph shows that the small batch size leads to over half the time being spent loading kernels to the GPU. The trace_viewer shows that while the GPU remains unblocked by the input, the tf ops appear to be sparsely scattered across the computation block of each step. In TensorFlow 2.3, a new Memory profiler tool was introduced that allows you to identify underutilization of the GPU memory and get an indication of whether you can safely increase the training batch size. In this example, we will artificially introduce a network bottleneck on the network input. We will do this by dropping every 9 out of 10 input records so that we require 10 times as much input data on the network to maintain the same throughput. Here is the code used to perform this exercise: # id generatordef id_gen(): e = 0 while True: yield e e += 1# enter id to feature dictdef add_id_label(f, i): f['id'] = i return f# create a dataset of indices and zip it with input datasetids = tf.data.Dataset.from_generator(id_gen, tf.int64)ds = tf.data.Dataset.zip((ds, ids))# enter id to feature dictds = ds.map(add_id_label, num_parallel_calls=tf.data.experimental.autotune)# filter out every 9 out of 10 recordsds = ds.filter(lambda f: tf.squeeze(tf.equal(tf.math.floormod(f['id'],10),0))) From the instance metrics, we can see that the network-in caps out at 33.4 GBytes per minute, only a bit more than twice the volume of the normal run (14.9 GBytes) despite the fact that we need ten times as much data. Throughput drops to 22 samples per second. Unsurprisingly, our program is highly input bound. The tf profiler reports that, of the total step time, 77.8% is spent waiting for data. The trace_viewer clearly shows the GPU sitting idle for the majority of each step as it waits for data from the tf_data_iterator_get_next op. TensorFlow offers ways to maximize the parallelization of the data processing (as demonstrated in the TensorBoard Profiler Tutorials) but this does not absolve you from optimizing your input data processing pipeline. If your data processing is resource intensive, it may impact the performance of your model, and you might want to consider moving some of your processing offline. If the heavy operation is GPU friendly, (e.g. a large convolution), you can also consider performing the operation on the GPU using the experimental map_on_gpu function, (but keep in mind the overhead of the data transfer). Another option is to choose a training instance with more CPU cores. In this example, we will simulate an overloaded pre-processing pipeline, by applying a separable_conv2d with filter size 7x7 to the input frame. The throughput drops to just 25 samples per second, and the maximum GPU utilization to 36%. The CPU utilization, on the other hand, jumps from 66% to 96%. Once again, the program is highly input bound, and the trace-viewer shows large chunks of GPU idle time. Careful analysis of the CPU section of the trace-viewer, (not shown here), shows that separable convolution taking up large chunks of the compute. In this example, we artificially increase the input data being passed to the GPU by blowing up the size of the input frame by a factor of 10. On the CPU side we simply replicate the input frame 10 times (using tf.tile()). On the GPU we receive the enlarged input frame, but immediately discard the added data. The throughput in this case drops to 84 samples per second, and the bottleneck is clearly evident on the trace-viewer. Notice how, for each step, the size of the block of Stream #20(MemcpyH2D) has grown, and how the GPU compute remains idle until the block has completed. In this example, we simulate the impact of an inefficient graph, by applying an 11x11 convolution filter to the output of the model before calculating the loss function. Unsurprisingly, the throughput drops slightly, to 96 samples per second. The impact on the graph can be viewed on the tf profiler tensorflow stats page, where we see that the added operation becomes the most time-consuming operation in the GPU. This table gives us information on the heaviest operations, which we can use to improve the model performance. In this example, we add a callback function that simulates processing the segmentation masks that are output by the model, by creating and storing 64 random images after every iteration. The first thing we notice, is that TensorFlow prints the following warning: WARNING:tensorflow:Method (on_train_batch_end) is slow compared to the batch update (0.814319). Check your callbacks. Additionally, the throughput drops to 43 samples per second, the GPU utilization drops to 46%, and tf profiler reports that the GPU is active for only 47% of each time step. The bottleneck is clearly seen on the trace-viewer where we see the GPU idle for the second half of each step. As we have shown, the ability to analyze and optimize the performance of your training sessions, can lead to meaningful savings in time and cost. The skills required to perform such analysis should exist in your DNN development team. The analysis should be an integral part of your team’s development methodology and incorporated into your DNN training life cycle. Your development plan should include details such as at when to run performance profiling, what tools to use, what type of tests to run, how invasive the tests should be, and more. In this post we have barely touched the surface of the world of performance analysis. There are, no doubt, many more tools and techniques, other kinds of bottlenecks, and other ways to squeeze more performance out of your training resources. Our goal was merely to introduce you into this world, and emphasize its importance in your day to day training. Best of luck to you!!
[ { "code": null, "e": 349, "s": 172, "text": "In previous posts (here and here), I told you about how our team uses the Amazon SageMaker and Amazon s3 services to train our deep neural networks on large quantities of data." }, { "code": null, "e": 1157, "s": 349, "text": "In this blog, I would like to discuss how to profile the performance of a DNN training session running in TensorFlow. When speaking of the “performance” of a DNN training session, one may be referring to a number of different things. In the context of this blog, “performance” profiling will refer to analysis of the speed at which the training is performed (as measured, for example, by the training throughput in iterations per second), and the manner in which the session utilizes the system resources to achieve this speed. We will not be referring to the performance of the model being trained, often measured by the loss or metric evaluation on a test set. An additional measure of performance is the number of batches required until the training converges. This is also out of the scope of this blog." }, { "code": null, "e": 1438, "s": 1157, "text": "In short, if you are trying to figure out why your training is running slowly, you have come to the right place. If you are searching for ways to improve the accuracy of your mnist model, or are searching for what optimizer settings to use to accelerate convergence, you have not." }, { "code": null, "e": 1639, "s": 1438, "text": "The examples we will review were written in TensorFlow and run in the cloud using the Amazon SageMaker service, but the discussion we will have is equally applicable to any other training environment." }, { "code": null, "e": 2033, "s": 1639, "text": "Any discussion on performance profiling your training requires that we be clear about what the goal is, or, what utility function we are trying to optimize. Your utility function will likely depend on a number of factors, including, the number of training instances at your disposal, the cost of those instances, the number of models you need to train, project scheduling constraints and more." }, { "code": null, "e": 2344, "s": 2033, "text": "In order to have a meaningful discussion, we will make some simplifying assumptions. Our goal will be to maximize the throughput of a training session, given a fixed training environment, without harming the quality of the resultant model, or increasing the number of training samples required for convergence." }, { "code": null, "e": 2422, "s": 2344, "text": "The goal, as stated, includes some ambiguities that we will promptly explain." }, { "code": null, "e": 2563, "s": 2422, "text": "Our first simplifying assumptions are that the training is being performed on a single instance/machine and that the instance type is fixed." }, { "code": null, "e": 3396, "s": 2563, "text": "Naturally, different models perform differently on different types of machines. In an ideal situation, we would always be able to choose a machine that is optimal for the model being trained, that is, a machine on which all resources would be fully utilized. That way, we would avoid the cost of resources than are not being used. Unfortunately, in the real world, we are usually faced with a fixed number of instance types to choose from. For example, Amazon SageMaker offers a wide variety of instance types to choose from, that differ in the types and number of GPUs, the number of CPUs, the network properties, memory size and more. On the other hand, one does not have the ability to freely choose (based on the properties of their model) a machine with a specific number of CPUs, a specific GPU and specific network bandwidth." }, { "code": null, "e": 3822, "s": 3396, "text": "In order to choose the most appropriate training instance, one must carefully weigh how well a model is suited to different training instances, versus considerations such as the cost and availability of those instances, as well as scheduling requirements. This requires a comprehensive analysis of the maximum achievable performance of training the model on each of the different instances types, as we describe in this post." }, { "code": null, "e": 4066, "s": 3822, "text": "We will limit our discussion to instance types with a single GPU. Specifically, we will work on machines with an NVIDIA® V100 Tensor Core GPU. If you are using the Amazon SageMaker service for training, this is the ml.p3.2xlarge instance type." }, { "code": null, "e": 4883, "s": 4066, "text": "There are many different libraries and frameworks available for training DNN models. As before, the training performance of a fixed model, fixed training algorithm and fixed HW, will vary across different SW solutions. As highlighted in the title of the post, our focus will be on the TensorFlow training environment. Even within this training environment, performance may depend on a number of factors such as the framework version, whether you choose a high level API, such as tf.estimator or tf.keras.model.fit, or implement a custom training loop, and the manner in which you feed your training data into the training pipeline. Our assumptions in this post will be that the training will be performed in TensorFlow 2.2, using the tf.keras.model.fit() API, and that the data will be fed using the tf.dataset APIs." }, { "code": null, "e": 5322, "s": 4883, "text": "Where there no constraints, speeding up the training throughput would be a piece of cake. For example, we could simply reduce the size of our model architecture and training would fly. Of course, this is likely to kill the ability of the training to converge and the resultant model predictions may be useless. Obviously, we must ensure that any actions we take to accelerate the training does not harm the quality of the resultant model." }, { "code": null, "e": 6054, "s": 5322, "text": "For our discussion, we introduce an additional constraint, which is, that we do not want to impact the overall time required for training convergence, as measured by the overall number of training samples fed into the network until convergence. In other words, we make the simplifying assumption that our model requires a fixed number of training samples to converge and that the options we have to optimize will not change that fixed number. Based on that assumption, and given a fixed instance and SW environment, our goal is to optimize the overall amount of time (in seconds) that the training takes, or, alternatively, the training throughput, measured in the number of samples being processed by the training loop per second." }, { "code": null, "e": 7000, "s": 6054, "text": "We emphasize that this is an artificial constraint we introduce to simplify the discussion. There certainly may be situations where a change to the model architecture would increase the number of samples required for convergence, while reducing the overall time to convergence. For example, reducing the bit precision of some of the variables is likely to increase the throughput, but also might require more steps to converge. If the overall time to train is reduced, and the resultant model predicts just as well, then this would be a great optimization. Another important example is increasing the batch size. Increasing the training batch size is one of the basic ways to increase throughput. However, there are some models for which the training quality may be sensitive to the batch size. We make the simplifying assumption that such an impact is negligible and can be overcome by tuning other hyper-parameters (such as the learning rate)." }, { "code": null, "e": 7434, "s": 7000, "text": "The units we will use to measure the throughput are the average number of samples processed by the training loop, per second. An, alternative, more common unit measurement for throughput is the average number of training iterations per second, steps per second, or batches per second. However, since this measurement is based on the chosen (global) batch size, it makes it hard to compare between runs that use different batch sizes." }, { "code": null, "e": 7638, "s": 7434, "text": "To extract this measurement, you can either rely on the logs that are printed by TensorFlow (at the end of every epoch), or implement the measurement on your own (e.g. with a custom TensorFlow callback)." }, { "code": null, "e": 8933, "s": 7638, "text": "Our main method for increasing training throughput is by increasing the utilization of the resources on our training instance. In theory, any underutilized resource is a potential opportunity to increase throughput. However, practically speaking, once the GPU, the most expensive and important system resource, is fully utilized, and assuming we are satisfied with the performance of our GPU operations, we will consider our mission accomplished. We could, in theory, consider offloading some of the training to the CPU, but the performance gain would likely be negligible (if there is any at all) — certainly not worth the headache. Underutilization could be a result of the pipeline not reaching its maximum capacity (e.g. all of the resources are under-utilized). In this case, increasing the throughput is fairly easy, (e.g. simply increase the batch size). If the pipeline is at maximum capacity, under-utilization of a system resource is typically the result of a bottleneck in the pipeline. For example, the GPU might be idle while it waits for training data to be prepared by the CPU. In such cases, we will attempt to increase the throughput by removing the bottleneck. For example, we might introduce parallelization between the CPU and GPU so that the GPU never has to wait for data." }, { "code": null, "e": 9084, "s": 8933, "text": "The general strategy is to perform the following two steps iteratively until we are satisfied with the throughput, or until the GPU is fully utilized:" }, { "code": null, "e": 9189, "s": 9084, "text": "1. Profile the training performance to identify bottlenecks in the pipeline and under-utilized resources" }, { "code": null, "e": 9246, "s": 9189, "text": "2. Address bottlenecks and increase resource utilization" }, { "code": null, "e": 9815, "s": 9246, "text": "Note that, at any given time, there may be more than one bottleneck in the pipeline. The CPU might be idle as it waits to receive data from the network, and the GPU might be idle as it waits for the CPU to prepare the data for training. Additionally, different bottlenecks might pop up at different stages of the training. For example, the GPU might be fully utilized but idle only during iterations when we save a checkpoint. Such bottlenecks, even if only periodic, could still potentially have a significant impact on the average throughput and should be addressed." }, { "code": null, "e": 10265, "s": 9815, "text": "This should be abundantly clear by now, but sometimes the obvious requires stating. All too often, I have encountered developers who are perfectly content with 40% GPU utilization. It makes me want to scream. The GPU is (usually) the most expensive resource you are using; if you are happy with any less than 90% utilization, you are wasting your (your company’s) money. Not to mention that you could probably be delivering your product much sooner." }, { "code": null, "e": 10419, "s": 10265, "text": "It’s all about the money. Training resources are expensive, and if you are not maximizing their utilization, you are committing a crime against humanity." }, { "code": null, "e": 10728, "s": 10419, "text": "I hope you are convinced of the importance of profiling your training performance and maximizing resource utilization. In the next section we will review some of the potential bottlenecks in a typical training pipeline. We will then survey some of the tools at our disposal for identifying these bottlenecks." }, { "code": null, "e": 11137, "s": 10728, "text": "In order to facilitate the discussion on the possible bottlenecks within a training session, we present the following diagram of a typical training pipeline. The training is broken down into eight steps, each of which can potentially impede the training flow. Note that while in this diagram training is performed on multiple GPUs, in this post, as mentioned above, we will assume that there is just one GPU." }, { "code": null, "e": 12564, "s": 11137, "text": "Unless you are auto-generating your training data, you are likely loading it from storage. This might be from local disk or it might be over the network, from a remote storage location. In either case, you are using system resources that could potentially block the pipeline. If the amount of raw data per training sample is particularly large, if your IO interface has high latency, or if the network bandwidth of your training instance is low, you may find your CPU sitting idly as it waits for the raw data to come in. A classic example of this is if you train with Amazon SageMaker using “filemode”. In “filemode” all of the training data is downloaded to local disk before the training even starts. If you have a lot of data, you could be waiting a while. The alternative Amazon Sagemaker option is to use “pipemode”. This allows you to stream data directly from s3 into your input data pipeline, thus avoiding the huge bottleneck to training startup. But even in the case of “pipemode” you can easily run up on resource limitations. For example, if your instance type supports network IO of up to 10 Gigabits per second, and each sample requires 100 Megabits of raw data, you will have an upper limit of 100 training samples per second, no matter how fast your GPU is. The way to overcome such issues is to reduce your raw data, compress some of the data or to choose an instance type with a higher network IO bandwidth." }, { "code": null, "e": 12928, "s": 12564, "text": "In the example we gave, the limitation came from the network IO bandwidth of the instance, but it could also come from a bandwidth on the amount of data that you can pull from s3, or from somewhere else along the line. (Side note: if you are pulling data from s3 without using pipe mode, make sure to choose an instance type with Elastic Network Adapter enabled.)" }, { "code": null, "e": 13648, "s": 12928, "text": "The next step in the training pipeline is the data pre-processing. In this stage, typically performed on the CPU, the raw data is prepared for entry to the training loop. This might include applying augmentations to input data, inserting masking elements, batching, filtering and more. The tensorflow.dataset functions include built-in functionality for parallelizing the processing operations within the CPU (e.g. the num_parallel_calls argument in the tf.dataset.map routine), and also for running the CPU in parallel with the GPU (e.g. tf.dataset.prefetch). However, if you are running heavy, or memory intensive computation in this stage, you might still find yourself with your GPU idle as it waits for data input." }, { "code": null, "e": 13769, "s": 13648, "text": "Update: Be sure to check out my recent post, on the topic of performance bottlenecks in the data preprocessing pipeline." }, { "code": null, "e": 14257, "s": 13769, "text": "In most cases, your CPU and GPU use different memory, and the training samples need to be copied from CPU memory to GPU memory before the training loop can run. This too could potentially result in a bottleneck, depending on the size of your data samples and the interface bandwidth. One thing you should consider, wherever possible, is to hold off on casting to higher bit representation (tf.cast()) or decompressing bit masks (tf.one_hot), until after the data is copied to GPU memory." }, { "code": null, "e": 14677, "s": 14257, "text": "The heart of the training pipeline is the forward and backward pipeline. This step is performed on the GPU. Being that the GPU is the most expensive resource, we want the GPU to constantly be active and at peak performance. In most cases, the average throughput, in number of samples trained per second, increases as we increase the batch size, so we will try to increase the batch size up to the GPU’s memory capacity." }, { "code": null, "e": 14891, "s": 14677, "text": "Obviously, the throughput of this step is a function of your model architecture and your loss function. There are quite a number of common methods for reducing the computation. Here is a very small sample of them:" }, { "code": null, "e": 14930, "s": 14891, "text": "· prefer conv layers over dense layers" }, { "code": null, "e": 15019, "s": 14930, "text": "· replace large convolutions with a series of smaller ones with the same receptive field" }, { "code": null, "e": 15073, "s": 15019, "text": "· use low precision or mixed precision variable types" }, { "code": null, "e": 15140, "s": 15073, "text": "· consider using TensorFlow native functions instead of tf.py_func" }, { "code": null, "e": 15171, "s": 15140, "text": "· prefer tf.where over tf.cond" }, { "code": null, "e": 15436, "s": 15171, "text": "· research how your model and layer settings, such as memory layout (channels first or last), and memory alignment (layer input and output size, number of channels, shapes of convolutional filters, etc) impact your GPU performance and design your model accordingly" }, { "code": null, "e": 15471, "s": 15436, "text": "· customize the graph optimization" }, { "code": null, "e": 16010, "s": 15471, "text": "One additional thing to look out for are graph operations, that are not supported by the GPU, and, therefore, offloaded back on to the CPU. Occasionally, you might find that in the middle of your train step, the GPU will send data back to the CPU for processing, and wait until the processed data is returned before resuming computation. Needless to say that this will kill your throughput. In this case, you should use profiling tools to pinpoint the problematic operations and make the necessary adjustments so that they run on the GPU." }, { "code": null, "e": 16737, "s": 16010, "text": "This step is only performed when training running distributed training on multiple GPUs, either on a single training instance or on multiple instances. We leave the discussion on distributed training for a future post, but will note that this step can also potentially introduce a bottleneck. During distributed training, each GPU must collect the gradients from all other GPUs. Depending on the distribution strategy, the number and size of the gradients, and the bandwidth of the communication channel between GPUs, a GPU may find itself idle while it collects the gradients. To solve such issues, one might reduce the bit precision of the gradients, tune the communication channel or consider other distribution strategies." }, { "code": null, "e": 17107, "s": 16737, "text": "During training, the GPU will return data to the CPU. Typically, this will include the loss and metric results, but may, periodically, also include more memory intensive output tensors or model weights. As before, this data transfer can potentially introduce a bottleneck at certain phases of the training, depending on the size of the data and the interface bandwidth." }, { "code": null, "e": 17444, "s": 17107, "text": "The CPU might perform some processing on the output data received from the GPU. This processing typically occurs within TensorFlow callbacks. These can be used to evaluate tensors, create image summaries, collect statistics, update the learning rate and more. There are different ways in which this could reduce the training throughput:" }, { "code": null, "e": 17666, "s": 17444, "text": "· If the processing is computation or memory intensive, this may become a performance bottleneck. If the processing is independent of the model GPU state, you might want to try running in a separate (non-blocking) thread." }, { "code": null, "e": 17803, "s": 17666, "text": "· Running a large number of callbacks could also bottleneck the pipeline. You might want to consider combining them into a small number." }, { "code": null, "e": 18059, "s": 17803, "text": "· If your callbacks are processing output on every iteration, you are also likely to be slowing down the throughput. Consider reducing the frequency of the processing, or adding the processing to the GPU model graph (e.g. using custom TensorFlow metrics)." }, { "code": null, "e": 18619, "s": 18059, "text": "During the training the CPU might periodically transfer event files, log files, or model checkpoints to storage. As before, a large quantity of data combined with a limited IO bandwidth could potentially lead to latency in the training pipeline. Even if you are careful to make the data transfer non-blocking (e.g. using dedicated CPU threads) you might be using network input and output channels that share the same limited bandwidth (as on Amazon SageMaker instances). In this case, the amount of raw training data being fed on the network input could drop." }, { "code": null, "e": 18954, "s": 18619, "text": "One way this could happen is if we collect all of our TensorFlow summaries in a single event file which grows and grows during the course of the training. Each time the event file is uploaded to s3, the amount of data passing on the network increases. When the file becomes very large, the data upload can interfere with the training." }, { "code": null, "e": 19152, "s": 18954, "text": "Now that we have an understanding of some of the bottlenecks we might face in a training pipeline, let’s review some of the tools and techniques at your disposal for identifying and analyzing them." }, { "code": null, "e": 19486, "s": 19152, "text": "A good place to start is to assess how the resources of the training instance are being utilized. In Amazon SageMaker these are provided as “Instance Metrics” which are displayed in the “Monitor” section of the training job page, as well as in Amazon SageMaker Studio. Here is an example of how this appears on the training job page:" }, { "code": null, "e": 20103, "s": 19486, "text": "The Instance Metrics include graphs of the memory utilization, CPU utilization, network in, network out, GPU memory utilization, GPU utilization, and disk utilization, where measurements are displayed at five minute intervals. You can use this to make sure things are running as expected and to get a high level indication of what can be improved. (We refer to this as “high level” because of the relatively infrequent measurements.) For example, you can verify that you are, in fact, running on the GPU, and assess how well you are using it. In addition, you can identify anomalies in the different metrics such as:" }, { "code": null, "e": 20171, "s": 20103, "text": "· dips in the CPU/GPU utilization which could indicate a bottleneck" }, { "code": null, "e": 20226, "s": 20171, "text": "· rising CPU memory which could indicate a memory leak" }, { "code": null, "e": 20309, "s": 20226, "text": "· a choppy network-in could indicate an issue with how we are pulling data from s3" }, { "code": null, "e": 20459, "s": 20309, "text": "· if the network-in is at maximum capacity (when compared to the training instance properties) this could indicate a bottleneck on the input pipeline" }, { "code": null, "e": 20585, "s": 20459, "text": "· a rising network-out could indicate that we are uploading a single file that keeps growing instead of uploading small files" }, { "code": null, "e": 20663, "s": 20585, "text": "· a delay in GPU start time could indicate a lengthy model compilation period" }, { "code": null, "e": 20957, "s": 20663, "text": "One thing worth noting is that the default behavior of TensorFlow is to take up all of the GPU memory. So don’t be overly alarmed (or happy) that the GPU memory utilization shows 100%. To configure TensorFlow to use only the memory it actually needs, you need to apply the lines of code below." }, { "code": null, "e": 21087, "s": 20957, "text": "gpus = tf.config.experimental.list_physical_devices('GPU')for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, True)" }, { "code": null, "e": 21418, "s": 21087, "text": "Pressing on the “View Instance Metrics” link will take you to the CloudWatch Management Console, where you can play around a bit with the measurements and graphs. For example, you can zoom in to specific intervals of the training, decrease the measurement intervals (to one minute), and display multiple metrics on a single graph." }, { "code": null, "e": 21702, "s": 21418, "text": "SageMaker allows you to include your own, custom, metrics in this window as well. These are referred to as “Algorithm Metrics”. For details, see the SageMaker documentation. For example, you can define the training throughput as a metric and have it displayed in this window as well." }, { "code": null, "e": 22103, "s": 21702, "text": "This method of performance analysis leaves much to be desired. Aside from the infrequency of the measurements, we receive little information regarding which parts of code require improvement. An underutilized GPU could stem from a low batch size or from a bottleneck. A highly utilized GPU may be a result of an inefficient loss function. Getting more information will require some heavier artillery." }, { "code": null, "e": 22465, "s": 22103, "text": "If you are running on your own training instance and not within the SageMaker service, you will need to collect the “instance metrics” yourself using common, off-the-shelf system profilers. In a linux environment you can use command line tools such as nmon, perf, strace, top and iotop. If you are using an NVIDIA® GPU you can use nvidia-smi (with the -l flag)." }, { "code": null, "e": 23155, "s": 22465, "text": "To get a more in depth picture of how the different stages of your training session are performing, you should use a performance profiler. Different profilers are available for different development frameworks. TenorFlow offers the TensorFlow Profiler for profiling tf models. Your first encounter with a performance profiler can be a bit intimidating. There are often multiple graphs, that might appear overloaded and seem, at first, confusing. It is not always immediately clear how to interpret the wealth of data that is reported. But once you get the hang of it, profilers can be very useful in evaluating resource utilization, identifying bottlenecks and improving model performance." }, { "code": null, "e": 23175, "s": 23155, "text": "TensorFlow Profiler" }, { "code": null, "e": 23433, "s": 23175, "text": "Check out the TensorFlow Profiler Guide and the TensorBoard Profiler Tutorial for instructions on how to use the profiler. When training with tf.keras.model.fit(), the easiest way to integrate profiling is by using the TensorBoard Keras Callback as follows:" }, { "code": null, "e": 23556, "s": 23433, "text": "tbc = tf.keras.callbacks.TensorBoard(log_dir='/tmp/tb', profile_batch='20, 24')" }, { "code": null, "e": 23744, "s": 23556, "text": "This will capture statistics on iterations 20 to 24 and save them to a file that can be opened and analyzed in TensorBoard. (The size of the interval impacts the amount of data captured.)" }, { "code": null, "e": 24217, "s": 23744, "text": "Note that the TensorFlow Profiler callback is limited in that it runs on a range of iterations, not on the whole training session. This means that to evaluate specific iterations (e.g. iterations where you save checkpoints) or to get a sense of how performance changes over time, you will need to run different profiling sessions and compare between them. Alternatively, you could use the more advanced profiling APIs that will allow you to collect statistics more freely." }, { "code": null, "e": 24429, "s": 24217, "text": "Sometimes that best way to get a good feel for how your training performs is by playing around with your program to see how different changes impact the performance. Here is a small sample of things you can try:" }, { "code": null, "e": 24554, "s": 24429, "text": "· You can train with different batch sizes to test the maximum GPU memory capacity and assess the impact on GPU utilization." }, { "code": null, "e": 24696, "s": 24554, "text": "· You can loop on the training dataset without performing training as described here to measure the maximum throughput of the input pipeline." }, { "code": null, "e": 24770, "s": 24696, "text": "· You can train with generated data to assess the maximum GPU throughput." }, { "code": null, "e": 24882, "s": 24770, "text": "· You can add and remove different parts of the pre-processing pipeline to evaluate their impact on throughput." }, { "code": null, "e": 25007, "s": 24882, "text": "· You can train with different, simple and complex loss functions to evaluate the impact of the loss function on throughput." }, { "code": null, "e": 25051, "s": 25007, "text": "· You can train with and without callbacks." }, { "code": null, "e": 25170, "s": 25051, "text": "· If you want to evaluate the impact of specific functions, replace them with simple dummy functions to assess impact." }, { "code": null, "e": 25345, "s": 25170, "text": "Another useful programming technique is to simply add prints (e.g. using tf.print()) and timers (e.g. tf.timestamp()) to evaluate the performance of different blocks of code." }, { "code": null, "e": 25792, "s": 25345, "text": "The information-interference trade-off refers to the simple observation that the more we change the original pipeline in order to extract meaningful performance data, the less meaningful that data actually is. The more we increase the frequency at which we poll the system for utilization metrics, the more the activity of the actual profiling begins to overshadow the activity of the training loop, essentially deeming the captured data useless." }, { "code": null, "e": 26007, "s": 25792, "text": "Finding the right balance is not always so easy. A complete performance analysis strategy should include profiling at different levels of invasion in order to get as clear a picture as possible of what is going on." }, { "code": null, "e": 26383, "s": 26007, "text": "In this section we will demonstrate some of the potential performance issues we have discussed in action. Note, that many of the examples we will show were inspired by true events; real issues we encountered during our training on AWS. For each example, we will demonstrate how to identify the performance issues by selecting and analyzing some of the profiling measurements." }, { "code": null, "e": 26770, "s": 26383, "text": "The model we will use is deep convolutional network that learns to perform pixel level segmentation on an input image. Our base model parallelizes the CPU and GPU processing and runs with a batch size of 64. In this case the training throughput is roughly 100 samples per second. The SageMaker dashboard reports GPU memory utilization of 98% and GPU utilization of between 95% and 100%." }, { "code": null, "e": 26999, "s": 26770, "text": "The efficiency of the GPU utilization can also be seen from the trace_viewer of the tf profiler where we can see that the GPU is almost always active. Recall that the tf profile was configured to run for five steps, steps 20–24." }, { "code": null, "e": 27165, "s": 26999, "text": "For the sake of comparison, we will also note that the Instance Metrics reports network-in of 14.9 GBytes per minute, and network-out of under 100 MBytes per minute." }, { "code": null, "e": 27679, "s": 27165, "text": "To evaluate the impact of the batch size on the performance, we reduce the batch size to 2, leaving all other model properties unchanged. The throughput drops all the way down to 40 samples per second. The effect on GPU utilization and GPU memory utilization is immediately noticeable from the “instance metrics” where we see a significant drop, down to around 60% and 23%, respectively. Naturally, each iteration takes a lot less time, but the percentage of the time during which the GPU is active is much lower." }, { "code": null, "e": 27811, "s": 27679, "text": "The tf profiler step time graph shows that the small batch size leads to over half the time being spent loading kernels to the GPU." }, { "code": null, "e": 27971, "s": 27811, "text": "The trace_viewer shows that while the GPU remains unblocked by the input, the tf ops appear to be sparsely scattered across the computation block of each step." }, { "code": null, "e": 28177, "s": 27971, "text": "In TensorFlow 2.3, a new Memory profiler tool was introduced that allows you to identify underutilization of the GPU memory and get an indication of whether you can safely increase the training batch size." }, { "code": null, "e": 28471, "s": 28177, "text": "In this example, we will artificially introduce a network bottleneck on the network input. We will do this by dropping every 9 out of 10 input records so that we require 10 times as much input data on the network to maintain the same throughput. Here is the code used to perform this exercise:" }, { "code": null, "e": 29008, "s": 28471, "text": "# id generatordef id_gen(): e = 0 while True: yield e e += 1# enter id to feature dictdef add_id_label(f, i): f['id'] = i return f# create a dataset of indices and zip it with input datasetids = tf.data.Dataset.from_generator(id_gen, tf.int64)ds = tf.data.Dataset.zip((ds, ids))# enter id to feature dictds = ds.map(add_id_label, num_parallel_calls=tf.data.experimental.autotune)# filter out every 9 out of 10 recordsds = ds.filter(lambda f: tf.squeeze(tf.equal(tf.math.floormod(f['id'],10),0)))" }, { "code": null, "e": 29407, "s": 29008, "text": "From the instance metrics, we can see that the network-in caps out at 33.4 GBytes per minute, only a bit more than twice the volume of the normal run (14.9 GBytes) despite the fact that we need ten times as much data. Throughput drops to 22 samples per second. Unsurprisingly, our program is highly input bound. The tf profiler reports that, of the total step time, 77.8% is spent waiting for data." }, { "code": null, "e": 29549, "s": 29407, "text": "The trace_viewer clearly shows the GPU sitting idle for the majority of each step as it waits for data from the tf_data_iterator_get_next op." }, { "code": null, "e": 30222, "s": 29549, "text": "TensorFlow offers ways to maximize the parallelization of the data processing (as demonstrated in the TensorBoard Profiler Tutorials) but this does not absolve you from optimizing your input data processing pipeline. If your data processing is resource intensive, it may impact the performance of your model, and you might want to consider moving some of your processing offline. If the heavy operation is GPU friendly, (e.g. a large convolution), you can also consider performing the operation on the GPU using the experimental map_on_gpu function, (but keep in mind the overhead of the data transfer). Another option is to choose a training instance with more CPU cores." }, { "code": null, "e": 30367, "s": 30222, "text": "In this example, we will simulate an overloaded pre-processing pipeline, by applying a separable_conv2d with filter size 7x7 to the input frame." }, { "code": null, "e": 30627, "s": 30367, "text": "The throughput drops to just 25 samples per second, and the maximum GPU utilization to 36%. The CPU utilization, on the other hand, jumps from 66% to 96%. Once again, the program is highly input bound, and the trace-viewer shows large chunks of GPU idle time." }, { "code": null, "e": 30774, "s": 30627, "text": "Careful analysis of the CPU section of the trace-viewer, (not shown here), shows that separable convolution taking up large chunks of the compute." }, { "code": null, "e": 31084, "s": 30774, "text": "In this example, we artificially increase the input data being passed to the GPU by blowing up the size of the input frame by a factor of 10. On the CPU side we simply replicate the input frame 10 times (using tf.tile()). On the GPU we receive the enlarged input frame, but immediately discard the added data." }, { "code": null, "e": 31203, "s": 31084, "text": "The throughput in this case drops to 84 samples per second, and the bottleneck is clearly evident on the trace-viewer." }, { "code": null, "e": 31356, "s": 31203, "text": "Notice how, for each step, the size of the block of Stream #20(MemcpyH2D) has grown, and how the GPU compute remains idle until the block has completed." }, { "code": null, "e": 31882, "s": 31356, "text": "In this example, we simulate the impact of an inefficient graph, by applying an 11x11 convolution filter to the output of the model before calculating the loss function. Unsurprisingly, the throughput drops slightly, to 96 samples per second. The impact on the graph can be viewed on the tf profiler tensorflow stats page, where we see that the added operation becomes the most time-consuming operation in the GPU. This table gives us information on the heaviest operations, which we can use to improve the model performance." }, { "code": null, "e": 32145, "s": 31882, "text": "In this example, we add a callback function that simulates processing the segmentation masks that are output by the model, by creating and storing 64 random images after every iteration. The first thing we notice, is that TensorFlow prints the following warning:" }, { "code": null, "e": 32263, "s": 32145, "text": "WARNING:tensorflow:Method (on_train_batch_end) is slow compared to the batch update (0.814319). Check your callbacks." }, { "code": null, "e": 32548, "s": 32263, "text": "Additionally, the throughput drops to 43 samples per second, the GPU utilization drops to 46%, and tf profiler reports that the GPU is active for only 47% of each time step. The bottleneck is clearly seen on the trace-viewer where we see the GPU idle for the second half of each step." }, { "code": null, "e": 33094, "s": 32548, "text": "As we have shown, the ability to analyze and optimize the performance of your training sessions, can lead to meaningful savings in time and cost. The skills required to perform such analysis should exist in your DNN development team. The analysis should be an integral part of your team’s development methodology and incorporated into your DNN training life cycle. Your development plan should include details such as at when to run performance profiling, what tools to use, what type of tests to run, how invasive the tests should be, and more." } ]
Python program to Remove and print every third from list until it becomes empty?
First we create a list, the index of the starting address is 0 and the position of the first third element is 2 and need to traverse till the list becomes empty and another important work to do every time we have to find the index of the next third element and print the value and after that reduce the length of the list. A:[10,20,30,40] OUTPUT:30 20 40 10 The first third element is 30, then we count from 40 for next third element 20,then again start from 40 for the next third element is 40 itself and finally 10 is printed. Step 1: The index of the list starts from 0 and the first third element will be at position 2. variable p=2,starting index id=0. Step 2: find the length of the list. listlen=len (LST) // length of the list(LST) Step 3: Traverse till the list becomes empty and each time find the index of the next third element. While(listlen>0) Id=(p+id)%listlen A=LST.pop(id)// removes and prints the required element Listlen-=1 End while # To remove to every third element until list becomes empty def removenumber(no): # list starts with # 0 index p = 3 - 1 id = 0 lenoflist = (len(no)) # breaks out once the # list becomes empty while lenoflist > 0: id = (p + id) % lenoflist # removes and prints the required # element print(no.pop(id)) lenoflist -= 1 # Driver code A=list() n=int(input("Enter the size of the array ::")) print("Enter the INTEGER number") for i in range(int(n)): p=int(input("n=")) A.append(int(p)) print("After remove third element, The List is") removenumber(A) # call function Enter the size of the array ::9 Enter the number n=10 n=20 n=30 n=40 n=50 n=60 n=70 n=80 n=90 After remove third element, The List is 30 60 90 40 80 50 20 70 10
[ { "code": null, "e": 1385, "s": 1062, "text": "First we create a list, the index of the starting address is 0 and the position of the first third element is 2 and need to traverse till the list becomes empty and another important work to do every time we have to find the index of the next third element and print the value and after that reduce the length of the list." }, { "code": null, "e": 1421, "s": 1385, "text": "A:[10,20,30,40]\nOUTPUT:30 20 40 10\n" }, { "code": null, "e": 1592, "s": 1421, "text": "The first third element is 30, then we count from 40 for next third element 20,then again start from 40 for the next third element is 40 itself and finally 10 is printed." }, { "code": null, "e": 1687, "s": 1592, "text": "Step 1: The index of the list starts from 0 and the first third element will be at position 2." }, { "code": null, "e": 1722, "s": 1687, "text": "variable p=2,starting index id=0.\n" }, { "code": null, "e": 1759, "s": 1722, "text": "Step 2: find the length of the list." }, { "code": null, "e": 1805, "s": 1759, "text": "listlen=len (LST)\t// length of the list(LST)\n" }, { "code": null, "e": 1906, "s": 1805, "text": "Step 3: Traverse till the list becomes empty and each time find the index of the next third element." }, { "code": null, "e": 2030, "s": 1906, "text": "While(listlen>0)\n Id=(p+id)%listlen\n A=LST.pop(id)// removes and prints the required element\n Listlen-=1\nEnd while" }, { "code": null, "e": 2673, "s": 2030, "text": "# To remove to every third element until list becomes empty\ndef removenumber(no):\n # list starts with\n # 0 index\n p = 3 - 1\n id = 0\n lenoflist = (len(no))\n\n # breaks out once the\n # list becomes empty\n while lenoflist > 0: \n id = (p + id) % lenoflist\n\n # removes and prints the required\n # element\n print(no.pop(id)) \n lenoflist -= 1\n\n# Driver code\nA=list() \nn=int(input(\"Enter the size of the array ::\"))\nprint(\"Enter the INTEGER number\")\nfor i in range(int(n)):\n p=int(input(\"n=\"))\n A.append(int(p))\nprint(\"After remove third element, The List is\")\nremovenumber(A) # call function" }, { "code": null, "e": 2835, "s": 2673, "text": "Enter the size of the array ::9\nEnter the number\nn=10\nn=20\nn=30\nn=40\nn=50\nn=60\nn=70\nn=80\nn=90\nAfter remove third element, The List is\n30\n60\n90\n40\n80\n50\n20\n70\n10\n" } ]
Speech to Text using AWS Transcribe, S3 and Lambda | by Janitha Tennakoon | Towards Data Science
Speech to text is the process of converting audio to text. For computer software and programs, audio files are near impossible to be used for visualization/analysis or to harvest data out of it in a meaningful way. Therefore there is the need of converting these audio files to text before they can be used for analysis and harvest data. Although speech to text seems very simple in the current technology world it involves many linguistic models and algorithms to provide a near 100% accuracy. Currently, there are many tools created by software providers who have created their own models and algorithms to provide this speech-to-text as a service. In this article, I am going to go through one such kind of service provided by AWS for speech to text named AWS Transcribe. AWS Transcribe is the speech-to-text solution provided by Amazon Web Services which has renowned to be very quick and have high accuracy.AWS Transcribe under the hood uses a deep learning process names ASR (automatic speech recognition) to convert the audio to text quickly and more accurately. It also has a separate service inside named Amazon Transcribe Medical to be used for medical documentation applications as well. AWS Transcribe has a well-created API where programs can automate transcribe jobs of converting audio files to text files. But once you start a transcribing job since it may take time depending on the file, AWS Transcribe will not send the output in the same request as a response. Since that we need to either poll continuously to check whether the transcribe job is completed or we are going to need to have some kind of event triggers to identify the status of the job. In this article, we are going to explore two kinds of such event triggers that will make it be possible to automate transcribe from start to end. Below is a brief overview of what we are going to accomplish in this article. Create two S3 buckets as input bucket and output bucket for AWS Transcribe. Create a Lambda function using python to trigger AWS Transcribe whenever a new file is uploaded to the input S3 bucket. Send an email with the transcription job details when the transcription is completed using S3 events. Send an email with the transcription job details when the transcription is completed using CloudWatch events. Scenario One — Send email using S3 Events Scenario Two — Send email using CloudWatch Events Above is the overall architecture of what we are trying to achieve in this article. We can either choose scenario one or two to receive email notifications. Now without any more explanations let’s dive into the implementation. Following services will be created in AWS in the following order. IAM role for Lambda to trigger Transcribe Lambda function Input and output S3 buckets SNS topic Since our Lambda function is going to trigger AWS Transcribe on behalf of our self we need to give permission to the Lambda function to call Transcribe service. For that let’s create a new IAM role that will be used by our Lambda function. Go to IAM Dashboard, select Create a role, and as AWS Service, select Lambda. Next from the policies select below two policies for our IAM role. CloudWatchLogsFullAccess AmazonTranscribeFullAccess Next, provide a role name and create the new role. Next, let’s create the Lambda function which will trigger the AWS Transcribe when we upload a new file to our input S3 bucket(which we will create in the next step). Go to Lambda dashboard and Create function. Select Python as the Runtime and on the Execution role select the role we created above. Copy the code given below to the lambda function. Code explanation is given below. The following steps will be followed when the Lambda function is triggered. The function will be triggered by an S3 event. So first we will extract the details of the S3 bucket and the file that triggered the event. Next, we will create a job name that is required by Transcribe API. In order to be unique, we attach UUID to the end of the file name. Next, we are calling start_transcription_job with the required parameters. Here for OutputBucketName, we need to specify the output S3 bucket which we are going to create next. So for now you can remove that field completely. Next, let’s start to create our S3 buckets. We are going to create two buckets, first, let’s create our input bucket where our audio files will be uploaded. After creating the S3 bucket go to properties and Event Notifications. Here is where we configure the S3 event to trigger the Lambda function we created whenever a new object is added to this bucket. Click on Create event notification and then provide a name. On Event types select All object create events. This will make sure to create an event when either a new object is uploaded, a rename happened on an existing object or a new object is copied directly to the bucket. For the Destination select the Lambda function we created. Now this will make sure that whenever a new file is created in this bucket our Lambda function will be triggered which will trigger AWS Transcribe. Now let’s start creating our output S3 bucket where the results from our AWS Transcribe will be available. Here we need to provide write access to our lambda function so it can write the output result on this bucket. First, create a new S3 bucket. Then first we need to create a new policy specifying write access to this S3 bucket. Go to the IAM dashboard and navigate to Policies. Then click on Create Policy and select JSON and add the following Policy. { "Version": "2012-10-17", "Statement": [ { "Action": [ "s3:PutObject" ], "Resource": [ "arn:aws:s3:::transcribe-output-tutorial/*" ], "Effect": "Allow" }, { "Action": [ "s3:ListBucket" ], "Resource": [ "arn:aws:s3:::transcribe-output-tutorial" ], "Effect": "Allow" } ]} Next in order to grant our created role for Lambda for write to S3 bucket. For this go back again to Lambda role we created earlier and attach this newly created policy to it. As the last step make sure to edit the Lambda function we created with the OutputBucketName as the new S3 bucket name we created now. The name should be only the bucket name without any prefixes. (ex:- transcribe-output) Now we configured all the components we need without the output notification emails. Let’s first try to test the configurations to check our system is so far working. Go to the input S3 bucket and upload an mp4 file to our input bucket. If everything goes without an issue if you go to Transcribe dashboard and under Transcription Jobs you should see a new job triggered by our Lambda function. After a couple of minutes, the status will be changed to completed and we will see the output. Check in the output S3 bucket as well for the output text object. If everything is working let’s move to the next step. Let’s move on to triggering an email notification once the Transcribe job is completed. We are going to cover two ways we can achieve this, using S3 events and CloudWatch events. But for both, we need to have an SNS topic created first. Go to the SNS dashboard and create a Topic. As the type select Standard. Next, if we are going to use S3 events we need to give permission to the S3 bucket to access this topic. In order to do that under AccessPolicy add the following lines at the end of the policy. { "Sid": "s3", "Effect": "Allow", "Principal": { "Service": "s3.amazonaws.com" }, "Action": "SNS:Publish", "Resource": "{YOUR_SNS_TOPIC_ARN}" } Now we can finish creating the topic. Next, we need to create a Subscrption to this topic which will be using the protocol email. Click on Create Subscription and select protocol as Email. Make sure to confirm the subscription by your email after you entered your email. Now that our SNS topic is created let’s move and try to implement scenario one, which is to trigger sending an email using S3 events. The main idea is to trigger our SNS topic whenever there is a new file uploaded by the AWS Transcribe Service to our output S3 bucket. To do that first go to our output S3 bucket. Go to properties and Create even notifications as we did for our input bucket. The event type will be the same as for the input bucket while this time the destination will be an SNS topic. Now when AWS Transcribe outputs the output result to our bucket we will automatically receive an email. You can try this out by renaming the object currently on our input bucket. Now after the transcribe is completed and it is uploaded to our output S3 bucket you will receive an email. Scenario two is to trigger the email using CloudWatch events. When a transcription job starts AWS Transcribe starts to send events to the CloudWatch. So the concept here is to create a trigger using these CloudWatch events whenever the transcription is completed. First let’s o to AWS CloudWatch, Events, and rules. Click on create a rule. Here we need to define a rule saying that we need to have a trigger when our transcription job either goes into a COMPLETED state or a FAILED state. { "source": [ "aws.transcribe" ], "detail-type": [ "Transcribe Job State Change" ], "detail": { "TranscriptionJobStatus": [ "COMPLETED", "FAILED" ] }} As Targets add our SNS topic. Next, create the rule by giving a name. Now try to rename or add a new object to our input S3 bucket and at the end, we will receive an email notifying the status of the Transcribe job. (If you already added an S3 event to the same topic make sure to remove it or it will trigger two emails.) That is all for this article. There are many other ways we can trigger an event after AWS Transcribe completes a job. But I will let you find those solutions for yourself. If you want to know more about AWS Transcribe below is the documentation. Thank you for reading this article and happy coding 😁😁😁
[ { "code": null, "e": 667, "s": 172, "text": "Speech to text is the process of converting audio to text. For computer software and programs, audio files are near impossible to be used for visualization/analysis or to harvest data out of it in a meaningful way. Therefore there is the need of converting these audio files to text before they can be used for analysis and harvest data. Although speech to text seems very simple in the current technology world it involves many linguistic models and algorithms to provide a near 100% accuracy." }, { "code": null, "e": 947, "s": 667, "text": "Currently, there are many tools created by software providers who have created their own models and algorithms to provide this speech-to-text as a service. In this article, I am going to go through one such kind of service provided by AWS for speech to text named AWS Transcribe." }, { "code": null, "e": 1371, "s": 947, "text": "AWS Transcribe is the speech-to-text solution provided by Amazon Web Services which has renowned to be very quick and have high accuracy.AWS Transcribe under the hood uses a deep learning process names ASR (automatic speech recognition) to convert the audio to text quickly and more accurately. It also has a separate service inside named Amazon Transcribe Medical to be used for medical documentation applications as well." }, { "code": null, "e": 2068, "s": 1371, "text": "AWS Transcribe has a well-created API where programs can automate transcribe jobs of converting audio files to text files. But once you start a transcribing job since it may take time depending on the file, AWS Transcribe will not send the output in the same request as a response. Since that we need to either poll continuously to check whether the transcribe job is completed or we are going to need to have some kind of event triggers to identify the status of the job. In this article, we are going to explore two kinds of such event triggers that will make it be possible to automate transcribe from start to end. Below is a brief overview of what we are going to accomplish in this article." }, { "code": null, "e": 2144, "s": 2068, "text": "Create two S3 buckets as input bucket and output bucket for AWS Transcribe." }, { "code": null, "e": 2264, "s": 2144, "text": "Create a Lambda function using python to trigger AWS Transcribe whenever a new file is uploaded to the input S3 bucket." }, { "code": null, "e": 2366, "s": 2264, "text": "Send an email with the transcription job details when the transcription is completed using S3 events." }, { "code": null, "e": 2476, "s": 2366, "text": "Send an email with the transcription job details when the transcription is completed using CloudWatch events." }, { "code": null, "e": 2518, "s": 2476, "text": "Scenario One — Send email using S3 Events" }, { "code": null, "e": 2568, "s": 2518, "text": "Scenario Two — Send email using CloudWatch Events" }, { "code": null, "e": 2861, "s": 2568, "text": "Above is the overall architecture of what we are trying to achieve in this article. We can either choose scenario one or two to receive email notifications. Now without any more explanations let’s dive into the implementation. Following services will be created in AWS in the following order." }, { "code": null, "e": 2903, "s": 2861, "text": "IAM role for Lambda to trigger Transcribe" }, { "code": null, "e": 2919, "s": 2903, "text": "Lambda function" }, { "code": null, "e": 2947, "s": 2919, "text": "Input and output S3 buckets" }, { "code": null, "e": 2957, "s": 2947, "text": "SNS topic" }, { "code": null, "e": 3197, "s": 2957, "text": "Since our Lambda function is going to trigger AWS Transcribe on behalf of our self we need to give permission to the Lambda function to call Transcribe service. For that let’s create a new IAM role that will be used by our Lambda function." }, { "code": null, "e": 3275, "s": 3197, "text": "Go to IAM Dashboard, select Create a role, and as AWS Service, select Lambda." }, { "code": null, "e": 3342, "s": 3275, "text": "Next from the policies select below two policies for our IAM role." }, { "code": null, "e": 3367, "s": 3342, "text": "CloudWatchLogsFullAccess" }, { "code": null, "e": 3394, "s": 3367, "text": "AmazonTranscribeFullAccess" }, { "code": null, "e": 3445, "s": 3394, "text": "Next, provide a role name and create the new role." }, { "code": null, "e": 3611, "s": 3445, "text": "Next, let’s create the Lambda function which will trigger the AWS Transcribe when we upload a new file to our input S3 bucket(which we will create in the next step)." }, { "code": null, "e": 3744, "s": 3611, "text": "Go to Lambda dashboard and Create function. Select Python as the Runtime and on the Execution role select the role we created above." }, { "code": null, "e": 3827, "s": 3744, "text": "Copy the code given below to the lambda function. Code explanation is given below." }, { "code": null, "e": 3903, "s": 3827, "text": "The following steps will be followed when the Lambda function is triggered." }, { "code": null, "e": 4043, "s": 3903, "text": "The function will be triggered by an S3 event. So first we will extract the details of the S3 bucket and the file that triggered the event." }, { "code": null, "e": 4178, "s": 4043, "text": "Next, we will create a job name that is required by Transcribe API. In order to be unique, we attach UUID to the end of the file name." }, { "code": null, "e": 4404, "s": 4178, "text": "Next, we are calling start_transcription_job with the required parameters. Here for OutputBucketName, we need to specify the output S3 bucket which we are going to create next. So for now you can remove that field completely." }, { "code": null, "e": 4561, "s": 4404, "text": "Next, let’s start to create our S3 buckets. We are going to create two buckets, first, let’s create our input bucket where our audio files will be uploaded." }, { "code": null, "e": 4761, "s": 4561, "text": "After creating the S3 bucket go to properties and Event Notifications. Here is where we configure the S3 event to trigger the Lambda function we created whenever a new object is added to this bucket." }, { "code": null, "e": 5036, "s": 4761, "text": "Click on Create event notification and then provide a name. On Event types select All object create events. This will make sure to create an event when either a new object is uploaded, a rename happened on an existing object or a new object is copied directly to the bucket." }, { "code": null, "e": 5243, "s": 5036, "text": "For the Destination select the Lambda function we created. Now this will make sure that whenever a new file is created in this bucket our Lambda function will be triggered which will trigger AWS Transcribe." }, { "code": null, "e": 5491, "s": 5243, "text": "Now let’s start creating our output S3 bucket where the results from our AWS Transcribe will be available. Here we need to provide write access to our lambda function so it can write the output result on this bucket. First, create a new S3 bucket." }, { "code": null, "e": 5700, "s": 5491, "text": "Then first we need to create a new policy specifying write access to this S3 bucket. Go to the IAM dashboard and navigate to Policies. Then click on Create Policy and select JSON and add the following Policy." }, { "code": null, "e": 6178, "s": 5700, "text": "{ \"Version\": \"2012-10-17\", \"Statement\": [ { \"Action\": [ \"s3:PutObject\" ], \"Resource\": [ \"arn:aws:s3:::transcribe-output-tutorial/*\" ], \"Effect\": \"Allow\" }, { \"Action\": [ \"s3:ListBucket\" ], \"Resource\": [ \"arn:aws:s3:::transcribe-output-tutorial\" ], \"Effect\": \"Allow\" } ]}" }, { "code": null, "e": 6354, "s": 6178, "text": "Next in order to grant our created role for Lambda for write to S3 bucket. For this go back again to Lambda role we created earlier and attach this newly created policy to it." }, { "code": null, "e": 6575, "s": 6354, "text": "As the last step make sure to edit the Lambda function we created with the OutputBucketName as the new S3 bucket name we created now. The name should be only the bucket name without any prefixes. (ex:- transcribe-output)" }, { "code": null, "e": 6970, "s": 6575, "text": "Now we configured all the components we need without the output notification emails. Let’s first try to test the configurations to check our system is so far working. Go to the input S3 bucket and upload an mp4 file to our input bucket. If everything goes without an issue if you go to Transcribe dashboard and under Transcription Jobs you should see a new job triggered by our Lambda function." }, { "code": null, "e": 7185, "s": 6970, "text": "After a couple of minutes, the status will be changed to completed and we will see the output. Check in the output S3 bucket as well for the output text object. If everything is working let’s move to the next step." }, { "code": null, "e": 7422, "s": 7185, "text": "Let’s move on to triggering an email notification once the Transcribe job is completed. We are going to cover two ways we can achieve this, using S3 events and CloudWatch events. But for both, we need to have an SNS topic created first." }, { "code": null, "e": 7495, "s": 7422, "text": "Go to the SNS dashboard and create a Topic. As the type select Standard." }, { "code": null, "e": 7689, "s": 7495, "text": "Next, if we are going to use S3 events we need to give permission to the S3 bucket to access this topic. In order to do that under AccessPolicy add the following lines at the end of the policy." }, { "code": null, "e": 7873, "s": 7689, "text": "{ \"Sid\": \"s3\", \"Effect\": \"Allow\", \"Principal\": { \"Service\": \"s3.amazonaws.com\" }, \"Action\": \"SNS:Publish\", \"Resource\": \"{YOUR_SNS_TOPIC_ARN}\" }" }, { "code": null, "e": 8003, "s": 7873, "text": "Now we can finish creating the topic. Next, we need to create a Subscrption to this topic which will be using the protocol email." }, { "code": null, "e": 8062, "s": 8003, "text": "Click on Create Subscription and select protocol as Email." }, { "code": null, "e": 8144, "s": 8062, "text": "Make sure to confirm the subscription by your email after you entered your email." }, { "code": null, "e": 8278, "s": 8144, "text": "Now that our SNS topic is created let’s move and try to implement scenario one, which is to trigger sending an email using S3 events." }, { "code": null, "e": 8537, "s": 8278, "text": "The main idea is to trigger our SNS topic whenever there is a new file uploaded by the AWS Transcribe Service to our output S3 bucket. To do that first go to our output S3 bucket. Go to properties and Create even notifications as we did for our input bucket." }, { "code": null, "e": 8647, "s": 8537, "text": "The event type will be the same as for the input bucket while this time the destination will be an SNS topic." }, { "code": null, "e": 8934, "s": 8647, "text": "Now when AWS Transcribe outputs the output result to our bucket we will automatically receive an email. You can try this out by renaming the object currently on our input bucket. Now after the transcribe is completed and it is uploaded to our output S3 bucket you will receive an email." }, { "code": null, "e": 9250, "s": 8934, "text": "Scenario two is to trigger the email using CloudWatch events. When a transcription job starts AWS Transcribe starts to send events to the CloudWatch. So the concept here is to create a trigger using these CloudWatch events whenever the transcription is completed. First let’s o to AWS CloudWatch, Events, and rules." }, { "code": null, "e": 9423, "s": 9250, "text": "Click on create a rule. Here we need to define a rule saying that we need to have a trigger when our transcription job either goes into a COMPLETED state or a FAILED state." }, { "code": null, "e": 9602, "s": 9423, "text": "{ \"source\": [ \"aws.transcribe\" ], \"detail-type\": [ \"Transcribe Job State Change\" ], \"detail\": { \"TranscriptionJobStatus\": [ \"COMPLETED\", \"FAILED\" ] }}" }, { "code": null, "e": 9672, "s": 9602, "text": "As Targets add our SNS topic. Next, create the rule by giving a name." }, { "code": null, "e": 9925, "s": 9672, "text": "Now try to rename or add a new object to our input S3 bucket and at the end, we will receive an email notifying the status of the Transcribe job. (If you already added an S3 event to the same topic make sure to remove it or it will trigger two emails.)" } ]
Run Python Code on Websites: Exploring Brython | by Kaustubh Gupta | Towards Data Science
Being a follower of Python for a long time, I never stop exploring this language to one level and kept searching for its implementation every day. One fine day I got to know about Brython, which aims to replace Javascript for web scripting. It allows you to directly use Python Scripts on a webpage to handle DOM (Document Object Model) elements and events, all using our favorite language Python. Let’s dive into how to implement such kind of script for your next project and how I won a competition (2nd position) using this technology! Before that, if you want to explore the android side of Python then make sure to check out my Android App in Python Series on Medium. towardsdatascience.com Javascript is considered as the language of the web which enables interactivity on the webpage. Nobody wants to surf static pages that can be built using HTML and a bit of CSS. Brython offers an intuitive way to interact with web page elements using Python. In the past also, python finds its usage in backend scripting using Django/Flask allowing users to build scalable websites with rapid development. While Bython focuses on applying this on the client-side too. To start with Brython, you have two options: You download the Brython package locally and then include it in your file. This can be done using pip: pip install brython then in an empty folder, brython-cli --install or, Directly use Brython CDN which gets updated as soon as a new update is released that frees you from manual updating the packages. <script src="https://cdn.jsdelivr.net/npm/brython@3.8.10/brython.min.js"> </script> <script src="https://cdn.jsdelivr.net/npm/brython@3.8.10/brython_stdlib.js"> </script> Let’s brush up on some basics to start developing some cool projects. Note that this requires you to have a basic understanding of DOM and familiarity with basic Javascript would be a plus point though not necessary. In your IDE, populate a basic HTML code, place an input field, and a span tag with an id. Also, add the Brython CDN using the script tag. It should probably look like this: Now bind this input event to the span tag using your Python script. To do this, we will use the document from the browser. Any type of script will be encapsulated in a script tag with the type of text/python and this can be defined under the body tag too. One more change that needs to be done is to include onload=”brython()” in the body tag (<body onload=”brython()”>) This is the script which will enable us to display text in realtime: Here, we have used a document object from the browser module to bind the id of the input (text) to the function show_text(). This function assigns the value of the input tag to the span tag using their ids. Here is a GIF to show what this HTML page does on loading the browser: Let’s look at another example to see how to make API calls using Brython which is the most exciting part about this. Consider a scenario where you want to host a machine learning web-based project. You created a model and now serving it as an API on any cloud platform such as Heroku, GCP, or AWS. Being a python developer, you may not be that much fluent with web development and find it difficult to handle the late responses or slow loading of your website. You can easily host your website using GitHub pages but it doesn't support flask or Django frameworks (for now). To handle such situations, you can easily create a basic HTML webpage (or take help from bootstrap with a bit of CSS) which asks the user to enter the required parameters, and then your Brython script makes the request to your model hosting and you display the results on the webpage. This will benefit in the way that the website will be hosted on GitHub making it easier to manage the codebase plus it will be up all the time. Let’s see the script to make an API call that returns a random joke: First, see the output of this file: Here the get joke button is bind to the API call function which makes AJAX calls to the server, returns the result, and then rendered to the display tag. I was given the problem statement to fetch music lyrics from the given API ad display them on the web. It takes the music artist author and the title/song name for which we want lyrics. Here is the GIF for the same: If you want to explore the source code of this, then here is the GitHub repository link. We saw how to implement python based scripts directly into the webpage using Brython. There is no doubt in the fact that currently Javascript can’t be replaced in terms of speed, usability, maintainability of code, and understanding. These python scripts require familiarity with DOM which can be well-practiced and understood more with more clarity with JS only. This is best suited for someone who is looking to showcase their python skills on the web for both back-end and front-end. Many people have built games, graphics using Pygame and turtle library. You can explore more about this over Google. That’s it from my side, follow me on medium to receive notifications about more interesting articles like these. With that said, Namaste!
[ { "code": null, "e": 711, "s": 172, "text": "Being a follower of Python for a long time, I never stop exploring this language to one level and kept searching for its implementation every day. One fine day I got to know about Brython, which aims to replace Javascript for web scripting. It allows you to directly use Python Scripts on a webpage to handle DOM (Document Object Model) elements and events, all using our favorite language Python. Let’s dive into how to implement such kind of script for your next project and how I won a competition (2nd position) using this technology!" }, { "code": null, "e": 845, "s": 711, "text": "Before that, if you want to explore the android side of Python then make sure to check out my Android App in Python Series on Medium." }, { "code": null, "e": 868, "s": 845, "text": "towardsdatascience.com" }, { "code": null, "e": 1380, "s": 868, "text": "Javascript is considered as the language of the web which enables interactivity on the webpage. Nobody wants to surf static pages that can be built using HTML and a bit of CSS. Brython offers an intuitive way to interact with web page elements using Python. In the past also, python finds its usage in backend scripting using Django/Flask allowing users to build scalable websites with rapid development. While Bython focuses on applying this on the client-side too. To start with Brython, you have two options:" }, { "code": null, "e": 1483, "s": 1380, "text": "You download the Brython package locally and then include it in your file. This can be done using pip:" }, { "code": null, "e": 1503, "s": 1483, "text": "pip install brython" }, { "code": null, "e": 1528, "s": 1503, "text": "then in an empty folder," }, { "code": null, "e": 1550, "s": 1528, "text": "brython-cli --install" }, { "code": null, "e": 1554, "s": 1550, "text": "or," }, { "code": null, "e": 1684, "s": 1554, "text": "Directly use Brython CDN which gets updated as soon as a new update is released that frees you from manual updating the packages." }, { "code": null, "e": 1855, "s": 1684, "text": "<script src=\"https://cdn.jsdelivr.net/npm/brython@3.8.10/brython.min.js\"> </script> <script src=\"https://cdn.jsdelivr.net/npm/brython@3.8.10/brython_stdlib.js\"> </script>" }, { "code": null, "e": 2245, "s": 1855, "text": "Let’s brush up on some basics to start developing some cool projects. Note that this requires you to have a basic understanding of DOM and familiarity with basic Javascript would be a plus point though not necessary. In your IDE, populate a basic HTML code, place an input field, and a span tag with an id. Also, add the Brython CDN using the script tag. It should probably look like this:" }, { "code": null, "e": 2685, "s": 2245, "text": "Now bind this input event to the span tag using your Python script. To do this, we will use the document from the browser. Any type of script will be encapsulated in a script tag with the type of text/python and this can be defined under the body tag too. One more change that needs to be done is to include onload=”brython()” in the body tag (<body onload=”brython()”>) This is the script which will enable us to display text in realtime:" }, { "code": null, "e": 2963, "s": 2685, "text": "Here, we have used a document object from the browser module to bind the id of the input (text) to the function show_text(). This function assigns the value of the input tag to the span tag using their ids. Here is a GIF to show what this HTML page does on loading the browser:" }, { "code": null, "e": 3537, "s": 2963, "text": "Let’s look at another example to see how to make API calls using Brython which is the most exciting part about this. Consider a scenario where you want to host a machine learning web-based project. You created a model and now serving it as an API on any cloud platform such as Heroku, GCP, or AWS. Being a python developer, you may not be that much fluent with web development and find it difficult to handle the late responses or slow loading of your website. You can easily host your website using GitHub pages but it doesn't support flask or Django frameworks (for now)." }, { "code": null, "e": 4035, "s": 3537, "text": "To handle such situations, you can easily create a basic HTML webpage (or take help from bootstrap with a bit of CSS) which asks the user to enter the required parameters, and then your Brython script makes the request to your model hosting and you display the results on the webpage. This will benefit in the way that the website will be hosted on GitHub making it easier to manage the codebase plus it will be up all the time. Let’s see the script to make an API call that returns a random joke:" }, { "code": null, "e": 4071, "s": 4035, "text": "First, see the output of this file:" }, { "code": null, "e": 4225, "s": 4071, "text": "Here the get joke button is bind to the API call function which makes AJAX calls to the server, returns the result, and then rendered to the display tag." }, { "code": null, "e": 4441, "s": 4225, "text": "I was given the problem statement to fetch music lyrics from the given API ad display them on the web. It takes the music artist author and the title/song name for which we want lyrics. Here is the GIF for the same:" }, { "code": null, "e": 4530, "s": 4441, "text": "If you want to explore the source code of this, then here is the GitHub repository link." }, { "code": null, "e": 5134, "s": 4530, "text": "We saw how to implement python based scripts directly into the webpage using Brython. There is no doubt in the fact that currently Javascript can’t be replaced in terms of speed, usability, maintainability of code, and understanding. These python scripts require familiarity with DOM which can be well-practiced and understood more with more clarity with JS only. This is best suited for someone who is looking to showcase their python skills on the web for both back-end and front-end. Many people have built games, graphics using Pygame and turtle library. You can explore more about this over Google." } ]
Java - compareTo() Method
The method compares the Number object that invoked the method to the argument. It is possible to compare Byte, Long, Integer, etc. However, two different types cannot be compared, both the argument and the Number object invoking the method should be of the same type. public int compareTo( NumberSubClass referenceName ) Here is the detail of parameters − referenceName − This could be a Byte, Double, Integer, Float, Long, or Short. referenceName − This could be a Byte, Double, Integer, Float, Long, or Short. If the Integer is greater than the argument then 1 is returned. If the Integer is equal to the argument then 0 is returned. If the Integer is less than the argument then -1 is returned. public class Test { public static void main(String args[]) { Integer x = 5; //Integer value is greater than the argument (5>3) so, output is 1 System.out.println(x.compareTo(3)); //Integer value is equal to the argument so, output is 0 System.out.println(x.compareTo(5)); //Integer value is less than the argument (5<8) so, output is −1 System.out.println(x.compareTo(8)); } } This will produce the following result − 1 0 -1 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2508, "s": 2377, "text": "The method compares the Number object that invoked the method to the argument. It is possible to compare Byte, Long, Integer, etc." }, { "code": null, "e": 2645, "s": 2508, "text": "However, two different types cannot be compared, both the argument and the Number object invoking the method should be of the same type." }, { "code": null, "e": 2699, "s": 2645, "text": "public int compareTo( NumberSubClass referenceName )\n" }, { "code": null, "e": 2734, "s": 2699, "text": "Here is the detail of parameters −" }, { "code": null, "e": 2812, "s": 2734, "text": "referenceName − This could be a Byte, Double, Integer, Float, Long, or Short." }, { "code": null, "e": 2890, "s": 2812, "text": "referenceName − This could be a Byte, Double, Integer, Float, Long, or Short." }, { "code": null, "e": 2954, "s": 2890, "text": "If the Integer is greater than the argument then 1 is returned." }, { "code": null, "e": 3014, "s": 2954, "text": "If the Integer is equal to the argument then 0 is returned." }, { "code": null, "e": 3076, "s": 3014, "text": "If the Integer is less than the argument then -1 is returned." }, { "code": null, "e": 3513, "s": 3076, "text": "public class Test {\n public static void main(String args[]) {\n Integer x = 5;\n //Integer value is greater than the argument (5>3) so, output is 1\n System.out.println(x.compareTo(3));\n //Integer value is equal to the argument so, output is 0\n System.out.println(x.compareTo(5));\n //Integer value is less than the argument (5<8) so, output is −1\n System.out.println(x.compareTo(8)); \n }\n}" }, { "code": null, "e": 3554, "s": 3513, "text": "This will produce the following result −" }, { "code": null, "e": 3562, "s": 3554, "text": "1\n0\n-1\n" }, { "code": null, "e": 3595, "s": 3562, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 3611, "s": 3595, "text": " Malhar Lathkar" }, { "code": null, "e": 3644, "s": 3611, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 3660, "s": 3644, "text": " Malhar Lathkar" }, { "code": null, "e": 3695, "s": 3660, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3709, "s": 3695, "text": " Anadi Sharma" }, { "code": null, "e": 3743, "s": 3709, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 3757, "s": 3743, "text": " Tushar Kale" }, { "code": null, "e": 3794, "s": 3757, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3809, "s": 3794, "text": " Monica Mittal" }, { "code": null, "e": 3842, "s": 3809, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 3861, "s": 3842, "text": " Arnab Chakraborty" }, { "code": null, "e": 3868, "s": 3861, "text": " Print" }, { "code": null, "e": 3879, "s": 3868, "text": " Add Notes" } ]
What is the syntax to define enums in javascript?
Enums are not supported in JavaScript natively. We can however create Enums using Object.freeze by creating objects containing all the enumerable properties and then freezing the object so that no new enum can be added to it. const Color = { RED: 1, BLUE: 2, GREEN: 3, YELLOW: 4 }; Object.freeze(Color); // Example usage: let carColor = Color.BLUE; // Trying to add new colors fails silently: Color.WHITE = 5; console.log(Color) { RED: 1, BLUE: 2, GREEN: 3, YELLOW: 4 }
[ { "code": null, "e": 1288, "s": 1062, "text": "Enums are not supported in JavaScript natively. We can however create Enums using Object.freeze by creating objects containing all the enumerable properties and then freezing the object so that no new enum can be added to it." }, { "code": null, "e": 1503, "s": 1288, "text": "const Color = {\n RED: 1,\n BLUE: 2,\n GREEN: 3,\n YELLOW: 4\n};\nObject.freeze(Color);\n// Example usage:\nlet carColor = Color.BLUE;\n// Trying to add new colors fails silently:\nColor.WHITE = 5;\nconsole.log(Color)" }, { "code": null, "e": 1544, "s": 1503, "text": "{ RED: 1, BLUE: 2, GREEN: 3, YELLOW: 4 }" } ]
Priority Queue | Set 1 (Introduction) - GeeksforGeeks
25 Jan, 2022 Priority Queue is an abstract data type, which is similar to a queue, however, in the priority queue, every element has some priority. The priority of the elements in a priority queue determines the order in which elements are removed from the priority queue. Therefore all the elements are either arranged in an ascending or descending order. So, a priority Queue is an extension of the queue with the following properties. Every item has a priority associated with it. An element with high priority is dequeued before an element with low priority. If two elements have the same priority, they are served according to their order in the queue. In the below priority queue, an element with a maximum ASCII value will have the highest priority. The elements with higher priority are served first. A typical priority queue supports the following operations:1) Insertion: When a new element is inserted in a priority queue, it moves to the empty slot from top to bottom and left to right. However, if the element is not in the correct place then it will be compared with the parent node. If the element is not in the correct order, the elements are swapped. The swapping process continues until all the elements are placed in the correct position. 2) Deletion: As you know that in a max heap, the maximum element is the root node. And it will remove the element which has maximum priority first. Thus, you remove the root node from the queue. This removal creates an empty slot, which will be further filled with new insertion. Then, it compares the newly inserted element with all the elements inside the queue to maintain the heap invariant. 3) Peek: This operation helps to return the maximum element from Max Heap or minimum element from Min Heap without deleting the node from the priority queue. 1) Ascending Order: As the name suggests, in ascending order priority queue, the element with a lower priority value is given a higher priority in the priority list. For example, if we have the following elements in a priority queue arranged in ascending order like 4,6,8,9,10. Here, 4 is the smallest number, therefore, it will get the highest priority in a priority queue. 2) Descending order: The root node is the maximum element in a max heap, as you may know. It will also remove the element with the highest priority first. As a result, the root node is removed from the queue. This deletion leaves an empty space, which will be filled with fresh insertions in the future. The heap invariant is then maintained by comparing the newly inserted element to all other entries in the queue. Priority queue can be implemented using the following data structures: Arrays Linked list Heap data structure Binary search tree Let’s discuss all these in detail.1) Using Array: A simple implementation is to use an array of the following structure. struct item { int item; int priority; } enqueue(): This function is used to insert new data into the queue. dequeue(): This function removes the element with the highest priority from the queue. peek()/top(): This function is used to get the highest priority element in the queue without removing it from the queue. Arrays enqueue() dequeue() peek() Time Complexity O(1) O(n) O(n) C++ // C++ program to implement Priority Queue// using Arrays#include <bits/stdc++.h>using namespace std; // Structure for the elements in the// priority queuestruct item { int value; int priority;}; // Store the element of a priority queueitem pr[100000]; // Pointer to the last indexint size = -1; // Function to insert a new element// into priority queuevoid enqueue(int value, int priority){ // Increase the size size++; // Insert the element pr[size].value = value; pr[size].priority = priority;} // Function to check the top elementint peek(){ int highestPriority = INT_MIN; int ind = -1; // Check for the element with // highest priority for (int i = 0; i <= size; i++) { // If priority is same choose // the element with the // highest value if (highestPriority == pr[i].priority && ind > -1 && pr[ind].value < pr[i].value) { highestPriority = pr[i].priority; ind = i; } else if (highestPriority < pr[i].priority) { highestPriority = pr[i].priority; ind = i; } } // Return position of the element return ind;} // Function to remove the element with// the highest priorityvoid dequeue(){ // Find the position of the element // with highest priority int ind = peek(); // Shift the element one index before // from the position of the element // with highest priority is found for (int i = ind; i < size; i++) { pr[i] = pr[i + 1]; } // Decrease the size of the // priority queue by one size--;} // Driver Codeint main(){ // Function Call to insert elements // as per the priority enqueue(10, 2); enqueue(14, 4); enqueue(16, 4); enqueue(12, 3); // Stores the top element // at the moment int ind = peek(); cout << pr[ind].value << endl; // Dequeue the top element dequeue(); // Check the top element ind = peek(); cout << pr[ind].value << endl; // Dequeue the top element dequeue(); // Check the top element ind = peek(); cout << pr[ind].value << endl; return 0;} 16 14 12 Note: Read this article for more details. 2) Using Linked List: In a LinkedList implementation, the entries are sorted in descending order based on their priority. The highest priority element is always added to the front of the priority queue, which is formed using linked lists. The functions like push(), pop(), and peek() are used to implement priority queue using a linked list and are explained as follows: push(): This function is used to insert new data into the queue. pop(): This function removes the element with the highest priority from the queue. peek() / top(): This function is used to get the highest priority element in the queue without removing it from the queue. Linked List push() pop() peek() Time Complexity O(n) O(1) O(1) C++ // C++ code to implement Priority Queue// using Linked List#include <bits/stdc++.h>using namespace std; // Nodetypedef struct node { int data; // Lower values indicate // higher priority int priority; struct node* next; } Node; // Function to create a new nodeNode* newNode(int d, int p){ Node* temp = (Node*)malloc(sizeof(Node)); temp->data = d; temp->priority = p; temp->next = NULL; return temp;} // Return the value at headint peek(Node** head) { return (*head)->data; } // Removes the element with the// highest priority form the listvoid pop(Node** head){ Node* temp = *head; (*head) = (*head)->next; free(temp);} // Function to push according to priorityvoid push(Node** head, int d, int p){ Node* start = (*head); // Create new Node Node* temp = newNode(d, p); // Special Case: The head of list has // lesser priority than new node if ((*head)->priority > p) { // Insert New Node before head temp->next = *head; (*head) = temp; } else { // Traverse the list and find a // position to insert new node while (start->next != NULL && start->next->priority < p) { start = start->next; } // Either at the ends of the list // or at required position temp->next = start->next; start->next = temp; }} // Function to check is list is emptyint isEmpty(Node** head) { return (*head) == NULL; } // Driver codeint main(){ // Create a Priority Queue // 7->4->5->6 Node* pq = newNode(4, 1); push(&pq, 5, 2); push(&pq, 6, 3); push(&pq, 7, 0); while (!isEmpty(&pq)) { cout << " " << peek(&pq); pop(&pq); } return 0;} 7 4 5 6 Refer to this article for more details. Note: We can also use Linked List, time complexity of all operations with linked list remains same as array. The advantage with linked list is deleteHighestPriority() can be more efficient as we don’t have to move items. 3) Using Heaps: Binary Heap is generally preferred for priority queue implementation because heaps provide better performance compared to arrays or LinkedList. Operation on Binary Heap are as follows: insert(p): Inserts a new element with priority p. extractMax(): Extracts an element with maximum priority. remove(i): Removes an element pointed by an iterator i. getMax(): Returns an element with maximum priority. changePriority(i, p): Changes the priority of an element pointed by i to p. Binary Heap insert() remove() peek() Time Complexity O(log n) O(log n) O(1) Refer to this article for code implementation. 4) Using Binary Search Tree: A Self-Balancing Binary Search Tree like AVL Tree, Red-Black Tree, etc. can also be used to implement a priority queue. Operations like peek(), insert() and delete() can be performed using BST. What is the difference between Priority Queue and Normal Queue? There is no priority attached to elements in a queue, the rule of first-in-first-out(FIFO) is implemented whereas, in a priority queue, the elements have a priority. The elements with higher priority are served first. Applications of Priority Queue: CPU Scheduling Graph algorithms like Dijkstra’s shortest path algorithm, Prim’s Minimum Spanning Tree, etc. Stack Implementation All queue applications where priority is involved. Data compression in Huffman code See also: Recent articles on Priority Queue!Applications of Priority Queue.Priority Queue in C++.Priority Queue in Java.Priority Queue in Python.Priority Queue in JavaScript. Recent articles on Priority Queue! Applications of Priority Queue. Priority Queue in C++. Priority Queue in Java. Priority Queue in Python. Priority Queue in JavaScript. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. anshikajain26 as5853535 priority-queue Queue Queue priority-queue Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Level Order Binary Tree Traversal Queue Interface In Java Queue in Python Circular Queue | Set 1 (Introduction and Array Implementation) Sliding Window Maximum (Maximum of all subarrays of size k) Array implementation of queue (Simple) Difference between Stack and Queue Data Structures Priority Queue in Python Program for Page Replacement Algorithms | Set 2 (FIFO) Print Nodes in Top View of Binary Tree
[ { "code": null, "e": 39113, "s": 39085, "text": "\n25 Jan, 2022" }, { "code": null, "e": 39457, "s": 39113, "text": "Priority Queue is an abstract data type, which is similar to a queue, however, in the priority queue, every element has some priority. The priority of the elements in a priority queue determines the order in which elements are removed from the priority queue. Therefore all the elements are either arranged in an ascending or descending order." }, { "code": null, "e": 39539, "s": 39457, "text": "So, a priority Queue is an extension of the queue with the following properties. " }, { "code": null, "e": 39585, "s": 39539, "text": "Every item has a priority associated with it." }, { "code": null, "e": 39664, "s": 39585, "text": "An element with high priority is dequeued before an element with low priority." }, { "code": null, "e": 39759, "s": 39664, "text": "If two elements have the same priority, they are served according to their order in the queue." }, { "code": null, "e": 39911, "s": 39759, "text": "In the below priority queue, an element with a maximum ASCII value will have the highest priority. The elements with higher priority are served first. " }, { "code": null, "e": 40360, "s": 39911, "text": "A typical priority queue supports the following operations:1) Insertion: When a new element is inserted in a priority queue, it moves to the empty slot from top to bottom and left to right. However, if the element is not in the correct place then it will be compared with the parent node. If the element is not in the correct order, the elements are swapped. The swapping process continues until all the elements are placed in the correct position." }, { "code": null, "e": 40757, "s": 40360, "text": "2) Deletion: As you know that in a max heap, the maximum element is the root node. And it will remove the element which has maximum priority first. Thus, you remove the root node from the queue. This removal creates an empty slot, which will be further filled with new insertion. Then, it compares the newly inserted element with all the elements inside the queue to maintain the heap invariant." }, { "code": null, "e": 40915, "s": 40757, "text": "3) Peek: This operation helps to return the maximum element from Max Heap or minimum element from Min Heap without deleting the node from the priority queue." }, { "code": null, "e": 41290, "s": 40915, "text": "1) Ascending Order: As the name suggests, in ascending order priority queue, the element with a lower priority value is given a higher priority in the priority list. For example, if we have the following elements in a priority queue arranged in ascending order like 4,6,8,9,10. Here, 4 is the smallest number, therefore, it will get the highest priority in a priority queue." }, { "code": null, "e": 41707, "s": 41290, "text": "2) Descending order: The root node is the maximum element in a max heap, as you may know. It will also remove the element with the highest priority first. As a result, the root node is removed from the queue. This deletion leaves an empty space, which will be filled with fresh insertions in the future. The heap invariant is then maintained by comparing the newly inserted element to all other entries in the queue." }, { "code": null, "e": 41779, "s": 41707, "text": "Priority queue can be implemented using the following data structures: " }, { "code": null, "e": 41786, "s": 41779, "text": "Arrays" }, { "code": null, "e": 41798, "s": 41786, "text": "Linked list" }, { "code": null, "e": 41818, "s": 41798, "text": "Heap data structure" }, { "code": null, "e": 41837, "s": 41818, "text": "Binary search tree" }, { "code": null, "e": 41959, "s": 41837, "text": "Let’s discuss all these in detail.1) Using Array: A simple implementation is to use an array of the following structure. " }, { "code": null, "e": 42005, "s": 41959, "text": "struct item {\n int item;\n int priority;\n}" }, { "code": null, "e": 42073, "s": 42005, "text": "enqueue(): This function is used to insert new data into the queue." }, { "code": null, "e": 42160, "s": 42073, "text": "dequeue(): This function removes the element with the highest priority from the queue." }, { "code": null, "e": 42281, "s": 42160, "text": "peek()/top(): This function is used to get the highest priority element in the queue without removing it from the queue." }, { "code": null, "e": 42288, "s": 42281, "text": "Arrays" }, { "code": null, "e": 42298, "s": 42288, "text": "enqueue()" }, { "code": null, "e": 42308, "s": 42298, "text": "dequeue()" }, { "code": null, "e": 42315, "s": 42308, "text": "peek()" }, { "code": null, "e": 42331, "s": 42315, "text": "Time Complexity" }, { "code": null, "e": 42336, "s": 42331, "text": "O(1)" }, { "code": null, "e": 42341, "s": 42336, "text": "O(n)" }, { "code": null, "e": 42346, "s": 42341, "text": "O(n)" }, { "code": null, "e": 42350, "s": 42346, "text": "C++" }, { "code": "// C++ program to implement Priority Queue// using Arrays#include <bits/stdc++.h>using namespace std; // Structure for the elements in the// priority queuestruct item { int value; int priority;}; // Store the element of a priority queueitem pr[100000]; // Pointer to the last indexint size = -1; // Function to insert a new element// into priority queuevoid enqueue(int value, int priority){ // Increase the size size++; // Insert the element pr[size].value = value; pr[size].priority = priority;} // Function to check the top elementint peek(){ int highestPriority = INT_MIN; int ind = -1; // Check for the element with // highest priority for (int i = 0; i <= size; i++) { // If priority is same choose // the element with the // highest value if (highestPriority == pr[i].priority && ind > -1 && pr[ind].value < pr[i].value) { highestPriority = pr[i].priority; ind = i; } else if (highestPriority < pr[i].priority) { highestPriority = pr[i].priority; ind = i; } } // Return position of the element return ind;} // Function to remove the element with// the highest priorityvoid dequeue(){ // Find the position of the element // with highest priority int ind = peek(); // Shift the element one index before // from the position of the element // with highest priority is found for (int i = ind; i < size; i++) { pr[i] = pr[i + 1]; } // Decrease the size of the // priority queue by one size--;} // Driver Codeint main(){ // Function Call to insert elements // as per the priority enqueue(10, 2); enqueue(14, 4); enqueue(16, 4); enqueue(12, 3); // Stores the top element // at the moment int ind = peek(); cout << pr[ind].value << endl; // Dequeue the top element dequeue(); // Check the top element ind = peek(); cout << pr[ind].value << endl; // Dequeue the top element dequeue(); // Check the top element ind = peek(); cout << pr[ind].value << endl; return 0;}", "e": 44479, "s": 42350, "text": null }, { "code": null, "e": 44488, "s": 44479, "text": "16\n14\n12" }, { "code": null, "e": 44530, "s": 44488, "text": "Note: Read this article for more details." }, { "code": null, "e": 44901, "s": 44530, "text": "2) Using Linked List: In a LinkedList implementation, the entries are sorted in descending order based on their priority. The highest priority element is always added to the front of the priority queue, which is formed using linked lists. The functions like push(), pop(), and peek() are used to implement priority queue using a linked list and are explained as follows:" }, { "code": null, "e": 44966, "s": 44901, "text": "push(): This function is used to insert new data into the queue." }, { "code": null, "e": 45049, "s": 44966, "text": "pop(): This function removes the element with the highest priority from the queue." }, { "code": null, "e": 45172, "s": 45049, "text": "peek() / top(): This function is used to get the highest priority element in the queue without removing it from the queue." }, { "code": null, "e": 45184, "s": 45172, "text": "Linked List" }, { "code": null, "e": 45191, "s": 45184, "text": "push()" }, { "code": null, "e": 45197, "s": 45191, "text": "pop()" }, { "code": null, "e": 45204, "s": 45197, "text": "peek()" }, { "code": null, "e": 45220, "s": 45204, "text": "Time Complexity" }, { "code": null, "e": 45229, "s": 45220, "text": " O(n) " }, { "code": null, "e": 45237, "s": 45229, "text": " O(1) " }, { "code": null, "e": 45242, "s": 45237, "text": "O(1)" }, { "code": null, "e": 45246, "s": 45242, "text": "C++" }, { "code": "// C++ code to implement Priority Queue// using Linked List#include <bits/stdc++.h>using namespace std; // Nodetypedef struct node { int data; // Lower values indicate // higher priority int priority; struct node* next; } Node; // Function to create a new nodeNode* newNode(int d, int p){ Node* temp = (Node*)malloc(sizeof(Node)); temp->data = d; temp->priority = p; temp->next = NULL; return temp;} // Return the value at headint peek(Node** head) { return (*head)->data; } // Removes the element with the// highest priority form the listvoid pop(Node** head){ Node* temp = *head; (*head) = (*head)->next; free(temp);} // Function to push according to priorityvoid push(Node** head, int d, int p){ Node* start = (*head); // Create new Node Node* temp = newNode(d, p); // Special Case: The head of list has // lesser priority than new node if ((*head)->priority > p) { // Insert New Node before head temp->next = *head; (*head) = temp; } else { // Traverse the list and find a // position to insert new node while (start->next != NULL && start->next->priority < p) { start = start->next; } // Either at the ends of the list // or at required position temp->next = start->next; start->next = temp; }} // Function to check is list is emptyint isEmpty(Node** head) { return (*head) == NULL; } // Driver codeint main(){ // Create a Priority Queue // 7->4->5->6 Node* pq = newNode(4, 1); push(&pq, 5, 2); push(&pq, 6, 3); push(&pq, 7, 0); while (!isEmpty(&pq)) { cout << \" \" << peek(&pq); pop(&pq); } return 0;}", "e": 46972, "s": 45246, "text": null }, { "code": null, "e": 46981, "s": 46972, "text": " 7 4 5 6" }, { "code": null, "e": 47021, "s": 46981, "text": "Refer to this article for more details." }, { "code": null, "e": 47243, "s": 47021, "text": "Note: We can also use Linked List, time complexity of all operations with linked list remains same as array. The advantage with linked list is deleteHighestPriority() can be more efficient as we don’t have to move items. " }, { "code": null, "e": 47445, "s": 47243, "text": "3) Using Heaps: Binary Heap is generally preferred for priority queue implementation because heaps provide better performance compared to arrays or LinkedList. Operation on Binary Heap are as follows: " }, { "code": null, "e": 47495, "s": 47445, "text": "insert(p): Inserts a new element with priority p." }, { "code": null, "e": 47552, "s": 47495, "text": "extractMax(): Extracts an element with maximum priority." }, { "code": null, "e": 47608, "s": 47552, "text": "remove(i): Removes an element pointed by an iterator i." }, { "code": null, "e": 47660, "s": 47608, "text": "getMax(): Returns an element with maximum priority." }, { "code": null, "e": 47736, "s": 47660, "text": "changePriority(i, p): Changes the priority of an element pointed by i to p." }, { "code": null, "e": 47748, "s": 47736, "text": "Binary Heap" }, { "code": null, "e": 47757, "s": 47748, "text": "insert()" }, { "code": null, "e": 47766, "s": 47757, "text": "remove()" }, { "code": null, "e": 47773, "s": 47766, "text": "peek()" }, { "code": null, "e": 47789, "s": 47773, "text": "Time Complexity" }, { "code": null, "e": 47798, "s": 47789, "text": "O(log n)" }, { "code": null, "e": 47807, "s": 47798, "text": "O(log n)" }, { "code": null, "e": 47812, "s": 47807, "text": "O(1)" }, { "code": null, "e": 47860, "s": 47812, "text": "Refer to this article for code implementation. " }, { "code": null, "e": 48083, "s": 47860, "text": "4) Using Binary Search Tree: A Self-Balancing Binary Search Tree like AVL Tree, Red-Black Tree, etc. can also be used to implement a priority queue. Operations like peek(), insert() and delete() can be performed using BST." }, { "code": null, "e": 48147, "s": 48083, "text": "What is the difference between Priority Queue and Normal Queue?" }, { "code": null, "e": 48365, "s": 48147, "text": "There is no priority attached to elements in a queue, the rule of first-in-first-out(FIFO) is implemented whereas, in a priority queue, the elements have a priority. The elements with higher priority are served first." }, { "code": null, "e": 48398, "s": 48365, "text": "Applications of Priority Queue: " }, { "code": null, "e": 48413, "s": 48398, "text": "CPU Scheduling" }, { "code": null, "e": 48506, "s": 48413, "text": "Graph algorithms like Dijkstra’s shortest path algorithm, Prim’s Minimum Spanning Tree, etc." }, { "code": null, "e": 48527, "s": 48506, "text": "Stack Implementation" }, { "code": null, "e": 48578, "s": 48527, "text": "All queue applications where priority is involved." }, { "code": null, "e": 48611, "s": 48578, "text": "Data compression in Huffman code" }, { "code": null, "e": 48622, "s": 48611, "text": "See also: " }, { "code": null, "e": 48787, "s": 48622, "text": "Recent articles on Priority Queue!Applications of Priority Queue.Priority Queue in C++.Priority Queue in Java.Priority Queue in Python.Priority Queue in JavaScript." }, { "code": null, "e": 48822, "s": 48787, "text": "Recent articles on Priority Queue!" }, { "code": null, "e": 48854, "s": 48822, "text": "Applications of Priority Queue." }, { "code": null, "e": 48877, "s": 48854, "text": "Priority Queue in C++." }, { "code": null, "e": 48901, "s": 48877, "text": "Priority Queue in Java." }, { "code": null, "e": 48927, "s": 48901, "text": "Priority Queue in Python." }, { "code": null, "e": 48957, "s": 48927, "text": "Priority Queue in JavaScript." }, { "code": null, "e": 49082, "s": 48957, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 49096, "s": 49082, "text": "anshikajain26" }, { "code": null, "e": 49106, "s": 49096, "text": "as5853535" }, { "code": null, "e": 49121, "s": 49106, "text": "priority-queue" }, { "code": null, "e": 49127, "s": 49121, "text": "Queue" }, { "code": null, "e": 49133, "s": 49127, "text": "Queue" }, { "code": null, "e": 49148, "s": 49133, "text": "priority-queue" }, { "code": null, "e": 49246, "s": 49148, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 49280, "s": 49246, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 49304, "s": 49280, "text": "Queue Interface In Java" }, { "code": null, "e": 49320, "s": 49304, "text": "Queue in Python" }, { "code": null, "e": 49383, "s": 49320, "text": "Circular Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 49443, "s": 49383, "text": "Sliding Window Maximum (Maximum of all subarrays of size k)" }, { "code": null, "e": 49482, "s": 49443, "text": "Array implementation of queue (Simple)" }, { "code": null, "e": 49533, "s": 49482, "text": "Difference between Stack and Queue Data Structures" }, { "code": null, "e": 49558, "s": 49533, "text": "Priority Queue in Python" }, { "code": null, "e": 49613, "s": 49558, "text": "Program for Page Replacement Algorithms | Set 2 (FIFO)" } ]
Accessing elements of a Pandas Series
Pandas series is a one-dimensional labeled array capable of holding data of any type (integer, string, float, python objects, etc.). The elements of a pandas series can be accessed using various methods. Let's first create a pandas series and then access it's elements. A panadas series is created by supplying data in various forms like ndarray, list, constants and the index values which must be unique and hashable. An example is given below. import pandas as pd s = pd.Series([11,8,6,14,25],index = ['a','b','c','d','e']) print s Running the above code gives us the following result − a 11 b 8 c 6 d 14 e 25 dtype: int64 We can access the data elements of a series by using various methods. We will continue to use the series created above to demonstrate the various methods of accessing. The first element is at the index 0 position. So it is accessed by mentioning the index value in the series. We can use both 0 or the custom index to fetch the value. import pandas as pd s = pd.Series([11,8,6,14,25],index = ['a','b','c','d','e']) print s[0] print s['a'] Running the above code gives us the following result − 11 11 In a similar manner as above we get the first three elements by using the : value in front of the index value of 3 or the appropriate custom index value. import pandas as pd s = pd.Series([11,8,6,14,25],index = ['a','b','c','d','e']) print s[:3] print s[:'c'] Running the above code gives us the following result − a 11 b 8 c 6 dtype: int64 a 11 b 8 c 6 dtype: int64 In a similar manner as above, we get the first three elements by using the: value at the end of the index value of 3 with a negative sign or the appropriate custom index value. import pandas as pd s = pd.Series([11,8,6,14,25],index = ['a','b','c','d','e']) print s[-3:] print s['c':] Running the above code gives us the following result − c 6 d 14 e 25 dtype: int64 c 6 d 14 e 25 dtype: int64 In this case, we use the custom index values to access non-sequential elements of the series. import pandas as pd s = pd.Series([11,8,6,14,25],index = ['a','b','c','d','e']) print s[['c','b','e']] Running the above code gives us the following result − c 6 b 8 e 25 dtype: int64
[ { "code": null, "e": 1266, "s": 1062, "text": "Pandas series is a one-dimensional labeled array capable of holding data of any type (integer, string, float, python objects, etc.). The elements of a pandas series can be accessed using various methods." }, { "code": null, "e": 1332, "s": 1266, "text": "Let's first create a pandas series and then access it's elements." }, { "code": null, "e": 1508, "s": 1332, "text": "A panadas series is created by supplying data in various forms like ndarray, list, constants and the index values which must be unique and hashable. An example is given below." }, { "code": null, "e": 1596, "s": 1508, "text": "import pandas as pd\ns = pd.Series([11,8,6,14,25],index = ['a','b','c','d','e'])\nprint s" }, { "code": null, "e": 1651, "s": 1596, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1700, "s": 1651, "text": "a 11\nb 8\nc 6\nd 14\ne 25\ndtype: int64" }, { "code": null, "e": 1868, "s": 1700, "text": "We can access the data elements of a series by using various methods. We will continue to use the series created above to demonstrate the various methods of accessing." }, { "code": null, "e": 2035, "s": 1868, "text": "The first element is at the index 0 position. So it is accessed by mentioning the index value in the series. We can use both 0 or the custom index to fetch the value." }, { "code": null, "e": 2139, "s": 2035, "text": "import pandas as pd\ns = pd.Series([11,8,6,14,25],index = ['a','b','c','d','e'])\nprint s[0]\nprint s['a']" }, { "code": null, "e": 2194, "s": 2139, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2200, "s": 2194, "text": "11\n11" }, { "code": null, "e": 2354, "s": 2200, "text": "In a similar manner as above we get the first three elements by using the : value in front of the index value of 3 or the appropriate custom index value." }, { "code": null, "e": 2460, "s": 2354, "text": "import pandas as pd\ns = pd.Series([11,8,6,14,25],index = ['a','b','c','d','e'])\nprint s[:3]\nprint s[:'c']" }, { "code": null, "e": 2515, "s": 2460, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2581, "s": 2515, "text": "a 11\nb 8\nc 6\ndtype: int64\na 11\nb 8\nc 6\ndtype: int64" }, { "code": null, "e": 2758, "s": 2581, "text": "In a similar manner as above, we get the first three elements by using the: value at the end of the index value of 3 with a negative sign or the appropriate custom index value." }, { "code": null, "e": 2865, "s": 2758, "text": "import pandas as pd\ns = pd.Series([11,8,6,14,25],index = ['a','b','c','d','e'])\nprint s[-3:]\nprint s['c':]" }, { "code": null, "e": 2920, "s": 2865, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2974, "s": 2920, "text": "c 6\nd 14\ne 25\ndtype: int64\nc 6\nd 14\ne 25\ndtype: int64" }, { "code": null, "e": 3068, "s": 2974, "text": "In this case, we use the custom index values to access non-sequential elements of the series." }, { "code": null, "e": 3171, "s": 3068, "text": "import pandas as pd\ns = pd.Series([11,8,6,14,25],index = ['a','b','c','d','e'])\nprint s[['c','b','e']]" }, { "code": null, "e": 3226, "s": 3171, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 3252, "s": 3226, "text": "c 6\nb 8\ne 25\ndtype: int64" } ]
How to Setup Virtual Hosts with Apache Web Server on Linux
In this article, you will learn about how to set up Apache virtual hosts on an Ubuntu Linux. During this process, you will learn how to serve different sites to different users depending on the domain/site they are requesting. The Apache web server is the most popular and powerful way of serving web sites on the internet. It is used for more than half of all the active websites on the internet and is extremely powerful and flexible. Apache gives its functionality and the components to individual units which can be customized and configured independently. The basic unit that describes a site or a domain is called a virtual host. This allows the administrator to use one server to host multiple domains or sites with a single interface or IP address by using a mechanism. $ sudo apt-get update $ sudo apt-get install apache2 After these steps are complete, we can get started. For Demo purpose, we shall configure apache to make a virtual host for webserver1.com and another for webserver2.com. This will be like a reference guide, but you should substitute your own site/domains. The first step here would be that, a directory structure shall hold the site information and data which will be served to visitors. By default, the top-level directory for apache is /var/www and we will be setting them to the individual directories under the /var/www directory for each site/domain. For each of our site, we are going to make site directories – $ sudo mkdir -p /var/www/webserver1.com $ sudo mkdir -p /var/www/webserver2.com Now, we have the directory structure of our site/domain, but they are created and owned by our root user. If we want our normal user to be able to modify files in our web directories, then we have to change the ownership to others normal users. $ sudo chown -R $USER:$USER /var/www/webserver1.com $ sudo chown -R $USER:$USER /var/www/webserver2.com We should also modify our permissions a little bit to ensure that read access is permitted to the general web directory and all of the files and folders it contains so that pages can be served correctly: $ sudo chmod -R 755 /var/www Your web server should now have the permissions it needs to serve the site, and your user should be able to create content within the necessary folders. First, we shall start with webserver1.com. Then, we can create an index.html file in our editor by typing: $ touch /var/www/webserver1.com/index.html Edit the index.html file with a simple HTML script which indicates the site it is connected to. <html> $ nano /var/www/webserver1.com/ index.html <html> <head> <title>Welcome to webserver1.com!</title> </head> <body> <h1>Success! The webserver1.com virtual host is working!</h1> </body> </html> class="result notranslate"$ cp /var/www/webserver1.com/index.html /var/www/webserver2.com/index.html We can then edit the file and modify the relevant pieces of information: $ nano /var/www/webserver2.com/public_html/index.html <html> <head> <title>Welcome to webserver2.com!</title> </head> <body> <h1>Success! The webserver2.com virtual host is working!</h1> </body> </html> Virtual host files are the configuration files that specify the virtual host and instructs the Apache to respond to various domain requests. $ sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/webserver1.com.conf $ sudo nano /etc/apache2/sites-available/webserver1.com.conf <VirtualHost *:80> ServerAdmin admin@webserver1.com ServerName webserver1.com ServerAlias www.webserver1.com DocumentRoot /var/www/webserver1.com/public_html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> Copy First Virtual Host file and customize for Second Domain webserver2.com $ sudo cp /etc/apache2/sites-available/webserver1.com.conf /etc/apache2/sites-available/webserver2.com.conf $ sudo nano /etc/apache2/sites-available/webserver2.com.conf You now need to modify all of the pieces of information to reference your second domain. When you are finished, it may look something like this: <VirtualHost *:80> ServerAdmin admin@webserver2.com ServerName webserver2.com ServerAlias www.webserver2.com DocumentRoot /var/www/webserver2.com/public_html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> Now that we have already created our virtual host files, we must enable these sites. Apache has its own tools that allow us to do this. $ sudo a2ensite webserver1.com.conf $ sudo a2ensite webserver2.com.conf We needed to restart Apache to make these changes take effect: $ sudo service apache2 restart * Restarting web server apache2 AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1. Set the 'ServerName' directive globally to suppress this message. This is a harmless message that does not affect our site. As these site/domains are not the public so no entry will be there to easy the steps we needed to edit the /etc/hosts file so that if we browse with domain names webserver1.com and webserver2.com we can see the web pages $ sudo /etc/hosts 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 192.168.1.84 website1.com 192.168.1.84 website1.com Now that you have two hosts configured, you can test your setup easily by opening the favorite browser and open the domains. http://webserver1.com http://webserver2.com After the configuration you should now have a single server handling two separate domain/site names. You can expand this process by following the steps we outlined above to make additional virtual hosts. There is no software limit for configuring the domain names Apache can handle any no of sites, we can make as many as sites/domains till your servers are capable of handling them.
[ { "code": null, "e": 1289, "s": 1062, "text": "In this article, you will learn about how to set up Apache virtual hosts on an Ubuntu Linux. During this process, you will learn how to serve different sites to different users depending on the domain/site they are requesting." }, { "code": null, "e": 1499, "s": 1289, "text": "The Apache web server is the most popular and powerful way of serving web sites on the internet. It is used for more than half of all the active websites on the internet and is extremely powerful and flexible." }, { "code": null, "e": 1698, "s": 1499, "text": "Apache gives its functionality and the components to individual units which can be customized and configured independently. The basic unit that describes a site or a domain is called a virtual host." }, { "code": null, "e": 1840, "s": 1698, "text": "This allows the administrator to use one server to host multiple domains or sites with a single interface or IP address by using a mechanism." }, { "code": null, "e": 1893, "s": 1840, "text": "$ sudo apt-get update\n$ sudo apt-get install apache2" }, { "code": null, "e": 1945, "s": 1893, "text": "After these steps are complete, we can get started." }, { "code": null, "e": 2149, "s": 1945, "text": "For Demo purpose, we shall configure apache to make a virtual host for webserver1.com and another for webserver2.com. This will be like a reference guide, but you should substitute your own site/domains." }, { "code": null, "e": 2449, "s": 2149, "text": "The first step here would be that, a directory structure shall hold the site information and data which will be served to visitors. By default, the top-level directory for apache is /var/www and we will be setting them to the individual directories under the /var/www directory for each site/domain." }, { "code": null, "e": 2511, "s": 2449, "text": "For each of our site, we are going to make site directories –" }, { "code": null, "e": 2591, "s": 2511, "text": "$ sudo mkdir -p /var/www/webserver1.com\n$ sudo mkdir -p /var/www/webserver2.com" }, { "code": null, "e": 2836, "s": 2591, "text": "Now, we have the directory structure of our site/domain, but they are created and owned by our root user. If we want our normal user to be able to modify files in our web directories, then we have to change the ownership to others normal users." }, { "code": null, "e": 2940, "s": 2836, "text": "$ sudo chown -R $USER:$USER /var/www/webserver1.com\n$ sudo chown -R $USER:$USER /var/www/webserver2.com" }, { "code": null, "e": 3144, "s": 2940, "text": "We should also modify our permissions a little bit to ensure that read access is permitted to the general web directory and all of the files and folders it contains so that pages can be served correctly:" }, { "code": null, "e": 3173, "s": 3144, "text": "$ sudo chmod -R 755 /var/www" }, { "code": null, "e": 3326, "s": 3173, "text": "Your web server should now have the permissions it needs to serve the site, and your user should be able to create content within the necessary folders." }, { "code": null, "e": 3433, "s": 3326, "text": "First, we shall start with webserver1.com. Then, we can create an index.html file in our editor by typing:" }, { "code": null, "e": 3476, "s": 3433, "text": "$ touch /var/www/webserver1.com/index.html" }, { "code": null, "e": 3579, "s": 3476, "text": "Edit the index.html file with a simple HTML script which indicates the site it is connected to. <html>" }, { "code": null, "e": 3795, "s": 3579, "text": "$ nano /var/www/webserver1.com/ index.html\n<html>\n <head>\n <title>Welcome to webserver1.com!</title>\n </head>\n <body>\n <h1>Success! The webserver1.com virtual host is working!</h1>\n </body>\n</html>" }, { "code": null, "e": 3896, "s": 3795, "text": "class=\"result notranslate\"$ cp /var/www/webserver1.com/index.html /var/www/webserver2.com/index.html" }, { "code": null, "e": 3969, "s": 3896, "text": "We can then edit the file and modify the relevant pieces of information:" }, { "code": null, "e": 4196, "s": 3969, "text": "$ nano /var/www/webserver2.com/public_html/index.html\n<html>\n <head>\n <title>Welcome to webserver2.com!</title>\n </head>\n <body>\n <h1>Success! The webserver2.com virtual host is working!</h1>\n </body>\n</html>" }, { "code": null, "e": 4337, "s": 4196, "text": "Virtual host files are the configuration files that specify the virtual host and instructs the Apache to respond to various domain requests." }, { "code": null, "e": 4779, "s": 4337, "text": "$ sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/webserver1.com.conf\n$ sudo nano /etc/apache2/sites-available/webserver1.com.conf\n<VirtualHost *:80>\n ServerAdmin admin@webserver1.com\n ServerName webserver1.com\n ServerAlias www.webserver1.com\n DocumentRoot /var/www/webserver1.com/public_html\n ErrorLog ${APACHE_LOG_DIR}/error.log\n CustomLog ${APACHE_LOG_DIR}/access.log combined\n</VirtualHost>" }, { "code": null, "e": 4855, "s": 4779, "text": "Copy First Virtual Host file and customize for Second Domain webserver2.com" }, { "code": null, "e": 5024, "s": 4855, "text": "$ sudo cp /etc/apache2/sites-available/webserver1.com.conf /etc/apache2/sites-available/webserver2.com.conf\n$ sudo nano /etc/apache2/sites-available/webserver2.com.conf" }, { "code": null, "e": 5169, "s": 5024, "text": "You now need to modify all of the pieces of information to reference your second domain. When you are finished, it may look something like this:" }, { "code": null, "e": 5445, "s": 5169, "text": "<VirtualHost *:80>\n ServerAdmin admin@webserver2.com\n ServerName webserver2.com\n ServerAlias www.webserver2.com\n DocumentRoot /var/www/webserver2.com/public_html\n ErrorLog ${APACHE_LOG_DIR}/error.log\n CustomLog ${APACHE_LOG_DIR}/access.log combined\n</VirtualHost>" }, { "code": null, "e": 5581, "s": 5445, "text": "Now that we have already created our virtual host files, we must enable these sites. Apache has its own tools that allow us to do this." }, { "code": null, "e": 5653, "s": 5581, "text": "$ sudo a2ensite webserver1.com.conf\n$ sudo a2ensite webserver2.com.conf" }, { "code": null, "e": 5716, "s": 5653, "text": "We needed to restart Apache to make these changes take effect:" }, { "code": null, "e": 6009, "s": 5716, "text": "$ sudo service apache2 restart\n* Restarting web server apache2\nAH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1.\nSet the 'ServerName' directive globally to suppress this message.\nThis is a harmless message that does not affect our site." }, { "code": null, "e": 6230, "s": 6009, "text": "As these site/domains are not the public so no entry will be there to easy the steps we needed to edit the /etc/hosts file so that if we browse with domain names webserver1.com and webserver2.com we can see the web pages" }, { "code": null, "e": 6448, "s": 6230, "text": "$ sudo /etc/hosts\n127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4\n::1 localhost localhost.localdomain localhost6 localhost6.localdomain6\n192.168.1.84 website1.com\n192.168.1.84 website1.com" }, { "code": null, "e": 6573, "s": 6448, "text": "Now that you have two hosts configured, you can test your setup easily by opening the favorite browser and open the domains." }, { "code": null, "e": 6595, "s": 6573, "text": "http://webserver1.com" }, { "code": null, "e": 6617, "s": 6595, "text": "http://webserver2.com" }, { "code": null, "e": 7001, "s": 6617, "text": "After the configuration you should now have a single server handling two separate domain/site names. You can expand this process by following the steps we outlined above to make additional virtual hosts. There is no software limit for configuring the domain names Apache can handle any no of sites, we can make as many as sites/domains till your servers are capable of handling them." } ]
Android Coding Style and Guidelines - GeeksforGeeks
25 Aug, 2021 While you writing code, there are some rules you need to follow to keep code easy to read and clean. If you are not new to coding, you probably already know about coding standards. Coding standards vary from person to person and can be different for different projects. Before starting adding or updating code in someone else’s project or open source project, you should first look around to identify the coding style they’ve used and try to follow the same. Here are some commonly accepted coding standards for android which will help you to write clean code. 1. Indent your code Properly with tabs or 4 white spaces. 2. Put braces on the same line as the code before them, not on their own line. Example: Java // This is Bad practiceclass myClass1{ int func2() { //... }} // This is good practiceclass MyClass { int func() { if(){ //... }else{ //... } }} 3. If the condition and the body fit on one line, you may put it all on one line. Example: Java if (condition) { body();} // can be written as if(condition) body(); // But not likeif(condition) body(); // Bad Practice 4. Use TODO comments for code that is temporary, a short-term solution, or good enough but not perfect. These comments should include the string “TODO” in all caps, followed by a colon. Example: Java // TODO: Use boolean Flag instead of int constant. 5. Switch case should always have a “default” statement to catch unexpected values. 6. Use standard predefined annotations in code wherever needed. Example: Java @Deprecated // used to mark component which no longer should be used. @Override // used to tell that declared method overrides method in superclass. @Nullable// tells that parameter, return value of method or field can be null. @NonNull// tells that parameter, return value of method or field can not be null. You should never leave your catch block empty, even if you are too sure that exception will never occur. Try to catch exceptions separately, do not catch generic exceptions.Try to use different “try” blocks for statements that can cause different exceptions. Ex.- separate parsing statements from Input statements into separate “try” blocks. Try to use different “try” blocks for statements that can cause different exceptions. Ex.- separate parsing statements from Input statements into separate “try” blocks. If you are confident about ignoring exceptions, then you should put an appropriate comment explaining why exceptions can be ignored, Example: Declare iteration variable in for loop itself. Java int i = 0; // bad practicefor(i= 0; i< 10; i++) // Good practicefor(int i=0; i<10; i++){ // do your work} // good practicefor(Iterator i = c.iterator(); i.hasNext()){ // do your work} Naming conventions in coding: Non-static, Non-public (i.e., private, default, and protected) field names should start with m, Ex.- int mVar. Static field names should start with s, Ex.- private static int sVar. Public fields should start with a lower case letter, Ex.- public int var. Public static final fields or constants should be in all caps with underscores, Ex.- public static final int MY_CONSTANT = 42. Class or interface name should always start with a capital letter and the first letter of the changing word should be also in capital Ex.- MyClass, MyInterface, MyCustomViewClass The class should have comments at the top which clearly state the purpose of the class creation. Same for functions. The function name should always start with a small letter, and the first letter of the changing word should be capitalized. Ex.- public int registeNewUser(), Naming conventions in XML: Layout files should match the name of the Android components that they are intended. Ex.- layout file for LoginActivity.class should be nam ed as activity_login.xml. When we are creating a layout that is going to be inflated by an Adapter, i.e., to populate a ListView or RecyclerView. In this case, the name of the layout should start with “item_”, Ex.- item_contact_card.xml. Layout resource id should use the naming convention where possible: <layout name>_<object type>_<object name>, Ex.- profile_imageview_avatar. When defining string in strings.xml, name of string should follow this syntax: <purpose>_<where>, Ex.- <string name=”hint_login_id”>Enter your login ID</string>. Drawable files should be named as <prefix>_<description>, prefixes used for icons, buttons, and action Bar are ic_, btn_, ab_ respectively. Ex.- btn_sign_up.xml, dialog_warning.xml, menu_primary.xml. All resources that are being used in the project should be defined in the “res” folder of the application in the following format: If you need to use string values in the application, then it should be defined in “res/values/string.xml”. If you need to use color in the application, then it should be defined in “res/values/colors.xml”. If you need to use static arrays in the application, then it should be defined in “res/values/arrays.xml”. If you need to use static dimensions in the application, then they should be defined in “res/values/dimens.xml”. If you need to use specific or custom styles for components used in the application, it should be defined in “res/values/styles.xml”. Picked Android Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? Flexbox-Layout in Android How to Post Data to API using Retrofit in Android? Retrofit with Kotlin Coroutine in Android Android Listview in Java with Example Fragment Lifecycle in Android How to Change the Background Color After Clicking the Button in Android? How to Get Current Location in Android?
[ { "code": null, "e": 26491, "s": 26463, "text": "\n25 Aug, 2021" }, { "code": null, "e": 27052, "s": 26491, "text": "While you writing code, there are some rules you need to follow to keep code easy to read and clean. If you are not new to coding, you probably already know about coding standards. Coding standards vary from person to person and can be different for different projects. Before starting adding or updating code in someone else’s project or open source project, you should first look around to identify the coding style they’ve used and try to follow the same. Here are some commonly accepted coding standards for android which will help you to write clean code." }, { "code": null, "e": 27110, "s": 27052, "text": "1. Indent your code Properly with tabs or 4 white spaces." }, { "code": null, "e": 27189, "s": 27110, "text": "2. Put braces on the same line as the code before them, not on their own line." }, { "code": null, "e": 27198, "s": 27189, "text": "Example:" }, { "code": null, "e": 27203, "s": 27198, "text": "Java" }, { "code": "// This is Bad practiceclass myClass1{ int func2() { //... }} // This is good practiceclass MyClass { int func() { if(){ //... }else{ //... } }}", "e": 27405, "s": 27203, "text": null }, { "code": null, "e": 27487, "s": 27405, "text": "3. If the condition and the body fit on one line, you may put it all on one line." }, { "code": null, "e": 27496, "s": 27487, "text": "Example:" }, { "code": null, "e": 27501, "s": 27496, "text": "Java" }, { "code": "if (condition) { body();} // can be written as if(condition) body(); // But not likeif(condition) body(); // Bad Practice", "e": 27631, "s": 27501, "text": null }, { "code": null, "e": 27817, "s": 27631, "text": "4. Use TODO comments for code that is temporary, a short-term solution, or good enough but not perfect. These comments should include the string “TODO” in all caps, followed by a colon." }, { "code": null, "e": 27826, "s": 27817, "text": "Example:" }, { "code": null, "e": 27831, "s": 27826, "text": "Java" }, { "code": "// TODO: Use boolean Flag instead of int constant.", "e": 27882, "s": 27831, "text": null }, { "code": null, "e": 27966, "s": 27882, "text": "5. Switch case should always have a “default” statement to catch unexpected values." }, { "code": null, "e": 28030, "s": 27966, "text": "6. Use standard predefined annotations in code wherever needed." }, { "code": null, "e": 28039, "s": 28030, "text": "Example:" }, { "code": null, "e": 28044, "s": 28039, "text": "Java" }, { "code": "@Deprecated // used to mark component which no longer should be used. @Override // used to tell that declared method overrides method in superclass. @Nullable// tells that parameter, return value of method or field can be null. @NonNull// tells that parameter, return value of method or field can not be null.", "e": 28357, "s": 28044, "text": null }, { "code": null, "e": 28462, "s": 28357, "text": "You should never leave your catch block empty, even if you are too sure that exception will never occur." }, { "code": null, "e": 28699, "s": 28462, "text": "Try to catch exceptions separately, do not catch generic exceptions.Try to use different “try” blocks for statements that can cause different exceptions. Ex.- separate parsing statements from Input statements into separate “try” blocks." }, { "code": null, "e": 28868, "s": 28699, "text": "Try to use different “try” blocks for statements that can cause different exceptions. Ex.- separate parsing statements from Input statements into separate “try” blocks." }, { "code": null, "e": 29001, "s": 28868, "text": "If you are confident about ignoring exceptions, then you should put an appropriate comment explaining why exceptions can be ignored," }, { "code": null, "e": 29057, "s": 29001, "text": "Example: Declare iteration variable in for loop itself." }, { "code": null, "e": 29062, "s": 29057, "text": "Java" }, { "code": "int i = 0; // bad practicefor(i= 0; i< 10; i++) // Good practicefor(int i=0; i<10; i++){ // do your work} // good practicefor(Iterator i = c.iterator(); i.hasNext()){ // do your work}", "e": 29259, "s": 29062, "text": null }, { "code": null, "e": 29289, "s": 29259, "text": "Naming conventions in coding:" }, { "code": null, "e": 29400, "s": 29289, "text": "Non-static, Non-public (i.e., private, default, and protected) field names should start with m, Ex.- int mVar." }, { "code": null, "e": 29470, "s": 29400, "text": "Static field names should start with s, Ex.- private static int sVar." }, { "code": null, "e": 29544, "s": 29470, "text": "Public fields should start with a lower case letter, Ex.- public int var." }, { "code": null, "e": 29671, "s": 29544, "text": "Public static final fields or constants should be in all caps with underscores, Ex.- public static final int MY_CONSTANT = 42." }, { "code": null, "e": 29851, "s": 29671, "text": "Class or interface name should always start with a capital letter and the first letter of the changing word should be also in capital Ex.- MyClass, MyInterface, MyCustomViewClass" }, { "code": null, "e": 29968, "s": 29851, "text": "The class should have comments at the top which clearly state the purpose of the class creation. Same for functions." }, { "code": null, "e": 30127, "s": 29968, "text": "The function name should always start with a small letter, and the first letter of the changing word should be capitalized. Ex.- public int registeNewUser(), " }, { "code": null, "e": 30154, "s": 30127, "text": "Naming conventions in XML:" }, { "code": null, "e": 30294, "s": 30154, "text": "Layout files should match the name of the Android components that they are intended. Ex.- layout file for LoginActivity.class should be nam" }, { "code": null, "e": 30320, "s": 30294, "text": "ed as activity_login.xml." }, { "code": null, "e": 30532, "s": 30320, "text": "When we are creating a layout that is going to be inflated by an Adapter, i.e., to populate a ListView or RecyclerView. In this case, the name of the layout should start with “item_”, Ex.- item_contact_card.xml." }, { "code": null, "e": 30674, "s": 30532, "text": "Layout resource id should use the naming convention where possible: <layout name>_<object type>_<object name>, Ex.- profile_imageview_avatar." }, { "code": null, "e": 30837, "s": 30674, "text": "When defining string in strings.xml, name of string should follow this syntax: <purpose>_<where>, Ex.- <string name=”hint_login_id”>Enter your login ID</string>." }, { "code": null, "e": 31038, "s": 30837, "text": "Drawable files should be named as <prefix>_<description>, prefixes used for icons, buttons, and action Bar are ic_, btn_, ab_ respectively. Ex.- btn_sign_up.xml, dialog_warning.xml, menu_primary.xml. " }, { "code": null, "e": 31169, "s": 31038, "text": "All resources that are being used in the project should be defined in the “res” folder of the application in the following format:" }, { "code": null, "e": 31276, "s": 31169, "text": "If you need to use string values in the application, then it should be defined in “res/values/string.xml”." }, { "code": null, "e": 31375, "s": 31276, "text": "If you need to use color in the application, then it should be defined in “res/values/colors.xml”." }, { "code": null, "e": 31482, "s": 31375, "text": "If you need to use static arrays in the application, then it should be defined in “res/values/arrays.xml”." }, { "code": null, "e": 31595, "s": 31482, "text": "If you need to use static dimensions in the application, then they should be defined in “res/values/dimens.xml”." }, { "code": null, "e": 31729, "s": 31595, "text": "If you need to use specific or custom styles for components used in the application, it should be defined in “res/values/styles.xml”." }, { "code": null, "e": 31736, "s": 31729, "text": "Picked" }, { "code": null, "e": 31744, "s": 31736, "text": "Android" }, { "code": null, "e": 31752, "s": 31744, "text": "Android" }, { "code": null, "e": 31850, "s": 31752, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31888, "s": 31850, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 31927, "s": 31888, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 31977, "s": 31927, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 32003, "s": 31977, "text": "Flexbox-Layout in Android" }, { "code": null, "e": 32054, "s": 32003, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 32096, "s": 32054, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 32134, "s": 32096, "text": "Android Listview in Java with Example" }, { "code": null, "e": 32164, "s": 32134, "text": "Fragment Lifecycle in Android" }, { "code": null, "e": 32237, "s": 32164, "text": "How to Change the Background Color After Clicking the Button in Android?" } ]
Filter Pandas Dataframe with multiple conditions - GeeksforGeeks
16 Mar, 2021 In this article, let’s discuss how to filter pandas dataframe with multiple conditions. There are possibilities of filtering data from Pandas dataframe with multiple conditions during the entire software development. The reason is dataframe may be having multiple columns and multiple rows. Selective display of columns with limited rows is always the expected view of users. To fulfill the user’s expectations and also help in machine deep learning scenarios, filtering of Pandas dataframe with multiple conditions is much necessary. Let us see the different ways to do the same. Creating a sample dataframe to proceed further Python3 # import moduleimport pandas as pd # assign datadataFrame = pd.DataFrame({'Name': [' RACHEL ', ' MONICA ', ' PHOEBE ', ' ROSS ', 'CHANDLER', ' JOEY '], 'Age': [30, 35, 37, 33, 34, 30], 'Salary': [100000, 93000, 88000, 120000, 94000, 95000], 'JOB': ['DESIGNER', 'CHEF', 'MASUS', 'PALENTOLOGY', 'IT', 'ARTIST']}) # display dataframedisplay(dataFrame) Output: Method 1: Using loc Here we will get all rows having Salary greater or equal to 100000 and Age < 40 and their JOB starts with ‘D’ from the dataframe. Print the details with Name and their JOB. For the above requirement, we can achieve this by using loc. It is used to access single or more rows and columns by label(s) or by a boolean array. loc works with column labels and indexes. Python3 # import moduleimport pandas as pd # assign datadataFrame = pd.DataFrame({'Name': [' RACHEL ', ' MONICA ', ' PHOEBE ', ' ROSS ', 'CHANDLER', ' JOEY '], 'Age': [30, 35, 37, 33, 34, 30], 'Salary': [100000, 93000, 88000, 120000, 94000, 95000], 'JOB': ['DESIGNER', 'CHEF', 'MASUS', 'PALENTOLOGY', 'IT', 'ARTIST']})# filter dataframedisplay(dataFrame.loc[(dataFrame['Salary']>=100000) & (dataFrame['Age']< 40) & (dataFrame['JOB'].str.startswith('D')), ['Name','JOB']]) Output: Output resolves for the given conditions and finally, we are going to show only 2 columns namely Name and JOB. Method 2: Using NumPy Here will get all rows having Salary greater or equal to 100000 and Age < 40 and their JOB starts with ‘D’ from the data frame. We need to use NumPy. Python3 # import moduleimport pandas as pdimport numpy as np # assign datadataFrame = pd.DataFrame({'Name': [' RACHEL ', ' MONICA ', ' PHOEBE ', ' ROSS ', 'CHANDLER', ' JOEY '], 'Age': [30, 35, 37, 33, 34, 30], 'Salary': [100000, 93000, 88000, 120000, 94000, 95000], 'JOB': ['DESIGNER', 'CHEF', 'MASUS', 'PALENTOLOGY', 'IT', 'ARTIST']}) # filter dataframe filtered_values = np.where((dataFrame['Salary']>=100000) & (dataFrame['Age']< 40) & (dataFrame['JOB'].str.startswith('D')))print(filtered_values)display(dataFrame.loc[filtered_values]) Output: In the above example, print(filtered_values) will give the output as (array([0], dtype=int64),) which indicates the first row with index value 0 will be the output. After that output will have 1 row with all the columns and it is retrieved as per the given conditions. Method 3: Using Query (eval and query works only with columns) In this approach, we get all rows having Salary lesser or equal to 100000 and Age < 40, and their JOB starts with ‘C’ from the dataframe. Its just query the columns of a DataFrame with a single or more Boolean expressions and if multiple, it is having & condition in the middle. Python3 # import moduleimport pandas as pd # assign datadataFrame = pd.DataFrame({'Name': [' RACHEL ', ' MONICA ', ' PHOEBE ', ' ROSS ', 'CHANDLER', ' JOEY '], 'Age': [30, 35, 37, 33, 34, 30], 'Salary': [100000, 93000, 88000, 120000, 94000, 95000], 'JOB': ['DESIGNER', 'CHEF', 'MASUS', 'PALENTOLOGY', 'IT', 'ARTIST']}) # filter dataframe display(dataFrame.query('Salary <= 100000 & Age < 40 & JOB.str.startswith("C").values')) Output: Method 4: pandas Boolean indexing multiple conditions standard way (“Boolean indexing” works with values in a column only) In this approach, we get all rows having Salary lesser or equal to 100000 and Age < 40 and their JOB starts with ‘P’ from the dataframe. In order to select the subset of data using the values in the dataframe and applying Boolean conditions, we need to follow these ways Python3 # import moduleimport pandas as pd # assign datadataFrame = pd.DataFrame({'Name': [' RACHEL ', ' MONICA ', ' PHOEBE ', ' ROSS ', 'CHANDLER', ' JOEY '], 'Age': [30, 35, 37, 33, 34, 30], 'Salary': [100000, 93000, 88000, 120000, 94000, 95000], 'JOB': ['DESIGNER', 'CHEF', 'MASUS', 'PALENTOLOGY', 'IT', 'ARTIST']}) # filter dataframe display(dataFrame[(dataFrame['Salary']>=100000) & (dataFrame['Age']<40) & dataFrame['JOB'].str.startswith('P')][['Name','Age','Salary']]) Output: We are mentioning a list of columns that need to be retrieved along with the Boolean conditions and since many conditions, it is having ‘&’. Method 5: Eval multiple conditions (“eval” and “query” works only with columns ) Here, we get all rows having Salary lesser or equal to 100000 and Age < 40 and their JOB starts with ‘A’ from the dataframe. Python3 # import moduleimport pandas as pd # assign datadataFrame = pd.DataFrame({'Name': [' RACHEL ', ' MONICA ', ' PHOEBE ', ' ROSS ', 'CHANDLER', ' JOEY '], 'Age': [30, 35, 37, 33, 34, 30], 'Salary': [100000, 93000, 88000, 120000, 94000, 95000], 'JOB': ['DESIGNER', 'CHEF', 'MASUS', 'PALENTOLOGY', 'IT', 'ARTIST']}) # filter dataframe display(dataFrame[dataFrame.eval("Salary <=100000 & (Age <40) & JOB.str.startswith('A').values")]) Output: Dataframes are a very essential concept in Python and filtration of data is required can be performed based on various conditions. They can be achieved in any one of the above ways. Ponts to be noted: loc works with column labels and indexes. eval and query works only with columns. Boolean indexing works with values in a column only. Picked Python pandas-dataFrame Python Pandas-exercise Python-pandas 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 How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Defaultdict in Python Python OOPs Concepts Python | os.path.join() method Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n16 Mar, 2021" }, { "code": null, "e": 24827, "s": 24292, "text": "In this article, let’s discuss how to filter pandas dataframe with multiple conditions. There are possibilities of filtering data from Pandas dataframe with multiple conditions during the entire software development. The reason is dataframe may be having multiple columns and multiple rows. Selective display of columns with limited rows is always the expected view of users. To fulfill the user’s expectations and also help in machine deep learning scenarios, filtering of Pandas dataframe with multiple conditions is much necessary." }, { "code": null, "e": 24873, "s": 24827, "text": "Let us see the different ways to do the same." }, { "code": null, "e": 24920, "s": 24873, "text": "Creating a sample dataframe to proceed further" }, { "code": null, "e": 24928, "s": 24920, "text": "Python3" }, { "code": "# import moduleimport pandas as pd # assign datadataFrame = pd.DataFrame({'Name': [' RACHEL ', ' MONICA ', ' PHOEBE ', ' ROSS ', 'CHANDLER', ' JOEY '], 'Age': [30, 35, 37, 33, 34, 30], 'Salary': [100000, 93000, 88000, 120000, 94000, 95000], 'JOB': ['DESIGNER', 'CHEF', 'MASUS', 'PALENTOLOGY', 'IT', 'ARTIST']}) # display dataframedisplay(dataFrame)", "e": 25515, "s": 24928, "text": null }, { "code": null, "e": 25523, "s": 25515, "text": "Output:" }, { "code": null, "e": 25543, "s": 25523, "text": "Method 1: Using loc" }, { "code": null, "e": 25907, "s": 25543, "text": "Here we will get all rows having Salary greater or equal to 100000 and Age < 40 and their JOB starts with ‘D’ from the dataframe. Print the details with Name and their JOB. For the above requirement, we can achieve this by using loc. It is used to access single or more rows and columns by label(s) or by a boolean array. loc works with column labels and indexes." }, { "code": null, "e": 25915, "s": 25907, "text": "Python3" }, { "code": "# import moduleimport pandas as pd # assign datadataFrame = pd.DataFrame({'Name': [' RACHEL ', ' MONICA ', ' PHOEBE ', ' ROSS ', 'CHANDLER', ' JOEY '], 'Age': [30, 35, 37, 33, 34, 30], 'Salary': [100000, 93000, 88000, 120000, 94000, 95000], 'JOB': ['DESIGNER', 'CHEF', 'MASUS', 'PALENTOLOGY', 'IT', 'ARTIST']})# filter dataframedisplay(dataFrame.loc[(dataFrame['Salary']>=100000) & (dataFrame['Age']< 40) & (dataFrame['JOB'].str.startswith('D')), ['Name','JOB']])", "e": 26635, "s": 25915, "text": null }, { "code": null, "e": 26643, "s": 26635, "text": "Output:" }, { "code": null, "e": 26754, "s": 26643, "text": "Output resolves for the given conditions and finally, we are going to show only 2 columns namely Name and JOB." }, { "code": null, "e": 26776, "s": 26754, "text": "Method 2: Using NumPy" }, { "code": null, "e": 26927, "s": 26776, "text": "Here will get all rows having Salary greater or equal to 100000 and Age < 40 and their JOB starts with ‘D’ from the data frame. We need to use NumPy. " }, { "code": null, "e": 26935, "s": 26927, "text": "Python3" }, { "code": "# import moduleimport pandas as pdimport numpy as np # assign datadataFrame = pd.DataFrame({'Name': [' RACHEL ', ' MONICA ', ' PHOEBE ', ' ROSS ', 'CHANDLER', ' JOEY '], 'Age': [30, 35, 37, 33, 34, 30], 'Salary': [100000, 93000, 88000, 120000, 94000, 95000], 'JOB': ['DESIGNER', 'CHEF', 'MASUS', 'PALENTOLOGY', 'IT', 'ARTIST']}) # filter dataframe filtered_values = np.where((dataFrame['Salary']>=100000) & (dataFrame['Age']< 40) & (dataFrame['JOB'].str.startswith('D')))print(filtered_values)display(dataFrame.loc[filtered_values])", "e": 27740, "s": 26935, "text": null }, { "code": null, "e": 27748, "s": 27740, "text": "Output:" }, { "code": null, "e": 28018, "s": 27748, "text": "In the above example, print(filtered_values) will give the output as (array([0], dtype=int64),) which indicates the first row with index value 0 will be the output. After that output will have 1 row with all the columns and it is retrieved as per the given conditions." }, { "code": null, "e": 28081, "s": 28018, "text": "Method 3: Using Query (eval and query works only with columns)" }, { "code": null, "e": 28360, "s": 28081, "text": "In this approach, we get all rows having Salary lesser or equal to 100000 and Age < 40, and their JOB starts with ‘C’ from the dataframe. Its just query the columns of a DataFrame with a single or more Boolean expressions and if multiple, it is having & condition in the middle." }, { "code": null, "e": 28368, "s": 28360, "text": "Python3" }, { "code": "# import moduleimport pandas as pd # assign datadataFrame = pd.DataFrame({'Name': [' RACHEL ', ' MONICA ', ' PHOEBE ', ' ROSS ', 'CHANDLER', ' JOEY '], 'Age': [30, 35, 37, 33, 34, 30], 'Salary': [100000, 93000, 88000, 120000, 94000, 95000], 'JOB': ['DESIGNER', 'CHEF', 'MASUS', 'PALENTOLOGY', 'IT', 'ARTIST']}) # filter dataframe display(dataFrame.query('Salary <= 100000 & Age < 40 & JOB.str.startswith(\"C\").values'))", "e": 29026, "s": 28368, "text": null }, { "code": null, "e": 29036, "s": 29026, "text": "Output: " }, { "code": null, "e": 29159, "s": 29036, "text": "Method 4: pandas Boolean indexing multiple conditions standard way (“Boolean indexing” works with values in a column only)" }, { "code": null, "e": 29430, "s": 29159, "text": "In this approach, we get all rows having Salary lesser or equal to 100000 and Age < 40 and their JOB starts with ‘P’ from the dataframe. In order to select the subset of data using the values in the dataframe and applying Boolean conditions, we need to follow these ways" }, { "code": null, "e": 29438, "s": 29430, "text": "Python3" }, { "code": "# import moduleimport pandas as pd # assign datadataFrame = pd.DataFrame({'Name': [' RACHEL ', ' MONICA ', ' PHOEBE ', ' ROSS ', 'CHANDLER', ' JOEY '], 'Age': [30, 35, 37, 33, 34, 30], 'Salary': [100000, 93000, 88000, 120000, 94000, 95000], 'JOB': ['DESIGNER', 'CHEF', 'MASUS', 'PALENTOLOGY', 'IT', 'ARTIST']}) # filter dataframe display(dataFrame[(dataFrame['Salary']>=100000) & (dataFrame['Age']<40) & dataFrame['JOB'].str.startswith('P')][['Name','Age','Salary']])", "e": 30144, "s": 29438, "text": null }, { "code": null, "e": 30153, "s": 30144, "text": "Output: " }, { "code": null, "e": 30294, "s": 30153, "text": "We are mentioning a list of columns that need to be retrieved along with the Boolean conditions and since many conditions, it is having ‘&’." }, { "code": null, "e": 30376, "s": 30294, "text": "Method 5: Eval multiple conditions (“eval” and “query” works only with columns )" }, { "code": null, "e": 30502, "s": 30376, "text": "Here, we get all rows having Salary lesser or equal to 100000 and Age < 40 and their JOB starts with ‘A’ from the dataframe. " }, { "code": null, "e": 30510, "s": 30502, "text": "Python3" }, { "code": "# import moduleimport pandas as pd # assign datadataFrame = pd.DataFrame({'Name': [' RACHEL ', ' MONICA ', ' PHOEBE ', ' ROSS ', 'CHANDLER', ' JOEY '], 'Age': [30, 35, 37, 33, 34, 30], 'Salary': [100000, 93000, 88000, 120000, 94000, 95000], 'JOB': ['DESIGNER', 'CHEF', 'MASUS', 'PALENTOLOGY', 'IT', 'ARTIST']}) # filter dataframe display(dataFrame[dataFrame.eval(\"Salary <=100000 & (Age <40) & JOB.str.startswith('A').values\")])", "e": 31177, "s": 30510, "text": null }, { "code": null, "e": 31185, "s": 31177, "text": "Output:" }, { "code": null, "e": 31386, "s": 31185, "text": "Dataframes are a very essential concept in Python and filtration of data is required can be performed based on various conditions. They can be achieved in any one of the above ways. Ponts to be noted:" }, { "code": null, "e": 31428, "s": 31386, "text": "loc works with column labels and indexes." }, { "code": null, "e": 31468, "s": 31428, "text": "eval and query works only with columns." }, { "code": null, "e": 31521, "s": 31468, "text": "Boolean indexing works with values in a column only." }, { "code": null, "e": 31528, "s": 31521, "text": "Picked" }, { "code": null, "e": 31552, "s": 31528, "text": "Python pandas-dataFrame" }, { "code": null, "e": 31575, "s": 31552, "text": "Python Pandas-exercise" }, { "code": null, "e": 31589, "s": 31575, "text": "Python-pandas" }, { "code": null, "e": 31596, "s": 31589, "text": "Python" }, { "code": null, "e": 31694, "s": 31596, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31703, "s": 31694, "text": "Comments" }, { "code": null, "e": 31716, "s": 31703, "text": "Old Comments" }, { "code": null, "e": 31748, "s": 31716, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 31803, "s": 31748, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 31859, "s": 31803, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 31901, "s": 31859, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 31943, "s": 31901, "text": "Check if element exists in list in Python" }, { "code": null, "e": 31982, "s": 31943, "text": "Python | Get unique values from a list" }, { "code": null, "e": 32004, "s": 31982, "text": "Defaultdict in Python" }, { "code": null, "e": 32025, "s": 32004, "text": "Python OOPs Concepts" }, { "code": null, "e": 32056, "s": 32025, "text": "Python | os.path.join() method" } ]
Tryit Editor v3.7
Tryit: HTML border color
[]
Convert a given Binary Tree to Doubly Linked List (Set 1) in C++
In this tutorial, we will be discussing a program to convert a binary tree to a doubly linked list. For this we will be provided with a binary tree. Our task is to convert it into a doubly linked list such that the left and right pointers become the previous and next pointers. Also the sequential order of the doubly linked list must be equal to the inorder traversal of the binary tree. For this we are having a very straight forward approach. We will be traversing the binary tree in in order way making the nodes of the doubly linked list along with and finally making the left and right to be the previous and next nodes respectively. Live Demo #include <iostream> using namespace std; //node structure of binary tree struct node{ int data; node* left; node* right; }; //traversing and making nodes for //doubly linked list void binarytodll(node *root, node **head){ if (root == NULL) return; static node* prev = NULL; //converting left subtree binarytodll(root->left, head); if (prev == NULL) *head = root; else { root->left = prev; prev->right = root; } prev = root; //converting right subtree binarytodll(root->right, head); } //allocating a new node node* newNode(int data) { node* new_node = new node; new_node->data = data; new_node->left = new_node->right = NULL; return (new_node); } //printing nodes of doubly linked list void print_dll(node *node){ while (node!=NULL) { cout << node->data << " "; node = node->right; } } int main(){ node *root = newNode(10); root->left = newNode(12); root->right = newNode(15); root->left->left = newNode(25); root->left->right = newNode(30); root->right->left = newNode(36); node *head = NULL; binarytodll(root, &head); print_dll(head); return 0; } 25 12 30 10 36 15
[ { "code": null, "e": 1162, "s": 1062, "text": "In this tutorial, we will be discussing a program to convert a binary tree to a doubly linked list." }, { "code": null, "e": 1451, "s": 1162, "text": "For this we will be provided with a binary tree. Our task is to convert it into a doubly linked list such that the left and right pointers become the previous and next pointers. Also the sequential order of the doubly linked list must be equal to the inorder traversal of the binary tree." }, { "code": null, "e": 1702, "s": 1451, "text": "For this we are having a very straight forward approach. We will be traversing the binary tree in in order way making the nodes of the doubly linked list along with and finally making the left and right to be the previous and next nodes respectively." }, { "code": null, "e": 1713, "s": 1702, "text": " Live Demo" }, { "code": null, "e": 2885, "s": 1713, "text": "#include <iostream>\nusing namespace std;\n//node structure of binary tree\nstruct node{\n int data;\n node* left;\n node* right;\n};\n//traversing and making nodes for\n//doubly linked list\nvoid binarytodll(node *root, node **head){\n if (root == NULL)\n return;\n static node* prev = NULL;\n //converting left subtree\n binarytodll(root->left, head);\n if (prev == NULL)\n *head = root;\n else {\n root->left = prev;\n prev->right = root;\n }\n prev = root;\n //converting right subtree\n binarytodll(root->right, head);\n}\n//allocating a new node\nnode* newNode(int data) {\n node* new_node = new node;\n new_node->data = data;\n new_node->left = new_node->right = NULL;\n return (new_node);\n}\n//printing nodes of doubly linked list\nvoid print_dll(node *node){\n while (node!=NULL) {\n cout << node->data << \" \";\n node = node->right;\n }\n}\nint main(){\n node *root = newNode(10);\n root->left = newNode(12);\n root->right = newNode(15);\n root->left->left = newNode(25);\n root->left->right = newNode(30);\n root->right->left = newNode(36);\n node *head = NULL;\n binarytodll(root, &head);\n print_dll(head);\n return 0;\n}" }, { "code": null, "e": 2903, "s": 2885, "text": "25 12 30 10 36 15" } ]