title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Magic Tables in SQL Server
11 Jun, 2021 Magic tables are the temporary logical tables that are created by the SQL server whenever there are insertion or deletion or update( D.M.L) operations. The recently performed operation on the rows gets stored in magic tables automatically. These are not physical table but they are just temporary internal tables. These magic tables can’t be retrieved directly, we need to use triggers to access these magic tables to get the deleted and inserted rows. When the following operations are done : INSERT – The recently inserted row gets added to the INSERTED magic table. DELETE –The recently deleted row gets added to the DELETED magic table. UPDATE –The updated row gets stored in INSERTED magic table and the old row or previous row gets stored in the DELETED magic table. Let us see how this works by using MSSQL as a server: Creating a database :Creating a database GeeksForGeeks by using the following SQL query as follows. CREATE DATABASE GeeksForGeeks; Using the database :Using the database student using the following SQL query as follows. USE GeeksForGeeks; Creating table students with SQL query as follows: CREATE TABLE students ( stu_id varchar(10), stu_name varchar(20), branch varchar(20) ); Verifying the database :To view the description of the table in the database GeeksForGeeks using the following SQL query as follows. EXEC sp_columns students; Inserting data into the table :Inserting rows into students table using the following SQL query as follows: INSERT INTO students VALUES ('1901401','DEVA','C.S'), ('1901402','HARSH','C.S'), ('1901403','ABHISHEK','C.S'), ('1901404','GARVIT','C.S'), ('1901405','SAMPATH','C.S'); Verifying the inserted data :Viewing the table after inserting rows by using the following SQL query as follows. SELECT * FROM students; Creating a trigger T1 on insert operation : CREATE TRIGGER T1 ON students AFTER INSERT AS BEGIN SELECT * FROM INSERTED END Inserting entries to check how trigger retrieves INSERTED magic table : INSERT INTO students VALUES ('1901406','PRADEEP','C.S'), ('1901407','DEVESH','C.S'); SELECT* FROM students ; Creating a trigger T2 on delete operation : CREATE TRIGGER T2 ON students AFTER DELETE AS BEGIN SELECT * FROM DELETED END Deleting entry to check how trigger retrieves DELETED magic table : DELETE FROM students WHERE stu_name = 'PRADEEP'; SELECT* FROM students ; Creating a trigger T3 on update operation : CREATE TRIGGER T3 ON students AFTER UPDATE AS BEGIN SELECT * FROM DELETED SELECT* FROM INSERTED END Updating entry to check how trigger retrieves DELETED, INSERTED magic tables since we find an old entry in a DELETED and updated entry in the INSERTED magic table : UPDATE students SET stu_name= 'DEVANSH' WHERE stu_id = '1901401' SELECT* FROM students DBMS-SQL Picked SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Jun, 2021" }, { "code": null, "e": 482, "s": 28, "text": "Magic tables are the temporary logical tables that are created by the SQL server whenever there are insertion or deletion or update( D.M.L) operations. The recently performed operation on the rows gets stored in magic tables automatically. These are not physical table but they are just temporary internal tables. These magic tables can’t be retrieved directly, we need to use triggers to access these magic tables to get the deleted and inserted rows." }, { "code": null, "e": 524, "s": 482, "text": "When the following operations are done : " }, { "code": null, "e": 600, "s": 524, "text": "INSERT – The recently inserted row gets added to the INSERTED magic table. " }, { "code": null, "e": 673, "s": 600, "text": "DELETE –The recently deleted row gets added to the DELETED magic table. " }, { "code": null, "e": 805, "s": 673, "text": "UPDATE –The updated row gets stored in INSERTED magic table and the old row or previous row gets stored in the DELETED magic table." }, { "code": null, "e": 859, "s": 805, "text": "Let us see how this works by using MSSQL as a server:" }, { "code": null, "e": 959, "s": 859, "text": "Creating a database :Creating a database GeeksForGeeks by using the following SQL query as follows." }, { "code": null, "e": 990, "s": 959, "text": "CREATE DATABASE GeeksForGeeks;" }, { "code": null, "e": 1079, "s": 990, "text": "Using the database :Using the database student using the following SQL query as follows." }, { "code": null, "e": 1098, "s": 1079, "text": "USE GeeksForGeeks;" }, { "code": null, "e": 1149, "s": 1098, "text": "Creating table students with SQL query as follows:" }, { "code": null, "e": 1241, "s": 1149, "text": "CREATE TABLE students\n( \n stu_id varchar(10),\n stu_name varchar(20),\n branch varchar(20)\n);" }, { "code": null, "e": 1374, "s": 1241, "text": "Verifying the database :To view the description of the table in the database GeeksForGeeks using the following SQL query as follows." }, { "code": null, "e": 1400, "s": 1374, "text": "EXEC sp_columns students;" }, { "code": null, "e": 1508, "s": 1400, "text": "Inserting data into the table :Inserting rows into students table using the following SQL query as follows:" }, { "code": null, "e": 1676, "s": 1508, "text": "INSERT INTO students VALUES\n('1901401','DEVA','C.S'),\n('1901402','HARSH','C.S'),\n('1901403','ABHISHEK','C.S'),\n('1901404','GARVIT','C.S'),\n('1901405','SAMPATH','C.S');" }, { "code": null, "e": 1789, "s": 1676, "text": "Verifying the inserted data :Viewing the table after inserting rows by using the following SQL query as follows." }, { "code": null, "e": 1813, "s": 1789, "text": "SELECT * FROM students;" }, { "code": null, "e": 1857, "s": 1813, "text": "Creating a trigger T1 on insert operation :" }, { "code": null, "e": 1936, "s": 1857, "text": "CREATE TRIGGER T1 ON students\nAFTER INSERT\nAS\nBEGIN\nSELECT * FROM INSERTED\nEND" }, { "code": null, "e": 2008, "s": 1936, "text": "Inserting entries to check how trigger retrieves INSERTED magic table :" }, { "code": null, "e": 2117, "s": 2008, "text": "INSERT INTO students VALUES\n('1901406','PRADEEP','C.S'),\n('1901407','DEVESH','C.S');\nSELECT* FROM students ;" }, { "code": null, "e": 2161, "s": 2117, "text": "Creating a trigger T2 on delete operation :" }, { "code": null, "e": 2239, "s": 2161, "text": "CREATE TRIGGER T2 ON students\nAFTER DELETE\nAS\nBEGIN\nSELECT * FROM DELETED\nEND" }, { "code": null, "e": 2307, "s": 2239, "text": "Deleting entry to check how trigger retrieves DELETED magic table :" }, { "code": null, "e": 2380, "s": 2307, "text": "DELETE FROM students\nWHERE stu_name = 'PRADEEP';\nSELECT* FROM students ;" }, { "code": null, "e": 2424, "s": 2380, "text": "Creating a trigger T3 on update operation :" }, { "code": null, "e": 2525, "s": 2424, "text": "CREATE TRIGGER T3 ON students\nAFTER UPDATE\nAS\nBEGIN\nSELECT * FROM DELETED\nSELECT* FROM INSERTED \nEND" }, { "code": null, "e": 2690, "s": 2525, "text": "Updating entry to check how trigger retrieves DELETED, INSERTED magic tables since we find an old entry in a DELETED and updated entry in the INSERTED magic table :" }, { "code": null, "e": 2778, "s": 2690, "text": "UPDATE students SET stu_name= 'DEVANSH' \nWHERE stu_id = '1901401'\nSELECT* FROM students" }, { "code": null, "e": 2787, "s": 2778, "text": "DBMS-SQL" }, { "code": null, "e": 2794, "s": 2787, "text": "Picked" }, { "code": null, "e": 2805, "s": 2794, "text": "SQL-Server" }, { "code": null, "e": 2809, "s": 2805, "text": "SQL" }, { "code": null, "e": 2813, "s": 2809, "text": "SQL" } ]
Program to calculate Electricity Bill
08 Nov, 2021 Given an integer U denoting the amount of KWh units of electricity consumed, the task is to calculate the electricity bill with the help of the below charges: 1 to 100 units – 100 to 200 units – 200 to 300 units – above 300 units – Examples: Input: U = 250 Output: 3500 Explanation: Charge for the first 100 units – 10*100 = 1000 Charge for the 100 to 200 units – 15*100 = 1500 Charge for the 200 to 250 units – 20*50 = 1000 Total Electricity Bill = 1000 + 1500 + 1000 = 3500Input: U = 95 Output: 950 Explanation: Charge for the first 100 units – 10*95 = 950 Total Electricity Bill = 950 Approach: The idea is to identify the charge bar in which it falls and then calculate the bill according to the charges mentioned above. Below is the illustration of the steps: Check units consumed is less than equal to the 100, If yes then the total electricity bill will be: Else if, check that units consumed is less than equal to the 200, if yes then total electricity bill will be: Else if, check that units consumed is less than equal to the 300, if yes then total electricity bill will be: Else if, check that units consumed greater than 300, if yes then total electricity bill will be: Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to calculate the// electricity bill#include<bits/stdc++.h>using namespace std; // Function to calculate the// electricity billint calculateBill(int units){ // Condition to find the charges // bar in which the units consumed // is fall if (units <= 100) { return units * 10; } else if (units <= 200) { return (100 * 10) + (units - 100) * 15; } else if (units <= 300) { return (100 * 10) + (100 * 15) + (units - 200) * 20; } else if (units > 300) { return (100 * 10) + (100 * 15) + (100 * 20) + (units - 300) * 25; } return 0;} // Driver Codeint main(){ int units = 250; cout << calculateBill(units);} // This code is contributed by spp____ // Java implementation to calculate the// electricity bill import java.util.*; class ComputeElectricityBill { // Function to calculate the // electricity bill public static int calculateBill(int units) { // Condition to find the charges // bar in which the units consumed // is fall if (units <= 100) { return units * 10; } else if (units <= 200) { return (100 * 10) + (units - 100) * 15; } else if (units <= 300) { return (100 * 10) + (100 * 15) + (units - 200) * 20; } else if (units > 300) { return (100 * 10) + (100 * 15) + (100 * 20) + (units - 300) * 25; } return 0; } // Driver Code public static void main(String args[]) { int units = 250; System.out.println( calculateBill(units)); }} # Python3 implementation to calculate the# electricity bill # Function to calculate the# electricity billdef calculateBill(units): # Condition to find the charges # bar in which the units consumed # is fall if (units <= 100): return units * 10; elif (units <= 200): return ((100 * 10) + (units - 100) * 15); elif (units <= 300): return ((100 * 10) + (100 * 15) + (units - 200) * 20); elif (units > 300): return ((100 * 10) + (100 * 15) + (100 * 20) + (units - 300) * 25); return 0; # Driver Codeunits = 250;print(calculateBill(units)); # This code is contributed by Code_Mech // C# implementation to calculate the// electricity billusing System; class ComputeElectricityBill{ // Function to calculate the// electricity billpublic static int calculateBill(int units){ // Condition to find the charges // bar in which the units consumed // is fall if (units <= 100) { return units * 10; } else if (units <= 200) { return (100 * 10) + (units - 100) * 15; } else if (units <= 300) { return (100 * 10) + (100 * 15) + (units - 200) * 20; } else if (units > 300) { return (100 * 10) + (100 * 15) + (100 * 20) + (units - 300) * 25; } return 0;} // Driver Codepublic static void Main(String []args){ int units = 250; Console.WriteLine(calculateBill(units));}} // This code is contributed by spp____ <script> // Javascript implementation to calculate the// electricity bill // Function to calculate the// electricity billfunction calculateBill(units){ // Condition to find the charges // bar in which the units consumed // is fall if (units <= 100) { return units * 10; } else if (units <= 200) { return (100 * 10) + (units - 100) * 15; } else if (units <= 300) { return (100 * 10) + (100 * 15) + (units - 200) * 20; } else if (units > 300) { return (100 * 10) + (100 * 15) + (100 * 20) + (units - 300) * 25; } return 0;} // Driver Codevar units = 250; document.write(calculateBill(units)); // This code is contributed by Khushboogoyal499 </script> 3500 Time Complexity: O(1) Auxiliary Space: O(1) spp____ Code_Mech khushboogoyal499 sushmitamittal1329 C Language C# C++ Java Mathematical Programming Language Python School Programming Mathematical Java CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Function Pointer in C std::string class in C++ Unordered Sets in C++ Standard Template Library What is the purpose of a function prototype? Enumeration (or enum) in C Difference between Abstract Class and Interface in C# C# | Multiple inheritance using interfaces C# Dictionary with examples C# | How to check whether a List contains a specified element C# | IsNullOrEmpty() Method
[ { "code": null, "e": 53, "s": 25, "text": "\n08 Nov, 2021" }, { "code": null, "e": 214, "s": 53, "text": "Given an integer U denoting the amount of KWh units of electricity consumed, the task is to calculate the electricity bill with the help of the below charges: " }, { "code": null, "e": 232, "s": 214, "text": "1 to 100 units – " }, { "code": null, "e": 252, "s": 232, "text": "100 to 200 units – " }, { "code": null, "e": 272, "s": 252, "text": "200 to 300 units – " }, { "code": null, "e": 291, "s": 272, "text": "above 300 units – " }, { "code": null, "e": 303, "s": 291, "text": "Examples: " }, { "code": null, "e": 651, "s": 303, "text": "Input: U = 250 Output: 3500 Explanation: Charge for the first 100 units – 10*100 = 1000 Charge for the 100 to 200 units – 15*100 = 1500 Charge for the 200 to 250 units – 20*50 = 1000 Total Electricity Bill = 1000 + 1500 + 1000 = 3500Input: U = 95 Output: 950 Explanation: Charge for the first 100 units – 10*95 = 950 Total Electricity Bill = 950 " }, { "code": null, "e": 832, "s": 653, "text": "Approach: The idea is to identify the charge bar in which it falls and then calculate the bill according to the charges mentioned above. Below is the illustration of the steps: " }, { "code": null, "e": 933, "s": 832, "text": "Check units consumed is less than equal to the 100, If yes then the total electricity bill will be: " }, { "code": null, "e": 1046, "s": 935, "text": "Else if, check that units consumed is less than equal to the 200, if yes then total electricity bill will be: " }, { "code": null, "e": 1159, "s": 1048, "text": "Else if, check that units consumed is less than equal to the 300, if yes then total electricity bill will be: " }, { "code": null, "e": 1259, "s": 1161, "text": "Else if, check that units consumed greater than 300, if yes then total electricity bill will be: " }, { "code": null, "e": 1314, "s": 1261, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1318, "s": 1314, "text": "C++" }, { "code": null, "e": 1323, "s": 1318, "text": "Java" }, { "code": null, "e": 1331, "s": 1323, "text": "Python3" }, { "code": null, "e": 1334, "s": 1331, "text": "C#" }, { "code": null, "e": 1345, "s": 1334, "text": "Javascript" }, { "code": "// C++ implementation to calculate the// electricity bill#include<bits/stdc++.h>using namespace std; // Function to calculate the// electricity billint calculateBill(int units){ // Condition to find the charges // bar in which the units consumed // is fall if (units <= 100) { return units * 10; } else if (units <= 200) { return (100 * 10) + (units - 100) * 15; } else if (units <= 300) { return (100 * 10) + (100 * 15) + (units - 200) * 20; } else if (units > 300) { return (100 * 10) + (100 * 15) + (100 * 20) + (units - 300) * 25; } return 0;} // Driver Codeint main(){ int units = 250; cout << calculateBill(units);} // This code is contributed by spp____", "e": 2173, "s": 1345, "text": null }, { "code": "// Java implementation to calculate the// electricity bill import java.util.*; class ComputeElectricityBill { // Function to calculate the // electricity bill public static int calculateBill(int units) { // Condition to find the charges // bar in which the units consumed // is fall if (units <= 100) { return units * 10; } else if (units <= 200) { return (100 * 10) + (units - 100) * 15; } else if (units <= 300) { return (100 * 10) + (100 * 15) + (units - 200) * 20; } else if (units > 300) { return (100 * 10) + (100 * 15) + (100 * 20) + (units - 300) * 25; } return 0; } // Driver Code public static void main(String args[]) { int units = 250; System.out.println( calculateBill(units)); }}", "e": 3204, "s": 2173, "text": null }, { "code": "# Python3 implementation to calculate the# electricity bill # Function to calculate the# electricity billdef calculateBill(units): # Condition to find the charges # bar in which the units consumed # is fall if (units <= 100): return units * 10; elif (units <= 200): return ((100 * 10) + (units - 100) * 15); elif (units <= 300): return ((100 * 10) + (100 * 15) + (units - 200) * 20); elif (units > 300): return ((100 * 10) + (100 * 15) + (100 * 20) + (units - 300) * 25); return 0; # Driver Codeunits = 250;print(calculateBill(units)); # This code is contributed by Code_Mech", "e": 3965, "s": 3204, "text": null }, { "code": "// C# implementation to calculate the// electricity billusing System; class ComputeElectricityBill{ // Function to calculate the// electricity billpublic static int calculateBill(int units){ // Condition to find the charges // bar in which the units consumed // is fall if (units <= 100) { return units * 10; } else if (units <= 200) { return (100 * 10) + (units - 100) * 15; } else if (units <= 300) { return (100 * 10) + (100 * 15) + (units - 200) * 20; } else if (units > 300) { return (100 * 10) + (100 * 15) + (100 * 20) + (units - 300) * 25; } return 0;} // Driver Codepublic static void Main(String []args){ int units = 250; Console.WriteLine(calculateBill(units));}} // This code is contributed by spp____", "e": 4851, "s": 3965, "text": null }, { "code": "<script> // Javascript implementation to calculate the// electricity bill // Function to calculate the// electricity billfunction calculateBill(units){ // Condition to find the charges // bar in which the units consumed // is fall if (units <= 100) { return units * 10; } else if (units <= 200) { return (100 * 10) + (units - 100) * 15; } else if (units <= 300) { return (100 * 10) + (100 * 15) + (units - 200) * 20; } else if (units > 300) { return (100 * 10) + (100 * 15) + (100 * 20) + (units - 300) * 25; } return 0;} // Driver Codevar units = 250; document.write(calculateBill(units)); // This code is contributed by Khushboogoyal499 </script>", "e": 5702, "s": 4851, "text": null }, { "code": null, "e": 5707, "s": 5702, "text": "3500" }, { "code": null, "e": 5731, "s": 5709, "text": "Time Complexity: O(1)" }, { "code": null, "e": 5753, "s": 5731, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 5761, "s": 5753, "text": "spp____" }, { "code": null, "e": 5771, "s": 5761, "text": "Code_Mech" }, { "code": null, "e": 5788, "s": 5771, "text": "khushboogoyal499" }, { "code": null, "e": 5807, "s": 5788, "text": "sushmitamittal1329" }, { "code": null, "e": 5818, "s": 5807, "text": "C Language" }, { "code": null, "e": 5821, "s": 5818, "text": "C#" }, { "code": null, "e": 5825, "s": 5821, "text": "C++" }, { "code": null, "e": 5830, "s": 5825, "text": "Java" }, { "code": null, "e": 5843, "s": 5830, "text": "Mathematical" }, { "code": null, "e": 5864, "s": 5843, "text": "Programming Language" }, { "code": null, "e": 5871, "s": 5864, "text": "Python" }, { "code": null, "e": 5890, "s": 5871, "text": "School Programming" }, { "code": null, "e": 5903, "s": 5890, "text": "Mathematical" }, { "code": null, "e": 5908, "s": 5903, "text": "Java" }, { "code": null, "e": 5912, "s": 5908, "text": "CPP" }, { "code": null, "e": 6010, "s": 5912, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6032, "s": 6010, "text": "Function Pointer in C" }, { "code": null, "e": 6057, "s": 6032, "text": "std::string class in C++" }, { "code": null, "e": 6105, "s": 6057, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 6150, "s": 6105, "text": "What is the purpose of a function prototype?" }, { "code": null, "e": 6177, "s": 6150, "text": "Enumeration (or enum) in C" }, { "code": null, "e": 6231, "s": 6177, "text": "Difference between Abstract Class and Interface in C#" }, { "code": null, "e": 6274, "s": 6231, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 6302, "s": 6274, "text": "C# Dictionary with examples" }, { "code": null, "e": 6364, "s": 6302, "text": "C# | How to check whether a List contains a specified element" } ]
Youden plot
09 Mar, 2021 A Youden Plot is a scatter plot representation of results obtained from N laboratories on two similar materials. The main objective of the plot is to find out which of the N labs gave unreliable or faulty results. Structure of the plot Fig 1: Structure of a youden plot As shown in Fig 1, the following elements are present in a Youden plot: x-axis: readings of sample I from N labs.y-axis: readings of sample II from N labs.Two parallel lines are drawn parallel to the x & y-axis in such a way that the data points on both sides of the line are same.Manhattan Median: The point where the two parallel lines intersect each other is known as the Manhattan median. A 45° reference line is drawn passing this point. There is a 95% coverage circle around the manhattan median. x-axis: readings of sample I from N labs. y-axis: readings of sample II from N labs. Two parallel lines are drawn parallel to the x & y-axis in such a way that the data points on both sides of the line are same. Manhattan Median: The point where the two parallel lines intersect each other is known as the Manhattan median. A 45° reference line is drawn passing this point. There is a 95% coverage circle around the manhattan median. Intuition Youden plots help in understanding the variations that occur in the measurements of two similar samples. It tells as about two types of variability: [As shown in Fig 2] Within-Lab variability: The variations in the results when multiple tests are performed on the two samples (A & B) within the same lab. It leads to repeatability problems.Between-Lab variability: The variations in the results among different labs performing tests on the same two samples (A & B). It leads to reproducability problems. Within-Lab variability: The variations in the results when multiple tests are performed on the two samples (A & B) within the same lab. It leads to repeatability problems. Between-Lab variability: The variations in the results among different labs performing tests on the same two samples (A & B). It leads to reproducability problems. Fig 2: Lab variabilities shown in Youden plot The plot also helps in detecting the presence of various types of errors like systematic and random errors. Systematic Error: These errors occur due to inconsistencies present in the experiment like faulty or uncalibrated equipment. They are fixable as we can find the source of the error by replicating the experiments. These are usually found within one lab performing the experiment. Random Error: These errors are unsystematic as they occur at random. They cannot be fixed due to their unpredictable nature. If random error >> systematic error, then the data points will cluster in the circle around the manhattan median. They lie further away from the 45° reference line. If systematic error >> random error, then the data points will cluster around the 45° reference line in an elliptical pattern. Any data points lying outside the coverage circle are called Outliers and they contribute to total error. Requirement The major requirement of this plot lies in the medical field mainly focusing on quality control. It helps in identifying various things like: Inconsistencies like repeatability and reproducability. Which lab results are inaccurate (outliers) Comparisons among and between lab experiments. Code Implementation in R R YoudenPlot <- function(A, B){ plot(A,B,asp = 1, xlab = "A", ylab = "B", pch=".") # manhattan median of sample A MMofA <- median(A) # manhattan median of sample B MMofB <- median(B) # in-built function to create horizontal and vertical lines in the plot abline(h = MMofB, v = MMofA) # in-built function to create the circle around the manhattan median. curve(x-(MMofA-MMofB),add=TRUE) d <- mean(A-B) d_prime <- A-B-d r <- 2.45*mean(abs(d_prime))*sqrt(pi)/2 t <- seq(0,2*pi,by=0.01) x <- r*cos(t)+MMofA y <- r*sin(t)+MMofB lines(x,y)} # rnorm (data_points, mean, variation)A <- rnorm(500,10,100)B <- rnorm(500,10,100) # Function call to create a sample youden plot.YoudenPlot(A,B) Output Fig 3: Code output of the sample youden plot Youden plot is a very powerful graphical tool used to analyse inter-laboratory data and help in finding within as well as between laboratory errors. Moreover, the Youden plot is considered to be useful for analyzing the performance of laboratories. It is prominently used in the fields of medical research for the purpose of quality assessment. For any doubt/query, comment below. ML-Statistics Machine Learning R Language Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Mar, 2021" }, { "code": null, "e": 243, "s": 28, "text": "A Youden Plot is a scatter plot representation of results obtained from N laboratories on two similar materials. The main objective of the plot is to find out which of the N labs gave unreliable or faulty results. " }, { "code": null, "e": 265, "s": 243, "text": "Structure of the plot" }, { "code": null, "e": 299, "s": 265, "text": "Fig 1: Structure of a youden plot" }, { "code": null, "e": 372, "s": 299, "text": "As shown in Fig 1, the following elements are present in a Youden plot: " }, { "code": null, "e": 804, "s": 372, "text": "x-axis: readings of sample I from N labs.y-axis: readings of sample II from N labs.Two parallel lines are drawn parallel to the x & y-axis in such a way that the data points on both sides of the line are same.Manhattan Median: The point where the two parallel lines intersect each other is known as the Manhattan median. A 45° reference line is drawn passing this point. There is a 95% coverage circle around the manhattan median." }, { "code": null, "e": 846, "s": 804, "text": "x-axis: readings of sample I from N labs." }, { "code": null, "e": 889, "s": 846, "text": "y-axis: readings of sample II from N labs." }, { "code": null, "e": 1016, "s": 889, "text": "Two parallel lines are drawn parallel to the x & y-axis in such a way that the data points on both sides of the line are same." }, { "code": null, "e": 1180, "s": 1016, "text": "Manhattan Median: The point where the two parallel lines intersect each other is known as the Manhattan median. A 45° reference line is drawn passing this point. " }, { "code": null, "e": 1240, "s": 1180, "text": "There is a 95% coverage circle around the manhattan median." }, { "code": null, "e": 1250, "s": 1240, "text": "Intuition" }, { "code": null, "e": 1419, "s": 1250, "text": "Youden plots help in understanding the variations that occur in the measurements of two similar samples. It tells as about two types of variability: [As shown in Fig 2]" }, { "code": null, "e": 1754, "s": 1419, "text": "Within-Lab variability: The variations in the results when multiple tests are performed on the two samples (A & B) within the same lab. It leads to repeatability problems.Between-Lab variability: The variations in the results among different labs performing tests on the same two samples (A & B). It leads to reproducability problems." }, { "code": null, "e": 1926, "s": 1754, "text": "Within-Lab variability: The variations in the results when multiple tests are performed on the two samples (A & B) within the same lab. It leads to repeatability problems." }, { "code": null, "e": 2090, "s": 1926, "text": "Between-Lab variability: The variations in the results among different labs performing tests on the same two samples (A & B). It leads to reproducability problems." }, { "code": null, "e": 2136, "s": 2090, "text": "Fig 2: Lab variabilities shown in Youden plot" }, { "code": null, "e": 2244, "s": 2136, "text": "The plot also helps in detecting the presence of various types of errors like systematic and random errors." }, { "code": null, "e": 2524, "s": 2244, "text": "Systematic Error: These errors occur due to inconsistencies present in the experiment like faulty or uncalibrated equipment. They are fixable as we can find the source of the error by replicating the experiments. These are usually found within one lab performing the experiment. " }, { "code": null, "e": 2650, "s": 2524, "text": "Random Error: These errors are unsystematic as they occur at random. They cannot be fixed due to their unpredictable nature. " }, { "code": null, "e": 2815, "s": 2650, "text": "If random error >> systematic error, then the data points will cluster in the circle around the manhattan median. They lie further away from the 45° reference line." }, { "code": null, "e": 2942, "s": 2815, "text": "If systematic error >> random error, then the data points will cluster around the 45° reference line in an elliptical pattern." }, { "code": null, "e": 3049, "s": 2942, "text": "Any data points lying outside the coverage circle are called Outliers and they contribute to total error. " }, { "code": null, "e": 3061, "s": 3049, "text": "Requirement" }, { "code": null, "e": 3203, "s": 3061, "text": "The major requirement of this plot lies in the medical field mainly focusing on quality control. It helps in identifying various things like:" }, { "code": null, "e": 3259, "s": 3203, "text": "Inconsistencies like repeatability and reproducability." }, { "code": null, "e": 3303, "s": 3259, "text": "Which lab results are inaccurate (outliers)" }, { "code": null, "e": 3350, "s": 3303, "text": "Comparisons among and between lab experiments." }, { "code": null, "e": 3375, "s": 3350, "text": "Code Implementation in R" }, { "code": null, "e": 3377, "s": 3375, "text": "R" }, { "code": "YoudenPlot <- function(A, B){ plot(A,B,asp = 1, xlab = \"A\", ylab = \"B\", pch=\".\") # manhattan median of sample A MMofA <- median(A) # manhattan median of sample B MMofB <- median(B) # in-built function to create horizontal and vertical lines in the plot abline(h = MMofB, v = MMofA) # in-built function to create the circle around the manhattan median. curve(x-(MMofA-MMofB),add=TRUE) d <- mean(A-B) d_prime <- A-B-d r <- 2.45*mean(abs(d_prime))*sqrt(pi)/2 t <- seq(0,2*pi,by=0.01) x <- r*cos(t)+MMofA y <- r*sin(t)+MMofB lines(x,y)} # rnorm (data_points, mean, variation)A <- rnorm(500,10,100)B <- rnorm(500,10,100) # Function call to create a sample youden plot.YoudenPlot(A,B)", "e": 4137, "s": 3377, "text": null }, { "code": null, "e": 4144, "s": 4137, "text": "Output" }, { "code": null, "e": 4189, "s": 4144, "text": "Fig 3: Code output of the sample youden plot" }, { "code": null, "e": 4570, "s": 4189, "text": "Youden plot is a very powerful graphical tool used to analyse inter-laboratory data and help in finding within as well as between laboratory errors. Moreover, the Youden plot is considered to be useful for analyzing the performance of laboratories. It is prominently used in the fields of medical research for the purpose of quality assessment. For any doubt/query, comment below." }, { "code": null, "e": 4584, "s": 4570, "text": "ML-Statistics" }, { "code": null, "e": 4601, "s": 4584, "text": "Machine Learning" }, { "code": null, "e": 4612, "s": 4601, "text": "R Language" }, { "code": null, "e": 4629, "s": 4612, "text": "Machine Learning" } ]
Maximize length of the String by concatenating characters from an Array of Strings
01 Jul, 2022 Given an array of strings arr[], the task is to find the maximum possible length of a string of distinct characters that can be generated by concatenating of the subsequence of the given array. Examples: Input: arr[] = {“ab”, “cd”, “ab”} Output: 4 Explanation: All possible combinations are {“”, “ab”, “cd”, “abcd”, “cdab”}. Therefore, maximum length possible is 4. Input: arr[] = {“abcdefgh”} Output: 8 Explanation: All possible combinations are: “”, “abcdefgh”. Therefore, the maximum length possible is 8. Approach: The idea is to use Recursion. Follow the steps below to solve the problem: Iterate from left to right and consider every string as a possible starting substring. Initialize a HashSet to store the distinct characters encountered so far. Once a string is selected as starting substring, check for every remaining string, if it only contains characters which have not occurred before. Append this string as a substring to the current string being generated. After performing the above steps, print the maximum length of a string that has been generated. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to check if all the// string characters are uniquebool check(string s){ set<char> a; // Check for repetition in // characters for (auto i : s) { if (a.count(i)) return false; a.insert(i); } return true;} // Function to generate all possible strings// from the given arrayvector<string> helper(vector<string>& arr, int ind){ // Base case if (ind == arr.size()) return { "" }; // Consider every string as // a starting substring and // store the generated string vector<string> tmp = helper(arr, ind + 1); vector<string> ret(tmp.begin(), tmp.end()); // Add current string to result of // other strings and check if // characters are unique or not for (auto i : tmp) { string test = i + arr[ind]; if (check(test)) ret.push_back(test); } return ret;} // Function to find the maximum// possible length of a stringint maxLength(vector<string>& arr){ vector<string> tmp = helper(arr, 0); int len = 0; // Return max length possible for (auto i : tmp) { len = len > i.size() ? len : i.size(); } // Return the answer return len;} // Driver Codeint main(){ vector<string> s; s.push_back("abcdefgh"); cout << maxLength(s); return 0;} // Java program to implement // the above approachimport java.util.*;import java.lang.*; class GFG{ // Function to check if all the// string characters are uniquestatic boolean check(String s){ HashSet<Character> a = new HashSet<>(); // Check for repetition in // characters for(int i = 0; i < s.length(); i++) { if (a.contains(s.charAt(i))) { return false; } a.add(s.charAt(i)); } return true;} // Function to generate all possible// strings from the given arraystatic ArrayList<String> helper(ArrayList<String> arr, int ind){ ArrayList<String> fin = new ArrayList<>(); fin.add(""); // Base case if (ind == arr.size() ) return fin; // Consider every string as // a starting substring and // store the generated string ArrayList<String> tmp = helper(arr, ind + 1); ArrayList<String> ret = new ArrayList<>(tmp); // Add current string to result of // other strings and check if // characters are unique or not for(int i = 0; i < tmp.size(); i++) { String test = tmp.get(i) + arr.get(ind); if (check(test)) ret.add(test); } return ret;} // Function to find the maximum// possible length of a stringstatic int maxLength(ArrayList<String> arr){ ArrayList<String> tmp = helper(arr, 0); int len = 0; // Return max length possible for(int i = 0; i < tmp.size(); i++) { len = len > tmp.get(i).length() ? len : tmp.get(i).length(); } // Return the answer return len;} // Driver codepublic static void main (String[] args){ ArrayList<String> s = new ArrayList<>(); s.add("abcdefgh"); System.out.println(maxLength(s));}} // This code is contributed by offbeat # Python3 program to implement# the above approach # Function to check if all the# string characters are uniquedef check(s): a = set() # Check for repetition in # characters for i in s: if i in a: return False a.add(i) return True # Function to generate all possible# strings from the given arraydef helper(arr, ind): # Base case if (ind == len(arr)): return [""] # Consider every string as # a starting substring and # store the generated string tmp = helper(arr, ind + 1) ret = tmp # Add current string to result of # other strings and check if # characters are unique or not for i in tmp: test = i + arr[ind] if (check(test)): ret.append(test) return ret # Function to find the maximum# possible length of a stringdef maxLength(arr): tmp = helper(arr, 0) l = 0 # Return max length possible for i in tmp: l = l if l > len(i) else len(i) # Return the answer return l # Driver Codeif __name__=='__main__': s = [] s.append("abcdefgh") print(maxLength(s)) # This code is contributed by pratham76 // C# program to implement// the above approachusing System;using System.Collections;using System.Collections.Generic;using System.Text; class GFG{ // Function to check if all the// string characters are uniquestatic bool check(string s){ HashSet<char> a = new HashSet<char>(); // Check for repetition in // characters for(int i = 0; i < s.Length; i++) { if (a.Contains(s[i])) { return false; } a.Add(s[i]); } return true;} // Function to generate all possible// strings from the given arraystatic ArrayList helper(ArrayList arr, int ind){ // Base case if (ind == arr.Count) return new ArrayList(){""}; // Consider every string as // a starting substring and // store the generated string ArrayList tmp = helper(arr, ind + 1); ArrayList ret = new ArrayList(tmp); // Add current string to result of // other strings and check if // characters are unique or not for(int i = 0; i < tmp.Count; i++) { string test = (string)tmp[i] + (string)arr[ind]; if (check(test)) ret.Add(test); } return ret;} // Function to find the maximum// possible length of a stringstatic int maxLength(ArrayList arr){ ArrayList tmp = helper(arr, 0); int len = 0; // Return max length possible for(int i = 0; i < tmp.Count; i++) { len = len > ((string)tmp[i]).Length ? len : ((string)tmp[i]).Length; } // Return the answer return len;} // Driver Codepublic static void Main(string[] args){ ArrayList s = new ArrayList(); s.Add("abcdefgh"); Console.Write(maxLength(s));}} // This code is contributed by rutvik_56 <script> // Javascript program to implement the above approach // Function to check if all the // string characters are unique function check(s) { let a = new Set(); // Check for repetition in // characters for(let i = 0; i < s.length; i++) { if (a.has(s[i])) { return false; } a.add(s[i]); } return true; } // Function to generate all possible // strings from the given array function helper(arr, ind) { let fin = []; fin.push(""); // Base case if (ind == arr.length) return fin; // Consider every string as // a starting substring and // store the generated string let tmp = helper(arr, ind + 1); let ret = tmp; // Add current string to result of // other strings and check if // characters are unique or not for(let i = 0; i < tmp.length; i++) { let test = tmp[i] + arr[ind]; if (check(test)) ret.push(test); } return ret; } // Function to find the maximum // possible length of a string function maxLength(arr) { let tmp = helper(arr, 0); let len = 0; // Return max length possible for(let i = 0; i < tmp.length; i++) { len = len > tmp[i].length ? len : tmp[i].length; } // Return the answer return len; } let s = []; s.push("abcdefgh"); document.write(maxLength(s)); // This code is contributed by suresh07.</script> 8 Time Complexity: O(2N) Auxiliary Space: O(N * 2N) Efficient Approach (Using Dynamic Programming): C++ #include <bits/stdc++.h>using namespace std; int maxLength(vector<string>& A){ vector<bitset<26> > dp = { bitset<26>() }; // auxiliary dp storage int res = 0; // will store number of unique chars in // resultant string for (auto& s : A) { bitset<26> a; // used to track unique chars for (char c : s) a.set(c - 'a'); int n = a.count(); if (n < s.size()) continue; // duplicate chars in current string for (int i = dp.size() - 1; i >= 0; --i) { bitset<26> c = dp[i]; if ((c & a).any()) continue; // if 1 or more char common dp.push_back(c | a); // valid concatenation res = max(res, (int)c.count() + n); } } return res;} int main(){ vector<string> v = { "ab", "cd", "ab" }; int ans = maxLength(v); cout << ans; // resultant answer string : cfbdghzest return 0;} 10 Time Complexity: O(N^2) Auxiliary Space: O(N * 26) rutvik_56 offbeat khushboogoyal499 pratham76 RahulJain6 sooda367 suresh07 sweetyty HashSet subsequence substring Arrays Hash Mathematical Recursion Strings Arrays Hash Strings Mathematical Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Jul, 2022" }, { "code": null, "e": 248, "s": 54, "text": "Given an array of strings arr[], the task is to find the maximum possible length of a string of distinct characters that can be generated by concatenating of the subsequence of the given array." }, { "code": null, "e": 258, "s": 248, "text": "Examples:" }, { "code": null, "e": 420, "s": 258, "text": "Input: arr[] = {“ab”, “cd”, “ab”} Output: 4 Explanation: All possible combinations are {“”, “ab”, “cd”, “abcd”, “cdab”}. Therefore, maximum length possible is 4." }, { "code": null, "e": 565, "s": 420, "text": "Input: arr[] = {“abcdefgh”} Output: 8 Explanation: All possible combinations are: “”, “abcdefgh”. Therefore, the maximum length possible is 8. " }, { "code": null, "e": 650, "s": 565, "text": "Approach: The idea is to use Recursion. Follow the steps below to solve the problem:" }, { "code": null, "e": 737, "s": 650, "text": "Iterate from left to right and consider every string as a possible starting substring." }, { "code": null, "e": 811, "s": 737, "text": "Initialize a HashSet to store the distinct characters encountered so far." }, { "code": null, "e": 1030, "s": 811, "text": "Once a string is selected as starting substring, check for every remaining string, if it only contains characters which have not occurred before. Append this string as a substring to the current string being generated." }, { "code": null, "e": 1126, "s": 1030, "text": "After performing the above steps, print the maximum length of a string that has been generated." }, { "code": null, "e": 1177, "s": 1126, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1181, "s": 1177, "text": "C++" }, { "code": null, "e": 1186, "s": 1181, "text": "Java" }, { "code": null, "e": 1194, "s": 1186, "text": "Python3" }, { "code": null, "e": 1197, "s": 1194, "text": "C#" }, { "code": null, "e": 1208, "s": 1197, "text": "Javascript" }, { "code": "// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to check if all the// string characters are uniquebool check(string s){ set<char> a; // Check for repetition in // characters for (auto i : s) { if (a.count(i)) return false; a.insert(i); } return true;} // Function to generate all possible strings// from the given arrayvector<string> helper(vector<string>& arr, int ind){ // Base case if (ind == arr.size()) return { \"\" }; // Consider every string as // a starting substring and // store the generated string vector<string> tmp = helper(arr, ind + 1); vector<string> ret(tmp.begin(), tmp.end()); // Add current string to result of // other strings and check if // characters are unique or not for (auto i : tmp) { string test = i + arr[ind]; if (check(test)) ret.push_back(test); } return ret;} // Function to find the maximum// possible length of a stringint maxLength(vector<string>& arr){ vector<string> tmp = helper(arr, 0); int len = 0; // Return max length possible for (auto i : tmp) { len = len > i.size() ? len : i.size(); } // Return the answer return len;} // Driver Codeint main(){ vector<string> s; s.push_back(\"abcdefgh\"); cout << maxLength(s); return 0;}", "e": 2677, "s": 1208, "text": null }, { "code": "// Java program to implement // the above approachimport java.util.*;import java.lang.*; class GFG{ // Function to check if all the// string characters are uniquestatic boolean check(String s){ HashSet<Character> a = new HashSet<>(); // Check for repetition in // characters for(int i = 0; i < s.length(); i++) { if (a.contains(s.charAt(i))) { return false; } a.add(s.charAt(i)); } return true;} // Function to generate all possible// strings from the given arraystatic ArrayList<String> helper(ArrayList<String> arr, int ind){ ArrayList<String> fin = new ArrayList<>(); fin.add(\"\"); // Base case if (ind == arr.size() ) return fin; // Consider every string as // a starting substring and // store the generated string ArrayList<String> tmp = helper(arr, ind + 1); ArrayList<String> ret = new ArrayList<>(tmp); // Add current string to result of // other strings and check if // characters are unique or not for(int i = 0; i < tmp.size(); i++) { String test = tmp.get(i) + arr.get(ind); if (check(test)) ret.add(test); } return ret;} // Function to find the maximum// possible length of a stringstatic int maxLength(ArrayList<String> arr){ ArrayList<String> tmp = helper(arr, 0); int len = 0; // Return max length possible for(int i = 0; i < tmp.size(); i++) { len = len > tmp.get(i).length() ? len : tmp.get(i).length(); } // Return the answer return len;} // Driver codepublic static void main (String[] args){ ArrayList<String> s = new ArrayList<>(); s.add(\"abcdefgh\"); System.out.println(maxLength(s));}} // This code is contributed by offbeat", "e": 4552, "s": 2677, "text": null }, { "code": "# Python3 program to implement# the above approach # Function to check if all the# string characters are uniquedef check(s): a = set() # Check for repetition in # characters for i in s: if i in a: return False a.add(i) return True # Function to generate all possible# strings from the given arraydef helper(arr, ind): # Base case if (ind == len(arr)): return [\"\"] # Consider every string as # a starting substring and # store the generated string tmp = helper(arr, ind + 1) ret = tmp # Add current string to result of # other strings and check if # characters are unique or not for i in tmp: test = i + arr[ind] if (check(test)): ret.append(test) return ret # Function to find the maximum# possible length of a stringdef maxLength(arr): tmp = helper(arr, 0) l = 0 # Return max length possible for i in tmp: l = l if l > len(i) else len(i) # Return the answer return l # Driver Codeif __name__=='__main__': s = [] s.append(\"abcdefgh\") print(maxLength(s)) # This code is contributed by pratham76", "e": 5750, "s": 4552, "text": null }, { "code": "// C# program to implement// the above approachusing System;using System.Collections;using System.Collections.Generic;using System.Text; class GFG{ // Function to check if all the// string characters are uniquestatic bool check(string s){ HashSet<char> a = new HashSet<char>(); // Check for repetition in // characters for(int i = 0; i < s.Length; i++) { if (a.Contains(s[i])) { return false; } a.Add(s[i]); } return true;} // Function to generate all possible// strings from the given arraystatic ArrayList helper(ArrayList arr, int ind){ // Base case if (ind == arr.Count) return new ArrayList(){\"\"}; // Consider every string as // a starting substring and // store the generated string ArrayList tmp = helper(arr, ind + 1); ArrayList ret = new ArrayList(tmp); // Add current string to result of // other strings and check if // characters are unique or not for(int i = 0; i < tmp.Count; i++) { string test = (string)tmp[i] + (string)arr[ind]; if (check(test)) ret.Add(test); } return ret;} // Function to find the maximum// possible length of a stringstatic int maxLength(ArrayList arr){ ArrayList tmp = helper(arr, 0); int len = 0; // Return max length possible for(int i = 0; i < tmp.Count; i++) { len = len > ((string)tmp[i]).Length ? len : ((string)tmp[i]).Length; } // Return the answer return len;} // Driver Codepublic static void Main(string[] args){ ArrayList s = new ArrayList(); s.Add(\"abcdefgh\"); Console.Write(maxLength(s));}} // This code is contributed by rutvik_56", "e": 7520, "s": 5750, "text": null }, { "code": "<script> // Javascript program to implement the above approach // Function to check if all the // string characters are unique function check(s) { let a = new Set(); // Check for repetition in // characters for(let i = 0; i < s.length; i++) { if (a.has(s[i])) { return false; } a.add(s[i]); } return true; } // Function to generate all possible // strings from the given array function helper(arr, ind) { let fin = []; fin.push(\"\"); // Base case if (ind == arr.length) return fin; // Consider every string as // a starting substring and // store the generated string let tmp = helper(arr, ind + 1); let ret = tmp; // Add current string to result of // other strings and check if // characters are unique or not for(let i = 0; i < tmp.length; i++) { let test = tmp[i] + arr[ind]; if (check(test)) ret.push(test); } return ret; } // Function to find the maximum // possible length of a string function maxLength(arr) { let tmp = helper(arr, 0); let len = 0; // Return max length possible for(let i = 0; i < tmp.length; i++) { len = len > tmp[i].length ? len : tmp[i].length; } // Return the answer return len; } let s = []; s.push(\"abcdefgh\"); document.write(maxLength(s)); // This code is contributed by suresh07.</script>", "e": 9162, "s": 7520, "text": null }, { "code": null, "e": 9164, "s": 9162, "text": "8" }, { "code": null, "e": 9215, "s": 9164, "text": "Time Complexity: O(2N) Auxiliary Space: O(N * 2N) " }, { "code": null, "e": 9264, "s": 9215, "text": "Efficient Approach (Using Dynamic Programming): " }, { "code": null, "e": 9268, "s": 9264, "text": "C++" }, { "code": "#include <bits/stdc++.h>using namespace std; int maxLength(vector<string>& A){ vector<bitset<26> > dp = { bitset<26>() }; // auxiliary dp storage int res = 0; // will store number of unique chars in // resultant string for (auto& s : A) { bitset<26> a; // used to track unique chars for (char c : s) a.set(c - 'a'); int n = a.count(); if (n < s.size()) continue; // duplicate chars in current string for (int i = dp.size() - 1; i >= 0; --i) { bitset<26> c = dp[i]; if ((c & a).any()) continue; // if 1 or more char common dp.push_back(c | a); // valid concatenation res = max(res, (int)c.count() + n); } } return res;} int main(){ vector<string> v = { \"ab\", \"cd\", \"ab\" }; int ans = maxLength(v); cout << ans; // resultant answer string : cfbdghzest return 0;}", "e": 10202, "s": 9268, "text": null }, { "code": null, "e": 10205, "s": 10202, "text": "10" }, { "code": null, "e": 10257, "s": 10205, "text": "Time Complexity: O(N^2) Auxiliary Space: O(N * 26) " }, { "code": null, "e": 10267, "s": 10257, "text": "rutvik_56" }, { "code": null, "e": 10275, "s": 10267, "text": "offbeat" }, { "code": null, "e": 10292, "s": 10275, "text": "khushboogoyal499" }, { "code": null, "e": 10302, "s": 10292, "text": "pratham76" }, { "code": null, "e": 10313, "s": 10302, "text": "RahulJain6" }, { "code": null, "e": 10322, "s": 10313, "text": "sooda367" }, { "code": null, "e": 10331, "s": 10322, "text": "suresh07" }, { "code": null, "e": 10340, "s": 10331, "text": "sweetyty" }, { "code": null, "e": 10348, "s": 10340, "text": "HashSet" }, { "code": null, "e": 10360, "s": 10348, "text": "subsequence" }, { "code": null, "e": 10370, "s": 10360, "text": "substring" }, { "code": null, "e": 10377, "s": 10370, "text": "Arrays" }, { "code": null, "e": 10382, "s": 10377, "text": "Hash" }, { "code": null, "e": 10395, "s": 10382, "text": "Mathematical" }, { "code": null, "e": 10405, "s": 10395, "text": "Recursion" }, { "code": null, "e": 10413, "s": 10405, "text": "Strings" }, { "code": null, "e": 10420, "s": 10413, "text": "Arrays" }, { "code": null, "e": 10425, "s": 10420, "text": "Hash" }, { "code": null, "e": 10433, "s": 10425, "text": "Strings" }, { "code": null, "e": 10446, "s": 10433, "text": "Mathematical" }, { "code": null, "e": 10456, "s": 10446, "text": "Recursion" } ]
Subgroup and Order of group | Mathematics
20 May, 2019 Prerequisite: Groups A nonempty subset H of the group G is a subgroup of G if H is a group under binary operation (*) of G. We use the notation H ≤ G to indicate that H is a subgroup of G. Also, if H is a proper subgroup then it is denoted by H < G . H ≠ φ if a, k ∈ H then ak ∈ H if a ∈ H then a-1 ∈ H Ex. – Integers (Z) is a subgroup of rationals (Q) under addition, (Z, +) < (Q, +) Note:G is a subgroup of itself and {e} is also subgroup of G, these are called trivial subgroup.Subgroup will have all the properties of a group.A subgroup H of the group G is a normal subgroup if g -1 H g = H for all g ∈ G.If H < K and K < G, then H < G (subgroup transitivity).if H and K are subgroups of a group G then H ∩ K is also a subgroup.if H and K are subgroups of a group G then H ∪ K is may or maynot be a subgroup. G is a subgroup of itself and {e} is also subgroup of G, these are called trivial subgroup. Subgroup will have all the properties of a group. A subgroup H of the group G is a normal subgroup if g -1 H g = H for all g ∈ G. If H < K and K < G, then H < G (subgroup transitivity). if H and K are subgroups of a group G then H ∩ K is also a subgroup. if H and K are subgroups of a group G then H ∪ K is may or maynot be a subgroup. Let H be a subgroup of a group G. If g ∈ G, the right coset of H generated by g is, Hg = { hg, h ∈ H };and similarly, the left coset of H generated by g is gH = { gh, h ∈ H } Example: Consider Z4 under addition (Z4, +), and let H={0, 2}. e = 0, e is identity element. Find the left cosets of H in G?Solution: The left cosets of H in G are, eH = e*H = { e * h | h ∈ H} = { 0+h| h ∈ H} = {0, 2}. 1H= 1*H = {1 * h | h ∈ H} = { 1+h| h ∈ H} = {1, 3}. 2H= 2*H = {2 * h | h ∈ H} = { 2+h| h ∈ H} = {0, 2}. 3H= 3*H = {3 * h |h ∈ H} = { 3+h| h ∈ H} = {1, 3}. Hence there are two cosets, namely 0*H= 2*H = {0, 2} and 1*H= 3*H = {1, 3}. The Order of a group (G) is the number of elements present in that group, i.e it’s cardinality. It is denoted by |G|.Order of element a ∈ G is the smallest positive integer n, such that an= e, where e denotes the identity element of the group, and an denotes the product of n copies of a. If no such n exists, a is said to have infinite order. All elements of finite groups have finite order. Lagrange’s Theorem: If H is a subgroup of finite group G then the order of subgroup H divides the order of group G. The order of every element of a finite group is finite. The Order of an element of a group is the same as that of its inverse a-1. If a is an element of order n and p is prime to n, then ap is also of order n. Order of any integral power of an element b cannot exceed the order of b. If the element a of a group G is order n, then ak=e if and only if n is a divisor of k. The order of the elements a and x-1ax is the same where a, x are any two elements of a group. If a and b are elements of a group then the order of ab is same as order of ba. Related GATE Questions:1) Gate CS 20182) Gate CS 2014 (Set-3) Engineering Mathematics Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n20 May, 2019" }, { "code": null, "e": 73, "s": 52, "text": "Prerequisite: Groups" }, { "code": null, "e": 303, "s": 73, "text": "A nonempty subset H of the group G is a subgroup of G if H is a group under binary operation (*) of G. We use the notation H ≤ G to indicate that H is a subgroup of G. Also, if H is a proper subgroup then it is denoted by H < G ." }, { "code": null, "e": 310, "s": 303, "text": "H ≠ φ" }, { "code": null, "e": 334, "s": 310, "text": "if a, k ∈ H then ak ∈ H" }, { "code": null, "e": 356, "s": 334, "text": "if a ∈ H then a-1 ∈ H" }, { "code": null, "e": 438, "s": 356, "text": "Ex. – Integers (Z) is a subgroup of rationals (Q) under addition, (Z, +) < (Q, +)" }, { "code": null, "e": 866, "s": 438, "text": "Note:G is a subgroup of itself and {e} is also subgroup of G, these are called trivial subgroup.Subgroup will have all the properties of a group.A subgroup H of the group G is a normal subgroup if g -1 H g = H for all g ∈ G.If H < K and K < G, then H < G (subgroup transitivity).if H and K are subgroups of a group G then H ∩ K is also a subgroup.if H and K are subgroups of a group G then H ∪ K is may or maynot be a subgroup." }, { "code": null, "e": 958, "s": 866, "text": "G is a subgroup of itself and {e} is also subgroup of G, these are called trivial subgroup." }, { "code": null, "e": 1008, "s": 958, "text": "Subgroup will have all the properties of a group." }, { "code": null, "e": 1088, "s": 1008, "text": "A subgroup H of the group G is a normal subgroup if g -1 H g = H for all g ∈ G." }, { "code": null, "e": 1144, "s": 1088, "text": "If H < K and K < G, then H < G (subgroup transitivity)." }, { "code": null, "e": 1213, "s": 1144, "text": "if H and K are subgroups of a group G then H ∩ K is also a subgroup." }, { "code": null, "e": 1294, "s": 1213, "text": "if H and K are subgroups of a group G then H ∪ K is may or maynot be a subgroup." }, { "code": null, "e": 1469, "s": 1294, "text": "Let H be a subgroup of a group G. If g ∈ G, the right coset of H generated by g is, Hg = { hg, h ∈ H };and similarly, the left coset of H generated by g is gH = { gh, h ∈ H }" }, { "code": null, "e": 1603, "s": 1469, "text": "Example: Consider Z4 under addition (Z4, +), and let H={0, 2}. e = 0, e is identity element. Find the left cosets of H in G?Solution:" }, { "code": null, "e": 1928, "s": 1603, "text": " The left cosets of H in G are,\n eH = e*H = { e * h | h ∈ H} = { 0+h| h ∈ H} = {0, 2}.\n 1H= 1*H = {1 * h | h ∈ H} = { 1+h| h ∈ H} = {1, 3}.\n 2H= 2*H = {2 * h | h ∈ H} = { 2+h| h ∈ H} = {0, 2}.\n 3H= 3*H = {3 * h |h ∈ H} = { 3+h| h ∈ H} = {1, 3}.\n Hence there are two cosets, namely 0*H= 2*H = {0, 2} and 1*H= 3*H = {1, 3}. " }, { "code": null, "e": 2321, "s": 1928, "text": "The Order of a group (G) is the number of elements present in that group, i.e it’s cardinality. It is denoted by |G|.Order of element a ∈ G is the smallest positive integer n, such that an= e, where e denotes the identity element of the group, and an denotes the product of n copies of a. If no such n exists, a is said to have infinite order. All elements of finite groups have finite order." }, { "code": null, "e": 2341, "s": 2321, "text": "Lagrange’s Theorem:" }, { "code": null, "e": 2437, "s": 2341, "text": "If H is a subgroup of finite group G then the order of subgroup H divides the order of group G." }, { "code": null, "e": 2493, "s": 2437, "text": "The order of every element of a finite group is finite." }, { "code": null, "e": 2568, "s": 2493, "text": "The Order of an element of a group is the same as that of its inverse a-1." }, { "code": null, "e": 2647, "s": 2568, "text": "If a is an element of order n and p is prime to n, then ap is also of order n." }, { "code": null, "e": 2721, "s": 2647, "text": "Order of any integral power of an element b cannot exceed the order of b." }, { "code": null, "e": 2809, "s": 2721, "text": "If the element a of a group G is order n, then ak=e if and only if n is a divisor of k." }, { "code": null, "e": 2903, "s": 2809, "text": "The order of the elements a and x-1ax is the same where a, x are any two elements of a group." }, { "code": null, "e": 2983, "s": 2903, "text": "If a and b are elements of a group then the order of ab is same as order of ba." }, { "code": null, "e": 3045, "s": 2983, "text": "Related GATE Questions:1) Gate CS 20182) Gate CS 2014 (Set-3)" }, { "code": null, "e": 3069, "s": 3045, "text": "Engineering Mathematics" } ]
Difference Between Callable and Runnable in Java - GeeksforGeeks
21 Apr, 2022 java.lang.Runnable is an interface that is to be implemented by a class whose instances are intended to be executed by a thread. There are two ways to start a new Thread – Subclass Thread and implement Runnable. There is no need of sub-classing Thread when a task can be done by overriding only run() method of Runnable. Callable interface and Runnable interface are used to encapsulate tasks supposed to be executed by another thread. However, Runnable instances can be run by Thread class as well as ExecutorService but Callable instances can only be executed via ExecutorService. Let us discuss differences between the two above interfaces as defined by discussing them individually later on concluding to major differences in a tabular format. Callable Interface In a callable interface that basically throws a checked exception and returns some results. This is one of the major differences between the upcoming Runnable interface where no value is being returned. In this interface, it simply computes a result else throws an exception if unable to do so. public interface Callable<V> { V call() throws exception ; } It is declared in the ‘java.util.concurrent‘ package.This interface also contains a single, no-argument method, called call() methodWe can’t create a thread by passing callable as a parameter.Callable can return results. Callable’s call() method contains the “throws Exception” clause, so we can easily propagate checked exceptions further. It is declared in the ‘java.util.concurrent‘ package. This interface also contains a single, no-argument method, called call() method We can’t create a thread by passing callable as a parameter. Callable can return results. Callable’s call() method contains the “throws Exception” clause, so we can easily propagate checked exceptions further. Example: Java // Java Program to illustrate Callable interface // Importing classes from java.util packageimport java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.Future;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors; // Class// Implementing the Callable interfaceclass CallableMessage implements Callable<String>{ public String call() throws Exception{ return "Hello World!"; } } public class CallableExample{ static ExecutorService executor = Executors.newFixedThreadPool(2); public static void main(String[] args) throws Exception{ CallableMessage task = new CallableMessage(); Future<String> message = executor.submit(task); System.out.println(message.get().toString()); }} Output: Hello World Runnable interface When an object implementing this interface is used to create a thread, starting the thread causes the object run method to be called in a separately executing thread. The general. contract of this run() method is that it may take any action whatsoever. public interface Runnable { public abstract void run(); } java.lang.Runnable is an interface and defines only one method called run(). It represents a task in Java that is executed by Thread. There are two ways to start a new thread using Runnable, one is by implementing the Runnable interface and another one is by subclassing the Thread class. Runnable cannot return the result of computation which is essential if you are performing some computing task in another thread, and Runnable cannot throw checked exceptions. Example Java // Java Program to implement Runnable interface // Importing FileNotFound class from// input output classes bundleimport java.io.FileNotFoundException;import java.util.concurrent.*; // Class// Implementing the Runnable interfaceclass RunnableImpl implements Runnable { public void run() { System.out.println("Hello World from a different thread than Main"); }}public class RunnableExample{ static ExecutorService executor = Executors.newFixedThreadPool(2); public static void main(String[] args){ // Creating and running runnable task using Thread class RunnableImpl task = new RunnableImpl(); Thread thread = new Thread(task); thread.start(); // Creating and running runnable task using Executor Service. executor.submit(task); }} ankitratnam1 java-interfaces Picked Technical Scripter 2020 Difference Between Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Difference between Prim's and Kruskal's algorithm for MST Difference between Internal and External fragmentation Differences and Applications of List, Tuple, Set and Dictionary in Python Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Reverse a string in Java
[ { "code": null, "e": 24883, "s": 24855, "text": "\n21 Apr, 2022" }, { "code": null, "e": 25204, "s": 24883, "text": "java.lang.Runnable is an interface that is to be implemented by a class whose instances are intended to be executed by a thread. There are two ways to start a new Thread – Subclass Thread and implement Runnable. There is no need of sub-classing Thread when a task can be done by overriding only run() method of Runnable." }, { "code": null, "e": 25319, "s": 25204, "text": "Callable interface and Runnable interface are used to encapsulate tasks supposed to be executed by another thread." }, { "code": null, "e": 25466, "s": 25319, "text": "However, Runnable instances can be run by Thread class as well as ExecutorService but Callable instances can only be executed via ExecutorService." }, { "code": null, "e": 25631, "s": 25466, "text": "Let us discuss differences between the two above interfaces as defined by discussing them individually later on concluding to major differences in a tabular format." }, { "code": null, "e": 25651, "s": 25631, "text": "Callable Interface " }, { "code": null, "e": 25946, "s": 25651, "text": "In a callable interface that basically throws a checked exception and returns some results. This is one of the major differences between the upcoming Runnable interface where no value is being returned. In this interface, it simply computes a result else throws an exception if unable to do so." }, { "code": null, "e": 26010, "s": 25946, "text": "public interface Callable<V> \n{\n V call() throws exception ;\n}" }, { "code": null, "e": 26351, "s": 26010, "text": "It is declared in the ‘java.util.concurrent‘ package.This interface also contains a single, no-argument method, called call() methodWe can’t create a thread by passing callable as a parameter.Callable can return results. Callable’s call() method contains the “throws Exception” clause, so we can easily propagate checked exceptions further." }, { "code": null, "e": 26405, "s": 26351, "text": "It is declared in the ‘java.util.concurrent‘ package." }, { "code": null, "e": 26485, "s": 26405, "text": "This interface also contains a single, no-argument method, called call() method" }, { "code": null, "e": 26546, "s": 26485, "text": "We can’t create a thread by passing callable as a parameter." }, { "code": null, "e": 26695, "s": 26546, "text": "Callable can return results. Callable’s call() method contains the “throws Exception” clause, so we can easily propagate checked exceptions further." }, { "code": null, "e": 26704, "s": 26695, "text": "Example:" }, { "code": null, "e": 26709, "s": 26704, "text": "Java" }, { "code": "// Java Program to illustrate Callable interface // Importing classes from java.util packageimport java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.Future;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors; // Class// Implementing the Callable interfaceclass CallableMessage implements Callable<String>{ public String call() throws Exception{ return \"Hello World!\"; } } public class CallableExample{ static ExecutorService executor = Executors.newFixedThreadPool(2); public static void main(String[] args) throws Exception{ CallableMessage task = new CallableMessage(); Future<String> message = executor.submit(task); System.out.println(message.get().toString()); }}", "e": 27480, "s": 26709, "text": null }, { "code": null, "e": 27488, "s": 27480, "text": "Output:" }, { "code": null, "e": 27500, "s": 27488, "text": "Hello World" }, { "code": null, "e": 27520, "s": 27500, "text": "Runnable interface " }, { "code": null, "e": 27774, "s": 27520, "text": "When an object implementing this interface is used to create a thread, starting the thread causes the object run method to be called in a separately executing thread. The general. contract of this run() method is that it may take any action whatsoever. " }, { "code": null, "e": 27835, "s": 27774, "text": "public interface Runnable \n{\n public abstract void run();\n}" }, { "code": null, "e": 27913, "s": 27835, "text": "java.lang.Runnable is an interface and defines only one method called run(). " }, { "code": null, "e": 27970, "s": 27913, "text": "It represents a task in Java that is executed by Thread." }, { "code": null, "e": 28125, "s": 27970, "text": "There are two ways to start a new thread using Runnable, one is by implementing the Runnable interface and another one is by subclassing the Thread class." }, { "code": null, "e": 28300, "s": 28125, "text": "Runnable cannot return the result of computation which is essential if you are performing some computing task in another thread, and Runnable cannot throw checked exceptions." }, { "code": null, "e": 28308, "s": 28300, "text": "Example" }, { "code": null, "e": 28313, "s": 28308, "text": "Java" }, { "code": "// Java Program to implement Runnable interface // Importing FileNotFound class from// input output classes bundleimport java.io.FileNotFoundException;import java.util.concurrent.*; // Class// Implementing the Runnable interfaceclass RunnableImpl implements Runnable { public void run() { System.out.println(\"Hello World from a different thread than Main\"); }}public class RunnableExample{ static ExecutorService executor = Executors.newFixedThreadPool(2); public static void main(String[] args){ // Creating and running runnable task using Thread class RunnableImpl task = new RunnableImpl(); Thread thread = new Thread(task); thread.start(); // Creating and running runnable task using Executor Service. executor.submit(task); }}", "e": 29111, "s": 28313, "text": null }, { "code": null, "e": 29124, "s": 29111, "text": "ankitratnam1" }, { "code": null, "e": 29140, "s": 29124, "text": "java-interfaces" }, { "code": null, "e": 29147, "s": 29140, "text": "Picked" }, { "code": null, "e": 29171, "s": 29147, "text": "Technical Scripter 2020" }, { "code": null, "e": 29190, "s": 29171, "text": "Difference Between" }, { "code": null, "e": 29195, "s": 29190, "text": "Java" }, { "code": null, "e": 29214, "s": 29195, "text": "Technical Scripter" }, { "code": null, "e": 29219, "s": 29214, "text": "Java" }, { "code": null, "e": 29317, "s": 29219, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29378, "s": 29317, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29446, "s": 29378, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 29504, "s": 29446, "text": "Difference between Prim's and Kruskal's algorithm for MST" }, { "code": null, "e": 29559, "s": 29504, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 29633, "s": 29559, "text": "Differences and Applications of List, Tuple, Set and Dictionary in Python" }, { "code": null, "e": 29648, "s": 29633, "text": "Arrays in Java" }, { "code": null, "e": 29692, "s": 29648, "text": "Split() String method in Java with examples" }, { "code": null, "e": 29714, "s": 29692, "text": "For-each loop in Java" }, { "code": null, "e": 29750, "s": 29714, "text": "Arrays.sort() in Java with examples" } ]
Static method in Interface in Java
To implement static method in Interface, the Java code is as follows − Live Demo interface my_interface{ static void static_fun(){ System.out.println("In the newly created static method"); } void method_override(String str); } public class Demo_interface implements my_interface{ public static void main(String[] args){ Demo_interface demo_inter = new Demo_interface(); my_interface.static_fun(); demo_inter.method_override("In the override method"); } @Override public void method_override(String str){ System.out.println(str); } } In the newly created static method In the override method An interface is defined, inside which a static function is defined. Another function named ‘method_override’ is defined without a body. This interface is implemented by another class named ‘Demo_interface’. Inside this class, the main function is defined, and an instance of this ‘Demo_interface’ is also created. The static function is called on this instance, and next, the ‘method_override’ function is called on this instance. An override specification is written, under which the ‘method_override’ is defined. This function just prints the string on the console.
[ { "code": null, "e": 1133, "s": 1062, "text": "To implement static method in Interface, the Java code is as follows −" }, { "code": null, "e": 1144, "s": 1133, "text": " Live Demo" }, { "code": null, "e": 1650, "s": 1144, "text": "interface my_interface{\n static void static_fun(){\n System.out.println(\"In the newly created static method\");\n }\n void method_override(String str);\n}\npublic class Demo_interface implements my_interface{\n public static void main(String[] args){\n Demo_interface demo_inter = new Demo_interface();\n my_interface.static_fun();\n demo_inter.method_override(\"In the override method\");\n }\n @Override\n public void method_override(String str){\n System.out.println(str);\n }\n}" }, { "code": null, "e": 1708, "s": 1650, "text": "In the newly created static method\nIn the override method" }, { "code": null, "e": 2276, "s": 1708, "text": "An interface is defined, inside which a static function is defined. Another function named ‘method_override’ is defined without a body. This interface is implemented by another class named\n‘Demo_interface’. Inside this class, the main function is defined, and an instance of this ‘Demo_interface’ is also created. The static function is called on this instance, and next, the\n‘method_override’ function is called on this instance. An override specification is written, under\nwhich the ‘method_override’ is defined. This function just prints the string on the console." } ]
Find the angle of Rotational Symmetry of an N-sided regular polygon - GeeksforGeeks
31 Mar, 2021 Given an integer N which is the number of sides of a regular polygon. The task is to find the smallest angle of rotation such that the generated regular polygons have a similar position and dimensions, i.e. the new rotated polygon is in symmetry with the initial one. A shape is said to have a rotation symmetry if there exists a rotation in the range [1, 360o] such that the new shape overlaps the initial shape completely. Examples: Input: N = 4 Output: 90 Explanation: A 4 sided regular polygon is a square and when it is rotated by 90 degrees it results in the similar square. Input: N = 8 Output: 45 Approach: For any N sided regular polygon, when rotated by 360 degrees, it aligns in the original position of the polygon. To find the minimum angle of rotation we use the property of symmetry of regular polygons. For an N sided regular polygon when rotated by 360/N degrees, the rotated polygon is in the same position as of the original polygon, which is the exterior angle of an N-sided regular polygon. For example: Consider N = 4, Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ program to find the angle// of Rotational Symmetry of// an N-sided regular polygon #include <bits/stdc++.h>using namespace std; // function to find required// minimum angle of rotationdouble minAnglRot(int N){ // Store the answer in // a double variable double res; // Calculating the angle // of rotation and type- // casting the integer N // to double type res = 360 / (double)N; return res;} // Driver codeint main(){ int N = 4; cout << "Angle of Rotational Symmetry: " << minAnglRot(N); return 0;} // Java program to find the angle// of Rotational Symmetry of// an N-sided regular polygonimport java.io.*;class GFG{ // function to find required// minimum angle of rotationstatic double minAnglRot(int N){ // Store the answer in // a double variable double res; // Calculating the angle // of rotation and type- // casting the integer N // to double type res = 360 / (double)N; return res;} // Driver codepublic static void main (String[] args){ int N = 4; System.out.println("Angle of Rotational Symmetry: " + minAnglRot(N));}} // This code is contributed by shivanisinghss2110 # Python3 program to find the angle# of Rotational Symmetry of# an N-sided regular polygon # Function to find required# minimum angle of rotationdef minAnglRot(N): # Store the answer in a # variable # Calculating the angle # of rotation and type- # casting the integer N # to type res = 360 // N return res # Driver codeif __name__ == '__main__': N = 4; print("Angle of Rotational Symmetry: ", minAnglRot(N)) # This code is contributed by mohit kumar 29 // C# program to find the angle// of Rotational Symmetry of// an N-sided regular polygonusing System;class GFG{ // function to find required// minimum angle of rotationstatic double minAnglRot(int N){ // Store the answer in // a double variable double res; // Calculating the angle // of rotation and type- // casting the integer N // to double type res = 360 / (double)N; return res;} // Driver codepublic static void Main (string[] args){ int N = 4; Console.Write("Angle of Rotational Symmetry: " + minAnglRot(N));}} // This code is contributed by rock_cool <script> // Javascript program to find the angle// of Rotational Symmetry of an N-sided// regular polygon // Function to find required// minimum angle of rotationfunction minAnglRot(N){ // Store the answer in // a double variable let res; // Calculating the angle of // rotation and type-casting // the integer N to double type res = 360 / N; return res;} // Driver codelet N = 4; document.write("Angle of Rotational Symmetry: " + minAnglRot(N)); // This code is contributed by divyeshrabadiya07 </script> Angle of Rotational Symmetry: 90 Time Complexity: O (1) Auxiliary Space: O (1) mohit kumar 29 shivanisinghss2110 rock_cool divyeshrabadiya07 Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping) Closest Pair of Points | O(nlogn) Implementation Line Clipping | Set 1 (Cohen–Sutherland Algorithm) Given n line segments, find if any two segments intersect Convex Hull | Set 2 (Graham Scan) Program for Fibonacci numbers C++ Data Types Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 25166, "s": 25138, "text": "\n31 Mar, 2021" }, { "code": null, "e": 25434, "s": 25166, "text": "Given an integer N which is the number of sides of a regular polygon. The task is to find the smallest angle of rotation such that the generated regular polygons have a similar position and dimensions, i.e. the new rotated polygon is in symmetry with the initial one." }, { "code": null, "e": 25591, "s": 25434, "text": "A shape is said to have a rotation symmetry if there exists a rotation in the range [1, 360o] such that the new shape overlaps the initial shape completely." }, { "code": null, "e": 25603, "s": 25591, "text": "Examples: " }, { "code": null, "e": 25749, "s": 25603, "text": "Input: N = 4 Output: 90 Explanation: A 4 sided regular polygon is a square and when it is rotated by 90 degrees it results in the similar square." }, { "code": null, "e": 25775, "s": 25749, "text": "Input: N = 8 Output: 45 " }, { "code": null, "e": 26182, "s": 25775, "text": "Approach: For any N sided regular polygon, when rotated by 360 degrees, it aligns in the original position of the polygon. To find the minimum angle of rotation we use the property of symmetry of regular polygons. For an N sided regular polygon when rotated by 360/N degrees, the rotated polygon is in the same position as of the original polygon, which is the exterior angle of an N-sided regular polygon." }, { "code": null, "e": 26212, "s": 26182, "text": "For example: Consider N = 4, " }, { "code": null, "e": 26264, "s": 26212, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 26268, "s": 26264, "text": "C++" }, { "code": null, "e": 26273, "s": 26268, "text": "Java" }, { "code": null, "e": 26281, "s": 26273, "text": "Python3" }, { "code": null, "e": 26284, "s": 26281, "text": "C#" }, { "code": null, "e": 26295, "s": 26284, "text": "Javascript" }, { "code": "// C++ program to find the angle// of Rotational Symmetry of// an N-sided regular polygon #include <bits/stdc++.h>using namespace std; // function to find required// minimum angle of rotationdouble minAnglRot(int N){ // Store the answer in // a double variable double res; // Calculating the angle // of rotation and type- // casting the integer N // to double type res = 360 / (double)N; return res;} // Driver codeint main(){ int N = 4; cout << \"Angle of Rotational Symmetry: \" << minAnglRot(N); return 0;}", "e": 26850, "s": 26295, "text": null }, { "code": "// Java program to find the angle// of Rotational Symmetry of// an N-sided regular polygonimport java.io.*;class GFG{ // function to find required// minimum angle of rotationstatic double minAnglRot(int N){ // Store the answer in // a double variable double res; // Calculating the angle // of rotation and type- // casting the integer N // to double type res = 360 / (double)N; return res;} // Driver codepublic static void main (String[] args){ int N = 4; System.out.println(\"Angle of Rotational Symmetry: \" + minAnglRot(N));}} // This code is contributed by shivanisinghss2110", "e": 27506, "s": 26850, "text": null }, { "code": "# Python3 program to find the angle# of Rotational Symmetry of# an N-sided regular polygon # Function to find required# minimum angle of rotationdef minAnglRot(N): # Store the answer in a # variable # Calculating the angle # of rotation and type- # casting the integer N # to type res = 360 // N return res # Driver codeif __name__ == '__main__': N = 4; print(\"Angle of Rotational Symmetry: \", minAnglRot(N)) # This code is contributed by mohit kumar 29 ", "e": 28023, "s": 27506, "text": null }, { "code": "// C# program to find the angle// of Rotational Symmetry of// an N-sided regular polygonusing System;class GFG{ // function to find required// minimum angle of rotationstatic double minAnglRot(int N){ // Store the answer in // a double variable double res; // Calculating the angle // of rotation and type- // casting the integer N // to double type res = 360 / (double)N; return res;} // Driver codepublic static void Main (string[] args){ int N = 4; Console.Write(\"Angle of Rotational Symmetry: \" + minAnglRot(N));}} // This code is contributed by rock_cool", "e": 28659, "s": 28023, "text": null }, { "code": "<script> // Javascript program to find the angle// of Rotational Symmetry of an N-sided// regular polygon // Function to find required// minimum angle of rotationfunction minAnglRot(N){ // Store the answer in // a double variable let res; // Calculating the angle of // rotation and type-casting // the integer N to double type res = 360 / N; return res;} // Driver codelet N = 4; document.write(\"Angle of Rotational Symmetry: \" + minAnglRot(N)); // This code is contributed by divyeshrabadiya07 </script>", "e": 29210, "s": 28659, "text": null }, { "code": null, "e": 29243, "s": 29210, "text": "Angle of Rotational Symmetry: 90" }, { "code": null, "e": 29292, "s": 29245, "text": "Time Complexity: O (1) Auxiliary Space: O (1) " }, { "code": null, "e": 29307, "s": 29292, "text": "mohit kumar 29" }, { "code": null, "e": 29326, "s": 29307, "text": "shivanisinghss2110" }, { "code": null, "e": 29336, "s": 29326, "text": "rock_cool" }, { "code": null, "e": 29354, "s": 29336, "text": "divyeshrabadiya07" }, { "code": null, "e": 29364, "s": 29354, "text": "Geometric" }, { "code": null, "e": 29377, "s": 29364, "text": "Mathematical" }, { "code": null, "e": 29390, "s": 29377, "text": "Mathematical" }, { "code": null, "e": 29400, "s": 29390, "text": "Geometric" }, { "code": null, "e": 29498, "s": 29400, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29507, "s": 29498, "text": "Comments" }, { "code": null, "e": 29520, "s": 29507, "text": "Old Comments" }, { "code": null, "e": 29573, "s": 29520, "text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)" }, { "code": null, "e": 29622, "s": 29573, "text": "Closest Pair of Points | O(nlogn) Implementation" }, { "code": null, "e": 29673, "s": 29622, "text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)" }, { "code": null, "e": 29731, "s": 29673, "text": "Given n line segments, find if any two segments intersect" }, { "code": null, "e": 29765, "s": 29731, "text": "Convex Hull | Set 2 (Graham Scan)" }, { "code": null, "e": 29795, "s": 29765, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 29810, "s": 29795, "text": "C++ Data Types" }, { "code": null, "e": 29870, "s": 29810, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 29913, "s": 29870, "text": "Set in C++ Standard Template Library (STL)" } ]
Foundation - Tabs
It is a navigation-based tab that displays the content into different panes without leaving the page. The following example demonstrates the use of tabs in Foundation − <!doctype html> <head> <meta charset = "utf-8" /> <meta http-equiv = "x-ua-compatible" content = "ie = edge" /> <meta name = "viewport" content = "width = device-width, initial-scale = 1.0" /> <title>Tabs</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/foundation.min.css" integrity="sha256-1mcRjtAxlSjp6XJBgrBeeCORfBp/ppyX4tsvpQVCcpA= sha384-b5S5X654rX3Wo6z5/hnQ4GBmKuIJKMPwrJXn52ypjztlnDK2w9+9hSMBz/asy9Gw sha512-M1VveR2JGzpgWHb0elGqPTltHK3xbvu3Brgjfg4cg5ZNtyyApxw/45yHYsZ/rCVbfoO5MSZxB241wWq642jLtA==" crossorigin="anonymous"> <!-- Compressed JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.0.1/js/vendor/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/foundation.min.js" integrity="sha256-WUKHnLrIrx8dew//IpSEmPN/NT3DGAEmIePQYIEJLLs= sha384-53StQWuVbn6figscdDC3xV00aYCPEz3srBdV/QGSXw3f19og3Tq2wTRe0vJqRTEO sha512-X9O+2f1ty1rzBJOC8AXBnuNUdyJg0m8xMKmbt9I3Vu/UOWmSg5zG+dtnje4wAZrKtkopz/PEDClHZ1LXx5IeOw==" crossorigin="anonymous"></script> </head> <body> <h2>Tabs Example</h2> <ul class = "tabs" data-tabs id = "tabs_example"> <li class = "tabs-title is-active"><a href = "#tab1">Player 1</a></li> <li class = "tabs-title"><a href = "#tab2">Player 2</a></li> <li class = "tabs-title"><a href = "#tab3">Player 3</a></li> <li class = "tabs-title"><a href = "#tab4">Player 4</a></li> <li class = "tabs-title"><a href = "#tab5">Player 5</a></li> </ul> <div class = "tabs-content" data-tabs-content = "tabs_example"> <div class = "tabs-panel is-active" id = "tab1"> <p>First Player</p> <p>Sachin Tendulkar</p> </div> <div class = "tabs-panel" id = "tab2"> <p>Second Player</p> <p>M S Dhoni</p> </div> <div class = "tabs-panel" id = "tab3"> <p>Third Player</p> <p>Shane Warne</p> </div> <div class = "tabs-panel" id = "tab4"> <p>Fourth Player</p> <p>Shaun Pollock</p> </div> <div class = "tabs-panel" id = "tab5"> <p>Five Player</p> <p>Adam Gilchrist</p> </div> </div> <script> $(document).ready(function() { $(document).foundation(); }) </script> </body> </html> Let us carry out the following steps to see how the above given code works − Save the above given html code tabs.html file. Save the above given html code tabs.html file. Open this HTML file in a browser, an output is displayed as shown below. Open this HTML file in a browser, an output is displayed as shown below. Player 1 Player 2 Player 3 Player 4 Player 5 First Player Sachin Tendulkar Second Player M S Dhoni Third Player Shane Warne Fourth Player Shaun Pollock Five Player Adam Gilchrist 117 Lectures 5.5 hours Shakthi Swaroop 61 Lectures 1.5 hours Hans Weemaes 17 Lectures 4 hours Stephen Kahuria 8 Lectures 50 mins Zenva 28 Lectures 2 hours Sandra L 16 Lectures 2.5 hours GreyCampus Inc. Print Add Notes Bookmark this page
[ { "code": null, "e": 2340, "s": 2238, "text": "It is a navigation-based tab that displays the content into different panes without leaving the page." }, { "code": null, "e": 2407, "s": 2340, "text": "The following example demonstrates the use of tabs in Foundation −" }, { "code": null, "e": 4898, "s": 2407, "text": "<!doctype html>\n <head>\n <meta charset = \"utf-8\" />\n <meta http-equiv = \"x-ua-compatible\" content = \"ie = edge\" />\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1.0\" />\n\n <title>Tabs</title>\n\n <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/foundation.min.css\" integrity=\"sha256-1mcRjtAxlSjp6XJBgrBeeCORfBp/ppyX4tsvpQVCcpA= sha384-b5S5X654rX3Wo6z5/hnQ4GBmKuIJKMPwrJXn52ypjztlnDK2w9+9hSMBz/asy9Gw sha512-M1VveR2JGzpgWHb0elGqPTltHK3xbvu3Brgjfg4cg5ZNtyyApxw/45yHYsZ/rCVbfoO5MSZxB241wWq642jLtA==\" crossorigin=\"anonymous\">\n\n <!-- Compressed JavaScript -->\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/foundation/6.0.1/js/vendor/jquery.min.js\"></script>\n <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/js/foundation.min.js\" integrity=\"sha256-WUKHnLrIrx8dew//IpSEmPN/NT3DGAEmIePQYIEJLLs= sha384-53StQWuVbn6figscdDC3xV00aYCPEz3srBdV/QGSXw3f19og3Tq2wTRe0vJqRTEO sha512-X9O+2f1ty1rzBJOC8AXBnuNUdyJg0m8xMKmbt9I3Vu/UOWmSg5zG+dtnje4wAZrKtkopz/PEDClHZ1LXx5IeOw==\" crossorigin=\"anonymous\"></script>\n\n </head>\n\n <body>\n <h2>Tabs Example</h2>\n\n <ul class = \"tabs\" data-tabs id = \"tabs_example\">\n <li class = \"tabs-title is-active\"><a href = \"#tab1\">Player 1</a></li>\n <li class = \"tabs-title\"><a href = \"#tab2\">Player 2</a></li>\n <li class = \"tabs-title\"><a href = \"#tab3\">Player 3</a></li>\n <li class = \"tabs-title\"><a href = \"#tab4\">Player 4</a></li>\n <li class = \"tabs-title\"><a href = \"#tab5\">Player 5</a></li>\n </ul>\n\n <div class = \"tabs-content\" data-tabs-content = \"tabs_example\">\n <div class = \"tabs-panel is-active\" id = \"tab1\">\n <p>First Player</p>\n <p>Sachin Tendulkar</p>\n </div>\n\n <div class = \"tabs-panel\" id = \"tab2\">\n <p>Second Player</p>\n <p>M S Dhoni</p>\n </div>\n\n <div class = \"tabs-panel\" id = \"tab3\">\n <p>Third Player</p>\n <p>Shane Warne</p>\n </div>\n\n <div class = \"tabs-panel\" id = \"tab4\">\n <p>Fourth Player</p>\n <p>Shaun Pollock</p>\n </div>\n\n <div class = \"tabs-panel\" id = \"tab5\">\n <p>Five Player</p>\n <p>Adam Gilchrist</p>\n </div>\n\n </div>\n\n <script>\n $(document).ready(function() {\n $(document).foundation();\n })\n </script>\n </body>\n</html>" }, { "code": null, "e": 4975, "s": 4898, "text": "Let us carry out the following steps to see how the above given code works −" }, { "code": null, "e": 5022, "s": 4975, "text": "Save the above given html code tabs.html file." }, { "code": null, "e": 5069, "s": 5022, "text": "Save the above given html code tabs.html file." }, { "code": null, "e": 5142, "s": 5069, "text": "Open this HTML file in a browser, an output is displayed as shown below." }, { "code": null, "e": 5215, "s": 5142, "text": "Open this HTML file in a browser, an output is displayed as shown below." }, { "code": null, "e": 5224, "s": 5215, "text": "Player 1" }, { "code": null, "e": 5233, "s": 5224, "text": "Player 2" }, { "code": null, "e": 5242, "s": 5233, "text": "Player 3" }, { "code": null, "e": 5251, "s": 5242, "text": "Player 4" }, { "code": null, "e": 5260, "s": 5251, "text": "Player 5" }, { "code": null, "e": 5273, "s": 5260, "text": "First Player" }, { "code": null, "e": 5290, "s": 5273, "text": "Sachin Tendulkar" }, { "code": null, "e": 5304, "s": 5290, "text": "Second Player" }, { "code": null, "e": 5314, "s": 5304, "text": "M S Dhoni" }, { "code": null, "e": 5327, "s": 5314, "text": "Third Player" }, { "code": null, "e": 5339, "s": 5327, "text": "Shane Warne" }, { "code": null, "e": 5353, "s": 5339, "text": "Fourth Player" }, { "code": null, "e": 5367, "s": 5353, "text": "Shaun Pollock" }, { "code": null, "e": 5379, "s": 5367, "text": "Five Player" }, { "code": null, "e": 5394, "s": 5379, "text": "Adam Gilchrist" }, { "code": null, "e": 5430, "s": 5394, "text": "\n 117 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5447, "s": 5430, "text": " Shakthi Swaroop" }, { "code": null, "e": 5482, "s": 5447, "text": "\n 61 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5496, "s": 5482, "text": " Hans Weemaes" }, { "code": null, "e": 5529, "s": 5496, "text": "\n 17 Lectures \n 4 hours \n" }, { "code": null, "e": 5546, "s": 5529, "text": " Stephen Kahuria" }, { "code": null, "e": 5577, "s": 5546, "text": "\n 8 Lectures \n 50 mins\n" }, { "code": null, "e": 5584, "s": 5577, "text": " Zenva" }, { "code": null, "e": 5617, "s": 5584, "text": "\n 28 Lectures \n 2 hours \n" }, { "code": null, "e": 5627, "s": 5617, "text": " Sandra L" }, { "code": null, "e": 5662, "s": 5627, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5679, "s": 5662, "text": " GreyCampus Inc." }, { "code": null, "e": 5686, "s": 5679, "text": " Print" }, { "code": null, "e": 5697, "s": 5686, "text": " Add Notes" } ]
How to Spoof SMS Message in Linux ? - GeeksforGeeks
18 Jul, 2021 In this article, we will show how to spoof SMS messages in Linux using two of the following tools:- fake-smsSocial Engineering Toolkit (SET) fake-sms Social Engineering Toolkit (SET) It is a tool written in simple script to send SMS anonymously. Send sms anonymously Fast sms delivery International sms sending available. One can send only one sms per day. Easy to install and use. First, one needs to clone the tool from github repo using the following command: git clone https://github.com/machine1337/fake-sms Change directory by, cd fake-sms Now we need to change permission before running it. chmod +x run.sh Run this tool first by typing the following command in your terminal window, ./run.sh Type 1 and hit enter to see the usage of this tool. Sending Fake SMS: Make sure that you use the victim’s country code and it should be without + and shouldn’t start with 0. For eg, 923443210111. Now enter your victim’s phone number with the country code and then type the message you want to send. Checking SMS status: Now to check your sms status, copy the text id which was shown when you sent the message. We can see from the above image that the status of our message is showing delivered, which means our message has been successfully delivered without any errors. Go to your applications and search social engineering toolkit and hit enter or simply type the following command: sudo setoolkit Type 1 to select social-engineering attacks. SMS Spoofing : Select SMS spoofing by typing 7 and hit enter. Spoofed Text Message: Type 1 again to perform an SMS spoofing attack. Crafting message: Type 1 to select an SMS attack to a single phone number, and enter the phone number preceded by ‘+’ and country code. Then, select to one-time use SMS option. Target’s Mob Number: Enter your target’s phone number and then enter the message you want to send. Select intermediary: Select the intermediary for the spoofed SMS message from the given 4 options. Select the first option. It is the only one free, the rest 3 are paid but it is buggy and might not work. So select option 3 which is a paid one, enter your pincode and send the message. And just like that, your spoofed message is sent. How To Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install FFmpeg on Windows? How to Install Jupyter Notebook on MacOS? How to Install Flutter on Visual Studio Code? How to Override compareTo Method in Java? How to Install Python Pandas on MacOS? AWK command in Unix/Linux with examples Sed Command in Linux/Unix with examples grep command in Unix/Linux TCP Server-Client implementation in C cut command in Linux with examples
[ { "code": null, "e": 24586, "s": 24558, "text": "\n18 Jul, 2021" }, { "code": null, "e": 24686, "s": 24586, "text": "In this article, we will show how to spoof SMS messages in Linux using two of the following tools:-" }, { "code": null, "e": 24727, "s": 24686, "text": "fake-smsSocial Engineering Toolkit (SET)" }, { "code": null, "e": 24736, "s": 24727, "text": "fake-sms" }, { "code": null, "e": 24769, "s": 24736, "text": "Social Engineering Toolkit (SET)" }, { "code": null, "e": 24832, "s": 24769, "text": "It is a tool written in simple script to send SMS anonymously." }, { "code": null, "e": 24853, "s": 24832, "text": "Send sms anonymously" }, { "code": null, "e": 24871, "s": 24853, "text": "Fast sms delivery" }, { "code": null, "e": 24908, "s": 24871, "text": "International sms sending available." }, { "code": null, "e": 24943, "s": 24908, "text": "One can send only one sms per day." }, { "code": null, "e": 24968, "s": 24943, "text": "Easy to install and use." }, { "code": null, "e": 25049, "s": 24968, "text": "First, one needs to clone the tool from github repo using the following command:" }, { "code": null, "e": 25100, "s": 25049, "text": " git clone https://github.com/machine1337/fake-sms" }, { "code": null, "e": 25121, "s": 25100, "text": "Change directory by," }, { "code": null, "e": 25133, "s": 25121, "text": "cd fake-sms" }, { "code": null, "e": 25185, "s": 25133, "text": "Now we need to change permission before running it." }, { "code": null, "e": 25201, "s": 25185, "text": "chmod +x run.sh" }, { "code": null, "e": 25278, "s": 25201, "text": "Run this tool first by typing the following command in your terminal window," }, { "code": null, "e": 25287, "s": 25278, "text": "./run.sh" }, { "code": null, "e": 25339, "s": 25287, "text": "Type 1 and hit enter to see the usage of this tool." }, { "code": null, "e": 25586, "s": 25339, "text": "Sending Fake SMS: Make sure that you use the victim’s country code and it should be without + and shouldn’t start with 0. For eg, 923443210111. Now enter your victim’s phone number with the country code and then type the message you want to send." }, { "code": null, "e": 25697, "s": 25586, "text": "Checking SMS status: Now to check your sms status, copy the text id which was shown when you sent the message." }, { "code": null, "e": 25858, "s": 25697, "text": "We can see from the above image that the status of our message is showing delivered, which means our message has been successfully delivered without any errors." }, { "code": null, "e": 25972, "s": 25858, "text": "Go to your applications and search social engineering toolkit and hit enter or simply type the following command:" }, { "code": null, "e": 25987, "s": 25972, "text": "sudo setoolkit" }, { "code": null, "e": 26032, "s": 25987, "text": "Type 1 to select social-engineering attacks." }, { "code": null, "e": 26094, "s": 26032, "text": "SMS Spoofing : Select SMS spoofing by typing 7 and hit enter." }, { "code": null, "e": 26164, "s": 26094, "text": "Spoofed Text Message: Type 1 again to perform an SMS spoofing attack." }, { "code": null, "e": 26342, "s": 26164, "text": "Crafting message: Type 1 to select an SMS attack to a single phone number, and enter the phone number preceded by ‘+’ and country code. Then, select to one-time use SMS option." }, { "code": null, "e": 26441, "s": 26342, "text": "Target’s Mob Number: Enter your target’s phone number and then enter the message you want to send." }, { "code": null, "e": 26727, "s": 26441, "text": "Select intermediary: Select the intermediary for the spoofed SMS message from the given 4 options. Select the first option. It is the only one free, the rest 3 are paid but it is buggy and might not work. So select option 3 which is a paid one, enter your pincode and send the message." }, { "code": null, "e": 26777, "s": 26727, "text": "And just like that, your spoofed message is sent." }, { "code": null, "e": 26784, "s": 26777, "text": "How To" }, { "code": null, "e": 26795, "s": 26784, "text": "Linux-Unix" }, { "code": null, "e": 26893, "s": 26795, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26902, "s": 26893, "text": "Comments" }, { "code": null, "e": 26915, "s": 26902, "text": "Old Comments" }, { "code": null, "e": 26949, "s": 26915, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 26991, "s": 26949, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 27037, "s": 26991, "text": "How to Install Flutter on Visual Studio Code?" }, { "code": null, "e": 27079, "s": 27037, "text": "How to Override compareTo Method in Java?" }, { "code": null, "e": 27118, "s": 27079, "text": "How to Install Python Pandas on MacOS?" }, { "code": null, "e": 27158, "s": 27118, "text": "AWK command in Unix/Linux with examples" }, { "code": null, "e": 27198, "s": 27158, "text": "Sed Command in Linux/Unix with examples" }, { "code": null, "e": 27225, "s": 27198, "text": "grep command in Unix/Linux" }, { "code": null, "e": 27263, "s": 27225, "text": "TCP Server-Client implementation in C" } ]
Data-Driven Cycling and Workout Prediction | by Ibrahim Kıvanç | Towards Data Science
In this blog post I’ll share how I turned data from my bike exercises into a Machine Learning based smart bot leveraging Microsoft Bot Framework and Microsoft Teams, which helps me achieve more with my training and be motivated all the time. I started cycling with a foldable bike at end of January 2020 and I fell in love with cycling. I also love working with data so I’ve recorded all my rides to Strava with Withings Steel HR smart watch. 🚴🏻🚴🏻 At the end of May I upgraded my city bike to a Gravel bike. I had great time with my new bike with outdoor activities until autumn. After practicing outside with nice weather, for cold weather I setup a pain-cave at my home for virtual rides on Zwift using Elite Arion AL13 roller with Misuro B+ sensor. Zwift is a virtual environment where you connect with your 3D avatar to ride with other athletes real-time. My Zwift account is connected with Strava to collect all my ride data, and I’ve completed “3700km” so far combining outdoor and indoor activities 🎉🎉 I’ve decided to analyze my data and after analyzing I’ve decided to take this to the next level with my engineering capabilities. This repo shows how to analyze your Strava data and visualize it using Jupyter Notebooks. Furthermore, this project aims to predict potential workout days and distance to find an optimal workout routine using your own data. This digital personal trainer can be used as a workout companion. This project first started as a data discovery of existing bulk data on Jupyter Notebook. During data exploration phase I saw some patterns and thought that, these patterns could help me get back in shape again. Shortly after, I’ve decided to build a predictive model to predict my workout, ride type and distance values. To use the prediction model within a bot framework, the model is exported as pickle file, a FastAPI based app serves the model in Python and a chat bot on Microsoft Teams calling this API help me to provide some inputs and then retrieve prediction. Let’s have a look at some highlights I achieved so far, here are some highlights about my data. In 1 year, I’ve completed around 3700 km including outdoor and indoor workout activities. Around 1/3 are virtual rides on Zwift. In 2019, I gained some fat, but as a result of my physical activities and some healthy food, I lost ~13kgs (~28lbs) during this time. I love below weekly graph showcasing all important life events happened in one year. Jan-Mar: A lot of a passion for workout April-June: Pandemic and lockdown in Turkey June-December: Enjoying riding outdoor and indoor December: new year break challenge #Rapha500 Jan: Blessed with a new family member :) Jan — March: Trying to find my old routine again, last but not least decided to build a digital personal trainer. So far, my longest distance in one ride is 62km, and I love this graph showing my performance over time; While I was checking ride types, I realized that after a certain point I only switched to Indoor Virtual Ride and I wanted to see if there’s a correlation between selecting indoor rides and the weather, specifically with Wind and Temperature. For that I used a Weather API to retrieve Weather condition during my workouts and results were clear; I don't like cycling at cold, rainy weathers, so after a point I switched back to just Indoor Virtual Rides. The graph below shows that below a certain temperature, I picked Indoor Ride. This is one of the features - I have added into my model for prediction. I spent some time to visualize my ride data using Jupyter Notebook and I found some patterns. These patterns were either conscious decisions by me or some decisions due to conditions. I decided to do an exercise on Feature Engineering Ride type is a factor for impacting the duration and day of the training , so I added a flag to signify whether a ride is a outdoor or indoor rideType — boolean flag As mentioned in the correlation, weather is one of the factors that affect my workout plan: Temperature - Celsius value as integer Wind - km/h value as integer Weather Description - Description if weather is cloudy, sunny, rainy etc. When I plotted the distance vs. weekend or weekdays, I found that my longest rides were on the weekend. Public holidays were another factor but for now, I’ve decided not to integrate those. DayOfWeek - integer But mostly I picked Tuesday and Thursday as weekday short ride days, and decided to add week of the day as a feature and use weekends as flag based on below graph isWeekend - boolean flag In hot summer days, I prefer early outdoor rides when the temperature is cooler than noon time. Based on the following plot, the hour of the day is effecting my ride and ride type as well so I’ve decided to add a feature for hour of the day hour - integer For my personal need and following the data analysis I wish to have a prediction which outputs the distance, i.e. how many kilometers I'm expected to ride and the ride type, i.e. whether the planned ride is indoor or outdoor. Therefore, I used the previous data analysis and engineered features to create a prediction model for Distance and Ride Type. For mental preparation, there are differences between riding indoor and outdoor, so generally I do prepare myself and my ride equipment the day before my workout based on my ride type. I do prefer going outside however I don’t like rainy and cold weather. In addition, I’d like to find the optimal the ride for my workout. This choice is also affecting my distance and hour of workout. Since it’s a classification problem, I have decided to pick Logistic Regression for predicting the ride type. Set training data: Every week, I set weekly distance goals I’d like to complete. The decision is also affected by external factors such as at “what time of the day?”, “How is the weather?”, “Is it hot outside or cold outside?”, “Is it windy?”, “Is it weekend or a weekday?” Given these factors, I’d like to predict my expected ride distance. This is a Regression problem and I've decided to pick Linear Regression for distance prediction. For both models (predicting distance and ride type), here are the engineered features I’ve decided to use in my models: ['hour','dayOfWeek','isWeekend','temp','wind','weather'] While I have decided to pick Logistic Regression for ride type and Linear Regression for distance, there could be more accurate models. The process of developing these models, is iterative and often requires more ride data, so this is just first step. There is a nice Machine Learning algorithm cheat sheet. You can learn more about ML algorithms and their applications. For workout prediction, Machine Learning model training is added into 7 — b Predict Workout Model Training.ipynb Jupyter notebook. Here are some steps covering steps to train a model: First I set training data with selected features (X): # select features as list of arrayX = data[['hour','dayOfWeek','isWeekend','temp','wind','weather']]X = X.to_numpy() Then I create the training data’s labels (Y): # set Distance valuesY_distance = data['Distance']Y_distance = Y_distance.to_numpy()​# set Ride Type ValuesY_rideType = data['rideType']Y_rideType = Y_rideType.to_numpy() Logistic Regression for RideType Prediction Logistic Regression for RideType Prediction For logistic regression I am providing all data for training and fit my final model. The model uses following features ['hour','dayOfWeek','isWeekend','temp','wind','weather']. Training data features: hour - value between 0 - 23 dayOfWeek - value between 0 - 6 isWeekend - for weekdays 0, for weekend 1 temp - integer temperature value in Celsius wind - integer wind value in km/h weather - weather description provided by Weather API Training prediction value: rideType - for outdoor cycling 0, for indoor cycling 1 # import Logistic Regression from sci-kit learnfrom sklearn.linear_model import LogisticRegression​# select training data and fit final modelmodel_lr = LogisticRegression(random_state=0).fit(X, Y_rideType)​# test prediction with a clear sunny Sunday weather dataresult_ridetype = model_lr.predict([[8,6,1,20,3,0]])print("Result type prediction=%s" % result_ridetype)​# test prediction with a cold Sunday weather dataresult_ridetype = model_lr.predict([[8,6,1,10,12,1]])print("Result type prediction=%s" % result_ridetype) 2. Linear Regression for distance prediction For prediction model I have total 168 workout data and I would like to use all of them as training data. Training data features: hour - value between 0 - 23 dayOfWeek - value between 0 - 6 isWeekend - for weekdays 0, for weekend 1 temp - integer temperature value in Celsius wind - integer wind value in km/h weather - weather description provided by Weather API Training prediction value: distance - distance value in kilometers. # import Linear Regression from sci-kit learnfrom sklearn.linear_model import LinearRegressionfrom sklearn.utils import shuffle# select training data and fit final modelmodel = LinearRegression()model.fit(X, Y_distance)# test prediction with a cold Monday weather dataresult_distance = model.predict([[8,0,0,10,15,0]])print("Result distance prediction=%s" % result_distance)# test prediction with a sunny Sunday weather dataresult_distance = model.predict([[6,6,1,26,3,1]])print("Result distance prediction=%s" % result_distance) 3. Export models as pickle file At this phase the trained models are exported as pickle files to be used via a web API. The web API is consuming data from a Weather API, collects necessary data features for prediction and outputs the prediction to the user. # import pickle libraryimport pickle​# save distance model file in the model folder for predictiondistance_model_file = "../web/model/distance_model.pkl"with open(distance_model_file, 'wb') as file: pickle.dump(model, file)​# save ride type model file in the model folder for predictionridetype_model_file = "../web/model/ridetype_model.pkl"with open(ridetype_model_file, 'wb') as file: pickle.dump(clf, file) This is an end-to-end solution, using Strava workout data exports as input. Strava contains indoor and outdoor workout ride data. To analyze the data, Jupyter Notebooks are used for Data Cleaning, Data Pre-Processing, Model Training and `Model Export. For machine learning model training and prediction, the scikit-learn Python package is used. The prediction model is exported by scikit-learn to predict my ride type and distance of my workout. The model, as a pickle file is hosted through FastAPI app which provides an API to pass parameters and predict weather information using 3rd party weather API. These values are used by the model for prediction. As a user interface, I’ve created a Conversational AI project using Microsoft Bot Framework to communicate with Fast API. I picked Microsoft Teams as canvas, since this is the platform I use regularly to communicate. With this solution I now can select my city, workout date and time, and I get a prediction providing distance and ride type values. Folder Structure: bot - Bot application to retrieve prediction model data - Data folder contains Strava output notebooks -All notebooks to analyze all data web - FastAPI for prediction model model - Contains models for prediction app.py - FastAPI web app for prediction model myconfig.py - Environmental variables utils.py - Common utility functions In this sample, Python 3.8.7 version is used, to run the project. Create virtual environment Create virtual environment python -m venv .venv 2. Activate your virtual environment for Mac: source ./venv/bin/activate 3. Install dependencies pip install -r notebooks/requirements.txt 4. Export your Strava Data from your profile Visit Settings > My Account > Download or Delete Your Account Click Download Request (optional) Download zip file to export into Data folder. 5. Create a Data folder and export your Strava Data into this folder. 6. Run Jupyter Notebook in your local jupyter notebook Weather data was not available to correlate with my workouts, so I’ve used a weather API to extract weather information for my existing workout days. I’ve used WorldWeatherOnline API for the latest weather forecasts for my ride locations. This API also offers weather forecasts up to 14 days in advance, hourly forecasting and weather warnings so this is very helpful for my prediction API as well. Run Python FastAPI for running on your local machine cd webpython app.py Predict Ride Type & Distance http://127.0.0.1:8000/predict?city=Istanbul&date=2021-04-10&time=14:00:00 Publish Python FastAPI to Azure Web App service cd webaz webapp up --sku B1 --name data-driven-cycling Update startup command on Azure Portal, Settings > Configuration > General settings > Startup Command gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app to re-deploy and update existing application: az webapp up Prerequisite: .NET Core SDK version 3.1 cd botdotnet run Or from Visual Studio Launch Visual Studio File -> Open -> Project/Solution Navigate to bot folder Select CyclingPrediction.csproj file Update your api url in Bots/Cycling.cs If you would like to test with your local Web API change to your local endpoint such as: string RequestURI = String.Format("http://127.0.0.1:8000/predict?city={0}&date={1}&time={2}",wCity,wDate,wTime); If you’ll test with your Azure Web API change to your azure endpoint such as: string RequestURI = String.Format("https://yourwebsite.azurewebsites.net/predict?city={0}&date={1}&time={2}",wCity,wDate,wTime); Press F5 to run the project Your bot service will be available at https://localhost:3979. Run your Bot Framework Emulator and connect to https://localhost:3979 endpoint After that your bot is ready for interaction. After you publish the bot you can connect with different conversational UI. I’ve connected with Microsoft Teams and named as Data Driven Cycling Bot. Once you send first message, it’s sending a card to pick City, Date and Time information to predict workout ride type and minimum distance. This has been a personal journey to discover insights from my existing data, then it turned out to a digital personal trainer. For next steps I would like to focus on, Setting a weekly target and predicting workout schedule for the week based on my target. Compare ride metrics and see the improvement over time. Supporting US metrics (now only supports km) Code is available athttps://github.com/ikivanc/Data-Driven-Cycling-and-Workout-Prediction Looking forward to hear new ideas and open for contributions.
[ { "code": null, "e": 413, "s": 171, "text": "In this blog post I’ll share how I turned data from my bike exercises into a Machine Learning based smart bot leveraging Microsoft Bot Framework and Microsoft Teams, which helps me achieve more with my training and be motivated all the time." }, { "code": null, "e": 619, "s": 413, "text": "I started cycling with a foldable bike at end of January 2020 and I fell in love with cycling. I also love working with data so I’ve recorded all my rides to Strava with Withings Steel HR smart watch. 🚴🏻🚴🏻" }, { "code": null, "e": 751, "s": 619, "text": "At the end of May I upgraded my city bike to a Gravel bike. I had great time with my new bike with outdoor activities until autumn." }, { "code": null, "e": 1031, "s": 751, "text": "After practicing outside with nice weather, for cold weather I setup a pain-cave at my home for virtual rides on Zwift using Elite Arion AL13 roller with Misuro B+ sensor. Zwift is a virtual environment where you connect with your 3D avatar to ride with other athletes real-time." }, { "code": null, "e": 1180, "s": 1031, "text": "My Zwift account is connected with Strava to collect all my ride data, and I’ve completed “3700km” so far combining outdoor and indoor activities 🎉🎉" }, { "code": null, "e": 1310, "s": 1180, "text": "I’ve decided to analyze my data and after analyzing I’ve decided to take this to the next level with my engineering capabilities." }, { "code": null, "e": 1600, "s": 1310, "text": "This repo shows how to analyze your Strava data and visualize it using Jupyter Notebooks. Furthermore, this project aims to predict potential workout days and distance to find an optimal workout routine using your own data. This digital personal trainer can be used as a workout companion." }, { "code": null, "e": 2171, "s": 1600, "text": "This project first started as a data discovery of existing bulk data on Jupyter Notebook. During data exploration phase I saw some patterns and thought that, these patterns could help me get back in shape again. Shortly after, I’ve decided to build a predictive model to predict my workout, ride type and distance values. To use the prediction model within a bot framework, the model is exported as pickle file, a FastAPI based app serves the model in Python and a chat bot on Microsoft Teams calling this API help me to provide some inputs and then retrieve prediction." }, { "code": null, "e": 2267, "s": 2171, "text": "Let’s have a look at some highlights I achieved so far, here are some highlights about my data." }, { "code": null, "e": 2396, "s": 2267, "text": "In 1 year, I’ve completed around 3700 km including outdoor and indoor workout activities. Around 1/3 are virtual rides on Zwift." }, { "code": null, "e": 2530, "s": 2396, "text": "In 2019, I gained some fat, but as a result of my physical activities and some healthy food, I lost ~13kgs (~28lbs) during this time." }, { "code": null, "e": 2615, "s": 2530, "text": "I love below weekly graph showcasing all important life events happened in one year." }, { "code": null, "e": 2655, "s": 2615, "text": "Jan-Mar: A lot of a passion for workout" }, { "code": null, "e": 2699, "s": 2655, "text": "April-June: Pandemic and lockdown in Turkey" }, { "code": null, "e": 2749, "s": 2699, "text": "June-December: Enjoying riding outdoor and indoor" }, { "code": null, "e": 2794, "s": 2749, "text": "December: new year break challenge #Rapha500" }, { "code": null, "e": 2835, "s": 2794, "text": "Jan: Blessed with a new family member :)" }, { "code": null, "e": 2949, "s": 2835, "text": "Jan — March: Trying to find my old routine again, last but not least decided to build a digital personal trainer." }, { "code": null, "e": 3054, "s": 2949, "text": "So far, my longest distance in one ride is 62km, and I love this graph showing my performance over time;" }, { "code": null, "e": 3660, "s": 3054, "text": "While I was checking ride types, I realized that after a certain point I only switched to Indoor Virtual Ride and I wanted to see if there’s a correlation between selecting indoor rides and the weather, specifically with Wind and Temperature. For that I used a Weather API to retrieve Weather condition during my workouts and results were clear; I don't like cycling at cold, rainy weathers, so after a point I switched back to just Indoor Virtual Rides. The graph below shows that below a certain temperature, I picked Indoor Ride. This is one of the features - I have added into my model for prediction." }, { "code": null, "e": 3844, "s": 3660, "text": "I spent some time to visualize my ride data using Jupyter Notebook and I found some patterns. These patterns were either conscious decisions by me or some decisions due to conditions." }, { "code": null, "e": 3895, "s": 3844, "text": "I decided to do an exercise on Feature Engineering" }, { "code": null, "e": 4037, "s": 3895, "text": "Ride type is a factor for impacting the duration and day of the training , so I added a flag to signify whether a ride is a outdoor or indoor" }, { "code": null, "e": 4061, "s": 4037, "text": "rideType — boolean flag" }, { "code": null, "e": 4153, "s": 4061, "text": "As mentioned in the correlation, weather is one of the factors that affect my workout plan:" }, { "code": null, "e": 4192, "s": 4153, "text": "Temperature - Celsius value as integer" }, { "code": null, "e": 4221, "s": 4192, "text": "Wind - km/h value as integer" }, { "code": null, "e": 4295, "s": 4221, "text": "Weather Description - Description if weather is cloudy, sunny, rainy etc." }, { "code": null, "e": 4485, "s": 4295, "text": "When I plotted the distance vs. weekend or weekdays, I found that my longest rides were on the weekend. Public holidays were another factor but for now, I’ve decided not to integrate those." }, { "code": null, "e": 4505, "s": 4485, "text": "DayOfWeek - integer" }, { "code": null, "e": 4668, "s": 4505, "text": "But mostly I picked Tuesday and Thursday as weekday short ride days, and decided to add week of the day as a feature and use weekends as flag based on below graph" }, { "code": null, "e": 4693, "s": 4668, "text": "isWeekend - boolean flag" }, { "code": null, "e": 4934, "s": 4693, "text": "In hot summer days, I prefer early outdoor rides when the temperature is cooler than noon time. Based on the following plot, the hour of the day is effecting my ride and ride type as well so I’ve decided to add a feature for hour of the day" }, { "code": null, "e": 4949, "s": 4934, "text": "hour - integer" }, { "code": null, "e": 5175, "s": 4949, "text": "For my personal need and following the data analysis I wish to have a prediction which outputs the distance, i.e. how many kilometers I'm expected to ride and the ride type, i.e. whether the planned ride is indoor or outdoor." }, { "code": null, "e": 5301, "s": 5175, "text": "Therefore, I used the previous data analysis and engineered features to create a prediction model for Distance and Ride Type." }, { "code": null, "e": 5624, "s": 5301, "text": "For mental preparation, there are differences between riding indoor and outdoor, so generally I do prepare myself and my ride equipment the day before my workout based on my ride type. I do prefer going outside however I don’t like rainy and cold weather. In addition, I’d like to find the optimal the ride for my workout." }, { "code": null, "e": 5797, "s": 5624, "text": "This choice is also affecting my distance and hour of workout. Since it’s a classification problem, I have decided to pick Logistic Regression for predicting the ride type." }, { "code": null, "e": 5816, "s": 5797, "text": "Set training data:" }, { "code": null, "e": 6071, "s": 5816, "text": "Every week, I set weekly distance goals I’d like to complete. The decision is also affected by external factors such as at “what time of the day?”, “How is the weather?”, “Is it hot outside or cold outside?”, “Is it windy?”, “Is it weekend or a weekday?”" }, { "code": null, "e": 6236, "s": 6071, "text": "Given these factors, I’d like to predict my expected ride distance. This is a Regression problem and I've decided to pick Linear Regression for distance prediction." }, { "code": null, "e": 6356, "s": 6236, "text": "For both models (predicting distance and ride type), here are the engineered features I’ve decided to use in my models:" }, { "code": null, "e": 6413, "s": 6356, "text": "['hour','dayOfWeek','isWeekend','temp','wind','weather']" }, { "code": null, "e": 6665, "s": 6413, "text": "While I have decided to pick Logistic Regression for ride type and Linear Regression for distance, there could be more accurate models. The process of developing these models, is iterative and often requires more ride data, so this is just first step." }, { "code": null, "e": 6784, "s": 6665, "text": "There is a nice Machine Learning algorithm cheat sheet. You can learn more about ML algorithms and their applications." }, { "code": null, "e": 6968, "s": 6784, "text": "For workout prediction, Machine Learning model training is added into 7 — b Predict Workout Model Training.ipynb Jupyter notebook. Here are some steps covering steps to train a model:" }, { "code": null, "e": 7022, "s": 6968, "text": "First I set training data with selected features (X):" }, { "code": null, "e": 7139, "s": 7022, "text": "# select features as list of arrayX = data[['hour','dayOfWeek','isWeekend','temp','wind','weather']]X = X.to_numpy()" }, { "code": null, "e": 7185, "s": 7139, "text": "Then I create the training data’s labels (Y):" }, { "code": null, "e": 7356, "s": 7185, "text": "# set Distance valuesY_distance = data['Distance']Y_distance = Y_distance.to_numpy()​# set Ride Type ValuesY_rideType = data['rideType']Y_rideType = Y_rideType.to_numpy()" }, { "code": null, "e": 7400, "s": 7356, "text": "Logistic Regression for RideType Prediction" }, { "code": null, "e": 7444, "s": 7400, "text": "Logistic Regression for RideType Prediction" }, { "code": null, "e": 7621, "s": 7444, "text": "For logistic regression I am providing all data for training and fit my final model. The model uses following features ['hour','dayOfWeek','isWeekend','temp','wind','weather']." }, { "code": null, "e": 7645, "s": 7621, "text": "Training data features:" }, { "code": null, "e": 7673, "s": 7645, "text": "hour - value between 0 - 23" }, { "code": null, "e": 7705, "s": 7673, "text": "dayOfWeek - value between 0 - 6" }, { "code": null, "e": 7747, "s": 7705, "text": "isWeekend - for weekdays 0, for weekend 1" }, { "code": null, "e": 7791, "s": 7747, "text": "temp - integer temperature value in Celsius" }, { "code": null, "e": 7825, "s": 7791, "text": "wind - integer wind value in km/h" }, { "code": null, "e": 7879, "s": 7825, "text": "weather - weather description provided by Weather API" }, { "code": null, "e": 7906, "s": 7879, "text": "Training prediction value:" }, { "code": null, "e": 7961, "s": 7906, "text": "rideType - for outdoor cycling 0, for indoor cycling 1" }, { "code": null, "e": 8483, "s": 7961, "text": "# import Logistic Regression from sci-kit learnfrom sklearn.linear_model import LogisticRegression​# select training data and fit final modelmodel_lr = LogisticRegression(random_state=0).fit(X, Y_rideType)​# test prediction with a clear sunny Sunday weather dataresult_ridetype = model_lr.predict([[8,6,1,20,3,0]])print(\"Result type prediction=%s\" % result_ridetype)​# test prediction with a cold Sunday weather dataresult_ridetype = model_lr.predict([[8,6,1,10,12,1]])print(\"Result type prediction=%s\" % result_ridetype)" }, { "code": null, "e": 8528, "s": 8483, "text": "2. Linear Regression for distance prediction" }, { "code": null, "e": 8633, "s": 8528, "text": "For prediction model I have total 168 workout data and I would like to use all of them as training data." }, { "code": null, "e": 8657, "s": 8633, "text": "Training data features:" }, { "code": null, "e": 8685, "s": 8657, "text": "hour - value between 0 - 23" }, { "code": null, "e": 8717, "s": 8685, "text": "dayOfWeek - value between 0 - 6" }, { "code": null, "e": 8759, "s": 8717, "text": "isWeekend - for weekdays 0, for weekend 1" }, { "code": null, "e": 8803, "s": 8759, "text": "temp - integer temperature value in Celsius" }, { "code": null, "e": 8837, "s": 8803, "text": "wind - integer wind value in km/h" }, { "code": null, "e": 8891, "s": 8837, "text": "weather - weather description provided by Weather API" }, { "code": null, "e": 8918, "s": 8891, "text": "Training prediction value:" }, { "code": null, "e": 8959, "s": 8918, "text": "distance - distance value in kilometers." }, { "code": null, "e": 9489, "s": 8959, "text": "# import Linear Regression from sci-kit learnfrom sklearn.linear_model import LinearRegressionfrom sklearn.utils import shuffle# select training data and fit final modelmodel = LinearRegression()model.fit(X, Y_distance)# test prediction with a cold Monday weather dataresult_distance = model.predict([[8,0,0,10,15,0]])print(\"Result distance prediction=%s\" % result_distance)# test prediction with a sunny Sunday weather dataresult_distance = model.predict([[6,6,1,26,3,1]])print(\"Result distance prediction=%s\" % result_distance)" }, { "code": null, "e": 9521, "s": 9489, "text": "3. Export models as pickle file" }, { "code": null, "e": 9747, "s": 9521, "text": "At this phase the trained models are exported as pickle files to be used via a web API. The web API is consuming data from a Weather API, collects necessary data features for prediction and outputs the prediction to the user." }, { "code": null, "e": 10157, "s": 9747, "text": "# import pickle libraryimport pickle​# save distance model file in the model folder for predictiondistance_model_file = \"../web/model/distance_model.pkl\"with open(distance_model_file, 'wb') as file: pickle.dump(model, file)​# save ride type model file in the model folder for predictionridetype_model_file = \"../web/model/ridetype_model.pkl\"with open(ridetype_model_file, 'wb') as file: pickle.dump(clf, file)" }, { "code": null, "e": 10603, "s": 10157, "text": "This is an end-to-end solution, using Strava workout data exports as input. Strava contains indoor and outdoor workout ride data. To analyze the data, Jupyter Notebooks are used for Data Cleaning, Data Pre-Processing, Model Training and `Model Export. For machine learning model training and prediction, the scikit-learn Python package is used. The prediction model is exported by scikit-learn to predict my ride type and distance of my workout." }, { "code": null, "e": 10814, "s": 10603, "text": "The model, as a pickle file is hosted through FastAPI app which provides an API to pass parameters and predict weather information using 3rd party weather API. These values are used by the model for prediction." }, { "code": null, "e": 11031, "s": 10814, "text": "As a user interface, I’ve created a Conversational AI project using Microsoft Bot Framework to communicate with Fast API. I picked Microsoft Teams as canvas, since this is the platform I use regularly to communicate." }, { "code": null, "e": 11163, "s": 11031, "text": "With this solution I now can select my city, workout date and time, and I get a prediction providing distance and ride type values." }, { "code": null, "e": 11181, "s": 11163, "text": "Folder Structure:" }, { "code": null, "e": 11232, "s": 11181, "text": "bot - Bot application to retrieve prediction model" }, { "code": null, "e": 11274, "s": 11232, "text": "data - Data folder contains Strava output" }, { "code": null, "e": 11319, "s": 11274, "text": "notebooks -All notebooks to analyze all data" }, { "code": null, "e": 11354, "s": 11319, "text": "web - FastAPI for prediction model" }, { "code": null, "e": 11393, "s": 11354, "text": "model - Contains models for prediction" }, { "code": null, "e": 11439, "s": 11393, "text": "app.py - FastAPI web app for prediction model" }, { "code": null, "e": 11477, "s": 11439, "text": "myconfig.py - Environmental variables" }, { "code": null, "e": 11513, "s": 11477, "text": "utils.py - Common utility functions" }, { "code": null, "e": 11579, "s": 11513, "text": "In this sample, Python 3.8.7 version is used, to run the project." }, { "code": null, "e": 11606, "s": 11579, "text": "Create virtual environment" }, { "code": null, "e": 11633, "s": 11606, "text": "Create virtual environment" }, { "code": null, "e": 11654, "s": 11633, "text": "python -m venv .venv" }, { "code": null, "e": 11700, "s": 11654, "text": "2. Activate your virtual environment for Mac:" }, { "code": null, "e": 11727, "s": 11700, "text": "source ./venv/bin/activate" }, { "code": null, "e": 11751, "s": 11727, "text": "3. Install dependencies" }, { "code": null, "e": 11793, "s": 11751, "text": "pip install -r notebooks/requirements.txt" }, { "code": null, "e": 11838, "s": 11793, "text": "4. Export your Strava Data from your profile" }, { "code": null, "e": 11900, "s": 11838, "text": "Visit Settings > My Account > Download or Delete Your Account" }, { "code": null, "e": 11934, "s": 11900, "text": "Click Download Request (optional)" }, { "code": null, "e": 11980, "s": 11934, "text": "Download zip file to export into Data folder." }, { "code": null, "e": 12050, "s": 11980, "text": "5. Create a Data folder and export your Strava Data into this folder." }, { "code": null, "e": 12088, "s": 12050, "text": "6. Run Jupyter Notebook in your local" }, { "code": null, "e": 12105, "s": 12088, "text": "jupyter notebook" }, { "code": null, "e": 12504, "s": 12105, "text": "Weather data was not available to correlate with my workouts, so I’ve used a weather API to extract weather information for my existing workout days. I’ve used WorldWeatherOnline API for the latest weather forecasts for my ride locations. This API also offers weather forecasts up to 14 days in advance, hourly forecasting and weather warnings so this is very helpful for my prediction API as well." }, { "code": null, "e": 12557, "s": 12504, "text": "Run Python FastAPI for running on your local machine" }, { "code": null, "e": 12577, "s": 12557, "text": "cd webpython app.py" }, { "code": null, "e": 12606, "s": 12577, "text": "Predict Ride Type & Distance" }, { "code": null, "e": 12680, "s": 12606, "text": "http://127.0.0.1:8000/predict?city=Istanbul&date=2021-04-10&time=14:00:00" }, { "code": null, "e": 12728, "s": 12680, "text": "Publish Python FastAPI to Azure Web App service" }, { "code": null, "e": 12783, "s": 12728, "text": "cd webaz webapp up --sku B1 --name data-driven-cycling" }, { "code": null, "e": 12885, "s": 12783, "text": "Update startup command on Azure Portal, Settings > Configuration > General settings > Startup Command" }, { "code": null, "e": 12941, "s": 12885, "text": "gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app" }, { "code": null, "e": 12987, "s": 12941, "text": "to re-deploy and update existing application:" }, { "code": null, "e": 13000, "s": 12987, "text": "az webapp up" }, { "code": null, "e": 13014, "s": 13000, "text": "Prerequisite:" }, { "code": null, "e": 13040, "s": 13014, "text": ".NET Core SDK version 3.1" }, { "code": null, "e": 13057, "s": 13040, "text": "cd botdotnet run" }, { "code": null, "e": 13079, "s": 13057, "text": "Or from Visual Studio" }, { "code": null, "e": 13100, "s": 13079, "text": "Launch Visual Studio" }, { "code": null, "e": 13133, "s": 13100, "text": "File -> Open -> Project/Solution" }, { "code": null, "e": 13156, "s": 13133, "text": "Navigate to bot folder" }, { "code": null, "e": 13193, "s": 13156, "text": "Select CyclingPrediction.csproj file" }, { "code": null, "e": 13232, "s": 13193, "text": "Update your api url in Bots/Cycling.cs" }, { "code": null, "e": 13321, "s": 13232, "text": "If you would like to test with your local Web API change to your local endpoint such as:" }, { "code": null, "e": 13434, "s": 13321, "text": "string RequestURI = String.Format(\"http://127.0.0.1:8000/predict?city={0}&date={1}&time={2}\",wCity,wDate,wTime);" }, { "code": null, "e": 13512, "s": 13434, "text": "If you’ll test with your Azure Web API change to your azure endpoint such as:" }, { "code": null, "e": 13641, "s": 13512, "text": "string RequestURI = String.Format(\"https://yourwebsite.azurewebsites.net/predict?city={0}&date={1}&time={2}\",wCity,wDate,wTime);" }, { "code": null, "e": 13669, "s": 13641, "text": "Press F5 to run the project" }, { "code": null, "e": 13810, "s": 13669, "text": "Your bot service will be available at https://localhost:3979. Run your Bot Framework Emulator and connect to https://localhost:3979 endpoint" }, { "code": null, "e": 13856, "s": 13810, "text": "After that your bot is ready for interaction." }, { "code": null, "e": 14006, "s": 13856, "text": "After you publish the bot you can connect with different conversational UI. I’ve connected with Microsoft Teams and named as Data Driven Cycling Bot." }, { "code": null, "e": 14146, "s": 14006, "text": "Once you send first message, it’s sending a card to pick City, Date and Time information to predict workout ride type and minimum distance." }, { "code": null, "e": 14273, "s": 14146, "text": "This has been a personal journey to discover insights from my existing data, then it turned out to a digital personal trainer." }, { "code": null, "e": 14314, "s": 14273, "text": "For next steps I would like to focus on," }, { "code": null, "e": 14403, "s": 14314, "text": "Setting a weekly target and predicting workout schedule for the week based on my target." }, { "code": null, "e": 14459, "s": 14403, "text": "Compare ride metrics and see the improvement over time." }, { "code": null, "e": 14504, "s": 14459, "text": "Supporting US metrics (now only supports km)" }, { "code": null, "e": 14594, "s": 14504, "text": "Code is available athttps://github.com/ikivanc/Data-Driven-Cycling-and-Workout-Prediction" } ]
What are the different data types of arrays in C#?
With C#, you can create an array of integers, chars, etc. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type stored at contiguous memory locations. This type can be integer, char, float, etc. The following is an array declaration showing the datatype usage − datatype[] Name_of_array; Here, datatype is used to specify the type of elements in the array. [ ] specifies the rank of the array. The rank specifies the size of the array. Name_of_array − specifies the name of the array. Set the integer array − int[] a; Set the double array − double[] z;
[ { "code": null, "e": 1346, "s": 1062, "text": "With C#, you can create an array of integers, chars, etc. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type stored at contiguous memory locations. This type can be integer, char, float, etc." }, { "code": null, "e": 1413, "s": 1346, "text": "The following is an array declaration showing the datatype usage −" }, { "code": null, "e": 1439, "s": 1413, "text": "datatype[] Name_of_array;" }, { "code": null, "e": 1445, "s": 1439, "text": "Here," }, { "code": null, "e": 1508, "s": 1445, "text": "datatype is used to specify the type of elements in the array." }, { "code": null, "e": 1587, "s": 1508, "text": "[ ] specifies the rank of the array. The rank specifies the size of the array." }, { "code": null, "e": 1636, "s": 1587, "text": "Name_of_array − specifies the name of the array." }, { "code": null, "e": 1660, "s": 1636, "text": "Set the integer array −" }, { "code": null, "e": 1670, "s": 1660, "text": "int[] a;\n" }, { "code": null, "e": 1693, "s": 1670, "text": "Set the double array −" }, { "code": null, "e": 1705, "s": 1693, "text": "double[] z;" } ]
C# | Array IndexOutofRange Exception - GeeksforGeeks
23 Jan, 2019 C# supports the creation and manipulation of arrays, as a data structure. The index of an array is an integer value that has value in the interval [0, n-1], where n is the size of the array. If a request for a negative or an index greater than or equal to the size of the array is made, then the C# throws an System.IndexOutOfRange Exception. This is unlike C/C++ where no index of the bound check is done. The IndexOutOfRangeException is a Runtime Exception thrown only at runtime. The C# Compiler does not check for this error during the compilation of a program. Example: // C# program to demonstrate the // IndexOutofRange Exception in arrayusing System; public class GFG { // Main Method public static void Main(String[] args) { int[] ar = {1, 2, 3, 4, 5}; // causing exception for (int i = 0; i <= ar.Length; i++) Console.WriteLine(ar[i]); }} Runtime Error: Unhandled Exception:System.IndexOutOfRangeException: Index was outside the bounds of the array.at GFG.Main (System.String[] args) <0x40bdbd50 + 0x00067> in :0[ERROR] FATAL UNHANDLED EXCEPTION: System.IndexOutOfRangeException: Index was outside the bounds of the array.at GFG.Main (System.String[] args) <0x40bdbd50 + 0x00067> in :0 Output: 1 2 3 4 5 Here if you carefully see, the array is of size 5. Therefore while accessing its element using for loop, the maximum value of index can be 4 but in our program, it is going till 5 and thus the exception. Let’s see another example using ArrayList: // C# program to demonstrate the // IndexOutofRange Exception in arrayusing System;using System.Collections; public class GFG { // Main Method public static void Main(String[] args) { // using ArrayList ArrayList lis = new ArrayList(); lis.Add("Geeks"); lis.Add("GFG"); Console.WriteLine(lis[2]); }} Runtime Error: Here error is a bit more informative than the previous one as follows: Unhandled Exception:System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: indexat System.Collections.ArrayList.get_Item (Int32 index) <0x7f2d36b2ff40 + 0x00082> in :0at GFG.Main (System.String[] args) <0x41b9fd50 + 0x0008b> in :0[ERROR] FATAL UNHANDLED EXCEPTION: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: indexat System.Collections.ArrayList.get_Item (Int32 index) <0x7f2d36b2ff40 + 0x00082> in :0at GFG.Main (System.String[] args) <0x41b9fd50 + 0x0008b> in :0 Lets understand it in a bit of detail: Index here defines the index we are trying to access. The size gives us information of the size of the list. Since size is 2, the last index we can access is (2-1)=1, and thus the exception The correct way to access array is : for (int i = 0; i < ar.Length; i++) { } Handling the Exception: Use for-each loop: This automatically handles indices while accessing the elements of an array.Syntax:for(int variable_name in array_variable) { // loop body } Syntax:for(int variable_name in array_variable) { // loop body } for(int variable_name in array_variable) { // loop body } Use Try-Catch: Consider enclosing your code inside a try-catch statement and manipulate the exception accordingly. As mentioned, C# won’t let you access an invalid index and will definitely throw an IndexOutOfRangeException. However, we should be careful inside the block of the catch statement, because if we don’t handle the exception appropriately, we may conceal it and thus, create a bug in your application. CSharp-Exception C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Destructors in C# Extension Method in C# HashSet in C# with Examples Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? Partial Classes in C# C# | Inheritance C# | List Class Difference between Hashtable and Dictionary in C# Lambda Expressions in C#
[ { "code": null, "e": 24302, "s": 24274, "text": "\n23 Jan, 2019" }, { "code": null, "e": 24868, "s": 24302, "text": "C# supports the creation and manipulation of arrays, as a data structure. The index of an array is an integer value that has value in the interval [0, n-1], where n is the size of the array. If a request for a negative or an index greater than or equal to the size of the array is made, then the C# throws an System.IndexOutOfRange Exception. This is unlike C/C++ where no index of the bound check is done. The IndexOutOfRangeException is a Runtime Exception thrown only at runtime. The C# Compiler does not check for this error during the compilation of a program." }, { "code": null, "e": 24877, "s": 24868, "text": "Example:" }, { "code": "// C# program to demonstrate the // IndexOutofRange Exception in arrayusing System; public class GFG { // Main Method public static void Main(String[] args) { int[] ar = {1, 2, 3, 4, 5}; // causing exception for (int i = 0; i <= ar.Length; i++) Console.WriteLine(ar[i]); }}", "e": 25212, "s": 24877, "text": null }, { "code": null, "e": 25227, "s": 25212, "text": "Runtime Error:" }, { "code": null, "e": 25559, "s": 25227, "text": "Unhandled Exception:System.IndexOutOfRangeException: Index was outside the bounds of the array.at GFG.Main (System.String[] args) <0x40bdbd50 + 0x00067> in :0[ERROR] FATAL UNHANDLED EXCEPTION: System.IndexOutOfRangeException: Index was outside the bounds of the array.at GFG.Main (System.String[] args) <0x40bdbd50 + 0x00067> in :0" }, { "code": null, "e": 25567, "s": 25559, "text": "Output:" }, { "code": null, "e": 25578, "s": 25567, "text": "1\n2\n3\n4\n5\n" }, { "code": null, "e": 25782, "s": 25578, "text": "Here if you carefully see, the array is of size 5. Therefore while accessing its element using for loop, the maximum value of index can be 4 but in our program, it is going till 5 and thus the exception." }, { "code": null, "e": 25825, "s": 25782, "text": "Let’s see another example using ArrayList:" }, { "code": "// C# program to demonstrate the // IndexOutofRange Exception in arrayusing System;using System.Collections; public class GFG { // Main Method public static void Main(String[] args) { // using ArrayList ArrayList lis = new ArrayList(); lis.Add(\"Geeks\"); lis.Add(\"GFG\"); Console.WriteLine(lis[2]); }}", "e": 26189, "s": 25825, "text": null }, { "code": null, "e": 26275, "s": 26189, "text": "Runtime Error: Here error is a bit more informative than the previous one as follows:" }, { "code": null, "e": 26917, "s": 26275, "text": "Unhandled Exception:System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: indexat System.Collections.ArrayList.get_Item (Int32 index) <0x7f2d36b2ff40 + 0x00082> in :0at GFG.Main (System.String[] args) <0x41b9fd50 + 0x0008b> in :0[ERROR] FATAL UNHANDLED EXCEPTION: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: indexat System.Collections.ArrayList.get_Item (Int32 index) <0x7f2d36b2ff40 + 0x00082> in :0at GFG.Main (System.String[] args) <0x41b9fd50 + 0x0008b> in :0" }, { "code": null, "e": 26956, "s": 26917, "text": "Lets understand it in a bit of detail:" }, { "code": null, "e": 27010, "s": 26956, "text": "Index here defines the index we are trying to access." }, { "code": null, "e": 27065, "s": 27010, "text": "The size gives us information of the size of the list." }, { "code": null, "e": 27146, "s": 27065, "text": "Since size is 2, the last index we can access is (2-1)=1, and thus the exception" }, { "code": null, "e": 27183, "s": 27146, "text": "The correct way to access array is :" }, { "code": null, "e": 27225, "s": 27183, "text": "for (int i = 0; i < ar.Length; i++) \n{\n}\n" }, { "code": null, "e": 27249, "s": 27225, "text": "Handling the Exception:" }, { "code": null, "e": 27416, "s": 27249, "text": "Use for-each loop: This automatically handles indices while accessing the elements of an array.Syntax:for(int variable_name in array_variable)\n{\n // loop body\n}\n\n" }, { "code": null, "e": 27488, "s": 27416, "text": "Syntax:for(int variable_name in array_variable)\n{\n // loop body\n}\n\n" }, { "code": null, "e": 27553, "s": 27488, "text": "for(int variable_name in array_variable)\n{\n // loop body\n}\n\n" }, { "code": null, "e": 27967, "s": 27553, "text": "Use Try-Catch: Consider enclosing your code inside a try-catch statement and manipulate the exception accordingly. As mentioned, C# won’t let you access an invalid index and will definitely throw an IndexOutOfRangeException. However, we should be careful inside the block of the catch statement, because if we don’t handle the exception appropriately, we may conceal it and thus, create a bug in your application." }, { "code": null, "e": 27984, "s": 27967, "text": "CSharp-Exception" }, { "code": null, "e": 27987, "s": 27984, "text": "C#" }, { "code": null, "e": 28085, "s": 27987, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28103, "s": 28085, "text": "Destructors in C#" }, { "code": null, "e": 28126, "s": 28103, "text": "Extension Method in C#" }, { "code": null, "e": 28154, "s": 28126, "text": "HashSet in C# with Examples" }, { "code": null, "e": 28194, "s": 28154, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 28237, "s": 28194, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 28259, "s": 28237, "text": "Partial Classes in C#" }, { "code": null, "e": 28276, "s": 28259, "text": "C# | Inheritance" }, { "code": null, "e": 28292, "s": 28276, "text": "C# | List Class" }, { "code": null, "e": 28342, "s": 28292, "text": "Difference between Hashtable and Dictionary in C#" } ]
Program to find Nth term in the given Series - GeeksforGeeks
01 Nov, 2021 Given a number N. The task is to write a program to find the N-th term in the below series: 1, 1, 2, 3, 4, 9, 8, 27, 16, 81, 32, 243, 64, 729, 128, 2187... Examples: Input : 4 Output : 3 Input : 11 Output : 32 On observing carefully, you will find that the series is a mixture of 2 series: All the odd terms in this series form a geometric series.All the even terms form yet another geometric series. All the odd terms in this series form a geometric series. All the even terms form yet another geometric series. The approach to solving the problem is quite simple. The odd positioned terms in the given series form a GP series with first term = 1 and common ration = 2. Similarly, the even positioned terms in the given series form a GP series with first term = 1 and common ration = 3.Therefore first check whether the input number N is even or odd. If it is even, set N=N/2(since there are Two GP series running parallelly) and find the Nth term by using formula an = a1·rn-1 with r=3. Similarly, if N is odd, set N=(n/2)+1 and do the same as previous with r=2.Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript // C++ program to find Nth term// in the given Series#include <iostream>#include <math.h> using namespace std; // Function to find the nth term// in the given seriesvoid findNthTerm(int n){ // If input number is even if (n % 2 == 0) { n = n / 2; cout << pow(3, n - 1) << endl; } // If input number is odd else { n = (n / 2) + 1; cout << pow(2, n - 1) << endl; }} // Driver Codeint main(){ int N = 4; findNthTerm(N); N = 11; findNthTerm(N); return 0;} // Java program to find Nth term// in the given Seriesimport java.io.*;import java.util.*;import java.lang.*; class GFG{// Function to find the nth term// in the given seriesstatic void findNthTerm(int n){ // If input number is even if (n % 2 == 0) { n = n / 2; System.out.print(Math.pow(3, n - 1) + "\n"); } // If input number is odd else { n = (n / 2) + 1; System.out.print(Math.pow(2, n - 1) + "\n"); }} // Driver Codepublic static void main(String[] args){ int N = 4; findNthTerm(N); N = 11; findNthTerm(N); }} // This code is contributed// by Akanksha Rai(Abby_akku) # Python3 program to find Nth term# in the given Series # Function to find the nth term# in the given seriesdef findNthTerm(n): # If input number is even if n % 2 == 0: n //= 2 print(3 ** (n - 1)) # If input number is odd else: n = (n // 2) + 1 print(2 ** (n - 1)) # Driver Codeif __name__=='__main__': N = 4 findNthTerm(N) N = 11 findNthTerm(N) # This code is contributed# by vaibhav29498 // C# program to find Nth term// in the given Seriesusing System; class GFG{// Function to find the nth// term in the given seriesstatic void findNthTerm(int n){ // If input number is even if (n % 2 == 0) { n = n / 2; Console.WriteLine(Math.Pow(3, n - 1)); } // If input number is odd else { n = (n / 2) + 1; Console.WriteLine(Math.Pow(2, n - 1)); }} // Driver Codepublic static void Main(){ int N = 4; findNthTerm(N); N = 11; findNthTerm(N);}} // This code is contributed// by chandan_jnu. <?php// php program to find Nth term// in the given Series // Function to find the nth term// in the given seriesfunction findNthTerm($n){ // If input number is even if ($n % 2 == 0) { $n = $n / 2; echo pow(3, $n - 1) . "\n"; } // If input number is odd else { $n = ($n / 2) + 1; echo pow(2, intval($n - 1)) . "\n"; }} // Driver Code$N = 4;findNthTerm($N); $N = 11;findNthTerm($N); // This code is contributed// by Akanksha Rai(Abby_akku)?> <script> // JavaScript program to find Nth term // in the given Series // Function to find the nth term // in the given series function findNthTerm(n) { // If input number is even if (n % 2 == 0) { n = Math.floor(n / 2); document.write(Math.pow(3, n - 1) + "<br>"); } // If input number is odd else { n = Math.floor(n / 2) + 1; document.write(Math.pow(2, n - 1) + "<br>"); } } // Driver Code let N = 4; findNthTerm(N); N = 11; findNthTerm(N); // This code is contributed by Mayank Tyagi </script> 3 32 Akanksha_Rai Chandan_Kumar vaibhav29498 mayanktyagi1709 khushboogoyal499 school-programming series TCS C++ Programs TCS series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. cin in C++ CSV file management using C++ Shallow Copy and Deep Copy in C++ Passing a function as a parameter in C++ Const keyword in C++ Program to implement Singly Linked List in C++ using class C++ Program to check if a given String is Palindrome or not Generics in C++ cout in C++ Passing and Returning Objects in C++
[ { "code": null, "e": 25368, "s": 25340, "text": "\n01 Nov, 2021" }, { "code": null, "e": 25461, "s": 25368, "text": "Given a number N. The task is to write a program to find the N-th term in the below series: " }, { "code": null, "e": 25525, "s": 25461, "text": "1, 1, 2, 3, 4, 9, 8, 27, 16, 81, 32, 243, 64, 729, 128, 2187..." }, { "code": null, "e": 25537, "s": 25525, "text": "Examples: " }, { "code": null, "e": 25583, "s": 25537, "text": "Input : 4\nOutput : 3\n\nInput : 11\nOutput : 32" }, { "code": null, "e": 25667, "s": 25585, "text": "On observing carefully, you will find that the series is a mixture of 2 series: " }, { "code": null, "e": 25778, "s": 25667, "text": "All the odd terms in this series form a geometric series.All the even terms form yet another geometric series." }, { "code": null, "e": 25836, "s": 25778, "text": "All the odd terms in this series form a geometric series." }, { "code": null, "e": 25890, "s": 25836, "text": "All the even terms form yet another geometric series." }, { "code": null, "e": 26490, "s": 25890, "text": "The approach to solving the problem is quite simple. The odd positioned terms in the given series form a GP series with first term = 1 and common ration = 2. Similarly, the even positioned terms in the given series form a GP series with first term = 1 and common ration = 3.Therefore first check whether the input number N is even or odd. If it is even, set N=N/2(since there are Two GP series running parallelly) and find the Nth term by using formula an = a1·rn-1 with r=3. Similarly, if N is odd, set N=(n/2)+1 and do the same as previous with r=2.Below is the implementation of above approach: " }, { "code": null, "e": 26494, "s": 26490, "text": "C++" }, { "code": null, "e": 26499, "s": 26494, "text": "Java" }, { "code": null, "e": 26507, "s": 26499, "text": "Python3" }, { "code": null, "e": 26510, "s": 26507, "text": "C#" }, { "code": null, "e": 26514, "s": 26510, "text": "PHP" }, { "code": null, "e": 26525, "s": 26514, "text": "Javascript" }, { "code": "// C++ program to find Nth term// in the given Series#include <iostream>#include <math.h> using namespace std; // Function to find the nth term// in the given seriesvoid findNthTerm(int n){ // If input number is even if (n % 2 == 0) { n = n / 2; cout << pow(3, n - 1) << endl; } // If input number is odd else { n = (n / 2) + 1; cout << pow(2, n - 1) << endl; }} // Driver Codeint main(){ int N = 4; findNthTerm(N); N = 11; findNthTerm(N); return 0;}", "e": 27039, "s": 26525, "text": null }, { "code": "// Java program to find Nth term// in the given Seriesimport java.io.*;import java.util.*;import java.lang.*; class GFG{// Function to find the nth term// in the given seriesstatic void findNthTerm(int n){ // If input number is even if (n % 2 == 0) { n = n / 2; System.out.print(Math.pow(3, n - 1) + \"\\n\"); } // If input number is odd else { n = (n / 2) + 1; System.out.print(Math.pow(2, n - 1) + \"\\n\"); }} // Driver Codepublic static void main(String[] args){ int N = 4; findNthTerm(N); N = 11; findNthTerm(N); }} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 27676, "s": 27039, "text": null }, { "code": "# Python3 program to find Nth term# in the given Series # Function to find the nth term# in the given seriesdef findNthTerm(n): # If input number is even if n % 2 == 0: n //= 2 print(3 ** (n - 1)) # If input number is odd else: n = (n // 2) + 1 print(2 ** (n - 1)) # Driver Codeif __name__=='__main__': N = 4 findNthTerm(N) N = 11 findNthTerm(N) # This code is contributed# by vaibhav29498", "e": 28119, "s": 27676, "text": null }, { "code": "// C# program to find Nth term// in the given Seriesusing System; class GFG{// Function to find the nth// term in the given seriesstatic void findNthTerm(int n){ // If input number is even if (n % 2 == 0) { n = n / 2; Console.WriteLine(Math.Pow(3, n - 1)); } // If input number is odd else { n = (n / 2) + 1; Console.WriteLine(Math.Pow(2, n - 1)); }} // Driver Codepublic static void Main(){ int N = 4; findNthTerm(N); N = 11; findNthTerm(N);}} // This code is contributed// by chandan_jnu.", "e": 28680, "s": 28119, "text": null }, { "code": "<?php// php program to find Nth term// in the given Series // Function to find the nth term// in the given seriesfunction findNthTerm($n){ // If input number is even if ($n % 2 == 0) { $n = $n / 2; echo pow(3, $n - 1) . \"\\n\"; } // If input number is odd else { $n = ($n / 2) + 1; echo pow(2, intval($n - 1)) . \"\\n\"; }} // Driver Code$N = 4;findNthTerm($N); $N = 11;findNthTerm($N); // This code is contributed// by Akanksha Rai(Abby_akku)?>", "e": 29173, "s": 28680, "text": null }, { "code": "<script> // JavaScript program to find Nth term // in the given Series // Function to find the nth term // in the given series function findNthTerm(n) { // If input number is even if (n % 2 == 0) { n = Math.floor(n / 2); document.write(Math.pow(3, n - 1) + \"<br>\"); } // If input number is odd else { n = Math.floor(n / 2) + 1; document.write(Math.pow(2, n - 1) + \"<br>\"); } } // Driver Code let N = 4; findNthTerm(N); N = 11; findNthTerm(N); // This code is contributed by Mayank Tyagi </script>", "e": 29796, "s": 29173, "text": null }, { "code": null, "e": 29801, "s": 29796, "text": "3\n32" }, { "code": null, "e": 29816, "s": 29803, "text": "Akanksha_Rai" }, { "code": null, "e": 29830, "s": 29816, "text": "Chandan_Kumar" }, { "code": null, "e": 29843, "s": 29830, "text": "vaibhav29498" }, { "code": null, "e": 29859, "s": 29843, "text": "mayanktyagi1709" }, { "code": null, "e": 29876, "s": 29859, "text": "khushboogoyal499" }, { "code": null, "e": 29895, "s": 29876, "text": "school-programming" }, { "code": null, "e": 29902, "s": 29895, "text": "series" }, { "code": null, "e": 29906, "s": 29902, "text": "TCS" }, { "code": null, "e": 29919, "s": 29906, "text": "C++ Programs" }, { "code": null, "e": 29923, "s": 29919, "text": "TCS" }, { "code": null, "e": 29930, "s": 29923, "text": "series" }, { "code": null, "e": 30028, "s": 29930, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30039, "s": 30028, "text": "cin in C++" }, { "code": null, "e": 30069, "s": 30039, "text": "CSV file management using C++" }, { "code": null, "e": 30103, "s": 30069, "text": "Shallow Copy and Deep Copy in C++" }, { "code": null, "e": 30144, "s": 30103, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 30165, "s": 30144, "text": "Const keyword in C++" }, { "code": null, "e": 30224, "s": 30165, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 30284, "s": 30224, "text": "C++ Program to check if a given String is Palindrome or not" }, { "code": null, "e": 30300, "s": 30284, "text": "Generics in C++" }, { "code": null, "e": 30312, "s": 30300, "text": "cout in C++" } ]
WhatWeb - Open Source Web Scanner - GeeksforGeeks
23 Sep, 2021 Whatweb is a free and open-source tool available on GitHub. Whatweb is a scanner written in the Ruby language. This tool can identify and recognize all the web technologies available on the target website. This tool can identify technologies used by websites such as blogging, content management system, all JavaScript libraries. Whatweb contains more than 180 modules. each module is responsible for grabbing particular information from the target website. Whatweb works as an information-gathering tool and can identify all the email addresses, SQL errors, technology used in the website. Step 1: Open your kali Linux operating system and use the following command to install the tool from GitHub. cd Desktop git clone https://github.com/urbanadventurer/WhatWeb/ Step 2: Now use the following command to move into the directory of the tool. cd Whatweb Step 3: Now you are in the directory of the tool. Use the following command to run the tool. ./whatweb The tool is running successfully. Now we will see examples to use the tool. Example 1: Use the Whatweb tool to scan a domain. ./whatweb <domain> Example 2: Use the Whatweb tool to scan a domain. ./whatweb <domain> Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Thread functions in C/C++ nohup Command in Linux with Examples mv command in Linux with examples Docker - COPY Instruction SED command in Linux | Set 2 chown command in Linux with Examples Basic Operators in Shell Scripting Array Basics in Shell Scripting | Set 1 scp command in Linux with Examples Named Pipe or FIFO with example C program
[ { "code": null, "e": 24406, "s": 24378, "text": "\n23 Sep, 2021" }, { "code": null, "e": 24998, "s": 24406, "text": "Whatweb is a free and open-source tool available on GitHub. Whatweb is a scanner written in the Ruby language. This tool can identify and recognize all the web technologies available on the target website. This tool can identify technologies used by websites such as blogging, content management system, all JavaScript libraries. Whatweb contains more than 180 modules. each module is responsible for grabbing particular information from the target website. Whatweb works as an information-gathering tool and can identify all the email addresses, SQL errors, technology used in the website." }, { "code": null, "e": 25107, "s": 24998, "text": "Step 1: Open your kali Linux operating system and use the following command to install the tool from GitHub." }, { "code": null, "e": 25172, "s": 25107, "text": "cd Desktop\ngit clone https://github.com/urbanadventurer/WhatWeb/" }, { "code": null, "e": 25250, "s": 25172, "text": "Step 2: Now use the following command to move into the directory of the tool." }, { "code": null, "e": 25261, "s": 25250, "text": "cd Whatweb" }, { "code": null, "e": 25354, "s": 25261, "text": "Step 3: Now you are in the directory of the tool. Use the following command to run the tool." }, { "code": null, "e": 25365, "s": 25354, "text": "./whatweb " }, { "code": null, "e": 25441, "s": 25365, "text": "The tool is running successfully. Now we will see examples to use the tool." }, { "code": null, "e": 25491, "s": 25441, "text": "Example 1: Use the Whatweb tool to scan a domain." }, { "code": null, "e": 25510, "s": 25491, "text": "./whatweb <domain>" }, { "code": null, "e": 25560, "s": 25510, "text": "Example 2: Use the Whatweb tool to scan a domain." }, { "code": null, "e": 25579, "s": 25560, "text": "./whatweb <domain>" }, { "code": null, "e": 25590, "s": 25579, "text": "Kali-Linux" }, { "code": null, "e": 25602, "s": 25590, "text": "Linux-Tools" }, { "code": null, "e": 25613, "s": 25602, "text": "Linux-Unix" }, { "code": null, "e": 25711, "s": 25613, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25720, "s": 25711, "text": "Comments" }, { "code": null, "e": 25733, "s": 25720, "text": "Old Comments" }, { "code": null, "e": 25759, "s": 25733, "text": "Thread functions in C/C++" }, { "code": null, "e": 25796, "s": 25759, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 25830, "s": 25796, "text": "mv command in Linux with examples" }, { "code": null, "e": 25856, "s": 25830, "text": "Docker - COPY Instruction" }, { "code": null, "e": 25885, "s": 25856, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 25922, "s": 25885, "text": "chown command in Linux with Examples" }, { "code": null, "e": 25957, "s": 25922, "text": "Basic Operators in Shell Scripting" }, { "code": null, "e": 25997, "s": 25957, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 26032, "s": 25997, "text": "scp command in Linux with Examples" } ]
Spring Boot - Eureka Server
Eureka Server is an application that holds the information about all client-service applications. Every Micro service will register into the Eureka server and Eureka server knows all the client applications running on each port and IP address. Eureka Server is also known as Discovery Server. In this chapter, we will learn in detail about How to build a Eureka server. Eureka Server comes with the bundle of Spring Cloud. For this, we need to develop the Eureka server and run it on the default port 8761. Visit the Spring Initializer homepage https://start.spring.io/ and download the Spring Boot project with Eureka server dependency. It is shown in the screenshot below − After downloading the project in main Spring Boot Application class file, we need to add @EnableEurekaServer annotation. The @EnableEurekaServer annotation is used to make your Spring Boot application acts as a Eureka Server. The code for main Spring Boot application class file is as shown below − package com.tutorialspoint.eurekaserver; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @SpringBootApplication @EnableEurekaServer public class EurekaserverApplication { public static void main(String[] args) { SpringApplication.run(EurekaserverApplication.class, args); } } Make sure Spring cloud Eureka server dependency is added in your build configuration file. The code for Maven user dependency is shown below − <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka-server</artifactId> </dependency> The code for Gradle user dependency is given below − compile('org.springframework.cloud:spring-cloud-starter-eureka-server') The complete build configuration file is given below − Maven pom.xml <?xml version = "1.0" encoding = "UTF-8"?> <project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorialspoint</groupId> <artifactId>eurekaserver</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>eurekaserver</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <spring-cloud.version>Edgware.RELEASE</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka-server</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Gradle – build.gradle buildscript { ext { springBootVersion = '1.5.9.RELEASE' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'org.springframework.boot' group = 'com.tutorialspoint' version = '0.0.1-SNAPSHOT' sourceCompatibility = 1.8 repositories { mavenCentral() } ext { springCloudVersion = 'Edgware.RELEASE' } dependencies { compile('org.springframework.cloud:spring-cloud-starter-eureka-server') testCompile('org.springframework.boot:spring-boot-starter-test') } dependencyManagement { imports { mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" } } By default, the Eureka Server registers itself into the discovery. You should add the below given configuration into your application.properties file or application.yml file. application.properties file is given below − eureka.client.registerWithEureka = false eureka.client.fetchRegistry = false server.port = 8761 The application.yml file is given below − eureka: client: registerWithEureka: false fetchRegistry: false server: port: 8761 Now, you can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands shown below − For Maven, use the command as shown below − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, you can use the command shown below − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory. Now, run the JAR file by using the following command − java –jar <JARFILE> You can find that the application has started on the Tomcat port 8761 as shown below − Now, hit the URL http://localhost:8761/ in your web browser and you can find the Eureka Server running on the port 8761 as shown below − 102 Lectures 8 hours Karthikeya T 39 Lectures 5 hours Chaand Sheikh 73 Lectures 5.5 hours Senol Atac 62 Lectures 4.5 hours Senol Atac 67 Lectures 4.5 hours Senol Atac 69 Lectures 5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 3318, "s": 3025, "text": "Eureka Server is an application that holds the information about all client-service applications. Every Micro service will register into the Eureka server and Eureka server knows all the client applications running on each port and IP address. Eureka Server is also known as Discovery Server." }, { "code": null, "e": 3395, "s": 3318, "text": "In this chapter, we will learn in detail about How to build a Eureka server." }, { "code": null, "e": 3532, "s": 3395, "text": "Eureka Server comes with the bundle of Spring Cloud. For this, we need to develop the Eureka server and run it on the default port 8761." }, { "code": null, "e": 3701, "s": 3532, "text": "Visit the Spring Initializer homepage https://start.spring.io/ and download the Spring Boot project with Eureka server dependency. It is shown in the screenshot below −" }, { "code": null, "e": 3927, "s": 3701, "text": "After downloading the project in main Spring Boot Application class file, we need to add @EnableEurekaServer annotation. The @EnableEurekaServer annotation is used to make your Spring Boot application acts as a Eureka Server." }, { "code": null, "e": 4000, "s": 3927, "text": "The code for main Spring Boot application class file is as shown below −" }, { "code": null, "e": 4437, "s": 4000, "text": "package com.tutorialspoint.eurekaserver;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;\n\n@SpringBootApplication\n@EnableEurekaServer\npublic class EurekaserverApplication {\n public static void main(String[] args) {\n SpringApplication.run(EurekaserverApplication.class, args);\n }\n}" }, { "code": null, "e": 4528, "s": 4437, "text": "Make sure Spring cloud Eureka server dependency is added in your build configuration file." }, { "code": null, "e": 4580, "s": 4528, "text": "The code for Maven user dependency is shown below −" }, { "code": null, "e": 4715, "s": 4580, "text": "<dependency>\n<groupId>org.springframework.cloud</groupId>\n <artifactId>spring-cloud-starter-eureka-server</artifactId>\n</dependency>" }, { "code": null, "e": 4768, "s": 4715, "text": "The code for Gradle user dependency is given below −" }, { "code": null, "e": 4841, "s": 4768, "text": "compile('org.springframework.cloud:spring-cloud-starter-eureka-server')\n" }, { "code": null, "e": 4896, "s": 4841, "text": "The complete build configuration file is given below −" }, { "code": null, "e": 4910, "s": 4896, "text": "Maven pom.xml" }, { "code": null, "e": 6971, "s": 4910, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<project xmlns = \"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0 \n http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n \n <modelVersion>4.0.0</modelVersion>\n <groupId>com.tutorialspoint</groupId>\n <artifactId>eurekaserver</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n <packaging>jar</packaging>\n <name>eurekaserver</name>\n <description>Demo project for Spring Boot</description>\n\n <parent>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-parent</artifactId>\n <version>1.5.9.RELEASE</version>\n <relativePath/> <!-- lookup parent from repository -->\n </parent>\n\n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n <java.version>1.8</java.version>\n <spring-cloud.version>Edgware.RELEASE</spring-cloud.version>\n </properties>\n\n <dependencies>\n <dependency>\n <groupId>org.springframework.cloud</groupId>\n <artifactId>spring-cloud-starter-eureka-server</artifactId>\n </dependency>\n\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-test</artifactId>\n <scope>test</scope>\n </dependency>\n </dependencies>\n\n <dependencyManagement>\n <dependencies>\n <dependency>\n <groupId>org.springframework.cloud</groupId>\n <artifactId>spring-cloud-dependencies</artifactId>\n <version>${spring-cloud.version}</version>\n <type>pom</type>\n <scope>import</scope>\n </dependency>\n </dependencies>\n </dependencyManagement>\n\n <build>\n <plugins>\n <plugin>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-maven-plugin</artifactId>\n </plugin>\n </plugins>\n </build>\n \n</project>" }, { "code": null, "e": 6993, "s": 6971, "text": "Gradle – build.gradle" }, { "code": null, "e": 7773, "s": 6993, "text": "buildscript {\n ext {\n springBootVersion = '1.5.9.RELEASE'\n }\n repositories {\n mavenCentral()\n }\n dependencies {\n classpath(\"org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}\")\n }\n}\n\napply plugin: 'java'\napply plugin: 'eclipse'\napply plugin: 'org.springframework.boot'\n\ngroup = 'com.tutorialspoint'\nversion = '0.0.1-SNAPSHOT'\nsourceCompatibility = 1.8\n\nrepositories {\n mavenCentral()\n}\next {\n springCloudVersion = 'Edgware.RELEASE'\n}\ndependencies {\n compile('org.springframework.cloud:spring-cloud-starter-eureka-server')\n testCompile('org.springframework.boot:spring-boot-starter-test')\n}\ndependencyManagement {\n imports {\n mavenBom \"org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}\"\n }\n}" }, { "code": null, "e": 7948, "s": 7773, "text": "By default, the Eureka Server registers itself into the discovery. You should add the below given configuration into your application.properties file or application.yml file." }, { "code": null, "e": 7993, "s": 7948, "text": "application.properties file is given below −" }, { "code": null, "e": 8089, "s": 7993, "text": "eureka.client.registerWithEureka = false\neureka.client.fetchRegistry = false\nserver.port = 8761" }, { "code": null, "e": 8131, "s": 8089, "text": "The application.yml file is given below −" }, { "code": null, "e": 8231, "s": 8131, "text": "eureka:\n client:\n registerWithEureka: false\n fetchRegistry: false\nserver:\n port: 8761" }, { "code": null, "e": 8363, "s": 8231, "text": "Now, you can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands shown below −" }, { "code": null, "e": 8407, "s": 8363, "text": "For Maven, use the command as shown below −" }, { "code": null, "e": 8426, "s": 8407, "text": "mvn clean install\n" }, { "code": null, "e": 8503, "s": 8426, "text": "After “BUILD SUCCESS”, you can find the JAR file under the target directory." }, { "code": null, "e": 8553, "s": 8503, "text": "For Gradle, you can use the command shown below −" }, { "code": null, "e": 8573, "s": 8553, "text": "gradle clean build\n" }, { "code": null, "e": 8657, "s": 8573, "text": "After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory." }, { "code": null, "e": 8712, "s": 8657, "text": "Now, run the JAR file by using the following command −" }, { "code": null, "e": 8735, "s": 8712, "text": " java –jar <JARFILE> \n" }, { "code": null, "e": 8822, "s": 8735, "text": "You can find that the application has started on the Tomcat port 8761 as shown below −" }, { "code": null, "e": 8959, "s": 8822, "text": "Now, hit the URL http://localhost:8761/ in your web browser and you can find the Eureka Server running on the port 8761 as shown below −" }, { "code": null, "e": 8993, "s": 8959, "text": "\n 102 Lectures \n 8 hours \n" }, { "code": null, "e": 9007, "s": 8993, "text": " Karthikeya T" }, { "code": null, "e": 9040, "s": 9007, "text": "\n 39 Lectures \n 5 hours \n" }, { "code": null, "e": 9055, "s": 9040, "text": " Chaand Sheikh" }, { "code": null, "e": 9090, "s": 9055, "text": "\n 73 Lectures \n 5.5 hours \n" }, { "code": null, "e": 9102, "s": 9090, "text": " Senol Atac" }, { "code": null, "e": 9137, "s": 9102, "text": "\n 62 Lectures \n 4.5 hours \n" }, { "code": null, "e": 9149, "s": 9137, "text": " Senol Atac" }, { "code": null, "e": 9184, "s": 9149, "text": "\n 67 Lectures \n 4.5 hours \n" }, { "code": null, "e": 9196, "s": 9184, "text": " Senol Atac" }, { "code": null, "e": 9229, "s": 9196, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 9241, "s": 9229, "text": " Senol Atac" }, { "code": null, "e": 9248, "s": 9241, "text": " Print" }, { "code": null, "e": 9259, "s": 9248, "text": " Add Notes" } ]
Data Structures | Binary Trees | Question 1 - GeeksforGeeks
28 Jun, 2021 Which of the following is a true about Binary Trees(A) Every binary tree is either complete or full.(B) Every complete binary tree is also a full binary tree.(C) Every full binary tree is also a complete binary tree.(D) No binary tree is both complete and full.(E) None of the aboveAnswer: (E)Explanation: A full binary tree (sometimes proper binary tree or 2-tree or strictly binary tree) is a tree in which every node other than the leaves has two children. A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. A) is incorrect. For example, the following Binary tree is neither complete nor full 12 / 20 / 30 B) is incorrect. The following binary tree is complete but not full 12 / \ 20 30 / 30 C) is incorrect. Following Binary tree is full, but not complete 12 / \ 20 30 / \ 20 40 D) is incorrect. Following Binary tree is both complete and full 12 / \ 20 30 / \ 10 40 Please refer http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_treesQuiz of this Question Binary Trees Quiz Data Structures Data Structures-Binary Trees Data Structures Data Structures Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Advantages and Disadvantages of Linked List Introduction to Data Structures | 10 most commonly used Data Structures FIFO vs LIFO approach in Programming Multilevel Linked List Advantages of vector over array in C++ Difference between data type and data structure Bit manipulation | Swap Endianness of a number Data Structures | Array | Question 2 Data Structures | Queue | Question 1 Program to create Custom Vector Class in C++
[ { "code": null, "e": 24992, "s": 24964, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25452, "s": 24992, "text": "Which of the following is a true about Binary Trees(A) Every binary tree is either complete or full.(B) Every complete binary tree is also a full binary tree.(C) Every full binary tree is also a complete binary tree.(D) No binary tree is both complete and full.(E) None of the aboveAnswer: (E)Explanation: A full binary tree (sometimes proper binary tree or 2-tree or strictly binary tree) is a tree in which every node other than the leaves has two children." }, { "code": null, "e": 25605, "s": 25452, "text": "A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible." }, { "code": null, "e": 25690, "s": 25605, "text": "A) is incorrect. For example, the following Binary tree is neither complete nor full" }, { "code": null, "e": 25716, "s": 25690, "text": " 12\n / \n 20\n /\n30" }, { "code": null, "e": 25784, "s": 25716, "text": "B) is incorrect. The following binary tree is complete but not full" }, { "code": null, "e": 25818, "s": 25784, "text": " 12\n / \\\n 20 30\n /\n30" }, { "code": null, "e": 25883, "s": 25818, "text": "C) is incorrect. Following Binary tree is full, but not complete" }, { "code": null, "e": 25940, "s": 25883, "text": " 12\n / \\\n 20 30\n / \\ \n 20 40\n" }, { "code": null, "e": 26005, "s": 25940, "text": "D) is incorrect. Following Binary tree is both complete and full" }, { "code": null, "e": 26055, "s": 26005, "text": " 12\n / \\\n 20 30\n / \\ \n 10 40\n" }, { "code": null, "e": 26152, "s": 26055, "text": "Please refer http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_treesQuiz of this Question" }, { "code": null, "e": 26170, "s": 26152, "text": "Binary Trees Quiz" }, { "code": null, "e": 26186, "s": 26170, "text": "Data Structures" }, { "code": null, "e": 26215, "s": 26186, "text": "Data Structures-Binary Trees" }, { "code": null, "e": 26231, "s": 26215, "text": "Data Structures" }, { "code": null, "e": 26247, "s": 26231, "text": "Data Structures" }, { "code": null, "e": 26345, "s": 26247, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26354, "s": 26345, "text": "Comments" }, { "code": null, "e": 26367, "s": 26354, "text": "Old Comments" }, { "code": null, "e": 26411, "s": 26367, "text": "Advantages and Disadvantages of Linked List" }, { "code": null, "e": 26483, "s": 26411, "text": "Introduction to Data Structures | 10 most commonly used Data Structures" }, { "code": null, "e": 26520, "s": 26483, "text": "FIFO vs LIFO approach in Programming" }, { "code": null, "e": 26543, "s": 26520, "text": "Multilevel Linked List" }, { "code": null, "e": 26582, "s": 26543, "text": "Advantages of vector over array in C++" }, { "code": null, "e": 26630, "s": 26582, "text": "Difference between data type and data structure" }, { "code": null, "e": 26677, "s": 26630, "text": "Bit manipulation | Swap Endianness of a number" }, { "code": null, "e": 26714, "s": 26677, "text": "Data Structures | Array | Question 2" }, { "code": null, "e": 26751, "s": 26714, "text": "Data Structures | Queue | Question 1" } ]
Android bundle to pass data between activities?
This example demonstrates how to pass data between activities. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <LinearLayout android:layout_width = "match_parent" android:layout_height = "wrap_content" android:gravity = "center_horizontal" android:orientation = "vertical" tools:ignore="MissingConstraints"> <EditText android:id = "@+id/etName" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:ems = "10" android:hint = "Enter a name" android:inputType = "text" /> <EditText android:id = "@+id/etPhone" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:ems = "10" android:hint = "Enter a Phone number" android:inputType = "number"/> <Button android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "Send data" android:id = "@+id/btnSend"/> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout> Step 3 − Add the following code to res/layout/activity_second.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width = "match_parent" android:layout_height = "wrap_content" android:gravity = "center_horizontal" android:orientation = "vertical" tools:ignore="MissingConstraints"> <TextView android:id="@+id/tvData" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:textSize="20sp" /> </LinearLayout> </LinearLayout> Step 4 − Add the following code to src/MainActivity.java package com.example.sample; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import android.os.Bundle; public class MainActivity extends AppCompatActivity { EditText etName; EditText etPhone; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); etName = findViewById(R.id.etName); etPhone = findViewById(R.id.etPhone); Button btnSend = findViewById(R.id.btnSend); btnSend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (TextUtils.isEmpty(etName.getText().toString()) && TextUtils.isEmpty(etPhone.getText().toString())) { Toast.makeText(MainActivity.this,"Something is wrong kindly check",Toast.LENGTH_LONG).show(); } else { sendUserData(etName.getText().toString(),etPhone.getText().toString()); } } }); } private void sendUserData(String username, String userPhone) { Userinfo userinfo = new Userinfo(); userinfo.setName(username); userinfo.setPhone(userPhone); Intent send = new Intent(MainActivity.this,SecondActivity.class); Bundle b = new Bundle(); b.putSerializable("serialzable",userinfo); send.putExtras(b); startActivity(send); } } Step 5 − Add the following code to src/SecondActivity.java package com.example.sample; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class SecondActivity extends AppCompatActivity { Userinfo userinfo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); TextView tvData = findViewById(R.id.tvData); userinfo = (Userinfo) getIntent().getSerializableExtra("serialzable"); String name = userinfo.getName(); String phone = userinfo.getPhone(); tvData.setText("Your entered name is "+name+" number is "+phone); } @Override protected void onPause() { super.onPause(); userinfo = null; } } Step 6 − Add the following code to src/Userinfo.java package com.example.sample; import java.io.Serializable; class Userinfo implements Serializable { String name; String phone; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } } Step 7 − Add the following code to Manifests/AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:dist="http://schemas.android.com/apk/distribution" package="com.example.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> <activity android:name=".SecondActivity"></activity> </application> <dist:module dist:instant="true" /> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and Click Run Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code.
[ { "code": null, "e": 1125, "s": 1062, "text": "This example demonstrates how to pass data between activities." }, { "code": null, "e": 1255, "s": 1125, "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": 1321, "s": 1255, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2693, "s": 1321, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<androidx.constraintlayout.widget.ConstraintLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <LinearLayout\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:gravity = \"center_horizontal\"\n android:orientation = \"vertical\"\n tools:ignore=\"MissingConstraints\">\n <EditText\n android:id = \"@+id/etName\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:ems = \"10\"\n android:hint = \"Enter a name\"\n android:inputType = \"text\" />\n <EditText\n android:id = \"@+id/etPhone\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:ems = \"10\"\n android:hint = \"Enter a Phone number\"\n android:inputType = \"number\"/>\n <Button\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:text = \"Send data\"\n android:id = \"@+id/btnSend\"/>\n </LinearLayout>\n</androidx.constraintlayout.widget.ConstraintLayout>" }, { "code": null, "e": 2761, "s": 2693, "text": "Step 3 − Add the following code to res/layout/activity_second.xml." }, { "code": null, "e": 3512, "s": 2761, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:orientation=\"vertical\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\">\n <LinearLayout\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:gravity = \"center_horizontal\"\n android:orientation = \"vertical\"\n tools:ignore=\"MissingConstraints\">\n <TextView\n android:id=\"@+id/tvData\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"wrap_content\"\n android:gravity=\"center\"\n android:textSize=\"20sp\" />\n </LinearLayout>\n</LinearLayout>" }, { "code": null, "e": 3570, "s": 3512, "text": "Step 4 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 5151, "s": 3570, "text": "package com.example.sample;\nimport androidx.appcompat.app.AppCompatActivity;\nimport android.content.Intent;\nimport android.text.TextUtils;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.Toast;\nimport android.os.Bundle;\npublic class MainActivity extends AppCompatActivity {\n EditText etName;\n EditText etPhone;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n etName = findViewById(R.id.etName);\n etPhone = findViewById(R.id.etPhone);\n Button btnSend = findViewById(R.id.btnSend);\n btnSend.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (TextUtils.isEmpty(etName.getText().toString()) &&\n TextUtils.isEmpty(etPhone.getText().toString())) {\n Toast.makeText(MainActivity.this,\"Something is wrong kindly\n check\",Toast.LENGTH_LONG).show();\n } else {\n sendUserData(etName.getText().toString(),etPhone.getText().toString());\n }\n }\n });\n }\n private void sendUserData(String username, String userPhone) {\n Userinfo userinfo = new Userinfo();\n userinfo.setName(username);\n userinfo.setPhone(userPhone);\n Intent send = new Intent(MainActivity.this,SecondActivity.class);\n Bundle b = new Bundle();\n b.putSerializable(\"serialzable\",userinfo);\n send.putExtras(b);\n startActivity(send);\n }\n}" }, { "code": null, "e": 5211, "s": 5151, "text": "Step 5 − Add the following code to src/SecondActivity.java" }, { "code": null, "e": 5966, "s": 5211, "text": "package com.example.sample;\nimport androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.TextView;\npublic class SecondActivity extends AppCompatActivity {\n Userinfo userinfo;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_second);\n TextView tvData = findViewById(R.id.tvData);\n userinfo = (Userinfo) getIntent().getSerializableExtra(\"serialzable\");\n String name = userinfo.getName();\n String phone = userinfo.getPhone();\n tvData.setText(\"Your entered name is \"+name+\" number is \"+phone);\n }\n @Override\n protected void onPause() {\n super.onPause();\n userinfo = null;\n }\n}" }, { "code": null, "e": 6020, "s": 5966, "text": "Step 6 − Add the following code to src/Userinfo.java" }, { "code": null, "e": 6399, "s": 6020, "text": "package com.example.sample;\nimport java.io.Serializable;\nclass Userinfo implements Serializable {\n String name;\n String phone;\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getPhone() {\n return phone;\n }\n public void setPhone(String phone) {\n this.phone = phone;\n }\n}" }, { "code": null, "e": 6465, "s": 6399, "text": "Step 7 − Add the following code to Manifests/AndroidManifest.xml" }, { "code": null, "e": 7300, "s": 6465, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:dist=\"http://schemas.android.com/apk/distribution\"\n package=\"com.example.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 <activity android:name=\".SecondActivity\"></activity>\n </application>\n <dist:module dist:instant=\"true\" />\n</manifest>" }, { "code": null, "e": 7647, "s": 7300, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and Click Run Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 7688, "s": 7647, "text": "Click here to download the project code." } ]
Excel Syntax
A formula in Excel is used to do mathematical calculations. Formulas always start with the equal sign = typed in the cell, followed by your calculation. Note: You claim the cell by selecting it and typing the equal sign (=) Select a cell Type the equal sign (=) Select a cell or type value Enter an arithmetic operator Select another cell or type value Press enter For example =1+1 is the formula to calculate 1+1=2 Note: The value of a cell is communicated by reference(value) for example A1(2) You can type values to cells and use them in your formulas. Lets type some dummy values to get started. Double click the cells to type values into them. Go ahead and type: A1(309) A2(320) B1(39) B2(35) Compare with the picture shown below: Note: Type values by selecting a cell, claim it by entering the equal sign (=) and then type your value. For example =309. Well done! You have successfully typed values to cells and now we can use them to create formulas. Here is how to do it, step by step. Select the cell C1 Type the equal sign (=) Left click on A1, the cell that has the (309) value Type the minus sign (-) Left click on B2, the cell that has the (35) value Hit enter Select the cell C1 Type the equal sign (=) Left click on A1, the cell that has the (309) value Type the minus sign (-) Left click on B2, the cell that has the (35) value Hit enter Tip: The formula can be typed directly without clicking the cells. The typed formula would be the same as the value in C1 (=A1-B2). The result after hitting the enter button is C1(274). Did you make it? Let's try one more example, this time let's make the formula =A2-B1. Here is how to do it, step by step. Select the cell C2 Type the equal sign (=) Left click A2, the cell that has the (320) value Type the minus sign (-) Left click B1, the cell that has the (39) value Hit the enter button Select the cell C2 Type the equal sign (=) Left click A2, the cell that has the (320) value Type the minus sign (-) Left click B1, the cell that has the (39) value Hit the enter button You got the result C2(281), right? Way to go! Note: You can make formulas with all four arithmetic operations, such as addition (+), subtraction (-), multiplication (*) and division (/). Here are some examples: =2+4 gives you 6 =4-2 gives you 2 =2*4 gives you 8 =2/4 gives you 0.5 In the next chapter you will learn about Ranges and how data can be moved in the Sheet. Complete the Excel formula: 1+1 Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 155, "s": 0, "text": "A formula in Excel is used to do mathematical calculations. Formulas always start with the equal sign = typed in the cell, followed by your calculation. \n" }, { "code": null, "e": 226, "s": 155, "text": "Note: You claim the cell by selecting it and typing the equal sign (=)" }, { "code": null, "e": 240, "s": 226, "text": "Select a cell" }, { "code": null, "e": 264, "s": 240, "text": "Type the equal sign (=)" }, { "code": null, "e": 292, "s": 264, "text": "Select a cell or type value" }, { "code": null, "e": 321, "s": 292, "text": "Enter an arithmetic operator" }, { "code": null, "e": 355, "s": 321, "text": "Select another cell or type value" }, { "code": null, "e": 367, "s": 355, "text": "Press enter" }, { "code": null, "e": 418, "s": 367, "text": "For example =1+1 is the formula to calculate 1+1=2" }, { "code": null, "e": 498, "s": 418, "text": "Note: The value of a cell is communicated by reference(value) for example A1(2)" }, { "code": null, "e": 558, "s": 498, "text": "You can type values to cells and use them in your formulas." }, { "code": null, "e": 670, "s": 558, "text": "Lets type some dummy values to get started. Double click the cells to type values into them. Go ahead and type:" }, { "code": null, "e": 678, "s": 670, "text": "A1(309)" }, { "code": null, "e": 686, "s": 678, "text": "A2(320)" }, { "code": null, "e": 693, "s": 686, "text": "B1(39)" }, { "code": null, "e": 700, "s": 693, "text": "B2(35)" }, { "code": null, "e": 738, "s": 700, "text": "Compare with the picture shown below:" }, { "code": null, "e": 862, "s": 738, "text": "Note: Type values by selecting a cell, claim it by entering the equal sign (=) \nand then type your value. For example =309." }, { "code": null, "e": 962, "s": 862, "text": "Well done! You have successfully typed values to cells and now we can use them to create formulas.\n" }, { "code": null, "e": 998, "s": 962, "text": "Here is how to do it, step by step." }, { "code": null, "e": 1180, "s": 998, "text": "\nSelect the cell C1\nType the equal sign (=)\nLeft click on A1, the cell that has the (309) value\nType the minus sign (-)\nLeft click on B2, the cell that has the (35) value\nHit enter\n" }, { "code": null, "e": 1199, "s": 1180, "text": "Select the cell C1" }, { "code": null, "e": 1223, "s": 1199, "text": "Type the equal sign (=)" }, { "code": null, "e": 1275, "s": 1223, "text": "Left click on A1, the cell that has the (309) value" }, { "code": null, "e": 1299, "s": 1275, "text": "Type the minus sign (-)" }, { "code": null, "e": 1350, "s": 1299, "text": "Left click on B2, the cell that has the (35) value" }, { "code": null, "e": 1360, "s": 1350, "text": "Hit enter" }, { "code": null, "e": 1493, "s": 1360, "text": "Tip: The formula can be typed directly without clicking the cells. The typed formula would be the same as the value in C1 (=A1-B2). " }, { "code": null, "e": 1566, "s": 1493, "text": "The result after hitting the enter button is C1(274). Did you make it? \n" }, { "code": null, "e": 1636, "s": 1566, "text": "Let's try one more example, this time let's make the formula =A2-B1. " }, { "code": null, "e": 1672, "s": 1636, "text": "Here is how to do it, step by step." }, { "code": null, "e": 1859, "s": 1672, "text": "\nSelect the cell C2\nType the equal sign (=)\nLeft click A2, the cell that has the (320) value\nType the minus sign (-)\nLeft click B1, the cell that has the (39) value\nHit the enter button\n" }, { "code": null, "e": 1878, "s": 1859, "text": "Select the cell C2" }, { "code": null, "e": 1902, "s": 1878, "text": "Type the equal sign (=)" }, { "code": null, "e": 1951, "s": 1902, "text": "Left click A2, the cell that has the (320) value" }, { "code": null, "e": 1975, "s": 1951, "text": "Type the minus sign (-)" }, { "code": null, "e": 2023, "s": 1975, "text": "Left click B1, the cell that has the (39) value" }, { "code": null, "e": 2044, "s": 2023, "text": "Hit the enter button" }, { "code": null, "e": 2090, "s": 2044, "text": "You got the result C2(281), right? Way to go!" }, { "code": null, "e": 2231, "s": 2090, "text": "Note: You can make formulas with all four arithmetic operations, such as addition (+), subtraction (-), multiplication (*) and division (/)." }, { "code": null, "e": 2255, "s": 2231, "text": "Here are some examples:" }, { "code": null, "e": 2272, "s": 2255, "text": "=2+4 gives you 6" }, { "code": null, "e": 2289, "s": 2272, "text": "=4-2 gives you 2" }, { "code": null, "e": 2306, "s": 2289, "text": "=2*4 gives you 8" }, { "code": null, "e": 2325, "s": 2306, "text": "=2/4 gives you 0.5" }, { "code": null, "e": 2414, "s": 2325, "text": "In the next chapter you will learn about Ranges and how data \ncan be moved in the Sheet." }, { "code": null, "e": 2442, "s": 2414, "text": "Complete the Excel formula:" }, { "code": null, "e": 2447, "s": 2442, "text": "1+1\n" }, { "code": null, "e": 2466, "s": 2447, "text": "Start the Exercise" }, { "code": null, "e": 2499, "s": 2466, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 2541, "s": 2499, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 2648, "s": 2541, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 2667, "s": 2648, "text": "[email protected]" } ]
What Is API and How To Use Youtube API | by Jiwon Jeong | Towards Data Science
Explaining the concept of API in plain English and how to scrape Youtube data using tuber package Last time I talked about strategies for a successful Youtuber. It was such an exciting project for me. But It wasn’t an easy one because I had to struggle with searching for how to get Youtube API key. There are lots of resources already but most of them are for web developers, and tutorials for R users are hardly seeable. After I managed to get the API key spending a whole day, I came across with the idea why not I leave a post for someone who would have the same problem with me. Today I’m going to talk about the concept of API and how to get API key. I will also introduce tuber package for analyzing data in R. If you haven’t used Google APIs and you are interested in doing a data science project with them, this post will be a good start. If you are unfamiliar with the word API, it could be hard to grasp the meaning of it at first. API stands for Application Programming Interface. Is this too ‘programmer’ language for you? That’s fine. I will explain the concept step by step. For your understanding, it would be better to start with two different interfaces. There are two kinds of interface, User Interface and Application Programming Interface. To simply put, UI is the interface for common users while API is the interface for programmers. You can see an example of UI below. It’s a common web page we encounter every day. How do we use them? We can use them simply by clicking the picture or words. This is the level for the common people, the interface for users. How could it be possible? That’s because the web developer hid all the codes required behind the button. And that is the interface for programmers where the codes and commands are living. In other words, API. You can think API as a set of codes, protocols, and functions to work and interact with software applications. With UI we work with simple buttons and tools while with API we work with predefined functions. Still hard for you? Then let’s suppose you are sitting in a restaurant. You want to have a nice beef steak and a glass of red wine for your dinner. You sit on the table and call.. who? The waiters! Then you get the menu and order what you want. After a few minutes later they will bring the dish. This is what API does. You don’t need to roll up your sleeves and do all the stuff like preparing the ingredients, cutting the vegetables, and grilling the meat by yourself. Waiters will do these steps for you, and all you have to do is just calling them and start your work from that stand. Likewise when the developers are working with programming tools or when the data scientists are wrangling with data, they don’t write every single code every single time. They use pre-made functions which are the sets of those basic codes operating under the hood. For instance, when you want to join two data into one, you call the join function (a ‘join’ waiter) and order it to work as you command (ordering the menu). Then it will return the required results (your dish). API now became a new kind of business models and strategies for companies to equip in the big data era. Then what’s so special? What makes API so hot these days? Let’s briefly talk about what we can do with it in a business context. APIs can generate massive amounts of value both internally and eternally. Managing and processing data is one of the crucial factors in business management, and every company has built IT systems. As the size of the data is increasing exponentially, however, there is a limitation to cope with all the data through the traditional IT system. In this sense, applying API can be a solution with better efficiency and security. It can break down barriers between systems, which enables simplifying work processes, inter-cooperation between organizations and higher protection of data. External merits of API are even fancier. If a company open their API either publicly or with extra fees, it can provide new services and acquire potential customers to their side. Customers can experience a higher level of services that weren’t available before. By offering API services, third-party developers can build whole new kinds of products that even the companies had never thought of. For example, Google Map, the most popular API among developers, wasn’t expected to draw that much effects at first. By Applying those data to real estate and various other fields, developers brought much higher values and assets back to Google. Nowadays the number of API is continuously increasing, and this trend will be ongoing or even more. Now we can say that the implementation and management of API of a company is one of the critical factors for its competitive and strategic values. To work with API, you need to get an authorized key first. It’s for obtaining an authorized key to be connected with API. API Providers, Youtube in this case, don’t merely provide their service without control. To preserve this interface and manage the users, they offer a unique access key to each user. With this, we can connect to the interface of the application. Just like we connect to electricity by plugging the power cord into an electric outlet, we plug our server into the storage with this unique key. And from that point, we can use the data and protocols of API. So now let’s start with how to get the authorized key. There is a very nice tutorial for getting the key. If you’re a web developer, you can follow this tutorial step by step. help.aolonnetwork.com If you are to do some data analysis, you don’t need all these steps. You follow the steps until number 9, and then choose ‘other’ instead of ‘web application.’ There are two different types of clients on the developer console, and the access methods are different for each case. Therefore if you try to get the key by ‘web application’ and ask for Oauth from your local computer, you could meet the error message like what I got. So click ‘other’ option then you will get the client key and secret key. Copy and paste them on your local computer. In R, there is tuber package which is made only for Youtube data analysis. You can draw various data including the number of videos of a particular channel, the number of views, likes and comments on a video and so on. To call this data in R, you need to install ‘tuber’ package first. Then you ask Google for the authorization token. install.packages('tuber')library(tuber)client_key = ''client_secret = ''yt_oauth(app_id = client_key, app_secret = client_secret) When you comment this code, a browser will pop up with some numbers allowing you to authorize the application. If you check your local tool, R will already be waiting for the numbers so copy and Paste the serial numbers. Now you finally get to be connected with Youtube API. I will also introduce some of the functions that could be useful for analyzing Youtube data from tuber package. get_all_channel_video_stats : This is the function for getting statistics on all the videos in a channel. You need a channel_id to use this. get_stats : This gives you statistics of a video with video_id. The return values are the count of views, likes, dislikes, favorites, and comments. get_video_details : This provides more specific information as the publish date of a video. You can also get titles, descriptions, thumbnails, and categories. get_all_comments : It gives you all the comments for a video so has great usage for text mining in respect of particular topics or channels list_channel_activities : This returns a list of channel activity. list_videos : It returns the most popular videos. There are other useful API calls, so I recommend you to check them. You can browse them from here. An excellent video for what is API: https://www.youtube.com/watch?v=s7wmiS2mSXY&t=75s Harvard report on strategic values of API: https://hbr.org/2015/01/the-strategic-value-of-apis Want to study more about API? ProgrammableWeb is an ‘API’ university delivering almost everything about API: https://www.programmableweb.com/ Don’t know what to do with Youtube data? Check out my previous work. You could get new inspirations from them! towardsdatascience.com towardsdatascience.com There are plenty of APIs already but, a small number of them open publicly. As data will directly transfer to the competitiveness in today’s world, I do understand companies’ intentions. I believe, however, they shouldn’t neglect the potentials of sharing economy. By making their internal data accessible, they will unleash the creativity of developers and data scientists all over the world to devise whole new uses for the data. Just like what we have done with open sources over the last years. Thank you for reading and hope you found this post helpful. If there is something need to be corrected, please share your insight! If you’d like to encourage an aspiring data scientist, please hit 👏 👏 👏! I’m always open to hearing your thoughts so feel free to share or contact me on LinkedIn. I’ll be back with another exciting story. Until then, happy machine learning.
[ { "code": null, "e": 269, "s": 171, "text": "Explaining the concept of API in plain English and how to scrape Youtube data using tuber package" }, { "code": null, "e": 755, "s": 269, "text": "Last time I talked about strategies for a successful Youtuber. It was such an exciting project for me. But It wasn’t an easy one because I had to struggle with searching for how to get Youtube API key. There are lots of resources already but most of them are for web developers, and tutorials for R users are hardly seeable. After I managed to get the API key spending a whole day, I came across with the idea why not I leave a post for someone who would have the same problem with me." }, { "code": null, "e": 1019, "s": 755, "text": "Today I’m going to talk about the concept of API and how to get API key. I will also introduce tuber package for analyzing data in R. If you haven’t used Google APIs and you are interested in doing a data science project with them, this post will be a good start." }, { "code": null, "e": 1261, "s": 1019, "text": "If you are unfamiliar with the word API, it could be hard to grasp the meaning of it at first. API stands for Application Programming Interface. Is this too ‘programmer’ language for you? That’s fine. I will explain the concept step by step." }, { "code": null, "e": 2170, "s": 1261, "text": "For your understanding, it would be better to start with two different interfaces. There are two kinds of interface, User Interface and Application Programming Interface. To simply put, UI is the interface for common users while API is the interface for programmers. You can see an example of UI below. It’s a common web page we encounter every day. How do we use them? We can use them simply by clicking the picture or words. This is the level for the common people, the interface for users. How could it be possible? That’s because the web developer hid all the codes required behind the button. And that is the interface for programmers where the codes and commands are living. In other words, API. You can think API as a set of codes, protocols, and functions to work and interact with software applications. With UI we work with simple buttons and tools while with API we work with predefined functions." }, { "code": null, "e": 2759, "s": 2170, "text": "Still hard for you? Then let’s suppose you are sitting in a restaurant. You want to have a nice beef steak and a glass of red wine for your dinner. You sit on the table and call.. who? The waiters! Then you get the menu and order what you want. After a few minutes later they will bring the dish. This is what API does. You don’t need to roll up your sleeves and do all the stuff like preparing the ingredients, cutting the vegetables, and grilling the meat by yourself. Waiters will do these steps for you, and all you have to do is just calling them and start your work from that stand." }, { "code": null, "e": 3235, "s": 2759, "text": "Likewise when the developers are working with programming tools or when the data scientists are wrangling with data, they don’t write every single code every single time. They use pre-made functions which are the sets of those basic codes operating under the hood. For instance, when you want to join two data into one, you call the join function (a ‘join’ waiter) and order it to work as you command (ordering the menu). Then it will return the required results (your dish)." }, { "code": null, "e": 3468, "s": 3235, "text": "API now became a new kind of business models and strategies for companies to equip in the big data era. Then what’s so special? What makes API so hot these days? Let’s briefly talk about what we can do with it in a business context." }, { "code": null, "e": 4050, "s": 3468, "text": "APIs can generate massive amounts of value both internally and eternally. Managing and processing data is one of the crucial factors in business management, and every company has built IT systems. As the size of the data is increasing exponentially, however, there is a limitation to cope with all the data through the traditional IT system. In this sense, applying API can be a solution with better efficiency and security. It can break down barriers between systems, which enables simplifying work processes, inter-cooperation between organizations and higher protection of data." }, { "code": null, "e": 4691, "s": 4050, "text": "External merits of API are even fancier. If a company open their API either publicly or with extra fees, it can provide new services and acquire potential customers to their side. Customers can experience a higher level of services that weren’t available before. By offering API services, third-party developers can build whole new kinds of products that even the companies had never thought of. For example, Google Map, the most popular API among developers, wasn’t expected to draw that much effects at first. By Applying those data to real estate and various other fields, developers brought much higher values and assets back to Google." }, { "code": null, "e": 4938, "s": 4691, "text": "Nowadays the number of API is continuously increasing, and this trend will be ongoing or even more. Now we can say that the implementation and management of API of a company is one of the critical factors for its competitive and strategic values." }, { "code": null, "e": 5515, "s": 4938, "text": "To work with API, you need to get an authorized key first. It’s for obtaining an authorized key to be connected with API. API Providers, Youtube in this case, don’t merely provide their service without control. To preserve this interface and manage the users, they offer a unique access key to each user. With this, we can connect to the interface of the application. Just like we connect to electricity by plugging the power cord into an electric outlet, we plug our server into the storage with this unique key. And from that point, we can use the data and protocols of API." }, { "code": null, "e": 5691, "s": 5515, "text": "So now let’s start with how to get the authorized key. There is a very nice tutorial for getting the key. If you’re a web developer, you can follow this tutorial step by step." }, { "code": null, "e": 5713, "s": 5691, "text": "help.aolonnetwork.com" }, { "code": null, "e": 6143, "s": 5713, "text": "If you are to do some data analysis, you don’t need all these steps. You follow the steps until number 9, and then choose ‘other’ instead of ‘web application.’ There are two different types of clients on the developer console, and the access methods are different for each case. Therefore if you try to get the key by ‘web application’ and ask for Oauth from your local computer, you could meet the error message like what I got." }, { "code": null, "e": 6260, "s": 6143, "text": "So click ‘other’ option then you will get the client key and secret key. Copy and paste them on your local computer." }, { "code": null, "e": 6595, "s": 6260, "text": "In R, there is tuber package which is made only for Youtube data analysis. You can draw various data including the number of videos of a particular channel, the number of views, likes and comments on a video and so on. To call this data in R, you need to install ‘tuber’ package first. Then you ask Google for the authorization token." }, { "code": null, "e": 6725, "s": 6595, "text": "install.packages('tuber')library(tuber)client_key = ''client_secret = ''yt_oauth(app_id = client_key, app_secret = client_secret)" }, { "code": null, "e": 7000, "s": 6725, "text": "When you comment this code, a browser will pop up with some numbers allowing you to authorize the application. If you check your local tool, R will already be waiting for the numbers so copy and Paste the serial numbers. Now you finally get to be connected with Youtube API." }, { "code": null, "e": 7112, "s": 7000, "text": "I will also introduce some of the functions that could be useful for analyzing Youtube data from tuber package." }, { "code": null, "e": 7253, "s": 7112, "text": "get_all_channel_video_stats : This is the function for getting statistics on all the videos in a channel. You need a channel_id to use this." }, { "code": null, "e": 7401, "s": 7253, "text": "get_stats : This gives you statistics of a video with video_id. The return values are the count of views, likes, dislikes, favorites, and comments." }, { "code": null, "e": 7560, "s": 7401, "text": "get_video_details : This provides more specific information as the publish date of a video. You can also get titles, descriptions, thumbnails, and categories." }, { "code": null, "e": 7700, "s": 7560, "text": "get_all_comments : It gives you all the comments for a video so has great usage for text mining in respect of particular topics or channels" }, { "code": null, "e": 7767, "s": 7700, "text": "list_channel_activities : This returns a list of channel activity." }, { "code": null, "e": 7817, "s": 7767, "text": "list_videos : It returns the most popular videos." }, { "code": null, "e": 7916, "s": 7817, "text": "There are other useful API calls, so I recommend you to check them. You can browse them from here." }, { "code": null, "e": 8002, "s": 7916, "text": "An excellent video for what is API: https://www.youtube.com/watch?v=s7wmiS2mSXY&t=75s" }, { "code": null, "e": 8097, "s": 8002, "text": "Harvard report on strategic values of API: https://hbr.org/2015/01/the-strategic-value-of-apis" }, { "code": null, "e": 8239, "s": 8097, "text": "Want to study more about API? ProgrammableWeb is an ‘API’ university delivering almost everything about API: https://www.programmableweb.com/" }, { "code": null, "e": 8350, "s": 8239, "text": "Don’t know what to do with Youtube data? Check out my previous work. You could get new inspirations from them!" }, { "code": null, "e": 8373, "s": 8350, "text": "towardsdatascience.com" }, { "code": null, "e": 8396, "s": 8373, "text": "towardsdatascience.com" }, { "code": null, "e": 8895, "s": 8396, "text": "There are plenty of APIs already but, a small number of them open publicly. As data will directly transfer to the competitiveness in today’s world, I do understand companies’ intentions. I believe, however, they shouldn’t neglect the potentials of sharing economy. By making their internal data accessible, they will unleash the creativity of developers and data scientists all over the world to devise whole new uses for the data. Just like what we have done with open sources over the last years." } ]
Difference between Structure and Union in C Program
In C we have container for both i.e. for same type data and multiple type data. For storage of data of same type C provides concept of Array which stores data variables of same type while for storing data of different type C has concept of structure and union that can store data variable of different type as well. Since both Structure and Union can hold different type of data in them but now on the basis of internal implementation we can find several differences in both of these containers. Following are the important differences between Structure and Union. struct struct_name{ type element1; type element2; . . } variable1, variable2, ...; union u_name{ type element1; type element2; . . } variable1, variable2, ...;
[ { "code": null, "e": 1378, "s": 1062, "text": "In C we have container for both i.e. for same type data and multiple type data. For storage of data of same type C provides concept of Array which stores data variables of same type while for storing data of different type C has concept of structure and union that can store data variable of different type as well." }, { "code": null, "e": 1558, "s": 1378, "text": "Since both Structure and Union can hold different type of data in them but now on the basis of internal implementation we can find several differences in both of these containers." }, { "code": null, "e": 1627, "s": 1558, "text": "Following are the important differences between Structure and Union." }, { "code": null, "e": 1722, "s": 1627, "text": "struct struct_name{\n type element1;\n type element2;\n .\n .\n} variable1, variable2, ...;" }, { "code": null, "e": 1811, "s": 1722, "text": "union u_name{\n type element1;\n type element2;\n .\n .\n} variable1, variable2, ...;" } ]
Checking if a double (or float) is NaN in C++
To check whether a floating point or double number is NaN (Not a Number) in C++, we can use the isnan() function. The isnan() function is present into the cmath library. This function is introduced in C++ version 11. So From C++11 next, we can use this function. #include <cmath> #include <iostream> using namespace std; main() { if(isnan(sqrt(30))) { //square root of 30 is a floating point number cout << "Square root of 30 is not a number" <<endl; } else { cout << "Square root of 30 is a number" <<endl; } if(isnan(sqrt(-30))) { //square root of -30 is an imaginary number cout << "Square root of -30 is not a number" <<endl; } else { cout << "Square root of -30 is a number" <<endl; } } Square root of 30 is a number Square root of -30 is not a number
[ { "code": null, "e": 1325, "s": 1062, "text": "To check whether a floating point or double number is NaN (Not a Number) in C++, we can use the isnan() function. The isnan() function is present into the cmath library. This function is introduced in C++ version 11. So From C++11 next, we can use this function." }, { "code": null, "e": 1796, "s": 1325, "text": "#include <cmath>\n#include <iostream>\nusing namespace std;\nmain() {\n if(isnan(sqrt(30))) { //square root of 30 is a floating point number\n cout << \"Square root of 30 is not a number\" <<endl;\n } else {\n cout << \"Square root of 30 is a number\" <<endl;\n }\n if(isnan(sqrt(-30))) { //square root of -30 is an imaginary number\n cout << \"Square root of -30 is not a number\" <<endl;\n } else {\n cout << \"Square root of -30 is a number\" <<endl;\n }\n}" }, { "code": null, "e": 1861, "s": 1796, "text": "Square root of 30 is a number\nSquare root of -30 is not a number" } ]
Equivalent to matlab's imagesc in Matplotlib
To make equivalent imagesc, we can use extent [left, right, bottom, top]. Create random data using numpy. Display the data as an image, i.e., on a 2D regular raster, with data and extent [−1, 1, −1, 1] arguments. To display the figure, use show() method. import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True data = np.random.rand(4, 4) plt.imshow(data, extent=[-1, 1, -1, 1]) plt.show()
[ { "code": null, "e": 1136, "s": 1062, "text": "To make equivalent imagesc, we can use extent [left, right, bottom, top]." }, { "code": null, "e": 1168, "s": 1136, "text": "Create random data using numpy." }, { "code": null, "e": 1275, "s": 1168, "text": "Display the data as an image, i.e., on a 2D regular raster, with data and extent [−1, 1, −1, 1]\narguments." }, { "code": null, "e": 1317, "s": 1275, "text": "To display the figure, use show() method." }, { "code": null, "e": 1539, "s": 1317, "text": "import numpy as np\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\ndata = np.random.rand(4, 4)\nplt.imshow(data, extent=[-1, 1, -1, 1])\nplt.show()" } ]
Excel DAX - Formulas
DAX is a formula language for creating custom calculations in Power PivotTables. You can use the DAX functions that are designed to work with relational data and perform dynamic aggregation in DAX formulas. DAX formulas are very similar to Excel formulas. To create a DAX formula, you type an equal sign, followed by a function name or expression and any required values or arguments. DAX formulas can include DAX functions and leverage their usage. This is where DAX formulas tend to differ from DAX functions in important ways. A DAX function always reference a complete column or a table. If you want to use only particular values from a table or column, you can add filters to the formula. A DAX function always reference a complete column or a table. If you want to use only particular values from a table or column, you can add filters to the formula. If you want to customize calculations on a row by row basis, Power Pivot provides functions that let you use the current row value or a related value to perform calculations that vary by context. If you want to customize calculations on a row by row basis, Power Pivot provides functions that let you use the current row value or a related value to perform calculations that vary by context. DAX includes a type of function that returns a table as its result, rather than a single value. These functions can be used to provide input to other functions, thus calculating values for entire tables or columns. DAX includes a type of function that returns a table as its result, rather than a single value. These functions can be used to provide input to other functions, thus calculating values for entire tables or columns. Some DAX functions provide time intelligence, which lets you create calculations using meaningful ranges of dates and compare the results across parallel periods. Some DAX functions provide time intelligence, which lets you create calculations using meaningful ranges of dates and compare the results across parallel periods. Every DAX formula has the following syntax − Each formula must begin with an equal sign. Each formula must begin with an equal sign. To the right of the equal sign, you can either type or select a function name, or type an expression. The expression can contain table names and column names connected by DAX operators. To the right of the equal sign, you can either type or select a function name, or type an expression. The expression can contain table names and column names connected by DAX operators. Following are some valid DAX formulas − [column_Cost] + [column_Tax] = Today () DAX provides the IntelliSense feature that will enable you to write DAX formulas promptly and correctly. With this feature, you need not type the table, column, and function names completely, but select the relevant names from the dropdown list while writing a DAX formula. Begin to type the first few letters of the function name. AutoComplete displays a list of available functions with the names beginning with those letters. Begin to type the first few letters of the function name. AutoComplete displays a list of available functions with the names beginning with those letters. Place the pointer on any of the function names. IntelliSense tooltip will be displayed giving you the use of the function. Place the pointer on any of the function names. IntelliSense tooltip will be displayed giving you the use of the function. Click the function name. The function name appears in the formula bar and the syntax is displayed, which will guide you as you select the arguments. Click the function name. The function name appears in the formula bar and the syntax is displayed, which will guide you as you select the arguments. Type the first letter of the table name that you want. AutoComplete displays a list of available tables and columns with the names beginning with that letter. Type the first letter of the table name that you want. AutoComplete displays a list of available tables and columns with the names beginning with that letter. Press TAB or click the name to add an item from the AutoComplete list to the formula. Press TAB or click the name to add an item from the AutoComplete list to the formula. Click the Fx button to display a list of available functions. To select a function from the dropdown list, use the arrow keys to highlight the item and click OK to add the function to the formula. Click the Fx button to display a list of available functions. To select a function from the dropdown list, use the arrow keys to highlight the item and click OK to add the function to the formula. Supply the arguments to the function by selecting them from a dropdown list of possible tables and columns or by typing in required values. Supply the arguments to the function by selecting them from a dropdown list of possible tables and columns or by typing in required values. Usage of this handy IntelliSense feature is highly recommended. You can use DAX formulas in creating calculated columns and calculated fields. You can use DAX formulas in calculated columns, by adding a column and then typing an expression in the formula bar. You create these formulas in the PowerPivot window. You can use DAX formulas in calculated columns, by adding a column and then typing an expression in the formula bar. You create these formulas in the PowerPivot window. You can use DAX formulas in calculated fields. You create these formulas − In the Excel window in the Calculated Field dialog box, or In the Power Pivot window in the calculation area of a table. You can use DAX formulas in calculated fields. You create these formulas − In the Excel window in the Calculated Field dialog box, or In the Excel window in the Calculated Field dialog box, or In the Power Pivot window in the calculation area of a table. In the Power Pivot window in the calculation area of a table. The same formula can behave differently depending on whether the formula is used in a calculated column or a calculated field. In a calculated column, the formula is always applied to every row in the column, throughout the table. Depending on the row context, the value might change. In a calculated column, the formula is always applied to every row in the column, throughout the table. Depending on the row context, the value might change. In a calculated field, however, the calculation of results is strongly dependent on the context. That is, the design of the PivotTable and the choice of row and column headings affects the values that are used in calculations. In a calculated field, however, the calculation of results is strongly dependent on the context. That is, the design of the PivotTable and the choice of row and column headings affects the values that are used in calculations. It is important to understand the concept of context in DAX to write DAX formulas. This can be a bit difficult in the beginning of your DAX journey, but once you get a grasp on it, you can write effective DAX formulas that are required for complex and dynamic data analysis. For details, refer to the chapter – DAX Context. You have already learnt about the IntelliSense feature in a previous section. Remember to use it while creating any DAX formula. To create a DAX formula, use the following steps − Type an equal sign. Type an equal sign. To the right of the equal sign, type the following − Type the first letter of a function or table name and select the complete name from the dropdown list. If you have chosen a function name, type parenthesis ‘(‘. If you have chosen the table name, type bracket ‘[‘. Type the first letter of the column name and select the complete name from the dropdown list. Close the column names with ‘]’ and function names with ‘)’. Type a DAX operator between expressions or type ‘,’ to separate function arguments. Repeat steps 1 - 5 till the DAX formula is complete. To the right of the equal sign, type the following − Type the first letter of a function or table name and select the complete name from the dropdown list. Type the first letter of a function or table name and select the complete name from the dropdown list. If you have chosen a function name, type parenthesis ‘(‘. If you have chosen a function name, type parenthesis ‘(‘. If you have chosen the table name, type bracket ‘[‘. Type the first letter of the column name and select the complete name from the dropdown list. If you have chosen the table name, type bracket ‘[‘. Type the first letter of the column name and select the complete name from the dropdown list. Close the column names with ‘]’ and function names with ‘)’. Close the column names with ‘]’ and function names with ‘)’. Type a DAX operator between expressions or type ‘,’ to separate function arguments. Type a DAX operator between expressions or type ‘,’ to separate function arguments. Repeat steps 1 - 5 till the DAX formula is complete. Repeat steps 1 - 5 till the DAX formula is complete. For example, you want to find the total sales amount in the East region. You can write a DAX formula as shown below. East_Sales is the name of the table. Amount is a column in the table. SUM ([East_Sales[Amount]) As already discussed in the chapter – DAX Syntax, it is a recommended practice to use the table name along with the column name in every reference to any column name. This is termed as – “the fully qualified name”. The DAX formula can vary based on whether it is for a calculated field or calculated column. Refer to the sections below for details. You can create a DAX formula for a calculated column in the Power Pivot window. Click the tab of the table in which you want to add the calculated column. Click the Design tab on the Ribbon. Click Add. Type the DAX formula for the calculated column in the formula bar. = DIVIDE (East_Sales[Amount], East_Sales[Units]) This DAX formula does the following for every row in the table East_Sales − Divides the value in Amount column of a row by the value in Units column in the same row. Divides the value in Amount column of a row by the value in Units column in the same row. Places the result in the new added column in the same row. Places the result in the new added column in the same row. Repeats steps 1 and 2 iteratively till it completes all the rows in the table. Repeats steps 1 and 2 iteratively till it completes all the rows in the table. You have added a column for Unit Price at which those units are sold with the above formula. As you can observe, calculated columns require computation and storage space as well. Hence, use calculated columns only if necessary. Use calculated fields where possible and sufficient. As you can observe, calculated columns require computation and storage space as well. Hence, use calculated columns only if necessary. Use calculated fields where possible and sufficient. Refer to the chapter - Calculated Columns for details. You can create a DAX formula for a calculated field either in the Excel window or in the Power Pivot window. In the case of calculated field, you need to provide the name beforehand. To create a DAX formula for a calculated field in the Excel window, use the Calculated Field dialog box. To create a DAX formula for a calculated field in the Excel window, use the Calculated Field dialog box. To create a DAX formula for a calculated field in the Power Pivot window, click a cell in the calculation area in the relevant table. Start the DAX formula with CalculatedFieldName:=. To create a DAX formula for a calculated field in the Power Pivot window, click a cell in the calculation area in the relevant table. Start the DAX formula with CalculatedFieldName:=. For example, Total East Sales Amount:=SUM ([East_Sales[Amount]) If you use Calculated Field dialog box in the Excel window, you can check the formula before you save it and make it as a mandatory habit to ensure the use of correct formulas. For more details on these options, refer to the chapter – Calculated Fields. Power Pivot window also has a formula bar that is like Excel window formula bar. Formula bar makes it easier to create and edit formulas, using the AutoComplete functionality so as to minimize syntax errors. To enter the name of a table, begin typing the name of the table. Formula AutoComplete provides a dropdown list containing valid table names that begin with those letters. You can start with one letter and type more letters to narrow down the list if required. To enter the name of a table, begin typing the name of the table. Formula AutoComplete provides a dropdown list containing valid table names that begin with those letters. You can start with one letter and type more letters to narrow down the list if required. To enter the name of a column, you can select it from the list of column names in the selected table. Type a bracket ‘[‘, to the right of the table name, and then choose the column from the list of columns in the selected table. To enter the name of a column, you can select it from the list of column names in the selected table. Type a bracket ‘[‘, to the right of the table name, and then choose the column from the list of columns in the selected table. Following are some tips for using AutoComplete − You can nest functions and formulas in a DAX formula. In such a case, you can use Formula AutoComplete in the middle of an existing formula with nested functions. The text immediately before the insertion point is used to display values in the dropdown list and all of the text after the insertion point remains unchanged. You can nest functions and formulas in a DAX formula. In such a case, you can use Formula AutoComplete in the middle of an existing formula with nested functions. The text immediately before the insertion point is used to display values in the dropdown list and all of the text after the insertion point remains unchanged. Defined names that you create for constants do not get displayed in the AutoComplete dropdown list, but you can still type them. Defined names that you create for constants do not get displayed in the AutoComplete dropdown list, but you can still type them. The closing parenthesis of functions is not automatically added. You need to do it by yourself. The closing parenthesis of functions is not automatically added. You need to do it by yourself. You must make sure that each function is syntactically correct. You must make sure that each function is syntactically correct. You can find the Insert Function button labelled as fx, both in the Power Pivot window and Excel window. The Insert Function button in the Power Pivot window is to the left of formula bar. The Insert Function button in the Power Pivot window is to the left of formula bar. The Insert Function button in the Excel window is in the Calculated Field dialog box to the right of Formula. The Insert Function button in the Excel window is in the Calculated Field dialog box to the right of Formula. When you click on the fx button, Insert Function dialog box appears. The Insert Function dialog box is the easiest way to find a DAX function that is relevant to your DAX formula. The Insert Function dialog box helps you select functions by category and provides short descriptions for each function. Suppose you want to create the following calculated field − Medal Count: = COUNTA (]Medal]) You can use Insert Function dialog box using the following steps − Click the calculation area of the Results table. Type the following in the formula bar − Medal Count: = Click the Insert Function button (fx). Insert Function dialog box appears. Select Statistical in the Select a category box as shown in the following screenshot. Select Statistical in the Select a category box as shown in the following screenshot. Select COUNTA in the Select a function box as shown in the following screenshot. Select COUNTA in the Select a function box as shown in the following screenshot. As you can observe, the selected DAX function syntax and the function description are displayed. This enables you to make sure that it is the function that you want to insert. Click OK. Medal Count:=COUNTA( appears in the formula bar and a tooltip displaying the function syntax also appears. Click OK. Medal Count:=COUNTA( appears in the formula bar and a tooltip displaying the function syntax also appears. Type [. This means you are about to type a column name. The names of all the columns and the calculated fields in the current table will be displayed in the dropdown list. You can use IntelliSense to complete the formula. Type [. This means you are about to type a column name. The names of all the columns and the calculated fields in the current table will be displayed in the dropdown list. You can use IntelliSense to complete the formula. Type M. The displayed names in the dropdown list will be limited to those starting with ‘M’. Type M. The displayed names in the dropdown list will be limited to those starting with ‘M’. Click Medal. Click Medal. Double-click Medal. Medal Count: = COUNTA([Medal] will be displayed in the formula bar. Close the parenthesis. Double-click Medal. Medal Count: = COUNTA([Medal] will be displayed in the formula bar. Close the parenthesis. Press Enter. You are done. You can use the same procedure to create a calculated column also. You can also follow the same steps to insert a function in the Calculated Field dialog box in the Excel window using the Insert Function feature. Press Enter. You are done. You can use the same procedure to create a calculated column also. You can also follow the same steps to insert a function in the Calculated Field dialog box in the Excel window using the Insert Function feature. Click the Insert Function (fx) button to the right of Formula. Click the Insert Function (fx) button to the right of Formula. Insert Function dialog box appears. The rest of the steps are the same as above. DAX formulas can contain up to 64 nested functions. But, it is unlikely that a DAX formula contains so many nested functions. If a DAX formula has many nested functions, it has the following disadvantages − The formula would be very difficult to create. If the formula has errors, it would be very difficult to debug. The formula evaluation would not be very fast. In such cases, you can split the formula into smaller manageable formulas and build the large formula incrementally. When you perform data analysis, you will perform calculations on aggregated data. There are several DAX aggregation functions, such as SUM, COUNT, MIN, MAX, DISTINCTCOUNT, etc. that you can use in DAX formulas. You can automatically create formulas using standard aggregations by using the AutoSum feature in the Power Pivot window. Click the Results tab in the Power Pivot window. Results table will be displayed. Click the Medal column. The entire column – Medal will be selected. Click the Home tab on the Ribbon. Click the down arrow next to AutoSum in the Calculations group. Click COUNT in the dropdown list. As you can observe, the calculated field Count of Medal appears in the calculation area below the column – Medal. The DAX formula also appears in the formula bar − Count of Medal: = COUNTA([Medal]) The AutoSum feature has done the work for you – created the calculated field for data aggregation. Further, AutoSum has taken the appropriate variant of the DAX function COUNT, i.e. COUNTA (DAX has COUNT, COUNTA, COUNTAX functions). A word of caution – To use AutoSum feature, you need to click the down arrow next to AutoSum on the Ribbon. If you click on the AutoSum itself instead, you will get − Sum of Medal: = SUM([Medal]) And an error is flagged as Medal is not a numeric data column and the text in the column cannot be converted to numbers. You can refer to the chapter - DAX Error Reference for details on DAX errors. As you are aware, in the Data Model of Power Pivot, you can work with multiple tables of data and connect the tables by defining relationships. This will enable you to create interesting DAX formulas that use the correlations of the columns among the related tables for calculations. When you create a relationship between two tables, you are expected to make sure that the two columns used as keys have values that match, at least for most of the rows, if not completely. In the Power Pivot Data Model, it is possible to have non-matching values in a key column and still create a relationship, because Power Pivot does not enforce referential integrity (look at the next section for details). However, the presence of blank or non-matching values in a key column might affect the results of the DAX formulas and the appearance of PivotTables. Establishing referential integrity involves building a set of rules to preserve the defined relationships between tables when you enter or delete data. If you do not exclusively ensure this, as Power Pivot does not enforce it, you might not get correct results with the DAX formulas created before data changes are made. If you enforce referential integrity, you can prevent the following pitfalls − Adding rows to a related table when there is no associated row in the primary table (i.e. with matching values in the key columns). Adding rows to a related table when there is no associated row in the primary table (i.e. with matching values in the key columns). Changing data in a primary table that would result in orphan rows in a related table (i.e. rows with a data value in the key column that does not have a matching value in the primary table key column). Changing data in a primary table that would result in orphan rows in a related table (i.e. rows with a data value in the key column that does not have a matching value in the primary table key column). Deleting rows from a primary table when there are matching data values in the rows of the related table. Deleting rows from a primary table when there are matching data values in the rows of the related table. 102 Lectures 10 hours Pavan Lalwani 101 Lectures 6 hours Pavan Lalwani 56 Lectures 5.5 hours Pavan Lalwani 63 Lectures 3.5 hours Yoda Learning 134 Lectures 8.5 hours Yoda Learning 33 Lectures 3 hours Abhishek And Pukhraj Print Add Notes Bookmark this page
[ { "code": null, "e": 2456, "s": 2249, "text": "DAX is a formula language for creating custom calculations in Power PivotTables. You can use the DAX functions that are designed to work with relational data and perform dynamic aggregation in DAX formulas." }, { "code": null, "e": 2634, "s": 2456, "text": "DAX formulas are very similar to Excel formulas. To create a DAX formula, you type an equal sign, followed by a function name or expression and any required values or arguments." }, { "code": null, "e": 2779, "s": 2634, "text": "DAX formulas can include DAX functions and leverage their usage. This is where DAX formulas tend to differ from DAX functions in important ways." }, { "code": null, "e": 2943, "s": 2779, "text": "A DAX function always reference a complete column or a table. If you want to use only particular values from a table or column, you can add filters to the formula." }, { "code": null, "e": 3107, "s": 2943, "text": "A DAX function always reference a complete column or a table. If you want to use only particular values from a table or column, you can add filters to the formula." }, { "code": null, "e": 3303, "s": 3107, "text": "If you want to customize calculations on a row by row basis, Power Pivot provides functions that let you use the current row value or a related value to perform calculations that vary by context." }, { "code": null, "e": 3499, "s": 3303, "text": "If you want to customize calculations on a row by row basis, Power Pivot provides functions that let you use the current row value or a related value to perform calculations that vary by context." }, { "code": null, "e": 3714, "s": 3499, "text": "DAX includes a type of function that returns a table as its result, rather than a single value. These functions can be used to provide input to other functions, thus calculating values for entire tables or columns." }, { "code": null, "e": 3929, "s": 3714, "text": "DAX includes a type of function that returns a table as its result, rather than a single value. These functions can be used to provide input to other functions, thus calculating values for entire tables or columns." }, { "code": null, "e": 4092, "s": 3929, "text": "Some DAX functions provide time intelligence, which lets you create calculations using meaningful ranges of dates and compare the results across parallel periods." }, { "code": null, "e": 4255, "s": 4092, "text": "Some DAX functions provide time intelligence, which lets you create calculations using meaningful ranges of dates and compare the results across parallel periods." }, { "code": null, "e": 4300, "s": 4255, "text": "Every DAX formula has the following syntax −" }, { "code": null, "e": 4344, "s": 4300, "text": "Each formula must begin with an equal sign." }, { "code": null, "e": 4388, "s": 4344, "text": "Each formula must begin with an equal sign." }, { "code": null, "e": 4574, "s": 4388, "text": "To the right of the equal sign, you can either type or select a function name, or type an expression. The expression can contain table names and column names connected by DAX operators." }, { "code": null, "e": 4760, "s": 4574, "text": "To the right of the equal sign, you can either type or select a function name, or type an expression. The expression can contain table names and column names connected by DAX operators." }, { "code": null, "e": 4800, "s": 4760, "text": "Following are some valid DAX formulas −" }, { "code": null, "e": 4829, "s": 4800, "text": "[column_Cost] + [column_Tax]" }, { "code": null, "e": 4840, "s": 4829, "text": "= Today ()" }, { "code": null, "e": 5114, "s": 4840, "text": "DAX provides the IntelliSense feature that will enable you to write DAX formulas promptly and correctly. With this feature, you need not type the table, column, and function names completely, but select the relevant names from the dropdown list while writing a DAX formula." }, { "code": null, "e": 5269, "s": 5114, "text": "Begin to type the first few letters of the function name. AutoComplete displays a list of available functions with the names beginning with those letters." }, { "code": null, "e": 5424, "s": 5269, "text": "Begin to type the first few letters of the function name. AutoComplete displays a list of available functions with the names beginning with those letters." }, { "code": null, "e": 5547, "s": 5424, "text": "Place the pointer on any of the function names. IntelliSense tooltip will be displayed giving you the use of the function." }, { "code": null, "e": 5670, "s": 5547, "text": "Place the pointer on any of the function names. IntelliSense tooltip will be displayed giving you the use of the function." }, { "code": null, "e": 5819, "s": 5670, "text": "Click the function name. The function name appears in the formula bar and the syntax is displayed, which will guide you as you select the arguments." }, { "code": null, "e": 5968, "s": 5819, "text": "Click the function name. The function name appears in the formula bar and the syntax is displayed, which will guide you as you select the arguments." }, { "code": null, "e": 6127, "s": 5968, "text": "Type the first letter of the table name that you want. AutoComplete displays a list of available tables and columns with the names beginning with that letter." }, { "code": null, "e": 6286, "s": 6127, "text": "Type the first letter of the table name that you want. AutoComplete displays a list of available tables and columns with the names beginning with that letter." }, { "code": null, "e": 6372, "s": 6286, "text": "Press TAB or click the name to add an item from the AutoComplete list to the formula." }, { "code": null, "e": 6458, "s": 6372, "text": "Press TAB or click the name to add an item from the AutoComplete list to the formula." }, { "code": null, "e": 6655, "s": 6458, "text": "Click the Fx button to display a list of available functions. To select a function from the dropdown list, use the arrow keys to highlight the item and click OK to add the function to the formula." }, { "code": null, "e": 6852, "s": 6655, "text": "Click the Fx button to display a list of available functions. To select a function from the dropdown list, use the arrow keys to highlight the item and click OK to add the function to the formula." }, { "code": null, "e": 6992, "s": 6852, "text": "Supply the arguments to the function by selecting them from a dropdown list of possible tables and columns or by typing in required values." }, { "code": null, "e": 7132, "s": 6992, "text": "Supply the arguments to the function by selecting them from a dropdown list of possible tables and columns or by typing in required values." }, { "code": null, "e": 7196, "s": 7132, "text": "Usage of this handy IntelliSense feature is highly recommended." }, { "code": null, "e": 7275, "s": 7196, "text": "You can use DAX formulas in creating calculated columns and calculated fields." }, { "code": null, "e": 7444, "s": 7275, "text": "You can use DAX formulas in calculated columns, by adding a column and then typing an expression in the formula bar. You create these formulas in the PowerPivot window." }, { "code": null, "e": 7613, "s": 7444, "text": "You can use DAX formulas in calculated columns, by adding a column and then typing an expression in the formula bar. You create these formulas in the PowerPivot window." }, { "code": null, "e": 7812, "s": 7613, "text": "You can use DAX formulas in calculated fields. You create these formulas −\n\nIn the Excel window in the Calculated Field dialog box, or\nIn the Power Pivot window in the calculation area of a table.\n\n" }, { "code": null, "e": 7887, "s": 7812, "text": "You can use DAX formulas in calculated fields. You create these formulas −" }, { "code": null, "e": 7946, "s": 7887, "text": "In the Excel window in the Calculated Field dialog box, or" }, { "code": null, "e": 8005, "s": 7946, "text": "In the Excel window in the Calculated Field dialog box, or" }, { "code": null, "e": 8067, "s": 8005, "text": "In the Power Pivot window in the calculation area of a table." }, { "code": null, "e": 8129, "s": 8067, "text": "In the Power Pivot window in the calculation area of a table." }, { "code": null, "e": 8256, "s": 8129, "text": "The same formula can behave differently depending on whether the formula is used in a calculated column or a calculated field." }, { "code": null, "e": 8414, "s": 8256, "text": "In a calculated column, the formula is always applied to every row in the column, throughout the table. Depending on the row context, the value might change." }, { "code": null, "e": 8572, "s": 8414, "text": "In a calculated column, the formula is always applied to every row in the column, throughout the table. Depending on the row context, the value might change." }, { "code": null, "e": 8799, "s": 8572, "text": "In a calculated field, however, the calculation of results is strongly dependent on the context. That is, the design of the PivotTable and the choice of row and column headings affects the values that are used in calculations." }, { "code": null, "e": 9026, "s": 8799, "text": "In a calculated field, however, the calculation of results is strongly dependent on the context. That is, the design of the PivotTable and the choice of row and column headings affects the values that are used in calculations." }, { "code": null, "e": 9350, "s": 9026, "text": "It is important to understand the concept of context in DAX to write DAX formulas. This can be a bit difficult in the beginning of your DAX journey, but once you get a grasp on it, you can write effective DAX formulas that are required for complex and dynamic data analysis. For details, refer to the chapter – DAX Context." }, { "code": null, "e": 9479, "s": 9350, "text": "You have already learnt about the IntelliSense feature in a previous section. Remember to use it while creating any DAX formula." }, { "code": null, "e": 9530, "s": 9479, "text": "To create a DAX formula, use the following steps −" }, { "code": null, "e": 9550, "s": 9530, "text": "Type an equal sign." }, { "code": null, "e": 9570, "s": 9550, "text": "Type an equal sign." }, { "code": null, "e": 10132, "s": 9570, "text": "To the right of the equal sign, type the following −\n\nType the first letter of a function or table name and select the complete name from the dropdown list.\nIf you have chosen a function name, type parenthesis ‘(‘.\nIf you have chosen the table name, type bracket ‘[‘. Type the first letter of the column name and select the complete name from the dropdown list.\nClose the column names with ‘]’ and function names with ‘)’.\nType a DAX operator between expressions or type ‘,’ to separate function arguments.\nRepeat steps 1 - 5 till the DAX formula is complete.\n\n" }, { "code": null, "e": 10185, "s": 10132, "text": "To the right of the equal sign, type the following −" }, { "code": null, "e": 10288, "s": 10185, "text": "Type the first letter of a function or table name and select the complete name from the dropdown list." }, { "code": null, "e": 10391, "s": 10288, "text": "Type the first letter of a function or table name and select the complete name from the dropdown list." }, { "code": null, "e": 10449, "s": 10391, "text": "If you have chosen a function name, type parenthesis ‘(‘." }, { "code": null, "e": 10507, "s": 10449, "text": "If you have chosen a function name, type parenthesis ‘(‘." }, { "code": null, "e": 10654, "s": 10507, "text": "If you have chosen the table name, type bracket ‘[‘. Type the first letter of the column name and select the complete name from the dropdown list." }, { "code": null, "e": 10801, "s": 10654, "text": "If you have chosen the table name, type bracket ‘[‘. Type the first letter of the column name and select the complete name from the dropdown list." }, { "code": null, "e": 10862, "s": 10801, "text": "Close the column names with ‘]’ and function names with ‘)’." }, { "code": null, "e": 10923, "s": 10862, "text": "Close the column names with ‘]’ and function names with ‘)’." }, { "code": null, "e": 11007, "s": 10923, "text": "Type a DAX operator between expressions or type ‘,’ to separate function arguments." }, { "code": null, "e": 11091, "s": 11007, "text": "Type a DAX operator between expressions or type ‘,’ to separate function arguments." }, { "code": null, "e": 11144, "s": 11091, "text": "Repeat steps 1 - 5 till the DAX formula is complete." }, { "code": null, "e": 11197, "s": 11144, "text": "Repeat steps 1 - 5 till the DAX formula is complete." }, { "code": null, "e": 11384, "s": 11197, "text": "For example, you want to find the total sales amount in the East region. You can write a DAX formula as shown below. East_Sales is the name of the table. Amount is a column in the table." }, { "code": null, "e": 11412, "s": 11384, "text": "SUM ([East_Sales[Amount]) \n" }, { "code": null, "e": 11627, "s": 11412, "text": "As already discussed in the chapter – DAX Syntax, it is a recommended practice to use the table name along with the column name in every reference to any column name. This is termed as – “the fully qualified name”." }, { "code": null, "e": 11761, "s": 11627, "text": "The DAX formula can vary based on whether it is for a calculated field or calculated column. Refer to the sections below for details." }, { "code": null, "e": 11841, "s": 11761, "text": "You can create a DAX formula for a calculated column in the Power Pivot window." }, { "code": null, "e": 11916, "s": 11841, "text": "Click the tab of the table in which you want to add the calculated column." }, { "code": null, "e": 11952, "s": 11916, "text": "Click the Design tab on the Ribbon." }, { "code": null, "e": 11963, "s": 11952, "text": "Click Add." }, { "code": null, "e": 12030, "s": 11963, "text": "Type the DAX formula for the calculated column in the formula bar." }, { "code": null, "e": 12080, "s": 12030, "text": "= DIVIDE (East_Sales[Amount], East_Sales[Units])\n" }, { "code": null, "e": 12156, "s": 12080, "text": "This DAX formula does the following for every row in the table East_Sales −" }, { "code": null, "e": 12246, "s": 12156, "text": "Divides the value in Amount column of a row by the value in Units column in the same row." }, { "code": null, "e": 12336, "s": 12246, "text": "Divides the value in Amount column of a row by the value in Units column in the same row." }, { "code": null, "e": 12395, "s": 12336, "text": "Places the result in the new added column in the same row." }, { "code": null, "e": 12454, "s": 12395, "text": "Places the result in the new added column in the same row." }, { "code": null, "e": 12533, "s": 12454, "text": "Repeats steps 1 and 2 iteratively till it completes all the rows in the table." }, { "code": null, "e": 12612, "s": 12533, "text": "Repeats steps 1 and 2 iteratively till it completes all the rows in the table." }, { "code": null, "e": 12705, "s": 12612, "text": "You have added a column for Unit Price at which those units are sold with the above formula." }, { "code": null, "e": 12893, "s": 12705, "text": "As you can observe, calculated columns require computation and storage space as well. Hence, use calculated columns only if necessary. Use calculated fields where possible and sufficient." }, { "code": null, "e": 13081, "s": 12893, "text": "As you can observe, calculated columns require computation and storage space as well. Hence, use calculated columns only if necessary. Use calculated fields where possible and sufficient." }, { "code": null, "e": 13136, "s": 13081, "text": "Refer to the chapter - Calculated Columns for details." }, { "code": null, "e": 13319, "s": 13136, "text": "You can create a DAX formula for a calculated field either in the Excel window or in the Power Pivot window. In the case of calculated field, you need to provide the name beforehand." }, { "code": null, "e": 13424, "s": 13319, "text": "To create a DAX formula for a calculated field in the Excel window, use the Calculated Field dialog box." }, { "code": null, "e": 13529, "s": 13424, "text": "To create a DAX formula for a calculated field in the Excel window, use the Calculated Field dialog box." }, { "code": null, "e": 13713, "s": 13529, "text": "To create a DAX formula for a calculated field in the Power Pivot window, click a cell in the calculation area in the relevant table. Start the DAX formula with CalculatedFieldName:=." }, { "code": null, "e": 13897, "s": 13713, "text": "To create a DAX formula for a calculated field in the Power Pivot window, click a cell in the calculation area in the relevant table. Start the DAX formula with CalculatedFieldName:=." }, { "code": null, "e": 13961, "s": 13897, "text": "For example, Total East Sales Amount:=SUM ([East_Sales[Amount])" }, { "code": null, "e": 14138, "s": 13961, "text": "If you use Calculated Field dialog box in the Excel window, you can check the formula before you save it and make it as a mandatory habit to ensure the use of correct formulas." }, { "code": null, "e": 14215, "s": 14138, "text": "For more details on these options, refer to the chapter – Calculated Fields." }, { "code": null, "e": 14423, "s": 14215, "text": "Power Pivot window also has a formula bar that is like Excel window formula bar. Formula bar makes it easier to create and edit formulas, using the AutoComplete functionality so as to minimize syntax errors." }, { "code": null, "e": 14684, "s": 14423, "text": "To enter the name of a table, begin typing the name of the table. Formula AutoComplete provides a dropdown list containing valid table names that begin with those letters. You can start with one letter and type more letters to narrow down the list if required." }, { "code": null, "e": 14945, "s": 14684, "text": "To enter the name of a table, begin typing the name of the table. Formula AutoComplete provides a dropdown list containing valid table names that begin with those letters. You can start with one letter and type more letters to narrow down the list if required." }, { "code": null, "e": 15174, "s": 14945, "text": "To enter the name of a column, you can select it from the list of column names in the selected table. Type a bracket ‘[‘, to the right of the table name, and then choose the column from the list of columns in the selected table." }, { "code": null, "e": 15403, "s": 15174, "text": "To enter the name of a column, you can select it from the list of column names in the selected table. Type a bracket ‘[‘, to the right of the table name, and then choose the column from the list of columns in the selected table." }, { "code": null, "e": 15452, "s": 15403, "text": "Following are some tips for using AutoComplete −" }, { "code": null, "e": 15775, "s": 15452, "text": "You can nest functions and formulas in a DAX formula. In such a case, you can use Formula AutoComplete in the middle of an existing formula with nested functions. The text immediately before the insertion point is used to display values in the dropdown list and all of the text after the insertion point remains unchanged." }, { "code": null, "e": 16098, "s": 15775, "text": "You can nest functions and formulas in a DAX formula. In such a case, you can use Formula AutoComplete in the middle of an existing formula with nested functions. The text immediately before the insertion point is used to display values in the dropdown list and all of the text after the insertion point remains unchanged." }, { "code": null, "e": 16227, "s": 16098, "text": "Defined names that you create for constants do not get displayed in the AutoComplete dropdown list, but you can still type them." }, { "code": null, "e": 16356, "s": 16227, "text": "Defined names that you create for constants do not get displayed in the AutoComplete dropdown list, but you can still type them." }, { "code": null, "e": 16452, "s": 16356, "text": "The closing parenthesis of functions is not automatically added. You need to do it by yourself." }, { "code": null, "e": 16548, "s": 16452, "text": "The closing parenthesis of functions is not automatically added. You need to do it by yourself." }, { "code": null, "e": 16612, "s": 16548, "text": "You must make sure that each function is syntactically correct." }, { "code": null, "e": 16676, "s": 16612, "text": "You must make sure that each function is syntactically correct." }, { "code": null, "e": 16781, "s": 16676, "text": "You can find the Insert Function button labelled as fx, both in the Power Pivot window and Excel window." }, { "code": null, "e": 16865, "s": 16781, "text": "The Insert Function button in the Power Pivot window is to the left of formula bar." }, { "code": null, "e": 16949, "s": 16865, "text": "The Insert Function button in the Power Pivot window is to the left of formula bar." }, { "code": null, "e": 17059, "s": 16949, "text": "The Insert Function button in the Excel window is in the Calculated Field dialog box to the right of Formula." }, { "code": null, "e": 17169, "s": 17059, "text": "The Insert Function button in the Excel window is in the Calculated Field dialog box to the right of Formula." }, { "code": null, "e": 17349, "s": 17169, "text": "When you click on the fx button, Insert Function dialog box appears. The Insert Function dialog box is the easiest way to find a DAX function that is relevant to your DAX formula." }, { "code": null, "e": 17470, "s": 17349, "text": "The Insert Function dialog box helps you select functions by category and provides short descriptions for each function." }, { "code": null, "e": 17530, "s": 17470, "text": "Suppose you want to create the following calculated field −" }, { "code": null, "e": 17564, "s": 17530, "text": "Medal Count: = COUNTA (]Medal]) \n" }, { "code": null, "e": 17631, "s": 17564, "text": "You can use Insert Function dialog box using the following steps −" }, { "code": null, "e": 17680, "s": 17631, "text": "Click the calculation area of the Results table." }, { "code": null, "e": 17720, "s": 17680, "text": "Type the following in the formula bar −" }, { "code": null, "e": 17737, "s": 17720, "text": "Medal Count: = \n" }, { "code": null, "e": 17776, "s": 17737, "text": "Click the Insert Function button (fx)." }, { "code": null, "e": 17812, "s": 17776, "text": "Insert Function dialog box appears." }, { "code": null, "e": 17898, "s": 17812, "text": "Select Statistical in the Select a category box as shown in the following screenshot." }, { "code": null, "e": 17984, "s": 17898, "text": "Select Statistical in the Select a category box as shown in the following screenshot." }, { "code": null, "e": 18065, "s": 17984, "text": "Select COUNTA in the Select a function box as shown in the following screenshot." }, { "code": null, "e": 18146, "s": 18065, "text": "Select COUNTA in the Select a function box as shown in the following screenshot." }, { "code": null, "e": 18322, "s": 18146, "text": "As you can observe, the selected DAX function syntax and the function description are displayed. This enables you to make sure that it is the function that you want to insert." }, { "code": null, "e": 18439, "s": 18322, "text": "Click OK. Medal Count:=COUNTA( appears in the formula bar and a tooltip displaying the function syntax also appears." }, { "code": null, "e": 18556, "s": 18439, "text": "Click OK. Medal Count:=COUNTA( appears in the formula bar and a tooltip displaying the function syntax also appears." }, { "code": null, "e": 18778, "s": 18556, "text": "Type [. This means you are about to type a column name. The names of all the columns and the calculated fields in the current table will be displayed in the dropdown list. You can use IntelliSense to complete the formula." }, { "code": null, "e": 19000, "s": 18778, "text": "Type [. This means you are about to type a column name. The names of all the columns and the calculated fields in the current table will be displayed in the dropdown list. You can use IntelliSense to complete the formula." }, { "code": null, "e": 19093, "s": 19000, "text": "Type M. The displayed names in the dropdown list will be limited to those starting with ‘M’." }, { "code": null, "e": 19186, "s": 19093, "text": "Type M. The displayed names in the dropdown list will be limited to those starting with ‘M’." }, { "code": null, "e": 19199, "s": 19186, "text": "Click Medal." }, { "code": null, "e": 19212, "s": 19199, "text": "Click Medal." }, { "code": null, "e": 19323, "s": 19212, "text": "Double-click Medal. Medal Count: = COUNTA([Medal] will be displayed in the formula bar. Close the parenthesis." }, { "code": null, "e": 19434, "s": 19323, "text": "Double-click Medal. Medal Count: = COUNTA([Medal] will be displayed in the formula bar. Close the parenthesis." }, { "code": null, "e": 19674, "s": 19434, "text": "Press Enter. You are done. You can use the same procedure to create a calculated column also. You can also follow the same steps to insert a function in the Calculated Field dialog box in the Excel window using the Insert Function feature." }, { "code": null, "e": 19914, "s": 19674, "text": "Press Enter. You are done. You can use the same procedure to create a calculated column also. You can also follow the same steps to insert a function in the Calculated Field dialog box in the Excel window using the Insert Function feature." }, { "code": null, "e": 19977, "s": 19914, "text": "Click the Insert Function (fx) button to the right of Formula." }, { "code": null, "e": 20040, "s": 19977, "text": "Click the Insert Function (fx) button to the right of Formula." }, { "code": null, "e": 20121, "s": 20040, "text": "Insert Function dialog box appears. The rest of the steps are the same as above." }, { "code": null, "e": 20247, "s": 20121, "text": "DAX formulas can contain up to 64 nested functions. But, it is unlikely that a DAX formula contains so many nested functions." }, { "code": null, "e": 20328, "s": 20247, "text": "If a DAX formula has many nested functions, it has the following disadvantages −" }, { "code": null, "e": 20375, "s": 20328, "text": "The formula would be very difficult to create." }, { "code": null, "e": 20439, "s": 20375, "text": "If the formula has errors, it would be very difficult to debug." }, { "code": null, "e": 20486, "s": 20439, "text": "The formula evaluation would not be very fast." }, { "code": null, "e": 20603, "s": 20486, "text": "In such cases, you can split the formula into smaller manageable formulas and build the large formula incrementally." }, { "code": null, "e": 20814, "s": 20603, "text": "When you perform data analysis, you will perform calculations on aggregated data. There are several DAX aggregation functions, such as SUM, COUNT, MIN, MAX, DISTINCTCOUNT, etc. that you can use in DAX formulas." }, { "code": null, "e": 20936, "s": 20814, "text": "You can automatically create formulas using standard aggregations by using the AutoSum feature in the Power Pivot window." }, { "code": null, "e": 21018, "s": 20936, "text": "Click the Results tab in the Power Pivot window. Results table will be displayed." }, { "code": null, "e": 21086, "s": 21018, "text": "Click the Medal column. The entire column – Medal will be selected." }, { "code": null, "e": 21120, "s": 21086, "text": "Click the Home tab on the Ribbon." }, { "code": null, "e": 21184, "s": 21120, "text": "Click the down arrow next to AutoSum in the Calculations group." }, { "code": null, "e": 21218, "s": 21184, "text": "Click COUNT in the dropdown list." }, { "code": null, "e": 21382, "s": 21218, "text": "As you can observe, the calculated field Count of Medal appears in the calculation area below the column – Medal. The DAX formula also appears in the formula bar −" }, { "code": null, "e": 21418, "s": 21382, "text": "Count of Medal: = COUNTA([Medal]) \n" }, { "code": null, "e": 21651, "s": 21418, "text": "The AutoSum feature has done the work for you – created the calculated field for data aggregation. Further, AutoSum has taken the appropriate variant of the DAX function COUNT, i.e. COUNTA (DAX has COUNT, COUNTA, COUNTAX functions)." }, { "code": null, "e": 21818, "s": 21651, "text": "A word of caution – To use AutoSum feature, you need to click the down arrow next to AutoSum on the Ribbon. If you click on the AutoSum itself instead, you will get −" }, { "code": null, "e": 21849, "s": 21818, "text": "Sum of Medal: = SUM([Medal]) \n" }, { "code": null, "e": 21970, "s": 21849, "text": "And an error is flagged as Medal is not a numeric data column and the text in the column cannot be converted to numbers." }, { "code": null, "e": 22048, "s": 21970, "text": "You can refer to the chapter - DAX Error Reference for details on DAX errors." }, { "code": null, "e": 22332, "s": 22048, "text": "As you are aware, in the Data Model of Power Pivot, you can work with multiple tables of data and connect the tables by defining relationships. This will enable you to create interesting DAX formulas that use the correlations of the columns among the related tables for calculations." }, { "code": null, "e": 22893, "s": 22332, "text": "When you create a relationship between two tables, you are expected to make sure that the two columns used as keys have values that match, at least for most of the rows, if not completely. In the Power Pivot Data Model, it is possible to have non-matching values in a key column and still create a relationship, because Power Pivot does not enforce referential integrity (look at the next section for details). However, the presence of blank or non-matching values in a key column might affect the results of the DAX formulas and the appearance of PivotTables." }, { "code": null, "e": 23214, "s": 22893, "text": "Establishing referential integrity involves building a set of rules to preserve the defined relationships between tables when you enter or delete data. If you do not exclusively ensure this, as Power Pivot does not enforce it, you might not get correct results with the DAX formulas created before data changes are made." }, { "code": null, "e": 23293, "s": 23214, "text": "If you enforce referential integrity, you can prevent the following pitfalls −" }, { "code": null, "e": 23425, "s": 23293, "text": "Adding rows to a related table when there is no associated row in the primary table (i.e. with matching values in the key columns)." }, { "code": null, "e": 23557, "s": 23425, "text": "Adding rows to a related table when there is no associated row in the primary table (i.e. with matching values in the key columns)." }, { "code": null, "e": 23759, "s": 23557, "text": "Changing data in a primary table that would result in orphan rows in a related table (i.e. rows with a data value in the key column that does not have a matching value in the primary table key column)." }, { "code": null, "e": 23961, "s": 23759, "text": "Changing data in a primary table that would result in orphan rows in a related table (i.e. rows with a data value in the key column that does not have a matching value in the primary table key column)." }, { "code": null, "e": 24066, "s": 23961, "text": "Deleting rows from a primary table when there are matching data values in the rows of the related table." }, { "code": null, "e": 24171, "s": 24066, "text": "Deleting rows from a primary table when there are matching data values in the rows of the related table." }, { "code": null, "e": 24206, "s": 24171, "text": "\n 102 Lectures \n 10 hours \n" }, { "code": null, "e": 24221, "s": 24206, "text": " Pavan Lalwani" }, { "code": null, "e": 24255, "s": 24221, "text": "\n 101 Lectures \n 6 hours \n" }, { "code": null, "e": 24270, "s": 24255, "text": " Pavan Lalwani" }, { "code": null, "e": 24305, "s": 24270, "text": "\n 56 Lectures \n 5.5 hours \n" }, { "code": null, "e": 24320, "s": 24305, "text": " Pavan Lalwani" }, { "code": null, "e": 24355, "s": 24320, "text": "\n 63 Lectures \n 3.5 hours \n" }, { "code": null, "e": 24370, "s": 24355, "text": " Yoda Learning" }, { "code": null, "e": 24406, "s": 24370, "text": "\n 134 Lectures \n 8.5 hours \n" }, { "code": null, "e": 24421, "s": 24406, "text": " Yoda Learning" }, { "code": null, "e": 24454, "s": 24421, "text": "\n 33 Lectures \n 3 hours \n" }, { "code": null, "e": 24476, "s": 24454, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 24483, "s": 24476, "text": " Print" }, { "code": null, "e": 24494, "s": 24483, "text": " Add Notes" } ]
Java Program to Count the Number of Lines, Words, Characters, and Paragraphs in a Text File - GeeksforGeeks
05 Oct, 2021 Counting the number of characters is essential because almost all the text boxes that rely on user input have certain limitations on the number of characters inserted. For example, the character limit on a Facebook post is 63206 characters. Whereas for a tweet on Twitter, the character limit is 140 characters, and the character limit is 80 per post for Snapchat. Determining character limits become crucial when the tweet and Facebook post updates are being done through APIs. This function is present under the java.io.File package. It creates a new File instance by converting the given pathname string into an abstract pathname. Syntax: public File(String pathname) Parameters: pathname - A pathname string This function is present under the java.io.FileInputStream package. It creates a FileInputStream by opening a connection to an actual file named by the File object file in the file system. Syntax: public FileInputStream(File file) throws FileNotFoundException Parameters: file - the file to be opened for reading. Throws: FileNotFoundException – if the file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading. SecurityException – if a security manager exists and its checkRead method denies read access to the file. This function is present under the java.io.InputStreamReader package. It creates an InputStreamReader that uses the default charset. Syntax: public InputStreamReader(InputStream in) Parameters: in - An InputStream This function is present under the java.io.BufferedReader package. It creates a buffering character-input stream that uses a default-sized input buffer. Syntax: public BufferedReader(Reader in) Parameters: in - A Reader Java // Java program to count the// number of lines, words, sentences, // characters, and whitespaces in a fileimport java.io.*; public class Test { public static void main(String[] args) throws IOException { File file = new File("C:\\Users\\hp\\Desktop\\TextReader.txt"); FileInputStream fileInputStream = new FileInputStream(file); InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String line; int wordCount = 0; int characterCount = 0; int paraCount = 0; int whiteSpaceCount = 0; int sentenceCount = 0; while ((line = bufferedReader.readLine()) != null) { if (line.equals("")) { paraCount += 1; } else { characterCount += line.length(); String words[] = line.split("\\s+"); wordCount += words.length; whiteSpaceCount += wordCount - 1; String sentence[] = line.split("[!?.:]+"); sentenceCount += sentence.length; } } if (sentenceCount >= 1) { paraCount++; } System.out.println("Total word count = "+ wordCount); System.out.println("Total number of sentences = "+ sentenceCount); System.out.println("Total number of characters = "+ characterCount); System.out.println("Number of paragraphs = "+ paraCount); System.out.println("Total number of whitespaces = "+ whiteSpaceCount); }} The TextReader.txt file contains the following data – Hello Geeks. My name is Nishkarsh Gandhi. GeeksforGeeks is a Computer Science portal for geeks. Output: Note: This program would not run on online compilers. Please make a txt file on your system and give its path to run this program on your system. This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect or you want to share more information about the topic discussed above. UmeshAgrawal sagar0719kumar sahilsehgals4392 nishkarshgandhi java-file-handling Java-I/O Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Interfaces in Java Singleton Class in Java Multithreading in Java Set in Java Collections in Java Queue Interface In Java Initializing a List in Java Different ways of Reading a text file in Java Constructors in Java Inheritance in Java
[ { "code": null, "e": 24514, "s": 24486, "text": "\n05 Oct, 2021" }, { "code": null, "e": 24879, "s": 24514, "text": "Counting the number of characters is essential because almost all the text boxes that rely on user input have certain limitations on the number of characters inserted. For example, the character limit on a Facebook post is 63206 characters. Whereas for a tweet on Twitter, the character limit is 140 characters, and the character limit is 80 per post for Snapchat." }, { "code": null, "e": 24994, "s": 24879, "text": "Determining character limits become crucial when the tweet and Facebook post updates are being done through APIs. " }, { "code": null, "e": 25150, "s": 24994, "text": "This function is present under the java.io.File package. It creates a new File instance by converting the given pathname string into an abstract pathname. " }, { "code": null, "e": 25159, "s": 25150, "text": "Syntax: " }, { "code": null, "e": 25188, "s": 25159, "text": "public File(String pathname)" }, { "code": null, "e": 25200, "s": 25188, "text": "Parameters:" }, { "code": null, "e": 25229, "s": 25200, "text": "pathname - A pathname string" }, { "code": null, "e": 25419, "s": 25229, "text": "This function is present under the java.io.FileInputStream package. It creates a FileInputStream by opening a connection to an actual file named by the File object file in the file system. " }, { "code": null, "e": 25428, "s": 25419, "text": "Syntax: " }, { "code": null, "e": 25491, "s": 25428, "text": "public FileInputStream(File file) throws FileNotFoundException" }, { "code": null, "e": 25503, "s": 25491, "text": "Parameters:" }, { "code": null, "e": 25545, "s": 25503, "text": "file - the file to be opened for reading." }, { "code": null, "e": 25553, "s": 25545, "text": "Throws:" }, { "code": null, "e": 25703, "s": 25553, "text": "FileNotFoundException – if the file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading." }, { "code": null, "e": 25809, "s": 25703, "text": "SecurityException – if a security manager exists and its checkRead method denies read access to the file." }, { "code": null, "e": 25943, "s": 25809, "text": "This function is present under the java.io.InputStreamReader package. It creates an InputStreamReader that uses the default charset. " }, { "code": null, "e": 25952, "s": 25943, "text": "Syntax: " }, { "code": null, "e": 25993, "s": 25952, "text": "public InputStreamReader(InputStream in)" }, { "code": null, "e": 26005, "s": 25993, "text": "Parameters:" }, { "code": null, "e": 26025, "s": 26005, "text": "in - An InputStream" }, { "code": null, "e": 26179, "s": 26025, "text": "This function is present under the java.io.BufferedReader package. It creates a buffering character-input stream that uses a default-sized input buffer. " }, { "code": null, "e": 26188, "s": 26179, "text": "Syntax: " }, { "code": null, "e": 26221, "s": 26188, "text": "public BufferedReader(Reader in)" }, { "code": null, "e": 26233, "s": 26221, "text": "Parameters:" }, { "code": null, "e": 26247, "s": 26233, "text": "in - A Reader" }, { "code": null, "e": 26252, "s": 26247, "text": "Java" }, { "code": "// Java program to count the// number of lines, words, sentences, // characters, and whitespaces in a fileimport java.io.*; public class Test { public static void main(String[] args) throws IOException { File file = new File(\"C:\\\\Users\\\\hp\\\\Desktop\\\\TextReader.txt\"); FileInputStream fileInputStream = new FileInputStream(file); InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String line; int wordCount = 0; int characterCount = 0; int paraCount = 0; int whiteSpaceCount = 0; int sentenceCount = 0; while ((line = bufferedReader.readLine()) != null) { if (line.equals(\"\")) { paraCount += 1; } else { characterCount += line.length(); String words[] = line.split(\"\\\\s+\"); wordCount += words.length; whiteSpaceCount += wordCount - 1; String sentence[] = line.split(\"[!?.:]+\"); sentenceCount += sentence.length; } } if (sentenceCount >= 1) { paraCount++; } System.out.println(\"Total word count = \"+ wordCount); System.out.println(\"Total number of sentences = \"+ sentenceCount); System.out.println(\"Total number of characters = \"+ characterCount); System.out.println(\"Number of paragraphs = \"+ paraCount); System.out.println(\"Total number of whitespaces = \"+ whiteSpaceCount); }}", "e": 27844, "s": 26252, "text": null }, { "code": null, "e": 27899, "s": 27844, "text": "The TextReader.txt file contains the following data – " }, { "code": null, "e": 27995, "s": 27899, "text": "Hello Geeks. My name is Nishkarsh Gandhi.\nGeeksforGeeks is a Computer Science portal for geeks." }, { "code": null, "e": 28003, "s": 27995, "text": "Output:" }, { "code": null, "e": 28150, "s": 28003, "text": "Note: This program would not run on online compilers. Please make a txt file on your system and give its path to run this program on your system. " }, { "code": null, "e": 28565, "s": 28150, "text": "This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect or you want to share more information about the topic discussed above." }, { "code": null, "e": 28578, "s": 28565, "text": "UmeshAgrawal" }, { "code": null, "e": 28593, "s": 28578, "text": "sagar0719kumar" }, { "code": null, "e": 28610, "s": 28593, "text": "sahilsehgals4392" }, { "code": null, "e": 28626, "s": 28610, "text": "nishkarshgandhi" }, { "code": null, "e": 28645, "s": 28626, "text": "java-file-handling" }, { "code": null, "e": 28654, "s": 28645, "text": "Java-I/O" }, { "code": null, "e": 28659, "s": 28654, "text": "Java" }, { "code": null, "e": 28664, "s": 28659, "text": "Java" }, { "code": null, "e": 28762, "s": 28664, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28771, "s": 28762, "text": "Comments" }, { "code": null, "e": 28784, "s": 28771, "text": "Old Comments" }, { "code": null, "e": 28803, "s": 28784, "text": "Interfaces in Java" }, { "code": null, "e": 28827, "s": 28803, "text": "Singleton Class in Java" }, { "code": null, "e": 28850, "s": 28827, "text": "Multithreading in Java" }, { "code": null, "e": 28862, "s": 28850, "text": "Set in Java" }, { "code": null, "e": 28882, "s": 28862, "text": "Collections in Java" }, { "code": null, "e": 28906, "s": 28882, "text": "Queue Interface In Java" }, { "code": null, "e": 28934, "s": 28906, "text": "Initializing a List in Java" }, { "code": null, "e": 28980, "s": 28934, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 29001, "s": 28980, "text": "Constructors in Java" } ]
Vector Projection using Python - GeeksforGeeks
29 Nov, 2019 A vector is a geometric object which has both magnitude (i.e. length) and direction. A vector is generally represented by a line segment with a certain direction connecting the initial point A and the terminal point B as shown in the figure below and is denoted by The projection of a vector onto another vector is given as Computing vector projection onto another vector in Python: # import numpy to perform operations on vectorimport numpy as np u = np.array([1, 2, 3]) # vector uv = np.array([5, 6, 2]) # vector v: # Task: Project vector u on vector v # finding norm of the vector vv_norm = np.sqrt(sum(v**2)) # Apply the formula as mentioned above# for projecting a vector onto another vector# find dot product using np.dot()proj_of_u_on_v = (np.dot(u, v)/v_norm**2)*v print("Projection of Vector u on Vector v is: ", proj_of_u_on_v) Output: Projection of Vector u on Vector v is: [1.76923077 2.12307692 0.70769231] One liner code for projecting a vector onto another vector: (np.dot(u, v)/np.dot(v, v))*v The projection of a vector onto a plane is calculated by subtracting the component of which is orthogonal to the plane from .where, is the plane normal vector. Computing vector projection onto a Plane in Python: # import numpy to perform operations on vectorimport numpy as np # vector u u = np.array([2, 5, 8]) # vector n: n is orthogonal vector to Plane Pn = np.array([1, 1, 7]) # Task: Project vector u on Plane P # finding norm of the vector n n_norm = np.sqrt(sum(n**2)) # Apply the formula as mentioned above# for projecting a vector onto the orthogonal vector n# find dot product using np.dot()proj_of_u_on_n = (np.dot(u, n)/n_norm**2)*n # subtract proj_of_u_on_n from u: # this is the projection of u on Plane Pprint("Projection of Vector u on Plane P is: ", u - proj_of_u_on_n) Output: Projection of Vector u on Plane P is: [ 0.76470588 3.76470588 -0.64705882] Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Decision Tree Reinforcement learning Decision Tree Introduction with example Python | Decision tree implementation Read JSON file using Python Adding new column to existing DataFrame in Pandas How to get column names in Pandas dataframe Python Dictionary Taking input in Python
[ { "code": null, "e": 25477, "s": 25449, "text": "\n29 Nov, 2019" }, { "code": null, "e": 25743, "s": 25477, "text": "A vector is a geometric object which has both magnitude (i.e. length) and direction. A vector is generally represented by a line segment with a certain direction connecting the initial point A and the terminal point B as shown in the figure below and is denoted by " }, { "code": null, "e": 25804, "s": 25743, "text": "The projection of a vector onto another vector is given as" }, { "code": null, "e": 25863, "s": 25804, "text": "Computing vector projection onto another vector in Python:" }, { "code": "# import numpy to perform operations on vectorimport numpy as np u = np.array([1, 2, 3]) # vector uv = np.array([5, 6, 2]) # vector v: # Task: Project vector u on vector v # finding norm of the vector vv_norm = np.sqrt(sum(v**2)) # Apply the formula as mentioned above# for projecting a vector onto another vector# find dot product using np.dot()proj_of_u_on_v = (np.dot(u, v)/v_norm**2)*v print(\"Projection of Vector u on Vector v is: \", proj_of_u_on_v)", "e": 26331, "s": 25863, "text": null }, { "code": null, "e": 26339, "s": 26331, "text": "Output:" }, { "code": null, "e": 26414, "s": 26339, "text": "Projection of Vector u on Vector v is: [1.76923077 2.12307692 0.70769231]" }, { "code": null, "e": 26474, "s": 26414, "text": "One liner code for projecting a vector onto another vector:" }, { "code": "(np.dot(u, v)/np.dot(v, v))*v", "e": 26504, "s": 26474, "text": null }, { "code": null, "e": 26667, "s": 26504, "text": "The projection of a vector onto a plane is calculated by subtracting the component of which is orthogonal to the plane from .where, is the plane normal vector." }, { "code": null, "e": 26719, "s": 26667, "text": "Computing vector projection onto a Plane in Python:" }, { "code": "# import numpy to perform operations on vectorimport numpy as np # vector u u = np.array([2, 5, 8]) # vector n: n is orthogonal vector to Plane Pn = np.array([1, 1, 7]) # Task: Project vector u on Plane P # finding norm of the vector n n_norm = np.sqrt(sum(n**2)) # Apply the formula as mentioned above# for projecting a vector onto the orthogonal vector n# find dot product using np.dot()proj_of_u_on_n = (np.dot(u, n)/n_norm**2)*n # subtract proj_of_u_on_n from u: # this is the projection of u on Plane Pprint(\"Projection of Vector u on Plane P is: \", u - proj_of_u_on_n)", "e": 27320, "s": 26719, "text": null }, { "code": null, "e": 27328, "s": 27320, "text": "Output:" }, { "code": null, "e": 27405, "s": 27328, "text": "Projection of Vector u on Plane P is: [ 0.76470588 3.76470588 -0.64705882]" }, { "code": null, "e": 27422, "s": 27405, "text": "Machine Learning" }, { "code": null, "e": 27429, "s": 27422, "text": "Python" }, { "code": null, "e": 27446, "s": 27429, "text": "Machine Learning" }, { "code": null, "e": 27544, "s": 27446, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27567, "s": 27544, "text": "ML | Linear Regression" }, { "code": null, "e": 27581, "s": 27567, "text": "Decision Tree" }, { "code": null, "e": 27604, "s": 27581, "text": "Reinforcement learning" }, { "code": null, "e": 27644, "s": 27604, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 27682, "s": 27644, "text": "Python | Decision tree implementation" }, { "code": null, "e": 27710, "s": 27682, "text": "Read JSON file using Python" }, { "code": null, "e": 27760, "s": 27710, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 27804, "s": 27760, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 27822, "s": 27804, "text": "Python Dictionary" } ]
JavaScript | Dialogue Boxes - GeeksforGeeks
01 Apr, 2022 JavaScript uses 3 kind of dialog boxes : ALERT, PROMPT and CONFIRM. These dialog boxes can be of very much help for making our website look more attractive. An alert box is used in the website to show a warning message to the user that they have entered the wrong value other than what is required to filled in that position. Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only one button “OK” to select and proceed. Example : JavaScript <!DOCTYPE html><html> <head> <script type="text/javascript"> function Warning() { alert ("Warning danger you have not filled everything"); document.write ("Warning danger you have not filled everything"); } </script> </head> <body> <p>Click me </p> <form> <input type="button" value="Click Me" onclick="Warning();" /> </form> </body></html> Output : A confirm box is often used if you want the user to verify or accept something. When a confirm box pops up, the user will have to click either “OK” or “Cancel” to proceed. If the user clicks on the OK button, the window method confirm() will return true. If the user clicks on the Cancel button, then confirm() returns false and will show null. Example : JavaScript <!DOCTYPE html><html> <head> <script type="text/javascript"> function Confirmation(){ var Val = confirm("Do you want to continue ?"); if( Val == true ){ document.write (" CONTINUED!"); return true; } else{ document.write ("NOT CONTINUED!"); return false; } } </script> </head> <body> <p>Click me: </p> <form> <input type="button" value="Click Me" onclick="Confirmation();" /> </form> </body></html> Output : A prompt box is often used if you want the user to input a value before entering a page. When a prompt box pops up, the user will have to click either “OK” or “Cancel” to proceed after entering an input value. If the user clicks the OK button, the window method prompt() will return the entered value from the text box. If the user clicks the Cancel button, the window method prompt() returns null. Example : JavaScript <!DOCTYPE html><html> <head> <script type="text/javascript"> function Value(){ var Val = prompt("Enter your name : ", "name"); document.write("You entered : " + Val); } </script> </head> <body> <p>Click me: </p> <form> <input type="button" value="Click Me" onclick="Value();" /> </form> </body></html> Output : Example : JavaScript <!DOCTYPE html><html><body> <p>Line-Breaks</p> <button onclick="alert('GEEKSFOR\nGEEKS')">CLICK ME</button> </body></html> Output : sweetyty manasborse123 javascript-form HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript How to calculate the number of days between two dates in javascript? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 31439, "s": 31411, "text": "\n01 Apr, 2022" }, { "code": null, "e": 31597, "s": 31439, "text": "JavaScript uses 3 kind of dialog boxes : ALERT, PROMPT and CONFIRM. These dialog boxes can be of very much help for making our website look more attractive. " }, { "code": null, "e": 31895, "s": 31597, "text": "An alert box is used in the website to show a warning message to the user that they have entered the wrong value other than what is required to filled in that position. Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only one button “OK” to select and proceed." }, { "code": null, "e": 31906, "s": 31895, "text": "Example : " }, { "code": null, "e": 31917, "s": 31906, "text": "JavaScript" }, { "code": "<!DOCTYPE html><html> <head> <script type=\"text/javascript\"> function Warning() { alert (\"Warning danger you have not filled everything\"); document.write (\"Warning danger you have not filled everything\"); } </script> </head> <body> <p>Click me </p> <form> <input type=\"button\" value=\"Click Me\" onclick=\"Warning();\" /> </form> </body></html>", "e": 32386, "s": 31917, "text": null }, { "code": null, "e": 32395, "s": 32386, "text": "Output :" }, { "code": null, "e": 32740, "s": 32395, "text": "A confirm box is often used if you want the user to verify or accept something. When a confirm box pops up, the user will have to click either “OK” or “Cancel” to proceed. If the user clicks on the OK button, the window method confirm() will return true. If the user clicks on the Cancel button, then confirm() returns false and will show null." }, { "code": null, "e": 32750, "s": 32740, "text": "Example :" }, { "code": null, "e": 32761, "s": 32750, "text": "JavaScript" }, { "code": "<!DOCTYPE html><html> <head> <script type=\"text/javascript\"> function Confirmation(){ var Val = confirm(\"Do you want to continue ?\"); if( Val == true ){ document.write (\" CONTINUED!\"); return true; } else{ document.write (\"NOT CONTINUED!\"); return false; } } </script> </head> <body> <p>Click me: </p> <form> <input type=\"button\" value=\"Click Me\" onclick=\"Confirmation();\" /> </form> </body></html>", "e": 33398, "s": 32761, "text": null }, { "code": null, "e": 33407, "s": 33398, "text": "Output :" }, { "code": null, "e": 33806, "s": 33407, "text": "A prompt box is often used if you want the user to input a value before entering a page. When a prompt box pops up, the user will have to click either “OK” or “Cancel” to proceed after entering an input value. If the user clicks the OK button, the window method prompt() will return the entered value from the text box. If the user clicks the Cancel button, the window method prompt() returns null." }, { "code": null, "e": 33816, "s": 33806, "text": "Example :" }, { "code": null, "e": 33827, "s": 33816, "text": "JavaScript" }, { "code": "<!DOCTYPE html><html> <head> <script type=\"text/javascript\"> function Value(){ var Val = prompt(\"Enter your name : \", \"name\"); document.write(\"You entered : \" + Val); } </script> </head> <body> <p>Click me: </p> <form> <input type=\"button\" value=\"Click Me\" onclick=\"Value();\" /> </form> </body></html>", "e": 34276, "s": 33827, "text": null }, { "code": null, "e": 34285, "s": 34276, "text": "Output :" }, { "code": null, "e": 34295, "s": 34285, "text": "Example :" }, { "code": null, "e": 34306, "s": 34295, "text": "JavaScript" }, { "code": "<!DOCTYPE html><html><body> <p>Line-Breaks</p> <button onclick=\"alert('GEEKSFOR\\nGEEKS')\">CLICK ME</button> </body></html>", "e": 34436, "s": 34306, "text": null }, { "code": null, "e": 34445, "s": 34436, "text": "Output :" }, { "code": null, "e": 34456, "s": 34447, "text": "sweetyty" }, { "code": null, "e": 34470, "s": 34456, "text": "manasborse123" }, { "code": null, "e": 34486, "s": 34470, "text": "javascript-form" }, { "code": null, "e": 34491, "s": 34486, "text": "HTML" }, { "code": null, "e": 34502, "s": 34491, "text": "JavaScript" }, { "code": null, "e": 34519, "s": 34502, "text": "Web Technologies" }, { "code": null, "e": 34524, "s": 34519, "text": "HTML" }, { "code": null, "e": 34622, "s": 34524, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34672, "s": 34622, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 34734, "s": 34672, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 34782, "s": 34734, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 34842, "s": 34782, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 34895, "s": 34842, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 34935, "s": 34895, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 34980, "s": 34935, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 35041, "s": 34980, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 35110, "s": 35041, "text": "How to calculate the number of days between two dates in javascript?" } ]
How can a String be validated (for alphabets) in java?
To validate a string for alphabets you can either compare each character in the String with the characters in the English alphabet (both cases) or, use regular expressions. The following program accepts a string value (name) from the user and finds out whether given string is a proper name by comparing each character in it with the characters in the English alphabet. Live Demo import java.util.Scanner; public class ValidatingString { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter your name: "); String str = sc.next(); boolean flag = true; for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if (!(ch >= 'a' && ch <= 'z'|| ch >= 'A' && ch <= 'Z')) { flag = false; } } if(flag) System.out.println("Given string is a proper name."); else System.out.println("Given string is a proper string is not a proper name."); } } Enter your name: krishna45 Given string is a proper string is not a proper name. Enter your name: kasyap Given string is a proper name. The following program accepts a string value (name) from the user and finds out whether the given string is a proper name, using a regular expression. Live Demo import java.util.Scanner; public class ValidatingString2 { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter your name: "); String str = sc.next(); if((!str.equals(null))&&str.matches("^[a-zA-Z]*$")) System.out.println("Given string is a proper name."); else System.out.println("Given string is a proper string is not a proper name."); } } Enter your name: krishna45 Given string is a proper string is not a proper name. Enter your name: kasyap Given string is a proper name.
[ { "code": null, "e": 1235, "s": 1062, "text": "To validate a string for alphabets you can either compare each character in the String with the characters in the English alphabet (both cases) or, use regular expressions." }, { "code": null, "e": 1432, "s": 1235, "text": "The following program accepts a string value (name) from the user and finds out whether given string is a proper name by comparing each character in it with the characters in the English alphabet." }, { "code": null, "e": 1443, "s": 1432, "text": " Live Demo" }, { "code": null, "e": 2067, "s": 1443, "text": "import java.util.Scanner;\npublic class ValidatingString {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter your name: \");\n String str = sc.next();\n boolean flag = true;\n for (int i = 0; i < str.length(); i++) {\n char ch = str.charAt(i);\n if (!(ch >= 'a' && ch <= 'z'|| ch >= 'A' && ch <= 'Z')) {\n flag = false;\n }\n }\n if(flag)\n System.out.println(\"Given string is a proper name.\");\n else\n System.out.println(\"Given string is a proper string is not a proper name.\");\n }\n}" }, { "code": null, "e": 2148, "s": 2067, "text": "Enter your name:\nkrishna45\nGiven string is a proper string is not a proper name." }, { "code": null, "e": 2203, "s": 2148, "text": "Enter your name:\nkasyap\nGiven string is a proper name." }, { "code": null, "e": 2354, "s": 2203, "text": "The following program accepts a string value (name) from the user and finds out whether the given string is a proper name, using a regular expression." }, { "code": null, "e": 2365, "s": 2354, "text": " Live Demo" }, { "code": null, "e": 2813, "s": 2365, "text": "import java.util.Scanner;\npublic class ValidatingString2 {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter your name: \");\n String str = sc.next();\n if((!str.equals(null))&&str.matches(\"^[a-zA-Z]*$\"))\n System.out.println(\"Given string is a proper name.\");\n else\n System.out.println(\"Given string is a proper string is not a proper name.\");\n }\n}" }, { "code": null, "e": 2894, "s": 2813, "text": "Enter your name:\nkrishna45\nGiven string is a proper string is not a proper name." }, { "code": null, "e": 2949, "s": 2894, "text": "Enter your name:\nkasyap\nGiven string is a proper name." } ]
Selenium Webdriver - Identify Single Element
Once we navigate to a webpage, we have to interact with the web elements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case. For this, our first job is to identify the element. We can use the id attribute for an element for its identification and utilize the method find_element_by_id. With this, the first element with the matching value of the attribute id is returned. In case there is no element with the matching value of the id attribute, NoSuchElementException shall be thrown. The syntax for identifying an element is as follows − driver.find_element_by_id("value of id attribute") Let us see the html code of a web element − The edit box highlighted in the above image has an id attribute with value gsc-i-id1. Let us try to input some text into this edit box after identifying it. The code implementation of identifying a web element is as follows − from selenium import webdriver #set chromedriver.exe path driver = webdriver.Chrome(executable_path='../drivers/chromedriver') #url launch driver.get("https://www.tutorialspoint.com/index.htm") #identify edit box with id l = driver.find_element_by_id('gsc-i-id1') #input text l.send_keys('Selenium') #obtain value entered v = l.get_attribute('value') print('Value entered: ' + v) #driver quit driver.quit() The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the value entered within the edit box (obtained from the get_attribute method) - Selenium gets printed in the console. Once we navigate to a webpage, we have to interact with the web elements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case. For this, our first job is to identify the element. We can use the name attribute for an element for its identification and utilize the method find_element_by_name. With this, the first element with the matching value of the attribute name is returned. In case there is no element with the matching value of the name attribute, NoSuchElementException shall be thrown. The syntax for identifying single element by name is as follows: driver.find_element_by_name("value of name attribute") Let us see the html code of a web element as given below − The edit box highlighted in the above image has a name attribute with value search. Let us try to input some text into this edit box after identifying it. The code implementation of identifying single element by name is as follows − from selenium import webdriver #set chromedriver.exe path driver = webdriver.Chrome(executable_path='../drivers/chromedriver') #url launch driver.get("https://www.tutorialspoint.com/index.htm") #identify edit box with name l = driver.find_element_by_name('search') #input text l.send_keys('Selenium Java') #obtain value entered v = l.get_attribute('value') print('Value entered: ' + v) #driver close driver.close() The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the value entered within the edit box (obtained from the get_attribute method) - Selenium Java gets printed in the console. Once we navigate to a webpage, we have to interact with the web elements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case. For this, our first job is to identify the element. We can use the class attribute for an element for its identification and utilise the method find_element_by_class_name. With this, the first element with the matching value of the attribute class is returned. In case there is no element with the matching value of the class attribute, NoSuchElementException shall be thrown. The syntax for identifying single element by Classname is as follows : driver.find_element_by_class_name("value of class attribute") Let us see the html code of a web element as given below − The web element highlighted in the above image has a class attribute with value heading. Let us try to obtain the text of that element after identifying it. The code implementation of identifying single element by Classname is as follows − from selenium import webdriver #set chromedriver.exe path driver = webdriver.Chrome(executable_path='../drivers/chromedriver') #url launch driver.get("https://www.tutorialspoint.com/about/about_careers.htm") #identify edit box with class l = driver.find_element_by_class_name('heading') #identify text v = l.text #text obtained print('Text is: ' + v) #driver close driver.close() The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the text of the webelement (obtained from the text method) - About Tutorialspoint gets printed in the console. Once we navigate to a webpage, we have to interact with the webelements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case. For this, our first job is to identify the element. We can use the tagname for an element for its identification and utilise the method find_element_by_tag_name. With this, the first element with the matching tagname is returned. In case there is no element with the matching tagname, NoSuchElementException shall be thrown. The syntax for identifying single element by Tagname is as follows: driver.find_element_by_tag_name("tagname of element") Let us see the html code of a web element as given below − The edit box highlighted in the above image has a tagname - input. Let us try to input some text into this edit box after identifying it. The code implementation of identifying single element by Tagname is as follows − from selenium import webdriver #set chromedriver.exe path driver = webdriver.Chrome(executable_path='../drivers/chromedriver') #url launch driver.get("https://www.tutorialspoint.com/index.htm") #identify edit box with tagname l = driver.find_element_by_tag_name('input') #input text l.send_keys('Selenium Python') #obtain value entered v = l.get_attribute('value') print('Value entered: ' + v) #driver close driver.close() The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the value entered within the edit box (obtained from the get_attribute method) - Selenium Python gets printed in the console. Once we navigate to a webpage, we may interact with a webelement by clicking a link to complete our automation test case. The link text is used for an element having the anchor tag. For this, our first job is to identify the element. We can use the link text attribute for an element for its identification and utilize the method find_element_by_link_text. With this, the first element with the matching value of the given link text is returned. In case there is no element with the matching value of the link text, NoSuchElementException shall be thrown. The syntax for identifying single element by Link Text is as follows: driver.find_element_by_link_text("value of link text") Let us see the html code of a web element as given below − The link highlighted in the above image has a tagname - a and the link text - Privacy Policy. Let us try to click on this link after identifying it. The code implementation of identifying single element by Link Text is as follows − from selenium import webdriver driver = webdriver.Chrome(executable_path='../drivers/chromedriver') #url launch driver.get("https://www.tutorialspoint.com/about/about_careers.htm") #identify link with link text l = driver.find_element_by_link_text('Privacy Policy') #perform click l.click() print('Page navigated after click: ' + driver.title) #driver quit driver.quit() The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the page title of the application (obtained from the driver.title method) - About Privacy Policy at Tutorials Point - Tutorialspoint gets printed in the console. Once we navigate to a webpage, we may interact with a web element by clicking a link to complete our automation test case. The partial link text is used for an element having the anchor tag. For this, our first job is to identify the element. We can use the partial link text attribute for an element for its identification and utilize the method find_element_by_partial_link_text. With this, the first element with the matching value of the given partial link text is returned. In case there is no element with the matching value of the partial link text, NoSuchElementException shall be thrown. The syntax for identifying single element by Partial Link Text is as follows − driver.find_element_by_partial_link_text("value of partial ink text") Let us see the html code of a web element as given below − The link highlighted in the above image has a tagname - a and the partial link text - Refund. Let us try to click on this link after identifying it. The code implementation for identifying single element by Partial Link Text is as follows − from selenium import webdriver driver = webdriver.Chrome(executable_path='../drivers/chromedriver') #url launch driver.get("https://www.tutorialspoint.com/about/about_careers.htm") #identify link with partial link text l = driver.find_element_by_partial_link_text('Refund') #perform click l.click() print('Page navigated after click: ' + driver.title) #driver quit driver.quit() The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the page title of the application (obtained from the driver.title method) - Return, Refund & Cancellation Policy - Tutorialspoint gets printed in the console. Once we navigate to a webpage, we have to interact with the webelements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case. For this, our first job is to identify the element. We can create a css selector for an element for its identification and use the method find_element_by_css_selector. With this, the first element with the matching value of the given css is returned. In case there is no element with the matching value of the css, NoSuchElementException shall be thrown. The syntax for identifying single element by CSS Selector is as follows − driver.find_element_by_css_selector("value of css") The rules to create a css expression are discussed below To identify the element with css, the expression should be tagname[attribute='value']. We can also specifically use the id attribute to create a css expression. To identify the element with css, the expression should be tagname[attribute='value']. We can also specifically use the id attribute to create a css expression. With id, the format of a css expression should be tagname#id. For example, input#txt [here input is the tagname and the txt is the value of the id attribute]. With id, the format of a css expression should be tagname#id. For example, input#txt [here input is the tagname and the txt is the value of the id attribute]. With class, the format of css expression should be tagname.class. For example, input.cls-txt [here input is the tagname and the cls-txt is the value of the class attribute]. With class, the format of css expression should be tagname.class. For example, input.cls-txt [here input is the tagname and the cls-txt is the value of the class attribute]. If there are n children of a parent element, and we want to identify the nth child, the css expression should have nth-of –type(n). If there are n children of a parent element, and we want to identify the nth child, the css expression should have nth-of –type(n). In the above code, if we want to identify the fourth li childof ul[Questions and Answers], the css expression should be ul.reading li:nth-of-type(4). Similarly, to identify the last child, the css expression should be ul.reading li:last-child. For attributes whose values are dynamically changing, we can use ^= to locate an element whose attribute value starts with a particular text. For example, input[name^='qa'] Here, input is the tagname and the value of the name attribute starts with qa. For attributes whose values are dynamically changing, we can use $ = to locate an element whose attribute value ends with a particular text. For example, input[class $ ='txt'] Here, input is the tagname and the value of the class attribute ends with txt. For attributes whose values are dynamically changing, we can use *= to locate an element whose attribute value contains a specific sub-text. For example, input[name*='nam'] Here, input is the tagname and the value of the name attribute contains the sub-text nam. Let us see the html code of a web element as given below − The edit box highlighted in the above image has a name attribute with value search, the css expression should be input[name='search']. Let us try to input some text into this edit box after identifying it. The code implementation of identifying single element by CSS Selector is as follows − from selenium import webdriver driver = webdriver.Chrome(executable_path='../drivers/chromedriver') #implicit wait time driver.implicitly_wait(5) #url launch driver.get("https://www.tutorialspoint.com/index.htm") #identify element with css l = driver.find_element_by_css_selector("input[name='search']") l.send_keys('Selenium Python') v = l.get_attribute('value') print('Value entered is: ' + v) #driver quit driver.quit() The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the value entered within the edit box (obtained from the get_attribute method) - Selenium Python gets printed in the console. Once we navigate to a webpage, we have to interact with the webelements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case. For this, our first job is to identify the element. We can create an xpath for an element for its identification and use the method find_element_by_xpath. With this, the first element with the matching value of the given xpath is returned. In case there is no element with the matching value of the xpath, NoSuchElementException shall be thrown. The syntax for identifying single element by Xpath is as follows − driver.find_element_by_xpath("value of xpath") The rules to create a xpath expression are discussed below − To identify the element with xpath, the expression should be //tagname[@attribute='value']. There can be two types of xpath – relative and absolute. The absolute xpath begins with / symbol and starts from the root node upto the element that we want to identify. To identify the element with xpath, the expression should be //tagname[@attribute='value']. There can be two types of xpath – relative and absolute. The absolute xpath begins with / symbol and starts from the root node upto the element that we want to identify. For example, /html/body/div[1]/div/div[1]/a The relative xpath begins with // symbol and does not start from the root node. The relative xpath begins with // symbol and does not start from the root node. For example, //img[@alt='tutorialspoint'] Let us see the html code of the highlighted link - Home starting from the root. The absolute xpath for this element can be as follows − /html/body/div[1]/div/div[1]/a. The relative xpath for element Home can be as follows − //a[@title='TutorialsPoint - Home']. There are also functions available which help to frame relative xpath expressions. text() It is used to identify an element with its visible text on the page. The xpath expression is as follows − //*[text()='Home']. starts-with It is used to identify an element whose attribute value begins with a specific text. This function is normally used for attributes whose value changes on each page load. Let us see the html of the link Q/A − The xpath expression should be as follows: //a[starts-with(@title, 'Questions &')]. contains() It identifies an element whose attribute value contains a sub-text. This function is normally used for attributes whose value changes on each page load. The xpath expression is as follows − //a[contains(@title, 'Questions & Answers')]. Let us see the html code of a webelement as shown below − The edit box highlighted in the above image has a name attribute with value search, the xpath expression should be //input[@name='search']. Let us try to input some text into this edit box after identifying it. The code implementation of identifying single element by XPath is as follows − from selenium import webdriver driver = webdriver.Chrome(executable_path='../drivers/chromedriver') #implicit wait time driver.implicitly_wait(5) #url launch driver.get("https://www.tutorialspoint.com/index.htm") #identify element with xpath l = driver.find_element_by_xpath("//input[@name='search']") l.send_keys('Selenium Python') v = l.get_attribute('value') print('Value entered is: ' + v) #driver quit driver.quit() The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the value entered within the edit box (obtained from the get_attribute method) - Selenium Python gets printed in the console. 46 Lectures 5.5 hours Aditya Dua 296 Lectures 146 hours Arun Motoori 411 Lectures 38.5 hours In28Minutes Official 22 Lectures 7 hours Arun Motoori 118 Lectures 17 hours Arun Motoori 278 Lectures 38.5 hours Lets Kode It Print Add Notes Bookmark this page
[ { "code": null, "e": 2409, "s": 2203, "text": "Once we navigate to a webpage, we have to interact with the web elements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case." }, { "code": null, "e": 2656, "s": 2409, "text": "For this, our first job is to identify the element. We can use the id attribute for an element for its identification and utilize the method find_element_by_id. With this, the first element with the matching value of the attribute id is returned." }, { "code": null, "e": 2769, "s": 2656, "text": "In case there is no element with the matching value of the id attribute, NoSuchElementException shall be thrown." }, { "code": null, "e": 2823, "s": 2769, "text": "The syntax for identifying an element is as follows −" }, { "code": null, "e": 2875, "s": 2823, "text": "driver.find_element_by_id(\"value of id attribute\")\n" }, { "code": null, "e": 2919, "s": 2875, "text": "Let us see the html code of a web element −" }, { "code": null, "e": 3076, "s": 2919, "text": "The edit box highlighted in the above image has an id attribute with value gsc-i-id1. Let us try to input some text into this edit box after identifying it." }, { "code": null, "e": 3145, "s": 3076, "text": "The code implementation of identifying a web element is as follows −" }, { "code": null, "e": 3552, "s": 3145, "text": "from selenium import webdriver\n#set chromedriver.exe path\ndriver = webdriver.Chrome(executable_path='../drivers/chromedriver')\n#url launch\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n#identify edit box with id\nl = driver.find_element_by_id('gsc-i-id1')\n#input text\nl.send_keys('Selenium')\n#obtain value entered\nv = l.get_attribute('value')\nprint('Value entered: ' + v)\n#driver quit\ndriver.quit()" }, { "code": null, "e": 3791, "s": 3552, "text": "The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the value entered within the edit box (obtained from the get_attribute method) - Selenium gets printed in the console." }, { "code": null, "e": 3997, "s": 3791, "text": "Once we navigate to a webpage, we have to interact with the web elements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case." }, { "code": null, "e": 4250, "s": 3997, "text": "For this, our first job is to identify the element. We can use the name attribute for an element for its identification and utilize the method find_element_by_name. With this, the first element with the matching value of the attribute name is returned." }, { "code": null, "e": 4365, "s": 4250, "text": "In case there is no element with the matching value of the name attribute, NoSuchElementException shall be thrown." }, { "code": null, "e": 4430, "s": 4365, "text": "The syntax for identifying single element by name is as follows:" }, { "code": null, "e": 4486, "s": 4430, "text": "driver.find_element_by_name(\"value of name attribute\")\n" }, { "code": null, "e": 4545, "s": 4486, "text": "Let us see the html code of a web element as given below −" }, { "code": null, "e": 4700, "s": 4545, "text": "The edit box highlighted in the above image has a name attribute with value search. Let us try to input some text into this edit box after identifying it." }, { "code": null, "e": 4778, "s": 4700, "text": "The code implementation of identifying single element by name is as follows −" }, { "code": null, "e": 5193, "s": 4778, "text": "from selenium import webdriver\n#set chromedriver.exe path\ndriver = webdriver.Chrome(executable_path='../drivers/chromedriver')\n#url launch\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n#identify edit box with name\nl = driver.find_element_by_name('search')\n#input text\nl.send_keys('Selenium Java')\n#obtain value entered\nv = l.get_attribute('value')\nprint('Value entered: ' + v)\n#driver close\ndriver.close()" }, { "code": null, "e": 5437, "s": 5193, "text": "The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the value entered within the edit box (obtained from the get_attribute method) - Selenium Java gets printed in the console." }, { "code": null, "e": 5643, "s": 5437, "text": "Once we navigate to a webpage, we have to interact with the web elements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case." }, { "code": null, "e": 5904, "s": 5643, "text": "For this, our first job is to identify the element. We can use the class attribute for an element for its identification and utilise the method find_element_by_class_name. With this, the first element with the matching value of the attribute class is returned." }, { "code": null, "e": 6020, "s": 5904, "text": "In case there is no element with the matching value of the class attribute, NoSuchElementException shall be thrown." }, { "code": null, "e": 6091, "s": 6020, "text": "The syntax for identifying single element by Classname is as follows :" }, { "code": null, "e": 6154, "s": 6091, "text": "driver.find_element_by_class_name(\"value of class attribute\")\n" }, { "code": null, "e": 6213, "s": 6154, "text": "Let us see the html code of a web element as given below −" }, { "code": null, "e": 6370, "s": 6213, "text": "The web element highlighted in the above image has a class attribute with value heading. Let us try to obtain the text of that element after identifying it." }, { "code": null, "e": 6453, "s": 6370, "text": "The code implementation of identifying single element by Classname is as follows −" }, { "code": null, "e": 6833, "s": 6453, "text": "from selenium import webdriver\n#set chromedriver.exe path\ndriver = webdriver.Chrome(executable_path='../drivers/chromedriver')\n#url launch\ndriver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\")\n#identify edit box with class\nl = driver.find_element_by_class_name('heading')\n#identify text\nv = l.text\n#text obtained\nprint('Text is: ' + v)\n#driver close\ndriver.close()" }, { "code": null, "e": 7064, "s": 6833, "text": "The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the text of the webelement (obtained from the text method) - About Tutorialspoint gets printed in the console." }, { "code": null, "e": 7269, "s": 7064, "text": "Once we navigate to a webpage, we have to interact with the webelements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case." }, { "code": null, "e": 7499, "s": 7269, "text": "For this, our first job is to identify the element. We can use the tagname for an element for its identification and utilise the method find_element_by_tag_name. With this, the first element with the matching tagname is returned." }, { "code": null, "e": 7594, "s": 7499, "text": "In case there is no element with the matching tagname, NoSuchElementException shall be thrown." }, { "code": null, "e": 7662, "s": 7594, "text": "The syntax for identifying single element by Tagname is as follows:" }, { "code": null, "e": 7717, "s": 7662, "text": "driver.find_element_by_tag_name(\"tagname of element\")\n" }, { "code": null, "e": 7776, "s": 7717, "text": "Let us see the html code of a web element as given below −" }, { "code": null, "e": 7914, "s": 7776, "text": "The edit box highlighted in the above image has a tagname - input. Let us try to input some text into this edit box after identifying it." }, { "code": null, "e": 7995, "s": 7914, "text": "The code implementation of identifying single element by Tagname is as follows −" }, { "code": null, "e": 8418, "s": 7995, "text": "from selenium import webdriver\n#set chromedriver.exe path\ndriver = webdriver.Chrome(executable_path='../drivers/chromedriver')\n#url launch\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n#identify edit box with tagname\nl = driver.find_element_by_tag_name('input')\n#input text\nl.send_keys('Selenium Python')\n#obtain value entered\nv = l.get_attribute('value')\nprint('Value entered: ' + v)\n#driver close\ndriver.close()" }, { "code": null, "e": 8664, "s": 8418, "text": "The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the value entered within the edit box (obtained from the get_attribute method) - Selenium Python gets printed in the console." }, { "code": null, "e": 8846, "s": 8664, "text": "Once we navigate to a webpage, we may interact with a webelement by clicking a link to complete our automation test case. The link text is used for an element having the anchor tag." }, { "code": null, "e": 9110, "s": 8846, "text": "For this, our first job is to identify the element. We can use the link text attribute for an element for its identification and utilize the method find_element_by_link_text. With this, the first element with the matching value of the given link text is returned." }, { "code": null, "e": 9220, "s": 9110, "text": "In case there is no element with the matching value of the link text, NoSuchElementException shall be thrown." }, { "code": null, "e": 9290, "s": 9220, "text": "The syntax for identifying single element by Link Text is as follows:" }, { "code": null, "e": 9346, "s": 9290, "text": "driver.find_element_by_link_text(\"value of link text\")\n" }, { "code": null, "e": 9405, "s": 9346, "text": "Let us see the html code of a web element as given below −" }, { "code": null, "e": 9554, "s": 9405, "text": "The link highlighted in the above image has a tagname - a and the link text - Privacy Policy. Let us try to click on this link after identifying it." }, { "code": null, "e": 9637, "s": 9554, "text": "The code implementation of identifying single element by Link Text is as follows −" }, { "code": null, "e": 10008, "s": 9637, "text": "from selenium import webdriver\ndriver = webdriver.Chrome(executable_path='../drivers/chromedriver')\n#url launch\ndriver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\")\n#identify link with link text\nl = driver.find_element_by_link_text('Privacy Policy')\n#perform click\nl.click()\nprint('Page navigated after click: ' + driver.title)\n#driver quit\ndriver.quit()" }, { "code": null, "e": 10290, "s": 10008, "text": "The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the page title of the application (obtained from the driver.title method) - About Privacy Policy at Tutorials Point - Tutorialspoint gets printed in the console." }, { "code": null, "e": 10481, "s": 10290, "text": "Once we navigate to a webpage, we may interact with a web element by clicking a link to complete our automation test case. The partial link text is used for an element having the anchor tag." }, { "code": null, "e": 10769, "s": 10481, "text": "For this, our first job is to identify the element. We can use the partial link text attribute for an element for its identification and utilize the method find_element_by_partial_link_text. With this, the first element with the matching value of the given partial link text is returned." }, { "code": null, "e": 10887, "s": 10769, "text": "In case there is no element with the matching value of the partial link text, NoSuchElementException shall be thrown." }, { "code": null, "e": 10966, "s": 10887, "text": "The syntax for identifying single element by Partial Link Text is as follows −" }, { "code": null, "e": 11037, "s": 10966, "text": "driver.find_element_by_partial_link_text(\"value of partial ink text\")\n" }, { "code": null, "e": 11096, "s": 11037, "text": "Let us see the html code of a web element as given below −" }, { "code": null, "e": 11245, "s": 11096, "text": "The link highlighted in the above image has a tagname - a and the partial link text - Refund. Let us try to click on this link after identifying it." }, { "code": null, "e": 11337, "s": 11245, "text": "The code implementation for identifying single element by Partial Link Text is as follows −" }, { "code": null, "e": 11716, "s": 11337, "text": "from selenium import webdriver\ndriver = webdriver.Chrome(executable_path='../drivers/chromedriver')\n#url launch\ndriver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\")\n#identify link with partial link text\nl = driver.find_element_by_partial_link_text('Refund')\n#perform click\nl.click()\nprint('Page navigated after click: ' + driver.title)\n#driver quit\ndriver.quit()" }, { "code": null, "e": 11995, "s": 11716, "text": "The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the page title of the application (obtained from the driver.title method) - Return, Refund & Cancellation Policy - Tutorialspoint gets printed in the console." }, { "code": null, "e": 12200, "s": 11995, "text": "Once we navigate to a webpage, we have to interact with the webelements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case." }, { "code": null, "e": 12451, "s": 12200, "text": "For this, our first job is to identify the element. We can create a css selector for an element for its identification and use the method find_element_by_css_selector. With this, the first element with the matching value of the given css is returned." }, { "code": null, "e": 12555, "s": 12451, "text": "In case there is no element with the matching value of the css, NoSuchElementException shall be thrown." }, { "code": null, "e": 12629, "s": 12555, "text": "The syntax for identifying single element by CSS Selector is as follows −" }, { "code": null, "e": 12682, "s": 12629, "text": "driver.find_element_by_css_selector(\"value of css\")\n" }, { "code": null, "e": 12739, "s": 12682, "text": "The rules to create a css expression are discussed below" }, { "code": null, "e": 12900, "s": 12739, "text": "To identify the element with css, the expression should be tagname[attribute='value']. We can also specifically use the id attribute to create a css expression." }, { "code": null, "e": 13061, "s": 12900, "text": "To identify the element with css, the expression should be tagname[attribute='value']. We can also specifically use the id attribute to create a css expression." }, { "code": null, "e": 13220, "s": 13061, "text": "With id, the format of a css expression should be tagname#id. For example, input#txt [here input is the tagname and the txt is the value of the id attribute]." }, { "code": null, "e": 13379, "s": 13220, "text": "With id, the format of a css expression should be tagname#id. For example, input#txt [here input is the tagname and the txt is the value of the id attribute]." }, { "code": null, "e": 13553, "s": 13379, "text": "With class, the format of css expression should be tagname.class. For example, input.cls-txt [here input is the tagname and the cls-txt is the value of the class attribute]." }, { "code": null, "e": 13727, "s": 13553, "text": "With class, the format of css expression should be tagname.class. For example, input.cls-txt [here input is the tagname and the cls-txt is the value of the class attribute]." }, { "code": null, "e": 13859, "s": 13727, "text": "If there are n children of a parent element, and we want to identify the nth child, the css expression should have nth-of –type(n)." }, { "code": null, "e": 13991, "s": 13859, "text": "If there are n children of a parent element, and we want to identify the nth child, the css expression should have nth-of –type(n)." }, { "code": null, "e": 14235, "s": 13991, "text": "In the above code, if we want to identify the fourth li childof ul[Questions and Answers], the css expression should be ul.reading li:nth-of-type(4). Similarly, to identify the last child, the css expression should be ul.reading li:last-child." }, { "code": null, "e": 14487, "s": 14235, "text": "For attributes whose values are dynamically changing, we can use ^= to locate an element whose attribute value starts with a particular text. For example, input[name^='qa'] Here, input is the tagname and the value of the name attribute starts with qa." }, { "code": null, "e": 14742, "s": 14487, "text": "For attributes whose values are dynamically changing, we can use $ = to locate an element whose attribute value ends with a particular text. For example, input[class $ ='txt'] Here, input is the tagname and the value of the class attribute ends with txt." }, { "code": null, "e": 15005, "s": 14742, "text": "For attributes whose values are dynamically changing, we can use *= to locate an element whose attribute value contains a specific sub-text. For example, input[name*='nam'] Here, input is the tagname and the value of the name attribute contains the sub-text nam." }, { "code": null, "e": 15064, "s": 15005, "text": "Let us see the html code of a web element as given below −" }, { "code": null, "e": 15270, "s": 15064, "text": "The edit box highlighted in the above image has a name attribute with value search, the css expression should be input[name='search']. Let us try to input some text into this edit box after identifying it." }, { "code": null, "e": 15356, "s": 15270, "text": "The code implementation of identifying single element by CSS Selector is as follows −" }, { "code": null, "e": 15779, "s": 15356, "text": "from selenium import webdriver\ndriver = webdriver.Chrome(executable_path='../drivers/chromedriver')\n#implicit wait time\ndriver.implicitly_wait(5)\n#url launch\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n#identify element with css\nl = driver.find_element_by_css_selector(\"input[name='search']\")\nl.send_keys('Selenium Python')\nv = l.get_attribute('value')\nprint('Value entered is: ' + v)\n#driver quit\ndriver.quit()" }, { "code": null, "e": 16025, "s": 15779, "text": "The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the value entered within the edit box (obtained from the get_attribute method) - Selenium Python gets printed in the console." }, { "code": null, "e": 16230, "s": 16025, "text": "Once we navigate to a webpage, we have to interact with the webelements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case." }, { "code": null, "e": 16470, "s": 16230, "text": "For this, our first job is to identify the element. We can create an xpath for an element for its identification and use the method find_element_by_xpath. With this, the first element with the matching value of the given xpath is returned." }, { "code": null, "e": 16576, "s": 16470, "text": "In case there is no element with the matching value of the xpath, NoSuchElementException shall be thrown." }, { "code": null, "e": 16643, "s": 16576, "text": "The syntax for identifying single element by Xpath is as follows −" }, { "code": null, "e": 16691, "s": 16643, "text": "driver.find_element_by_xpath(\"value of xpath\")\n" }, { "code": null, "e": 16752, "s": 16691, "text": "The rules to create a xpath expression are discussed below −" }, { "code": null, "e": 17014, "s": 16752, "text": "To identify the element with xpath, the expression should be //tagname[@attribute='value']. There can be two types of xpath – relative and absolute. The absolute xpath begins with / symbol and starts from the root node upto the element that we want to identify." }, { "code": null, "e": 17276, "s": 17014, "text": "To identify the element with xpath, the expression should be //tagname[@attribute='value']. There can be two types of xpath – relative and absolute. The absolute xpath begins with / symbol and starts from the root node upto the element that we want to identify." }, { "code": null, "e": 17289, "s": 17276, "text": "For example," }, { "code": null, "e": 17321, "s": 17289, "text": "/html/body/div[1]/div/div[1]/a\n" }, { "code": null, "e": 17401, "s": 17321, "text": "The relative xpath begins with // symbol and does not start from the root node." }, { "code": null, "e": 17481, "s": 17401, "text": "The relative xpath begins with // symbol and does not start from the root node." }, { "code": null, "e": 17494, "s": 17481, "text": "For example," }, { "code": null, "e": 17524, "s": 17494, "text": "//img[@alt='tutorialspoint']\n" }, { "code": null, "e": 17604, "s": 17524, "text": "Let us see the html code of the highlighted link - Home starting from the root." }, { "code": null, "e": 17660, "s": 17604, "text": "The absolute xpath for this element can be as follows −" }, { "code": null, "e": 17693, "s": 17660, "text": "/html/body/div[1]/div/div[1]/a.\n" }, { "code": null, "e": 17749, "s": 17693, "text": "The relative xpath for element Home can be as follows −" }, { "code": null, "e": 17787, "s": 17749, "text": "//a[@title='TutorialsPoint - Home'].\n" }, { "code": null, "e": 17870, "s": 17787, "text": "There are also functions available which help to frame relative xpath expressions." }, { "code": null, "e": 17877, "s": 17870, "text": "text()" }, { "code": null, "e": 17983, "s": 17877, "text": "It is used to identify an element with its visible text on the page. The xpath expression is as follows −" }, { "code": null, "e": 18004, "s": 17983, "text": "//*[text()='Home'].\n" }, { "code": null, "e": 18016, "s": 18004, "text": "starts-with" }, { "code": null, "e": 18186, "s": 18016, "text": "It is used to identify an element whose attribute value begins with a specific text. This function is normally used for attributes whose value changes on each page load." }, { "code": null, "e": 18224, "s": 18186, "text": "Let us see the html of the link Q/A −" }, { "code": null, "e": 18267, "s": 18224, "text": "The xpath expression should be as follows:" }, { "code": null, "e": 18309, "s": 18267, "text": "//a[starts-with(@title, 'Questions &')].\n" }, { "code": null, "e": 18320, "s": 18309, "text": "contains()" }, { "code": null, "e": 18473, "s": 18320, "text": "It identifies an element whose attribute value contains a sub-text. This function is normally used for attributes whose value changes on each page load." }, { "code": null, "e": 18510, "s": 18473, "text": "The xpath expression is as follows −" }, { "code": null, "e": 18557, "s": 18510, "text": "//a[contains(@title, 'Questions & Answers')].\n" }, { "code": null, "e": 18615, "s": 18557, "text": "Let us see the html code of a webelement as shown below −" }, { "code": null, "e": 18826, "s": 18615, "text": "The edit box highlighted in the above image has a name attribute with value search, the xpath expression should be //input[@name='search']. Let us try to input some text into this edit box after identifying it." }, { "code": null, "e": 18905, "s": 18826, "text": "The code implementation of identifying single element by XPath is as follows −" }, { "code": null, "e": 19326, "s": 18905, "text": "from selenium import webdriver\ndriver = webdriver.Chrome(executable_path='../drivers/chromedriver')\n#implicit wait time\ndriver.implicitly_wait(5)\n#url launch\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n#identify element with xpath\nl = driver.find_element_by_xpath(\"//input[@name='search']\")\nl.send_keys('Selenium Python')\nv = l.get_attribute('value')\nprint('Value entered is: ' + v)\n#driver quit\ndriver.quit()" }, { "code": null, "e": 19572, "s": 19326, "text": "The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the value entered within the edit box (obtained from the get_attribute method) - Selenium Python gets printed in the console." }, { "code": null, "e": 19607, "s": 19572, "text": "\n 46 Lectures \n 5.5 hours \n" }, { "code": null, "e": 19619, "s": 19607, "text": " Aditya Dua" }, { "code": null, "e": 19655, "s": 19619, "text": "\n 296 Lectures \n 146 hours \n" }, { "code": null, "e": 19669, "s": 19655, "text": " Arun Motoori" }, { "code": null, "e": 19706, "s": 19669, "text": "\n 411 Lectures \n 38.5 hours \n" }, { "code": null, "e": 19728, "s": 19706, "text": " In28Minutes Official" }, { "code": null, "e": 19761, "s": 19728, "text": "\n 22 Lectures \n 7 hours \n" }, { "code": null, "e": 19775, "s": 19761, "text": " Arun Motoori" }, { "code": null, "e": 19810, "s": 19775, "text": "\n 118 Lectures \n 17 hours \n" }, { "code": null, "e": 19824, "s": 19810, "text": " Arun Motoori" }, { "code": null, "e": 19861, "s": 19824, "text": "\n 278 Lectures \n 38.5 hours \n" }, { "code": null, "e": 19875, "s": 19861, "text": " Lets Kode It" }, { "code": null, "e": 19882, "s": 19875, "text": " Print" }, { "code": null, "e": 19893, "s": 19882, "text": " Add Notes" } ]
How to get the position of the current frame in OpenCV using C++?
The current frame means that you are playing a video and the frame shown now is the current frame. It is also referred to as the active frame. In many application, you can require to get the number of the current frame. The following program reads the position of the current frame and shows it in the console window. #include<opencv2/opencv.hpp>//OpenCV header to use VideoCapture class// #include<iostream> using namespace std; using namespace cv; int main() { Mat myImage;//Declaring a matrix to load the frames// namedWindow("Video Player");//Declaring the video to show the video// VideoCapture cap("video.mp4");//Declaring an object to load video from device// if(!cap.isOpened()){ //This section prompt an error message if no video stream is found// cout << "No video stream detected" << endl; system("pause"); return-1; } while (true){ //Taking an everlasting loop to show the video// cap >> myImage; int current_Frame;//Declaring an integer variable to store the position of the current frame// current_Frame = cap.get(CAP_PROP_POS_FRAMES);//Reading the position of current frame// if (myImage.empty()){ //Breaking the loop if no video frame is detected// break; } cout << "Current Frame Number:" << current_Frame << endl; imshow("Video Player", myImage);//Showing the video// char c = (char)waitKey(25);//Allowing 25 milliseconds frame processing time and initiating break condition// if (c == 27){ //If 'Esc' is entered break the loop// break; } } cap.release();//Releasing the buffer memory// return 0; } This program will play the video and show the current frame's position in the console window.
[ { "code": null, "e": 1282, "s": 1062, "text": "The current frame means that you are playing a video and the frame shown now is the current frame. It is also referred to as the active frame. In many application, you can require to get the number of the current frame." }, { "code": null, "e": 1380, "s": 1282, "text": "The following program reads the position of the current frame and shows it in the console window." }, { "code": null, "e": 2704, "s": 1380, "text": "#include<opencv2/opencv.hpp>//OpenCV header to use VideoCapture class//\n#include<iostream>\nusing namespace std;\nusing namespace cv;\nint main() {\n Mat myImage;//Declaring a matrix to load the frames//\n namedWindow(\"Video Player\");//Declaring the video to show the video//\n VideoCapture cap(\"video.mp4\");//Declaring an object to load video from device// \n if(!cap.isOpened()){ //This section prompt an error message if no video stream is found//\n cout << \"No video stream detected\" << endl;\n system(\"pause\");\n return-1;\n }\n while (true){ //Taking an everlasting loop to show the video//\n cap >> myImage;\n int current_Frame;//Declaring an integer variable to store the position of the current frame//\n current_Frame = cap.get(CAP_PROP_POS_FRAMES);//Reading the position of current frame//\n if (myImage.empty()){ //Breaking the loop if no video frame is detected//\n break;\n }\n cout << \"Current Frame Number:\" << current_Frame << endl;\n imshow(\"Video Player\", myImage);//Showing the video//\n char c = (char)waitKey(25);//Allowing 25 milliseconds frame processing time and initiating break condition//\n if (c == 27){ //If 'Esc' is entered break the loop//\n break;\n }\n }\n cap.release();//Releasing the buffer memory//\n return 0;\n}" }, { "code": null, "e": 2798, "s": 2704, "text": "This program will play the video and show the current frame's position in the console window." } ]
Point Processing in Image Processing using Python-OpenCV
10 May, 2020 OpenCV is the huge open-source library for computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems. By using it, one can process images and videos to identify objects, faces, or even the handwriting of a human. All the processing done on the pixel values. Point processing operations take the form – s = T ( r ) Here, T is referred to as a grey level transformation function or a point processing operation, s refers to the processed image pixel value and r refers to the original image pixel value. Image Negative: s = (L-1) – r, where L= number of grey levels Thresholding: s = L-1 for r > threshold s = 0 for r < threshold Grey level slicing with background: s = L-1 for a < r < b, here a and b define some specific range of grey level s = r otherwise. Below is the implementation. Original Input Image : import cv2import numpy as np # Image negativeimg = cv2.imread('food.jpeg',0) # To ascertain total numbers of # rows and columns of the image,# size of the imagem,n = img.shape # To find the maximum grey level# value in the imageL = img.max() # Maximum grey level value minus # the original image gives the# negative imageimg_neg = L-img # convert the np array img_neg to # a png imagecv2.imwrite('Cameraman_Negative.png', img_neg) # Thresholding without background # Let threshold =T# Let pixel value in the original be denoted by r# Let pixel value in the new image be denoted by s# If r<T, s= 0# If r>T, s=255 T = 150 # create a array of zerosimg_thresh = np.zeros((m,n), dtype = int) for i in range(m): for j in range(n): if img[i,j] < T: img_thresh[i,j]= 0 else: img_thresh[i,j] = 255 # Convert array to png imagecv2.imwrite('Cameraman_Thresh.png', img_thresh) # the lower threshold valueT1 = 100 # the upper threshold valueT2 = 180 # create a array of zerosimg_thresh_back = np.zeros((m,n), dtype = int) for i in range(m): for j in range(n): if T1 < img[i,j] < T2: img_thresh_back[i,j]= 255 else: img_thresh_back[i,j] = img[i,j] # Convert array to png imagecv2.imwrite('Cameraman_Thresh_Back.png', img_thresh_back) Output : Image Negative Output : Image with Thresholding : Output : Image with Grey Level Slicing with Background Python-OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 May, 2020" }, { "code": null, "e": 335, "s": 28, "text": "OpenCV is the huge open-source library for computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems. By using it, one can process images and videos to identify objects, faces, or even the handwriting of a human." }, { "code": null, "e": 424, "s": 335, "text": "All the processing done on the pixel values. Point processing operations take the form –" }, { "code": null, "e": 436, "s": 424, "text": "s = T ( r )" }, { "code": null, "e": 624, "s": 436, "text": "Here, T is referred to as a grey level transformation function or a point processing operation, s refers to the processed image pixel value and r refers to the original image pixel value." }, { "code": null, "e": 640, "s": 624, "text": "Image Negative:" }, { "code": null, "e": 686, "s": 640, "text": "s = (L-1) – r, where L= number of grey levels" }, { "code": null, "e": 700, "s": 686, "text": "Thresholding:" }, { "code": null, "e": 750, "s": 700, "text": "s = L-1 for r > threshold\ns = 0 for r < threshold" }, { "code": null, "e": 786, "s": 750, "text": "Grey level slicing with background:" }, { "code": null, "e": 880, "s": 786, "text": "s = L-1 for a < r < b,\nhere a and b define some specific range of grey level\ns = r otherwise." }, { "code": null, "e": 909, "s": 880, "text": "Below is the implementation." }, { "code": null, "e": 932, "s": 909, "text": "Original Input Image :" }, { "code": "import cv2import numpy as np # Image negativeimg = cv2.imread('food.jpeg',0) # To ascertain total numbers of # rows and columns of the image,# size of the imagem,n = img.shape # To find the maximum grey level# value in the imageL = img.max() # Maximum grey level value minus # the original image gives the# negative imageimg_neg = L-img # convert the np array img_neg to # a png imagecv2.imwrite('Cameraman_Negative.png', img_neg) # Thresholding without background # Let threshold =T# Let pixel value in the original be denoted by r# Let pixel value in the new image be denoted by s# If r<T, s= 0# If r>T, s=255 T = 150 # create a array of zerosimg_thresh = np.zeros((m,n), dtype = int) for i in range(m): for j in range(n): if img[i,j] < T: img_thresh[i,j]= 0 else: img_thresh[i,j] = 255 # Convert array to png imagecv2.imwrite('Cameraman_Thresh.png', img_thresh) # the lower threshold valueT1 = 100 # the upper threshold valueT2 = 180 # create a array of zerosimg_thresh_back = np.zeros((m,n), dtype = int) for i in range(m): for j in range(n): if T1 < img[i,j] < T2: img_thresh_back[i,j]= 255 else: img_thresh_back[i,j] = img[i,j] # Convert array to png imagecv2.imwrite('Cameraman_Thresh_Back.png', img_thresh_back)", "e": 2300, "s": 932, "text": null }, { "code": null, "e": 2324, "s": 2300, "text": "Output : Image Negative" }, { "code": null, "e": 2359, "s": 2324, "text": "Output : Image with Thresholding :" }, { "code": null, "e": 2414, "s": 2359, "text": "Output : Image with Grey Level Slicing with Background" }, { "code": null, "e": 2428, "s": 2414, "text": "Python-OpenCV" }, { "code": null, "e": 2435, "s": 2428, "text": "Python" } ]
Java Program for focal length of a spherical mirror
06 Dec, 2018 Focal length is the distance between the center of the mirror to the principal foci. In order to determine the focal length of a spherical mirror we should know the radius of curvature of that mirror. The distance from the vertex to the center of curvature is called radius of curvature. The focal length is half the radius of curvature.Formula : F = ( R / 2 ) for concave mirror F = - ( R / 2 ) for convex mirror Examples : For a convex mirror Input : R = 30 Output : F = 15 For a convex mirror Input : R = 25 Output : F = - 12.5 // Java program to determine// the focal length of a// of a spherical mirrorimport java.util.*;import java.lang.*; public class GfG{ // Determines focal length // of a spherical concave // mirror public static float focal_length_concave(float R) { return R / 2 ; } // Determines focal length of a // spherical convex mirror public static float focal_length_convex(float R) { return - ( R / 2 ) ; } // Driver function public static void main(String argc[]) { float R = 30 ; System.out.print("Focal length of" + "spherical concave"+ "mirror is : "+ focal_length_concave(R) + " units\n"); System.out.println("Focal length of"+ "spherical convex"+ "mirror is : "+ focal_length_convex(R) + " units"); }} /* This code is contributed by Sagar Shukla */ Focal length ofspherical concavemirror is : 15.0 units Focal length ofspherical convexmirror is : -15.0 units Please refer complete article on Program to determine focal length of a spherical mirror for more details! Java Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Iterate Over the Characters of a String in Java How to Convert Char to String in Java? How to Get Elements By Index from HashSet in Java? Java Program to Write into a File How to Write Data into Excel Sheet using Java? Java Program to Read a File to String Comparing two ArrayList In Java SHA-1 Hash Java Program to Convert File to a Byte Array Java Program to Find Sum of Array Elements
[ { "code": null, "e": 53, "s": 25, "text": "\n06 Dec, 2018" }, { "code": null, "e": 341, "s": 53, "text": "Focal length is the distance between the center of the mirror to the principal foci. In order to determine the focal length of a spherical mirror we should know the radius of curvature of that mirror. The distance from the vertex to the center of curvature is called radius of curvature." }, { "code": null, "e": 400, "s": 341, "text": "The focal length is half the radius of curvature.Formula :" }, { "code": null, "e": 479, "s": 400, "text": "F = ( R / 2 ) for concave mirror\nF = - ( R / 2 ) for convex mirror" }, { "code": null, "e": 490, "s": 479, "text": "Examples :" }, { "code": null, "e": 600, "s": 490, "text": "For a convex mirror\nInput : R = 30 \nOutput : F = 15\n\n\nFor a convex mirror\nInput : R = 25\nOutput : F = - 12.5\n" }, { "code": "// Java program to determine// the focal length of a// of a spherical mirrorimport java.util.*;import java.lang.*; public class GfG{ // Determines focal length // of a spherical concave // mirror public static float focal_length_concave(float R) { return R / 2 ; } // Determines focal length of a // spherical convex mirror public static float focal_length_convex(float R) { return - ( R / 2 ) ; } // Driver function public static void main(String argc[]) { float R = 30 ; System.out.print(\"Focal length of\" + \"spherical concave\"+ \"mirror is : \"+ focal_length_concave(R) + \" units\\n\"); System.out.println(\"Focal length of\"+ \"spherical convex\"+ \"mirror is : \"+ focal_length_convex(R) + \" units\"); }} /* This code is contributed by Sagar Shukla */", "e": 1675, "s": 600, "text": null }, { "code": null, "e": 1786, "s": 1675, "text": "Focal length ofspherical concavemirror is : 15.0 units\nFocal length ofspherical convexmirror is : -15.0 units\n" }, { "code": null, "e": 1893, "s": 1786, "text": "Please refer complete article on Program to determine focal length of a spherical mirror for more details!" }, { "code": null, "e": 1907, "s": 1893, "text": "Java Programs" }, { "code": null, "e": 2005, "s": 1907, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2053, "s": 2005, "text": "Iterate Over the Characters of a String in Java" }, { "code": null, "e": 2092, "s": 2053, "text": "How to Convert Char to String in Java?" }, { "code": null, "e": 2143, "s": 2092, "text": "How to Get Elements By Index from HashSet in Java?" }, { "code": null, "e": 2177, "s": 2143, "text": "Java Program to Write into a File" }, { "code": null, "e": 2224, "s": 2177, "text": "How to Write Data into Excel Sheet using Java?" }, { "code": null, "e": 2262, "s": 2224, "text": "Java Program to Read a File to String" }, { "code": null, "e": 2294, "s": 2262, "text": "Comparing two ArrayList In Java" }, { "code": null, "e": 2305, "s": 2294, "text": "SHA-1 Hash" }, { "code": null, "e": 2350, "s": 2305, "text": "Java Program to Convert File to a Byte Array" } ]
Tailwind CSS Overflow
23 Mar, 2022 This class accepts more than one value in Tailwind CSS. It is the alternative to the CSS Overflow property. This overflow is for controlling how an element content is handled that is too large for the container. It tells whether to clip content or to add scroll bars There is separate property in CSS for CSS Overflow-x and CSS Overflow-y, Overflow classes: overflow-auto overflow-hidden overflow-visible overflow-scroll overflow-x-auto overflow-y-auto overflow-x-hidden overflow-y-hidden overflow-x-visible overflow-y-visible overflow-x-scroll overflow-y-scroll overflow-auto: It automatically adds a scrollbar whenever it is required. This class adds scrollbars to an element in the event that its content overflows the boundary of that element. Syntax: <element class="overflow-auto">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"></head> <body class="text-center"> <center> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Overflow Class</b> <div class="overflow-auto bg-green-200 p-4 mx-16 h-24 text-justify"> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course </div> </center></body> </html> Output: overflow-hidden: The overflow is clipped and the rest of the content is invisible. This class is used to clip any content within an element that overflows the bounds of that element. Syntax: <element class="overflow-hidden">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"></head> <body class="text-center"> <center> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Overflow Class</b> <div class="overflow-hidden bg-green-200 p-4 mx-16 h-24 text-justify"> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course </div> </center></body> </html> Output: overflow-visible: The content is not clipped and visible outside the element box. This class used to prevent content within an element from being clipped. Syntax: <element class="overflow-visible">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"></head> <body class="text-center"> <center> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Overflow Class</b> <div class="overflow-visible bg-green-200 p-4 mx-16 h-24 text-justify"> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course </div> </center></body> </html> Output: overflow-scroll: The overflow is clipped but a scrollbar is added to see the rest of the content. The scrollbar can be horizontal or vertical. This class is used when you need to show scrollbars, this utility will only be shown if scrolling is necessary. Syntax: <element class="overflow-scroll">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"></head> <body class="text-center"> <center> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Overflow Class</b> <div class="overflow-scroll bg-green-200 p-4 mx-16 h-24 text-justify"> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? </div> </center></body> </html> Output: Overflow-x: This class specifies whether to add a scroll bar, clip the content, or display overflow content of a block-level element when it overflows at the left and right edges. overflow-x-auto: It provides a scrolling mechanism for overflowing boxes. Syntax: <element class="overflow-x-auto">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"></head> <body class="text-center"> <center> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Overflow-x Class</b> <div class="overflow-x-auto bg-green-200 p-4 mx-16 h-24 text-justify"> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? </div> </center></body> </html> Output: overflow-x-hidden: It is used to clip the content and no scrolling mechanism is provided on the x-axis. Syntax: <element class="overflow-x-hidden">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"></head> <body class="text-center"> <center> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Overflow-x Class</b> <div class="overflow-x-hidden bg-green-200 p-4 mx-16 h-12 text-justify"> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? </div> </center></body> </html> Output: overflow-x-visible: This class does not clip the content. The content may be rendered outside the left and right edges. Syntax: <element class="overflow-x-visible">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"></head> <body class="text-center"> <center> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Overflow-x Class</b> <div class="overflow-x-visible bg-green-200 p-4 mx-16 h-24 text-justify"> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? </div> </center></body> </html> Output: overflow-x-scroll: It is used to clip the content and providing a scrolling mechanism. Syntax: <element class="overflow-x-scroll">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"></head> <body class="text-center"> <center> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Overflow-x Class</b> <div class="overflow-x-scroll bg-green-200 p-4 mx-16 h-24 text-justify"> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? </div> </center></body> </html> Output: Overflow-y: This class specifies whether to add a scroll bar, clip the content, or display overflow content of a block-level element when it overflows at the top and bottom edges. overflow-y-auto: It provides a scrolling mechanism for overflowing boxes. Syntax: <element class="overflow-y-auto">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"></head> <body class="text-center"> <center> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Overflow-y Class</b> <div class="overflow-y-auto bg-green-200 p-4 mx-16 h-24 text-justify"> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? </div> </center></body> </html> Output: overflow-y-hidden: It is used to clip the content and no scrolling mechanism is provided on the y-axis. Syntax: <element class="overflow-y-hidden">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"></head> <body class="text-center"> <center> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Overflow-y Class</b> <div class="overflow-y-hidden bg-green-200 p-4 mx-16 h-24 text-justify"> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? </div> </center></body> </html> Output: overflow-y-visible: This class does not clip the content. The content may be rendered outside the left and right edges. Syntax: <element class="overflow-y-visible">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"></head> <body class="text-center"> <center> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Overflow-y Class</b> <div class="overflow-y-visible bg-green-200 p-4 mx-16 h-24 text-justify"> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? </div> </center></body> </html> Output: overflow-y-scroll: It is used to clip the content and also provides a scrolling mechanism. Syntax: <element class="overflow-y-scroll">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"></head> <body class="text-center"> <center> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Overflow-y Class</b> <div class="overflow-y-scroll bg-green-200 p-4 mx-16 h-24 text-justify"> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? </div> </center></body> </html> Output: Tailwind CSS Tailwind-Layout CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Mar, 2022" }, { "code": null, "e": 295, "s": 28, "text": "This class accepts more than one value in Tailwind CSS. It is the alternative to the CSS Overflow property. This overflow is for controlling how an element content is handled that is too large for the container. It tells whether to clip content or to add scroll bars" }, { "code": null, "e": 369, "s": 295, "text": "There is separate property in CSS for CSS Overflow-x and CSS Overflow-y, " }, { "code": null, "e": 387, "s": 369, "text": "Overflow classes:" }, { "code": null, "e": 402, "s": 387, "text": "overflow-auto " }, { "code": null, "e": 419, "s": 402, "text": "overflow-hidden " }, { "code": null, "e": 437, "s": 419, "text": "overflow-visible " }, { "code": null, "e": 454, "s": 437, "text": "overflow-scroll " }, { "code": null, "e": 471, "s": 454, "text": "overflow-x-auto " }, { "code": null, "e": 488, "s": 471, "text": "overflow-y-auto " }, { "code": null, "e": 507, "s": 488, "text": "overflow-x-hidden " }, { "code": null, "e": 526, "s": 507, "text": "overflow-y-hidden " }, { "code": null, "e": 546, "s": 526, "text": "overflow-x-visible " }, { "code": null, "e": 566, "s": 546, "text": "overflow-y-visible " }, { "code": null, "e": 585, "s": 566, "text": "overflow-x-scroll " }, { "code": null, "e": 604, "s": 585, "text": "overflow-y-scroll " }, { "code": null, "e": 790, "s": 604, "text": "overflow-auto: It automatically adds a scrollbar whenever it is required. This class adds scrollbars to an element in the event that its content overflows the boundary of that element." }, { "code": null, "e": 798, "s": 790, "text": "Syntax:" }, { "code": null, "e": 843, "s": 798, "text": "<element class=\"overflow-auto\">...</element>" }, { "code": null, "e": 852, "s": 843, "text": "Example:" }, { "code": null, "e": 857, "s": 852, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"></head> <body class=\"text-center\"> <center> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Overflow Class</b> <div class=\"overflow-auto bg-green-200 p-4 mx-16 h-24 text-justify\"> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course </div> </center></body> </html>", "e": 2275, "s": 857, "text": null }, { "code": null, "e": 2283, "s": 2275, "text": "Output:" }, { "code": null, "e": 2466, "s": 2283, "text": "overflow-hidden: The overflow is clipped and the rest of the content is invisible. This class is used to clip any content within an element that overflows the bounds of that element." }, { "code": null, "e": 2474, "s": 2466, "text": "Syntax:" }, { "code": null, "e": 2521, "s": 2474, "text": "<element class=\"overflow-hidden\">...</element>" }, { "code": null, "e": 2530, "s": 2521, "text": "Example:" }, { "code": null, "e": 2535, "s": 2530, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"></head> <body class=\"text-center\"> <center> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Overflow Class</b> <div class=\"overflow-hidden bg-green-200 p-4 mx-16 h-24 text-justify\"> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course </div> </center></body> </html>", "e": 3931, "s": 2535, "text": null }, { "code": null, "e": 3939, "s": 3931, "text": "Output:" }, { "code": null, "e": 4094, "s": 3939, "text": "overflow-visible: The content is not clipped and visible outside the element box. This class used to prevent content within an element from being clipped." }, { "code": null, "e": 4102, "s": 4094, "text": "Syntax:" }, { "code": null, "e": 4150, "s": 4102, "text": "<element class=\"overflow-visible\">...</element>" }, { "code": null, "e": 4159, "s": 4150, "text": "Example:" }, { "code": null, "e": 4164, "s": 4159, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"></head> <body class=\"text-center\"> <center> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Overflow Class</b> <div class=\"overflow-visible bg-green-200 p-4 mx-16 h-24 text-justify\"> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course </div> </center></body> </html>", "e": 5561, "s": 4164, "text": null }, { "code": null, "e": 5569, "s": 5561, "text": "Output:" }, { "code": null, "e": 5824, "s": 5569, "text": "overflow-scroll: The overflow is clipped but a scrollbar is added to see the rest of the content. The scrollbar can be horizontal or vertical. This class is used when you need to show scrollbars, this utility will only be shown if scrolling is necessary." }, { "code": null, "e": 5832, "s": 5824, "text": "Syntax:" }, { "code": null, "e": 5879, "s": 5832, "text": "<element class=\"overflow-scroll\">...</element>" }, { "code": null, "e": 5888, "s": 5879, "text": "Example:" }, { "code": null, "e": 5893, "s": 5888, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"></head> <body class=\"text-center\"> <center> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Overflow Class</b> <div class=\"overflow-scroll bg-green-200 p-4 mx-16 h-24 text-justify\"> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? </div> </center></body> </html>", "e": 6539, "s": 5893, "text": null }, { "code": null, "e": 6547, "s": 6539, "text": "Output:" }, { "code": null, "e": 6727, "s": 6547, "text": "Overflow-x: This class specifies whether to add a scroll bar, clip the content, or display overflow content of a block-level element when it overflows at the left and right edges." }, { "code": null, "e": 6801, "s": 6727, "text": "overflow-x-auto: It provides a scrolling mechanism for overflowing boxes." }, { "code": null, "e": 6809, "s": 6801, "text": "Syntax:" }, { "code": null, "e": 6856, "s": 6809, "text": "<element class=\"overflow-x-auto\">...</element>" }, { "code": null, "e": 6865, "s": 6856, "text": "Example:" }, { "code": null, "e": 6870, "s": 6865, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"></head> <body class=\"text-center\"> <center> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Overflow-x Class</b> <div class=\"overflow-x-auto bg-green-200 p-4 mx-16 h-24 text-justify\"> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? </div> </center></body> </html>", "e": 7530, "s": 6870, "text": null }, { "code": null, "e": 7538, "s": 7530, "text": "Output:" }, { "code": null, "e": 7642, "s": 7538, "text": "overflow-x-hidden: It is used to clip the content and no scrolling mechanism is provided on the x-axis." }, { "code": null, "e": 7650, "s": 7642, "text": "Syntax:" }, { "code": null, "e": 7699, "s": 7650, "text": "<element class=\"overflow-x-hidden\">...</element>" }, { "code": null, "e": 7708, "s": 7699, "text": "Example:" }, { "code": null, "e": 7713, "s": 7708, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"></head> <body class=\"text-center\"> <center> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Overflow-x Class</b> <div class=\"overflow-x-hidden bg-green-200 p-4 mx-16 h-12 text-justify\"> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? </div> </center></body> </html>", "e": 8375, "s": 7713, "text": null }, { "code": null, "e": 8383, "s": 8375, "text": "Output:" }, { "code": null, "e": 8503, "s": 8383, "text": "overflow-x-visible: This class does not clip the content. The content may be rendered outside the left and right edges." }, { "code": null, "e": 8511, "s": 8503, "text": "Syntax:" }, { "code": null, "e": 8561, "s": 8511, "text": "<element class=\"overflow-x-visible\">...</element>" }, { "code": null, "e": 8570, "s": 8561, "text": "Example:" }, { "code": null, "e": 8575, "s": 8570, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"></head> <body class=\"text-center\"> <center> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Overflow-x Class</b> <div class=\"overflow-x-visible bg-green-200 p-4 mx-16 h-24 text-justify\"> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? </div> </center></body> </html>", "e": 9238, "s": 8575, "text": null }, { "code": null, "e": 9246, "s": 9238, "text": "Output:" }, { "code": null, "e": 9333, "s": 9246, "text": "overflow-x-scroll: It is used to clip the content and providing a scrolling mechanism." }, { "code": null, "e": 9341, "s": 9333, "text": "Syntax:" }, { "code": null, "e": 9390, "s": 9341, "text": "<element class=\"overflow-x-scroll\">...</element>" }, { "code": null, "e": 9399, "s": 9390, "text": "Example:" }, { "code": null, "e": 9404, "s": 9399, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"></head> <body class=\"text-center\"> <center> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Overflow-x Class</b> <div class=\"overflow-x-scroll bg-green-200 p-4 mx-16 h-24 text-justify\"> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? </div> </center></body> </html>", "e": 10066, "s": 9404, "text": null }, { "code": null, "e": 10075, "s": 10066, "text": "Output: " }, { "code": null, "e": 10255, "s": 10075, "text": "Overflow-y: This class specifies whether to add a scroll bar, clip the content, or display overflow content of a block-level element when it overflows at the top and bottom edges." }, { "code": null, "e": 10329, "s": 10255, "text": "overflow-y-auto: It provides a scrolling mechanism for overflowing boxes." }, { "code": null, "e": 10337, "s": 10329, "text": "Syntax:" }, { "code": null, "e": 10384, "s": 10337, "text": "<element class=\"overflow-y-auto\">...</element>" }, { "code": null, "e": 10393, "s": 10384, "text": "Example:" }, { "code": null, "e": 10398, "s": 10393, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"></head> <body class=\"text-center\"> <center> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Overflow-y Class</b> <div class=\"overflow-y-auto bg-green-200 p-4 mx-16 h-24 text-justify\"> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? </div> </center></body> </html>", "e": 11066, "s": 10398, "text": null }, { "code": null, "e": 11074, "s": 11066, "text": "Output:" }, { "code": null, "e": 11178, "s": 11074, "text": "overflow-y-hidden: It is used to clip the content and no scrolling mechanism is provided on the y-axis." }, { "code": null, "e": 11186, "s": 11178, "text": "Syntax:" }, { "code": null, "e": 11235, "s": 11186, "text": "<element class=\"overflow-y-hidden\">...</element>" }, { "code": null, "e": 11244, "s": 11235, "text": "Example:" }, { "code": null, "e": 11249, "s": 11244, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"></head> <body class=\"text-center\"> <center> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Overflow-y Class</b> <div class=\"overflow-y-hidden bg-green-200 p-4 mx-16 h-24 text-justify\"> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? </div> </center></body> </html>", "e": 11918, "s": 11249, "text": null }, { "code": null, "e": 11926, "s": 11918, "text": "Output:" }, { "code": null, "e": 12046, "s": 11926, "text": "overflow-y-visible: This class does not clip the content. The content may be rendered outside the left and right edges." }, { "code": null, "e": 12054, "s": 12046, "text": "Syntax:" }, { "code": null, "e": 12104, "s": 12054, "text": "<element class=\"overflow-y-visible\">...</element>" }, { "code": null, "e": 12113, "s": 12104, "text": "Example:" }, { "code": null, "e": 12118, "s": 12113, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"></head> <body class=\"text-center\"> <center> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Overflow-y Class</b> <div class=\"overflow-y-visible bg-green-200 p-4 mx-16 h-24 text-justify\"> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? </div> </center></body> </html>", "e": 12767, "s": 12118, "text": null }, { "code": null, "e": 12775, "s": 12767, "text": "Output:" }, { "code": null, "e": 12866, "s": 12775, "text": "overflow-y-scroll: It is used to clip the content and also provides a scrolling mechanism." }, { "code": null, "e": 12874, "s": 12866, "text": "Syntax:" }, { "code": null, "e": 12923, "s": 12874, "text": "<element class=\"overflow-y-scroll\">...</element>" }, { "code": null, "e": 12932, "s": 12923, "text": "Example:" }, { "code": null, "e": 12937, "s": 12932, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"></head> <body class=\"text-center\"> <center> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Overflow-y Class</b> <div class=\"overflow-y-scroll bg-green-200 p-4 mx-16 h-24 text-justify\"> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? </div> </center></body> </html>", "e": 13587, "s": 12937, "text": null }, { "code": null, "e": 13595, "s": 13587, "text": "Output:" }, { "code": null, "e": 13608, "s": 13595, "text": "Tailwind CSS" }, { "code": null, "e": 13624, "s": 13608, "text": "Tailwind-Layout" }, { "code": null, "e": 13628, "s": 13624, "text": "CSS" }, { "code": null, "e": 13645, "s": 13628, "text": "Web Technologies" }, { "code": null, "e": 13743, "s": 13645, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13791, "s": 13743, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 13853, "s": 13791, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 13903, "s": 13853, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 13961, "s": 13903, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 14011, "s": 13961, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 14044, "s": 14011, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 14106, "s": 14044, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 14167, "s": 14106, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 14217, "s": 14167, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python | sep parameter in print()
21 Jan, 2021 The separator between the arguments to print() function in Python is space by default (softspace feature) , which can be modified and can be made to any character, integer or string as per our choice. The ‘sep’ parameter is used to achieve the same, it is found only in python 3.x or later. It is also used for formatting the output strings. Examples: Python3 #code for disabling the softspace featureprint('G','F','G', sep='') #for formatting a dateprint('09','12','2016', sep='-') #another exampleprint('pratik','geeksforgeeks', sep='@') Output: GFG 09-12-2016 pratik@geeksforgeeks The sep parameter when used with the end parameter it produces awesome results. Some examples by combining the sep and end parameters. Python3 print('G','F', sep='', end='')print('G')#\n provides new line after printing the yearprint('09','12','2016', sep='-', end='\n') print('prtk','agarwal', sep='', end='@')print('geeksforgeeks') Output: GFG 09-12-2016 prtkagarwal@geeksforgeeks Note: Please change the language from Python to Python 3 in the online ide. Go to your interactive python ide by typing python in your cmd ( windows ) or terminal ( linux ) Python3 #import the below module and see what happensimport antigravity#NOTE - it wont work on online ide This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. AshisKumarSahu rubicminer kishan797 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 Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? Iterate over a list in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Jan, 2021" }, { "code": null, "e": 395, "s": 52, "text": "The separator between the arguments to print() function in Python is space by default (softspace feature) , which can be modified and can be made to any character, integer or string as per our choice. The ‘sep’ parameter is used to achieve the same, it is found only in python 3.x or later. It is also used for formatting the output strings. " }, { "code": null, "e": 405, "s": 395, "text": "Examples:" }, { "code": null, "e": 413, "s": 405, "text": "Python3" }, { "code": "#code for disabling the softspace featureprint('G','F','G', sep='') #for formatting a dateprint('09','12','2016', sep='-') #another exampleprint('pratik','geeksforgeeks', sep='@')", "e": 593, "s": 413, "text": null }, { "code": null, "e": 603, "s": 593, "text": "Output: " }, { "code": null, "e": 639, "s": 603, "text": "GFG\n09-12-2016\npratik@geeksforgeeks" }, { "code": null, "e": 775, "s": 639, "text": "The sep parameter when used with the end parameter it produces awesome results. Some examples by combining the sep and end parameters. " }, { "code": null, "e": 783, "s": 775, "text": "Python3" }, { "code": "print('G','F', sep='', end='')print('G')#\\n provides new line after printing the yearprint('09','12','2016', sep='-', end='\\n') print('prtk','agarwal', sep='', end='@')print('geeksforgeeks')", "e": 974, "s": 783, "text": null }, { "code": null, "e": 984, "s": 974, "text": "Output: " }, { "code": null, "e": 1025, "s": 984, "text": "GFG\n09-12-2016\nprtkagarwal@geeksforgeeks" }, { "code": null, "e": 1199, "s": 1025, "text": "Note: Please change the language from Python to Python 3 in the online ide. Go to your interactive python ide by typing python in your cmd ( windows ) or terminal ( linux ) " }, { "code": null, "e": 1207, "s": 1199, "text": "Python3" }, { "code": "#import the below module and see what happensimport antigravity#NOTE - it wont work on online ide", "e": 1305, "s": 1207, "text": null }, { "code": null, "e": 1732, "s": 1305, "text": "This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 1747, "s": 1732, "text": "AshisKumarSahu" }, { "code": null, "e": 1758, "s": 1747, "text": "rubicminer" }, { "code": null, "e": 1768, "s": 1758, "text": "kishan797" }, { "code": null, "e": 1775, "s": 1768, "text": "Python" }, { "code": null, "e": 1873, "s": 1775, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1901, "s": 1873, "text": "Read JSON file using Python" }, { "code": null, "e": 1951, "s": 1901, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 1973, "s": 1951, "text": "Python map() function" }, { "code": null, "e": 2017, "s": 1973, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 2059, "s": 2017, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2081, "s": 2059, "text": "Enumerate() in Python" }, { "code": null, "e": 2116, "s": 2081, "text": "Read a file line by line in Python" }, { "code": null, "e": 2142, "s": 2116, "text": "Python String | replace()" }, { "code": null, "e": 2174, "s": 2142, "text": "How to Install PIP on Windows ?" } ]
Python MongoDB – find_one_and_replace Query
02 Sep, 2021 find_one_and_replace() method search one document if finds then replaces with the given second parameter in MongoDb. find_one_and_replace() method is differ from find_one_and_update() with the help of filter it replace the document rather than update the existing document. Syntax: find_one_and_replace(filter, replacement, projection=None, sort=None, return_document=ReturnDocument.BEFORE, session=None, **kwargs)Parameters filter: A query for replacement of a matched document. replacement: replacement document. projection: it is optional.A list of a field that should be returned in the result. sort: key, direction pair for the sort order of query. return_document: Return the original document without replacement. **kwargs: Additional commands. Sample database used in all the below examples: Example 1: Python3 import pymongo # establishing connection# to the databaseclient = pymongo.MongoClient("mongodb://localhost:27017/") # Database namedb = client["mydatabase"] # Collection namecol = db["gfg"] # replace with the help of# find_one_and_replace()col.find_one_and_replace({'coursename':'SYSTEM DESIGN'}, {'coursename': 'PHP'}) # print the document after replacementfor x in col.find({}, {"_id":0, "coursename": 1, "price": 1 }): print(x) Output: Example 2: Python3 import pymongo # establishing connection# to the databaseclient = pymongo.MongoClient("mongodb://localhost:27017/") # Database namedb = client["mydatabase"] # Collection namecol = db["gfg"] # replace with the help of# find_one_and_replace()col.find_one_and_replace({'price':9999}, {'price':19999}) # print the document after replacementfor x in col.find({}, {"_id":0, "coursename": 1, "price": 1 }): print(x) Output: abhishek0719kadiyan Python-mongoDB Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Sep, 2021" }, { "code": null, "e": 303, "s": 28, "text": "find_one_and_replace() method search one document if finds then replaces with the given second parameter in MongoDb. find_one_and_replace() method is differ from find_one_and_update() with the help of filter it replace the document rather than update the existing document. " }, { "code": null, "e": 783, "s": 303, "text": "Syntax: find_one_and_replace(filter, replacement, projection=None, sort=None, return_document=ReturnDocument.BEFORE, session=None, **kwargs)Parameters filter: A query for replacement of a matched document. replacement: replacement document. projection: it is optional.A list of a field that should be returned in the result. sort: key, direction pair for the sort order of query. return_document: Return the original document without replacement. **kwargs: Additional commands. " }, { "code": null, "e": 832, "s": 783, "text": "Sample database used in all the below examples: " }, { "code": null, "e": 844, "s": 832, "text": "Example 1: " }, { "code": null, "e": 852, "s": 844, "text": "Python3" }, { "code": "import pymongo # establishing connection# to the databaseclient = pymongo.MongoClient(\"mongodb://localhost:27017/\") # Database namedb = client[\"mydatabase\"] # Collection namecol = db[\"gfg\"] # replace with the help of# find_one_and_replace()col.find_one_and_replace({'coursename':'SYSTEM DESIGN'}, {'coursename': 'PHP'}) # print the document after replacementfor x in col.find({}, {\"_id\":0, \"coursename\": 1, \"price\": 1 }): print(x)", "e": 1320, "s": 852, "text": null }, { "code": null, "e": 1330, "s": 1320, "text": "Output: " }, { "code": null, "e": 1343, "s": 1330, "text": "Example 2: " }, { "code": null, "e": 1351, "s": 1343, "text": "Python3" }, { "code": "import pymongo # establishing connection# to the databaseclient = pymongo.MongoClient(\"mongodb://localhost:27017/\") # Database namedb = client[\"mydatabase\"] # Collection namecol = db[\"gfg\"] # replace with the help of# find_one_and_replace()col.find_one_and_replace({'price':9999}, {'price':19999}) # print the document after replacementfor x in col.find({}, {\"_id\":0, \"coursename\": 1, \"price\": 1 }): print(x)", "e": 1776, "s": 1351, "text": null }, { "code": null, "e": 1786, "s": 1776, "text": "Output: " }, { "code": null, "e": 1808, "s": 1788, "text": "abhishek0719kadiyan" }, { "code": null, "e": 1823, "s": 1808, "text": "Python-mongoDB" }, { "code": null, "e": 1830, "s": 1823, "text": "Python" }, { "code": null, "e": 1928, "s": 1830, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1960, "s": 1928, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1987, "s": 1960, "text": "Python Classes and Objects" }, { "code": null, "e": 2008, "s": 1987, "text": "Python OOPs Concepts" }, { "code": null, "e": 2031, "s": 2008, "text": "Introduction To PYTHON" }, { "code": null, "e": 2087, "s": 2031, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2118, "s": 2087, "text": "Python | os.path.join() method" }, { "code": null, "e": 2160, "s": 2118, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2202, "s": 2160, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2241, "s": 2202, "text": "Python | Get unique values from a list" } ]
What is Escrow Smart Contract?
11 May, 2022 Escrow is the third party which holds the asset(asset can be money, bond, stocks) on the presence of two parties. Escrow will release the fund when certain conditions are met.For Example, “A” is a seller and wants to sell his car, “B” is a buyer who wants to buy “A”‘s car so they will contact Escrow “C”(an arbiter) which hold the asset until “B” receives the car. When this condition will be met, Escrow will release the fund to “A”. This solves the issue of trust and prevents any discrepancy.Lets the write a smart contract for the Escrow using solidity language. Here Smart contract will hold the asset, which will be released on when conditions are fulfilled. Solidity pragma solidity 0.6.0; // Defining a Contractcontract escrow{ // Declaring the state variables address payable public buyer; address payable public seller; address payable public arbiter; mapping(address => uint) TotalAmount; // Defining a enumerator 'State' enum State{ // Following are the data members awate_payment, awate_delivery, complete } // Declaring the object of the enumerator State public state; // Defining function modifier 'instate' modifier instate(State expected_state){ require(state == expected_state); _; } // Defining function modifier 'onlyBuyer' modifier onlyBuyer(){ require(msg.sender == buyer || msg.sender == arbiter); _; } // Defining function modifier 'onlySeller' modifier onlySeller(){ require(msg.sender == seller); _; } // Defining a constructor constructor(address payable _buyer, address payable _sender) public{ // Assigning the values of the // state variables arbiter = msg.sender; buyer = _buyer; seller = _sender; state = State.awate_payment; } // Defining function to confirm payment function confirm_payment() onlyBuyer instate( State.awate_payment) public payable{ state = State.awate_delivery; } // Defining function to confirm delivery function confirm_Delivery() onlyBuyer instate( State.awate_delivery) public{ seller.transfer(address(this).balance); state = State.complete; } // Defining function to return payment function ReturnPayment() onlySeller instate( State.awate_delivery)public{ buyer.transfer(address(this).balance); } } Solidity-Basics Blockchain Solidity Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to connect ReactJS with MetaMask ? Solidity - Libraries Solidity - While, Do-While, and For Loop Solidity - Functions Blockchain - Hyperledger vs Ethereum Solidity - Libraries Solidity - While, Do-While, and For Loop Solidity - Functions Solidity - Variables What are Events in Solidity?
[ { "code": null, "e": 52, "s": 24, "text": "\n11 May, 2022" }, { "code": null, "e": 719, "s": 52, "text": "Escrow is the third party which holds the asset(asset can be money, bond, stocks) on the presence of two parties. Escrow will release the fund when certain conditions are met.For Example, “A” is a seller and wants to sell his car, “B” is a buyer who wants to buy “A”‘s car so they will contact Escrow “C”(an arbiter) which hold the asset until “B” receives the car. When this condition will be met, Escrow will release the fund to “A”. This solves the issue of trust and prevents any discrepancy.Lets the write a smart contract for the Escrow using solidity language. Here Smart contract will hold the asset, which will be released on when conditions are fulfilled. " }, { "code": null, "e": 728, "s": 719, "text": "Solidity" }, { "code": "pragma solidity 0.6.0; // Defining a Contractcontract escrow{ // Declaring the state variables address payable public buyer; address payable public seller; address payable public arbiter; mapping(address => uint) TotalAmount; // Defining a enumerator 'State' enum State{ // Following are the data members awate_payment, awate_delivery, complete } // Declaring the object of the enumerator State public state; // Defining function modifier 'instate' modifier instate(State expected_state){ require(state == expected_state); _; } // Defining function modifier 'onlyBuyer' modifier onlyBuyer(){ require(msg.sender == buyer || msg.sender == arbiter); _; } // Defining function modifier 'onlySeller' modifier onlySeller(){ require(msg.sender == seller); _; } // Defining a constructor constructor(address payable _buyer, address payable _sender) public{ // Assigning the values of the // state variables arbiter = msg.sender; buyer = _buyer; seller = _sender; state = State.awate_payment; } // Defining function to confirm payment function confirm_payment() onlyBuyer instate( State.awate_payment) public payable{ state = State.awate_delivery; } // Defining function to confirm delivery function confirm_Delivery() onlyBuyer instate( State.awate_delivery) public{ seller.transfer(address(this).balance); state = State.complete; } // Defining function to return payment function ReturnPayment() onlySeller instate( State.awate_delivery)public{ buyer.transfer(address(this).balance); } }", "e": 2593, "s": 728, "text": null }, { "code": null, "e": 2609, "s": 2593, "text": "Solidity-Basics" }, { "code": null, "e": 2620, "s": 2609, "text": "Blockchain" }, { "code": null, "e": 2629, "s": 2620, "text": "Solidity" }, { "code": null, "e": 2727, "s": 2629, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2766, "s": 2727, "text": "How to connect ReactJS with MetaMask ?" }, { "code": null, "e": 2787, "s": 2766, "text": "Solidity - Libraries" }, { "code": null, "e": 2828, "s": 2787, "text": "Solidity - While, Do-While, and For Loop" }, { "code": null, "e": 2849, "s": 2828, "text": "Solidity - Functions" }, { "code": null, "e": 2886, "s": 2849, "text": "Blockchain - Hyperledger vs Ethereum" }, { "code": null, "e": 2907, "s": 2886, "text": "Solidity - Libraries" }, { "code": null, "e": 2948, "s": 2907, "text": "Solidity - While, Do-While, and For Loop" }, { "code": null, "e": 2969, "s": 2948, "text": "Solidity - Functions" }, { "code": null, "e": 2990, "s": 2969, "text": "Solidity - Variables" } ]
Program to accept String starting with Capital letter
20 May, 2021 Given a string str consisting of alphabets, the task is to check whether the given string is starting with a Capital Letter or Not.Examples: Input: str = "GeeksforGeeks" Output: Accepted Input: str = "geeksforgeeks" Output: Not Accepted Approach: Find the ASCII value of the first character of the string Check if this value lies in the range of [65, 90] or not If yes, print Accepted Else print Not Accepted Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to accept String// starting with Capital letter #include <iostream>using namespace std; // Function to check if first// character is Capitalint checkIfStartsWithCapital(string str){ if (str[0] >= 'A' && str[0] <= 'Z') return 1; else return 0;} // Function to checkvoid check(string str){ if (checkIfStartsWithCapital(str)) cout << "Accepted\n"; else cout << "Not Accepted\n";} // Driver functionint main(){ string str = "GeeksforGeeks"; check(str); str = "geeksforgeeks"; check(str); return 0;} // Java program to accept String// starting with Capital letterclass GFG{ // Function to check if first // character is Capital static int checkIfStartsWithCapital(String str) { if (str.charAt(0) >= 'A' && str.charAt(0)<= 'Z') return 1; else return 0; } // Function to check static void check(String str) { if (checkIfStartsWithCapital(str) == 1) System.out.println("Accepted"); else System.out.println("Not Accepted"); } // Driver function public static void main (String[] args) { String str = "GeeksforGeeks"; check(str); str = "geeksforgeeks"; check(str); }} // This code is contributed by AnkitRai01 # Python3 program to accept String# starting with Capital letter # Function to check if first# character is Capitaldef checkIfStartsWithCapital(string) : if (string[0] >= 'A' and string[0] <= 'Z') : return 1; else : return 0; # Function to checkdef check(string) : if (checkIfStartsWithCapital(string)) : print("Accepted"); else : print("Not Accepted"); # Driver functionif __name__ == "__main__" : string = "GeeksforGeeks"; check(string); string = "geeksforgeeks"; check(string); # This code is contributed by AnkitRai01 // C# program to accept String// starting with Capital letterusing System; class GFG{ // Function to check if first // character is Capital static int checkIfStartsWithCapital(string str) { if (str[0] >= 'A' && str[0]<= 'Z') return 1; else return 0; } // Function to check static void check(string str) { if (checkIfStartsWithCapital(str) == 1) Console.WriteLine("Accepted"); else Console.WriteLine("Not Accepted"); } // Driver function public static void Main() { string str = "GeeksforGeeks"; check(str); str = "geeksforgeeks"; check(str); }} // This code is contributed by AnkitRai01 <script> // JavaScript program to accept String// starting with Capital letter // Function to check if first// character is Capitalfunction checkIfStartsWithCapital(str){ if (str[0] >= 'A' && str[0] <= 'Z') return 1; else return 0;} // Function to checkfunction check(str){ if (checkIfStartsWithCapital(str)) document.write( "Accepted<br>"); else document.write( "Not Accepted<br>");} // Driver function var str = "GeeksforGeeks";check(str);str= "geeksforgeeks";check(str); </script> Accepted Not Accepted ankthon itsok School Programming Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n20 May, 2021" }, { "code": null, "e": 171, "s": 28, "text": "Given a string str consisting of alphabets, the task is to check whether the given string is starting with a Capital Letter or Not.Examples: " }, { "code": null, "e": 268, "s": 171, "text": "Input: str = \"GeeksforGeeks\"\nOutput: Accepted\n\nInput: str = \"geeksforgeeks\"\nOutput: Not Accepted" }, { "code": null, "e": 282, "s": 270, "text": "Approach: " }, { "code": null, "e": 342, "s": 282, "text": "Find the ASCII value of the first character of the string " }, { "code": null, "e": 401, "s": 342, "text": "Check if this value lies in the range of [65, 90] or not " }, { "code": null, "e": 426, "s": 401, "text": "If yes, print Accepted " }, { "code": null, "e": 452, "s": 426, "text": "Else print Not Accepted " }, { "code": null, "e": 505, "s": 452, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 509, "s": 505, "text": "C++" }, { "code": null, "e": 514, "s": 509, "text": "Java" }, { "code": null, "e": 522, "s": 514, "text": "Python3" }, { "code": null, "e": 525, "s": 522, "text": "C#" }, { "code": null, "e": 536, "s": 525, "text": "Javascript" }, { "code": "// C++ program to accept String// starting with Capital letter #include <iostream>using namespace std; // Function to check if first// character is Capitalint checkIfStartsWithCapital(string str){ if (str[0] >= 'A' && str[0] <= 'Z') return 1; else return 0;} // Function to checkvoid check(string str){ if (checkIfStartsWithCapital(str)) cout << \"Accepted\\n\"; else cout << \"Not Accepted\\n\";} // Driver functionint main(){ string str = \"GeeksforGeeks\"; check(str); str = \"geeksforgeeks\"; check(str); return 0;}", "e": 1104, "s": 536, "text": null }, { "code": "// Java program to accept String// starting with Capital letterclass GFG{ // Function to check if first // character is Capital static int checkIfStartsWithCapital(String str) { if (str.charAt(0) >= 'A' && str.charAt(0)<= 'Z') return 1; else return 0; } // Function to check static void check(String str) { if (checkIfStartsWithCapital(str) == 1) System.out.println(\"Accepted\"); else System.out.println(\"Not Accepted\"); } // Driver function public static void main (String[] args) { String str = \"GeeksforGeeks\"; check(str); str = \"geeksforgeeks\"; check(str); }} // This code is contributed by AnkitRai01", "e": 1873, "s": 1104, "text": null }, { "code": "# Python3 program to accept String# starting with Capital letter # Function to check if first# character is Capitaldef checkIfStartsWithCapital(string) : if (string[0] >= 'A' and string[0] <= 'Z') : return 1; else : return 0; # Function to checkdef check(string) : if (checkIfStartsWithCapital(string)) : print(\"Accepted\"); else : print(\"Not Accepted\"); # Driver functionif __name__ == \"__main__\" : string = \"GeeksforGeeks\"; check(string); string = \"geeksforgeeks\"; check(string); # This code is contributed by AnkitRai01", "e": 2451, "s": 1873, "text": null }, { "code": "// C# program to accept String// starting with Capital letterusing System; class GFG{ // Function to check if first // character is Capital static int checkIfStartsWithCapital(string str) { if (str[0] >= 'A' && str[0]<= 'Z') return 1; else return 0; } // Function to check static void check(string str) { if (checkIfStartsWithCapital(str) == 1) Console.WriteLine(\"Accepted\"); else Console.WriteLine(\"Not Accepted\"); } // Driver function public static void Main() { string str = \"GeeksforGeeks\"; check(str); str = \"geeksforgeeks\"; check(str); }} // This code is contributed by AnkitRai01", "e": 3202, "s": 2451, "text": null }, { "code": "<script> // JavaScript program to accept String// starting with Capital letter // Function to check if first// character is Capitalfunction checkIfStartsWithCapital(str){ if (str[0] >= 'A' && str[0] <= 'Z') return 1; else return 0;} // Function to checkfunction check(str){ if (checkIfStartsWithCapital(str)) document.write( \"Accepted<br>\"); else document.write( \"Not Accepted<br>\");} // Driver function var str = \"GeeksforGeeks\";check(str);str= \"geeksforgeeks\";check(str); </script>", "e": 3729, "s": 3202, "text": null }, { "code": null, "e": 3751, "s": 3729, "text": "Accepted\nNot Accepted" }, { "code": null, "e": 3761, "s": 3753, "text": "ankthon" }, { "code": null, "e": 3767, "s": 3761, "text": "itsok" }, { "code": null, "e": 3786, "s": 3767, "text": "School Programming" }, { "code": null, "e": 3794, "s": 3786, "text": "Strings" }, { "code": null, "e": 3802, "s": 3794, "text": "Strings" } ]
Python | Pandas Index.delete()
16 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 Index.delete() function returns a new object with the passed locations deleted. We can pass more than one locations to be deleted in the form of list. Syntax: Index.delete(loc) Parameters :loc : Scalar/List of Indices Returns : new_index : Index Example #1: Use Index.delete() function to delete the first value in the Index. # importing pandas as pdimport pandas as pd # Creating the Indexidx = pd.Index(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']) # Print the Indexidx Output : Let’s delete the month of ‘Jan’. It is present at the 0th index so we will pass 0 as an argument to the function. # delete the first label in the given Indexidx.delete(0) Output :As we can see in the output, the function has returned an object with its first label deleted. Example #2: Use Index.delete() function to delete more than one labels in the Index. # importing pandas as pdimport pandas as pd # Creating the Indexidx = pd.Index(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']) # Print the Indexidx Output : Let’s delete the second, third, fourth and fifth indices from the Index. We pass a list of values to be deleted to the function. # to delete values present at 2nd, 3rd, 4th and 5th place in the Index.idx.delete([2, 3, 4, 5]) Output :As we can see the labels corresponding to the passed values in the Index has been deleted. Python pandas-indexing Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Dec, 2018" }, { "code": null, "e": 242, "s": 28, "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": 400, "s": 242, "text": "Pandas Index.delete() function returns a new object with the passed locations deleted. We can pass more than one locations to be deleted in the form of list." }, { "code": null, "e": 426, "s": 400, "text": "Syntax: Index.delete(loc)" }, { "code": null, "e": 467, "s": 426, "text": "Parameters :loc : Scalar/List of Indices" }, { "code": null, "e": 495, "s": 467, "text": "Returns : new_index : Index" }, { "code": null, "e": 575, "s": 495, "text": "Example #1: Use Index.delete() function to delete the first value in the Index." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Indexidx = pd.Index(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']) # Print the Indexidx", "e": 778, "s": 575, "text": null }, { "code": null, "e": 787, "s": 778, "text": "Output :" }, { "code": null, "e": 901, "s": 787, "text": "Let’s delete the month of ‘Jan’. It is present at the 0th index so we will pass 0 as an argument to the function." }, { "code": "# delete the first label in the given Indexidx.delete(0)", "e": 958, "s": 901, "text": null }, { "code": null, "e": 1146, "s": 958, "text": "Output :As we can see in the output, the function has returned an object with its first label deleted. Example #2: Use Index.delete() function to delete more than one labels in the Index." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Indexidx = pd.Index(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']) # Print the Indexidx", "e": 1349, "s": 1146, "text": null }, { "code": null, "e": 1358, "s": 1349, "text": "Output :" }, { "code": null, "e": 1487, "s": 1358, "text": "Let’s delete the second, third, fourth and fifth indices from the Index. We pass a list of values to be deleted to the function." }, { "code": "# to delete values present at 2nd, 3rd, 4th and 5th place in the Index.idx.delete([2, 3, 4, 5])", "e": 1583, "s": 1487, "text": null }, { "code": null, "e": 1682, "s": 1583, "text": "Output :As we can see the labels corresponding to the passed values in the Index has been deleted." }, { "code": null, "e": 1705, "s": 1682, "text": "Python pandas-indexing" }, { "code": null, "e": 1719, "s": 1705, "text": "Python-pandas" }, { "code": null, "e": 1726, "s": 1719, "text": "Python" } ]
Writing clean if else statements
13 Jan, 2022 Using if else chaining some time looks more complex, this can be avoided by writing the code in small blocks. Use of conditional statement increases the code readability and much more. One best practice should be handling error case first. Below shown example shows how to handle error cases and simplify the if else logic.Examples 1: updateCache()- It’s a method in which on the basis of some class level variables decision is taken for update main db. updateBackupDb()- It’s a method to update the DB. Using this type of if else is harder to debug and extend any feature in existing function. Before optimization Java // A simple method handling the data// base operation related taskprivate void updateDb(boolean isForceUpdate) { // isUpdateReady is class level // variable if (isUpdateReady) { // isForceUpdate is argument variable // and based on this inner blocks is // executed if (isForceUpdate) { // isSynchCompleted is also class // level variable, based on its // true/false updateDbMain is called // here updateBackupDb is called // in both the cases if (isSynchCompleted) { updateDbMain(true); updateBackupDb(true); } else { updateDbMain(false); updateBackupDb(true); } } else { // execute this if isUpdateReady is // false i. e., this is dependent on // if condition updateCache(!isCacheEnabled); // end of second isForceUpdate block } // end of first if block } // end of method} Observations : In below code the boolean variables has been identified and based on that code is broken into small blocks using if and return statement. 1. If update is not ready then this is not required to enter in method just exit from this method. 2. Similarly is force update boolean is false then perform the task in if statement – updating the cache and returning from this method. 3. In the last step rest all task is done updating backup db and updating main db. After optimization Java // A simple method handling the// data base operation related// taskprivate void updateDb(boolean isForceUpdate) { // If isUpdateReaday boolean is not // true then return from this method, // nothing was done in else block if (!isUpdateReady) return; // Now if isForceUpdate boolean is // not true then only updating the // cache otherwise this block was // not called if (!isForceUpdate) { updateCache(!isCacheEnabled); return; } // After all above condition is not // fulfilled below code is executed // this backup method was called two // times thus calling only single time updateBackupDb(true); // main db is updated based on sync // completed method updateDbMain(isSynchCompleted ? true : false);} Note- What major consideration is taken in above optimization version is simplify the if else based on the conditional statement. The benefit of this type of easy blocks of code is – for the next developer it is very easy to debug/understand/extend this method.Example 2: Explaining this idea via existing JAVA API code example This code snippet is taken from Java Doc:- JDK sub string code JAVA API Existing code from above API- this is written perfect. After Optimization Java public String substring(int beginIndex, int endIndex) { // My comment - Below are the example of // correct use of if else, checking // condition and returning from // methods, // this is not about throwing error ie // return or throw error or do something // else - the idea is braking if // else // chaining. if (beginIndex < 0) { throw new StringIndexOutOfBoundsException(beginIndex); } if (endIndex > value.length) { throw new StringIndexOutOfBoundsException(endIndex); } int subLen = endIndex - beginIndex; if (subLen < 0) { throw new StringIndexOutOfBoundsException(subLen); } return ((beginIndex == 0) && (endIndex == value.length)) ? this : new String(value, beginIndex, subLen);} If any one use if else as shown in below example after modifying above logic, it will be very complex but at the end producing same result so i would not prefer to implement as shown below – Before optimization Java public String substring(int beginIndex, int endIndex) { if (beginIndex < 0) { throw new StringIndexOutOfBoundsException(beginIndex); } else { // Again why this else block is used, // this need not to write, see above // correct implementation if (endIndex > value.length) { throw new StringIndexOutOfBoundsException(endIndex); } else { // This else is also not required int subLen = endIndex - beginIndex; if (subLen < 0) { throw new StringIndexOutOfBoundsException(subLen); } } return ((beginIndex == 0) && (endIndex == value.length)) ? this : new String(value, beginIndex, subLen); }} After seeing above two examples it can be observed that error handling is done while entering in method. This is good practice to handle error condition first.Overall if if else can be used in small blocks based on requirement that will remove code complexity and code will be easy to use/debug/maintain/extend. ArjitMalviya rkbhola5 Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Jan, 2022" }, { "code": null, "e": 645, "s": 28, "text": "Using if else chaining some time looks more complex, this can be avoided by writing the code in small blocks. Use of conditional statement increases the code readability and much more. One best practice should be handling error case first. Below shown example shows how to handle error cases and simplify the if else logic.Examples 1: updateCache()- It’s a method in which on the basis of some class level variables decision is taken for update main db. updateBackupDb()- It’s a method to update the DB. Using this type of if else is harder to debug and extend any feature in existing function. Before optimization " }, { "code": null, "e": 650, "s": 645, "text": "Java" }, { "code": "// A simple method handling the data// base operation related taskprivate void updateDb(boolean isForceUpdate) { // isUpdateReady is class level // variable if (isUpdateReady) { // isForceUpdate is argument variable // and based on this inner blocks is // executed if (isForceUpdate) { // isSynchCompleted is also class // level variable, based on its // true/false updateDbMain is called // here updateBackupDb is called // in both the cases if (isSynchCompleted) { updateDbMain(true); updateBackupDb(true); } else { updateDbMain(false); updateBackupDb(true); } } else { // execute this if isUpdateReady is // false i. e., this is dependent on // if condition updateCache(!isCacheEnabled); // end of second isForceUpdate block } // end of first if block } // end of method}", "e": 1552, "s": 650, "text": null }, { "code": null, "e": 2045, "s": 1552, "text": "Observations : In below code the boolean variables has been identified and based on that code is broken into small blocks using if and return statement. 1. If update is not ready then this is not required to enter in method just exit from this method. 2. Similarly is force update boolean is false then perform the task in if statement – updating the cache and returning from this method. 3. In the last step rest all task is done updating backup db and updating main db. After optimization " }, { "code": null, "e": 2050, "s": 2045, "text": "Java" }, { "code": "// A simple method handling the// data base operation related// taskprivate void updateDb(boolean isForceUpdate) { // If isUpdateReaday boolean is not // true then return from this method, // nothing was done in else block if (!isUpdateReady) return; // Now if isForceUpdate boolean is // not true then only updating the // cache otherwise this block was // not called if (!isForceUpdate) { updateCache(!isCacheEnabled); return; } // After all above condition is not // fulfilled below code is executed // this backup method was called two // times thus calling only single time updateBackupDb(true); // main db is updated based on sync // completed method updateDbMain(isSynchCompleted ? true : false);}", "e": 2786, "s": 2050, "text": null }, { "code": null, "e": 3262, "s": 2786, "text": "Note- What major consideration is taken in above optimization version is simplify the if else based on the conditional statement. The benefit of this type of easy blocks of code is – for the next developer it is very easy to debug/understand/extend this method.Example 2: Explaining this idea via existing JAVA API code example This code snippet is taken from Java Doc:- JDK sub string code JAVA API Existing code from above API- this is written perfect. After Optimization " }, { "code": null, "e": 3267, "s": 3262, "text": "Java" }, { "code": "public String substring(int beginIndex, int endIndex) { // My comment - Below are the example of // correct use of if else, checking // condition and returning from // methods, // this is not about throwing error ie // return or throw error or do something // else - the idea is braking if // else // chaining. if (beginIndex < 0) { throw new StringIndexOutOfBoundsException(beginIndex); } if (endIndex > value.length) { throw new StringIndexOutOfBoundsException(endIndex); } int subLen = endIndex - beginIndex; if (subLen < 0) { throw new StringIndexOutOfBoundsException(subLen); } return ((beginIndex == 0) && (endIndex == value.length)) ? this : new String(value, beginIndex, subLen);}", "e": 3994, "s": 3267, "text": null }, { "code": null, "e": 4207, "s": 3994, "text": "If any one use if else as shown in below example after modifying above logic, it will be very complex but at the end producing same result so i would not prefer to implement as shown below – Before optimization " }, { "code": null, "e": 4212, "s": 4207, "text": "Java" }, { "code": "public String substring(int beginIndex, int endIndex) { if (beginIndex < 0) { throw new StringIndexOutOfBoundsException(beginIndex); } else { // Again why this else block is used, // this need not to write, see above // correct implementation if (endIndex > value.length) { throw new StringIndexOutOfBoundsException(endIndex); } else { // This else is also not required int subLen = endIndex - beginIndex; if (subLen < 0) { throw new StringIndexOutOfBoundsException(subLen); } } return ((beginIndex == 0) && (endIndex == value.length)) ? this : new String(value, beginIndex, subLen); }}", "e": 4875, "s": 4212, "text": null }, { "code": null, "e": 5188, "s": 4875, "text": "After seeing above two examples it can be observed that error handling is done while entering in method. This is good practice to handle error condition first.Overall if if else can be used in small blocks based on requirement that will remove code complexity and code will be easy to use/debug/maintain/extend. " }, { "code": null, "e": 5201, "s": 5188, "text": "ArjitMalviya" }, { "code": null, "e": 5210, "s": 5201, "text": "rkbhola5" }, { "code": null, "e": 5215, "s": 5210, "text": "Java" }, { "code": null, "e": 5220, "s": 5215, "text": "Java" } ]
Total number of possible Binary Search Trees using Catalan Number
16 Jun, 2022 Given an integer N, the task is to count the number of possible Binary Search Trees with N keys. Examples: Input: N = 2 Output: 2 For N = 2, there are 2 unique BSTs 1 2 \ / 2 1 Input: N = 9 Output: 4862 Approach: The number of binary search trees that will be formed with N keys can be calculated by simply evaluating the corresponding number in Catalan Number series. First few Catalan numbers for n = 0, 1, 2, 3, ... are 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, ...Catalan numbers satisfy the following recursive formula: Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <iostream>using namespace std; // Function to return the count// of unique BSTs with n keysint uniqueBSTs(int n){ int n1, n2, sum = 0; // Base cases if (n == 1 || n == 0) return 1; // Find the nth Catalan number for (int i = 1; i <= n; i++) { // Recursive calls n1 = uniqueBSTs(i - 1); n2 = uniqueBSTs(n - i); sum += n1 * n2; } // Return the nth Catalan number return sum;} // Driver codeint main(){ int n = 2; // Function call cout << uniqueBSTs(n); return 0;} // Java implementation of the approachimport java.io.*; class GFG { // Function to return the count // of unique BSTs with n keys static int uniqueBSTs(int n) { int n1, n2, sum = 0; // Base cases if (n == 1 || n == 0) return 1; // Find the nth Catalan number for (int i = 1; i <= n; i++) { // Recursive calls n1 = uniqueBSTs(i - 1); n2 = uniqueBSTs(n - i); sum += n1 * n2; } // Return the nth Catalan number return sum; } // Driver code public static void main(String[] args) { int n = 2; // Function call System.out.println(uniqueBSTs(n)); }} // This code is contributed by jit_t. # Python3 implementation of the approach # Function to return the count# of unique BSTs with n keys def uniqueBSTs(n): n1, n2, sum = 0, 0, 0 # Base cases if (n == 1 or n == 0): return 1 # Find the nth Catalan number for i in range(1, n + 1): # Recursive calls n1 = uniqueBSTs(i - 1) n2 = uniqueBSTs(n - i) sum += n1 * n2 # Return the nth Catalan number return sum # Driver coden = 2 # Function callprint(uniqueBSTs(n)) # This code is contributed by Mohit Kumar // C# implementation of the approachusing System; class GFG { // Function to return the count // of unique BSTs with n keys static int uniqueBSTs(int n) { int n1, n2, sum = 0; // Base cases if (n == 1 || n == 0) return 1; // Find the nth Catalan number for (int i = 1; i <= n; i++) { // Recursive calls n1 = uniqueBSTs(i - 1); n2 = uniqueBSTs(n - i); sum += n1 * n2; } // Return the nth Catalan number return sum; } // Driver code static public void Main() { int n = 2; // Function call Console.WriteLine(uniqueBSTs(n)); }} // This code is contributed by ajit. <script> // Javascript implementation of the approach // Function to return the count // of unique BSTs with n keys function uniqueBSTs(n) { let n1, n2, sum = 0; // Base cases if (n == 1 || n == 0) return 1; // Find the nth Catalan number for (let i = 1; i <= n; i++) { // Recursive calls n1 = uniqueBSTs(i - 1); n2 = uniqueBSTs(n - i); sum += n1 * n2; } // Return the nth Catalan number return sum; } let n = 2; // Function call document.write(uniqueBSTs(n)); </script> 2 The problem can be solved in a dynamic programming way. Here is a snippet of how the recurrence tree will proceed: G(4) / | | \ G(0)G(3) G(1)G(2) G(2)G(1) G(3)G(0) / | \ G(0)G(2) G(1)G(1) G(2)G(0) / \ G(0)G(1) G(1)G(0) // base case Note: Without memoization, the time complexity is upper bounded by O(N x N!).Given a sequence 1...n, to construct a Binary Search Tree (BST) out of the sequence, we could enumerate each number i in the sequence, and use the number as the root, naturally, the subsequence 1...(i-1) on its left side would lay on the left branch of the root, and similarly the right subsequence (i+1)...n lay on the right branch of the root. We then can construct the subtree from the subsequence recursively. Through the above approach, we could ensure that the BST that we construct is all unique since they have unique roots. The problem is to calculate the number of unique BST. To do so, we need to define two functions: 1.G(n): the number of unique BST for a sequence of length n. 2.F(i, n), 1 <= i <= n: The number of unique BST, where the number i is the root of BST, and the sequence ranges from 1 to n. As one can see, G(n) is the actual function we need to calculate in order to solve the problem. And G(n) can be derived from F(i, n), which at the end, would recursively refer to G(n). First of all, given the above definitions, we can see that the total number of unique BST G(n), is the sum of BST F(i) using each number i as a root. i.e., G(n) = F(1, n) + F(2, n) + ... + F(n, n). Given a sequence 1...n, we pick a number i out of the sequence as the root, then the number of unique BST with the specified root F(i), is the cartesian product of the number of BST for its left and right subtrees.For example, F(2, 4): the number of unique BST tree with number 2 as its root. To construct an unique BST out of the entire sequence [1, 2, 3, 4] with 2 as the root, which is to say, we need to construct an unique BST out of its left subsequence [1] and another BST out of the right subsequence [3,4], and then combine them together (i.e. cartesian product). F(i, n) = G(i-1) * G(n-i) 1 <= i <= n Combining the above two formulas, we obtain the recursive formula for G(n). i.e. G(n) = G(0) * G(n-1) + G(1) * G(n-2) + ... + G(n-1) * G(0) In terms of calculation, we need to start with the lower number, since the value of G(n) depends on the values of G(0) ... G(n-1). Below is the above implementation of the above algorithm: C++ Java Python3 C# Javascript // C++ dynamic programming implementation of the approach#include <iostream>using namespace std; // Function to return the count// of unique BSTs with n keysint uniqueBSTs(int n){ // construct a dp array to store the // subsequent results int dparray[n + 1] = { 0 }; // there is only one combination to construct a // BST out of a sequence of dparray[0] = dparray[1] = 1; // length 1 (only a root) or 0 (empty tree). for (int i = 2; i <= n; ++i) { // choosing every value as root for (int k = 1; k <= i; ++k) { dparray[i] += dparray[k - 1] * dparray[i - k]; } } return dparray[n];} // Driver codeint main(){ int n = 2; // Function call cout << uniqueBSTs(n); return 0;} // Java dynamic programming implementation of the approachimport java.io.*;import java.util.*;class GFG{ // Function to return the count // of unique BSTs with n keys static int uniqueBSTs(int n) { // construct a dp array to store the // subsequent results int[] dparray = new int[n + 1]; Arrays.fill(dparray, 0); // there is only one combination to construct a // BST out of a sequence of dparray[0] = dparray[1] = 1; // length 1 (only a root) or 0 (empty tree). for (int i = 2; i <= n; ++i) { // choosing every value as root for (int k = 1; k <= i; ++k) { dparray[i] += dparray[k - 1] * dparray[i - k]; } } return dparray[n]; } // Driver code public static void main (String[] args) { int n = 2; // Function call System.out.println(uniqueBSTs(n)); }} // This code is contributed by avanitrachhadiya2155 # Python3 dynamic programming# implementation of the approach # Function to return the count# of unique BSTs with n keysdef uniqueBSTs(n): # Construct a dp array to store the # subsequent results dparray = [0 for i in range(n + 1)] # There is only one combination to # construct a BST out of a sequence of dparray[0] = 1 dparray[1] = 1 # length 1 (only a root) or 0 (empty tree). for i in range(2, n + 1, 1): # Choosing every value as root for k in range(1, i + 1, 1): dparray[i] += (dparray[k - 1] * dparray[i - k]) return dparray[n] # Driver codeif __name__ == '__main__': n = 2 # Function call print(uniqueBSTs(n)) # This code is contributed by bgangwar59 // C# dynamic programming implementation// of the approachusing System; class GFG{ // Function to return the count// of unique BSTs with n keysstatic int uniqueBSTs(int n){ // construct a dp array to store the // subsequent results int[] dparray = new int[n + 1]; // there is only one combination to // construct a BST out of a sequence of dparray[0] = dparray[1] = 1; // length 1 (only a root) or 0 (empty tree). for(int i = 2; i <= n; ++i) { // Choosing every value as root for(int k = 1; k <= i; ++k) { dparray[i] += dparray[k - 1] * dparray[i - k]; } } return dparray[n];} // Driver codepublic static void Main(String[] args){ int n = 2; // Function call Console.WriteLine(uniqueBSTs(n));}} // This code is contributed by Amit Katiyar <script> // Javascript dynamic programming // implementation of the approach // Function to return the count // of unique BSTs with n keys function uniqueBSTs(n) { // construct a dp array to store the // subsequent results let dparray = new Array(n + 1); dparray.fill(0); // there is only one combination to construct a // BST out of a sequence of dparray[0] = dparray[1] = 1; // length 1 (only a root) or 0 (empty tree). for (let i = 2; i <= n; ++i) { // choosing every value as root for (let k = 1; k <= i; ++k) { dparray[i] += dparray[k - 1] * dparray[i - k]; } } return dparray[n]; } let n = 2; // Function call document.write(uniqueBSTs(n)); </script> 2 Time Complexity: O(N2) Space Complexity: O(N) In this post, we will discuss an O(n) and an O(1) space solution based on Dynamic Programming. We know that the formula for Catalan number for a variable n is which simplifies to Similarly Catalan number for (n-1) nodes = The formula for n nodes can be rewritten as = Catalan number for (n-1) nodes* So for every iteration for ‘i’ going from 1 to n we will store catalan number for ‘i-1’ nodes and compute for ith node. Below is the implementation for the above approach: C++ Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; // Function to find number of unique BSTint numberOfBST(int n){ // For n=1 answer is 1 long v = 1; for (int i = 2; i <= n; i++) { // using previous answer in v to calculate current // catalan number. v = ((v * (i * 2) * (i * 2 - 1)) / ((i + 1) * (i))); } return v;} int main(){ int n = 4; cout << "Number of Unique BST for " << n << " nodes is " << numberOfBST(n) << endl; return 0;} class GFG{ // Function to find number of unique BSTstatic long numberOfBST(int n){ // For n=1 answer is 1 long v = 1; for(int i = 2; i <= n; i++) { // Using previous answer in v to calculate // current catalan number. v = ((v * (i * 2) * (i * 2 - 1)) / ((i + 1) * (i))); } return v;} // Driver codepublic static void main(String[] args){ int n = 4; System.out.print("Number of Unique BST for " + n + " nodes is " + numberOfBST(n) + "\n");}} // This code is contributed by shikhasingrajput # Function to find number of unique BSTdef numberOfBST(n): # For n=1 answer is 1 v = 1 for i in range(2, n + 1): # using previous answer in v to calculate current catalan number. v = ((v * (i * 2) * (i * 2 - 1)) / ((i + 1) * (i))) return int(v) n = 4print("Number of Unique BST for", n, "nodes is", numberOfBST(n)) # This code is contributed by divyesh072019. using System;class GFG { // Function to find number of unique BST static int numberOfBST(int n) { // For n=1 answer is 1 int v = 1; for (int i = 2; i <= n; i++) { // using previous answer in v to calculate current // catalan number. v = ((v * (i * 2) * (i * 2 - 1)) / ((i + 1) * (i))); } return v; } static void Main() { int n = 4; Console.Write("Number of Unique BST for " + n + " nodes is " + numberOfBST(n)); }} // This code is contributed by rameshtravel07. <script> // Function to find number of unique BST function numberOfBST(n) { // For n=1 answer is 1 let v = 1; for (let i = 2; i <= n; i++) { // using previous answer in v to calculate current // catalan number. v = ((v * (i * 2) * (i * 2 - 1)) / ((i + 1) * (i))); } return v; } let n = 4; document.write("Number of Unique BST for " + n + " nodes is " + numberOfBST(n)); // This code is contributed by mukesh07.</script> Number of Unique BST for 4 nodes is 14 Time Complexity: O(n)Auxiliary Space: O(1). jit_t mohit kumar 29 AkashAryan bgangwar59 avanitrachhadiya2155 divyeshrabadiya07 vaibhavrabadiya117 amit143katiyar rahul mishra mukesh07 divyesh072019 rameshtravel07 shikhasingrajput vinayedula catalan Binary Search Tree Competitive Programming Recursion Tree Recursion Binary Search Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Jun, 2022" }, { "code": null, "e": 151, "s": 54, "text": "Given an integer N, the task is to count the number of possible Binary Search Trees with N keys." }, { "code": null, "e": 163, "s": 151, "text": "Examples: " }, { "code": null, "e": 313, "s": 163, "text": "Input: N = 2\nOutput: 2\nFor N = 2, there are 2 unique BSTs\n 1 2 \n \\ /\n 2 1\n\nInput: N = 9\nOutput: 4862" }, { "code": null, "e": 636, "s": 313, "text": "Approach: The number of binary search trees that will be formed with N keys can be calculated by simply evaluating the corresponding number in Catalan Number series. First few Catalan numbers for n = 0, 1, 2, 3, ... are 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, ...Catalan numbers satisfy the following recursive formula: " }, { "code": null, "e": 688, "s": 636, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 692, "s": 688, "text": "C++" }, { "code": null, "e": 697, "s": 692, "text": "Java" }, { "code": null, "e": 705, "s": 697, "text": "Python3" }, { "code": null, "e": 708, "s": 705, "text": "C#" }, { "code": null, "e": 719, "s": 708, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <iostream>using namespace std; // Function to return the count// of unique BSTs with n keysint uniqueBSTs(int n){ int n1, n2, sum = 0; // Base cases if (n == 1 || n == 0) return 1; // Find the nth Catalan number for (int i = 1; i <= n; i++) { // Recursive calls n1 = uniqueBSTs(i - 1); n2 = uniqueBSTs(n - i); sum += n1 * n2; } // Return the nth Catalan number return sum;} // Driver codeint main(){ int n = 2; // Function call cout << uniqueBSTs(n); return 0;}", "e": 1304, "s": 719, "text": null }, { "code": "// Java implementation of the approachimport java.io.*; class GFG { // Function to return the count // of unique BSTs with n keys static int uniqueBSTs(int n) { int n1, n2, sum = 0; // Base cases if (n == 1 || n == 0) return 1; // Find the nth Catalan number for (int i = 1; i <= n; i++) { // Recursive calls n1 = uniqueBSTs(i - 1); n2 = uniqueBSTs(n - i); sum += n1 * n2; } // Return the nth Catalan number return sum; } // Driver code public static void main(String[] args) { int n = 2; // Function call System.out.println(uniqueBSTs(n)); }} // This code is contributed by jit_t.", "e": 2061, "s": 1304, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the count# of unique BSTs with n keys def uniqueBSTs(n): n1, n2, sum = 0, 0, 0 # Base cases if (n == 1 or n == 0): return 1 # Find the nth Catalan number for i in range(1, n + 1): # Recursive calls n1 = uniqueBSTs(i - 1) n2 = uniqueBSTs(n - i) sum += n1 * n2 # Return the nth Catalan number return sum # Driver coden = 2 # Function callprint(uniqueBSTs(n)) # This code is contributed by Mohit Kumar", "e": 2585, "s": 2061, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG { // Function to return the count // of unique BSTs with n keys static int uniqueBSTs(int n) { int n1, n2, sum = 0; // Base cases if (n == 1 || n == 0) return 1; // Find the nth Catalan number for (int i = 1; i <= n; i++) { // Recursive calls n1 = uniqueBSTs(i - 1); n2 = uniqueBSTs(n - i); sum += n1 * n2; } // Return the nth Catalan number return sum; } // Driver code static public void Main() { int n = 2; // Function call Console.WriteLine(uniqueBSTs(n)); }} // This code is contributed by ajit.", "e": 3325, "s": 2585, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the count // of unique BSTs with n keys function uniqueBSTs(n) { let n1, n2, sum = 0; // Base cases if (n == 1 || n == 0) return 1; // Find the nth Catalan number for (let i = 1; i <= n; i++) { // Recursive calls n1 = uniqueBSTs(i - 1); n2 = uniqueBSTs(n - i); sum += n1 * n2; } // Return the nth Catalan number return sum; } let n = 2; // Function call document.write(uniqueBSTs(n)); </script>", "e": 3965, "s": 3325, "text": null }, { "code": null, "e": 3967, "s": 3965, "text": "2" }, { "code": null, "e": 4083, "s": 3967, "text": "The problem can be solved in a dynamic programming way. Here is a snippet of how the recurrence tree will proceed: " }, { "code": null, "e": 4361, "s": 4083, "text": " G(4)\n / | | \\\n G(0)G(3) G(1)G(2) G(2)G(1) G(3)G(0) \n / | \\\n G(0)G(2) G(1)G(1) G(2)G(0) \n / \\\nG(0)G(1) G(1)G(0) // base case " }, { "code": null, "e": 4972, "s": 4361, "text": "Note: Without memoization, the time complexity is upper bounded by O(N x N!).Given a sequence 1...n, to construct a Binary Search Tree (BST) out of the sequence, we could enumerate each number i in the sequence, and use the number as the root, naturally, the subsequence 1...(i-1) on its left side would lay on the left branch of the root, and similarly the right subsequence (i+1)...n lay on the right branch of the root. We then can construct the subtree from the subsequence recursively. Through the above approach, we could ensure that the BST that we construct is all unique since they have unique roots. " }, { "code": null, "e": 5070, "s": 4972, "text": "The problem is to calculate the number of unique BST. To do so, we need to define two functions: " }, { "code": null, "e": 6426, "s": 5070, "text": "1.G(n): the number of unique BST for a \n sequence of length n.\n2.F(i, n), 1 <= i <= n: The number of unique \n BST, where the number i is the root of BST, \n and the sequence ranges from 1 to n. As one can \n see, G(n) is the actual function we need to calculate \n in order to solve the problem. And G(n) can be derived\n from F(i, n), which at the end, would recursively refer \n to G(n).\nFirst of all, given the above definitions, we can see \nthat the total number of unique BST G(n), is the sum of \nBST F(i) using each number i as a root. i.e.,\nG(n) = F(1, n) + F(2, n) + ... + F(n, n).\nGiven a sequence 1...n, we pick a number i out of the \nsequence as the root, then the number of \nunique BST with the specified root F(i), is the \ncartesian product of the number of BST for \nits left and right subtrees.For example, F(2, 4): \nthe number of unique BST tree with number 2 \nas its root. To construct an unique BST out of the \nentire sequence [1, 2, 3, 4] with 2 as the \nroot, which is to say, we need to construct an unique \nBST out of its left subsequence [1] and another BST out \nof the right subsequence [3,4], and then combine them \ntogether (i.e. cartesian \nproduct). F(i, n) = G(i-1) * G(n-i) 1 <= i <= n \nCombining the above two formulas, we obtain the \nrecursive formula for G(n). i.e.\n\nG(n) = G(0) * G(n-1) + G(1) * G(n-2) + ... + G(n-1) * G(0) " }, { "code": null, "e": 6558, "s": 6426, "text": "In terms of calculation, we need to start with the lower number, since the value of G(n) depends on the values of G(0) ... G(n-1). " }, { "code": null, "e": 6616, "s": 6558, "text": "Below is the above implementation of the above algorithm:" }, { "code": null, "e": 6620, "s": 6616, "text": "C++" }, { "code": null, "e": 6625, "s": 6620, "text": "Java" }, { "code": null, "e": 6633, "s": 6625, "text": "Python3" }, { "code": null, "e": 6636, "s": 6633, "text": "C#" }, { "code": null, "e": 6647, "s": 6636, "text": "Javascript" }, { "code": "// C++ dynamic programming implementation of the approach#include <iostream>using namespace std; // Function to return the count// of unique BSTs with n keysint uniqueBSTs(int n){ // construct a dp array to store the // subsequent results int dparray[n + 1] = { 0 }; // there is only one combination to construct a // BST out of a sequence of dparray[0] = dparray[1] = 1; // length 1 (only a root) or 0 (empty tree). for (int i = 2; i <= n; ++i) { // choosing every value as root for (int k = 1; k <= i; ++k) { dparray[i] += dparray[k - 1] * dparray[i - k]; } } return dparray[n];} // Driver codeint main(){ int n = 2; // Function call cout << uniqueBSTs(n); return 0;}", "e": 7409, "s": 6647, "text": null }, { "code": "// Java dynamic programming implementation of the approachimport java.io.*;import java.util.*;class GFG{ // Function to return the count // of unique BSTs with n keys static int uniqueBSTs(int n) { // construct a dp array to store the // subsequent results int[] dparray = new int[n + 1]; Arrays.fill(dparray, 0); // there is only one combination to construct a // BST out of a sequence of dparray[0] = dparray[1] = 1; // length 1 (only a root) or 0 (empty tree). for (int i = 2; i <= n; ++i) { // choosing every value as root for (int k = 1; k <= i; ++k) { dparray[i] += dparray[k - 1] * dparray[i - k]; } } return dparray[n]; } // Driver code public static void main (String[] args) { int n = 2; // Function call System.out.println(uniqueBSTs(n)); }} // This code is contributed by avanitrachhadiya2155", "e": 8450, "s": 7409, "text": null }, { "code": "# Python3 dynamic programming# implementation of the approach # Function to return the count# of unique BSTs with n keysdef uniqueBSTs(n): # Construct a dp array to store the # subsequent results dparray = [0 for i in range(n + 1)] # There is only one combination to # construct a BST out of a sequence of dparray[0] = 1 dparray[1] = 1 # length 1 (only a root) or 0 (empty tree). for i in range(2, n + 1, 1): # Choosing every value as root for k in range(1, i + 1, 1): dparray[i] += (dparray[k - 1] * dparray[i - k]) return dparray[n] # Driver codeif __name__ == '__main__': n = 2 # Function call print(uniqueBSTs(n)) # This code is contributed by bgangwar59", "e": 9251, "s": 8450, "text": null }, { "code": "// C# dynamic programming implementation// of the approachusing System; class GFG{ // Function to return the count// of unique BSTs with n keysstatic int uniqueBSTs(int n){ // construct a dp array to store the // subsequent results int[] dparray = new int[n + 1]; // there is only one combination to // construct a BST out of a sequence of dparray[0] = dparray[1] = 1; // length 1 (only a root) or 0 (empty tree). for(int i = 2; i <= n; ++i) { // Choosing every value as root for(int k = 1; k <= i; ++k) { dparray[i] += dparray[k - 1] * dparray[i - k]; } } return dparray[n];} // Driver codepublic static void Main(String[] args){ int n = 2; // Function call Console.WriteLine(uniqueBSTs(n));}} // This code is contributed by Amit Katiyar", "e": 10121, "s": 9251, "text": null }, { "code": "<script> // Javascript dynamic programming // implementation of the approach // Function to return the count // of unique BSTs with n keys function uniqueBSTs(n) { // construct a dp array to store the // subsequent results let dparray = new Array(n + 1); dparray.fill(0); // there is only one combination to construct a // BST out of a sequence of dparray[0] = dparray[1] = 1; // length 1 (only a root) or 0 (empty tree). for (let i = 2; i <= n; ++i) { // choosing every value as root for (let k = 1; k <= i; ++k) { dparray[i] += dparray[k - 1] * dparray[i - k]; } } return dparray[n]; } let n = 2; // Function call document.write(uniqueBSTs(n)); </script>", "e": 11006, "s": 10121, "text": null }, { "code": null, "e": 11008, "s": 11006, "text": "2" }, { "code": null, "e": 11054, "s": 11008, "text": "Time Complexity: O(N2) Space Complexity: O(N)" }, { "code": null, "e": 11149, "s": 11054, "text": "In this post, we will discuss an O(n) and an O(1) space solution based on Dynamic Programming." }, { "code": null, "e": 11237, "s": 11149, "text": " We know that the formula for Catalan number for a variable n is which simplifies to " }, { "code": null, "e": 11282, "s": 11237, "text": "Similarly Catalan number for (n-1) nodes = " }, { "code": null, "e": 11327, "s": 11282, "text": "The formula for n nodes can be rewritten as " }, { "code": null, "e": 11418, "s": 11327, "text": " = Catalan number for (n-1) nodes* " }, { "code": null, "e": 11538, "s": 11418, "text": "So for every iteration for ‘i’ going from 1 to n we will store catalan number for ‘i-1’ nodes and compute for ith node." }, { "code": null, "e": 11590, "s": 11538, "text": "Below is the implementation for the above approach:" }, { "code": null, "e": 11594, "s": 11590, "text": "C++" }, { "code": null, "e": 11599, "s": 11594, "text": "Java" }, { "code": null, "e": 11607, "s": 11599, "text": "Python3" }, { "code": null, "e": 11610, "s": 11607, "text": "C#" }, { "code": null, "e": 11621, "s": 11610, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; // Function to find number of unique BSTint numberOfBST(int n){ // For n=1 answer is 1 long v = 1; for (int i = 2; i <= n; i++) { // using previous answer in v to calculate current // catalan number. v = ((v * (i * 2) * (i * 2 - 1)) / ((i + 1) * (i))); } return v;} int main(){ int n = 4; cout << \"Number of Unique BST for \" << n << \" nodes is \" << numberOfBST(n) << endl; return 0;}", "e": 12103, "s": 11621, "text": null }, { "code": "class GFG{ // Function to find number of unique BSTstatic long numberOfBST(int n){ // For n=1 answer is 1 long v = 1; for(int i = 2; i <= n; i++) { // Using previous answer in v to calculate // current catalan number. v = ((v * (i * 2) * (i * 2 - 1)) / ((i + 1) * (i))); } return v;} // Driver codepublic static void main(String[] args){ int n = 4; System.out.print(\"Number of Unique BST for \" + n + \" nodes is \" + numberOfBST(n) + \"\\n\");}} // This code is contributed by shikhasingrajput", "e": 12682, "s": 12103, "text": null }, { "code": "# Function to find number of unique BSTdef numberOfBST(n): # For n=1 answer is 1 v = 1 for i in range(2, n + 1): # using previous answer in v to calculate current catalan number. v = ((v * (i * 2) * (i * 2 - 1)) / ((i + 1) * (i))) return int(v) n = 4print(\"Number of Unique BST for\", n, \"nodes is\", numberOfBST(n)) # This code is contributed by divyesh072019.", "e": 13078, "s": 12682, "text": null }, { "code": "using System;class GFG { // Function to find number of unique BST static int numberOfBST(int n) { // For n=1 answer is 1 int v = 1; for (int i = 2; i <= n; i++) { // using previous answer in v to calculate current // catalan number. v = ((v * (i * 2) * (i * 2 - 1)) / ((i + 1) * (i))); } return v; } static void Main() { int n = 4; Console.Write(\"Number of Unique BST for \" + n + \" nodes is \" + numberOfBST(n)); }} // This code is contributed by rameshtravel07.", "e": 13659, "s": 13078, "text": null }, { "code": "<script> // Function to find number of unique BST function numberOfBST(n) { // For n=1 answer is 1 let v = 1; for (let i = 2; i <= n; i++) { // using previous answer in v to calculate current // catalan number. v = ((v * (i * 2) * (i * 2 - 1)) / ((i + 1) * (i))); } return v; } let n = 4; document.write(\"Number of Unique BST for \" + n + \" nodes is \" + numberOfBST(n)); // This code is contributed by mukesh07.</script>", "e": 14184, "s": 13659, "text": null }, { "code": null, "e": 14223, "s": 14184, "text": "Number of Unique BST for 4 nodes is 14" }, { "code": null, "e": 14268, "s": 14223, "text": "Time Complexity: O(n)Auxiliary Space: O(1). " }, { "code": null, "e": 14274, "s": 14268, "text": "jit_t" }, { "code": null, "e": 14289, "s": 14274, "text": "mohit kumar 29" }, { "code": null, "e": 14300, "s": 14289, "text": "AkashAryan" }, { "code": null, "e": 14311, "s": 14300, "text": "bgangwar59" }, { "code": null, "e": 14332, "s": 14311, "text": "avanitrachhadiya2155" }, { "code": null, "e": 14350, "s": 14332, "text": "divyeshrabadiya07" }, { "code": null, "e": 14369, "s": 14350, "text": "vaibhavrabadiya117" }, { "code": null, "e": 14384, "s": 14369, "text": "amit143katiyar" }, { "code": null, "e": 14397, "s": 14384, "text": "rahul mishra" }, { "code": null, "e": 14406, "s": 14397, "text": "mukesh07" }, { "code": null, "e": 14420, "s": 14406, "text": "divyesh072019" }, { "code": null, "e": 14435, "s": 14420, "text": "rameshtravel07" }, { "code": null, "e": 14452, "s": 14435, "text": "shikhasingrajput" }, { "code": null, "e": 14463, "s": 14452, "text": "vinayedula" }, { "code": null, "e": 14471, "s": 14463, "text": "catalan" }, { "code": null, "e": 14490, "s": 14471, "text": "Binary Search Tree" }, { "code": null, "e": 14514, "s": 14490, "text": "Competitive Programming" }, { "code": null, "e": 14524, "s": 14514, "text": "Recursion" }, { "code": null, "e": 14529, "s": 14524, "text": "Tree" }, { "code": null, "e": 14539, "s": 14529, "text": "Recursion" }, { "code": null, "e": 14558, "s": 14539, "text": "Binary Search Tree" }, { "code": null, "e": 14563, "s": 14558, "text": "Tree" } ]
Detect Cycle in a Directed Graph
17 Jun, 2022 Given a directed graph, check whether the graph contains a cycle or not. Your function should return true if the given graph contains at least one cycle, else return false.Example, Input: n = 4, e = 6 0 -> 1, 0 -> 2, 1 -> 2, 2 -> 0, 2 -> 3, 3 -> 3 Output: Yes Explanation: Diagram: The diagram clearly shows a cycle 0 -> 2 -> 0 Input:n = 4, e = 4 0 -> 1, 0 -> 2, 1 -> 2, 2 -> 3 Output:No Explanation: Diagram: The diagram clearly shows no cycle Solution using Depth First Search or DFS Approach: Depth First Traversal can be used to detect a cycle in a Graph. DFS for a connected graph produces a tree. There is a cycle in a graph only if there is a back edge present in the graph. A back edge is an edge that is from a node to itself (self-loop) or one of its ancestors in the tree produced by DFS. In the following graph, there are 3 back edges, marked with a cross sign. We can observe that these 3 back edges indicate 3 cycles present in the graph. For a disconnected graph, Get the DFS forest as output. To detect cycle, check for a cycle in individual trees by checking back edges.To detect a back edge, keep track of vertices currently in the recursion stack of function for DFS traversal. If a vertex is reached that is already in the recursion stack, then there is a cycle in the tree. The edge that connects the current vertex to the vertex in the recursion stack is a back edge. Use recStack[] array to keep track of vertices in the recursion stack.Dry run of the above approach: In the above image there is a mistake node 1 is making a directed edge to 2 not with 0 please make a note. Algorithm: Create the graph using the given number of edges and vertices.Create a recursive function that initializes the current index or vertex, visited, and recursion stack.Mark the current node as visited and also mark the index in recursion stack.Find all the vertices which are not visited and are adjacent to the current node. Recursively call the function for those vertices, If the recursive function returns true, return true.If the adjacent vertices are already marked in the recursion stack then return true.Create a wrapper class, that calls the recursive function for all the vertices and if any function returns true return true. Else if for all vertices the function returns false return false. Create the graph using the given number of edges and vertices.Create a recursive function that initializes the current index or vertex, visited, and recursion stack.Mark the current node as visited and also mark the index in recursion stack.Find all the vertices which are not visited and are adjacent to the current node. Recursively call the function for those vertices, If the recursive function returns true, return true.If the adjacent vertices are already marked in the recursion stack then return true.Create a wrapper class, that calls the recursive function for all the vertices and if any function returns true return true. Else if for all vertices the function returns false return false. Create the graph using the given number of edges and vertices. Create a recursive function that initializes the current index or vertex, visited, and recursion stack. Mark the current node as visited and also mark the index in recursion stack. Find all the vertices which are not visited and are adjacent to the current node. Recursively call the function for those vertices, If the recursive function returns true, return true. If the adjacent vertices are already marked in the recursion stack then return true. Create a wrapper class, that calls the recursive function for all the vertices and if any function returns true return true. Else if for all vertices the function returns false return false. Implementation: C++ Java Python C# Javascript // A C++ Program to detect cycle in a graph#include<bits/stdc++.h> using namespace std; class Graph{ int V; // No. of vertices list<int> *adj; // Pointer to an array containing adjacency lists bool isCyclicUtil(int v, bool visited[], bool *rs); // used by isCyclic()public: Graph(int V); // Constructor void addEdge(int v, int w); // to add an edge to graph bool isCyclic(); // returns true if there is a cycle in this graph}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} // This function is a variation of DFSUtil() in // https://www.geeksforgeeks.org/archives/18212bool Graph::isCyclicUtil(int v, bool visited[], bool *recStack){ if(visited[v] == false) { // Mark the current node as visited and part of recursion stack visited[v] = true; recStack[v] = true; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for(i = adj[v].begin(); i != adj[v].end(); ++i) { if ( !visited[*i] && isCyclicUtil(*i, visited, recStack) ) return true; else if (recStack[*i]) return true; } } recStack[v] = false; // remove the vertex from recursion stack return false;} // Returns true if the graph contains a cycle, else false.// This function is a variation of DFS() in // https://www.geeksforgeeks.org/archives/18212bool Graph::isCyclic(){ // Mark all the vertices as not visited and not part of recursion // stack bool *visited = new bool[V]; bool *recStack = new bool[V]; for(int i = 0; i < V; i++) { visited[i] = false; recStack[i] = false; } // Call the recursive helper function to detect cycle in different // DFS trees for(int i = 0; i < V; i++) if ( !visited[i] && isCyclicUtil(i, visited, recStack)) return true; return false;} int main(){ // Create a graph given in the above diagram Graph g(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); if(g.isCyclic()) cout << "Graph contains cycle"; else cout << "Graph doesn't contain cycle"; return 0;} // A Java Program to detect cycle in a graphimport java.util.ArrayList;import java.util.LinkedList;import java.util.List; class Graph { private final int V; private final List<List<Integer>> adj; public Graph(int V) { this.V = V; adj = new ArrayList<>(V); for (int i = 0; i < V; i++) adj.add(new LinkedList<>()); } // This function is a variation of DFSUtil() in // https://www.geeksforgeeks.org/archives/18212 private boolean isCyclicUtil(int i, boolean[] visited, boolean[] recStack) { // Mark the current node as visited and // part of recursion stack if (recStack[i]) return true; if (visited[i]) return false; visited[i] = true; recStack[i] = true; List<Integer> children = adj.get(i); for (Integer c: children) if (isCyclicUtil(c, visited, recStack)) return true; recStack[i] = false; return false; } private void addEdge(int source, int dest) { adj.get(source).add(dest); } // Returns true if the graph contains a // cycle, else false. // This function is a variation of DFS() in // https://www.geeksforgeeks.org/archives/18212 private boolean isCyclic() { // Mark all the vertices as not visited and // not part of recursion stack boolean[] visited = new boolean[V]; boolean[] recStack = new boolean[V]; // Call the recursive helper function to // detect cycle in different DFS trees for (int i = 0; i < V; i++) if (isCyclicUtil(i, visited, recStack)) return true; return false; } // Driver code public static void main(String[] args) { Graph graph = new Graph(4); graph.addEdge(0, 1); graph.addEdge(0, 2); graph.addEdge(1, 2); graph.addEdge(2, 0); graph.addEdge(2, 3); graph.addEdge(3, 3); if(graph.isCyclic()) System.out.println("Graph contains cycle"); else System.out.println("Graph doesn't " + "contain cycle"); }} // This code is contributed by Sagar Shah. # Python program to detect cycle # in a graph from collections import defaultdict class Graph(): def __init__(self,vertices): self.graph = defaultdict(list) self.V = vertices def addEdge(self,u,v): self.graph[u].append(v) def isCyclicUtil(self, v, visited, recStack): # Mark current node as visited and # adds to recursion stack visited[v] = True recStack[v] = True # Recur for all neighbours # if any neighbour is visited and in # recStack then graph is cyclic for neighbour in self.graph[v]: if visited[neighbour] == False: if self.isCyclicUtil(neighbour, visited, recStack) == True: return True elif recStack[neighbour] == True: return True # The node needs to be popped from # recursion stack before function ends recStack[v] = False return False # Returns true if graph is cyclic else false def isCyclic(self): visited = [False] * (self.V + 1) recStack = [False] * (self.V + 1) for node in range(self.V): if visited[node] == False: if self.isCyclicUtil(node,visited,recStack) == True: return True return False g = Graph(4)g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 2)g.addEdge(2, 0)g.addEdge(2, 3)g.addEdge(3, 3)if g.isCyclic() == 1: print "Graph has a cycle"else: print "Graph has no cycle" # Thanks to Divyanshu Mehta for contributing this code // A C# Program to detect cycle in a graph using System;using System.Collections.Generic; public class Graph { private readonly int V; private readonly List<List<int>> adj; public Graph(int V) { this.V = V; adj = new List<List<int>>(V); for (int i = 0; i < V; i++) adj.Add(new List<int>()); } // This function is a variation of DFSUtil() in // https://www.geeksforgeeks.org/archives/18212 private bool isCyclicUtil(int i, bool[] visited, bool[] recStack) { // Mark the current node as visited and // part of recursion stack if (recStack[i]) return true; if (visited[i]) return false; visited[i] = true; recStack[i] = true; List<int> children = adj[i]; foreach (int c in children) if (isCyclicUtil(c, visited, recStack)) return true; recStack[i] = false; return false; } private void addEdge(int sou, int dest) { adj[sou].Add(dest); } // Returns true if the graph contains a // cycle, else false. // This function is a variation of DFS() in // https://www.geeksforgeeks.org/archives/18212 private bool isCyclic() { // Mark all the vertices as not visited and // not part of recursion stack bool[] visited = new bool[V]; bool[] recStack = new bool[V]; // Call the recursive helper function to // detect cycle in different DFS trees for (int i = 0; i < V; i++) if (isCyclicUtil(i, visited, recStack)) return true; return false; } // Driver code public static void Main(String[] args) { Graph graph = new Graph(4); graph.addEdge(0, 1); graph.addEdge(0, 2); graph.addEdge(1, 2); graph.addEdge(2, 0); graph.addEdge(2, 3); graph.addEdge(3, 3); if(graph.isCyclic()) Console.WriteLine("Graph contains cycle"); else Console.WriteLine("Graph doesn't " + "contain cycle"); } } // This code contributed by Rajput-Ji <script> // A JavaScript Program to detect cycle in a graph let V;let adj=[];function Graph(v){ V=v; for (let i = 0; i < V; i++) adj.push([]);} // This function is a variation of DFSUtil() in // https://www.geeksforgeeks.org/archives/18212function isCyclicUtil(i,visited,recStack){ // Mark the current node as visited and // part of recursion stack if (recStack[i]) return true; if (visited[i]) return false; visited[i] = true; recStack[i] = true; let children = adj[i]; for (let c=0;c< children.length;c++) if (isCyclicUtil(children, visited, recStack)) return true; recStack[i] = false; return false;} function addEdge(source,dest){ adj.push(dest);} // Returns true if the graph contains a // cycle, else false. // This function is a variation of DFS() in // https://www.geeksforgeeks.org/archives/18212function isCyclic(){ // Mark all the vertices as not visited and // not part of recursion stack let visited = new Array(V); let recStack = new Array(V); for(let i=0;i<V;i++) { visited[i]=false; recStack[i]=false; } // Call the recursive helper function to // detect cycle in different DFS trees for (let i = 0; i < V; i++) if (isCyclicUtil(i, visited, recStack)) return true; return false;} // Driver codeGraph(4);addEdge(0, 1);addEdge(0, 2);addEdge(1, 2);addEdge(2, 0);addEdge(2, 3);addEdge(3, 3); if(isCyclic()) document.write("Graph contains cycle");else document.write("Graph doesn't " + "contain cycle"); // This code is contributed by patel2127 </script> Output: Graph contains cycle Complexity Analysis: Time Complexity: O(V+E). Time Complexity of this method is same as time complexity of DFS traversal which is O(V+E).Space Complexity: O(V). To store the visited and recursion stack O(V) space is needed. Time Complexity: O(V+E). Time Complexity of this method is same as time complexity of DFS traversal which is O(V+E). Space Complexity: O(V). To store the visited and recursion stack O(V) space is needed. Detect Cycle in a Directed Graph | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersDetect Cycle in a Directed Graph | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 7:14•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=joqmqvHC_Bo" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> In the below article, another O(V + E) method is discussed : Detect Cycle in a direct graph using colors SagarShah1 AmanjotKaur3 kyungsut Rajput-Ji andrew1234 nailwalhimanshu muhammedazeem nikhilis18 avanitrachhadiya2155 rishi2024csit1073 codingbeastsaysyadav surinderdawra388 hardikkoriintern Adobe Amazon BankBazaar DFS Flipkart graph-cycle MakeMyTrip Microsoft Oracle Rockstand Samsung Graph Flipkart Amazon Microsoft Samsung MakeMyTrip Oracle Adobe BankBazaar Rockstand DFS Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Breadth First Search or BFS for a Graph Depth First Search or DFS for a Graph Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Graph and its representations Find if there is a path between two vertices in a directed graph Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Introduction to Data Structures Floyd Warshall Algorithm | DP-16 Find if there is a path between two vertices in an undirected graph
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Jun, 2022" }, { "code": null, "e": 236, "s": 54, "text": "Given a directed graph, check whether the graph contains a cycle or not. Your function should return true if the given graph contains at least one cycle, else return false.Example, " }, { "code": null, "e": 337, "s": 236, "text": "Input: n = 4, e = 6\n0 -> 1, 0 -> 2, 1 -> 2, 2 -> 0, 2 -> 3, 3 -> 3\nOutput: Yes\nExplanation:\nDiagram:" }, { "code": null, "e": 466, "s": 337, "text": "The diagram clearly shows a cycle 0 -> 2 -> 0\n\nInput:n = 4, e = 4\n0 -> 1, 0 -> 2, 1 -> 2, 2 -> 3\nOutput:No\nExplanation:\nDiagram:" }, { "code": null, "e": 501, "s": 466, "text": "The diagram clearly shows no cycle" }, { "code": null, "e": 542, "s": 501, "text": "Solution using Depth First Search or DFS" }, { "code": null, "e": 1010, "s": 542, "text": "Approach: Depth First Traversal can be used to detect a cycle in a Graph. DFS for a connected graph produces a tree. There is a cycle in a graph only if there is a back edge present in the graph. A back edge is an edge that is from a node to itself (self-loop) or one of its ancestors in the tree produced by DFS. In the following graph, there are 3 back edges, marked with a cross sign. We can observe that these 3 back edges indicate 3 cycles present in the graph. " }, { "code": null, "e": 1550, "s": 1010, "text": "For a disconnected graph, Get the DFS forest as output. To detect cycle, check for a cycle in individual trees by checking back edges.To detect a back edge, keep track of vertices currently in the recursion stack of function for DFS traversal. If a vertex is reached that is already in the recursion stack, then there is a cycle in the tree. The edge that connects the current vertex to the vertex in the recursion stack is a back edge. Use recStack[] array to keep track of vertices in the recursion stack.Dry run of the above approach: " }, { "code": null, "e": 1657, "s": 1550, "text": "In the above image there is a mistake node 1 is making a directed edge to 2 not with 0 please make a note." }, { "code": null, "e": 2368, "s": 1657, "text": "Algorithm: Create the graph using the given number of edges and vertices.Create a recursive function that initializes the current index or vertex, visited, and recursion stack.Mark the current node as visited and also mark the index in recursion stack.Find all the vertices which are not visited and are adjacent to the current node. Recursively call the function for those vertices, If the recursive function returns true, return true.If the adjacent vertices are already marked in the recursion stack then return true.Create a wrapper class, that calls the recursive function for all the vertices and if any function returns true return true. Else if for all vertices the function returns false return false." }, { "code": null, "e": 3068, "s": 2368, "text": "Create the graph using the given number of edges and vertices.Create a recursive function that initializes the current index or vertex, visited, and recursion stack.Mark the current node as visited and also mark the index in recursion stack.Find all the vertices which are not visited and are adjacent to the current node. Recursively call the function for those vertices, If the recursive function returns true, return true.If the adjacent vertices are already marked in the recursion stack then return true.Create a wrapper class, that calls the recursive function for all the vertices and if any function returns true return true. Else if for all vertices the function returns false return false." }, { "code": null, "e": 3131, "s": 3068, "text": "Create the graph using the given number of edges and vertices." }, { "code": null, "e": 3235, "s": 3131, "text": "Create a recursive function that initializes the current index or vertex, visited, and recursion stack." }, { "code": null, "e": 3312, "s": 3235, "text": "Mark the current node as visited and also mark the index in recursion stack." }, { "code": null, "e": 3497, "s": 3312, "text": "Find all the vertices which are not visited and are adjacent to the current node. Recursively call the function for those vertices, If the recursive function returns true, return true." }, { "code": null, "e": 3582, "s": 3497, "text": "If the adjacent vertices are already marked in the recursion stack then return true." }, { "code": null, "e": 3773, "s": 3582, "text": "Create a wrapper class, that calls the recursive function for all the vertices and if any function returns true return true. Else if for all vertices the function returns false return false." }, { "code": null, "e": 3790, "s": 3773, "text": "Implementation: " }, { "code": null, "e": 3794, "s": 3790, "text": "C++" }, { "code": null, "e": 3799, "s": 3794, "text": "Java" }, { "code": null, "e": 3806, "s": 3799, "text": "Python" }, { "code": null, "e": 3809, "s": 3806, "text": "C#" }, { "code": null, "e": 3820, "s": 3809, "text": "Javascript" }, { "code": "// A C++ Program to detect cycle in a graph#include<bits/stdc++.h> using namespace std; class Graph{ int V; // No. of vertices list<int> *adj; // Pointer to an array containing adjacency lists bool isCyclicUtil(int v, bool visited[], bool *rs); // used by isCyclic()public: Graph(int V); // Constructor void addEdge(int v, int w); // to add an edge to graph bool isCyclic(); // returns true if there is a cycle in this graph}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} // This function is a variation of DFSUtil() in // https://www.geeksforgeeks.org/archives/18212bool Graph::isCyclicUtil(int v, bool visited[], bool *recStack){ if(visited[v] == false) { // Mark the current node as visited and part of recursion stack visited[v] = true; recStack[v] = true; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for(i = adj[v].begin(); i != adj[v].end(); ++i) { if ( !visited[*i] && isCyclicUtil(*i, visited, recStack) ) return true; else if (recStack[*i]) return true; } } recStack[v] = false; // remove the vertex from recursion stack return false;} // Returns true if the graph contains a cycle, else false.// This function is a variation of DFS() in // https://www.geeksforgeeks.org/archives/18212bool Graph::isCyclic(){ // Mark all the vertices as not visited and not part of recursion // stack bool *visited = new bool[V]; bool *recStack = new bool[V]; for(int i = 0; i < V; i++) { visited[i] = false; recStack[i] = false; } // Call the recursive helper function to detect cycle in different // DFS trees for(int i = 0; i < V; i++) if ( !visited[i] && isCyclicUtil(i, visited, recStack)) return true; return false;} int main(){ // Create a graph given in the above diagram Graph g(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); if(g.isCyclic()) cout << \"Graph contains cycle\"; else cout << \"Graph doesn't contain cycle\"; return 0;}", "e": 6130, "s": 3820, "text": null }, { "code": "// A Java Program to detect cycle in a graphimport java.util.ArrayList;import java.util.LinkedList;import java.util.List; class Graph { private final int V; private final List<List<Integer>> adj; public Graph(int V) { this.V = V; adj = new ArrayList<>(V); for (int i = 0; i < V; i++) adj.add(new LinkedList<>()); } // This function is a variation of DFSUtil() in // https://www.geeksforgeeks.org/archives/18212 private boolean isCyclicUtil(int i, boolean[] visited, boolean[] recStack) { // Mark the current node as visited and // part of recursion stack if (recStack[i]) return true; if (visited[i]) return false; visited[i] = true; recStack[i] = true; List<Integer> children = adj.get(i); for (Integer c: children) if (isCyclicUtil(c, visited, recStack)) return true; recStack[i] = false; return false; } private void addEdge(int source, int dest) { adj.get(source).add(dest); } // Returns true if the graph contains a // cycle, else false. // This function is a variation of DFS() in // https://www.geeksforgeeks.org/archives/18212 private boolean isCyclic() { // Mark all the vertices as not visited and // not part of recursion stack boolean[] visited = new boolean[V]; boolean[] recStack = new boolean[V]; // Call the recursive helper function to // detect cycle in different DFS trees for (int i = 0; i < V; i++) if (isCyclicUtil(i, visited, recStack)) return true; return false; } // Driver code public static void main(String[] args) { Graph graph = new Graph(4); graph.addEdge(0, 1); graph.addEdge(0, 2); graph.addEdge(1, 2); graph.addEdge(2, 0); graph.addEdge(2, 3); graph.addEdge(3, 3); if(graph.isCyclic()) System.out.println(\"Graph contains cycle\"); else System.out.println(\"Graph doesn't \" + \"contain cycle\"); }} // This code is contributed by Sagar Shah.", "e": 8504, "s": 6130, "text": null }, { "code": "# Python program to detect cycle # in a graph from collections import defaultdict class Graph(): def __init__(self,vertices): self.graph = defaultdict(list) self.V = vertices def addEdge(self,u,v): self.graph[u].append(v) def isCyclicUtil(self, v, visited, recStack): # Mark current node as visited and # adds to recursion stack visited[v] = True recStack[v] = True # Recur for all neighbours # if any neighbour is visited and in # recStack then graph is cyclic for neighbour in self.graph[v]: if visited[neighbour] == False: if self.isCyclicUtil(neighbour, visited, recStack) == True: return True elif recStack[neighbour] == True: return True # The node needs to be popped from # recursion stack before function ends recStack[v] = False return False # Returns true if graph is cyclic else false def isCyclic(self): visited = [False] * (self.V + 1) recStack = [False] * (self.V + 1) for node in range(self.V): if visited[node] == False: if self.isCyclicUtil(node,visited,recStack) == True: return True return False g = Graph(4)g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 2)g.addEdge(2, 0)g.addEdge(2, 3)g.addEdge(3, 3)if g.isCyclic() == 1: print \"Graph has a cycle\"else: print \"Graph has no cycle\" # Thanks to Divyanshu Mehta for contributing this code", "e": 10045, "s": 8504, "text": null }, { "code": "// A C# Program to detect cycle in a graph using System;using System.Collections.Generic; public class Graph { private readonly int V; private readonly List<List<int>> adj; public Graph(int V) { this.V = V; adj = new List<List<int>>(V); for (int i = 0; i < V; i++) adj.Add(new List<int>()); } // This function is a variation of DFSUtil() in // https://www.geeksforgeeks.org/archives/18212 private bool isCyclicUtil(int i, bool[] visited, bool[] recStack) { // Mark the current node as visited and // part of recursion stack if (recStack[i]) return true; if (visited[i]) return false; visited[i] = true; recStack[i] = true; List<int> children = adj[i]; foreach (int c in children) if (isCyclicUtil(c, visited, recStack)) return true; recStack[i] = false; return false; } private void addEdge(int sou, int dest) { adj[sou].Add(dest); } // Returns true if the graph contains a // cycle, else false. // This function is a variation of DFS() in // https://www.geeksforgeeks.org/archives/18212 private bool isCyclic() { // Mark all the vertices as not visited and // not part of recursion stack bool[] visited = new bool[V]; bool[] recStack = new bool[V]; // Call the recursive helper function to // detect cycle in different DFS trees for (int i = 0; i < V; i++) if (isCyclicUtil(i, visited, recStack)) return true; return false; } // Driver code public static void Main(String[] args) { Graph graph = new Graph(4); graph.addEdge(0, 1); graph.addEdge(0, 2); graph.addEdge(1, 2); graph.addEdge(2, 0); graph.addEdge(2, 3); graph.addEdge(3, 3); if(graph.isCyclic()) Console.WriteLine(\"Graph contains cycle\"); else Console.WriteLine(\"Graph doesn't \" + \"contain cycle\"); } } // This code contributed by Rajput-Ji", "e": 12407, "s": 10045, "text": null }, { "code": "<script> // A JavaScript Program to detect cycle in a graph let V;let adj=[];function Graph(v){ V=v; for (let i = 0; i < V; i++) adj.push([]);} // This function is a variation of DFSUtil() in // https://www.geeksforgeeks.org/archives/18212function isCyclicUtil(i,visited,recStack){ // Mark the current node as visited and // part of recursion stack if (recStack[i]) return true; if (visited[i]) return false; visited[i] = true; recStack[i] = true; let children = adj[i]; for (let c=0;c< children.length;c++) if (isCyclicUtil(children, visited, recStack)) return true; recStack[i] = false; return false;} function addEdge(source,dest){ adj.push(dest);} // Returns true if the graph contains a // cycle, else false. // This function is a variation of DFS() in // https://www.geeksforgeeks.org/archives/18212function isCyclic(){ // Mark all the vertices as not visited and // not part of recursion stack let visited = new Array(V); let recStack = new Array(V); for(let i=0;i<V;i++) { visited[i]=false; recStack[i]=false; } // Call the recursive helper function to // detect cycle in different DFS trees for (let i = 0; i < V; i++) if (isCyclicUtil(i, visited, recStack)) return true; return false;} // Driver codeGraph(4);addEdge(0, 1);addEdge(0, 2);addEdge(1, 2);addEdge(2, 0);addEdge(2, 3);addEdge(3, 3); if(isCyclic()) document.write(\"Graph contains cycle\");else document.write(\"Graph doesn't \" + \"contain cycle\"); // This code is contributed by patel2127 </script>", "e": 14249, "s": 12407, "text": null }, { "code": null, "e": 14258, "s": 14249, "text": "Output: " }, { "code": null, "e": 14279, "s": 14258, "text": "Graph contains cycle" }, { "code": null, "e": 14503, "s": 14279, "text": "Complexity Analysis: Time Complexity: O(V+E). Time Complexity of this method is same as time complexity of DFS traversal which is O(V+E).Space Complexity: O(V). To store the visited and recursion stack O(V) space is needed." }, { "code": null, "e": 14620, "s": 14503, "text": "Time Complexity: O(V+E). Time Complexity of this method is same as time complexity of DFS traversal which is O(V+E)." }, { "code": null, "e": 14707, "s": 14620, "text": "Space Complexity: O(V). To store the visited and recursion stack O(V) space is needed." }, { "code": null, "e": 15589, "s": 14707, "text": "Detect Cycle in a Directed Graph | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersDetect Cycle in a Directed Graph | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 7:14•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=joqmqvHC_Bo\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 15695, "s": 15589, "text": "In the below article, another O(V + E) method is discussed : Detect Cycle in a direct graph using colors " }, { "code": null, "e": 15706, "s": 15695, "text": "SagarShah1" }, { "code": null, "e": 15719, "s": 15706, "text": "AmanjotKaur3" }, { "code": null, "e": 15728, "s": 15719, "text": "kyungsut" }, { "code": null, "e": 15738, "s": 15728, "text": "Rajput-Ji" }, { "code": null, "e": 15749, "s": 15738, "text": "andrew1234" }, { "code": null, "e": 15765, "s": 15749, "text": "nailwalhimanshu" }, { "code": null, "e": 15779, "s": 15765, "text": "muhammedazeem" }, { "code": null, "e": 15790, "s": 15779, "text": "nikhilis18" }, { "code": null, "e": 15811, "s": 15790, "text": "avanitrachhadiya2155" }, { "code": null, "e": 15829, "s": 15811, "text": "rishi2024csit1073" }, { "code": null, "e": 15850, "s": 15829, "text": "codingbeastsaysyadav" }, { "code": null, "e": 15867, "s": 15850, "text": "surinderdawra388" }, { "code": null, "e": 15884, "s": 15867, "text": "hardikkoriintern" }, { "code": null, "e": 15890, "s": 15884, "text": "Adobe" }, { "code": null, "e": 15897, "s": 15890, "text": "Amazon" }, { "code": null, "e": 15908, "s": 15897, "text": "BankBazaar" }, { "code": null, "e": 15912, "s": 15908, "text": "DFS" }, { "code": null, "e": 15921, "s": 15912, "text": "Flipkart" }, { "code": null, "e": 15933, "s": 15921, "text": "graph-cycle" }, { "code": null, "e": 15944, "s": 15933, "text": "MakeMyTrip" }, { "code": null, "e": 15954, "s": 15944, "text": "Microsoft" }, { "code": null, "e": 15961, "s": 15954, "text": "Oracle" }, { "code": null, "e": 15971, "s": 15961, "text": "Rockstand" }, { "code": null, "e": 15979, "s": 15971, "text": "Samsung" }, { "code": null, "e": 15985, "s": 15979, "text": "Graph" }, { "code": null, "e": 15994, "s": 15985, "text": "Flipkart" }, { "code": null, "e": 16001, "s": 15994, "text": "Amazon" }, { "code": null, "e": 16011, "s": 16001, "text": "Microsoft" }, { "code": null, "e": 16019, "s": 16011, "text": "Samsung" }, { "code": null, "e": 16030, "s": 16019, "text": "MakeMyTrip" }, { "code": null, "e": 16037, "s": 16030, "text": "Oracle" }, { "code": null, "e": 16043, "s": 16037, "text": "Adobe" }, { "code": null, "e": 16054, "s": 16043, "text": "BankBazaar" }, { "code": null, "e": 16064, "s": 16054, "text": "Rockstand" }, { "code": null, "e": 16068, "s": 16064, "text": "DFS" }, { "code": null, "e": 16074, "s": 16068, "text": "Graph" }, { "code": null, "e": 16172, "s": 16074, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 16212, "s": 16172, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 16250, "s": 16212, "text": "Depth First Search or DFS for a Graph" }, { "code": null, "e": 16301, "s": 16250, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 16352, "s": 16301, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 16382, "s": 16352, "text": "Graph and its representations" }, { "code": null, "e": 16447, "s": 16382, "text": "Find if there is a path between two vertices in a directed graph" }, { "code": null, "e": 16505, "s": 16447, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 16537, "s": 16505, "text": "Introduction to Data Structures" }, { "code": null, "e": 16570, "s": 16537, "text": "Floyd Warshall Algorithm | DP-16" } ]
How to create a weight converter with HTML and JavaScript ?
27 Sep, 2021 Introduction: What we generally call “weight” in our daily lives is theoretically referred to as mass, and it calculates the amount of matter in an object. But we can use mass and weight almost interchangeably by simply multiplying or dividing it by the Earth’s gravitational acceleration, g and this is because of gravitational force the Earth exerts on us is approximately constant. To prevent misunderstanding or unnecessary confusion, we’re talking about mass units, but we’re referring to them as weight units. The weight converter helps you convert between kilograms, grams, pounds, ounces, and stones. All of which are measurements of weight and mass. This is very useful for beginners to train their logic in javascript. Create a Weight Converter Step 1: Add HTML First you have to create an input field to convert a value from one weight measurement to another. HTML <p> <!-- label to input field--> <label>Kilograms</label> <!-- input field to enter the data--> <!-- kiloweightConvert function call function kiloweightConvert to evaluate value--> <input id="Kilograms" type="number" placeholder="Kilograms" oninput="kiloweightConvert(this.value)" onchange="kiloweightConvert(this.value)"></p> The <input> tag use as an input field where the users can enter their data and placeholder is attribute that specifies a short hint that describes the expected value of an <input> element to be enter by user. The oninput is a event occurs when an element gets user input i.e. when the value of an <input> or <textarea> element is changed. In above code this attribute contains value “kiloweightConvert(this.value)” and it works when oninput event triggered. The onchange event is occur when the value of an element has been changed. These both events are similar but the difference is that the oninput event gets activated after the value of an element has changed, while onchange event occurs when the element loses its focus, after the content has been changed. The onchange event is also works on <select> elements. Second, create an output field for result of the conversion. HTML <!--output field--> <p>Pounds: <span id="Pounds"></span></p> <p>Ounces: <span id="Ounces"></span></p> <p>Grams: <span id="Grams"></span></p> <p>Stones: <span id="Stones"></span></p> <span> tag is a generic inline container for inline elements and content which is used to mark up a part of a text, for grouping and applying styles to inline elements. Step 2: Add JavaScript Now, it’s time for build functionality using javascript . The following function will evaluate the value and return result. Javascript //function that evaluate the value and returns resultfunction kiloweightConvert(value) { document.getElementById("Pounds").innerHTML=value*2.2046; document.getElementById("Ounces").innerHTML=value*35.274; document.getElementById("Grams").innerHTML=value*1000; document.getElementById("Stones").innerHTML=value*0.1574;} If you use innerHTML, you can modify the content of the page without refreshing it. This will make the website more responsive and quicker to user inputs. The innerHTML property can also be used along with getElementById() in JavaScript code to refer to an HTML element and modify its contents. The method getElementById() returns an element object that represents an element whose id property matches the specified string. You can also try the following measurements to make a weight converter. To get your head around the conversions between different units, feel free to use the weight conversion chart given below. This conversion table will be very useful in designing the weight converter according to your preferences. Example: Given below shows how to convert a value from Kilogram to other measurements: HTML <!DOCTYPE html><html> <head> <title>Weight Converter</title> <!-- for styling --> <style> span { color: Green; } </style> </head> <body> <!-- Title of your Converter --> <h2 style="color: Green;">Weight Converter</h2> <p>Enter a value in the Kilograms field to convert :</p> <p> <!-- label the input field --> <label>Kilograms</label> <!-- input tag for enter the data --> <!-- kiloweightConvert function call function kiloweightConvert to evaluate value--> <input id="Kilograms" type="number" placeholder="kilograms" oninput="kiloweightConvert(this.value)" onchange="kiloweightConvert(this.value)" /> </p> <!-- output field--> <p>Pounds: <span id="Pounds"></span></p> <p>Ounces: <span id="Ounces"></span></p> <p>Grams: <span id="Grams"></span></p> <p>Stones: <span id="Stones"></span></p> <script> //function that evaluates the weight and return result function kiloweightConvert(value) { document.getElementById("Pounds").innerHTML = value * 2.2046; document.getElementById("Ounces").innerHTML = value * 35.274; document.getElementById("Grams").innerHTML = value * 1000; document.getElementById("Stones").innerHTML = value * 0.1574; } </script> </body></html> Output: sagartomar9927 JavaScript-Misc HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Sep, 2021" }, { "code": null, "e": 43, "s": 28, "text": "Introduction: " }, { "code": null, "e": 545, "s": 43, "text": "What we generally call “weight” in our daily lives is theoretically referred to as mass, and it calculates the amount of matter in an object. But we can use mass and weight almost interchangeably by simply multiplying or dividing it by the Earth’s gravitational acceleration, g and this is because of gravitational force the Earth exerts on us is approximately constant. To prevent misunderstanding or unnecessary confusion, we’re talking about mass units, but we’re referring to them as weight units." }, { "code": null, "e": 758, "s": 545, "text": "The weight converter helps you convert between kilograms, grams, pounds, ounces, and stones. All of which are measurements of weight and mass. This is very useful for beginners to train their logic in javascript." }, { "code": null, "e": 784, "s": 758, "text": "Create a Weight Converter" }, { "code": null, "e": 801, "s": 784, "text": "Step 1: Add HTML" }, { "code": null, "e": 900, "s": 801, "text": "First you have to create an input field to convert a value from one weight measurement to another." }, { "code": null, "e": 905, "s": 900, "text": "HTML" }, { "code": "<p> <!-- label to input field--> <label>Kilograms</label> <!-- input field to enter the data--> <!-- kiloweightConvert function call function kiloweightConvert to evaluate value--> <input id=\"Kilograms\" type=\"number\" placeholder=\"Kilograms\" oninput=\"kiloweightConvert(this.value)\" onchange=\"kiloweightConvert(this.value)\"></p>", "e": 1248, "s": 905, "text": null }, { "code": null, "e": 1457, "s": 1248, "text": "The <input> tag use as an input field where the users can enter their data and placeholder is attribute that specifies a short hint that describes the expected value of an <input> element to be enter by user." }, { "code": null, "e": 1706, "s": 1457, "text": "The oninput is a event occurs when an element gets user input i.e. when the value of an <input> or <textarea> element is changed. In above code this attribute contains value “kiloweightConvert(this.value)” and it works when oninput event triggered." }, { "code": null, "e": 1781, "s": 1706, "text": "The onchange event is occur when the value of an element has been changed." }, { "code": null, "e": 2067, "s": 1781, "text": "These both events are similar but the difference is that the oninput event gets activated after the value of an element has changed, while onchange event occurs when the element loses its focus, after the content has been changed. The onchange event is also works on <select> elements." }, { "code": null, "e": 2128, "s": 2067, "text": "Second, create an output field for result of the conversion." }, { "code": null, "e": 2133, "s": 2128, "text": "HTML" }, { "code": "<!--output field--> <p>Pounds: <span id=\"Pounds\"></span></p> <p>Ounces: <span id=\"Ounces\"></span></p> <p>Grams: <span id=\"Grams\"></span></p> <p>Stones: <span id=\"Stones\"></span></p>", "e": 2318, "s": 2133, "text": null }, { "code": null, "e": 2487, "s": 2318, "text": "<span> tag is a generic inline container for inline elements and content which is used to mark up a part of a text, for grouping and applying styles to inline elements." }, { "code": null, "e": 2510, "s": 2487, "text": "Step 2: Add JavaScript" }, { "code": null, "e": 2634, "s": 2510, "text": "Now, it’s time for build functionality using javascript . The following function will evaluate the value and return result." }, { "code": null, "e": 2645, "s": 2634, "text": "Javascript" }, { "code": "//function that evaluate the value and returns resultfunction kiloweightConvert(value) { document.getElementById(\"Pounds\").innerHTML=value*2.2046; document.getElementById(\"Ounces\").innerHTML=value*35.274; document.getElementById(\"Grams\").innerHTML=value*1000; document.getElementById(\"Stones\").innerHTML=value*0.1574;}", "e": 2968, "s": 2645, "text": null }, { "code": null, "e": 3393, "s": 2968, "text": "If you use innerHTML, you can modify the content of the page without refreshing it. This will make the website more responsive and quicker to user inputs. The innerHTML property can also be used along with getElementById() in JavaScript code to refer to an HTML element and modify its contents. The method getElementById() returns an element object that represents an element whose id property matches the specified string." }, { "code": null, "e": 3466, "s": 3393, "text": "You can also try the following measurements to make a weight converter. " }, { "code": null, "e": 3698, "s": 3466, "text": "To get your head around the conversions between different units, feel free to use the weight conversion chart given below. This conversion table will be very useful in designing the weight converter according to your preferences." }, { "code": null, "e": 3787, "s": 3698, "text": "Example: Given below shows how to convert a value from Kilogram to other measurements: " }, { "code": null, "e": 3792, "s": 3787, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Weight Converter</title> <!-- for styling --> <style> span { color: Green; } </style> </head> <body> <!-- Title of your Converter --> <h2 style=\"color: Green;\">Weight Converter</h2> <p>Enter a value in the Kilograms field to convert :</p> <p> <!-- label the input field --> <label>Kilograms</label> <!-- input tag for enter the data --> <!-- kiloweightConvert function call function kiloweightConvert to evaluate value--> <input id=\"Kilograms\" type=\"number\" placeholder=\"kilograms\" oninput=\"kiloweightConvert(this.value)\" onchange=\"kiloweightConvert(this.value)\" /> </p> <!-- output field--> <p>Pounds: <span id=\"Pounds\"></span></p> <p>Ounces: <span id=\"Ounces\"></span></p> <p>Grams: <span id=\"Grams\"></span></p> <p>Stones: <span id=\"Stones\"></span></p> <script> //function that evaluates the weight and return result function kiloweightConvert(value) { document.getElementById(\"Pounds\").innerHTML = value * 2.2046; document.getElementById(\"Ounces\").innerHTML = value * 35.274; document.getElementById(\"Grams\").innerHTML = value * 1000; document.getElementById(\"Stones\").innerHTML = value * 0.1574; } </script> </body></html>", "e": 5410, "s": 3792, "text": null }, { "code": null, "e": 5419, "s": 5410, "text": "Output: " }, { "code": null, "e": 5436, "s": 5421, "text": "sagartomar9927" }, { "code": null, "e": 5452, "s": 5436, "text": "JavaScript-Misc" }, { "code": null, "e": 5457, "s": 5452, "text": "HTML" }, { "code": null, "e": 5468, "s": 5457, "text": "JavaScript" }, { "code": null, "e": 5485, "s": 5468, "text": "Web Technologies" }, { "code": null, "e": 5490, "s": 5485, "text": "HTML" } ]
How to Use Universal Image Loader Library in Android?
08 Jun, 2022 UIL (Universal Image Loader) is a similar library to that of Picasso and Glide which performs loading images from any web URL into ImageView of Android. This image loading library has been created to provide a powerful, flexible, and customizable solution to load images in Android from Server. This image loading library is being created by an indie developer and it is present in the top list of GitHub. Features of UIL (universal Image Loader) library: This library provides Multi-thread image loading. Image caching can be done in memory and on the user’s device. Listening loading process (including downloading progress). Many customizable features are available for every display image call. Note: 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: Add dependency of UIL Image library in build.gradle file. Navigate to the gradle scripts and then to build.gradle(Module) level. Add below line in build.gradle file in the dependencies section. implementation ‘com.nostra13.universalimageloader:universal-image-loader:1.9.5’ Step 3: Add google repository in the build.gradle file of the application project if by default it is not there buildscript { repositories { google() mavenCentral() } All Jetpack components are available in the Google Maven repository, include them in the build.gradle file allprojects { repositories { google() mavenCentral() } } Step 4: Add internet permission in the AndroidManifest.xml file Navigate to the app > Manifest to open the Manifest file. XML <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.gtappdevelopers.camviewlibrary"> <!--Permission for internet--> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <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/Theme.CamViewLibrary"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Step 5: Create a new ImageView in your activity_main.xml. Navigate to the app > res > layout to open the activity_main.xml file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--Image view for loading our image--> <ImageView android:id="@+id/idImageView" android:layout_width="200dp" android:layout_height="200dp" android:layout_centerInParent="true" android:contentDescription="@string/app_name" /> </RelativeLayout> Step 6: Initialize your ImageView and use UIL(Universal Image Loader) in the MainActivity.java file Navigate to the app > java > your apps package name > MainActivity.java file. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.widget.ImageView;import androidx.appcompat.app.AppCompatActivity;import com.nostra13.universalimageloader.core.DisplayImageOptions;import com.nostra13.universalimageloader.core.ImageLoader;import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; public class MainActivity extends AppCompatActivity { private ImageView img; DisplayImageOptions options; ImageLoader imageLoader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialize image loader before using imageLoader = ImageLoader.getInstance(); imageLoader.init( ImageLoaderConfiguration.createDefault( getApplicationContext())); // initialize imageview from activity_main.xml img = findViewById(R.id.idImageView); // URL for our image that we have to load.. String imageUri = "https://www.geeksforgeeks.org/wp-content/uploads/gfg_200X200-1.png"; // with below method we are setting display option // for our image.. options = new DisplayImageOptions .Builder() // stub image will display when your // image is loading .showStubImage( R.drawable.ic_launcher_foreground) // below image will be displayed when // the image url is empty .showImageForEmptyUri( R.drawable.ic_launcher_background) // cachememory method will caches the // image in users external storage .cacheInMemory() // cache on disc will caches the image // in users internal storage .cacheOnDisc() // build will build the view for // displaying image.. .build(); // below method will display image inside our image // view.. imageLoader.displayImage(imageUri, img, options, null); }} Note: All drawables are present in the drawable folder. You can add the drawable in the drawable folder. To access the drawable folder. Navigate to app > res > drawables > this folder is having all your drawables. hemantjain99 android Picked Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android SDK and it's Components Flutter - Custom Bottom Navigation Bar How to Communicate Between Fragments in Android? Retrofit with Kotlin Coroutine in Android Arrays in Java Arrays.sort() in Java with examples Split() String method in Java with examples Reverse a string in Java Object Oriented Programming (OOPs) Concept in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jun, 2022" }, { "code": null, "e": 484, "s": 28, "text": "UIL (Universal Image Loader) is a similar library to that of Picasso and Glide which performs loading images from any web URL into ImageView of Android. This image loading library has been created to provide a powerful, flexible, and customizable solution to load images in Android from Server. This image loading library is being created by an indie developer and it is present in the top list of GitHub. Features of UIL (universal Image Loader) library:" }, { "code": null, "e": 534, "s": 484, "text": "This library provides Multi-thread image loading." }, { "code": null, "e": 596, "s": 534, "text": "Image caching can be done in memory and on the user’s device." }, { "code": null, "e": 656, "s": 596, "text": "Listening loading process (including downloading progress)." }, { "code": null, "e": 727, "s": 656, "text": "Many customizable features are available for every display image call." }, { "code": null, "e": 798, "s": 727, "text": "Note: We are going to implement this project using the Java language. " }, { "code": null, "e": 827, "s": 798, "text": "Step 1: Create a New Project" }, { "code": null, "e": 989, "s": 827, "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": 1055, "s": 989, "text": "Step 2: Add dependency of UIL Image library in build.gradle file." }, { "code": null, "e": 1191, "s": 1055, "text": "Navigate to the gradle scripts and then to build.gradle(Module) level. Add below line in build.gradle file in the dependencies section." }, { "code": null, "e": 1271, "s": 1191, "text": "implementation ‘com.nostra13.universalimageloader:universal-image-loader:1.9.5’" }, { "code": null, "e": 1383, "s": 1271, "text": "Step 3: Add google repository in the build.gradle file of the application project if by default it is not there" }, { "code": null, "e": 1397, "s": 1383, "text": "buildscript {" }, { "code": null, "e": 1412, "s": 1397, "text": "repositories {" }, { "code": null, "e": 1424, "s": 1412, "text": " google()" }, { "code": null, "e": 1442, "s": 1424, "text": " mavenCentral()" }, { "code": null, "e": 1444, "s": 1442, "text": "}" }, { "code": null, "e": 1551, "s": 1444, "text": "All Jetpack components are available in the Google Maven repository, include them in the build.gradle file" }, { "code": null, "e": 1565, "s": 1551, "text": "allprojects {" }, { "code": null, "e": 1580, "s": 1565, "text": "repositories {" }, { "code": null, "e": 1592, "s": 1580, "text": " google()" }, { "code": null, "e": 1609, "s": 1592, "text": " mavenCentral()" }, { "code": null, "e": 1611, "s": 1609, "text": "}" }, { "code": null, "e": 1613, "s": 1611, "text": "}" }, { "code": null, "e": 1677, "s": 1613, "text": "Step 4: Add internet permission in the AndroidManifest.xml file" }, { "code": null, "e": 1736, "s": 1677, "text": "Navigate to the app > Manifest to open the Manifest file. " }, { "code": null, "e": 1740, "s": 1736, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.gtappdevelopers.camviewlibrary\"> <!--Permission for internet--> <uses-permission android:name=\"android.permission.INTERNET\" /> <uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\"/> <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/Theme.CamViewLibrary\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application> </manifest>", "e": 2643, "s": 1740, "text": null }, { "code": null, "e": 2701, "s": 2643, "text": "Step 5: Create a new ImageView in your activity_main.xml." }, { "code": null, "e": 2823, "s": 2701, "text": "Navigate to the app > res > layout to open the activity_main.xml file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 2827, "s": 2823, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--Image view for loading our image--> <ImageView android:id=\"@+id/idImageView\" android:layout_width=\"200dp\" android:layout_height=\"200dp\" android:layout_centerInParent=\"true\" android:contentDescription=\"@string/app_name\" /> </RelativeLayout>", "e": 3392, "s": 2827, "text": null }, { "code": null, "e": 3492, "s": 3392, "text": "Step 6: Initialize your ImageView and use UIL(Universal Image Loader) in the MainActivity.java file" }, { "code": null, "e": 3695, "s": 3492, "text": "Navigate to the app > java > your apps package name > MainActivity.java file. 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": 3700, "s": 3695, "text": "Java" }, { "code": "import android.os.Bundle;import android.widget.ImageView;import androidx.appcompat.app.AppCompatActivity;import com.nostra13.universalimageloader.core.DisplayImageOptions;import com.nostra13.universalimageloader.core.ImageLoader;import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; public class MainActivity extends AppCompatActivity { private ImageView img; DisplayImageOptions options; ImageLoader imageLoader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialize image loader before using imageLoader = ImageLoader.getInstance(); imageLoader.init( ImageLoaderConfiguration.createDefault( getApplicationContext())); // initialize imageview from activity_main.xml img = findViewById(R.id.idImageView); // URL for our image that we have to load.. String imageUri = \"https://www.geeksforgeeks.org/wp-content/uploads/gfg_200X200-1.png\"; // with below method we are setting display option // for our image.. options = new DisplayImageOptions .Builder() // stub image will display when your // image is loading .showStubImage( R.drawable.ic_launcher_foreground) // below image will be displayed when // the image url is empty .showImageForEmptyUri( R.drawable.ic_launcher_background) // cachememory method will caches the // image in users external storage .cacheInMemory() // cache on disc will caches the image // in users internal storage .cacheOnDisc() // build will build the view for // displaying image.. .build(); // below method will display image inside our image // view.. imageLoader.displayImage(imageUri, img, options, null); }}", "e": 5950, "s": 3700, "text": null }, { "code": null, "e": 6165, "s": 5950, "text": "Note: All drawables are present in the drawable folder. You can add the drawable in the drawable folder. To access the drawable folder. Navigate to app > res > drawables > this folder is having all your drawables. " }, { "code": null, "e": 6178, "s": 6165, "text": "hemantjain99" }, { "code": null, "e": 6186, "s": 6178, "text": "android" }, { "code": null, "e": 6193, "s": 6186, "text": "Picked" }, { "code": null, "e": 6217, "s": 6193, "text": "Technical Scripter 2020" }, { "code": null, "e": 6225, "s": 6217, "text": "Android" }, { "code": null, "e": 6230, "s": 6225, "text": "Java" }, { "code": null, "e": 6249, "s": 6230, "text": "Technical Scripter" }, { "code": null, "e": 6254, "s": 6249, "text": "Java" }, { "code": null, "e": 6262, "s": 6254, "text": "Android" }, { "code": null, "e": 6360, "s": 6262, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6429, "s": 6360, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 6461, "s": 6429, "text": "Android SDK and it's Components" }, { "code": null, "e": 6500, "s": 6461, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 6549, "s": 6500, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 6591, "s": 6549, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 6606, "s": 6591, "text": "Arrays in Java" }, { "code": null, "e": 6642, "s": 6606, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 6686, "s": 6642, "text": "Split() String method in Java with examples" }, { "code": null, "e": 6711, "s": 6686, "text": "Reverse a string in Java" } ]
Multidimensional Collections in Java
22 Nov, 2021 In Java, we have a Collection framework that provides functionality to store a group of objects. This is called a single-dimensional ArrayList where we can have only one element in a row. Geek but what if we want to make a multidimensional ArrayList, for this functionality for which we do have Multidimensional Collections (or Nested Collections) in Java. Multidimensional Collections (or Nested Collections) is a collection of groups of objects where each group can have any number of objects dynamically. Hence, here we can store any number of elements in a group whenever we want. Illustration: Single dimensional ArrayList : [121, 432, 12, 56, 456, 3, 1023] [Apple, Orange, Pear, Mango] Syntax: ArrayList <Object> x = new ArrayList <Object>(); Unlike Arrays, we are not bound with the size of any row in Multidimensional collections. Therefore, if we want to use a Multidimensional architecture where we can create any number of objects dynamically in a row, then we should go for Multidimensional collections in java. Syntax: Multidimensional Collections ArrayList<ArrayList<Object>> a = new ArrayList<ArrayList<Object>>(); Illustration: Multidimensional ArrayList: [[3, 4], [12, 13, 14, 15], [22, 23, 24], [33]] Let us quickly peek onto add() method for multidimensional ArrayList which are as follows: boolean add( ArrayList<Object> e): It is used to insert elements in the specified collection. void add( int index, ArrayList<Object> e): It is used to insert the elements at the specified position in a Collection. Example 1: Java // Java Program to Illustrate Multidimensional ArrayList // Importing required classesimport java.util.*; // Main class// MultidimensionalArrayListclass GFG { // Method 1 // To create and return 2D ArrayList static List create2DArrayList() { // Creating a 2D ArrayList of Integer type ArrayList<ArrayList<Integer> > x = new ArrayList<ArrayList<Integer> >(); // One space allocated for R0 x.add(new ArrayList<Integer>()); // Adding 3 to R0 created above x(R0, C0) x.get(0).add(0, 3); // Creating R1 and adding values // Note: Another way for adding values in 2D // collections x.add( new ArrayList<Integer>(Arrays.asList(3, 4, 6))); // Adding 366 to x(R1, C0) x.get(1).add(0, 366); // Adding 576 to x(R1, C4) x.get(1).add(4, 576); // Now, adding values to R2 x.add(2, new ArrayList<>(Arrays.asList(3, 84))); // Adding values to R3 x.add(new ArrayList<Integer>( Arrays.asList(83, 6684, 776))); // Adding values to R4 x.add(new ArrayList<>(Arrays.asList(8))); // Appending values to R4 x.get(4).addAll(Arrays.asList(9, 10, 11)); // Appending values to R1, but start appending from // C3 x.get(1).addAll(3, Arrays.asList(22, 1000)); // This method will return 2D array return x; } // Method 2 // Main driver method public static void main(String args[]) { // Display message prior for better readability System.out.println("2D ArrayList :"); // Printing 2D ArrayList by calling Method 1 System.out.println(create2DArrayList()); }} 2D ArrayList : [[3], [366, 3, 4, 22, 1000, 6, 576], [3, 84], [83, 6684, 776], [8, 9, 10, 11]] Now let us see the same implementation of multidimensional LinkedHashSet and in order to show how it behaves differently. Similarly, we can implement any other Collection as Multidimensional Collection as depicted below: Syntax: HashSet< HashSet<Object> > a = new HashSet< HashSet<Object> >(); Note: LinkedHashSet class contains unique elements & maintains insertion order. Therefore, in Multidimensional LinkedHashSet uniqueness will be maintained inside rows also. Example 2: Java // Java Program to Illustrate Multidimensional LinkedHashSet // Importing required classesimport java.util.*; // Main class// Multidimensional LinkedHashSetclass GFG { // Method 1 // To create and return 2D LinkedHashSet static Set create2DLinkedHashSet() { // Creating an empty 2D LinkedHashSet LinkedHashSet<LinkedHashSet<String> > x = new LinkedHashSet<LinkedHashSet<String> >(); // Creating R0 x.add(new LinkedHashSet<String>( Arrays.asList("Apple", "Orange"))); // Creating R1, here "Coffee" will be considered as // only one object to maintain uniqueness x.add(new LinkedHashSet<String>(Arrays.asList( "Tea", "Coffee", "Milk", "Coffee", "Water"))); // Creating R2 x.add(new LinkedHashSet<String>( Arrays.asList("Tomato", "Potato", "Onion"))); // Creating R3 but it will not be added as it // contains the same items as R2 // Note: LinkedHashSet inserts only unique items x.add(new LinkedHashSet<String>( Arrays.asList("Tomato", "Potato", "Onion"))); // Returning multidimensional LinkedHashSet return x; } // Method 2 // Main driver method public static void main(String[] args) { // Display message for better readability System.out.println("2D LinkedHashSet :"); // Printing 2D LinkedHashSet by // calling method 1 System.out.println(create2DLinkedHashSet()); }} 2D LinkedHashSet : [[Apple, Orange], [Tea, Coffee, Milk, Water], [Tomato, Potato, Onion]] Sagar_Gupta solankimayank kashishsoda Java - util package Java-Collections Data Structures Java Data Structures Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Nov, 2021" }, { "code": null, "e": 410, "s": 52, "text": "In Java, we have a Collection framework that provides functionality to store a group of objects. This is called a single-dimensional ArrayList where we can have only one element in a row. Geek but what if we want to make a multidimensional ArrayList, for this functionality for which we do have Multidimensional Collections (or Nested Collections) in Java. " }, { "code": null, "e": 638, "s": 410, "text": "Multidimensional Collections (or Nested Collections) is a collection of groups of objects where each group can have any number of objects dynamically. Hence, here we can store any number of elements in a group whenever we want." }, { "code": null, "e": 652, "s": 638, "text": "Illustration:" }, { "code": null, "e": 749, "s": 652, "text": "Single dimensional ArrayList :\n [121, 432, 12, 56, 456, 3, 1023]\n [Apple, Orange, Pear, Mango]" }, { "code": null, "e": 759, "s": 749, "text": "Syntax: " }, { "code": null, "e": 808, "s": 759, "text": "ArrayList <Object> x = new ArrayList <Object>();" }, { "code": null, "e": 1083, "s": 808, "text": "Unlike Arrays, we are not bound with the size of any row in Multidimensional collections. Therefore, if we want to use a Multidimensional architecture where we can create any number of objects dynamically in a row, then we should go for Multidimensional collections in java." }, { "code": null, "e": 1120, "s": 1083, "text": "Syntax: Multidimensional Collections" }, { "code": null, "e": 1189, "s": 1120, "text": "ArrayList<ArrayList<Object>> a = new ArrayList<ArrayList<Object>>();" }, { "code": null, "e": 1204, "s": 1189, "text": "Illustration: " }, { "code": null, "e": 1279, "s": 1204, "text": "Multidimensional ArrayList: [[3, 4], [12, 13, 14, 15], [22, 23, 24], [33]]" }, { "code": null, "e": 1371, "s": 1279, "text": " Let us quickly peek onto add() method for multidimensional ArrayList which are as follows:" }, { "code": null, "e": 1465, "s": 1371, "text": "boolean add( ArrayList<Object> e): It is used to insert elements in the specified collection." }, { "code": null, "e": 1585, "s": 1465, "text": "void add( int index, ArrayList<Object> e): It is used to insert the elements at the specified position in a Collection." }, { "code": null, "e": 1596, "s": 1585, "text": "Example 1:" }, { "code": null, "e": 1601, "s": 1596, "text": "Java" }, { "code": "// Java Program to Illustrate Multidimensional ArrayList // Importing required classesimport java.util.*; // Main class// MultidimensionalArrayListclass GFG { // Method 1 // To create and return 2D ArrayList static List create2DArrayList() { // Creating a 2D ArrayList of Integer type ArrayList<ArrayList<Integer> > x = new ArrayList<ArrayList<Integer> >(); // One space allocated for R0 x.add(new ArrayList<Integer>()); // Adding 3 to R0 created above x(R0, C0) x.get(0).add(0, 3); // Creating R1 and adding values // Note: Another way for adding values in 2D // collections x.add( new ArrayList<Integer>(Arrays.asList(3, 4, 6))); // Adding 366 to x(R1, C0) x.get(1).add(0, 366); // Adding 576 to x(R1, C4) x.get(1).add(4, 576); // Now, adding values to R2 x.add(2, new ArrayList<>(Arrays.asList(3, 84))); // Adding values to R3 x.add(new ArrayList<Integer>( Arrays.asList(83, 6684, 776))); // Adding values to R4 x.add(new ArrayList<>(Arrays.asList(8))); // Appending values to R4 x.get(4).addAll(Arrays.asList(9, 10, 11)); // Appending values to R1, but start appending from // C3 x.get(1).addAll(3, Arrays.asList(22, 1000)); // This method will return 2D array return x; } // Method 2 // Main driver method public static void main(String args[]) { // Display message prior for better readability System.out.println(\"2D ArrayList :\"); // Printing 2D ArrayList by calling Method 1 System.out.println(create2DArrayList()); }}", "e": 3323, "s": 1601, "text": null }, { "code": null, "e": 3417, "s": 3323, "text": "2D ArrayList :\n[[3], [366, 3, 4, 22, 1000, 6, 576], [3, 84], [83, 6684, 776], [8, 9, 10, 11]]" }, { "code": null, "e": 3640, "s": 3417, "text": " Now let us see the same implementation of multidimensional LinkedHashSet and in order to show how it behaves differently. Similarly, we can implement any other Collection as Multidimensional Collection as depicted below: " }, { "code": null, "e": 3649, "s": 3640, "text": "Syntax: " }, { "code": null, "e": 3715, "s": 3649, "text": "HashSet< HashSet<Object> > a = new HashSet< HashSet<Object> >(); " }, { "code": null, "e": 3888, "s": 3715, "text": "Note: LinkedHashSet class contains unique elements & maintains insertion order. Therefore, in Multidimensional LinkedHashSet uniqueness will be maintained inside rows also." }, { "code": null, "e": 3899, "s": 3888, "text": "Example 2:" }, { "code": null, "e": 3904, "s": 3899, "text": "Java" }, { "code": "// Java Program to Illustrate Multidimensional LinkedHashSet // Importing required classesimport java.util.*; // Main class// Multidimensional LinkedHashSetclass GFG { // Method 1 // To create and return 2D LinkedHashSet static Set create2DLinkedHashSet() { // Creating an empty 2D LinkedHashSet LinkedHashSet<LinkedHashSet<String> > x = new LinkedHashSet<LinkedHashSet<String> >(); // Creating R0 x.add(new LinkedHashSet<String>( Arrays.asList(\"Apple\", \"Orange\"))); // Creating R1, here \"Coffee\" will be considered as // only one object to maintain uniqueness x.add(new LinkedHashSet<String>(Arrays.asList( \"Tea\", \"Coffee\", \"Milk\", \"Coffee\", \"Water\"))); // Creating R2 x.add(new LinkedHashSet<String>( Arrays.asList(\"Tomato\", \"Potato\", \"Onion\"))); // Creating R3 but it will not be added as it // contains the same items as R2 // Note: LinkedHashSet inserts only unique items x.add(new LinkedHashSet<String>( Arrays.asList(\"Tomato\", \"Potato\", \"Onion\"))); // Returning multidimensional LinkedHashSet return x; } // Method 2 // Main driver method public static void main(String[] args) { // Display message for better readability System.out.println(\"2D LinkedHashSet :\"); // Printing 2D LinkedHashSet by // calling method 1 System.out.println(create2DLinkedHashSet()); }}", "e": 5410, "s": 3904, "text": null }, { "code": null, "e": 5500, "s": 5410, "text": "2D LinkedHashSet :\n[[Apple, Orange], [Tea, Coffee, Milk, Water], [Tomato, Potato, Onion]]" }, { "code": null, "e": 5512, "s": 5500, "text": "Sagar_Gupta" }, { "code": null, "e": 5526, "s": 5512, "text": "solankimayank" }, { "code": null, "e": 5538, "s": 5526, "text": "kashishsoda" }, { "code": null, "e": 5558, "s": 5538, "text": "Java - util package" }, { "code": null, "e": 5575, "s": 5558, "text": "Java-Collections" }, { "code": null, "e": 5591, "s": 5575, "text": "Data Structures" }, { "code": null, "e": 5596, "s": 5591, "text": "Java" }, { "code": null, "e": 5612, "s": 5596, "text": "Data Structures" }, { "code": null, "e": 5617, "s": 5612, "text": "Java" }, { "code": null, "e": 5634, "s": 5617, "text": "Java-Collections" } ]
How to set the Alignment of the Text in RadioButton in C#?
30 Jun, 2019 In Windows Forms, RadioButton control is used to select a single option among the group of the options. For example, select your gender from the given list, so you will choose only one option among three options like Male or Female or Transgender. In Windows Forms, you are allowed to adjust the alignment of the RadioButton using the TextAlign Property of the RadioButton.The value of this property is specified by the ContentAlignment enum, it contains 9 different types of values for text alignment, i.e, BottomCenter, BottomLeft, BottomRight, MiddleCenter, MiddleLeft, MiddleRight, TopCenter, TopLeft, and TopRight. The default value of this property is MiddleLeft. You can set this property in two different ways: 1. Design-Time: It is the easiest way to set the alignment of the text of the RadioButton as shown in the following steps: Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Drag the RadioButton control from the ToolBox and drop it on the windows form. You are allowed to place a RadioButton control anywhere on the windows form according to your need. Step 3: After drag and drop you will go to the properties of the RadioButton control to set the alignment of the text of the RadioButton.Output: Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the alignment of the text of the RadioButton control programmatically with the help of given syntax: public override System.Drawing.ContentAlignment TextAlign { get; set; } Here, ContentAlignment is the ContentAlignment’s values. It will throw an InvalidEnumArgumentException if the value doesn’t belong to ContentAlignment’s values. The following steps show how to set the alignment of the text of the RadioButton dynamically: Step 1: Create a radio button using the RadioButton() constructor is provided by the RadioButton class.// Creating radio button RadioButton r1 = new RadioButton(); // Creating radio button RadioButton r1 = new RadioButton(); Step 2: After creating RadioButton, set the TextAlign property of the RadioButton provided by the RadioButton class.// Setting the alignment of the text of the radio button r2.TextAlign = ContentAlignment.MiddleLeft; // Setting the alignment of the text of the radio button r2.TextAlign = ContentAlignment.MiddleLeft; Step 3: And last add this RadioButton control to the form using Add() method.// Add this radio button to the form this.Controls.Add(r1); Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp23 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting label Label l = new Label(); l.AutoSize = true; l.Location = new Point(176, 40); l.Text = "Select Post"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the // properties of the RadioButton RadioButton r1 = new RadioButton(); r1.AutoSize = true; r1.Text = "Intern"; r1.Location = new Point(286, 40); r1.TextAlign = ContentAlignment.MiddleLeft; // Adding this label to the form this.Controls.Add(r1); // Creating and setting the // properties of the RadioButton RadioButton r2 = new RadioButton(); r2.AutoSize = true; r2.Text = "Team Leader"; r2.Location = new Point(356, 40); r2.TextAlign = ContentAlignment.MiddleLeft; // Adding this label to the form this.Controls.Add(r2); // Creating and setting the // properties of the RadioButton RadioButton r3 = new RadioButton(); r3.AutoSize = true; r3.Text = "Software Engineer"; r3.Location = new Point(470, 40); r3.TextAlign = ContentAlignment.MiddleLeft; // Adding this label to the form this.Controls.Add(r3); }}}Output: // Add this radio button to the form this.Controls.Add(r1); Example: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp23 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting label Label l = new Label(); l.AutoSize = true; l.Location = new Point(176, 40); l.Text = "Select Post"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the // properties of the RadioButton RadioButton r1 = new RadioButton(); r1.AutoSize = true; r1.Text = "Intern"; r1.Location = new Point(286, 40); r1.TextAlign = ContentAlignment.MiddleLeft; // Adding this label to the form this.Controls.Add(r1); // Creating and setting the // properties of the RadioButton RadioButton r2 = new RadioButton(); r2.AutoSize = true; r2.Text = "Team Leader"; r2.Location = new Point(356, 40); r2.TextAlign = ContentAlignment.MiddleLeft; // Adding this label to the form this.Controls.Add(r2); // Creating and setting the // properties of the RadioButton RadioButton r3 = new RadioButton(); r3.AutoSize = true; r3.Text = "Software Engineer"; r3.Location = new Point(470, 40); r3.TextAlign = ContentAlignment.MiddleLeft; // Adding this label to the form this.Controls.Add(r3); }}} Output: C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Delegates Introduction to .NET Framework C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework C# | Method Overriding C# | String.IndexOf( ) Method | Set - 1 C# | Constructors C# | Class and Object Extension Method in C# C# | Replace() Method
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jun, 2019" }, { "code": null, "e": 747, "s": 28, "text": "In Windows Forms, RadioButton control is used to select a single option among the group of the options. For example, select your gender from the given list, so you will choose only one option among three options like Male or Female or Transgender. In Windows Forms, you are allowed to adjust the alignment of the RadioButton using the TextAlign Property of the RadioButton.The value of this property is specified by the ContentAlignment enum, it contains 9 different types of values for text alignment, i.e, BottomCenter, BottomLeft, BottomRight, MiddleCenter, MiddleLeft, MiddleRight, TopCenter, TopLeft, and TopRight. The default value of this property is MiddleLeft. You can set this property in two different ways:" }, { "code": null, "e": 870, "s": 747, "text": "1. Design-Time: It is the easiest way to set the alignment of the text of the RadioButton as shown in the following steps:" }, { "code": null, "e": 986, "s": 870, "text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 1173, "s": 986, "text": "Step 2: Drag the RadioButton control from the ToolBox and drop it on the windows form. You are allowed to place a RadioButton control anywhere on the windows form according to your need." }, { "code": null, "e": 1318, "s": 1173, "text": "Step 3: After drag and drop you will go to the properties of the RadioButton control to set the alignment of the text of the RadioButton.Output:" }, { "code": null, "e": 1326, "s": 1318, "text": "Output:" }, { "code": null, "e": 1519, "s": 1326, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the alignment of the text of the RadioButton control programmatically with the help of given syntax:" }, { "code": null, "e": 1591, "s": 1519, "text": "public override System.Drawing.ContentAlignment TextAlign { get; set; }" }, { "code": null, "e": 1846, "s": 1591, "text": "Here, ContentAlignment is the ContentAlignment’s values. It will throw an InvalidEnumArgumentException if the value doesn’t belong to ContentAlignment’s values. The following steps show how to set the alignment of the text of the RadioButton dynamically:" }, { "code": null, "e": 2011, "s": 1846, "text": "Step 1: Create a radio button using the RadioButton() constructor is provided by the RadioButton class.// Creating radio button\nRadioButton r1 = new RadioButton();\n" }, { "code": null, "e": 2073, "s": 2011, "text": "// Creating radio button\nRadioButton r1 = new RadioButton();\n" }, { "code": null, "e": 2291, "s": 2073, "text": "Step 2: After creating RadioButton, set the TextAlign property of the RadioButton provided by the RadioButton class.// Setting the alignment of the text of the radio button\nr2.TextAlign = ContentAlignment.MiddleLeft;\n" }, { "code": null, "e": 2393, "s": 2291, "text": "// Setting the alignment of the text of the radio button\nr2.TextAlign = ContentAlignment.MiddleLeft;\n" }, { "code": null, "e": 4242, "s": 2393, "text": "Step 3: And last add this RadioButton control to the form using Add() method.// Add this radio button to the form\nthis.Controls.Add(r1);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp23 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting label Label l = new Label(); l.AutoSize = true; l.Location = new Point(176, 40); l.Text = \"Select Post\"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the // properties of the RadioButton RadioButton r1 = new RadioButton(); r1.AutoSize = true; r1.Text = \"Intern\"; r1.Location = new Point(286, 40); r1.TextAlign = ContentAlignment.MiddleLeft; // Adding this label to the form this.Controls.Add(r1); // Creating and setting the // properties of the RadioButton RadioButton r2 = new RadioButton(); r2.AutoSize = true; r2.Text = \"Team Leader\"; r2.Location = new Point(356, 40); r2.TextAlign = ContentAlignment.MiddleLeft; // Adding this label to the form this.Controls.Add(r2); // Creating and setting the // properties of the RadioButton RadioButton r3 = new RadioButton(); r3.AutoSize = true; r3.Text = \"Software Engineer\"; r3.Location = new Point(470, 40); r3.TextAlign = ContentAlignment.MiddleLeft; // Adding this label to the form this.Controls.Add(r3); }}}Output:" }, { "code": null, "e": 4303, "s": 4242, "text": "// Add this radio button to the form\nthis.Controls.Add(r1);\n" }, { "code": null, "e": 4312, "s": 4303, "text": "Example:" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp23 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting label Label l = new Label(); l.AutoSize = true; l.Location = new Point(176, 40); l.Text = \"Select Post\"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the // properties of the RadioButton RadioButton r1 = new RadioButton(); r1.AutoSize = true; r1.Text = \"Intern\"; r1.Location = new Point(286, 40); r1.TextAlign = ContentAlignment.MiddleLeft; // Adding this label to the form this.Controls.Add(r1); // Creating and setting the // properties of the RadioButton RadioButton r2 = new RadioButton(); r2.AutoSize = true; r2.Text = \"Team Leader\"; r2.Location = new Point(356, 40); r2.TextAlign = ContentAlignment.MiddleLeft; // Adding this label to the form this.Controls.Add(r2); // Creating and setting the // properties of the RadioButton RadioButton r3 = new RadioButton(); r3.AutoSize = true; r3.Text = \"Software Engineer\"; r3.Location = new Point(470, 40); r3.TextAlign = ContentAlignment.MiddleLeft; // Adding this label to the form this.Controls.Add(r3); }}}", "e": 6009, "s": 4312, "text": null }, { "code": null, "e": 6017, "s": 6009, "text": "Output:" }, { "code": null, "e": 6020, "s": 6017, "text": "C#" }, { "code": null, "e": 6118, "s": 6020, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6133, "s": 6118, "text": "C# | Delegates" }, { "code": null, "e": 6164, "s": 6133, "text": "Introduction to .NET Framework" }, { "code": null, "e": 6207, "s": 6164, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 6256, "s": 6207, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 6279, "s": 6256, "text": "C# | Method Overriding" }, { "code": null, "e": 6319, "s": 6279, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 6337, "s": 6319, "text": "C# | Constructors" }, { "code": null, "e": 6359, "s": 6337, "text": "C# | Class and Object" }, { "code": null, "e": 6382, "s": 6359, "text": "Extension Method in C#" } ]
Python | Grid Layout in Kivy without .kv file
11 Aug, 2021 Kivy is a platform independent as it can be run on Android, IOS, linux and Windows etc. Kivy provides you the functionality to write the code for once and run it on different platforms. It is basically used to develop the Android application, but it Does not mean that it can not be used on Desktops applications. ???????? Kivy Tutorial – Learn Kivy with Examples. The widget must be placed in a specific column/row. Each child is automatically assigned a position determined by the layout configuration and the child’s index in the children list. Grid Layout must always contain any one of the below input constraints: GridLayout.cols or GridLayout.rows. If you do not specify cols or rows, the Layout will throw an exception. The GridLayout arranges children in a matrix. It takes the available space and divides it into columns and rows, then adds widgets to the resulting “cells”. The row and columns are just like the same as we observe in a matrix, here we can adjust the size of each grid. Initial the size is given by the col_default_width and row_default_height properties. We can force the default size by setting the col_force_default or row_force_default property. This will force the layout to ignore the width and size_hint properties of children and use the default size. The first thing we need to do to use a GridLayout is to import it. from kivy.uix.gridlayout import GridLayout Basic Approach to create GridLayout: 1) import kivy 2) import kivyApp 3) import button 4) import Gridlayout 5) Set minimum version(optional) 6) create App class: - define build function : add widget (Buttons) 7) return Layout/widget/Class(according to requirement) 8) Run an instance of the class Implementation of the approach –Code #1: In the example below, all widgets will have an equal size. By default, the size_hint is (1, 1), so a Widget will take the full size of the parent: Python3 # Sample Python application demonstrating # How to create GridLayout in Kivy # import kivy moduleimport kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # creates the button in kivy # if not imported shows the error from kivy.uix.button import Button # The GridLayout arranges children in a matrix.# It takes the available space and# divides it into columns and rows,# then adds widgets to the resulting “cells”.from kivy.uix.gridlayout import GridLayout # creating the App classclass Grid_LayoutApp(App): # to build the application we have to # return a widget on the build() function. def build(self): # adding GridLayouts in App # Defining number of column # You can use row as well depends on need layout = GridLayout(cols = 2) # 1st row layout.add_widget(Button(text ='Hello 1')) layout.add_widget(Button(text ='World 1')) # 2nd row layout.add_widget(Button(text ='Hello 2')) layout.add_widget(Button(text ='World 2')) # 3rd row layout.add_widget(Button(text ='Hello 3')) layout.add_widget(Button(text ='World 3')) # 4th row layout.add_widget(Button(text ='Hello 4')) layout.add_widget(Button(text ='World 4')) # returning the layout return layout # creating object of the App classroot = Grid_LayoutApp()# run the Approot.run() Output: Now just change the class code in the above code with the code #2 and code#3 other than that all will be same as code#1 and run the code after changes you will get the below results. Code #2: Now, let’s fix the size of Hello buttons to 100px instead of using size_hint_x=1: Python3 # creating the App classclass Grid_LayoutApp(App): # to build the application we have to # return a widget on the build() function. def build(self): # adding GridLayouts in App # Defining number of column # You can use row as well depends on need layout = GridLayout(cols = 2) # 1st row layout.add_widget(Button(text ='Hello 1', size_hint_x = None, width = 100)) layout.add_widget(Button(text ='World 1')) # 2nd row layout.add_widget(Button(text ='Hello 2', size_hint_x = None, width = 100)) layout.add_widget(Button(text ='World 2')) # 3rd row layout.add_widget(Button(text ='Hello 3', size_hint_x = None, width = 100)) layout.add_widget(Button(text ='World 3')) # 4th row layout.add_widget(Button(text ='Hello 4', size_hint_x = None, width = 100)) layout.add_widget(Button(text ='World 4')) # returning the layout return layout Output: Code #3: Now, let’s fix the row height to a specific size: Python3 # creating the App classclass Grid_LayoutApp(App): # to build the application we have to # return a widget on the build() function. def build(self): # adding GridLayouts in App # Defining number of column and size of the buttons i.e height layout = GridLayout(cols = 2, row_force_default = True, row_default_height = 30) # 1st row layout.add_widget(Button(text ='Hello 1', size_hint_x = None, width = 100)) layout.add_widget(Button(text ='World 1')) # 2nd row layout.add_widget(Button(text ='Hello 2', size_hint_x = None, width = 100)) layout.add_widget(Button(text ='World 2')) # 3rd row layout.add_widget(Button(text ='Hello 3', size_hint_x = None, width = 100)) layout.add_widget(Button(text ='World 3')) # 4th row layout.add_widget(Button(text ='Hello 4', size_hint_x = None, width = 100)) layout.add_widget(Button(text ='World 4')) # returning the layout return layout Output: Reference: https://kivy.org/doc/stable/api-kivy.uix.gridlayout.html sweetyty anikakapoor Python-gui Python-kivy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Aug, 2021" }, { "code": null, "e": 343, "s": 28, "text": "Kivy is a platform independent as it can be run on Android, IOS, linux and Windows etc. Kivy provides you the functionality to write the code for once and run it on different platforms. It is basically used to develop the Android application, but it Does not mean that it can not be used on Desktops applications. " }, { "code": null, "e": 394, "s": 343, "text": "???????? Kivy Tutorial – Learn Kivy with Examples." }, { "code": null, "e": 577, "s": 394, "text": "The widget must be placed in a specific column/row. Each child is automatically assigned a position determined by the layout configuration and the child’s index in the children list." }, { "code": null, "e": 757, "s": 577, "text": "Grid Layout must always contain any one of the below input constraints: GridLayout.cols or GridLayout.rows. If you do not specify cols or rows, the Layout will throw an exception." }, { "code": null, "e": 914, "s": 757, "text": "The GridLayout arranges children in a matrix. It takes the available space and divides it into columns and rows, then adds widgets to the resulting “cells”." }, { "code": null, "e": 1026, "s": 914, "text": "The row and columns are just like the same as we observe in a matrix, here we can adjust the size of each grid." }, { "code": null, "e": 1316, "s": 1026, "text": "Initial the size is given by the col_default_width and row_default_height properties. We can force the default size by setting the col_force_default or row_force_default property. This will force the layout to ignore the width and size_hint properties of children and use the default size." }, { "code": null, "e": 1385, "s": 1316, "text": "The first thing we need to do to use a GridLayout is to import it. " }, { "code": null, "e": 1429, "s": 1385, "text": "from kivy.uix.gridlayout import GridLayout " }, { "code": null, "e": 1468, "s": 1429, "text": "Basic Approach to create GridLayout: " }, { "code": null, "e": 1752, "s": 1468, "text": "1) import kivy\n2) import kivyApp\n3) import button\n4) import Gridlayout\n5) Set minimum version(optional)\n6) create App class:\n - define build function\n : add widget (Buttons)\n7) return Layout/widget/Class(according to requirement)\n8) Run an instance of the class" }, { "code": null, "e": 1944, "s": 1752, "text": " Implementation of the approach –Code #1: In the example below, all widgets will have an equal size. By default, the size_hint is (1, 1), so a Widget will take the full size of the parent: " }, { "code": null, "e": 1952, "s": 1944, "text": "Python3" }, { "code": "# Sample Python application demonstrating # How to create GridLayout in Kivy # import kivy moduleimport kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # creates the button in kivy # if not imported shows the error from kivy.uix.button import Button # The GridLayout arranges children in a matrix.# It takes the available space and# divides it into columns and rows,# then adds widgets to the resulting “cells”.from kivy.uix.gridlayout import GridLayout # creating the App classclass Grid_LayoutApp(App): # to build the application we have to # return a widget on the build() function. def build(self): # adding GridLayouts in App # Defining number of column # You can use row as well depends on need layout = GridLayout(cols = 2) # 1st row layout.add_widget(Button(text ='Hello 1')) layout.add_widget(Button(text ='World 1')) # 2nd row layout.add_widget(Button(text ='Hello 2')) layout.add_widget(Button(text ='World 2')) # 3rd row layout.add_widget(Button(text ='Hello 3')) layout.add_widget(Button(text ='World 3')) # 4th row layout.add_widget(Button(text ='Hello 4')) layout.add_widget(Button(text ='World 4')) # returning the layout return layout # creating object of the App classroot = Grid_LayoutApp()# run the Approot.run()", "e": 3425, "s": 1952, "text": null }, { "code": null, "e": 3435, "s": 3425, "text": "Output: " }, { "code": null, "e": 3710, "s": 3435, "text": "Now just change the class code in the above code with the code #2 and code#3 other than that all will be same as code#1 and run the code after changes you will get the below results. Code #2: Now, let’s fix the size of Hello buttons to 100px instead of using size_hint_x=1: " }, { "code": null, "e": 3718, "s": 3710, "text": "Python3" }, { "code": "# creating the App classclass Grid_LayoutApp(App): # to build the application we have to # return a widget on the build() function. def build(self): # adding GridLayouts in App # Defining number of column # You can use row as well depends on need layout = GridLayout(cols = 2) # 1st row layout.add_widget(Button(text ='Hello 1', size_hint_x = None, width = 100)) layout.add_widget(Button(text ='World 1')) # 2nd row layout.add_widget(Button(text ='Hello 2', size_hint_x = None, width = 100)) layout.add_widget(Button(text ='World 2')) # 3rd row layout.add_widget(Button(text ='Hello 3', size_hint_x = None, width = 100)) layout.add_widget(Button(text ='World 3')) # 4th row layout.add_widget(Button(text ='Hello 4', size_hint_x = None, width = 100)) layout.add_widget(Button(text ='World 4')) # returning the layout return layout", "e": 4690, "s": 3718, "text": null }, { "code": null, "e": 4700, "s": 4690, "text": "Output: " }, { "code": null, "e": 4760, "s": 4700, "text": "Code #3: Now, let’s fix the row height to a specific size: " }, { "code": null, "e": 4768, "s": 4760, "text": "Python3" }, { "code": "# creating the App classclass Grid_LayoutApp(App): # to build the application we have to # return a widget on the build() function. def build(self): # adding GridLayouts in App # Defining number of column and size of the buttons i.e height layout = GridLayout(cols = 2, row_force_default = True, row_default_height = 30) # 1st row layout.add_widget(Button(text ='Hello 1', size_hint_x = None, width = 100)) layout.add_widget(Button(text ='World 1')) # 2nd row layout.add_widget(Button(text ='Hello 2', size_hint_x = None, width = 100)) layout.add_widget(Button(text ='World 2')) # 3rd row layout.add_widget(Button(text ='Hello 3', size_hint_x = None, width = 100)) layout.add_widget(Button(text ='World 3')) # 4th row layout.add_widget(Button(text ='Hello 4', size_hint_x = None, width = 100)) layout.add_widget(Button(text ='World 4')) # returning the layout return layout", "e": 5804, "s": 4768, "text": null }, { "code": null, "e": 5814, "s": 5804, "text": "Output: " }, { "code": null, "e": 5885, "s": 5814, "text": " Reference: https://kivy.org/doc/stable/api-kivy.uix.gridlayout.html " }, { "code": null, "e": 5894, "s": 5885, "text": "sweetyty" }, { "code": null, "e": 5906, "s": 5894, "text": "anikakapoor" }, { "code": null, "e": 5917, "s": 5906, "text": "Python-gui" }, { "code": null, "e": 5929, "s": 5917, "text": "Python-kivy" }, { "code": null, "e": 5936, "s": 5929, "text": "Python" } ]
Create a website using HTML CSS and JavaScript that stores data in Firebase
02 Nov, 2021 Following are some simple steps in order to connect our static Web Page with Firebase. Step 1: Firstly, We are going to create a project on Firebase to connect our static web page. Visit the Firebase page for configuring your project. Visit the website and click the On Add Project button as shown below. Step 2: Give a Name to your project and click on the Continue button. Step 3: Now click on the Continue button. Step 4: Now choose Default Account For Firebase and click on the Create Project button. Step 5: Now your project is created and you are now good to go. Step 6: Now click on the 3rd icon that’s the Web button(</>). Step 7: Give a nickname to your web project and click on the Register App button. Step 8: Now you will see the configuration of your App like this. Copy this code somewhere as we will use it later. Step 9: Click on the Realtime Database as shown below. Step 10: Now click on the Create Database button. Step 11: Now click on the Test Mode and then click on the Enable button. Step 12: Activate Firebase Storage. Click on Storage button in the left and the click on Get Started. After that this box will pop up . Click on Next. Then Click on Done. Project Setup: Now Create an HTML file and copy the script code which you copied in Step 8. The following file is just a sample for you to understand how to configure your project. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <title>Collecting Data</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"></head> <body class="container" style="margin-top: 50px; width: 50%; height:auto;"> <h2 class="text-primary" style= "margin-left: 15px; margin-bottom: 10px"> Hey There,Help Us In Collecting Data </h2> <form class="container" id="contactForm"> <div class="card"> <div class="card-body"> <div class="form-group"> <label for="exampleFormControlInput1"> Enter Your Name </label> <input type="text" class="form-control" id="name" placeholder="Enter your name"> </div> <div class="form-group"> <label for="exampleFormControlInput1"> Email address </label> <input type="email" class="form-control" id="email" placeholder="[email protected]"> </div> </div> <button type="submit" class="btn btn-primary" style="margin-left: 15px; margin-top: 10px"> Submit </button> </div> </form> <script src="https://www.gstatic.com/firebasejs/3.7.4/firebase.js"> </script> <script> var firebaseConfig = { apiKey: "Use Your Api Key Here", authDomain: "Use Your authDomain Here", databaseURL: "Use Your databaseURL Here", projectId: "Use Your projectId Here", storageBucket: "Use Your storageBucket Here", messagingSenderId: "Use Your messagingSenderId Here", appId: "Use Your appId Here" }; firebase.initializeApp(firebaseConfig); var messagesRef = firebase.database() .ref('Collected Data'); document.getElementById('contactForm') .addEventListener('submit', submitForm); function submitForm(e) { e.preventDefault(); // Get values var name = getInputVal('name'); var email = getInputVal('email'); saveMessage(name, email); document.getElementById('contactForm').reset(); } // Function to get get form values function getInputVal(id) { return document.getElementById(id).value; } // Save message to firebase function saveMessage(name, email) { var newMessageRef = messagesRef.push(); newMessageRef.set({ name: name, email: email, }); } </script></body> </html> Output: Entering some sample values of Name and Email address in the given form as shown below. After clicking the Submit button, the data is getting stored in the real-time database as shown below. annianni varshagumber28 Firebase CSS HTML JavaScript Technical Scripter Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of CSS (Cascading Style Sheet) How to set space between the flexbox ? How to position a div at the bottom of its container using CSS? How to Upload Image into Database and Display it using PHP ? Design a Tribute Page using HTML & CSS REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Design a Tribute Page using HTML & CSS
[ { "code": null, "e": 54, "s": 26, "text": "\n02 Nov, 2021" }, { "code": null, "e": 142, "s": 54, "text": "Following are some simple steps in order to connect our static Web Page with Firebase. " }, { "code": null, "e": 360, "s": 142, "text": "Step 1: Firstly, We are going to create a project on Firebase to connect our static web page. Visit the Firebase page for configuring your project. Visit the website and click the On Add Project button as shown below." }, { "code": null, "e": 430, "s": 360, "text": "Step 2: Give a Name to your project and click on the Continue button." }, { "code": null, "e": 472, "s": 430, "text": "Step 3: Now click on the Continue button." }, { "code": null, "e": 560, "s": 472, "text": "Step 4: Now choose Default Account For Firebase and click on the Create Project button." }, { "code": null, "e": 624, "s": 560, "text": "Step 5: Now your project is created and you are now good to go." }, { "code": null, "e": 686, "s": 624, "text": "Step 6: Now click on the 3rd icon that’s the Web button(</>)." }, { "code": null, "e": 768, "s": 686, "text": "Step 7: Give a nickname to your web project and click on the Register App button." }, { "code": null, "e": 884, "s": 768, "text": "Step 8: Now you will see the configuration of your App like this. Copy this code somewhere as we will use it later." }, { "code": null, "e": 939, "s": 884, "text": "Step 9: Click on the Realtime Database as shown below." }, { "code": null, "e": 989, "s": 939, "text": "Step 10: Now click on the Create Database button." }, { "code": null, "e": 1062, "s": 989, "text": "Step 11: Now click on the Test Mode and then click on the Enable button." }, { "code": null, "e": 1164, "s": 1062, "text": "Step 12: Activate Firebase Storage. Click on Storage button in the left and the click on Get Started." }, { "code": null, "e": 1213, "s": 1164, "text": "After that this box will pop up . Click on Next." }, { "code": null, "e": 1235, "s": 1215, "text": "Then Click on Done." }, { "code": null, "e": 1252, "s": 1237, "text": "Project Setup:" }, { "code": null, "e": 1418, "s": 1252, "text": "Now Create an HTML file and copy the script code which you copied in Step 8. The following file is just a sample for you to understand how to configure your project." }, { "code": null, "e": 1425, "s": 1420, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <title>Collecting Data</title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" integrity=\"sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2\" crossorigin=\"anonymous\"></head> <body class=\"container\" style=\"margin-top: 50px; width: 50%; height:auto;\"> <h2 class=\"text-primary\" style= \"margin-left: 15px; margin-bottom: 10px\"> Hey There,Help Us In Collecting Data </h2> <form class=\"container\" id=\"contactForm\"> <div class=\"card\"> <div class=\"card-body\"> <div class=\"form-group\"> <label for=\"exampleFormControlInput1\"> Enter Your Name </label> <input type=\"text\" class=\"form-control\" id=\"name\" placeholder=\"Enter your name\"> </div> <div class=\"form-group\"> <label for=\"exampleFormControlInput1\"> Email address </label> <input type=\"email\" class=\"form-control\" id=\"email\" placeholder=\"[email protected]\"> </div> </div> <button type=\"submit\" class=\"btn btn-primary\" style=\"margin-left: 15px; margin-top: 10px\"> Submit </button> </div> </form> <script src=\"https://www.gstatic.com/firebasejs/3.7.4/firebase.js\"> </script> <script> var firebaseConfig = { apiKey: \"Use Your Api Key Here\", authDomain: \"Use Your authDomain Here\", databaseURL: \"Use Your databaseURL Here\", projectId: \"Use Your projectId Here\", storageBucket: \"Use Your storageBucket Here\", messagingSenderId: \"Use Your messagingSenderId Here\", appId: \"Use Your appId Here\" }; firebase.initializeApp(firebaseConfig); var messagesRef = firebase.database() .ref('Collected Data'); document.getElementById('contactForm') .addEventListener('submit', submitForm); function submitForm(e) { e.preventDefault(); // Get values var name = getInputVal('name'); var email = getInputVal('email'); saveMessage(name, email); document.getElementById('contactForm').reset(); } // Function to get get form values function getInputVal(id) { return document.getElementById(id).value; } // Save message to firebase function saveMessage(name, email) { var newMessageRef = messagesRef.push(); newMessageRef.set({ name: name, email: email, }); } </script></body> </html>", "e": 4476, "s": 1425, "text": null }, { "code": null, "e": 4484, "s": 4476, "text": "Output:" }, { "code": null, "e": 4572, "s": 4484, "text": "Entering some sample values of Name and Email address in the given form as shown below." }, { "code": null, "e": 4675, "s": 4572, "text": "After clicking the Submit button, the data is getting stored in the real-time database as shown below." }, { "code": null, "e": 4684, "s": 4675, "text": "annianni" }, { "code": null, "e": 4699, "s": 4684, "text": "varshagumber28" }, { "code": null, "e": 4708, "s": 4699, "text": "Firebase" }, { "code": null, "e": 4712, "s": 4708, "text": "CSS" }, { "code": null, "e": 4717, "s": 4712, "text": "HTML" }, { "code": null, "e": 4728, "s": 4717, "text": "JavaScript" }, { "code": null, "e": 4747, "s": 4728, "text": "Technical Scripter" }, { "code": null, "e": 4764, "s": 4747, "text": "Web Technologies" }, { "code": null, "e": 4769, "s": 4764, "text": "HTML" }, { "code": null, "e": 4867, "s": 4769, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4904, "s": 4867, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 4943, "s": 4904, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 5007, "s": 4943, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 5068, "s": 5007, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 5107, "s": 5068, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 5131, "s": 5107, "text": "REST API (Introduction)" }, { "code": null, "e": 5184, "s": 5131, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 5244, "s": 5184, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 5305, "s": 5244, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Program to print multiplication table of a number
15 Apr, 2021 Given a number n as input, we need to print its table. Examples : Input : 5 Output : 5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25 5 * 6 = 30 5 * 7 = 35 5 * 8 = 40 5 * 9 = 45 5 * 10 = 50 Input : 8 Output : 8 * 1 = 8 8 * 2 = 16 8 * 3 = 24 8 * 4 = 32 8 * 5 = 40 8 * 6 = 48 8 * 7 = 56 8 * 8 = 64 8 * 9 = 72 8 * 10 = 80 8 * 11 = 88 8 * 12 = 96 Example 1: Display Multiplication table up to 10 Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. C++ Java Python C# PHP Javascript // CPP program to print table of a number#include <iostream>using namespace std; int main(){ int n = 5; // Change here to change output for (int i = 1; i <= 10; ++i) cout << n << " * " << i << " = " << n * i << endl; return 0;} // Java program to print table// of a numberimport java.io.*; class table{ // Driver code public static void main(String arg[]) { // Change here to change output int n = 5; for (int i = 1; i <= 10; ++i) System.out.println(n + " * " + i + " = " + n * i); }} // This code is contributed by Anant Agarwal. # Python Program to print table# of a number upto 10 def table(n): for i in range (1, 11): # multiples from 1 to 10 print "%d * %d = %d" % (n, i, n * i) # number for which table is evaluatedn = 5table(n) # This article is contributed by Shubham Rana // C# program to print// table of a numberusing System; class GFG{ // Driver code public static void Main() { // Change here to // change output int n = 5; for (int i = 1; i <= 10; ++i) Console.Write(n + " * " + i + " = " + n * i + "\n"); }} // This code is contributed// by Smitha. <?php// PHP program to print// table of a number // Driver Code$n = 5; // Change here to // change outputfor ($i = 1; $i <= 10; ++$i) echo $n , " * " , $i , " = " , $n * $i , "\n"; // This code is contributed// by Smitha?> <script> // Javascript program to print// table of a number // Driver Code // Change here to change outputlet n = 5;for (let i = 1; i <= 10; ++i) document.write( n + " * " +i + " = " + n * i +"<br>"); // This code is contributed// by bobby </script> Output : 5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25 5 * 6 = 30 5 * 7 = 35 5 * 8 = 40 5 * 9 = 45 5 * 10 = 50 This program above computes the multiplication table up to 10 only.The program below is the modification of above program in which the user is also asked to entered the range up to which multiplication table should be displayed.Example 2: Display multiplication table up to a given range C++ Java Python C# PHP Javascript // CPP program to print table over a range.#include <iostream>using namespace std;int main(){ int n = 8; // Change here to change input number int range = 12; // Change here to change result. for (int i = 1; i <= range; ++i) cout << n << " * " << i << " = " << n * i << endl; return 0;} // Java program to print table// over given range.import java.io.*; class table{ // Driver code public static void main(String arg[]) { // Change here to change input number int n = 8; // Change here to change result int range = 12; for (int i = 1; i <= range; ++i) System.out.println(n + " * " + i + " = " + n * i); }} // This code is contributed by Anant Agarwal. # Python Program to print table# of a number given range def table(n, r): for i in range (1, r + 1): # multiples from 1 to r (range) print "%d * %d = %d" % (n, i, n * i) # number for which table is evaluatedn = 8 # range upto which multiples are to be calculatedr = 12table(n,r) # This article is contributed by Shubham Rana // C# program to print// table over given range.using System; class GFG{ // Driver code public static void Main() { // Change here to // change input number int n = 8; // Change here to // change result int range = 12; for (int i = 1; i <= range; ++i) Console.Write(n + " * " + i + " = " + n * i + "\n"); }} // This code is contributed// by Smitha. <?php// PHP program to print// table over a range. $n = 8; // Change here to // change input number$range = 12; // Change here to // change result.for ($i = 1; $i <= $range; ++$i) echo $n , " * " , $i , " = ", $n * $i , "\n"; // This code is contributed// by m_kit?> <script> // Javascript program to print// table of a number in range // Driver Code// Change here to// change input number let n = 8; // Change here to// change result.let range = 12;for (let i = 1; i <= range; ++i) document.write( n + " * " +i + " = " + n * i +"<br>"); // This code is contributed// by bobby </script> Output: 8 * 1 = 8 8 * 2 = 16 8 * 3 = 24 8 * 4 = 32 8 * 5 = 40 8 * 6 = 48 8 * 7 = 56 8 * 8 = 64 8 * 9 = 72 8 * 10 = 80 8 * 11 = 88 8 * 12 = 96 This article is contributed by Anurag Rawat. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Smitha Dinesh Semwal jit_t gottumukkalabobby Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Prime Numbers Find minimum number of coins that make a given value Algorithm to solve Rubik's Cube Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 53, "s": 25, "text": "\n15 Apr, 2021" }, { "code": null, "e": 110, "s": 53, "text": "Given a number n as input, we need to print its table. " }, { "code": null, "e": 123, "s": 110, "text": "Examples : " }, { "code": null, "e": 588, "s": 123, "text": "Input : 5\nOutput : 5 * 1 = 5\n 5 * 2 = 10\n 5 * 3 = 15\n 5 * 4 = 20\n 5 * 5 = 25\n 5 * 6 = 30\n 5 * 7 = 35\n 5 * 8 = 40\n 5 * 9 = 45\n 5 * 10 = 50\n\nInput : 8\nOutput : 8 * 1 = 8\n 8 * 2 = 16\n 8 * 3 = 24\n 8 * 4 = 32\n 8 * 5 = 40\n 8 * 6 = 48\n 8 * 7 = 56\n 8 * 8 = 64\n 8 * 9 = 72\n 8 * 10 = 80\n 8 * 11 = 88\n 8 * 12 = 96" }, { "code": null, "e": 641, "s": 590, "text": "Example 1: Display Multiplication table up to 10 " }, { "code": null, "e": 650, "s": 641, "text": "Chapters" }, { "code": null, "e": 677, "s": 650, "text": "descriptions off, selected" }, { "code": null, "e": 727, "s": 677, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 750, "s": 727, "text": "captions off, selected" }, { "code": null, "e": 758, "s": 750, "text": "English" }, { "code": null, "e": 782, "s": 758, "text": "This is a modal window." }, { "code": null, "e": 851, "s": 782, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 873, "s": 851, "text": "End of dialog window." }, { "code": null, "e": 877, "s": 873, "text": "C++" }, { "code": null, "e": 882, "s": 877, "text": "Java" }, { "code": null, "e": 889, "s": 882, "text": "Python" }, { "code": null, "e": 892, "s": 889, "text": "C#" }, { "code": null, "e": 896, "s": 892, "text": "PHP" }, { "code": null, "e": 907, "s": 896, "text": "Javascript" }, { "code": "// CPP program to print table of a number#include <iostream>using namespace std; int main(){ int n = 5; // Change here to change output for (int i = 1; i <= 10; ++i) cout << n << \" * \" << i << \" = \" << n * i << endl; return 0;}", "e": 1169, "s": 907, "text": null }, { "code": "// Java program to print table// of a numberimport java.io.*; class table{ // Driver code public static void main(String arg[]) { // Change here to change output int n = 5; for (int i = 1; i <= 10; ++i) System.out.println(n + \" * \" + i + \" = \" + n * i); }} // This code is contributed by Anant Agarwal.", "e": 1559, "s": 1169, "text": null }, { "code": "# Python Program to print table# of a number upto 10 def table(n): for i in range (1, 11): # multiples from 1 to 10 print \"%d * %d = %d\" % (n, i, n * i) # number for which table is evaluatedn = 5table(n) # This article is contributed by Shubham Rana", "e": 1835, "s": 1559, "text": null }, { "code": "// C# program to print// table of a numberusing System; class GFG{ // Driver code public static void Main() { // Change here to // change output int n = 5; for (int i = 1; i <= 10; ++i) Console.Write(n + \" * \" + i + \" = \" + n * i + \"\\n\"); }} // This code is contributed// by Smitha.", "e": 2237, "s": 1835, "text": null }, { "code": "<?php// PHP program to print// table of a number // Driver Code$n = 5; // Change here to // change outputfor ($i = 1; $i <= 10; ++$i) echo $n , \" * \" , $i , \" = \" , $n * $i , \"\\n\"; // This code is contributed// by Smitha?>", "e": 2506, "s": 2237, "text": null }, { "code": "<script> // Javascript program to print// table of a number // Driver Code // Change here to change outputlet n = 5;for (let i = 1; i <= 10; ++i) document.write( n + \" * \" +i + \" = \" + n * i +\"<br>\"); // This code is contributed// by bobby </script>", "e": 2793, "s": 2506, "text": null }, { "code": null, "e": 2803, "s": 2793, "text": "Output : " }, { "code": null, "e": 2913, "s": 2803, "text": "5 * 1 = 5\n5 * 2 = 10\n5 * 3 = 15\n5 * 4 = 20\n5 * 5 = 25\n5 * 6 = 30\n5 * 7 = 35\n5 * 8 = 40\n5 * 9 = 45\n5 * 10 = 50" }, { "code": null, "e": 3203, "s": 2913, "text": "This program above computes the multiplication table up to 10 only.The program below is the modification of above program in which the user is also asked to entered the range up to which multiplication table should be displayed.Example 2: Display multiplication table up to a given range " }, { "code": null, "e": 3207, "s": 3203, "text": "C++" }, { "code": null, "e": 3212, "s": 3207, "text": "Java" }, { "code": null, "e": 3219, "s": 3212, "text": "Python" }, { "code": null, "e": 3222, "s": 3219, "text": "C#" }, { "code": null, "e": 3226, "s": 3222, "text": "PHP" }, { "code": null, "e": 3237, "s": 3226, "text": "Javascript" }, { "code": "// CPP program to print table over a range.#include <iostream>using namespace std;int main(){ int n = 8; // Change here to change input number int range = 12; // Change here to change result. for (int i = 1; i <= range; ++i) cout << n << \" * \" << i << \" = \" << n * i << endl; return 0;}", "e": 3556, "s": 3237, "text": null }, { "code": "// Java program to print table// over given range.import java.io.*; class table{ // Driver code public static void main(String arg[]) { // Change here to change input number int n = 8; // Change here to change result int range = 12; for (int i = 1; i <= range; ++i) System.out.println(n + \" * \" + i + \" = \" + n * i); }} // This code is contributed by Anant Agarwal.", "e": 4030, "s": 3556, "text": null }, { "code": "# Python Program to print table# of a number given range def table(n, r): for i in range (1, r + 1): # multiples from 1 to r (range) print \"%d * %d = %d\" % (n, i, n * i) # number for which table is evaluatedn = 8 # range upto which multiples are to be calculatedr = 12table(n,r) # This article is contributed by Shubham Rana", "e": 4381, "s": 4030, "text": null }, { "code": "// C# program to print// table over given range.using System; class GFG{ // Driver code public static void Main() { // Change here to // change input number int n = 8; // Change here to // change result int range = 12; for (int i = 1; i <= range; ++i) Console.Write(n + \" * \" + i + \" = \" + n * i + \"\\n\"); }} // This code is contributed// by Smitha.", "e": 4870, "s": 4381, "text": null }, { "code": "<?php// PHP program to print// table over a range. $n = 8; // Change here to // change input number$range = 12; // Change here to // change result.for ($i = 1; $i <= $range; ++$i) echo $n , \" * \" , $i , \" = \", $n * $i , \"\\n\"; // This code is contributed// by m_kit?>", "e": 5175, "s": 4870, "text": null }, { "code": "<script> // Javascript program to print// table of a number in range // Driver Code// Change here to// change input number let n = 8; // Change here to// change result.let range = 12;for (let i = 1; i <= range; ++i) document.write( n + \" * \" +i + \" = \" + n * i +\"<br>\"); // This code is contributed// by bobby </script>", "e": 5532, "s": 5175, "text": null }, { "code": null, "e": 5541, "s": 5532, "text": "Output: " }, { "code": null, "e": 5675, "s": 5541, "text": "8 * 1 = 8\n8 * 2 = 16\n8 * 3 = 24\n8 * 4 = 32\n8 * 5 = 40\n8 * 6 = 48\n8 * 7 = 56\n8 * 8 = 64\n8 * 9 = 72\n8 * 10 = 80\n8 * 11 = 88\n8 * 12 = 96" }, { "code": null, "e": 6100, "s": 5675, "text": "This article is contributed by Anurag Rawat. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 6121, "s": 6100, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 6127, "s": 6121, "text": "jit_t" }, { "code": null, "e": 6145, "s": 6127, "text": "gottumukkalabobby" }, { "code": null, "e": 6158, "s": 6145, "text": "Mathematical" }, { "code": null, "e": 6177, "s": 6158, "text": "School Programming" }, { "code": null, "e": 6190, "s": 6177, "text": "Mathematical" }, { "code": null, "e": 6288, "s": 6190, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6312, "s": 6288, "text": "Merge two sorted arrays" }, { "code": null, "e": 6333, "s": 6312, "text": "Operators in C / C++" }, { "code": null, "e": 6347, "s": 6333, "text": "Prime Numbers" }, { "code": null, "e": 6400, "s": 6347, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 6432, "s": 6400, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 6450, "s": 6432, "text": "Python Dictionary" }, { "code": null, "e": 6475, "s": 6450, "text": "Reverse a string in Java" }, { "code": null, "e": 6491, "s": 6475, "text": "Arrays in C/C++" }, { "code": null, "e": 6514, "s": 6491, "text": "Introduction To PYTHON" } ]
Multiple-Processor Scheduling in Operating System
27 Feb, 2020 In multiple-processor scheduling multiple CPU’s are available and hence Load Sharing becomes possible. However multiple processor scheduling is more complex as compared to single processor scheduling. In multiple processor scheduling there are cases when the processors are identical i.e. HOMOGENEOUS, in terms of their functionality, we can use any processor available to run any process in the queue. One approach is when all the scheduling decisions and I/O processing are handled by a single processor which is called the Master Server and the other processors executes only the user code. This is simple and reduces the need of data sharing. This entire scenario is called Asymmetric Multiprocessing. A second approach uses Symmetric Multiprocessing where each processor is self scheduling. All processes may be in a common ready queue or each processor may have its own private queue for ready processes. The scheduling proceeds further by having the scheduler for each processor examine the ready queue and select a process to execute. Processor Affinity means a processes has an affinity for the processor on which it is currently running.When a process runs on a specific processor there are certain effects on the cache memory. The data most recently accessed by the process populate the cache for the processor and as a result successive memory access by the process are often satisfied in the cache memory. Now if the process migrates to another processor, the contents of the cache memory must be invalidated for the first processor and the cache for the second processor must be repopulated. Because of the high cost of invalidating and repopulating caches, most of the SMP(symmetric multiprocessing) systems try to avoid migration of processes from one processor to another and try to keep a process running on the same processor. This is known as PROCESSOR AFFINITY. There are two types of processor affinity: Soft Affinity – When an operating system has a policy of attempting to keep a process running on the same processor but not guaranteeing it will do so, this situation is called soft affinity.Hard Affinity – Hard Affinity allows a process to specify a subset of processors on which it may run. Some systems such as Linux implements soft affinity but also provide some system calls like sched_setaffinity() that supports hard affinity. Soft Affinity – When an operating system has a policy of attempting to keep a process running on the same processor but not guaranteeing it will do so, this situation is called soft affinity. Hard Affinity – Hard Affinity allows a process to specify a subset of processors on which it may run. Some systems such as Linux implements soft affinity but also provide some system calls like sched_setaffinity() that supports hard affinity. Load Balancing is the phenomena which keeps the workload evenly distributed across all processors in an SMP system. Load balancing is necessary only on systems where each processor has its own private queue of process which are eligible to execute. Load balancing is unnecessary because once a processor becomes idle it immediately extracts a runnable process from the common run queue. On SMP(symmetric multiprocessing), it is important to keep the workload balanced among all processors to fully utilize the benefits of having more than one processor else one or more processor will sit idle while other processors have high workloads along with lists of processors awaiting the CPU. There are two general approaches to load balancing : Push Migration – In push migration a task routinely checks the load on each processor and if it finds an imbalance then it evenly distributes load on each processors by moving the processes from overloaded to idle or less busy processors.Pull Migration – Pull Migration occurs when an idle processor pulls a waiting task from a busy processor for its execution. Push Migration – In push migration a task routinely checks the load on each processor and if it finds an imbalance then it evenly distributes load on each processors by moving the processes from overloaded to idle or less busy processors. Pull Migration – Pull Migration occurs when an idle processor pulls a waiting task from a busy processor for its execution. In multicore processors multiple processor cores are places on the same physical chip. Each core has a register set to maintain its architectural state and thus appears to the operating system as a separate physical processor. SMP systems that use multicore processors are faster and consume less power than systems in which each processor has its own physical chip. However multicore processors may complicate the scheduling problems. When processor accesses memory then it spends a significant amount of time waiting for the data to become available. This situation is called MEMORY STALL. It occurs for various reasons such as cache miss, which is accessing the data that is not in the cache memory. In such cases the processor can spend upto fifty percent of its time waiting for data to become available from the memory. To solve this problem recent hardware designs have implemented multithreaded processor cores in which two or more hardware threads are assigned to each core. Therefore if one thread stalls while waiting for the memory, core can switch to another thread. There are two ways to multithread a processor : Coarse-Grained Multithreading – In coarse grained multithreading a thread executes on a processor until a long latency event such as a memory stall occurs, because of the delay caused by the long latency event, the processor must switch to another thread to begin execution. The cost of switching between threads is high as the instruction pipeline must be terminated before the other thread can begin execution on the processor core. Once this new thread begins execution it begins filling the pipeline with its instructions.Fine-Grained Multithreading – This multithreading switches between threads at a much finer level mainly at the boundary of an instruction cycle. The architectural design of fine grained systems include logic for thread switching and as a result the cost of switching between threads is small. Coarse-Grained Multithreading – In coarse grained multithreading a thread executes on a processor until a long latency event such as a memory stall occurs, because of the delay caused by the long latency event, the processor must switch to another thread to begin execution. The cost of switching between threads is high as the instruction pipeline must be terminated before the other thread can begin execution on the processor core. Once this new thread begins execution it begins filling the pipeline with its instructions. Fine-Grained Multithreading – This multithreading switches between threads at a much finer level mainly at the boundary of an instruction cycle. The architectural design of fine grained systems include logic for thread switching and as a result the cost of switching between threads is small. In this type of multiple-processor scheduling even a single CPU system acts like a multiple-processor system. In a system with Virtualization, the virtualization presents one or more virtual CPU to each of virtual machines running on the system and then schedules the use of physical CPU among the virtual machines. Most virtualized environments have one host operating system and many guest operating systems. The host operating system creates and manages the virtual machines. Each virtual machine has a guest operating system installed and applications run within that guest.Each guest operating system may be assigned for specific use cases,applications or users including time sharing or even real-time operation. Any guest operating-system scheduling algorithm that assumes a certain amount of progress in a given amount of time will be negatively impacted by the virtualization. A time sharing operating system tries to allot 100 milliseconds to each time slice to give users a reasonable response time. A given 100 millisecond time slice may take much more than 100 milliseconds of virtual CPU time. Depending on how busy the system is, the time slice may take a second or more which results in a very poor response time for users logged into that virtual machine. The net effect of such scheduling layering is that individual virtualized operating systems receive only a portion of the available CPU cycles, even though they believe they are receiving all cycles and that they are scheduling all of those cycles.Commonly, the time-of-day clocks in virtual machines are incorrect because timers take no longer to trigger than they would on dedicated CPU’s. Virtualizations can thus undo the good scheduling-algorithm efforts of the operating systems within virtual machines. Reference –Operating System Principles – Galvin VighneshKamath rashimnarayantiku Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Ricart–Agrawala Algorithm in Mutual Exclusion in Distributed System Lamport's Algorithm for Mutual Exclusion in Distributed System Maekawa’s Algorithm for Mutual Exclusion in Distributed System Chandy–Lamport's global state recording algorithm What is Distributed shared memory and its advantages Suzuki–Kasami Algorithm for Mutual Exclusion in Distributed System Memory Management in Operating System Cache Memory in Computer Organization Mutual exclusion in distributed system LRU Cache Implementation
[ { "code": null, "e": 54, "s": 26, "text": "\n27 Feb, 2020" }, { "code": null, "e": 457, "s": 54, "text": "In multiple-processor scheduling multiple CPU’s are available and hence Load Sharing becomes possible. However multiple processor scheduling is more complex as compared to single processor scheduling. In multiple processor scheduling there are cases when the processors are identical i.e. HOMOGENEOUS, in terms of their functionality, we can use any processor available to run any process in the queue." }, { "code": null, "e": 760, "s": 457, "text": "One approach is when all the scheduling decisions and I/O processing are handled by a single processor which is called the Master Server and the other processors executes only the user code. This is simple and reduces the need of data sharing. This entire scenario is called Asymmetric Multiprocessing." }, { "code": null, "e": 1097, "s": 760, "text": "A second approach uses Symmetric Multiprocessing where each processor is self scheduling. All processes may be in a common ready queue or each processor may have its own private queue for ready processes. The scheduling proceeds further by having the scheduler for each processor examine the ready queue and select a process to execute." }, { "code": null, "e": 1937, "s": 1097, "text": "Processor Affinity means a processes has an affinity for the processor on which it is currently running.When a process runs on a specific processor there are certain effects on the cache memory. The data most recently accessed by the process populate the cache for the processor and as a result successive memory access by the process are often satisfied in the cache memory. Now if the process migrates to another processor, the contents of the cache memory must be invalidated for the first processor and the cache for the second processor must be repopulated. Because of the high cost of invalidating and repopulating caches, most of the SMP(symmetric multiprocessing) systems try to avoid migration of processes from one processor to another and try to keep a process running on the same processor. This is known as PROCESSOR AFFINITY." }, { "code": null, "e": 1980, "s": 1937, "text": "There are two types of processor affinity:" }, { "code": null, "e": 2414, "s": 1980, "text": "Soft Affinity – When an operating system has a policy of attempting to keep a process running on the same processor but not guaranteeing it will do so, this situation is called soft affinity.Hard Affinity – Hard Affinity allows a process to specify a subset of processors on which it may run. Some systems such as Linux implements soft affinity but also provide some system calls like sched_setaffinity() that supports hard affinity." }, { "code": null, "e": 2606, "s": 2414, "text": "Soft Affinity – When an operating system has a policy of attempting to keep a process running on the same processor but not guaranteeing it will do so, this situation is called soft affinity." }, { "code": null, "e": 2849, "s": 2606, "text": "Hard Affinity – Hard Affinity allows a process to specify a subset of processors on which it may run. Some systems such as Linux implements soft affinity but also provide some system calls like sched_setaffinity() that supports hard affinity." }, { "code": null, "e": 3535, "s": 2849, "text": "Load Balancing is the phenomena which keeps the workload evenly distributed across all processors in an SMP system. Load balancing is necessary only on systems where each processor has its own private queue of process which are eligible to execute. Load balancing is unnecessary because once a processor becomes idle it immediately extracts a runnable process from the common run queue. On SMP(symmetric multiprocessing), it is important to keep the workload balanced among all processors to fully utilize the benefits of having more than one processor else one or more processor will sit idle while other processors have high workloads along with lists of processors awaiting the CPU." }, { "code": null, "e": 3588, "s": 3535, "text": "There are two general approaches to load balancing :" }, { "code": null, "e": 3950, "s": 3588, "text": "Push Migration – In push migration a task routinely checks the load on each processor and if it finds an imbalance then it evenly distributes load on each processors by moving the processes from overloaded to idle or less busy processors.Pull Migration – Pull Migration occurs when an idle processor pulls a waiting task from a busy processor for its execution." }, { "code": null, "e": 4189, "s": 3950, "text": "Push Migration – In push migration a task routinely checks the load on each processor and if it finds an imbalance then it evenly distributes load on each processors by moving the processes from overloaded to idle or less busy processors." }, { "code": null, "e": 4313, "s": 4189, "text": "Pull Migration – Pull Migration occurs when an idle processor pulls a waiting task from a busy processor for its execution." }, { "code": null, "e": 4680, "s": 4313, "text": "In multicore processors multiple processor cores are places on the same physical chip. Each core has a register set to maintain its architectural state and thus appears to the operating system as a separate physical processor. SMP systems that use multicore processors are faster and consume less power than systems in which each processor has its own physical chip." }, { "code": null, "e": 5393, "s": 4680, "text": "However multicore processors may complicate the scheduling problems. When processor accesses memory then it spends a significant amount of time waiting for the data to become available. This situation is called MEMORY STALL. It occurs for various reasons such as cache miss, which is accessing the data that is not in the cache memory. In such cases the processor can spend upto fifty percent of its time waiting for data to become available from the memory. To solve this problem recent hardware designs have implemented multithreaded processor cores in which two or more hardware threads are assigned to each core. Therefore if one thread stalls while waiting for the memory, core can switch to another thread." }, { "code": null, "e": 5441, "s": 5393, "text": "There are two ways to multithread a processor :" }, { "code": null, "e": 6260, "s": 5441, "text": "Coarse-Grained Multithreading – In coarse grained multithreading a thread executes on a processor until a long latency event such as a memory stall occurs, because of the delay caused by the long latency event, the processor must switch to another thread to begin execution. The cost of switching between threads is high as the instruction pipeline must be terminated before the other thread can begin execution on the processor core. Once this new thread begins execution it begins filling the pipeline with its instructions.Fine-Grained Multithreading – This multithreading switches between threads at a much finer level mainly at the boundary of an instruction cycle. The architectural design of fine grained systems include logic for thread switching and as a result the cost of switching between threads is small." }, { "code": null, "e": 6787, "s": 6260, "text": "Coarse-Grained Multithreading – In coarse grained multithreading a thread executes on a processor until a long latency event such as a memory stall occurs, because of the delay caused by the long latency event, the processor must switch to another thread to begin execution. The cost of switching between threads is high as the instruction pipeline must be terminated before the other thread can begin execution on the processor core. Once this new thread begins execution it begins filling the pipeline with its instructions." }, { "code": null, "e": 7080, "s": 6787, "text": "Fine-Grained Multithreading – This multithreading switches between threads at a much finer level mainly at the boundary of an instruction cycle. The architectural design of fine grained systems include logic for thread switching and as a result the cost of switching between threads is small." }, { "code": null, "e": 8745, "s": 7080, "text": "In this type of multiple-processor scheduling even a single CPU system acts like a multiple-processor system. In a system with Virtualization, the virtualization presents one or more virtual CPU to each of virtual machines running on the system and then schedules the use of physical CPU among the virtual machines. Most virtualized environments have one host operating system and many guest operating systems. The host operating system creates and manages the virtual machines. Each virtual machine has a guest operating system installed and applications run within that guest.Each guest operating system may be assigned for specific use cases,applications or users including time sharing or even real-time operation. Any guest operating-system scheduling algorithm that assumes a certain amount of progress in a given amount of time will be negatively impacted by the virtualization. A time sharing operating system tries to allot 100 milliseconds to each time slice to give users a reasonable response time. A given 100 millisecond time slice may take much more than 100 milliseconds of virtual CPU time. Depending on how busy the system is, the time slice may take a second or more which results in a very poor response time for users logged into that virtual machine. The net effect of such scheduling layering is that individual virtualized operating systems receive only a portion of the available CPU cycles, even though they believe they are receiving all cycles and that they are scheduling all of those cycles.Commonly, the time-of-day clocks in virtual machines are incorrect because timers take no longer to trigger than they would on dedicated CPU’s." }, { "code": null, "e": 8863, "s": 8745, "text": "Virtualizations can thus undo the good scheduling-algorithm efforts of the operating systems within virtual machines." }, { "code": null, "e": 8911, "s": 8863, "text": "Reference –Operating System Principles – Galvin" }, { "code": null, "e": 8926, "s": 8911, "text": "VighneshKamath" }, { "code": null, "e": 8944, "s": 8926, "text": "rashimnarayantiku" }, { "code": null, "e": 8962, "s": 8944, "text": "Operating Systems" }, { "code": null, "e": 8980, "s": 8962, "text": "Operating Systems" }, { "code": null, "e": 9078, "s": 8980, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9146, "s": 9078, "text": "Ricart–Agrawala Algorithm in Mutual Exclusion in Distributed System" }, { "code": null, "e": 9209, "s": 9146, "text": "Lamport's Algorithm for Mutual Exclusion in Distributed System" }, { "code": null, "e": 9272, "s": 9209, "text": "Maekawa’s Algorithm for Mutual Exclusion in Distributed System" }, { "code": null, "e": 9322, "s": 9272, "text": "Chandy–Lamport's global state recording algorithm" }, { "code": null, "e": 9375, "s": 9322, "text": "What is Distributed shared memory and its advantages" }, { "code": null, "e": 9442, "s": 9375, "text": "Suzuki–Kasami Algorithm for Mutual Exclusion in Distributed System" }, { "code": null, "e": 9480, "s": 9442, "text": "Memory Management in Operating System" }, { "code": null, "e": 9518, "s": 9480, "text": "Cache Memory in Computer Organization" }, { "code": null, "e": 9557, "s": 9518, "text": "Mutual exclusion in distributed system" } ]
Basic Android Login Form Example - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In this tutorials, we are going to see how to create a simple Android Login Form using Android Studio. Android SDK Version 27 Android AppCompact-v7:27.0.1 Gradle Android Studio 3.1 Creating a simple Android login screen under Linear Layout. apply plugin: 'com.android.application' android { compileSdkVersion 27 defaultConfig { applicationId "com.onlinetutorialspoint.official.simplelogin" minSdkVersion 23 targetSdkVersion 27 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:27.0.1' implementation 'com.android.support.constraint:constraint-layout:1.0.2' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.1' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1' } Creating a basic login form layout using LinearLayout having one text box, password and Login button. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.onlinetutorialspoint.official.simplelogin.MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:layout_marginLeft="16dp" android:layout_marginRight="16dp" android:layout_centerInParent="true"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="UserName" android:id="@+id/username"/> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="password" android:id="@+id/password" android:inputType="textPassword" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Login" android:background="#3f76ff" android:textColor="#fff" android:id="@+id/login"/> </LinearLayout> </RelativeLayout> Creating MainActivity.java, responsible to read the input from the about layout and validate the user inputs. package com.onlinetutorialspoint.official.simplelogin; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.util.Objects; public class MainActivity extends AppCompatActivity { EditText username,password; Button login; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); username=findViewById(R.id.username); password=findViewById(R.id.password); login=findViewById(R.id.login); login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(Objects.equals(username.getText().toString(), "admin")&&Objects.equals(password.getText().toString(),"admin")) { Toast.makeText(MainActivity.this,"You have Authenticated Successfully",Toast.LENGTH_LONG).show(); }else { Toast.makeText(MainActivity.this,"Authentication Failed",Toast.LENGTH_LONG).show(); } } }); } } Run Android Virtual Device (AVD): Giving Valid Credentials: admin – admin Giving invalid credentials: Happy Learning 🙂 Java Swing Login Example Spring MVC Login Form Example Tutorials Spring Boot Validation Login Form Example Python Selenium Automate the Login Form Spring Hibernate Example PHP Form Handling Example Spring Boot MVC Example Tutorials Spring Form Custom Validation Example How to add Android Device to Android Studio Spring MVC Form Validation Example Android Hello World Example How to install Android Studio on Windows 10 How to Configure Android Studio How to install Android SDK Windows 10 Manual Process Basic Hibernate Example with XML Configuration Java Swing Login Example Spring MVC Login Form Example Tutorials Spring Boot Validation Login Form Example Python Selenium Automate the Login Form Spring Hibernate Example PHP Form Handling Example Spring Boot MVC Example Tutorials Spring Form Custom Validation Example How to add Android Device to Android Studio Spring MVC Form Validation Example Android Hello World Example How to install Android Studio on Windows 10 How to Configure Android Studio How to install Android SDK Windows 10 Manual Process Basic Hibernate Example with XML Configuration nisha August 10, 2018 at 1:06 pm - Reply Its actually a great and helpful piece of information. I really want to learn android, I have entered in android with a great curiosity but today its become very difficult for me to learn, So please recommend me a startup....! Thank You nisha August 10, 2018 at 1:06 pm - Reply Its actually a great and helpful piece of information. I really want to learn android, I have entered in android with a great curiosity but today its become very difficult for me to learn, So please recommend me a startup....! Thank You Its actually a great and helpful piece of information. I really want to learn android, I have entered in android with a great curiosity but today its become very difficult for me to learn, So please recommend me a startup....!
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 501, "s": 398, "text": "In this tutorials, we are going to see how to create a simple Android Login Form using Android Studio." }, { "code": null, "e": 524, "s": 501, "text": "Android SDK Version 27" }, { "code": null, "e": 553, "s": 524, "text": "Android AppCompact-v7:27.0.1" }, { "code": null, "e": 560, "s": 553, "text": "Gradle" }, { "code": null, "e": 579, "s": 560, "text": "Android Studio 3.1" }, { "code": null, "e": 639, "s": 579, "text": "Creating a simple Android login screen under Linear Layout." }, { "code": null, "e": 1589, "s": 639, "text": "apply plugin: 'com.android.application'\n\nandroid {\n compileSdkVersion 27\n defaultConfig {\n applicationId \"com.onlinetutorialspoint.official.simplelogin\"\n minSdkVersion 23\n targetSdkVersion 27\n versionCode 1\n versionName \"1.0\"\n testInstrumentationRunner \"android.support.test.runner.AndroidJUnitRunner\"\n }\n buildTypes {\n release {\n minifyEnabled false\n proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\n }\n }\n}\n\ndependencies {\n implementation fileTree(dir: 'libs', include: ['*.jar'])\n implementation 'com.android.support:appcompat-v7:27.0.1'\n implementation 'com.android.support.constraint:constraint-layout:1.0.2'\n testImplementation 'junit:junit:4.12'\n androidTestImplementation 'com.android.support.test:runner:1.0.1'\n androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'\n}" }, { "code": null, "e": 1691, "s": 1589, "text": "Creating a basic login form layout using LinearLayout having one text box, password and Login button." }, { "code": null, "e": 2965, "s": 1691, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\"com.onlinetutorialspoint.official.simplelogin.MainActivity\">\n\n<LinearLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:orientation=\"vertical\"\n android:layout_marginLeft=\"16dp\"\n android:layout_marginRight=\"16dp\"\n\n android:layout_centerInParent=\"true\">\n\n <EditText\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:hint=\"UserName\"\n android:id=\"@+id/username\"/>\n<EditText\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:hint=\"password\"\n android:id=\"@+id/password\"\n android:inputType=\"textPassword\"\n />\n\n <Button\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:text=\"Login\"\n android:background=\"#3f76ff\"\n android:textColor=\"#fff\"\n android:id=\"@+id/login\"/>\n \n</LinearLayout>\n\n</RelativeLayout>\n" }, { "code": null, "e": 3075, "s": 2965, "text": "Creating MainActivity.java, responsible to read the input from the about layout and validate the user inputs." }, { "code": null, "e": 4337, "s": 3075, "text": "package com.onlinetutorialspoint.official.simplelogin;\n\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.Toast;\n\nimport java.util.Objects;\n\npublic class MainActivity extends AppCompatActivity {\nEditText username,password;\nButton login;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n username=findViewById(R.id.username);\n password=findViewById(R.id.password);\n login=findViewById(R.id.login);\n login.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n if(Objects.equals(username.getText().toString(), \"admin\")&&Objects.equals(password.getText().toString(),\"admin\"))\n {\n Toast.makeText(MainActivity.this,\"You have Authenticated Successfully\",Toast.LENGTH_LONG).show();\n\n }else\n {\n Toast.makeText(MainActivity.this,\"Authentication Failed\",Toast.LENGTH_LONG).show();\n }\n\n }\n });\n\n }\n}\n" }, { "code": null, "e": 4371, "s": 4337, "text": "Run Android Virtual Device (AVD):" }, { "code": null, "e": 4411, "s": 4371, "text": "Giving Valid Credentials: admin – admin" }, { "code": null, "e": 4439, "s": 4411, "text": "Giving invalid credentials:" }, { "code": null, "e": 4456, "s": 4439, "text": "Happy Learning 🙂" }, { "code": null, "e": 5011, "s": 4456, "text": "\nJava Swing Login Example\nSpring MVC Login Form Example Tutorials\nSpring Boot Validation Login Form Example\nPython Selenium Automate the Login Form\nSpring Hibernate Example\nPHP Form Handling Example\nSpring Boot MVC Example Tutorials\nSpring Form Custom Validation Example\nHow to add Android Device to Android Studio\nSpring MVC Form Validation Example\nAndroid Hello World Example\nHow to install Android Studio on Windows 10\nHow to Configure Android Studio\nHow to install Android SDK Windows 10 Manual Process\nBasic Hibernate Example with XML Configuration\n" }, { "code": null, "e": 5036, "s": 5011, "text": "Java Swing Login Example" }, { "code": null, "e": 5076, "s": 5036, "text": "Spring MVC Login Form Example Tutorials" }, { "code": null, "e": 5118, "s": 5076, "text": "Spring Boot Validation Login Form Example" }, { "code": null, "e": 5158, "s": 5118, "text": "Python Selenium Automate the Login Form" }, { "code": null, "e": 5183, "s": 5158, "text": "Spring Hibernate Example" }, { "code": null, "e": 5209, "s": 5183, "text": "PHP Form Handling Example" }, { "code": null, "e": 5243, "s": 5209, "text": "Spring Boot MVC Example Tutorials" }, { "code": null, "e": 5281, "s": 5243, "text": "Spring Form Custom Validation Example" }, { "code": null, "e": 5325, "s": 5281, "text": "How to add Android Device to Android Studio" }, { "code": null, "e": 5360, "s": 5325, "text": "Spring MVC Form Validation Example" }, { "code": null, "e": 5388, "s": 5360, "text": "Android Hello World Example" }, { "code": null, "e": 5432, "s": 5388, "text": "How to install Android Studio on Windows 10" }, { "code": null, "e": 5464, "s": 5432, "text": "How to Configure Android Studio" }, { "code": null, "e": 5517, "s": 5464, "text": "How to install Android SDK Windows 10 Manual Process" }, { "code": null, "e": 5564, "s": 5517, "text": "Basic Hibernate Example with XML Configuration" }, { "code": null, "e": 5856, "s": 5564, "text": "\n\n\n\n\n\nnisha\nAugust 10, 2018 at 1:06 pm - Reply \n\nIts actually a great and helpful piece of information. I really want to learn android, I have entered in android with a great curiosity but today its become very difficult for me to learn, So please recommend me a startup....!\nThank You\n\n\n\n\n" }, { "code": null, "e": 6146, "s": 5856, "text": "\n\n\n\n\nnisha\nAugust 10, 2018 at 1:06 pm - Reply \n\nIts actually a great and helpful piece of information. I really want to learn android, I have entered in android with a great curiosity but today its become very difficult for me to learn, So please recommend me a startup....!\nThank You\n\n\n\n" } ]
How to Install Kotlin on Linux? - GeeksforGeeks
26 Nov, 2021 Kotlin is a programming language introduced by JetBrains in 2011, the official designer of the most intelligent Java IDE, named Intellij IDEA. This is a strongly statically typed general-purpose programming language that runs on JVM. In 2017, Kotlin is sponsored by Google, announced as one of the official languages for Android Development. In this article, we will learn How can we install the Kotlin programming language in Linux. Follow the below steps to install Koptlin on your Linux system. Step 1: Upgrade Packages Open your Linux terminal and update your package information from all configured sources. # sudo apt update Step 2: Install JDK Install the Java Software Development Kit (JDK). Kotlin is based on JDK. JDK is used to compile Kotlin programs. When you run the following command you will be asked to enter Y or N enter Y and click enter. # sudo apt install default-jdk Step 3: Install Kotlin using SDKMAN SDKMAN is an easier way to install Kotlin on UNIX-based systems. After Installing SDKMAN restart your computer. # curl -s https://get.sdkman.io | bash Now we will install Kotlin using the following command. # sdk install kotlin After executing the above command Kotlin will be installed in your system. Now we will create a Kotlin file and check it by doing compile and run. Step 4: Create a Kotlin file Open any editor and write the following code there and save that file with the .kt extension. Here I’m creating a file with Kotlin.kt name. For creating a file write nano fileName.kt in your terminal. Then write your Kotlin code inside that file and save it using ctrl + x and then press y. Kotlin // Function in Kotlinfun main(args: Array<String>) { // Print statement println("GeeksforGeeks")} Step 5: Compile Kotlin file Navigate to that folder in which you have created your Kotlin file and then compile that file using the following command. Replace Kotlin.kt with your file name and The value of the -d option specifies the name of the output file. # kotlinc Kotlin.kt -include-runtime -d outPutFile.jar Step 6: Run the Kotlin Program Now we will check the output by running the following command. # java -jar outPutFile.jar Output: GeeksforGeeks how-to-install Picked How To Installation Guide Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install FFmpeg on Windows? How to Add External JAR File to an IntelliJ IDEA Project? How to Set Git Username and Password in GitBash? How to create a nested RecyclerView in Android How to Create and Setup Spring Boot Project in Eclipse IDE? Installation of Node.js on Linux How to Install FFmpeg on Windows? How to Install Pygame on Windows ? How to Add External JAR File to an IntelliJ IDEA Project? How to Install Jupyter Notebook on MacOS?
[ { "code": null, "e": 26307, "s": 26279, "text": "\n26 Nov, 2021" }, { "code": null, "e": 26649, "s": 26307, "text": "Kotlin is a programming language introduced by JetBrains in 2011, the official designer of the most intelligent Java IDE, named Intellij IDEA. This is a strongly statically typed general-purpose programming language that runs on JVM. In 2017, Kotlin is sponsored by Google, announced as one of the official languages for Android Development." }, { "code": null, "e": 26742, "s": 26649, "text": "In this article, we will learn How can we install the Kotlin programming language in Linux. " }, { "code": null, "e": 26806, "s": 26742, "text": "Follow the below steps to install Koptlin on your Linux system." }, { "code": null, "e": 26832, "s": 26806, "text": "Step 1: Upgrade Packages " }, { "code": null, "e": 26922, "s": 26832, "text": "Open your Linux terminal and update your package information from all configured sources." }, { "code": null, "e": 26940, "s": 26922, "text": "# sudo apt update" }, { "code": null, "e": 26960, "s": 26940, "text": "Step 2: Install JDK" }, { "code": null, "e": 27167, "s": 26960, "text": "Install the Java Software Development Kit (JDK). Kotlin is based on JDK. JDK is used to compile Kotlin programs. When you run the following command you will be asked to enter Y or N enter Y and click enter." }, { "code": null, "e": 27198, "s": 27167, "text": "# sudo apt install default-jdk" }, { "code": null, "e": 27234, "s": 27198, "text": "Step 3: Install Kotlin using SDKMAN" }, { "code": null, "e": 27346, "s": 27234, "text": "SDKMAN is an easier way to install Kotlin on UNIX-based systems. After Installing SDKMAN restart your computer." }, { "code": null, "e": 27385, "s": 27346, "text": "# curl -s https://get.sdkman.io | bash" }, { "code": null, "e": 27441, "s": 27385, "text": "Now we will install Kotlin using the following command." }, { "code": null, "e": 27462, "s": 27441, "text": "# sdk install kotlin" }, { "code": null, "e": 27609, "s": 27462, "text": "After executing the above command Kotlin will be installed in your system. Now we will create a Kotlin file and check it by doing compile and run." }, { "code": null, "e": 27638, "s": 27609, "text": "Step 4: Create a Kotlin file" }, { "code": null, "e": 27778, "s": 27638, "text": "Open any editor and write the following code there and save that file with the .kt extension. Here I’m creating a file with Kotlin.kt name." }, { "code": null, "e": 27931, "s": 27778, "text": "For creating a file write nano fileName.kt in your terminal. Then write your Kotlin code inside that file and save it using ctrl + x and then press y. " }, { "code": null, "e": 27938, "s": 27931, "text": "Kotlin" }, { "code": "// Function in Kotlinfun main(args: Array<String>) { // Print statement println(\"GeeksforGeeks\")}", "e": 28046, "s": 27938, "text": null }, { "code": null, "e": 28074, "s": 28046, "text": "Step 5: Compile Kotlin file" }, { "code": null, "e": 28305, "s": 28074, "text": "Navigate to that folder in which you have created your Kotlin file and then compile that file using the following command. Replace Kotlin.kt with your file name and The value of the -d option specifies the name of the output file." }, { "code": null, "e": 28360, "s": 28305, "text": "# kotlinc Kotlin.kt -include-runtime -d outPutFile.jar" }, { "code": null, "e": 28391, "s": 28360, "text": "Step 6: Run the Kotlin Program" }, { "code": null, "e": 28454, "s": 28391, "text": "Now we will check the output by running the following command." }, { "code": null, "e": 28481, "s": 28454, "text": "# java -jar outPutFile.jar" }, { "code": null, "e": 28489, "s": 28481, "text": "Output:" }, { "code": null, "e": 28503, "s": 28489, "text": "GeeksforGeeks" }, { "code": null, "e": 28518, "s": 28503, "text": "how-to-install" }, { "code": null, "e": 28525, "s": 28518, "text": "Picked" }, { "code": null, "e": 28532, "s": 28525, "text": "How To" }, { "code": null, "e": 28551, "s": 28532, "text": "Installation Guide" }, { "code": null, "e": 28649, "s": 28551, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28683, "s": 28649, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 28741, "s": 28683, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 28790, "s": 28741, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 28837, "s": 28790, "text": "How to create a nested RecyclerView in Android" }, { "code": null, "e": 28897, "s": 28837, "text": "How to Create and Setup Spring Boot Project in Eclipse IDE?" }, { "code": null, "e": 28930, "s": 28897, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28964, "s": 28930, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 28999, "s": 28964, "text": "How to Install Pygame on Windows ?" }, { "code": null, "e": 29057, "s": 28999, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" } ]
How to return custom result type from an action method in C# ASP.NET WebAPI?
We can create our own custom class as a result type by implementing IHttpActionResult interface. IHttpActionResult contains a single method, ExecuteAsync, which asynchronously creates an HttpResponseMessage instance. public interface IHttpActionResult { Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken); } If a controller action returns an IHttpActionResult, Web API calls the ExecuteAsync method to create an HttpResponseMessage. Then it converts the HttpResponseMessage into an HTTP response message. To have our own custom result we must create a class that implements IHttpActionResult interface. using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http; namespace DemoWebApplication.Controllers{ public class CustomResult : IHttpActionResult{ string _value; HttpRequestMessage _request; public CustomResult(string value, HttpRequestMessage request){ _value = value; _request = request; } public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken){ var response = new HttpResponseMessage(){ Content = new StringContent($"Customized Result: {_value}"), RequestMessage = _request }; return Task.FromResult(response); } } } Contoller Action − using DemoWebApplication.Models; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace DemoWebApplication.Controllers{ public class DemoController : ApiController{ public IHttpActionResult Get(int id){ List<Student> students = new List<Student>{ new Student{ Id = 1, Name = "Mark" }, new Student{ Id = 2, Name = "John" } }; var studentForId = students.FirstOrDefault(x => x.Id == id); return new CustomResult(studentForId.Name, Request); } } } Here is the postman output of the endpoint which returns custom result.
[ { "code": null, "e": 1279, "s": 1062, "text": "We can create our own custom class as a result type by implementing IHttpActionResult interface. IHttpActionResult contains a single method,\nExecuteAsync, which asynchronously creates an HttpResponseMessage instance." }, { "code": null, "e": 1401, "s": 1279, "text": "public interface IHttpActionResult\n{\n Task<HttpResponseMessage> ExecuteAsync(CancellationToken\n cancellationToken);\n}" }, { "code": null, "e": 1598, "s": 1401, "text": "If a controller action returns an IHttpActionResult, Web API calls the ExecuteAsync\nmethod to create an HttpResponseMessage. Then it converts the HttpResponseMessage into an HTTP response message." }, { "code": null, "e": 1696, "s": 1598, "text": "To have our own custom result we must create a class that implements\nIHttpActionResult interface." }, { "code": null, "e": 2403, "s": 1696, "text": "using System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http;\nnamespace DemoWebApplication.Controllers{\n public class CustomResult : IHttpActionResult{\n string _value;\n HttpRequestMessage _request;\n public CustomResult(string value, HttpRequestMessage request){\n _value = value;\n _request = request;\n }\n public Task<HttpResponseMessage> ExecuteAsync(CancellationToken\n cancellationToken){\n var response = new HttpResponseMessage(){\n Content = new StringContent($\"Customized Result: {_value}\"),\n RequestMessage = _request\n };\n return Task.FromResult(response);\n }\n }\n}" }, { "code": null, "e": 2422, "s": 2403, "text": "Contoller Action −" }, { "code": null, "e": 3060, "s": 2422, "text": "using DemoWebApplication.Models;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Http;\nnamespace DemoWebApplication.Controllers{\n public class DemoController : ApiController{\n public IHttpActionResult Get(int id){\n List<Student> students = new List<Student>{\n new Student{\n Id = 1,\n Name = \"Mark\"\n },\n new Student{\n Id = 2,\n Name = \"John\"\n }\n };\n var studentForId = students.FirstOrDefault(x => x.Id == id);\n return new CustomResult(studentForId.Name, Request);\n }\n }\n}" }, { "code": null, "e": 3132, "s": 3060, "text": "Here is the postman output of the endpoint which returns custom result." } ]
Generating Lyndon words of length n - GeeksforGeeks
25 Feb, 2019 Given an integer n and an array of characters S, the task is to generate Lyndon words of length n having characters from S. A Lyndon word is a string which is strictly less than all of its rotations in lexicographic order. For example, the string “012” is a Lyndon word as it is less than its rotations “120” and “201”, but “102” is not a Lyndon word as it is greater than its rotation “021”.Note: “000” is not considered to be a Lyndon word as it is equal to the string obtained by rotating it. Examples: Input: n = 2, S = {0, 1, 2}Output: 010212Other possible strings of length 2 are “00”, “11”, “20”, “21”, and “22”. All of these are eithergreater than or equal to one of their rotations. Input: n = 1, S = {0, 1, 2}Output: 012 Approach: There exists an efficient approach to generate Lyndon words which was given by Jean-Pierre Duval, which can be used to generate all the Lyndon words upto length n in time proportional to the number of such words. (Please refer to the paper “Average cost of Duval’s algorithm for generating Lyndon words” by Berstel et al. for the proof)The algorithm generates the Lyndon words in a lexicographic order. If w is a Lyndon word, the next word is obtained by the following steps: Repeat w to form a string v of length n, such that v[i] = w[i mod |w|].While the last character of v is the last one in the sorted ordering of S, remove it.Replace the last character of v by its successor in the sorted ordering of S. Repeat w to form a string v of length n, such that v[i] = w[i mod |w|]. While the last character of v is the last one in the sorted ordering of S, remove it. Replace the last character of v by its successor in the sorted ordering of S. For example, if n = 5, S = {a, b, c, d}, and w = “add” then we get v = “addad”.Since ‘d’ is the last character in the sorted ordering of S, we remove it to get “adda”and then replace the last ‘a’ by its successor ‘b’ to get the Lyndon word “addb”. Below is the implementation of the above approach: C++ Python3 // C++ implementation of // the above approach #include<bits/stdc++.h>using namespace std; int main(){ int n = 2; char S[] = {'0', '1', '2' }; int k = 3; sort(S, S + 3); // To store the indices // of the characters vector<int> w; w.push_back(-1); // Loop till w is not empty while(w.size() > 0) { // Incrementing the last character w[w.size()-1]++; int m = w.size(); if(m == n) { string str; for(int i = 0; i < w.size(); i++) { str += S[w[i]]; } cout << str << endl; } // Repeating w to get a // n-length string while(w.size() < n) { w.push_back(w[w.size() - m]); } // Removing the last character // as long it is equal to // the largest character in S while(w.size() > 0 && w[w.size() - 1] == k - 1) { w.pop_back(); } } return 0;} // This code is contributed by AdeshSingh1 # Python implementation of# the above approach n = 2S = ['0', '1', '2']k = len(S)S.sort() # To store the indices# of the charactersw = [-1] # Loop till w is not emptywhile w: # Incrementing the last character w[-1] += 1 m = len(w) if m == n: print(''.join(S[i] for i in w)) # Repeating w to get a # n-length string while len(w) < n: w.append(w[-m]) # Removing the last character # as long it is equal to # the largest character in S while w and w[-1] == k - 1: w.pop() 01 02 12 AdeshSingh1 rotation Technical Scripter 2018 Combinatorial Strings Technical Scripter Strings Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Combinations with repetitions Largest number by rearranging digits of a given positive or negative number Ways to sum to N using Natural Numbers up to K with repetitions allowed Given number of matches played, find number of teams in tournament Generate all possible combinations of at most X characters from a given array Reverse a string in Java Write a program to reverse an array or string Longest Common Subsequence | DP-4 C++ Data Types Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 25476, "s": 25448, "text": "\n25 Feb, 2019" }, { "code": null, "e": 25600, "s": 25476, "text": "Given an integer n and an array of characters S, the task is to generate Lyndon words of length n having characters from S." }, { "code": null, "e": 25972, "s": 25600, "text": "A Lyndon word is a string which is strictly less than all of its rotations in lexicographic order. For example, the string “012” is a Lyndon word as it is less than its rotations “120” and “201”, but “102” is not a Lyndon word as it is greater than its rotation “021”.Note: “000” is not considered to be a Lyndon word as it is equal to the string obtained by rotating it." }, { "code": null, "e": 25982, "s": 25972, "text": "Examples:" }, { "code": null, "e": 26168, "s": 25982, "text": "Input: n = 2, S = {0, 1, 2}Output: 010212Other possible strings of length 2 are “00”, “11”, “20”, “21”, and “22”. All of these are eithergreater than or equal to one of their rotations." }, { "code": null, "e": 26207, "s": 26168, "text": "Input: n = 1, S = {0, 1, 2}Output: 012" }, { "code": null, "e": 26693, "s": 26207, "text": "Approach: There exists an efficient approach to generate Lyndon words which was given by Jean-Pierre Duval, which can be used to generate all the Lyndon words upto length n in time proportional to the number of such words. (Please refer to the paper “Average cost of Duval’s algorithm for generating Lyndon words” by Berstel et al. for the proof)The algorithm generates the Lyndon words in a lexicographic order. If w is a Lyndon word, the next word is obtained by the following steps:" }, { "code": null, "e": 26927, "s": 26693, "text": "Repeat w to form a string v of length n, such that v[i] = w[i mod |w|].While the last character of v is the last one in the sorted ordering of S, remove it.Replace the last character of v by its successor in the sorted ordering of S." }, { "code": null, "e": 26999, "s": 26927, "text": "Repeat w to form a string v of length n, such that v[i] = w[i mod |w|]." }, { "code": null, "e": 27085, "s": 26999, "text": "While the last character of v is the last one in the sorted ordering of S, remove it." }, { "code": null, "e": 27163, "s": 27085, "text": "Replace the last character of v by its successor in the sorted ordering of S." }, { "code": null, "e": 27411, "s": 27163, "text": "For example, if n = 5, S = {a, b, c, d}, and w = “add” then we get v = “addad”.Since ‘d’ is the last character in the sorted ordering of S, we remove it to get “adda”and then replace the last ‘a’ by its successor ‘b’ to get the Lyndon word “addb”." }, { "code": null, "e": 27462, "s": 27411, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27466, "s": 27462, "text": "C++" }, { "code": null, "e": 27474, "s": 27466, "text": "Python3" }, { "code": "// C++ implementation of // the above approach #include<bits/stdc++.h>using namespace std; int main(){ int n = 2; char S[] = {'0', '1', '2' }; int k = 3; sort(S, S + 3); // To store the indices // of the characters vector<int> w; w.push_back(-1); // Loop till w is not empty while(w.size() > 0) { // Incrementing the last character w[w.size()-1]++; int m = w.size(); if(m == n) { string str; for(int i = 0; i < w.size(); i++) { str += S[w[i]]; } cout << str << endl; } // Repeating w to get a // n-length string while(w.size() < n) { w.push_back(w[w.size() - m]); } // Removing the last character // as long it is equal to // the largest character in S while(w.size() > 0 && w[w.size() - 1] == k - 1) { w.pop_back(); } } return 0;} // This code is contributed by AdeshSingh1", "e": 28546, "s": 27474, "text": null }, { "code": "# Python implementation of# the above approach n = 2S = ['0', '1', '2']k = len(S)S.sort() # To store the indices# of the charactersw = [-1] # Loop till w is not emptywhile w: # Incrementing the last character w[-1] += 1 m = len(w) if m == n: print(''.join(S[i] for i in w)) # Repeating w to get a # n-length string while len(w) < n: w.append(w[-m]) # Removing the last character # as long it is equal to # the largest character in S while w and w[-1] == k - 1: w.pop()", "e": 29082, "s": 28546, "text": null }, { "code": null, "e": 29092, "s": 29082, "text": "01\n02\n12\n" }, { "code": null, "e": 29104, "s": 29092, "text": "AdeshSingh1" }, { "code": null, "e": 29113, "s": 29104, "text": "rotation" }, { "code": null, "e": 29137, "s": 29113, "text": "Technical Scripter 2018" }, { "code": null, "e": 29151, "s": 29137, "text": "Combinatorial" }, { "code": null, "e": 29159, "s": 29151, "text": "Strings" }, { "code": null, "e": 29178, "s": 29159, "text": "Technical Scripter" }, { "code": null, "e": 29186, "s": 29178, "text": "Strings" }, { "code": null, "e": 29200, "s": 29186, "text": "Combinatorial" }, { "code": null, "e": 29298, "s": 29200, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29307, "s": 29298, "text": "Comments" }, { "code": null, "e": 29320, "s": 29307, "text": "Old Comments" }, { "code": null, "e": 29350, "s": 29320, "text": "Combinations with repetitions" }, { "code": null, "e": 29426, "s": 29350, "text": "Largest number by rearranging digits of a given positive or negative number" }, { "code": null, "e": 29498, "s": 29426, "text": "Ways to sum to N using Natural Numbers up to K with repetitions allowed" }, { "code": null, "e": 29565, "s": 29498, "text": "Given number of matches played, find number of teams in tournament" }, { "code": null, "e": 29643, "s": 29565, "text": "Generate all possible combinations of at most X characters from a given array" }, { "code": null, "e": 29668, "s": 29643, "text": "Reverse a string in Java" }, { "code": null, "e": 29714, "s": 29668, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 29748, "s": 29714, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 29763, "s": 29748, "text": "C++ Data Types" } ]
Bootstrap Tables
A basic Bootstrap table has a light padding and only horizontal dividers. The .table class adds basic styling to a table: The .table-striped class adds zebra-stripes to a table: The .table-bordered class adds borders on all sides of the table and cells: The .table-hover class adds a hover effect (grey background color) on table rows: The .table-condensed class makes a table more compact by cutting cell padding in half: Contextual classes can be used to color table rows (<tr>) or table cells (<td>): The contextual classes that can be used are: The .table-responsive class creates a responsive table. The table will then scroll horizontally on small devices (under 768px). When viewing on anything larger than 768px wide, there is no difference: Add a class attribute to style the table as a basic Bootstrap table. <table > <tr> <td>John</td> <td>Doe</td> <td>[email protected]</td> <tr> <tr> <td>Mary</td> <td>Moe</td> <td>[email protected]</td> </tr> <tr> <td>July</td> <td>Dooley</td> <td>[email protected]</td> </tr> <table> Start the Exercise For a complete reference of all table classes, go to our complete Bootstrap Tables Reference. We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 74, "s": 0, "text": "A basic Bootstrap table has a light padding and only horizontal dividers." }, { "code": null, "e": 122, "s": 74, "text": "The .table class adds basic styling to a table:" }, { "code": null, "e": 178, "s": 122, "text": "The .table-striped class adds zebra-stripes to a table:" }, { "code": null, "e": 254, "s": 178, "text": "The .table-bordered class adds borders on all sides of the table and cells:" }, { "code": null, "e": 336, "s": 254, "text": "The .table-hover class adds a hover effect (grey background color) on table rows:" }, { "code": null, "e": 423, "s": 336, "text": "The .table-condensed class makes a table more compact by cutting cell padding in half:" }, { "code": null, "e": 504, "s": 423, "text": "Contextual classes can be used to color table rows (<tr>) or table cells (<td>):" }, { "code": null, "e": 549, "s": 504, "text": "The contextual classes that can be used are:" }, { "code": null, "e": 752, "s": 549, "text": "The .table-responsive class creates a responsive table. The table will then \nscroll horizontally on small devices (under 768px). When viewing on anything \nlarger than 768px wide, there is no difference:" }, { "code": null, "e": 821, "s": 752, "text": "Add a class attribute to style the table as a basic Bootstrap table." }, { "code": null, "e": 1081, "s": 821, "text": "<table >\n <tr>\n <td>John</td>\n <td>Doe</td>\n <td>[email protected]</td>\n <tr>\n <tr>\n <td>Mary</td>\n <td>Moe</td>\n <td>[email protected]</td>\n </tr>\n <tr>\n <td>July</td>\n <td>Dooley</td>\n <td>[email protected]</td>\n </tr>\n<table>\n" }, { "code": null, "e": 1100, "s": 1081, "text": "Start the Exercise" }, { "code": null, "e": 1194, "s": 1100, "text": "For a complete reference of all table classes, go to our complete\nBootstrap Tables Reference." }, { "code": null, "e": 1227, "s": 1194, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1269, "s": 1227, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1376, "s": 1269, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 1395, "s": 1376, "text": "[email protected]" } ]
Integrating Tableau and R for Regression Analyses | by Emily A. Halford | Towards Data Science
Tableau has taken the data visualization world by storm, and for good reason. Beautiful and complex visualizations, dashboards, and reports can be created quickly and without any coding experience within its user-friendly interface. Tableau is particularly useful for the creation of interactive visualizations, as filters can be added to a single visualization or full dashboard with just a few clicks. However, Tableau is limited in its analytic capabilities. The calculated fields feature allows for simple measures such as means, sums, and date differences to be calculated, and Tableau has some built-in features for adding regression lines or identifying clustering. For any sort of advanced analyses, however, Tableau falls short. R, on the other hand, was created by statisticians and therefore has extraordinary analytic capabilities. Between its built-in functions and those contained within the seemingly endless list of available packages, there’s little that you can’t do in R from an analytic standpoint. However, visualization in R presents more of a challenge. The development of packages like ggplot2 and plotly has significantly advanced R’s data visualization abilities, but these packages are still not as easy to use as Tableau’s interface. It takes a fair amount of coding ability to build a well-designed, interactive dashboard or visualization in R. Even for those with coding expertise, it is simply much more time-consuming to write R code to make one plot in a dashboard act as a filter for others, to add explanatory text, to restructure your data for a particular visualization (which often isn’t even necessary in Tableau), to resize graphs in a dashboard, to apply color, or to accomplish any number of other tasks which can be quickly accomplished in Tableau’s drag-and-drop environment. Fortunately, Tableau is able to connect to R, enabling users to reap the benefits of both tools at once. To demonstrate this process and its usefulness, I will walk through a sample regression analysis conducted using R code and Tableau visualizations. In order for R and Tableau to be used together, a connection has to be set up using the “Rserve” package. First, install the “Rserve” package in R. The first code option is simply the standard code for installing R packages from CRAN. I am also including code for installing the “Rserve” package from RForge, as the CRAN install has frequently given me errors. install.packages('Rserve')ORinstall.packages('Rserve',, "http://rforge.net/", type = "source") Next, just load the newly-installed “Rserve” package: library(Rserve) The only other step that needs to be taken in R is to run the following command, which sets up a socket server and allows requests to be sent to R: Rserve(args = "--no-save") Rserve should now be working, so let’s switch over to Tableau. Under “Help,” click “Settings and Performance” and then “Manage Analytics Extension Connection”: The following “Analytics Extension Connection” window should open. Select “Rserve” as the Analytics Extension, as well as “localhost” for server and “6311" for Port. Once that’s all entered, click the “Test Connection” button in the lower left corner of the window: After you click the Test Connection button, you should receive the following message indicating that your connection has been set up successfully: If you receive this message, then you’re good to go. We will be staying in Tableau for the rest of this tutorial, although we will need to keep R running to maintain the connection. The data that I will be using in this tutorial come from NYC OpenData and represent inmates in custody in New York City. Included variables represent attributes such as mental health designation, race, gender, age, custody level, legal status, sealed status, security risk group membership, top charge, and infraction flag. The data are publicly available and are available for download here. I’m curious as to whether or not custody level (minimum, medium, or maximum) predicts whether or not an individual has a mental health designation, and will create a logistic regression model with mental health designation as my outcome and custody level as my predictor. Before setting up a connection to Tableau, I used the following R code to prepare these data and to write a csv file containing the cleaned data: library(tidyverse)data = read.csv("./Daily_Inmates_In_Custody.csv") %>% mutate( bradh_numeric = ifelse(BRADH == "Y", "1", ifelse(BRADH == "N", "0", BRADH)), bradh_numeric = as.numeric(bradh_numeric), custody_numeric = ifelse(CUSTODY_LEVEL == "MIN", "0", ifelse(CUSTODY_LEVEL == "MED", "1", ifelse(CUSTODY_LEVEL == "MAX", "2", CUSTODY_LEVEL)) ), custody_numeric = as.numeric(custody_numeric)) %>% filter( custody_numeric == 0 | custody_numeric == 1 | custody_numeric == 2 )write_csv(data, "./daily_inmates.csv") Once this file is connected to Tableau (in Tableau, click “Connect to Data,” select “Text File,” and navigate to your csv), we will use a calculated field to create our regression model. Select “Create Calculated Field” from the drop-down menu in the Data panel: I’ve named my calculated field “Regression.” Within the SCRIPT_REAL() calculation function, you can enter your code for analysis in R. If you’re familiar with using logistic regression models in R, then the code below will look extremely familiar. The important difference to get used to in Tableau is that instead of entering your variable names directly into your glm() function, “.arg” placeholders are used and the variables are specified below the glm() code (see Bradh Numeric and Custody Numeric). It’s a bit unintuitive to adjust to at first, so I recommend also running your analysis in R the first few times so that you can check your work. If your calculation can be completed, you will see “The calculation is valid.” in the bottom left corner. If you’re receiving this message, go ahead and hit the green “OK” button. You will now see your calculated field (indicated by the equals sign before the #) with your numeric table elements on the left-hand side of your screen. First, let’s just visualize the fitted values for the three custody levels included in our analysis by dragging the “Custody Level” pill to Columns and the “Regression” pill to Rows. I’ve also added “Custody Level” under Color: These fitted values are hovering around 0.5, indicating that custody level isn’t a great predictor of an individual’s mental health status. But here’s where Tableau really shines. Let’s say that we want to see how this relationship differs based on race and gender. In R, answering this question would involve adding race and gender to our regression model and figuring out fitted values for particular groups of people based upon the resulting coefficients. In Tableau, however, we can simply add these variables as filters to our visualization and interact with the product to see where the relationship is more interesting. Drag the “Race” and “Gender” pills into the Filters box, as shown below: In order to interact with these filters, right-click on the filter pills and select “Show Filter.” You’ll see the filters appear on your screen: When all of the boxes are checked, the regression fitted values remain unchanged because the entire sample is still included in the analysis. By selecting certain boxes, however, it’s easy to instead see the relationship between custody level and mental health designation among Black women: Or white women: Or Asian men: These filters make it easy to see that certain sub-populations do have meaningful relationships between custody level and mental health designation, and that these relationships are very different among varying racial and gender groups. * Note: The data dictionary for this dataset does not provide descriptions of the included racial groups. I am therefore making assumptions about what the single-letter designations stand for. It is also unclear if the gender measure truly represents gender or if it’s really capturing sex. In this example, we used a logistic regression analysis to answer an explanatory question (how does mental health designation differ by custody level, race, and gender?), and visualization served the primary purpose of exploring this relationship. Similar approaches could be taken with other analytic techniques such as k-means clustering, as Tableau’s visualization capabilities provide a useful means of exploring how your clusters change within different subsets of your data. However, the integration of Tableau and R has so much potential beyond simple exploration. For example, integration of these tools is particularly useful for geospatial analyses given that Tableau truly excels at producing maps but lacks this advanced analytic ability. Additionally, these tools can be used together to better visualize predictive analyses such as linear regression or time-series analyses. Projects that require advanced analyses of really any sort, as well as complex and interactive visualizations and dashboards, would likely benefit from the combined capabilities of both Tableau and R. The strengths of Tableau and R complement each other well, and learning how to use them together can maximize your efficiency while simultaneously enhancing your data visualization products.
[ { "code": null, "e": 910, "s": 172, "text": "Tableau has taken the data visualization world by storm, and for good reason. Beautiful and complex visualizations, dashboards, and reports can be created quickly and without any coding experience within its user-friendly interface. Tableau is particularly useful for the creation of interactive visualizations, as filters can be added to a single visualization or full dashboard with just a few clicks. However, Tableau is limited in its analytic capabilities. The calculated fields feature allows for simple measures such as means, sums, and date differences to be calculated, and Tableau has some built-in features for adding regression lines or identifying clustering. For any sort of advanced analyses, however, Tableau falls short." }, { "code": null, "e": 1992, "s": 910, "text": "R, on the other hand, was created by statisticians and therefore has extraordinary analytic capabilities. Between its built-in functions and those contained within the seemingly endless list of available packages, there’s little that you can’t do in R from an analytic standpoint. However, visualization in R presents more of a challenge. The development of packages like ggplot2 and plotly has significantly advanced R’s data visualization abilities, but these packages are still not as easy to use as Tableau’s interface. It takes a fair amount of coding ability to build a well-designed, interactive dashboard or visualization in R. Even for those with coding expertise, it is simply much more time-consuming to write R code to make one plot in a dashboard act as a filter for others, to add explanatory text, to restructure your data for a particular visualization (which often isn’t even necessary in Tableau), to resize graphs in a dashboard, to apply color, or to accomplish any number of other tasks which can be quickly accomplished in Tableau’s drag-and-drop environment." }, { "code": null, "e": 2245, "s": 1992, "text": "Fortunately, Tableau is able to connect to R, enabling users to reap the benefits of both tools at once. To demonstrate this process and its usefulness, I will walk through a sample regression analysis conducted using R code and Tableau visualizations." }, { "code": null, "e": 2351, "s": 2245, "text": "In order for R and Tableau to be used together, a connection has to be set up using the “Rserve” package." }, { "code": null, "e": 2606, "s": 2351, "text": "First, install the “Rserve” package in R. The first code option is simply the standard code for installing R packages from CRAN. I am also including code for installing the “Rserve” package from RForge, as the CRAN install has frequently given me errors." }, { "code": null, "e": 2701, "s": 2606, "text": "install.packages('Rserve')ORinstall.packages('Rserve',, \"http://rforge.net/\", type = \"source\")" }, { "code": null, "e": 2755, "s": 2701, "text": "Next, just load the newly-installed “Rserve” package:" }, { "code": null, "e": 2771, "s": 2755, "text": "library(Rserve)" }, { "code": null, "e": 2919, "s": 2771, "text": "The only other step that needs to be taken in R is to run the following command, which sets up a socket server and allows requests to be sent to R:" }, { "code": null, "e": 2946, "s": 2919, "text": "Rserve(args = \"--no-save\")" }, { "code": null, "e": 3009, "s": 2946, "text": "Rserve should now be working, so let’s switch over to Tableau." }, { "code": null, "e": 3106, "s": 3009, "text": "Under “Help,” click “Settings and Performance” and then “Manage Analytics Extension Connection”:" }, { "code": null, "e": 3372, "s": 3106, "text": "The following “Analytics Extension Connection” window should open. Select “Rserve” as the Analytics Extension, as well as “localhost” for server and “6311\" for Port. Once that’s all entered, click the “Test Connection” button in the lower left corner of the window:" }, { "code": null, "e": 3519, "s": 3372, "text": "After you click the Test Connection button, you should receive the following message indicating that your connection has been set up successfully:" }, { "code": null, "e": 3701, "s": 3519, "text": "If you receive this message, then you’re good to go. We will be staying in Tableau for the rest of this tutorial, although we will need to keep R running to maintain the connection." }, { "code": null, "e": 4094, "s": 3701, "text": "The data that I will be using in this tutorial come from NYC OpenData and represent inmates in custody in New York City. Included variables represent attributes such as mental health designation, race, gender, age, custody level, legal status, sealed status, security risk group membership, top charge, and infraction flag. The data are publicly available and are available for download here." }, { "code": null, "e": 4512, "s": 4094, "text": "I’m curious as to whether or not custody level (minimum, medium, or maximum) predicts whether or not an individual has a mental health designation, and will create a logistic regression model with mental health designation as my outcome and custody level as my predictor. Before setting up a connection to Tableau, I used the following R code to prepare these data and to write a csv file containing the cleaned data:" }, { "code": null, "e": 5127, "s": 4512, "text": "library(tidyverse)data = read.csv(\"./Daily_Inmates_In_Custody.csv\") %>% mutate( bradh_numeric = ifelse(BRADH == \"Y\", \"1\", ifelse(BRADH == \"N\", \"0\", BRADH)), bradh_numeric = as.numeric(bradh_numeric), custody_numeric = ifelse(CUSTODY_LEVEL == \"MIN\", \"0\", ifelse(CUSTODY_LEVEL == \"MED\", \"1\", ifelse(CUSTODY_LEVEL == \"MAX\", \"2\", CUSTODY_LEVEL)) ), custody_numeric = as.numeric(custody_numeric)) %>% filter( custody_numeric == 0 | custody_numeric == 1 | custody_numeric == 2 )write_csv(data, \"./daily_inmates.csv\")" }, { "code": null, "e": 5390, "s": 5127, "text": "Once this file is connected to Tableau (in Tableau, click “Connect to Data,” select “Text File,” and navigate to your csv), we will use a calculated field to create our regression model. Select “Create Calculated Field” from the drop-down menu in the Data panel:" }, { "code": null, "e": 6041, "s": 5390, "text": "I’ve named my calculated field “Regression.” Within the SCRIPT_REAL() calculation function, you can enter your code for analysis in R. If you’re familiar with using logistic regression models in R, then the code below will look extremely familiar. The important difference to get used to in Tableau is that instead of entering your variable names directly into your glm() function, “.arg” placeholders are used and the variables are specified below the glm() code (see Bradh Numeric and Custody Numeric). It’s a bit unintuitive to adjust to at first, so I recommend also running your analysis in R the first few times so that you can check your work." }, { "code": null, "e": 6221, "s": 6041, "text": "If your calculation can be completed, you will see “The calculation is valid.” in the bottom left corner. If you’re receiving this message, go ahead and hit the green “OK” button." }, { "code": null, "e": 6375, "s": 6221, "text": "You will now see your calculated field (indicated by the equals sign before the #) with your numeric table elements on the left-hand side of your screen." }, { "code": null, "e": 6603, "s": 6375, "text": "First, let’s just visualize the fitted values for the three custody levels included in our analysis by dragging the “Custody Level” pill to Columns and the “Regression” pill to Rows. I’ve also added “Custody Level” under Color:" }, { "code": null, "e": 7230, "s": 6603, "text": "These fitted values are hovering around 0.5, indicating that custody level isn’t a great predictor of an individual’s mental health status. But here’s where Tableau really shines. Let’s say that we want to see how this relationship differs based on race and gender. In R, answering this question would involve adding race and gender to our regression model and figuring out fitted values for particular groups of people based upon the resulting coefficients. In Tableau, however, we can simply add these variables as filters to our visualization and interact with the product to see where the relationship is more interesting." }, { "code": null, "e": 7303, "s": 7230, "text": "Drag the “Race” and “Gender” pills into the Filters box, as shown below:" }, { "code": null, "e": 7448, "s": 7303, "text": "In order to interact with these filters, right-click on the filter pills and select “Show Filter.” You’ll see the filters appear on your screen:" }, { "code": null, "e": 7740, "s": 7448, "text": "When all of the boxes are checked, the regression fitted values remain unchanged because the entire sample is still included in the analysis. By selecting certain boxes, however, it’s easy to instead see the relationship between custody level and mental health designation among Black women:" }, { "code": null, "e": 7756, "s": 7740, "text": "Or white women:" }, { "code": null, "e": 7770, "s": 7756, "text": "Or Asian men:" }, { "code": null, "e": 8007, "s": 7770, "text": "These filters make it easy to see that certain sub-populations do have meaningful relationships between custody level and mental health designation, and that these relationships are very different among varying racial and gender groups." }, { "code": null, "e": 8298, "s": 8007, "text": "* Note: The data dictionary for this dataset does not provide descriptions of the included racial groups. I am therefore making assumptions about what the single-letter designations stand for. It is also unclear if the gender measure truly represents gender or if it’s really capturing sex." }, { "code": null, "e": 8779, "s": 8298, "text": "In this example, we used a logistic regression analysis to answer an explanatory question (how does mental health designation differ by custody level, race, and gender?), and visualization served the primary purpose of exploring this relationship. Similar approaches could be taken with other analytic techniques such as k-means clustering, as Tableau’s visualization capabilities provide a useful means of exploring how your clusters change within different subsets of your data." }, { "code": null, "e": 9388, "s": 8779, "text": "However, the integration of Tableau and R has so much potential beyond simple exploration. For example, integration of these tools is particularly useful for geospatial analyses given that Tableau truly excels at producing maps but lacks this advanced analytic ability. Additionally, these tools can be used together to better visualize predictive analyses such as linear regression or time-series analyses. Projects that require advanced analyses of really any sort, as well as complex and interactive visualizations and dashboards, would likely benefit from the combined capabilities of both Tableau and R." } ]
ASP.NET WP - Add Data to Database
In this chapter, we will be covering how to create a page that lets users add data to the Customers table in the database. In this example, you will also understand when the record is inserted, then the page displays the updated table using the ListCustomers.cshtml page that we have created in the previous chapter. In this example, you will also understand when the record is inserted, then the page displays the updated table using the ListCustomers.cshtml page that we have created in the previous chapter. In this page, we also add validation to make sure that the data which the user enters is valid for the database. For example, user has entered data for all the required columns. In this page, we also add validation to make sure that the data which the user enters is valid for the database. For example, user has entered data for all the required columns. Let’s add a new CSHTML file to your website. Enter InsertCustomer.cshtml in the Name field and click OK. Now create a new web page in which the user can insert data in the Customers table, so replace InsertCustomer.cshtml file with the following code. @{ Validation.RequireField("FirstName", "First Name is required."); Validation.RequireField("LastName", "Last Name is required."); Validation.RequireField("Address", "Address is required."); var db = Database.Open("WebPagesCustomers"); var FirstName = Request.Form["FirstName"]; var LastName = Request.Form["LastName"]; var Address = Request.Form["Address"]; if (IsPost && Validation.IsValid()) { // Define the insert query. The values to assign to the // columns in the Customers table are defined as parameters // with the VALUES keyword. if(ModelState.IsValid) { var insertQuery = "INSERT INTO Customers (FirstName, LastName, Address) " + "VALUES (@0, @1, @2)"; db.Execute(insertQuery, FirstName, LastName, Address); // Display the page that lists products. Response.Redirect("~/ListCustomers"); } } } <!DOCTYPE html> <html> <head> <title>Add Customer</title> <style type = "text/css"> label { float:left; width: 8em; text-align: right; margin-right: 0.5em; } fieldset { padding: 1em; border: 1px solid; width: 50em; } legend { padding: 2px 4px; border: 1px solid; font-weight:bold; } .validation-summary-errors { font-weight:bold; color:red; font-size: 11pt; } </style> </head> <body> <h1>Add New Customer</h1> @Html.ValidationSummary("Errors with your submission:") <form method = "post" action = ""> <fieldset> <legend>Add Customer</legend> <div> <label>First Name:</label> <input name = "FirstName" type = "text" size = "50" value = "@FirstName"/> </div> <div> <label>Last Name:</label> <input name = "LastName" type = "text" size = "50" value = "@LastName" /> </div> <div> <label>Address:</label> <input name = "Address" type = "text" size = "50" value = "@Address" /> </div> <div> <label> </label> <input type = "submit" value = "Insert" class = "submit" /> </div> </fieldset> </form> </body> </html> Now let’s run the application and specify the following url − http://localhost:36905/InsertCustomer and you will see the following web page. In the above screenshot, you can see that we have added validation, so you click the insert button without entering any data or miss any of the above mentioned field then you will see that it displays the error message as shown in the following screenshot. Now let’s enter some data in all the fields. Now click on Insert and you will see the updated list of customers as shown in the following screenshot. 51 Lectures 5.5 hours Anadi Sharma 44 Lectures 4.5 hours Kaushik Roy Chowdhury 42 Lectures 18 hours SHIVPRASAD KOIRALA 57 Lectures 3.5 hours University Code 40 Lectures 2.5 hours University Code 138 Lectures 9 hours Bhrugen Patel Print Add Notes Bookmark this page
[ { "code": null, "e": 2408, "s": 2285, "text": "In this chapter, we will be covering how to create a page that lets users add data to the Customers table in the database." }, { "code": null, "e": 2602, "s": 2408, "text": "In this example, you will also understand when the record is inserted, then the page displays the updated table using the ListCustomers.cshtml page that we have created in the previous chapter." }, { "code": null, "e": 2796, "s": 2602, "text": "In this example, you will also understand when the record is inserted, then the page displays the updated table using the ListCustomers.cshtml page that we have created in the previous chapter." }, { "code": null, "e": 2974, "s": 2796, "text": "In this page, we also add validation to make sure that the data which the user enters is valid for the database. For example, user has entered data for all the required columns." }, { "code": null, "e": 3152, "s": 2974, "text": "In this page, we also add validation to make sure that the data which the user enters is valid for the database. For example, user has entered data for all the required columns." }, { "code": null, "e": 3197, "s": 3152, "text": "Let’s add a new CSHTML file to your website." }, { "code": null, "e": 3257, "s": 3197, "text": "Enter InsertCustomer.cshtml in the Name field and click OK." }, { "code": null, "e": 3404, "s": 3257, "text": "Now create a new web page in which the user can insert data in the Customers table, so replace InsertCustomer.cshtml file with the following code." }, { "code": null, "e": 5951, "s": 3404, "text": "@{\n Validation.RequireField(\"FirstName\", \"First Name is required.\");\n Validation.RequireField(\"LastName\", \"Last Name is required.\");\n Validation.RequireField(\"Address\", \"Address is required.\");\n \n var db = Database.Open(\"WebPagesCustomers\");\n var FirstName = Request.Form[\"FirstName\"];\n var LastName = Request.Form[\"LastName\"];\n var Address = Request.Form[\"Address\"];\n \n if (IsPost && Validation.IsValid()) {\n // Define the insert query. The values to assign to the\n // columns in the Customers table are defined as parameters\n // with the VALUES keyword.\n \n if(ModelState.IsValid) {\n var insertQuery = \"INSERT INTO Customers (FirstName, LastName, Address) \" +\n \"VALUES (@0, @1, @2)\";\n db.Execute(insertQuery, FirstName, LastName, Address);\n \n // Display the page that lists products.\n Response.Redirect(\"~/ListCustomers\");\n }\n }\n}\n\n<!DOCTYPE html>\n<html>\n \n <head>\n <title>Add Customer</title>\n <style type = \"text/css\">\n label {\n float:left; \n width: 8em; \n text-align: \n right;\n margin-right: 0.5em;\n }\n fieldset {\n padding: 1em; \n border: 1px solid; \n width: 50em;\n }\n legend {\n padding: 2px 4px; \n border: 1px solid; \n font-weight:bold;\n }\n .validation-summary-errors {\n font-weight:bold; \n color:red;\n font-size: 11pt;\n }\n </style>\n \n </head>\n <body>\n <h1>Add New Customer</h1>\n @Html.ValidationSummary(\"Errors with your submission:\")\n \n <form method = \"post\" action = \"\">\n <fieldset>\n <legend>Add Customer</legend>\n <div>\n <label>First Name:</label>\n <input name = \"FirstName\" type = \"text\" size = \"50\" value = \"@FirstName\"/>\n </div>\n \n <div>\n <label>Last Name:</label>\n <input name = \"LastName\" type = \"text\" size = \"50\" value = \"@LastName\" />\n </div>\n \n <div>\n <label>Address:</label>\n <input name = \"Address\" type = \"text\" size = \"50\" value = \"@Address\" />\n </div>\n \n <div>\n <label> </label>\n <input type = \"submit\" value = \"Insert\" class = \"submit\" />\n </div>\n </fieldset>\n </form>\n \n </body>\n</html>" }, { "code": null, "e": 6092, "s": 5951, "text": "Now let’s run the application and specify the following url − http://localhost:36905/InsertCustomer and you will see the following web page." }, { "code": null, "e": 6349, "s": 6092, "text": "In the above screenshot, you can see that we have added validation, so you click the insert button without entering any data or miss any of the above mentioned field then you will see that it displays the error message as shown in the following screenshot." }, { "code": null, "e": 6394, "s": 6349, "text": "Now let’s enter some data in all the fields." }, { "code": null, "e": 6499, "s": 6394, "text": "Now click on Insert and you will see the updated list of customers as shown in the following screenshot." }, { "code": null, "e": 6534, "s": 6499, "text": "\n 51 Lectures \n 5.5 hours \n" }, { "code": null, "e": 6548, "s": 6534, "text": " Anadi Sharma" }, { "code": null, "e": 6583, "s": 6548, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6606, "s": 6583, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 6640, "s": 6606, "text": "\n 42 Lectures \n 18 hours \n" }, { "code": null, "e": 6660, "s": 6640, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 6695, "s": 6660, "text": "\n 57 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6712, "s": 6695, "text": " University Code" }, { "code": null, "e": 6747, "s": 6712, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6764, "s": 6747, "text": " University Code" }, { "code": null, "e": 6798, "s": 6764, "text": "\n 138 Lectures \n 9 hours \n" }, { "code": null, "e": 6813, "s": 6798, "text": " Bhrugen Patel" }, { "code": null, "e": 6820, "s": 6813, "text": " Print" }, { "code": null, "e": 6831, "s": 6820, "text": " Add Notes" } ]
Contextualized Topic Modeling with Python (EACL2021) | by Federico Bianchi | Towards Data Science
In this blog post, I discuss our latest published paper on topic modeling: Bianchi, F., Terragni, S., Hovy, D., Nozza, D., & Fersini, E. (2021). Cross-lingual Contextualized Topic Models with Zero-shot Learning. European Chapter of the Association for Computational Linguistics (EACL). https://arxiv.org/pdf/2004.07737/ Suppose we have a small set of documents in Portuguese that is not large enough to reliably run standard topic modeling algorithms. However, we have enough English documents in the same domain. With our cross-lingual zero-shot topic model (ZeroShotTM), we can first learn topics on English and then predict topics for Portuguese documents (as long as we use pre-trained representations that account for both English and Portuguese). We also release a Python package that can be used to run topic modeling! Take a look at our github page and at our colab tutorial! Topic models allow us to extract meaningful patterns from text, making it easier to glance over textual data and better understand the latent distributions of topics that live underneath. Say you want to get a bird’s eye view on a set of documents you have at hand; well it is not a great idea to read them one by one, right? Topic models can help: they look at your document collection and they extract recurrent themes. Topic models usually make two main assumptions. First of all, a document can talk about different topics in different proportions. For example, imagine that we have three topics, i.e. “human being”, “evolution” and “diseases”. A document can talk a little about humans, a little about evolution, and the remaining about animals. In probabilistic terms, we can say that it talks 20% about humans, 20% about evolution, and 60% about animals. This can be easily expressed by a multinomial distribution over the topics. This probability distribution is called document-topic distribution. Secondly, a topic in topic modeling is not an unordered list of words: in a topic like “animal, cat, dog, puppy, ” each word of the vocabulary contributes with a specific weight. In other words, also a topic can be expressed by a multinomial distribution, where the words of the vocabulary with the highest probability are the ones that contribute the most to the given topic. This distribution is called word-topic distribution. The most well-known topic model is LDA (Blei et al., 2003) that also assumes that words in a document are independent of each other, i.e. are expressed as Bag Of Words (BoW). Several topic models have been proposed across the years, addressing a wide variety of problems and tasks. State-of-the-art topic models include neural topic models based on variational autoencoders (VAE) (Kingma & Welling, 2014). However, this kind of models usually have to deal with two limitations: Once trained, most topic models cannot deal with unseen words, this is because they are based on Bag of Words (BoW) representations, which cannot account for missing terms.It is difficult to apply topic models to multilingual corpora without combining the vocabulary of multiple languages (Minmo et al, 2009; Jagarlamudi et al, 2010), making the task computationally expensive and without any support for zero-shot learning. Once trained, most topic models cannot deal with unseen words, this is because they are based on Bag of Words (BoW) representations, which cannot account for missing terms. It is difficult to apply topic models to multilingual corpora without combining the vocabulary of multiple languages (Minmo et al, 2009; Jagarlamudi et al, 2010), making the task computationally expensive and without any support for zero-shot learning. How do we solve this? Our new neural topic model, ZeroShotTM, takes care of both problems we just illustrated. ZeroShotTM is a neural variational topic model that is based on recent advances in language pre-training (for example, contextualized word embedding models such as BERT). Yes, you got it right! We propose to combine deep learning based topic models with recent embeddings techniques such as BERT or XLM. A pre-trained representation of the documents is passed to the neural architecture and then used to reconstruct the original BoW of the document. Once the model is trained, ZeroShotTM can generate the representations of the test documents, thus predicting their topic distributions even if the documents contain unseen words during training. Moreover, if we use a multilingual pre-trained representation during training, we can get a significant advantage at test time. Using representations that share the same embedding space allows the model to learn topic representations that are shared by documents in different languages. A trained model can then predict the topics of documents in unseen languages during training. We extend a neural topic model, ProdLDA (Srivastava & Sutton, 2017), that is based on a Variational Autoencoder. ProdLDA takes as input the BoW representation of a document and learns two parameters μ and σ2 of a Gaussian distribution. A continuous latent representation is sampled from these parameters and then passed through a softplus, thus obtaining the document-topic distribution of the document. Then, this topic-document representation is used to reconstruct the original document BOW representation. Instead of using the BoW representation of documents as model input, we pass the pre-trained document representation to the neural architecture and then use it to reconstruct the original BoW of the document. Once the model is trained, ZeroShotTM can generate the representations of the test documents, thus predicting their topic distributions even if the documents contain unseen words during training. ZeroShotTM has two main advantages: 1) it can handle missing words in the test set and 2) inherits the multilingual capabilities of recent pre-trained multilingual models. With standard topic models, you often have to remove from the data those words you have in the test set but that are missing in the training set. In this case, since we rely on a contextualized model, we can use it to build the document representation of the test document expressing the full power of these embeddings. Moreover, standard multilingual topic modeling requires to take care of multiple language vocabularies. ZeroShotTM can be trained on English data (that is a data-rich language) and tested on more low resource data. For example, you can train it on English Wikipedia documents and test it on completely unseen Portuguese documents, as we show in the paper. We have built an entire package around this model. You can run the topic models and get results with a few lines of code. On the package homepage, we have different Colab Notebooks that can help you run experiments. You can follow the example here or directly on colab. Depending on the use case, you might want to use a specific contextualized model. In this case, we are going to use the distiluse-base-multilingual-cased model. When using topic models, it is always better to perform text pre-processing, but when we are dealing with contextualized models, such as BERT or the Universal Sentence Encoder it might be better not to do much pre-processing (as these models are contextual and use the context a lot). We are going to train a topic model on English Wikipedia documents and predict the topics for Italian documents. The first thing you need to do is to install the package, from the command line you can run: Be sure to install the correct PyTorch version for your system and also, if you want to use CUDA, install the version that supports CUDA (you might find it easier to use colab). Let’s download some data, we are going to get them from an online repository. These two commands will download the English abstracts and the Italian documents. If you open the English file, the first document you see should contain the following text: The Mid-Peninsula Highway is a proposed freeway across the Niagara Peninsula in the Canadian province of Ontario. Although plans for a highway connecting Hamilton to Fort Erie south of the Niagara Escarpment have surfaced for decades,it was not until The Niagara... Now, let’s apply some preprocessing. We need this step to create the bag of words that is going to be used by our model to represent the topics; Nevertheless, we will still use the non pre-processed dataset to generate the representations from distiluse-base-multilingual-cased model. Our pre-processed documents will contain only the 2K most frequent words, this is an optimization step that allows us to remove words that might not be too meaningful. The TopicModelDataPreparation object allows us to create our dataset to train the topic model. Then with the use of our ZeroShotTM object, we can train the model. One thing we can quickly check is our topics. Running the following method should get you some topics in output They are noice, ain’t they? [['house', 'built', 'located', 'national', 'historic'], ['family', 'found', 'species', 'mm', 'moth'], ['district', 'village', 'km', 'county', 'west'], ['station', 'line', 'railway', 'river', 'near'], ['member', 'politician', 'party', 'general', 'political'],...... If you want to have a better visualization you can get it using this: So now, we need to do some inferences. We could nonetheless predict the topic from some new unseen English documents, but why don’t we try with Italian? The procedure is similar to what we have already seen; in this case, we are going to collect the topic distributions for each document and extract the most probable topic for each document. The document contained the following text, about a movie: Bound - Torbido inganno (Bound) è un film del 1996 scritto e diretto da Lana e Lilly Wachowski. È il primo film diretto dalle sorelle Wachowski, prima del grande successo cinematografico e mediatico di Matrix, che avverrà quasi quattro anni dopo Look at the predicted topic: ['film', 'produced', 'released', 'series', 'directed', 'television', 'written', 'starring', 'game', 'album'] Makes sense, right? This ends this blog post, feel free to send me an email if you have questions or if you have something you’d like to discuss :) You can also find me on Twitter. Blei, D. M., Ng, A. Y., & Jordan, M. I. (2003). Latent dirichlet allocation. JMLR. Jagarlamudi, J., & Daumé, H. (2010). Extracting multilingual topics from unaligned comparable corpora. ECIR. Kingma, D. P., & Welling, M. (2014). Auto-encoding variational bayes. ICLR. Mimno, D., Wallach, H., Naradowsky, J., Smith, D. A., & McCallum, A. (2009, August). Polylingual topic models. EMNLP. Srivastava, A., & Sutton, C. (2017). Autoencoding variational inference for topic models. ICLR. The content of this blog post has been mainly written by me and by Silvia Terragni. Many thanks to Debora Nozza and Dirk Hovy for the comments on a previous version of this article.
[ { "code": null, "e": 247, "s": 172, "text": "In this blog post, I discuss our latest published paper on topic modeling:" }, { "code": null, "e": 492, "s": 247, "text": "Bianchi, F., Terragni, S., Hovy, D., Nozza, D., & Fersini, E. (2021). Cross-lingual Contextualized Topic Models with Zero-shot Learning. European Chapter of the Association for Computational Linguistics (EACL). https://arxiv.org/pdf/2004.07737/" }, { "code": null, "e": 925, "s": 492, "text": "Suppose we have a small set of documents in Portuguese that is not large enough to reliably run standard topic modeling algorithms. However, we have enough English documents in the same domain. With our cross-lingual zero-shot topic model (ZeroShotTM), we can first learn topics on English and then predict topics for Portuguese documents (as long as we use pre-trained representations that account for both English and Portuguese)." }, { "code": null, "e": 1056, "s": 925, "text": "We also release a Python package that can be used to run topic modeling! Take a look at our github page and at our colab tutorial!" }, { "code": null, "e": 1382, "s": 1056, "text": "Topic models allow us to extract meaningful patterns from text, making it easier to glance over textual data and better understand the latent distributions of topics that live underneath. Say you want to get a bird’s eye view on a set of documents you have at hand; well it is not a great idea to read them one by one, right?" }, { "code": null, "e": 1478, "s": 1382, "text": "Topic models can help: they look at your document collection and they extract recurrent themes." }, { "code": null, "e": 1526, "s": 1478, "text": "Topic models usually make two main assumptions." }, { "code": null, "e": 2063, "s": 1526, "text": "First of all, a document can talk about different topics in different proportions. For example, imagine that we have three topics, i.e. “human being”, “evolution” and “diseases”. A document can talk a little about humans, a little about evolution, and the remaining about animals. In probabilistic terms, we can say that it talks 20% about humans, 20% about evolution, and 60% about animals. This can be easily expressed by a multinomial distribution over the topics. This probability distribution is called document-topic distribution." }, { "code": null, "e": 2493, "s": 2063, "text": "Secondly, a topic in topic modeling is not an unordered list of words: in a topic like “animal, cat, dog, puppy, ” each word of the vocabulary contributes with a specific weight. In other words, also a topic can be expressed by a multinomial distribution, where the words of the vocabulary with the highest probability are the ones that contribute the most to the given topic. This distribution is called word-topic distribution." }, { "code": null, "e": 2899, "s": 2493, "text": "The most well-known topic model is LDA (Blei et al., 2003) that also assumes that words in a document are independent of each other, i.e. are expressed as Bag Of Words (BoW). Several topic models have been proposed across the years, addressing a wide variety of problems and tasks. State-of-the-art topic models include neural topic models based on variational autoencoders (VAE) (Kingma & Welling, 2014)." }, { "code": null, "e": 2971, "s": 2899, "text": "However, this kind of models usually have to deal with two limitations:" }, { "code": null, "e": 3396, "s": 2971, "text": "Once trained, most topic models cannot deal with unseen words, this is because they are based on Bag of Words (BoW) representations, which cannot account for missing terms.It is difficult to apply topic models to multilingual corpora without combining the vocabulary of multiple languages (Minmo et al, 2009; Jagarlamudi et al, 2010), making the task computationally expensive and without any support for zero-shot learning." }, { "code": null, "e": 3569, "s": 3396, "text": "Once trained, most topic models cannot deal with unseen words, this is because they are based on Bag of Words (BoW) representations, which cannot account for missing terms." }, { "code": null, "e": 3822, "s": 3569, "text": "It is difficult to apply topic models to multilingual corpora without combining the vocabulary of multiple languages (Minmo et al, 2009; Jagarlamudi et al, 2010), making the task computationally expensive and without any support for zero-shot learning." }, { "code": null, "e": 3844, "s": 3822, "text": "How do we solve this?" }, { "code": null, "e": 4104, "s": 3844, "text": "Our new neural topic model, ZeroShotTM, takes care of both problems we just illustrated. ZeroShotTM is a neural variational topic model that is based on recent advances in language pre-training (for example, contextualized word embedding models such as BERT)." }, { "code": null, "e": 4237, "s": 4104, "text": "Yes, you got it right! We propose to combine deep learning based topic models with recent embeddings techniques such as BERT or XLM." }, { "code": null, "e": 4579, "s": 4237, "text": "A pre-trained representation of the documents is passed to the neural architecture and then used to reconstruct the original BoW of the document. Once the model is trained, ZeroShotTM can generate the representations of the test documents, thus predicting their topic distributions even if the documents contain unseen words during training." }, { "code": null, "e": 4960, "s": 4579, "text": "Moreover, if we use a multilingual pre-trained representation during training, we can get a significant advantage at test time. Using representations that share the same embedding space allows the model to learn topic representations that are shared by documents in different languages. A trained model can then predict the topics of documents in unseen languages during training." }, { "code": null, "e": 5470, "s": 4960, "text": "We extend a neural topic model, ProdLDA (Srivastava & Sutton, 2017), that is based on a Variational Autoencoder. ProdLDA takes as input the BoW representation of a document and learns two parameters μ and σ2 of a Gaussian distribution. A continuous latent representation is sampled from these parameters and then passed through a softplus, thus obtaining the document-topic distribution of the document. Then, this topic-document representation is used to reconstruct the original document BOW representation." }, { "code": null, "e": 5875, "s": 5470, "text": "Instead of using the BoW representation of documents as model input, we pass the pre-trained document representation to the neural architecture and then use it to reconstruct the original BoW of the document. Once the model is trained, ZeroShotTM can generate the representations of the test documents, thus predicting their topic distributions even if the documents contain unseen words during training." }, { "code": null, "e": 6047, "s": 5875, "text": "ZeroShotTM has two main advantages: 1) it can handle missing words in the test set and 2) inherits the multilingual capabilities of recent pre-trained multilingual models." }, { "code": null, "e": 6471, "s": 6047, "text": "With standard topic models, you often have to remove from the data those words you have in the test set but that are missing in the training set. In this case, since we rely on a contextualized model, we can use it to build the document representation of the test document expressing the full power of these embeddings. Moreover, standard multilingual topic modeling requires to take care of multiple language vocabularies." }, { "code": null, "e": 6723, "s": 6471, "text": "ZeroShotTM can be trained on English data (that is a data-rich language) and tested on more low resource data. For example, you can train it on English Wikipedia documents and test it on completely unseen Portuguese documents, as we show in the paper." }, { "code": null, "e": 6939, "s": 6723, "text": "We have built an entire package around this model. You can run the topic models and get results with a few lines of code. On the package homepage, we have different Colab Notebooks that can help you run experiments." }, { "code": null, "e": 6993, "s": 6939, "text": "You can follow the example here or directly on colab." }, { "code": null, "e": 7154, "s": 6993, "text": "Depending on the use case, you might want to use a specific contextualized model. In this case, we are going to use the distiluse-base-multilingual-cased model." }, { "code": null, "e": 7439, "s": 7154, "text": "When using topic models, it is always better to perform text pre-processing, but when we are dealing with contextualized models, such as BERT or the Universal Sentence Encoder it might be better not to do much pre-processing (as these models are contextual and use the context a lot)." }, { "code": null, "e": 7552, "s": 7439, "text": "We are going to train a topic model on English Wikipedia documents and predict the topics for Italian documents." }, { "code": null, "e": 7645, "s": 7552, "text": "The first thing you need to do is to install the package, from the command line you can run:" }, { "code": null, "e": 7823, "s": 7645, "text": "Be sure to install the correct PyTorch version for your system and also, if you want to use CUDA, install the version that supports CUDA (you might find it easier to use colab)." }, { "code": null, "e": 7983, "s": 7823, "text": "Let’s download some data, we are going to get them from an online repository. These two commands will download the English abstracts and the Italian documents." }, { "code": null, "e": 8075, "s": 7983, "text": "If you open the English file, the first document you see should contain the following text:" }, { "code": null, "e": 8341, "s": 8075, "text": "The Mid-Peninsula Highway is a proposed freeway across the Niagara Peninsula in the Canadian province of Ontario. Although plans for a highway connecting Hamilton to Fort Erie south of the Niagara Escarpment have surfaced for decades,it was not until The Niagara..." }, { "code": null, "e": 8626, "s": 8341, "text": "Now, let’s apply some preprocessing. We need this step to create the bag of words that is going to be used by our model to represent the topics; Nevertheless, we will still use the non pre-processed dataset to generate the representations from distiluse-base-multilingual-cased model." }, { "code": null, "e": 8957, "s": 8626, "text": "Our pre-processed documents will contain only the 2K most frequent words, this is an optimization step that allows us to remove words that might not be too meaningful. The TopicModelDataPreparation object allows us to create our dataset to train the topic model. Then with the use of our ZeroShotTM object, we can train the model." }, { "code": null, "e": 9069, "s": 8957, "text": "One thing we can quickly check is our topics. Running the following method should get you some topics in output" }, { "code": null, "e": 9097, "s": 9069, "text": "They are noice, ain’t they?" }, { "code": null, "e": 9362, "s": 9097, "text": "[['house', 'built', 'located', 'national', 'historic'], ['family', 'found', 'species', 'mm', 'moth'], ['district', 'village', 'km', 'county', 'west'], ['station', 'line', 'railway', 'river', 'near'], ['member', 'politician', 'party', 'general', 'political'],......" }, { "code": null, "e": 9432, "s": 9362, "text": "If you want to have a better visualization you can get it using this:" }, { "code": null, "e": 9585, "s": 9432, "text": "So now, we need to do some inferences. We could nonetheless predict the topic from some new unseen English documents, but why don’t we try with Italian?" }, { "code": null, "e": 9775, "s": 9585, "text": "The procedure is similar to what we have already seen; in this case, we are going to collect the topic distributions for each document and extract the most probable topic for each document." }, { "code": null, "e": 9833, "s": 9775, "text": "The document contained the following text, about a movie:" }, { "code": null, "e": 10082, "s": 9833, "text": "Bound - Torbido inganno (Bound) è un film del 1996 scritto e diretto da Lana e Lilly Wachowski. È il primo film diretto dalle sorelle Wachowski, prima del grande successo cinematografico e mediatico di Matrix, che avverrà quasi quattro anni dopo" }, { "code": null, "e": 10111, "s": 10082, "text": "Look at the predicted topic:" }, { "code": null, "e": 10220, "s": 10111, "text": "['film', 'produced', 'released', 'series', 'directed', 'television', 'written', 'starring', 'game', 'album']" }, { "code": null, "e": 10240, "s": 10220, "text": "Makes sense, right?" }, { "code": null, "e": 10401, "s": 10240, "text": "This ends this blog post, feel free to send me an email if you have questions or if you have something you’d like to discuss :) You can also find me on Twitter." }, { "code": null, "e": 10484, "s": 10401, "text": "Blei, D. M., Ng, A. Y., & Jordan, M. I. (2003). Latent dirichlet allocation. JMLR." }, { "code": null, "e": 10594, "s": 10484, "text": "Jagarlamudi, J., & Daumé, H. (2010). Extracting multilingual topics from unaligned comparable corpora. ECIR." }, { "code": null, "e": 10670, "s": 10594, "text": "Kingma, D. P., & Welling, M. (2014). Auto-encoding variational bayes. ICLR." }, { "code": null, "e": 10788, "s": 10670, "text": "Mimno, D., Wallach, H., Naradowsky, J., Smith, D. A., & McCallum, A. (2009, August). Polylingual topic models. EMNLP." }, { "code": null, "e": 10884, "s": 10788, "text": "Srivastava, A., & Sutton, C. (2017). Autoencoding variational inference for topic models. ICLR." } ]
Install PostgreSQL on Mac - GeeksforGeeks
04 Oct, 2021 This is a step-by-step guide to install PostgreSQL on a Mac OS machine. We will be installing PostgreSQL version 11.3 on Mac using the installer provided by EnterpriseDB in this article. There are three crucial steps for the installation of PostgreSQL as follows: Download PostgreSQL EnterpriseDB installer for MacInstall PostgreSQLVerify the installation Download PostgreSQL EnterpriseDB installer for Mac Install PostgreSQL Verify the installation You can download the latest stable PostgreSQL Installer specific to your Mac OS by clicking here. After downloading the installer run the downloaded dmg package as administrator user and follow the below steps: Step 1: Click the Next button Step 2: Choose the installation folder, where you want PostgreSQL to be installed, and click on Next. Step 3: Select the components as per your requirement to install and click the Next button. Step 4: Select the database directory where you want to store the data an click on Next. Step 5: Set the password for the database superuser (Postgres) Step 6: Set the port for PostgreSQL. Make sure that no other applications are using this port. If unsure leave it to its default (5432) and click on Next. Step 7: Choose the default locale used by the database and click the Next button. Step 8: Click the Next button to start the installation. Wait for the installation to complete, it might take a few minutes. You can check the installation using the below command in the terminal: ps -ef | grep postgres This will result in the below image: anikaseth98 postgreSQL-basics PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. PostgreSQL - Psql commands PostgreSQL - Change Column Type PostgreSQL - For Loops PostgreSQL - Function Returning A Table PostgreSQL - Create Auto-increment Column using SERIAL PostgreSQL - ARRAY_AGG() Function PostgreSQL - CREATE PROCEDURE PostgreSQL - DROP INDEX PostgreSQL - Copy Table PostgreSQL - Cursor
[ { "code": null, "e": 29245, "s": 29217, "text": "\n04 Oct, 2021" }, { "code": null, "e": 29433, "s": 29245, "text": "This is a step-by-step guide to install PostgreSQL on a Mac OS machine. We will be installing PostgreSQL version 11.3 on Mac using the installer provided by EnterpriseDB in this article. " }, { "code": null, "e": 29511, "s": 29433, "text": "There are three crucial steps for the installation of PostgreSQL as follows: " }, { "code": null, "e": 29603, "s": 29511, "text": "Download PostgreSQL EnterpriseDB installer for MacInstall PostgreSQLVerify the installation" }, { "code": null, "e": 29654, "s": 29603, "text": "Download PostgreSQL EnterpriseDB installer for Mac" }, { "code": null, "e": 29673, "s": 29654, "text": "Install PostgreSQL" }, { "code": null, "e": 29697, "s": 29673, "text": "Verify the installation" }, { "code": null, "e": 29797, "s": 29697, "text": "You can download the latest stable PostgreSQL Installer specific to your Mac OS by clicking here. " }, { "code": null, "e": 29911, "s": 29797, "text": "After downloading the installer run the downloaded dmg package as administrator user and follow the below steps: " }, { "code": null, "e": 29942, "s": 29911, "text": "Step 1: Click the Next button " }, { "code": null, "e": 30046, "s": 29942, "text": "Step 2: Choose the installation folder, where you want PostgreSQL to be installed, and click on Next. " }, { "code": null, "e": 30139, "s": 30046, "text": "Step 3: Select the components as per your requirement to install and click the Next button. " }, { "code": null, "e": 30230, "s": 30139, "text": "Step 4: Select the database directory where you want to store the data an click on Next. " }, { "code": null, "e": 30294, "s": 30230, "text": "Step 5: Set the password for the database superuser (Postgres) " }, { "code": null, "e": 30450, "s": 30294, "text": "Step 6: Set the port for PostgreSQL. Make sure that no other applications are using this port. If unsure leave it to its default (5432) and click on Next. " }, { "code": null, "e": 30533, "s": 30450, "text": "Step 7: Choose the default locale used by the database and click the Next button. " }, { "code": null, "e": 30591, "s": 30533, "text": "Step 8: Click the Next button to start the installation. " }, { "code": null, "e": 30661, "s": 30591, "text": "Wait for the installation to complete, it might take a few minutes. " }, { "code": null, "e": 30735, "s": 30661, "text": "You can check the installation using the below command in the terminal: " }, { "code": null, "e": 30758, "s": 30735, "text": "ps -ef | grep postgres" }, { "code": null, "e": 30795, "s": 30758, "text": "This will result in the below image:" }, { "code": null, "e": 30809, "s": 30797, "text": "anikaseth98" }, { "code": null, "e": 30827, "s": 30809, "text": "postgreSQL-basics" }, { "code": null, "e": 30838, "s": 30827, "text": "PostgreSQL" }, { "code": null, "e": 30936, "s": 30838, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30963, "s": 30936, "text": "PostgreSQL - Psql commands" }, { "code": null, "e": 30995, "s": 30963, "text": "PostgreSQL - Change Column Type" }, { "code": null, "e": 31018, "s": 30995, "text": "PostgreSQL - For Loops" }, { "code": null, "e": 31058, "s": 31018, "text": "PostgreSQL - Function Returning A Table" }, { "code": null, "e": 31113, "s": 31058, "text": "PostgreSQL - Create Auto-increment Column using SERIAL" }, { "code": null, "e": 31147, "s": 31113, "text": "PostgreSQL - ARRAY_AGG() Function" }, { "code": null, "e": 31177, "s": 31147, "text": "PostgreSQL - CREATE PROCEDURE" }, { "code": null, "e": 31201, "s": 31177, "text": "PostgreSQL - DROP INDEX" }, { "code": null, "e": 31225, "s": 31201, "text": "PostgreSQL - Copy Table" } ]
Nutanix Interview Experience 2018 - GeeksforGeeks
24 Oct, 2018 Round 1: Coding Round [Hackerrank] – 60 Mins – 2 Ques Q1: Given a set of mutual friends in a class, can you divide the class in two groups such that:For all students in a group, each student is a friend of every other student? Note: Friendship is not transitive, i.e. if A and B are friends, and B and C are friends, it does not imply that A and C are friends. A group having a single student is a valid group in itself. Input:First line of input will contain t: number of test cases First Line of each test case will contain two inputs N, M.N nodes and M relations. Next M lines contains two nodes A, B.A B means A and B are friends. Output: YES if you can, NO if no such division possible. Example:16 71 22 33 12 44 55 66 4Output of this: TRUE 1-2-3 is fully connected subgraph.4-5-6 is fully connected subgraph. Follow Up: GeeksForGeeks Q2: Given a carpet of size a*b [length*breadth] and a box of size c*d, one has to fit the carpet in box in minimum number of moves. A move is to fold the carpet in half, either by length or breadth. One can even turn the carpet by 90 degrees any number of times, won’t be counted as a move. Example:Box = 6 * 10Carpet = 8 * 12 Output: No of moves = 1 Fold the carpet by breadth, 12/2so now carpet is 6*8 and can fit fine. Approach:Try thinking of comparing smaller numbers and larger numbers. and just dividing the bigger number by 2, and rotating as many times needed. Results: The cutoff of this round was passing at least 7/8 test cases of Q2. No one was able to pass all the test cases of Q1. 5 of us proceeded to the next round.Round 2: Debugging Round [Pen and Paper] – 50 Mins A C Code of Infix to Postfix Conversion was provided, 90-100 lines of code. Basic layout of code: struct stack_node { // using linked-list struct for stack nodes // this one seemed fine, no bugs // needed to be taken care of push() // insert at the end approach used here // changed the whole function to use // insert at the beginning approach // even malloc wasn’t used for new nodes pop() // deletion from the end // used deletion from front // free wasn’t used in deletion front() // used to get value of top of node // no issues here bool precedence() // had some issues in parameter // checks, swapped the parameters};main(){ struct node* head; // isn’t null initialised // make sure not to use nullptr, as it’s C int i = 0, j = 0; for (i = 0; i < strlen(infixStr); i++) { if (infixStr[i] >= ‘A’ && infixStr <= ‘Z’) postfix[j] = infixStr[i]; // j++ needed here do { char stackTop = front(head); // no check was done for head == null, // either here or in front () pop(head); // didn’t needed pop at the very first // peek of stack top if (precedence(infixStr[i], stackTop)) { push(infixStr[i], head); break; } else { postfix[j] = infixStr[i]; // many things need to be corrected here // pop ( ) needs to be called here // the postfix j++ bug again // postfix [j++] = stackTop, rather than infixStr } } while (1); printf(“% s”, postFix); // missed adding a ‘\0’ terminator here }}// This is just a gist of the actual code Results: 3 out of 5 proceeded to the next round. Round 3: Interview Round [Face to Face] – 45 MinsCandidate-1:Started with Resume.Discussions on previous job [ had a 1 year experience before M.Tech ].To-and-Fro on what challenges faced as per multiple processors or multi-threads. Explained a bug where malloc initiated system lock and some other signal tried to acquire the lock, a race condition. And the methodology of how to find the source of the problem and asynchronous tasks at the core of it. The interviewer seemed to be happy with it. Only one question was to be discussed in this round. Given a binary tree and a number X, find:all the nodes at a distance X from rootall the nodes at a distance X from leaf nodes Example:Graph:11 11 1 1 11 1 0 0 0 0 0 0and X = 2. Pictorially the graph looked like: Output: Nodes at Distance 2 from Root: 4 [D E F G]Nodes at Distance 2 from Leaf: 2 [ A and B] Follow-Up: Part A of the Question was simple. For Part B:Spent time explaining the different approaches to the solution (starting with Exponential, then O(n^2)).20-25 mins had been gone till this point. Then tried defining structures for creating a graph and using properties of BFS [adjacency list structures].The interviewer stopped me there only and suggested thinking of a different solution, where we don’t even want to create a tree. Since we got the input as a complete binary tree [ as 0’s and 1’s ]So formulated a formula for finding nodes.Formulated a simple solution from it( if a leaf is at input[i][j] position, then it’s resulting nodes would be atinput [i] [j / (2^X)]. Now here comes the tricky part:Interviewer asked me if the resulting solution already contains node “A”, then devise a technique so that we don’t see A again and again. This was sort of a small but an impactful performance improvement.After a few minutes of discussion, gave an approach where we need not lookinput [i] [ j – 2^K] nodes, as they’d give same answer (defined a structure of storing leafs in right to left, and bottom to up manner, keeping count of 0’s in each row). The interviewer asked me to code it up, but I didn’t got much time to do it (maybe he was using a stopwatch or something). Wrote partial code and time’s up. RESULT: SELECTEDCandidate-2:Started with a brief introduction about myself.The same problem (binary tree) was given. I was supposed to write full code including taking input. But I asked if pseudo code would do and he agreed. I did a simple BFS for part (a) and DFS for part (b), an O(n) solution, and he was happy with it. Asked me to optimise once I was done with the code.Discussed a few other questions on my resume later, but seems it was only because I finished early with the code. Asked about my learning expectations at Nutanix, and about problems I faced while doing one of the projects I had mentioned in my resume. RESULT: SELECTED Candidate-3:Started with a small introduction and asked about my hobbies.Same problem was also given to me. I was asked not to write pseudo code and was asked to write the code in python. I was able to solve the first question and wrote the code. I also solved the second problem but struggled with writing code. After around 45-50 min the interviewer stopped me.Later I was asked couple of questions about my resume and previous internship(2-3 min) RESULT: NOT SELECTED Nutanix On-Campus Interview Experiences Nutanix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience for SDE-1 (Off-Campus) Amazon AWS Interview Experience for SDE-1 Zoho Interview | Set 3 (Off-Campus) Difference between ANN, CNN and RNN Amazon Interview Experience Amazon Interview Experience for SDE-1 JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021 Amazon Interview Experience (Off-Campus) 2022 Infosys Interview Experience for DSE 2022 Amazon Interview Experience for SDE-1 (On-Campus)
[ { "code": null, "e": 26319, "s": 26291, "text": "\n24 Oct, 2018" }, { "code": null, "e": 26373, "s": 26319, "text": "Round 1: Coding Round [Hackerrank] – 60 Mins – 2 Ques" }, { "code": null, "e": 26546, "s": 26373, "text": "Q1: Given a set of mutual friends in a class, can you divide the class in two groups such that:For all students in a group, each student is a friend of every other student?" }, { "code": null, "e": 26680, "s": 26546, "text": "Note: Friendship is not transitive, i.e. if A and B are friends, and B and C are friends, it does not imply that A and C are friends." }, { "code": null, "e": 26740, "s": 26680, "text": "A group having a single student is a valid group in itself." }, { "code": null, "e": 26803, "s": 26740, "text": "Input:First line of input will contain t: number of test cases" }, { "code": null, "e": 26886, "s": 26803, "text": "First Line of each test case will contain two inputs N, M.N nodes and M relations." }, { "code": null, "e": 26954, "s": 26886, "text": "Next M lines contains two nodes A, B.A B means A and B are friends." }, { "code": null, "e": 27011, "s": 26954, "text": "Output: YES if you can, NO if no such division possible." }, { "code": null, "e": 27065, "s": 27011, "text": "Example:16 71 22 33 12 44 55 66 4Output of this: TRUE" }, { "code": null, "e": 27134, "s": 27065, "text": "1-2-3 is fully connected subgraph.4-5-6 is fully connected subgraph." }, { "code": null, "e": 27159, "s": 27134, "text": "Follow Up: GeeksForGeeks" }, { "code": null, "e": 27358, "s": 27159, "text": "Q2: Given a carpet of size a*b [length*breadth] and a box of size c*d, one has to fit the carpet in box in minimum number of moves. A move is to fold the carpet in half, either by length or breadth." }, { "code": null, "e": 27450, "s": 27358, "text": "One can even turn the carpet by 90 degrees any number of times, won’t be counted as a move." }, { "code": null, "e": 27486, "s": 27450, "text": "Example:Box = 6 * 10Carpet = 8 * 12" }, { "code": null, "e": 27510, "s": 27486, "text": "Output: No of moves = 1" }, { "code": null, "e": 27581, "s": 27510, "text": "Fold the carpet by breadth, 12/2so now carpet is 6*8 and can fit fine." }, { "code": null, "e": 27729, "s": 27581, "text": "Approach:Try thinking of comparing smaller numbers and larger numbers. and just dividing the bigger number by 2, and rotating as many times needed." }, { "code": null, "e": 27856, "s": 27729, "text": "Results: The cutoff of this round was passing at least 7/8 test cases of Q2. No one was able to pass all the test cases of Q1." }, { "code": null, "e": 27943, "s": 27856, "text": "5 of us proceeded to the next round.Round 2: Debugging Round [Pen and Paper] – 50 Mins" }, { "code": null, "e": 28019, "s": 27943, "text": "A C Code of Infix to Postfix Conversion was provided, 90-100 lines of code." }, { "code": null, "e": 28041, "s": 28019, "text": "Basic layout of code:" }, { "code": "struct stack_node { // using linked-list struct for stack nodes // this one seemed fine, no bugs // needed to be taken care of push() // insert at the end approach used here // changed the whole function to use // insert at the beginning approach // even malloc wasn’t used for new nodes pop() // deletion from the end // used deletion from front // free wasn’t used in deletion front() // used to get value of top of node // no issues here bool precedence() // had some issues in parameter // checks, swapped the parameters};main(){ struct node* head; // isn’t null initialised // make sure not to use nullptr, as it’s C int i = 0, j = 0; for (i = 0; i < strlen(infixStr); i++) { if (infixStr[i] >= ‘A’ && infixStr <= ‘Z’) postfix[j] = infixStr[i]; // j++ needed here do { char stackTop = front(head); // no check was done for head == null, // either here or in front () pop(head); // didn’t needed pop at the very first // peek of stack top if (precedence(infixStr[i], stackTop)) { push(infixStr[i], head); break; } else { postfix[j] = infixStr[i]; // many things need to be corrected here // pop ( ) needs to be called here // the postfix j++ bug again // postfix [j++] = stackTop, rather than infixStr } } while (1); printf(“% s”, postFix); // missed adding a ‘\\0’ terminator here }}// This is just a gist of the actual code", "e": 29739, "s": 28041, "text": null }, { "code": null, "e": 29748, "s": 29739, "text": "Results:" }, { "code": null, "e": 29788, "s": 29748, "text": "3 out of 5 proceeded to the next round." }, { "code": null, "e": 30020, "s": 29788, "text": "Round 3: Interview Round [Face to Face] – 45 MinsCandidate-1:Started with Resume.Discussions on previous job [ had a 1 year experience before M.Tech ].To-and-Fro on what challenges faced as per multiple processors or multi-threads." }, { "code": null, "e": 30241, "s": 30020, "text": "Explained a bug where malloc initiated system lock and some other signal tried to acquire the lock, a race condition. And the methodology of how to find the source of the problem and asynchronous tasks at the core of it." }, { "code": null, "e": 30285, "s": 30241, "text": "The interviewer seemed to be happy with it." }, { "code": null, "e": 30338, "s": 30285, "text": "Only one question was to be discussed in this round." }, { "code": null, "e": 30464, "s": 30338, "text": "Given a binary tree and a number X, find:all the nodes at a distance X from rootall the nodes at a distance X from leaf nodes" }, { "code": null, "e": 30515, "s": 30464, "text": "Example:Graph:11 11 1 1 11 1 0 0 0 0 0 0and X = 2." }, { "code": null, "e": 30550, "s": 30515, "text": "Pictorially the graph looked like:" }, { "code": null, "e": 30558, "s": 30550, "text": "Output:" }, { "code": null, "e": 30644, "s": 30558, "text": "Nodes at Distance 2 from Root: 4 [D E F G]Nodes at Distance 2 from Leaf: 2 [ A and B]" }, { "code": null, "e": 30655, "s": 30644, "text": "Follow-Up:" }, { "code": null, "e": 30690, "s": 30655, "text": "Part A of the Question was simple." }, { "code": null, "e": 30847, "s": 30690, "text": "For Part B:Spent time explaining the different approaches to the solution (starting with Exponential, then O(n^2)).20-25 mins had been gone till this point." }, { "code": null, "e": 31084, "s": 30847, "text": "Then tried defining structures for creating a graph and using properties of BFS [adjacency list structures].The interviewer stopped me there only and suggested thinking of a different solution, where we don’t even want to create a tree." }, { "code": null, "e": 31329, "s": 31084, "text": "Since we got the input as a complete binary tree [ as 0’s and 1’s ]So formulated a formula for finding nodes.Formulated a simple solution from it( if a leaf is at input[i][j] position, then it’s resulting nodes would be atinput [i] [j / (2^X)]." }, { "code": null, "e": 31498, "s": 31329, "text": "Now here comes the tricky part:Interviewer asked me if the resulting solution already contains node “A”, then devise a technique so that we don’t see A again and again." }, { "code": null, "e": 31809, "s": 31498, "text": "This was sort of a small but an impactful performance improvement.After a few minutes of discussion, gave an approach where we need not lookinput [i] [ j – 2^K] nodes, as they’d give same answer (defined a structure of storing leafs in right to left, and bottom to up manner, keeping count of 0’s in each row)." }, { "code": null, "e": 31966, "s": 31809, "text": "The interviewer asked me to code it up, but I didn’t got much time to do it (maybe he was using a stopwatch or something). Wrote partial code and time’s up." }, { "code": null, "e": 32593, "s": 31966, "text": "RESULT: SELECTEDCandidate-2:Started with a brief introduction about myself.The same problem (binary tree) was given. I was supposed to write full code including taking input. But I asked if pseudo code would do and he agreed. I did a simple BFS for part (a) and DFS for part (b), an O(n) solution, and he was happy with it. Asked me to optimise once I was done with the code.Discussed a few other questions on my resume later, but seems it was only because I finished early with the code. Asked about my learning expectations at Nutanix, and about problems I faced while doing one of the projects I had mentioned in my resume." }, { "code": null, "e": 32610, "s": 32593, "text": "RESULT: SELECTED" }, { "code": null, "e": 33060, "s": 32610, "text": "Candidate-3:Started with a small introduction and asked about my hobbies.Same problem was also given to me. I was asked not to write pseudo code and was asked to write the code in python. I was able to solve the first question and wrote the code. I also solved the second problem but struggled with writing code. After around 45-50 min the interviewer stopped me.Later I was asked couple of questions about my resume and previous internship(2-3 min)" }, { "code": null, "e": 33081, "s": 33060, "text": "RESULT: NOT SELECTED" }, { "code": null, "e": 33089, "s": 33081, "text": "Nutanix" }, { "code": null, "e": 33099, "s": 33089, "text": "On-Campus" }, { "code": null, "e": 33121, "s": 33099, "text": "Interview Experiences" }, { "code": null, "e": 33129, "s": 33121, "text": "Nutanix" }, { "code": null, "e": 33227, "s": 33129, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33278, "s": 33227, "text": "Amazon Interview Experience for SDE-1 (Off-Campus)" }, { "code": null, "e": 33320, "s": 33278, "text": "Amazon AWS Interview Experience for SDE-1" }, { "code": null, "e": 33356, "s": 33320, "text": "Zoho Interview | Set 3 (Off-Campus)" }, { "code": null, "e": 33392, "s": 33356, "text": "Difference between ANN, CNN and RNN" }, { "code": null, "e": 33420, "s": 33392, "text": "Amazon Interview Experience" }, { "code": null, "e": 33458, "s": 33420, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 33530, "s": 33458, "text": "JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021" }, { "code": null, "e": 33576, "s": 33530, "text": "Amazon Interview Experience (Off-Campus) 2022" }, { "code": null, "e": 33618, "s": 33576, "text": "Infosys Interview Experience for DSE 2022" } ]
Arduino - Conditional Operator ? :
The conditional operator ? : is the only ternary operator in C. expression1 ? expression2 : expression3 Expression1 is evaluated first. If its value is true, then expression2 is evaluated and expression3 is ignored. If expression1 is evaluated as false, then expression3 evaluates and expression2 is ignored. The result will be a value of either expression2 or expression3 depending upon which of them evaluates as True. Conditional operator associates from right to left. Example /* Find max(a, b): */ max = ( a > b ) ? a : b; /* Convert small letter to capital: */ /* (no parentheses are actually necessary) */ c = ( c >= 'a' && c <= 'z' ) ? ( c - 32 ) : c; expression1 must be a scalar expression; expression2 and expression3 must obey one of the following rules. Both expressions have to be of arithmetic type. expression2 and expression3 are subjected to usual arithmetic conversions, which determines the resulting type. >Both expressions have to be of void type. The resulting type is void. 65 Lectures 6.5 hours Amit Rana 43 Lectures 3 hours Amit Rana 20 Lectures 2 hours Ashraf Said 19 Lectures 1.5 hours Ashraf Said 11 Lectures 47 mins Ashraf Said 9 Lectures 41 mins Ashraf Said Print Add Notes Bookmark this page
[ { "code": null, "e": 2934, "s": 2870, "text": "The conditional operator ? : is the only ternary operator in C." }, { "code": null, "e": 2975, "s": 2934, "text": "expression1 ? expression2 : expression3\n" }, { "code": null, "e": 3292, "s": 2975, "text": "Expression1 is evaluated first. If its value is true, then expression2 is evaluated and expression3 is ignored. If expression1 is evaluated as false, then expression3 evaluates and expression2 is ignored. The result will be a value of either expression2 or expression3 depending upon which of them evaluates as True." }, { "code": null, "e": 3344, "s": 3292, "text": "Conditional operator associates from right to left." }, { "code": null, "e": 3352, "s": 3344, "text": "Example" }, { "code": null, "e": 3531, "s": 3352, "text": "/* Find max(a, b): */\nmax = ( a > b ) ? a : b;\n/* Convert small letter to capital: */\n/* (no parentheses are actually necessary) */\nc = ( c >= 'a' && c <= 'z' ) ? ( c - 32 ) : c;" }, { "code": null, "e": 3638, "s": 3531, "text": "expression1 must be a scalar expression; expression2 and expression3 must obey one of the following rules." }, { "code": null, "e": 3686, "s": 3638, "text": "Both expressions have to be of arithmetic type." }, { "code": null, "e": 3798, "s": 3686, "text": "expression2 and expression3 are subjected to usual arithmetic conversions, which determines the resulting type." }, { "code": null, "e": 3869, "s": 3798, "text": ">Both expressions have to be of void type. The resulting type is void." }, { "code": null, "e": 3904, "s": 3869, "text": "\n 65 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3915, "s": 3904, "text": " Amit Rana" }, { "code": null, "e": 3948, "s": 3915, "text": "\n 43 Lectures \n 3 hours \n" }, { "code": null, "e": 3959, "s": 3948, "text": " Amit Rana" }, { "code": null, "e": 3992, "s": 3959, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 4005, "s": 3992, "text": " Ashraf Said" }, { "code": null, "e": 4040, "s": 4005, "text": "\n 19 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4053, "s": 4040, "text": " Ashraf Said" }, { "code": null, "e": 4085, "s": 4053, "text": "\n 11 Lectures \n 47 mins\n" }, { "code": null, "e": 4098, "s": 4085, "text": " Ashraf Said" }, { "code": null, "e": 4129, "s": 4098, "text": "\n 9 Lectures \n 41 mins\n" }, { "code": null, "e": 4142, "s": 4129, "text": " Ashraf Said" }, { "code": null, "e": 4149, "s": 4142, "text": " Print" }, { "code": null, "e": 4160, "s": 4149, "text": " Add Notes" } ]
How to Install php-curl in Ubuntu ? - GeeksforGeeks
05 Oct, 2021 CURL stands for Client URL. It is a Linux Terminal command which is used to transferring data from one server to another server. It is a free and open-source data transfer tool that uses the following protocols: IMAP, IMAPS, POP, POP3, POP3S, DICT, FILE HTTP, HTTPS, SMB, SMBS, SMTP, SMTPS, FTP, FTPS, TELNET, RTSP, RMTP, and TFTP. It displays a meter-like progress bar while running and indicating various parameters like the amount of transferred data, speed of data transfer and estimated time left. Following are the steps for the installation of PHP-CURL on your Ubuntu system: Step 1: Install PHP libraries for the server by running the following command:$ sudo add-apt-repository ppa:ondrej/php $ sudo add-apt-repository ppa:ondrej/php Step 2: Then, update the server:$ sudo apt update $ sudo apt update Step 3: Now, install CURL.$ sudo apt install curl $ sudo apt install curl Step 4: You can check the version of curl installed by the command:$ dpkg -l curl $ dpkg -l curl Step 5: Once you have installed CURL on Ubuntu 18.04 PHP server, you need to restart your webserver on which PHP is running:If you are using Apache server then use either of the following commands to restart the server:$ sudo service apache2 restartor$ sudo /etc/init.d/apache2 restartSimilarly, if you are using Nginx server, then use either of the following commands:$ sudo systemctl restart nginxor$ sudo /etc/init.d/nginx restart If you are using Apache server then use either of the following commands to restart the server: $ sudo service apache2 restart or $ sudo /etc/init.d/apache2 restart Similarly, if you are using Nginx server, then use either of the following commands: $ sudo systemctl restart nginx or $ sudo /etc/init.d/nginx restart PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. how-to-install PHP-Misc Picked How To Installation Guide PHP PHP Programs Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Align Text in HTML? How to filter object array based on attributes? Java Tutorial How to Install FFmpeg on Windows? How to integrate Git Bash with Visual Studio Code? Installation of Node.js on Linux How to Install FFmpeg on Windows? How to Install Anaconda on Windows? How to Install Pygame on Windows ? How to Add External JAR File to an IntelliJ IDEA Project?
[ { "code": null, "e": 25467, "s": 25439, "text": "\n05 Oct, 2021" }, { "code": null, "e": 25799, "s": 25467, "text": "CURL stands for Client URL. It is a Linux Terminal command which is used to transferring data from one server to another server. It is a free and open-source data transfer tool that uses the following protocols: IMAP, IMAPS, POP, POP3, POP3S, DICT, FILE HTTP, HTTPS, SMB, SMBS, SMTP, SMTPS, FTP, FTPS, TELNET, RTSP, RMTP, and TFTP." }, { "code": null, "e": 25970, "s": 25799, "text": "It displays a meter-like progress bar while running and indicating various parameters like the amount of transferred data, speed of data transfer and estimated time left." }, { "code": null, "e": 26050, "s": 25970, "text": "Following are the steps for the installation of PHP-CURL on your Ubuntu system:" }, { "code": null, "e": 26169, "s": 26050, "text": "Step 1: Install PHP libraries for the server by running the following command:$ sudo add-apt-repository ppa:ondrej/php" }, { "code": null, "e": 26210, "s": 26169, "text": "$ sudo add-apt-repository ppa:ondrej/php" }, { "code": null, "e": 26260, "s": 26210, "text": "Step 2: Then, update the server:$ sudo apt update" }, { "code": null, "e": 26278, "s": 26260, "text": "$ sudo apt update" }, { "code": null, "e": 26328, "s": 26278, "text": "Step 3: Now, install CURL.$ sudo apt install curl" }, { "code": null, "e": 26352, "s": 26328, "text": "$ sudo apt install curl" }, { "code": null, "e": 26434, "s": 26352, "text": "Step 4: You can check the version of curl installed by the command:$ dpkg -l curl" }, { "code": null, "e": 26449, "s": 26434, "text": "$ dpkg -l curl" }, { "code": null, "e": 26883, "s": 26449, "text": "Step 5: Once you have installed CURL on Ubuntu 18.04 PHP server, you need to restart your webserver on which PHP is running:If you are using Apache server then use either of the following commands to restart the server:$ sudo service apache2 restartor$ sudo /etc/init.d/apache2 restartSimilarly, if you are using Nginx server, then use either of the following commands:$ sudo systemctl restart nginxor$ sudo /etc/init.d/nginx restart" }, { "code": null, "e": 26979, "s": 26883, "text": "If you are using Apache server then use either of the following commands to restart the server:" }, { "code": null, "e": 27010, "s": 26979, "text": "$ sudo service apache2 restart" }, { "code": null, "e": 27013, "s": 27010, "text": "or" }, { "code": null, "e": 27048, "s": 27013, "text": "$ sudo /etc/init.d/apache2 restart" }, { "code": null, "e": 27133, "s": 27048, "text": "Similarly, if you are using Nginx server, then use either of the following commands:" }, { "code": null, "e": 27164, "s": 27133, "text": "$ sudo systemctl restart nginx" }, { "code": null, "e": 27167, "s": 27164, "text": "or" }, { "code": null, "e": 27200, "s": 27167, "text": "$ sudo /etc/init.d/nginx restart" }, { "code": null, "e": 27369, "s": 27200, "text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples." }, { "code": null, "e": 27384, "s": 27369, "text": "how-to-install" }, { "code": null, "e": 27393, "s": 27384, "text": "PHP-Misc" }, { "code": null, "e": 27400, "s": 27393, "text": "Picked" }, { "code": null, "e": 27407, "s": 27400, "text": "How To" }, { "code": null, "e": 27426, "s": 27407, "text": "Installation Guide" }, { "code": null, "e": 27430, "s": 27426, "text": "PHP" }, { "code": null, "e": 27443, "s": 27430, "text": "PHP Programs" }, { "code": null, "e": 27460, "s": 27443, "text": "Web Technologies" }, { "code": null, "e": 27487, "s": 27460, "text": "Web technologies Questions" }, { "code": null, "e": 27491, "s": 27487, "text": "PHP" }, { "code": null, "e": 27589, "s": 27491, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27616, "s": 27589, "text": "How to Align Text in HTML?" }, { "code": null, "e": 27664, "s": 27616, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 27678, "s": 27664, "text": "Java Tutorial" }, { "code": null, "e": 27712, "s": 27678, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 27763, "s": 27712, "text": "How to integrate Git Bash with Visual Studio Code?" }, { "code": null, "e": 27796, "s": 27763, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27830, "s": 27796, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 27866, "s": 27830, "text": "How to Install Anaconda on Windows?" }, { "code": null, "e": 27901, "s": 27866, "text": "How to Install Pygame on Windows ?" } ]
Ext.js - Data
Data package is used for loading and saving all the data in the application. Data package has numerous number of classes but the most important classes are − Model Store Proxy The base class for model is Ext.data.Model. It represents an entity in an application. It binds the store data to view. It has mapping of backend data objects to the view dataIndex. The data is fetched with the help of store. For creating a model, we need to extend Ext.data.Model class and we need to define the fields, their name, and mapping. Ext.define('StudentDataModel', { extend: 'Ext.data.Model', fields: [ {name: 'name', mapping : 'name'}, {name: 'age', mapping : 'age'}, {name: 'marks', mapping : 'marks'} ] }); Here, the name should be the same as the dataIndex, which we declare in the view and the mapping should match the data, either static or dynamic from the database, which is to be fetched using store. The base class for store is Ext.data.Store. It contains the data locally cached, which is to be rendered on view with the help of model objects. Store fetches the data using proxies, which has the path defined for services to fetch the backend data. Store data can be fetched in two ways - static or dynamic. For static store, we will have all the data present in the store as shown in the following code. Ext.create('Ext.data.Store', { model: 'StudentDataModel', data: [ { name : "Asha", age : "16", marks : "90" }, { name : "Vinit", age : "18", marks : "95" }, { name : "Anand", age : "20", marks : "68" }, { name : "Niharika", age : "21", marks : "86" }, { name : "Manali", age : "22", marks : "57" } ]; }); Dynamic data can be fetched using proxy. We can have proxy which can fetch data from Ajax, Rest, and Json. The base class for proxy is Ext.data.proxy.Proxy. Proxy is used by Models and Stores to handle the loading and saving of Model data. There are two types of proxies Client Proxy Server Proxy Client proxies include Memory and Local Storage using HTML5 local storage. Server proxies handle data from the remote server using Ajax, Json data, and Rest service. Defining proxies in the server Ext.create('Ext.data.Store', { model: 'StudentDataModel', proxy : { type : 'rest', actionMethods : { read : 'POST' // Get or Post type based on requirement }, url : 'restUrlPathOrJsonFilePath', // here we have to include the rest URL path // which fetches data from database or Json file path where the data is stored reader: { type : 'json', // the type of data which is fetched is of JSON type root : 'data' }, } }); Print Add Notes Bookmark this page
[ { "code": null, "e": 2100, "s": 2023, "text": "Data package is used for loading and saving all the data in the application." }, { "code": null, "e": 2181, "s": 2100, "text": "Data package has numerous number of classes but the most important classes are −" }, { "code": null, "e": 2187, "s": 2181, "text": "Model" }, { "code": null, "e": 2193, "s": 2187, "text": "Store" }, { "code": null, "e": 2199, "s": 2193, "text": "Proxy" }, { "code": null, "e": 2425, "s": 2199, "text": "The base class for model is Ext.data.Model. It represents an entity in an application. It binds the store data to view. It has mapping of backend data objects to the view dataIndex. The data is fetched with the help of store." }, { "code": null, "e": 2545, "s": 2425, "text": "For creating a model, we need to extend Ext.data.Model class and we need to define the fields, their name, and mapping." }, { "code": null, "e": 2748, "s": 2545, "text": "Ext.define('StudentDataModel', {\n extend: 'Ext.data.Model',\n fields: [\n {name: 'name', mapping : 'name'},\n {name: 'age', mapping : 'age'},\n {name: 'marks', mapping : 'marks'}\n ]\n});" }, { "code": null, "e": 2948, "s": 2748, "text": "Here, the name should be the same as the dataIndex, which we declare in the view and the mapping should match the data, either static or dynamic from the database, which is to be fetched using store." }, { "code": null, "e": 3198, "s": 2948, "text": "The base class for store is Ext.data.Store. It contains the data locally cached, which is to be rendered on view with the help of model objects. Store fetches the data using proxies, which has the path defined for services to fetch the backend data." }, { "code": null, "e": 3257, "s": 3198, "text": "Store data can be fetched in two ways - static or dynamic." }, { "code": null, "e": 3354, "s": 3257, "text": "For static store, we will have all the data present in the store as shown in the following code." }, { "code": null, "e": 3698, "s": 3354, "text": "Ext.create('Ext.data.Store', {\n model: 'StudentDataModel',\n data: [\n { name : \"Asha\", age : \"16\", marks : \"90\" },\n { name : \"Vinit\", age : \"18\", marks : \"95\" },\n { name : \"Anand\", age : \"20\", marks : \"68\" },\n { name : \"Niharika\", age : \"21\", marks : \"86\" },\n { name : \"Manali\", age : \"22\", marks : \"57\" }\n ];\n});" }, { "code": null, "e": 3805, "s": 3698, "text": "Dynamic data can be fetched using proxy. We can have proxy which can fetch data from Ajax, Rest, and Json." }, { "code": null, "e": 3938, "s": 3805, "text": "The base class for proxy is Ext.data.proxy.Proxy. Proxy is used by Models and Stores to handle the loading and saving of Model data." }, { "code": null, "e": 3969, "s": 3938, "text": "There are two types of proxies" }, { "code": null, "e": 3982, "s": 3969, "text": "Client Proxy" }, { "code": null, "e": 3995, "s": 3982, "text": "Server Proxy" }, { "code": null, "e": 4070, "s": 3995, "text": "Client proxies include Memory and Local Storage using HTML5 local storage." }, { "code": null, "e": 4161, "s": 4070, "text": "Server proxies handle data from the remote server using Ajax, Json data, and Rest service." }, { "code": null, "e": 4192, "s": 4161, "text": "Defining proxies in the server" }, { "code": null, "e": 4692, "s": 4192, "text": "Ext.create('Ext.data.Store', {\n model: 'StudentDataModel',\n proxy : {\n type : 'rest',\n actionMethods : {\n read : 'POST' // Get or Post type based on requirement\n },\n url : 'restUrlPathOrJsonFilePath', // here we have to include the rest URL path \n // which fetches data from database or Json file path where the data is stored\n reader: {\n type : 'json', // the type of data which is fetched is of JSON type\n root : 'data'\n },\n }\n});" }, { "code": null, "e": 4699, "s": 4692, "text": " Print" }, { "code": null, "e": 4710, "s": 4699, "text": " Add Notes" } ]
Using Lambda Function with Amazon SNS
Amazon SNS is a service used for push notification. In this chapter, we will explain working of AWS Lambda and Amazon SNS with the help of an example where will perform the following actions − Create Topic in SNS Service and use AWS Lambda Add Topics to CloudWatch Create Topic in SNS Service and use AWS Lambda Add Topics to CloudWatch Send SNS text message on phone number given. Send SNS text message on phone number given. To create Topic in SNS Service and use AWS Lambda Add Topics to CloudWatch, we need not follow the steps given below − Create Topic in SNS Create Role for permission in IAM Create AWS Lambda Function Publish to topic to activate trigger Check the message details in CloudWatch service. To send SNS text message on phone number given, we need to do the following − Add code in AWS Lambda to send message to your phone. In this example, we will create a topic in SNS. When details are entered in the topic to publish, AWS Lambda is triggered. The topic details are logged in CloudWatch and a message is sent on phone by AWS Lambda. Here is a basic block diagram which explains the same − You will have to follow the steps given below to create topic in SNS − Login to AWS Console and go to SNS service in Amazon as shown below − Click Simple Notification Service and Create topic in it. Then, you have to click Create new topic button as shown − Enter the Topic name and Display name and click on Create topic. You should see the topic name in the display as follows − To create a Role to work with AWS Lambda and SNS service, we need to login to AWS console. Then, select IAM from Amazon services and click role from left side as shown below. Observe that we have added policies for SNS, Lambda and CloudWatch. Add rolename and click Create role button to complete the process of role creation. In this section, let us understand how to create AWS Lambda function using nodejs as the runtime. For this purpose, login to AWS console and choose AWS Lambda from AWS services. Add the function name, role details etc and create the AWS Lambda function as shown. To add SNS trigger, enter SNS configuration details as shown − Then, select SNS topic and Add the trigger to AWS Lambda function as shown − Then, add AWS lambda code given below − exports.handler = function(event, context, callback) { console.log("AWS lambda and SNS trigger "); console.log(event); const sns = event.Records[0].Sns.Message; console.log(sns) callback(null, sns); }; In the above code, event.Records[0].Sns.Message gives the message details added. We have added console logs to see them in CloudWatch. Now, save the Lambda function with required memory and time allocation. Recall that we have already created topic in SNS in Step 1. We will now publish in the topic and see the details in CloudWatch which will be triggered by AWS Lambda − First Select name of the topic you want to publish. Click on Publish to topic button − Enter the Subject and Message details as shown below − You can also select JSON message format to send in JSON style. Click Publish the message button at the end of the screen. Log intoAWS console and open CloudWatch service. Click on logs on left side and select the logs for AWS Lambda function created. You can find the following display for the logs with messages created as shown above − Here will use SNS Text messaging to send message on the phone using AWS Lambda. You can use the following code to update AWS Lambda code as follows − const aws = require("aws-sdk"); const sns = new aws.SNS({ region:'us-east-1' }); exports.handler = function(event, context, callback) { console.log("AWS lambda and SNS trigger "); console.log(event); const snsmessage = event.Records[0].Sns.Message; console.log(snsmessage); sns.publish({ Message: snsmessage, PhoneNumber: '+911212121212' }, function (err, data) { if (err) { console.log(err); callback(err, null); } else { console.log(data); callback(null, data); } }); }; We have added AWS SDK and the SNS service to use to send message. The message from the event coming from SNS is send as text message on the phone number given. Observe the following code for example − sns.publish({ Message: snsmessage, PhoneNumber: '+911212121212' }, function (err, data) { if (err) { console.log(err); callback(err, null); } else { console.log(data); callback(null, data); } }); Enter the topic now to see the message in cloudwatch and the phone number given above. Click Publish message to publish the message. You see a message on the phone number given as follows − 35 Lectures 7.5 hours Mr. Pradeep Kshetrapal 30 Lectures 3.5 hours Priyanka Choudhary 44 Lectures 7.5 hours Eduonix Learning Solutions 51 Lectures 6 hours Manuj Aggarwal 41 Lectures 5 hours AR Shankar 14 Lectures 1 hours Zach Miller Print Add Notes Bookmark this page
[ { "code": null, "e": 2599, "s": 2406, "text": "Amazon SNS is a service used for push notification. In this chapter, we will explain working of AWS Lambda and Amazon SNS with the help of an example where will perform the following actions −" }, { "code": null, "e": 2671, "s": 2599, "text": "Create Topic in SNS Service and use AWS Lambda Add Topics to CloudWatch" }, { "code": null, "e": 2743, "s": 2671, "text": "Create Topic in SNS Service and use AWS Lambda Add Topics to CloudWatch" }, { "code": null, "e": 2788, "s": 2743, "text": "Send SNS text message on phone number given." }, { "code": null, "e": 2833, "s": 2788, "text": "Send SNS text message on phone number given." }, { "code": null, "e": 2952, "s": 2833, "text": "To create Topic in SNS Service and use AWS Lambda Add Topics to CloudWatch, we need not follow the steps given below −" }, { "code": null, "e": 2972, "s": 2952, "text": "Create Topic in SNS" }, { "code": null, "e": 3006, "s": 2972, "text": "Create Role for permission in IAM" }, { "code": null, "e": 3033, "s": 3006, "text": "Create AWS Lambda Function" }, { "code": null, "e": 3070, "s": 3033, "text": "Publish to topic to activate trigger" }, { "code": null, "e": 3119, "s": 3070, "text": "Check the message details in CloudWatch service." }, { "code": null, "e": 3197, "s": 3119, "text": "To send SNS text message on phone number given, we need to do the following −" }, { "code": null, "e": 3251, "s": 3197, "text": "Add code in AWS Lambda to send message to your phone." }, { "code": null, "e": 3463, "s": 3251, "text": "In this example, we will create a topic in SNS. When details are entered in the topic to publish, AWS Lambda is triggered. The topic details are logged in CloudWatch and a message is sent on phone by AWS Lambda." }, { "code": null, "e": 3519, "s": 3463, "text": "Here is a basic block diagram which explains the same −" }, { "code": null, "e": 3590, "s": 3519, "text": "You will have to follow the steps given below to create topic in SNS −" }, { "code": null, "e": 3660, "s": 3590, "text": "Login to AWS Console and go to SNS service in Amazon as shown below −" }, { "code": null, "e": 3718, "s": 3660, "text": "Click Simple Notification Service and Create topic in it." }, { "code": null, "e": 3777, "s": 3718, "text": "Then, you have to click Create new topic button as shown −" }, { "code": null, "e": 3900, "s": 3777, "text": "Enter the Topic name and Display name and click on Create topic. You should see the topic name in the display as follows −" }, { "code": null, "e": 4075, "s": 3900, "text": "To create a Role to work with AWS Lambda and SNS service, we need to login to AWS console. Then, select IAM from Amazon services and click role from left side as shown below." }, { "code": null, "e": 4227, "s": 4075, "text": "Observe that we have added policies for SNS, Lambda and CloudWatch. Add rolename and click Create role button to complete the process of role creation." }, { "code": null, "e": 4325, "s": 4227, "text": "In this section, let us understand how to create AWS Lambda function using nodejs as the runtime." }, { "code": null, "e": 4490, "s": 4325, "text": "For this purpose, login to AWS console and choose AWS Lambda from AWS services. Add the function name, role details etc and create the AWS Lambda function as shown." }, { "code": null, "e": 4553, "s": 4490, "text": "To add SNS trigger, enter SNS configuration details as shown −" }, { "code": null, "e": 4630, "s": 4553, "text": "Then, select SNS topic and Add the trigger to AWS Lambda function as shown −" }, { "code": null, "e": 4670, "s": 4630, "text": "Then, add AWS lambda code given below −" }, { "code": null, "e": 4887, "s": 4670, "text": "exports.handler = function(event, context, callback) {\n console.log(\"AWS lambda and SNS trigger \");\n console.log(event);\n const sns = event.Records[0].Sns.Message;\n console.log(sns)\n callback(null, sns);\n};" }, { "code": null, "e": 5094, "s": 4887, "text": "In the above code, event.Records[0].Sns.Message gives the message details added. We have added console logs to see them in CloudWatch. Now, save the Lambda function with required memory and time allocation." }, { "code": null, "e": 5261, "s": 5094, "text": "Recall that we have already created topic in SNS in Step 1. We will now publish in the topic and see the details in CloudWatch which will be triggered by AWS Lambda −" }, { "code": null, "e": 5348, "s": 5261, "text": "First Select name of the topic you want to publish. Click on Publish to topic button −" }, { "code": null, "e": 5403, "s": 5348, "text": "Enter the Subject and Message details as shown below −" }, { "code": null, "e": 5525, "s": 5403, "text": "You can also select JSON message format to send in JSON style. Click Publish the message button at the end of the screen." }, { "code": null, "e": 5741, "s": 5525, "text": "Log intoAWS console and open CloudWatch service. Click on logs on left side and select the logs for AWS Lambda function created. You can find the following display for the logs with messages created as shown above −" }, { "code": null, "e": 5891, "s": 5741, "text": "Here will use SNS Text messaging to send message on the phone using AWS Lambda. You can use the following code to update AWS Lambda code as follows −" }, { "code": null, "e": 6456, "s": 5891, "text": "const aws = require(\"aws-sdk\");\nconst sns = new aws.SNS({\n region:'us-east-1'\n});\nexports.handler = function(event, context, callback) {\n console.log(\"AWS lambda and SNS trigger \");\n console.log(event);\n const snsmessage = event.Records[0].Sns.Message;\n console.log(snsmessage);\n sns.publish({\n Message: snsmessage,\n PhoneNumber: '+911212121212'\n }, function (err, data) {\n if (err) {\n console.log(err);\n callback(err, null);\n } else {\n console.log(data);\n callback(null, data);\n }\t\n });\n};" }, { "code": null, "e": 6616, "s": 6456, "text": "We have added AWS SDK and the SNS service to use to send message. The message from the event coming from SNS is send as text message on the phone number given." }, { "code": null, "e": 6657, "s": 6616, "text": "Observe the following code for example −" }, { "code": null, "e": 6893, "s": 6657, "text": "sns.publish({\n Message: snsmessage,\n PhoneNumber: '+911212121212'\n}, function (err, data) {\n if (err) {\n console.log(err);\n callback(err, null);\n } else {\n console.log(data);\n callback(null, data);\n }\t\n});" }, { "code": null, "e": 6980, "s": 6893, "text": "Enter the topic now to see the message in cloudwatch and the phone number given above." }, { "code": null, "e": 7083, "s": 6980, "text": "Click Publish message to publish the message. You see a message on the phone number given as follows −" }, { "code": null, "e": 7118, "s": 7083, "text": "\n 35 Lectures \n 7.5 hours \n" }, { "code": null, "e": 7142, "s": 7118, "text": " Mr. Pradeep Kshetrapal" }, { "code": null, "e": 7177, "s": 7142, "text": "\n 30 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7197, "s": 7177, "text": " Priyanka Choudhary" }, { "code": null, "e": 7232, "s": 7197, "text": "\n 44 Lectures \n 7.5 hours \n" }, { "code": null, "e": 7260, "s": 7232, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 7293, "s": 7260, "text": "\n 51 Lectures \n 6 hours \n" }, { "code": null, "e": 7309, "s": 7293, "text": " Manuj Aggarwal" }, { "code": null, "e": 7342, "s": 7309, "text": "\n 41 Lectures \n 5 hours \n" }, { "code": null, "e": 7354, "s": 7342, "text": " AR Shankar" }, { "code": null, "e": 7387, "s": 7354, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 7400, "s": 7387, "text": " Zach Miller" }, { "code": null, "e": 7407, "s": 7400, "text": " Print" }, { "code": null, "e": 7418, "s": 7407, "text": " Add Notes" } ]
Google Maps - Info Window
In addition to markers, polygons, polylines, and other geometrical shapes, we can also draw an Info Window on the map. This chapter explains how to use the Info Window. Info Window is used to add any kind of information to the map. For instance, if you want to provide information about a location on the map, you can use an info window. Usually the info window is attached to a marker. You can attach an info window by instantiating the google.maps.InfoWindow class. It has the following properties − Content − You can pass your content in String format using this option. Content − You can pass your content in String format using this option. position − You can choose the position of the info window using this option. position − You can choose the position of the info window using this option. maxWidth − By default, the info window's width will be stretched till the text is wrapped. By specifying maxWidth, we can restrict the size of the info window horizontally. maxWidth − By default, the info window's width will be stretched till the text is wrapped. By specifying maxWidth, we can restrict the size of the info window horizontally. The following example shows how to set the marker and specify an info window above it − <!DOCTYPE html> <html> <head> <script src = "https://maps.googleapis.com/maps/api/js"></script> <script> function loadMap() { var mapOptions = { center:new google.maps.LatLng(17.433053, 78.412172), zoom:5 } var map = new google.maps.Map(document.getElementById("sample"),mapOptions); var marker = new google.maps.Marker({ position: new google.maps.LatLng(17.433053, 78.412172), map: map, draggable:true, icon:'/scripts/img/logo-footer.png' }); marker.setMap(map); var infowindow = new google.maps.InfoWindow({ content:"388-A , Road no 22, Jubilee Hills, Hyderabad Telangana, INDIA-500033" }); infowindow.open(map,marker); } </script> </head> <body onload = "loadMap()"> <div id = "sample" style = "width:580px; height:400px;"></div> </body> </html> It will produce the following output − 20 Lectures 2.5 hours Asif Hussain 7 Lectures 1 hours Aditya Kulkarni 33 Lectures 2.5 hours Sasha Miller 22 Lectures 1.5 hours Zach Miller 16 Lectures 1.5 hours Sasha Miller 23 Lectures 2.5 hours Sasha Miller Print Add Notes Bookmark this page
[ { "code": null, "e": 2001, "s": 1832, "text": "In addition to markers, polygons, polylines, and other geometrical shapes, we can also draw an Info Window on the map. This chapter explains how to use the Info Window." }, { "code": null, "e": 2334, "s": 2001, "text": "Info Window is used to add any kind of information to the map. For instance, if you want to provide information about a location on the map, you can use an info window. Usually the info window is attached to a marker. You can attach an info window by instantiating the google.maps.InfoWindow class. It has the following properties −" }, { "code": null, "e": 2406, "s": 2334, "text": "Content − You can pass your content in String format using this option." }, { "code": null, "e": 2478, "s": 2406, "text": "Content − You can pass your content in String format using this option." }, { "code": null, "e": 2555, "s": 2478, "text": "position − You can choose the position of the info window using this option." }, { "code": null, "e": 2632, "s": 2555, "text": "position − You can choose the position of the info window using this option." }, { "code": null, "e": 2805, "s": 2632, "text": "maxWidth − By default, the info window's width will be stretched till the text is wrapped. By specifying maxWidth, we can restrict the size of the info window horizontally." }, { "code": null, "e": 2978, "s": 2805, "text": "maxWidth − By default, the info window's width will be stretched till the text is wrapped. By specifying maxWidth, we can restrict the size of the info window horizontally." }, { "code": null, "e": 3066, "s": 2978, "text": "The following example shows how to set the marker and specify an info window above it −" }, { "code": null, "e": 4169, "s": 3066, "text": "<!DOCTYPE html>\n<html>\n \n <head>\n <script src = \"https://maps.googleapis.com/maps/api/js\"></script>\n \n <script>\n function loadMap() {\n\t\t\t\n var mapOptions = {\n center:new google.maps.LatLng(17.433053, 78.412172),\n zoom:5\n }\n \n var map = new google.maps.Map(document.getElementById(\"sample\"),mapOptions);\n \n var marker = new google.maps.Marker({\n position: new google.maps.LatLng(17.433053, 78.412172),\n map: map,\n draggable:true,\n icon:'/scripts/img/logo-footer.png'\n });\n \n marker.setMap(map);\n \n var infowindow = new google.maps.InfoWindow({\n content:\"388-A , Road no 22, Jubilee Hills, Hyderabad Telangana, INDIA-500033\"\n });\n\t\t\t\t\n infowindow.open(map,marker);\n }\n </script>\n \n </head>\n \n <body onload = \"loadMap()\">\n <div id = \"sample\" style = \"width:580px; height:400px;\"></div>\n </body>\n \n</html>" }, { "code": null, "e": 4208, "s": 4169, "text": "It will produce the following output −" }, { "code": null, "e": 4243, "s": 4208, "text": "\n 20 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4257, "s": 4243, "text": " Asif Hussain" }, { "code": null, "e": 4289, "s": 4257, "text": "\n 7 Lectures \n 1 hours \n" }, { "code": null, "e": 4306, "s": 4289, "text": " Aditya Kulkarni" }, { "code": null, "e": 4341, "s": 4306, "text": "\n 33 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4355, "s": 4341, "text": " Sasha Miller" }, { "code": null, "e": 4390, "s": 4355, "text": "\n 22 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4403, "s": 4390, "text": " Zach Miller" }, { "code": null, "e": 4438, "s": 4403, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4452, "s": 4438, "text": " Sasha Miller" }, { "code": null, "e": 4487, "s": 4452, "text": "\n 23 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4501, "s": 4487, "text": " Sasha Miller" }, { "code": null, "e": 4508, "s": 4501, "text": " Print" }, { "code": null, "e": 4519, "s": 4508, "text": " Add Notes" } ]
How to split multiline string into an array of lines in JavaScript ? - GeeksforGeeks
13 Apr, 2021 Multiline string in JavaScript means a string having two or more lines. To split a multiline string to an array we need to use split() in our JavaScript code. split(separator, limit): The split() function is used to split the data depending upon the attributes we are passing in it. The separator attributes specify that from this word/sign the string will be divided. The limit attribute is optional, it specifies how many splits will be there. Example 1: HTML <!DOCTYPE html><html> <body> <h1>Welcome to Geeks for Geeks</h1> <button onclick="myFunction()"> Go </button> <p id="StringToArray"></p> <script> function myFunction() { var string = "Are you ready?" + "<br>So let's get started"; var array = string.split("<br>"); document.getElementById("StringToArray") .innerHTML = array; } </script></body> </html> Output: In this, when we will click on the “Go” button the array of the multiline string will be displayed on the screen separated by “,”. Example 2: Now, let’s see how to get a particular index of an array. HTML <!DOCTYPE html><html> <body> <h1>Welcome to Geeks for Geeks</h1> <button onclick="myFunction()">Go</button> <p id="StringToArray"></p> <script> function myFunction() { var string = "Are you ready?" + "<br>So let's get started"; var array = string.split("<br>"); document.getElementById("StringToArray") .innerHTML = array[1]; } </script></body> </html> Output: As we wrote array[1], hence only the 2nd line has been printed. If we will write array[2], then it will be undefined as this array contains data in the first two indexes only that are 0 and 1 respectively. Example 3: Now, let’s try to take string as an user input. HTML <!DOCTYPE html><html> <body> <h1>Welcome to Geeks for Geeks</h1> <textarea id="write" placeholder="Write something" style="height:100px;"> </textarea> <button onclick="myFunction()">Go</button> <p id="StringToArray"></p> <script> function myFunction() { var string = document .getElementById("write").value; var array = string.split("."); document.getElementById("StringToArray") .innerHTML = array; } </script></body> </html> Output: JavaScript-Methods JavaScript-Questions javascript-string Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to calculate the number of days between two dates in javascript? Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Convert a string to an integer in JavaScript File uploading in React.js Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 37914, "s": 37886, "text": "\n13 Apr, 2021" }, { "code": null, "e": 38074, "s": 37914, "text": "Multiline string in JavaScript means a string having two or more lines. To split a multiline string to an array we need to use split() in our JavaScript code. " }, { "code": null, "e": 38361, "s": 38074, "text": "split(separator, limit): The split() function is used to split the data depending upon the attributes we are passing in it. The separator attributes specify that from this word/sign the string will be divided. The limit attribute is optional, it specifies how many splits will be there." }, { "code": null, "e": 38372, "s": 38361, "text": "Example 1:" }, { "code": null, "e": 38377, "s": 38372, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h1>Welcome to Geeks for Geeks</h1> <button onclick=\"myFunction()\"> Go </button> <p id=\"StringToArray\"></p> <script> function myFunction() { var string = \"Are you ready?\" + \"<br>So let's get started\"; var array = string.split(\"<br>\"); document.getElementById(\"StringToArray\") .innerHTML = array; } </script></body> </html>", "e": 38846, "s": 38377, "text": null }, { "code": null, "e": 38854, "s": 38846, "text": "Output:" }, { "code": null, "e": 38985, "s": 38854, "text": "In this, when we will click on the “Go” button the array of the multiline string will be displayed on the screen separated by “,”." }, { "code": null, "e": 39054, "s": 38985, "text": "Example 2: Now, let’s see how to get a particular index of an array." }, { "code": null, "e": 39059, "s": 39054, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h1>Welcome to Geeks for Geeks</h1> <button onclick=\"myFunction()\">Go</button> <p id=\"StringToArray\"></p> <script> function myFunction() { var string = \"Are you ready?\" + \"<br>So let's get started\"; var array = string.split(\"<br>\"); document.getElementById(\"StringToArray\") .innerHTML = array[1]; } </script></body> </html>", "e": 39519, "s": 39059, "text": null }, { "code": null, "e": 39527, "s": 39519, "text": "Output:" }, { "code": null, "e": 39733, "s": 39527, "text": "As we wrote array[1], hence only the 2nd line has been printed. If we will write array[2], then it will be undefined as this array contains data in the first two indexes only that are 0 and 1 respectively." }, { "code": null, "e": 39792, "s": 39733, "text": "Example 3: Now, let’s try to take string as an user input." }, { "code": null, "e": 39797, "s": 39792, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h1>Welcome to Geeks for Geeks</h1> <textarea id=\"write\" placeholder=\"Write something\" style=\"height:100px;\"> </textarea> <button onclick=\"myFunction()\">Go</button> <p id=\"StringToArray\"></p> <script> function myFunction() { var string = document .getElementById(\"write\").value; var array = string.split(\".\"); document.getElementById(\"StringToArray\") .innerHTML = array; } </script></body> </html>", "e": 40356, "s": 39797, "text": null }, { "code": null, "e": 40364, "s": 40356, "text": "Output:" }, { "code": null, "e": 40383, "s": 40364, "text": "JavaScript-Methods" }, { "code": null, "e": 40404, "s": 40383, "text": "JavaScript-Questions" }, { "code": null, "e": 40422, "s": 40404, "text": "javascript-string" }, { "code": null, "e": 40429, "s": 40422, "text": "Picked" }, { "code": null, "e": 40440, "s": 40429, "text": "JavaScript" }, { "code": null, "e": 40457, "s": 40440, "text": "Web Technologies" }, { "code": null, "e": 40555, "s": 40457, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40564, "s": 40555, "text": "Comments" }, { "code": null, "e": 40577, "s": 40564, "text": "Old Comments" }, { "code": null, "e": 40646, "s": 40577, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 40707, "s": 40646, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 40779, "s": 40707, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 40824, "s": 40779, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 40851, "s": 40824, "text": "File uploading in React.js" }, { "code": null, "e": 40893, "s": 40851, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 40926, "s": 40893, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 40969, "s": 40926, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 41031, "s": 40969, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
How to create blur activity background in android?
This example demonstrate about How to create blue activity background in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:app = "http://schemas.android.com/apk/res-auto" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:gravity = "center" android:layout_height = "match_parent" tools:context = ".MainActivity" android:background = "@drawable/ic_launcher_background" android:orientation = "vertical"> <TextView android:id = "@+id/text" android:textSize = "30sp" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> </LinearLayout> In the above code, we have taken text view to show sample text. Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.telephony.TelephonyManager; import android.view.WindowManager; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private static final int PERMISSION_REQUEST_CODE = 100; TextView textView; TelephonyManager telephonyManager; @RequiresApi(api = Build.VERSION_CODES.P) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND, WindowManager.LayoutParams.FLAG_BLUR_BEHIND); setContentView(R.layout.activity_main); textView = findViewById(R.id.text); textView.setText("Blur Behind Flag"); } } Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code
[ { "code": null, "e": 1144, "s": 1062, "text": "This example demonstrate about How to create blue activity background in android." }, { "code": null, "e": 1273, "s": 1144, "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": 1338, "s": 1273, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1993, "s": 1338, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:gravity = \"center\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:background = \"@drawable/ic_launcher_background\"\n android:orientation = \"vertical\">\n <TextView\n android:id = \"@+id/text\"\n android:textSize = \"30sp\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n</LinearLayout>" }, { "code": null, "e": 2057, "s": 1993, "text": "In the above code, we have taken text view to show sample text." }, { "code": null, "e": 2114, "s": 2057, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2998, "s": 2114, "text": "package com.example.myapplication;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.telephony.TelephonyManager;\nimport android.view.WindowManager;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n private static final int PERMISSION_REQUEST_CODE = 100;\n TextView textView;\n TelephonyManager telephonyManager;\n @RequiresApi(api = Build.VERSION_CODES.P)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,\n WindowManager.LayoutParams.FLAG_BLUR_BEHIND);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.text);\n textView.setText(\"Blur Behind Flag\");\n }\n}" }, { "code": null, "e": 3345, "s": 2998, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 3385, "s": 3345, "text": "Click here to download the project code" } ]
Democratizing Historical Weather Data Analysis with R | by Sabi Horvat | Towards Data Science
As a Data Scientist, I was interested in finding weather data to perform a regression analysis on sales. That is to say, I wanted to understand if weather had a measurable impact on online or in-store sales. I’ve researched similar business questions related to weather in the past ten years, and my hope is that the following tutorial can help others with similar questions. When I started gardening and choosing the right plants for an area, I found the following maps to provide useful information as a rule of thumb. And now that my partner and I own land around our residence and can invest in our gardening ambitions, I dove deeper into what these statistics mean and where the data comes from. With today’s open data, it is possible to calculate these statistics for a postal code (ZIP code) near you. I find the data analysis fun and more accurate than using a magnifying glass on printed-out maps. To have the data available for answering specific questions can also be helpful. USDA Plant Hardiness Zone Maps—the most common map I’ve seen at garden centers and nurseries in the US; used for selecting plants that will survive the winter Chill Hours Maps — if you want to plant peach trees, cherry trees, and other plants that require minimum chill hours in to set fruit US Precipitation Maps —rainfall affects many considerations when planning a landscape, even if you have a consistent water source Last Spring Freeze — The Farmer’s Almanac and the region’s gardeners and farmers are also a good resource to understand when it might be okay to start planting in the spring. Frost Depth Maps — if you plan to dig in fence posts or irrigation lines, it is helpful to know the expected frost depth on the land. Plant Heat Zone Maps —excessive heat for certain plants can be a problem. For the following plots, daily precipitation and temperature data has been obtained from the NOAA National Centers for Environmental Information (Climate.gov), via the online search & download option as a comma separated value (CSV) file. The data has the following columns: DATE = YYYY-MM-DD STATION = Weather Station ID NAME = Description of the Weather Station PRCP = Precipitation in rainfall (inches) SNOW = Precipitation in Snowfall (inches) TMIN = Daily Minimum Temperature This data could be analyzed in a spreadsheet, but if you want the process to be repeatable with the click of a button for any postal code, writing a program with R may be a better way. If you would like to follow along, you may copy my GitHub “weather” repository (towardsDS folder) with a free GitHub account. Or you can download the CSV file directly if you go to this link and Save Page As... If you already use R, you may skip this section. For new useRs, the process for installation is documented on many sites, but this should point you in the right direction. For data analysis and modeling, I recommend using RStudio with R. Download and install R from the CRAN library, which you can find at r-project.org/ . Select the CRAN mirror of your choice for the download.Download and install RStudio from the RStudio download page. The free desktop version is the best way to start.Open RStudio to create a new file, and choose File > New File > R Script if you’d like to follow along. R Markdown and the other options are also great, but in this tutorial we’ll use a simple R Script.Alternatively, when you open an existing file with RStudio if RStudio is not yet open, RStudio will automatically set your directory path to the path of that file.In RStudio, click on Tools > Install Packages... to install the libraries used in the script.To execute one line of code at a time, position the cursor on that line and press Command+Enter on a Mac or Control+Enter on a PC. If the code extends to another line, using a pipe or until a closed parenthesis, the entire code block is executed and the cursor is moved.To view or copy the entire R script instead of the snippets below, visit the full R script on Github. Download and install R from the CRAN library, which you can find at r-project.org/ . Select the CRAN mirror of your choice for the download. Download and install RStudio from the RStudio download page. The free desktop version is the best way to start. Open RStudio to create a new file, and choose File > New File > R Script if you’d like to follow along. R Markdown and the other options are also great, but in this tutorial we’ll use a simple R Script. Alternatively, when you open an existing file with RStudio if RStudio is not yet open, RStudio will automatically set your directory path to the path of that file. In RStudio, click on Tools > Install Packages... to install the libraries used in the script. To execute one line of code at a time, position the cursor on that line and press Command+Enter on a Mac or Control+Enter on a PC. If the code extends to another line, using a pipe or until a closed parenthesis, the entire code block is executed and the cursor is moved. To view or copy the entire R script instead of the snippets below, visit the full R script on Github. First, import the tidyverse library and use its read_csv() function to import the weather data. The tidyverse is a collection of libraries that includes dplyr, tidyr, ggplot2, and others. To learn more about the tidyverse, please read R for Data Science. The other libraries in this script provide functions for data wrangling with dates (lubridate) and functions for customizing plots with the grammar of graphics library ggplot2 (ggthemes, ggtext). Output: spec_tbl_df [29,342 × 6] (S3: spec_tbl_df/tbl_df/tbl/data.frame) $ STATION: chr [1:29342] "USW00024229" "USW00024229" "USW00024229" "USW00024229" ... $ NAME : chr [1:29342] "PORTLAND INTERNATIONAL AIRPORT, OR US" "PORTLAND INTERNATIONAL AIRPORT, OR US" "PORTLAND INTERNATIONAL AIRPORT, OR US" "PORTLAND INTERNATIONAL AIRPORT, OR US" ... $ DATE : Date[1:29342], format: "1940-10-14" "1940-10-15" ... $ PRCP : num [1:29342] 0 0 0 0.13 0 0 0.14 0.05 0 0.63 ... $ SNOW : num [1:29342] 0 0 0 0 0 0 0 0 0 0 ... $ TMIN : num [1:29342] 53 52 50 58 58 59 54 48 41 53 ... - attr(*, "spec")= .. cols( .. STATION = col_character(), .. NAME = col_character(), .. DATE = col_date(format = ""), .. PRCP = col_double(), .. SNOW = col_double(), .. TMIN = col_double() .. ) The weather data has now been imported into the data frame csv_data. A key point to check is the number of weather stations in data, as we’ll want to explore only one weather station at a time. The str() function shows the structure of the data frame and that there are at least four weather stations with data in this ZIP code. In the next step, we’ll select one weather station for the rest of the analysis by filtering on a station and performing other data wrangling tasks separated by the pipes %>% syntax enabled by the tidyverse. Output: # A tibble: 1 x 3 NAME min_date max_date * <chr> <date> <date> 1 PORTLAND INTERNATIONAL AIRPORT, OR US 1940-10-14 2021-02-12 The CSV file has data for this station from 1940–10–14 to 2021-02–12. Since we want to look at full years of data only, in the following code block the data is filtered to the range from 1941 to 2020. Now that we have 80 years of data available, we can answer questions such as “What was the single day with the most amount of rainfall, and how many inches of rain were measured that day?” Output: # A tibble: 2 x 6 STATION NAME DATE PRCP SNOW TMIN <chr> <chr> <date> <dbl> <dbl> <dbl>1 USW00024229 PORTLAND INTERNATIONAL... 1943-01-21 1.1 14.4 192 USW00024229 PORTLAND INTERNATIONAL... 1996-11-19 2.69 NA 34 The highest recorded rainfall at the Portland, Oregon airport (PDX) weather station was 2.69 inches measured on 1996–11–19. The highest recorded snowfall occurred on 1943–01–21 with 14.4 inches measured. My favorite way to understand the climate of an area is to view a box-and-whisker plot of monthly rainfall. You might be able to find this data for your area, or at least something similar like the Climate Charts on Wikipedia, but with R you have the ability to zero in on the data by ZIP code or any other granularity that may not have published charts. Additionally, you may want to know the time period of the data included for the graph and experiment with the impact of using different date ranges. Output: Was using the last 80 years of data appropriate, or would using only the most recent 20 years be more reflective of the climate? For this particular ZIP code, the additional (or less) data didn’t change the plot significantly, but I chose to display the full 80 years since the extra outliers that show up on the graph are interesting. Now let’s see a plot for snowfall. Since snowfall is less common in this ZIP code, the following plot is based on an annual snowfall. Output: It is interesting to note that inspecting only the last 20 years of data versus the full 80 years of data would produce a very different result. In the last twenty years, measured snowfall was rare in this area, although the last five years have resumed trends of the previous century. Gardeners will keep an eye on the weather forecast, and keen gardeners will want to understand historical trends as well. An area of particular interest is the last freeze each spring. If seeds or starts are planted too early, they may succumb to a late frost. On the other end of the growing season, the first freeze each fall is a good indication of when to ensure the harvest is completed for crops that cannot withstand an early frost. Output: Absorbing this data visually, it seems that the last freeze has been earlier in March in recent years. The local wisdom that states it is risky to plant before mid-April seems to be supported by the last 30 years of data. Although in some recent years, the soil has been too saturated with winter/spring rains to allow for planting earlier anyway. The last analysis that I’ll share is in regards to cold hardiness for plants. The USDA Plant Hardiness Zone Maps produced in collaboration with Oregon State University (OSU) show the average annual extreme minimum temperature from 1976–2005. While the amount of work to recreate such a map is extensive, we can recreate a more up-to-date data point for a particular ZIP code. Most nurseries label each variety of tree, bush, and other perennial plants with the plant hardiness zone to indicate where each variety is likely to pull through the colder months into the next year. The 97218 ZIP code seems to fall into the coloring of region 8b, which means it is safe to plant varieties that are likely to survive at an annual extreme low temperature between 15 to 20 degrees Fahrenheit. Let’s compare the data used from 1976–2005 to newer data from 1991–2020 to see if there has been any significant change. Output (1976–2005): year annual_extreme_low Min. :1976 Min. : 9.00 1st Qu.:1983 1st Qu.:14.00 Median :1990 Median :19.00 Mean :1990 Mean :19.20 3rd Qu.:1998 3rd Qu.:24.75 Max. :2005 Max. :27.00 Output (1991–2020): year annual_extreme_low Min. :1991 Min. :11.00 1st Qu.:1998 1st Qu.:18.00 Median :2006 Median :22.00 Mean :2006 Mean :20.77 3rd Qu.:2013 3rd Qu.:25.75 Max. :2020 Max. :27.00 The mean annual extreme low from the newer 30-year average is 1.6 degrees Fahrenheit warmer (now 20.8 compared to 19.2). This change, now above the cusp of 20, is enough to put this postal code into the 9a hardiness zone. Actually, microclimates within the region are already noted to be possibly in the 9a hardiness zone on the USDA/OSU map, if you look beyond the colors and notice the annotation. Perhaps this may be due to the heat island effect of the metropolitan area. I hope you’ve enjoyed this tutorial- and if this was your first time using R- I hope that this motivates you to learn more and democratize data analysis! And if you would like to read (and write) more articles like this, please consider signing up for medium using my referral link: https://sabolch-horvat.medium.com/membership [Updated 2021–12–18]: In “The Data”, added information on how to access the CSV data file directly from GitHub.
[ { "code": null, "e": 548, "s": 172, "text": "As a Data Scientist, I was interested in finding weather data to perform a regression analysis on sales. That is to say, I wanted to understand if weather had a measurable impact on online or in-store sales. I’ve researched similar business questions related to weather in the past ten years, and my hope is that the following tutorial can help others with similar questions." }, { "code": null, "e": 1160, "s": 548, "text": "When I started gardening and choosing the right plants for an area, I found the following maps to provide useful information as a rule of thumb. And now that my partner and I own land around our residence and can invest in our gardening ambitions, I dove deeper into what these statistics mean and where the data comes from. With today’s open data, it is possible to calculate these statistics for a postal code (ZIP code) near you. I find the data analysis fun and more accurate than using a magnifying glass on printed-out maps. To have the data available for answering specific questions can also be helpful." }, { "code": null, "e": 1319, "s": 1160, "text": "USDA Plant Hardiness Zone Maps—the most common map I’ve seen at garden centers and nurseries in the US; used for selecting plants that will survive the winter" }, { "code": null, "e": 1452, "s": 1319, "text": "Chill Hours Maps — if you want to plant peach trees, cherry trees, and other plants that require minimum chill hours in to set fruit" }, { "code": null, "e": 1582, "s": 1452, "text": "US Precipitation Maps —rainfall affects many considerations when planning a landscape, even if you have a consistent water source" }, { "code": null, "e": 1757, "s": 1582, "text": "Last Spring Freeze — The Farmer’s Almanac and the region’s gardeners and farmers are also a good resource to understand when it might be okay to start planting in the spring." }, { "code": null, "e": 1891, "s": 1757, "text": "Frost Depth Maps — if you plan to dig in fence posts or irrigation lines, it is helpful to know the expected frost depth on the land." }, { "code": null, "e": 1965, "s": 1891, "text": "Plant Heat Zone Maps —excessive heat for certain plants can be a problem." }, { "code": null, "e": 2240, "s": 1965, "text": "For the following plots, daily precipitation and temperature data has been obtained from the NOAA National Centers for Environmental Information (Climate.gov), via the online search & download option as a comma separated value (CSV) file. The data has the following columns:" }, { "code": null, "e": 2258, "s": 2240, "text": "DATE = YYYY-MM-DD" }, { "code": null, "e": 2287, "s": 2258, "text": "STATION = Weather Station ID" }, { "code": null, "e": 2329, "s": 2287, "text": "NAME = Description of the Weather Station" }, { "code": null, "e": 2371, "s": 2329, "text": "PRCP = Precipitation in rainfall (inches)" }, { "code": null, "e": 2413, "s": 2371, "text": "SNOW = Precipitation in Snowfall (inches)" }, { "code": null, "e": 2446, "s": 2413, "text": "TMIN = Daily Minimum Temperature" }, { "code": null, "e": 2631, "s": 2446, "text": "This data could be analyzed in a spreadsheet, but if you want the process to be repeatable with the click of a button for any postal code, writing a program with R may be a better way." }, { "code": null, "e": 2842, "s": 2631, "text": "If you would like to follow along, you may copy my GitHub “weather” repository (towardsDS folder) with a free GitHub account. Or you can download the CSV file directly if you go to this link and Save Page As..." }, { "code": null, "e": 3080, "s": 2842, "text": "If you already use R, you may skip this section. For new useRs, the process for installation is documented on many sites, but this should point you in the right direction. For data analysis and modeling, I recommend using RStudio with R." }, { "code": null, "e": 4161, "s": 3080, "text": "Download and install R from the CRAN library, which you can find at r-project.org/ . Select the CRAN mirror of your choice for the download.Download and install RStudio from the RStudio download page. The free desktop version is the best way to start.Open RStudio to create a new file, and choose File > New File > R Script if you’d like to follow along. R Markdown and the other options are also great, but in this tutorial we’ll use a simple R Script.Alternatively, when you open an existing file with RStudio if RStudio is not yet open, RStudio will automatically set your directory path to the path of that file.In RStudio, click on Tools > Install Packages... to install the libraries used in the script.To execute one line of code at a time, position the cursor on that line and press Command+Enter on a Mac or Control+Enter on a PC. If the code extends to another line, using a pipe or until a closed parenthesis, the entire code block is executed and the cursor is moved.To view or copy the entire R script instead of the snippets below, visit the full R script on Github." }, { "code": null, "e": 4302, "s": 4161, "text": "Download and install R from the CRAN library, which you can find at r-project.org/ . Select the CRAN mirror of your choice for the download." }, { "code": null, "e": 4414, "s": 4302, "text": "Download and install RStudio from the RStudio download page. The free desktop version is the best way to start." }, { "code": null, "e": 4617, "s": 4414, "text": "Open RStudio to create a new file, and choose File > New File > R Script if you’d like to follow along. R Markdown and the other options are also great, but in this tutorial we’ll use a simple R Script." }, { "code": null, "e": 4781, "s": 4617, "text": "Alternatively, when you open an existing file with RStudio if RStudio is not yet open, RStudio will automatically set your directory path to the path of that file." }, { "code": null, "e": 4875, "s": 4781, "text": "In RStudio, click on Tools > Install Packages... to install the libraries used in the script." }, { "code": null, "e": 5146, "s": 4875, "text": "To execute one line of code at a time, position the cursor on that line and press Command+Enter on a Mac or Control+Enter on a PC. If the code extends to another line, using a pipe or until a closed parenthesis, the entire code block is executed and the cursor is moved." }, { "code": null, "e": 5248, "s": 5146, "text": "To view or copy the entire R script instead of the snippets below, visit the full R script on Github." }, { "code": null, "e": 5503, "s": 5248, "text": "First, import the tidyverse library and use its read_csv() function to import the weather data. The tidyverse is a collection of libraries that includes dplyr, tidyr, ggplot2, and others. To learn more about the tidyverse, please read R for Data Science." }, { "code": null, "e": 5699, "s": 5503, "text": "The other libraries in this script provide functions for data wrangling with dates (lubridate) and functions for customizing plots with the grammar of graphics library ggplot2 (ggthemes, ggtext)." }, { "code": null, "e": 5707, "s": 5699, "text": "Output:" }, { "code": null, "e": 6493, "s": 5707, "text": "spec_tbl_df [29,342 × 6] (S3: spec_tbl_df/tbl_df/tbl/data.frame) $ STATION: chr [1:29342] \"USW00024229\" \"USW00024229\" \"USW00024229\" \"USW00024229\" ... $ NAME : chr [1:29342] \"PORTLAND INTERNATIONAL AIRPORT, OR US\" \"PORTLAND INTERNATIONAL AIRPORT, OR US\" \"PORTLAND INTERNATIONAL AIRPORT, OR US\" \"PORTLAND INTERNATIONAL AIRPORT, OR US\" ... $ DATE : Date[1:29342], format: \"1940-10-14\" \"1940-10-15\" ... $ PRCP : num [1:29342] 0 0 0 0.13 0 0 0.14 0.05 0 0.63 ... $ SNOW : num [1:29342] 0 0 0 0 0 0 0 0 0 0 ... $ TMIN : num [1:29342] 53 52 50 58 58 59 54 48 41 53 ... - attr(*, \"spec\")= .. cols( .. STATION = col_character(), .. NAME = col_character(), .. DATE = col_date(format = \"\"), .. PRCP = col_double(), .. SNOW = col_double(), .. TMIN = col_double() .. )" }, { "code": null, "e": 6822, "s": 6493, "text": "The weather data has now been imported into the data frame csv_data. A key point to check is the number of weather stations in data, as we’ll want to explore only one weather station at a time. The str() function shows the structure of the data frame and that there are at least four weather stations with data in this ZIP code." }, { "code": null, "e": 7030, "s": 6822, "text": "In the next step, we’ll select one weather station for the rest of the analysis by filtering on a station and performing other data wrangling tasks separated by the pipes %>% syntax enabled by the tidyverse." }, { "code": null, "e": 7038, "s": 7030, "text": "Output:" }, { "code": null, "e": 7239, "s": 7038, "text": "# A tibble: 1 x 3 NAME min_date max_date * <chr> <date> <date> 1 PORTLAND INTERNATIONAL AIRPORT, OR US 1940-10-14 2021-02-12" }, { "code": null, "e": 7440, "s": 7239, "text": "The CSV file has data for this station from 1940–10–14 to 2021-02–12. Since we want to look at full years of data only, in the following code block the data is filtered to the range from 1941 to 2020." }, { "code": null, "e": 7629, "s": 7440, "text": "Now that we have 80 years of data available, we can answer questions such as “What was the single day with the most amount of rainfall, and how many inches of rain were measured that day?”" }, { "code": null, "e": 7637, "s": 7629, "text": "Output:" }, { "code": null, "e": 7927, "s": 7637, "text": "# A tibble: 2 x 6 STATION NAME DATE PRCP SNOW TMIN <chr> <chr> <date> <dbl> <dbl> <dbl>1 USW00024229 PORTLAND INTERNATIONAL... 1943-01-21 1.1 14.4 192 USW00024229 PORTLAND INTERNATIONAL... 1996-11-19 2.69 NA 34" }, { "code": null, "e": 8131, "s": 7927, "text": "The highest recorded rainfall at the Portland, Oregon airport (PDX) weather station was 2.69 inches measured on 1996–11–19. The highest recorded snowfall occurred on 1943–01–21 with 14.4 inches measured." }, { "code": null, "e": 8635, "s": 8131, "text": "My favorite way to understand the climate of an area is to view a box-and-whisker plot of monthly rainfall. You might be able to find this data for your area, or at least something similar like the Climate Charts on Wikipedia, but with R you have the ability to zero in on the data by ZIP code or any other granularity that may not have published charts. Additionally, you may want to know the time period of the data included for the graph and experiment with the impact of using different date ranges." }, { "code": null, "e": 8643, "s": 8635, "text": "Output:" }, { "code": null, "e": 8979, "s": 8643, "text": "Was using the last 80 years of data appropriate, or would using only the most recent 20 years be more reflective of the climate? For this particular ZIP code, the additional (or less) data didn’t change the plot significantly, but I chose to display the full 80 years since the extra outliers that show up on the graph are interesting." }, { "code": null, "e": 9113, "s": 8979, "text": "Now let’s see a plot for snowfall. Since snowfall is less common in this ZIP code, the following plot is based on an annual snowfall." }, { "code": null, "e": 9121, "s": 9113, "text": "Output:" }, { "code": null, "e": 9407, "s": 9121, "text": "It is interesting to note that inspecting only the last 20 years of data versus the full 80 years of data would produce a very different result. In the last twenty years, measured snowfall was rare in this area, although the last five years have resumed trends of the previous century." }, { "code": null, "e": 9847, "s": 9407, "text": "Gardeners will keep an eye on the weather forecast, and keen gardeners will want to understand historical trends as well. An area of particular interest is the last freeze each spring. If seeds or starts are planted too early, they may succumb to a late frost. On the other end of the growing season, the first freeze each fall is a good indication of when to ensure the harvest is completed for crops that cannot withstand an early frost." }, { "code": null, "e": 9855, "s": 9847, "text": "Output:" }, { "code": null, "e": 10203, "s": 9855, "text": "Absorbing this data visually, it seems that the last freeze has been earlier in March in recent years. The local wisdom that states it is risky to plant before mid-April seems to be supported by the last 30 years of data. Although in some recent years, the soil has been too saturated with winter/spring rains to allow for planting earlier anyway." }, { "code": null, "e": 10579, "s": 10203, "text": "The last analysis that I’ll share is in regards to cold hardiness for plants. The USDA Plant Hardiness Zone Maps produced in collaboration with Oregon State University (OSU) show the average annual extreme minimum temperature from 1976–2005. While the amount of work to recreate such a map is extensive, we can recreate a more up-to-date data point for a particular ZIP code." }, { "code": null, "e": 11109, "s": 10579, "text": "Most nurseries label each variety of tree, bush, and other perennial plants with the plant hardiness zone to indicate where each variety is likely to pull through the colder months into the next year. The 97218 ZIP code seems to fall into the coloring of region 8b, which means it is safe to plant varieties that are likely to survive at an annual extreme low temperature between 15 to 20 degrees Fahrenheit. Let’s compare the data used from 1976–2005 to newer data from 1991–2020 to see if there has been any significant change." }, { "code": null, "e": 11129, "s": 11109, "text": "Output (1976–2005):" }, { "code": null, "e": 11362, "s": 11129, "text": "year annual_extreme_low Min. :1976 Min. : 9.00 1st Qu.:1983 1st Qu.:14.00 Median :1990 Median :19.00 Mean :1990 Mean :19.20 3rd Qu.:1998 3rd Qu.:24.75 Max. :2005 Max. :27.00" }, { "code": null, "e": 11382, "s": 11362, "text": "Output (1991–2020):" }, { "code": null, "e": 11615, "s": 11382, "text": "year annual_extreme_low Min. :1991 Min. :11.00 1st Qu.:1998 1st Qu.:18.00 Median :2006 Median :22.00 Mean :2006 Mean :20.77 3rd Qu.:2013 3rd Qu.:25.75 Max. :2020 Max. :27.00" }, { "code": null, "e": 12091, "s": 11615, "text": "The mean annual extreme low from the newer 30-year average is 1.6 degrees Fahrenheit warmer (now 20.8 compared to 19.2). This change, now above the cusp of 20, is enough to put this postal code into the 9a hardiness zone. Actually, microclimates within the region are already noted to be possibly in the 9a hardiness zone on the USDA/OSU map, if you look beyond the colors and notice the annotation. Perhaps this may be due to the heat island effect of the metropolitan area." }, { "code": null, "e": 12245, "s": 12091, "text": "I hope you’ve enjoyed this tutorial- and if this was your first time using R- I hope that this motivates you to learn more and democratize data analysis!" }, { "code": null, "e": 12419, "s": 12245, "text": "And if you would like to read (and write) more articles like this, please consider signing up for medium using my referral link: https://sabolch-horvat.medium.com/membership" } ]
Histograms with Plotly Express: Complete Guide | by Vaclav Dekanovsky | Towards Data Science
A histogram is a special kind of bar chart showing the distribution of a variable(s). Plotly.Express allows creating several types of histograms from a dataset using a single function px.histogram(df, parameters). In this article, I’d like to explore all the parameters and how they influence the look and feel of the chart. Plotly.Express is the higher-level API of the python Plotly library specially designed to work with the data frames. It creates interactive charts which you can zoom in and out, switch on and off parts of the graph and a tooltip with information appears when you hover over any element on the plot. All the charts can be created using this notebook on the GitHub. Feel free to download, play, and update it. Installation Dataset — used in examples Types of histogram Histogram using plotly Bar chart Parameters: color, barmode, nbins, histfunc, cumulative, barnorm, histnorm, category_orders, range_x and range_y, color_discrete_sequence, color_discrete_map, facet_col and facet_row, hover_name and hover_data, orientation, marginal, animation_Frame Plotly.Express was introduced in the version 4.0.0 of the plotly library and you can easily install it using: # pip pip install plotly# anacondaconda install -c anaconda plotly Plotly Express also requires pandas to be installed, otherwise, you will get this error when you try to import it. [In]: import plotly.express as px[Out]: ImportError: Plotly express requires pandas to be installed. There are additional requirements if you want to use the plotly in Jupyter notebooks. For Jupyter Lab you need jupyterlab-plotly. In a regular notebook, I had to install nbformat (conda install -c anaconda nbformat) towardsdatascience.com Histogram is used anytime you want to overview a distribution: occurrences of error over time finished products for each shift statistical distribution — height, weight, age, prices, salaries, speed, time, temperature, cycle, delta ranges Plotly’s histogram is easy to use not only for regular histograms but it’s easy to use it for the creation of some types of bar charts. You can recognize the histogram from the bar chart through the gaps — the histogram doesn’t have gaps between the bars. I’ll use my favorite dataset about tourist arrivals to the countries worldwide and how much they spend on their vacation. The data were preprocessed into a long-form — each category Country Name, Region, Year is a column and each combination of these categories occupy a row showing two data-values number of visotors and receipts locals got from these tourists in USD. Data about tourists go from 1995–2018. Plotly.Express can do miracles in case each category and each value is a column of the dataset. In the example I’ll use: long_df — full dataset for 215 countries and years 95–2018 yr2018 — data for the year 2018 spfrit — data about Spain, France, and Italy The most usual histogram displays a distribution of a numeric variable split into bins. In our case, the number of visitors in 2018 is spread between 0 and 89 322 000. # import the librariesimport plotly.express as pximport pandas as pd# create the simples histogrampx.histogram(yr2018, x="visitors") The simples histogram split 215 countries into 18 bins each covering 5 million visitors range. The first bin includes 157 countries which were visited by 0–4.9M tourists, seconds 17 countries which attracted 5–9.9M visitors and so on. You have more options about how to create the bins, they can be based on a category (e.g. Region in our dataframe) or a date value which plotly split into bins containing several days, months or years. You might have noticed that ranged and categorical histograms show count of countries which fall into the bin, but date histogram shows the number of visitors. You can specify what column is aggregated into the histogram using y — parameter. Because our dataset contains 215 countries each year, counting the rows would result in a flat histogram. Beside x and y plotly’s histograms have many other parameters which are described in the documentation — histogram. Let’s review them one by one, so that you get some idea how to include histogram into your next visualization. Like all the other Plotly.Express chart, color parameter expects a column which contains some category and it will color values belonging to this category by a separate color. fig = px.histogram(yr2018, x="visitors", nbins=10, color="Region", title="Visitors per region")fig.show() Because the histogram is actually a bar chart, you can set three types of bars: stacked — values are stacked on top of one another grouped — shows histogram as a grouped bar chart overlayed — displays the semi-transparent bars on the top of each other The bars must be split by color so that barmode has any effect. In the example above we see, that every year Araba is visited by 0–5M tourists, but Turkey and Spain occupy higher bins. If you’re interested in how tourism evolved in these countries over the years, you can quickly achieve it by changing x and y parameters. fig = px.histogram(sptuar, x="years", y="visitors", color="Country Name", barmode="group", title=f"Visitors in Aruba, Spain, Turkey - {barmode}")fig.update_layout(yaxis_title="Number of Visitors")fig.update_xaxes(type='category')fig.show() Besides changing x and y I have also assigned the chart into a variable fig which allowed us to update the yaxis using fig.update_layout(yaxis_title="title axis") and more importantly, modify the year color not to be considered neither as int nor as date, but as a category which means every year has a separate bar fig.update_xaxes(type="category"). Plotly chart is stored as a dictionary in the background, which you can review by printing fig.to_dict() If you use the categories, nbins parameter is ignored and plotly draws a bar for each category. But if your x is numerical or date type, plotly split your data into n number of bins. Documentation says: nbins (int) — Positive integer. Sets the number of bins. But in reality, the number of bins usually differs. I have tried to run my chart with different nbins with these results: nbins = 3–2 bins nbins = 5–5 bins nbins = 10–9 bins nbins = 20–18 bins Even the example page about plotly histograms has nbins=20 resulting in 11 bins only. Though increasing the number usually leads to an increased number of bins. Plotly also determines where the bins start and end. For example, using years for binning can start the range in either 1990, 1994 or 1995. nbins = 3–3 bins (1990–1999, 2000–2009, 2010–2019) nbins = 5–5 bins (95–99, 00–04, 05–09, 10–14, 15–19) nbins = 10–5 bins (95–99, 00–04, 05–09, 10–14, 15–19) nbins = 20–13 bins (94–95, 96–97, 98–99, 00–01 ...) You have limited ability to influence the number and the ranges of the bins, but Plotly quickly evolves so this will most probably improve in the future versions. To get the complete power over the bins, calculate them yourself and plot using plotly express bar chart as showed at the end of this article. So far we have seen histogram counting and summing the values. Plotly’s histogram allows to aggregate values using 5 functions — count, sum, avg, min, max. Of course, when we use ranged bins, then the avg yields the average of the bin, min its minimum and max the maximum, so the avg, min and max always form kind of raising stairs. In this case, it’s more interesting to apply a histogram to the categorical values, which technically creates a bar chart. If the cumulative parameter is set to False, the histogram displays the frequency (sum, avg ...) as it is, though if it’s True then each follow-up bar cumulates the values of all the preceding bars. This parameter allows displaying either the exact values if barnorm is None or showing the percentage of each color-category. You can achieve that by setting barnorm to fraction or percent. The last image on the right was modified adding a percent sign by fig.update_layout(yaxis={"ticksuffix":"%"}). In case you apply barnorm on the grouped chart, the proportions remain the same, but the absolute values change to fractions or percentages: The xaxis was formatted so that the labels are bigger using fig.update_layout(yaxis={"tickfont":{"size":18}}). Sum of barnorm percentages for one bin equals to 100% while histnorm reaches 100% once all the bars with the same color are summed up. It offer 5 options: None — absolute value of the aggregate is displayed percent — percentage (0–100%) of the total value in the bin probability — fraction (0–1) of the total in the bin density — aggregate divided by total (the sum of all bar areas equals the total number of sample points) probability density — the output of histfunc for a given bin is normalized such that it corresponds to the probability that a random event whose distribution is described by the output of histfunc will fall into that bin (the sum of all bar areas equals 1) I have explored the density and probability density from several perspectives, but there might be a bug because the values for cumulative and ordinary chart per bin differs. When you divide the chart by color you might be interested in defining the order of these colored categories. By default, the order is based on the appearance in the input dataframe which can be hard to control. Using category_order let you order the categories on the plot. You must specify for which column you define the order (as a dictionary). It’s the column you used in the color parameter. fig = px.histogram(spfrit, x="years", y="visitors", color="Country Name", barmode="group", title=f"Ordered Italy, Spain, France", category_orders={"Country Name":["Italy","Spain","France"]} )fig.show() These two parameters don’t change the chart’s ranges, but they zoom in the data based on the boundaries set. You can always unzoom using Plotly’s interactive menu. fig = px.histogram(long_df, x="years", y="receipts", range_x=["2009","2018"], title="Yearly Histogram", )fig.show() When you zoom in a lot, you can see that plotly thinks that the years are floats, because it will add labels like 2016.5. If you want to make sure that Plotly display years always as "2016" and never with decimal 2016.5 or months Jan 2016 use fig.update_xaxes(type='category'). That will hoverer change the histogram to a bar chart and gaps between the bins will appear. The color_discrete_sequence parameter lets you influence the color of the bars. The simples histogram has all the bars having the same color, which you can change using: px.histogram(df, x="column", color_discrete_sequence=["blue"]) Plotly expects a list as input, so you have to wrap your color into a list ["#00ff00"]. You can use either color name — blue, red, lightgrey and if you don’t guess the correct name, plotly’s error will provide the full list of colors accessible by name: ValueError: Invalid value of type 'builtins.str' received for the 'color' property of histogram.marker Received value: 'lightgreene' The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, ... You can also use hash string or rgb/rgba, hsl/hsla and hsv/hsva (google this term if they don’t right the bell). The last a stands for alpha which controls the opacity of the bar. If you list more than one color for an un-split histogram where you don’t use the color parameter, only the first color in the list is applied. When you split the bars using color the tints you provide in the color_discrete_sequence will paint bars in each category. You can change the order or categories using the previous param — category_orders. If you are not certain which colors to pick, but you want to have the colors which fit together, try some prebuild color sets which are part of plotly. fig = px.histogram(... color_discrete_sequence=px.colors.qualitative.Pastel2,...) You can assign the colors using a dictionary as well. In that case you use the parameter color_discrete_map. The keys of this dict are the values in the column specified in color. px.histogram(df, x="column",color="Country Names",color_discrete_map={ "Spain":"lightgreen", "France":"rgba(0,0,0,100)", "Italy":"#FFFF00"}) There is also an option to use a column in the data frame which contains the names of the colors or their hash codes. In the case you use color="column with colors name" and color_discrete_map="identity". The downside of this approach is that you lose the interactive legend, because it doesn’t contain the names of the categories (e.g. Country Names) anymore, but the names of the colors. # create a color column specifying color for each of the countriesspfrit["color"] = spfrit["Country Name"].map({"Spain":"red", "France":"black", "Italy":"orange"})# spfrit now contains: # country_name year visitors color# Spain 1995 32971000 red# France 1995 60033000 black# ...""" Parameter color_discrete_map using identity in case color contains real color names/hex codes """fig = px.histogram(spfrit, x="year", y="visitors", color="color", barmode="group", title=f"Histnorm {histnorm} histogram", category_orders={"Country Name":["Italy","Spain","France"]}, color_discrete_map="identity")fig.show() Sometimes you prefer to show the categories separately next to each other in the columns or on the top of each other in rows. facet_col and facet_row parameters are destined for this purpose. Usually, you combine the facet_col or facet_row with a color parameter to differentiate the color of the bars in each row or column as well. px.histogram(df, x="value column", color="column", facet_col="column") If you have too many columns you can split them after every x-th column by parameter facet_col_wrap. The following example shows 9 categories split after 3 columns by facet_col_wrap=3 px.histogram(df, x="value column", color="column", facet_col="column", facet_col_wrap=n) All the plots are connected so that when you zoom in or pan one of the graphs, all the others will change as well. Rows don’t have facet_row_wrap argument, but you can adjust the spacing between the rows via facet_row_spacing. px.histogram(df, x="value column", color="column", facet_row="column", facet_row_spacing=0.2) Hover_name and hover_data influence the look of the tooltip. hover_name highlights the column on the top of the tooltip and hover_data allow to remove or add a column to the tooltip using hover_data={# to remove"Column Name 1":False, # to add"Column Name 2":True} These parameters always worked well in plotly, but in the case of histogram there’s some bug and hover_name doesn’t work at all while hover_data only works sometimes. The histogram can be oriented horizontally or vertically. Orientation parameter has two values v and h but the orientation is rather influenced by x and y. Switch the order of x and y and you rotate the horizontal chart vertically. If you need to reverse the order of the axes, so that the lowest numerical bin is on the top rather than the bottom, use: fig.update_yaxes(autorange="reversed") The same applies in case you specify both x and y. By switching them you turn the horizontal plot into a vertical one and v.v. On the picture above you can see that hover shows tooltips for all the categories. It’s because I’ve clicked on the Compare data on hover icon (second from the right) in the Plotly menu. An interesting parameter I’d like to show you is the option to add a marginal subplot showing the detailed distribution of the variables. You can choose from 4 types of the marginal plot: histogram — which is basically the same as the histogram below it rug — which shows exact spots of each data value within the violin — doing the violin plot, estimating the probability density of the variable box — box plot highlighting the median, first and third quartile Marginal plots can be drawn even for more than one category. In such a case a separate marginal chart will be calculated. Note that in this case, you cannot use barmode="group". The last parameter we will discuss today is another interactive feature of Plotly which let you animate the chart. Adding a single parameter animation_frame="years" turns the plot into an animation which can be started by the play and stop buttons or you can navigate to separate slides by clicking to the menu. It’s often necessary to specify the range of the animated chart to avoid changes in the dimensions of the grid. px.histogram(spfrit, y="Country Name", x="visitors", color="Country Name", barmode="group", # add the animation animation_frame="years", # anchor the ranges so that the chart doesn't change frame to frame range_x=[0,spfrit["visitors"].max()*1.1]) It can be used on the categorical column too. px.histogram(long_df, x="years", y="visitors", color="Region", animation_frame="Region", color_discrete_sequence=px.colors.qualitative.Safe, range_y=[0,long_df.groupby(["Region","years"])["visitors"].sum().max()*1.1] ) As you have seen when we have discussed the nbins parameter Plotly is stubborn about binning the data. If you want to keep your freedom you can always bin the data yourself and plot a regular bar chart. Using pd.cut to bin the data, groupby to aggregate the values in the bin and passing the results to the px.bar(df, parameter) allow you to get the histogram of your own. This way you have many more options. You can display the bins on the x-axis (5, 10] or you can display just the bordering number 10M, 20M etc. when you bin using pd.cut(df, bins=bins, labels=bins[1:]). You can add labels into or above the bars showing how many occurrences contain each bar. Using fig.update_layout(bargap=0) let you adjust the gap between the bars Alternatively, you can bin the data by numpy’s np.histogram. # bin with np.histogramcounts, bins = np.histogram(yr2018["visitors"], bins=bins)# turn into data framedf = pd.DataFrame({"bins":bins[1:], "counts":counts})# chart using Plotly.Expressfig = px.bar(df, x="bins", y="counts", text="counts") Plotly’s histograms are a quick way to picture a distribution of the data variable. Plotly Express histograms are also useful to draw many kinds of bar charts, aggregating data into categories or over time. So far Plotly histograms however lack some features (which are available for other plotly charts), especially the option to add labels. The bins are not easy to modify and nbins parameter doesn’t always deliver the expected results. You can always do the calculations yourself and draw the results using px.bar(). Plotly is being regularly improved, so maybe these things will be updated soon and we might have an option to add an estimated distribution curve overlay too. Now it’s your turn to explore the histograms. Download a dataset, for example, historical temperatures in cities around the world and study the distribution of temperatures in various regions. If you liked this article, check other guidelines:* Visualize error log with Plotly* How to split data into test and train set* Various pandas persistance methods* Unzip all archives in a folderMany graphics on this page were created using canva.com (affiliate link, when you click on it and purchase a product, you won't pay more, but I can receive a small reward; you can always write canva.com to your browser to avoid this). Canva offer some free templates and graphics too. All the charts can be run through the python script in this notebook — Histograms with Plotly on Github.
[ { "code": null, "e": 496, "s": 171, "text": "A histogram is a special kind of bar chart showing the distribution of a variable(s). Plotly.Express allows creating several types of histograms from a dataset using a single function px.histogram(df, parameters). In this article, I’d like to explore all the parameters and how they influence the look and feel of the chart." }, { "code": null, "e": 795, "s": 496, "text": "Plotly.Express is the higher-level API of the python Plotly library specially designed to work with the data frames. It creates interactive charts which you can zoom in and out, switch on and off parts of the graph and a tooltip with information appears when you hover over any element on the plot." }, { "code": null, "e": 904, "s": 795, "text": "All the charts can be created using this notebook on the GitHub. Feel free to download, play, and update it." }, { "code": null, "e": 917, "s": 904, "text": "Installation" }, { "code": null, "e": 944, "s": 917, "text": "Dataset — used in examples" }, { "code": null, "e": 963, "s": 944, "text": "Types of histogram" }, { "code": null, "e": 996, "s": 963, "text": "Histogram using plotly Bar chart" }, { "code": null, "e": 1246, "s": 996, "text": "Parameters: color, barmode, nbins, histfunc, cumulative, barnorm, histnorm, category_orders, range_x and range_y, color_discrete_sequence, color_discrete_map, facet_col and facet_row, hover_name and hover_data, orientation, marginal, animation_Frame" }, { "code": null, "e": 1356, "s": 1246, "text": "Plotly.Express was introduced in the version 4.0.0 of the plotly library and you can easily install it using:" }, { "code": null, "e": 1423, "s": 1356, "text": "# pip pip install plotly# anacondaconda install -c anaconda plotly" }, { "code": null, "e": 1538, "s": 1423, "text": "Plotly Express also requires pandas to be installed, otherwise, you will get this error when you try to import it." }, { "code": null, "e": 1639, "s": 1538, "text": "[In]: import plotly.express as px[Out]: ImportError: Plotly express requires pandas to be installed." }, { "code": null, "e": 1855, "s": 1639, "text": "There are additional requirements if you want to use the plotly in Jupyter notebooks. For Jupyter Lab you need jupyterlab-plotly. In a regular notebook, I had to install nbformat (conda install -c anaconda nbformat)" }, { "code": null, "e": 1878, "s": 1855, "text": "towardsdatascience.com" }, { "code": null, "e": 1941, "s": 1878, "text": "Histogram is used anytime you want to overview a distribution:" }, { "code": null, "e": 1972, "s": 1941, "text": "occurrences of error over time" }, { "code": null, "e": 2005, "s": 1972, "text": "finished products for each shift" }, { "code": null, "e": 2117, "s": 2005, "text": "statistical distribution — height, weight, age, prices, salaries, speed, time, temperature, cycle, delta ranges" }, { "code": null, "e": 2373, "s": 2117, "text": "Plotly’s histogram is easy to use not only for regular histograms but it’s easy to use it for the creation of some types of bar charts. You can recognize the histogram from the bar chart through the gaps — the histogram doesn’t have gaps between the bars." }, { "code": null, "e": 2782, "s": 2373, "text": "I’ll use my favorite dataset about tourist arrivals to the countries worldwide and how much they spend on their vacation. The data were preprocessed into a long-form — each category Country Name, Region, Year is a column and each combination of these categories occupy a row showing two data-values number of visotors and receipts locals got from these tourists in USD. Data about tourists go from 1995–2018." }, { "code": null, "e": 2903, "s": 2782, "text": "Plotly.Express can do miracles in case each category and each value is a column of the dataset. In the example I’ll use:" }, { "code": null, "e": 2962, "s": 2903, "text": "long_df — full dataset for 215 countries and years 95–2018" }, { "code": null, "e": 2994, "s": 2962, "text": "yr2018 — data for the year 2018" }, { "code": null, "e": 3039, "s": 2994, "text": "spfrit — data about Spain, France, and Italy" }, { "code": null, "e": 3207, "s": 3039, "text": "The most usual histogram displays a distribution of a numeric variable split into bins. In our case, the number of visitors in 2018 is spread between 0 and 89 322 000." }, { "code": null, "e": 3340, "s": 3207, "text": "# import the librariesimport plotly.express as pximport pandas as pd# create the simples histogrampx.histogram(yr2018, x=\"visitors\")" }, { "code": null, "e": 3575, "s": 3340, "text": "The simples histogram split 215 countries into 18 bins each covering 5 million visitors range. The first bin includes 157 countries which were visited by 0–4.9M tourists, seconds 17 countries which attracted 5–9.9M visitors and so on." }, { "code": null, "e": 3777, "s": 3575, "text": "You have more options about how to create the bins, they can be based on a category (e.g. Region in our dataframe) or a date value which plotly split into bins containing several days, months or years." }, { "code": null, "e": 4125, "s": 3777, "text": "You might have noticed that ranged and categorical histograms show count of countries which fall into the bin, but date histogram shows the number of visitors. You can specify what column is aggregated into the histogram using y — parameter. Because our dataset contains 215 countries each year, counting the rows would result in a flat histogram." }, { "code": null, "e": 4352, "s": 4125, "text": "Beside x and y plotly’s histograms have many other parameters which are described in the documentation — histogram. Let’s review them one by one, so that you get some idea how to include histogram into your next visualization." }, { "code": null, "e": 4528, "s": 4352, "text": "Like all the other Plotly.Express chart, color parameter expects a column which contains some category and it will color values belonging to this category by a separate color." }, { "code": null, "e": 4634, "s": 4528, "text": "fig = px.histogram(yr2018, x=\"visitors\", nbins=10, color=\"Region\", title=\"Visitors per region\")fig.show()" }, { "code": null, "e": 4714, "s": 4634, "text": "Because the histogram is actually a bar chart, you can set three types of bars:" }, { "code": null, "e": 4765, "s": 4714, "text": "stacked — values are stacked on top of one another" }, { "code": null, "e": 4814, "s": 4765, "text": "grouped — shows histogram as a grouped bar chart" }, { "code": null, "e": 4886, "s": 4814, "text": "overlayed — displays the semi-transparent bars on the top of each other" }, { "code": null, "e": 5071, "s": 4886, "text": "The bars must be split by color so that barmode has any effect. In the example above we see, that every year Araba is visited by 0–5M tourists, but Turkey and Spain occupy higher bins." }, { "code": null, "e": 5209, "s": 5071, "text": "If you’re interested in how tourism evolved in these countries over the years, you can quickly achieve it by changing x and y parameters." }, { "code": null, "e": 5508, "s": 5209, "text": "fig = px.histogram(sptuar, x=\"years\", y=\"visitors\", color=\"Country Name\", barmode=\"group\", title=f\"Visitors in Aruba, Spain, Turkey - {barmode}\")fig.update_layout(yaxis_title=\"Number of Visitors\")fig.update_xaxes(type='category')fig.show()" }, { "code": null, "e": 5859, "s": 5508, "text": "Besides changing x and y I have also assigned the chart into a variable fig which allowed us to update the yaxis using fig.update_layout(yaxis_title=\"title axis\") and more importantly, modify the year color not to be considered neither as int nor as date, but as a category which means every year has a separate bar fig.update_xaxes(type=\"category\")." }, { "code": null, "e": 5964, "s": 5859, "text": "Plotly chart is stored as a dictionary in the background, which you can review by printing fig.to_dict()" }, { "code": null, "e": 6167, "s": 5964, "text": "If you use the categories, nbins parameter is ignored and plotly draws a bar for each category. But if your x is numerical or date type, plotly split your data into n number of bins. Documentation says:" }, { "code": null, "e": 6224, "s": 6167, "text": "nbins (int) — Positive integer. Sets the number of bins." }, { "code": null, "e": 6346, "s": 6224, "text": "But in reality, the number of bins usually differs. I have tried to run my chart with different nbins with these results:" }, { "code": null, "e": 6363, "s": 6346, "text": "nbins = 3–2 bins" }, { "code": null, "e": 6380, "s": 6363, "text": "nbins = 5–5 bins" }, { "code": null, "e": 6398, "s": 6380, "text": "nbins = 10–9 bins" }, { "code": null, "e": 6417, "s": 6398, "text": "nbins = 20–18 bins" }, { "code": null, "e": 6718, "s": 6417, "text": "Even the example page about plotly histograms has nbins=20 resulting in 11 bins only. Though increasing the number usually leads to an increased number of bins. Plotly also determines where the bins start and end. For example, using years for binning can start the range in either 1990, 1994 or 1995." }, { "code": null, "e": 6769, "s": 6718, "text": "nbins = 3–3 bins (1990–1999, 2000–2009, 2010–2019)" }, { "code": null, "e": 6822, "s": 6769, "text": "nbins = 5–5 bins (95–99, 00–04, 05–09, 10–14, 15–19)" }, { "code": null, "e": 6876, "s": 6822, "text": "nbins = 10–5 bins (95–99, 00–04, 05–09, 10–14, 15–19)" }, { "code": null, "e": 6928, "s": 6876, "text": "nbins = 20–13 bins (94–95, 96–97, 98–99, 00–01 ...)" }, { "code": null, "e": 7091, "s": 6928, "text": "You have limited ability to influence the number and the ranges of the bins, but Plotly quickly evolves so this will most probably improve in the future versions." }, { "code": null, "e": 7234, "s": 7091, "text": "To get the complete power over the bins, calculate them yourself and plot using plotly express bar chart as showed at the end of this article." }, { "code": null, "e": 7390, "s": 7234, "text": "So far we have seen histogram counting and summing the values. Plotly’s histogram allows to aggregate values using 5 functions — count, sum, avg, min, max." }, { "code": null, "e": 7690, "s": 7390, "text": "Of course, when we use ranged bins, then the avg yields the average of the bin, min its minimum and max the maximum, so the avg, min and max always form kind of raising stairs. In this case, it’s more interesting to apply a histogram to the categorical values, which technically creates a bar chart." }, { "code": null, "e": 7889, "s": 7690, "text": "If the cumulative parameter is set to False, the histogram displays the frequency (sum, avg ...) as it is, though if it’s True then each follow-up bar cumulates the values of all the preceding bars." }, { "code": null, "e": 8079, "s": 7889, "text": "This parameter allows displaying either the exact values if barnorm is None or showing the percentage of each color-category. You can achieve that by setting barnorm to fraction or percent." }, { "code": null, "e": 8190, "s": 8079, "text": "The last image on the right was modified adding a percent sign by fig.update_layout(yaxis={\"ticksuffix\":\"%\"})." }, { "code": null, "e": 8331, "s": 8190, "text": "In case you apply barnorm on the grouped chart, the proportions remain the same, but the absolute values change to fractions or percentages:" }, { "code": null, "e": 8442, "s": 8331, "text": "The xaxis was formatted so that the labels are bigger using fig.update_layout(yaxis={\"tickfont\":{\"size\":18}})." }, { "code": null, "e": 8597, "s": 8442, "text": "Sum of barnorm percentages for one bin equals to 100% while histnorm reaches 100% once all the bars with the same color are summed up. It offer 5 options:" }, { "code": null, "e": 8649, "s": 8597, "text": "None — absolute value of the aggregate is displayed" }, { "code": null, "e": 8709, "s": 8649, "text": "percent — percentage (0–100%) of the total value in the bin" }, { "code": null, "e": 8762, "s": 8709, "text": "probability — fraction (0–1) of the total in the bin" }, { "code": null, "e": 8867, "s": 8762, "text": "density — aggregate divided by total (the sum of all bar areas equals the total number of sample points)" }, { "code": null, "e": 9124, "s": 8867, "text": "probability density — the output of histfunc for a given bin is normalized such that it corresponds to the probability that a random event whose distribution is described by the output of histfunc will fall into that bin (the sum of all bar areas equals 1)" }, { "code": null, "e": 9298, "s": 9124, "text": "I have explored the density and probability density from several perspectives, but there might be a bug because the values for cumulative and ordinary chart per bin differs." }, { "code": null, "e": 9573, "s": 9298, "text": "When you divide the chart by color you might be interested in defining the order of these colored categories. By default, the order is based on the appearance in the input dataframe which can be hard to control. Using category_order let you order the categories on the plot." }, { "code": null, "e": 9696, "s": 9573, "text": "You must specify for which column you define the order (as a dictionary). It’s the column you used in the color parameter." }, { "code": null, "e": 9934, "s": 9696, "text": "fig = px.histogram(spfrit, x=\"years\", y=\"visitors\", color=\"Country Name\", barmode=\"group\", title=f\"Ordered Italy, Spain, France\", category_orders={\"Country Name\":[\"Italy\",\"Spain\",\"France\"]} )fig.show()" }, { "code": null, "e": 10098, "s": 9934, "text": "These two parameters don’t change the chart’s ranges, but they zoom in the data based on the boundaries set. You can always unzoom using Plotly’s interactive menu." }, { "code": null, "e": 10306, "s": 10098, "text": "fig = px.histogram(long_df, x=\"years\", y=\"receipts\", range_x=[\"2009\",\"2018\"], title=\"Yearly Histogram\", )fig.show()" }, { "code": null, "e": 10677, "s": 10306, "text": "When you zoom in a lot, you can see that plotly thinks that the years are floats, because it will add labels like 2016.5. If you want to make sure that Plotly display years always as \"2016\" and never with decimal 2016.5 or months Jan 2016 use fig.update_xaxes(type='category'). That will hoverer change the histogram to a bar chart and gaps between the bins will appear." }, { "code": null, "e": 10847, "s": 10677, "text": "The color_discrete_sequence parameter lets you influence the color of the bars. The simples histogram has all the bars having the same color, which you can change using:" }, { "code": null, "e": 10914, "s": 10847, "text": "px.histogram(df, x=\"column\", color_discrete_sequence=[\"blue\"])" }, { "code": null, "e": 11168, "s": 10914, "text": "Plotly expects a list as input, so you have to wrap your color into a list [\"#00ff00\"]. You can use either color name — blue, red, lightgrey and if you don’t guess the correct name, plotly’s error will provide the full list of colors accessible by name:" }, { "code": null, "e": 11706, "s": 11168, "text": "ValueError: Invalid value of type 'builtins.str' received for the 'color' property of histogram.marker Received value: 'lightgreene' The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, ..." }, { "code": null, "e": 11886, "s": 11706, "text": "You can also use hash string or rgb/rgba, hsl/hsla and hsv/hsva (google this term if they don’t right the bell). The last a stands for alpha which controls the opacity of the bar." }, { "code": null, "e": 12236, "s": 11886, "text": "If you list more than one color for an un-split histogram where you don’t use the color parameter, only the first color in the list is applied. When you split the bars using color the tints you provide in the color_discrete_sequence will paint bars in each category. You can change the order or categories using the previous param — category_orders." }, { "code": null, "e": 12388, "s": 12236, "text": "If you are not certain which colors to pick, but you want to have the colors which fit together, try some prebuild color sets which are part of plotly." }, { "code": null, "e": 12491, "s": 12388, "text": "fig = px.histogram(... color_discrete_sequence=px.colors.qualitative.Pastel2,...)" }, { "code": null, "e": 12671, "s": 12491, "text": "You can assign the colors using a dictionary as well. In that case you use the parameter color_discrete_map. The keys of this dict are the values in the column specified in color." }, { "code": null, "e": 12823, "s": 12671, "text": "px.histogram(df, x=\"column\",color=\"Country Names\",color_discrete_map={ \"Spain\":\"lightgreen\", \"France\":\"rgba(0,0,0,100)\", \"Italy\":\"#FFFF00\"})" }, { "code": null, "e": 13213, "s": 12823, "text": "There is also an option to use a column in the data frame which contains the names of the colors or their hash codes. In the case you use color=\"column with colors name\" and color_discrete_map=\"identity\". The downside of this approach is that you lose the interactive legend, because it doesn’t contain the names of the categories (e.g. Country Names) anymore, but the names of the colors." }, { "code": null, "e": 13831, "s": 13213, "text": "# create a color column specifying color for each of the countriesspfrit[\"color\"] = spfrit[\"Country Name\"].map({\"Spain\":\"red\", \"France\":\"black\", \"Italy\":\"orange\"})# spfrit now contains: # country_name year visitors color# Spain 1995 32971000 red# France 1995 60033000 black# ...\"\"\" Parameter color_discrete_map using identity in case color contains real color names/hex codes \"\"\"fig = px.histogram(spfrit, x=\"year\", y=\"visitors\", color=\"color\", barmode=\"group\", title=f\"Histnorm {histnorm} histogram\", category_orders={\"Country Name\":[\"Italy\",\"Spain\",\"France\"]}, color_discrete_map=\"identity\")fig.show()" }, { "code": null, "e": 14023, "s": 13831, "text": "Sometimes you prefer to show the categories separately next to each other in the columns or on the top of each other in rows. facet_col and facet_row parameters are destined for this purpose." }, { "code": null, "e": 14164, "s": 14023, "text": "Usually, you combine the facet_col or facet_row with a color parameter to differentiate the color of the bars in each row or column as well." }, { "code": null, "e": 14239, "s": 14164, "text": "px.histogram(df, x=\"value column\", color=\"column\", facet_col=\"column\")" }, { "code": null, "e": 14423, "s": 14239, "text": "If you have too many columns you can split them after every x-th column by parameter facet_col_wrap. The following example shows 9 categories split after 3 columns by facet_col_wrap=3" }, { "code": null, "e": 14515, "s": 14423, "text": "px.histogram(df, x=\"value column\", color=\"column\", facet_col=\"column\", facet_col_wrap=n)" }, { "code": null, "e": 14630, "s": 14515, "text": "All the plots are connected so that when you zoom in or pan one of the graphs, all the others will change as well." }, { "code": null, "e": 14742, "s": 14630, "text": "Rows don’t have facet_row_wrap argument, but you can adjust the spacing between the rows via facet_row_spacing." }, { "code": null, "e": 14839, "s": 14742, "text": "px.histogram(df, x=\"value column\", color=\"column\", facet_row=\"column\", facet_row_spacing=0.2)" }, { "code": null, "e": 15027, "s": 14839, "text": "Hover_name and hover_data influence the look of the tooltip. hover_name highlights the column on the top of the tooltip and hover_data allow to remove or add a column to the tooltip using" }, { "code": null, "e": 15103, "s": 15027, "text": "hover_data={# to remove\"Column Name 1\":False, # to add\"Column Name 2\":True}" }, { "code": null, "e": 15270, "s": 15103, "text": "These parameters always worked well in plotly, but in the case of histogram there’s some bug and hover_name doesn’t work at all while hover_data only works sometimes." }, { "code": null, "e": 15502, "s": 15270, "text": "The histogram can be oriented horizontally or vertically. Orientation parameter has two values v and h but the orientation is rather influenced by x and y. Switch the order of x and y and you rotate the horizontal chart vertically." }, { "code": null, "e": 15624, "s": 15502, "text": "If you need to reverse the order of the axes, so that the lowest numerical bin is on the top rather than the bottom, use:" }, { "code": null, "e": 15663, "s": 15624, "text": "fig.update_yaxes(autorange=\"reversed\")" }, { "code": null, "e": 15790, "s": 15663, "text": "The same applies in case you specify both x and y. By switching them you turn the horizontal plot into a vertical one and v.v." }, { "code": null, "e": 15977, "s": 15790, "text": "On the picture above you can see that hover shows tooltips for all the categories. It’s because I’ve clicked on the Compare data on hover icon (second from the right) in the Plotly menu." }, { "code": null, "e": 16165, "s": 15977, "text": "An interesting parameter I’d like to show you is the option to add a marginal subplot showing the detailed distribution of the variables. You can choose from 4 types of the marginal plot:" }, { "code": null, "e": 16231, "s": 16165, "text": "histogram — which is basically the same as the histogram below it" }, { "code": null, "e": 16291, "s": 16231, "text": "rug — which shows exact spots of each data value within the" }, { "code": null, "e": 16374, "s": 16291, "text": "violin — doing the violin plot, estimating the probability density of the variable" }, { "code": null, "e": 16439, "s": 16374, "text": "box — box plot highlighting the median, first and third quartile" }, { "code": null, "e": 16617, "s": 16439, "text": "Marginal plots can be drawn even for more than one category. In such a case a separate marginal chart will be calculated. Note that in this case, you cannot use barmode=\"group\"." }, { "code": null, "e": 16929, "s": 16617, "text": "The last parameter we will discuss today is another interactive feature of Plotly which let you animate the chart. Adding a single parameter animation_frame=\"years\" turns the plot into an animation which can be started by the play and stop buttons or you can navigate to separate slides by clicking to the menu." }, { "code": null, "e": 17041, "s": 16929, "text": "It’s often necessary to specify the range of the animated chart to avoid changes in the dimensions of the grid." }, { "code": null, "e": 17325, "s": 17041, "text": "px.histogram(spfrit, y=\"Country Name\", x=\"visitors\", color=\"Country Name\", barmode=\"group\", # add the animation animation_frame=\"years\", # anchor the ranges so that the chart doesn't change frame to frame range_x=[0,spfrit[\"visitors\"].max()*1.1])" }, { "code": null, "e": 17371, "s": 17325, "text": "It can be used on the categorical column too." }, { "code": null, "e": 17620, "s": 17371, "text": "px.histogram(long_df, x=\"years\", y=\"visitors\", color=\"Region\", animation_frame=\"Region\", color_discrete_sequence=px.colors.qualitative.Safe, range_y=[0,long_df.groupby([\"Region\",\"years\"])[\"visitors\"].sum().max()*1.1] )" }, { "code": null, "e": 17993, "s": 17620, "text": "As you have seen when we have discussed the nbins parameter Plotly is stubborn about binning the data. If you want to keep your freedom you can always bin the data yourself and plot a regular bar chart. Using pd.cut to bin the data, groupby to aggregate the values in the bin and passing the results to the px.bar(df, parameter) allow you to get the histogram of your own." }, { "code": null, "e": 18358, "s": 17993, "text": "This way you have many more options. You can display the bins on the x-axis (5, 10] or you can display just the bordering number 10M, 20M etc. when you bin using pd.cut(df, bins=bins, labels=bins[1:]). You can add labels into or above the bars showing how many occurrences contain each bar. Using fig.update_layout(bargap=0) let you adjust the gap between the bars" }, { "code": null, "e": 18419, "s": 18358, "text": "Alternatively, you can bin the data by numpy’s np.histogram." }, { "code": null, "e": 18657, "s": 18419, "text": "# bin with np.histogramcounts, bins = np.histogram(yr2018[\"visitors\"], bins=bins)# turn into data framedf = pd.DataFrame({\"bins\":bins[1:], \"counts\":counts})# chart using Plotly.Expressfig = px.bar(df, x=\"bins\", y=\"counts\", text=\"counts\")" }, { "code": null, "e": 18864, "s": 18657, "text": "Plotly’s histograms are a quick way to picture a distribution of the data variable. Plotly Express histograms are also useful to draw many kinds of bar charts, aggregating data into categories or over time." }, { "code": null, "e": 19178, "s": 18864, "text": "So far Plotly histograms however lack some features (which are available for other plotly charts), especially the option to add labels. The bins are not easy to modify and nbins parameter doesn’t always deliver the expected results. You can always do the calculations yourself and draw the results using px.bar()." }, { "code": null, "e": 19337, "s": 19178, "text": "Plotly is being regularly improved, so maybe these things will be updated soon and we might have an option to add an estimated distribution curve overlay too." }, { "code": null, "e": 19530, "s": 19337, "text": "Now it’s your turn to explore the histograms. Download a dataset, for example, historical temperatures in cities around the world and study the distribution of temperatures in various regions." }, { "code": null, "e": 20009, "s": 19530, "text": "If you liked this article, check other guidelines:* Visualize error log with Plotly* How to split data into test and train set* Various pandas persistance methods* Unzip all archives in a folderMany graphics on this page were created using canva.com (affiliate link, when you click on it and purchase a product, you won't pay more, but I can receive a small reward; you can always write canva.com to your browser to avoid this). Canva offer some free templates and graphics too." } ]
Apache Presto - Custom Function Application
Create a Maven project to develop Presto custom function. Create SimpleFunctionsFactory class to implement FunctionFactory interface. package com.tutorialspoint.simple.functions; import com.facebook.presto.metadata.FunctionFactory; import com.facebook.presto.metadata.FunctionListBuilder; import com.facebook.presto.metadata.SqlFunction; import com.facebook.presto.spi.type.TypeManager; import java.util.List; public class SimpleFunctionFactory implements FunctionFactory { private final TypeManager typeManager; public SimpleFunctionFactory(TypeManager typeManager) { this.typeManager = typeManager; } @Override public List<SqlFunction> listFunctions() { return new FunctionListBuilder(typeManager) .scalar(SimpleFunctions.class) .getFunctions(); } } Create a SimpleFunctionsPlugin class to implement Plugin interface. package com.tutorialspoint.simple.functions; import com.facebook.presto.metadata.FunctionFactory; import com.facebook.presto.spi.Plugin; import com.facebook.presto.spi.type.TypeManager; import com.google.common.collect.ImmutableList; import javax.inject.Inject; import java.util.List; import static java.util.Objects.requireNonNull; public class SimpleFunctionsPlugin implements Plugin { private TypeManager typeManager; @Inject public void setTypeManager(TypeManager typeManager) { this.typeManager = requireNonNull(typeManager, "typeManager is null”); //Inject TypeManager class here } @Override public <T> List<T> getServices(Class<T> type){ if (type == FunctionFactory.class) { return ImmutableList.of(type.cast(new SimpleFunctionFactory(typeManager))); } return ImmutableList.of(); } } Create a resource file which is specified in the implementation package. (com.tutorialspoint.simple.functions.SimpleFunctionsPlugin) Now move to the resource file location @ /path/to/resource/ Then add the changes, com.facebook.presto.spi.Plugin Add the following dependencies to pom.xml file. <?xml version = "1.0"?> <project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorialspoint.simple.functions</groupId> <artifactId>presto-simple-functions</artifactId> <packaging>jar</packaging> <version>1.0</version> <name>presto-simple-functions</name> <description>Simple test functions for Presto</description> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>com.facebook.presto</groupId> <artifactId>presto-spi</artifactId> <version>0.149</version> </dependency> <dependency> <groupId>com.facebook.presto</groupId> <artifactId>presto-main</artifactId> <version>0.149</version> </dependency> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>19.0</version> </dependency> </dependencies> <build> <finalName>presto-simple-functions</finalName> <plugins> <!-- Make this jar executable --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>2.3.2</version> </plugin> </plugins> </build> </project> Create SimpleFunctions class using Presto attributes. package com.tutorialspoint.simple.functions; import com.facebook.presto.operator.Description; import com.facebook.presto.operator.scalar.ScalarFunction; import com.facebook.presto.operator.scalar.StringFunctions; import com.facebook.presto.spi.type.StandardTypes; import com.facebook.presto.type.LiteralParameters; import com.facebook.presto.type.SqlType; public final class SimpleFunctions { private SimpleFunctions() { } @Description("Returns summation of two numbers") @ScalarFunction(“mysum") //function name @SqlType(StandardTypes.BIGINT) public static long sum(@SqlType(StandardTypes.BIGINT) long num1, @SqlType(StandardTypes.BIGINT) long num2) { return num1 + num2; } } After the application is created compile and execute the application. It will produce the JAR file. Copy the file and move the JAR file into the target Presto server plugin directory. mvn compile mvn package Now restart Presto server and connect Presto client. Then execute the custom function application as explained below, $ ./presto --catalog mysql --schema default presto:default> select mysum(10,10); _col0 ------- 20 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": 2064, "s": 2006, "text": "Create a Maven project to develop Presto custom function." }, { "code": null, "e": 2140, "s": 2064, "text": "Create SimpleFunctionsFactory class to implement FunctionFactory interface." }, { "code": null, "e": 2834, "s": 2140, "text": "package com.tutorialspoint.simple.functions; \n\nimport com.facebook.presto.metadata.FunctionFactory; \nimport com.facebook.presto.metadata.FunctionListBuilder; \nimport com.facebook.presto.metadata.SqlFunction; \nimport com.facebook.presto.spi.type.TypeManager; \nimport java.util.List; \n\npublic class SimpleFunctionFactory implements FunctionFactory { \n \n private final TypeManager typeManager; \n public SimpleFunctionFactory(TypeManager typeManager) { \n this.typeManager = typeManager; \n } \n @Override \n \n public List<SqlFunction> listFunctions() { \n return new FunctionListBuilder(typeManager) \n .scalar(SimpleFunctions.class) \n .getFunctions(); \n } \n}" }, { "code": null, "e": 2902, "s": 2834, "text": "Create a SimpleFunctionsPlugin class to implement Plugin interface." }, { "code": null, "e": 3790, "s": 2902, "text": "package com.tutorialspoint.simple.functions; \n\nimport com.facebook.presto.metadata.FunctionFactory; \nimport com.facebook.presto.spi.Plugin; \nimport com.facebook.presto.spi.type.TypeManager; \nimport com.google.common.collect.ImmutableList; \nimport javax.inject.Inject; \nimport java.util.List; \nimport static java.util.Objects.requireNonNull; \n\npublic class SimpleFunctionsPlugin implements Plugin { \n private TypeManager typeManager; \n @Inject \n \n public void setTypeManager(TypeManager typeManager) { \n this.typeManager = requireNonNull(typeManager, \"typeManager is null”); \n //Inject TypeManager class here \n } \n @Override \n \n public <T> List<T> getServices(Class<T> type){ \n if (type == FunctionFactory.class) { \n return ImmutableList.of(type.cast(new SimpleFunctionFactory(typeManager))); \n } \n return ImmutableList.of(); \n } \n}" }, { "code": null, "e": 3863, "s": 3790, "text": "Create a resource file which is specified in the implementation package." }, { "code": null, "e": 3924, "s": 3863, "text": "(com.tutorialspoint.simple.functions.SimpleFunctionsPlugin)\n" }, { "code": null, "e": 3984, "s": 3924, "text": "Now move to the resource file location @ /path/to/resource/" }, { "code": null, "e": 4006, "s": 3984, "text": "Then add the changes," }, { "code": null, "e": 4039, "s": 4006, "text": "com.facebook.presto.spi.Plugin \n" }, { "code": null, "e": 4087, "s": 4039, "text": "Add the following dependencies to pom.xml file." }, { "code": null, "e": 5828, "s": 4087, "text": "<?xml version = \"1.0\"?> \n<project xmlns = \"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0 \n http://maven.apache.org/xsd/maven-4.0.0.xsd\"> \n \n <modelVersion>4.0.0</modelVersion> \n <groupId>com.tutorialspoint.simple.functions</groupId> \n <artifactId>presto-simple-functions</artifactId> \n <packaging>jar</packaging> \n <version>1.0</version>\n <name>presto-simple-functions</name>\n <description>Simple test functions for Presto</description> \n <properties> \n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n </properties> \n <dependencies> \n <dependency> \n <groupId>com.facebook.presto</groupId> \n <artifactId>presto-spi</artifactId>\n <version>0.149</version> \n </dependency> \n <dependency> \n <groupId>com.facebook.presto</groupId> \n <artifactId>presto-main</artifactId> \n <version>0.149</version> \n </dependency> \n <dependency> \n <groupId>javax.inject</groupId> \n <artifactId>javax.inject</artifactId> \n <version>1</version> \n </dependency> \n <dependency> \n <groupId>com.google.guava</groupId> \n <artifactId>guava</artifactId> \n <version>19.0</version> \n </dependency> \n </dependencies> \n <build> \n <finalName>presto-simple-functions</finalName> \n <plugins> \n <!-- Make this jar executable --> \n <plugin> \n <groupId>org.apache.maven.plugins</groupId> \n <artifactId>maven-jar-plugin</artifactId> \n <version>2.3.2</version> \n </plugin> \n </plugins> \n </build> \n</project>" }, { "code": null, "e": 5882, "s": 5828, "text": "Create SimpleFunctions class using Presto attributes." }, { "code": null, "e": 6625, "s": 5882, "text": "package com.tutorialspoint.simple.functions; \n\nimport com.facebook.presto.operator.Description; \nimport com.facebook.presto.operator.scalar.ScalarFunction; \nimport com.facebook.presto.operator.scalar.StringFunctions; \nimport com.facebook.presto.spi.type.StandardTypes; \nimport com.facebook.presto.type.LiteralParameters; \nimport com.facebook.presto.type.SqlType; \n\npublic final class SimpleFunctions { \n private SimpleFunctions() { \n } \n \n @Description(\"Returns summation of two numbers\") \n @ScalarFunction(“mysum\") \n //function name \n @SqlType(StandardTypes.BIGINT) \n \n public static long sum(@SqlType(StandardTypes.BIGINT) long num1, \n @SqlType(StandardTypes.BIGINT) long num2) { \n return num1 + num2; \n } \n}" }, { "code": null, "e": 6809, "s": 6625, "text": "After the application is created compile and execute the application. It will produce the JAR file. Copy the file and move the JAR file into the target Presto server plugin directory." }, { "code": null, "e": 6822, "s": 6809, "text": "mvn compile\n" }, { "code": null, "e": 6835, "s": 6822, "text": "mvn package\n" }, { "code": null, "e": 6953, "s": 6835, "text": "Now restart Presto server and connect Presto client. Then execute the custom function application as explained below," }, { "code": null, "e": 6998, "s": 6953, "text": "$ ./presto --catalog mysql --schema default\n" }, { "code": null, "e": 7035, "s": 6998, "text": "presto:default> select mysum(10,10);" }, { "code": null, "e": 7060, "s": 7035, "text": " _col0 \n------- \n 20 \n" }, { "code": null, "e": 7095, "s": 7060, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7114, "s": 7095, "text": " Arnab Chakraborty" }, { "code": null, "e": 7149, "s": 7114, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7170, "s": 7149, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 7203, "s": 7170, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 7216, "s": 7203, "text": " Nilay Mehta" }, { "code": null, "e": 7251, "s": 7216, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7269, "s": 7251, "text": " Bigdata Engineer" }, { "code": null, "e": 7302, "s": 7269, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 7320, "s": 7302, "text": " Bigdata Engineer" }, { "code": null, "e": 7353, "s": 7320, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 7371, "s": 7353, "text": " Bigdata Engineer" }, { "code": null, "e": 7378, "s": 7371, "text": " Print" }, { "code": null, "e": 7389, "s": 7378, "text": " Add Notes" } ]
Cassandra - Create Index
You can create an index in Cassandra using the command CREATE INDEX. Its syntax is as follows − CREATE INDEX <identifier> ON <tablename> Given below is an example to create an index to a column. Here we are creating an index to a column ‘emp_name’ in a table named emp. cqlsh:tutorialspoint> CREATE INDEX name ON emp1 (emp_name); You can create an index to a column of a table using the execute() method of Session class. Follow the steps given below to create an index to a column in a table. 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 the 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 the cluster object using 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, then 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 ” ); Here we are using the KeySpace called tp. Therefore, create the session object as shown below. Session session = cluster.connect(“ tp” ); 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 the following example, we are creating an index to a column called emp_name, in a table named emp. You have to store the query in a string variable and pass it to the execute() method as shown below. //Query String query = "CREATE INDEX name ON emp1 (emp_name);"; session.execute(query); Given below is the complete program to create an index of a column in a table in Cassandra using Java API. import com.datastax.driver.core.Cluster; import com.datastax.driver.core.Session; public class Create_Index { public static void main(String args[]){ //Query String query = "CREATE INDEX name ON emp1 (emp_name);"; Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build(); //Creating Session object Session session = cluster.connect("tp"); //Executing the query session.execute(query); System.out.println("Index 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_Index.java $java Create_Index Under normal conditions, it should produce the following output − Index created 27 Lectures 2 hours Navdeep Kaur 34 Lectures 1.5 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2383, "s": 2287, "text": "You can create an index in Cassandra using the command CREATE INDEX. Its syntax is as follows −" }, { "code": null, "e": 2425, "s": 2383, "text": "CREATE INDEX <identifier> ON <tablename>\n" }, { "code": null, "e": 2558, "s": 2425, "text": "Given below is an example to create an index to a column. Here we are creating an index to a column ‘emp_name’ in a table named emp." }, { "code": null, "e": 2619, "s": 2558, "text": "cqlsh:tutorialspoint> CREATE INDEX name ON emp1 (emp_name);\n" }, { "code": null, "e": 2783, "s": 2619, "text": "You can create an index to a column of a table using the execute() method of Session class. Follow the steps given below to create an index to a column in a table." }, { "code": null, "e": 2893, "s": 2783, "text": "First of all, create an instance of Cluster.builder class of com.datastax.driver.core package as shown below." }, { "code": null, "e": 2974, "s": 2893, "text": "//Creating Cluster.Builder object\nCluster.Builder builder1 = Cluster.builder();\n" }, { "code": null, "e": 3118, "s": 2974, "text": "Add a contact point (IP address of the node) using the addContactPoint() method of Cluster.Builder object. This method returns Cluster.Builder." }, { "code": null, "e": 3237, "s": 3118, "text": "//Adding contact point to the Cluster.Builder object\nCluster.Builder builder2 = build.addContactPoint( \"127.0.0.1\" );\n" }, { "code": null, "e": 3422, "s": 3237, "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": 3479, "s": 3422, "text": "//Building a cluster\nCluster cluster = builder.build();\n" }, { "code": null, "e": 3556, "s": 3479, "text": "You can build the cluster object using a single line of code as shown below." }, { "code": null, "e": 3631, "s": 3556, "text": "Cluster cluster = Cluster.builder().addContactPoint(\"127.0.0.1\").build();\n" }, { "code": null, "e": 3728, "s": 3631, "text": "Create an instance of Session object using the connect() method of Cluster class as shown below." }, { "code": null, "e": 3767, "s": 3728, "text": "Session session = cluster.connect( );\n" }, { "code": null, "e": 3970, "s": 3767, "text": "This method creates a new session and initializes it. If you already have a keyspace, then 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": 4031, "s": 3970, "text": "Session session = cluster.connect(“ Your keyspace name ” );\n" }, { "code": null, "e": 4126, "s": 4031, "text": "Here we are using the KeySpace called tp. Therefore, create the session object as shown below." }, { "code": null, "e": 4170, "s": 4126, "text": "Session session = cluster.connect(“ tp” );\n" }, { "code": null, "e": 4419, "s": 4170, "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": 4622, "s": 4419, "text": "In the following example, we are creating an index to a column called emp_name, in a table named emp. You have to store the query in a string variable and pass it to the execute() method as shown below." }, { "code": null, "e": 4711, "s": 4622, "text": "//Query\nString query = \"CREATE INDEX name ON emp1 (emp_name);\";\nsession.execute(query);\n" }, { "code": null, "e": 4818, "s": 4711, "text": "Given below is the complete program to create an index of a column in a table in Cassandra using Java API." }, { "code": null, "e": 5328, "s": 4818, "text": "import com.datastax.driver.core.Cluster;\nimport com.datastax.driver.core.Session;\n\npublic class Create_Index {\n \n public static void main(String args[]){\n\n //Query\n String query = \"CREATE INDEX name ON emp1 (emp_name);\";\n Cluster cluster = Cluster.builder().addContactPoint(\"127.0.0.1\").build();\n \n //Creating Session object\n Session session = cluster.connect(\"tp\");\n \n //Executing the query\n session.execute(query);\n System.out.println(\"Index created\");\n }\n}" }, { "code": null, "e": 5480, "s": 5328, "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": 5525, "s": 5480, "text": "$javac Create_Index.java\n$java Create_Index\n" }, { "code": null, "e": 5591, "s": 5525, "text": "Under normal conditions, it should produce the following output −" }, { "code": null, "e": 5606, "s": 5591, "text": "Index created\n" }, { "code": null, "e": 5639, "s": 5606, "text": "\n 27 Lectures \n 2 hours \n" }, { "code": null, "e": 5653, "s": 5639, "text": " Navdeep Kaur" }, { "code": null, "e": 5688, "s": 5653, "text": "\n 34 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5706, "s": 5688, "text": " Bigdata Engineer" }, { "code": null, "e": 5713, "s": 5706, "text": " Print" }, { "code": null, "e": 5724, "s": 5713, "text": " Add Notes" } ]
Categorical Data, Jaccard’s Coefficient, and Multiprocessing | by Casey Whorton | Towards Data Science
An airport in Florida is closer to the Detroit airport than one in Hyderabad, and we know that because we measure the distances using latitude and longitude (Hyderabad is a huge city in India). But, how do we say one shopping basket’s contents are closer to another’s? Or one forest is more similar to another in terms of the animals that live in them? We can treat these as comparisons between sets and measure the similarity (or dissimilarity) between them using Jaccard’s coefficient (We’ll use coefficient and similarity score interchangeably). For large datasets, this can be a big task, so we can use parallel processing to do it in a shortened period of time. See the full notebook on kaggle. So, when comparing two sets (which can be an array, a series, or even a vector of binary values) the numerator is the count of elements shared between the sets and the denominator is the count of elements from both sets. In our case, the denominator is the size of the either set, so we can also say that this similarity score is the number of shared elements divided by the number of elements that could be shared. Let’s check out a simple example: from sklearn.metrics import jaccard_scorefrom scipy.spatial.distance import jaccardx = [[1,1,1],[1,0,1],[0,0,0]]print(x)[[1, 1, 1], [1, 0, 1], [0, 0, 0]]jaccard(x[0],x[1])0.33jaccard_score(x[0],x[1])0.66 The array x has three rows. The first row will be the observation we wish to compare to. Notice how the Jaccard function returns the number of elements not shared between the first two rows. The jaccard_score function returns the opposite: it’s the number of elements shared between the first two rows. One shows the dissimilarity and the other shows the similarity. I personally prefer the similarity score offered in scikit-learn, but it’s important you are aware of the difference. (Further be aware that some people make the distinction that the element 0 shouldn’t be included at all in the calculation. This makes sense when under certain circumstances.) Now that we’ve seen this metric under a simple case, let’s apply it to a larger dataset. import numpy as npimport pandas as pdx0 = np.random.choice([0, 1], size=(100000,100), p=[4./5, 1./5])x1 = np.random.choice([0, 1], size=(100000,100), p=[1./3, 2./3])x2 = np.random.choice([0, 1], size=(100000,100), p=[1./2, 1./2])colnames = ['x_'+str(i) for i in range(0,100)]X = pd.DataFrame(data = np.stack([x0,x1,x2]).reshape(300000,100))X.columns = colnamestarget = np.ones(100).astype(int) Our target is one observation where all the features are set to 1. Imagine a basket that has bought every item available on your web store and you want to see which observations are closest to it. This is mainly for the purposes of the example, but you can see how this can extend to other use-cases. A huge array of 300k observations is created with binary value data (1s and 0s) to stand in for indicator features or dummy variables. The first third has a probability of (1/5) of being 1, the second third a probability of (2/3), and the last third a probability of (1/2). Let’s see how many observations overlap with our target and by how much! But first, let’s make use of the multiprocessing package and create a partial function to compare several observations to the target in parallel (this is a huge time and memory saver). from functools import partialimport multiprocessing as mppartial_jaccard = partial(jaccard_score, target)with mp.Pool() as pool: results = pool.map(partial_jaccard, [row for row in X.values]) The above code takes almost a minute (~50 seconds). This is after multiprocessing and on 300k observations with 100 features. You’re likely to come across datasets with more features and more observations. Attempting to accomplish the above task in a loop caused my computer to crash entirely (blue screen/frowny face), but if you are brave then you should try on a subset of data and see how long it takes. Below is the result. You’ll see that for the first third of the data (the one with 1/5 probability of being a 1) you can see that there is a peak with a Jaccard’s similarity score of 0.2 (20%). Similarly for the other peaks. This confirms that the comparisons are working with our multiprocessing and partial function. When you have binary data (as is the case with indicator features or dummy variables) and you want to create some type of distance metric between your observations, consider this Jaccard’s coefficient/similarity score. It’s fairly intuitive, but takes a little bit of extra work to make the measurement on lots of data. Consider this metric for a dashboard or a report and if you consider it for a clustering task, remember that making pairwise comparisons is a huge task for your computer to handle and you should consider making cluster centers and comparing to those instead.
[ { "code": null, "e": 872, "s": 172, "text": "An airport in Florida is closer to the Detroit airport than one in Hyderabad, and we know that because we measure the distances using latitude and longitude (Hyderabad is a huge city in India). But, how do we say one shopping basket’s contents are closer to another’s? Or one forest is more similar to another in terms of the animals that live in them? We can treat these as comparisons between sets and measure the similarity (or dissimilarity) between them using Jaccard’s coefficient (We’ll use coefficient and similarity score interchangeably). For large datasets, this can be a big task, so we can use parallel processing to do it in a shortened period of time. See the full notebook on kaggle." }, { "code": null, "e": 1288, "s": 872, "text": "So, when comparing two sets (which can be an array, a series, or even a vector of binary values) the numerator is the count of elements shared between the sets and the denominator is the count of elements from both sets. In our case, the denominator is the size of the either set, so we can also say that this similarity score is the number of shared elements divided by the number of elements that could be shared." }, { "code": null, "e": 1322, "s": 1288, "text": "Let’s check out a simple example:" }, { "code": null, "e": 1526, "s": 1322, "text": "from sklearn.metrics import jaccard_scorefrom scipy.spatial.distance import jaccardx = [[1,1,1],[1,0,1],[0,0,0]]print(x)[[1, 1, 1], [1, 0, 1], [0, 0, 0]]jaccard(x[0],x[1])0.33jaccard_score(x[0],x[1])0.66" }, { "code": null, "e": 2011, "s": 1526, "text": "The array x has three rows. The first row will be the observation we wish to compare to. Notice how the Jaccard function returns the number of elements not shared between the first two rows. The jaccard_score function returns the opposite: it’s the number of elements shared between the first two rows. One shows the dissimilarity and the other shows the similarity. I personally prefer the similarity score offered in scikit-learn, but it’s important you are aware of the difference." }, { "code": null, "e": 2187, "s": 2011, "text": "(Further be aware that some people make the distinction that the element 0 shouldn’t be included at all in the calculation. This makes sense when under certain circumstances.)" }, { "code": null, "e": 2276, "s": 2187, "text": "Now that we’ve seen this metric under a simple case, let’s apply it to a larger dataset." }, { "code": null, "e": 2670, "s": 2276, "text": "import numpy as npimport pandas as pdx0 = np.random.choice([0, 1], size=(100000,100), p=[4./5, 1./5])x1 = np.random.choice([0, 1], size=(100000,100), p=[1./3, 2./3])x2 = np.random.choice([0, 1], size=(100000,100), p=[1./2, 1./2])colnames = ['x_'+str(i) for i in range(0,100)]X = pd.DataFrame(data = np.stack([x0,x1,x2]).reshape(300000,100))X.columns = colnamestarget = np.ones(100).astype(int)" }, { "code": null, "e": 2971, "s": 2670, "text": "Our target is one observation where all the features are set to 1. Imagine a basket that has bought every item available on your web store and you want to see which observations are closest to it. This is mainly for the purposes of the example, but you can see how this can extend to other use-cases." }, { "code": null, "e": 3503, "s": 2971, "text": "A huge array of 300k observations is created with binary value data (1s and 0s) to stand in for indicator features or dummy variables. The first third has a probability of (1/5) of being 1, the second third a probability of (2/3), and the last third a probability of (1/2). Let’s see how many observations overlap with our target and by how much! But first, let’s make use of the multiprocessing package and create a partial function to compare several observations to the target in parallel (this is a huge time and memory saver)." }, { "code": null, "e": 3698, "s": 3503, "text": "from functools import partialimport multiprocessing as mppartial_jaccard = partial(jaccard_score, target)with mp.Pool() as pool: results = pool.map(partial_jaccard, [row for row in X.values])" }, { "code": null, "e": 4106, "s": 3698, "text": "The above code takes almost a minute (~50 seconds). This is after multiprocessing and on 300k observations with 100 features. You’re likely to come across datasets with more features and more observations. Attempting to accomplish the above task in a loop caused my computer to crash entirely (blue screen/frowny face), but if you are brave then you should try on a subset of data and see how long it takes." }, { "code": null, "e": 4425, "s": 4106, "text": "Below is the result. You’ll see that for the first third of the data (the one with 1/5 probability of being a 1) you can see that there is a peak with a Jaccard’s similarity score of 0.2 (20%). Similarly for the other peaks. This confirms that the comparisons are working with our multiprocessing and partial function." } ]
Dunder or magic methods in python
magic methods that allow us to do some pretty neat tricks in object oriented programming. These methods are identified by a two underscores (__) used as prefix and suffix. As example, function as interceptors that are automatically called when certain conditions are met. In python __repr__ is a built-in function used to compute the "official" string representation of an object, while __str__ is a built-in function that computes the "informal" string representations of an object. Live Demo class String: # magic method to initiate object def __init__(self, string): self.string = string # Driver Code if __name__ == '__main__': # object creation my_string = String('Python') # print object location print(my_string) <__main__.String object at 0x000000BF0D411908> Live Demo class String: # magic method to initiate object def __init__(self, string): self.string = string # print our string object def __repr__(self): return 'Object: {}'.format(self.string) # Driver Code if __name__ == '__main__': # object creation my_string = String('Python') # print object location print(my_string) Object: Python Live Demo class String: # magic method to initiate object def __init__(self, string): self.string = string # print our string object def __repr__(self): return 'Object: {}'.format(self.string) # Driver Code if __name__ == '__main__': # object creation my_string = String('Python') # concatenate String object and a string print(my_string + ' Program') TypeError: unsupported operand type(s) for +: 'String' and 'str' Now add __add__ method to String class class String: # magic method to initiate object def __init__(self, string): self.string = string # print our string object def __repr__(self): return 'Object: {}'.format(self.string) def __add__(self, other): return self.string + other # Driver Code if __name__ == '__main__': # object creation my_string = String('Hello') # concatenate String object and a string print(my_string +' Python') Hello Python
[ { "code": null, "e": 1334, "s": 1062, "text": "magic methods that allow us to do some pretty neat tricks in object oriented programming. These methods are identified by a two underscores (__) used as prefix and suffix. As example, function as interceptors that are automatically called when certain conditions are met." }, { "code": null, "e": 1546, "s": 1334, "text": "In python __repr__ is a built-in function used to compute the \"official\" string representation of an object, while __str__ is a built-in function that computes the \"informal\" string representations of an object." }, { "code": null, "e": 1557, "s": 1546, "text": " Live Demo" }, { "code": null, "e": 1807, "s": 1557, "text": "class String:\n # magic method to initiate object\n def __init__(self, string):\n self.string = string\n# Driver Code\nif __name__ == '__main__':\n # object creation\n my_string = String('Python')\n # print object location\n print(my_string)" }, { "code": null, "e": 1855, "s": 1807, "text": "<__main__.String object at 0x000000BF0D411908>\n" }, { "code": null, "e": 1866, "s": 1855, "text": " Live Demo" }, { "code": null, "e": 2214, "s": 1866, "text": "class String:\n # magic method to initiate object\n def __init__(self, string):\n self.string = string\n # print our string object\n def __repr__(self):\n return 'Object: {}'.format(self.string)\n# Driver Code\nif __name__ == '__main__':\n # object creation\n my_string = String('Python')\n # print object location\n print(my_string)" }, { "code": null, "e": 2230, "s": 2214, "text": "Object: Python\n" }, { "code": null, "e": 2241, "s": 2230, "text": " Live Demo" }, { "code": null, "e": 2619, "s": 2241, "text": "class String:\n # magic method to initiate object\n def __init__(self, string):\n self.string = string\n # print our string object\n def __repr__(self):\n return 'Object: {}'.format(self.string)\n# Driver Code\nif __name__ == '__main__':\n # object creation\n my_string = String('Python')\n # concatenate String object and a string\n print(my_string + ' Program')" }, { "code": null, "e": 2685, "s": 2619, "text": "TypeError: unsupported operand type(s) for +: 'String' and 'str'\n" }, { "code": null, "e": 2724, "s": 2685, "text": "Now add __add__ method to String class" }, { "code": null, "e": 3161, "s": 2724, "text": "class String:\n # magic method to initiate object\n def __init__(self, string):\n self.string = string\n # print our string object\n def __repr__(self):\n return 'Object: {}'.format(self.string)\n def __add__(self, other):\n return self.string + other\n# Driver Code\nif __name__ == '__main__':\n # object creation\n my_string = String('Hello')\n # concatenate String object and a string\n print(my_string +' Python')" }, { "code": null, "e": 3175, "s": 3161, "text": "Hello Python\n" } ]
How to add list in alert dialog?
This example demonstrate about how to add list in alert dialog Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:layout_width = "match_parent" android:gravity = "center" android:layout_height = "match_parent"> <TextView android:id = "@+id/click" android:layout_width = "wrap_content" android:textSize = "30sp" android:layout_height = "wrap_content" android:text = "Click"/> </LinearLayout> In the above code, we have taken text view. Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.annotation.TargetApi; import android.content.DialogInterface; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { TextView text; @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); text = findViewById(R.id.click); text.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showAlertDialog(); } }); } private void showAlertDialog() { AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this); alertDialog.setTitle("AlertDialog"); String[] items = {"java","android","Data Structures","HTML","CSS"}; alertDialog.setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch(which) { case 0: Toast.makeText(MainActivity.this,"Clicked on java",Toast.LENGTH_LONG).show(); break; case 1: Toast.makeText(MainActivity.this,"Clicked on android",Toast.LENGTH_LONG).show(); break; case 2: Toast.makeText(MainActivity.this,"Clicked on Data Structures",Toast.LENGTH_LONG).show(); break; case 3: Toast.makeText(MainActivity.this,"Clicked on HTML",Toast.LENGTH_LONG).show(); break; case 4: Toast.makeText(MainActivity.this,"Clicked on CSS",Toast.LENGTH_LONG).show(); break; } } }); AlertDialog alert = alertDialog.create(); alert.setCanceledOnTouchOutside(false); alert.show(); } } Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Now click on textview to open Alert Dialog.
[ { "code": null, "e": 1125, "s": 1062, "text": "This example demonstrate about how to add list in alert dialog" }, { "code": null, "e": 1254, "s": 1125, "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": 1319, "s": 1254, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1764, "s": 1319, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n android:layout_width = \"match_parent\"\n android:gravity = \"center\"\n android:layout_height = \"match_parent\">\n <TextView\n android:id = \"@+id/click\"\n android:layout_width = \"wrap_content\"\n android:textSize = \"30sp\"\n android:layout_height = \"wrap_content\"\n android:text = \"Click\"/>\n</LinearLayout>" }, { "code": null, "e": 1808, "s": 1764, "text": "In the above code, we have taken text view." }, { "code": null, "e": 1865, "s": 1808, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 4019, "s": 1865, "text": "package com.example.myapplication;\nimport android.annotation.TargetApi;\nimport android.content.DialogInterface;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.v7.app.AlertDialog;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Switch;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\npublic class MainActivity extends AppCompatActivity {\n TextView text;\n @TargetApi(Build.VERSION_CODES.LOLLIPOP)\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n text = findViewById(R.id.click);\n text.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n showAlertDialog();\n }\n });\n }\n private void showAlertDialog() {\n AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);\n alertDialog.setTitle(\"AlertDialog\");\n String[] items = {\"java\",\"android\",\"Data Structures\",\"HTML\",\"CSS\"};\n alertDialog.setItems(items, new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n switch(which) {\n case 0:\n Toast.makeText(MainActivity.this,\"Clicked on java\",Toast.LENGTH_LONG).show();\n break;\n case 1:\n Toast.makeText(MainActivity.this,\"Clicked on android\",Toast.LENGTH_LONG).show();\n break;\n case 2:\n Toast.makeText(MainActivity.this,\"Clicked on Data Structures\",Toast.LENGTH_LONG).show();\n break;\n case 3:\n Toast.makeText(MainActivity.this,\"Clicked on HTML\",Toast.LENGTH_LONG).show();\n break;\n case 4:\n Toast.makeText(MainActivity.this,\"Clicked on CSS\",Toast.LENGTH_LONG).show();\n break;\n }\n }\n });\n AlertDialog alert = alertDialog.create();\n alert.setCanceledOnTouchOutside(false);\n alert.show();\n }\n}" }, { "code": null, "e": 4366, "s": 4019, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 4410, "s": 4366, "text": "Now click on textview to open Alert Dialog." } ]
list empty() function in C++ STL
In this article we will be discussing the working, syntax and examples of list::empty() function in C++. List is a data structure that allows constant time insertion and deletion anywhere in sequence. Lists are implemented as doubly linked lists. Lists allow non-contiguous memory allocation. List perform better insertion extraction and moving of element in any position in container than array, vector and deque. In List the direct access to the element is slow and list is similar to forward_list, but forward list objects are single linked lists and they can only be iterated forwards. list::empty() is an inbuilt function in C++ STL which is declared in header file. list::empty() checks whether the given list container is empty(size is 0) or not, and returns true value if the list is empty and false if the list is not empty. bool list_name.empty(); This function accepts no value. This function returns true if the container size is zero and false if the container size is not zero. In the below code we will call a function empty() to check whether a list is empty or not and if the list is empty then we will insert elements to a list using push_back() function to check the result. Live Demo #include <bits/stdc++.h> using namespace std; int main() { list<int> myList; //to create a list //call empty() function to check if list is empty or not if (myList.empty()) cout << "my list is empty\n"; else cout << "my list isn’t empty\n"; //push_back() is used to insert element in a list myList.push_back(1); myList.push_back(2); myList.push_back(3); myList.push_back(4); if (myList.empty()) cout << "my list is empty\n"; else cout << "my list is not empty\n"; return 0; } If we run the above code it will generate the following output my list is empty my list is not empty In the below code we are trying to multiply the numbers from 1-10 and for that − First insert elements into the list using push_back() function First insert elements into the list using push_back() function Traverse the list until it won’t get empty using the function empty(). Traverse the list until it won’t get empty using the function empty(). Print the result Print the result #include <bits/stdc++.h> using namespace std; int main (){ list<int> myList; int product = 0; for (int i=1;i<=10;++i) mylist.push_back(i); while (!mylist.empty()){ product *= myList.front(); myList.pop_front(); } cout << "product of numbers from 1-10 is: " <<product << '\n'; return 0; } If we run the above code it will generate the following output product of numbers from 1-10 is: 3628800
[ { "code": null, "e": 1167, "s": 1062, "text": "In this article we will be discussing the working, syntax and examples of list::empty() function in C++." }, { "code": null, "e": 1652, "s": 1167, "text": "List is a data structure that allows constant time insertion and deletion anywhere in sequence. Lists are implemented as doubly linked lists. Lists allow non-contiguous memory allocation. List perform better insertion extraction and moving of element in any position in container than array, vector and deque. In List the direct access to the element is slow and list is similar to forward_list, but forward list objects are single linked lists and they can only be iterated forwards." }, { "code": null, "e": 1896, "s": 1652, "text": "list::empty() is an inbuilt function in C++ STL which is declared in header file. list::empty() checks whether the given list container is empty(size is 0) or not, and returns true value if the list is empty and false if the list is not empty." }, { "code": null, "e": 1920, "s": 1896, "text": "bool list_name.empty();" }, { "code": null, "e": 1952, "s": 1920, "text": "This function accepts no value." }, { "code": null, "e": 2054, "s": 1952, "text": "This function returns true if the container size is zero and false if the container size is not zero." }, { "code": null, "e": 2256, "s": 2054, "text": "In the below code we will call a function empty() to check whether a list is empty or not and if the list is empty then we will insert elements to a list using push_back() function to check the result." }, { "code": null, "e": 2267, "s": 2256, "text": " Live Demo" }, { "code": null, "e": 2803, "s": 2267, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint main() {\n list<int> myList; //to create a list\n //call empty() function to check if list is empty or not\n if (myList.empty())\n cout << \"my list is empty\\n\";\n else\n cout << \"my list isn’t empty\\n\";\n //push_back() is used to insert element in a list\n myList.push_back(1);\n myList.push_back(2);\n myList.push_back(3);\n myList.push_back(4);\n if (myList.empty())\n cout << \"my list is empty\\n\";\n else\n cout << \"my list is not empty\\n\";\n return 0;\n}" }, { "code": null, "e": 2866, "s": 2803, "text": "If we run the above code it will generate the following output" }, { "code": null, "e": 2906, "s": 2866, "text": "my list is empty\nmy list is not empty\n\n" }, { "code": null, "e": 2987, "s": 2906, "text": "In the below code we are trying to multiply the numbers from 1-10 and for that −" }, { "code": null, "e": 3050, "s": 2987, "text": "First insert elements into the list using push_back() function" }, { "code": null, "e": 3113, "s": 3050, "text": "First insert elements into the list using push_back() function" }, { "code": null, "e": 3184, "s": 3113, "text": "Traverse the list until it won’t get empty using the function empty()." }, { "code": null, "e": 3255, "s": 3184, "text": "Traverse the list until it won’t get empty using the function empty()." }, { "code": null, "e": 3272, "s": 3255, "text": "Print the result" }, { "code": null, "e": 3289, "s": 3272, "text": "Print the result" }, { "code": null, "e": 3614, "s": 3289, "text": "#include <bits/stdc++.h> \nusing namespace std;\nint main (){\n list<int> myList;\n int product = 0;\n for (int i=1;i<=10;++i)\n mylist.push_back(i);\n while (!mylist.empty()){\n product *= myList.front();\n myList.pop_front();\n }\n cout << \"product of numbers from 1-10 is: \" <<product << '\\n';\n return 0;\n}" }, { "code": null, "e": 3677, "s": 3614, "text": "If we run the above code it will generate the following output" }, { "code": null, "e": 3718, "s": 3677, "text": "product of numbers from 1-10 is: 3628800" } ]
C# Program to create Pascal’s Triangle
A Pascal’s triangle contains numbers in a triangular form where the edges of the triangle are the number 1 and a number inside the triangle is the sum of the 2 numbers directly above it. A program that demonstrates the creation of the Pascal’s triangle is given as follows. Live Demo using System; namespace PascalTriangleDemo { class Example { public static void Main() { int rows = 5, val = 1, blank, i, j; Console.WriteLine("Pascal's triangle"); for(i = 0; i<rows; i++) { for(blank = 1; blank <= rows-i; blank++) Console.Write(" "); for(j = 0; j <= i; j++) { if (j == 0||i == 0) val = 1; else val = val*(i-j+1)/j; Console.Write(val + " "); } Console.WriteLine(); } } } } The output of the above program is as follows. Pascal's triangle 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Now, let us understand the above program. The Pascal’s triangle is created using a nested for loop. The outer for loop situates the blanks required for the creation of a row in the triangle and the inner for loop specifies the values that are to be printed to create a Pascal’s triangle. The code snippet for this is given as follows. for(i = 0; i<rows; i++) { for(blank = 1; blank <= rows-i; blank++) Console.Write(" "); for(j = 0; j <= i; j++) { if (j == 0||i == 0) val = 1; else val = val*(i-j+1)/j; Console.Write(val + " "); } Console.WriteLine(); }
[ { "code": null, "e": 1249, "s": 1062, "text": "A Pascal’s triangle contains numbers in a triangular form where the edges of the triangle are the number 1 and a number inside the triangle is the sum of the 2 numbers directly above it." }, { "code": null, "e": 1336, "s": 1249, "text": "A program that demonstrates the creation of the Pascal’s triangle is given as follows." }, { "code": null, "e": 1347, "s": 1336, "text": " Live Demo" }, { "code": null, "e": 1926, "s": 1347, "text": "using System;\nnamespace PascalTriangleDemo {\n class Example {\n public static void Main() {\n int rows = 5, val = 1, blank, i, j;\n Console.WriteLine(\"Pascal's triangle\");\n for(i = 0; i<rows; i++) {\n for(blank = 1; blank <= rows-i; blank++)\n Console.Write(\" \");\n for(j = 0; j <= i; j++) {\n if (j == 0||i == 0)\n val = 1;\n else\n val = val*(i-j+1)/j;\n Console.Write(val + \" \");\n }\n Console.WriteLine();\n }\n }\n }\n}" }, { "code": null, "e": 1973, "s": 1926, "text": "The output of the above program is as follows." }, { "code": null, "e": 2021, "s": 1973, "text": "Pascal's triangle\n1\n1 1\n1 2 1\n1 3 3 1\n1 4 6 4 1" }, { "code": null, "e": 2063, "s": 2021, "text": "Now, let us understand the above program." }, { "code": null, "e": 2356, "s": 2063, "text": "The Pascal’s triangle is created using a nested for loop. The outer for loop situates the blanks required for the creation of a row in the triangle and the inner for loop specifies the values that are to be printed to create a Pascal’s triangle. The code snippet for this is given as follows." }, { "code": null, "e": 2620, "s": 2356, "text": "for(i = 0; i<rows; i++) {\n for(blank = 1; blank <= rows-i; blank++)\n Console.Write(\" \");\n for(j = 0; j <= i; j++) {\n if (j == 0||i == 0)\n val = 1;\n else\n val = val*(i-j+1)/j;\n Console.Write(val + \" \");\n }\n Console.WriteLine();\n}" } ]
Why C++ is partially Object Oriented Language? - GeeksforGeeks
30 May, 2017 The basic thing which are the essential feature of an object oriented programming are Inheritance, Polymorphism and Encapsulation. Any programming language that supports these feature completely are complete Object-oriented programming language whereas any language that supports all three feature but does not supports all features completely are Partial Object-oriented programming language. Inheritance is used to provide the concept of code-reusability.Polymorphism makes a language able to perform different task at different instance.Encapsulation makes data abstraction (security or privacy to data) possible. In object-oriented programming language, Encapsulation is achieved with the help of a class. Here are the reasons C++ is called partial or semi Object Oriented Language: Main function is outside the class : C++ supports object-oriented programming, but OO is not intrinsic to the language. You can write a valid, well-coded, excellently-styled C++ program without using an object even once.In C++, main function is mandatory, which executes first but it resides outside the class and from there we create objects. So, here creation of class becomes optional and we can write code without using class.#include <bits/stdc++.h>using namespace std; int main(){ cout << "Hello World"; return 0;}While in JAVA, main function is executed first and it reside in the class which is mandatory. So, we can’t do anything without making Class. For doing the same thing as above, we need to make a class as :class hello{ public static void main(String args[]) { System.out.println("Hello World"); }}Concept of Global variable : In C++, we can declare a variable globally, which can be accessible from anywhere and hence, it does not provides complete privacy to the data as no one can be restricted to access and modify those data and so, it provides encapsulation partially whereas In JAVA, we can declare variable inside class only and we can provide access specifier to it.#include <iostream>using namespace std; // Global variable declaration:int g = 50; int main () { // global variable g cout << g; // Local variable g g = 20; cout << g; return 0;}Output:50 20 So, in JAVA, basically every data is asked explicitly by user if it should be accessible or not.Availability of Friend function: Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful to allow a particular class to access private members of other class.Therefore, again the Object oriented features can be violated by C++. Main function is outside the class : C++ supports object-oriented programming, but OO is not intrinsic to the language. You can write a valid, well-coded, excellently-styled C++ program without using an object even once.In C++, main function is mandatory, which executes first but it resides outside the class and from there we create objects. So, here creation of class becomes optional and we can write code without using class.#include <bits/stdc++.h>using namespace std; int main(){ cout << "Hello World"; return 0;}While in JAVA, main function is executed first and it reside in the class which is mandatory. So, we can’t do anything without making Class. For doing the same thing as above, we need to make a class as :class hello{ public static void main(String args[]) { System.out.println("Hello World"); }} #include <bits/stdc++.h>using namespace std; int main(){ cout << "Hello World"; return 0;} While in JAVA, main function is executed first and it reside in the class which is mandatory. So, we can’t do anything without making Class. For doing the same thing as above, we need to make a class as : class hello{ public static void main(String args[]) { System.out.println("Hello World"); }} Concept of Global variable : In C++, we can declare a variable globally, which can be accessible from anywhere and hence, it does not provides complete privacy to the data as no one can be restricted to access and modify those data and so, it provides encapsulation partially whereas In JAVA, we can declare variable inside class only and we can provide access specifier to it.#include <iostream>using namespace std; // Global variable declaration:int g = 50; int main () { // global variable g cout << g; // Local variable g g = 20; cout << g; return 0;}Output:50 20 So, in JAVA, basically every data is asked explicitly by user if it should be accessible or not. #include <iostream>using namespace std; // Global variable declaration:int g = 50; int main () { // global variable g cout << g; // Local variable g g = 20; cout << g; return 0;} Output: 50 20 So, in JAVA, basically every data is asked explicitly by user if it should be accessible or not. Availability of Friend function: Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful to allow a particular class to access private members of other class.Therefore, again the Object oriented features can be violated by C++. Related Article: Why Java is not a purely Object-Oriented Language? This article is contributed by Aditya Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Sorting a vector in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) Convert string to char array in C++ Iterators in C++ STL Inline Functions in C++ List in C++ Standard Template Library (STL) Multithreading in C++
[ { "code": null, "e": 24122, "s": 24094, "text": "\n30 May, 2017" }, { "code": null, "e": 24516, "s": 24122, "text": "The basic thing which are the essential feature of an object oriented programming are Inheritance, Polymorphism and Encapsulation. Any programming language that supports these feature completely are complete Object-oriented programming language whereas any language that supports all three feature but does not supports all features completely are Partial Object-oriented programming language." }, { "code": null, "e": 24832, "s": 24516, "text": "Inheritance is used to provide the concept of code-reusability.Polymorphism makes a language able to perform different task at different instance.Encapsulation makes data abstraction (security or privacy to data) possible. In object-oriented programming language, Encapsulation is achieved with the help of a class." }, { "code": null, "e": 24909, "s": 24832, "text": "Here are the reasons C++ is called partial or semi Object Oriented Language:" }, { "code": null, "e": 26752, "s": 24909, "text": "Main function is outside the class : C++ supports object-oriented programming, but OO is not intrinsic to the language. You can write a valid, well-coded, excellently-styled C++ program without using an object even once.In C++, main function is mandatory, which executes first but it resides outside the class and from there we create objects. So, here creation of class becomes optional and we can write code without using class.#include <bits/stdc++.h>using namespace std; int main(){ cout << \"Hello World\"; return 0;}While in JAVA, main function is executed first and it reside in the class which is mandatory. So, we can’t do anything without making Class. For doing the same thing as above, we need to make a class as :class hello{ public static void main(String args[]) { System.out.println(\"Hello World\"); }}Concept of Global variable : In C++, we can declare a variable globally, which can be accessible from anywhere and hence, it does not provides complete privacy to the data as no one can be restricted to access and modify those data and so, it provides encapsulation partially whereas In JAVA, we can declare variable inside class only and we can provide access specifier to it.#include <iostream>using namespace std; // Global variable declaration:int g = 50; int main () { // global variable g cout << g; // Local variable g g = 20; cout << g; return 0;}Output:50 20 So, in JAVA, basically every data is asked explicitly by user if it should be accessible or not.Availability of Friend function: Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful to allow a particular class to access private members of other class.Therefore, again the Object oriented features can be violated by C++." }, { "code": null, "e": 27591, "s": 26752, "text": "Main function is outside the class : C++ supports object-oriented programming, but OO is not intrinsic to the language. You can write a valid, well-coded, excellently-styled C++ program without using an object even once.In C++, main function is mandatory, which executes first but it resides outside the class and from there we create objects. So, here creation of class becomes optional and we can write code without using class.#include <bits/stdc++.h>using namespace std; int main(){ cout << \"Hello World\"; return 0;}While in JAVA, main function is executed first and it reside in the class which is mandatory. So, we can’t do anything without making Class. For doing the same thing as above, we need to make a class as :class hello{ public static void main(String args[]) { System.out.println(\"Hello World\"); }}" }, { "code": "#include <bits/stdc++.h>using namespace std; int main(){ cout << \"Hello World\"; return 0;}", "e": 27689, "s": 27591, "text": null }, { "code": null, "e": 27894, "s": 27689, "text": "While in JAVA, main function is executed first and it reside in the class which is mandatory. So, we can’t do anything without making Class. For doing the same thing as above, we need to make a class as :" }, { "code": "class hello{ public static void main(String args[]) { System.out.println(\"Hello World\"); }}", "e": 28002, "s": 27894, "text": null }, { "code": null, "e": 28694, "s": 28002, "text": "Concept of Global variable : In C++, we can declare a variable globally, which can be accessible from anywhere and hence, it does not provides complete privacy to the data as no one can be restricted to access and modify those data and so, it provides encapsulation partially whereas In JAVA, we can declare variable inside class only and we can provide access specifier to it.#include <iostream>using namespace std; // Global variable declaration:int g = 50; int main () { // global variable g cout << g; // Local variable g g = 20; cout << g; return 0;}Output:50 20 So, in JAVA, basically every data is asked explicitly by user if it should be accessible or not." }, { "code": "#include <iostream>using namespace std; // Global variable declaration:int g = 50; int main () { // global variable g cout << g; // Local variable g g = 20; cout << g; return 0;}", "e": 28900, "s": 28694, "text": null }, { "code": null, "e": 28908, "s": 28900, "text": "Output:" }, { "code": null, "e": 28915, "s": 28908, "text": "50 20 " }, { "code": null, "e": 29012, "s": 28915, "text": "So, in JAVA, basically every data is asked explicitly by user if it should be accessible or not." }, { "code": null, "e": 29326, "s": 29012, "text": "Availability of Friend function: Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful to allow a particular class to access private members of other class.Therefore, again the Object oriented features can be violated by C++." }, { "code": null, "e": 29394, "s": 29326, "text": "Related Article: Why Java is not a purely Object-Oriented Language?" }, { "code": null, "e": 29694, "s": 29394, "text": "This article is contributed by Aditya Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 29819, "s": 29694, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 29823, "s": 29819, "text": "C++" }, { "code": null, "e": 29827, "s": 29823, "text": "CPP" }, { "code": null, "e": 29925, "s": 29827, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29953, "s": 29925, "text": "Operator Overloading in C++" }, { "code": null, "e": 29973, "s": 29953, "text": "Polymorphism in C++" }, { "code": null, "e": 29997, "s": 29973, "text": "Sorting a vector in C++" }, { "code": null, "e": 30030, "s": 29997, "text": "Friend class and function in C++" }, { "code": null, "e": 30074, "s": 30030, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 30110, "s": 30074, "text": "Convert string to char array in C++" }, { "code": null, "e": 30131, "s": 30110, "text": "Iterators in C++ STL" }, { "code": null, "e": 30155, "s": 30131, "text": "Inline Functions in C++" }, { "code": null, "e": 30199, "s": 30155, "text": "List in C++ Standard Template Library (STL)" } ]
GUI application to search a country name from a given state or city name using Python - GeeksforGeeks
04 Dec, 2021 In these articles, we are going to write python scripts to search a country from a given state or city name and bind it with the GUI application. We will be using the GeoPy module. GeoPy modules make it easier to locate the coordinates of addresses, cities, countries, landmarks, and Zipcode. Before starting we need to install the GeoPy module, so let’s run to this command on your terminal. pip install geopy Approach: Import module Use Nominatim API to access the corresponding to set of coordinates geocode() to get the location of a given place The GUI would look like below: Note: Nominatim uses OpenStreetMap data to find locations on Earth by name and address (geocoding). Below is the Implementation: Python3 from geopy.geocoders import Nominatim geolocator = Nominatim(user_agent = "geoapiExercises")location = geolocator.geocode("Delhi")print("Country Name: ", location) Output: Country Name: Delhi, Kotwali Tehsil, Central Delhi, Delhi, 110006, India Application for Searching Country from given city/state with Tkinter: This Script implements the above Implementation into a GUI. Python3 # importing the modulesfrom geopy.geocoders import Nominatimfrom tkinter import *from tkinter import messagebox def getinfo(): geolocator = Nominatim(user_agent = "geoapiExercises") place = e.get() place_res.set(place) location = geolocator.geocode(place) res.set(location) # object of tkinter# and background set for light greymaster = Tk()master.configure(bg = 'light grey') # variable Classes in tkinterplace_res = StringVar();res = StringVar(); # creating label for each information# name using widget LabelLabel(master, text = "Enter place :" , bg = "light grey").grid(row = 0, sticky = W)Label(master, text = "Place :" , bg = "light grey").grid(row = 1, sticky = W)Label(master, text = "Country Address :" , bg = "light grey").grid(row = 2, sticky = W) # creating label for class variable# name using widget EntryLabel(master, text = "", textvariable = place_res, bg = "light grey").grid(row = 1, column = 1, sticky = W)Label(master, text = "", textvariable = res, bg = "light grey").grid(row = 2, column = 1, sticky = W) e = Entry(master)e.grid(row = 0, column = 1) # creating a button using the widget # Button that will call the submit functionb = Button(master, text = "Show", command = getinfo )b.grid(row = 0, column = 2, columnspan = 2, rowspan = 2, padx = 5, pady = 5) mainloop() Output: abhigoya nnr223442 Python Tkinter-exercises Python-tkinter python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Box Plot in Python using Matplotlib Bar Plot in Matplotlib Python | Get dictionary keys as a list Python | Convert set into a list Ways to filter Pandas DataFrame by column values Python - Call function from another file loops in python Multithreading in Python | Set 2 (Synchronization) Python Dictionary keys() method Python Lambda Functions
[ { "code": null, "e": 23901, "s": 23873, "text": "\n04 Dec, 2021" }, { "code": null, "e": 24194, "s": 23901, "text": "In these articles, we are going to write python scripts to search a country from a given state or city name and bind it with the GUI application. We will be using the GeoPy module. GeoPy modules make it easier to locate the coordinates of addresses, cities, countries, landmarks, and Zipcode." }, { "code": null, "e": 24294, "s": 24194, "text": "Before starting we need to install the GeoPy module, so let’s run to this command on your terminal." }, { "code": null, "e": 24312, "s": 24294, "text": "pip install geopy" }, { "code": null, "e": 24322, "s": 24312, "text": "Approach:" }, { "code": null, "e": 24336, "s": 24322, "text": "Import module" }, { "code": null, "e": 24404, "s": 24336, "text": "Use Nominatim API to access the corresponding to set of coordinates" }, { "code": null, "e": 24451, "s": 24404, "text": "geocode() to get the location of a given place" }, { "code": null, "e": 24482, "s": 24451, "text": "The GUI would look like below:" }, { "code": null, "e": 24582, "s": 24482, "text": "Note: Nominatim uses OpenStreetMap data to find locations on Earth by name and address (geocoding)." }, { "code": null, "e": 24611, "s": 24582, "text": "Below is the Implementation:" }, { "code": null, "e": 24619, "s": 24611, "text": "Python3" }, { "code": "from geopy.geocoders import Nominatim geolocator = Nominatim(user_agent = \"geoapiExercises\")location = geolocator.geocode(\"Delhi\")print(\"Country Name: \", location)", "e": 24784, "s": 24619, "text": null }, { "code": null, "e": 24793, "s": 24784, "text": "Output: " }, { "code": null, "e": 24869, "s": 24793, "text": "Country Name: Delhi, Kotwali Tehsil, Central Delhi, Delhi, 110006, India " }, { "code": null, "e": 24999, "s": 24869, "text": "Application for Searching Country from given city/state with Tkinter: This Script implements the above Implementation into a GUI." }, { "code": null, "e": 25007, "s": 24999, "text": "Python3" }, { "code": "# importing the modulesfrom geopy.geocoders import Nominatimfrom tkinter import *from tkinter import messagebox def getinfo(): geolocator = Nominatim(user_agent = \"geoapiExercises\") place = e.get() place_res.set(place) location = geolocator.geocode(place) res.set(location) # object of tkinter# and background set for light greymaster = Tk()master.configure(bg = 'light grey') # variable Classes in tkinterplace_res = StringVar();res = StringVar(); # creating label for each information# name using widget LabelLabel(master, text = \"Enter place :\" , bg = \"light grey\").grid(row = 0, sticky = W)Label(master, text = \"Place :\" , bg = \"light grey\").grid(row = 1, sticky = W)Label(master, text = \"Country Address :\" , bg = \"light grey\").grid(row = 2, sticky = W) # creating label for class variable# name using widget EntryLabel(master, text = \"\", textvariable = place_res, bg = \"light grey\").grid(row = 1, column = 1, sticky = W)Label(master, text = \"\", textvariable = res, bg = \"light grey\").grid(row = 2, column = 1, sticky = W) e = Entry(master)e.grid(row = 0, column = 1) # creating a button using the widget # Button that will call the submit functionb = Button(master, text = \"Show\", command = getinfo )b.grid(row = 0, column = 2, columnspan = 2, rowspan = 2, padx = 5, pady = 5) mainloop()", "e": 26347, "s": 25007, "text": null }, { "code": null, "e": 26356, "s": 26347, "text": " Output:" }, { "code": null, "e": 26365, "s": 26356, "text": "abhigoya" }, { "code": null, "e": 26375, "s": 26365, "text": "nnr223442" }, { "code": null, "e": 26400, "s": 26375, "text": "Python Tkinter-exercises" }, { "code": null, "e": 26415, "s": 26400, "text": "Python-tkinter" }, { "code": null, "e": 26430, "s": 26415, "text": "python-utility" }, { "code": null, "e": 26437, "s": 26430, "text": "Python" }, { "code": null, "e": 26535, "s": 26437, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26544, "s": 26535, "text": "Comments" }, { "code": null, "e": 26557, "s": 26544, "text": "Old Comments" }, { "code": null, "e": 26593, "s": 26557, "text": "Box Plot in Python using Matplotlib" }, { "code": null, "e": 26616, "s": 26593, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 26655, "s": 26616, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26688, "s": 26655, "text": "Python | Convert set into a list" }, { "code": null, "e": 26737, "s": 26688, "text": "Ways to filter Pandas DataFrame by column values" }, { "code": null, "e": 26778, "s": 26737, "text": "Python - Call function from another file" }, { "code": null, "e": 26794, "s": 26778, "text": "loops in python" }, { "code": null, "e": 26845, "s": 26794, "text": "Multithreading in Python | Set 2 (Synchronization)" }, { "code": null, "e": 26877, "s": 26845, "text": "Python Dictionary keys() method" } ]
Plot data from a .txt file using matplotlib
To plot data from .txt file using matplotlib, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Initialize empty lists for bar_names and bar_heights. Open a sample .txt file in read "r" mode and append to bar's name and height list. Make a bar plot. To display the figure, use show() method. from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True bar_names = [] bar_heights = [] for line in open("test_data.txt", "r"): bar_name, bar_height = line.split() bar_names.append(bar_name) bar_heights.append(bar_height) plt.bar(bar_names, bar_heights) plt.show() "test_data.txt" contains the following data − Javed 12 Raju 14 Rishi 15 Kiran 10 Satish 17 Arun 23 It will produce the following output
[ { "code": null, "e": 1142, "s": 1062, "text": "To plot data from .txt file using matplotlib, we can take the following steps −" }, { "code": null, "e": 1218, "s": 1142, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1272, "s": 1218, "text": "Initialize empty lists for bar_names and bar_heights." }, { "code": null, "e": 1355, "s": 1272, "text": "Open a sample .txt file in read \"r\" mode and append to bar's name and height list." }, { "code": null, "e": 1372, "s": 1355, "text": "Make a bar plot." }, { "code": null, "e": 1414, "s": 1372, "text": "To display the figure, use show() method." }, { "code": null, "e": 1752, "s": 1414, "text": "from matplotlib import pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nbar_names = []\nbar_heights = []\n\nfor line in open(\"test_data.txt\", \"r\"):\nbar_name, bar_height = line.split()\nbar_names.append(bar_name)\nbar_heights.append(bar_height)\n\nplt.bar(bar_names, bar_heights)\n\nplt.show()" }, { "code": null, "e": 1798, "s": 1752, "text": "\"test_data.txt\" contains the following data −" }, { "code": null, "e": 1858, "s": 1798, "text": "Javed 12\nRaju 14\nRishi 15\nKiran 10\nSatish 17\nArun 23" }, { "code": null, "e": 1895, "s": 1858, "text": "It will produce the following output" } ]
C# OverflowException
OverflowException is thrown when the parameter value is out of integer ranges. Let us see an example. When we set a value to int.Parse() method that is out of integer range, then OverflowException is thrown as shown below − Live Demo using System; class Demo { static void Main() { string str = "757657657657657"; int res = int.Parse(str); } } The following error is thrown when the above program is compiled since we have passed a value that is out of integer (Int32) range. Unhandled Exception: System.OverflowException: Value was either too large or too small for an Int32.
[ { "code": null, "e": 1141, "s": 1062, "text": "OverflowException is thrown when the parameter value is out of integer ranges." }, { "code": null, "e": 1164, "s": 1141, "text": "Let us see an example." }, { "code": null, "e": 1286, "s": 1164, "text": "When we set a value to int.Parse() method that is out of integer range, then OverflowException is thrown as shown below −" }, { "code": null, "e": 1297, "s": 1286, "text": " Live Demo" }, { "code": null, "e": 1425, "s": 1297, "text": "using System;\nclass Demo {\n static void Main() {\n string str = \"757657657657657\";\n int res = int.Parse(str);\n }\n}" }, { "code": null, "e": 1557, "s": 1425, "text": "The following error is thrown when the above program is compiled since we have passed a value that is out of integer (Int32) range." }, { "code": null, "e": 1658, "s": 1557, "text": "Unhandled Exception:\nSystem.OverflowException: Value was either too large or too small for an Int32." } ]
Automated Login For Captive Portals in Linux - GeeksforGeeks
19 Feb, 2020 Every time you connect to a private network, may it be your college, office, school, etc. the captive portal screen appears where you have to enter your credentials provided by the organization. The idea is to automate that process so that whenever we are connected to any router in the same network, it automatically gets logged in. Note: In the following article, the steps are provided which may not work for every network, but the idea is to understand the process, and it can be tried as most of the captive portals are loosely built, so it is worth a try. System Requirement: Any Unix based system, preferably ubuntu Linux. Packages that need to be Installed: wget, w3m. (can be installed using apt-get) Step 1: Study of the captive portal page. This is one of the important steps and has to be carried out keenly. Right-Click on the text area provided and select inspect (Considering the browser being used is Chrome/Firefox). Notice the “name” field in the input text area. It must be something like ‘username’ or ‘password'(as shown in the image). The HTML will have JavaScript embedded into it(Obviously!). Notice the functions getting called by it. Step 2: Study the JavaScript Code. The functions that we saw earlier must be in the javascript code that the browser is using. That can be accessed in the same way the HTML was accessed. Go to the inspect and this time, click on the sources and you will see the JS codes for the website. Note: Generally these codes will be in a single straight line, so hard to interpret. Hence any online beautifier can be used to format the code to make it more readable. Step 3: Finding the link! As we very well know that every HTTP POST request is used to send data to a server. So, now in the javascript code, there must be a link or say query that is being made up and sending the POST request. So we have to find the query. The important part here is not finding the query but finding the signature that is being used along with the link. Signature means here the number of variables required, their sequence, etc. Sometimes some variables require timestamp, so a dummy value can be supplied to it(if required, the actual timestamp can also be used). Notice in the given image, the “mode” variable is given value as 191, which means login state and the value 193 which means logout state. This can be derived by reading the code keenly. Query that was found for login: queryString = “mode=191&username=” + encodeURIComponent(UserValue) + “&password=” + encodeURIComponent(document.frmHTTPClientLogin.password.value) + “&a=” + (new Date).getTime() + producttype; Query that was found for logout: queryString = “mode=193&username=” + encodeURIComponent(document.frmHTTPClientLogin.username.value) + “&a=” + (new Date).getTime() + producttype; Step 4: Creation of own query string with the variables. Once the query is observed, it is easy to make the own query with the same variables and filling in the appropriate data accordingly. The link that was made in this case was as follows : 'mode=191&username=admin&password=root&a=1551345153461' An important thing to be noted here is that one might think that this string can be appended to the IP of the captive portal and then used in browser. For example, http://192.168.1.8/loginpage.html?mode=191&username=admin&password=root&a=1551345153461 But it is important to note that this won’t work in all cases this can only work in the case where the backend technology like PHP was used where variable parsing using link is possible. Step 5: Sending the POST request using the terminal. Once the POST request can be sent by the terminal in Linux, then it can be inserted in a bash script for automation. To send POST request here, a non-graphical browser was used made for Linux. There are many non-graphical browsers out there like lynx, w3m, etc. In this case, the w3m browser was used. It can be studied easily from the manual pages of Linux. The use of POST by w3m is well explained in its manual page (shown in the image). In this case, Ajax was used to communicate with the backend and the request-response was in XML, hence the POST request was to be sent to an XML link and not a normal HTML page. This may vary network to network. The page to which the request is to be sent can be identified in the same JavaScript code in which the variables were found. Finally, the command would look something like this: w3m -post – http://192.168.1.8:8294/login.xml<<<'mode=191&username=admin&password=root&a=1551345153461' Step 6: Inserting it into a bash script. To make the process automated, it is necessary to make a bash script file that will run every time you connect to the network of your organization. To make a simple bash script go to terminal and type nano autologin Nano is a command-line editor, which will now create a file named autologin. Now paste the following script in the editor, by pressing ctrl+shift+V. Note: To create a bash file do not enter an extension to the filename as Linux never works on extension but identifies the files internally. Linux knows itself, whether the file is an ASCII text file, doc file or a bash file. #!/bin/bash wget -q --tries=10 --timeout=10 http://192.168.1.8:8294 if [[ $? -eq 0 ]]; then w3m -post - http://192.168.1.8:8294/login.xml <<<'mode=191&username=admin&password=root&a=1551345153461' echo "Online!" else echo "Unreachable!" fi Explanation: The first line of the code indicates that the file is a bash script, which is to be executed using bash only and the location of it is /bin/bash. wget is a Linux command, it is basically a program that is used to get content from the internet. Here, in this case, wget is used to check the connectivity of the PC to the network, the IP is checked that if it is active or not. If that IP is not active then that means that the device is not connected to the private network of the organization and the script won’t be executed further. The flags to wget are the number of tries to do before aborting, similarly for timeout. -q is used to turn off verbose. The $? is an environment variable that is used to store return values in Linux environment. If wget returns false, $? turns 0 and the control will go to else and nothing will happen. But when the IP is active, i.e. when wget will return a positive return value, it will be reflected in $? and the command w3m will be executed and the login will be done successfully. Step 7: Making the script executable, every time it is connected to a network. This is the final part, where the script is to be made executable, every time it is connected to any network. It will internally find if the network is the private network of the organization or not and will log in accordingly. For this step, go to your /etc/network folder. In this folder, there are 4 folders(as of the latest version of ubuntu-19.10) named: if-down.d, if-post-down.d, if-pre-up.d, if-up.d. The script just was written has to be pasted in the “if-up.d” folder. Linux internally calls all the scripts present in this folder every time it is connected to a new network. Note: If you don’t find the 4 folders by default, create the one we need and add the entry to the /etc/network/interfaces file. To paste the script, go to the directory where the script is present, and type: sudo cp autologin /etc/network/if-up.d Step 8: Making the file executable and rebooting network. The ownership of the file must be changed to root. Hence type the command: sudo chown root:root autologin Then give the permissions to make the file executable: sudo chmod +x autologin Finally, restart the network manager for the new settings to take place! /etc/init.d/network-manager restart This should make your PC able to login to the private network automatically, every time you connect it to the network! Although now you are logged in, the pop-up window of the captive portal may always occur for logging into the network, every time you connect to a network. To get rid of it, go to Settings->Privacy and turn the Connectivity Checking off. Technical Scripter 2019 Linux-Unix Technical Scripter TechTips Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. nohup Command in Linux with Examples scp command in Linux with Examples Thread functions in C/C++ mv command in Linux with examples chown command in Linux with Examples How to Find the Wi-Fi Password Using CMD in Windows? How to Run a Python Script using Docker? Docker - COPY Instruction Running Python script on GPU. Setting up the environment in Java
[ { "code": null, "e": 24408, "s": 24380, "text": "\n19 Feb, 2020" }, { "code": null, "e": 24742, "s": 24408, "text": "Every time you connect to a private network, may it be your college, office, school, etc. the captive portal screen appears where you have to enter your credentials provided by the organization. The idea is to automate that process so that whenever we are connected to any router in the same network, it automatically gets logged in." }, { "code": null, "e": 24970, "s": 24742, "text": "Note: In the following article, the steps are provided which may not work for every network, but the idea is to understand the process, and it can be tried as most of the captive portals are loosely built, so it is worth a try." }, { "code": null, "e": 25038, "s": 24970, "text": "System Requirement: Any Unix based system, preferably ubuntu Linux." }, { "code": null, "e": 25118, "s": 25038, "text": "Packages that need to be Installed: wget, w3m. (can be installed using apt-get)" }, { "code": null, "e": 25465, "s": 25118, "text": "Step 1: Study of the captive portal page. This is one of the important steps and has to be carried out keenly. Right-Click on the text area provided and select inspect (Considering the browser being used is Chrome/Firefox). Notice the “name” field in the input text area. It must be something like ‘username’ or ‘password'(as shown in the image)." }, { "code": null, "e": 25568, "s": 25465, "text": "The HTML will have JavaScript embedded into it(Obviously!). Notice the functions getting called by it." }, { "code": null, "e": 25856, "s": 25568, "text": "Step 2: Study the JavaScript Code. The functions that we saw earlier must be in the javascript code that the browser is using. That can be accessed in the same way the HTML was accessed. Go to the inspect and this time, click on the sources and you will see the JS codes for the website." }, { "code": null, "e": 26026, "s": 25856, "text": "Note: Generally these codes will be in a single straight line, so hard to interpret. Hence any online beautifier can be used to format the code to make it more readable." }, { "code": null, "e": 26399, "s": 26026, "text": "Step 3: Finding the link! As we very well know that every HTTP POST request is used to send data to a server. So, now in the javascript code, there must be a link or say query that is being made up and sending the POST request. So we have to find the query. The important part here is not finding the query but finding the signature that is being used along with the link." }, { "code": null, "e": 26797, "s": 26399, "text": "Signature means here the number of variables required, their sequence, etc. Sometimes some variables require timestamp, so a dummy value can be supplied to it(if required, the actual timestamp can also be used). Notice in the given image, the “mode” variable is given value as 191, which means login state and the value 193 which means logout state. This can be derived by reading the code keenly." }, { "code": null, "e": 26829, "s": 26797, "text": "Query that was found for login:" }, { "code": null, "e": 27022, "s": 26829, "text": "queryString = “mode=191&username=” + encodeURIComponent(UserValue) + “&password=” + encodeURIComponent(document.frmHTTPClientLogin.password.value) + “&a=” + (new Date).getTime() + producttype;" }, { "code": null, "e": 27055, "s": 27022, "text": "Query that was found for logout:" }, { "code": null, "e": 27201, "s": 27055, "text": "queryString = “mode=193&username=” + encodeURIComponent(document.frmHTTPClientLogin.username.value) + “&a=” + (new Date).getTime() + producttype;" }, { "code": null, "e": 27445, "s": 27201, "text": "Step 4: Creation of own query string with the variables. Once the query is observed, it is easy to make the own query with the same variables and filling in the appropriate data accordingly. The link that was made in this case was as follows :" }, { "code": null, "e": 27501, "s": 27445, "text": "'mode=191&username=admin&password=root&a=1551345153461'" }, { "code": null, "e": 27665, "s": 27501, "text": "An important thing to be noted here is that one might think that this string can be appended to the IP of the captive portal and then used in browser. For example," }, { "code": null, "e": 27753, "s": 27665, "text": "http://192.168.1.8/loginpage.html?mode=191&username=admin&password=root&a=1551345153461" }, { "code": null, "e": 27940, "s": 27753, "text": "But it is important to note that this won’t work in all cases this can only work in the case where the backend technology like PHP was used where variable parsing using link is possible." }, { "code": null, "e": 28434, "s": 27940, "text": "Step 5: Sending the POST request using the terminal. Once the POST request can be sent by the terminal in Linux, then it can be inserted in a bash script for automation. To send POST request here, a non-graphical browser was used made for Linux. There are many non-graphical browsers out there like lynx, w3m, etc. In this case, the w3m browser was used. It can be studied easily from the manual pages of Linux. The use of POST by w3m is well explained in its manual page (shown in the image)." }, { "code": null, "e": 28824, "s": 28434, "text": "In this case, Ajax was used to communicate with the backend and the request-response was in XML, hence the POST request was to be sent to an XML link and not a normal HTML page. This may vary network to network. The page to which the request is to be sent can be identified in the same JavaScript code in which the variables were found. Finally, the command would look something like this:" }, { "code": null, "e": 28928, "s": 28824, "text": "w3m -post – http://192.168.1.8:8294/login.xml<<<'mode=191&username=admin&password=root&a=1551345153461'" }, { "code": null, "e": 29170, "s": 28928, "text": "Step 6: Inserting it into a bash script. To make the process automated, it is necessary to make a bash script file that will run every time you connect to the network of your organization. To make a simple bash script go to terminal and type" }, { "code": null, "e": 29185, "s": 29170, "text": "nano autologin" }, { "code": null, "e": 29334, "s": 29185, "text": "Nano is a command-line editor, which will now create a file named autologin. Now paste the following script in the editor, by pressing ctrl+shift+V." }, { "code": null, "e": 29560, "s": 29334, "text": "Note: To create a bash file do not enter an extension to the filename as Linux never works on extension but identifies the files internally. Linux knows itself, whether the file is an ASCII text file, doc file or a bash file." }, { "code": null, "e": 29823, "s": 29560, "text": "#!/bin/bash\n\nwget -q --tries=10 --timeout=10 http://192.168.1.8:8294\nif [[ $? -eq 0 ]]; then\n w3m -post - http://192.168.1.8:8294/login.xml <<<'mode=191&username=admin&password=root&a=1551345153461'\n echo \"Online!\"\nelse\n echo \"Unreachable!\"\nfi\n" }, { "code": null, "e": 29836, "s": 29823, "text": "Explanation:" }, { "code": null, "e": 29982, "s": 29836, "text": "The first line of the code indicates that the file is a bash script, which is to be executed using bash only and the location of it is /bin/bash." }, { "code": null, "e": 30080, "s": 29982, "text": "wget is a Linux command, it is basically a program that is used to get content from the internet." }, { "code": null, "e": 30371, "s": 30080, "text": "Here, in this case, wget is used to check the connectivity of the PC to the network, the IP is checked that if it is active or not. If that IP is not active then that means that the device is not connected to the private network of the organization and the script won’t be executed further." }, { "code": null, "e": 30491, "s": 30371, "text": "The flags to wget are the number of tries to do before aborting, similarly for timeout. -q is used to turn off verbose." }, { "code": null, "e": 30674, "s": 30491, "text": "The $? is an environment variable that is used to store return values in Linux environment. If wget returns false, $? turns 0 and the control will go to else and nothing will happen." }, { "code": null, "e": 30858, "s": 30674, "text": "But when the IP is active, i.e. when wget will return a positive return value, it will be reflected in $? and the command w3m will be executed and the login will be done successfully." }, { "code": null, "e": 31212, "s": 30858, "text": "Step 7: Making the script executable, every time it is connected to a network. This is the final part, where the script is to be made executable, every time it is connected to any network. It will internally find if the network is the private network of the organization or not and will log in accordingly. For this step, go to your /etc/network folder." }, { "code": null, "e": 31523, "s": 31212, "text": "In this folder, there are 4 folders(as of the latest version of ubuntu-19.10) named: if-down.d, if-post-down.d, if-pre-up.d, if-up.d. The script just was written has to be pasted in the “if-up.d” folder. Linux internally calls all the scripts present in this folder every time it is connected to a new network." }, { "code": null, "e": 31731, "s": 31523, "text": "Note: If you don’t find the 4 folders by default, create the one we need and add the entry to the /etc/network/interfaces file. To paste the script, go to the directory where the script is present, and type:" }, { "code": null, "e": 31771, "s": 31731, "text": "sudo cp autologin /etc/network/if-up.d\n" }, { "code": null, "e": 31904, "s": 31771, "text": "Step 8: Making the file executable and rebooting network. The ownership of the file must be changed to root. Hence type the command:" }, { "code": null, "e": 31936, "s": 31904, "text": "sudo chown root:root autologin\n" }, { "code": null, "e": 31991, "s": 31936, "text": "Then give the permissions to make the file executable:" }, { "code": null, "e": 32016, "s": 31991, "text": "sudo chmod +x autologin\n" }, { "code": null, "e": 32089, "s": 32016, "text": "Finally, restart the network manager for the new settings to take place!" }, { "code": null, "e": 32126, "s": 32089, "text": "/etc/init.d/network-manager restart\n" }, { "code": null, "e": 32483, "s": 32126, "text": "This should make your PC able to login to the private network automatically, every time you connect it to the network! Although now you are logged in, the pop-up window of the captive portal may always occur for logging into the network, every time you connect to a network. To get rid of it, go to Settings->Privacy and turn the Connectivity Checking off." }, { "code": null, "e": 32507, "s": 32483, "text": "Technical Scripter 2019" }, { "code": null, "e": 32518, "s": 32507, "text": "Linux-Unix" }, { "code": null, "e": 32537, "s": 32518, "text": "Technical Scripter" }, { "code": null, "e": 32546, "s": 32537, "text": "TechTips" }, { "code": null, "e": 32563, "s": 32546, "text": "Web Technologies" }, { "code": null, "e": 32661, "s": 32563, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32698, "s": 32661, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 32733, "s": 32698, "text": "scp command in Linux with Examples" }, { "code": null, "e": 32759, "s": 32733, "text": "Thread functions in C/C++" }, { "code": null, "e": 32793, "s": 32759, "text": "mv command in Linux with examples" }, { "code": null, "e": 32830, "s": 32793, "text": "chown command in Linux with Examples" }, { "code": null, "e": 32883, "s": 32830, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 32924, "s": 32883, "text": "How to Run a Python Script using Docker?" }, { "code": null, "e": 32950, "s": 32924, "text": "Docker - COPY Instruction" }, { "code": null, "e": 32980, "s": 32950, "text": "Running Python script on GPU." } ]
The Art of Finding the Best Features for Machine Learning | by Rebecca Vickery | Towards Data Science
A machine learning model maps a set of data inputs, known as features, to a predictor or target variable. The goal of this process is for the model to learn a pattern or mapping between these inputs and the target variable so that given new data, where the target is unknown, the model can accurately predict the target variable. For any given data set we want to develop a model that is able to predict with the highest degree of accuracy possible. In machine learning, there are many levers that impact the performance of the model. In general, these include the following: The algorithm choice. The parameters used in the algorithm. The quantity and quality of the data set. The features used to train the model. Often in a data set, the given set of features in their raw form do not provide enough, or the most optimal, information to train a performant model. In some instances, it may be beneficial to remove unnecessary or conflicting features and this is known as feature selection. In other cases model performance may be improved if we transform one or more features into a different representation to provide better information to the model, this is known as feature engineering. In many situations using all the features available in a data set will not result in the most predictive model. Depending on the type of model being used, the size of the data set and various other factors, including excess features, can reduce model performance. There are three main goals to feature selection. Improve the accuracy with which the model is able to predict for new data. Reduce computational cost. Produce a more interpretable model. There are a number of reasons why you may remove certain features over others. This includes the relationships that exist between features, wether a statistical relationship to the target variable exists or is significant enough, or the value of the information contained within a feature. Feature selection can be performed manually by analysis of the data set both pre and post-training, or through automated statistical methods. There are a number of reasons why you may want to remove a feature from the training phase. These include: A feature that is highly correlated with another feature in the data set. If this is the case then both features are in essence providing the same information. Some algorithms are sensitive to correlated features. Features that provide little to no information. An example would be a feature where most examples have the same value. Features that have little to no statistical relationship with the target variable. Features can be selected through data analysis performed either before or after training a model. Here are a couple of common techniques to manually perform feature selection. Correlation plot One manual technique to perform feature selection is to create a visualisation which plots the correlation measure for every feature in the data set. Seaborn is a good python library to use for this. The below code produces a correlation plot for features in the breast cancer data set available from the scikit-learn API. # library importsimport pandas as pdfrom sklearn.datasets import load_breast_cancerimport matplotlib.pyplot as plt%matplotlib inlineimport seaborn as snsimport numpy as np# load the breast_cancer data set from the scikit-learn apibreast_cancer = load_breast_cancer()data = pd.DataFrame(data=breast_cancer['data'], columns = breast_cancer['feature_names'])data['target'] = breast_cancer['target']data.head()# use the pands .corr() function to compute pairwise correlations for the dataframecorr = data.corr()# visualise the data with seabornmask = np.triu(np.ones_like(corr, dtype=np.bool))sns.set_style(style = 'white')f, ax = plt.subplots(figsize=(11, 9))cmap = sns.diverging_palette(10, 250, as_cmap=True)sns.heatmap(corr, mask=mask, cmap=cmap, square=True, linewidths=.5, cbar_kws={"shrink": .5}, ax=ax) In the resulting visualisation, we can identify some features that are closely correlated and we may, therefore, want to remove some of these, and some features that have very low correlation with the target variable which we may also want to remove. Feature importances Once we have trained a model it is possible to apply further statistical analysis to understand the effects features have on the output of the model and determine from this which features are most useful. There are a number of tools and techniques available to determine feature importance. Some techniques are unique to a specific algorithm, whereas others can be applied to a wide range of models and are known as model agnostic. To illustrate feature importances I will use the built-in feature importances method for a random forest classifier in scikit-learn. The code below fits the classifier and creates a plot displaying the feature importances. from sklearn.model_selection import train_test_splitfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import train_test_split# Spliiting data into test and train setsX_train, X_test, y_train, y_test = train_test_split(data.drop('target', axis=1), data['target'], test_size=0.20, random_state=0)# fitting the modelmodel = RandomForestClassifier(n_estimators=500, n_jobs=-1, random_state=42)model.fit(X_train, y_train)# plotting feature importancesfeatures = data.drop('target', axis=1).columnsimportances = model.feature_importances_indices = np.argsort(importances)plt.figure(figsize=(10,15))plt.title('Feature Importances')plt.barh(range(len(indices)), importances[indices], color='b', align='center')plt.yticks(range(len(indices)), [features[i] for i in indices])plt.xlabel('Relative Importance')plt.show() This gives a good indicator of those features that are having an impact on the model and those that are not. We may choose to remove some of the less important features after analysing this chart. There are a number of mechanisms that use statistical methods to find the optimal set of features to use in a model automatically. The scikit-learn library contains a number of methods that provide a very simple implementation for many of these techniques. Variance threshold In statistics, variance is the squared deviation of a variable from its mean, in other words, how far are the data points spread out for a given variable? Suppose we were building a machine learning model to detect breast cancer and the data set had a boolean variable for gender. This data set is likely to consist almost entirely of one gender and therefore nearly all data points would be 1. This variable would have extremely low variance and would be not at all useful for predicting the target variable. This is one of the most simple approaches to feature selection. The scikit-learn library has a method called VarianceThreshold . This method takes a threshold value and when fitted to a feature set will remove any features below this threshold. The default value for the threshold is 0 and this will remove any features with zero variance, or in other words where all values are the same. Let’s apply this default setting to the breast cancer data set we used earlier to find out if any features are eliminated. from sklearn.feature_selection import VarianceThresholdX = data.drop('target', axis=1)selector = VarianceThreshold()print("Original feature shape:", X.shape)new_X = selector.fit_transform(X)print("Transformed feature shape:", new_X.shape) The output shows that the transformed features are the same shape so all features have at least some variance. Univariate feature selection Univariate feature selection applies univariate statistical tests to features and selects those which perform the best in these tests. Univariate tests are tests which involve only one dependent variable. This includes analysis of variance (ANOVA), linear regressions and t-tests of means. Again scikit-learn provides a number of feature selection methods that apply a variety of different univariate tests to find the best features for machine learning. We will apply one of these, known as SelectKBest to the breast cancer data set. This function selects the k best features based on a univariate statistical test. The default value of k is 10, so 10 features will be kept, and the default test is f_classif. The f_classif test is used for categorical targets as is the case for the breast cancer data set. If the target is a continuous variable f_regression should be used. The f_classif test is based on the Analysis of Variance (ANOVA) statistical test which compares the means of a number of groups, or in our case features, and determines whether any of those means are statistically significant from one another. The below code applies this function using the default parameters to the breast cancer data set. from sklearn.feature_selection import SelectKBestX = data.drop('target', axis=1)y = data['target']selector = SelectKBest()print("Original feature shape:", X.shape)new_X = selector.fit_transform(X, y)print("Transformed feature shape:", new_X.shape) The output shows that the function has reduced the features to 10. We could experiment with different values of k, training multiple models, until we find the optimum number of features. Recursive feature elimination This method performs model training on a gradually smaller and smaller set of features. Each time the feature importances or coefficients are calculated and the features with the lowest scores are removed. At the end of this process, the optimal set of features is known. As this method involves repeatably training a model we need to instantiate an estimator first. This method also works best if the data is first scaled so I have added a preprocessing step that normalizes the features. from sklearn.feature_selection import RFECVfrom sklearn.svm import SVRfrom sklearn import preprocessingX_normalized = preprocessing.normalize(X, norm='l2')y = yestimator = SVR(kernel="linear")selector = RFECV(estimator, step=1, cv=2)selector = selector.fit(X, y)print("Features selected", selector.support_)print("Feature ranking", selector.ranking_) The output below shows the features that have been selected and their ranking. Where the goal of feature selection is to reduce the dimensionality of a data set by removing unnecessary features, feature engineering is about transforming existing features and constructing new features to improve the performance of a model. There are three main reasons why we may need to perform feature engineering to develop an optimal model. Features cannot be used in their raw form. This includes features such as dates and times, where a machine learning model can only make use of the information contained within them if they are transformed into a numerical representation e.g. integer representation of the day of the week.Features can be used in their raw form but the information contained within the feature is stronger if the data is aggregated or represented in a different way. An example here might be a feature containing the age of a person, aggregating the ages into buckets or bins may better represent the relationship to the target.A feature on its own does not have a strong enough statistical relationship with the target but when combined with another feature has a meaningful relationship. Let’s say we have a data set that has a number of features based on credit history for a group of customers and a target that denotes if they have defaulted on a loan. Suppose we have a loan amount and a salary value. If we combined these into a new feature called “loan to salary ratio” this may give more or better information than those features alone. Features cannot be used in their raw form. This includes features such as dates and times, where a machine learning model can only make use of the information contained within them if they are transformed into a numerical representation e.g. integer representation of the day of the week. Features can be used in their raw form but the information contained within the feature is stronger if the data is aggregated or represented in a different way. An example here might be a feature containing the age of a person, aggregating the ages into buckets or bins may better represent the relationship to the target. A feature on its own does not have a strong enough statistical relationship with the target but when combined with another feature has a meaningful relationship. Let’s say we have a data set that has a number of features based on credit history for a group of customers and a target that denotes if they have defaulted on a loan. Suppose we have a loan amount and a salary value. If we combined these into a new feature called “loan to salary ratio” this may give more or better information than those features alone. Feature engineering can be performed through data analysis, intuition and domain knowledge. Often similar techniques to those used for manual feature selection are performed. For example, observing how features correlate to the target and how they perform in terms of feature importance indicates which features to explore further in terms of analysis. If we go back to the example of the loan data set, let's imagine we have an age variable which from a correlation plot appears to have some relationship to the target variable. We might find when we further analyse this relationship that those that default are skewed towards a particular age group. In this case, we might engineer a feature that picks out this age group and this may provide better information to the model. Manual feature engineering can be an extremely time-consuming process and requires a large amount of human intuition and domain knowledge to get right. There are tools available which have the ability to automatically synthesise a large number of new features. The Featuretools python library is an example of a tool that can perform automated feature engineering on a data set. Let’s install this library and walk through an example of automated feature engineering on the breast cancer data set. Featuretools can be installed via pip. pip install featuretools Featuretools is designed to work with relational data sets (tables or dataframes that can be joined together with a unique identifier). The featuretools library refers to each table as an entity. The breast cancer data set consists of only one entity but we can still use featuretools to generate the features. However, we need to first create a new column containing a unique id. The below code uses the index of the data frame to create a new id column. data['id'] = data.index + 1 Next, we import featuretools and create the entity set. import featuretools as ftes = ft.EntitySet(id = 'data')es.entity_from_dataframe(entity_id = 'data', dataframe = data, index = 'id') This gives the following output. We can now use the library to perform feature synthesis. feature_matrix, feature_names = ft.dfs(entityset=es, target_entity = 'data', max_depth = 2, verbose = 1, n_jobs = 3) Featuretools has created 31 new features. We can view all the new features by running the following. feature_matrix.columns A machine learning model is only as good as the data that it is trained on. Therefore the steps discussed in this article of feature selection and engineering are some of the most important, and often time-consuming, parts of machine learning model development. This article has given a broad overview of the theory, tools and techniques in this field. However, this is an extremely broad area and requires a lot of practice with a variety of different data sets to really learn the art of finding the best features for machine learning. Thanks for reading! I send out a monthly newsletter if you would like to join please sign up via this link. Looking forward to being part of your learning journey!
[ { "code": null, "e": 502, "s": 172, "text": "A machine learning model maps a set of data inputs, known as features, to a predictor or target variable. The goal of this process is for the model to learn a pattern or mapping between these inputs and the target variable so that given new data, where the target is unknown, the model can accurately predict the target variable." }, { "code": null, "e": 748, "s": 502, "text": "For any given data set we want to develop a model that is able to predict with the highest degree of accuracy possible. In machine learning, there are many levers that impact the performance of the model. In general, these include the following:" }, { "code": null, "e": 770, "s": 748, "text": "The algorithm choice." }, { "code": null, "e": 808, "s": 770, "text": "The parameters used in the algorithm." }, { "code": null, "e": 850, "s": 808, "text": "The quantity and quality of the data set." }, { "code": null, "e": 888, "s": 850, "text": "The features used to train the model." }, { "code": null, "e": 1164, "s": 888, "text": "Often in a data set, the given set of features in their raw form do not provide enough, or the most optimal, information to train a performant model. In some instances, it may be beneficial to remove unnecessary or conflicting features and this is known as feature selection." }, { "code": null, "e": 1364, "s": 1164, "text": "In other cases model performance may be improved if we transform one or more features into a different representation to provide better information to the model, this is known as feature engineering." }, { "code": null, "e": 1628, "s": 1364, "text": "In many situations using all the features available in a data set will not result in the most predictive model. Depending on the type of model being used, the size of the data set and various other factors, including excess features, can reduce model performance." }, { "code": null, "e": 1677, "s": 1628, "text": "There are three main goals to feature selection." }, { "code": null, "e": 1752, "s": 1677, "text": "Improve the accuracy with which the model is able to predict for new data." }, { "code": null, "e": 1779, "s": 1752, "text": "Reduce computational cost." }, { "code": null, "e": 1815, "s": 1779, "text": "Produce a more interpretable model." }, { "code": null, "e": 2105, "s": 1815, "text": "There are a number of reasons why you may remove certain features over others. This includes the relationships that exist between features, wether a statistical relationship to the target variable exists or is significant enough, or the value of the information contained within a feature." }, { "code": null, "e": 2247, "s": 2105, "text": "Feature selection can be performed manually by analysis of the data set both pre and post-training, or through automated statistical methods." }, { "code": null, "e": 2354, "s": 2247, "text": "There are a number of reasons why you may want to remove a feature from the training phase. These include:" }, { "code": null, "e": 2568, "s": 2354, "text": "A feature that is highly correlated with another feature in the data set. If this is the case then both features are in essence providing the same information. Some algorithms are sensitive to correlated features." }, { "code": null, "e": 2687, "s": 2568, "text": "Features that provide little to no information. An example would be a feature where most examples have the same value." }, { "code": null, "e": 2770, "s": 2687, "text": "Features that have little to no statistical relationship with the target variable." }, { "code": null, "e": 2946, "s": 2770, "text": "Features can be selected through data analysis performed either before or after training a model. Here are a couple of common techniques to manually perform feature selection." }, { "code": null, "e": 2963, "s": 2946, "text": "Correlation plot" }, { "code": null, "e": 3286, "s": 2963, "text": "One manual technique to perform feature selection is to create a visualisation which plots the correlation measure for every feature in the data set. Seaborn is a good python library to use for this. The below code produces a correlation plot for features in the breast cancer data set available from the scikit-learn API." }, { "code": null, "e": 4108, "s": 3286, "text": "# library importsimport pandas as pdfrom sklearn.datasets import load_breast_cancerimport matplotlib.pyplot as plt%matplotlib inlineimport seaborn as snsimport numpy as np# load the breast_cancer data set from the scikit-learn apibreast_cancer = load_breast_cancer()data = pd.DataFrame(data=breast_cancer['data'], columns = breast_cancer['feature_names'])data['target'] = breast_cancer['target']data.head()# use the pands .corr() function to compute pairwise correlations for the dataframecorr = data.corr()# visualise the data with seabornmask = np.triu(np.ones_like(corr, dtype=np.bool))sns.set_style(style = 'white')f, ax = plt.subplots(figsize=(11, 9))cmap = sns.diverging_palette(10, 250, as_cmap=True)sns.heatmap(corr, mask=mask, cmap=cmap, square=True, linewidths=.5, cbar_kws={\"shrink\": .5}, ax=ax)" }, { "code": null, "e": 4359, "s": 4108, "text": "In the resulting visualisation, we can identify some features that are closely correlated and we may, therefore, want to remove some of these, and some features that have very low correlation with the target variable which we may also want to remove." }, { "code": null, "e": 4379, "s": 4359, "text": "Feature importances" }, { "code": null, "e": 4584, "s": 4379, "text": "Once we have trained a model it is possible to apply further statistical analysis to understand the effects features have on the output of the model and determine from this which features are most useful." }, { "code": null, "e": 4811, "s": 4584, "text": "There are a number of tools and techniques available to determine feature importance. Some techniques are unique to a specific algorithm, whereas others can be applied to a wide range of models and are known as model agnostic." }, { "code": null, "e": 5034, "s": 4811, "text": "To illustrate feature importances I will use the built-in feature importances method for a random forest classifier in scikit-learn. The code below fits the classifier and creates a plot displaying the feature importances." }, { "code": null, "e": 5873, "s": 5034, "text": "from sklearn.model_selection import train_test_splitfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import train_test_split# Spliiting data into test and train setsX_train, X_test, y_train, y_test = train_test_split(data.drop('target', axis=1), data['target'], test_size=0.20, random_state=0)# fitting the modelmodel = RandomForestClassifier(n_estimators=500, n_jobs=-1, random_state=42)model.fit(X_train, y_train)# plotting feature importancesfeatures = data.drop('target', axis=1).columnsimportances = model.feature_importances_indices = np.argsort(importances)plt.figure(figsize=(10,15))plt.title('Feature Importances')plt.barh(range(len(indices)), importances[indices], color='b', align='center')plt.yticks(range(len(indices)), [features[i] for i in indices])plt.xlabel('Relative Importance')plt.show()" }, { "code": null, "e": 6070, "s": 5873, "text": "This gives a good indicator of those features that are having an impact on the model and those that are not. We may choose to remove some of the less important features after analysing this chart." }, { "code": null, "e": 6327, "s": 6070, "text": "There are a number of mechanisms that use statistical methods to find the optimal set of features to use in a model automatically. The scikit-learn library contains a number of methods that provide a very simple implementation for many of these techniques." }, { "code": null, "e": 6346, "s": 6327, "text": "Variance threshold" }, { "code": null, "e": 6501, "s": 6346, "text": "In statistics, variance is the squared deviation of a variable from its mean, in other words, how far are the data points spread out for a given variable?" }, { "code": null, "e": 6856, "s": 6501, "text": "Suppose we were building a machine learning model to detect breast cancer and the data set had a boolean variable for gender. This data set is likely to consist almost entirely of one gender and therefore nearly all data points would be 1. This variable would have extremely low variance and would be not at all useful for predicting the target variable." }, { "code": null, "e": 7245, "s": 6856, "text": "This is one of the most simple approaches to feature selection. The scikit-learn library has a method called VarianceThreshold . This method takes a threshold value and when fitted to a feature set will remove any features below this threshold. The default value for the threshold is 0 and this will remove any features with zero variance, or in other words where all values are the same." }, { "code": null, "e": 7368, "s": 7245, "text": "Let’s apply this default setting to the breast cancer data set we used earlier to find out if any features are eliminated." }, { "code": null, "e": 7607, "s": 7368, "text": "from sklearn.feature_selection import VarianceThresholdX = data.drop('target', axis=1)selector = VarianceThreshold()print(\"Original feature shape:\", X.shape)new_X = selector.fit_transform(X)print(\"Transformed feature shape:\", new_X.shape)" }, { "code": null, "e": 7718, "s": 7607, "text": "The output shows that the transformed features are the same shape so all features have at least some variance." }, { "code": null, "e": 7747, "s": 7718, "text": "Univariate feature selection" }, { "code": null, "e": 8037, "s": 7747, "text": "Univariate feature selection applies univariate statistical tests to features and selects those which perform the best in these tests. Univariate tests are tests which involve only one dependent variable. This includes analysis of variance (ANOVA), linear regressions and t-tests of means." }, { "code": null, "e": 8202, "s": 8037, "text": "Again scikit-learn provides a number of feature selection methods that apply a variety of different univariate tests to find the best features for machine learning." }, { "code": null, "e": 8458, "s": 8202, "text": "We will apply one of these, known as SelectKBest to the breast cancer data set. This function selects the k best features based on a univariate statistical test. The default value of k is 10, so 10 features will be kept, and the default test is f_classif." }, { "code": null, "e": 8868, "s": 8458, "text": "The f_classif test is used for categorical targets as is the case for the breast cancer data set. If the target is a continuous variable f_regression should be used. The f_classif test is based on the Analysis of Variance (ANOVA) statistical test which compares the means of a number of groups, or in our case features, and determines whether any of those means are statistically significant from one another." }, { "code": null, "e": 8965, "s": 8868, "text": "The below code applies this function using the default parameters to the breast cancer data set." }, { "code": null, "e": 9213, "s": 8965, "text": "from sklearn.feature_selection import SelectKBestX = data.drop('target', axis=1)y = data['target']selector = SelectKBest()print(\"Original feature shape:\", X.shape)new_X = selector.fit_transform(X, y)print(\"Transformed feature shape:\", new_X.shape)" }, { "code": null, "e": 9400, "s": 9213, "text": "The output shows that the function has reduced the features to 10. We could experiment with different values of k, training multiple models, until we find the optimum number of features." }, { "code": null, "e": 9430, "s": 9400, "text": "Recursive feature elimination" }, { "code": null, "e": 9702, "s": 9430, "text": "This method performs model training on a gradually smaller and smaller set of features. Each time the feature importances or coefficients are calculated and the features with the lowest scores are removed. At the end of this process, the optimal set of features is known." }, { "code": null, "e": 9920, "s": 9702, "text": "As this method involves repeatably training a model we need to instantiate an estimator first. This method also works best if the data is first scaled so I have added a preprocessing step that normalizes the features." }, { "code": null, "e": 10271, "s": 9920, "text": "from sklearn.feature_selection import RFECVfrom sklearn.svm import SVRfrom sklearn import preprocessingX_normalized = preprocessing.normalize(X, norm='l2')y = yestimator = SVR(kernel=\"linear\")selector = RFECV(estimator, step=1, cv=2)selector = selector.fit(X, y)print(\"Features selected\", selector.support_)print(\"Feature ranking\", selector.ranking_)" }, { "code": null, "e": 10350, "s": 10271, "text": "The output below shows the features that have been selected and their ranking." }, { "code": null, "e": 10595, "s": 10350, "text": "Where the goal of feature selection is to reduce the dimensionality of a data set by removing unnecessary features, feature engineering is about transforming existing features and constructing new features to improve the performance of a model." }, { "code": null, "e": 10700, "s": 10595, "text": "There are three main reasons why we may need to perform feature engineering to develop an optimal model." }, { "code": null, "e": 11828, "s": 10700, "text": "Features cannot be used in their raw form. This includes features such as dates and times, where a machine learning model can only make use of the information contained within them if they are transformed into a numerical representation e.g. integer representation of the day of the week.Features can be used in their raw form but the information contained within the feature is stronger if the data is aggregated or represented in a different way. An example here might be a feature containing the age of a person, aggregating the ages into buckets or bins may better represent the relationship to the target.A feature on its own does not have a strong enough statistical relationship with the target but when combined with another feature has a meaningful relationship. Let’s say we have a data set that has a number of features based on credit history for a group of customers and a target that denotes if they have defaulted on a loan. Suppose we have a loan amount and a salary value. If we combined these into a new feature called “loan to salary ratio” this may give more or better information than those features alone." }, { "code": null, "e": 12117, "s": 11828, "text": "Features cannot be used in their raw form. This includes features such as dates and times, where a machine learning model can only make use of the information contained within them if they are transformed into a numerical representation e.g. integer representation of the day of the week." }, { "code": null, "e": 12440, "s": 12117, "text": "Features can be used in their raw form but the information contained within the feature is stronger if the data is aggregated or represented in a different way. An example here might be a feature containing the age of a person, aggregating the ages into buckets or bins may better represent the relationship to the target." }, { "code": null, "e": 12958, "s": 12440, "text": "A feature on its own does not have a strong enough statistical relationship with the target but when combined with another feature has a meaningful relationship. Let’s say we have a data set that has a number of features based on credit history for a group of customers and a target that denotes if they have defaulted on a loan. Suppose we have a loan amount and a salary value. If we combined these into a new feature called “loan to salary ratio” this may give more or better information than those features alone." }, { "code": null, "e": 13133, "s": 12958, "text": "Feature engineering can be performed through data analysis, intuition and domain knowledge. Often similar techniques to those used for manual feature selection are performed." }, { "code": null, "e": 13311, "s": 13133, "text": "For example, observing how features correlate to the target and how they perform in terms of feature importance indicates which features to explore further in terms of analysis." }, { "code": null, "e": 13737, "s": 13311, "text": "If we go back to the example of the loan data set, let's imagine we have an age variable which from a correlation plot appears to have some relationship to the target variable. We might find when we further analyse this relationship that those that default are skewed towards a particular age group. In this case, we might engineer a feature that picks out this age group and this may provide better information to the model." }, { "code": null, "e": 13998, "s": 13737, "text": "Manual feature engineering can be an extremely time-consuming process and requires a large amount of human intuition and domain knowledge to get right. There are tools available which have the ability to automatically synthesise a large number of new features." }, { "code": null, "e": 14235, "s": 13998, "text": "The Featuretools python library is an example of a tool that can perform automated feature engineering on a data set. Let’s install this library and walk through an example of automated feature engineering on the breast cancer data set." }, { "code": null, "e": 14274, "s": 14235, "text": "Featuretools can be installed via pip." }, { "code": null, "e": 14299, "s": 14274, "text": "pip install featuretools" }, { "code": null, "e": 14495, "s": 14299, "text": "Featuretools is designed to work with relational data sets (tables or dataframes that can be joined together with a unique identifier). The featuretools library refers to each table as an entity." }, { "code": null, "e": 14755, "s": 14495, "text": "The breast cancer data set consists of only one entity but we can still use featuretools to generate the features. However, we need to first create a new column containing a unique id. The below code uses the index of the data frame to create a new id column." }, { "code": null, "e": 14783, "s": 14755, "text": "data['id'] = data.index + 1" }, { "code": null, "e": 14839, "s": 14783, "text": "Next, we import featuretools and create the entity set." }, { "code": null, "e": 14971, "s": 14839, "text": "import featuretools as ftes = ft.EntitySet(id = 'data')es.entity_from_dataframe(entity_id = 'data', dataframe = data, index = 'id')" }, { "code": null, "e": 15004, "s": 14971, "text": "This gives the following output." }, { "code": null, "e": 15061, "s": 15004, "text": "We can now use the library to perform feature synthesis." }, { "code": null, "e": 15178, "s": 15061, "text": "feature_matrix, feature_names = ft.dfs(entityset=es, target_entity = 'data', max_depth = 2, verbose = 1, n_jobs = 3)" }, { "code": null, "e": 15220, "s": 15178, "text": "Featuretools has created 31 new features." }, { "code": null, "e": 15279, "s": 15220, "text": "We can view all the new features by running the following." }, { "code": null, "e": 15302, "s": 15279, "text": "feature_matrix.columns" }, { "code": null, "e": 15840, "s": 15302, "text": "A machine learning model is only as good as the data that it is trained on. Therefore the steps discussed in this article of feature selection and engineering are some of the most important, and often time-consuming, parts of machine learning model development. This article has given a broad overview of the theory, tools and techniques in this field. However, this is an extremely broad area and requires a lot of practice with a variety of different data sets to really learn the art of finding the best features for machine learning." }, { "code": null, "e": 15860, "s": 15840, "text": "Thanks for reading!" } ]
Difference between ASP and ASP.NET - GeeksforGeeks
02 Feb, 2022 ASP: ASP stands for Active Server Pages. It is a development framework used for building web pages. ASP was introduced in 1998 by Microsoft as its first server-side scripting language. The file extension of ASP pages are .asp and are normally written in VBScript. It is an old but still powerful tool for making dynamic web pages. ASP is a technology (much like PHP) for executing scripts on a web server.Example: html <!DOCTYPE html><html> <body> <%response.write("Welcome to GeeksforGeeks!")%></body> </html> Output: Welcome to GeeksforGeeks! ASP.NET: ASP.NET was released in 2002 by Microsoft as a successor to ASP. It is also a server-side web framework, open-source, which is designed for the generation of dynamic web pages. The file extension of ASP.NET pages is .aspx and is normally written in C# (C sharp). The latest version of ASP.NET is ASP.NET 4.6.Example: csharp @{ var rank = 50;}<html><body>@if (rank < 60){ <p>Welcome to GeeksforGeeks!</p>}</body></html> Output: Welcome to GeeksforGeeks! Difference between ASP and ASP.NET: itskawal2000 Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Roadmap to Become a Web Developer in 2022 How to fetch data from an API in ReactJS ? 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 create footer to stay at the bottom of a Web page? Node.js fs.readFileSync() Method How to set the default value for an HTML <select> element ? File uploading in React.js How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 24157, "s": 24129, "text": "\n02 Feb, 2022" }, { "code": null, "e": 24573, "s": 24157, "text": "ASP: ASP stands for Active Server Pages. It is a development framework used for building web pages. ASP was introduced in 1998 by Microsoft as its first server-side scripting language. The file extension of ASP pages are .asp and are normally written in VBScript. It is an old but still powerful tool for making dynamic web pages. ASP is a technology (much like PHP) for executing scripts on a web server.Example: " }, { "code": null, "e": 24578, "s": 24573, "text": "html" }, { "code": "<!DOCTYPE html><html> <body> <%response.write(\"Welcome to GeeksforGeeks!\")%></body> </html> ", "e": 24692, "s": 24578, "text": null }, { "code": null, "e": 24702, "s": 24692, "text": "Output: " }, { "code": null, "e": 24728, "s": 24702, "text": "Welcome to GeeksforGeeks!" }, { "code": null, "e": 25055, "s": 24728, "text": "ASP.NET: ASP.NET was released in 2002 by Microsoft as a successor to ASP. It is also a server-side web framework, open-source, which is designed for the generation of dynamic web pages. The file extension of ASP.NET pages is .aspx and is normally written in C# (C sharp). The latest version of ASP.NET is ASP.NET 4.6.Example: " }, { "code": null, "e": 25062, "s": 25055, "text": "csharp" }, { "code": "@{ var rank = 50;}<html><body>@if (rank < 60){ <p>Welcome to GeeksforGeeks!</p>}</body></html>", "e": 25163, "s": 25062, "text": null }, { "code": null, "e": 25173, "s": 25163, "text": "Output: " }, { "code": null, "e": 25199, "s": 25173, "text": "Welcome to GeeksforGeeks!" }, { "code": null, "e": 25237, "s": 25199, "text": "Difference between ASP and ASP.NET: " }, { "code": null, "e": 25252, "s": 25239, "text": "itskawal2000" }, { "code": null, "e": 25269, "s": 25252, "text": "Web Technologies" }, { "code": null, "e": 25367, "s": 25269, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25409, "s": 25367, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 25452, "s": 25409, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 25497, "s": 25452, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 25558, "s": 25497, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 25630, "s": 25558, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 25688, "s": 25630, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 25721, "s": 25688, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 25781, "s": 25721, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 25808, "s": 25781, "text": "File uploading in React.js" } ]
Matrix manipulation in Python
In Python we can solve the different matrix manipulations and operations. Numpy Module provides different methods for matrix operations. add() − add elements of two matrices. subtract() − subtract elements of two matrices. divide() − divide elements of two matrices. multiply() − multiply elements of two matrices. dot() − It performs matrix multiplication, does not element wise multiplication. sqrt() − square root of each element of matrix. sum(x,axis) − add to all the elements in matrix. Second argument is optional, it is used when we want to compute the column sum if axis is 0 and row sum if axis is 1. “T” − It performs transpose of the specified matrix. Live Demo import numpy # Two matrices are initialized by value x = numpy.array([[1, 2], [4, 5]]) y = numpy.array([[7, 8], [9, 10]]) # add()is used to add matrices print ("Addition of two matrices: ") print (numpy.add(x,y)) # subtract()is used to subtract matrices print ("Subtraction of two matrices : ") print (numpy.subtract(x,y)) # divide()is used to divide matrices print ("Matrix Division : ") print (numpy.divide(x,y)) print ("Multiplication of two matrices: ") print (numpy.multiply(x,y)) print ("The product of two matrices : ") print (numpy.dot(x,y)) print ("square root is : ") print (numpy.sqrt(x)) print ("The summation of elements : ") print (numpy.sum(y)) print ("The column wise summation : ") print (numpy.sum(y,axis=0)) print ("The row wise summation: ") print (numpy.sum(y,axis=1)) # using "T" to transpose the matrix print ("Matrix transposition : ") print (x.T) Addition of two matrices: [[ 8 10] [13 15]] Subtraction of two matrices : [[-6 -6] [-5 -5]] Matrix Division : [[0.14285714 0.25 ] [0.44444444 0.5 ]] Multiplication of two matrices: [[ 7 16] [36 50]] The product of two matrices : [[25 28] [73 82]] square root is : [[1. 1.41421356] [2. 2.23606798]] The summation of elements : 34 The column wise summation : [16 18] The row wise summation: [15 19] Matrix transposition : [[1 4] [2 5]]
[ { "code": null, "e": 1199, "s": 1062, "text": "In Python we can solve the different matrix manipulations and operations. Numpy Module provides different methods for matrix operations." }, { "code": null, "e": 1237, "s": 1199, "text": "add() − add elements of two matrices." }, { "code": null, "e": 1285, "s": 1237, "text": "subtract() − subtract elements of two matrices." }, { "code": null, "e": 1329, "s": 1285, "text": "divide() − divide elements of two matrices." }, { "code": null, "e": 1377, "s": 1329, "text": "multiply() − multiply elements of two matrices." }, { "code": null, "e": 1458, "s": 1377, "text": "dot() − It performs matrix multiplication, does not element wise multiplication." }, { "code": null, "e": 1507, "s": 1458, "text": "sqrt() − square root of each element of matrix." }, { "code": null, "e": 1674, "s": 1507, "text": "sum(x,axis) − add to all the elements in matrix. Second argument is optional, it is used when we want to compute the column sum if axis is 0 and row sum if axis is 1." }, { "code": null, "e": 1727, "s": 1674, "text": "“T” − It performs transpose of the specified matrix." }, { "code": null, "e": 1738, "s": 1727, "text": " Live Demo" }, { "code": null, "e": 2612, "s": 1738, "text": "import numpy\n# Two matrices are initialized by value\nx = numpy.array([[1, 2], [4, 5]])\ny = numpy.array([[7, 8], [9, 10]])\n# add()is used to add matrices\nprint (\"Addition of two matrices: \")\nprint (numpy.add(x,y))\n# subtract()is used to subtract matrices\nprint (\"Subtraction of two matrices : \")\nprint (numpy.subtract(x,y))\n# divide()is used to divide matrices\nprint (\"Matrix Division : \")\nprint (numpy.divide(x,y))\nprint (\"Multiplication of two matrices: \")\nprint (numpy.multiply(x,y))\nprint (\"The product of two matrices : \")\nprint (numpy.dot(x,y))\nprint (\"square root is : \")\nprint (numpy.sqrt(x))\nprint (\"The summation of elements : \")\nprint (numpy.sum(y))\nprint (\"The column wise summation : \")\nprint (numpy.sum(y,axis=0))\nprint (\"The row wise summation: \")\nprint (numpy.sum(y,axis=1))\n# using \"T\" to transpose the matrix\nprint (\"Matrix transposition : \")\nprint (x.T)" }, { "code": null, "e": 3084, "s": 2612, "text": "Addition of two matrices: \n[[ 8 10]\n [13 15]]\nSubtraction of two matrices :\n[[-6 -6]\n [-5 -5]]\nMatrix Division :\n[[0.14285714 0.25 ]\n [0.44444444 0.5 ]]\nMultiplication of two matrices: \n[[ 7 16]\n [36 50]]\nThe product of two matrices :\n[[25 28]\n [73 82]]\nsquare root is :\n[[1. 1.41421356]\n [2. 2.23606798]]\nThe summation of elements :\n34\nThe column wise summation :\n[16 18]\nThe row wise summation: \n[15 19]\nMatrix transposition :\n[[1 4]\n[2 5]]\n" } ]
Angular PrimeNG Dropdown Component - GeeksforGeeks
11 Sep, 2021 Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Dropdown component in Angular ngx Bootstrap. We will also learn about the various properties, events, methods & styling along with their syntaxes that will be used in the code example. Dropdown component: It is used to make to choose the objects from the given list of items. Properties: options: It is an array object representing select items to display as the available options. It is of array data type, the default value is null. optionLabel: It is used to give the name to a label of an option. It is of string data type, the default value is the label. optionValue: It is used to give the name to a value of an option, defaults to the option itself when not defined. It is of string data type, the default value is value. optionGroupLabel: It is used to give a name to a label in the option group. It is of string data type, the default value is the label. optionGroupChildren: It is used to give a name to the options field in the option group. It is of string data type, the default value is item. name: It is used to set the name of the input element. It is of string data type, the default value is null. scrollHeight: It is used to set the height of the viewport in pixels, a scrollbar is defined if the height of the list exceeds this value. It is of string data type, the default value is 200px. style: It is used to set an inline style of the element. It is of string data type, the default value is null. styleClass: It is used to set the style class of the element. It is of string data type, the default value is null. filter: It is used to display an input field to filter the items on keyup. It is of boolean data type, the default value is false. filterValue: It is a filter displayed with this value. It is of string data type, the default value is null. filterBy: It decides which field or fields (comma separated) to search against. It is of string data type, the default value is null. filterMatchMode: It is used to define how the items are filtered. It is of string data type, the default value is contains. filterPlaceholder: It is used to set the placeholder text to show when filter input is empty. It is of string data type, the default value is null. filterLocale: It is used to set the locale to use in filtering. The default locale is the host environment’s current locale. It is of string data type, the default value is undefined. required: It specifies that an input field must be filled out before submitting the form. It is of the boolean data type, the default value is false. disabled: It specifies that the component should be disabled. It is of the boolean data type, the default value is false. readonly: It specifies that the component cannot be edited. It is of the boolean data type, the default value is false. emptyMessage: It is used to set the text to display when there is no data. It is of string data type. emptyFilterMessage: It is used to set the text to display when filtering does not return any results. It is of string data type. ariaLabelledBy: It is the ariaLabelledBy property that establishes relationships between the component and label(s) where its value should be one or more element IDs. It is of string data type, the default value is null. editable: It is used to specify the custom value instead of predefined options that can be entered using the editable input field. It is of the boolean data type, the default value is false. maxlength: It is used to specify the maximum number of characters allowed in the editable input field, It is of number datatype, the default value is null. appendTo: This property takes the ID of the element on which overlay is appended to. It accepts any data type, the default value is null. tabindex: It is used to set the index of the element in tabbing order. It is of number datatype, the default value is null. inputId: It is an ID identifier of the underlying input element. It is of string data type, the default value is null. dataKey: It is a property to uniquely identify a value in options. It is of string data type, the default value is null. autofocus: it specifies that the component should automatically focus on load. It is of the boolean data type, the default value is false. autofocusFilter: It is used to apply focus to the filter element when the overlay is shown. It is of the boolean data type, the default value is false. resetFilterOnHide: It is used to clear the filter value when hiding the dropdown. It is of the boolean data type, the default value is false. dropdownIcon: It is used to set the icon class of the dropdown icon. It is of string data type, the default value is pi pi-chevron-down. emptyFilterMessage: It is used to set the text to display when filtering does not return any results. It is of string data type. autoDisplayFirst: It is used to specify whether to display the first item as the label if no placeholder is defined and the value is null. It is of the boolean data type, the default value is true. group: It is used to specify whether to display options as grouped when nested options are provided. It is of the boolean data type, the default value is false. showClear: It is used to show the clear icon which is displayed to clear the value. It is of boolean data type, the default value is false. baseZIndex: It is used to set the base zIndex value to use in the layering. It is of number datatype, the default value is 0. autoZIndex: It is used to specify whether to automatically manage the layering. It is of the boolean data type, the default value is true. showTransitionOptions: It is used to set the Transition options of the show animation. It is of string data type, the default value is .12s cubic-bezier(0, 0, 0.2, 1). hideTransitionOptions: It is used to set the transition options of the hide animation. It is of string data type, the default value is .1s linear. ariaFilterLabel: It is used to define a string that labels the filter input. It is of string data type, the default value is null. tooltip: It is used to show the advisory information to display in a tooltip on hover. It accepts any data type, the default value is null. tooltipStyleClass: It is used to set the Style class of the tooltip. It is of string data type, the default value is null. tooltipPosition: It is used to set the position of the tooltip, the valid values are right, left, top and bottom. It is of string data type, the default value is top. tooltipPositionStyle: It is used to set the type of CSS position. It is of string data type, the default value is absolute. Events: onClick: It is a callback that is fired when the component is clicked. onChange: It is a callback that is fired when the value of the dropdown changes. onFilter: It is a callback that is fired when data is filtered. onFocus: It is a callback that is fired when dropdown gets focus. onBlur: It is a callback that is fired when dropdown loses focus. onShow: It is a callback that is fired when the dropdown overlay gets visible. onHide: It is a callback that is fired when the dropdown overlay gets hidden. Methods: resetFilter: It is used to resets the filter. focus: It is used to apply the focus. show: It is used to displays the panel. hide: It is used to hides the panel. Styling: p-dropdown: It is a styling container element. p-dropdown-clearable: It is a styling container element when showClear is on. p-dropdown-label: It is a styling element to display the label of the selected option. p-dropdown-trigger: It is a styling icon element. p-dropdown-panel: It is a styling panel element. p-dropdown-items-wrapper: It is a styling wrapper element of the items list. p-dropdown-items: It is a styling list element of items. p-dropdown-item: It is a list item. p-dropdown-filter-container: It is a styling container of filter input. p-dropdown-filter: It is a styling filter element. p-dropdown-open: It is a styling container element when the overlay is visible. Creating Angular application & module installation: Step 1: Create an Angular application using the following command. ng new appname Step 2: After creating your project folder i.e. appname, move to it using the following command. cd appname Step 3: Install PrimeNG in your given directory. npm install primeng --save npm install primeicons --save Project Structure: It will look like the following: Example 1: This is the basic example that shows how to use the dropdown component. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG dropdowm component</h5><p-dropdown [options]="lang" placeholder="Select a Language" optionLabel="name" [showClear]="true"></p-dropdown> app.component.ts import { Component } from "@angular/core"; @Component({ selector: "my-app", templateUrl: "./app.component.html"})export class AppComponent { lang = [ { name: "HTML" }, { name: "ReactJS" }, { name: "Angular" }, { name: "Bootstrap" }, { name: "PrimeNG" }, ];} app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { FormsModule } from "@angular/forms";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { DropdownModule } from "primeng/dropdown"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, DropdownModule, FormsModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} Output: Example 2: In this example, we will know how to use editable property in the dropdown component. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG dropdowm component</h5><p-dropdown [options]='[{name: "Editable1"}, {name: "Editable2"}, {name: "Editable3"}, {name: "Editable4"}, {name: "Editable5"}]' editable="true" placeholder="Select a Language" optionLabel="name" [showClear]="true"></p-dropdown> app.component.ts import { Component } from "@angular/core"; @Component({ selector: "my-app", templateUrl: "./app.component.html", styleUrls: ["./app.component.scss"],})export class AppComponent { } app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { FormsModule } from "@angular/forms";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { DropdownModule } from "primeng/dropdown"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, DropdownModule, FormsModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} Output: Reference: https://primefaces.org/primeng/showcase/#/dropdown Angular-PrimeNG AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Auth Guards in Angular 9/10/11 Angular PrimeNG Calendar Component What is AOT and JIT Compiler in Angular ? Angular PrimeNG Messages Component How to set focus on input field automatically on page load in AngularJS ? 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": 25712, "s": 25684, "text": "\n11 Sep, 2021" }, { "code": null, "e": 26143, "s": 25712, "text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Dropdown component in Angular ngx Bootstrap. We will also learn about the various properties, events, methods & styling along with their syntaxes that will be used in the code example. " }, { "code": null, "e": 26235, "s": 26143, "text": "Dropdown component: It is used to make to choose the objects from the given list of items. " }, { "code": null, "e": 26247, "s": 26235, "text": "Properties:" }, { "code": null, "e": 26394, "s": 26247, "text": "options: It is an array object representing select items to display as the available options. It is of array data type, the default value is null." }, { "code": null, "e": 26519, "s": 26394, "text": "optionLabel: It is used to give the name to a label of an option. It is of string data type, the default value is the label." }, { "code": null, "e": 26688, "s": 26519, "text": "optionValue: It is used to give the name to a value of an option, defaults to the option itself when not defined. It is of string data type, the default value is value." }, { "code": null, "e": 26823, "s": 26688, "text": "optionGroupLabel: It is used to give a name to a label in the option group. It is of string data type, the default value is the label." }, { "code": null, "e": 26966, "s": 26823, "text": "optionGroupChildren: It is used to give a name to the options field in the option group. It is of string data type, the default value is item." }, { "code": null, "e": 27075, "s": 26966, "text": "name: It is used to set the name of the input element. It is of string data type, the default value is null." }, { "code": null, "e": 27269, "s": 27075, "text": "scrollHeight: It is used to set the height of the viewport in pixels, a scrollbar is defined if the height of the list exceeds this value. It is of string data type, the default value is 200px." }, { "code": null, "e": 27380, "s": 27269, "text": "style: It is used to set an inline style of the element. It is of string data type, the default value is null." }, { "code": null, "e": 27497, "s": 27380, "text": "styleClass: It is used to set the style class of the element. It is of string data type, the default value is null." }, { "code": null, "e": 27628, "s": 27497, "text": "filter: It is used to display an input field to filter the items on keyup. It is of boolean data type, the default value is false." }, { "code": null, "e": 27737, "s": 27628, "text": "filterValue: It is a filter displayed with this value. It is of string data type, the default value is null." }, { "code": null, "e": 27871, "s": 27737, "text": "filterBy: It decides which field or fields (comma separated) to search against. It is of string data type, the default value is null." }, { "code": null, "e": 27995, "s": 27871, "text": "filterMatchMode: It is used to define how the items are filtered. It is of string data type, the default value is contains." }, { "code": null, "e": 28143, "s": 27995, "text": "filterPlaceholder: It is used to set the placeholder text to show when filter input is empty. It is of string data type, the default value is null." }, { "code": null, "e": 28327, "s": 28143, "text": "filterLocale: It is used to set the locale to use in filtering. The default locale is the host environment’s current locale. It is of string data type, the default value is undefined." }, { "code": null, "e": 28477, "s": 28327, "text": "required: It specifies that an input field must be filled out before submitting the form. It is of the boolean data type, the default value is false." }, { "code": null, "e": 28599, "s": 28477, "text": "disabled: It specifies that the component should be disabled. It is of the boolean data type, the default value is false." }, { "code": null, "e": 28719, "s": 28599, "text": "readonly: It specifies that the component cannot be edited. It is of the boolean data type, the default value is false." }, { "code": null, "e": 28821, "s": 28719, "text": "emptyMessage: It is used to set the text to display when there is no data. It is of string data type." }, { "code": null, "e": 28950, "s": 28821, "text": "emptyFilterMessage: It is used to set the text to display when filtering does not return any results. It is of string data type." }, { "code": null, "e": 29171, "s": 28950, "text": "ariaLabelledBy: It is the ariaLabelledBy property that establishes relationships between the component and label(s) where its value should be one or more element IDs. It is of string data type, the default value is null." }, { "code": null, "e": 29362, "s": 29171, "text": "editable: It is used to specify the custom value instead of predefined options that can be entered using the editable input field. It is of the boolean data type, the default value is false." }, { "code": null, "e": 29518, "s": 29362, "text": "maxlength: It is used to specify the maximum number of characters allowed in the editable input field, It is of number datatype, the default value is null." }, { "code": null, "e": 29656, "s": 29518, "text": "appendTo: This property takes the ID of the element on which overlay is appended to. It accepts any data type, the default value is null." }, { "code": null, "e": 29780, "s": 29656, "text": "tabindex: It is used to set the index of the element in tabbing order. It is of number datatype, the default value is null." }, { "code": null, "e": 29900, "s": 29780, "text": "inputId: It is an ID identifier of the underlying input element. It is of string data type, the default value is null." }, { "code": null, "e": 30021, "s": 29900, "text": "dataKey: It is a property to uniquely identify a value in options. It is of string data type, the default value is null." }, { "code": null, "e": 30160, "s": 30021, "text": "autofocus: it specifies that the component should automatically focus on load. It is of the boolean data type, the default value is false." }, { "code": null, "e": 30312, "s": 30160, "text": "autofocusFilter: It is used to apply focus to the filter element when the overlay is shown. It is of the boolean data type, the default value is false." }, { "code": null, "e": 30454, "s": 30312, "text": "resetFilterOnHide: It is used to clear the filter value when hiding the dropdown. It is of the boolean data type, the default value is false." }, { "code": null, "e": 30591, "s": 30454, "text": "dropdownIcon: It is used to set the icon class of the dropdown icon. It is of string data type, the default value is pi pi-chevron-down." }, { "code": null, "e": 30720, "s": 30591, "text": "emptyFilterMessage: It is used to set the text to display when filtering does not return any results. It is of string data type." }, { "code": null, "e": 30918, "s": 30720, "text": "autoDisplayFirst: It is used to specify whether to display the first item as the label if no placeholder is defined and the value is null. It is of the boolean data type, the default value is true." }, { "code": null, "e": 31079, "s": 30918, "text": "group: It is used to specify whether to display options as grouped when nested options are provided. It is of the boolean data type, the default value is false." }, { "code": null, "e": 31219, "s": 31079, "text": "showClear: It is used to show the clear icon which is displayed to clear the value. It is of boolean data type, the default value is false." }, { "code": null, "e": 31345, "s": 31219, "text": "baseZIndex: It is used to set the base zIndex value to use in the layering. It is of number datatype, the default value is 0." }, { "code": null, "e": 31484, "s": 31345, "text": "autoZIndex: It is used to specify whether to automatically manage the layering. It is of the boolean data type, the default value is true." }, { "code": null, "e": 31652, "s": 31484, "text": "showTransitionOptions: It is used to set the Transition options of the show animation. It is of string data type, the default value is .12s cubic-bezier(0, 0, 0.2, 1)." }, { "code": null, "e": 31799, "s": 31652, "text": "hideTransitionOptions: It is used to set the transition options of the hide animation. It is of string data type, the default value is .1s linear." }, { "code": null, "e": 31930, "s": 31799, "text": "ariaFilterLabel: It is used to define a string that labels the filter input. It is of string data type, the default value is null." }, { "code": null, "e": 32070, "s": 31930, "text": "tooltip: It is used to show the advisory information to display in a tooltip on hover. It accepts any data type, the default value is null." }, { "code": null, "e": 32193, "s": 32070, "text": "tooltipStyleClass: It is used to set the Style class of the tooltip. It is of string data type, the default value is null." }, { "code": null, "e": 32360, "s": 32193, "text": "tooltipPosition: It is used to set the position of the tooltip, the valid values are right, left, top and bottom. It is of string data type, the default value is top." }, { "code": null, "e": 32484, "s": 32360, "text": "tooltipPositionStyle: It is used to set the type of CSS position. It is of string data type, the default value is absolute." }, { "code": null, "e": 32492, "s": 32484, "text": "Events:" }, { "code": null, "e": 32563, "s": 32492, "text": "onClick: It is a callback that is fired when the component is clicked." }, { "code": null, "e": 32644, "s": 32563, "text": "onChange: It is a callback that is fired when the value of the dropdown changes." }, { "code": null, "e": 32708, "s": 32644, "text": "onFilter: It is a callback that is fired when data is filtered." }, { "code": null, "e": 32774, "s": 32708, "text": "onFocus: It is a callback that is fired when dropdown gets focus." }, { "code": null, "e": 32840, "s": 32774, "text": "onBlur: It is a callback that is fired when dropdown loses focus." }, { "code": null, "e": 32919, "s": 32840, "text": "onShow: It is a callback that is fired when the dropdown overlay gets visible." }, { "code": null, "e": 32997, "s": 32919, "text": "onHide: It is a callback that is fired when the dropdown overlay gets hidden." }, { "code": null, "e": 33008, "s": 32999, "text": "Methods:" }, { "code": null, "e": 33054, "s": 33008, "text": "resetFilter: It is used to resets the filter." }, { "code": null, "e": 33092, "s": 33054, "text": "focus: It is used to apply the focus." }, { "code": null, "e": 33132, "s": 33092, "text": "show: It is used to displays the panel." }, { "code": null, "e": 33169, "s": 33132, "text": "hide: It is used to hides the panel." }, { "code": null, "e": 33178, "s": 33169, "text": "Styling:" }, { "code": null, "e": 33225, "s": 33178, "text": "p-dropdown: It is a styling container element." }, { "code": null, "e": 33303, "s": 33225, "text": "p-dropdown-clearable: It is a styling container element when showClear is on." }, { "code": null, "e": 33390, "s": 33303, "text": "p-dropdown-label: It is a styling element to display the label of the selected option." }, { "code": null, "e": 33440, "s": 33390, "text": "p-dropdown-trigger: It is a styling icon element." }, { "code": null, "e": 33489, "s": 33440, "text": "p-dropdown-panel: It is a styling panel element." }, { "code": null, "e": 33566, "s": 33489, "text": "p-dropdown-items-wrapper: It is a styling wrapper element of the items list." }, { "code": null, "e": 33623, "s": 33566, "text": "p-dropdown-items: It is a styling list element of items." }, { "code": null, "e": 33659, "s": 33623, "text": "p-dropdown-item: It is a list item." }, { "code": null, "e": 33731, "s": 33659, "text": "p-dropdown-filter-container: It is a styling container of filter input." }, { "code": null, "e": 33782, "s": 33731, "text": "p-dropdown-filter: It is a styling filter element." }, { "code": null, "e": 33862, "s": 33782, "text": "p-dropdown-open: It is a styling container element when the overlay is visible." }, { "code": null, "e": 33915, "s": 33862, "text": "Creating Angular application & module installation:" }, { "code": null, "e": 33982, "s": 33915, "text": "Step 1: Create an Angular application using the following command." }, { "code": null, "e": 33997, "s": 33982, "text": "ng new appname" }, { "code": null, "e": 34094, "s": 33997, "text": "Step 2: After creating your project folder i.e. appname, move to it using the following command." }, { "code": null, "e": 34105, "s": 34094, "text": "cd appname" }, { "code": null, "e": 34154, "s": 34105, "text": "Step 3: Install PrimeNG in your given directory." }, { "code": null, "e": 34211, "s": 34154, "text": "npm install primeng --save\nnpm install primeicons --save" }, { "code": null, "e": 34263, "s": 34211, "text": "Project Structure: It will look like the following:" }, { "code": null, "e": 34346, "s": 34263, "text": "Example 1: This is the basic example that shows how to use the dropdown component." }, { "code": null, "e": 34365, "s": 34346, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG dropdowm component</h5><p-dropdown [options]=\"lang\" placeholder=\"Select a Language\" optionLabel=\"name\" [showClear]=\"true\"></p-dropdown>", "e": 34539, "s": 34365, "text": null }, { "code": null, "e": 34558, "s": 34541, "text": "app.component.ts" }, { "code": "import { Component } from \"@angular/core\"; @Component({ selector: \"my-app\", templateUrl: \"./app.component.html\"})export class AppComponent { lang = [ { name: \"HTML\" }, { name: \"ReactJS\" }, { name: \"Angular\" }, { name: \"Bootstrap\" }, { name: \"PrimeNG\" }, ];}", "e": 34836, "s": 34558, "text": null }, { "code": null, "e": 34850, "s": 34836, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { FormsModule } from \"@angular/forms\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { DropdownModule } from \"primeng/dropdown\"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, DropdownModule, FormsModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 35373, "s": 34850, "text": null }, { "code": null, "e": 35381, "s": 35373, "text": "Output:" }, { "code": null, "e": 35479, "s": 35381, "text": "Example 2: In this example, we will know how to use editable property in the dropdown component. " }, { "code": null, "e": 35498, "s": 35479, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG dropdowm component</h5><p-dropdown [options]='[{name: \"Editable1\"}, {name: \"Editable2\"}, {name: \"Editable3\"}, {name: \"Editable4\"}, {name: \"Editable5\"}]' editable=\"true\" placeholder=\"Select a Language\" optionLabel=\"name\" [showClear]=\"true\"></p-dropdown>", "e": 35816, "s": 35498, "text": null }, { "code": null, "e": 35833, "s": 35816, "text": "app.component.ts" }, { "code": "import { Component } from \"@angular/core\"; @Component({ selector: \"my-app\", templateUrl: \"./app.component.html\", styleUrls: [\"./app.component.scss\"],})export class AppComponent { }", "e": 36019, "s": 35833, "text": null }, { "code": null, "e": 36033, "s": 36019, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { FormsModule } from \"@angular/forms\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { DropdownModule } from \"primeng/dropdown\"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, DropdownModule, FormsModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 36556, "s": 36033, "text": null }, { "code": null, "e": 36564, "s": 36556, "text": "Output:" }, { "code": null, "e": 36626, "s": 36564, "text": "Reference: https://primefaces.org/primeng/showcase/#/dropdown" }, { "code": null, "e": 36642, "s": 36626, "text": "Angular-PrimeNG" }, { "code": null, "e": 36652, "s": 36642, "text": "AngularJS" }, { "code": null, "e": 36669, "s": 36652, "text": "Web Technologies" }, { "code": null, "e": 36767, "s": 36669, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36798, "s": 36767, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 36833, "s": 36798, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 36875, "s": 36833, "text": "What is AOT and JIT Compiler in Angular ?" }, { "code": null, "e": 36910, "s": 36875, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 36984, "s": 36910, "text": "How to set focus on input field automatically on page load in AngularJS ?" }, { "code": null, "e": 37024, "s": 36984, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 37057, "s": 37024, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 37102, "s": 37057, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 37145, "s": 37102, "text": "How to fetch data from an API in ReactJS ?" } ]
Maximum and minimum of an array using minimum number of comparisons - GeeksforGeeks
09 Apr, 2022 Write a C function to return minimum and maximum in an array. Your program should make the minimum number of comparisons. First of all, how do we return multiple values from a C function? We can do it either using structures or pointers. We have created a structure named pair (which contains min and max) to return multiple values. c Java C# struct pair { int min; int max; }; static class pair { int min; int max; }; // This code contributed by Rajput-Ji public static class pair { public int min; public int max; }; // This code contributed by Rajput-Ji And the function declaration becomes: struct pair getMinMax(int arr[], int n) where arr[] is the array of size n whose minimum and maximum are needed. METHOD 1 (Simple Linear Search) Initialize values of min and max as minimum and maximum of the first two elements respectively. Starting from 3rd, compare each element with max and min, and change max and min accordingly (i.e., if the element is smaller than min then change min, else if the element is greater than max then change max, else ignore the element) C++ C Java Python3 C# Javascript // C++ program of above implementation #include<iostream> using namespace std; // Pair struct is used to return // two values from getMinMax() struct Pair { int min; int max; }; Pair getMinMax(int arr[], int n) { struct Pair minmax; int i; // If there is only one element // then return it as min and max both if (n == 1) { minmax.max = arr[0]; minmax.min = arr[0]; return minmax; } // If there are more than one elements, // then initialize min and max if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.max = arr[1]; minmax.min = arr[0]; } for(i = 2; i < n; i++) { if (arr[i] > minmax.max) minmax.max = arr[i]; else if (arr[i] < minmax.min) minmax.min = arr[i]; } return minmax; } // Driver code int main() { int arr[] = { 1000, 11, 445, 1, 330, 3000 }; int arr_size = 6; struct Pair minmax = getMinMax(arr, arr_size); cout << "Minimum element is " << minmax.min << endl; cout << "Maximum element is " << minmax.max; return 0; } // This code is contributed by nik_3112 /* structure is used to return two values from minMax() */ #include<stdio.h> struct pair { int min; int max; }; struct pair getMinMax(int arr[], int n) { struct pair minmax; int i; /*If there is only one element then return it as min and max both*/ if (n == 1) { minmax.max = arr[0]; minmax.min = arr[0]; return minmax; } /* If there are more than one elements, then initialize min and max*/ if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.max = arr[1]; minmax.min = arr[0]; } for (i = 2; i<n; i++) { if (arr[i] > minmax.max) minmax.max = arr[i]; else if (arr[i] < minmax.min) minmax.min = arr[i]; } return minmax; } /* Driver program to test above function */ int main() { int arr[] = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; struct pair minmax = getMinMax (arr, arr_size); printf("nMinimum element is %d", minmax.min); printf("nMaximum element is %d", minmax.max); getchar(); } // Java program of above implementation public class GFG { /* Class Pair is used to return two values from getMinMax() */ static class Pair { int min; int max; } static Pair getMinMax(int arr[], int n) { Pair minmax = new Pair(); int i; /*If there is only one element then return it as min and max both*/ if (n == 1) { minmax.max = arr[0]; minmax.min = arr[0]; return minmax; } /* If there are more than one elements, then initialize min and max*/ if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.max = arr[1]; minmax.min = arr[0]; } for (i = 2; i < n; i++) { if (arr[i] > minmax.max) { minmax.max = arr[i]; } else if (arr[i] < minmax.min) { minmax.min = arr[i]; } } return minmax; } /* Driver program to test above function */ public static void main(String args[]) { int arr[] = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; Pair minmax = getMinMax(arr, arr_size); System.out.printf("\nMinimum element is %d", minmax.min); System.out.printf("\nMaximum element is %d", minmax.max); } } # Python program of above implementation # structure is used to return two values from minMax() class pair: def __init__(self): self.min = 0 self.max = 0 def getMinMax(arr: list, n: int) -> pair: minmax = pair() # If there is only one element then return it as min and max both if n == 1: minmax.max = arr[0] minmax.min = arr[0] return minmax # If there are more than one elements, then initialize min # and max if arr[0] > arr[1]: minmax.max = arr[0] minmax.min = arr[1] else: minmax.max = arr[1] minmax.min = arr[0] for i in range(2, n): if arr[i] > minmax.max: minmax.max = arr[i] elif arr[i] < minmax.min: minmax.min = arr[i] return minmax # Driver Code if __name__ == "__main__": arr = [1000, 11, 445, 1, 330, 3000] arr_size = 6 minmax = getMinMax(arr, arr_size) print("Minimum element is", minmax.min) print("Maximum element is", minmax.max) # This code is contributed by # sanjeev2552 // C# program of above implementation using System; class GFG { /* Class Pair is used to return two values from getMinMax() */ class Pair { public int min; public int max; } static Pair getMinMax(int []arr, int n) { Pair minmax = new Pair(); int i; /* If there is only one element then return it as min and max both*/ if (n == 1) { minmax.max = arr[0]; minmax.min = arr[0]; return minmax; } /* If there are more than one elements, then initialize min and max*/ if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.max = arr[1]; minmax.min = arr[0]; } for (i = 2; i < n; i++) { if (arr[i] > minmax.max) { minmax.max = arr[i]; } else if (arr[i] < minmax.min) { minmax.min = arr[i]; } } return minmax; } // Driver Code public static void Main(String []args) { int []arr = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; Pair minmax = getMinMax(arr, arr_size); Console.Write("Minimum element is {0}", minmax.min); Console.Write("\nMaximum element is {0}", minmax.max); } } // This code is contributed by PrinciRaj1992 <script> // JavaScript program of above implementation /* Class Pair is used to return two values from getMinMax() */ function getMinMax(arr, n) { minmax = new Array(); var i; var min; var max; /*If there is only one element then return it as min and max both*/ if (n == 1) { minmax.max = arr[0]; minmax.min = arr[0]; return minmax; } /* If there are more than one elements, then initialize min and max*/ if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.max = arr[1]; minmax.min = arr[0]; } for (i = 2; i < n; i++) { if (arr[i] > minmax.max) { minmax.max = arr[i]; } else if (arr[i] < minmax.min) { minmax.min = arr[i]; } } return minmax; } /* Driver program to test above function */ var arr = [1000, 11, 445, 1, 330, 3000]; var arr_size = 6; minmax = getMinMax(arr, arr_size); document.write("\nMinimum element is " ,minmax.min +"<br>"); document.write("\nMaximum element is " , minmax.max); // This code is contributed by shivanisinghss2110 </script> Output: Minimum element is 1 Maximum element is 3000 Time Complexity: O(n) Auxiliary Space: O(1) as no extra space was needed. In this method, the total number of comparisons is 1 + 2(n-2) in the worst case and 1 + n – 2 in the best case. In the above implementation, the worst case occurs when elements are sorted in descending order and the best case occurs when elements are sorted in ascending order. METHOD 2 (Tournament Method) Divide the array into two parts and compare the maximums and minimums of the two parts to get the maximum and the minimum of the whole array. Pair MaxMin(array, array_size) if array_size = 1 return element as both max and min else if arry_size = 2 one comparison to determine max and min return that pair else /* array_size > 2 */ recur for max and min of left half recur for max and min of right half one comparison determines true max of the two candidates one comparison determines true min of the two candidates return the pair of max and min Implementation C++ C Java Python3 C# Javascript // C++ program of above implementation #include<iostream> using namespace std; // structure is used to return // two values from minMax() struct Pair { int min; int max; }; struct Pair getMinMax(int arr[], int low, int high) { struct Pair minmax, mml, mmr; int mid; // If there is only one element if (low == high) { minmax.max = arr[low]; minmax.min = arr[low]; return minmax; } // If there are two elements if (high == low + 1) { if (arr[low] > arr[high]) { minmax.max = arr[low]; minmax.min = arr[high]; } else { minmax.max = arr[high]; minmax.min = arr[low]; } return minmax; } // If there are more than 2 elements mid = (low + high) / 2; mml = getMinMax(arr, low, mid); mmr = getMinMax(arr, mid + 1, high); // Compare minimums of two parts if (mml.min < mmr.min) minmax.min = mml.min; else minmax.min = mmr.min; // Compare maximums of two parts if (mml.max > mmr.max) minmax.max = mml.max; else minmax.max = mmr.max; return minmax; } // Driver code int main() { int arr[] = { 1000, 11, 445, 1, 330, 3000 }; int arr_size = 6; struct Pair minmax = getMinMax(arr, 0, arr_size - 1); cout << "Minimum element is " << minmax.min << endl; cout << "Maximum element is " << minmax.max; return 0; } // This code is contributed by nik_3112 /* structure is used to return two values from minMax() */ #include<stdio.h> struct pair { int min; int max; }; struct pair getMinMax(int arr[], int low, int high) { struct pair minmax, mml, mmr; int mid; // If there is only one element if (low == high) { minmax.max = arr[low]; minmax.min = arr[low]; return minmax; } /* If there are two elements */ if (high == low + 1) { if (arr[low] > arr[high]) { minmax.max = arr[low]; minmax.min = arr[high]; } else { minmax.max = arr[high]; minmax.min = arr[low]; } return minmax; } /* If there are more than 2 elements */ mid = (low + high)/2; mml = getMinMax(arr, low, mid); mmr = getMinMax(arr, mid+1, high); /* compare minimums of two parts*/ if (mml.min < mmr.min) minmax.min = mml.min; else minmax.min = mmr.min; /* compare maximums of two parts*/ if (mml.max > mmr.max) minmax.max = mml.max; else minmax.max = mmr.max; return minmax; } /* Driver program to test above function */ int main() { int arr[] = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; struct pair minmax = getMinMax(arr, 0, arr_size-1); printf("nMinimum element is %d", minmax.min); printf("nMaximum element is %d", minmax.max); getchar(); } // Java program of above implementation public class GFG { /* Class Pair is used to return two values from getMinMax() */ static class Pair { int min; int max; } static Pair getMinMax(int arr[], int low, int high) { Pair minmax = new Pair(); Pair mml = new Pair(); Pair mmr = new Pair(); int mid; // If there is only one element if (low == high) { minmax.max = arr[low]; minmax.min = arr[low]; return minmax; } /* If there are two elements */ if (high == low + 1) { if (arr[low] > arr[high]) { minmax.max = arr[low]; minmax.min = arr[high]; } else { minmax.max = arr[high]; minmax.min = arr[low]; } return minmax; } /* If there are more than 2 elements */ mid = (low + high) / 2; mml = getMinMax(arr, low, mid); mmr = getMinMax(arr, mid + 1, high); /* compare minimums of two parts*/ if (mml.min < mmr.min) { minmax.min = mml.min; } else { minmax.min = mmr.min; } /* compare maximums of two parts*/ if (mml.max > mmr.max) { minmax.max = mml.max; } else { minmax.max = mmr.max; } return minmax; } /* Driver program to test above function */ public static void main(String args[]) { int arr[] = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; Pair minmax = getMinMax(arr, 0, arr_size - 1); System.out.printf("\nMinimum element is %d", minmax.min); System.out.printf("\nMaximum element is %d", minmax.max); } } # Python program of above implementation def getMinMax(low, high, arr): arr_max = arr[low] arr_min = arr[low] # If there is only one element if low == high: arr_max = arr[low] arr_min = arr[low] return (arr_max, arr_min) # If there is only two element elif high == low + 1: if arr[low] > arr[high]: arr_max = arr[low] arr_min = arr[high] else: arr_max = arr[high] arr_min = arr[low] return (arr_max, arr_min) else: # If there are more than 2 elements mid = int((low + high) / 2) arr_max1, arr_min1 = getMinMax(low, mid, arr) arr_max2, arr_min2 = getMinMax(mid + 1, high, arr) return (max(arr_max1, arr_max2), min(arr_min1, arr_min2)) # Driver code arr = [1000, 11, 445, 1, 330, 3000] high = len(arr) - 1 low = 0 arr_max, arr_min = getMinMax(low, high, arr) print('Minimum element is ', arr_min) print('nMaximum element is ', arr_max) # This code is contributed by DeepakChhitarka // C# implementation of the approach using System; public class GFG { /* Class Pair is used to return two values from getMinMax() */ public class Pair { public int min; public int max; } static Pair getMinMax(int []arr, int low, int high) { Pair minmax = new Pair(); Pair mml = new Pair(); Pair mmr = new Pair(); int mid; // If there is only one element if (low == high) { minmax.max = arr[low]; minmax.min = arr[low]; return minmax; } /* If there are two elements */ if (high == low + 1) { if (arr[low] > arr[high]) { minmax.max = arr[low]; minmax.min = arr[high]; } else { minmax.max = arr[high]; minmax.min = arr[low]; } return minmax; } /* If there are more than 2 elements */ mid = (low + high) / 2; mml = getMinMax(arr, low, mid); mmr = getMinMax(arr, mid + 1, high); /* compare minimums of two parts*/ if (mml.min < mmr.min) { minmax.min = mml.min; } else { minmax.min = mmr.min; } /* compare maximums of two parts*/ if (mml.max > mmr.max) { minmax.max = mml.max; } else { minmax.max = mmr.max; } return minmax; } /* Driver program to test above function */ public static void Main(String []args) { int []arr = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; Pair minmax = getMinMax(arr, 0, arr_size - 1); Console.Write("\nMinimum element is {0}", minmax.min); Console.Write("\nMaximum element is {0}", minmax.max); } } // This code contributed by Rajput-Ji <script> // Javascript program of above implementation /* Class Pair is used to return two values from getMinMax() */ class Pair { constructor(){ this.min = -1; this.max = 10000000; } } function getMinMax(arr , low , high) { var minmax = new Pair(); var mml = new Pair(); var mmr = new Pair(); var mid; // If there is only one element if (low == high) { minmax.max = arr[low]; minmax.min = arr[low]; return minmax; } /* If there are two elements */ if (high == low + 1) { if (arr[low] > arr[high]) { minmax.max = arr[low]; minmax.min = arr[high]; } else { minmax.max = arr[high]; minmax.min = arr[low]; } return minmax; } /* If there are more than 2 elements */ mid = parseInt((low + high) / 2); mml = getMinMax(arr, low, mid); mmr = getMinMax(arr, mid + 1, high); /* compare minimums of two parts */ if (mml.min < mmr.min) { minmax.min = mml.min; } else { minmax.min = mmr.min; } /* compare maximums of two parts */ if (mml.max > mmr.max) { minmax.max = mml.max; } else { minmax.max = mmr.max; } return minmax; } /* Driver program to test above function */ var arr = [ 1000, 11, 445, 1, 330, 3000 ]; var arr_size = 6; var minmax = getMinMax(arr, 0, arr_size - 1); document.write("\nMinimum element is ", minmax.min); document.write("<br/>Maximum element is ", minmax.max); // This code is contributed by Rajput-Ji </script> Output: Minimum element is 1 Maximum element is 3000 Time Complexity: O(n) Auxiliary Space: O(log n) as the stack space will be filled for the maximum height of the tree formed during recursive calls same as a binary tree. Total number of comparisons: let the number of comparisons be T(n). T(n) can be written as follows: Algorithmic Paradigm: Divide and Conquer T(n) = T(floor(n/2)) + T(ceil(n/2)) + 2 T(2) = 1 T(1) = 0 If n is a power of 2, then we can write T(n) as: T(n) = 2T(n/2) + 2 After solving the above recursion, we get T(n) = 3n/2 -2 Thus, the approach does 3n/2 -2 comparisons if n is a power of 2. And it does more than 3n/2 -2 comparisons if n is not a power of 2. METHOD 3 (Compare in Pairs) If n is odd then initialize min and max as first element. If n is even then initialize min and max as minimum and maximum of the first two elements respectively. For rest of the elements, pick them in pairs and compare their maximum and minimum with max and min respectively. C++ C Java Python3 C# // C++ program of above implementation #include<iostream> using namespace std; // Structure is used to return // two values from minMax() struct Pair { int min; int max; }; struct Pair getMinMax(int arr[], int n) { struct Pair minmax; int i; // If array has even number of elements // then initialize the first two elements // as minimum and maximum if (n % 2 == 0) { if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.min = arr[0]; minmax.max = arr[1]; } // Set the starting index for loop i = 2; } // If array has odd number of elements // then initialize the first element as // minimum and maximum else { minmax.min = arr[0]; minmax.max = arr[0]; // Set the starting index for loop i = 1; } // In the while loop, pick elements in // pair and compare the pair with max // and min so far while (i < n - 1) { if (arr[i] > arr[i + 1]) { if(arr[i] > minmax.max) minmax.max = arr[i]; if(arr[i + 1] < minmax.min) minmax.min = arr[i + 1]; } else { if (arr[i + 1] > minmax.max) minmax.max = arr[i + 1]; if (arr[i] < minmax.min) minmax.min = arr[i]; } // Increment the index by 2 as // two elements are processed in loop i += 2; } return minmax; } // Driver code int main() { int arr[] = { 1000, 11, 445, 1, 330, 3000 }; int arr_size = 6; Pair minmax = getMinMax(arr, arr_size); cout << "nMinimum element is " << minmax.min << endl; cout << "nMaximum element is " << minmax.max; return 0; } // This code is contributed by nik_3112 #include<stdio.h> /* structure is used to return two values from minMax() */ struct pair { int min; int max; }; struct pair getMinMax(int arr[], int n) { struct pair minmax; int i; /* If array has even number of elements then initialize the first two elements as minimum and maximum */ if (n%2 == 0) { if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.min = arr[0]; minmax.max = arr[1]; } i = 2; /* set the starting index for loop */ } /* If array has odd number of elements then initialize the first element as minimum and maximum */ else { minmax.min = arr[0]; minmax.max = arr[0]; i = 1; /* set the starting index for loop */ } /* In the while loop, pick elements in pair and compare the pair with max and min so far */ while (i < n-1) { if (arr[i] > arr[i+1]) { if(arr[i] > minmax.max) minmax.max = arr[i]; if(arr[i+1] < minmax.min) minmax.min = arr[i+1]; } else { if (arr[i+1] > minmax.max) minmax.max = arr[i+1]; if (arr[i] < minmax.min) minmax.min = arr[i]; } i += 2; /* Increment the index by 2 as two elements are processed in loop */ } return minmax; } /* Driver program to test above function */ int main() { int arr[] = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; struct pair minmax = getMinMax (arr, arr_size); printf("nMinimum element is %d", minmax.min); printf("nMaximum element is %d", minmax.max); getchar(); } // Java program of above implementation public class GFG { /* Class Pair is used to return two values from getMinMax() */ static class Pair { int min; int max; } static Pair getMinMax(int arr[], int n) { Pair minmax = new Pair(); int i; /* If array has even number of elements then initialize the first two elements as minimum and maximum */ if (n % 2 == 0) { if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.min = arr[0]; minmax.max = arr[1]; } i = 2; /* set the starting index for loop */ } /* If array has odd number of elements then initialize the first element as minimum and maximum */ else { minmax.min = arr[0]; minmax.max = arr[0]; i = 1; /* set the starting index for loop */ } /* In the while loop, pick elements in pair and compare the pair with max and min so far */ while (i < n - 1) { if (arr[i] > arr[i + 1]) { if (arr[i] > minmax.max) { minmax.max = arr[i]; } if (arr[i + 1] < minmax.min) { minmax.min = arr[i + 1]; } } else { if (arr[i + 1] > minmax.max) { minmax.max = arr[i + 1]; } if (arr[i] < minmax.min) { minmax.min = arr[i]; } } i += 2; /* Increment the index by 2 as two elements are processed in loop */ } return minmax; } /* Driver program to test above function */ public static void main(String args[]) { int arr[] = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; Pair minmax = getMinMax(arr, arr_size); System.out.printf("\nMinimum element is %d", minmax.min); System.out.printf("\nMaximum element is %d", minmax.max); } } # Python3 program of above implementation def getMinMax(arr): n = len(arr) # If array has even number of elements then # initialize the first two elements as minimum # and maximum if(n % 2 == 0): mx = max(arr[0], arr[1]) mn = min(arr[0], arr[1]) # set the starting index for loop i = 2 # If array has odd number of elements then # initialize the first element as minimum # and maximum else: mx = mn = arr[0] # set the starting index for loop i = 1 # In the while loop, pick elements in pair and # compare the pair with max and min so far while(i < n - 1): if arr[i] < arr[i + 1]: mx = max(mx, arr[i + 1]) mn = min(mn, arr[i]) else: mx = max(mx, arr[i]) mn = min(mn, arr[i + 1]) # Increment the index by 2 as two # elements are processed in loop i += 2 return (mx, mn) # Driver Code if __name__ =='__main__': arr = [1000, 11, 445, 1, 330, 3000] mx, mn = getMinMax(arr) print("Minimum element is", mn) print("Maximum element is", mx) # This code is contributed by Kaustav // C# program of above implementation using System; class GFG { /* Class Pair is used to return two values from getMinMax() */ public class Pair { public int min; public int max; } static Pair getMinMax(int []arr, int n) { Pair minmax = new Pair(); int i; /* If array has even number of elements then initialize the first two elements as minimum and maximum */ if (n % 2 == 0) { if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.min = arr[0]; minmax.max = arr[1]; } i = 2; } /* set the starting index for loop */ /* If array has odd number of elements then initialize the first element as minimum and maximum */ else { minmax.min = arr[0]; minmax.max = arr[0]; i = 1; /* set the starting index for loop */ } /* In the while loop, pick elements in pair and compare the pair with max and min so far */ while (i < n - 1) { if (arr[i] > arr[i + 1]) { if (arr[i] > minmax.max) { minmax.max = arr[i]; } if (arr[i + 1] < minmax.min) { minmax.min = arr[i + 1]; } } else { if (arr[i + 1] > minmax.max) { minmax.max = arr[i + 1]; } if (arr[i] < minmax.min) { minmax.min = arr[i]; } } i += 2; /* Increment the index by 2 as two elements are processed in loop */ } return minmax; } // Driver Code public static void Main(String []args) { int []arr = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; Pair minmax = getMinMax(arr, arr_size); Console.Write("Minimum element is {0}", minmax.min); Console.Write("\nMaximum element is {0}", minmax.max); } } // This code is contributed by 29AjayKumar Output: Minimum element is 1 Maximum element is 3000 Time Complexity: O(n) Auxiliary Space: O(1) as no extra space was needed. Total number of comparisons: Different for even and odd n, see below: If n is odd: 3*(n-1)/2 If n is even: 1 Initial comparison for initializing min and max, and 3(n-2)/2 comparisons for rest of the elements = 1 + 3*(n-2)/2 = 3n/2 -2 Second and third approaches make the equal number of comparisons when n is a power of 2. In general, method 3 seems to be the best.Please write comments if you find any bug in the above programs/algorithms or a better way to solve the same problem. kamleshbhalui Rajput-Ji Kaustav kumar Chanda Akanksha_Rai princiraj1992 29AjayKumar sanjeev2552 DeepakChhitarka nik_3112 maafkaroplz anjalitejasvi501 anshulpurohit11 dhairyabahl5 shivanisinghss2110 abhishekolympics prophet1999 Numbers Arrays Divide and Conquer Searching Arrays Searching Divide and Conquer Numbers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Arrays in Java Arrays in C/C++ Program for array rotation Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Merge Sort QuickSort Binary Search Program for Tower of Hanoi Divide and Conquer Algorithm | Introduction
[ { "code": null, "e": 31904, "s": 31873, "text": " \n09 Apr, 2022\n" }, { "code": null, "e": 32027, "s": 31904, "text": "Write a C function to return minimum and maximum in an array. Your program should make the minimum number of comparisons. " }, { "code": null, "e": 32239, "s": 32027, "text": "First of all, how do we return multiple values from a C function? We can do it either using structures or pointers. We have created a structure named pair (which contains min and max) to return multiple values. " }, { "code": null, "e": 32241, "s": 32239, "text": "c" }, { "code": null, "e": 32246, "s": 32241, "text": "Java" }, { "code": null, "e": 32249, "s": 32246, "text": "C#" }, { "code": "\n\n\n\n\n\n\nstruct pair \n{\n int min;\n int max;\n}; \n\n\n\n\n\n", "e": 32314, "s": 32259, "text": null }, { "code": "\n\n\n\n\n\n\nstatic class pair \n{\n int min;\n int max;\n};\n \n// This code contributed by Rajput-Ji \n\n\n\n\n\n", "e": 32424, "s": 32324, "text": null }, { "code": "\n\n\n\n\n\n\npublic static class pair {\n public int min;\n public int max;\n};\n// This code contributed by Rajput-Ji \n\n\n\n\n\n", "e": 32556, "s": 32434, "text": null }, { "code": null, "e": 32708, "s": 32556, "text": "And the function declaration becomes: struct pair getMinMax(int arr[], int n) where arr[] is the array of size n whose minimum and maximum are needed. " }, { "code": null, "e": 33071, "s": 32708, "text": "METHOD 1 (Simple Linear Search) Initialize values of min and max as minimum and maximum of the first two elements respectively. Starting from 3rd, compare each element with max and min, and change max and min accordingly (i.e., if the element is smaller than min then change min, else if the element is greater than max then change max, else ignore the element) " }, { "code": null, "e": 33075, "s": 33071, "text": "C++" }, { "code": null, "e": 33077, "s": 33075, "text": "C" }, { "code": null, "e": 33082, "s": 33077, "text": "Java" }, { "code": null, "e": 33090, "s": 33082, "text": "Python3" }, { "code": null, "e": 33093, "s": 33090, "text": "C#" }, { "code": null, "e": 33104, "s": 33093, "text": "Javascript" }, { "code": "\n\n\n\n\n\n\n// C++ program of above implementation \n#include<iostream>\nusing namespace std;\n \n// Pair struct is used to return \n// two values from getMinMax()\nstruct Pair \n{\n int min;\n int max;\n}; \n \nPair getMinMax(int arr[], int n)\n{\n struct Pair minmax; \n int i;\n \n // If there is only one element \n // then return it as min and max both\n if (n == 1)\n {\n minmax.max = arr[0];\n minmax.min = arr[0]; \n return minmax;\n } \n \n // If there are more than one elements,\n // then initialize min and max\n if (arr[0] > arr[1]) \n {\n minmax.max = arr[0];\n minmax.min = arr[1];\n } \n else\n {\n minmax.max = arr[1];\n minmax.min = arr[0];\n } \n \n for(i = 2; i < n; i++)\n {\n if (arr[i] > minmax.max) \n minmax.max = arr[i];\n \n else if (arr[i] < minmax.min) \n minmax.min = arr[i];\n }\n return minmax;\n}\n \n// Driver code\nint main()\n{\n int arr[] = { 1000, 11, 445, \n 1, 330, 3000 };\n int arr_size = 6;\n \n struct Pair minmax = getMinMax(arr, arr_size);\n \n cout << \"Minimum element is \"\n << minmax.min << endl;\n cout << \"Maximum element is \"\n << minmax.max;\n \n return 0;\n} \n \n// This code is contributed by nik_3112\n\n\n\n\n\n", "e": 34462, "s": 33114, "text": null }, { "code": "\n\n\n\n\n\n\n/* structure is used to return two values from minMax() */\n#include<stdio.h>\nstruct pair \n{\n int min;\n int max;\n}; \n \nstruct pair getMinMax(int arr[], int n)\n{\n struct pair minmax; \n int i;\n \n /*If there is only one element then return it as min and max both*/\n if (n == 1)\n {\n minmax.max = arr[0];\n minmax.min = arr[0]; \n return minmax;\n } \n \n /* If there are more than one elements, then initialize min \n and max*/\n if (arr[0] > arr[1]) \n {\n minmax.max = arr[0];\n minmax.min = arr[1];\n } \n else\n {\n minmax.max = arr[1];\n minmax.min = arr[0];\n } \n \n for (i = 2; i<n; i++)\n {\n if (arr[i] > minmax.max) \n minmax.max = arr[i];\n \n else if (arr[i] < minmax.min) \n minmax.min = arr[i];\n }\n \n return minmax;\n}\n \n/* Driver program to test above function */\nint main()\n{\n int arr[] = {1000, 11, 445, 1, 330, 3000};\n int arr_size = 6;\n struct pair minmax = getMinMax (arr, arr_size);\n printf(\"nMinimum element is %d\", minmax.min);\n printf(\"nMaximum element is %d\", minmax.max);\n getchar();\n} \n\n\n\n\n\n", "e": 35583, "s": 34472, "text": null }, { "code": "\n\n\n\n\n\n\n// Java program of above implementation\npublic class GFG {\n/* Class Pair is used to return two values from getMinMax() */\n static class Pair {\n \n int min;\n int max;\n }\n \n static Pair getMinMax(int arr[], int n) {\n Pair minmax = new Pair();\n int i;\n \n /*If there is only one element then return it as min and max both*/\n if (n == 1) {\n minmax.max = arr[0];\n minmax.min = arr[0];\n return minmax;\n }\n \n /* If there are more than one elements, then initialize min \n and max*/\n if (arr[0] > arr[1]) {\n minmax.max = arr[0];\n minmax.min = arr[1];\n } else {\n minmax.max = arr[1];\n minmax.min = arr[0];\n }\n \n for (i = 2; i < n; i++) {\n if (arr[i] > minmax.max) {\n minmax.max = arr[i];\n } else if (arr[i] < minmax.min) {\n minmax.min = arr[i];\n }\n }\n \n return minmax;\n }\n \n /* Driver program to test above function */\n public static void main(String args[]) {\n int arr[] = {1000, 11, 445, 1, 330, 3000};\n int arr_size = 6;\n Pair minmax = getMinMax(arr, arr_size);\n System.out.printf(\"\\nMinimum element is %d\", minmax.min);\n System.out.printf(\"\\nMaximum element is %d\", minmax.max);\n \n }\n \n}\n\n\n\n\n\n", "e": 36984, "s": 35593, "text": null }, { "code": "\n\n\n\n\n\n\n# Python program of above implementation\n \n# structure is used to return two values from minMax()\n \nclass pair:\n def __init__(self):\n self.min = 0\n self.max = 0\n \ndef getMinMax(arr: list, n: int) -> pair:\n minmax = pair()\n \n # If there is only one element then return it as min and max both\n if n == 1:\n minmax.max = arr[0]\n minmax.min = arr[0]\n return minmax\n \n # If there are more than one elements, then initialize min\n # and max\n if arr[0] > arr[1]:\n minmax.max = arr[0]\n minmax.min = arr[1]\n else:\n minmax.max = arr[1]\n minmax.min = arr[0]\n \n for i in range(2, n):\n if arr[i] > minmax.max:\n minmax.max = arr[i]\n elif arr[i] < minmax.min:\n minmax.min = arr[i]\n \n return minmax\n \n# Driver Code\nif __name__ == \"__main__\":\n arr = [1000, 11, 445, 1, 330, 3000]\n arr_size = 6\n minmax = getMinMax(arr, arr_size)\n print(\"Minimum element is\", minmax.min)\n print(\"Maximum element is\", minmax.max)\n \n# This code is contributed by\n# sanjeev2552\n\n\n\n\n\n", "e": 38089, "s": 36994, "text": null }, { "code": "\n\n\n\n\n\n\n// C# program of above implementation\nusing System;\n \nclass GFG \n{\n /* Class Pair is used to return \n two values from getMinMax() */\n class Pair \n {\n public int min;\n public int max;\n }\n \n static Pair getMinMax(int []arr, int n)\n {\n Pair minmax = new Pair();\n int i;\n \n /* If there is only one element \n then return it as min and max both*/\n if (n == 1)\n {\n minmax.max = arr[0];\n minmax.min = arr[0];\n return minmax;\n }\n \n /* If there are more than one elements,\n then initialize min and max*/\n if (arr[0] > arr[1])\n {\n minmax.max = arr[0];\n minmax.min = arr[1];\n } \n else\n {\n minmax.max = arr[1];\n minmax.min = arr[0];\n }\n \n for (i = 2; i < n; i++)\n {\n if (arr[i] > minmax.max) \n {\n minmax.max = arr[i];\n } \n else if (arr[i] < minmax.min)\n {\n minmax.min = arr[i];\n }\n }\n return minmax;\n }\n \n // Driver Code\n public static void Main(String []args) \n {\n int []arr = {1000, 11, 445, 1, 330, 3000};\n int arr_size = 6;\n Pair minmax = getMinMax(arr, arr_size);\n Console.Write(\"Minimum element is {0}\",\n minmax.min);\n Console.Write(\"\\nMaximum element is {0}\", \n minmax.max);\n }\n}\n \n// This code is contributed by PrinciRaj1992\n\n\n\n\n\n", "e": 39694, "s": 38099, "text": null }, { "code": "\n\n\n\n\n\n\n<script>\n// JavaScript program of above implementation\n \n/* Class Pair is used to return two values from getMinMax() */\n function getMinMax(arr, n)\n {\n minmax = new Array();\n var i;\n var min;\n var max;\n \n /*If there is only one element then return it as min and max both*/\n if (n == 1) {\n minmax.max = arr[0];\n minmax.min = arr[0];\n return minmax;\n }\n \n /* If there are more than one elements, then initialize min \n and max*/\n if (arr[0] > arr[1]) {\n minmax.max = arr[0];\n minmax.min = arr[1];\n } else {\n minmax.max = arr[1];\n minmax.min = arr[0];\n }\n \n for (i = 2; i < n; i++) {\n if (arr[i] > minmax.max) {\n minmax.max = arr[i];\n } else if (arr[i] < minmax.min) {\n minmax.min = arr[i];\n }\n }\n \n return minmax;\n }\n \n /* Driver program to test above function */\n \n var arr = [1000, 11, 445, 1, 330, 3000];\n var arr_size = 6;\n minmax = getMinMax(arr, arr_size);\n document.write(\"\\nMinimum element is \" ,minmax.min +\"<br>\");\n document.write(\"\\nMaximum element is \" , minmax.max);\n \n// This code is contributed by shivanisinghss2110\n</script>\n\n\n\n\n\n", "e": 41049, "s": 39704, "text": null }, { "code": null, "e": 41058, "s": 41049, "text": "Output: " }, { "code": null, "e": 41103, "s": 41058, "text": "Minimum element is 1\nMaximum element is 3000" }, { "code": null, "e": 41125, "s": 41103, "text": "Time Complexity: O(n)" }, { "code": null, "e": 41177, "s": 41125, "text": "Auxiliary Space: O(1) as no extra space was needed." }, { "code": null, "e": 41455, "s": 41177, "text": "In this method, the total number of comparisons is 1 + 2(n-2) in the worst case and 1 + n – 2 in the best case. In the above implementation, the worst case occurs when elements are sorted in descending order and the best case occurs when elements are sorted in ascending order." }, { "code": null, "e": 41626, "s": 41455, "text": "METHOD 2 (Tournament Method) Divide the array into two parts and compare the maximums and minimums of the two parts to get the maximum and the minimum of the whole array." }, { "code": null, "e": 42092, "s": 41626, "text": "Pair MaxMin(array, array_size)\n if array_size = 1\n return element as both max and min\n else if arry_size = 2\n one comparison to determine max and min\n return that pair\n else /* array_size > 2 */\n recur for max and min of left half\n recur for max and min of right half\n one comparison determines true max of the two candidates\n one comparison determines true min of the two candidates\n return the pair of max and min" }, { "code": null, "e": 42108, "s": 42092, "text": "Implementation " }, { "code": null, "e": 42112, "s": 42108, "text": "C++" }, { "code": null, "e": 42114, "s": 42112, "text": "C" }, { "code": null, "e": 42119, "s": 42114, "text": "Java" }, { "code": null, "e": 42127, "s": 42119, "text": "Python3" }, { "code": null, "e": 42130, "s": 42127, "text": "C#" }, { "code": null, "e": 42141, "s": 42130, "text": "Javascript" }, { "code": "\n\n\n\n\n\n\n// C++ program of above implementation \n#include<iostream>\nusing namespace std;\n \n// structure is used to return \n// two values from minMax() \nstruct Pair \n{\n int min;\n int max;\n}; \n \nstruct Pair getMinMax(int arr[], int low,\n int high)\n{\n struct Pair minmax, mml, mmr; \n int mid;\n \n // If there is only one element \n if (low == high)\n {\n minmax.max = arr[low];\n minmax.min = arr[low]; \n return minmax;\n } \n \n // If there are two elements \n if (high == low + 1)\n { \n if (arr[low] > arr[high]) \n {\n minmax.max = arr[low];\n minmax.min = arr[high];\n } \n else\n {\n minmax.max = arr[high];\n minmax.min = arr[low];\n } \n return minmax;\n }\n \n // If there are more than 2 elements \n mid = (low + high) / 2; \n mml = getMinMax(arr, low, mid);\n mmr = getMinMax(arr, mid + 1, high); \n \n // Compare minimums of two parts\n if (mml.min < mmr.min)\n minmax.min = mml.min;\n else\n minmax.min = mmr.min; \n \n // Compare maximums of two parts\n if (mml.max > mmr.max)\n minmax.max = mml.max;\n else\n minmax.max = mmr.max; \n \n return minmax;\n}\n \n// Driver code\nint main()\n{\n int arr[] = { 1000, 11, 445,\n 1, 330, 3000 };\n int arr_size = 6;\n \n struct Pair minmax = getMinMax(arr, 0, \n arr_size - 1);\n \n cout << \"Minimum element is \"\n << minmax.min << endl;\n cout << \"Maximum element is \"\n << minmax.max;\n \n return 0;\n}\n \n// This code is contributed by nik_3112\n\n\n\n\n\n", "e": 43900, "s": 42151, "text": null }, { "code": "\n\n\n\n\n\n\n/* structure is used to return two values from minMax() */\n#include<stdio.h>\nstruct pair \n{\n int min;\n int max;\n}; \n \nstruct pair getMinMax(int arr[], int low, int high)\n{\n struct pair minmax, mml, mmr; \n int mid;\n \n // If there is only one element \n if (low == high)\n {\n minmax.max = arr[low];\n minmax.min = arr[low]; \n return minmax;\n } \n \n /* If there are two elements */\n if (high == low + 1)\n { \n if (arr[low] > arr[high]) \n {\n minmax.max = arr[low];\n minmax.min = arr[high];\n } \n else\n {\n minmax.max = arr[high];\n minmax.min = arr[low];\n } \n return minmax;\n }\n \n /* If there are more than 2 elements */\n mid = (low + high)/2; \n mml = getMinMax(arr, low, mid);\n mmr = getMinMax(arr, mid+1, high); \n \n /* compare minimums of two parts*/\n if (mml.min < mmr.min)\n minmax.min = mml.min;\n else\n minmax.min = mmr.min; \n \n /* compare maximums of two parts*/\n if (mml.max > mmr.max)\n minmax.max = mml.max;\n else\n minmax.max = mmr.max; \n \n return minmax;\n}\n \n/* Driver program to test above function */\nint main()\n{\n int arr[] = {1000, 11, 445, 1, 330, 3000};\n int arr_size = 6;\n struct pair minmax = getMinMax(arr, 0, arr_size-1);\n printf(\"nMinimum element is %d\", minmax.min);\n printf(\"nMaximum element is %d\", minmax.max);\n getchar();\n}\n\n\n\n\n\n", "e": 45305, "s": 43910, "text": null }, { "code": "\n\n\n\n\n\n\n// Java program of above implementation\npublic class GFG {\n/* Class Pair is used to return two values from getMinMax() */\n static class Pair {\n \n int min;\n int max;\n }\n \n static Pair getMinMax(int arr[], int low, int high) {\n Pair minmax = new Pair();\n Pair mml = new Pair();\n Pair mmr = new Pair();\n int mid;\n \n // If there is only one element \n if (low == high) {\n minmax.max = arr[low];\n minmax.min = arr[low];\n return minmax;\n }\n \n /* If there are two elements */\n if (high == low + 1) {\n if (arr[low] > arr[high]) {\n minmax.max = arr[low];\n minmax.min = arr[high];\n } else {\n minmax.max = arr[high];\n minmax.min = arr[low];\n }\n return minmax;\n }\n \n /* If there are more than 2 elements */\n mid = (low + high) / 2;\n mml = getMinMax(arr, low, mid);\n mmr = getMinMax(arr, mid + 1, high);\n \n /* compare minimums of two parts*/\n if (mml.min < mmr.min) {\n minmax.min = mml.min;\n } else {\n minmax.min = mmr.min;\n }\n \n /* compare maximums of two parts*/\n if (mml.max > mmr.max) {\n minmax.max = mml.max;\n } else {\n minmax.max = mmr.max;\n }\n \n return minmax;\n }\n \n /* Driver program to test above function */\n public static void main(String args[]) {\n int arr[] = {1000, 11, 445, 1, 330, 3000};\n int arr_size = 6;\n Pair minmax = getMinMax(arr, 0, arr_size - 1);\n System.out.printf(\"\\nMinimum element is %d\", minmax.min);\n System.out.printf(\"\\nMaximum element is %d\", minmax.max);\n \n }\n}\n\n\n\n\n\n", "e": 47122, "s": 45315, "text": null }, { "code": "\n\n\n\n\n\n\n# Python program of above implementation\ndef getMinMax(low, high, arr):\n arr_max = arr[low]\n arr_min = arr[low]\n \n # If there is only one element \n if low == high:\n arr_max = arr[low]\n arr_min = arr[low]\n return (arr_max, arr_min)\n \n # If there is only two element\n elif high == low + 1:\n if arr[low] > arr[high]:\n arr_max = arr[low]\n arr_min = arr[high]\n else:\n arr_max = arr[high]\n arr_min = arr[low]\n return (arr_max, arr_min)\n else:\n \n # If there are more than 2 elements\n mid = int((low + high) / 2)\n arr_max1, arr_min1 = getMinMax(low, mid, arr)\n arr_max2, arr_min2 = getMinMax(mid + 1, high, arr)\n \n return (max(arr_max1, arr_max2), min(arr_min1, arr_min2))\n \n# Driver code\narr = [1000, 11, 445, 1, 330, 3000]\nhigh = len(arr) - 1\nlow = 0\narr_max, arr_min = getMinMax(low, high, arr)\nprint('Minimum element is ', arr_min)\nprint('nMaximum element is ', arr_max)\n \n# This code is contributed by DeepakChhitarka\n\n\n\n\n\n", "e": 48218, "s": 47132, "text": null }, { "code": "\n\n\n\n\n\n\n// C# implementation of the approach\nusing System;\n \npublic class GFG {\n/* Class Pair is used to return two values from getMinMax() */\n public class Pair {\n \n public int min;\n public int max;\n }\n \n static Pair getMinMax(int []arr, int low, int high) {\n Pair minmax = new Pair();\n Pair mml = new Pair();\n Pair mmr = new Pair();\n int mid;\n \n // If there is only one element \n if (low == high) {\n minmax.max = arr[low];\n minmax.min = arr[low];\n return minmax;\n }\n \n /* If there are two elements */\n if (high == low + 1) {\n if (arr[low] > arr[high]) {\n minmax.max = arr[low];\n minmax.min = arr[high];\n } else {\n minmax.max = arr[high];\n minmax.min = arr[low];\n }\n return minmax;\n }\n \n /* If there are more than 2 elements */\n mid = (low + high) / 2;\n mml = getMinMax(arr, low, mid);\n mmr = getMinMax(arr, mid + 1, high);\n \n /* compare minimums of two parts*/\n if (mml.min < mmr.min) {\n minmax.min = mml.min;\n } else {\n minmax.min = mmr.min;\n }\n \n /* compare maximums of two parts*/\n if (mml.max > mmr.max) {\n minmax.max = mml.max;\n } else {\n minmax.max = mmr.max;\n }\n \n return minmax;\n }\n \n /* Driver program to test above function */\n public static void Main(String []args) {\n int []arr = {1000, 11, 445, 1, 330, 3000};\n int arr_size = 6;\n Pair minmax = getMinMax(arr, 0, arr_size - 1);\n Console.Write(\"\\nMinimum element is {0}\", minmax.min);\n Console.Write(\"\\nMaximum element is {0}\", minmax.max);\n \n }\n}\n \n// This code contributed by Rajput-Ji\n\n\n\n\n\n", "e": 50126, "s": 48228, "text": null }, { "code": "\n\n\n\n\n\n\n<script>\n// Javascript program of above implementation\n \n /* Class Pair is used to return two values from getMinMax() */\n class Pair {\n constructor(){\n this.min = -1;\n this.max = 10000000;\n }\n }\n \n function getMinMax(arr , low , high) {\n var minmax = new Pair();\n var mml = new Pair();\n var mmr = new Pair();\n var mid;\n \n // If there is only one element\n if (low == high) {\n minmax.max = arr[low];\n minmax.min = arr[low];\n return minmax;\n }\n \n /* If there are two elements */\n if (high == low + 1) {\n if (arr[low] > arr[high]) {\n minmax.max = arr[low];\n minmax.min = arr[high];\n } else {\n minmax.max = arr[high];\n minmax.min = arr[low];\n }\n return minmax;\n }\n \n /* If there are more than 2 elements */\n mid = parseInt((low + high) / 2);\n mml = getMinMax(arr, low, mid);\n mmr = getMinMax(arr, mid + 1, high);\n \n /* compare minimums of two parts */\n if (mml.min < mmr.min) {\n minmax.min = mml.min;\n } else {\n minmax.min = mmr.min;\n }\n \n /* compare maximums of two parts */\n if (mml.max > mmr.max) {\n minmax.max = mml.max;\n } else {\n minmax.max = mmr.max;\n }\n \n return minmax;\n }\n \n /* Driver program to test above function */\n var arr = [ 1000, 11, 445, 1, 330, 3000 ];\n var arr_size = 6;\n var minmax = getMinMax(arr, 0, arr_size - 1);\n document.write(\"\\nMinimum element is \", minmax.min);\n document.write(\"<br/>Maximum element is \", minmax.max);\n \n// This code is contributed by Rajput-Ji \n</script>\n\n\n\n\n\n", "e": 51976, "s": 50136, "text": null }, { "code": null, "e": 51985, "s": 51976, "text": "Output: " }, { "code": null, "e": 52030, "s": 51985, "text": "Minimum element is 1\nMaximum element is 3000" }, { "code": null, "e": 52052, "s": 52030, "text": "Time Complexity: O(n)" }, { "code": null, "e": 52200, "s": 52052, "text": "Auxiliary Space: O(log n) as the stack space will be filled for the maximum height of the tree formed during recursive calls same as a binary tree." }, { "code": null, "e": 52342, "s": 52200, "text": "Total number of comparisons: let the number of comparisons be T(n). T(n) can be written as follows: Algorithmic Paradigm: Divide and Conquer " }, { "code": null, "e": 52422, "s": 52342, "text": " \n T(n) = T(floor(n/2)) + T(ceil(n/2)) + 2 \n T(2) = 1\n T(1) = 0" }, { "code": null, "e": 52472, "s": 52422, "text": "If n is a power of 2, then we can write T(n) as: " }, { "code": null, "e": 52494, "s": 52472, "text": " T(n) = 2T(n/2) + 2" }, { "code": null, "e": 52537, "s": 52494, "text": "After solving the above recursion, we get " }, { "code": null, "e": 52555, "s": 52537, "text": " T(n) = 3n/2 -2" }, { "code": null, "e": 52689, "s": 52555, "text": "Thus, the approach does 3n/2 -2 comparisons if n is a power of 2. And it does more than 3n/2 -2 comparisons if n is not a power of 2." }, { "code": null, "e": 52994, "s": 52689, "text": "METHOD 3 (Compare in Pairs) If n is odd then initialize min and max as first element. If n is even then initialize min and max as minimum and maximum of the first two elements respectively. For rest of the elements, pick them in pairs and compare their maximum and minimum with max and min respectively. " }, { "code": null, "e": 52998, "s": 52994, "text": "C++" }, { "code": null, "e": 53000, "s": 52998, "text": "C" }, { "code": null, "e": 53005, "s": 53000, "text": "Java" }, { "code": null, "e": 53013, "s": 53005, "text": "Python3" }, { "code": null, "e": 53016, "s": 53013, "text": "C#" }, { "code": "\n\n\n\n\n\n\n// C++ program of above implementation \n#include<iostream> \nusing namespace std; \n \n// Structure is used to return \n// two values from minMax() \nstruct Pair \n{ \n int min; \n int max; \n}; \n \nstruct Pair getMinMax(int arr[], int n) \n{ \n struct Pair minmax; \n int i; \n \n // If array has even number of elements \n // then initialize the first two elements \n // as minimum and maximum \n if (n % 2 == 0) \n { \n if (arr[0] > arr[1]) \n { \n minmax.max = arr[0]; \n minmax.min = arr[1]; \n } \n else\n { \n minmax.min = arr[0]; \n minmax.max = arr[1]; \n } \n \n // Set the starting index for loop \n i = 2; \n } \n \n // If array has odd number of elements \n // then initialize the first element as \n // minimum and maximum \n else\n { \n minmax.min = arr[0]; \n minmax.max = arr[0]; \n \n // Set the starting index for loop \n i = 1; \n } \n \n // In the while loop, pick elements in \n // pair and compare the pair with max \n // and min so far \n while (i < n - 1) \n { \n if (arr[i] > arr[i + 1]) \n { \n if(arr[i] > minmax.max) \n minmax.max = arr[i]; \n \n if(arr[i + 1] < minmax.min) \n minmax.min = arr[i + 1]; \n } \n else \n { \n if (arr[i + 1] > minmax.max) \n minmax.max = arr[i + 1]; \n \n if (arr[i] < minmax.min) \n minmax.min = arr[i]; \n } \n \n // Increment the index by 2 as \n // two elements are processed in loop \n i += 2; \n } \n return minmax; \n} \n \n// Driver code \nint main() \n{ \n int arr[] = { 1000, 11, 445, \n 1, 330, 3000 }; \n int arr_size = 6; \n \n Pair minmax = getMinMax(arr, arr_size); \n \n cout << \"nMinimum element is \"\n << minmax.min << endl; \n cout << \"nMaximum element is \"\n << minmax.max; \n \n return 0; \n} \n \n// This code is contributed by nik_3112 \n\n\n\n\n\n", "e": 55231, "s": 53026, "text": null }, { "code": "\n\n\n\n\n\n\n#include<stdio.h>\n \n/* structure is used to return two values from minMax() */\nstruct pair \n{\n int min;\n int max;\n}; \n \nstruct pair getMinMax(int arr[], int n)\n{\n struct pair minmax; \n int i; \n \n /* If array has even number of elements then \n initialize the first two elements as minimum and \n maximum */\n if (n%2 == 0)\n { \n if (arr[0] > arr[1]) \n {\n minmax.max = arr[0];\n minmax.min = arr[1];\n } \n else\n {\n minmax.min = arr[0];\n minmax.max = arr[1];\n }\n i = 2; /* set the starting index for loop */\n } \n \n /* If array has odd number of elements then \n initialize the first element as minimum and \n maximum */\n else\n {\n minmax.min = arr[0];\n minmax.max = arr[0];\n i = 1; /* set the starting index for loop */\n }\n \n /* In the while loop, pick elements in pair and \n compare the pair with max and min so far */ \n while (i < n-1) \n { \n if (arr[i] > arr[i+1]) \n {\n if(arr[i] > minmax.max) \n minmax.max = arr[i];\n if(arr[i+1] < minmax.min) \n minmax.min = arr[i+1]; \n } \n else \n {\n if (arr[i+1] > minmax.max) \n minmax.max = arr[i+1];\n if (arr[i] < minmax.min) \n minmax.min = arr[i]; \n } \n i += 2; /* Increment the index by 2 as two \n elements are processed in loop */\n } \n \n return minmax;\n} \n \n/* Driver program to test above function */\nint main()\n{\n int arr[] = {1000, 11, 445, 1, 330, 3000};\n int arr_size = 6;\n struct pair minmax = getMinMax (arr, arr_size);\n printf(\"nMinimum element is %d\", minmax.min);\n printf(\"nMaximum element is %d\", minmax.max);\n getchar();\n}\n\n\n\n\n\n", "e": 57012, "s": 55241, "text": null }, { "code": "\n\n\n\n\n\n\n// Java program of above implementation\npublic class GFG {\n \n/* Class Pair is used to return two values from getMinMax() */\n static class Pair {\n \n int min;\n int max;\n }\n \n static Pair getMinMax(int arr[], int n) {\n Pair minmax = new Pair();\n int i;\n /* If array has even number of elements then \n initialize the first two elements as minimum and \n maximum */\n if (n % 2 == 0) {\n if (arr[0] > arr[1]) {\n minmax.max = arr[0];\n minmax.min = arr[1];\n } else {\n minmax.min = arr[0];\n minmax.max = arr[1];\n }\n i = 2;\n /* set the starting index for loop */\n } /* If array has odd number of elements then \n initialize the first element as minimum and \n maximum */ else {\n minmax.min = arr[0];\n minmax.max = arr[0];\n i = 1;\n /* set the starting index for loop */\n }\n \n /* In the while loop, pick elements in pair and \n compare the pair with max and min so far */\n while (i < n - 1) {\n if (arr[i] > arr[i + 1]) {\n if (arr[i] > minmax.max) {\n minmax.max = arr[i];\n }\n if (arr[i + 1] < minmax.min) {\n minmax.min = arr[i + 1];\n }\n } else {\n if (arr[i + 1] > minmax.max) {\n minmax.max = arr[i + 1];\n }\n if (arr[i] < minmax.min) {\n minmax.min = arr[i];\n }\n }\n i += 2;\n /* Increment the index by 2 as two \n elements are processed in loop */\n }\n \n return minmax;\n }\n \n /* Driver program to test above function */\n public static void main(String args[]) {\n int arr[] = {1000, 11, 445, 1, 330, 3000};\n int arr_size = 6;\n Pair minmax = getMinMax(arr, arr_size);\n System.out.printf(\"\\nMinimum element is %d\", minmax.min);\n System.out.printf(\"\\nMaximum element is %d\", minmax.max);\n \n }\n}\n\n\n\n\n\n", "e": 59189, "s": 57022, "text": null }, { "code": "\n\n\n\n\n\n\n# Python3 program of above implementation \ndef getMinMax(arr):\n \n n = len(arr)\n \n # If array has even number of elements then \n # initialize the first two elements as minimum \n # and maximum \n if(n % 2 == 0):\n mx = max(arr[0], arr[1])\n mn = min(arr[0], arr[1])\n \n # set the starting index for loop \n i = 2\n \n # If array has odd number of elements then \n # initialize the first element as minimum \n # and maximum \n else:\n mx = mn = arr[0]\n \n # set the starting index for loop \n i = 1\n \n # In the while loop, pick elements in pair and \n # compare the pair with max and min so far \n while(i < n - 1):\n if arr[i] < arr[i + 1]:\n mx = max(mx, arr[i + 1])\n mn = min(mn, arr[i])\n else:\n mx = max(mx, arr[i])\n mn = min(mn, arr[i + 1])\n \n # Increment the index by 2 as two \n # elements are processed in loop \n i += 2\n \n return (mx, mn)\n \n# Driver Code\nif __name__ =='__main__':\n \n arr = [1000, 11, 445, 1, 330, 3000]\n mx, mn = getMinMax(arr)\n print(\"Minimum element is\", mn)\n print(\"Maximum element is\", mx)\n \n# This code is contributed by Kaustav\n\n\n\n\n\n", "e": 60497, "s": 59199, "text": null }, { "code": "\n\n\n\n\n\n\n// C# program of above implementation\nusing System;\n \nclass GFG \n{\n \n /* Class Pair is used to return \n two values from getMinMax() */\n public class Pair \n {\n public int min;\n public int max;\n }\n \n static Pair getMinMax(int []arr, int n)\n {\n Pair minmax = new Pair();\n int i;\n \n /* If array has even number of elements \n then initialize the first two elements \n as minimum and maximum */\n if (n % 2 == 0) \n {\n if (arr[0] > arr[1])\n {\n minmax.max = arr[0];\n minmax.min = arr[1];\n } \n else\n {\n minmax.min = arr[0];\n minmax.max = arr[1];\n }\n i = 2;\n }\n \n /* set the starting index for loop */\n /* If array has odd number of elements then \n initialize the first element as minimum and \n maximum */\n else\n {\n minmax.min = arr[0];\n minmax.max = arr[0];\n i = 1;\n /* set the starting index for loop */\n }\n \n /* In the while loop, pick elements in pair and \n compare the pair with max and min so far */\n while (i < n - 1) \n {\n if (arr[i] > arr[i + 1]) \n {\n if (arr[i] > minmax.max) \n {\n minmax.max = arr[i];\n }\n if (arr[i + 1] < minmax.min)\n {\n minmax.min = arr[i + 1];\n }\n } \n else\n {\n if (arr[i + 1] > minmax.max)\n {\n minmax.max = arr[i + 1];\n }\n if (arr[i] < minmax.min)\n {\n minmax.min = arr[i];\n }\n }\n i += 2;\n \n /* Increment the index by 2 as two \n elements are processed in loop */\n }\n return minmax;\n }\n \n // Driver Code\n public static void Main(String []args) \n {\n int []arr = {1000, 11, 445, 1, 330, 3000};\n int arr_size = 6;\n Pair minmax = getMinMax(arr, arr_size);\n Console.Write(\"Minimum element is {0}\",\n minmax.min);\n Console.Write(\"\\nMaximum element is {0}\", \n minmax.max);\n }\n}\n \n// This code is contributed by 29AjayKumar\n\n\n\n\n\n", "e": 63023, "s": 60507, "text": null }, { "code": null, "e": 63032, "s": 63023, "text": "Output: " }, { "code": null, "e": 63077, "s": 63032, "text": "Minimum element is 1\nMaximum element is 3000" }, { "code": null, "e": 63099, "s": 63077, "text": "Time Complexity: O(n)" }, { "code": null, "e": 63151, "s": 63099, "text": "Auxiliary Space: O(1) as no extra space was needed." }, { "code": null, "e": 63222, "s": 63151, "text": "Total number of comparisons: Different for even and odd n, see below: " }, { "code": null, "e": 63460, "s": 63222, "text": " If n is odd: 3*(n-1)/2 \n If n is even: 1 Initial comparison for initializing min and max, \n and 3(n-2)/2 comparisons for rest of the elements \n = 1 + 3*(n-2)/2 = 3n/2 -2" }, { "code": null, "e": 63710, "s": 63460, "text": "Second and third approaches make the equal number of comparisons when n is a power of 2. In general, method 3 seems to be the best.Please write comments if you find any bug in the above programs/algorithms or a better way to solve the same problem. " }, { "code": null, "e": 63724, "s": 63710, "text": "kamleshbhalui" }, { "code": null, "e": 63734, "s": 63724, "text": "Rajput-Ji" }, { "code": null, "e": 63755, "s": 63734, "text": "Kaustav kumar Chanda" }, { "code": null, "e": 63768, "s": 63755, "text": "Akanksha_Rai" }, { "code": null, "e": 63782, "s": 63768, "text": "princiraj1992" }, { "code": null, "e": 63794, "s": 63782, "text": "29AjayKumar" }, { "code": null, "e": 63806, "s": 63794, "text": "sanjeev2552" }, { "code": null, "e": 63822, "s": 63806, "text": "DeepakChhitarka" }, { "code": null, "e": 63831, "s": 63822, "text": "nik_3112" }, { "code": null, "e": 63843, "s": 63831, "text": "maafkaroplz" }, { "code": null, "e": 63860, "s": 63843, "text": "anjalitejasvi501" }, { "code": null, "e": 63876, "s": 63860, "text": "anshulpurohit11" }, { "code": null, "e": 63889, "s": 63876, "text": "dhairyabahl5" }, { "code": null, "e": 63908, "s": 63889, "text": "shivanisinghss2110" }, { "code": null, "e": 63925, "s": 63908, "text": "abhishekolympics" }, { "code": null, "e": 63937, "s": 63925, "text": "prophet1999" }, { "code": null, "e": 63947, "s": 63937, "text": "\nNumbers\n" }, { "code": null, "e": 63956, "s": 63947, "text": "\nArrays\n" }, { "code": null, "e": 63977, "s": 63956, "text": "\nDivide and Conquer\n" }, { "code": null, "e": 63989, "s": 63977, "text": "\nSearching\n" }, { "code": null, "e": 63996, "s": 63989, "text": "Arrays" }, { "code": null, "e": 64006, "s": 63996, "text": "Searching" }, { "code": null, "e": 64025, "s": 64006, "text": "Divide and Conquer" }, { "code": null, "e": 64033, "s": 64025, "text": "Numbers" }, { "code": null, "e": 64238, "s": 64033, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 64247, "s": 64238, "text": "Comments" }, { "code": null, "e": 64260, "s": 64247, "text": "Old Comments" }, { "code": null, "e": 64275, "s": 64260, "text": "Arrays in Java" }, { "code": null, "e": 64291, "s": 64275, "text": "Arrays in C/C++" }, { "code": null, "e": 64318, "s": 64291, "text": "Program for array rotation" }, { "code": null, "e": 64366, "s": 64318, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 64410, "s": 64366, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 64421, "s": 64410, "text": "Merge Sort" }, { "code": null, "e": 64431, "s": 64421, "text": "QuickSort" }, { "code": null, "e": 64445, "s": 64431, "text": "Binary Search" }, { "code": null, "e": 64472, "s": 64445, "text": "Program for Tower of Hanoi" } ]
Find largest element from array without using conditional operator - GeeksforGeeks
19 Nov, 2021 Given an array of n-elements, we have to find the largest element among them without using any conditional operator like greater than or less than.Examples: Input : arr[] = {5, 7, 2, 9} Output : Largest element = 9 Input : arr[] = {15, 0, 2, 15} Output : Largest element = 15 First Approach (Use of Hashing) : To find the largest element from the array we may use the concept the of hashing where we should maintain a hash table of all element and then after processing all array element we should find the largest element in hash by simply traversing the hash table from end. But there are some drawbacks of this approach like in case of very large elements maintaining a hash table is either not possible or not feasible.Better Approach (Use of Bitwise AND) : Recently we have learn how to find the largest AND value pair from a given array. Also, we know that if we take bitwise AND of any number with INT_MAX (whose all bits are set bits) then the result will be that number itself. Now, using this property we will try to find the largest element from the array without any use conditional operator like greater than or less than.For finding the largest element we will first insert an extra element i.e. INT_MAX in array, and after that we will try to find the maximum AND value of any pair from the array. This obtained maximum value will contain AND value of INT_MAX and largest element of original array and is our required result.Below is the implementation of above approach : C++ Java Python3 C# PHP Javascript // C++ Program to find largest element from array#include <bits/stdc++.h>using namespace std; // Utility function to check number of// elements having set msb as of patternint checkBit(int pattern, vector<int> arr, int n){ int count = 0; for (int i = 0; i < n; i++) if ((pattern & arr[i]) == pattern) count++; return count;} // Function for finding maximum and value pairint largest(int arr[], int n){ // Create a vector of given array vector<int> v(arr, arr + n); // Insert INT_MAX and update n v.push_back(INT_MAX); n++; int res = 0; // Iterate over total of 30bits from // msb to lsb for (int bit = 31; bit >= 0; bit--) { // Find the count of element having set msb int count = checkBit(res | (1 << bit), v, n); // if count | 1 != 1 set particular // bit in result if ((count | 1) != 1) res |= (1 << bit); } return res;} // Driver Codeint main(){ int arr[] = { 4, 8, 6, 2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Largest element = " << largest(arr, n); return 0;} // Java Program to find largest element from arrayimport java.util.Vector;import java.util.Arrays; class GfG{ // Utility function to check number of// elements having set msb as of patternstatic int checkBit(int pattern, Vector<Integer> arr, int n){ int count = 0; for (int i = 0; i < n; i++) if ((pattern & arr.get(i)) == pattern) count++; return count;} // Function for finding maximum and value pairstatic int largest(int arr[], int n){ // Create a vector of given array Vector<Integer> v = new Vector<>(); for(Integer a:arr) v.add(a); // Insert INT_MAX and update n v.add(Integer.MAX_VALUE); n++; int res = 0; // Iterate over total of 30bits from // msb to lsb for (int bit = 31; bit >= 0; bit--) { // Find the count of element having set msb int count = checkBit(res | (1 << bit), v, n); // if count | 1 != 1 set particular // bit in result if ((count | 1) != 1) res |= (1 << bit); } return res;} // Driver Codepublic static void main(String[] args){ int arr[] = { 4, 8, 6, 2 }; int n = arr.length; System.out.println("Largest element = " + largest(arr, n));}} /* This code contributed by PrinciRaj1992 */ # Python3 Program to find largest# element from arrayimport math as mt # Utility function to check number of# elements having set msb as of patterndef checkBit(pattern, arr, n): count = 0 for i in range(n): if ((pattern & arr[i]) == pattern): count += 1 return count # Function for finding maximum# and value pairdef largest(arr, n): # Create a vector of given array v = arr # Insert max value of Int and update n v.append(2**31 - 1) n = n + 1 res = 0 # Iterate over total of 30bits # from msb to lsb for bit in range(31, -1, -1): # Find the count of element # having set msb count = checkBit(res | (1 << bit), v, n) # if count | 1 != 1 set particular # bit in result if ((count | 1) != 1): res |= (1 << bit) return res # Driver Codearr = [4, 8, 6, 2]n = len(arr)print("Largest element =", largest(arr, n)) # This code is contributed by# Mohit kumar 29 // C# Program to find largest element from arrayusing System; using System.Collections.Generic; class GfG{ // Utility function to check number of// elements having set msb as of patternstatic int checkBit(int pattern, List<int> arr, int n){ int count = 0; for (int i = 0; i < n; i++) if ((pattern & arr[i]) == pattern) count++; return count;} // Function for finding maximum and value pairstatic int largest(int []arr, int n){ // Create a vector of given array List<int> v = new List<int>(); foreach(int a in arr) v.Add(a); // Insert INT_MAX and update n v.Add(int.MaxValue); n++; int res = 0; // Iterate over total of 30bits from // msb to lsb for (int bit = 31; bit >= 0; bit--) { // Find the count of element having set msb int count = checkBit(res | (1 << bit), v, n); // if count | 1 != 1 set particular // bit in result if ((count | 1) != 1) res |= (1 << bit); } return res;} // Driver Codepublic static void Main(String[] args){ int []arr = { 4, 8, 6, 2 }; int n = arr.Length; Console.WriteLine("Largest element = " + largest(arr, n));}} // This code contributed by Rajput-Ji <?php// php Program to find largest// element from array // Utility function to check// number of elements having// set msb as of patternfunction checkBit($pattern,$arr,$n){ $count = 0; for ($i = 0; $i < $n; $i++) if (($pattern & $arr[$i]) == $pattern) $count++; return $count;} // Function for finding// maximum and value pairfunction largest($arr, $n){ $res = 0; // Iterate over total of // 30bits from msb to lsb for ($bit = 31; $bit >= 0; $bit--) { // Find the count of element // having set msb $count = checkBit($res | (1 << $bit),$arr, $n); // if count | 1 != 1 set // particular bit in result if ($count | 1 != 1) $res |= (1 << $bit); } return $res;} // Driver code $arr = array( 4, 8, 6, 2 ); $n = sizeof($arr) / sizeof($arr[0]); echo "Largest element = ". largest($arr, $n); // This code is contributed by mits ?> <script>// javascript Program to find largest element from array // Utility function to check number of// elements having set msb as of patternfunction checkBit( pattern, arr, n){ let count = 0; for (let i = 0; i < n; i++) if ((pattern & arr[i]) == pattern) count++; return count;} // Function for finding maximum and value pairfunction largest( arr, n){ // Create a vector of given array let v = []; for(let i = 0;i<n;i++){ v.push(arr[i]) } // Insert INT_MAX and update n v.push(Math.pow(2,31)-1); n++; let res = 0; // Iterate over total of 30bits from // msb to lsb for (let bit = 31; bit >= 0; bit--) { // Find the count of element having set msb let count = checkBit(res | (1 << bit), v, n); // if count | 1 != 1 set particular // bit in result if ((count | 1) != 1) res |= (1 << bit); } return res;} let a = [ 4, 8, 6, 2 ];n = a.length;document.write("Largest element = ");document.write(largest(a, n)); // This code is contributed by rohitsingh07052.</script> Output: Largest element = 8 Time Complexity: O(32) Auxiliary Space: O(N) Mithun Kumar mohit kumar 29 princiraj1992 Rajput-Ji rohitsingh07052 Arrays Bit Magic Arrays Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java Linear Search Bitwise Operators in C/C++ Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Cyclic Redundancy Check and Modulo-2 Division Count set bits in an integer
[ { "code": null, "e": 24884, "s": 24856, "text": "\n19 Nov, 2021" }, { "code": null, "e": 25043, "s": 24884, "text": "Given an array of n-elements, we have to find the largest element among them without using any conditional operator like greater than or less than.Examples: " }, { "code": null, "e": 25163, "s": 25043, "text": "Input : arr[] = {5, 7, 2, 9}\nOutput : Largest element = 9\n\nInput : arr[] = {15, 0, 2, 15}\nOutput : Largest element = 15" }, { "code": null, "e": 26379, "s": 25165, "text": "First Approach (Use of Hashing) : To find the largest element from the array we may use the concept the of hashing where we should maintain a hash table of all element and then after processing all array element we should find the largest element in hash by simply traversing the hash table from end. But there are some drawbacks of this approach like in case of very large elements maintaining a hash table is either not possible or not feasible.Better Approach (Use of Bitwise AND) : Recently we have learn how to find the largest AND value pair from a given array. Also, we know that if we take bitwise AND of any number with INT_MAX (whose all bits are set bits) then the result will be that number itself. Now, using this property we will try to find the largest element from the array without any use conditional operator like greater than or less than.For finding the largest element we will first insert an extra element i.e. INT_MAX in array, and after that we will try to find the maximum AND value of any pair from the array. This obtained maximum value will contain AND value of INT_MAX and largest element of original array and is our required result.Below is the implementation of above approach : " }, { "code": null, "e": 26383, "s": 26379, "text": "C++" }, { "code": null, "e": 26388, "s": 26383, "text": "Java" }, { "code": null, "e": 26396, "s": 26388, "text": "Python3" }, { "code": null, "e": 26399, "s": 26396, "text": "C#" }, { "code": null, "e": 26403, "s": 26399, "text": "PHP" }, { "code": null, "e": 26414, "s": 26403, "text": "Javascript" }, { "code": "// C++ Program to find largest element from array#include <bits/stdc++.h>using namespace std; // Utility function to check number of// elements having set msb as of patternint checkBit(int pattern, vector<int> arr, int n){ int count = 0; for (int i = 0; i < n; i++) if ((pattern & arr[i]) == pattern) count++; return count;} // Function for finding maximum and value pairint largest(int arr[], int n){ // Create a vector of given array vector<int> v(arr, arr + n); // Insert INT_MAX and update n v.push_back(INT_MAX); n++; int res = 0; // Iterate over total of 30bits from // msb to lsb for (int bit = 31; bit >= 0; bit--) { // Find the count of element having set msb int count = checkBit(res | (1 << bit), v, n); // if count | 1 != 1 set particular // bit in result if ((count | 1) != 1) res |= (1 << bit); } return res;} // Driver Codeint main(){ int arr[] = { 4, 8, 6, 2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Largest element = \" << largest(arr, n); return 0;}", "e": 27517, "s": 26414, "text": null }, { "code": "// Java Program to find largest element from arrayimport java.util.Vector;import java.util.Arrays; class GfG{ // Utility function to check number of// elements having set msb as of patternstatic int checkBit(int pattern, Vector<Integer> arr, int n){ int count = 0; for (int i = 0; i < n; i++) if ((pattern & arr.get(i)) == pattern) count++; return count;} // Function for finding maximum and value pairstatic int largest(int arr[], int n){ // Create a vector of given array Vector<Integer> v = new Vector<>(); for(Integer a:arr) v.add(a); // Insert INT_MAX and update n v.add(Integer.MAX_VALUE); n++; int res = 0; // Iterate over total of 30bits from // msb to lsb for (int bit = 31; bit >= 0; bit--) { // Find the count of element having set msb int count = checkBit(res | (1 << bit), v, n); // if count | 1 != 1 set particular // bit in result if ((count | 1) != 1) res |= (1 << bit); } return res;} // Driver Codepublic static void main(String[] args){ int arr[] = { 4, 8, 6, 2 }; int n = arr.length; System.out.println(\"Largest element = \" + largest(arr, n));}} /* This code contributed by PrinciRaj1992 */", "e": 28789, "s": 27517, "text": null }, { "code": "# Python3 Program to find largest# element from arrayimport math as mt # Utility function to check number of# elements having set msb as of patterndef checkBit(pattern, arr, n): count = 0 for i in range(n): if ((pattern & arr[i]) == pattern): count += 1 return count # Function for finding maximum# and value pairdef largest(arr, n): # Create a vector of given array v = arr # Insert max value of Int and update n v.append(2**31 - 1) n = n + 1 res = 0 # Iterate over total of 30bits # from msb to lsb for bit in range(31, -1, -1): # Find the count of element # having set msb count = checkBit(res | (1 << bit), v, n) # if count | 1 != 1 set particular # bit in result if ((count | 1) != 1): res |= (1 << bit) return res # Driver Codearr = [4, 8, 6, 2]n = len(arr)print(\"Largest element =\", largest(arr, n)) # This code is contributed by# Mohit kumar 29", "e": 29763, "s": 28789, "text": null }, { "code": "// C# Program to find largest element from arrayusing System; using System.Collections.Generic; class GfG{ // Utility function to check number of// elements having set msb as of patternstatic int checkBit(int pattern, List<int> arr, int n){ int count = 0; for (int i = 0; i < n; i++) if ((pattern & arr[i]) == pattern) count++; return count;} // Function for finding maximum and value pairstatic int largest(int []arr, int n){ // Create a vector of given array List<int> v = new List<int>(); foreach(int a in arr) v.Add(a); // Insert INT_MAX and update n v.Add(int.MaxValue); n++; int res = 0; // Iterate over total of 30bits from // msb to lsb for (int bit = 31; bit >= 0; bit--) { // Find the count of element having set msb int count = checkBit(res | (1 << bit), v, n); // if count | 1 != 1 set particular // bit in result if ((count | 1) != 1) res |= (1 << bit); } return res;} // Driver Codepublic static void Main(String[] args){ int []arr = { 4, 8, 6, 2 }; int n = arr.Length; Console.WriteLine(\"Largest element = \" + largest(arr, n));}} // This code contributed by Rajput-Ji", "e": 31021, "s": 29763, "text": null }, { "code": "<?php// php Program to find largest// element from array // Utility function to check// number of elements having// set msb as of patternfunction checkBit($pattern,$arr,$n){ $count = 0; for ($i = 0; $i < $n; $i++) if (($pattern & $arr[$i]) == $pattern) $count++; return $count;} // Function for finding// maximum and value pairfunction largest($arr, $n){ $res = 0; // Iterate over total of // 30bits from msb to lsb for ($bit = 31; $bit >= 0; $bit--) { // Find the count of element // having set msb $count = checkBit($res | (1 << $bit),$arr, $n); // if count | 1 != 1 set // particular bit in result if ($count | 1 != 1) $res |= (1 << $bit); } return $res;} // Driver code $arr = array( 4, 8, 6, 2 ); $n = sizeof($arr) / sizeof($arr[0]); echo \"Largest element = \". largest($arr, $n); // This code is contributed by mits ?>", "e": 31963, "s": 31021, "text": null }, { "code": "<script>// javascript Program to find largest element from array // Utility function to check number of// elements having set msb as of patternfunction checkBit( pattern, arr, n){ let count = 0; for (let i = 0; i < n; i++) if ((pattern & arr[i]) == pattern) count++; return count;} // Function for finding maximum and value pairfunction largest( arr, n){ // Create a vector of given array let v = []; for(let i = 0;i<n;i++){ v.push(arr[i]) } // Insert INT_MAX and update n v.push(Math.pow(2,31)-1); n++; let res = 0; // Iterate over total of 30bits from // msb to lsb for (let bit = 31; bit >= 0; bit--) { // Find the count of element having set msb let count = checkBit(res | (1 << bit), v, n); // if count | 1 != 1 set particular // bit in result if ((count | 1) != 1) res |= (1 << bit); } return res;} let a = [ 4, 8, 6, 2 ];n = a.length;document.write(\"Largest element = \");document.write(largest(a, n)); // This code is contributed by rohitsingh07052.</script>", "e": 33061, "s": 31963, "text": null }, { "code": null, "e": 33071, "s": 33061, "text": "Output: " }, { "code": null, "e": 33091, "s": 33071, "text": "Largest element = 8" }, { "code": null, "e": 33114, "s": 33091, "text": "Time Complexity: O(32)" }, { "code": null, "e": 33137, "s": 33114, "text": "Auxiliary Space: O(N) " }, { "code": null, "e": 33150, "s": 33137, "text": "Mithun Kumar" }, { "code": null, "e": 33165, "s": 33150, "text": "mohit kumar 29" }, { "code": null, "e": 33179, "s": 33165, "text": "princiraj1992" }, { "code": null, "e": 33189, "s": 33179, "text": "Rajput-Ji" }, { "code": null, "e": 33205, "s": 33189, "text": "rohitsingh07052" }, { "code": null, "e": 33212, "s": 33205, "text": "Arrays" }, { "code": null, "e": 33222, "s": 33212, "text": "Bit Magic" }, { "code": null, "e": 33229, "s": 33222, "text": "Arrays" }, { "code": null, "e": 33239, "s": 33229, "text": "Bit Magic" }, { "code": null, "e": 33337, "s": 33239, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33346, "s": 33337, "text": "Comments" }, { "code": null, "e": 33359, "s": 33346, "text": "Old Comments" }, { "code": null, "e": 33407, "s": 33359, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 33451, "s": 33407, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 33474, "s": 33451, "text": "Introduction to Arrays" }, { "code": null, "e": 33506, "s": 33474, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 33520, "s": 33506, "text": "Linear Search" }, { "code": null, "e": 33547, "s": 33520, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 33593, "s": 33547, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 33661, "s": 33593, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 33707, "s": 33661, "text": "Cyclic Redundancy Check and Modulo-2 Division" } ]
Python Tuple min() Method
Python tuple method min() returns the elements from the tuple with minimum value. Following is the syntax for min() method − min(tuple) tuple − This is a tuple from which min valued element to be returned. tuple − This is a tuple from which min valued element to be returned. This method returns the elements from the tuple with minimum value. The following example shows the usage of min() method. #!/usr/bin/python tuple1, tuple2 = (123, 'xyz', 'zara', 'abc'), (456, 700, 200) print "min value element : ", min(tuple1) print "min value element : ", min(tuple2) When we run above program, it produces following result − min value element : 123 min value element : 200 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2326, "s": 2244, "text": "Python tuple method min() returns the elements from the tuple with minimum value." }, { "code": null, "e": 2369, "s": 2326, "text": "Following is the syntax for min() method −" }, { "code": null, "e": 2381, "s": 2369, "text": "min(tuple)\n" }, { "code": null, "e": 2452, "s": 2381, "text": "tuple − This is a tuple from which min valued element to be returned. " }, { "code": null, "e": 2523, "s": 2452, "text": "tuple − This is a tuple from which min valued element to be returned. " }, { "code": null, "e": 2591, "s": 2523, "text": "This method returns the elements from the tuple with minimum value." }, { "code": null, "e": 2646, "s": 2591, "text": "The following example shows the usage of min() method." }, { "code": null, "e": 2811, "s": 2646, "text": "#!/usr/bin/python\n\ntuple1, tuple2 = (123, 'xyz', 'zara', 'abc'), (456, 700, 200)\nprint \"min value element : \", min(tuple1)\nprint \"min value element : \", min(tuple2)" }, { "code": null, "e": 2869, "s": 2811, "text": "When we run above program, it produces following result −" }, { "code": null, "e": 2920, "s": 2869, "text": "min value element : 123\nmin value element : 200\n" }, { "code": null, "e": 2957, "s": 2920, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 2973, "s": 2957, "text": " Malhar Lathkar" }, { "code": null, "e": 3006, "s": 2973, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3025, "s": 3006, "text": " Arnab Chakraborty" }, { "code": null, "e": 3060, "s": 3025, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3082, "s": 3060, "text": " In28Minutes Official" }, { "code": null, "e": 3116, "s": 3082, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3144, "s": 3116, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3179, "s": 3144, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3193, "s": 3179, "text": " Lets Kode It" }, { "code": null, "e": 3226, "s": 3193, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3243, "s": 3226, "text": " Abhilash Nelson" }, { "code": null, "e": 3250, "s": 3243, "text": " Print" }, { "code": null, "e": 3261, "s": 3250, "text": " Add Notes" } ]
11 Visualization Examples to Practice Matplotlib | by Soner Yıldırım | Towards Data Science
Data visualization is very important in the field of data science. It is not only used for delivering results but also an essential part in exploratory data analysis. Matplotlib is a widely-used Python data visualization library. In fact, many other libraries are built on top of Matplotlib such as Seaborn. The syntax of Matplotlib is usually more complicated than other visualization libraries for Python. However, it offers you flexibility. You can customize the plots freely. This post can be considered as a Matplotlib tutorial but heavily focused on the practical side. In each example, I will try to produce a different plot that points out important features of Matplotlib. I will do examples on a customer churn dataset that is available on Kaggle. I use this dataset quite often because it is a good mixture of categorical and numerical variables. Besides, it carries a purpose so the examples constitute an exploratory data analysis process. Let’s first install the dependencies: import numpy as npimport pandas as pdimport matplotlib.pyplot as plt%matplotlib inline Matplotlib consists of 3 layers which are the Backend, Artist, and Scripting layers. The scripting layer is the matplotlib.pyplot interface. The scripting layer makes it relatively easy to create plots because it automates the process of putting everything together. Thus, it is the most widely-used layer by data scientists. We will read the dataset into a Pandas dataframe. cols = ['CreditScore', 'Geography', 'Gender', 'Age', 'Tenure', 'Balance', 'NumOfProducts', 'IsActiveMember', 'EstimatedSalary','Exited']churn = pd.read_csv("/content/Churn_Modelling.csv", usecols=cols)churn.head() The dataset contains some features about the customers of a bank and their bank account. The “Exited” column indicates whether a customer churned (i.e. left the bank). We are ready to start. This one is pretty simple but a good example for bar plots. plt.figure(figsize=(8,5))plt.title("Number of Customers", fontsize=14)plt.bar(x=churn['Geography'].value_counts().index, height=churn.Geography.value_counts().values) In the first line, we create a Figure object with a specific size. The next line adds a title to the Figure object. The bar function plots the actual data. The default settings are usually appropriate but minor adjustments might be necessary in some cases. For instance, we can increase the fontsize and also adjust the value range of y-axis. plt.xticks(fontsize=12, rotation=45)plt.yticks(ticks=np.arange(0, 7000, 1000), fontsize=12) Adding these two lines of codes to the previous plot will produce: The default figure size is (6,4) which I think is pretty small. If you don’t want to explicitly define the size for each figure, you may want to change the default setting. The rcParams package of matplotlib is used to store and change the default settings. plt.rcParams.get('figure.figsize')[6.0, 4.0] As you can see, the default size is (6,4). Let’s change it to (8,5): plt.rcParams['figure.figsize'] = (8,5) We can also change the default setting for other parameters such as line style, line width, and so on. I have also changed the fontsize of xtick and yticks to 12. plt.rc('xtick', labelsize=12)plt.rc('ytick', labelsize=12) Histogram is used to visualize the distribution of a variable. The following syntax will create a simple histogram of customer balances. plt.hist(x=churn['Balance']) Most the customers have zero balance. When zero balance excluded, the distribution is close to the normal (Gaussian) distribution. The two essential features that define a histogram are the number of bins and the value range. The default value for the number of bins is 10 so the value range will be divided into 10 equal bins. For instance, the first bin in the previous histogram is 0–25000. Increasing the bin size is like having more resolution. We will get a more accurate overview of the distribution to some point. The value range is defined by taking the minimum and maximum values of the column. We can adjust it to exclude the outliers or specific values. plt.hist(x=churn['Balance'], bins=12, color='darkgrey', range=(25000, 225000))plt.title("Distribution on Balance (25000 - 225000)", fontsize=14) The values that are lower than 25000 or higher than 225000 are excluded and the number of bins increase from 10 to 16. We now see a typical normal distribution. Scatter plots are commonly used to map the relationship between numerical variables. We can visualize the correlation between variables using a scatter plot. sample = churn.sample(n=200, random_state=42) #small sampleplt.scatter(x=sample['CreditScore'], y=sample['Age']) It seems like there is not a correlation between the age and credit score. We can put multiple scatter plots on the same Figure object. Although the syntax is longer than some other libraries (e.g. Seaborn), Matplotlib is highly flexible in terms of subplots. We will do several examples that consist of subplots. The subplots function creates a Figure and a set of subplots: fig, ax = plt.subplots() We can create multiple plots on the figure and identify them with a legend. plt.title("France vs Germany", fontsize=14)ax.scatter(x=sample[sample.Geography == 'France']['CreditScore'], y=sample[sample.Geography == 'France']['Age'])ax.scatter(x=sample[sample.Geography == 'Germany']['CreditScore'], y=sample[sample.Geography == 'Germany']['Age'])ax.legend(labels=['France','Germany'], loc='lower left', fontsize=12) The subplots do not have to be on top of each other. The subplots function allows creating a grid of subplots by using the nrows and ncols parameters. fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, ncols=1) We have an empty grid of subplots. In the following examples, we will see how to fill these subplots and make small adjustments to make them look nicer. Before adding the titles, let’s put a little space between the subplots so that they will look better. We will do that with tight_layout function. We can also remove the xticks in between and only have the ones at the bottom. This can be done with the sharex parameter. fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, ncols=1, figsize=(9,6), sharex=True)fig.tight_layout(pad=2) There are two ways to access the subplots. One way is to define them explicitly and the other way is to use indexing. # 1fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1)first subplot: ax1first subplot: ax2# 2fig, axs = plt.subplots(nrows=2, ncols=1)first subplot: axs[0]second subplot: axs[1] We will create a grid of 2 columns and add bar plots to each one. fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, sharey=True,figsize=(8,5))countries = churn.Geography.value_counts()products = churn.NumOfProducts.value_counts()ax1.bar(x=countries.index, height=countries.values)ax1.set_title("Countries", fontsize=12)ax2.bar(x=products.index, height=products.values)ax2.set_title("Number of Products", fontsize=12) 2D histograms visualize the distributions of a pair of variables. We get an overview of how the values of two variables change together. Let’s create a 2D histogram of the credit score and age. plt.title("Credit Score vs Age", fontsize=15)plt.hist2d(x=churn.CreditScore, y=churn.Age) The most populated group consists of the customers between ages 30 and 40 and have credit scores between 600 and 700. What we have covered in this post is just a small part of Matplotlib’s capabilities. Some of the information I shared can be considered as a detail while some of them are very basic. However, they all are useful in making the most out of Matplotlib. The best way to master Matplotlib, like in any other subject, is to practice. Once you are comfortable with the basic functionality, you can proceed to the more advanced features. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 338, "s": 171, "text": "Data visualization is very important in the field of data science. It is not only used for delivering results but also an essential part in exploratory data analysis." }, { "code": null, "e": 479, "s": 338, "text": "Matplotlib is a widely-used Python data visualization library. In fact, many other libraries are built on top of Matplotlib such as Seaborn." }, { "code": null, "e": 651, "s": 479, "text": "The syntax of Matplotlib is usually more complicated than other visualization libraries for Python. However, it offers you flexibility. You can customize the plots freely." }, { "code": null, "e": 853, "s": 651, "text": "This post can be considered as a Matplotlib tutorial but heavily focused on the practical side. In each example, I will try to produce a different plot that points out important features of Matplotlib." }, { "code": null, "e": 1124, "s": 853, "text": "I will do examples on a customer churn dataset that is available on Kaggle. I use this dataset quite often because it is a good mixture of categorical and numerical variables. Besides, it carries a purpose so the examples constitute an exploratory data analysis process." }, { "code": null, "e": 1162, "s": 1124, "text": "Let’s first install the dependencies:" }, { "code": null, "e": 1249, "s": 1162, "text": "import numpy as npimport pandas as pdimport matplotlib.pyplot as plt%matplotlib inline" }, { "code": null, "e": 1390, "s": 1249, "text": "Matplotlib consists of 3 layers which are the Backend, Artist, and Scripting layers. The scripting layer is the matplotlib.pyplot interface." }, { "code": null, "e": 1575, "s": 1390, "text": "The scripting layer makes it relatively easy to create plots because it automates the process of putting everything together. Thus, it is the most widely-used layer by data scientists." }, { "code": null, "e": 1625, "s": 1575, "text": "We will read the dataset into a Pandas dataframe." }, { "code": null, "e": 1839, "s": 1625, "text": "cols = ['CreditScore', 'Geography', 'Gender', 'Age', 'Tenure', 'Balance', 'NumOfProducts', 'IsActiveMember', 'EstimatedSalary','Exited']churn = pd.read_csv(\"/content/Churn_Modelling.csv\", usecols=cols)churn.head()" }, { "code": null, "e": 2007, "s": 1839, "text": "The dataset contains some features about the customers of a bank and their bank account. The “Exited” column indicates whether a customer churned (i.e. left the bank)." }, { "code": null, "e": 2030, "s": 2007, "text": "We are ready to start." }, { "code": null, "e": 2090, "s": 2030, "text": "This one is pretty simple but a good example for bar plots." }, { "code": null, "e": 2264, "s": 2090, "text": "plt.figure(figsize=(8,5))plt.title(\"Number of Customers\", fontsize=14)plt.bar(x=churn['Geography'].value_counts().index, height=churn.Geography.value_counts().values)" }, { "code": null, "e": 2420, "s": 2264, "text": "In the first line, we create a Figure object with a specific size. The next line adds a title to the Figure object. The bar function plots the actual data." }, { "code": null, "e": 2607, "s": 2420, "text": "The default settings are usually appropriate but minor adjustments might be necessary in some cases. For instance, we can increase the fontsize and also adjust the value range of y-axis." }, { "code": null, "e": 2699, "s": 2607, "text": "plt.xticks(fontsize=12, rotation=45)plt.yticks(ticks=np.arange(0, 7000, 1000), fontsize=12)" }, { "code": null, "e": 2766, "s": 2699, "text": "Adding these two lines of codes to the previous plot will produce:" }, { "code": null, "e": 2939, "s": 2766, "text": "The default figure size is (6,4) which I think is pretty small. If you don’t want to explicitly define the size for each figure, you may want to change the default setting." }, { "code": null, "e": 3024, "s": 2939, "text": "The rcParams package of matplotlib is used to store and change the default settings." }, { "code": null, "e": 3069, "s": 3024, "text": "plt.rcParams.get('figure.figsize')[6.0, 4.0]" }, { "code": null, "e": 3138, "s": 3069, "text": "As you can see, the default size is (6,4). Let’s change it to (8,5):" }, { "code": null, "e": 3177, "s": 3138, "text": "plt.rcParams['figure.figsize'] = (8,5)" }, { "code": null, "e": 3280, "s": 3177, "text": "We can also change the default setting for other parameters such as line style, line width, and so on." }, { "code": null, "e": 3340, "s": 3280, "text": "I have also changed the fontsize of xtick and yticks to 12." }, { "code": null, "e": 3399, "s": 3340, "text": "plt.rc('xtick', labelsize=12)plt.rc('ytick', labelsize=12)" }, { "code": null, "e": 3462, "s": 3399, "text": "Histogram is used to visualize the distribution of a variable." }, { "code": null, "e": 3536, "s": 3462, "text": "The following syntax will create a simple histogram of customer balances." }, { "code": null, "e": 3565, "s": 3536, "text": "plt.hist(x=churn['Balance'])" }, { "code": null, "e": 3696, "s": 3565, "text": "Most the customers have zero balance. When zero balance excluded, the distribution is close to the normal (Gaussian) distribution." }, { "code": null, "e": 3791, "s": 3696, "text": "The two essential features that define a histogram are the number of bins and the value range." }, { "code": null, "e": 4087, "s": 3791, "text": "The default value for the number of bins is 10 so the value range will be divided into 10 equal bins. For instance, the first bin in the previous histogram is 0–25000. Increasing the bin size is like having more resolution. We will get a more accurate overview of the distribution to some point." }, { "code": null, "e": 4231, "s": 4087, "text": "The value range is defined by taking the minimum and maximum values of the column. We can adjust it to exclude the outliers or specific values." }, { "code": null, "e": 4384, "s": 4231, "text": "plt.hist(x=churn['Balance'], bins=12, color='darkgrey', range=(25000, 225000))plt.title(\"Distribution on Balance (25000 - 225000)\", fontsize=14)" }, { "code": null, "e": 4545, "s": 4384, "text": "The values that are lower than 25000 or higher than 225000 are excluded and the number of bins increase from 10 to 16. We now see a typical normal distribution." }, { "code": null, "e": 4703, "s": 4545, "text": "Scatter plots are commonly used to map the relationship between numerical variables. We can visualize the correlation between variables using a scatter plot." }, { "code": null, "e": 4816, "s": 4703, "text": "sample = churn.sample(n=200, random_state=42) #small sampleplt.scatter(x=sample['CreditScore'], y=sample['Age'])" }, { "code": null, "e": 4891, "s": 4816, "text": "It seems like there is not a correlation between the age and credit score." }, { "code": null, "e": 5130, "s": 4891, "text": "We can put multiple scatter plots on the same Figure object. Although the syntax is longer than some other libraries (e.g. Seaborn), Matplotlib is highly flexible in terms of subplots. We will do several examples that consist of subplots." }, { "code": null, "e": 5192, "s": 5130, "text": "The subplots function creates a Figure and a set of subplots:" }, { "code": null, "e": 5217, "s": 5192, "text": "fig, ax = plt.subplots()" }, { "code": null, "e": 5293, "s": 5217, "text": "We can create multiple plots on the figure and identify them with a legend." }, { "code": null, "e": 5632, "s": 5293, "text": "plt.title(\"France vs Germany\", fontsize=14)ax.scatter(x=sample[sample.Geography == 'France']['CreditScore'], y=sample[sample.Geography == 'France']['Age'])ax.scatter(x=sample[sample.Geography == 'Germany']['CreditScore'], y=sample[sample.Geography == 'Germany']['Age'])ax.legend(labels=['France','Germany'], loc='lower left', fontsize=12)" }, { "code": null, "e": 5783, "s": 5632, "text": "The subplots do not have to be on top of each other. The subplots function allows creating a grid of subplots by using the nrows and ncols parameters." }, { "code": null, "e": 5837, "s": 5783, "text": "fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, ncols=1)" }, { "code": null, "e": 5990, "s": 5837, "text": "We have an empty grid of subplots. In the following examples, we will see how to fill these subplots and make small adjustments to make them look nicer." }, { "code": null, "e": 6137, "s": 5990, "text": "Before adding the titles, let’s put a little space between the subplots so that they will look better. We will do that with tight_layout function." }, { "code": null, "e": 6260, "s": 6137, "text": "We can also remove the xticks in between and only have the ones at the bottom. This can be done with the sharex parameter." }, { "code": null, "e": 6365, "s": 6260, "text": "fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, ncols=1, figsize=(9,6), sharex=True)fig.tight_layout(pad=2)" }, { "code": null, "e": 6483, "s": 6365, "text": "There are two ways to access the subplots. One way is to define them explicitly and the other way is to use indexing." }, { "code": null, "e": 6658, "s": 6483, "text": "# 1fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1)first subplot: ax1first subplot: ax2# 2fig, axs = plt.subplots(nrows=2, ncols=1)first subplot: axs[0]second subplot: axs[1]" }, { "code": null, "e": 6724, "s": 6658, "text": "We will create a grid of 2 columns and add bar plots to each one." }, { "code": null, "e": 7074, "s": 6724, "text": "fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, sharey=True,figsize=(8,5))countries = churn.Geography.value_counts()products = churn.NumOfProducts.value_counts()ax1.bar(x=countries.index, height=countries.values)ax1.set_title(\"Countries\", fontsize=12)ax2.bar(x=products.index, height=products.values)ax2.set_title(\"Number of Products\", fontsize=12)" }, { "code": null, "e": 7211, "s": 7074, "text": "2D histograms visualize the distributions of a pair of variables. We get an overview of how the values of two variables change together." }, { "code": null, "e": 7268, "s": 7211, "text": "Let’s create a 2D histogram of the credit score and age." }, { "code": null, "e": 7358, "s": 7268, "text": "plt.title(\"Credit Score vs Age\", fontsize=15)plt.hist2d(x=churn.CreditScore, y=churn.Age)" }, { "code": null, "e": 7476, "s": 7358, "text": "The most populated group consists of the customers between ages 30 and 40 and have credit scores between 600 and 700." }, { "code": null, "e": 7726, "s": 7476, "text": "What we have covered in this post is just a small part of Matplotlib’s capabilities. Some of the information I shared can be considered as a detail while some of them are very basic. However, they all are useful in making the most out of Matplotlib." }, { "code": null, "e": 7906, "s": 7726, "text": "The best way to master Matplotlib, like in any other subject, is to practice. Once you are comfortable with the basic functionality, you can proceed to the more advanced features." } ]
Output of Python Programs | Set 20 (Tuples) - GeeksforGeeks
18 Sep, 2020 Prerequisite : TuplesNote: Output of all these programs is tested on Python3 1. What will be the output of the following program ? tuple = (1, 2, 3, 4)tuple.append( (5, 6, 7) )print(len(my_tuple)) Options: 125Error 1 2 5 Error Output: 4. Error Explanation: In this case an exception will be thrown as tuples are immutable and don’t have an append method. 2. What will be the output of the following program ? tuple = {}tuple[(1,2,4)] = 8tuple[(4,2,1)] = 10tuple[(1,2)] = 12_sum = 0for k in tuple: _sum += tuple[k]print(len(tuple) + _sum) Options: 34123133 34 12 31 33 Output: 4. 33 Explanation: Tuples can be used for keys into dictionary. The tuples can have mixed lengths and the order of the items in the tuple is considered when comparing the equality of the keys. 3. What will be the output of the following program ? tuple1 = (1, 2, 4, 3)tuple2 = (1, 2, 3, 4)print(tuple1 < tuple2) Options: ErrorTrueFalseUnexpected Error True False Unexpected Output: 3. False Explanation: In this case elements will be compared one by one. So, when it compares 4 with 3 it will return False. 4. What will be the output of the following program ? tuple = (1, 2, 3)print(2 * tuple) Options: (1, 2, 3, 1, 2, 3)(1, 2, 3, 4, 5, 6)(3, 6, 9)Error (1, 2, 3, 1, 2, 3) (1, 2, 3, 4, 5, 6) (3, 6, 9) Error Output: 1. (1, 2, 3, 1, 2, 3) Explanation: ‘*’ operator is used to concatenate tuples. 5. What will be the output of the following program ? tuple=("Check")*3print(tuple) Options: Unexpected(3Check)CheckCheckCheckSyntax Error Unexpected (3Check) CheckCheckCheck Syntax Error Output: 3. CheckCheckCheck Explanation: Here “Check” will be treated as is a string not a tuple as there is no comma after the element. Python-Output python-tuple Program Output Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Output of Java programs | Set 13 (Collections) Output of Java Program | Set 3 Different ways to copy a string in C/C++ Output of C++ programs | Set 34 (File Handling) Output of Java program | Set 28 Output of Java Programs | Set 48 (Static keyword) Runtime Errors Output of Java Programs | Set 12 Output of Java program | Set 5 Output of Java Program | Set 20 (Inheritance)
[ { "code": null, "e": 25971, "s": 25943, "text": "\n18 Sep, 2020" }, { "code": null, "e": 26048, "s": 25971, "text": "Prerequisite : TuplesNote: Output of all these programs is tested on Python3" }, { "code": null, "e": 26102, "s": 26048, "text": "1. What will be the output of the following program ?" }, { "code": "tuple = (1, 2, 3, 4)tuple.append( (5, 6, 7) )print(len(my_tuple))", "e": 26168, "s": 26102, "text": null }, { "code": null, "e": 26177, "s": 26168, "text": "Options:" }, { "code": null, "e": 26186, "s": 26177, "text": "125Error" }, { "code": null, "e": 26188, "s": 26186, "text": "1" }, { "code": null, "e": 26190, "s": 26188, "text": "2" }, { "code": null, "e": 26192, "s": 26190, "text": "5" }, { "code": null, "e": 26198, "s": 26192, "text": "Error" }, { "code": null, "e": 26206, "s": 26198, "text": "Output:" }, { "code": null, "e": 26215, "s": 26206, "text": "4. Error" }, { "code": null, "e": 26326, "s": 26215, "text": "Explanation: In this case an exception will be thrown as tuples are immutable and don’t have an append method." }, { "code": null, "e": 26380, "s": 26326, "text": "2. What will be the output of the following program ?" }, { "code": "tuple = {}tuple[(1,2,4)] = 8tuple[(4,2,1)] = 10tuple[(1,2)] = 12_sum = 0for k in tuple: _sum += tuple[k]print(len(tuple) + _sum)", "e": 26512, "s": 26380, "text": null }, { "code": null, "e": 26521, "s": 26512, "text": "Options:" }, { "code": null, "e": 26530, "s": 26521, "text": "34123133" }, { "code": null, "e": 26533, "s": 26530, "text": "34" }, { "code": null, "e": 26536, "s": 26533, "text": "12" }, { "code": null, "e": 26539, "s": 26536, "text": "31" }, { "code": null, "e": 26542, "s": 26539, "text": "33" }, { "code": null, "e": 26550, "s": 26542, "text": "Output:" }, { "code": null, "e": 26556, "s": 26550, "text": "4. 33" }, { "code": null, "e": 26743, "s": 26556, "text": "Explanation: Tuples can be used for keys into dictionary. The tuples can have mixed lengths and the order of the items in the tuple is considered when comparing the equality of the keys." }, { "code": null, "e": 26797, "s": 26743, "text": "3. What will be the output of the following program ?" }, { "code": "tuple1 = (1, 2, 4, 3)tuple2 = (1, 2, 3, 4)print(tuple1 < tuple2)", "e": 26862, "s": 26797, "text": null }, { "code": null, "e": 26871, "s": 26862, "text": "Options:" }, { "code": null, "e": 26896, "s": 26871, "text": "ErrorTrueFalseUnexpected" }, { "code": null, "e": 26902, "s": 26896, "text": "Error" }, { "code": null, "e": 26907, "s": 26902, "text": "True" }, { "code": null, "e": 26913, "s": 26907, "text": "False" }, { "code": null, "e": 26924, "s": 26913, "text": "Unexpected" }, { "code": null, "e": 26932, "s": 26924, "text": "Output:" }, { "code": null, "e": 26941, "s": 26932, "text": "3. False" }, { "code": null, "e": 27057, "s": 26941, "text": "Explanation: In this case elements will be compared one by one. So, when it compares 4 with 3 it will return False." }, { "code": null, "e": 27111, "s": 27057, "text": "4. What will be the output of the following program ?" }, { "code": "tuple = (1, 2, 3)print(2 * tuple)", "e": 27145, "s": 27111, "text": null }, { "code": null, "e": 27154, "s": 27145, "text": "Options:" }, { "code": null, "e": 27205, "s": 27154, "text": "(1, 2, 3, 1, 2, 3)(1, 2, 3, 4, 5, 6)(3, 6, 9)Error" }, { "code": null, "e": 27224, "s": 27205, "text": "(1, 2, 3, 1, 2, 3)" }, { "code": null, "e": 27243, "s": 27224, "text": "(1, 2, 3, 4, 5, 6)" }, { "code": null, "e": 27253, "s": 27243, "text": "(3, 6, 9)" }, { "code": null, "e": 27259, "s": 27253, "text": "Error" }, { "code": null, "e": 27267, "s": 27259, "text": "Output:" }, { "code": null, "e": 27289, "s": 27267, "text": "1. (1, 2, 3, 1, 2, 3)" }, { "code": null, "e": 27346, "s": 27289, "text": "Explanation: ‘*’ operator is used to concatenate tuples." }, { "code": null, "e": 27400, "s": 27346, "text": "5. What will be the output of the following program ?" }, { "code": "tuple=(\"Check\")*3print(tuple)", "e": 27430, "s": 27400, "text": null }, { "code": null, "e": 27439, "s": 27430, "text": "Options:" }, { "code": null, "e": 27485, "s": 27439, "text": "Unexpected(3Check)CheckCheckCheckSyntax Error" }, { "code": null, "e": 27496, "s": 27485, "text": "Unexpected" }, { "code": null, "e": 27505, "s": 27496, "text": "(3Check)" }, { "code": null, "e": 27521, "s": 27505, "text": "CheckCheckCheck" }, { "code": null, "e": 27534, "s": 27521, "text": "Syntax Error" }, { "code": null, "e": 27542, "s": 27534, "text": "Output:" }, { "code": null, "e": 27561, "s": 27542, "text": "3. CheckCheckCheck" }, { "code": null, "e": 27670, "s": 27561, "text": "Explanation: Here “Check” will be treated as is a string not a tuple as there is no comma after the element." }, { "code": null, "e": 27684, "s": 27670, "text": "Python-Output" }, { "code": null, "e": 27697, "s": 27684, "text": "python-tuple" }, { "code": null, "e": 27712, "s": 27697, "text": "Program Output" }, { "code": null, "e": 27810, "s": 27712, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27857, "s": 27810, "text": "Output of Java programs | Set 13 (Collections)" }, { "code": null, "e": 27888, "s": 27857, "text": "Output of Java Program | Set 3" }, { "code": null, "e": 27929, "s": 27888, "text": "Different ways to copy a string in C/C++" }, { "code": null, "e": 27977, "s": 27929, "text": "Output of C++ programs | Set 34 (File Handling)" }, { "code": null, "e": 28009, "s": 27977, "text": "Output of Java program | Set 28" }, { "code": null, "e": 28059, "s": 28009, "text": "Output of Java Programs | Set 48 (Static keyword)" }, { "code": null, "e": 28074, "s": 28059, "text": "Runtime Errors" }, { "code": null, "e": 28107, "s": 28074, "text": "Output of Java Programs | Set 12" }, { "code": null, "e": 28138, "s": 28107, "text": "Output of Java program | Set 5" } ]
TypeScript - Array shift()
shift()method removes the first element from an array and returns that element. array.shift(); Returns the removed single value of the array. var arr = [10, 1, 2, 3].shift(); console.log("Shifted value is : " + arr ); On compiling, it will generate the same code in JavaScript. Its output is as follows − Shifted value is : 10 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": 2128, "s": 2048, "text": "shift()method removes the first element from an array and returns that element." }, { "code": null, "e": 2144, "s": 2128, "text": "array.shift();\n" }, { "code": null, "e": 2191, "s": 2144, "text": "Returns the removed single value of the array." }, { "code": null, "e": 2269, "s": 2191, "text": "var arr = [10, 1, 2, 3].shift(); \nconsole.log(\"Shifted value is : \" + arr );\n" }, { "code": null, "e": 2329, "s": 2269, "text": "On compiling, it will generate the same code in JavaScript." }, { "code": null, "e": 2356, "s": 2329, "text": "Its output is as follows −" }, { "code": null, "e": 2379, "s": 2356, "text": "Shifted value is : 10\n" }, { "code": null, "e": 2412, "s": 2379, "text": "\n 45 Lectures \n 4 hours \n" }, { "code": null, "e": 2426, "s": 2412, "text": " Antonio Papa" }, { "code": null, "e": 2459, "s": 2426, "text": "\n 41 Lectures \n 7 hours \n" }, { "code": null, "e": 2473, "s": 2459, "text": " Haider Malik" }, { "code": null, "e": 2508, "s": 2473, "text": "\n 60 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2528, "s": 2508, "text": " Skillbakerystudios" }, { "code": null, "e": 2561, "s": 2528, "text": "\n 77 Lectures \n 8 hours \n" }, { "code": null, "e": 2575, "s": 2561, "text": " Sean Bradley" }, { "code": null, "e": 2610, "s": 2575, "text": "\n 77 Lectures \n 3.5 hours \n" }, { "code": null, "e": 2626, "s": 2610, "text": " TELCOMA Global" }, { "code": null, "e": 2659, "s": 2626, "text": "\n 19 Lectures \n 3 hours \n" }, { "code": null, "e": 2679, "s": 2659, "text": " Christopher Frewin" }, { "code": null, "e": 2686, "s": 2679, "text": " Print" }, { "code": null, "e": 2697, "s": 2686, "text": " Add Notes" } ]
AbstractQueue in Java with Examples - GeeksforGeeks
10 Feb, 2022 The AbstractQueue class in Java is a part of the Java Collection Framework and implements the Collection interface and the AbstractCollection class. It provides skeletal implementations of some Queue operations. The implementations in this class are appropriate when the base implementation does not allow null elements. Methods add, remove, and element are based on offer, poll, and peek, respectively, but throw exceptions instead of indicating failure via false or null returns. Class Hierarchy: java.lang.Object ↳ java.util.AbstractCollection<E> ↳ Class AbstractQueue<E> This class implements Iterable<E>, Collection<E>, Queue<E> interfaces and extends AbstractCollection Declaration: public abstract class AbstractQueue<E> extends AbstractCollection<E> implements Queue<E> E – Type of element maintained by the Collection Framework class or interface. Since AbstractQueue is an abstract class, it’s implementation is provided by its sub-classes. Below shows the list of classes that can provide the implementation. To create it, we need to it from java.util.AbstractQueue. protected AbstractQueue(): The default constructor, but being abstract, it doesn’t allow to create an AbstractQueue object. The implementation should be provided by one of its subclasses like ArrayBlockingQueue, ConcurrentLinkedQueue, DelayQueue, LinkedBlockingDeque, LinkedBlockingQueue, LinkedTransferQueue, PriorityBlockingQueue, PriorityQueue, SynchronousQueue. AbstractQueue<E> objName = new ArrayBlockingQueue<E>(); Below is a sample program to illustrate AbstractQueue in Java: Java // Java code to illustrate AbstractQueue import java.util.*;import java.util.concurrent.LinkedBlockingQueue; public class AbstractQueueExample { public static void main(String[] argv) throws Exception { // Creating object of AbstractQueue<Integer> AbstractQueue<Integer> AQ = new LinkedBlockingQueue<Integer>(); // Adding elements to the Queue AQ.add(10); AQ.add(20); AQ.add(30); AQ.add(40); AQ.add(50); // print the queue contents to the console System.out.println("AbstractQueue contains: " + AQ); }} AbstractQueue contains: [10, 20, 30, 40, 50] 1. Adding Elements To add elements into the AbstractQueue, it provides two methods. The add(E e) method inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions. It returns true upon success and throws an IllegalStateException if no space is currently available. The addAll(E e) method adds all the elements in the specified collection to this queue. Java // Java program to illustrate the// adding elements to the AbstractQueue import java.util.*;import java.util.concurrent.LinkedBlockingQueue; public class AddingElementsExample { public static void main(String[] argv) throws Exception { // Since AbstractQueue is an abstract class // create object using LinkedBlockingQueue AbstractQueue<Integer> AQ1 = new LinkedBlockingQueue<Integer>(); // Populating AQ AQ1.add(10); AQ1.add(20); AQ1.add(30); AQ1.add(40); AQ1.add(50); // print AQ System.out.println("AbstractQueue contains : " + AQ1); // Since AbstractQueue is an abstract class // create object using LinkedBlockingQueue AbstractQueue<Integer> AQ2 = new LinkedBlockingQueue<Integer>(); // print AQ2 initially System.out.println("AbstractQueue2 initially contains : " + AQ2); // adds elements of AQ1 in AQ2 AQ2.addAll(AQ1); System.out.println( "AbstractQueue1 after addition contains : " + AQ2); }} AbstractQueue contains : [10, 20, 30, 40, 50] AbstractQueue2 initially contains : [] AbstractQueue1 after addition contains : [10, 20, 30, 40, 50] 2. Remove the Elements To remove the elements from AbstractQueue, it provides remove() and clear() methods. The remove() method returns and removes the head of this queue. The clear() method removes all the elements from this queue. The queue will be empty after this call returns. Java // Java program to illustrate the// removal of elements from AbstractQueue import java.util.*;import java.util.concurrent.LinkedBlockingQueue; public class RemovingElementsExample { public static void main(String[] argv) throws Exception { // Since AbstractQueue is an abstract class // create object using LinkedBlockingQueue AbstractQueue<Integer> AQ1 = new LinkedBlockingQueue<Integer>(); // Add elements using add method AQ1.add(10); AQ1.add(20); AQ1.add(30); AQ1.add(40); AQ1.add(50); // print the queue contents to the console System.out.println("AbstractQueue1 contains : " + AQ1); // Retrieves the head int head = AQ1.remove(); // print the head element to the console System.out.println("head : " + head); // print the modified queue System.out.println("AbstractQueue1 after removal of head : " + AQ1); // remove all the elements AQ1.clear(); // print the modified queue System.out.println("AbstractQueue1 : " + AQ1); }} AbstractQueue1 contains : [10, 20, 30, 40, 50] head : 10 AbstractQueue1 after removal of head : [20, 30, 40, 50] AbstractQueue1 : [] 3. Accessing the Elements The element() method of AbstractQueue retrieves but does not remove, the head of this queue. Java // Java program to illustrate the// accessing element from AbstractQueue import java.util.*;import java.util.concurrent.LinkedBlockingQueue; public class AccessingElementExample { public static void main(String[] argv) throws Exception { // Since AbstractQueue is an abstract class // create object using LinkedBlockingQueue AbstractQueue<Integer> AQ1 = new LinkedBlockingQueue<Integer>(); // Populating AQ1 using add method AQ1.add(10); AQ1.add(20); AQ1.add(30); AQ1.add(40); AQ1.add(50); // print AQ to the console System.out.println("AbstractQueue1 contains : " + AQ1); // access the head element System.out.println("head : " + AQ1.element()); }} AbstractQueue1 contains : [10, 20, 30, 40, 50] head : 10 METHOD DESCRIPTION METHOD DESCRIPTION METHOD DESCRIPTION METHOD DESCRIPTION METHOD DESCRIPTION Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/AbstractQueue.html Ganeshchowdharysadanala sagar0719kumar Java - util package java-AbstractQueue Java-Collections Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples How to iterate any Map in Java Interfaces in Java Initialize an ArrayList in Java ArrayList in Java Multidimensional Arrays in Java Singleton Class in Java LinkedList in Java Collections in Java
[ { "code": null, "e": 24086, "s": 24058, "text": "\n10 Feb, 2022" }, { "code": null, "e": 24586, "s": 24086, "text": "The AbstractQueue class in Java is a part of the Java Collection Framework and implements the Collection interface and the AbstractCollection class. It provides skeletal implementations of some Queue operations. The implementations in this class are appropriate when the base implementation does not allow null elements. Methods add, remove, and element are based on offer, poll, and peek, respectively, but throw exceptions instead of indicating failure via false or null returns. Class Hierarchy: " }, { "code": null, "e": 24667, "s": 24586, "text": "java.lang.Object\n ↳ java.util.AbstractCollection<E>\n ↳ Class AbstractQueue<E>" }, { "code": null, "e": 24768, "s": 24667, "text": "This class implements Iterable<E>, Collection<E>, Queue<E> interfaces and extends AbstractCollection" }, { "code": null, "e": 24782, "s": 24768, "text": "Declaration: " }, { "code": null, "e": 24873, "s": 24782, "text": "public abstract class AbstractQueue<E> extends AbstractCollection<E> implements Queue<E> " }, { "code": null, "e": 24952, "s": 24873, "text": "E – Type of element maintained by the Collection Framework class or interface." }, { "code": null, "e": 25173, "s": 24952, "text": "Since AbstractQueue is an abstract class, it’s implementation is provided by its sub-classes. Below shows the list of classes that can provide the implementation. To create it, we need to it from java.util.AbstractQueue." }, { "code": null, "e": 25539, "s": 25173, "text": "protected AbstractQueue(): The default constructor, but being abstract, it doesn’t allow to create an AbstractQueue object. The implementation should be provided by one of its subclasses like ArrayBlockingQueue, ConcurrentLinkedQueue, DelayQueue, LinkedBlockingDeque, LinkedBlockingQueue, LinkedTransferQueue, PriorityBlockingQueue, PriorityQueue, SynchronousQueue." }, { "code": null, "e": 25595, "s": 25539, "text": "AbstractQueue<E> objName = new ArrayBlockingQueue<E>();" }, { "code": null, "e": 25661, "s": 25595, "text": " Below is a sample program to illustrate AbstractQueue in Java: " }, { "code": null, "e": 25666, "s": 25661, "text": "Java" }, { "code": "// Java code to illustrate AbstractQueue import java.util.*;import java.util.concurrent.LinkedBlockingQueue; public class AbstractQueueExample { public static void main(String[] argv) throws Exception { // Creating object of AbstractQueue<Integer> AbstractQueue<Integer> AQ = new LinkedBlockingQueue<Integer>(); // Adding elements to the Queue AQ.add(10); AQ.add(20); AQ.add(30); AQ.add(40); AQ.add(50); // print the queue contents to the console System.out.println(\"AbstractQueue contains: \" + AQ); }}", "e": 26251, "s": 25666, "text": null }, { "code": null, "e": 26296, "s": 26251, "text": "AbstractQueue contains: [10, 20, 30, 40, 50]" }, { "code": null, "e": 26317, "s": 26298, "text": "1. Adding Elements" }, { "code": null, "e": 26717, "s": 26317, "text": "To add elements into the AbstractQueue, it provides two methods. The add(E e) method inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions. It returns true upon success and throws an IllegalStateException if no space is currently available. The addAll(E e) method adds all the elements in the specified collection to this queue." }, { "code": null, "e": 26722, "s": 26717, "text": "Java" }, { "code": "// Java program to illustrate the// adding elements to the AbstractQueue import java.util.*;import java.util.concurrent.LinkedBlockingQueue; public class AddingElementsExample { public static void main(String[] argv) throws Exception { // Since AbstractQueue is an abstract class // create object using LinkedBlockingQueue AbstractQueue<Integer> AQ1 = new LinkedBlockingQueue<Integer>(); // Populating AQ AQ1.add(10); AQ1.add(20); AQ1.add(30); AQ1.add(40); AQ1.add(50); // print AQ System.out.println(\"AbstractQueue contains : \" + AQ1); // Since AbstractQueue is an abstract class // create object using LinkedBlockingQueue AbstractQueue<Integer> AQ2 = new LinkedBlockingQueue<Integer>(); // print AQ2 initially System.out.println(\"AbstractQueue2 initially contains : \" + AQ2); // adds elements of AQ1 in AQ2 AQ2.addAll(AQ1); System.out.println( \"AbstractQueue1 after addition contains : \" + AQ2); }}", "e": 27798, "s": 26722, "text": null }, { "code": null, "e": 27952, "s": 27805, "text": "AbstractQueue contains : [10, 20, 30, 40, 50]\nAbstractQueue2 initially contains : []\nAbstractQueue1 after addition contains : [10, 20, 30, 40, 50]" }, { "code": null, "e": 27976, "s": 27952, "text": "2. Remove the Elements " }, { "code": null, "e": 28063, "s": 27978, "text": "To remove the elements from AbstractQueue, it provides remove() and clear() methods." }, { "code": null, "e": 28129, "s": 28065, "text": "The remove() method returns and removes the head of this queue." }, { "code": null, "e": 28239, "s": 28129, "text": "The clear() method removes all the elements from this queue. The queue will be empty after this call returns." }, { "code": null, "e": 28246, "s": 28241, "text": "Java" }, { "code": "// Java program to illustrate the// removal of elements from AbstractQueue import java.util.*;import java.util.concurrent.LinkedBlockingQueue; public class RemovingElementsExample { public static void main(String[] argv) throws Exception { // Since AbstractQueue is an abstract class // create object using LinkedBlockingQueue AbstractQueue<Integer> AQ1 = new LinkedBlockingQueue<Integer>(); // Add elements using add method AQ1.add(10); AQ1.add(20); AQ1.add(30); AQ1.add(40); AQ1.add(50); // print the queue contents to the console System.out.println(\"AbstractQueue1 contains : \" + AQ1); // Retrieves the head int head = AQ1.remove(); // print the head element to the console System.out.println(\"head : \" + head); // print the modified queue System.out.println(\"AbstractQueue1 after removal of head : \" + AQ1); // remove all the elements AQ1.clear(); // print the modified queue System.out.println(\"AbstractQueue1 : \" + AQ1); }}", "e": 29339, "s": 28246, "text": null }, { "code": null, "e": 29479, "s": 29346, "text": "AbstractQueue1 contains : [10, 20, 30, 40, 50]\nhead : 10\nAbstractQueue1 after removal of head : [20, 30, 40, 50]\nAbstractQueue1 : []" }, { "code": null, "e": 29505, "s": 29479, "text": "3. Accessing the Elements" }, { "code": null, "e": 29600, "s": 29507, "text": "The element() method of AbstractQueue retrieves but does not remove, the head of this queue." }, { "code": null, "e": 29607, "s": 29602, "text": "Java" }, { "code": "// Java program to illustrate the// accessing element from AbstractQueue import java.util.*;import java.util.concurrent.LinkedBlockingQueue; public class AccessingElementExample { public static void main(String[] argv) throws Exception { // Since AbstractQueue is an abstract class // create object using LinkedBlockingQueue AbstractQueue<Integer> AQ1 = new LinkedBlockingQueue<Integer>(); // Populating AQ1 using add method AQ1.add(10); AQ1.add(20); AQ1.add(30); AQ1.add(40); AQ1.add(50); // print AQ to the console System.out.println(\"AbstractQueue1 contains : \" + AQ1); // access the head element System.out.println(\"head : \" + AQ1.element()); }}", "e": 30361, "s": 29607, "text": null }, { "code": null, "e": 30425, "s": 30368, "text": "AbstractQueue1 contains : [10, 20, 30, 40, 50]\nhead : 10" }, { "code": null, "e": 30432, "s": 30425, "text": "METHOD" }, { "code": null, "e": 30444, "s": 30432, "text": "DESCRIPTION" }, { "code": null, "e": 30451, "s": 30444, "text": "METHOD" }, { "code": null, "e": 30463, "s": 30451, "text": "DESCRIPTION" }, { "code": null, "e": 30470, "s": 30463, "text": "METHOD" }, { "code": null, "e": 30482, "s": 30470, "text": "DESCRIPTION" }, { "code": null, "e": 30489, "s": 30482, "text": "METHOD" }, { "code": null, "e": 30501, "s": 30489, "text": "DESCRIPTION" }, { "code": null, "e": 30508, "s": 30501, "text": "METHOD" }, { "code": null, "e": 30520, "s": 30508, "text": "DESCRIPTION" }, { "code": null, "e": 30621, "s": 30520, "text": "Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/AbstractQueue.html" }, { "code": null, "e": 30647, "s": 30623, "text": "Ganeshchowdharysadanala" }, { "code": null, "e": 30662, "s": 30647, "text": "sagar0719kumar" }, { "code": null, "e": 30682, "s": 30662, "text": "Java - util package" }, { "code": null, "e": 30701, "s": 30682, "text": "java-AbstractQueue" }, { "code": null, "e": 30718, "s": 30701, "text": "Java-Collections" }, { "code": null, "e": 30723, "s": 30718, "text": "Java" }, { "code": null, "e": 30728, "s": 30723, "text": "Java" }, { "code": null, "e": 30745, "s": 30728, "text": "Java-Collections" }, { "code": null, "e": 30843, "s": 30745, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30852, "s": 30843, "text": "Comments" }, { "code": null, "e": 30865, "s": 30852, "text": "Old Comments" }, { "code": null, "e": 30916, "s": 30865, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 30946, "s": 30916, "text": "HashMap in Java with Examples" }, { "code": null, "e": 30977, "s": 30946, "text": "How to iterate any Map in Java" }, { "code": null, "e": 30996, "s": 30977, "text": "Interfaces in Java" }, { "code": null, "e": 31028, "s": 30996, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 31046, "s": 31028, "text": "ArrayList in Java" }, { "code": null, "e": 31078, "s": 31046, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 31102, "s": 31078, "text": "Singleton Class in Java" }, { "code": null, "e": 31121, "s": 31102, "text": "LinkedList in Java" } ]
DateTime.DaysInMonth() Method in C#
The DateTime.DaysInMonth() method in C# is used to return the number of days in the specified month and year. For example, 31 for month value 1 i.e. January. Following is the syntax − public static int DaysInMonth (int year, int month); Let us now see an example to implement the DateTime.DaysInMonth() method − using System; public class Demo { public static void Main() { DateTime date1 = new DateTime(2019, 08, 20, 6, 20, 40); DateTime date2 = new DateTime(2019, 06, 20, 6, 20, 40); Console.WriteLine("DateTime 1 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", date1); Console.WriteLine("Days in DateTime 1 month = "+DateTime.DaysInMonth(2019, 08)); Console.WriteLine("\nDateTime 2 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", date2); Console.WriteLine("Days in DateTime 2 month = "+DateTime.DaysInMonth(2019, 06)); int res = date1.CompareTo(date2); // returns >0 since date1 is later than date2 Console.WriteLine("\nReturn Value (comparison) = "+res); } } This will produce the following output − DateTime 1 = 20 August 2019, 06:20:40 Days in DateTime 1 month = 31 DateTime 2 = 20 June 2019, 06:20:40 Days in DateTime 2 month = 30 Return Value (comparison) = 1 Let us now see another example to implement the DateTime.DaysInMonth() method − using System; public class Demo { public static void Main(){ int year1 = 2019, year2 = 2016; int FebMonth = 2; Console.WriteLine("Days in 2019, Feb month = "+DateTime.DaysInMonth(year1, FebMonth)); Console.WriteLine("Days in 2016, Feb month = "+DateTime.DaysInMonth(year2, FebMonth)); } } This will produce the following output − Days in 2019, Feb month = 28 Days in 2016, Feb month = 29
[ { "code": null, "e": 1220, "s": 1062, "text": "The DateTime.DaysInMonth() method in C# is used to return the number of days in the specified month and year. For example, 31 for month value 1 i.e. January." }, { "code": null, "e": 1246, "s": 1220, "text": "Following is the syntax −" }, { "code": null, "e": 1299, "s": 1246, "text": "public static int DaysInMonth (int year, int month);" }, { "code": null, "e": 1374, "s": 1299, "text": "Let us now see an example to implement the DateTime.DaysInMonth() method −" }, { "code": null, "e": 2069, "s": 1374, "text": "using System;\npublic class Demo {\n public static void Main() {\n DateTime date1 = new DateTime(2019, 08, 20, 6, 20, 40);\n DateTime date2 = new DateTime(2019, 06, 20, 6, 20, 40);\n Console.WriteLine(\"DateTime 1 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} \", date1);\n Console.WriteLine(\"Days in DateTime 1 month = \"+DateTime.DaysInMonth(2019, 08));\n Console.WriteLine(\"\\nDateTime 2 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} \", date2);\n Console.WriteLine(\"Days in DateTime 2 month = \"+DateTime.DaysInMonth(2019, 06));\n int res = date1.CompareTo(date2);\n // returns >0 since date1 is later than date2\n Console.WriteLine(\"\\nReturn Value (comparison) = \"+res);\n }\n}" }, { "code": null, "e": 2110, "s": 2069, "text": "This will produce the following output −" }, { "code": null, "e": 2274, "s": 2110, "text": "DateTime 1 = 20 August 2019, 06:20:40\nDays in DateTime 1 month = 31\nDateTime 2 = 20 June 2019, 06:20:40\nDays in DateTime 2 month = 30\nReturn Value (comparison) = 1" }, { "code": null, "e": 2354, "s": 2274, "text": "Let us now see another example to implement the DateTime.DaysInMonth() method −" }, { "code": null, "e": 2673, "s": 2354, "text": "using System;\npublic class Demo {\n public static void Main(){\n int year1 = 2019, year2 = 2016;\n int FebMonth = 2;\n Console.WriteLine(\"Days in 2019, Feb month = \"+DateTime.DaysInMonth(year1, FebMonth));\n Console.WriteLine(\"Days in 2016, Feb month = \"+DateTime.DaysInMonth(year2, FebMonth));\n }\n}" }, { "code": null, "e": 2714, "s": 2673, "text": "This will produce the following output −" }, { "code": null, "e": 2772, "s": 2714, "text": "Days in 2019, Feb month = 28\nDays in 2016, Feb month = 29" } ]
How to count the number of tables in a MySQL database?
To count the total number of tables, use the concept of count(*) with table_schema. First, to check how many tables are present in our database “business”, we need to use the ‘show’ command. mysql> show tables; The following is the output that displays all the tables in the database "business". +--------------------------+ | Tables_in_business | +--------------------------+ | addcheckconstraintdemo | | addcolumntable | | addconstraintdemo | | addnotnulldemo | | alphademo | | autoincrement | | autoincrementtable | | backticksymbol | | bookindexes | | chardemo | | checkdemo | | clonestudent | | columnexistdemo | | columnvaluenulldemo | | commaseperatedemo | | currentdatetime | | dateadddemo | | deletedemo | | deleterecord | | demo | | demo1 | | demoascii | | demoauto | | demobcrypt | | demoemptyandnull | | demoint | | demoonreplace | | demoschema | | demowhere | | distcountdemo | | distinctdemo | | distinctdemo1 | | duplicatebookindexes | | duplicatefound | | employeerecords | | employeetable | | escapedeom | | existsrowdemo | | findandreplacedemo | | firsttable | | foreigntable | | foreigntabledemo | | functionindexdemo | | functiontriggersdemo | | groupconcatenatedemo | | groupdemo | | groupdemo1 | | groupt_concatdemo | | ifelsedemo | | imagedemo | | incasesensdemo | | indexingdemo | | int1demo | | intdemo | | keydemo | | latandlangdemo | | limitoffsetdemo | | milliseconddemo | | modifycolumnnamedemo | | modifydatatype | | moneydemo | | moviecollection | | multipleindexdemo | | multiplerecordwithvalues | | myisamtoinnodbdemo | | mytable | | mytable1 | | newstudent | | nextpreviousdemo | | nonasciidemo | | nthrecorddemo | | nulldemo | | nullwithselect | | numbercolumndemo | | ondemo | | originaltable | | pasthistory | | presenthistory | | primarytable | | primarytable1 | | primarytabledemo | | qutesdemo | | rowcountdemo | | rownumberdemo | | rowstranspose | | rowstransposedemo | | saveintotextfile | | saveoutputintext | | secondtable | | sequencedemo | | singlequotesdemo | | smallintdemo | | sortingvarchardemo | | sourcetable | | spacecolumn | | student | | studentrecordwithmyisam | | studenttable | | table1 | | table2 | | tabledemo | | tbldemotrail | | tblf | | tblfirst | | tblfunctiontrigger | | tblifdemo | | tblp | | tblselectdemo | | tblstudent | | tbluni | | tblupdatelimit | | textdemo | | texturl | | timestampdemo | | trailingandleadingdemo | | transcationdemo | | triggedemo | | trigger1 | | trigger2demo | | trimdemo | | trimdemo2 | | uniqueconstdemo | | uniquedemo | | unsigneddemo | | updtable | | usernameandpassworddemo | | varchardemo | | varchardemo1 | | varchardemo2 | | varcharurl | | whereconditon | | xmldemo | +--------------------------+ 132 rows in set (0.01 sec) In the above, we have 132 tables in the database business. To check the count of tables. mysql> SELECT count(*) AS TOTALNUMBEROFTABLES -> FROM INFORMATION_SCHEMA.TABLES -> WHERE TABLE_SCHEMA = 'business'; The following output gives the count of all the tables. +---------------------+ | TOTALNUMBEROFTABLES | +---------------------+ | 132 | +---------------------+ 1 row in set (0.01 sec)
[ { "code": null, "e": 1253, "s": 1062, "text": "To count the total number of tables, use the concept of count(*) with table_schema. First, to check how many tables are present in our database “business”, we need to use the ‘show’ command." }, { "code": null, "e": 1273, "s": 1253, "text": "mysql> show tables;" }, { "code": null, "e": 1358, "s": 1273, "text": "The following is the output that displays all the tables in the database \"business\"." }, { "code": null, "e": 5330, "s": 1358, "text": "+--------------------------+\n| Tables_in_business |\n+--------------------------+\n| addcheckconstraintdemo |\n| addcolumntable |\n| addconstraintdemo |\n| addnotnulldemo |\n| alphademo |\n| autoincrement |\n| autoincrementtable |\n| backticksymbol |\n| bookindexes |\n| chardemo |\n| checkdemo |\n| clonestudent |\n| columnexistdemo |\n| columnvaluenulldemo |\n| commaseperatedemo |\n| currentdatetime |\n| dateadddemo |\n| deletedemo |\n| deleterecord |\n| demo |\n| demo1 |\n| demoascii |\n| demoauto |\n| demobcrypt |\n| demoemptyandnull |\n| demoint |\n| demoonreplace |\n| demoschema |\n| demowhere |\n| distcountdemo |\n| distinctdemo |\n| distinctdemo1 |\n| duplicatebookindexes |\n| duplicatefound |\n| employeerecords |\n| employeetable |\n| escapedeom |\n| existsrowdemo |\n| findandreplacedemo |\n| firsttable |\n| foreigntable |\n| foreigntabledemo |\n| functionindexdemo |\n| functiontriggersdemo |\n| groupconcatenatedemo |\n| groupdemo |\n| groupdemo1 |\n| groupt_concatdemo |\n| ifelsedemo |\n| imagedemo |\n| incasesensdemo |\n| indexingdemo |\n| int1demo |\n| intdemo |\n| keydemo |\n| latandlangdemo |\n| limitoffsetdemo |\n| milliseconddemo |\n| modifycolumnnamedemo |\n| modifydatatype |\n| moneydemo |\n| moviecollection |\n| multipleindexdemo |\n| multiplerecordwithvalues |\n| myisamtoinnodbdemo |\n| mytable |\n| mytable1 |\n| newstudent |\n| nextpreviousdemo |\n| nonasciidemo |\n| nthrecorddemo |\n| nulldemo |\n| nullwithselect |\n| numbercolumndemo |\n| ondemo |\n| originaltable |\n| pasthistory |\n| presenthistory |\n| primarytable |\n| primarytable1 |\n| primarytabledemo |\n| qutesdemo |\n| rowcountdemo |\n| rownumberdemo |\n| rowstranspose |\n| rowstransposedemo |\n| saveintotextfile |\n| saveoutputintext |\n| secondtable |\n| sequencedemo |\n| singlequotesdemo |\n| smallintdemo |\n| sortingvarchardemo |\n| sourcetable |\n| spacecolumn |\n| student |\n| studentrecordwithmyisam |\n| studenttable |\n| table1 |\n| table2 |\n| tabledemo |\n| tbldemotrail |\n| tblf |\n| tblfirst |\n| tblfunctiontrigger |\n| tblifdemo |\n| tblp |\n| tblselectdemo |\n| tblstudent |\n| tbluni |\n| tblupdatelimit |\n| textdemo |\n| texturl |\n| timestampdemo |\n| trailingandleadingdemo |\n| transcationdemo |\n| triggedemo |\n| trigger1 |\n| trigger2demo |\n| trimdemo |\n| trimdemo2 |\n| uniqueconstdemo |\n| uniquedemo |\n| unsigneddemo |\n| updtable |\n| usernameandpassworddemo |\n| varchardemo |\n| varchardemo1 |\n| varchardemo2 |\n| varcharurl |\n| whereconditon |\n| xmldemo |\n+--------------------------+\n132 rows in set (0.01 sec)\n" }, { "code": null, "e": 5389, "s": 5330, "text": "In the above, we have 132 tables in the database business." }, { "code": null, "e": 5419, "s": 5389, "text": "To check the count of tables." }, { "code": null, "e": 5541, "s": 5419, "text": "mysql> SELECT count(*) AS TOTALNUMBEROFTABLES\n -> FROM INFORMATION_SCHEMA.TABLES\n -> WHERE TABLE_SCHEMA = 'business';" }, { "code": null, "e": 5597, "s": 5541, "text": "The following output gives the count of all the tables." }, { "code": null, "e": 5742, "s": 5597, "text": "+---------------------+\n| TOTALNUMBEROFTABLES |\n+---------------------+\n| 132 |\n+---------------------+\n1 row in set (0.01 sec)\n" } ]
BigInteger Class in C#
Use the BigInteger to handle big numbers in C#. The assembly to add for BigInteger is System. Numerics. In c# Big integer is found in System.Numerics.BigInteger. The syntax of BigInteger − [SerializableAttribute] public struct BigInteger : IFormattable, IComparable, IComparable<BigInteger>, IEquatable<BigInteger> Let us see an example code snippet − BigInteger num = BigInteger.Multiply(Int64.MaxValue, Int64.MaxValue); You can create BigInteger like this − BigInteger num = new BigInteger(double.MaxValue); The following are some of its constructors −
[ { "code": null, "e": 1166, "s": 1062, "text": "Use the BigInteger to handle big numbers in C#. The assembly to add for BigInteger is System. Numerics." }, { "code": null, "e": 1224, "s": 1166, "text": "In c# Big integer is found in System.Numerics.BigInteger." }, { "code": null, "e": 1251, "s": 1224, "text": "The syntax of BigInteger −" }, { "code": null, "e": 1377, "s": 1251, "text": "[SerializableAttribute]\npublic struct BigInteger : IFormattable, IComparable, IComparable<BigInteger>, IEquatable<BigInteger>" }, { "code": null, "e": 1414, "s": 1377, "text": "Let us see an example code snippet −" }, { "code": null, "e": 1484, "s": 1414, "text": "BigInteger num = BigInteger.Multiply(Int64.MaxValue, Int64.MaxValue);" }, { "code": null, "e": 1522, "s": 1484, "text": "You can create BigInteger like this −" }, { "code": null, "e": 1572, "s": 1522, "text": "BigInteger num = new BigInteger(double.MaxValue);" }, { "code": null, "e": 1617, "s": 1572, "text": "The following are some of its constructors −" } ]
How to find the median of all columns in an R data frame?
The median is the value in a vector that divide the data into two equal parts. To find the median of all columns, we can use apply function. For example, if we have a data frame df that contains numerical columns then the median for all the columns can be calculated as apply(df,2,median). Consider the below data frame − Live Demo set.seed(7) x1<-rnorm(20,5,1) x2<-rnorm(20,100,5) x3<-rnorm(20,100,2) x4<-rnorm(20,25,3) x5<-rnorm(20,30,4) df1<-data.frame(x1,x2,x3,x4,x5) df1 x1 x2 x3 x4 x5 1 7.287247 104.19875 102.43710 25.22911 31.37034 2 3.803228 103.52671 98.60137 25.47747 30.01699 3 4.305707 106.52982 99.42913 26.63102 30.11688 4 4.587707 93.06002 97.37689 27.11442 28.42631 5 4.029327 106.36458 99.21798 25.95691 26.82918 6 4.052720 100.92096 99.19695 28.32775 28.75319 7 5.748139 103.76140 102.70104 27.30746 28.61573 8 4.883045 102.95873 101.18238 28.46042 28.78157 9 5.152658 95.08474 100.20105 28.78205 22.85643 10 7.189978 98.61968 101.86214 27.10187 32.34910 11 5.356986 95.64574 99.47452 26.29788 36.54318 12 7.716752 103.59355 99.98466 22.23219 27.41831 13 7.281452 100.55326 100.73431 23.15325 32.47597 14 5.324021 99.60767 103.41433 22.40002 30.94557 15 6.896067 97.89755 101.44748 20.08145 33.38600 16 5.467681 97.18937 100.96207 21.02248 27.70542 17 4.106199 104.98757 96.86426 22.33289 34.47197 18 4.692672 94.47435 100.63650 23.32719 23.84000 19 4.995178 99.28856 100.33198 24.81279 28.24750 20 5.988164 101.57497 98.20018 32.26808 29.39731 Finding the median of all columns in data frame df1 − apply(df1,2,median) x1 x2 x3 x4 x5 5.238339 100.737114 100.266517 25.717187 29.089439 Let’s have a look at another example − Live Demo y1<-sample(1:5,20,replace=TRUE) y2<-sample(1:2,20,replace=TRUE) y3<-sample(1:6,20,replace=TRUE) y4<-sample(1:10,20,replace=TRUE) df2<-data.frame(y1,y2,y3,y4) df2 y1 y2 y3 y4 1 2 2 5 5 2 5 2 3 9 3 2 2 2 10 4 3 2 1 5 5 1 1 1 3 6 1 2 4 3 7 3 1 6 1 8 2 2 5 9 9 2 1 5 1 10 4 2 2 5 11 3 1 6 7 12 5 1 4 9 13 2 2 3 3 14 4 2 1 6 15 2 1 1 7 16 1 2 5 10 17 3 1 4 7 18 2 1 1 6 19 5 2 3 2 20 1 2 6 7 Finding the median of all columns in data frame df2 − apply(df2,2,median) y1 y2 y3 y4 2.0 2.0 3.5 6.0
[ { "code": null, "e": 1352, "s": 1062, "text": "The median is the value in a vector that divide the data into two equal parts. To find the median of all columns, we can use apply function. For example, if we have a data frame df that contains numerical columns then the median for all the columns can be calculated as apply(df,2,median)." }, { "code": null, "e": 1384, "s": 1352, "text": "Consider the below data frame −" }, { "code": null, "e": 1395, "s": 1384, "text": " Live Demo" }, { "code": null, "e": 1539, "s": 1395, "text": "set.seed(7)\nx1<-rnorm(20,5,1)\nx2<-rnorm(20,100,5)\nx3<-rnorm(20,100,2)\nx4<-rnorm(20,25,3)\nx5<-rnorm(20,30,4)\ndf1<-data.frame(x1,x2,x3,x4,x5)\ndf1" }, { "code": null, "e": 2558, "s": 1539, "text": " x1 x2 x3 x4 x5\n1 7.287247 104.19875 102.43710 25.22911 31.37034\n2 3.803228 103.52671 98.60137 25.47747 30.01699\n3 4.305707 106.52982 99.42913 26.63102 30.11688\n4 4.587707 93.06002 97.37689 27.11442 28.42631\n5 4.029327 106.36458 99.21798 25.95691 26.82918\n6 4.052720 100.92096 99.19695 28.32775 28.75319\n7 5.748139 103.76140 102.70104 27.30746 28.61573\n8 4.883045 102.95873 101.18238 28.46042 28.78157\n9 5.152658 95.08474 100.20105 28.78205 22.85643\n10 7.189978 98.61968 101.86214 27.10187 32.34910\n11 5.356986 95.64574 99.47452 26.29788 36.54318\n12 7.716752 103.59355 99.98466 22.23219 27.41831\n13 7.281452 100.55326 100.73431 23.15325 32.47597\n14 5.324021 99.60767 103.41433 22.40002 30.94557\n15 6.896067 97.89755 101.44748 20.08145 33.38600\n16 5.467681 97.18937 100.96207 21.02248 27.70542\n17 4.106199 104.98757 96.86426 22.33289 34.47197\n18 4.692672 94.47435 100.63650 23.32719 23.84000\n19 4.995178 99.28856 100.33198 24.81279 28.24750\n20 5.988164 101.57497 98.20018 32.26808 29.39731" }, { "code": null, "e": 2612, "s": 2558, "text": "Finding the median of all columns in data frame df1 −" }, { "code": null, "e": 2632, "s": 2612, "text": "apply(df1,2,median)" }, { "code": null, "e": 2730, "s": 2632, "text": " x1 x2 x3 x4 x5\n5.238339 100.737114 100.266517 25.717187 29.089439" }, { "code": null, "e": 2769, "s": 2730, "text": "Let’s have a look at another example −" }, { "code": null, "e": 2780, "s": 2769, "text": " Live Demo" }, { "code": null, "e": 2942, "s": 2780, "text": "y1<-sample(1:5,20,replace=TRUE)\ny2<-sample(1:2,20,replace=TRUE)\ny3<-sample(1:6,20,replace=TRUE)\ny4<-sample(1:10,20,replace=TRUE)\ndf2<-data.frame(y1,y2,y3,y4)\ndf2" }, { "code": null, "e": 3218, "s": 2942, "text": " y1 y2 y3 y4\n1 2 2 5 5\n2 5 2 3 9\n3 2 2 2 10\n4 3 2 1 5\n5 1 1 1 3\n6 1 2 4 3\n7 3 1 6 1\n8 2 2 5 9\n9 2 1 5 1\n10 4 2 2 5\n11 3 1 6 7\n12 5 1 4 9\n13 2 2 3 3\n14 4 2 1 6\n15 2 1 1 7\n16 1 2 5 10\n17 3 1 4 7\n18 2 1 1 6\n19 5 2 3 2\n20 1 2 6 7" }, { "code": null, "e": 3272, "s": 3218, "text": "Finding the median of all columns in data frame df2 −" }, { "code": null, "e": 3292, "s": 3272, "text": "apply(df2,2,median)" }, { "code": null, "e": 3323, "s": 3292, "text": " y1 y2 y3 y4\n2.0 2.0 3.5 6.0" } ]
Cut rope to maximise product | Practice | GeeksforGeeks
Given a rope of length N meters, cut the rope into several ropes of varying lengths in a way that maximizes product of lengths of all resulting ropes. You must make at least one cut. Example 1: Input: N = 2 Output: 1 Explanation: Since 1 cut is mandatory. Maximum obtainable product is 1*1 = 1. Example 2: Input: N = 5 Output: 6 Explanation: Maximum obtainable product is 2*3 = 6. Your Task: You don't need to read input or print anything. Your task is to complete the function maxProduct() which takes n as input parameter and returns the maximum product. Expected Time Complexity: O(N2) Expected Auxiliary Space: O(N) Constraints: 1 ≤ N ≤ 100 0 nihalbaranwal This comment was deleted. 0 abhishekguptaaa3 months ago long long dp[102]; long long solve( long long n) { if(dp[n]!=-1) { return dp[n]; } long long mx=0; for(long long i=1;i<n;i++) { mx=max(mx, max(1LL*i*(n-i), 1LL*i*dp[n-i]) ); } return dp[n]=mx; } long long maxProduct(int n) { dp[n+1]; memset(dp,-1,sizeof(dp)); dp[0]=0; dp[1]=0; dp[2]=1; dp[3]=2; dp[4]=4; if(n<=4) { return dp[n]; } else { for(int i=5;i<n+1;i++) { solve(1LL*i); } return dp[n]; } }}; 0 abc123programming6 months ago JAVA SOLUTION class Solution { long maxProduct(int n) { long[] dp= new long[n+1]; for(int i=0;i<dp.length;i++){ dp[i]= -1; } long ans= maxP(n,dp); return ans; } static long maxP(int n,long[] dp){ if(n<=1){ return 0; } if(n==2){ return 1; } if(n==3){ return 2; } dp[0]=dp[1]=0; dp[2]=1; if(dp[n] != -1){ return dp[n]; } long max=0; for(int i=1;i<n;i++){ max=Math.max(max, Math.max( i*(n-i), i*maxP((n-i),dp))); } return dp[n]=max; }} 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": 409, "s": 226, "text": "Given a rope of length N meters, cut the rope into several ropes of varying lengths in a way that maximizes product of lengths of all resulting ropes. You must make at least one cut." }, { "code": null, "e": 420, "s": 409, "text": "Example 1:" }, { "code": null, "e": 521, "s": 420, "text": "Input:\nN = 2\nOutput: 1\nExplanation: Since 1 cut is mandatory.\nMaximum obtainable product is 1*1 = 1." }, { "code": null, "e": 533, "s": 521, "text": "\nExample 2:" }, { "code": null, "e": 609, "s": 533, "text": "Input:\nN = 5\nOutput: 6\nExplanation: \nMaximum obtainable product is 2*3 = 6." }, { "code": null, "e": 786, "s": 609, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function maxProduct() which takes n as input parameter and returns the maximum product." }, { "code": null, "e": 850, "s": 786, "text": "\nExpected Time Complexity: O(N2)\nExpected Auxiliary Space: O(N)" }, { "code": null, "e": 876, "s": 850, "text": "\nConstraints:\n1 ≤ N ≤ 100" }, { "code": null, "e": 880, "s": 878, "text": "0" }, { "code": null, "e": 894, "s": 880, "text": "nihalbaranwal" }, { "code": null, "e": 920, "s": 894, "text": "This comment was deleted." }, { "code": null, "e": 922, "s": 920, "text": "0" }, { "code": null, "e": 950, "s": 922, "text": "abhishekguptaaa3 months ago" }, { "code": null, "e": 1232, "s": 950, "text": " long long dp[102]; long long solve( long long n) { if(dp[n]!=-1) { return dp[n]; } long long mx=0; for(long long i=1;i<n;i++) { mx=max(mx, max(1LL*i*(n-i), 1LL*i*dp[n-i]) ); } return dp[n]=mx; } " }, { "code": null, "e": 1625, "s": 1232, "text": " long long maxProduct(int n) { dp[n+1]; memset(dp,-1,sizeof(dp)); dp[0]=0; dp[1]=0; dp[2]=1; dp[3]=2; dp[4]=4; if(n<=4) { return dp[n]; } else { for(int i=5;i<n+1;i++) { solve(1LL*i); } return dp[n]; } }};" }, { "code": null, "e": 1627, "s": 1625, "text": "0" }, { "code": null, "e": 1657, "s": 1627, "text": "abc123programming6 months ago" }, { "code": null, "e": 1671, "s": 1657, "text": "JAVA SOLUTION" }, { "code": null, "e": 2343, "s": 1677, "text": "class Solution { long maxProduct(int n) { long[] dp= new long[n+1]; for(int i=0;i<dp.length;i++){ dp[i]= -1; } long ans= maxP(n,dp); return ans; } static long maxP(int n,long[] dp){ if(n<=1){ return 0; } if(n==2){ return 1; } if(n==3){ return 2; } dp[0]=dp[1]=0; dp[2]=1; if(dp[n] != -1){ return dp[n]; } long max=0; for(int i=1;i<n;i++){ max=Math.max(max, Math.max( i*(n-i), i*maxP((n-i),dp))); } return dp[n]=max; }}" }, { "code": null, "e": 2489, "s": 2343, "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": 2525, "s": 2489, "text": " Login to access your submissions. " }, { "code": null, "e": 2535, "s": 2525, "text": "\nProblem\n" }, { "code": null, "e": 2545, "s": 2535, "text": "\nContest\n" }, { "code": null, "e": 2608, "s": 2545, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 2756, "s": 2608, "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": 2964, "s": 2756, "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": 3070, "s": 2964, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to quickly join data by location in Python — Spatial join | by Abdishakur | Towards Data Science
The chances are high that you have joined two tables if you have used Pandas Library. It is incredible how easy it is to combine two different datasets that share columns. But do you know that there is an easy way to join tables (DataFrames) based on locations? I show you an efficient way to join your tables using Spatial join. Spatial join is similar to joining data by attributes. The key difference is only that the tables are joined based on their locations in the spatial join. It is necessary to have matching keys in both tables to perform join by attributes; in contrast, you need locations (Latitude & Longitude) to perform the spatial join. Use cases for spatial join are many. Let us say you have schools as points and districts as areas (Polygon) and you want to determine how many schools are in each district. By performing a spatial join, you can quickly transfer the point table into areas table or vice-versa. Enough for the concept and hypothetical example. Let us take a concrete example. I want to get the count of how many Airbnb listings are in each voting district. I use Airbnb Dataset for Stockholm in this tutorial. The highlighted datasets are used to demonstrate the spatial join. Let us read first the tables in pandas as usual with .read_csv(). In step 2, We convert the latitude and longitude into Geometry using Geopandas. The neighbourhoods data is in Geojson, so we can directly read in Geopandas. Geopandas is a high-level pandas library that makes it easy to work with location data. import pandas as pdimport geopandas as gpd# 1- Listing pointslistings = pd.read_csv(“data/stockholm_listings.csv”)# 2 - convert to Geopandas Geodataframegdf_listings = gpd.GeoDataFrame(listings, geometry=gpd.points_from_xy(listings.longitude, listings.latitude))# 3 - Neighbourhoodsgeojson_file = “data/stockholm_neighbourhoods.geojson”neighborhoods = gpd.read_file(geojson_file) The gdf_listings table has different columns for each property, including hostname, neighbourhood, latitude and longitude. And Geopandas conversion adds the geometry column which allows us to do the spatial join. On the other hand, the Geojson neighbourhood file holds the neighbourhoods name and Geometry. Both datasets have neighbourhood column, and if you plot them overlayed, they perfectly align well (Map below), and we can easily Groupby and take the size of each neighbourhood to count the number of listings in each neighbourhood. But, imagine you have a different set of neighbourhoods (Polygons). Let us say the voting districts (smaller areas) which offer a better granularity and have other interesting attributes like population totals. Let me read the data first with Geopandas. stockholm_areas = gpd.read_file(“data/stockholm_areas.geojson”)stockholm_areas.head() Each voting district has aDesocolumn which holds the code for the district and Totalwhich has a total population in each district. These new granular (smaller) areas also perfectly overlay with the points dataset, but the problem is that we don’t have which voting district the point belongs. The data only came with neighbourhoods column Let us say we are interested in counting the number of listings per the voting area (voting districts). Although it is not readily available in our columns, we can do this easily and this where spatial join comes handy. With one line of code, you can determine which point is within each voting district. sjoined_listings = gpd.sjoin(gdf_listings, stockholm_areas, op=”within”)sjoined_listings.head() The above code joins gdf_listings to stockholm_areasbased on their locations. The op parameter determines what kind of join you want. In this case, we provided “within” — that determines which area the point belongs. Here is a sample of 5 rows from the joined table. As you can see, this table joins the two based on their locations. We have the attributes of the point as well as which area the point belongs. Now it is easy to count how many listings are in each area with pandas group-by function. We can perform pandas Groupby like this, to get how many listings are in each voting district area. grouped = sjoined_listings.groupby(“Deso”).size()df = grouped.to_frame().reset_index()df.columns = [‘Deso’, ‘listings_count’] We end up with a DataFrame of district area code Deso and listing counts in each area. Notice that this grouped data is a Dataframe. If you want to have it with Voting areas dataset, you can simply use pandas merge function based on “Deso” column on both Dataframes. merged_areas = stockholm_areas.merge(df, on=’Deso’, how=’outer’) The result of the merge is GeoDataFrame which you can plot geographically. The following is Choroplpleth map for the number of listings in each voting district. Give spatial join a try if you have some ideas otherwise try joining Airbnb dataset of a city of your choice and with different areas. Spatial joins are a powerful tool not often used in data science. It is quite intuitive and straightforward to do in Python with the help of Geopandas. In this tutorial, we have performed a spatial join with a practical example using Airbnb dataset. I hope you find this useful to add it to your data science skills. The code for this tutorial is available in this GitHub repository. github.com A google colab notebook is also included in the github repository if you want to run the code for this article directly.
[ { "code": null, "e": 434, "s": 172, "text": "The chances are high that you have joined two tables if you have used Pandas Library. It is incredible how easy it is to combine two different datasets that share columns. But do you know that there is an easy way to join tables (DataFrames) based on locations?" }, { "code": null, "e": 825, "s": 434, "text": "I show you an efficient way to join your tables using Spatial join. Spatial join is similar to joining data by attributes. The key difference is only that the tables are joined based on their locations in the spatial join. It is necessary to have matching keys in both tables to perform join by attributes; in contrast, you need locations (Latitude & Longitude) to perform the spatial join." }, { "code": null, "e": 1101, "s": 825, "text": "Use cases for spatial join are many. Let us say you have schools as points and districts as areas (Polygon) and you want to determine how many schools are in each district. By performing a spatial join, you can quickly transfer the point table into areas table or vice-versa." }, { "code": null, "e": 1383, "s": 1101, "text": "Enough for the concept and hypothetical example. Let us take a concrete example. I want to get the count of how many Airbnb listings are in each voting district. I use Airbnb Dataset for Stockholm in this tutorial. The highlighted datasets are used to demonstrate the spatial join." }, { "code": null, "e": 1694, "s": 1383, "text": "Let us read first the tables in pandas as usual with .read_csv(). In step 2, We convert the latitude and longitude into Geometry using Geopandas. The neighbourhoods data is in Geojson, so we can directly read in Geopandas. Geopandas is a high-level pandas library that makes it easy to work with location data." }, { "code": null, "e": 2077, "s": 1694, "text": "import pandas as pdimport geopandas as gpd# 1- Listing pointslistings = pd.read_csv(“data/stockholm_listings.csv”)# 2 - convert to Geopandas Geodataframegdf_listings = gpd.GeoDataFrame(listings, geometry=gpd.points_from_xy(listings.longitude, listings.latitude))# 3 - Neighbourhoodsgeojson_file = “data/stockholm_neighbourhoods.geojson”neighborhoods = gpd.read_file(geojson_file)" }, { "code": null, "e": 2290, "s": 2077, "text": "The gdf_listings table has different columns for each property, including hostname, neighbourhood, latitude and longitude. And Geopandas conversion adds the geometry column which allows us to do the spatial join." }, { "code": null, "e": 2384, "s": 2290, "text": "On the other hand, the Geojson neighbourhood file holds the neighbourhoods name and Geometry." }, { "code": null, "e": 2617, "s": 2384, "text": "Both datasets have neighbourhood column, and if you plot them overlayed, they perfectly align well (Map below), and we can easily Groupby and take the size of each neighbourhood to count the number of listings in each neighbourhood." }, { "code": null, "e": 2871, "s": 2617, "text": "But, imagine you have a different set of neighbourhoods (Polygons). Let us say the voting districts (smaller areas) which offer a better granularity and have other interesting attributes like population totals. Let me read the data first with Geopandas." }, { "code": null, "e": 2957, "s": 2871, "text": "stockholm_areas = gpd.read_file(“data/stockholm_areas.geojson”)stockholm_areas.head()" }, { "code": null, "e": 3296, "s": 2957, "text": "Each voting district has aDesocolumn which holds the code for the district and Totalwhich has a total population in each district. These new granular (smaller) areas also perfectly overlay with the points dataset, but the problem is that we don’t have which voting district the point belongs. The data only came with neighbourhoods column" }, { "code": null, "e": 3601, "s": 3296, "text": "Let us say we are interested in counting the number of listings per the voting area (voting districts). Although it is not readily available in our columns, we can do this easily and this where spatial join comes handy. With one line of code, you can determine which point is within each voting district." }, { "code": null, "e": 3697, "s": 3601, "text": "sjoined_listings = gpd.sjoin(gdf_listings, stockholm_areas, op=”within”)sjoined_listings.head()" }, { "code": null, "e": 3964, "s": 3697, "text": "The above code joins gdf_listings to stockholm_areasbased on their locations. The op parameter determines what kind of join you want. In this case, we provided “within” — that determines which area the point belongs. Here is a sample of 5 rows from the joined table." }, { "code": null, "e": 4298, "s": 3964, "text": "As you can see, this table joins the two based on their locations. We have the attributes of the point as well as which area the point belongs. Now it is easy to count how many listings are in each area with pandas group-by function. We can perform pandas Groupby like this, to get how many listings are in each voting district area." }, { "code": null, "e": 4424, "s": 4298, "text": "grouped = sjoined_listings.groupby(“Deso”).size()df = grouped.to_frame().reset_index()df.columns = [‘Deso’, ‘listings_count’]" }, { "code": null, "e": 4511, "s": 4424, "text": "We end up with a DataFrame of district area code Deso and listing counts in each area." }, { "code": null, "e": 4691, "s": 4511, "text": "Notice that this grouped data is a Dataframe. If you want to have it with Voting areas dataset, you can simply use pandas merge function based on “Deso” column on both Dataframes." }, { "code": null, "e": 4756, "s": 4691, "text": "merged_areas = stockholm_areas.merge(df, on=’Deso’, how=’outer’)" }, { "code": null, "e": 4917, "s": 4756, "text": "The result of the merge is GeoDataFrame which you can plot geographically. The following is Choroplpleth map for the number of listings in each voting district." }, { "code": null, "e": 5052, "s": 4917, "text": "Give spatial join a try if you have some ideas otherwise try joining Airbnb dataset of a city of your choice and with different areas." }, { "code": null, "e": 5369, "s": 5052, "text": "Spatial joins are a powerful tool not often used in data science. It is quite intuitive and straightforward to do in Python with the help of Geopandas. In this tutorial, we have performed a spatial join with a practical example using Airbnb dataset. I hope you find this useful to add it to your data science skills." }, { "code": null, "e": 5436, "s": 5369, "text": "The code for this tutorial is available in this GitHub repository." }, { "code": null, "e": 5447, "s": 5436, "text": "github.com" } ]
Choose maximum weight with given weight and value ratio - GeeksforGeeks
17 Jun, 2021 Given weights and values of n items and a value k. We need to choose a subset of these items in such a way that ratio of the sum of weight and sum of values of chosen items is K and sum of weight is maximum among all possible subset choices. Input : weight[] = [4, 8, 9] values[] = [2, 4, 6] K = 2 Output : 12 We can choose only first and second item only, because (4 + 8) / (2 + 4) = 2 which is equal to K we can't include third item with weight 9 because then ratio condition won't be satisfied so result will be (4 + 8) = 12 We can solve this problem using dynamic programming. We can make a 2 state dp where dp(i, j) will store maximum possible sum of weights under given conditions when total items are N and required ratio is K. Now in two states of dp, we will store the last item chosen and the difference between sum of weight and sum of values. We will multiply item values by K so that second state of dp will actually store (sum of weight – K*(sum of values)) for chosen items. Now we can see that our answer will be stored in dp(N-1, 0) because as last item is (N-1)th so all items are being considered and difference between sum of weight and K*(sum of values) is 0 that means sum of weight and sum of values has a ratio K. After defining above dp state we can write transition among states simply as shown below, dp(last, diff) = max (dp(last - 1, diff), dp(last-1, diff + wt[last] - val[last]*K)) dp(last – 1, diff) represents the condition when current item is not chosen and dp(last – 1, diff + wt[last] – val[last] * K)) represents the condition when current item is chosen so difference is updated with weight and value of current item. In below code a top-down approach is used for solving this dynamic programming and for storing dp states a map is used because the difference can be negative also and the 2D array can create problem in that case and special care need to be taken. C++ Java Python3 // C++ program to choose item with maximum// sum of weight under given constraint#include <bits/stdc++.h>using namespace std; // memoized recursive method to return maximum// weight with K as ratio of weight and valuesint maxWeightRec(int wt[], int val[], int K, map<pair<int, int>, int>& mp, int last, int diff){ // base cases : if no item is remaining if (last == -1) { if (diff == 0) return 0; else return INT_MIN; } // first make pair with last chosen item and // difference between weight and values pair<int, int> tmp = make_pair(last, diff); if (mp.find(tmp) != mp.end()) return mp[tmp]; /* choose maximum value from following two 1) not selecting the current item and calling recursively 2) selection current item, including the weight and updating the difference before calling recursively */ mp[tmp] = max(maxWeightRec(wt, val, K, mp, last - 1, diff), wt[last] + maxWeightRec(wt, val, K, mp, last - 1, diff + wt[last] - val[last] * K)); return mp[tmp];} // method returns maximum sum of weight with K// as ration of sum of weight and their valuesint maxWeight(int wt[], int val[], int K, int N){ map<pair<int, int>, int> mp; return maxWeightRec(wt, val, K, mp, N - 1, 0);} // Driver code to test above methodsint main(){ int wt[] = {4, 8, 9}; int val[] = {2, 4, 6}; int N = sizeof(wt) / sizeof(int); int K = 2; cout << maxWeight(wt, val, K, N); return 0;} // Java program to choose item with maximum// sum of weight under given constraint import java.awt.Point;import java.util.HashMap; class Test{ // memoized recursive method to return maximum // weight with K as ratio of weight and values static int maxWeightRec(int wt[], int val[], int K, HashMap<Point, Integer> hm, int last, int diff) { // base cases : if no item is remaining if (last == -1) { if (diff == 0) return 0; else return Integer.MIN_VALUE; } // first make pair with last chosen item and // difference between weight and values Point tmp = new Point(last, diff); if (hm.containsKey(tmp)) return hm.get(tmp); /* choose maximum value from following two 1) not selecting the current item and calling recursively 2) selection current item, including the weight and updating the difference before calling recursively */ hm.put(tmp,Math.max(maxWeightRec(wt, val, K, hm, last - 1, diff), wt[last] + maxWeightRec(wt, val, K, hm, last - 1, diff + wt[last] - val[last] * K))); return hm.get(tmp); } // method returns maximum sum of weight with K // as ration of sum of weight and their values static int maxWeight(int wt[], int val[], int K, int N) { HashMap<Point, Integer> hm = new HashMap<>(); return maxWeightRec(wt, val, K, hm, N - 1, 0); } // Driver method public static void main(String args[]) { int wt[] = {4, 8, 9}; int val[] = {2, 4, 6}; int K = 2; System.out.println(maxWeight(wt, val, K, wt.length)); }}// This code is contributed by Gaurav Miglani # Python3 program to choose item with maximum# sum of weight under given constraintINT_MIN = -9999999999 def maxWeightRec(wt, val, K, mp, last, diff): # memoized recursive method to return maximum # weight with K as ratio of weight and values # base cases : if no item is remaining if last == -1: if diff == 0: return 0 else: return INT_MIN # first make pair with last chosen item and # difference between weight and values tmp = (last, diff) if tmp in mp: return mp[tmp] # choose maximum value from following two # 1) not selecting the current item and # calling recursively # 2) selection current item, including # the weight and updating the difference # before calling recursively mp[tmp] = max(maxWeightRec(wt, val, K, mp, last - 1, diff), wt[last] + maxWeightRec(wt, val, K, mp, last - 1, diff + wt[last] - val[last] * K)) return mp[tmp] def maxWeight(wt, val, K, N): # method returns maximum sum of weight with K # as ration of sum of weight and their values return maxWeightRec(wt, val, K, {}, N - 1, 0) # Driver codeif __name__ == "__main__": wt = [4, 8, 9] val = [2, 4, 6] N = len(wt) K = 2 print(maxWeight(wt, val, K, N)) # This code is contributed# by vibhu4agarwal Output: 12 This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vibhu4agarwal simmytarika5 Dynamic Programming Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Longest Palindromic Substring | Set 1 Subset Sum Problem | DP-25 Matrix Chain Multiplication | DP-8 Overlapping Subproblems Property in Dynamic Programming | DP-1 Sieve of Eratosthenes Edit Distance | DP-5 Minimum number of jumps to reach end
[ { "code": null, "e": 24576, "s": 24548, "text": "\n17 Jun, 2021" }, { "code": null, "e": 24819, "s": 24576, "text": "Given weights and values of n items and a value k. We need to choose a subset of these items in such a way that ratio of the sum of weight and sum of values of chosen items is K and sum of weight is maximum among all possible subset choices. " }, { "code": null, "e": 25124, "s": 24819, "text": "Input : weight[] = [4, 8, 9]\n values[] = [2, 4, 6]\n K = 2\nOutput : 12\nWe can choose only first and second item only, \nbecause (4 + 8) / (2 + 4) = 2 which is equal to K\nwe can't include third item with weight 9 because \nthen ratio condition won't be satisfied so result \nwill be (4 + 8) = 12" }, { "code": null, "e": 25928, "s": 25126, "text": "We can solve this problem using dynamic programming. We can make a 2 state dp where dp(i, j) will store maximum possible sum of weights under given conditions when total items are N and required ratio is K. Now in two states of dp, we will store the last item chosen and the difference between sum of weight and sum of values. We will multiply item values by K so that second state of dp will actually store (sum of weight – K*(sum of values)) for chosen items. Now we can see that our answer will be stored in dp(N-1, 0) because as last item is (N-1)th so all items are being considered and difference between sum of weight and K*(sum of values) is 0 that means sum of weight and sum of values has a ratio K. After defining above dp state we can write transition among states simply as shown below, " }, { "code": null, "e": 26301, "s": 25928, "text": "dp(last, diff) = max (dp(last - 1, diff), \n dp(last-1, diff + wt[last] - val[last]*K))\n\ndp(last – 1, diff) represents the condition when current\n item is not chosen and \ndp(last – 1, diff + wt[last] – val[last] * K)) represents \nthe condition when current item is chosen so difference \nis updated with weight and value of current item." }, { "code": null, "e": 26549, "s": 26301, "text": "In below code a top-down approach is used for solving this dynamic programming and for storing dp states a map is used because the difference can be negative also and the 2D array can create problem in that case and special care need to be taken. " }, { "code": null, "e": 26553, "s": 26549, "text": "C++" }, { "code": null, "e": 26558, "s": 26553, "text": "Java" }, { "code": null, "e": 26566, "s": 26558, "text": "Python3" }, { "code": "// C++ program to choose item with maximum// sum of weight under given constraint#include <bits/stdc++.h>using namespace std; // memoized recursive method to return maximum// weight with K as ratio of weight and valuesint maxWeightRec(int wt[], int val[], int K, map<pair<int, int>, int>& mp, int last, int diff){ // base cases : if no item is remaining if (last == -1) { if (diff == 0) return 0; else return INT_MIN; } // first make pair with last chosen item and // difference between weight and values pair<int, int> tmp = make_pair(last, diff); if (mp.find(tmp) != mp.end()) return mp[tmp]; /* choose maximum value from following two 1) not selecting the current item and calling recursively 2) selection current item, including the weight and updating the difference before calling recursively */ mp[tmp] = max(maxWeightRec(wt, val, K, mp, last - 1, diff), wt[last] + maxWeightRec(wt, val, K, mp, last - 1, diff + wt[last] - val[last] * K)); return mp[tmp];} // method returns maximum sum of weight with K// as ration of sum of weight and their valuesint maxWeight(int wt[], int val[], int K, int N){ map<pair<int, int>, int> mp; return maxWeightRec(wt, val, K, mp, N - 1, 0);} // Driver code to test above methodsint main(){ int wt[] = {4, 8, 9}; int val[] = {2, 4, 6}; int N = sizeof(wt) / sizeof(int); int K = 2; cout << maxWeight(wt, val, K, N); return 0;}", "e": 28163, "s": 26566, "text": null }, { "code": "// Java program to choose item with maximum// sum of weight under given constraint import java.awt.Point;import java.util.HashMap; class Test{ // memoized recursive method to return maximum // weight with K as ratio of weight and values static int maxWeightRec(int wt[], int val[], int K, HashMap<Point, Integer> hm, int last, int diff) { // base cases : if no item is remaining if (last == -1) { if (diff == 0) return 0; else return Integer.MIN_VALUE; } // first make pair with last chosen item and // difference between weight and values Point tmp = new Point(last, diff); if (hm.containsKey(tmp)) return hm.get(tmp); /* choose maximum value from following two 1) not selecting the current item and calling recursively 2) selection current item, including the weight and updating the difference before calling recursively */ hm.put(tmp,Math.max(maxWeightRec(wt, val, K, hm, last - 1, diff), wt[last] + maxWeightRec(wt, val, K, hm, last - 1, diff + wt[last] - val[last] * K))); return hm.get(tmp); } // method returns maximum sum of weight with K // as ration of sum of weight and their values static int maxWeight(int wt[], int val[], int K, int N) { HashMap<Point, Integer> hm = new HashMap<>(); return maxWeightRec(wt, val, K, hm, N - 1, 0); } // Driver method public static void main(String args[]) { int wt[] = {4, 8, 9}; int val[] = {2, 4, 6}; int K = 2; System.out.println(maxWeight(wt, val, K, wt.length)); }}// This code is contributed by Gaurav Miglani", "e": 30056, "s": 28163, "text": null }, { "code": "# Python3 program to choose item with maximum# sum of weight under given constraintINT_MIN = -9999999999 def maxWeightRec(wt, val, K, mp, last, diff): # memoized recursive method to return maximum # weight with K as ratio of weight and values # base cases : if no item is remaining if last == -1: if diff == 0: return 0 else: return INT_MIN # first make pair with last chosen item and # difference between weight and values tmp = (last, diff) if tmp in mp: return mp[tmp] # choose maximum value from following two # 1) not selecting the current item and # calling recursively # 2) selection current item, including # the weight and updating the difference # before calling recursively mp[tmp] = max(maxWeightRec(wt, val, K, mp, last - 1, diff), wt[last] + maxWeightRec(wt, val, K, mp, last - 1, diff + wt[last] - val[last] * K)) return mp[tmp] def maxWeight(wt, val, K, N): # method returns maximum sum of weight with K # as ration of sum of weight and their values return maxWeightRec(wt, val, K, {}, N - 1, 0) # Driver codeif __name__ == \"__main__\": wt = [4, 8, 9] val = [2, 4, 6] N = len(wt) K = 2 print(maxWeight(wt, val, K, N)) # This code is contributed# by vibhu4agarwal", "e": 31479, "s": 30056, "text": null }, { "code": null, "e": 31489, "s": 31479, "text": "Output: " }, { "code": null, "e": 31492, "s": 31489, "text": "12" }, { "code": null, "e": 31916, "s": 31492, "text": "This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 31930, "s": 31916, "text": "vibhu4agarwal" }, { "code": null, "e": 31943, "s": 31930, "text": "simmytarika5" }, { "code": null, "e": 31963, "s": 31943, "text": "Dynamic Programming" }, { "code": null, "e": 31983, "s": 31963, "text": "Dynamic Programming" }, { "code": null, "e": 32081, "s": 31983, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32090, "s": 32081, "text": "Comments" }, { "code": null, "e": 32103, "s": 32090, "text": "Old Comments" }, { "code": null, "e": 32134, "s": 32103, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 32167, "s": 32134, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 32235, "s": 32167, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 32273, "s": 32235, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 32300, "s": 32273, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 32335, "s": 32300, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 32398, "s": 32335, "text": "Overlapping Subproblems Property in Dynamic Programming | DP-1" }, { "code": null, "e": 32420, "s": 32398, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 32441, "s": 32420, "text": "Edit Distance | DP-5" } ]
Python - Sentiment Analysis using Affin - GeeksforGeeks
18 Apr, 2022 Afinn is the simplest yet popular lexicons used for sentiment analysis developed by Finn Årup Nielsen. It contains 3300+ words with a polarity score associated with each word. In python, there is an in-built function for this lexicon. Let’s see its syntax- Installing the library: python3 # codeprint("GFG")pip install afinn /#installing in windowspip3 install afinn /#installing in linux!pip install afinn#installing in jupyter Code: Python code for sentiment analysis using Affin python3 #importing necessary librariesfrom afinn import Afinnimport pandas as pd #instantiate afinnafn = Afinn() #creating list sentencesnews_df = ['les gens pensent aux chiens','i hate flowers', 'hes kind and smart','we are kind to good people'] # compute scores (polarity) and labelsscores = [afn.score(article) for article in news_df]sentiment = ['positive' if score > 0 else 'negative' if score < 0 else 'neutral' for score in scores] # dataframe creationdf = pd.DataFrame()df['topic'] = news_dfdf['scores'] = scoresdf['sentiments'] = sentimentprint(df) Output: topic scores sentiments 0 les gens pensent aux chiens 0.0 neutral 1 i hate flowers -3.0 negative 2 hes kind and smart 3.0 positive 3 we are kind to good people 5.0 positive The best part of this library package is that one can find score sentiment of different languages as well. python3 afn = Afinn(language = 'da') #assigning 'da' danish to the object variable.afn.score('du er den mest modbydelige tæve') Output: -5.0 Thus, Afinn can we used easily to get scores immediately. varshagumber28 Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Selecting rows in pandas DataFrame based on conditions How To Convert Python Dictionary To JSON? Check if element exists in list in Python 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": 24292, "s": 24264, "text": "\n18 Apr, 2022" }, { "code": null, "e": 24528, "s": 24292, "text": "Afinn is the simplest yet popular lexicons used for sentiment analysis developed by Finn Årup Nielsen. It contains 3300+ words with a polarity score associated with each word. In python, there is an in-built function for this lexicon." }, { "code": null, "e": 24550, "s": 24528, "text": "Let’s see its syntax-" }, { "code": null, "e": 24574, "s": 24550, "text": "Installing the library:" }, { "code": null, "e": 24582, "s": 24574, "text": "python3" }, { "code": "# codeprint(\"GFG\")pip install afinn /#installing in windowspip3 install afinn /#installing in linux!pip install afinn#installing in jupyter", "e": 24722, "s": 24582, "text": null }, { "code": null, "e": 24775, "s": 24722, "text": "Code: Python code for sentiment analysis using Affin" }, { "code": null, "e": 24783, "s": 24775, "text": "python3" }, { "code": "#importing necessary librariesfrom afinn import Afinnimport pandas as pd #instantiate afinnafn = Afinn() #creating list sentencesnews_df = ['les gens pensent aux chiens','i hate flowers', 'hes kind and smart','we are kind to good people'] # compute scores (polarity) and labelsscores = [afn.score(article) for article in news_df]sentiment = ['positive' if score > 0 else 'negative' if score < 0 else 'neutral' for score in scores] # dataframe creationdf = pd.DataFrame()df['topic'] = news_dfdf['scores'] = scoresdf['sentiments'] = sentimentprint(df)", "e": 25442, "s": 24783, "text": null }, { "code": null, "e": 25450, "s": 25442, "text": "Output:" }, { "code": null, "e": 25675, "s": 25450, "text": "topic scores sentiments\n0 les gens pensent aux chiens 0.0 neutral\n1 i hate flowers -3.0 negative\n2 hes kind and smart 3.0 positive\n3 we are kind to good people 5.0 positive" }, { "code": null, "e": 25782, "s": 25675, "text": "The best part of this library package is that one can find score sentiment of different languages as well." }, { "code": null, "e": 25790, "s": 25782, "text": "python3" }, { "code": "afn = Afinn(language = 'da') #assigning 'da' danish to the object variable.afn.score('du er den mest modbydelige tæve')", "e": 25910, "s": 25790, "text": null }, { "code": null, "e": 25918, "s": 25910, "text": "Output:" }, { "code": null, "e": 25923, "s": 25918, "text": "-5.0" }, { "code": null, "e": 25981, "s": 25923, "text": "Thus, Afinn can we used easily to get scores immediately." }, { "code": null, "e": 25996, "s": 25981, "text": "varshagumber28" }, { "code": null, "e": 26003, "s": 25996, "text": "Python" }, { "code": null, "e": 26101, "s": 26003, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26110, "s": 26101, "text": "Comments" }, { "code": null, "e": 26123, "s": 26110, "text": "Old Comments" }, { "code": null, "e": 26155, "s": 26123, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26211, "s": 26155, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26266, "s": 26211, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26308, "s": 26266, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26350, "s": 26308, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26381, "s": 26350, "text": "Python | os.path.join() method" }, { "code": null, "e": 26420, "s": 26381, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26449, "s": 26420, "text": "Create a directory in Python" }, { "code": null, "e": 26471, "s": 26449, "text": "Defaultdict in Python" } ]
HTML Object tag - GeeksforGeeks
17 Mar, 2022 The <object> tag is an HTML tag and used to display multimedia like audios, videos, images, PDFs, and Flash in web pages. It can also be used for displaying another webpage inside the HTML page. The <param> tag is also used along with this tag to define various parameters. Any text that is written within <object> and </object> tags are considered as an alternative text that appears when the data specified is not supported by the browser. This tag supports all Global and Event attributes of HTML. Example: HTML <!DOCTYPE html> <html> <body> <h1>HTML Object Tag</h1> <!--HTML object tag starts here--> <object data="https://media.geeksforgeeks.org/wp-content/cdn-uploads/Geek_logi_-low_res.png"width="550px" height="150px">GeeksforGeeks <!--HTML object tag ends here--> </object> </body> </html> Output: The <object> tag has the following attributes: Supported Browsers: Google Chrome Internet Explorer Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. Akanksha_Rai shubhamyadav4 HTML-Tags HTML HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? How to Insert Form Data into Database using PHP ? Hide or show elements in HTML using display property REST API (Introduction) CSS to put icon inside an input element in a form Form validation using HTML and JavaScript
[ { "code": null, "e": 23148, "s": 23120, "text": "\n17 Mar, 2022" }, { "code": null, "e": 23660, "s": 23148, "text": "The <object> tag is an HTML tag and used to display multimedia like audios, videos, images, PDFs, and Flash in web pages. It can also be used for displaying another webpage inside the HTML page. The <param> tag is also used along with this tag to define various parameters. Any text that is written within <object> and </object> tags are considered as an alternative text that appears when the data specified is not supported by the browser. This tag supports all Global and Event attributes of HTML. Example: " }, { "code": null, "e": 23665, "s": 23660, "text": "HTML" }, { "code": "<!DOCTYPE html> <html> <body> <h1>HTML Object Tag</h1> <!--HTML object tag starts here--> <object data=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/Geek_logi_-low_res.png\"width=\"550px\" height=\"150px\">GeeksforGeeks <!--HTML object tag ends here--> </object> </body> </html> ", "e": 24010, "s": 23665, "text": null }, { "code": null, "e": 24020, "s": 24010, "text": "Output: " }, { "code": null, "e": 24069, "s": 24020, "text": "The <object> tag has the following attributes: " }, { "code": null, "e": 24091, "s": 24069, "text": "Supported Browsers: " }, { "code": null, "e": 24105, "s": 24091, "text": "Google Chrome" }, { "code": null, "e": 24123, "s": 24105, "text": "Internet Explorer" }, { "code": null, "e": 24131, "s": 24123, "text": "Firefox" }, { "code": null, "e": 24137, "s": 24131, "text": "Opera" }, { "code": null, "e": 24144, "s": 24137, "text": "Safari" }, { "code": null, "e": 24283, "s": 24146, "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": 24296, "s": 24283, "text": "Akanksha_Rai" }, { "code": null, "e": 24310, "s": 24296, "text": "shubhamyadav4" }, { "code": null, "e": 24320, "s": 24310, "text": "HTML-Tags" }, { "code": null, "e": 24325, "s": 24320, "text": "HTML" }, { "code": null, "e": 24330, "s": 24325, "text": "HTML" }, { "code": null, "e": 24428, "s": 24330, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24437, "s": 24428, "text": "Comments" }, { "code": null, "e": 24450, "s": 24437, "text": "Old Comments" }, { "code": null, "e": 24512, "s": 24450, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 24562, "s": 24512, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 24610, "s": 24562, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 24670, "s": 24610, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 24731, "s": 24670, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 24781, "s": 24731, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 24834, "s": 24781, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 24858, "s": 24834, "text": "REST API (Introduction)" }, { "code": null, "e": 24908, "s": 24858, "text": "CSS to put icon inside an input element in a form" } ]