title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
jMeter - Database Test Plan
In this chapter, we will see how to create a simple test plan to test the database server. For our test purpose we use the MYSQL database server. You can use any other database for testing. For installation and table creation in MYSQL please refer MYSQL Tutorial. Once MYSQL is installed, follow the steps below to setup the database − Create a database with name "tutorial". Create a database with name "tutorial". Create a table tutorials_tbl. Create a table tutorials_tbl. Insert records into tutorials_tbl as shown below − Insert records into tutorials_tbl as shown below − mysql> use TUTORIALS; Database changed mysql> INSERT INTO tutorials_tbl ->(tutorial_title, tutorial_author, submission_date) ->VALUES ->("Learn PHP", "John Poul", NOW()); Query OK, 1 row affected (0.01 sec) mysql> INSERT INTO tutorials_tbl ->(tutorial_title, tutorial_author, submission_date) ->VALUES ->("Learn MySQL", "Abdul S", NOW()); Query OK, 1 row affected (0.01 sec) mysql> INSERT INTO tutorials_tbl ->(tutorial_title, tutorial_author, submission_date) ->VALUES ->("JAVA Tutorial", "Sanjay", '2007-05-06'); Query OK, 1 row affected (0.01 sec) mysql> Copy the appropriate JDBC driver to /home/manisha/apache-jmeter-2.9/lib. Copy the appropriate JDBC driver to /home/manisha/apache-jmeter-2.9/lib. Let us start the JMeter from /home/manisha/apache-jmeter-2.9/bin/jmeter.sh. To create a Thread group, Right-click on Test Plan. Right-click on Test Plan. Select Add → Threads (Users) → Thread Group. Select Add → Threads (Users) → Thread Group. Thus, thread group gets added under the Test Plan node. Thus, thread group gets added under the Test Plan node. Rename this Thread Group as JDBC Users. Rename this Thread Group as JDBC Users. We will not change the default properties of the Thread Group. Now that we defined our users, it is time to define the tasks that they will be performing. In this section, specify the JDBC requests to perform. Right-click on the JDBC Users element. Right-click on the JDBC Users element. Select Add → Config Element → JDBC Connection Configuration. Select Add → Config Element → JDBC Connection Configuration. Set up the following fields (we are using MySQL database called tutorial) − Variable name bound to pool. This needs to identify the configuration uniquely. It is used by the JDBC Sampler to identify the configuration to be used. We have named it as test. Database URL − jdbc:mysql://localhost:3306/tutorial. JDBC Driver class: com.mysql.jdbc.Driver. Username: root. Password: password for root. Set up the following fields (we are using MySQL database called tutorial) − Variable name bound to pool. This needs to identify the configuration uniquely. It is used by the JDBC Sampler to identify the configuration to be used. We have named it as test. Variable name bound to pool. This needs to identify the configuration uniquely. It is used by the JDBC Sampler to identify the configuration to be used. We have named it as test. Database URL − jdbc:mysql://localhost:3306/tutorial. Database URL − jdbc:mysql://localhost:3306/tutorial. JDBC Driver class: com.mysql.jdbc.Driver. JDBC Driver class: com.mysql.jdbc.Driver. Username: root. Username: root. Password: password for root. Password: password for root. The other fields on the screen are left as defaults as shown below − Now add a JDBC Request which refers to the JDBC Configuration pool defined above. Select JDBC Users element. Click your right mouse button to get the Add menu Click your right mouse button to get the Add menu Select Add → Sampler → JDBC Request. Select Add → Sampler → JDBC Request. Select this new element to view its Control Panel. Select this new element to view its Control Panel. Edit the properties as shown below − Variable name bound to pool. This needs to uniquely identify the configuration. It is used by the JDBC Sampler to identify the configuration to be used. Named it as test. Name − Learn. Enter the Pool Name − test (same as in the configuration element). Query Type − Select statement. Enter the SQL Query String field. Edit the properties as shown below − Variable name bound to pool. This needs to uniquely identify the configuration. It is used by the JDBC Sampler to identify the configuration to be used. Named it as test. Variable name bound to pool. This needs to uniquely identify the configuration. It is used by the JDBC Sampler to identify the configuration to be used. Named it as test. Name − Learn. Name − Learn. Enter the Pool Name − test (same as in the configuration element). Enter the Pool Name − test (same as in the configuration element). Query Type − Select statement. Query Type − Select statement. Enter the SQL Query String field. Enter the SQL Query String field. Now add the Listener element. This element is responsible for storing all of the results of your JDBC requests in a file and presenting a visual model of the data. Select the JDBC Users element Select the JDBC Users element Add a View Results Tree listener (Add → Listener → View Results Tree). Add a View Results Tree listener (Add → Listener → View Results Tree). Now save the above test plan as db_test.jmx. Execute this test plan using Run → Start option. In the last image, you can see that two records are selected. 59 Lectures 9.5 hours Rahul Shetty 54 Lectures 13.5 hours Wallace Tauriac 23 Lectures 1.5 hours Anuja Jain 12 Lectures 1 hours Spotle Learn Print Add Notes Bookmark this page
[ { "code": null, "e": 2169, "s": 1905, "text": "In this chapter, we will see how to create a simple test plan to test the database server. For our test purpose we use the MYSQL database server. You can use any other database for testing. For installation and table creation in MYSQL please refer MYSQL Tutorial." }, { "code": null, "e": 2241, "s": 2169, "text": "Once MYSQL is installed, follow the steps below to setup the database −" }, { "code": null, "e": 2281, "s": 2241, "text": "Create a database with name \"tutorial\"." }, { "code": null, "e": 2321, "s": 2281, "text": "Create a database with name \"tutorial\"." }, { "code": null, "e": 2351, "s": 2321, "text": "Create a table tutorials_tbl." }, { "code": null, "e": 2381, "s": 2351, "text": "Create a table tutorials_tbl." }, { "code": null, "e": 2432, "s": 2381, "text": "Insert records into tutorials_tbl as shown below −" }, { "code": null, "e": 2483, "s": 2432, "text": "Insert records into tutorials_tbl as shown below −" }, { "code": null, "e": 3076, "s": 2483, "text": "mysql> use TUTORIALS;\nDatabase changed\nmysql> INSERT INTO tutorials_tbl \n ->(tutorial_title, tutorial_author, submission_date)\n ->VALUES\n ->(\"Learn PHP\", \"John Poul\", NOW());\n \nQuery OK, 1 row affected (0.01 sec)\nmysql> INSERT INTO tutorials_tbl\n ->(tutorial_title, tutorial_author, submission_date)\n ->VALUES\n ->(\"Learn MySQL\", \"Abdul S\", NOW());\n \nQuery OK, 1 row affected (0.01 sec)\nmysql> INSERT INTO tutorials_tbl\n ->(tutorial_title, tutorial_author, submission_date)\n ->VALUES\n ->(\"JAVA Tutorial\", \"Sanjay\", '2007-05-06');\n\nQuery OK, 1 row affected (0.01 sec)\nmysql>\n" }, { "code": null, "e": 3149, "s": 3076, "text": "Copy the appropriate JDBC driver to /home/manisha/apache-jmeter-2.9/lib." }, { "code": null, "e": 3222, "s": 3149, "text": "Copy the appropriate JDBC driver to /home/manisha/apache-jmeter-2.9/lib." }, { "code": null, "e": 3298, "s": 3222, "text": "Let us start the JMeter from /home/manisha/apache-jmeter-2.9/bin/jmeter.sh." }, { "code": null, "e": 3324, "s": 3298, "text": "To create a Thread group," }, { "code": null, "e": 3350, "s": 3324, "text": "Right-click on Test Plan." }, { "code": null, "e": 3376, "s": 3350, "text": "Right-click on Test Plan." }, { "code": null, "e": 3421, "s": 3376, "text": "Select Add → Threads (Users) → Thread Group." }, { "code": null, "e": 3466, "s": 3421, "text": "Select Add → Threads (Users) → Thread Group." }, { "code": null, "e": 3522, "s": 3466, "text": "Thus, thread group gets added under the Test Plan node." }, { "code": null, "e": 3578, "s": 3522, "text": "Thus, thread group gets added under the Test Plan node." }, { "code": null, "e": 3618, "s": 3578, "text": "Rename this Thread Group as JDBC Users." }, { "code": null, "e": 3658, "s": 3618, "text": "Rename this Thread Group as JDBC Users." }, { "code": null, "e": 3721, "s": 3658, "text": "We will not change the default properties of the Thread Group." }, { "code": null, "e": 3868, "s": 3721, "text": "Now that we defined our users, it is time to define the tasks that they will be performing. In this section, specify the JDBC requests to perform." }, { "code": null, "e": 3907, "s": 3868, "text": "Right-click on the JDBC Users element." }, { "code": null, "e": 3946, "s": 3907, "text": "Right-click on the JDBC Users element." }, { "code": null, "e": 4007, "s": 3946, "text": "Select Add → Config Element → JDBC Connection Configuration." }, { "code": null, "e": 4068, "s": 4007, "text": "Select Add → Config Element → JDBC Connection Configuration." }, { "code": null, "e": 4466, "s": 4068, "text": "Set up the following fields (we are using MySQL database called tutorial) −\n\nVariable name bound to pool. This needs to identify the configuration uniquely. It is used by the JDBC Sampler to identify the configuration to be used. We have named it as test.\nDatabase URL − jdbc:mysql://localhost:3306/tutorial.\nJDBC Driver class: com.mysql.jdbc.Driver.\nUsername: root.\nPassword: password for root.\n\n" }, { "code": null, "e": 4542, "s": 4466, "text": "Set up the following fields (we are using MySQL database called tutorial) −" }, { "code": null, "e": 4721, "s": 4542, "text": "Variable name bound to pool. This needs to identify the configuration uniquely. It is used by the JDBC Sampler to identify the configuration to be used. We have named it as test." }, { "code": null, "e": 4900, "s": 4721, "text": "Variable name bound to pool. This needs to identify the configuration uniquely. It is used by the JDBC Sampler to identify the configuration to be used. We have named it as test." }, { "code": null, "e": 4953, "s": 4900, "text": "Database URL − jdbc:mysql://localhost:3306/tutorial." }, { "code": null, "e": 5006, "s": 4953, "text": "Database URL − jdbc:mysql://localhost:3306/tutorial." }, { "code": null, "e": 5048, "s": 5006, "text": "JDBC Driver class: com.mysql.jdbc.Driver." }, { "code": null, "e": 5090, "s": 5048, "text": "JDBC Driver class: com.mysql.jdbc.Driver." }, { "code": null, "e": 5106, "s": 5090, "text": "Username: root." }, { "code": null, "e": 5122, "s": 5106, "text": "Username: root." }, { "code": null, "e": 5151, "s": 5122, "text": "Password: password for root." }, { "code": null, "e": 5180, "s": 5151, "text": "Password: password for root." }, { "code": null, "e": 5249, "s": 5180, "text": "The other fields on the screen are left as defaults as shown below −" }, { "code": null, "e": 5358, "s": 5249, "text": "Now add a JDBC Request which refers to the JDBC Configuration pool defined above. Select JDBC Users element." }, { "code": null, "e": 5408, "s": 5358, "text": "Click your right mouse button to get the Add menu" }, { "code": null, "e": 5458, "s": 5408, "text": "Click your right mouse button to get the Add menu" }, { "code": null, "e": 5495, "s": 5458, "text": "Select Add → Sampler → JDBC Request." }, { "code": null, "e": 5532, "s": 5495, "text": "Select Add → Sampler → JDBC Request." }, { "code": null, "e": 5583, "s": 5532, "text": "Select this new element to view its Control Panel." }, { "code": null, "e": 5634, "s": 5583, "text": "Select this new element to view its Control Panel." }, { "code": null, "e": 5991, "s": 5634, "text": "Edit the properties as shown below −\n\nVariable name bound to pool. This needs to uniquely identify the configuration. It is used by the JDBC Sampler to identify the configuration to be used. Named it as test.\nName − Learn.\nEnter the Pool Name − test (same as in the configuration element).\nQuery Type − Select statement.\nEnter the SQL Query String field.\n\n" }, { "code": null, "e": 6028, "s": 5991, "text": "Edit the properties as shown below −" }, { "code": null, "e": 6199, "s": 6028, "text": "Variable name bound to pool. This needs to uniquely identify the configuration. It is used by the JDBC Sampler to identify the configuration to be used. Named it as test." }, { "code": null, "e": 6370, "s": 6199, "text": "Variable name bound to pool. This needs to uniquely identify the configuration. It is used by the JDBC Sampler to identify the configuration to be used. Named it as test." }, { "code": null, "e": 6384, "s": 6370, "text": "Name − Learn." }, { "code": null, "e": 6398, "s": 6384, "text": "Name − Learn." }, { "code": null, "e": 6465, "s": 6398, "text": "Enter the Pool Name − test (same as in the configuration element)." }, { "code": null, "e": 6532, "s": 6465, "text": "Enter the Pool Name − test (same as in the configuration element)." }, { "code": null, "e": 6563, "s": 6532, "text": "Query Type − Select statement." }, { "code": null, "e": 6594, "s": 6563, "text": "Query Type − Select statement." }, { "code": null, "e": 6628, "s": 6594, "text": "Enter the SQL Query String field." }, { "code": null, "e": 6662, "s": 6628, "text": "Enter the SQL Query String field." }, { "code": null, "e": 6826, "s": 6662, "text": "Now add the Listener element. This element is responsible for storing all of the results of your JDBC requests in a file and presenting a visual model of the data." }, { "code": null, "e": 6856, "s": 6826, "text": "Select the JDBC Users element" }, { "code": null, "e": 6886, "s": 6856, "text": "Select the JDBC Users element" }, { "code": null, "e": 6957, "s": 6886, "text": "Add a View Results Tree listener (Add → Listener → View Results Tree)." }, { "code": null, "e": 7028, "s": 6957, "text": "Add a View Results Tree listener (Add → Listener → View Results Tree)." }, { "code": null, "e": 7122, "s": 7028, "text": "Now save the above test plan as db_test.jmx. Execute this test plan using Run → Start option." }, { "code": null, "e": 7184, "s": 7122, "text": "In the last image, you can see that two records are selected." }, { "code": null, "e": 7219, "s": 7184, "text": "\n 59 Lectures \n 9.5 hours \n" }, { "code": null, "e": 7233, "s": 7219, "text": " Rahul Shetty" }, { "code": null, "e": 7269, "s": 7233, "text": "\n 54 Lectures \n 13.5 hours \n" }, { "code": null, "e": 7286, "s": 7269, "text": " Wallace Tauriac" }, { "code": null, "e": 7321, "s": 7286, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7333, "s": 7321, "text": " Anuja Jain" }, { "code": null, "e": 7366, "s": 7333, "text": "\n 12 Lectures \n 1 hours \n" }, { "code": null, "e": 7380, "s": 7366, "text": " Spotle Learn" }, { "code": null, "e": 7387, "s": 7380, "text": " Print" }, { "code": null, "e": 7398, "s": 7387, "text": " Add Notes" } ]
Min Number of Flips | Practice | GeeksforGeeks
Given a binary string, that is it contains only 0s and 1s. We need to make this string a sequence of alternate characters by flipping some of the bits, our goal is to minimize the number of bits to be flipped. Example 1: Input: S = "001" Output: 1 Explanation: We can flip the 0th bit to 1 to have 101. Example 2: Input: S = "0001010111" Output: 2 Explanation: We can flip the 1st and 8th bit bit to have "0101010101" 101. Your Task: You don't need to read input or print anything. Your task is to complete the function minFlips() which takes the string S as input and returns the minimum number of flips required. Expected Time Complexity: O(|S|). Expected Auxiliary Space: O(1). Constraints: 1<=|S|<=105 0 aditilal01in 6 hours We first create two strings of the same size and compare it with the input to get the minimumint minFlips (string S){ string prod1=""; string prod2=""; for(int i=0;i<S.size();i++) { if(i%2 == 0) { prod1+="0"; } else { prod1+="1"; } } for(int i=0;i<S.size();i++) { if(i%2 == 0) { prod2+="1"; } else { prod2+="0"; } } int count1=0; int count2=0; for(int i=0;i<S.size();i++) { if(S[i]!=prod1[i]) { count1++; } } for(int i=0;i<S.size();i++) { if(S[i]!=prod2[i]) { count2++; } } int ans = min(count1,count2); return ans;} 0 ayushmishra29 This comment was deleted. 0 shilsoumyadip2 weeks ago int minFlips (string S){ // your code here int c1 = 0; int c2 = 0; for(int i =0; i<S.length();i++) { if(i%2 != 0 and S[i] == '0') c1++; if(i%2 == 0 and S[i] == '1') c1++; if(i%2 != 0 and S[i] == '1') c2++; if(i%2 == 0 and S[i] == '0') c2++; } return min(c1,c2);} 0 codewithaddy2 weeks ago C++ Solution Total Time Taken: 0.04/1.26 int minFlips (string s) { int n=s.length(); int c1=0,c2=0; for(int i=0; i<n;i++){ if((s[i]-48)!=i%2){ c1++; } } for(int i=0; i<n;i++){ if((s[i]-48)==i%2){ c2++; } } return min(c1,c2); } 0 18951a04c33 weeks ago Python 3 class Solution: def minFlips(self, s): count1=0 count2=0 for i in range(len(s)): if (i%2==0 and s[i]!="1") or (i%2!=0 and s[i]!="0"): count1+=1 if (i%2==0 and s[i]!="0") or (i%2!=0 and s[i]!="1"): count2+=1 return min(count1,count2) +1 aloksinghbais022 months ago C++ solution having time complexity as O(|S|) and space complexity as O(1) is as follows :- Execution Time :- 0.0 / 1.3 sec int minFlips (string S){ int cnt1 = 0,cnt2 = 0; int n = S.length(); for(int i = 0; i < n; i++){ if(i & 1){ if(S[i] != '0') cnt1++; if(S[i] != '1') cnt2++; } else{ if(S[i] != '1') cnt1++; if(S[i] != '0') cnt2++; } } return min(cnt1,cnt2);} 0 khunalshaik2 months ago def minFlips(self, S): # initialize length and duplicate string of perfect output to compare with given string and return the result of minimum difference. l = len(S) count1 = "1" count2 = "0" for i in range(l-1): if i % 2 == 0 : count1 += "0" count2 += "1" else: count1 += "1" count2 += "0" diff1, diff2 = 0 , 0 for i in range(len(S)): if S[i] == count1[i] : diff2 += 1 else: diff1 += 1 return min(diff1, diff2) 0 sunghunet2 months ago int XOR(string bits1,string bits2){ // return sum of 1s if(bits1.length() != bits2.length()) return -1; int osum = 0; for(int i = 0;i < bits1.length();i++) { if(bits1[i] != bits2[i]) osum += 1; } return osum; } int minFlips(string S) { string zeroFirst = "0",oneFirst = "1"; for(int i = 2;i <= S.length();i++){ if(i % 2 == 0) { zeroFirst += "1"; oneFirst += "0"; } else { zeroFirst += "0"; oneFirst += "1"; } } int xZero = XOR(S,zeroFirst),xOne = XOR(S,oneFirst); return (xZero > xOne) ? xOne : xZero; } +2 manishmaheshwari81332 months ago JAVA CODE TC=O(|s|) SC=O(1) class Solution { public int minFlips(String S) { int fir=0,sec=0; for(int i=0;i<S.length();i++){ if((i%2==0 && S.charAt(i)=='1')||(i%2!=0 && S.charAt(i)=='0'))fir++; else sec++; } return Math.min(fir,sec); } } another solution TC=O(2|s|) SC=O(1) class Solution { public int minFlips(String S) { int fir=0,sec=0; for(int i=0;i<S.length();i++){ if(i%2==0){ if(S.charAt(i)!='0')fir++; }else{ if(S.charAt(i)!='1')fir++; } } for(int i=0;i<S.length();i++){ if(i%2==0){ if(S.charAt(i)!='1')sec++; }else{ if(S.charAt(i)!='0')sec++; } } return Math.min(fir,sec); } } +1 absaarali15482 months ago int minFlips (string S){ int s = 0 , n = S.length(); for(int i = 0 ; i < n ; i+=2) if(S[i]=='1') s++; for(int i = 1 ; i < n ; i+=2) if(S[i]=='0') s++; return min(s,n-s);} 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": 448, "s": 238, "text": "Given a binary string, that is it contains only 0s and 1s. We need to make this string a sequence of alternate characters by flipping some of the bits, our goal is to minimize the number of bits to be flipped." }, { "code": null, "e": 459, "s": 448, "text": "Example 1:" }, { "code": null, "e": 545, "s": 459, "text": "Input:\nS = \"001\"\nOutput: 1\nExplanation: \nWe can flip the 0th bit to 1 to have\n101.\n\n\n" }, { "code": null, "e": 556, "s": 545, "text": "Example 2:" }, { "code": null, "e": 668, "s": 556, "text": "Input:\nS = \"0001010111\" \nOutput: 2\nExplanation: We can flip the 1st and 8th bit \nbit to have \"0101010101\"\n101.\n" }, { "code": null, "e": 861, "s": 668, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function minFlips() which takes the string S as input and returns the minimum number of flips required." }, { "code": null, "e": 928, "s": 861, "text": "\nExpected Time Complexity: O(|S|).\nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 954, "s": 928, "text": "\nConstraints:\n1<=|S|<=105" }, { "code": null, "e": 958, "s": 956, "text": "0" }, { "code": null, "e": 979, "s": 958, "text": "aditilal01in 6 hours" }, { "code": null, "e": 1754, "s": 979, "text": "We first create two strings of the same size and compare it with the input to get the minimumint minFlips (string S){ string prod1=\"\"; string prod2=\"\"; for(int i=0;i<S.size();i++) { if(i%2 == 0) { prod1+=\"0\"; } else { prod1+=\"1\"; } } for(int i=0;i<S.size();i++) { if(i%2 == 0) { prod2+=\"1\"; } else { prod2+=\"0\"; } } int count1=0; int count2=0; for(int i=0;i<S.size();i++) { if(S[i]!=prod1[i]) { count1++; } } for(int i=0;i<S.size();i++) { if(S[i]!=prod2[i]) { count2++; } } int ans = min(count1,count2); return ans;}" }, { "code": null, "e": 1756, "s": 1754, "text": "0" }, { "code": null, "e": 1770, "s": 1756, "text": "ayushmishra29" }, { "code": null, "e": 1796, "s": 1770, "text": "This comment was deleted." }, { "code": null, "e": 1798, "s": 1796, "text": "0" }, { "code": null, "e": 1823, "s": 1798, "text": "shilsoumyadip2 weeks ago" }, { "code": null, "e": 2124, "s": 1823, "text": "int minFlips (string S){ // your code here int c1 = 0; int c2 = 0; for(int i =0; i<S.length();i++) { if(i%2 != 0 and S[i] == '0') c1++; if(i%2 == 0 and S[i] == '1') c1++; if(i%2 != 0 and S[i] == '1') c2++; if(i%2 == 0 and S[i] == '0') c2++; } return min(c1,c2);}" }, { "code": null, "e": 2126, "s": 2124, "text": "0" }, { "code": null, "e": 2150, "s": 2126, "text": "codewithaddy2 weeks ago" }, { "code": null, "e": 2163, "s": 2150, "text": "C++ Solution" }, { "code": null, "e": 2191, "s": 2163, "text": "Total Time Taken: 0.04/1.26" }, { "code": null, "e": 2466, "s": 2191, "text": "int minFlips (string s)\n{\n \n int n=s.length();\n int c1=0,c2=0;\n for(int i=0; i<n;i++){\n if((s[i]-48)!=i%2){\n c1++;\n }\n }\n for(int i=0; i<n;i++){\n if((s[i]-48)==i%2){\n c2++;\n }\n }\n return min(c1,c2);\n}" }, { "code": null, "e": 2468, "s": 2466, "text": "0" }, { "code": null, "e": 2490, "s": 2468, "text": "18951a04c33 weeks ago" }, { "code": null, "e": 2499, "s": 2490, "text": "Python 3" }, { "code": null, "e": 2824, "s": 2499, "text": "class Solution:\n def minFlips(self, s):\n count1=0\n count2=0\n for i in range(len(s)):\n if (i%2==0 and s[i]!=\"1\") or (i%2!=0 and s[i]!=\"0\"):\n count1+=1\n if (i%2==0 and s[i]!=\"0\") or (i%2!=0 and s[i]!=\"1\"):\n count2+=1\n return min(count1,count2)" }, { "code": null, "e": 2827, "s": 2824, "text": "+1" }, { "code": null, "e": 2855, "s": 2827, "text": "aloksinghbais022 months ago" }, { "code": null, "e": 2948, "s": 2855, "text": "C++ solution having time complexity as O(|S|) and space complexity as O(1) is as follows :- " }, { "code": null, "e": 2982, "s": 2950, "text": "Execution Time :- 0.0 / 1.3 sec" }, { "code": null, "e": 3297, "s": 2984, "text": "int minFlips (string S){ int cnt1 = 0,cnt2 = 0; int n = S.length(); for(int i = 0; i < n; i++){ if(i & 1){ if(S[i] != '0') cnt1++; if(S[i] != '1') cnt2++; } else{ if(S[i] != '1') cnt1++; if(S[i] != '0') cnt2++; } } return min(cnt1,cnt2);}" }, { "code": null, "e": 3299, "s": 3297, "text": "0" }, { "code": null, "e": 3323, "s": 3299, "text": "khunalshaik2 months ago" }, { "code": null, "e": 3990, "s": 3323, "text": "def minFlips(self, S):\n # initialize length and duplicate string of perfect output to compare with given string and return the result of minimum difference.\n l = len(S)\n count1 = \"1\"\n count2 = \"0\"\n \n for i in range(l-1):\n \n if i % 2 == 0 :\n count1 += \"0\"\n count2 += \"1\"\n \n else:\n count1 += \"1\"\n count2 += \"0\"\n \n diff1, diff2 = 0 , 0\n \n for i in range(len(S)):\n \n if S[i] == count1[i] :\n diff2 += 1\n \n else:\n diff1 += 1\n \n return min(diff1, diff2)" }, { "code": null, "e": 3992, "s": 3990, "text": "0" }, { "code": null, "e": 4014, "s": 3992, "text": "sunghunet2 months ago" }, { "code": null, "e": 4561, "s": 4014, "text": "int XOR(string bits1,string bits2){\n\t// return sum of 1s \n\n\tif(bits1.length() != bits2.length())\n\t\treturn -1;\n\n\tint osum = 0;\n\tfor(int i = 0;i < bits1.length();i++) {\n\t\tif(bits1[i] != bits2[i])\n\t\t\tosum += 1;\n\t}\n\treturn osum;\n}\n\nint minFlips(string S)\n{\n\tstring zeroFirst = \"0\",oneFirst = \"1\";\n\tfor(int i = 2;i <= S.length();i++){\n\t\tif(i % 2 == 0) {\n\t\t\tzeroFirst += \"1\";\n\t\t\toneFirst += \"0\";\n\t\t} else {\n\t\t\tzeroFirst += \"0\";\n\t\t\toneFirst += \"1\";\n\t\t}\n\t}\n\n\tint xZero = XOR(S,zeroFirst),xOne = XOR(S,oneFirst);\n\n\treturn (xZero > xOne) ? xOne : xZero;\n}" }, { "code": null, "e": 4564, "s": 4561, "text": "+2" }, { "code": null, "e": 4597, "s": 4564, "text": "manishmaheshwari81332 months ago" }, { "code": null, "e": 4607, "s": 4597, "text": "JAVA CODE" }, { "code": null, "e": 4617, "s": 4607, "text": "TC=O(|s|)" }, { "code": null, "e": 4625, "s": 4617, "text": "SC=O(1)" }, { "code": null, "e": 4909, "s": 4625, "text": "class Solution {\n public int minFlips(String S) {\n int fir=0,sec=0;\n\n for(int i=0;i<S.length();i++){\n if((i%2==0 && S.charAt(i)=='1')||(i%2!=0 && S.charAt(i)=='0'))fir++;\n else sec++;\n }\n \n return Math.min(fir,sec);\n }\n}" }, { "code": null, "e": 4928, "s": 4911, "text": "another solution" }, { "code": null, "e": 4939, "s": 4928, "text": "TC=O(2|s|)" }, { "code": null, "e": 4947, "s": 4939, "text": "SC=O(1)" }, { "code": null, "e": 5502, "s": 4947, "text": "class Solution {\n public int minFlips(String S) {\n int fir=0,sec=0;\n \n \n for(int i=0;i<S.length();i++){\n if(i%2==0){\n if(S.charAt(i)!='0')fir++;\n }else{\n if(S.charAt(i)!='1')fir++;\n }\n }\n \n for(int i=0;i<S.length();i++){\n if(i%2==0){\n if(S.charAt(i)!='1')sec++;\n }else{\n if(S.charAt(i)!='0')sec++;\n }\n }\n \n return Math.min(fir,sec);\n \n }\n}" }, { "code": null, "e": 5505, "s": 5502, "text": "+1" }, { "code": null, "e": 5531, "s": 5505, "text": "absaarali15482 months ago" }, { "code": null, "e": 5742, "s": 5531, "text": "int minFlips (string S){ int s = 0 , n = S.length(); for(int i = 0 ; i < n ; i+=2) if(S[i]=='1') s++; for(int i = 1 ; i < n ; i+=2) if(S[i]=='0') s++; return min(s,n-s);}" }, { "code": null, "e": 5888, "s": 5742, "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": 5924, "s": 5888, "text": " Login to access your submissions. " }, { "code": null, "e": 5934, "s": 5924, "text": "\nProblem\n" }, { "code": null, "e": 5944, "s": 5934, "text": "\nContest\n" }, { "code": null, "e": 6007, "s": 5944, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6155, "s": 6007, "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": 6363, "s": 6155, "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": 6469, "s": 6363, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Python Overview and Installation
Python is an open source scripting language which is high-level, interpreted, interactive and object-oriented. It is designed to be highly readable. The syntax of Python language is easy to understand and uses English keywords frequently. Python provides the following major features − Python is processed at runtime using the interpreter. There is no need to compile a program before execution. It is similar to PERL and PHP. Python follows object-oriented style and design patterns. It includes class definition with various features like encapsulation and polymorphism. The key points of Python programming language are as follows − It includes functional and structured programming and methods as well as object oriented programming methods. It includes functional and structured programming and methods as well as object oriented programming methods. It can be used as a scripting language or as a programming language. It can be used as a scripting language or as a programming language. It includes automatic garbage collection. It includes automatic garbage collection. It includes high-level dynamic data types and supports various dynamic type checking. It includes high-level dynamic data types and supports various dynamic type checking. Python includes a feature of integration with C, C++ and languages like Java. Python includes a feature of integration with C, C++ and languages like Java. The download link for Python language is as follows − www.python.org/downloadsIt includes packages for various operating systems like Windows, MacOS and Linux distributions. The basic declaration of strings is shown below − str = 'Hello World!' The lists of python can be declared as compound data types, separated by commas and enclosed within square brackets ([]). list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] tinylist = [123, 'john'] A tuple is dynamic data type of Python which consists of number of values separated by commas. Tuples are enclosed with parentheses. tinytuple = (123, 'john') Python dictionary is a type of hash table. A dictionary key can be almost any data type of Python, which are usually numbers or strings. tinydict = {'name': 'omkar','code':6734, 'dept': 'sales'} Python includes a package called cryptography which provides cryptographic recipes and primitives. It supports Python 2.7, Python 3.4+, and PyPy 5.3+. The basic installation of cryptography package is achieved through following command − pip install cryptography There are various packages with both high level recipes and low level interfaces to common cryptographic algorithms such as symmetric ciphers, message digests and key derivation functions. Throughout this tutorial, we will be using various packages of Python for implementation of cryptographic algorithms. 10 Lectures 2 hours Total Seminars 10 Lectures 2 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2531, "s": 2292, "text": "Python is an open source scripting language which is high-level, interpreted, interactive and object-oriented. It is designed to be highly readable. The syntax of Python language is easy to understand and uses English keywords frequently." }, { "code": null, "e": 2578, "s": 2531, "text": "Python provides the following major features −" }, { "code": null, "e": 2719, "s": 2578, "text": "Python is processed at runtime using the interpreter. There is no need to compile a program before execution. It is similar to PERL and PHP." }, { "code": null, "e": 2865, "s": 2719, "text": "Python follows object-oriented style and design patterns. It includes class definition with various features like encapsulation and polymorphism." }, { "code": null, "e": 2928, "s": 2865, "text": "The key points of Python programming language are as follows −" }, { "code": null, "e": 3038, "s": 2928, "text": "It includes functional and structured programming and methods as well as object oriented programming methods." }, { "code": null, "e": 3148, "s": 3038, "text": "It includes functional and structured programming and methods as well as object oriented programming methods." }, { "code": null, "e": 3217, "s": 3148, "text": "It can be used as a scripting language or as a programming language." }, { "code": null, "e": 3286, "s": 3217, "text": "It can be used as a scripting language or as a programming language." }, { "code": null, "e": 3328, "s": 3286, "text": "It includes automatic garbage collection." }, { "code": null, "e": 3370, "s": 3328, "text": "It includes automatic garbage collection." }, { "code": null, "e": 3456, "s": 3370, "text": "It includes high-level dynamic data types and supports various dynamic type checking." }, { "code": null, "e": 3542, "s": 3456, "text": "It includes high-level dynamic data types and supports various dynamic type checking." }, { "code": null, "e": 3620, "s": 3542, "text": "Python includes a feature of integration with C, C++ and languages like Java." }, { "code": null, "e": 3698, "s": 3620, "text": "Python includes a feature of integration with C, C++ and languages like Java." }, { "code": null, "e": 3872, "s": 3698, "text": "The download link for Python language is as follows − www.python.org/downloadsIt includes packages for various operating systems like Windows, MacOS and Linux distributions." }, { "code": null, "e": 3922, "s": 3872, "text": "The basic declaration of strings is shown below −" }, { "code": null, "e": 3944, "s": 3922, "text": "str = 'Hello World!'\n" }, { "code": null, "e": 4066, "s": 3944, "text": "The lists of python can be declared as compound data types, separated by commas and enclosed within square brackets ([])." }, { "code": null, "e": 4136, "s": 4066, "text": "list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]\ntinylist = [123, 'john']\n" }, { "code": null, "e": 4269, "s": 4136, "text": "A tuple is dynamic data type of Python which consists of number of values separated by commas. Tuples are enclosed with parentheses." }, { "code": null, "e": 4296, "s": 4269, "text": "tinytuple = (123, 'john')\n" }, { "code": null, "e": 4433, "s": 4296, "text": "Python dictionary is a type of hash table. A dictionary key can be almost any data type of Python, which are usually numbers or strings." }, { "code": null, "e": 4492, "s": 4433, "text": "tinydict = {'name': 'omkar','code':6734, 'dept': 'sales'}\n" }, { "code": null, "e": 4730, "s": 4492, "text": "Python includes a package called cryptography which provides cryptographic recipes and primitives. It supports Python 2.7, Python 3.4+, and PyPy 5.3+. The basic installation of cryptography package is achieved through following command −" }, { "code": null, "e": 4756, "s": 4730, "text": "pip install cryptography\n" }, { "code": null, "e": 4945, "s": 4756, "text": "There are various packages with both high level recipes and low level interfaces to common cryptographic algorithms such as symmetric ciphers, message digests and key derivation functions." }, { "code": null, "e": 5063, "s": 4945, "text": "Throughout this tutorial, we will be using various packages of Python for implementation of cryptographic algorithms." }, { "code": null, "e": 5096, "s": 5063, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 5112, "s": 5096, "text": " Total Seminars" }, { "code": null, "e": 5145, "s": 5112, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 5168, "s": 5145, "text": " Stone River ELearning" }, { "code": null, "e": 5175, "s": 5168, "text": " Print" }, { "code": null, "e": 5186, "s": 5175, "text": " Add Notes" } ]
Code a Deep Neural Network. Hands on Practice of Building a Deep... | by Jeremy Zhang | Towards Data Science
In last post, we’ve built a 1-hidden layer neural network with basic functions in python. To generalize and empower our network, in this post, we will build a n-layer neural network to do a binary classification task, in which n is customisable (it is recommended to go over my last introduction of neural network as the basics of theory would not be repeated here). All images created on my own, referred images are source-added. Firstly, weights need to be initialized for different layers. Note that in general, the input is not considered as a layer, but output is. (For detailed training and testing process, please check here) We’ve learnt that for lth layer: where n^[0] equals the number input feature. Consider a neural network below: In this case, the first W^[1] would have shape (4, 2) , and the second W^[2] would have shape (1, 4) . Where input requires to be a list, for the case above the input layer would be [2, 4, 1] And our initialized weights need to be small enough so that the gradient would large in the backpropagation process and learning would be faster. The forward process would be straight-forward as listed below: Where l is the lth layer and g(x) is the activation function. Here we would use 2 different activation function: All the function above applies to matrix. The forward propagation would be following the equations above. Note that in our implementation, except the last layer we use sigmoid activation, the rest we use relu activation function. Still we consider this a binary classification, the cost of a batch would be: Where a is the predicted value, and y is the actual one. Now that our forward process has finished, in order to let our model to improve through iterations, let’s get to the key which is backward propagation. [source: https://github.com/enggen/Deep-Learning-Coursera ] The backward gradient can be calculated in recurrent fashion: First, implementation of derivative of sigmoid and relu is required. For symmetrical reasons, here we have both functions with the same input even though it is not required. Following the equations above, we have our implementation of backward propagation. Note that except the last layer where sigmoid function is used, the rest we all apply relu derivative to get the gradients. Now given the gradients, we have our weights updated as following: Let’s have our model apply on created dataset with 200 features. Now let’s have our model trained. Here we have a 3-layer NN with 200 input features. To have the detailed training process, please check my github.
[ { "code": null, "e": 538, "s": 171, "text": "In last post, we’ve built a 1-hidden layer neural network with basic functions in python. To generalize and empower our network, in this post, we will build a n-layer neural network to do a binary classification task, in which n is customisable (it is recommended to go over my last introduction of neural network as the basics of theory would not be repeated here)." }, { "code": null, "e": 602, "s": 538, "text": "All images created on my own, referred images are source-added." }, { "code": null, "e": 741, "s": 602, "text": "Firstly, weights need to be initialized for different layers. Note that in general, the input is not considered as a layer, but output is." }, { "code": null, "e": 804, "s": 741, "text": "(For detailed training and testing process, please check here)" }, { "code": null, "e": 837, "s": 804, "text": "We’ve learnt that for lth layer:" }, { "code": null, "e": 882, "s": 837, "text": "where n^[0] equals the number input feature." }, { "code": null, "e": 915, "s": 882, "text": "Consider a neural network below:" }, { "code": null, "e": 1018, "s": 915, "text": "In this case, the first W^[1] would have shape (4, 2) , and the second W^[2] would have shape (1, 4) ." }, { "code": null, "e": 1097, "s": 1018, "text": "Where input requires to be a list, for the case above the input layer would be" }, { "code": null, "e": 1107, "s": 1097, "text": "[2, 4, 1]" }, { "code": null, "e": 1253, "s": 1107, "text": "And our initialized weights need to be small enough so that the gradient would large in the backpropagation process and learning would be faster." }, { "code": null, "e": 1316, "s": 1253, "text": "The forward process would be straight-forward as listed below:" }, { "code": null, "e": 1429, "s": 1316, "text": "Where l is the lth layer and g(x) is the activation function. Here we would use 2 different activation function:" }, { "code": null, "e": 1471, "s": 1429, "text": "All the function above applies to matrix." }, { "code": null, "e": 1659, "s": 1471, "text": "The forward propagation would be following the equations above. Note that in our implementation, except the last layer we use sigmoid activation, the rest we use relu activation function." }, { "code": null, "e": 1737, "s": 1659, "text": "Still we consider this a binary classification, the cost of a batch would be:" }, { "code": null, "e": 1794, "s": 1737, "text": "Where a is the predicted value, and y is the actual one." }, { "code": null, "e": 1946, "s": 1794, "text": "Now that our forward process has finished, in order to let our model to improve through iterations, let’s get to the key which is backward propagation." }, { "code": null, "e": 2006, "s": 1946, "text": "[source: https://github.com/enggen/Deep-Learning-Coursera ]" }, { "code": null, "e": 2068, "s": 2006, "text": "The backward gradient can be calculated in recurrent fashion:" }, { "code": null, "e": 2137, "s": 2068, "text": "First, implementation of derivative of sigmoid and relu is required." }, { "code": null, "e": 2242, "s": 2137, "text": "For symmetrical reasons, here we have both functions with the same input even though it is not required." }, { "code": null, "e": 2449, "s": 2242, "text": "Following the equations above, we have our implementation of backward propagation. Note that except the last layer where sigmoid function is used, the rest we all apply relu derivative to get the gradients." }, { "code": null, "e": 2516, "s": 2449, "text": "Now given the gradients, we have our weights updated as following:" }, { "code": null, "e": 2581, "s": 2516, "text": "Let’s have our model apply on created dataset with 200 features." }, { "code": null, "e": 2615, "s": 2581, "text": "Now let’s have our model trained." }, { "code": null, "e": 2666, "s": 2615, "text": "Here we have a 3-layer NN with 200 input features." } ]
Operating Systems | Set 8 - GeeksforGeeks
27 Mar, 2017 Following questions have been asked in GATE 2009 CS exam. 1) In which one of the following page replacement policies, Belady’s anomaly may occur?(A) FIFO(B) Optimal(C) LRU(D) MRU Answer (A)Belady’s anomaly proves that it is possible to have more page faults when increasing the number of page frames while using the First in First Out (FIFO) page replacement algorithm.See the wiki page for an example of increasing page faults with number of page frames. 2) The essential content(s) in each entry of a page table is / are(A) Virtual page number(B) Page frame number(C) Both virtual page number and page frame number(D) Access right information Answer (B)A page table entry must contain Page frame number. Virtual page number is typically used as index in page table to get the corresponding page frame number. See this for details. 3) Consider a system with 4 types of resources R1 (3 units), R2 (2 units), R3 (3 units), R4 (2 units). A non-preemptive resource allocation policy is used. At any given instance, a request is not entertained if it cannot be completely satisfied. Three processes P1, P2, P3 request the sources as follows if executed independently. Process P1: t=0: requests 2 units of R2 t=1: requests 1 unit of R3 t=3: requests 2 units of R1 t=5: releases 1 unit of R2 and 1 unit of R1. t=7: releases 1 unit of R3 t=8: requests 2 units of R4 t=10: Finishes Process P2: t=0: requests 2 units of R3 t=2: requests 1 unit of R4 t=4: requests 1 unit of R1 t=6: releases 1 unit of R3 t=8: Finishes Process P3: t=0: requests 1 unit of R4 t=2: requests 2 units of R1 t=5: releases 2 units of R1 t=7: requests 1 unit of R2 t=8: requests 1 unit of R3 t=9: Finishes Which one of the following statements is TRUE if all three processes run concurrently starting at time t=0?(A) All processes will finish without any deadlock(B) Only P1 and P2 will be in deadlock.(C) Only P1 and P3 will be in a deadlock.(D) All three processes will be in deadlock Answer (A)We can apply the following Deadlock Detection algorithm and see that there is no process waiting indefinitely for a resource. See this for deadlock detection algorithm. 4) Consider a disk system with 100 cylinders. The requests to access the cylinders occur in following sequence:4, 34, 10, 7, 19, 73, 2, 15, 6, 20Assuming that the head is currently at cylinder 50, what is the time taken to satisfy all requests if it takes 1ms to move from one cylinder to adjacent one and shortest seek time first policy is used?(A) 95ms(B) 119ms(C) 233ms(D) 276ms Answer (B)4, 34, 10, 7, 19, 73, 2, 15, 6, 20Since shortest seek time first policy is used, head will first move to 34. This move will cause 16*1 ms. After 34, head will move to 20 which will cause 14*1 ms. And so on. So cylinders are accessed in following order 34, 20, 19, 15, 10, 7, 6, 4, 2, 73 and total time will be (16 + 14 + 1 + 4 + 5 + 3 + 1 + 2 + 2 + 71)*1 = 119 ms. Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc. Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above. GATE-CS-2009 GATE CS MCQ Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Page Replacement Algorithms in Operating Systems Differences between TCP and UDP Semaphores in Process Synchronization Inter Process Communication (IPC) Introduction of Operating System - Set 1 Data Structures and Algorithms | Set 25 Operating Systems | Set 1 Practice questions on Height balanced/AVL Tree Computer Networks | Set 1 Computer Networks | Set 2
[ { "code": null, "e": 25265, "s": 25237, "text": "\n27 Mar, 2017" }, { "code": null, "e": 25323, "s": 25265, "text": "Following questions have been asked in GATE 2009 CS exam." }, { "code": null, "e": 25444, "s": 25323, "text": "1) In which one of the following page replacement policies, Belady’s anomaly may occur?(A) FIFO(B) Optimal(C) LRU(D) MRU" }, { "code": null, "e": 25721, "s": 25444, "text": "Answer (A)Belady’s anomaly proves that it is possible to have more page faults when increasing the number of page frames while using the First in First Out (FIFO) page replacement algorithm.See the wiki page for an example of increasing page faults with number of page frames." }, { "code": null, "e": 25910, "s": 25721, "text": "2) The essential content(s) in each entry of a page table is / are(A) Virtual page number(B) Page frame number(C) Both virtual page number and page frame number(D) Access right information" }, { "code": null, "e": 26098, "s": 25910, "text": "Answer (B)A page table entry must contain Page frame number. Virtual page number is typically used as index in page table to get the corresponding page frame number. See this for details." }, { "code": null, "e": 26429, "s": 26098, "text": "3) Consider a system with 4 types of resources R1 (3 units), R2 (2 units), R3 (3 units), R4 (2 units). A non-preemptive resource allocation policy is used. At any given instance, a request is not entertained if it cannot be completely satisfied. Three processes P1, P2, P3 request the sources as follows if executed independently." }, { "code": null, "e": 26970, "s": 26429, "text": "Process P1: \nt=0: requests 2 units of R2 \nt=1: requests 1 unit of R3 \nt=3: requests 2 units of R1 \nt=5: releases 1 unit of R2 \n and 1 unit of R1. \nt=7: releases 1 unit of R3 \nt=8: requests 2 units of R4 \nt=10: Finishes\n\nProcess P2: \nt=0: requests 2 units of R3 \nt=2: requests 1 unit of R4 \nt=4: requests 1 unit of R1 \nt=6: releases 1 unit of R3 \nt=8: Finishes\n\nProcess P3: \nt=0: requests 1 unit of R4 \nt=2: requests 2 units of R1 \nt=5: releases 2 units of R1 \nt=7: requests 1 unit of R2 \nt=8: requests 1 unit of R3 \nt=9: Finishes\n" }, { "code": null, "e": 27251, "s": 26970, "text": "Which one of the following statements is TRUE if all three processes run concurrently starting at time t=0?(A) All processes will finish without any deadlock(B) Only P1 and P2 will be in deadlock.(C) Only P1 and P3 will be in a deadlock.(D) All three processes will be in deadlock" }, { "code": null, "e": 27430, "s": 27251, "text": "Answer (A)We can apply the following Deadlock Detection algorithm and see that there is no process waiting indefinitely for a resource. See this for deadlock detection algorithm." }, { "code": null, "e": 27812, "s": 27430, "text": "4) Consider a disk system with 100 cylinders. The requests to access the cylinders occur in following sequence:4, 34, 10, 7, 19, 73, 2, 15, 6, 20Assuming that the head is currently at cylinder 50, what is the time taken to satisfy all requests if it takes 1ms to move from one cylinder to adjacent one and shortest seek time first policy is used?(A) 95ms(B) 119ms(C) 233ms(D) 276ms" }, { "code": null, "e": 28187, "s": 27812, "text": "Answer (B)4, 34, 10, 7, 19, 73, 2, 15, 6, 20Since shortest seek time first policy is used, head will first move to 34. This move will cause 16*1 ms. After 34, head will move to 20 which will cause 14*1 ms. And so on. So cylinders are accessed in following order 34, 20, 19, 15, 10, 7, 6, 4, 2, 73 and total time will be (16 + 14 + 1 + 4 + 5 + 3 + 1 + 2 + 2 + 71)*1 = 119 ms." }, { "code": null, "e": 28301, "s": 28187, "text": "Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc." }, { "code": null, "e": 28450, "s": 28301, "text": "Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above." }, { "code": null, "e": 28463, "s": 28450, "text": "GATE-CS-2009" }, { "code": null, "e": 28471, "s": 28463, "text": "GATE CS" }, { "code": null, "e": 28475, "s": 28471, "text": "MCQ" }, { "code": null, "e": 28493, "s": 28475, "text": "Operating Systems" }, { "code": null, "e": 28511, "s": 28493, "text": "Operating Systems" }, { "code": null, "e": 28609, "s": 28511, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28658, "s": 28609, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 28690, "s": 28658, "text": "Differences between TCP and UDP" }, { "code": null, "e": 28728, "s": 28690, "text": "Semaphores in Process Synchronization" }, { "code": null, "e": 28762, "s": 28728, "text": "Inter Process Communication (IPC)" }, { "code": null, "e": 28803, "s": 28762, "text": "Introduction of Operating System - Set 1" }, { "code": null, "e": 28843, "s": 28803, "text": "Data Structures and Algorithms | Set 25" }, { "code": null, "e": 28869, "s": 28843, "text": "Operating Systems | Set 1" }, { "code": null, "e": 28916, "s": 28869, "text": "Practice questions on Height balanced/AVL Tree" }, { "code": null, "e": 28942, "s": 28916, "text": "Computer Networks | Set 1" } ]
W3Schools Code Game
W3Schools is optimized for learning, testing, and training. Examples might be simplified to improve reading and basic understanding. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy. Copyright 1999-2022 by Refsnes Data. All Rights Reserved.
[]
Create your own smart baby monitor with a RaspberryPi and Tensorflow | by Fabio Manganiello | Towards Data Science
An updated version of this story is available on the Platypush blog. Some of you may have noticed that it’s been a while since my last article. That’s because I’ve become a dad in the meantime, and I’ve had to take a momentary break from my projects to deal with some parental tasks that can’t (yet) be automated. Or, can they? While we’re probably still a few years away from a robot that can completely take charge of the task of changing your son’s diapers (assuming that enough crazy parents agree to test such a device on their own toddlers), there are some less risky parental duties out there that offer some margin for automation. One of the first things I’ve come to realize as a father is that infants can really cry a lot, and even if I’m at home I may not always be nearby enough to hear my son’s cries. Commercial baby monitors usually step in to fill that gap and they act as intercoms that let you hear your baby’s sounds even if you’re in another room. But I’ve soon realized that commercial baby monitors are dumber than the ideal device I’d want. They don’t detect your baby’s cries — they simply act like intercoms that take sound from a source to a speaker. It’s up to the parent to move the speaker as they move to different rooms, as they can’t play the sound on any other existing audio infrastructure. They usually come with low-power speakers, and they usually can’t be connected to external speakers — it means that if I’m in another room playing music I may miss my baby’s cries, even if the monitor is in the same room as mine. And most of them work on low-power radio waves, which means that they usually won’t work if the baby is in his/her room and you have to take a short walk down to the basement. So I’ve come with a specification for a smart baby monitor. It should run on anything as simple and cheap as a RaspberryPi with a cheap USB microphone. It should detect my baby’s cries and notify me (ideally on my phone) when he starts/stops crying, or track the data points on my dashboard, or do any kind of tasks that I’d want to run when my son is crying. It shouldn’t only act as a dumb intercom that delivers sound from a source to one single type of compatible device. It should be able to stream the audio on any device — my own speakers, my smartphone, my computer etc. It should work no matter the distance between the source and the speaker, with no need to move the speaker around the house. It should also come with a camera, so I can either check in real-time how my baby is doing or I can get a picture or a short video feed of the crib when he starts crying to check that everything is alright. Let’s see how to use our favourite open-source tools to get this job done. First of all, get a RaspberryPi and flash any compatible Linux OS on an SD card — it’s better to use any RaspberryPi 3 or higher to run the Tensorflow model. Also get a compatible USB microphone — anything will work, really. Then install the dependencies that we’ll need: [sudo] apt-get install ffmpeg lame libatlas-base-dev alsa-utils[sudo] pip3 install tensorflow As a first step, we’ll have to record enough audio samples where the baby cries and where the baby doesn’t cry that we’ll use later to train the audio detection model. Note: in this example I’ll show how to use sound detection to recognize a baby’s cries, but the same exact procedure can be used to detect any type of sounds — as long as they’re long enough (e.g. an alarm or your neighbour’s drilling) and loud enough over the background noise. First, take a look at the recognized audio input devices: arecord -l On my RaspberryPi I get the following output (note that I have two USB microphones): **** List of CAPTURE Hardware Devices ****card 1: Device [USB PnP Sound Device], device 0: USB Audio [USB Audio] Subdevices: 0/1 Subdevice #0: subdevice #0card 2: Device_1 [USB PnP Sound Device], device 0: USB Audio [USB Audio] Subdevices: 0/1 Subdevice #0: subdevice #0 I want to use the second microphone to record sounds — that’s card 2, device 0. The ALSA way of identifying it is either hw:2,0 (which accesses the hardware device directly) or plughw:2,0(which infers sample rate and format conversion plugins if required). Make sure that you have enough space on your SD card or plug an external USB drive, and then start recording some audio: arecord -D plughw:2,0 -c 1 -f cd | lame - audio.mp3 Record a few minutes or hours of audio while your baby is in the same room — preferably with long sessions both of silence, baby cries and other non-related sounds — and Ctrl-C the process when done. Repeat the procedure as many times as you like to get audio samples over different moments of the day or over different days. Once you have enough audio samples, it’s time to copy them over to your computer to train the model — either use scp to copy the files, or copy them directly from the SD card/USB drive. Let’s store them all under the same directory, e.g. ~/datasets/sound-detect/audio. Also, let’s create a new folder for each of the samples. Each folder will contain an audio file (named audio.mp3) and a labels file (named labels.json) that we’ll use to label the negative/positive audio segments in the audio file. So the structure of the raw dataset will be something like: ~/datasets/sound-detect/audio -> sample_1 -> audio.mp3 -> labels.json -> sample_2 -> audio.mp3 -> labels.json ... The boring part comes now: labeling the recorded audio files — and it can be particularly masochistic if they contain hours of your own baby’s cries. Open each of the dataset audio files either in your favourite audio player or in Audacity and create a new labels.json file in each of the samples directories. Identify the exact time where the cries start and where they end, and report them in labels.json as a key-value structure in the form time_string -> label. Example: { "00:00": "negative", "02:13": "positive", "04:57": "negative", "15:41": "positive", "18:24": "negative"} In the example above, all the audio segments between 00:00 and 02:12 will be labelled as negative, all the audio segments between 02:13 and 04:56 will be labelled as positive, and so on. Once you have labelled all the audio samples, let’s proceed with generating the dataset that will be fed to the Tensorflow model. I have created a generic library and set of utilities for sound monitoring called micmon. Let’s start with installing it: git clone [email protected]:/BlackLight/micmon.gitcd micmon[sudo] pip3 install -r requirements.txt[sudo] python3 setup.py build install The model is designed to work on frequency samples instead of raw audio. The reason is that, if we want to detect a specific sound, that sound will have a specific “spectral” signature — i.e. a base frequency (or a narrow range where the base frequency may usually fall) and a specific set of harmonics bound to the base frequency by specific ratios. Moreover, the ratios between such frequencies are not affected neither by amplitude (the frequency ratios are constant regardless of the input volume) nor by phase (a continuous sound will have the same spectral signature regardless of when you start recording it). Such an amplitude and time invariant property makes this approach much more likely to train a robust sound detection model compared to the case where we simply feed raw audio samples to a model. Moreover, this model can be simpler (we can easily group frequencies into bins without affecting the performance, thus we can effectively perform dimensional reduction), much lighter (the model will have between 50 and 100 frequency bands as input values, regardless of the sample duration, while one second of raw audio usually contains 44100 data points, and the length of the input increases with the duration of the sample) and less prone to overfit. micmon provides the logic to calculate the FFT (Fast-Fourier Transform) of some segments of the audio samples, group the resulting spectrum into bands with low-pass and high-pass filters and save the result to a set of numpy compressed (.npz) files. You can do it over command-line through the micmon-datagen command: micmon-datagen \ --low 250 --high 2500 --bins 100 \ --sample-duration 2 --channels 1 \ ~/datasets/sound-detect/audio ~/datasets/sound-detect/data In the example above we generate a dataset from raw audio samples stored under ~/dataset/sound-detect/audio and store the resulting spectral data to ~/datasets/sound-detect/data. --low and --high respectively identify the lowest and highest frequency to be taken into account in the resulting spectrum. The default values are respectively 20 Hz (lowest frequency audible to a human ear) and 20 kHz (highest frequency audible to a healthy and young human ear). However, you may usually want to restrict this range to capture as much as possible of the sound that you want to detect and limit as much as possible any other type of audio background and unrelated harmonics. I have found in my case that a 250–2500 Hz range is good enough to detect baby cries. Baby cries are usually high-pitched (consider that the highest note an opera soprano can reach is around 1000 Hz), and you may usually want to at least double the highest frequency to make sure that you get enough higher harmonics (the harmonics are the higher frequencies that actually give a timbre, or colour, to a sound), but not too high to pollute the spectrum with harmonics from other background sounds. I also cut anything below 250 Hz — a baby’s cry sound probably won’t have much happening on those low frequencies, and including them may also skew detection. A good approach is to open some positive audio samples in e.g. Audacity or any equalizer/spectrum analyzer, check which frequencies are dominant in the positive samples and center your dataset around those frequencies. --bins specifies the number of groups for the frequency space (default: 100). A higher number of bins means a higher frequency resolution/granularity, but if it’s too high it may make the model prone to overfit. The script splits the original audio into smaller segments and it calculates the spectral “signature” of each of those segments. --sample-duration specifies how long each of these segments should be (default: 2 seconds). A higher value may work better with sounds that last longer, but it’ll decrease the time-to-detection and it’ll probably fail on short sounds. A lower value may work better with shorter sounds, but the captured segments may not have enough information to reliably identify the sound if the sound is longer. An alternative approach to the micmon-datagen script is to make your own script for generating the dataset through the provided micmon API. Example: Whether you used micmon-datagen or the micmon Python API, at the end of the process you should find a bunch of .npz files under ~/datasets/sound-detect/data, one for each labelled audio file in the original dataset. We can use this dataset to train our neural network for sound detection. micmon uses Tensorflow+Keras to define and train the model. It can easily be done with the provided Python API. Example: After running this script (and after you’re happy with the model’s accuracy) you’ll find your new model saved under ~/models/sound-detect. In my case it was sufficient to collect ~5 hours of sounds from my baby’s room and define a good frequency range to train a model with >98% accuracy. If you trained this model on your computer, just copy it to the RaspberryPi and you’re ready for the next step. Time to make a script that uses the previously trained model on live audio data from the microphone and notifies us when our baby is crying: Run the script on the RaspberryPi and leave it running for a bit — it will print negative if no cries have been detected over the past 2 seconds and positive otherwise. There’s not much use however in a script that simply prints a message to the standard output if our baby is crying — we want to be notified! Let’s use Platypush to cover this part. In this example, we’ll use the pushbullet integration to send a message to our mobile when cry is detected. Let’s install Redis (used by Platypush to receive messages) and Platypush with the HTTP and Pushbullet integrations: [sudo] apt-get install redis-server[sudo] systemctl start redis-server.service[sudo] systemctl enable redis-server.service[sudo] pip3 install 'platypush[http,pushbullet]' Install the Pushbullet app on your smartphone and head to pushbullet.com to get an API token. Then create a ~/.config/platypush/config.yaml file that enables the HTTP and Pushbullet integrations: backend.http: enabled: Truepushbullet: token: YOUR_TOKEN Now, let’s modify the previous script so that, instead of printing a message to the standard output, it triggers a CustomEvent that can be captured by a Platypush hook: Save the script above as e.g. ~/bin/micmon_detect.py. The script only triggers an event if at least positive_samples samples are detected over a sliding window of window_length seconds (that’s to reduce the noise caused by prediction errors or temporary glitches), and it only triggers an event when the current prediction goes from negative to positive or the other way around. The event is then dispatched to Platypush over the RedisBus. The script should also be general-purpose enough to work with any sound model (not necessarily that of a crying infant), any positive/negative labels, any frequency range and any type of output event. Let’s now create a Platypush hook to react on the event and send a notification to our devices. First, prepare the Platypush scripts directory if it’s not been created already: mkdir -p ~/.config/platypush/scriptscd ~/.config/platypush/scripts# Define the directory as a moduletouch __init__.py# Create a script for the baby-cry eventsvi babymonitor.py Content of babymonitor.py: Now create a service file for Platypush if it’s not present already and start/enable the service so it will automatically restart on termination or reboot: mkdir -p ~/.config/systemd/userwget -O ~/.config/systemd/user/platypush.service \ https://raw.githubusercontent.com/BlackLight/platypush/master/examples/systemd/platypush.servicesystemctl --user start platypush.servicesystemctl --user enable platypush.service And also create a service file for the baby monitor — e.g. ~/.config/systemd/user/babymonitor.service: [Unit]Description=Monitor to detect my baby's criesAfter=network.target sound.target[Service]ExecStart=/home/pi/bin/micmon_detect.py -i plughw:2,0 -e baby-cry -w 10 -n 2 ~/models/sound-detectRestart=alwaysRestartSec=10[Install]WantedBy=default.target This service will start the microphone monitor on the ALSA device plughw:2,0and it will fire a baby-cry event with state=positive if at least 2 positive 2-second samples have been detected over the past 10 seconds and the previous state was negative, and state=negative if less than 2 positive samples were detected over the past 10 seconds and the previous state was positive. We can then start/enable the service: systemctl --user start babymonitor.servicesystemctl --user enable babymonitor.service Verify that as soon as the baby starts crying you receive a notification on your phone. If you don’t you may other review the labels you applied to your audio samples, the architecture and parameters of your neural network, or the sample length/window/frequency band parameters. Also, consider that this is a relatively basic example of automation — feel free to spice it up with more automation tasks. For example, you can send a request to another Platypush device (e.g. in your bedroom or living room) with the tts plugin to say aloud that the baby is crying. You can also extend the micmon_detect.py script so that the captured audio samples can also be streamed over HTTP — for example using a Flask wrapper and ffmpeg for the audio conversion. Another interesting use case is to send data points to your local database when the baby starts/stops crying (you can refer to my previous article on how to use Platypush+PostgreSQL+Mosquitto+Grafana to create your flexible and self-managed dashboards): it’s a useful set of data to track when your baby sleeps, is awake or needs feeding. And, again, monitoring my baby has been the main motivation behind developing micmon, but the exact same procedure can be used to train and use models to detect any type of sound. Finally, you may consider using a good power bank or a pack of lithium batteries to make your sound monitor mobile. Once you have a good audio feed and a way to detect when a positive audio sequence starts/stops, you may want to add a video feed to keep an eye on your baby. While in my first set up I had mounted a PiCamera on the same RaspberryPi 3 I used for the audio detection, I found this configuration quite unpractical. A RaspberryPi 3 sitting in its case, with an attached pack of batteries and a camera somehow glued on top can be quite bulky if you’re looking for a light camera that you can easily install on a stand or flexible arm and you can move around to keep an eye on your baby wherever he/she is. I have eventually opted for a smaller RaspberryPi Zero with a PiCamera compatible case and a small power bank. Like on the other device, plug an SD card with a RaspberryPi-compatible OS. Then plug a RaspberryPi-compatible camera in its slot, make sure that the camera module is enabled in raspi-config and install Platypush with the PiCamera integration: [sudo] pip3 install 'platypush[http,camera,picamera]' Then add the camera configuration in ~/.config/platypush/config.yaml: camera.pi: listen_port: 5001 You can already check this configuration on Platypush restart and get snapshots from the camera over HTTP: wget http://raspberry-pi:8008/camera/pi/photo.jpg Or open the video feed in your browser: http://raspberry-pi:8008/camera/pi/video.mjpg Or you can create a hook that starts streaming the camera feed over TCP/H264 when the application starts: mkdir -p ~/.config/platypush/scriptscd ~/.config/platypush/scriptstouch __init__.pyvi camera.py Content of camera.py: You will be able to play the feed in e.g. VLC: vlc tcp/h264://raspberry-pi:5001 Or on your phone either through the VLC app or apps like RPi Camera Viewer. Last step is to set up a direct microphone stream from your baby’s RaspberryPi to whichever client you may want to use. The Tensorflow model is good to nudge you when the baby is crying, but we all know that machine learning models aren’t exactly notorious for achieving 100% accuracy. Some time you may simply be sitting in another room and want to hear what’s happening in your baby’s room. I have made a tool/library for purpose called micstream — it can actually be used in any situation where you want to set up an audio feed from a microphone over HTTP/mp3. Note: if you use a microphone to feed audio to the Tensorflow model, then you’ll need another microphone for streaming. Just clone the repository and install the software (the only dependency is the ffmpeg executable installed on the system): git clone https://github.com/BlackLight/micstream.gitcd micstream[sudo] python3 setup.py install You can get a full list of the available options with micstream --help. For example, if you want to set up streaming on the 3rd audio input device (use arecord -l to get the full list), on the /baby.mp3 endpoint, listening on port 8088 and with 96 kbps bitrate, then the command will be: micstream -i plughw:3,0 -e '/baby.mp3' -b 96 -p 8088 You can now simply open http://your-rpi:8088/baby.mp3 from any browser or audio player and you’ll have a real-time audio feed from the baby monitor.
[ { "code": null, "e": 241, "s": 172, "text": "An updated version of this story is available on the Platypush blog." }, { "code": null, "e": 486, "s": 241, "text": "Some of you may have noticed that it’s been a while since my last article. That’s because I’ve become a dad in the meantime, and I’ve had to take a momentary break from my projects to deal with some parental tasks that can’t (yet) be automated." }, { "code": null, "e": 811, "s": 486, "text": "Or, can they? While we’re probably still a few years away from a robot that can completely take charge of the task of changing your son’s diapers (assuming that enough crazy parents agree to test such a device on their own toddlers), there are some less risky parental duties out there that offer some margin for automation." }, { "code": null, "e": 1904, "s": 811, "text": "One of the first things I’ve come to realize as a father is that infants can really cry a lot, and even if I’m at home I may not always be nearby enough to hear my son’s cries. Commercial baby monitors usually step in to fill that gap and they act as intercoms that let you hear your baby’s sounds even if you’re in another room. But I’ve soon realized that commercial baby monitors are dumber than the ideal device I’d want. They don’t detect your baby’s cries — they simply act like intercoms that take sound from a source to a speaker. It’s up to the parent to move the speaker as they move to different rooms, as they can’t play the sound on any other existing audio infrastructure. They usually come with low-power speakers, and they usually can’t be connected to external speakers — it means that if I’m in another room playing music I may miss my baby’s cries, even if the monitor is in the same room as mine. And most of them work on low-power radio waves, which means that they usually won’t work if the baby is in his/her room and you have to take a short walk down to the basement." }, { "code": null, "e": 1964, "s": 1904, "text": "So I’ve come with a specification for a smart baby monitor." }, { "code": null, "e": 2056, "s": 1964, "text": "It should run on anything as simple and cheap as a RaspberryPi with a cheap USB microphone." }, { "code": null, "e": 2380, "s": 2056, "text": "It should detect my baby’s cries and notify me (ideally on my phone) when he starts/stops crying, or track the data points on my dashboard, or do any kind of tasks that I’d want to run when my son is crying. It shouldn’t only act as a dumb intercom that delivers sound from a source to one single type of compatible device." }, { "code": null, "e": 2483, "s": 2380, "text": "It should be able to stream the audio on any device — my own speakers, my smartphone, my computer etc." }, { "code": null, "e": 2608, "s": 2483, "text": "It should work no matter the distance between the source and the speaker, with no need to move the speaker around the house." }, { "code": null, "e": 2815, "s": 2608, "text": "It should also come with a camera, so I can either check in real-time how my baby is doing or I can get a picture or a short video feed of the crib when he starts crying to check that everything is alright." }, { "code": null, "e": 2890, "s": 2815, "text": "Let’s see how to use our favourite open-source tools to get this job done." }, { "code": null, "e": 3115, "s": 2890, "text": "First of all, get a RaspberryPi and flash any compatible Linux OS on an SD card — it’s better to use any RaspberryPi 3 or higher to run the Tensorflow model. Also get a compatible USB microphone — anything will work, really." }, { "code": null, "e": 3162, "s": 3115, "text": "Then install the dependencies that we’ll need:" }, { "code": null, "e": 3256, "s": 3162, "text": "[sudo] apt-get install ffmpeg lame libatlas-base-dev alsa-utils[sudo] pip3 install tensorflow" }, { "code": null, "e": 3703, "s": 3256, "text": "As a first step, we’ll have to record enough audio samples where the baby cries and where the baby doesn’t cry that we’ll use later to train the audio detection model. Note: in this example I’ll show how to use sound detection to recognize a baby’s cries, but the same exact procedure can be used to detect any type of sounds — as long as they’re long enough (e.g. an alarm or your neighbour’s drilling) and loud enough over the background noise." }, { "code": null, "e": 3761, "s": 3703, "text": "First, take a look at the recognized audio input devices:" }, { "code": null, "e": 3772, "s": 3761, "text": "arecord -l" }, { "code": null, "e": 3857, "s": 3772, "text": "On my RaspberryPi I get the following output (note that I have two USB microphones):" }, { "code": null, "e": 4132, "s": 3857, "text": "**** List of CAPTURE Hardware Devices ****card 1: Device [USB PnP Sound Device], device 0: USB Audio [USB Audio] Subdevices: 0/1 Subdevice #0: subdevice #0card 2: Device_1 [USB PnP Sound Device], device 0: USB Audio [USB Audio] Subdevices: 0/1 Subdevice #0: subdevice #0" }, { "code": null, "e": 4510, "s": 4132, "text": "I want to use the second microphone to record sounds — that’s card 2, device 0. The ALSA way of identifying it is either hw:2,0 (which accesses the hardware device directly) or plughw:2,0(which infers sample rate and format conversion plugins if required). Make sure that you have enough space on your SD card or plug an external USB drive, and then start recording some audio:" }, { "code": null, "e": 4562, "s": 4510, "text": "arecord -D plughw:2,0 -c 1 -f cd | lame - audio.mp3" }, { "code": null, "e": 4888, "s": 4562, "text": "Record a few minutes or hours of audio while your baby is in the same room — preferably with long sessions both of silence, baby cries and other non-related sounds — and Ctrl-C the process when done. Repeat the procedure as many times as you like to get audio samples over different moments of the day or over different days." }, { "code": null, "e": 5074, "s": 4888, "text": "Once you have enough audio samples, it’s time to copy them over to your computer to train the model — either use scp to copy the files, or copy them directly from the SD card/USB drive." }, { "code": null, "e": 5449, "s": 5074, "text": "Let’s store them all under the same directory, e.g. ~/datasets/sound-detect/audio. Also, let’s create a new folder for each of the samples. Each folder will contain an audio file (named audio.mp3) and a labels file (named labels.json) that we’ll use to label the negative/positive audio segments in the audio file. So the structure of the raw dataset will be something like:" }, { "code": null, "e": 5578, "s": 5449, "text": "~/datasets/sound-detect/audio -> sample_1 -> audio.mp3 -> labels.json -> sample_2 -> audio.mp3 -> labels.json ..." }, { "code": null, "e": 6053, "s": 5578, "text": "The boring part comes now: labeling the recorded audio files — and it can be particularly masochistic if they contain hours of your own baby’s cries. Open each of the dataset audio files either in your favourite audio player or in Audacity and create a new labels.json file in each of the samples directories. Identify the exact time where the cries start and where they end, and report them in labels.json as a key-value structure in the form time_string -> label. Example:" }, { "code": null, "e": 6165, "s": 6053, "text": "{ \"00:00\": \"negative\", \"02:13\": \"positive\", \"04:57\": \"negative\", \"15:41\": \"positive\", \"18:24\": \"negative\"}" }, { "code": null, "e": 6352, "s": 6165, "text": "In the example above, all the audio segments between 00:00 and 02:12 will be labelled as negative, all the audio segments between 02:13 and 04:56 will be labelled as positive, and so on." }, { "code": null, "e": 6604, "s": 6352, "text": "Once you have labelled all the audio samples, let’s proceed with generating the dataset that will be fed to the Tensorflow model. I have created a generic library and set of utilities for sound monitoring called micmon. Let’s start with installing it:" }, { "code": null, "e": 6737, "s": 6604, "text": "git clone [email protected]:/BlackLight/micmon.gitcd micmon[sudo] pip3 install -r requirements.txt[sudo] python3 setup.py build install" }, { "code": null, "e": 8004, "s": 6737, "text": "The model is designed to work on frequency samples instead of raw audio. The reason is that, if we want to detect a specific sound, that sound will have a specific “spectral” signature — i.e. a base frequency (or a narrow range where the base frequency may usually fall) and a specific set of harmonics bound to the base frequency by specific ratios. Moreover, the ratios between such frequencies are not affected neither by amplitude (the frequency ratios are constant regardless of the input volume) nor by phase (a continuous sound will have the same spectral signature regardless of when you start recording it). Such an amplitude and time invariant property makes this approach much more likely to train a robust sound detection model compared to the case where we simply feed raw audio samples to a model. Moreover, this model can be simpler (we can easily group frequencies into bins without affecting the performance, thus we can effectively perform dimensional reduction), much lighter (the model will have between 50 and 100 frequency bands as input values, regardless of the sample duration, while one second of raw audio usually contains 44100 data points, and the length of the input increases with the duration of the sample) and less prone to overfit." }, { "code": null, "e": 8322, "s": 8004, "text": "micmon provides the logic to calculate the FFT (Fast-Fourier Transform) of some segments of the audio samples, group the resulting spectrum into bands with low-pass and high-pass filters and save the result to a set of numpy compressed (.npz) files. You can do it over command-line through the micmon-datagen command:" }, { "code": null, "e": 8478, "s": 8322, "text": "micmon-datagen \\ --low 250 --high 2500 --bins 100 \\ --sample-duration 2 --channels 1 \\ ~/datasets/sound-detect/audio ~/datasets/sound-detect/data" }, { "code": null, "e": 10237, "s": 8478, "text": "In the example above we generate a dataset from raw audio samples stored under ~/dataset/sound-detect/audio and store the resulting spectral data to ~/datasets/sound-detect/data. --low and --high respectively identify the lowest and highest frequency to be taken into account in the resulting spectrum. The default values are respectively 20 Hz (lowest frequency audible to a human ear) and 20 kHz (highest frequency audible to a healthy and young human ear). However, you may usually want to restrict this range to capture as much as possible of the sound that you want to detect and limit as much as possible any other type of audio background and unrelated harmonics. I have found in my case that a 250–2500 Hz range is good enough to detect baby cries. Baby cries are usually high-pitched (consider that the highest note an opera soprano can reach is around 1000 Hz), and you may usually want to at least double the highest frequency to make sure that you get enough higher harmonics (the harmonics are the higher frequencies that actually give a timbre, or colour, to a sound), but not too high to pollute the spectrum with harmonics from other background sounds. I also cut anything below 250 Hz — a baby’s cry sound probably won’t have much happening on those low frequencies, and including them may also skew detection. A good approach is to open some positive audio samples in e.g. Audacity or any equalizer/spectrum analyzer, check which frequencies are dominant in the positive samples and center your dataset around those frequencies. --bins specifies the number of groups for the frequency space (default: 100). A higher number of bins means a higher frequency resolution/granularity, but if it’s too high it may make the model prone to overfit." }, { "code": null, "e": 10765, "s": 10237, "text": "The script splits the original audio into smaller segments and it calculates the spectral “signature” of each of those segments. --sample-duration specifies how long each of these segments should be (default: 2 seconds). A higher value may work better with sounds that last longer, but it’ll decrease the time-to-detection and it’ll probably fail on short sounds. A lower value may work better with shorter sounds, but the captured segments may not have enough information to reliably identify the sound if the sound is longer." }, { "code": null, "e": 10914, "s": 10765, "text": "An alternative approach to the micmon-datagen script is to make your own script for generating the dataset through the provided micmon API. Example:" }, { "code": null, "e": 11203, "s": 10914, "text": "Whether you used micmon-datagen or the micmon Python API, at the end of the process you should find a bunch of .npz files under ~/datasets/sound-detect/data, one for each labelled audio file in the original dataset. We can use this dataset to train our neural network for sound detection." }, { "code": null, "e": 11324, "s": 11203, "text": "micmon uses Tensorflow+Keras to define and train the model. It can easily be done with the provided Python API. Example:" }, { "code": null, "e": 11725, "s": 11324, "text": "After running this script (and after you’re happy with the model’s accuracy) you’ll find your new model saved under ~/models/sound-detect. In my case it was sufficient to collect ~5 hours of sounds from my baby’s room and define a good frequency range to train a model with >98% accuracy. If you trained this model on your computer, just copy it to the RaspberryPi and you’re ready for the next step." }, { "code": null, "e": 11866, "s": 11725, "text": "Time to make a script that uses the previously trained model on live audio data from the microphone and notifies us when our baby is crying:" }, { "code": null, "e": 12035, "s": 11866, "text": "Run the script on the RaspberryPi and leave it running for a bit — it will print negative if no cries have been detected over the past 2 seconds and positive otherwise." }, { "code": null, "e": 12441, "s": 12035, "text": "There’s not much use however in a script that simply prints a message to the standard output if our baby is crying — we want to be notified! Let’s use Platypush to cover this part. In this example, we’ll use the pushbullet integration to send a message to our mobile when cry is detected. Let’s install Redis (used by Platypush to receive messages) and Platypush with the HTTP and Pushbullet integrations:" }, { "code": null, "e": 12612, "s": 12441, "text": "[sudo] apt-get install redis-server[sudo] systemctl start redis-server.service[sudo] systemctl enable redis-server.service[sudo] pip3 install 'platypush[http,pushbullet]'" }, { "code": null, "e": 12808, "s": 12612, "text": "Install the Pushbullet app on your smartphone and head to pushbullet.com to get an API token. Then create a ~/.config/platypush/config.yaml file that enables the HTTP and Pushbullet integrations:" }, { "code": null, "e": 12867, "s": 12808, "text": "backend.http: enabled: Truepushbullet: token: YOUR_TOKEN" }, { "code": null, "e": 13036, "s": 12867, "text": "Now, let’s modify the previous script so that, instead of printing a message to the standard output, it triggers a CustomEvent that can be captured by a Platypush hook:" }, { "code": null, "e": 13677, "s": 13036, "text": "Save the script above as e.g. ~/bin/micmon_detect.py. The script only triggers an event if at least positive_samples samples are detected over a sliding window of window_length seconds (that’s to reduce the noise caused by prediction errors or temporary glitches), and it only triggers an event when the current prediction goes from negative to positive or the other way around. The event is then dispatched to Platypush over the RedisBus. The script should also be general-purpose enough to work with any sound model (not necessarily that of a crying infant), any positive/negative labels, any frequency range and any type of output event." }, { "code": null, "e": 13854, "s": 13677, "text": "Let’s now create a Platypush hook to react on the event and send a notification to our devices. First, prepare the Platypush scripts directory if it’s not been created already:" }, { "code": null, "e": 14030, "s": 13854, "text": "mkdir -p ~/.config/platypush/scriptscd ~/.config/platypush/scripts# Define the directory as a moduletouch __init__.py# Create a script for the baby-cry eventsvi babymonitor.py" }, { "code": null, "e": 14057, "s": 14030, "text": "Content of babymonitor.py:" }, { "code": null, "e": 14213, "s": 14057, "text": "Now create a service file for Platypush if it’s not present already and start/enable the service so it will automatically restart on termination or reboot:" }, { "code": null, "e": 14476, "s": 14213, "text": "mkdir -p ~/.config/systemd/userwget -O ~/.config/systemd/user/platypush.service \\ https://raw.githubusercontent.com/BlackLight/platypush/master/examples/systemd/platypush.servicesystemctl --user start platypush.servicesystemctl --user enable platypush.service" }, { "code": null, "e": 14579, "s": 14476, "text": "And also create a service file for the baby monitor — e.g. ~/.config/systemd/user/babymonitor.service:" }, { "code": null, "e": 14830, "s": 14579, "text": "[Unit]Description=Monitor to detect my baby's criesAfter=network.target sound.target[Service]ExecStart=/home/pi/bin/micmon_detect.py -i plughw:2,0 -e baby-cry -w 10 -n 2 ~/models/sound-detectRestart=alwaysRestartSec=10[Install]WantedBy=default.target" }, { "code": null, "e": 15246, "s": 14830, "text": "This service will start the microphone monitor on the ALSA device plughw:2,0and it will fire a baby-cry event with state=positive if at least 2 positive 2-second samples have been detected over the past 10 seconds and the previous state was negative, and state=negative if less than 2 positive samples were detected over the past 10 seconds and the previous state was positive. We can then start/enable the service:" }, { "code": null, "e": 15332, "s": 15246, "text": "systemctl --user start babymonitor.servicesystemctl --user enable babymonitor.service" }, { "code": null, "e": 15611, "s": 15332, "text": "Verify that as soon as the baby starts crying you receive a notification on your phone. If you don’t you may other review the labels you applied to your audio samples, the architecture and parameters of your neural network, or the sample length/window/frequency band parameters." }, { "code": null, "e": 16717, "s": 15611, "text": "Also, consider that this is a relatively basic example of automation — feel free to spice it up with more automation tasks. For example, you can send a request to another Platypush device (e.g. in your bedroom or living room) with the tts plugin to say aloud that the baby is crying. You can also extend the micmon_detect.py script so that the captured audio samples can also be streamed over HTTP — for example using a Flask wrapper and ffmpeg for the audio conversion. Another interesting use case is to send data points to your local database when the baby starts/stops crying (you can refer to my previous article on how to use Platypush+PostgreSQL+Mosquitto+Grafana to create your flexible and self-managed dashboards): it’s a useful set of data to track when your baby sleeps, is awake or needs feeding. And, again, monitoring my baby has been the main motivation behind developing micmon, but the exact same procedure can be used to train and use models to detect any type of sound. Finally, you may consider using a good power bank or a pack of lithium batteries to make your sound monitor mobile." }, { "code": null, "e": 17430, "s": 16717, "text": "Once you have a good audio feed and a way to detect when a positive audio sequence starts/stops, you may want to add a video feed to keep an eye on your baby. While in my first set up I had mounted a PiCamera on the same RaspberryPi 3 I used for the audio detection, I found this configuration quite unpractical. A RaspberryPi 3 sitting in its case, with an attached pack of batteries and a camera somehow glued on top can be quite bulky if you’re looking for a light camera that you can easily install on a stand or flexible arm and you can move around to keep an eye on your baby wherever he/she is. I have eventually opted for a smaller RaspberryPi Zero with a PiCamera compatible case and a small power bank." }, { "code": null, "e": 17674, "s": 17430, "text": "Like on the other device, plug an SD card with a RaspberryPi-compatible OS. Then plug a RaspberryPi-compatible camera in its slot, make sure that the camera module is enabled in raspi-config and install Platypush with the PiCamera integration:" }, { "code": null, "e": 17728, "s": 17674, "text": "[sudo] pip3 install 'platypush[http,camera,picamera]'" }, { "code": null, "e": 17798, "s": 17728, "text": "Then add the camera configuration in ~/.config/platypush/config.yaml:" }, { "code": null, "e": 17830, "s": 17798, "text": "camera.pi: listen_port: 5001" }, { "code": null, "e": 17937, "s": 17830, "text": "You can already check this configuration on Platypush restart and get snapshots from the camera over HTTP:" }, { "code": null, "e": 17987, "s": 17937, "text": "wget http://raspberry-pi:8008/camera/pi/photo.jpg" }, { "code": null, "e": 18027, "s": 17987, "text": "Or open the video feed in your browser:" }, { "code": null, "e": 18073, "s": 18027, "text": "http://raspberry-pi:8008/camera/pi/video.mjpg" }, { "code": null, "e": 18179, "s": 18073, "text": "Or you can create a hook that starts streaming the camera feed over TCP/H264 when the application starts:" }, { "code": null, "e": 18275, "s": 18179, "text": "mkdir -p ~/.config/platypush/scriptscd ~/.config/platypush/scriptstouch __init__.pyvi camera.py" }, { "code": null, "e": 18297, "s": 18275, "text": "Content of camera.py:" }, { "code": null, "e": 18344, "s": 18297, "text": "You will be able to play the feed in e.g. VLC:" }, { "code": null, "e": 18377, "s": 18344, "text": "vlc tcp/h264://raspberry-pi:5001" }, { "code": null, "e": 18453, "s": 18377, "text": "Or on your phone either through the VLC app or apps like RPi Camera Viewer." }, { "code": null, "e": 18846, "s": 18453, "text": "Last step is to set up a direct microphone stream from your baby’s RaspberryPi to whichever client you may want to use. The Tensorflow model is good to nudge you when the baby is crying, but we all know that machine learning models aren’t exactly notorious for achieving 100% accuracy. Some time you may simply be sitting in another room and want to hear what’s happening in your baby’s room." }, { "code": null, "e": 19137, "s": 18846, "text": "I have made a tool/library for purpose called micstream — it can actually be used in any situation where you want to set up an audio feed from a microphone over HTTP/mp3. Note: if you use a microphone to feed audio to the Tensorflow model, then you’ll need another microphone for streaming." }, { "code": null, "e": 19260, "s": 19137, "text": "Just clone the repository and install the software (the only dependency is the ffmpeg executable installed on the system):" }, { "code": null, "e": 19357, "s": 19260, "text": "git clone https://github.com/BlackLight/micstream.gitcd micstream[sudo] python3 setup.py install" }, { "code": null, "e": 19645, "s": 19357, "text": "You can get a full list of the available options with micstream --help. For example, if you want to set up streaming on the 3rd audio input device (use arecord -l to get the full list), on the /baby.mp3 endpoint, listening on port 8088 and with 96 kbps bitrate, then the command will be:" }, { "code": null, "e": 19698, "s": 19645, "text": "micstream -i plughw:3,0 -e '/baby.mp3' -b 96 -p 8088" } ]
Gulp - Installation
This article provides a step-by-step procedure of Gulp installation. Operating System − Cross-platform Operating System − Cross-platform Browser Support − IE (Internet Explorer 8+), Firefox, Google Chrome, Safari, Opera Browser Support − IE (Internet Explorer 8+), Firefox, Google Chrome, Safari, Opera Step 1 − We need Node.js to run Gulp examples. To download Node.js, open the https://nodejs.org/en/, you will see a screen as shown below − Download the latest features version of the zip file. Step 2 − Next, run the setup to install the NodeJs on your computer. Step 3 − You need to set environment variables. Right-click on My Computer. Select Properties. Select Advanced tab and click ‘Environment Variables’. Under Environment Variables window, double-click on the PATH as shown in the following screen. Under Environment Variables window, double-click on the PATH as shown in the following screen. You will get an Edit User Variable window as shown in the following screenshot. Add Node.js folder path in the Variable Value field as C:\Program Files\nodejs\node_modules\npm. If the path is set already for other files, then you need to put a semicolon (;) after that and add the Node.js path as shown in the following screenshot. You will get an Edit User Variable window as shown in the following screenshot. Add Node.js folder path in the Variable Value field as C:\Program Files\nodejs\node_modules\npm. If the path is set already for other files, then you need to put a semicolon (;) after that and add the Node.js path as shown in the following screenshot. At the end, click the ‘Ok’ button. System Variable Under System variables, double-click on Path as shown in the following screen. Under System variables, double-click on Path as shown in the following screen. You will get an Edit System Variable window as shown in the following screenshot. Add Node.js folder path in the Variable Value field as C:\Program Files\nodejs\ and click ‘Ok’ as shown in the following screenshot. You will get an Edit System Variable window as shown in the following screenshot. Add Node.js folder path in the Variable Value field as C:\Program Files\nodejs\ and click ‘Ok’ as shown in the following screenshot. Step 4 − Open the command prompt in your system and enter the following command. It will display the installed Node.js version. node -v Step 5 − In the command prompt, enter the following command to display the version of npm (Node.js package manager) which is used to install modules. It will display the installed Node.js version. npm -v Step 6 − In the command prompt, enter the following command to install Gulp. Adding “-g” flag ensures that the Gulp is globally available for any project. npm install gulp -g Step 7 − To verify that Gulp has been installed successfully, enter the following command to display the Gulp version. gulp -v Print Add Notes Bookmark this page
[ { "code": null, "e": 1885, "s": 1816, "text": "This article provides a step-by-step procedure of Gulp installation." }, { "code": null, "e": 1919, "s": 1885, "text": "Operating System − Cross-platform" }, { "code": null, "e": 1953, "s": 1919, "text": "Operating System − Cross-platform" }, { "code": null, "e": 2036, "s": 1953, "text": "Browser Support − IE (Internet Explorer 8+), Firefox, Google Chrome, Safari, Opera" }, { "code": null, "e": 2119, "s": 2036, "text": "Browser Support − IE (Internet Explorer 8+), Firefox, Google Chrome, Safari, Opera" }, { "code": null, "e": 2259, "s": 2119, "text": "Step 1 − We need Node.js to run Gulp examples. To download Node.js, open the https://nodejs.org/en/, you will see a screen as shown below −" }, { "code": null, "e": 2313, "s": 2259, "text": "Download the latest features version of the zip file." }, { "code": null, "e": 2382, "s": 2313, "text": "Step 2 − Next, run the setup to install the NodeJs on your computer." }, { "code": null, "e": 2430, "s": 2382, "text": "Step 3 − You need to set environment variables." }, { "code": null, "e": 2458, "s": 2430, "text": "Right-click on My Computer." }, { "code": null, "e": 2477, "s": 2458, "text": "Select Properties." }, { "code": null, "e": 2532, "s": 2477, "text": "Select Advanced tab and click ‘Environment Variables’." }, { "code": null, "e": 2627, "s": 2532, "text": "Under Environment Variables window, double-click on the PATH as shown in the following screen." }, { "code": null, "e": 2722, "s": 2627, "text": "Under Environment Variables window, double-click on the PATH as shown in the following screen." }, { "code": null, "e": 3054, "s": 2722, "text": "You will get an Edit User Variable window as shown in the following screenshot. Add Node.js folder path in the Variable Value field as C:\\Program Files\\nodejs\\node_modules\\npm. If the path is set already for other files, then you need to put a semicolon (;) after that and add the Node.js path as shown in the following screenshot." }, { "code": null, "e": 3386, "s": 3054, "text": "You will get an Edit User Variable window as shown in the following screenshot. Add Node.js folder path in the Variable Value field as C:\\Program Files\\nodejs\\node_modules\\npm. If the path is set already for other files, then you need to put a semicolon (;) after that and add the Node.js path as shown in the following screenshot." }, { "code": null, "e": 3421, "s": 3386, "text": "At the end, click the ‘Ok’ button." }, { "code": null, "e": 3437, "s": 3421, "text": "System Variable" }, { "code": null, "e": 3516, "s": 3437, "text": "Under System variables, double-click on Path as shown in the following screen." }, { "code": null, "e": 3595, "s": 3516, "text": "Under System variables, double-click on Path as shown in the following screen." }, { "code": null, "e": 3810, "s": 3595, "text": "You will get an Edit System Variable window as shown in the following screenshot. Add Node.js folder path in the Variable Value field as C:\\Program Files\\nodejs\\ and click ‘Ok’ as shown in the following screenshot." }, { "code": null, "e": 4025, "s": 3810, "text": "You will get an Edit System Variable window as shown in the following screenshot. Add Node.js folder path in the Variable Value field as C:\\Program Files\\nodejs\\ and click ‘Ok’ as shown in the following screenshot." }, { "code": null, "e": 4153, "s": 4025, "text": "Step 4 − Open the command prompt in your system and enter the following command. It will display the installed Node.js version." }, { "code": null, "e": 4162, "s": 4153, "text": "node -v\n" }, { "code": null, "e": 4359, "s": 4162, "text": "Step 5 − In the command prompt, enter the following command to display the version of npm (Node.js package manager) which is used to install modules. It will display the installed Node.js version." }, { "code": null, "e": 4367, "s": 4359, "text": "npm -v\n" }, { "code": null, "e": 4522, "s": 4367, "text": "Step 6 − In the command prompt, enter the following command to install Gulp. Adding “-g” flag ensures that the Gulp is globally available for any project." }, { "code": null, "e": 4543, "s": 4522, "text": "npm install gulp -g\n" }, { "code": null, "e": 4662, "s": 4543, "text": "Step 7 − To verify that Gulp has been installed successfully, enter the following command to display the Gulp version." }, { "code": null, "e": 4671, "s": 4662, "text": "gulp -v\n" }, { "code": null, "e": 4678, "s": 4671, "text": " Print" }, { "code": null, "e": 4689, "s": 4678, "text": " Add Notes" } ]
Line detection in python with OpenCV?
In this post, we are going to learn, how to detect lines in an image, with the help of a technique called Hough transform. Hough transform is a feature extraction method to detect any simple shape, if you can represent that shape in mathematical form. It somehow manage to detect the shape even if it is broken or distorted a little bit. We will see how it works for a line. A “simple” shape is one that can be represented by only a few parameters. For example, a line can be represented by two parameters only (slope, intercept) and a circle has three parameters – the coordinates of the center and the radius (x,y, r). A line can be represented by an equation- or in parametric form it can be representated as, as where (ρ) is the perpendicular distance from origin to the line, and Θ is the angle formed by this perpendicular line and horizontal axis measured in counter-clockwise (This representation is used in OpenCV). Check below image So if line is passing below the origin, it will have a positive rho and angle less than 180. If it is going above the origin, instead of taking angle greater than 180, angle is taken less than 180, and rho is taken negative. Any vertical line will have 0 degree and horizontal lines will have 90 degree. Any line can be representated in these two terms (ρ,Θ). So first it creates a 2D array or accumulator (to hold values of two parameters) and it is set to 0 initially. Where rows denote the ρ and columns denote the Θ. Size of array depends on the accuracy we need, for example, if we need accuracy of angles to be 1 degree, you need 180 columns and ρ, is the maximum distance possible is the diagonal length of the image and ρ is the maximum distance possible is the diagonal length of the image. So taking one pixel accuracy and number of rows can be diagonal length of the image. Consider we have an image of 100*100 with a horizontal line at the middle. Take the first point of the line, and we know its (x,y) values. Now in the equation, pu the values Θ=0,1,2,3...180 and check the ρ value you get. For every (ρ,Θ) pair, increment value by one is our accumulator in its corresponding (ρ,Θ) cells. So now in accumulator, the cell (50,90) = 1 along with some other cells. Now take the second spot on the line. Repeat the same procedure as we did for first spot. Increment the values in the cells corresponding to (ρ,Θ) you get. This time, the cell (50,90)=2. So we are actually voting the (ρ,Θ) values. We continue this process for every point on the line. At each spot, the cell (50,90) will be incremented or voted up, while other cells may not be voted up. This way, at the end, the cell(50,90) will have maximum votes. So if you search the accumulator for maximum votes, you get the value (50,90) which says, there is a line in this image at distance 50 from origin and at angle 90 degrees. This is how hough transform for lines works. Everything explained above is encapsulated in the OpenCV function, cv2.HoughLines(). It simply returns an array of (ρ,Θ) values where ρ is measured in pixels and Θ is measured in radians. Below is a program of line detection using openCV and hough line transform. Below is actual image of a parking lot, and we are going to do line detection on this image using hough line transform and OpenCV library. import cv2 import numpy as np img = cv2.imread("parkingLot1.jpg") gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray, 75, 150) lines = cv2.HoughLinesP(edges, 1, np.pi/180, 30, maxLineGap=250) for line in lines: x1, y1, x2, y2 = line[0] cv2.line(img, (x1, y1), (x2, y2), (0, 0, 128), 1) cv2.imshow("linesEdges", edges) cv2.imshow("linesDetected", img) cv2.waitKey(0) cv2.destroyAllWindows() And lines detected−
[ { "code": null, "e": 1185, "s": 1062, "text": "In this post, we are going to learn, how to detect lines in an image, with the help of a technique called Hough transform." }, { "code": null, "e": 1437, "s": 1185, "text": "Hough transform is a feature extraction method to detect any simple shape, if you can represent that shape in mathematical form. It somehow manage to detect the shape even if it is broken or distorted a little bit. We will see how it works for a line." }, { "code": null, "e": 1683, "s": 1437, "text": "A “simple” shape is one that can be represented by only a few parameters. For example, a line can be represented by two parameters only (slope, intercept) and a circle has three parameters – the coordinates of the center and the radius (x,y, r)." }, { "code": null, "e": 2007, "s": 1683, "text": "A line can be represented by an equation- or in parametric form it can be representated as, as where (ρ) is the perpendicular distance from origin to the line, and Θ is the angle formed by this perpendicular line and horizontal axis measured in counter-clockwise (This representation is used in OpenCV). Check below image" }, { "code": null, "e": 2311, "s": 2007, "text": "So if line is passing below the origin, it will have a positive rho and angle less than 180. If it is going above the origin, instead of taking angle greater than 180, angle is taken less than 180, and rho is taken negative. Any vertical line will have 0 degree and horizontal lines will have 90 degree." }, { "code": null, "e": 2892, "s": 2311, "text": "Any line can be representated in these two terms (ρ,Θ). So first it creates a 2D array or accumulator (to hold values of two parameters) and it is set to 0 initially. Where rows denote the ρ and columns denote the Θ. Size of array depends on the accuracy we need, for example, if we need accuracy of angles to be 1 degree, you need 180 columns and ρ, is the maximum distance possible is the diagonal length of the image and ρ is the maximum distance possible is the diagonal length of the image. So taking one pixel accuracy and number of rows can be diagonal length of the image." }, { "code": null, "e": 3952, "s": 2892, "text": "Consider we have an image of 100*100 with a horizontal line at the middle. Take the first point of the line, and we know its (x,y) values. Now in the equation, pu the values Θ=0,1,2,3...180 and check the ρ value you get. For every (ρ,Θ) pair, increment value by one is our accumulator in its corresponding (ρ,Θ) cells. So now in accumulator, the cell (50,90) = 1 along with some other cells. Now take the second spot on the line. Repeat the same procedure as we did for first spot. Increment the values in the cells corresponding to (ρ,Θ) you get. This time, the cell (50,90)=2. So we are actually voting the (ρ,Θ) values. We continue this process for every point on the line. At each spot, the cell (50,90) will be incremented or voted up, while other cells may not be voted up. This way, at the end, the cell(50,90) will have maximum votes. So if you search the accumulator for maximum votes, you get the value (50,90) which says, there is a line in this image at distance 50 from origin and at angle 90 degrees. This is how hough transform for lines works." }, { "code": null, "e": 4140, "s": 3952, "text": "Everything explained above is encapsulated in the OpenCV function, cv2.HoughLines(). It simply returns an array of (ρ,Θ) values where ρ is measured in pixels and Θ is measured in radians." }, { "code": null, "e": 4216, "s": 4140, "text": "Below is a program of line detection using openCV and hough line transform." }, { "code": null, "e": 4355, "s": 4216, "text": "Below is actual image of a parking lot, and we are going to do line detection on this image using hough line transform and OpenCV library." }, { "code": null, "e": 4768, "s": 4355, "text": "import cv2\nimport numpy as np\nimg = cv2.imread(\"parkingLot1.jpg\")\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\nedges = cv2.Canny(gray, 75, 150)\nlines = cv2.HoughLinesP(edges, 1, np.pi/180, 30, maxLineGap=250)\nfor line in lines:\n x1, y1, x2, y2 = line[0]\n cv2.line(img, (x1, y1), (x2, y2), (0, 0, 128), 1)\ncv2.imshow(\"linesEdges\", edges)\ncv2.imshow(\"linesDetected\", img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()" }, { "code": null, "e": 4788, "s": 4768, "text": "And lines detected−" } ]
Find sum of all Boundary and Diagonal element of a Matrix - GeeksforGeeks
14 Dec, 2021 Given a 2D array arr[][] of order NxN, the task is to find the sum of all the elements present in both the diagonals and boundary elements of the given arr[][]. Examples: Input: arr[][] = { {1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 4} } Output: 40 Explanation: The Sum of elements on the boundary is 1 + 2 + 3 + 4 + 4 + 4 + 4 + 3 + 2 + 1 + 1 + 1 = 30. The Sum of elements on the diagonals which do not intersect with the boundary elements is 2 + 3 + 2 + 3 = 10. Therefore the required sum is 30 + 10 = 40.Input: arr[][] = { {1, 2, 3}, {1, 2, 3}, {1, 2, 3}} Output: 18 Explanation: The Sum of elements on the boundary is 1 + 2 + 3 + 3 + 3 + 2 + 1 + 1 = 16. The Sum of elements on the diagonals which do not intersect with the boundary elements is 2. Therefore the required sum is 16 + 2 = 18. Approach: Traverse the given 2D array with two loops, one for rows(say i) and another for columns(say j).If i equals to j or (i + j) equals to (size of column – 1) then that element contributes to diagonals of the given 2D array.If (i or j equals to 0) or (i or j equals to size of column – 1) then that element contributes to boundary elements of the given 2D array.The sum of all the element satisfying above two conditions gives the required sum. Traverse the given 2D array with two loops, one for rows(say i) and another for columns(say j). If i equals to j or (i + j) equals to (size of column – 1) then that element contributes to diagonals of the given 2D array. If (i or j equals to 0) or (i or j equals to size of column – 1) then that element contributes to boundary elements of the given 2D array. The sum of all the element satisfying above two conditions gives the required sum. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the above approach #include "bits/stdc++.h"using namespace std; const int N = 4; // Function to find the sum of all diagonal// and Boundary elementsvoid diagonalBoundarySum(int arr[N][N]){ int requiredSum = 0; // Traverse arr[][] // Loop from i to N-1 for rows for (int i = 0; i < N; i++) { // Loop from j = N-1 for columns for (int j = 0; j < N; j++) { // Condition for diagonal // elements if (i == j || (i + j) == N - 1) { requiredSum += arr[i][j]; } // Condition for Boundary // elements else if (i == 0 || j == 0 || i == N - 1 || j == N - 1) { requiredSum += arr[i][j]; } } } // Print the final Sum cout << requiredSum << endl;} // Driver Codeint main(){ int arr[][4] = { { 1, 2, 3, 4 }, { 1, 2, 3, 4 }, { 1, 2, 3, 4 }, { 1, 2, 3, 4 } }; diagonalBoundarySum(arr); return 0;} // Java implementation of the above approachimport java.util.*; class GFG{ public static int N = 4; // Function to find the sum of all diagonal // and Boundary elements static void diagonalBoundarySum(int arr[][]){ int requiredSum = 0; // Traverse arr[][] // Loop from i to N-1 for rows for (int i = 0; i < N; i++) { // Loop from j = N-1 for columns for (int j = 0; j < N; j++) { // Condition for diagonal // elements if (i == j || (i + j) == N - 1) { requiredSum += arr[i][j]; } // Condition for Boundary // elements else if (i == 0 || j == 0 || i == N - 1|| j == N - 1) { requiredSum += arr[i][j]; } } } // Print the final Sum System.out.println(requiredSum); } // Driver Code public static void main(String args[]) { int arr[][] = { { 1, 2, 3, 4 },{ 1, 2, 3, 4 }, { 1, 2, 3, 4 },{ 1, 2, 3, 4 } }; diagonalBoundarySum(arr); }} // This code is contributed by AbhiThakur # Python implementation of the above approach N = 4; # Function to find the sum of all diagonal# and Boundary elementsdef diagonalBoundarySum(arr): requiredSum = 0; # Traverse arr # Loop from i to N-1 for rows for i in range(N): # Loop from j = N-1 for columns for j in range(N): # Condition for diagonal # elements if (i == j or (i + j) == N - 1): requiredSum += arr[i][j]; # Condition for Boundary # elements elif(i == 0 or j == 0 or i == N - 1 or j == N - 1): requiredSum += arr[i][j]; # Print the final Sum print(requiredSum); # Driver Codeif __name__ == '__main__': arr = [[ 1, 2, 3, 4 ], [ 1, 2, 3, 4 ], [ 1, 2, 3, 4 ], [ 1, 2, 3, 4 ]]; diagonalBoundarySum(arr); # This code is contributed by 29AjayKumar // C# implementation of the above approachusing System; class GFG{ public static int N = 4; // Function to find the sum of all diagonal // and Boundary elements static void diagonalBoundarySum(int[, ] arr){ int requiredSum = 0; // Traverse arr[][] // Loop from i to N-1 for rows for (int i = 0; i < N; i++) { // Loop from j = N-1 for columns for (int j = 0; j < N; j++) { // Condition for diagonal // elements if (i == j || (i + j) == N - 1) { requiredSum += arr[i,j]; } // Condition for Boundary // elements else if (i == 0 || j == 0 || i == N - 1|| j == N - 1) { requiredSum += arr[i,j]; } } } // Print the final Sum Console.WriteLine(requiredSum); } // Driver Code public static void Main() { int[, ] arr = { { 1, 2, 3, 4 },{ 1, 2, 3, 4 },{ 1, 2, 3, 4 },{ 1, 2, 3, 4 } }; diagonalBoundarySum(arr); }} // This code is contributed by abhaysingh290895 <script>// Java script implementation of the above approachlet N = 4; // Function to find the sum of all diagonal // and Boundary elements function diagonalBoundarySum(arr){ let requiredSum = 0; // Traverse arr[][] // Loop from i to N-1 for rows for (let i = 0; i < N; i++) { // Loop from j = N-1 for columns for (let j = 0; j < N; j++) { // Condition for diagonal // elements if (i == j || (i + j) == N - 1) { requiredSum += arr[i][j]; } // Condition for Boundary // elements else if (i == 0 || j == 0 || i == N - 1|| j == N - 1) { requiredSum += arr[i][j]; } } } // Print the final Sum document.write(requiredSum); } // Driver Code let arr = [[ 1, 2, 3, 4 ],[ 1, 2, 3, 4 ], [1, 2, 3, 4 ],[ 1, 2, 3, 4 ]]; diagonalBoundarySum(arr); // contributed by sravan kumar</script> 40 abhaysingh290895 29AjayKumar sravankumar8128 ankita_saini debojyoti0391 Arrays Matrix School Programming Arrays Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Window Sliding Technique Trapping Rain Water Building Heap from Array Reversal algorithm for array rotation Program to find sum of elements in a given array Matrix Chain Multiplication | DP-8 Rat in a Maze | Backtracking-2 Divide and Conquer | Set 5 (Strassen's Matrix Multiplication) Sudoku | Backtracking-7 Find the number of islands | Set 1 (Using DFS)
[ { "code": null, "e": 24821, "s": 24793, "text": "\n14 Dec, 2021" }, { "code": null, "e": 24994, "s": 24821, "text": "Given a 2D array arr[][] of order NxN, the task is to find the sum of all the elements present in both the diagonals and boundary elements of the given arr[][]. Examples: " }, { "code": null, "e": 25627, "s": 24994, "text": "Input: arr[][] = { {1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 4} } Output: 40 Explanation: The Sum of elements on the boundary is 1 + 2 + 3 + 4 + 4 + 4 + 4 + 3 + 2 + 1 + 1 + 1 = 30. The Sum of elements on the diagonals which do not intersect with the boundary elements is 2 + 3 + 2 + 3 = 10. Therefore the required sum is 30 + 10 = 40.Input: arr[][] = { {1, 2, 3}, {1, 2, 3}, {1, 2, 3}} Output: 18 Explanation: The Sum of elements on the boundary is 1 + 2 + 3 + 3 + 3 + 2 + 1 + 1 = 16. The Sum of elements on the diagonals which do not intersect with the boundary elements is 2. Therefore the required sum is 16 + 2 = 18. " }, { "code": null, "e": 25641, "s": 25629, "text": "Approach: " }, { "code": null, "e": 26083, "s": 25643, "text": "Traverse the given 2D array with two loops, one for rows(say i) and another for columns(say j).If i equals to j or (i + j) equals to (size of column – 1) then that element contributes to diagonals of the given 2D array.If (i or j equals to 0) or (i or j equals to size of column – 1) then that element contributes to boundary elements of the given 2D array.The sum of all the element satisfying above two conditions gives the required sum." }, { "code": null, "e": 26179, "s": 26083, "text": "Traverse the given 2D array with two loops, one for rows(say i) and another for columns(say j)." }, { "code": null, "e": 26304, "s": 26179, "text": "If i equals to j or (i + j) equals to (size of column – 1) then that element contributes to diagonals of the given 2D array." }, { "code": null, "e": 26443, "s": 26304, "text": "If (i or j equals to 0) or (i or j equals to size of column – 1) then that element contributes to boundary elements of the given 2D array." }, { "code": null, "e": 26526, "s": 26443, "text": "The sum of all the element satisfying above two conditions gives the required sum." }, { "code": null, "e": 26579, "s": 26526, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26583, "s": 26579, "text": "C++" }, { "code": null, "e": 26588, "s": 26583, "text": "Java" }, { "code": null, "e": 26596, "s": 26588, "text": "Python3" }, { "code": null, "e": 26599, "s": 26596, "text": "C#" }, { "code": null, "e": 26610, "s": 26599, "text": "Javascript" }, { "code": "// C++ implementation of the above approach #include \"bits/stdc++.h\"using namespace std; const int N = 4; // Function to find the sum of all diagonal// and Boundary elementsvoid diagonalBoundarySum(int arr[N][N]){ int requiredSum = 0; // Traverse arr[][] // Loop from i to N-1 for rows for (int i = 0; i < N; i++) { // Loop from j = N-1 for columns for (int j = 0; j < N; j++) { // Condition for diagonal // elements if (i == j || (i + j) == N - 1) { requiredSum += arr[i][j]; } // Condition for Boundary // elements else if (i == 0 || j == 0 || i == N - 1 || j == N - 1) { requiredSum += arr[i][j]; } } } // Print the final Sum cout << requiredSum << endl;} // Driver Codeint main(){ int arr[][4] = { { 1, 2, 3, 4 }, { 1, 2, 3, 4 }, { 1, 2, 3, 4 }, { 1, 2, 3, 4 } }; diagonalBoundarySum(arr); return 0;}", "e": 27691, "s": 26610, "text": null }, { "code": "// Java implementation of the above approachimport java.util.*; class GFG{ public static int N = 4; // Function to find the sum of all diagonal // and Boundary elements static void diagonalBoundarySum(int arr[][]){ int requiredSum = 0; // Traverse arr[][] // Loop from i to N-1 for rows for (int i = 0; i < N; i++) { // Loop from j = N-1 for columns for (int j = 0; j < N; j++) { // Condition for diagonal // elements if (i == j || (i + j) == N - 1) { requiredSum += arr[i][j]; } // Condition for Boundary // elements else if (i == 0 || j == 0 || i == N - 1|| j == N - 1) { requiredSum += arr[i][j]; } } } // Print the final Sum System.out.println(requiredSum); } // Driver Code public static void main(String args[]) { int arr[][] = { { 1, 2, 3, 4 },{ 1, 2, 3, 4 }, { 1, 2, 3, 4 },{ 1, 2, 3, 4 } }; diagonalBoundarySum(arr); }} // This code is contributed by AbhiThakur", "e": 28919, "s": 27691, "text": null }, { "code": "# Python implementation of the above approach N = 4; # Function to find the sum of all diagonal# and Boundary elementsdef diagonalBoundarySum(arr): requiredSum = 0; # Traverse arr # Loop from i to N-1 for rows for i in range(N): # Loop from j = N-1 for columns for j in range(N): # Condition for diagonal # elements if (i == j or (i + j) == N - 1): requiredSum += arr[i][j]; # Condition for Boundary # elements elif(i == 0 or j == 0 or i == N - 1 or j == N - 1): requiredSum += arr[i][j]; # Print the final Sum print(requiredSum); # Driver Codeif __name__ == '__main__': arr = [[ 1, 2, 3, 4 ], [ 1, 2, 3, 4 ], [ 1, 2, 3, 4 ], [ 1, 2, 3, 4 ]]; diagonalBoundarySum(arr); # This code is contributed by 29AjayKumar", "e": 29792, "s": 28919, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG{ public static int N = 4; // Function to find the sum of all diagonal // and Boundary elements static void diagonalBoundarySum(int[, ] arr){ int requiredSum = 0; // Traverse arr[][] // Loop from i to N-1 for rows for (int i = 0; i < N; i++) { // Loop from j = N-1 for columns for (int j = 0; j < N; j++) { // Condition for diagonal // elements if (i == j || (i + j) == N - 1) { requiredSum += arr[i,j]; } // Condition for Boundary // elements else if (i == 0 || j == 0 || i == N - 1|| j == N - 1) { requiredSum += arr[i,j]; } } } // Print the final Sum Console.WriteLine(requiredSum); } // Driver Code public static void Main() { int[, ] arr = { { 1, 2, 3, 4 },{ 1, 2, 3, 4 },{ 1, 2, 3, 4 },{ 1, 2, 3, 4 } }; diagonalBoundarySum(arr); }} // This code is contributed by abhaysingh290895", "e": 30978, "s": 29792, "text": null }, { "code": "<script>// Java script implementation of the above approachlet N = 4; // Function to find the sum of all diagonal // and Boundary elements function diagonalBoundarySum(arr){ let requiredSum = 0; // Traverse arr[][] // Loop from i to N-1 for rows for (let i = 0; i < N; i++) { // Loop from j = N-1 for columns for (let j = 0; j < N; j++) { // Condition for diagonal // elements if (i == j || (i + j) == N - 1) { requiredSum += arr[i][j]; } // Condition for Boundary // elements else if (i == 0 || j == 0 || i == N - 1|| j == N - 1) { requiredSum += arr[i][j]; } } } // Print the final Sum document.write(requiredSum); } // Driver Code let arr = [[ 1, 2, 3, 4 ],[ 1, 2, 3, 4 ], [1, 2, 3, 4 ],[ 1, 2, 3, 4 ]]; diagonalBoundarySum(arr); // contributed by sravan kumar</script>", "e": 32097, "s": 30978, "text": null }, { "code": null, "e": 32100, "s": 32097, "text": "40" }, { "code": null, "e": 32119, "s": 32102, "text": "abhaysingh290895" }, { "code": null, "e": 32131, "s": 32119, "text": "29AjayKumar" }, { "code": null, "e": 32147, "s": 32131, "text": "sravankumar8128" }, { "code": null, "e": 32160, "s": 32147, "text": "ankita_saini" }, { "code": null, "e": 32174, "s": 32160, "text": "debojyoti0391" }, { "code": null, "e": 32181, "s": 32174, "text": "Arrays" }, { "code": null, "e": 32188, "s": 32181, "text": "Matrix" }, { "code": null, "e": 32207, "s": 32188, "text": "School Programming" }, { "code": null, "e": 32214, "s": 32207, "text": "Arrays" }, { "code": null, "e": 32221, "s": 32214, "text": "Matrix" }, { "code": null, "e": 32319, "s": 32221, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32344, "s": 32319, "text": "Window Sliding Technique" }, { "code": null, "e": 32364, "s": 32344, "text": "Trapping Rain Water" }, { "code": null, "e": 32389, "s": 32364, "text": "Building Heap from Array" }, { "code": null, "e": 32427, "s": 32389, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 32476, "s": 32427, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 32511, "s": 32476, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 32542, "s": 32511, "text": "Rat in a Maze | Backtracking-2" }, { "code": null, "e": 32604, "s": 32542, "text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)" }, { "code": null, "e": 32628, "s": 32604, "text": "Sudoku | Backtracking-7" } ]
N meetings in one room | Practice | GeeksforGeeks
There is one meeting room in a firm. There are N meetings in the form of (start[i], end[i]) where start[i] is start time of meeting i and end[i] is finish time of meeting i. What is the maximum number of meetings that can be accommodated in the meeting room when only one meeting can be held in the meeting room at a particular time? Note: Start time of one chosen meeting can't be equal to the end time of the other chosen meeting. Example 1: Input: N = 6 start[] = {1,3,0,5,8,5} end[] = {2,4,6,7,9,9} Output: 4 Explanation: Maximum four meetings can be held with given start and end timings. The meetings are - (1, 2),(3, 4), (5,7) and (8,9) Example 2: Input: N = 3 start[] = {10, 12, 20} end[] = {20, 25, 30} Output: 1 Explanation: Only one meetings can be held with given start and end timings. Your Task : You don't need to read inputs or print anything. Complete the function maxMeetings() that takes two arrays start[] and end[] along with their size N as input parameters and returns the maximum number of meetings that can be held in the meeting room. Expected Time Complexity : O(N*LogN) Expected Auxilliary Space : O(N) Constraints: 1 ≤ N ≤ 105 0 ≤ start[i] < end[i] ≤ 105 0 dwivedisatyam12348 hours ago python code res=[] for i in range(n): res.append([start[i],end[i]]) res.sort(key=lambda x:(x[1],x[0])) ans,j,i=1,1,0 for j in range(n): if res[j][0]>res[i][1]: ans+=1 i=j return ans 0 gd29843 days ago int maxMeetings(int start[], int end[], int n) { // Your code here if(n==0) return 0; vector<vector<int>> vec; for(int i{};i<n;i++){ vector<int> v; v.push_back(end[i]); v.push_back(start[i]); // v.push_back(i+1); vec.push_back(v); } sort(vec.begin(), vec.end()); int limit = vec[0][0]; int count{1}; for(int i{1};i<vec.size();i++){ if(vec[i][1]>limit){ limit = vec[i][0]; count++; } } return count; } //east or west vector is the best 0 sikkusaurav1234 days ago int maxMeetings(int start[], int end[], int n) { // Your code here vector<pair<int,int>>v; int starting_point,ending_point; int counting=1; for(int i=0;i<n;i++) { v.push_back(make_pair(end[i],start[i])); } sort(v.begin(),v.end()); starting_point=v[0].second; ending_point=v[0].first; for(int i=1;i<n;i++) { if(v[i].second>ending_point) { ending_point=v[i].first; counting++; } } return counting; } 0 dhruvpurwar155 days ago // { Driver Code Starts #include <bits/stdc++.h> using namespace std; // } Driver Code Ends class Solution { public: //Function to find the maximum number of meetings that can //be performed in a meeting room. bool static cmp(pair<int,int>a, pair<int,int>b){ if(a.second==b.second){ return a.first>b.first; } return a.second<b.second; } int maxMeetings(int start[], int end[], int n) { // Your code here vector<pair<int,int>>vec(n); for(int i=0;i<n;i++){ vec[i].first=start[i]; vec[i].second= end[i]; } // for(auto x: vec){ // cout<<x.first<<" "<<x.second<<endl; // } sort(vec.begin(), vec.end(), cmp); int res=1; int prev=0; for(int i=1;i<n;i++){ if(vec[i].first>vec[prev].second){ res++; prev=i; } } return res; } }; // { Driver Code Starts. int main() { int t; cin >> t; while (t--) { int n; cin >> n; int start[n], end[n]; for (int i = 0; i < n; i++) cin >> start[i]; for (int i = 0; i < n; i++) cin >> end[i]; Solution ob; int ans = ob.maxMeetings(start, end, n); cout << ans << endl; } return 0; } // } Driver Code Ends 0 dhruvpurwar155 days ago ans.push_back(totalJobs); 0 doshividhi0215 days ago def maximumMeetings(self,n,start,end): # code here meetings = list() count = 1 for i in range(len(start)): meet = list() meet.append(start[i]) meet.append(end[i]) meetings.append(meet) sorted(meetings,key=lambda x:x[1]) limit = meetings[0][1] for i in range(1,len(start)): if(meetings[i][0] >= limit): limit = meetings[i][1] count +=1 return count What's wrong in this? 0 ahmedxahoor721 week ago int maxMeetings(int start[], int end[], int n) { // Your code here vector<pair<int,int>>v; for(int i=0;i<n;i++){ v.push_back({end[i],start[i]}); } sort(v.begin(),v.end()); int c=1; int s=v[0].second,e=v[0].first; for(int i=1;i<v.size();i++){ if(v[i].second>e){ c++; e=v[i].first; } } return c; } 0 pruthvibelgaonkar4691 week ago TIME TAKEN 0.55 SECONDS bool static comp(pair<int,int>a,pair<int,int>b) { if(a.second==b.second) return a.first<b.first; return a.second<b.second; } int maxMeetings(int start[], int end[], int n) { vector<pair<int,int>>v(n); for(int i=0;i<n;i++) { v[i]={start[i],end[i]}; } sort(v.begin(),v.end(),comp); int i=0; int j=1; int c=1; while(j<n) { if(v[i].second<v[j].first) { c++; i=j; j++; } else { j++; } } return c; } +1 shreyas172 weeks ago // { Driver Code Starts #include <bits/stdc++.h> using namespace std; // } Driver Code Ends class Solution { public: //Function to find the maximum number of meetings that can //be performed in a meeting room. static bool secc(const pair<int ,int>&a , const pair<int,int>&b){ return a.second < b.second ; } int maxMeetings(int start[], int end[], int n) { vector<pair<int,int>>vp ; for(int i=0;i<n;++i){ vp.push_back({start[i],end[i]}) ; } sort(vp.begin(),vp.end(),secc) ; int total = 0 ; int p = 0 ; for(int i=1;i<n;i++){ if(vp[p].second >= vp[i].first){ continue; } else{ total++ ; p = i ; } } return total+1 ; } }; // { Driver Code Starts. int main() { int t; cin >> t; while (t--) { int n; cin >> n; int start[n], end[n]; for (int i = 0; i < n; i++) cin >> start[i]; for (int i = 0; i < n; i++) cin >> end[i]; Solution ob; int ans = ob.maxMeetings(start, end, n); cout << ans << endl; } return 0; } // } Driver Code Ends 0 jainmuskan5652 weeks ago //be performed in a meeting room. static bool comp(pair<int,int> a, pair<int,int>b){ if(a.second== b.second){ return a.first<b.first; } return a.second<b.second; } int maxMeetings(int start[], int end[], int n) { // greedy // sort wrt the finish time vector<pair<int,int>> act(n); for(int i=0;i<n;i++){ act[i]= {start[i], end[i]}; } sort(act.begin(),act.end(), comp); int i=0, j=1, count=1; while(j<n){ if(act[i].second<act[j].first){ i=j; count++; } j++; } return count; } 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": 573, "s": 238, "text": "There is one meeting room in a firm. There are N meetings in the form of (start[i], end[i]) where start[i] is start time of meeting i and end[i] is finish time of meeting i.\nWhat is the maximum number of meetings that can be accommodated in the meeting room when only one meeting can be held in the meeting room at a particular time? " }, { "code": null, "e": 672, "s": 573, "text": "Note: Start time of one chosen meeting can't be equal to the end time of the other chosen meeting." }, { "code": null, "e": 684, "s": 672, "text": "\nExample 1:" }, { "code": null, "e": 887, "s": 684, "text": "Input:\nN = 6\nstart[] = {1,3,0,5,8,5}\nend[] = {2,4,6,7,9,9}\nOutput: \n4\nExplanation:\nMaximum four meetings can be held with\ngiven start and end timings.\nThe meetings are - (1, 2),(3, 4), (5,7) and (8,9)\n" }, { "code": null, "e": 898, "s": 887, "text": "Example 2:" }, { "code": null, "e": 1043, "s": 898, "text": "Input:\nN = 3\nstart[] = {10, 12, 20}\nend[] = {20, 25, 30}\nOutput: \n1\nExplanation:\nOnly one meetings can be held\nwith given start and end timings." }, { "code": null, "e": 1306, "s": 1043, "text": "\nYour Task :\nYou don't need to read inputs or print anything. Complete the function maxMeetings() that takes two arrays start[] and end[] along with their size N as input parameters and returns the maximum number of meetings that can be held in the meeting room." }, { "code": null, "e": 1377, "s": 1306, "text": "\nExpected Time Complexity : O(N*LogN)\nExpected Auxilliary Space : O(N)" }, { "code": null, "e": 1431, "s": 1377, "text": "\nConstraints:\n1 ≤ N ≤ 105\n0 ≤ start[i] < end[i] ≤ 105" }, { "code": null, "e": 1433, "s": 1431, "text": "0" }, { "code": null, "e": 1462, "s": 1433, "text": "dwivedisatyam12348 hours ago" }, { "code": null, "e": 1475, "s": 1462, "text": "python code " }, { "code": null, "e": 1732, "s": 1477, "text": " res=[] for i in range(n): res.append([start[i],end[i]]) res.sort(key=lambda x:(x[1],x[0])) ans,j,i=1,1,0 for j in range(n): if res[j][0]>res[i][1]: ans+=1 i=j return ans" }, { "code": null, "e": 1734, "s": 1732, "text": "0" }, { "code": null, "e": 1751, "s": 1734, "text": "gd29843 days ago" }, { "code": null, "e": 2341, "s": 1751, "text": " int maxMeetings(int start[], int end[], int n) { // Your code here if(n==0) return 0; vector<vector<int>> vec; for(int i{};i<n;i++){ vector<int> v; v.push_back(end[i]); v.push_back(start[i]); // v.push_back(i+1); vec.push_back(v); } sort(vec.begin(), vec.end()); int limit = vec[0][0]; int count{1}; for(int i{1};i<vec.size();i++){ if(vec[i][1]>limit){ limit = vec[i][0]; count++; } } return count; }" }, { "code": null, "e": 2375, "s": 2341, "text": "//east or west vector is the best" }, { "code": null, "e": 2377, "s": 2375, "text": "0" }, { "code": null, "e": 2402, "s": 2377, "text": "sikkusaurav1234 days ago" }, { "code": null, "e": 2972, "s": 2402, "text": "int maxMeetings(int start[], int end[], int n) { // Your code here vector<pair<int,int>>v; int starting_point,ending_point; int counting=1; for(int i=0;i<n;i++) { v.push_back(make_pair(end[i],start[i])); } sort(v.begin(),v.end()); starting_point=v[0].second; ending_point=v[0].first; for(int i=1;i<n;i++) { if(v[i].second>ending_point) { ending_point=v[i].first; counting++; } } return counting; }" }, { "code": null, "e": 2974, "s": 2972, "text": "0" }, { "code": null, "e": 2998, "s": 2974, "text": "dhruvpurwar155 days ago" }, { "code": null, "e": 4398, "s": 2998, "text": "// { Driver Code Starts\n#include <bits/stdc++.h>\nusing namespace std;\n\n // } Driver Code Ends\nclass Solution\n{\n public:\n //Function to find the maximum number of meetings that can\n //be performed in a meeting room.\n bool static cmp(pair<int,int>a, pair<int,int>b){\n if(a.second==b.second){\n return a.first>b.first;\n }\n return a.second<b.second;\n }\n int maxMeetings(int start[], int end[], int n)\n {\n // Your code here\n vector<pair<int,int>>vec(n);\n for(int i=0;i<n;i++){\n vec[i].first=start[i];\n vec[i].second= end[i];\n }\n \n // for(auto x: vec){\n // cout<<x.first<<\" \"<<x.second<<endl;\n // }\n \n sort(vec.begin(), vec.end(), cmp);\n int res=1;\n int prev=0;\n for(int i=1;i<n;i++){\n if(vec[i].first>vec[prev].second){\n res++;\n prev=i;\n }\n }\n \n return res;\n }\n};\n\n// { Driver Code Starts.\nint main() {\n int t;\n cin >> t;\n while (t--) {\n int n;\n cin >> n;\n int start[n], end[n];\n for (int i = 0; i < n; i++) cin >> start[i];\n\n for (int i = 0; i < n; i++) cin >> end[i];\n\n Solution ob;\n int ans = ob.maxMeetings(start, end, n);\n cout << ans << endl;\n }\n return 0;\n} // } Driver Code Ends" }, { "code": null, "e": 4400, "s": 4398, "text": "0" }, { "code": null, "e": 4424, "s": 4400, "text": "dhruvpurwar155 days ago" }, { "code": null, "e": 4450, "s": 4424, "text": "ans.push_back(totalJobs);" }, { "code": null, "e": 4452, "s": 4450, "text": "0" }, { "code": null, "e": 4476, "s": 4452, "text": "doshividhi0215 days ago" }, { "code": null, "e": 4965, "s": 4476, "text": "def maximumMeetings(self,n,start,end): # code here meetings = list() count = 1 for i in range(len(start)): meet = list() meet.append(start[i]) meet.append(end[i]) meetings.append(meet) sorted(meetings,key=lambda x:x[1]) limit = meetings[0][1] for i in range(1,len(start)): if(meetings[i][0] >= limit): limit = meetings[i][1] count +=1 return count" }, { "code": null, "e": 4991, "s": 4969, "text": "What's wrong in this?" }, { "code": null, "e": 4993, "s": 4991, "text": "0" }, { "code": null, "e": 5017, "s": 4993, "text": "ahmedxahoor721 week ago" }, { "code": null, "e": 5453, "s": 5017, "text": "int maxMeetings(int start[], int end[], int n) { // Your code here vector<pair<int,int>>v; for(int i=0;i<n;i++){ v.push_back({end[i],start[i]}); } sort(v.begin(),v.end()); int c=1; int s=v[0].second,e=v[0].first; for(int i=1;i<v.size();i++){ if(v[i].second>e){ c++; e=v[i].first; } } return c; }" }, { "code": null, "e": 5455, "s": 5453, "text": "0" }, { "code": null, "e": 5486, "s": 5455, "text": "pruthvibelgaonkar4691 week ago" }, { "code": null, "e": 5510, "s": 5486, "text": "TIME TAKEN 0.55 SECONDS" }, { "code": null, "e": 6130, "s": 5512, "text": " bool static comp(pair<int,int>a,pair<int,int>b) { if(a.second==b.second) return a.first<b.first; return a.second<b.second; } int maxMeetings(int start[], int end[], int n) { vector<pair<int,int>>v(n); for(int i=0;i<n;i++) { v[i]={start[i],end[i]}; } sort(v.begin(),v.end(),comp); int i=0; int j=1; int c=1; while(j<n) { if(v[i].second<v[j].first) { c++; i=j; j++; } else { j++; } } return c; }" }, { "code": null, "e": 6133, "s": 6130, "text": "+1" }, { "code": null, "e": 6154, "s": 6133, "text": "shreyas172 weeks ago" }, { "code": null, "e": 7441, "s": 6154, "text": "// { Driver Code Starts\n#include <bits/stdc++.h>\nusing namespace std;\n\n // } Driver Code Ends\nclass Solution\n{\n public:\n //Function to find the maximum number of meetings that can\n //be performed in a meeting room.\n static bool secc(const pair<int ,int>&a , const pair<int,int>&b){\n return a.second < b.second ; \n }\n int maxMeetings(int start[], int end[], int n)\n {\n vector<pair<int,int>>vp ; \n for(int i=0;i<n;++i){\n vp.push_back({start[i],end[i]}) ; \n }\n \n sort(vp.begin(),vp.end(),secc) ; \n \n int total = 0 ; \n int p = 0 ; \n \n for(int i=1;i<n;i++){\n if(vp[p].second >= vp[i].first){\n continue; \n }\n else{\n total++ ; \n p = i ; \n }\n }\n return total+1 ; \n \n }\n};\n\n// { Driver Code Starts.\nint main() {\n int t;\n cin >> t;\n while (t--) {\n int n;\n cin >> n;\n int start[n], end[n];\n for (int i = 0; i < n; i++) cin >> start[i];\n\n for (int i = 0; i < n; i++) cin >> end[i];\n\n Solution ob;\n int ans = ob.maxMeetings(start, end, n);\n cout << ans << endl;\n }\n return 0;\n} // } Driver Code Ends" }, { "code": null, "e": 7443, "s": 7441, "text": "0" }, { "code": null, "e": 7468, "s": 7443, "text": "jainmuskan5652 weeks ago" }, { "code": null, "e": 8112, "s": 7468, "text": " //be performed in a meeting room. static bool comp(pair<int,int> a, pair<int,int>b){ if(a.second== b.second){ return a.first<b.first; } return a.second<b.second; } int maxMeetings(int start[], int end[], int n) { // greedy // sort wrt the finish time vector<pair<int,int>> act(n); for(int i=0;i<n;i++){ act[i]= {start[i], end[i]}; } sort(act.begin(),act.end(), comp); int i=0, j=1, count=1; while(j<n){ if(act[i].second<act[j].first){ i=j; count++; } j++; } return count; }" }, { "code": null, "e": 8258, "s": 8112, "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": 8294, "s": 8258, "text": " Login to access your submissions. " }, { "code": null, "e": 8304, "s": 8294, "text": "\nProblem\n" }, { "code": null, "e": 8314, "s": 8304, "text": "\nContest\n" }, { "code": null, "e": 8377, "s": 8314, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 8525, "s": 8377, "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": 8733, "s": 8525, "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": 8839, "s": 8733, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
What is STORED PROCEDURE in a DB2? How will you create a new stored procedure?
The DB2 STORED PROCEDURE are the programs which are directly managed by DBMS. The STORED PROCEDURE generally contains SQLs and they can be called by application programs. The STORED PROCEDURE processes the query and returns the result to the application program. The STORED PROCEDURES can be used for the SQLs which are very often used, so instead of using the same SQL query again and again, we can simply use STORED PROCEDURE. The other benefit of STORED PROCEDURE is that they are fast and have good performance as compared to static SQLs used in application programs. The STORED PROCEDURE can be written in many languages like COBOL, JAVA, C++, etc. Once we have written a STORED PROCEDURE in any of the languages, we have to register this STORED PROCEDURE in DB2 using below command. CREATE PROCEDURE ORDERSTAT (IN ORDER_ID CHAR(8), OUT ORDER_STATUS CHAR(3)) A STORED PROCEDURE with the name ORDERSTAT will be created using the above command which will take the input as ORDER_ID and gives ORDER_STATUS in output.
[ { "code": null, "e": 1491, "s": 1062, "text": "The DB2 STORED PROCEDURE are the programs which are directly managed by DBMS. The STORED PROCEDURE generally contains SQLs and they can be called by application programs. The STORED PROCEDURE processes the query and returns the result to the application program. The STORED PROCEDURES can be used for the SQLs which are very often used, so instead of using the same SQL query again and again, we can simply use STORED PROCEDURE." }, { "code": null, "e": 1851, "s": 1491, "text": "The other benefit of STORED PROCEDURE is that they are fast and have good performance as compared to static SQLs used in application programs. The STORED PROCEDURE can be written in many languages like COBOL, JAVA, C++, etc. Once we have written a STORED PROCEDURE in any of the languages, we have to register this STORED PROCEDURE in DB2 using below command." }, { "code": null, "e": 1929, "s": 1851, "text": "CREATE PROCEDURE ORDERSTAT (IN ORDER_ID CHAR(8),\n OUT ORDER_STATUS CHAR(3))" }, { "code": null, "e": 2084, "s": 1929, "text": "A STORED PROCEDURE with the name ORDERSTAT will be created using the above command which will take the input as ORDER_ID and gives ORDER_STATUS in output." } ]
Bitwise XOR of a Binary array - GeeksforGeeks
21 May, 2021 Given a binary array arr[], the task is to calculate the bitwise XOR of all the elements in this array and print it. Examples: Input: arr[] = {“100”, “1001”, “0011”} Output: 1110 0100 XOR 1001 XOR 0011 = 1110 Input: arr[] = {“10”, “11”, “1000001”} Output: 1000000 Approach: Step 1: First find the maximum-sized binary string. Step 2: Make all the binary strings in an array to the size of the maximum sized string, by adding 0s at the Most Significant Bit Step 3: Now find the resultant string by performing bitwise XOR on all the binary strings in the array. For Examples: Let the binary array be {“100”, “001”, and “1111”}.Here the maximum sized binary string is 4.Make all the binary strings in the array of size 4, by adding 0s at the MSB. Now the binary array becomes {“0100”, “0001” and “1111”}Performing bitwise XOR on all the binary strings in the array Let the binary array be {“100”, “001”, and “1111”}. Here the maximum sized binary string is 4. Make all the binary strings in the array of size 4, by adding 0s at the MSB. Now the binary array becomes {“0100”, “0001” and “1111”} Performing bitwise XOR on all the binary strings in the array “0100” XOR “0001” XOR “1111” = “1110” Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach #include <bits/stdc++.h>using namespace std; // Function to return the bitwise XOR// of all the binary stringsvoid strBitwiseXOR(string* arr, int n){ string result; int max_len = INT_MIN; // Get max size and reverse each string // Since we have to perform XOR operation // on bits from right to left // Reversing the string will make it easier // to perform operation from left to right for (int i = 0; i < n; i++) { max_len = max(max_len, (int)arr[i].size()); reverse(arr[i].begin(), arr[i].end()); } for (int i = 0; i < n; i++) { // Add 0s to the end // of strings if needed string s; for (int j = 0; j < max_len - arr[i].size(); j++) s += '0'; arr[i] = arr[i] + s; } // Perform XOR operation on each bit for (int i = 0; i < max_len; i++) { int pres_bit = 0; for (int j = 0; j < n; j++) pres_bit = pres_bit ^ (arr[j][i] - '0'); result += (pres_bit + '0'); } // Reverse the resultant string // to get the final string reverse(result.begin(), result.end()); // Return the final string cout << result;} // Driver codeint main(){ string arr[] = { "1000", "10001", "0011" }; int n = sizeof(arr) / sizeof(arr[0]); strBitwiseXOR(arr, n); return 0;} // Java implementation of the approachimport java.io.*;import java.util.*; class GFG{ // Function to return the// reverse stringstatic String reverse(String str){ String rev = ""; for(int i = str.length() - 1; i >= 0; i--) rev = rev + str.charAt(i); return rev;} // Function to return the bitwise XOR// of all the binary stringsstatic String strBitwiseXOR(String[] arr, int n){ String result = ""; int max_len = Integer.MIN_VALUE; // Get max size and reverse each string // Since we have to perform XOR operation // on bits from right to left // Reversing the string will make it easier // to perform operation from left to right for(int i = 0; i < n; i++) { max_len = Math.max(max_len, (int)arr[i].length()); arr[i] = reverse(arr[i]); } for(int i = 0; i < n; i++) { // Add 0s to the end // of strings if needed String s = ""; for(int j = 0; j < max_len - arr[i].length(); j++) s += '0'; arr[i] = arr[i] + s; } // Perform XOR operation on each bit for(int i = 0; i < max_len; i++) { int pres_bit = 0; for(int j = 0; j < n; j++) pres_bit = pres_bit ^ (arr[j].charAt(i) - '0'); result += (char)(pres_bit + '0'); } // Reverse the resultant string // to get the final string result = reverse(result); // Return the final string return result;} // Driver codepublic static void main(String[] args){ String[] arr = { "1000", "10001", "0011" }; int n = arr.length; System.out.print(strBitwiseXOR(arr, n));}} // This code is contributed by akhilsaini # Function to return the bitwise XOR# of all the binary stringsimport sysdef strBitwiseXOR(arr, n): result = "" max_len = -1 # Get max size and reverse each string # Since we have to perform XOR operation # on bits from right to left # Reversing the string will make it easier # to perform operation from left to right for i in range(n): max_len = max(max_len, len(arr[i])) arr[i] = arr[i][::-1] for i in range(n): # Add 0s to the end # of strings if needed s = "" # t = max_len - len(arr[i]) for j in range(max_len - len(arr[i])): s += "0" arr[i] = arr[i] + s # Perform XOR operation on each bit for i in range(max_len): pres_bit = 0 for j in range(n): pres_bit = pres_bit ^ (ord(arr[j][i]) - ord('0')) result += chr((pres_bit) + ord('0')) # Reverse the resultant string # to get the final string result = result[::-1] # Return the final string print(result) # Driver codeif(__name__ == "__main__"): arr = ["1000", "10001", "0011"] n = len(arr) strBitwiseXOR(arr, n) # This code is contributed by skylags // C# implementation of the approachusing System; class GFG{ // Function to return the// reverse stringstatic string reverse(string str){ string rev = ""; for(int i = str.Length - 1; i >= 0; i--) rev = rev + str[i]; return rev;} // Function to return the bitwise XOR// of all the binary stringsstatic string strBitwiseXOR(string[] arr, int n){ string result = ""; int max_len = int.MinValue; // Get max size and reverse each string // Since we have to perform XOR operation // on bits from right to left // Reversing the string will make it easier // to perform operation from left to right for(int i = 0; i < n; i++) { max_len = Math.Max(max_len, (int)arr[i].Length); arr[i] = reverse(arr[i]); } for(int i = 0; i < n; i++) { // Add 0s to the end // of strings if needed string s = ""; for(int j = 0; j < max_len - arr[i].Length; j++) s += '0'; arr[i] = arr[i] + s; } // Perform XOR operation on each bit for(int i = 0; i < max_len; i++) { int pres_bit = 0; for(int j = 0; j < n; j++) pres_bit = pres_bit ^ (arr[j][i] - '0'); result += (char)(pres_bit + '0'); } // Reverse the resultant string // to get the final string result = reverse(result); // Return the final string return result;} // Driver codepublic static void Main(){ string[] arr = { "1000", "10001", "0011" }; int n = arr.Length; Console.Write(strBitwiseXOR(arr, n));}} // This code is contributed by akhilsaini <script> // Javascript implementation of the approach // Function to return the bitwise XOR// of all the binary stringsfunction strBitwiseXOR(arr, n){ var result = ""; var max_len = -1000000000; // Get max size and reverse each string // Since we have to perform XOR operation // on bits from right to left // Reversing the string will make it easier // to perform operation from left to right for (var i = 0; i < n; i++) { max_len = Math.max(max_len, arr[i].length); arr[i] = arr[i].split('').reverse().join(''); } for (var i = 0; i < n; i++) { // Add 0s to the end // of strings if needed var s; for (var j = 0; j < max_len - arr[i].length; j++) s += '0'; arr[i] = arr[i] + s; } // Perform XOR operation on each bit for (var i = 0; i < max_len; i++) { var pres_bit = 0; for (var j = 0; j < n; j++) pres_bit = pres_bit ^ (arr[j][i] - '0'.charCodeAt(0)); result += (pres_bit + '0'.charCodeAt(0)); } // Reverse the resultant string // to get the final string result = result.split('').reverse().join(''); // Return the final string document.write( result);} // Driver codevar arr = ["1000", "10001", "0011"];var n = arr.length;strBitwiseXOR(arr, n); </script> 11010 skylags akhilsaini noob2000 binary-string Bitwise-XOR Arrays Bit Magic Strings Arrays Strings Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stack Data Structure (Introduction and Program) Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Introduction to Arrays Bitwise Operators in C/C++ Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Count set bits in an integer Cyclic Redundancy Check and Modulo-2 Division
[ { "code": null, "e": 24792, "s": 24764, "text": "\n21 May, 2021" }, { "code": null, "e": 24909, "s": 24792, "text": "Given a binary array arr[], the task is to calculate the bitwise XOR of all the elements in this array and print it." }, { "code": null, "e": 24920, "s": 24909, "text": "Examples: " }, { "code": null, "e": 25002, "s": 24920, "text": "Input: arr[] = {“100”, “1001”, “0011”} Output: 1110 0100 XOR 1001 XOR 0011 = 1110" }, { "code": null, "e": 25058, "s": 25002, "text": "Input: arr[] = {“10”, “11”, “1000001”} Output: 1000000 " }, { "code": null, "e": 25069, "s": 25058, "text": "Approach: " }, { "code": null, "e": 25121, "s": 25069, "text": "Step 1: First find the maximum-sized binary string." }, { "code": null, "e": 25251, "s": 25121, "text": "Step 2: Make all the binary strings in an array to the size of the maximum sized string, by adding 0s at the Most Significant Bit" }, { "code": null, "e": 25355, "s": 25251, "text": "Step 3: Now find the resultant string by performing bitwise XOR on all the binary strings in the array." }, { "code": null, "e": 25370, "s": 25355, "text": "For Examples: " }, { "code": null, "e": 25658, "s": 25370, "text": "Let the binary array be {“100”, “001”, and “1111”}.Here the maximum sized binary string is 4.Make all the binary strings in the array of size 4, by adding 0s at the MSB. Now the binary array becomes {“0100”, “0001” and “1111”}Performing bitwise XOR on all the binary strings in the array" }, { "code": null, "e": 25710, "s": 25658, "text": "Let the binary array be {“100”, “001”, and “1111”}." }, { "code": null, "e": 25753, "s": 25710, "text": "Here the maximum sized binary string is 4." }, { "code": null, "e": 25887, "s": 25753, "text": "Make all the binary strings in the array of size 4, by adding 0s at the MSB. Now the binary array becomes {“0100”, “0001” and “1111”}" }, { "code": null, "e": 25949, "s": 25887, "text": "Performing bitwise XOR on all the binary strings in the array" }, { "code": null, "e": 25987, "s": 25949, "text": "“0100” XOR “0001” XOR “1111” = “1110”" }, { "code": null, "e": 26040, "s": 25987, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26044, "s": 26040, "text": "C++" }, { "code": null, "e": 26049, "s": 26044, "text": "Java" }, { "code": null, "e": 26057, "s": 26049, "text": "Python3" }, { "code": null, "e": 26060, "s": 26057, "text": "C#" }, { "code": null, "e": 26071, "s": 26060, "text": "Javascript" }, { "code": "// C++ implementation of the approach #include <bits/stdc++.h>using namespace std; // Function to return the bitwise XOR// of all the binary stringsvoid strBitwiseXOR(string* arr, int n){ string result; int max_len = INT_MIN; // Get max size and reverse each string // Since we have to perform XOR operation // on bits from right to left // Reversing the string will make it easier // to perform operation from left to right for (int i = 0; i < n; i++) { max_len = max(max_len, (int)arr[i].size()); reverse(arr[i].begin(), arr[i].end()); } for (int i = 0; i < n; i++) { // Add 0s to the end // of strings if needed string s; for (int j = 0; j < max_len - arr[i].size(); j++) s += '0'; arr[i] = arr[i] + s; } // Perform XOR operation on each bit for (int i = 0; i < max_len; i++) { int pres_bit = 0; for (int j = 0; j < n; j++) pres_bit = pres_bit ^ (arr[j][i] - '0'); result += (pres_bit + '0'); } // Reverse the resultant string // to get the final string reverse(result.begin(), result.end()); // Return the final string cout << result;} // Driver codeint main(){ string arr[] = { \"1000\", \"10001\", \"0011\" }; int n = sizeof(arr) / sizeof(arr[0]); strBitwiseXOR(arr, n); return 0;}", "e": 27485, "s": 26071, "text": null }, { "code": "// Java implementation of the approachimport java.io.*;import java.util.*; class GFG{ // Function to return the// reverse stringstatic String reverse(String str){ String rev = \"\"; for(int i = str.length() - 1; i >= 0; i--) rev = rev + str.charAt(i); return rev;} // Function to return the bitwise XOR// of all the binary stringsstatic String strBitwiseXOR(String[] arr, int n){ String result = \"\"; int max_len = Integer.MIN_VALUE; // Get max size and reverse each string // Since we have to perform XOR operation // on bits from right to left // Reversing the string will make it easier // to perform operation from left to right for(int i = 0; i < n; i++) { max_len = Math.max(max_len, (int)arr[i].length()); arr[i] = reverse(arr[i]); } for(int i = 0; i < n; i++) { // Add 0s to the end // of strings if needed String s = \"\"; for(int j = 0; j < max_len - arr[i].length(); j++) s += '0'; arr[i] = arr[i] + s; } // Perform XOR operation on each bit for(int i = 0; i < max_len; i++) { int pres_bit = 0; for(int j = 0; j < n; j++) pres_bit = pres_bit ^ (arr[j].charAt(i) - '0'); result += (char)(pres_bit + '0'); } // Reverse the resultant string // to get the final string result = reverse(result); // Return the final string return result;} // Driver codepublic static void main(String[] args){ String[] arr = { \"1000\", \"10001\", \"0011\" }; int n = arr.length; System.out.print(strBitwiseXOR(arr, n));}} // This code is contributed by akhilsaini", "e": 29199, "s": 27485, "text": null }, { "code": "# Function to return the bitwise XOR# of all the binary stringsimport sysdef strBitwiseXOR(arr, n): result = \"\" max_len = -1 # Get max size and reverse each string # Since we have to perform XOR operation # on bits from right to left # Reversing the string will make it easier # to perform operation from left to right for i in range(n): max_len = max(max_len, len(arr[i])) arr[i] = arr[i][::-1] for i in range(n): # Add 0s to the end # of strings if needed s = \"\" # t = max_len - len(arr[i]) for j in range(max_len - len(arr[i])): s += \"0\" arr[i] = arr[i] + s # Perform XOR operation on each bit for i in range(max_len): pres_bit = 0 for j in range(n): pres_bit = pres_bit ^ (ord(arr[j][i]) - ord('0')) result += chr((pres_bit) + ord('0')) # Reverse the resultant string # to get the final string result = result[::-1] # Return the final string print(result) # Driver codeif(__name__ == \"__main__\"): arr = [\"1000\", \"10001\", \"0011\"] n = len(arr) strBitwiseXOR(arr, n) # This code is contributed by skylags", "e": 30379, "s": 29199, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the// reverse stringstatic string reverse(string str){ string rev = \"\"; for(int i = str.Length - 1; i >= 0; i--) rev = rev + str[i]; return rev;} // Function to return the bitwise XOR// of all the binary stringsstatic string strBitwiseXOR(string[] arr, int n){ string result = \"\"; int max_len = int.MinValue; // Get max size and reverse each string // Since we have to perform XOR operation // on bits from right to left // Reversing the string will make it easier // to perform operation from left to right for(int i = 0; i < n; i++) { max_len = Math.Max(max_len, (int)arr[i].Length); arr[i] = reverse(arr[i]); } for(int i = 0; i < n; i++) { // Add 0s to the end // of strings if needed string s = \"\"; for(int j = 0; j < max_len - arr[i].Length; j++) s += '0'; arr[i] = arr[i] + s; } // Perform XOR operation on each bit for(int i = 0; i < max_len; i++) { int pres_bit = 0; for(int j = 0; j < n; j++) pres_bit = pres_bit ^ (arr[j][i] - '0'); result += (char)(pres_bit + '0'); } // Reverse the resultant string // to get the final string result = reverse(result); // Return the final string return result;} // Driver codepublic static void Main(){ string[] arr = { \"1000\", \"10001\", \"0011\" }; int n = arr.Length; Console.Write(strBitwiseXOR(arr, n));}} // This code is contributed by akhilsaini", "e": 32040, "s": 30379, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the bitwise XOR// of all the binary stringsfunction strBitwiseXOR(arr, n){ var result = \"\"; var max_len = -1000000000; // Get max size and reverse each string // Since we have to perform XOR operation // on bits from right to left // Reversing the string will make it easier // to perform operation from left to right for (var i = 0; i < n; i++) { max_len = Math.max(max_len, arr[i].length); arr[i] = arr[i].split('').reverse().join(''); } for (var i = 0; i < n; i++) { // Add 0s to the end // of strings if needed var s; for (var j = 0; j < max_len - arr[i].length; j++) s += '0'; arr[i] = arr[i] + s; } // Perform XOR operation on each bit for (var i = 0; i < max_len; i++) { var pres_bit = 0; for (var j = 0; j < n; j++) pres_bit = pres_bit ^ (arr[j][i] - '0'.charCodeAt(0)); result += (pres_bit + '0'.charCodeAt(0)); } // Reverse the resultant string // to get the final string result = result.split('').reverse().join(''); // Return the final string document.write( result);} // Driver codevar arr = [\"1000\", \"10001\", \"0011\"];var n = arr.length;strBitwiseXOR(arr, n); </script>", "e": 33404, "s": 32040, "text": null }, { "code": null, "e": 33410, "s": 33404, "text": "11010" }, { "code": null, "e": 33420, "s": 33412, "text": "skylags" }, { "code": null, "e": 33431, "s": 33420, "text": "akhilsaini" }, { "code": null, "e": 33440, "s": 33431, "text": "noob2000" }, { "code": null, "e": 33454, "s": 33440, "text": "binary-string" }, { "code": null, "e": 33466, "s": 33454, "text": "Bitwise-XOR" }, { "code": null, "e": 33473, "s": 33466, "text": "Arrays" }, { "code": null, "e": 33483, "s": 33473, "text": "Bit Magic" }, { "code": null, "e": 33491, "s": 33483, "text": "Strings" }, { "code": null, "e": 33498, "s": 33491, "text": "Arrays" }, { "code": null, "e": 33506, "s": 33498, "text": "Strings" }, { "code": null, "e": 33516, "s": 33506, "text": "Bit Magic" }, { "code": null, "e": 33614, "s": 33516, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33662, "s": 33614, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 33730, "s": 33662, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 33774, "s": 33730, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 33806, "s": 33774, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 33829, "s": 33806, "text": "Introduction to Arrays" }, { "code": null, "e": 33856, "s": 33829, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 33902, "s": 33856, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 33970, "s": 33902, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 33999, "s": 33970, "text": "Count set bits in an integer" } ]
Different Types of Time Series Decomposition | by Andrew Plummer | Towards Data Science
Abraham Maslow writes, “I suppose it is tempting, if the only tool you have is a hammer, to treat everything as if it were a nail”. This is the situation that aspiring data scientists find themselves in when analyzing time series data. The seasonal_decompose function from Python’s Statsmodels library is the hammer, and every time series data is just another nail. Decomposing our time series is an important step in improving forecast accuracy and creating causal insights. The seasonal_decompose function is okay for time series decomposition but there are other approaches that are great. And, as data scientists, we always want to use what is great. Abraham Maslow writes, “I suppose it is tempting, if the only tool you have is a hammer, to treat everything as if it were a nail”. This article has the following goals: Explain the importance of time series decomposition.Explain the problems with the seasonal_decompose function.Introduce alternative approaches to time series decomposition Explain the importance of time series decomposition. Explain the problems with the seasonal_decompose function. Introduce alternative approaches to time series decomposition Time series decomposition refers to the method by which we reduce our time series data into its following four components: Trend [T]Cycle [C]Seasonality [S]Remainder [R] Trend [T] Cycle [C] Seasonality [S] Remainder [R] The trend of a time series refers to the general direction in which the time series is moving. Time series can have a positive or a negative trend, but can also have no trend. For example, the GDP growth rate for the United States (and many advanced economies) does not have a trend because economic forces keep the growth rate relatively stable. The cycle for time series data refers to its tendency to rise and fall at inconsistent frequencies. We often use the cycle component of a time series to discuss business cycles in economic data. The seasonal component of a time series is similar to its cycle component except for one important difference: the seasonal component refers to data that rises and falls at consistent frequencies. The tourism industry is well-acquainted with the seasonal component. A country’s tourism industry experiences high revenues in the warmer months, and then its revenues slowly inch towards the precipice of a cliff at the first sign of snow. The remainder is what’s left of the time series data after removing its trend, cycle, and seasonal components. It is the random fluctuation in the time series data that the above components cannot explain. When forecasting, it is advantageous to use a ‘seasonally-adjusted’ time series, which is just a time series with the seasonal component removed. This allows a forecaster to focus on predicting the general trend of the data. A second reason to use time series decomposition is to identify any interesting behavior in the seasonal component. Then, we can research why our data moves in the way it does. Interestingly, Statsmodels knows that there are better ways to decompose time series data than the usual seasonal_decompose function. They warn us (emphasis is my own): This [seasonal_decompose] is a naive decomposition. More sophisticated methods should be preferred — Statsmodels Documentation Seasonal_decompose uses the classical decomposition method, of which there are two types: additive and multiplicative. Additive decomposition argues that time series data is a function of the sum of its components. Thus, where Y is the time series data, T is the trend-cycle component, S is the seasonal component, and R is the remainder. Rearranging gives us, Rather than a sum, the multiplicative decomposition argues that time series data is a function of the product of its components. Thus, And, rearranging gives us, We can usually identify an additive or multiplicative time series from its variation. If the magnitude of the seasonal component changes with time, then the series is multiplicative. Otherwise, the series is additive. Notice that the magnitude of the seasonal component — the difference between the maximum point of the series and the red line — is relatively constant from 2011 onward in the additive time series. However, in the multiplicative series, the magnitude of the seasonal component grows as time increases. Note: identifying whether a series is additive or multiplicative is trickier than the above image might suggest. Oftentimes, one component of the time series might be additive while the others are multiplicative. For example, you can reasonably have a time series where And, thus, The classical approach to time series decomposition has several issues: It uses two-sided moving averages to estimate the trend-cycle. Thus, the first few observations and the last few observations are absent from the trend-cycle.It assumes that the seasonal component is constant throughout the entire series. While this may be an accurate assumption for short time periods, this assumption becomes untenable for longer periods. For example, innovations in air travel and other modes of transportation have made fundamental changes in the tourism industry for many economies; and thus, it would be incorrect to assume that its seasonal variation has remained stable throughout its history.The trend line over-smooths the data. Thus, it is not responsive to sharp fluctuations. This causes a large remainder component. It uses two-sided moving averages to estimate the trend-cycle. Thus, the first few observations and the last few observations are absent from the trend-cycle. It assumes that the seasonal component is constant throughout the entire series. While this may be an accurate assumption for short time periods, this assumption becomes untenable for longer periods. For example, innovations in air travel and other modes of transportation have made fundamental changes in the tourism industry for many economies; and thus, it would be incorrect to assume that its seasonal variation has remained stable throughout its history. The trend line over-smooths the data. Thus, it is not responsive to sharp fluctuations. This causes a large remainder component. Thankfully, there are approaches to time series decomposition that resolve the above issues. X11 Decomposition creates a trend-cycle for all observations. As well, the X11 Decomposition allows the seasonal component to change slowly. I’m unaware of any Python library that implements the X-11 procedure. However, this can be done relatively easily with the seas function in R’s seasonal package. You might be able to use the rpy2 library to replicate the R code in Python. (I will update this article later this week once I’ve found a work-around). seas(data, x11 = "") Let’s compare the results of the X11 decomposition with those of a classical decomposition. In R: library(forecast)library(ggplot2)autoplot(AirPassengers) Because the seasonal component increases with time, we know that we should use multiplicative decomposition. mfit <- decompose(x = AirPassengers, type = "multiplicative")autoplot(mfit) Notice that the seasonal component is unchanging, the remainder component has a lot of large values, and the trend line is missing some observations from the beginning and from the end of our data set. Now, if we use the X11 decomposition, fit <- seas(x = AirPassengers, x11 = "")autoplot(fit) You should notice three things: The seasonal component increases with time, thus reflecting the fundamental changes in the airline industry since 1950.The remainder component is smaller than was the case when we had done the classical decomposition. This is because our trend line is a good fit for the raw data.There are no missing observations in the trend line. The seasonal component increases with time, thus reflecting the fundamental changes in the airline industry since 1950. The remainder component is smaller than was the case when we had done the classical decomposition. This is because our trend line is a good fit for the raw data. There are no missing observations in the trend line. One problem with X11 is that it only handles monthly and quarterly data. Another is that it is not robust to outliers. Therefore, in 1990, researchers at the University of Michigan and Bell Labs published “STL: Seasonal-Trend Decomposition Procedure Based on Loess”. The STL approach to time series decomposition has the following advantages over the X11 aproach: It handles any type of seasonality.The user can control the rate of change of the seasonal component.It is robust to outliers. It handles any type of seasonality. The user can control the rate of change of the seasonal component. It is robust to outliers. We can implement STL in Python with the STL function. from statsmodels.tsa.seasonal import STL We can change the smoothness of the trend-cycle and the seasonal components by passing an integer into the trend and seasonal arguments in the STL function. The seasonal argument is set to 7 by default (it is also recommended that you use a seasonal smoother greater than or equal to 7). If a trend value is not specified, then Statsmodels calculates a trend value by using the smallest odd integer greater than The choice of the seasonal smoother is up to you. The larger is the integer, the more ‘smooth’ your seasonal component becomes. This causes less of the variation in your data to be attributed to its seasonal component. Thus, you must decide how much variation in your data can be reasonably attributed to the seasonal component. The originators of the STL method suggest using a seasonal diagnostic plot, and then experimenting with different smoother values to determine which value seems right. Unfortunately, there is no implementation of this in Python (there is in R, however). from statsmodels.tsa.seasonal import STLimport matplotlib.pyplot as pltimport pandas as pddf = df[:len(df) - 1] # Removes the last row in the data setcolumns = ['Month', 'Passengers']df.columns = columnsdf.head() df = df.set_index('Month') # Set the index to datetime object.df = df.asfreq('MS') # Set frequency# Set robust to True to handle outliersres = STL(df, robust = True).fit() res.plot()plt.show() The variation in the seasonal component has changed more rapidly than was the case when we had used the X11 decomposition. Because the STL decomposition is also robust to outliers, its estimation of the seasonal component is likely more accurate than the estimation from X11. Feel free to experiment with the seasonal argument in the STL function. Just make sure that you use an odd integer. If you’d like to seasonally adjust your data, then subtract the seasonal component from the raw data. That is, df['Seasonally Adjusted'] = df['Passengers'] - res.seasonaldf.head() Now you know alternative approaches to seasonal decomposition. These alternative approaches will give you better estimates of the seasonality and trend-cycle components of your time series than you would have received with Statsmodels’s seasonal_decompose function. You will also be able to use these approaches to obtain more accurate forecasts, and to better identify interesting patterns in your data set. [1] Hyndman, R.J., & Athanasopoulos, G. (2018) Forecasting: principles and practice, 2nd edition, OTexts: Melbourne, Australia. OTexts.com/fpp2. [2]https://www.statsmodels.org/stable/generated/statsmodels.tsa.seasonal.seasonal_decompose.html [3] Sutcliffe, Andrew. (1993) “X11 Time Series Decomposition and Sampling Errors”, Australian Bureau of Statistics: Melbourne, Australia. [4] Cleveland, R.B., Cleveland W.S., McRae J.E., & Terpenning, I. (1990) “STL: Seasonal-Trend Decomposition Procedure Based on Loess”, Journal of Official Statistics. [5] Gardner, Dillon R. (2017) “STL Algorithm Explained: STL Part II”. The trend term can be non-linear. Also, there are two types of trends: stochastic and deterministic. I will discuss these in a later article.The seasonal_decompose function can also estimate a one-sided moving average; however, this causes there to be more missing observations at the beginning of the series than if we had used the two-sided approach, and zero missing observations at the end of the series. The trend term can be non-linear. Also, there are two types of trends: stochastic and deterministic. I will discuss these in a later article. The seasonal_decompose function can also estimate a one-sided moving average; however, this causes there to be more missing observations at the beginning of the series than if we had used the two-sided approach, and zero missing observations at the end of the series.
[ { "code": null, "e": 304, "s": 172, "text": "Abraham Maslow writes, “I suppose it is tempting, if the only tool you have is a hammer, to treat everything as if it were a nail”." }, { "code": null, "e": 538, "s": 304, "text": "This is the situation that aspiring data scientists find themselves in when analyzing time series data. The seasonal_decompose function from Python’s Statsmodels library is the hammer, and every time series data is just another nail." }, { "code": null, "e": 648, "s": 538, "text": "Decomposing our time series is an important step in improving forecast accuracy and creating causal insights." }, { "code": null, "e": 827, "s": 648, "text": "The seasonal_decompose function is okay for time series decomposition but there are other approaches that are great. And, as data scientists, we always want to use what is great." }, { "code": null, "e": 959, "s": 827, "text": "Abraham Maslow writes, “I suppose it is tempting, if the only tool you have is a hammer, to treat everything as if it were a nail”." }, { "code": null, "e": 997, "s": 959, "text": "This article has the following goals:" }, { "code": null, "e": 1169, "s": 997, "text": "Explain the importance of time series decomposition.Explain the problems with the seasonal_decompose function.Introduce alternative approaches to time series decomposition" }, { "code": null, "e": 1222, "s": 1169, "text": "Explain the importance of time series decomposition." }, { "code": null, "e": 1281, "s": 1222, "text": "Explain the problems with the seasonal_decompose function." }, { "code": null, "e": 1343, "s": 1281, "text": "Introduce alternative approaches to time series decomposition" }, { "code": null, "e": 1466, "s": 1343, "text": "Time series decomposition refers to the method by which we reduce our time series data into its following four components:" }, { "code": null, "e": 1513, "s": 1466, "text": "Trend [T]Cycle [C]Seasonality [S]Remainder [R]" }, { "code": null, "e": 1523, "s": 1513, "text": "Trend [T]" }, { "code": null, "e": 1533, "s": 1523, "text": "Cycle [C]" }, { "code": null, "e": 1549, "s": 1533, "text": "Seasonality [S]" }, { "code": null, "e": 1563, "s": 1549, "text": "Remainder [R]" }, { "code": null, "e": 1739, "s": 1563, "text": "The trend of a time series refers to the general direction in which the time series is moving. Time series can have a positive or a negative trend, but can also have no trend." }, { "code": null, "e": 1910, "s": 1739, "text": "For example, the GDP growth rate for the United States (and many advanced economies) does not have a trend because economic forces keep the growth rate relatively stable." }, { "code": null, "e": 2105, "s": 1910, "text": "The cycle for time series data refers to its tendency to rise and fall at inconsistent frequencies. We often use the cycle component of a time series to discuss business cycles in economic data." }, { "code": null, "e": 2302, "s": 2105, "text": "The seasonal component of a time series is similar to its cycle component except for one important difference: the seasonal component refers to data that rises and falls at consistent frequencies." }, { "code": null, "e": 2542, "s": 2302, "text": "The tourism industry is well-acquainted with the seasonal component. A country’s tourism industry experiences high revenues in the warmer months, and then its revenues slowly inch towards the precipice of a cliff at the first sign of snow." }, { "code": null, "e": 2748, "s": 2542, "text": "The remainder is what’s left of the time series data after removing its trend, cycle, and seasonal components. It is the random fluctuation in the time series data that the above components cannot explain." }, { "code": null, "e": 2973, "s": 2748, "text": "When forecasting, it is advantageous to use a ‘seasonally-adjusted’ time series, which is just a time series with the seasonal component removed. This allows a forecaster to focus on predicting the general trend of the data." }, { "code": null, "e": 3150, "s": 2973, "text": "A second reason to use time series decomposition is to identify any interesting behavior in the seasonal component. Then, we can research why our data moves in the way it does." }, { "code": null, "e": 3284, "s": 3150, "text": "Interestingly, Statsmodels knows that there are better ways to decompose time series data than the usual seasonal_decompose function." }, { "code": null, "e": 3319, "s": 3284, "text": "They warn us (emphasis is my own):" }, { "code": null, "e": 3446, "s": 3319, "text": "This [seasonal_decompose] is a naive decomposition. More sophisticated methods should be preferred — Statsmodels Documentation" }, { "code": null, "e": 3565, "s": 3446, "text": "Seasonal_decompose uses the classical decomposition method, of which there are two types: additive and multiplicative." }, { "code": null, "e": 3667, "s": 3565, "text": "Additive decomposition argues that time series data is a function of the sum of its components. Thus," }, { "code": null, "e": 3785, "s": 3667, "text": "where Y is the time series data, T is the trend-cycle component, S is the seasonal component, and R is the remainder." }, { "code": null, "e": 3807, "s": 3785, "text": "Rearranging gives us," }, { "code": null, "e": 3942, "s": 3807, "text": "Rather than a sum, the multiplicative decomposition argues that time series data is a function of the product of its components. Thus," }, { "code": null, "e": 3969, "s": 3942, "text": "And, rearranging gives us," }, { "code": null, "e": 4187, "s": 3969, "text": "We can usually identify an additive or multiplicative time series from its variation. If the magnitude of the seasonal component changes with time, then the series is multiplicative. Otherwise, the series is additive." }, { "code": null, "e": 4384, "s": 4187, "text": "Notice that the magnitude of the seasonal component — the difference between the maximum point of the series and the red line — is relatively constant from 2011 onward in the additive time series." }, { "code": null, "e": 4488, "s": 4384, "text": "However, in the multiplicative series, the magnitude of the seasonal component grows as time increases." }, { "code": null, "e": 4701, "s": 4488, "text": "Note: identifying whether a series is additive or multiplicative is trickier than the above image might suggest. Oftentimes, one component of the time series might be additive while the others are multiplicative." }, { "code": null, "e": 4758, "s": 4701, "text": "For example, you can reasonably have a time series where" }, { "code": null, "e": 4769, "s": 4758, "text": "And, thus," }, { "code": null, "e": 4841, "s": 4769, "text": "The classical approach to time series decomposition has several issues:" }, { "code": null, "e": 5588, "s": 4841, "text": "It uses two-sided moving averages to estimate the trend-cycle. Thus, the first few observations and the last few observations are absent from the trend-cycle.It assumes that the seasonal component is constant throughout the entire series. While this may be an accurate assumption for short time periods, this assumption becomes untenable for longer periods. For example, innovations in air travel and other modes of transportation have made fundamental changes in the tourism industry for many economies; and thus, it would be incorrect to assume that its seasonal variation has remained stable throughout its history.The trend line over-smooths the data. Thus, it is not responsive to sharp fluctuations. This causes a large remainder component." }, { "code": null, "e": 5747, "s": 5588, "text": "It uses two-sided moving averages to estimate the trend-cycle. Thus, the first few observations and the last few observations are absent from the trend-cycle." }, { "code": null, "e": 6208, "s": 5747, "text": "It assumes that the seasonal component is constant throughout the entire series. While this may be an accurate assumption for short time periods, this assumption becomes untenable for longer periods. For example, innovations in air travel and other modes of transportation have made fundamental changes in the tourism industry for many economies; and thus, it would be incorrect to assume that its seasonal variation has remained stable throughout its history." }, { "code": null, "e": 6337, "s": 6208, "text": "The trend line over-smooths the data. Thus, it is not responsive to sharp fluctuations. This causes a large remainder component." }, { "code": null, "e": 6430, "s": 6337, "text": "Thankfully, there are approaches to time series decomposition that resolve the above issues." }, { "code": null, "e": 6571, "s": 6430, "text": "X11 Decomposition creates a trend-cycle for all observations. As well, the X11 Decomposition allows the seasonal component to change slowly." }, { "code": null, "e": 6886, "s": 6571, "text": "I’m unaware of any Python library that implements the X-11 procedure. However, this can be done relatively easily with the seas function in R’s seasonal package. You might be able to use the rpy2 library to replicate the R code in Python. (I will update this article later this week once I’ve found a work-around)." }, { "code": null, "e": 6907, "s": 6886, "text": "seas(data, x11 = \"\")" }, { "code": null, "e": 6999, "s": 6907, "text": "Let’s compare the results of the X11 decomposition with those of a classical decomposition." }, { "code": null, "e": 7005, "s": 6999, "text": "In R:" }, { "code": null, "e": 7062, "s": 7005, "text": "library(forecast)library(ggplot2)autoplot(AirPassengers)" }, { "code": null, "e": 7171, "s": 7062, "text": "Because the seasonal component increases with time, we know that we should use multiplicative decomposition." }, { "code": null, "e": 7247, "s": 7171, "text": "mfit <- decompose(x = AirPassengers, type = \"multiplicative\")autoplot(mfit)" }, { "code": null, "e": 7449, "s": 7247, "text": "Notice that the seasonal component is unchanging, the remainder component has a lot of large values, and the trend line is missing some observations from the beginning and from the end of our data set." }, { "code": null, "e": 7487, "s": 7449, "text": "Now, if we use the X11 decomposition," }, { "code": null, "e": 7541, "s": 7487, "text": "fit <- seas(x = AirPassengers, x11 = \"\")autoplot(fit)" }, { "code": null, "e": 7573, "s": 7541, "text": "You should notice three things:" }, { "code": null, "e": 7906, "s": 7573, "text": "The seasonal component increases with time, thus reflecting the fundamental changes in the airline industry since 1950.The remainder component is smaller than was the case when we had done the classical decomposition. This is because our trend line is a good fit for the raw data.There are no missing observations in the trend line." }, { "code": null, "e": 8026, "s": 7906, "text": "The seasonal component increases with time, thus reflecting the fundamental changes in the airline industry since 1950." }, { "code": null, "e": 8188, "s": 8026, "text": "The remainder component is smaller than was the case when we had done the classical decomposition. This is because our trend line is a good fit for the raw data." }, { "code": null, "e": 8241, "s": 8188, "text": "There are no missing observations in the trend line." }, { "code": null, "e": 8314, "s": 8241, "text": "One problem with X11 is that it only handles monthly and quarterly data." }, { "code": null, "e": 8360, "s": 8314, "text": "Another is that it is not robust to outliers." }, { "code": null, "e": 8508, "s": 8360, "text": "Therefore, in 1990, researchers at the University of Michigan and Bell Labs published “STL: Seasonal-Trend Decomposition Procedure Based on Loess”." }, { "code": null, "e": 8605, "s": 8508, "text": "The STL approach to time series decomposition has the following advantages over the X11 aproach:" }, { "code": null, "e": 8732, "s": 8605, "text": "It handles any type of seasonality.The user can control the rate of change of the seasonal component.It is robust to outliers." }, { "code": null, "e": 8768, "s": 8732, "text": "It handles any type of seasonality." }, { "code": null, "e": 8835, "s": 8768, "text": "The user can control the rate of change of the seasonal component." }, { "code": null, "e": 8861, "s": 8835, "text": "It is robust to outliers." }, { "code": null, "e": 8915, "s": 8861, "text": "We can implement STL in Python with the STL function." }, { "code": null, "e": 8956, "s": 8915, "text": "from statsmodels.tsa.seasonal import STL" }, { "code": null, "e": 9244, "s": 8956, "text": "We can change the smoothness of the trend-cycle and the seasonal components by passing an integer into the trend and seasonal arguments in the STL function. The seasonal argument is set to 7 by default (it is also recommended that you use a seasonal smoother greater than or equal to 7)." }, { "code": null, "e": 9368, "s": 9244, "text": "If a trend value is not specified, then Statsmodels calculates a trend value by using the smallest odd integer greater than" }, { "code": null, "e": 9697, "s": 9368, "text": "The choice of the seasonal smoother is up to you. The larger is the integer, the more ‘smooth’ your seasonal component becomes. This causes less of the variation in your data to be attributed to its seasonal component. Thus, you must decide how much variation in your data can be reasonably attributed to the seasonal component." }, { "code": null, "e": 9951, "s": 9697, "text": "The originators of the STL method suggest using a seasonal diagnostic plot, and then experimenting with different smoother values to determine which value seems right. Unfortunately, there is no implementation of this in Python (there is in R, however)." }, { "code": null, "e": 10164, "s": 9951, "text": "from statsmodels.tsa.seasonal import STLimport matplotlib.pyplot as pltimport pandas as pddf = df[:len(df) - 1] # Removes the last row in the data setcolumns = ['Month', 'Passengers']df.columns = columnsdf.head()" }, { "code": null, "e": 10357, "s": 10164, "text": "df = df.set_index('Month') # Set the index to datetime object.df = df.asfreq('MS') # Set frequency# Set robust to True to handle outliersres = STL(df, robust = True).fit() res.plot()plt.show()" }, { "code": null, "e": 10633, "s": 10357, "text": "The variation in the seasonal component has changed more rapidly than was the case when we had used the X11 decomposition. Because the STL decomposition is also robust to outliers, its estimation of the seasonal component is likely more accurate than the estimation from X11." }, { "code": null, "e": 10749, "s": 10633, "text": "Feel free to experiment with the seasonal argument in the STL function. Just make sure that you use an odd integer." }, { "code": null, "e": 10851, "s": 10749, "text": "If you’d like to seasonally adjust your data, then subtract the seasonal component from the raw data." }, { "code": null, "e": 10860, "s": 10851, "text": "That is," }, { "code": null, "e": 10929, "s": 10860, "text": "df['Seasonally Adjusted'] = df['Passengers'] - res.seasonaldf.head()" }, { "code": null, "e": 11195, "s": 10929, "text": "Now you know alternative approaches to seasonal decomposition. These alternative approaches will give you better estimates of the seasonality and trend-cycle components of your time series than you would have received with Statsmodels’s seasonal_decompose function." }, { "code": null, "e": 11338, "s": 11195, "text": "You will also be able to use these approaches to obtain more accurate forecasts, and to better identify interesting patterns in your data set." }, { "code": null, "e": 11483, "s": 11338, "text": "[1] Hyndman, R.J., & Athanasopoulos, G. (2018) Forecasting: principles and practice, 2nd edition, OTexts: Melbourne, Australia. OTexts.com/fpp2." }, { "code": null, "e": 11580, "s": 11483, "text": "[2]https://www.statsmodels.org/stable/generated/statsmodels.tsa.seasonal.seasonal_decompose.html" }, { "code": null, "e": 11718, "s": 11580, "text": "[3] Sutcliffe, Andrew. (1993) “X11 Time Series Decomposition and Sampling Errors”, Australian Bureau of Statistics: Melbourne, Australia." }, { "code": null, "e": 11885, "s": 11718, "text": "[4] Cleveland, R.B., Cleveland W.S., McRae J.E., & Terpenning, I. (1990) “STL: Seasonal-Trend Decomposition Procedure Based on Loess”, Journal of Official Statistics." }, { "code": null, "e": 11955, "s": 11885, "text": "[5] Gardner, Dillon R. (2017) “STL Algorithm Explained: STL Part II”." }, { "code": null, "e": 12364, "s": 11955, "text": "The trend term can be non-linear. Also, there are two types of trends: stochastic and deterministic. I will discuss these in a later article.The seasonal_decompose function can also estimate a one-sided moving average; however, this causes there to be more missing observations at the beginning of the series than if we had used the two-sided approach, and zero missing observations at the end of the series." }, { "code": null, "e": 12506, "s": 12364, "text": "The trend term can be non-linear. Also, there are two types of trends: stochastic and deterministic. I will discuss these in a later article." } ]
Building a Conversational Chatbot for Slack using Rasa and Python -Part 2 | by Parul Pandey | Towards Data Science
Note: This article was written long ago and there may be changes in RASA which haven’t been incorporated into the article. It is advised to go to their official documentation site for the latest details. “Slack went down again, so the colleagues had to talk to each other”. When slack went down momentarily during mid-2018, the whole tech world had descended into chaos and mayhem. Internet was flooded with discussions on slack and #Slack was trending on Twitter. Well, slack has already become an integral part of a lot of companies and people use it a lot to communicate and discuss things. Some companies which work remotely use slack all the time for real-time communication. This is the concluding part of the article: Building a Conversational Chatbot for Slack using Rasa and Python -Part 1. In the first part, we discussed in detail about Rasa Stack: an open source machine learning toolkit that lets developers expand bots beyond answering simple questions. We then used two modules of Rasa namely Rasa NLU and Rasa Core to build a fully functional chatbot capable of checking in on people’s mood and take the necessary actions to cheer them up. The actions included showing the users an image of a dog, cat or bird depending upon the user’s choice. In this article, we will utilize all the generated files to deploy the Bot on slack. I highly recommend that you read Part 1 before attempting Part 2. Unlike the previous part, we will have to install the latest version of Rasa Core. It is highly recommended that you create a virtual environment and then proceed with the installations #creating a virtual environmentconda create --name bot python=3.6#Activate the new environment to use itWINDOWS: activate botLINUX, macOS: source activate bot#Install latest Rasa stack#Rasa NLUpython -m pip install rasa_nlu[spacy] (https://rasa.com/docs/nlu/installation/)#Rasa Corepython -m pip install -U rasa_core (https://rasa.com/docs/core/installation/)#Language Modelpython -m spacy download en_core_web_mdpython -m spacy link en_core_web_md en --force; Clone my GitHub repository. The repository contains the files generated in Part 1. However, due to some changes in Rasa API w.r.t versions, there are some changes in the functions and commands. Let’s us create a slack integration by creating a slack app. Let’s go through the process of creating a Slack app. Create a Slack account and go to https://api.slack.com/. Now choose either an existing development Slack workplace(in case you have one) or create a new one. Name it DemoWorkplace or anything you like. Now create a Slack app in DemoWorkplace and give it a name. Let’s call our app Robo. Start adding features and functionalities to the app. We’ll first create a bot user under the Bots Tab and integrate it into the app. This will make the app conversational. Since this bot will be created as a user, we can choose to keep it constantly online. Save all the changes made. To make sure that the bot has been integrated, navigate to the Add Features and Functionality under Basic Information Taband make sure that the Bots and Permissions Tabs are active. Our bot has been integrated into the app. Next, we can add a lit bit more info about our bot including a picture, a description and a background colour. Scroll to Display Information and add in the information. Save all changes as you go. Lastly, we need to install this app into our workplace which we defined earlier. Authorize it and we have our app ready and integrated into the workplace. The process has been summarised in the gif below. Ngrok is a multi-platform tunnelling, reverse proxy software that establishes secure tunnels from a public endpoint such as the internet to a locally running network service. In simple words it means, it opens access to your local app from the internet. Download ngrok from here. make sure you Login first. Unzip to install via $ unzip /path/to/ngrok.zip Connect your account via $ ./ngrok <authtoken> Navigate to the directory where you unzipped ngrok and type $ ngrok <authtoken> in the console. The token can be accessed from here. Fire it up. Start it by telling it which port we want to expose to the public internet : ./ngrok http 5004 If all goes well you should see the following screen: Here http://-------.ngrok.io is the ngrok url. Create a Python Script Since we are done with all the requirements, it’s time to deploy our bot. For this, we will need to write a Python script called run_app.py, which will integrate our chatbot with the slack app that we created above. We will begin by creating a slack connector for our Rasa chatbot. We will use RasaNLU interpreter to load the NLU model directly from the python script. We will train our model again to make sure everything is good and running. python nlu_model.py The actions file that we created in Part 1, now needs to be run on a separate server. This is a change in the latest version of Rasa Core. Read the documentation for more details. Start the custom action server python -m rasa_core_sdk.endpoint --actions actions Open a new terminal and train the Rasa Core model python dialogue_management_model.py Start the Agent by running run_app.py file . Make sure to provide the slack token in the script. The slack token can be obtained as follows. Start the ngrok on port 5004 and grab your ngrok_url. Provide the url: https://<your_ngrok_url>/webhooks/slack/webhook to ‘Event Subscriptions’ page of the Slack configuration. Wait for it to be verified. Lastly, subscribe to some Workplace events like : app_mention so that our bot responds when someone mentions it by name message_im which allows the user to send direct messages to the bot. Make sure to save all the changes as you go Ensure the custom actions server is runningEnsure ngrok is running on port 5004Navigate to Slack interface and talk to your bot This might sound like a herculean task but if you follow it step wise step, you will finally be able to create a working slackbot called Robo in no time. You will be able to chat with your bot, like the way I am able to: This was a pretty comprehensive tutorial but the fact that we were able to build a fully function Slackbot makes all the hard work worthwhile. Rasa is a pretty useful library and you can experiment and tinker with it to create some truly useful chatbots. Read Part 1 here Link to Github Repository
[ { "code": null, "e": 376, "s": 172, "text": "Note: This article was written long ago and there may be changes in RASA which haven’t been incorporated into the article. It is advised to go to their official documentation site for the latest details." }, { "code": null, "e": 446, "s": 376, "text": "“Slack went down again, so the colleagues had to talk to each other”." }, { "code": null, "e": 853, "s": 446, "text": "When slack went down momentarily during mid-2018, the whole tech world had descended into chaos and mayhem. Internet was flooded with discussions on slack and #Slack was trending on Twitter. Well, slack has already become an integral part of a lot of companies and people use it a lot to communicate and discuss things. Some companies which work remotely use slack all the time for real-time communication." }, { "code": null, "e": 1432, "s": 853, "text": "This is the concluding part of the article: Building a Conversational Chatbot for Slack using Rasa and Python -Part 1. In the first part, we discussed in detail about Rasa Stack: an open source machine learning toolkit that lets developers expand bots beyond answering simple questions. We then used two modules of Rasa namely Rasa NLU and Rasa Core to build a fully functional chatbot capable of checking in on people’s mood and take the necessary actions to cheer them up. The actions included showing the users an image of a dog, cat or bird depending upon the user’s choice." }, { "code": null, "e": 1583, "s": 1432, "text": "In this article, we will utilize all the generated files to deploy the Bot on slack. I highly recommend that you read Part 1 before attempting Part 2." }, { "code": null, "e": 1769, "s": 1583, "text": "Unlike the previous part, we will have to install the latest version of Rasa Core. It is highly recommended that you create a virtual environment and then proceed with the installations" }, { "code": null, "e": 2230, "s": 1769, "text": "#creating a virtual environmentconda create --name bot python=3.6#Activate the new environment to use itWINDOWS: activate botLINUX, macOS: source activate bot#Install latest Rasa stack#Rasa NLUpython -m pip install rasa_nlu[spacy] (https://rasa.com/docs/nlu/installation/)#Rasa Corepython -m pip install -U rasa_core (https://rasa.com/docs/core/installation/)#Language Modelpython -m spacy download en_core_web_mdpython -m spacy link en_core_web_md en --force;" }, { "code": null, "e": 2258, "s": 2230, "text": "Clone my GitHub repository." }, { "code": null, "e": 2424, "s": 2258, "text": "The repository contains the files generated in Part 1. However, due to some changes in Rasa API w.r.t versions, there are some changes in the functions and commands." }, { "code": null, "e": 2539, "s": 2424, "text": "Let’s us create a slack integration by creating a slack app. Let’s go through the process of creating a Slack app." }, { "code": null, "e": 2741, "s": 2539, "text": "Create a Slack account and go to https://api.slack.com/. Now choose either an existing development Slack workplace(in case you have one) or create a new one. Name it DemoWorkplace or anything you like." }, { "code": null, "e": 2826, "s": 2741, "text": "Now create a Slack app in DemoWorkplace and give it a name. Let’s call our app Robo." }, { "code": null, "e": 3112, "s": 2826, "text": "Start adding features and functionalities to the app. We’ll first create a bot user under the Bots Tab and integrate it into the app. This will make the app conversational. Since this bot will be created as a user, we can choose to keep it constantly online. Save all the changes made." }, { "code": null, "e": 3336, "s": 3112, "text": "To make sure that the bot has been integrated, navigate to the Add Features and Functionality under Basic Information Taband make sure that the Bots and Permissions Tabs are active. Our bot has been integrated into the app." }, { "code": null, "e": 3505, "s": 3336, "text": "Next, we can add a lit bit more info about our bot including a picture, a description and a background colour. Scroll to Display Information and add in the information." }, { "code": null, "e": 3533, "s": 3505, "text": "Save all changes as you go." }, { "code": null, "e": 3688, "s": 3533, "text": "Lastly, we need to install this app into our workplace which we defined earlier. Authorize it and we have our app ready and integrated into the workplace." }, { "code": null, "e": 3738, "s": 3688, "text": "The process has been summarised in the gif below." }, { "code": null, "e": 3992, "s": 3738, "text": "Ngrok is a multi-platform tunnelling, reverse proxy software that establishes secure tunnels from a public endpoint such as the internet to a locally running network service. In simple words it means, it opens access to your local app from the internet." }, { "code": null, "e": 4045, "s": 3992, "text": "Download ngrok from here. make sure you Login first." }, { "code": null, "e": 4093, "s": 4045, "text": "Unzip to install via $ unzip /path/to/ngrok.zip" }, { "code": null, "e": 4140, "s": 4093, "text": "Connect your account via $ ./ngrok <authtoken>" }, { "code": null, "e": 4273, "s": 4140, "text": "Navigate to the directory where you unzipped ngrok and type $ ngrok <authtoken> in the console. The token can be accessed from here." }, { "code": null, "e": 4285, "s": 4273, "text": "Fire it up." }, { "code": null, "e": 4380, "s": 4285, "text": "Start it by telling it which port we want to expose to the public internet : ./ngrok http 5004" }, { "code": null, "e": 4434, "s": 4380, "text": "If all goes well you should see the following screen:" }, { "code": null, "e": 4481, "s": 4434, "text": "Here http://-------.ngrok.io is the ngrok url." }, { "code": null, "e": 4504, "s": 4481, "text": "Create a Python Script" }, { "code": null, "e": 4873, "s": 4504, "text": "Since we are done with all the requirements, it’s time to deploy our bot. For this, we will need to write a Python script called run_app.py, which will integrate our chatbot with the slack app that we created above. We will begin by creating a slack connector for our Rasa chatbot. We will use RasaNLU interpreter to load the NLU model directly from the python script." }, { "code": null, "e": 4948, "s": 4873, "text": "We will train our model again to make sure everything is good and running." }, { "code": null, "e": 4968, "s": 4948, "text": "python nlu_model.py" }, { "code": null, "e": 5148, "s": 4968, "text": "The actions file that we created in Part 1, now needs to be run on a separate server. This is a change in the latest version of Rasa Core. Read the documentation for more details." }, { "code": null, "e": 5179, "s": 5148, "text": "Start the custom action server" }, { "code": null, "e": 5230, "s": 5179, "text": "python -m rasa_core_sdk.endpoint --actions actions" }, { "code": null, "e": 5280, "s": 5230, "text": "Open a new terminal and train the Rasa Core model" }, { "code": null, "e": 5316, "s": 5280, "text": "python dialogue_management_model.py" }, { "code": null, "e": 5457, "s": 5316, "text": "Start the Agent by running run_app.py file . Make sure to provide the slack token in the script. The slack token can be obtained as follows." }, { "code": null, "e": 5511, "s": 5457, "text": "Start the ngrok on port 5004 and grab your ngrok_url." }, { "code": null, "e": 5662, "s": 5511, "text": "Provide the url: https://<your_ngrok_url>/webhooks/slack/webhook to ‘Event Subscriptions’ page of the Slack configuration. Wait for it to be verified." }, { "code": null, "e": 5712, "s": 5662, "text": "Lastly, subscribe to some Workplace events like :" }, { "code": null, "e": 5782, "s": 5712, "text": "app_mention so that our bot responds when someone mentions it by name" }, { "code": null, "e": 5851, "s": 5782, "text": "message_im which allows the user to send direct messages to the bot." }, { "code": null, "e": 5895, "s": 5851, "text": "Make sure to save all the changes as you go" }, { "code": null, "e": 6023, "s": 5895, "text": "Ensure the custom actions server is runningEnsure ngrok is running on port 5004Navigate to Slack interface and talk to your bot" }, { "code": null, "e": 6244, "s": 6023, "text": "This might sound like a herculean task but if you follow it step wise step, you will finally be able to create a working slackbot called Robo in no time. You will be able to chat with your bot, like the way I am able to:" }, { "code": null, "e": 6499, "s": 6244, "text": "This was a pretty comprehensive tutorial but the fact that we were able to build a fully function Slackbot makes all the hard work worthwhile. Rasa is a pretty useful library and you can experiment and tinker with it to create some truly useful chatbots." }, { "code": null, "e": 6516, "s": 6499, "text": "Read Part 1 here" } ]
Python | Sort dictionary by value list length - GeeksforGeeks
11 May, 2020 While working with Python, one might come to a problem in which one needs to perform a sort on dictionary list value length. This can be typically in case of scoring or any type of count algorithm. Let’s discuss a method by which this task can be performed. Method : Using sorted() + join() + lambdaThe combination of above functions can be used to perform this particular task. In this, we just use the lambda function to perform this particular task, sorted and join function perform the required sorting and encapsulation of result respectively. # Python3 code to demonstrate working of# Sort dictionary by value list length# using sorted() + join() + lambda # Initialize dictionarytest_dict = {'is' : [1, 2], 'gfg' : [3], 'best' : [1, 3, 4]} # Printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # using sorted() + join() + lambda# Sort dictionary by value list lengthres = ' '.join(sorted(test_dict, key = lambda key: len(test_dict[key]))) # printing result print("Sorted keys by value list : " + res) The original dictionary is : {'is': [1, 2], 'best': [1, 3, 4], 'gfg': [3]} Sorted keys by value list : gfg is best Python dictionary-programs Python-sort Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 26355, "s": 26327, "text": "\n11 May, 2020" }, { "code": null, "e": 26613, "s": 26355, "text": "While working with Python, one might come to a problem in which one needs to perform a sort on dictionary list value length. This can be typically in case of scoring or any type of count algorithm. Let’s discuss a method by which this task can be performed." }, { "code": null, "e": 26904, "s": 26613, "text": "Method : Using sorted() + join() + lambdaThe combination of above functions can be used to perform this particular task. In this, we just use the lambda function to perform this particular task, sorted and join function perform the required sorting and encapsulation of result respectively." }, { "code": "# Python3 code to demonstrate working of# Sort dictionary by value list length# using sorted() + join() + lambda # Initialize dictionarytest_dict = {'is' : [1, 2], 'gfg' : [3], 'best' : [1, 3, 4]} # Printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # using sorted() + join() + lambda# Sort dictionary by value list lengthres = ' '.join(sorted(test_dict, key = lambda key: len(test_dict[key]))) # printing result print(\"Sorted keys by value list : \" + res)", "e": 27398, "s": 26904, "text": null }, { "code": null, "e": 27514, "s": 27398, "text": "The original dictionary is : {'is': [1, 2], 'best': [1, 3, 4], 'gfg': [3]}\nSorted keys by value list : gfg is best\n" }, { "code": null, "e": 27541, "s": 27514, "text": "Python dictionary-programs" }, { "code": null, "e": 27553, "s": 27541, "text": "Python-sort" }, { "code": null, "e": 27560, "s": 27553, "text": "Python" }, { "code": null, "e": 27576, "s": 27560, "text": "Python Programs" }, { "code": null, "e": 27674, "s": 27576, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27692, "s": 27674, "text": "Python Dictionary" }, { "code": null, "e": 27727, "s": 27692, "text": "Read a file line by line in Python" }, { "code": null, "e": 27759, "s": 27727, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27781, "s": 27759, "text": "Enumerate() in Python" }, { "code": null, "e": 27823, "s": 27781, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27866, "s": 27823, "text": "Python program to convert a list to string" }, { "code": null, "e": 27888, "s": 27866, "text": "Defaultdict in Python" }, { "code": null, "e": 27927, "s": 27888, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27973, "s": 27927, "text": "Python | Split string into list of characters" } ]
Machine Learning Project 9 — Predict weight based on height and gender | by Omair Aasim | Towards Data Science
Today I am going to be working on this Kaggle dataset. This dataset has 10,000 rows and provides the weight, height and gender of the person. We have to build and train a model on this dataset so it can predict the weight of a person given their gender and height. This is the first project that we are working on that has a large dataset. So this is going to be interesting. #100DaysOfMLCode #100ProjectsInML Let’s get started. First we will load the dataset. Below is the sample dataset — The full data file can be found here. The dataset contains 3 columns namely “Gender”, “Height” and “Weight”. Height is given in inches and weight in pounds. Let’s analyze the data. dataset.info(): This method returns the output below. It basically shows the number of entries, the column names and the column types. Below is the output of the command. <class ‘pandas.core.frame.DataFrame’>RangeIndex: 10000 entries, 0 to 9999Data columns (total 3 columns):Gender 10000 non-null objectHeight 10000 non-null float64Weight 10000 non-null float64dtypes: float64(2), object(1)memory usage: 234.5+ KB dataset.describe(): The describe method displays basic statistical information on the numerical values of the dataset like mean, standard deviation, percentile, min and max. For example: for height, we can see that the average is 66.36 inches and the min height is 54.26 inches and max height is 78.99 inches. Similarly for weight, the average is 161.44 lbs, the min weight is 64.7 lbs and the max weight is 269.98 lbs. Below is the output of the command. Height Weightcount 10000.000000 10000.000000mean 66.367560 161.440357std 3.847528 32.108439min 54.263133 64.70012725% 63.505620 135.81805150% 66.318070 161.21292875% 69.174262 187.169525max 78.998742 269.989699 dataset.isnull().sum() This method is basically used to check if there are any null values in the dataset. This will list number of null values in each column Below is the output of the command. We can see that there are no null values in any of the 3 columns. Gender 0Height 0Weight 0dtype: int64 Before we run any machine learning models, we have to convert all categorical values (text values) to numerical values. In our dataset, we can see that we have one field — “Gender” which is categorical. So we have to convert this field into numerical. The typical way of converting categorical values to numerical is by using the LabelEncoder class to convert Text to Numbers and then using OneHotEncoder to add dummy variables. We did this in our Project 2. But this is useful only if the categorical field contains more than 2 values — for instance, let’s say we have a field called “City” and it contains more than 2 values like “Houston”, “New York” and “San Francisco”. In this case, we will first use LabelEncoder to convert the cities to numbers like: “Houston” => 0 and “New York” => 1 and “San Francisco” => 2. Then we will use OneHotEncoder to add 3 dummy variables one for each city. Finally, we will drop one dummy variable to avoid the dummy variable trap. The rule of thumb is — if a categorical field has k values then you will need k-1 dummy variables. Now in our case, our “Gender” field contains only 2 values — “Male” and “Female”. When we use LabelEncoder, it will convert say “Male” =>0 and “Female” => 1. Since it contains only 2 values, there is no need for us to use OneHotEncoder and add dummy variables. If we use OneHotEncoder, it will end up adding 2 dummy variables but we will end up dropping 1 to avoid the dummy trap. So it makes no sense to do it. So if a categorical field has 2 values — there are 2 ways for us to do this. Use LabelEncoder Replace directly in DataFrame Rather than using a LabelEncoder, we can directly replace Male with 0 and Female with 1 in the DataFrame as shown below: In both cases, the Gender will be converted to 0 for Male and 1 for Female as shown below in screenshot of X. We will use 80% of the data for training and 20% of the data for testing. We will use the LinearRegression to train our model. Let’s compare the predicted values (lin_pred) with the actual values (y_test). We can see that our model did a fairly good job. There are a couple of metrics we can check to see how well our model performed. One of them is the R squared. We can see that our R squared is showing almost 90% accuracy which is good. The Mean Squared Error and Mean Absolute Error we will explore in future projects. R square = 0.9052889824534557Mean squared Error = 97.87152220196164Mean absolute Error = 7.955916525326746R square = 0.9052889824534557Mean squared Error = 97.87152220196164Mean absolute Error = 7.955916525326746 Let’s see how well the model does in predicting my weight. I’m 6ft 2 — that’s 74 inches. My predicted weight = [197.2481918] All I can say is that it’s not accurate :) — Maybe I am just an outlier — well outliers is another topic we will leave for another day. I had fun building this project. Looking for the next challenging project that I will be solving next. The source code can be found here.
[ { "code": null, "e": 547, "s": 171, "text": "Today I am going to be working on this Kaggle dataset. This dataset has 10,000 rows and provides the weight, height and gender of the person. We have to build and train a model on this dataset so it can predict the weight of a person given their gender and height. This is the first project that we are working on that has a large dataset. So this is going to be interesting." }, { "code": null, "e": 581, "s": 547, "text": "#100DaysOfMLCode #100ProjectsInML" }, { "code": null, "e": 600, "s": 581, "text": "Let’s get started." }, { "code": null, "e": 700, "s": 600, "text": "First we will load the dataset. Below is the sample dataset — The full data file can be found here." }, { "code": null, "e": 771, "s": 700, "text": "The dataset contains 3 columns namely “Gender”, “Height” and “Weight”." }, { "code": null, "e": 819, "s": 771, "text": "Height is given in inches and weight in pounds." }, { "code": null, "e": 843, "s": 819, "text": "Let’s analyze the data." }, { "code": null, "e": 859, "s": 843, "text": "dataset.info():" }, { "code": null, "e": 1014, "s": 859, "text": "This method returns the output below. It basically shows the number of entries, the column names and the column types. Below is the output of the command." }, { "code": null, "e": 1257, "s": 1014, "text": "<class ‘pandas.core.frame.DataFrame’>RangeIndex: 10000 entries, 0 to 9999Data columns (total 3 columns):Gender 10000 non-null objectHeight 10000 non-null float64Weight 10000 non-null float64dtypes: float64(2), object(1)memory usage: 234.5+ KB" }, { "code": null, "e": 1277, "s": 1257, "text": "dataset.describe():" }, { "code": null, "e": 1431, "s": 1277, "text": "The describe method displays basic statistical information on the numerical values of the dataset like mean, standard deviation, percentile, min and max." }, { "code": null, "e": 1567, "s": 1431, "text": "For example: for height, we can see that the average is 66.36 inches and the min height is 54.26 inches and max height is 78.99 inches." }, { "code": null, "e": 1677, "s": 1567, "text": "Similarly for weight, the average is 161.44 lbs, the min weight is 64.7 lbs and the max weight is 269.98 lbs." }, { "code": null, "e": 1713, "s": 1677, "text": "Below is the output of the command." }, { "code": null, "e": 2020, "s": 1713, "text": " Height Weightcount 10000.000000 10000.000000mean 66.367560 161.440357std 3.847528 32.108439min 54.263133 64.70012725% 63.505620 135.81805150% 66.318070 161.21292875% 69.174262 187.169525max 78.998742 269.989699" }, { "code": null, "e": 2043, "s": 2020, "text": "dataset.isnull().sum()" }, { "code": null, "e": 2179, "s": 2043, "text": "This method is basically used to check if there are any null values in the dataset. This will list number of null values in each column" }, { "code": null, "e": 2281, "s": 2179, "text": "Below is the output of the command. We can see that there are no null values in any of the 3 columns." }, { "code": null, "e": 2318, "s": 2281, "text": "Gender 0Height 0Weight 0dtype: int64" }, { "code": null, "e": 2570, "s": 2318, "text": "Before we run any machine learning models, we have to convert all categorical values (text values) to numerical values. In our dataset, we can see that we have one field — “Gender” which is categorical. So we have to convert this field into numerical." }, { "code": null, "e": 2777, "s": 2570, "text": "The typical way of converting categorical values to numerical is by using the LabelEncoder class to convert Text to Numbers and then using OneHotEncoder to add dummy variables. We did this in our Project 2." }, { "code": null, "e": 2993, "s": 2777, "text": "But this is useful only if the categorical field contains more than 2 values — for instance, let’s say we have a field called “City” and it contains more than 2 values like “Houston”, “New York” and “San Francisco”." }, { "code": null, "e": 3138, "s": 2993, "text": "In this case, we will first use LabelEncoder to convert the cities to numbers like: “Houston” => 0 and “New York” => 1 and “San Francisco” => 2." }, { "code": null, "e": 3288, "s": 3138, "text": "Then we will use OneHotEncoder to add 3 dummy variables one for each city. Finally, we will drop one dummy variable to avoid the dummy variable trap." }, { "code": null, "e": 3387, "s": 3288, "text": "The rule of thumb is — if a categorical field has k values then you will need k-1 dummy variables." }, { "code": null, "e": 3799, "s": 3387, "text": "Now in our case, our “Gender” field contains only 2 values — “Male” and “Female”. When we use LabelEncoder, it will convert say “Male” =>0 and “Female” => 1. Since it contains only 2 values, there is no need for us to use OneHotEncoder and add dummy variables. If we use OneHotEncoder, it will end up adding 2 dummy variables but we will end up dropping 1 to avoid the dummy trap. So it makes no sense to do it." }, { "code": null, "e": 3876, "s": 3799, "text": "So if a categorical field has 2 values — there are 2 ways for us to do this." }, { "code": null, "e": 3893, "s": 3876, "text": "Use LabelEncoder" }, { "code": null, "e": 3923, "s": 3893, "text": "Replace directly in DataFrame" }, { "code": null, "e": 4044, "s": 3923, "text": "Rather than using a LabelEncoder, we can directly replace Male with 0 and Female with 1 in the DataFrame as shown below:" }, { "code": null, "e": 4154, "s": 4044, "text": "In both cases, the Gender will be converted to 0 for Male and 1 for Female as shown below in screenshot of X." }, { "code": null, "e": 4228, "s": 4154, "text": "We will use 80% of the data for training and 20% of the data for testing." }, { "code": null, "e": 4281, "s": 4228, "text": "We will use the LinearRegression to train our model." }, { "code": null, "e": 4409, "s": 4281, "text": "Let’s compare the predicted values (lin_pred) with the actual values (y_test). We can see that our model did a fairly good job." }, { "code": null, "e": 4519, "s": 4409, "text": "There are a couple of metrics we can check to see how well our model performed. One of them is the R squared." }, { "code": null, "e": 4678, "s": 4519, "text": "We can see that our R squared is showing almost 90% accuracy which is good. The Mean Squared Error and Mean Absolute Error we will explore in future projects." }, { "code": null, "e": 4891, "s": 4678, "text": "R square = 0.9052889824534557Mean squared Error = 97.87152220196164Mean absolute Error = 7.955916525326746R square = 0.9052889824534557Mean squared Error = 97.87152220196164Mean absolute Error = 7.955916525326746" }, { "code": null, "e": 4980, "s": 4891, "text": "Let’s see how well the model does in predicting my weight. I’m 6ft 2 — that’s 74 inches." }, { "code": null, "e": 5016, "s": 4980, "text": "My predicted weight = [197.2481918]" }, { "code": null, "e": 5152, "s": 5016, "text": "All I can say is that it’s not accurate :) — Maybe I am just an outlier — well outliers is another topic we will leave for another day." }, { "code": null, "e": 5255, "s": 5152, "text": "I had fun building this project. Looking for the next challenging project that I will be solving next." } ]
Using DDL Statements Questions
1.What is the full form of DDL in Oracle DB? Data Deleting Language Data Definition Language Data Delegating Language Dummy Data Language Data Deleting Language Data Definition Language Data Delegating Language Dummy Data Language Answer: B. DDL is one of the categories of SQL which stands for Data Definition Language. Other SQL types are DML, DCL, and TCL. 2.DDL statements are used for which of the following Oracle database objects? Tables Sub-queries Rows Columns Tables Sub-queries Rows Columns Answer: A. DDL contains commands like CREATE, ALTER and ANALYZE which are used to CREATE TABLEs, view stored subprograms and packages in a database schema. 3.What is the basic unit of storage in Oracle Database that contains data? View Column Query Table View Column Query Table Answer: D. Table is the basic unit of physical storage of data in Oracle database. 4.Which of the below options best define a View? It is the shorter form of a table It is the logical representation of the subsets from one or more tables It has only one row and one column None of the above It is the shorter form of a table It is the logical representation of the subsets from one or more tables It has only one row and one column None of the above Answer: B. View is a query which behaves like a window to format the data contained in one or more tables. Views do not contain any physical data but just a query which are created during runtime. 5. Which of the following are database objects? Table Sequence Synonym All of the above Table Sequence Synonym All of the above Answer: D. Objects which are physically stored in database schema are database objects. 6. Which of the following database objects generate numeric values? Table View Index Sequence Table View Index Sequence Answer: D. Sequence are used to generate unique values starting with a definite value and incremented by a specified factor. A sequence can be created to generate a series of integers. The values generated by a sequence can be stored in any table. A sequence is created with the CREATE SEQUENCE command. 7.Which of the following database objects gives an alternative name to an object? Synonym Sequence View Index Synonym Sequence View Index Answer: A. A synonym provides a permanent alias for a database object. A public synonym is available to any database user. A private synonym is available only to the user who created it. A synonym is created by using the CREATE SYNONYM command. A synonym is deleted by using the DROP SYNONYM command. Only a user with DBA privileges can drop a public synonym. 8.Which of the following database objects improves the performance of some queries? Table Synonym View Index Table Synonym View Index Answer: D. 9. When a table can be created? When the database is not being used by any user When the database is newly created It can be created any time, even when a user is using the database None of the above When the database is not being used by any user When the database is newly created It can be created any time, even when a user is using the database None of the above Answer: C. An index can be created to speed up the query process. DML operations are always slower when indexes exist. Oracle 11g creates an index for PRIMARY KEY and UNIQUE constraints automatically. An explicit index is created with the CREATE INDEX command. An index can be used by Oracle 11g automatically if a query criterion or sort operation is based on a column or an expression used to create the index. 10. What is true about a table? It is not mandatory to specify the size of a table The size of each table is the same A table can be modified online None of the above It is not mandatory to specify the size of a table The size of each table is the same A table can be modified online None of the above Answer: A, C. 11. A table named 123_A is created for storing the number of employees in an organization. What is wrong in the name of the table? The name of a table cannot start with a digit Nothing is wrong in this name. You cannot use an underscore while naming a table None of the above The name of a table cannot start with a digit Nothing is wrong in this name. You cannot use an underscore while naming a table None of the above Answer: A. As per the object naming conventions, table name must start with an alphabet. 12. What is the range of number of letters a table name can have? 1-20 characters 1-10 characters 1-30 characters 1-50 characters 1-20 characters 1-10 characters 1-30 characters 1-50 characters Answer: C. A table name cannot exceed more than 30 characters. 13 Which of the following characters can be used to name a table? A to Z a to z 0 to 9 All of the above A to Z a to z 0 to 9 All of the above Answer: D. As per the standard naming convention in Oracle, object's name can contain alphabets in any case. Mandatorily, first place is for letters while the rest can be mix of letters and digits. 14. Which of the following special characters can be used to name a table? @ # $ _ (underscore) @ # $ _ (underscore) Answer: B, C, D. No other special character, except (#, $, _), are allowed while naming a table. Use of special characters in the table name is discouraged. 15. What is true about the name of a table? A table can have a name which is used by some other object owned by the same user A sequence and a table can have same names A view and a table can have the same name A table name must not duplicate the name of another object owned by the same user A table can have a name which is used by some other object owned by the same user A sequence and a table can have same names A view and a table can have the same name A table name must not duplicate the name of another object owned by the same user Answer: D. By virtue of namespace, a table name cannot be same as any other schema objects. Schema objects which share the same namespace include tables, views, sequences, private synonyms, stored procedures, stored functions, packages, materialized views, and user-defined types. 16.You create a table and name it as COUNT. What will be the outcome of CREATE TABLE script? The table will not be created The table will be created and an underscore will be added automatically to the name COUNT_ An ORA error will be thrown The table COUNT will be created without any errors The table will not be created The table will be created and an underscore will be added automatically to the name COUNT_ An ORA error will be thrown The table COUNT will be created without any errors Answer: A, C. You cannot create a table with the name same as an Oracle Server reserved word. 17. You create a table using quoted identifiers ' '. How will you refer this table? 'table_name' "table_name" Either of A or B None of the above 'table_name' "table_name" Either of A or B None of the above Answer: B. If the table is created with the name having a quoted identifier, it must be addressed using double quotes. Using quoted identifiers is not recommended. Quoted identifiers are case-sensitive 18. You create a table named EMPLOYEES. What among the following is possible? It can be referred to as eMPLOYEES It can be referred to as EMPLoyees It can be referred to as employees All of the above It can be referred to as eMPLOYEES It can be referred to as EMPLoyees It can be referred to as employees All of the above Answer: D. Unquoted objects names are not case-senstive in Oracle. 19. What among the following are the pre-requisites for creating a table? CREATE TABLE privilege Storage space Data in the table None of the above CREATE TABLE privilege Storage space Data in the table None of the above Answer: A, B. A user must possess the CREATE TABLE privilege and must have sufficient space to allocate the initial extent to the table segment. 20. What is the syntax for creating a table? CREATE TABLE [schema.] table (column datatype [DEFAULT expr] [,..] ); CREATE TABLE INTO [schema.] table (column datatype [DEFAULT expr] [,..] ); CREATE TABLE VALUES [schema.] table (column datatype [DEFAULT expr] [,..] ); None of the above CREATE TABLE [schema.] table (column datatype [DEFAULT expr] [,..] ); CREATE TABLE INTO [schema.] table (column datatype [DEFAULT expr] [,..] ); CREATE TABLE VALUES [schema.] table (column datatype [DEFAULT expr] [,..] ); None of the above Answer: A. 21. Pick the element which you must specify while creating a table. Column name Column Data type Column size All of the above Column name Column Data type Column size All of the above Answer: D. A table must have atleasr one column, its data type specification, and precision (if required). 22. A user named "Kevin" wants to access a table which is owned by another user named "Jonathan". Which of the following will work for Kevin? Select * from Kevin.employees; Select * from jonathan.employees; Either of A or B None of the above Select * from Kevin.employees; Select * from jonathan.employees; Either of A or B None of the above Answer: B. 23. What is true about a schema? A schema is owned by a database user and has the same name as that user Each user owns a single schema Schema objects include database links All of the above A schema is owned by a database user and has the same name as that user Each user owns a single schema Schema objects include database links All of the above Answer: D. The user space in a database is known as schema. A schema contains the objects which are owned or accessed by the user. Each user can have single schema of its own. 24. What among the following is true about tables? A default value is given to a table A default value can be given to a column of a table during an INSERT statement Either of A or B None of the above A default value is given to a table A default value can be given to a column of a table during an INSERT statement Either of A or B None of the above Answer: B. A default value can be specified for a column during the definition using the keyword DEFAULT. 25. Which of the following can be used with the DEFAULT option while creating a table? Strings Expressions SQL functions All of the above Strings Expressions SQL functions All of the above Answer: D. The default value for a column can either be a literal or a derivative using SQL function. 26. Which of the following command is used to see the structure of a table? UPDATE SHOW DESCRIBE SPOOL UPDATE SHOW DESCRIBE SPOOL Answer: C. DESCRIBE is a SQL*Plus command to list the structure of the table. 27.What is the limit of CHECK constraints on a column? No limit 1 2 4 No limit 1 2 4 Answer: A. Oracle imposes no limit on the check constraints on a column. 28. Which of the following commands will drop table employees? (Consider the table structure as given) SQL> DESC employees Name Null? Type ----------------------- -------- ---------------- EMPLOYEE_ID NOT NULL NUMBER(6) FIRST_NAME VARCHAR2(20) LAST_NAME NOT NULL VARCHAR2(25) EMAIL NOT NULL VARCHAR2(25) PHONE_NUMBER VARCHAR2(20) HIRE_DATE NOT NULL DATE JOB_ID NOT NULL VARCHAR2(10) SALARY NUMBER(8,2) COMMISSION_PCT NUMBER(2,2) MANAGER_ID NUMBER(6) DEPARTMENT_ID NUMBER(4) DROP employees DROP TABLE employees TRUNCATE employees None of the above DROP employees DROP employees DROP TABLE employees DROP TABLE employees TRUNCATE employees TRUNCATE employees None of the above Answer: B. 29. What is true about a namespace? It is a group of object types Within a namespace, all the object names should be uniquely identified by schema and name The same type of objects in different namespaces can share the same name All of the above It is a group of object types Within a namespace, all the object names should be uniquely identified by schema and name The same type of objects in different namespaces can share the same name All of the above Answer: D. A namespace defines a group of object types,within which all names must be uniquely identified-by schema and name.Objects in different namespaces can share the same name. 30. Which of the following object types share the same namespace? Synonyms Table Views All of the above Synonyms Table Views All of the above Answer: D. 31. What among the following is true about a table and an index? An index and a table can have the same name in a schema An index and a table within a schema cannot have the same name Neither of A nor B None of the above An index and a table can have the same name in a schema An index and a table within a schema cannot have the same name Neither of A nor B None of the above Answer: A. As the index and constraints share the same namespace, a table and an index can have the same name. 32. What is true about creating a table? While creating a table, each column should be assigned a data type Data type assignment to columns is not mandatory A data type has to be assigned to a table and not to a column None of the above While creating a table, each column should be assigned a data type Data type assignment to columns is not mandatory A data type has to be assigned to a table and not to a column None of the above Answer: A. Each column must possess behavioral attributes like data types and precision in order to build the structure of the table. 33. Suppose you create a table as shown below: CREATE TABLE employees (emp_id NUMBER(4), last_name VARCHAR2 (20) ); How much space will Oracle allocate to the LAST_NAME column? If there are no rows, then Oracle will not allocate any space to the last_name column If rows are populated then Oracle will allocate unlimited space to the last_name column Neither of A nor B None of the above options If there are no rows, then Oracle will not allocate any space to the last_name column If rows are populated then Oracle will allocate unlimited space to the last_name column Neither of A nor B None of the above options Answer: A. 34. What is the range of size that a VARCHAR2 data type can take? 1 byte to 2 byte 1 byte to 2000 bytes 1 byte to 4000 bytes None of the above 1 byte to 2 byte 1 byte to 2000 bytes 1 byte to 4000 bytes None of the above Answer: C. Until Oracle 11g Release 2, string data type VARCHAR2 can maximum contain 4000 bytes. 35.What is the range of size that a CHAR data type can take? 1 byte to 2 byte 1 byte to 2000 bytes 1 byte to 4000 bytes 1 byte to 3000 bytes 1 byte to 2 byte 1 byte to 2000 bytes 1 byte to 4000 bytes 1 byte to 3000 bytes Answer: B. Until Oracle 11g Release 2, string data type CHAR can maximum contain 2000 bytes. 36. What is true about the CHAR data type? If the data is not the length of the column, then it will be replaced with NULL values If the data is not the length of the column, then it will be padded with spaces It is mandatory to have the data of the same size as mentioned in the CHAR size, else it throws an ORA error None of the above If the data is not the length of the column, then it will be replaced with NULL values If the data is not the length of the column, then it will be padded with spaces It is mandatory to have the data of the same size as mentioned in the CHAR size, else it throws an ORA error None of the above Answer: B. CHAR provides a fixed length storage to a value while VARCHAR2 is flexible. If the data of length less than CHAR precision is inserted in a CHAR column, the remaining length will be padded to the column value. 37. Which of the following is a data type for variable length binary data? VARCHAR VARCHAR2 RAW NVARCHAR2 VARCHAR VARCHAR2 RAW NVARCHAR2 Answer: C. 38. What is the precision allowed for the NUMBER data type? 1 to 20 1 to 4K 1 to 30 1 to 38 digits 1 to 20 1 to 4K 1 to 30 1 to 38 digits Answer: D. Until Oracle 11g Release 2, primary data type NUMBER had the maximum precision of 38 digits. 39. What is the scale allowed for the NUMBER data type? 1 to 20 -84 to 100 -84 to 127 None of the above 1 to 20 -84 to 100 -84 to 127 None of the above Answer: C. 40. Which of the following are the data types for date and time data? TIMESTAMP INTERVAL DAY TO SECOND TIMESTAMP WITH LOCAL TIMEZONE All of the above TIMESTAMP INTERVAL DAY TO SECOND TIMESTAMP WITH LOCAL TIMEZONE All of the above Answer: D. 41. Which of the following data types are for large objects? CLOB BLOB RAW All of the above CLOB BLOB RAW All of the above Answer: A, B. LOB data types in SQL are BLOB, CLOB, and BFILE. 42. What will happen if the inserted value is of a smaller length as defined for a VARCHAR2 data type column? It will throw an ORA error It will get inserted successfully and the value will take up as much space as it needs. It will get inserted and the remaining space will be padded with spaces None of the above It will throw an ORA error It will get inserted successfully and the value will take up as much space as it needs. It will get inserted and the remaining space will be padded with spaces None of the above Answer: B. VARCHAR2 contains variable length character data. 43. What does NUMBER (8, 2) in oracle mean? It means there are 8 digits in total, 6 digits before the decimal and 2 after the decimal It means there are 10 digits in total with 8 digits before the decimal and 2 after decimal It means there are 2 digits before the decimal and 8 after the decimal point None of the above It means there are 8 digits in total, 6 digits before the decimal and 2 after the decimal It means there are 10 digits in total with 8 digits before the decimal and 2 after decimal It means there are 2 digits before the decimal and 8 after the decimal point None of the above Answer: A. The p indicates precision,the total number of digits to the left and right of the decimal position, to a maximum of 38 digits; the s, or scale, indicates the number of positions to the right of the decimal.Example: NUMBER(7, 2) can store a numeric value up to 99999.99. If precision or scale isn't specified, the column defaults to a precision of 38 digits. 44. Which of the following queries will create a table with no rows in it? CREATE TABLE emp AS SELECT 0 from dual; CREATE TABLE emp AS SELECT * from employees where 1=1; CREATE TABLE emp AS SELECT * from employees where 1=2; CREATE TABLE emp AS SELECT 0 from employees; CREATE TABLE emp AS SELECT 0 from dual; CREATE TABLE emp AS SELECT 0 from dual; CREATE TABLE emp AS SELECT * from employees where 1=1; CREATE TABLE emp AS SELECT * from employees where 1=1; CREATE TABLE emp AS SELECT * from employees where 1=2; CREATE TABLE emp AS SELECT * from employees where 1=2; CREATE TABLE emp AS SELECT 0 from employees; CREATE TABLE emp AS SELECT 0 from employees; Answer: C. The direct path operation CTAS (CREATE TABLE .. AS SELECT..) can be used to copy the structure of an existing table without copying the data. 45. Which of the following statements would add a column to a table already created? ALTER TABLE table_name add column (job varchar2(20)); ALTER TABLE table_name add job varchar2(20); ALTER TABLE table_name add (job varchar2(20)); ALTER TABLE table_name add column (job); ALTER TABLE table_name add column (job varchar2(20)); ALTER TABLE table_name add column (job varchar2(20)); ALTER TABLE table_name add job varchar2(20); ALTER TABLE table_name add job varchar2(20); ALTER TABLE table_name add (job varchar2(20)); ALTER TABLE table_name add (job varchar2(20)); ALTER TABLE table_name add column (job); ALTER TABLE table_name add column (job); Answer: C. The ALTER TABLE command allows a user to add a new column to a table.The same rules for creating a column in a new table apply to adding a column to an existing table.The new column must be defined by a column name and datatype (and width, if applicable).A default value can also be assigned. The difference is that the new column is added at the end of the existing table-it will be the last column. 46. Which of the following statements will modify the data type of an already existing column? ALTER TABLE table_name MODIFY (job varchar2(10) ); ALTER TABLE table_name MODIFY job varchar2(10); ALTER TABLE table_name MODIFY column (job varchar2(10) ); ALTER TABLE table_name MODIFY (job varchar2(10) ); ALTER TABLE table_name MODIFY (job varchar2(10) ); ALTER TABLE table_name MODIFY (job varchar2(10) ); ALTER TABLE table_name MODIFY job varchar2(10); ALTER TABLE table_name MODIFY job varchar2(10); ALTER TABLE table_name MODIFY column (job varchar2(10) ); ALTER TABLE table_name MODIFY column (job varchar2(10) ); ALTER TABLE table_name MODIFY (job varchar2(10) ); ALTER TABLE table_name MODIFY (job varchar2(10) ); Answer: A. The ALTER TABLE..MODIFY is used to modify column definition in a table. The admissible changes are increasing column precision, change datatype within a datatype family, or change the default value of the column. 47. Which of the following statements will remove a column from the table? ALTER TABLE table_name DROP (job varchar2(10) ); ALTER TABLE table table_name DROP COLUMN (job varchar2(10) ); ALTER TABLE table table_name DROP COLUMN (job); ALTER TABLE table_name MODIFY (job varchar2(10) ); ALTER TABLE table_name DROP (job varchar2(10) ); ALTER TABLE table_name DROP (job varchar2(10) ); ALTER TABLE table table_name DROP COLUMN (job varchar2(10) ); ALTER TABLE table table_name DROP COLUMN (job varchar2(10) ); ALTER TABLE table table_name DROP COLUMN (job); ALTER TABLE table table_name DROP COLUMN (job); ALTER TABLE table_name MODIFY (job varchar2(10) ); ALTER TABLE table_name MODIFY (job varchar2(10) ); Answer: C. The ALTER TABLE..DROP COLUMN can be used to drop a column from the table. 48. Which of the following will rename the column emp_id to empno? ALTER TABLE employees RENAME column emp_id to empno; ALTER TABLE employees RENAME emp_id to empno; ALTER TABLE employees RENAME column emp_id to empno; None of the above; ALTER TABLE employees RENAME column emp_id to empno; ALTER TABLE employees RENAME column emp_id to empno; ALTER TABLE employees RENAME emp_id to empno; ALTER TABLE employees RENAME emp_id to empno; ALTER TABLE employees RENAME column emp_id to empno; ALTER TABLE employees RENAME column emp_id to empno; None of the above; Answer: A. The ALTER TABLE..RENAME can be used to rename an existing column in teh table. 49. You need to mark the table employees as read only. Which of the following statements will you execute to get the required result? ALTER TABLE employees set READ; ALTER TABLE employees READ ONLY; ALTER TABLE employees READ_ONLY; ALTER TABLE employees set READ ONLY; ALTER TABLE employees set READ; ALTER TABLE employees set READ; ALTER TABLE employees READ ONLY; ALTER TABLE employees READ ONLY; ALTER TABLE employees READ_ONLY; ALTER TABLE employees READ_ONLY; ALTER TABLE employees set READ ONLY; ALTER TABLE employees set READ ONLY; Answer: B. A table can be marked read only to make it passive against the DML and DDL statements. The read only feature was introduced in Oracle 11g. 50. What among the following is true about DDL statements? DDL commands become the part of ongoing transaction DDL commands are auto commit and end the ongoing active transaction If the DDL command fails, the current transaction is still committed If the DDL command fails, the current transaction is rolled back DDL commands become the part of ongoing transaction DDL commands are auto commit and end the ongoing active transaction If the DDL command fails, the current transaction is still committed If the DDL command fails, the current transaction is rolled back Answer: B. DDL commands are auto commit only if they are successfully executed without errors. If DDL command fails, the ongoing transaction is still active in the session and not committed into the database. 51. What happens if there is an active transaction against a table on which a DDL is issued? The transaction rolls back The transaction is committed and terminated Both A and B None of the above The transaction rolls back The transaction is committed and terminated Both A and B None of the above Answer: B. 52. Which of the following commands will remove unused columns in an SQL statement? ALTER TABLE tablename DROP COLUMN column_name; ALTER TABLE tablename DROP unused columns; ALTER TABLE tablename set unused column; ALTER TABLE tablename DROP columns; ALTER TABLE tablename DROP COLUMN column_name; ALTER TABLE tablename DROP COLUMN column_name; ALTER TABLE tablename DROP unused columns; ALTER TABLE tablename DROP unused columns; ALTER TABLE tablename set unused column; ALTER TABLE tablename set unused column; ALTER TABLE tablename DROP columns; ALTER TABLE tablename DROP columns; Answer: C. The SET UNUSED command drops only the un-used columns from a table and is faster 53. What happens when a table which is marked Read Only is attempted for drop? It will throw an error It will no longer remain Read Only but cannot be dropped either It will be dropped without errors It will remain un-touched It will throw an error It will no longer remain Read Only but cannot be dropped either It will be dropped without errors It will remain un-touched Answer: C. The DROP command affects the data dictionary definition of the tables which are not Read Only and hence dropping is possible Consider the following statement and answer the questions 54 and 55 that follow: CREATE TABLE departments (dept_id NUMBER (2), dept_name VARCHAR2(14), create_date DATE DEFAULT SYSDATE); 54. What will happen if the DEFAULT clause specification is removed from the statement? The script will throw error because DATE columns must be specified with a default value A system generated default value will be assigned to the column Table will be created with no default value for CREATE_DATE column None of the above The script will throw error because DATE columns must be specified with a default value A system generated default value will be assigned to the column Table will be created with no default value for CREATE_DATE column None of the above Answer: C. 55.What is true about the above statement? It will automatically commit the transaction in session It will create the table DEPARTMENTS in the schema It will set a default value for CREATE_DATE column None of the above It will automatically commit the transaction in session It will create the table DEPARTMENTS in the schema It will set a default value for CREATE_DATE column None of the above Answer: A, B, C. 56. Up to which limit can a BLOB data type column hold values? 1 KB 2 GB 4 GB 3 KB 1 KB 2 GB 4 GB 3 KB Answer: C. As per Oracle 11g, the maximum size of data accomodated in a BLOB can be 4GB. 57.What is the difference between CLOB and BLOB data types? (Choose the most appropriate answer) CLOB is character data , BLOB is binary data CLOB is character data up to 2GB, BLOB is binary data up to 4 GB CLOB is character data up to 4 GB, BLOB is binary data up to 4 GB None of the above CLOB is character data , BLOB is binary data CLOB is character data up to 2GB, BLOB is binary data up to 4 GB CLOB is character data up to 4 GB, BLOB is binary data up to 4 GB None of the above Answer: C. CLOB is a character large object which is used to store character files like PDF, docs and text files while BLOB is a binary LOB used to store media files. 58.What among the following is a ROWID? It is a serial number given to a set of rows starting with 1 It is an alphanumeric address given to a row in a table Both A and B None of the above It is a serial number given to a set of rows starting with 1 It is an alphanumeric address given to a row in a table Both A and B None of the above Answer: B. It is a base-64 system representing the unique address of a row in its table. 59.What is the data type used for storing Binary data stored in an external file (up to 4 GB)? BLOB CLOB CFILE BFILE BLOB CLOB CFILE BFILE Answer: D. BFILE is an external LOB type which is used to refer external media files. Internal LOB types are BLOB and CLOB which are used for binary large files and character large files stored in the database. 60. What is true about a table created with a sub-query? A VARCHAR2 data type column is not copied when a table is created using a sub-query A CLOB data type column is not copied when a table is created using a sub-query A LONG column is not copied when a table is created using a sub-query None of the above A VARCHAR2 data type column is not copied when a table is created using a sub-query A CLOB data type column is not copied when a table is created using a sub-query A LONG column is not copied when a table is created using a sub-query None of the above Answer: C. The CTAS method to create a table doesn't copies the LONG column. 61. Which of the following data types cannot be used with a GROUP BY and an ORDER BY clause? CLOB VARCHAR2 CHAR LONG CLOB VARCHAR2 CHAR LONG Answer: D. LONG data types cannot be used in GROUP BY and ORDER BY clause. 62. How many LONG columns can a table contain? None Maximum 2 Minimum 2 Only one None Maximum 2 Minimum 2 Only one Answer: D. A table can contain maximum one column of LONG type. 63.Which of the following data types cannot be constrained in SQL? VARCHAR2 LONG CHAR DATE VARCHAR2 LONG CHAR DATE Answer: B. Constraints cannot be created on LONG type columns. 64. Which of the following data types can you use if you want a date with fractional seconds? DATE VARCHAR2 TIMESTAMP None of the above DATE VARCHAR2 TIMESTAMP None of the above Answer: C. The TIMESTAMP data type provides additional precised information of date values. It provides fractional seconds and time zone information. 65. You need to store an interval of days, hours, minutes and seconds in a column. Which of the data type would help? TIMESTAMP INTERVAL YEAR TO MONTH INTERVAL DAY TO SECOND None of the above TIMESTAMP INTERVAL YEAR TO MONTH INTERVAL DAY TO SECOND None of the above Answer: C. 66.You need to find how many employees were hired in June, 2011 and June, 2012. Which of the following data types will help? INTERVAL DAY TO SECOND TIMESTAMP DATE INTERVAL YEAR TO MONTH INTERVAL DAY TO SECOND TIMESTAMP DATE INTERVAL YEAR TO MONTH Answer: D. 67. What is true about constraints? They enforce rules at the row level They enforce rules at the table level It is mandatory to have constraints created while creating a table None of the above They enforce rules at the row level They enforce rules at the table level It is mandatory to have constraints created while creating a table None of the above Answer: B. A constraint is a rule applied to data being added to a table. It represents business rules, policies, or procedures.Data violating the constraint isn't added to the table.A constraint can be included during table creation as part of the CREATE TABLE command or added to an existing table with the ALTER TABLE command. A constraint based on composite columns (more than one column) must be created by using the table-level approach. 68. How are constraints helpful? They limit the storage capacity of a table and hence save DB space They prevent the modification of a table They prevent deletion of a table if there are dependencies None of the above They limit the storage capacity of a table and hence save DB space They prevent the modification of a table They prevent deletion of a table if there are dependencies None of the above Answer: C. A constraint is a rule applied to data being added to a table.It represents business rules, policies, or procedures.Data violating the constraint isn't added to the table. 69.A RAW data type column can store variable-length binary strings up to what value? 10 GB 1 TB 2 GB 4 GB 10 GB 1 TB 2 GB 4 GB Answer: C. 70. Which of the following are valid constraints in Oracle? INDEX GENERAL UNIQUE PRIMARY KEY INDEX GENERAL UNIQUE PRIMARY KEY Answer: C, D. A NOT NULL constraint can be created only with the column-level approach. A PRIMARY KEY constraint doesn't allow duplicate or NULL values in the designated column. Only one PRIMARY KEY constraint is allowed in a table. A FOREIGN KEY constraint requires that the column entry match a referenced column entry in the table or be NULL. A UNIQUE constraint is similar to a PRIMARY KEY constraint, except it allows storing NULL values in the specified column. A CHECK constraint ensures that data meets a given condition before it's added to the table. 71. Which of the below DML operations consider constraints on a column? INSERT UNION DELETE UPDATE INSERT UNION DELETE UPDATE Answer: A, C, D. All the DML operations obey constraints on the columns of the table. 72. When can a constraint be created? While creating a table After creating a table Both A and B None of the above While creating a table After creating a table Both A and B None of the above Answer: C. A constraint can be included during table creation as part of the CREATE TABLE command or added to an existing table with the ALTER TABLE command. 73 Where are constraints stored? In the SGA In a table In data dictionary None of the above In the SGA In a table In data dictionary None of the above Answer: C. 74. You create a constraint but do not name it. What will be the default name given to the constraint? SYS_Cn SYS_constraint SYS_Const SYS_C0 SYS_Cn SYS_constraint SYS_Const SYS_C0 Answer: A. By default, Oracle gives a generic name to the constraints SYS_Cn, where the n is an integer to keep the name of a constraint unique. 75. What is the functional difference between a column-level constraint and a table-level constraint? Column-level constraint applies to all the columns of a table Table-level constraint applies to all the columns of a table They both are functionally the same, only the syntax is different None of the above Column-level constraint applies to all the columns of a table Table-level constraint applies to all the columns of a table They both are functionally the same, only the syntax is different None of the above Answer: C. Functionally, the table level constraints and column level constraints work similar. Composite constraints can be defined at table level only. 76. What is true about column-level constraints? They can be created before the creation of a table They can be created before the defining of a column They are included when the column is defined None of the above They can be created before the creation of a table They can be created before the defining of a column They are included when the column is defined None of the above Answer: C. Column level constraints are defined along with the column specification. 77. What is true about NOT NULL constraints in SQL? They should be defined at the table level They should be defined at the column level They should be defined only on one column They should be defined only on one row They should be defined at the table level They should be defined at the column level They should be defined only on one column They should be defined only on one row Answer: B. A NOT NULL constraint can be created only with the column-level approach. Consider the following statement and answer the questions 78 and 79 that follow: CREATE TABLE employees ( emp_id NUMBER (6) CONSTRAINT emp_emp_id_PK PRIMARY KEY, first_name VARCHAR2(20), last_name VARCHAR2(20), hire_date DATE ); 78.Which type of constraint is created in the above statement? Column level constraint Table level constraint Named constraint Specification constraint Column level constraint Table level constraint Named constraint Specification constraint Answer: A. A column level constraint is created along with the column definition. 79. What modification can be made to the above statement to give it a table level constraint? CONSTRAINT emp_emp_id_PK PRIMARY KEY CONSTRAINT emp_emp_id_PK PRIMARY KEY (EMP_ID) CONSTRAINT emp_emp_id_PK EMP_ID PRIMARY KEY CONSTRAINT PRIMARY KEY emp_emp_id_PK CONSTRAINT emp_emp_id_PK PRIMARY KEY CONSTRAINT emp_emp_id_PK PRIMARY KEY (EMP_ID) CONSTRAINT emp_emp_id_PK EMP_ID PRIMARY KEY CONSTRAINT PRIMARY KEY emp_emp_id_PK Answer: B. 80. What is true about PRIMARY KEY constraint? It applies a NOT NULL constraint implicitly to the column on which it is defined It applies a UNIQUE KEY constraint implicitly to the column on which it is defined It applies a CHECK constraint implicitly to the column on which it is defined It applies a DEFAULT constraint implicitly to the column on which it is defined It applies a NOT NULL constraint implicitly to the column on which it is defined It applies a UNIQUE KEY constraint implicitly to the column on which it is defined It applies a CHECK constraint implicitly to the column on which it is defined It applies a DEFAULT constraint implicitly to the column on which it is defined Answer: A. A PRIMARY KEY constraint doesn't allow duplicate or NULL values in the designated column. Only one PRIMARY KEY constraint is allowed in a table. 81. What among the following is true regarding a UNIQUE KEY constraint? UNIQUE KEY constraint and PRIMARY KEY constraint are the same UNIQUE KEY constraint allows NULL values if there is no NOT NULL defined on the column(s) We can have two identical rows when a UNIQUE KEY constraint is defined on a column None of the above UNIQUE KEY constraint and PRIMARY KEY constraint are the same UNIQUE KEY constraint allows NULL values if there is no NOT NULL defined on the column(s) We can have two identical rows when a UNIQUE KEY constraint is defined on a column None of the above Answer: B. A UNIQUE constraint is similar to a PRIMARY KEY constraint, except it allows storing NULL values in the specified column. Consider the following statement and answer the questions 82 and 83 that follow: CREATE TABLE employees ( emp_id NUMBER (6) first_name VARCHAR2(20), last_name VARCHAR2(20), job VARCHAR2(20), hire_date DATE CONSTRAINT emp_job_UK UNIQUE (job)); 82. Which of the below statements interpret the above CREATE TABLE script? This table cannot have two identical Job IDs This table can have two or more identical Job IDs This table can have NULL values in the JOB column None of the above This table cannot have two identical Job IDs This table can have two or more identical Job IDs This table can have NULL values in the JOB column None of the above Answer: A, C. A UNIQUE constraint on the JOB column will restrict duplicate value but allows nulls. 83. If the constraint emp_job_UK is modified as emp_job_PK PRIMARY KEY (job), what will be outcome? This change can happen only if there's no NULL value in the JOB column This change can happen without any restrictions This change will change the values of the column JOB None of the above This change can happen only if there's no NULL value in the JOB column This change can happen without any restrictions This change will change the values of the column JOB None of the above Answer: A. 84. What is true about the UNIQUE key constraint? A unique key index is implicitly created when a UNIQUE constraint is defined on a column A PRIMARY KEY constraint is implicitly created when a UNIQUE constraint is defined on a column A NOT NULL constraint is implicitly created when a UNIQUE constraint is defined on a column None of the above A unique key index is implicitly created when a UNIQUE constraint is defined on a column A PRIMARY KEY constraint is implicitly created when a UNIQUE constraint is defined on a column A NOT NULL constraint is implicitly created when a UNIQUE constraint is defined on a column None of the above Answer: A. When a unique constraint is imposed on a table, Oracle internally creates a unique key index on the column to restrict the duplication of values. 85. Which of the following is true about indexes? If an UPDATE statement is executed on a table, the indexes need to be manually updated as well If a DELETE statement is executed on a table, the indexes need to manually deleted as well When a table is dropped, the indexes are automatically dropped If an UPDATE statement is executed on a table, the corresponding indexes are updated as well. If an UPDATE statement is executed on a table, the indexes need to be manually updated as well If a DELETE statement is executed on a table, the indexes need to manually deleted as well When a table is dropped, the indexes are automatically dropped If an UPDATE statement is executed on a table, the corresponding indexes are updated as well. Answer: C, D. 86.Which of the following CREATE TABLE statements is valid? CREATE TABLE EMPLOYEES (emp_id NUMBER (2) PRIMARY KEY, first_name VARCHAR(20), last_name VARCHAR(20), hire_date DATE NOT NULL); CREATE TABLE EMPLOYEES (emp_id NUMBER (2) PRIMARY KEY NOT NULL, first_name VARCHAR(20), last_name VARCHAR(20), hire_date DATE NOT NULL PRIMARY KEY); CREATE TABLE EMPLOYEES (emp_id NUMBER (2) PRIMARY KEY, first_name VARCHAR(20), last_name VARCHAR(20), hire_date DATE NOT NULL UNIQUE); CREATE TABLE EMPLOYEES (emp_id NUMBER (2), first_name VARCHAR(20), last_name VARCHAR(20), hire_date DATE NOT NULL, CONSTRAINT emp_emp_id_PK PRIMARY KEY (emp_id)); CREATE TABLE EMPLOYEES (emp_id NUMBER (2) PRIMARY KEY, first_name VARCHAR(20), last_name VARCHAR(20), hire_date DATE NOT NULL); CREATE TABLE EMPLOYEES (emp_id NUMBER (2) PRIMARY KEY, first_name VARCHAR(20), last_name VARCHAR(20), hire_date DATE NOT NULL); CREATE TABLE EMPLOYEES (emp_id NUMBER (2) PRIMARY KEY NOT NULL, first_name VARCHAR(20), last_name VARCHAR(20), hire_date DATE NOT NULL PRIMARY KEY); CREATE TABLE EMPLOYEES (emp_id NUMBER (2) PRIMARY KEY NOT NULL, first_name VARCHAR(20), last_name VARCHAR(20), hire_date DATE NOT NULL PRIMARY KEY); CREATE TABLE EMPLOYEES (emp_id NUMBER (2) PRIMARY KEY, first_name VARCHAR(20), last_name VARCHAR(20), hire_date DATE NOT NULL UNIQUE); CREATE TABLE EMPLOYEES (emp_id NUMBER (2) PRIMARY KEY, first_name VARCHAR(20), last_name VARCHAR(20), hire_date DATE NOT NULL UNIQUE); CREATE TABLE EMPLOYEES (emp_id NUMBER (2), first_name VARCHAR(20), last_name VARCHAR(20), hire_date DATE NOT NULL, CONSTRAINT emp_emp_id_PK PRIMARY KEY (emp_id)); CREATE TABLE EMPLOYEES (emp_id NUMBER (2), first_name VARCHAR(20), last_name VARCHAR(20), hire_date DATE NOT NULL, CONSTRAINT emp_emp_id_PK PRIMARY KEY (emp_id)); Answer: A, C, D. All the CREATE TABLE scripts are valid. 87. How many PRIMARY KEY constraints can a table have? 0 Unlimited 2 1 0 Unlimited 2 1 Answer: D. A table can have one and only one primary key. 88. You want to put a CHECK constraint on the EMP_ID such that it should be equal to the current value of a Sequence through which it is getting its values. Which of the following statements will help you achieve this? Emp_id NUMBER (10) CONSTRAINT emp_emp_id_chk CHECK (emp_id = EMPNO.CURRVAL); Emp_id NUMBER (10) CONSTRAINT emp_emp_id_chk CHECK (emp_id = EMPNO.NEXTVAL); Emp_id NUMBER (10) CONSTRAINT emp_emp_id_chk CHECK (EMPNO.CURRVAL); None of the above Emp_id NUMBER (10) CONSTRAINT emp_emp_id_chk CHECK (emp_id = EMPNO.CURRVAL); Emp_id NUMBER (10) CONSTRAINT emp_emp_id_chk CHECK (emp_id = EMPNO.NEXTVAL); Emp_id NUMBER (10) CONSTRAINT emp_emp_id_chk CHECK (EMPNO.CURRVAL); None of the above Answer: D. You cannot use CURRVAL, NEXTVAL, LEVEL and ROWNUM pseudo columns in the CHECK constraint 89. Which of the following commands will help in converting the foreign key values to NULL? ON DELETE CASCADE ON DELETE SET NULL CASCADE REFERENCES ON DELETE CASCADE ON DELETE SET NULL CASCADE REFERENCES Answer: B. 90. You need to add a constraint to the EMPLOYEES table which restricts the addition of those employees who have salaries less than 10000. Which of the following commands will give you the required results? ALTER TABLE employees ADD CONSTRAINT emp_emp_sal_CHECK CHECK (salary >= 10000); ALTER TABLE employees ADD CHECK CONSTRAINT emp_emp_sal_CHECK (salary>10000); ALTER TABLE employees ADD CONSTRAINT CHECK emp_emp_sal_CHECK (salary = 10000); ALTER TABLE employees ADD CONSTRAINT emp_emp_sal_CHECK (salary < 10000); ALTER TABLE employees ADD CONSTRAINT emp_emp_sal_CHECK CHECK (salary >= 10000); ALTER TABLE employees ADD CONSTRAINT emp_emp_sal_CHECK CHECK (salary >= 10000); ALTER TABLE employees ADD CHECK CONSTRAINT emp_emp_sal_CHECK (salary>10000); ALTER TABLE employees ADD CHECK CONSTRAINT emp_emp_sal_CHECK (salary>10000); ALTER TABLE employees ADD CONSTRAINT CHECK emp_emp_sal_CHECK (salary = 10000); ALTER TABLE employees ADD CONSTRAINT CHECK emp_emp_sal_CHECK (salary = 10000); ALTER TABLE employees ADD CONSTRAINT emp_emp_sal_CHECK (salary < 10000); ALTER TABLE employees ADD CONSTRAINT emp_emp_sal_CHECK (salary < 10000); Answer: A. 91. You need to add a constraint to the EMPLOYEES table which imposes a restriction that the HIRE_DATE for all the employees should be equal to SYSDATE-7. Which of the following statements will give you the required results? ALTER TABLE employees ADD CHECK CONSTRAINT emp_emp_sal_CHECK ( to_char(hire_date,'DD-MON-YY') = SYSDATE -7); ALTER TABLE employees ADD CONSTRAINT CHECK emp_emp_sal_CHECK ( to_char(hire_date,'DD-MON-YY') = SYSDATE -7); ALTER TABLE employees ADD emp_emp_sal_CHECK CHECK ( to_char(hire_date,'DD-MON-YY') = SYSDATE -7); None of the above ALTER TABLE employees ADD CHECK CONSTRAINT emp_emp_sal_CHECK ( to_char(hire_date,'DD-MON-YY') = SYSDATE -7); ALTER TABLE employees ADD CHECK CONSTRAINT emp_emp_sal_CHECK ( to_char(hire_date,'DD-MON-YY') = SYSDATE -7); ALTER TABLE employees ADD CONSTRAINT CHECK emp_emp_sal_CHECK ( to_char(hire_date,'DD-MON-YY') = SYSDATE -7); ALTER TABLE employees ADD CONSTRAINT CHECK emp_emp_sal_CHECK ( to_char(hire_date,'DD-MON-YY') = SYSDATE -7); ALTER TABLE employees ADD emp_emp_sal_CHECK CHECK ( to_char(hire_date,'DD-MON-YY') = SYSDATE -7); ALTER TABLE employees ADD emp_emp_sal_CHECK CHECK ( to_char(hire_date,'DD-MON-YY') = SYSDATE -7); None of the above Answer: D. You cannot use SYSDATE, UID, USER and USERENV functions in the CHECK constraint. Consider the following query and answer the questions 92 to 94 that follow: CREATE TABLE EMPLOYEES (emp_id NUMBER (2), first_name VARCHAR(20), last_name VARCHAR(20), dept_id NUMBER (10), hire_date DATE DEFAULT SYSDATE CONSTRAINT emp_emp_id_PK PRIMARY KEY (emp_id, hire_date) CONSTRAINT emp_dept_FK FOREIGN KEY (dept_id) REFERENCES departments (dept_id) ); 92. Which of the below statements interpret the CREATE TABLE script? A FOREIGN KEY constraint is defined at the table level on the column DEPT_ID The FOREIGN KEY constraint defined references the DEPT_ID from the DEPARTMENTS table Both A and B None of the above A FOREIGN KEY constraint is defined at the table level on the column DEPT_ID The FOREIGN KEY constraint defined references the DEPT_ID from the DEPARTMENTS table Both A and B None of the above Answer: C. The keywords FOREIGN KEY and REFERENCES are used when we define a FOREIGN KEY constraint for referential integrity. 93. You need to delete all the dependent rows in DEPARTMENTS table when you delete the EMPLOYEES table. Which of the following command will solve the purpose? (Consider the table structures as given) SQL> DESC employees Name Null? Type ----------------------- -------- ---------------- EMPLOYEE_ID NOT NULL NUMBER(6) FIRST_NAME VARCHAR2(20) LAST_NAME NOT NULL VARCHAR2(25) EMAIL NOT NULL VARCHAR2(25) PHONE_NUMBER VARCHAR2(20) HIRE_DATE NOT NULL DATE JOB_ID NOT NULL VARCHAR2(10) SALARY NUMBER(8,2) COMMISSION_PCT NUMBER(2,2) MANAGER_ID NUMBER(6) DEPARTMENT_ID NUMBER(4) SQL> DESC departments Name Null? Type ----------------------- -------- ---------------- DEPARTMENT_ID NOT NULL NUMBER(4) DEPARTMENT_NAME NOT NULL VARCHAR2(30) MANAGER_ID NUMBER(6) LOCATION_ID NUMBER(4) ON DELETE SET NULL ON DELETE CASCADE DELETE ALL FOR UPDATE ON DELETE SET NULL ON DELETE CASCADE DELETE ALL FOR UPDATE Answer: B. If ON DELETE CASCADE is included in the constraint definition and a record is deleted from the parent table,any corresponding records in the child table are also deleted automatically. 94. The EMPLOYEES table as shown below, has 5 employees who work in department 10. An executive from admin department issues the below query. DELETE FROM departments WHERE dept_id = 10; What will be the outcome of this query? (Assume the table structures as shown) SQL> DESC employees Name Null? Type ----------------------- -------- ---------------- EMPLOYEE_ID NOT NULL NUMBER(6) FIRST_NAME VARCHAR2(20) LAST_NAME NOT NULL VARCHAR2(25) EMAIL NOT NULL VARCHAR2(25) PHONE_NUMBER VARCHAR2(20) HIRE_DATE NOT NULL DATE JOB_ID NOT NULL VARCHAR2(10) SALARY NUMBER(8,2) COMMISSION_PCT NUMBER(2,2) MANAGER_ID NUMBER(6) DEPARTMENT_ID NUMBER(4) SQL> DESC departments Name Null? Type ----------------------- -------- ---------------- DEPARTMENT_ID NOT NULL NUMBER(4) DEPARTMENT_NAME NOT NULL VARCHAR2(30) MANAGER_ID NUMBER(6) LOCATION_ID NUMBER(4) Integrity constraint error Successful execution Neither of A nor B None of the above Integrity constraint error Successful execution Neither of A nor B None of the above Answer: A. The DEPT_ID from DEPARTMENTS is the foreign key in the table EMPLOYEES and there are employees in department 10 ,hence a value cannot be deleted from the parent table unless the child record is found.
[ { "code": null, "e": 2642, "s": 2597, "text": "1.What is the full form of DDL in Oracle DB?" }, { "code": null, "e": 2737, "s": 2642, "text": "\nData Deleting Language\nData Definition Language\nData Delegating Language\nDummy Data Language\n" }, { "code": null, "e": 2760, "s": 2737, "text": "Data Deleting Language" }, { "code": null, "e": 2785, "s": 2760, "text": "Data Definition Language" }, { "code": null, "e": 2810, "s": 2785, "text": "Data Delegating Language" }, { "code": null, "e": 2830, "s": 2810, "text": "Dummy Data Language" }, { "code": null, "e": 2959, "s": 2830, "text": "Answer: B. DDL is one of the categories of SQL which stands for Data Definition Language. Other SQL types are DML, DCL, and TCL." }, { "code": null, "e": 3037, "s": 2959, "text": "2.DDL statements are used for which of the following Oracle database objects?" }, { "code": null, "e": 3071, "s": 3037, "text": "\nTables\nSub-queries\nRows\nColumns\n" }, { "code": null, "e": 3078, "s": 3071, "text": "Tables" }, { "code": null, "e": 3090, "s": 3078, "text": "Sub-queries" }, { "code": null, "e": 3095, "s": 3090, "text": "Rows" }, { "code": null, "e": 3103, "s": 3095, "text": "Columns" }, { "code": null, "e": 3259, "s": 3103, "text": "Answer: A. DDL contains commands like CREATE, ALTER and ANALYZE which are used to CREATE TABLEs, view stored subprograms and packages in a database schema." }, { "code": null, "e": 3334, "s": 3259, "text": "3.What is the basic unit of storage in Oracle Database that contains data?" }, { "code": null, "e": 3360, "s": 3334, "text": "\nView\nColumn\nQuery\nTable\n" }, { "code": null, "e": 3365, "s": 3360, "text": "View" }, { "code": null, "e": 3372, "s": 3365, "text": "Column" }, { "code": null, "e": 3378, "s": 3372, "text": "Query" }, { "code": null, "e": 3384, "s": 3378, "text": "Table" }, { "code": null, "e": 3467, "s": 3384, "text": "Answer: D. Table is the basic unit of physical storage of data in Oracle database." }, { "code": null, "e": 3516, "s": 3467, "text": "4.Which of the below options best define a View?" }, { "code": null, "e": 3677, "s": 3516, "text": "\nIt is the shorter form of a table\nIt is the logical representation of the subsets from one or more tables\nIt has only one row and one column\nNone of the above\n" }, { "code": null, "e": 3711, "s": 3677, "text": "It is the shorter form of a table" }, { "code": null, "e": 3783, "s": 3711, "text": "It is the logical representation of the subsets from one or more tables" }, { "code": null, "e": 3818, "s": 3783, "text": "It has only one row and one column" }, { "code": null, "e": 3836, "s": 3818, "text": "None of the above" }, { "code": null, "e": 4033, "s": 3836, "text": "Answer: B. View is a query which behaves like a window to format the data contained in one or more tables. Views do not contain any physical data but just a query which are created during runtime." }, { "code": null, "e": 4081, "s": 4033, "text": "5.\tWhich of the following are database objects?" }, { "code": null, "e": 4123, "s": 4081, "text": "\nTable\nSequence\nSynonym\nAll of the above\n" }, { "code": null, "e": 4129, "s": 4123, "text": "Table" }, { "code": null, "e": 4138, "s": 4129, "text": "Sequence" }, { "code": null, "e": 4146, "s": 4138, "text": "Synonym" }, { "code": null, "e": 4163, "s": 4146, "text": "All of the above" }, { "code": null, "e": 4251, "s": 4163, "text": "Answer: D. Objects which are physically stored in database schema are database objects." }, { "code": null, "e": 4319, "s": 4251, "text": "6.\tWhich of the following database objects generate numeric values?" }, { "code": null, "e": 4347, "s": 4319, "text": "\nTable\nView\nIndex\nSequence\n" }, { "code": null, "e": 4353, "s": 4347, "text": "Table" }, { "code": null, "e": 4358, "s": 4353, "text": "View" }, { "code": null, "e": 4364, "s": 4358, "text": "Index" }, { "code": null, "e": 4373, "s": 4364, "text": "Sequence" }, { "code": null, "e": 4677, "s": 4373, "text": "Answer: D. Sequence are used to generate unique values starting with a definite value and incremented by a specified factor. A sequence can be created to generate a series of integers. The values generated by a sequence can be stored in any table. A sequence is created with the CREATE SEQUENCE command." }, { "code": null, "e": 4759, "s": 4677, "text": "7.Which of the following database objects gives an alternative name to an object?" }, { "code": null, "e": 4789, "s": 4759, "text": "\nSynonym\nSequence\nView\nIndex\n" }, { "code": null, "e": 4797, "s": 4789, "text": "Synonym" }, { "code": null, "e": 4806, "s": 4797, "text": "Sequence" }, { "code": null, "e": 4811, "s": 4806, "text": "View" }, { "code": null, "e": 4817, "s": 4811, "text": "Index" }, { "code": null, "e": 5177, "s": 4817, "text": "Answer: A. A synonym provides a permanent alias for a database object. A public synonym is available to any database user. A private synonym is available only to the user who created it. A synonym is created by using the CREATE SYNONYM command. A synonym is deleted by using the DROP SYNONYM command. Only a user with DBA privileges can drop a public synonym." }, { "code": null, "e": 5261, "s": 5177, "text": "8.Which of the following database objects improves the performance of some queries?" }, { "code": null, "e": 5288, "s": 5261, "text": "\nTable\nSynonym\nView\nIndex\n" }, { "code": null, "e": 5294, "s": 5288, "text": "Table" }, { "code": null, "e": 5302, "s": 5294, "text": "Synonym" }, { "code": null, "e": 5307, "s": 5302, "text": "View" }, { "code": null, "e": 5313, "s": 5307, "text": "Index" }, { "code": null, "e": 5325, "s": 5313, "text": "Answer: D. " }, { "code": null, "e": 5357, "s": 5325, "text": "9.\tWhen a table can be created?" }, { "code": null, "e": 5527, "s": 5357, "text": "\nWhen the database is not being used by any user\nWhen the database is newly created\nIt can be created any time, even when a user is using the database\nNone of the above\n" }, { "code": null, "e": 5575, "s": 5527, "text": "When the database is not being used by any user" }, { "code": null, "e": 5610, "s": 5575, "text": "When the database is newly created" }, { "code": null, "e": 5677, "s": 5610, "text": "It can be created any time, even when a user is using the database" }, { "code": null, "e": 5695, "s": 5677, "text": "None of the above" }, { "code": null, "e": 6108, "s": 5695, "text": "Answer: C. An index can be created to speed up the query process. DML operations are always slower when indexes exist. Oracle 11g creates an index for PRIMARY KEY and UNIQUE constraints automatically. An explicit index is created with the CREATE INDEX command. An index can be used by Oracle 11g automatically if a query criterion or sort operation is based on a column or an expression used to create the index." }, { "code": null, "e": 6140, "s": 6108, "text": "10.\tWhat is true about a table?" }, { "code": null, "e": 6277, "s": 6140, "text": "\nIt is not mandatory to specify the size of a table\nThe size of each table is the same\nA table can be modified online\nNone of the above\n" }, { "code": null, "e": 6328, "s": 6277, "text": "It is not mandatory to specify the size of a table" }, { "code": null, "e": 6363, "s": 6328, "text": "The size of each table is the same" }, { "code": null, "e": 6394, "s": 6363, "text": "A table can be modified online" }, { "code": null, "e": 6412, "s": 6394, "text": "None of the above" }, { "code": null, "e": 6427, "s": 6412, "text": "Answer: A, C. " }, { "code": null, "e": 6559, "s": 6427, "text": "11.\tA table named 123_A is created for storing the number of employees in an organization. What is wrong in the name of the table?" }, { "code": null, "e": 6706, "s": 6559, "text": "\nThe name of a table cannot start with a digit\nNothing is wrong in this name.\nYou cannot use an underscore while naming a table\nNone of the above\n" }, { "code": null, "e": 6752, "s": 6706, "text": "The name of a table cannot start with a digit" }, { "code": null, "e": 6783, "s": 6752, "text": "Nothing is wrong in this name." }, { "code": null, "e": 6833, "s": 6783, "text": "You cannot use an underscore while naming a table" }, { "code": null, "e": 6851, "s": 6833, "text": "None of the above" }, { "code": null, "e": 6940, "s": 6851, "text": "Answer: A. As per the object naming conventions, table name must start with an alphabet." }, { "code": null, "e": 7006, "s": 6940, "text": "12.\tWhat is the range of number of letters a table name can have?" }, { "code": null, "e": 7072, "s": 7006, "text": "\n1-20 characters\n1-10 characters\n1-30 characters\n1-50 characters\n" }, { "code": null, "e": 7088, "s": 7072, "text": "1-20 characters" }, { "code": null, "e": 7104, "s": 7088, "text": "1-10 characters" }, { "code": null, "e": 7120, "s": 7104, "text": "1-30 characters" }, { "code": null, "e": 7136, "s": 7120, "text": "1-50 characters" }, { "code": null, "e": 7199, "s": 7136, "text": "Answer: C. A table name cannot exceed more than 30 characters." }, { "code": null, "e": 7265, "s": 7199, "text": "13 Which of the following characters can be used to name a table?" }, { "code": null, "e": 7305, "s": 7265, "text": "\nA to Z\na to z\n0 to 9\nAll of the above\n" }, { "code": null, "e": 7312, "s": 7305, "text": "A to Z" }, { "code": null, "e": 7319, "s": 7312, "text": "a to z" }, { "code": null, "e": 7326, "s": 7319, "text": "0 to 9" }, { "code": null, "e": 7343, "s": 7326, "text": "All of the above" }, { "code": null, "e": 7541, "s": 7343, "text": "Answer: D. As per the standard naming convention in Oracle, object's name can contain alphabets in any case. Mandatorily, first place is for letters while the rest can be mix of letters and digits." }, { "code": null, "e": 7616, "s": 7541, "text": "14.\tWhich of the following special characters can be used to name a table?" }, { "code": null, "e": 7639, "s": 7616, "text": "\n@\n#\n$\n_ (underscore)\n" }, { "code": null, "e": 7641, "s": 7639, "text": "@" }, { "code": null, "e": 7643, "s": 7641, "text": "#" }, { "code": null, "e": 7645, "s": 7643, "text": "$" }, { "code": null, "e": 7660, "s": 7645, "text": "_ (underscore)" }, { "code": null, "e": 7818, "s": 7660, "text": "Answer: B, C, D. No other special character, except (#, $, _), are allowed while naming a table. Use of special characters in the table name is discouraged." }, { "code": null, "e": 7862, "s": 7818, "text": "15.\tWhat is true about the name of a table?" }, { "code": null, "e": 8113, "s": 7862, "text": "\nA table can have a name which is used by some other object owned by the same user\nA sequence and a table can have same names\nA view and a table can have the same name\nA table name must not duplicate the name of another object owned by the same user\n" }, { "code": null, "e": 8195, "s": 8113, "text": "A table can have a name which is used by some other object owned by the same user" }, { "code": null, "e": 8238, "s": 8195, "text": "A sequence and a table can have same names" }, { "code": null, "e": 8280, "s": 8238, "text": "A view and a table can have the same name" }, { "code": null, "e": 8362, "s": 8280, "text": "A table name must not duplicate the name of another object owned by the same user" }, { "code": null, "e": 8643, "s": 8362, "text": "Answer: D. By virtue of namespace, a table name cannot be same as any other schema objects. Schema objects which share the same namespace include tables, views, sequences, private synonyms, stored procedures, stored functions, packages, materialized views, and user-defined types." }, { "code": null, "e": 8736, "s": 8643, "text": "16.You create a table and name it as COUNT. What will be the outcome of CREATE TABLE script?" }, { "code": null, "e": 8938, "s": 8736, "text": "\nThe table will not be created\nThe table will be created and an underscore will be added automatically to the name COUNT_\nAn ORA error will be thrown\nThe table COUNT will be created without any errors\n" }, { "code": null, "e": 8968, "s": 8938, "text": "The table will not be created" }, { "code": null, "e": 9059, "s": 8968, "text": "The table will be created and an underscore will be added automatically to the name COUNT_" }, { "code": null, "e": 9087, "s": 9059, "text": "An ORA error will be thrown" }, { "code": null, "e": 9138, "s": 9087, "text": "The table COUNT will be created without any errors" }, { "code": null, "e": 9232, "s": 9138, "text": "Answer: A, C. You cannot create a table with the name same as an Oracle Server reserved word." }, { "code": null, "e": 9316, "s": 9232, "text": "17.\tYou create a table using quoted identifiers ' '. How will you refer this table?" }, { "code": null, "e": 9383, "s": 9316, "text": "\n'table_name'\n\n\"table_name\"\n\nEither of A or B\n\nNone of the above\n\n" }, { "code": null, "e": 9397, "s": 9383, "text": "'table_name'\n" }, { "code": null, "e": 9411, "s": 9397, "text": "\"table_name\"\n" }, { "code": null, "e": 9429, "s": 9411, "text": "Either of A or B\n" }, { "code": null, "e": 9448, "s": 9429, "text": "None of the above\n" }, { "code": null, "e": 9650, "s": 9448, "text": "Answer: B. If the table is created with the name having a quoted identifier, it must be addressed using double quotes. Using quoted identifiers is not recommended. Quoted identifiers are case-sensitive" }, { "code": null, "e": 9728, "s": 9650, "text": "18.\tYou create a table named EMPLOYEES. What among the following is possible?" }, { "code": null, "e": 9852, "s": 9728, "text": "\nIt can be referred to as eMPLOYEES\nIt can be referred to as EMPLoyees\nIt can be referred to as employees\nAll of the above\n" }, { "code": null, "e": 9887, "s": 9852, "text": "It can be referred to as eMPLOYEES" }, { "code": null, "e": 9922, "s": 9887, "text": "It can be referred to as EMPLoyees" }, { "code": null, "e": 9957, "s": 9922, "text": "It can be referred to as employees" }, { "code": null, "e": 9974, "s": 9957, "text": "All of the above" }, { "code": null, "e": 10041, "s": 9974, "text": "Answer: D. Unquoted objects names are not case-senstive in Oracle." }, { "code": null, "e": 10115, "s": 10041, "text": "19.\tWhat among the following are the pre-requisites for creating a table?" }, { "code": null, "e": 10194, "s": 10115, "text": "\nCREATE TABLE privilege\n\nStorage space\n\nData in the table\n\nNone of the above\n\n" }, { "code": null, "e": 10218, "s": 10194, "text": "CREATE TABLE privilege\n" }, { "code": null, "e": 10233, "s": 10218, "text": "Storage space\n" }, { "code": null, "e": 10252, "s": 10233, "text": "Data in the table\n" }, { "code": null, "e": 10271, "s": 10252, "text": "None of the above\n" }, { "code": null, "e": 10416, "s": 10271, "text": "Answer: A, B. A user must possess the CREATE TABLE privilege and must have sufficient space to allocate the initial extent to the table segment." }, { "code": null, "e": 10461, "s": 10416, "text": "20.\tWhat is the syntax for creating a table?" }, { "code": null, "e": 10711, "s": 10461, "text": "\nCREATE TABLE [schema.] table (column datatype [DEFAULT expr] [,..] ); \n\nCREATE TABLE INTO [schema.] table (column datatype [DEFAULT expr] [,..] ); \n\nCREATE TABLE VALUES [schema.] table (column datatype [DEFAULT expr] [,..] ); \n\nNone of the above\n\n" }, { "code": null, "e": 10783, "s": 10711, "text": "CREATE TABLE [schema.] table (column datatype [DEFAULT expr] [,..] ); \n" }, { "code": null, "e": 10860, "s": 10783, "text": "CREATE TABLE INTO [schema.] table (column datatype [DEFAULT expr] [,..] ); \n" }, { "code": null, "e": 10940, "s": 10860, "text": "CREATE TABLE VALUES [schema.] table (column datatype [DEFAULT expr] [,..] ); \n" }, { "code": null, "e": 10959, "s": 10940, "text": "None of the above\n" }, { "code": null, "e": 10971, "s": 10959, "text": "Answer: A. " }, { "code": null, "e": 11039, "s": 10971, "text": "21.\tPick the element which you must specify while creating a table." }, { "code": null, "e": 11099, "s": 11039, "text": "\nColumn name\nColumn Data type\nColumn size\nAll of the above\n" }, { "code": null, "e": 11111, "s": 11099, "text": "Column name" }, { "code": null, "e": 11128, "s": 11111, "text": "Column Data type" }, { "code": null, "e": 11140, "s": 11128, "text": "Column size" }, { "code": null, "e": 11157, "s": 11140, "text": "All of the above" }, { "code": null, "e": 11264, "s": 11157, "text": "Answer: D. A table must have atleasr one column, its data type specification, and precision (if required)." }, { "code": null, "e": 11406, "s": 11264, "text": "22.\tA user named \"Kevin\" wants to access a table which is owned by another user named \"Jonathan\". Which of the following will work for Kevin?" }, { "code": null, "e": 11509, "s": 11406, "text": "\nSelect * from Kevin.employees; \nSelect * from jonathan.employees;\nEither of A or B\nNone of the above\n" }, { "code": null, "e": 11541, "s": 11509, "text": "Select * from Kevin.employees; " }, { "code": null, "e": 11575, "s": 11541, "text": "Select * from jonathan.employees;" }, { "code": null, "e": 11592, "s": 11575, "text": "Either of A or B" }, { "code": null, "e": 11610, "s": 11592, "text": "None of the above" }, { "code": null, "e": 11622, "s": 11610, "text": "Answer: B. " }, { "code": null, "e": 11655, "s": 11622, "text": "23.\tWhat is true about a schema?" }, { "code": null, "e": 11815, "s": 11655, "text": "\nA schema is owned by a database user and has the same name as that user\nEach user owns a single schema\nSchema objects include database links\nAll of the above\n" }, { "code": null, "e": 11887, "s": 11815, "text": "A schema is owned by a database user and has the same name as that user" }, { "code": null, "e": 11918, "s": 11887, "text": "Each user owns a single schema" }, { "code": null, "e": 11956, "s": 11918, "text": "Schema objects include database links" }, { "code": null, "e": 11973, "s": 11956, "text": "All of the above" }, { "code": null, "e": 12149, "s": 11973, "text": "Answer: D. The user space in a database is known as schema. A schema contains the objects which are owned or accessed by the user. Each user can have single schema of its own." }, { "code": null, "e": 12200, "s": 12149, "text": "24.\tWhat among the following is true about tables?" }, { "code": null, "e": 12352, "s": 12200, "text": "\nA default value is given to a table\nA default value can be given to a column of a table during an INSERT statement\nEither of A or B\nNone of the above\n" }, { "code": null, "e": 12388, "s": 12352, "text": "A default value is given to a table" }, { "code": null, "e": 12467, "s": 12388, "text": "A default value can be given to a column of a table during an INSERT statement" }, { "code": null, "e": 12484, "s": 12467, "text": "Either of A or B" }, { "code": null, "e": 12502, "s": 12484, "text": "None of the above" }, { "code": null, "e": 12608, "s": 12502, "text": "Answer: B. A default value can be specified for a column during the definition using the keyword DEFAULT." }, { "code": null, "e": 12695, "s": 12608, "text": "25.\tWhich of the following can be used with the DEFAULT option while creating a table?" }, { "code": null, "e": 12748, "s": 12695, "text": "\nStrings\nExpressions\nSQL functions\nAll of the above\n" }, { "code": null, "e": 12756, "s": 12748, "text": "Strings" }, { "code": null, "e": 12768, "s": 12756, "text": "Expressions" }, { "code": null, "e": 12782, "s": 12768, "text": "SQL functions" }, { "code": null, "e": 12799, "s": 12782, "text": "All of the above" }, { "code": null, "e": 12901, "s": 12799, "text": "Answer: D. The default value for a column can either be a literal or a derivative using SQL function." }, { "code": null, "e": 12977, "s": 12901, "text": "26.\tWhich of the following command is used to see the structure of a table?" }, { "code": null, "e": 13006, "s": 12977, "text": "\nUPDATE\nSHOW\nDESCRIBE\nSPOOL\n" }, { "code": null, "e": 13013, "s": 13006, "text": "UPDATE" }, { "code": null, "e": 13018, "s": 13013, "text": "SHOW" }, { "code": null, "e": 13027, "s": 13018, "text": "DESCRIBE" }, { "code": null, "e": 13033, "s": 13027, "text": "SPOOL" }, { "code": null, "e": 13111, "s": 13033, "text": "Answer: C. DESCRIBE is a SQL*Plus command to list the structure of the table." }, { "code": null, "e": 13166, "s": 13111, "text": "27.What is the limit of CHECK constraints on a column?" }, { "code": null, "e": 13183, "s": 13166, "text": "\nNo limit\n1\n2\n4\n" }, { "code": null, "e": 13192, "s": 13183, "text": "No limit" }, { "code": null, "e": 13194, "s": 13192, "text": "1" }, { "code": null, "e": 13196, "s": 13194, "text": "2" }, { "code": null, "e": 13198, "s": 13196, "text": "4" }, { "code": null, "e": 13271, "s": 13198, "text": "Answer: A. Oracle imposes no limit on the check constraints on a column." }, { "code": null, "e": 13374, "s": 13271, "text": "28.\tWhich of the following commands will drop table employees? (Consider the table structure as given)" }, { "code": null, "e": 13800, "s": 13374, "text": "SQL> DESC employees\n Name\t\t\t Null?\t Type\n ----------------------- -------- ----------------\n EMPLOYEE_ID\t\t NOT NULL NUMBER(6)\n FIRST_NAME\t\t\t VARCHAR2(20)\n LAST_NAME\t\t NOT NULL VARCHAR2(25)\n EMAIL\t\t\t NOT NULL VARCHAR2(25)\n PHONE_NUMBER\t\t\t VARCHAR2(20)\n HIRE_DATE\t\t NOT NULL DATE\n JOB_ID \t\t NOT NULL VARCHAR2(10)\n SALARY \t\t\t NUMBER(8,2)\n COMMISSION_PCT \t\t NUMBER(2,2)\n MANAGER_ID\t\t\t NUMBER(6)\n DEPARTMENT_ID\t\t\t NUMBER(4)" }, { "code": null, "e": 13875, "s": 13800, "text": "\nDROP employees\nDROP TABLE employees\nTRUNCATE employees\nNone of the above\n" }, { "code": null, "e": 13890, "s": 13875, "text": "DROP employees" }, { "code": null, "e": 13905, "s": 13890, "text": "DROP employees" }, { "code": null, "e": 13926, "s": 13905, "text": "DROP TABLE employees" }, { "code": null, "e": 13947, "s": 13926, "text": "DROP TABLE employees" }, { "code": null, "e": 13966, "s": 13947, "text": "TRUNCATE employees" }, { "code": null, "e": 13985, "s": 13966, "text": "TRUNCATE employees" }, { "code": null, "e": 14003, "s": 13985, "text": "None of the above" }, { "code": null, "e": 14015, "s": 14003, "text": "Answer: B. " }, { "code": null, "e": 14052, "s": 14015, "text": " 29.\tWhat is true about a namespace?" }, { "code": null, "e": 14264, "s": 14052, "text": "\nIt is a group of object types\nWithin a namespace, all the object names should be uniquely identified by schema and name\nThe same type of objects in different namespaces can share the same name\nAll of the above\n" }, { "code": null, "e": 14294, "s": 14264, "text": "It is a group of object types" }, { "code": null, "e": 14384, "s": 14294, "text": "Within a namespace, all the object names should be uniquely identified by schema and name" }, { "code": null, "e": 14457, "s": 14384, "text": "The same type of objects in different namespaces can share the same name" }, { "code": null, "e": 14474, "s": 14457, "text": "All of the above" }, { "code": null, "e": 14656, "s": 14474, "text": "Answer: D. A namespace defines a group of object types,within which all names must be uniquely identified-by schema and name.Objects in different namespaces can share the same name." }, { "code": null, "e": 14723, "s": 14656, "text": " 30.\tWhich of the following object types share the same namespace?" }, { "code": null, "e": 14763, "s": 14723, "text": "\nSynonyms\nTable\nViews\nAll of the above\n" }, { "code": null, "e": 14772, "s": 14763, "text": "Synonyms" }, { "code": null, "e": 14778, "s": 14772, "text": "Table" }, { "code": null, "e": 14784, "s": 14778, "text": "Views" }, { "code": null, "e": 14801, "s": 14784, "text": "All of the above" }, { "code": null, "e": 14813, "s": 14801, "text": "Answer: D. " }, { "code": null, "e": 14879, "s": 14813, "text": " 31.\tWhat among the following is true about a table and an index?" }, { "code": null, "e": 15037, "s": 14879, "text": "\nAn index and a table can have the same name in a schema\nAn index and a table within a schema cannot have the same name\nNeither of A nor B\nNone of the above\n" }, { "code": null, "e": 15093, "s": 15037, "text": "An index and a table can have the same name in a schema" }, { "code": null, "e": 15156, "s": 15093, "text": "An index and a table within a schema cannot have the same name" }, { "code": null, "e": 15175, "s": 15156, "text": "Neither of A nor B" }, { "code": null, "e": 15193, "s": 15175, "text": "None of the above" }, { "code": null, "e": 15304, "s": 15193, "text": "Answer: A. As the index and constraints share the same namespace, a table and an index can have the same name." }, { "code": null, "e": 15346, "s": 15304, "text": " 32.\tWhat is true about creating a table?" }, { "code": null, "e": 15544, "s": 15346, "text": "\nWhile creating a table, each column should be assigned a data type\nData type assignment to columns is not mandatory\nA data type has to be assigned to a table and not to a column\nNone of the above\n" }, { "code": null, "e": 15611, "s": 15544, "text": "While creating a table, each column should be assigned a data type" }, { "code": null, "e": 15660, "s": 15611, "text": "Data type assignment to columns is not mandatory" }, { "code": null, "e": 15722, "s": 15660, "text": "A data type has to be assigned to a table and not to a column" }, { "code": null, "e": 15740, "s": 15722, "text": "None of the above" }, { "code": null, "e": 15874, "s": 15740, "text": "Answer: A. Each column must possess behavioral attributes like data types and precision in order to build the structure of the table." }, { "code": null, "e": 15922, "s": 15874, "text": " 33.\tSuppose you create a table as shown below:" }, { "code": null, "e": 15991, "s": 15922, "text": "CREATE TABLE employees\n(emp_id NUMBER(4),\nlast_name VARCHAR2 (20)\n);" }, { "code": null, "e": 16052, "s": 15991, "text": "How much space will Oracle allocate to the LAST_NAME column?" }, { "code": null, "e": 16277, "s": 16052, "text": "\nIf there are no rows, then Oracle will not allocate any space to the last_name column\n\nIf rows are populated then Oracle will allocate unlimited space to the last_name column\n\nNeither of A nor B\n\nNone of the above options\n\n" }, { "code": null, "e": 16364, "s": 16277, "text": "If there are no rows, then Oracle will not allocate any space to the last_name column\n" }, { "code": null, "e": 16453, "s": 16364, "text": "If rows are populated then Oracle will allocate unlimited space to the last_name column\n" }, { "code": null, "e": 16473, "s": 16453, "text": "Neither of A nor B\n" }, { "code": null, "e": 16500, "s": 16473, "text": "None of the above options\n" }, { "code": null, "e": 16512, "s": 16500, "text": "Answer: A. " }, { "code": null, "e": 16579, "s": 16512, "text": " 34.\tWhat is the range of size that a VARCHAR2 data type can take?" }, { "code": null, "e": 16658, "s": 16579, "text": "\n1 byte to 2 byte\n1 byte to 2000 bytes\n1 byte to 4000 bytes\nNone of the above\n" }, { "code": null, "e": 16675, "s": 16658, "text": "1 byte to 2 byte" }, { "code": null, "e": 16696, "s": 16675, "text": "1 byte to 2000 bytes" }, { "code": null, "e": 16717, "s": 16696, "text": "1 byte to 4000 bytes" }, { "code": null, "e": 16735, "s": 16717, "text": "None of the above" }, { "code": null, "e": 16832, "s": 16735, "text": "Answer: C. Until Oracle 11g Release 2, string data type VARCHAR2 can maximum contain 4000 bytes." }, { "code": null, "e": 16893, "s": 16832, "text": "35.What is the range of size that a CHAR data type can take?" }, { "code": null, "e": 16975, "s": 16893, "text": "\n1 byte to 2 byte\n1 byte to 2000 bytes\n1 byte to 4000 bytes\n1 byte to 3000 bytes\n" }, { "code": null, "e": 16992, "s": 16975, "text": "1 byte to 2 byte" }, { "code": null, "e": 17013, "s": 16992, "text": "1 byte to 2000 bytes" }, { "code": null, "e": 17034, "s": 17013, "text": "1 byte to 4000 bytes" }, { "code": null, "e": 17055, "s": 17034, "text": "1 byte to 3000 bytes" }, { "code": null, "e": 17148, "s": 17055, "text": "Answer: B. Until Oracle 11g Release 2, string data type CHAR can maximum contain 2000 bytes." }, { "code": null, "e": 17192, "s": 17148, "text": " 36.\tWhat is true about the CHAR data type?" }, { "code": null, "e": 17488, "s": 17192, "text": "\nIf the data is not the length of the column, then it will be replaced with NULL values\nIf the data is not the length of the column, then it will be padded with spaces\nIt is mandatory to have the data of the same size as mentioned in the CHAR size, else it throws an ORA error\nNone of the above\n" }, { "code": null, "e": 17575, "s": 17488, "text": "If the data is not the length of the column, then it will be replaced with NULL values" }, { "code": null, "e": 17655, "s": 17575, "text": "If the data is not the length of the column, then it will be padded with spaces" }, { "code": null, "e": 17764, "s": 17655, "text": "It is mandatory to have the data of the same size as mentioned in the CHAR size, else it throws an ORA error" }, { "code": null, "e": 17782, "s": 17764, "text": "None of the above" }, { "code": null, "e": 18004, "s": 17782, "text": "Answer: B. CHAR provides a fixed length storage to a value while VARCHAR2 is flexible. If the data of length less than CHAR precision is inserted in a CHAR column, the remaining length will be padded to the column value. " }, { "code": null, "e": 18080, "s": 18004, "text": " 37.\tWhich of the following is a data type for variable length binary data?" }, { "code": null, "e": 18113, "s": 18080, "text": "\nVARCHAR\nVARCHAR2\nRAW\nNVARCHAR2\n" }, { "code": null, "e": 18121, "s": 18113, "text": "VARCHAR" }, { "code": null, "e": 18130, "s": 18121, "text": "VARCHAR2" }, { "code": null, "e": 18134, "s": 18130, "text": "RAW" }, { "code": null, "e": 18144, "s": 18134, "text": "NVARCHAR2" }, { "code": null, "e": 18156, "s": 18144, "text": "Answer: C. " }, { "code": null, "e": 18217, "s": 18156, "text": " 38.\tWhat is the precision allowed for the NUMBER data type?" }, { "code": null, "e": 18258, "s": 18217, "text": "\n1 to 20\n1 to 4K\n1 to 30\n1 to 38 digits\n" }, { "code": null, "e": 18266, "s": 18258, "text": "1 to 20" }, { "code": null, "e": 18274, "s": 18266, "text": "1 to 4K" }, { "code": null, "e": 18282, "s": 18274, "text": "1 to 30" }, { "code": null, "e": 18297, "s": 18282, "text": "1 to 38 digits" }, { "code": null, "e": 18401, "s": 18297, "text": "Answer: D. Until Oracle 11g Release 2, primary data type NUMBER had the maximum precision of 38 digits." }, { "code": null, "e": 18458, "s": 18401, "text": " 39.\tWhat is the scale allowed for the NUMBER data type?" }, { "code": null, "e": 18512, "s": 18458, "text": "\n1 to 20\n\n-84 to 100\n\n-84 to 127\n\nNone of the above\n\n" }, { "code": null, "e": 18521, "s": 18512, "text": "1 to 20\n" }, { "code": null, "e": 18533, "s": 18521, "text": "-84 to 100\n" }, { "code": null, "e": 18545, "s": 18533, "text": "-84 to 127\n" }, { "code": null, "e": 18564, "s": 18545, "text": "None of the above\n" }, { "code": null, "e": 18576, "s": 18564, "text": "Answer: C. " }, { "code": null, "e": 18647, "s": 18576, "text": " 40.\tWhich of the following are the data types for date and time data?" }, { "code": null, "e": 18733, "s": 18647, "text": "\nTIMESTAMP\n\nINTERVAL DAY TO SECOND\n\nTIMESTAMP WITH LOCAL TIMEZONE\n\nAll of the above\n\n" }, { "code": null, "e": 18744, "s": 18733, "text": "TIMESTAMP\n" }, { "code": null, "e": 18768, "s": 18744, "text": "INTERVAL DAY TO SECOND\n" }, { "code": null, "e": 18799, "s": 18768, "text": "TIMESTAMP WITH LOCAL TIMEZONE\n" }, { "code": null, "e": 18817, "s": 18799, "text": "All of the above\n" }, { "code": null, "e": 18829, "s": 18817, "text": "Answer: D. " }, { "code": null, "e": 18891, "s": 18829, "text": " 41.\tWhich of the following data types are for large objects?" }, { "code": null, "e": 18924, "s": 18891, "text": "\nCLOB\nBLOB\nRAW\nAll of the above\n" }, { "code": null, "e": 18929, "s": 18924, "text": "CLOB" }, { "code": null, "e": 18934, "s": 18929, "text": "BLOB" }, { "code": null, "e": 18938, "s": 18934, "text": "RAW" }, { "code": null, "e": 18955, "s": 18938, "text": "All of the above" }, { "code": null, "e": 19018, "s": 18955, "text": "Answer: A, B. LOB data types in SQL are BLOB, CLOB, and BFILE." }, { "code": null, "e": 19129, "s": 19018, "text": " 42.\tWhat will happen if the inserted value is of a smaller length as defined for a VARCHAR2 data type column?" }, { "code": null, "e": 19336, "s": 19129, "text": "\nIt will throw an ORA error\nIt will get inserted successfully and the value will take up as much space as it needs.\nIt will get inserted and the remaining space will be padded with spaces\nNone of the above\n" }, { "code": null, "e": 19363, "s": 19336, "text": "It will throw an ORA error" }, { "code": null, "e": 19451, "s": 19363, "text": "It will get inserted successfully and the value will take up as much space as it needs." }, { "code": null, "e": 19523, "s": 19451, "text": "It will get inserted and the remaining space will be padded with spaces" }, { "code": null, "e": 19541, "s": 19523, "text": "None of the above" }, { "code": null, "e": 19602, "s": 19541, "text": "Answer: B. VARCHAR2 contains variable length character data." }, { "code": null, "e": 19647, "s": 19602, "text": " 43.\tWhat does NUMBER (8, 2) in oracle mean?" }, { "code": null, "e": 19926, "s": 19647, "text": "\nIt means there are 8 digits in total, 6 digits before the decimal and 2 after the decimal\nIt means there are 10 digits in total with 8 digits before the decimal and 2 after decimal\nIt means there are 2 digits before the decimal and 8 after the decimal point\nNone of the above\n\n" }, { "code": null, "e": 20016, "s": 19926, "text": "It means there are 8 digits in total, 6 digits before the decimal and 2 after the decimal" }, { "code": null, "e": 20107, "s": 20016, "text": "It means there are 10 digits in total with 8 digits before the decimal and 2 after decimal" }, { "code": null, "e": 20184, "s": 20107, "text": "It means there are 2 digits before the decimal and 8 after the decimal point" }, { "code": null, "e": 20203, "s": 20184, "text": "None of the above\n" }, { "code": null, "e": 20572, "s": 20203, "text": "Answer: A. The p indicates precision,the total number of digits to the left and right of the decimal position, to a maximum of 38 digits; the s, or scale, indicates the number of positions to the right of the decimal.Example: NUMBER(7, 2) can store a numeric value up to 99999.99. If precision or scale isn't specified, the column defaults to a precision of 38 digits." }, { "code": null, "e": 20648, "s": 20572, "text": " 44.\tWhich of the following queries will create a table with no rows in it?" }, { "code": null, "e": 20845, "s": 20648, "text": "\nCREATE TABLE emp AS SELECT 0 from dual;\nCREATE TABLE emp AS SELECT * from employees where 1=1;\nCREATE TABLE emp AS SELECT * from employees where 1=2;\nCREATE TABLE emp AS SELECT 0 from employees;\n" }, { "code": null, "e": 20885, "s": 20845, "text": "CREATE TABLE emp AS SELECT 0 from dual;" }, { "code": null, "e": 20925, "s": 20885, "text": "CREATE TABLE emp AS SELECT 0 from dual;" }, { "code": null, "e": 20980, "s": 20925, "text": "CREATE TABLE emp AS SELECT * from employees where 1=1;" }, { "code": null, "e": 21035, "s": 20980, "text": "CREATE TABLE emp AS SELECT * from employees where 1=1;" }, { "code": null, "e": 21090, "s": 21035, "text": "CREATE TABLE emp AS SELECT * from employees where 1=2;" }, { "code": null, "e": 21145, "s": 21090, "text": "CREATE TABLE emp AS SELECT * from employees where 1=2;" }, { "code": null, "e": 21190, "s": 21145, "text": "CREATE TABLE emp AS SELECT 0 from employees;" }, { "code": null, "e": 21235, "s": 21190, "text": "CREATE TABLE emp AS SELECT 0 from employees;" }, { "code": null, "e": 21388, "s": 21235, "text": "Answer: C. The direct path operation CTAS (CREATE TABLE .. AS SELECT..) can be used to copy the structure of an existing table without copying the data." }, { "code": null, "e": 21474, "s": 21388, "text": " 45.\tWhich of the following statements would add a column to a table already created?" }, { "code": null, "e": 21663, "s": 21474, "text": "\nALTER TABLE table_name add column (job varchar2(20));\nALTER TABLE table_name add job varchar2(20);\nALTER TABLE table_name add (job varchar2(20));\nALTER TABLE table_name add column (job);\n" }, { "code": null, "e": 21717, "s": 21663, "text": "ALTER TABLE table_name add column (job varchar2(20));" }, { "code": null, "e": 21771, "s": 21717, "text": "ALTER TABLE table_name add column (job varchar2(20));" }, { "code": null, "e": 21816, "s": 21771, "text": "ALTER TABLE table_name add job varchar2(20);" }, { "code": null, "e": 21861, "s": 21816, "text": "ALTER TABLE table_name add job varchar2(20);" }, { "code": null, "e": 21908, "s": 21861, "text": "ALTER TABLE table_name add (job varchar2(20));" }, { "code": null, "e": 21955, "s": 21908, "text": "ALTER TABLE table_name add (job varchar2(20));" }, { "code": null, "e": 21996, "s": 21955, "text": "ALTER TABLE table_name add column (job);" }, { "code": null, "e": 22037, "s": 21996, "text": "ALTER TABLE table_name add column (job);" }, { "code": null, "e": 22449, "s": 22037, "text": "Answer: C. The ALTER TABLE command allows a user to add a new column to a table.The same rules for creating a column in a new table apply to adding a column to an existing table.The new column must be defined by a column name and datatype (and width, if applicable).A default value can also be assigned. The difference is that the new column is added at the end of the existing table-it will be the last column." }, { "code": null, "e": 22545, "s": 22449, "text": " 46.\tWhich of the following statements will modify the data type of an already existing column?" }, { "code": null, "e": 22755, "s": 22545, "text": "\nALTER TABLE table_name MODIFY (job varchar2(10) );\nALTER TABLE table_name MODIFY job varchar2(10);\nALTER TABLE table_name MODIFY column (job varchar2(10) );\nALTER TABLE table_name MODIFY (job varchar2(10) );\n" }, { "code": null, "e": 22806, "s": 22755, "text": "ALTER TABLE table_name MODIFY (job varchar2(10) );" }, { "code": null, "e": 22857, "s": 22806, "text": "ALTER TABLE table_name MODIFY (job varchar2(10) );" }, { "code": null, "e": 22905, "s": 22857, "text": "ALTER TABLE table_name MODIFY job varchar2(10);" }, { "code": null, "e": 22953, "s": 22905, "text": "ALTER TABLE table_name MODIFY job varchar2(10);" }, { "code": null, "e": 23011, "s": 22953, "text": "ALTER TABLE table_name MODIFY column (job varchar2(10) );" }, { "code": null, "e": 23069, "s": 23011, "text": "ALTER TABLE table_name MODIFY column (job varchar2(10) );" }, { "code": null, "e": 23120, "s": 23069, "text": "ALTER TABLE table_name MODIFY (job varchar2(10) );" }, { "code": null, "e": 23171, "s": 23120, "text": "ALTER TABLE table_name MODIFY (job varchar2(10) );" }, { "code": null, "e": 23395, "s": 23171, "text": "Answer: A. The ALTER TABLE..MODIFY is used to modify column definition in a table. The admissible changes are increasing column precision, change datatype within a datatype family, or change the default value of the column." }, { "code": null, "e": 23471, "s": 23395, "text": " 47.\tWhich of the following statements will remove a column from the table?" }, { "code": null, "e": 23684, "s": 23471, "text": "\n ALTER TABLE table_name DROP (job varchar2(10) );\nALTER TABLE table table_name DROP COLUMN (job varchar2(10) );\nALTER TABLE table table_name DROP COLUMN (job);\nALTER TABLE table_name MODIFY (job varchar2(10) );\n" }, { "code": null, "e": 23734, "s": 23684, "text": " ALTER TABLE table_name DROP (job varchar2(10) );" }, { "code": null, "e": 23784, "s": 23734, "text": " ALTER TABLE table_name DROP (job varchar2(10) );" }, { "code": null, "e": 23846, "s": 23784, "text": "ALTER TABLE table table_name DROP COLUMN (job varchar2(10) );" }, { "code": null, "e": 23908, "s": 23846, "text": "ALTER TABLE table table_name DROP COLUMN (job varchar2(10) );" }, { "code": null, "e": 23956, "s": 23908, "text": "ALTER TABLE table table_name DROP COLUMN (job);" }, { "code": null, "e": 24004, "s": 23956, "text": "ALTER TABLE table table_name DROP COLUMN (job);" }, { "code": null, "e": 24055, "s": 24004, "text": "ALTER TABLE table_name MODIFY (job varchar2(10) );" }, { "code": null, "e": 24106, "s": 24055, "text": "ALTER TABLE table_name MODIFY (job varchar2(10) );" }, { "code": null, "e": 24191, "s": 24106, "text": "Answer: C. The ALTER TABLE..DROP COLUMN can be used to drop a column from the table." }, { "code": null, "e": 24260, "s": 24191, "text": " 48.\tWhich of the following will rename the column emp_id to empno?" }, { "code": null, "e": 24433, "s": 24260, "text": "\nALTER TABLE employees RENAME column emp_id to empno;\nALTER TABLE employees RENAME emp_id to empno;\nALTER TABLE employees RENAME column emp_id to empno;\nNone of the above;\n" }, { "code": null, "e": 24486, "s": 24433, "text": "ALTER TABLE employees RENAME column emp_id to empno;" }, { "code": null, "e": 24539, "s": 24486, "text": "ALTER TABLE employees RENAME column emp_id to empno;" }, { "code": null, "e": 24585, "s": 24539, "text": "ALTER TABLE employees RENAME emp_id to empno;" }, { "code": null, "e": 24631, "s": 24585, "text": "ALTER TABLE employees RENAME emp_id to empno;" }, { "code": null, "e": 24684, "s": 24631, "text": "ALTER TABLE employees RENAME column emp_id to empno;" }, { "code": null, "e": 24737, "s": 24684, "text": "ALTER TABLE employees RENAME column emp_id to empno;" }, { "code": null, "e": 24756, "s": 24737, "text": "None of the above;" }, { "code": null, "e": 24846, "s": 24756, "text": "Answer: A. The ALTER TABLE..RENAME can be used to rename an existing column in teh table." }, { "code": null, "e": 24981, "s": 24846, "text": " 49.\tYou need to mark the table employees as read only. Which of the following statements will you execute to get the required result?" }, { "code": null, "e": 25118, "s": 24981, "text": "\nALTER TABLE employees set READ;\nALTER TABLE employees READ ONLY;\nALTER TABLE employees READ_ONLY;\nALTER TABLE employees set READ ONLY;\n" }, { "code": null, "e": 25150, "s": 25118, "text": "ALTER TABLE employees set READ;" }, { "code": null, "e": 25182, "s": 25150, "text": "ALTER TABLE employees set READ;" }, { "code": null, "e": 25215, "s": 25182, "text": "ALTER TABLE employees READ ONLY;" }, { "code": null, "e": 25248, "s": 25215, "text": "ALTER TABLE employees READ ONLY;" }, { "code": null, "e": 25281, "s": 25248, "text": "ALTER TABLE employees READ_ONLY;" }, { "code": null, "e": 25314, "s": 25281, "text": "ALTER TABLE employees READ_ONLY;" }, { "code": null, "e": 25351, "s": 25314, "text": "ALTER TABLE employees set READ ONLY;" }, { "code": null, "e": 25388, "s": 25351, "text": "ALTER TABLE employees set READ ONLY;" }, { "code": null, "e": 25538, "s": 25388, "text": "Answer: B. A table can be marked read only to make it passive against the DML and DDL statements. The read only feature was introduced in Oracle 11g." }, { "code": null, "e": 25598, "s": 25538, "text": " 50.\tWhat among the following is true about DDL statements?" }, { "code": null, "e": 25854, "s": 25598, "text": "\nDDL commands become the part of ongoing transaction\nDDL commands are auto commit and end the ongoing active transaction\nIf the DDL command fails, the current transaction is still committed\nIf the DDL command fails, the current transaction is rolled back\n" }, { "code": null, "e": 25906, "s": 25854, "text": "DDL commands become the part of ongoing transaction" }, { "code": null, "e": 25974, "s": 25906, "text": "DDL commands are auto commit and end the ongoing active transaction" }, { "code": null, "e": 26043, "s": 25974, "text": "If the DDL command fails, the current transaction is still committed" }, { "code": null, "e": 26108, "s": 26043, "text": "If the DDL command fails, the current transaction is rolled back" }, { "code": null, "e": 26317, "s": 26108, "text": "Answer: B. DDL commands are auto commit only if they are successfully executed without errors. If DDL command fails, the ongoing transaction is still active in the session and not committed into the database." }, { "code": null, "e": 26411, "s": 26317, "text": " 51.\tWhat happens if there is an active transaction against a table on which a DDL is issued?" }, { "code": null, "e": 26515, "s": 26411, "text": "\nThe transaction rolls back\nThe transaction is committed and terminated\nBoth A and B\nNone of the above\n" }, { "code": null, "e": 26542, "s": 26515, "text": "The transaction rolls back" }, { "code": null, "e": 26586, "s": 26542, "text": "The transaction is committed and terminated" }, { "code": null, "e": 26599, "s": 26586, "text": "Both A and B" }, { "code": null, "e": 26617, "s": 26599, "text": "None of the above" }, { "code": null, "e": 26629, "s": 26617, "text": "Answer: B. " }, { "code": null, "e": 26714, "s": 26629, "text": " 52.\tWhich of the following commands will remove unused columns in an SQL statement?" }, { "code": null, "e": 26883, "s": 26714, "text": "\nALTER TABLE tablename DROP COLUMN column_name;\nALTER TABLE tablename DROP unused columns;\nALTER TABLE tablename set unused column;\nALTER TABLE tablename DROP columns;\n" }, { "code": null, "e": 26930, "s": 26883, "text": "ALTER TABLE tablename DROP COLUMN column_name;" }, { "code": null, "e": 26977, "s": 26930, "text": "ALTER TABLE tablename DROP COLUMN column_name;" }, { "code": null, "e": 27020, "s": 26977, "text": "ALTER TABLE tablename DROP unused columns;" }, { "code": null, "e": 27063, "s": 27020, "text": "ALTER TABLE tablename DROP unused columns;" }, { "code": null, "e": 27104, "s": 27063, "text": "ALTER TABLE tablename set unused column;" }, { "code": null, "e": 27145, "s": 27104, "text": "ALTER TABLE tablename set unused column;" }, { "code": null, "e": 27181, "s": 27145, "text": "ALTER TABLE tablename DROP columns;" }, { "code": null, "e": 27217, "s": 27181, "text": "ALTER TABLE tablename DROP columns;" }, { "code": null, "e": 27309, "s": 27217, "text": "Answer: C. The SET UNUSED command drops only the un-used columns from a table and is faster" }, { "code": null, "e": 27389, "s": 27309, "text": " 53.\tWhat happens when a table which is marked Read Only is attempted for drop?" }, { "code": null, "e": 27538, "s": 27389, "text": "\nIt will throw an error\nIt will no longer remain Read Only but cannot be dropped either\nIt will be dropped without errors\nIt will remain un-touched\n" }, { "code": null, "e": 27561, "s": 27538, "text": "It will throw an error" }, { "code": null, "e": 27625, "s": 27561, "text": "It will no longer remain Read Only but cannot be dropped either" }, { "code": null, "e": 27659, "s": 27625, "text": "It will be dropped without errors" }, { "code": null, "e": 27685, "s": 27659, "text": "It will remain un-touched" }, { "code": null, "e": 27821, "s": 27685, "text": "Answer: C. The DROP command affects the data dictionary definition of the tables which are not Read Only and hence dropping is possible" }, { "code": null, "e": 27902, "s": 27821, "text": "Consider the following statement and answer the questions 54 and 55 that follow:" }, { "code": null, "e": 28011, "s": 27902, "text": "CREATE TABLE departments \n(dept_id NUMBER (2),\n dept_name VARCHAR2(14),\n create_date DATE DEFAULT SYSDATE); " }, { "code": null, "e": 28099, "s": 28011, "text": "54.\tWhat will happen if the DEFAULT clause specification is removed from the statement?" }, { "code": null, "e": 28338, "s": 28099, "text": "\nThe script will throw error because DATE columns must be specified with a default value\nA system generated default value will be assigned to the column\nTable will be created with no default value for CREATE_DATE column\nNone of the above\n" }, { "code": null, "e": 28426, "s": 28338, "text": "The script will throw error because DATE columns must be specified with a default value" }, { "code": null, "e": 28490, "s": 28426, "text": "A system generated default value will be assigned to the column" }, { "code": null, "e": 28557, "s": 28490, "text": "Table will be created with no default value for CREATE_DATE column" }, { "code": null, "e": 28575, "s": 28557, "text": "None of the above" }, { "code": null, "e": 28587, "s": 28575, "text": "Answer: C. " }, { "code": null, "e": 28630, "s": 28587, "text": "55.What is true about the above statement?" }, { "code": null, "e": 28808, "s": 28630, "text": "\nIt will automatically commit the transaction in session\nIt will create the table DEPARTMENTS in the schema\nIt will set a default value for CREATE_DATE column\nNone of the above\n" }, { "code": null, "e": 28864, "s": 28808, "text": "It will automatically commit the transaction in session" }, { "code": null, "e": 28915, "s": 28864, "text": "It will create the table DEPARTMENTS in the schema" }, { "code": null, "e": 28966, "s": 28915, "text": "It will set a default value for CREATE_DATE column" }, { "code": null, "e": 28984, "s": 28966, "text": "None of the above" }, { "code": null, "e": 29002, "s": 28984, "text": "Answer: A, B, C. " }, { "code": null, "e": 29065, "s": 29002, "text": "56.\tUp to which limit can a BLOB data type column hold values?" }, { "code": null, "e": 29091, "s": 29065, "text": "\n1 KB\n\n2 GB\n\n4 GB\n\n3 KB\n\n" }, { "code": null, "e": 29097, "s": 29091, "text": "1 KB\n" }, { "code": null, "e": 29103, "s": 29097, "text": "2 GB\n" }, { "code": null, "e": 29109, "s": 29103, "text": "4 GB\n" }, { "code": null, "e": 29115, "s": 29109, "text": "3 KB\n" }, { "code": null, "e": 29204, "s": 29115, "text": "Answer: C. As per Oracle 11g, the maximum size of data accomodated in a BLOB can be 4GB." }, { "code": null, "e": 29301, "s": 29204, "text": "57.What is the difference between CLOB and BLOB data types? (Choose the most appropriate answer)" }, { "code": null, "e": 29497, "s": 29301, "text": "\nCLOB is character data , BLOB is binary data\nCLOB is character data up to 2GB, BLOB is binary data up to 4 GB\nCLOB is character data up to 4 GB, BLOB is binary data up to 4 GB\nNone of the above\n" }, { "code": null, "e": 29542, "s": 29497, "text": "CLOB is character data , BLOB is binary data" }, { "code": null, "e": 29607, "s": 29542, "text": "CLOB is character data up to 2GB, BLOB is binary data up to 4 GB" }, { "code": null, "e": 29673, "s": 29607, "text": "CLOB is character data up to 4 GB, BLOB is binary data up to 4 GB" }, { "code": null, "e": 29691, "s": 29673, "text": "None of the above" }, { "code": null, "e": 29858, "s": 29691, "text": "Answer: C. CLOB is a character large object which is used to store character files like PDF, docs and text files while BLOB is a binary LOB used to store media files." }, { "code": null, "e": 29898, "s": 29858, "text": "58.What among the following is a ROWID?" }, { "code": null, "e": 30048, "s": 29898, "text": "\nIt is a serial number given to a set of rows starting with 1\nIt is an alphanumeric address given to a row in a table\nBoth A and B\nNone of the above\n" }, { "code": null, "e": 30109, "s": 30048, "text": "It is a serial number given to a set of rows starting with 1" }, { "code": null, "e": 30165, "s": 30109, "text": "It is an alphanumeric address given to a row in a table" }, { "code": null, "e": 30178, "s": 30165, "text": "Both A and B" }, { "code": null, "e": 30196, "s": 30178, "text": "None of the above" }, { "code": null, "e": 30285, "s": 30196, "text": "Answer: B. It is a base-64 system representing the unique address of a row in its table." }, { "code": null, "e": 30380, "s": 30285, "text": "59.What is the data type used for storing Binary data stored in an external file (up to 4 GB)?" }, { "code": null, "e": 30404, "s": 30380, "text": "\nBLOB\nCLOB\nCFILE\nBFILE\n" }, { "code": null, "e": 30409, "s": 30404, "text": "BLOB" }, { "code": null, "e": 30414, "s": 30409, "text": "CLOB" }, { "code": null, "e": 30420, "s": 30414, "text": "CFILE" }, { "code": null, "e": 30426, "s": 30420, "text": "BFILE" }, { "code": null, "e": 30637, "s": 30426, "text": "Answer: D. BFILE is an external LOB type which is used to refer external media files. Internal LOB types are BLOB and CLOB which are used for binary large files and character large files stored in the database." }, { "code": null, "e": 30694, "s": 30637, "text": "60.\tWhat is true about a table created with a sub-query?" }, { "code": null, "e": 30948, "s": 30694, "text": "\nA VARCHAR2 data type column is not copied when a table is created using a sub-query\nA CLOB data type column is not copied when a table is created using a sub-query\nA LONG column is not copied when a table is created using a sub-query\nNone of the above\n" }, { "code": null, "e": 31032, "s": 30948, "text": "A VARCHAR2 data type column is not copied when a table is created using a sub-query" }, { "code": null, "e": 31112, "s": 31032, "text": "A CLOB data type column is not copied when a table is created using a sub-query" }, { "code": null, "e": 31182, "s": 31112, "text": "A LONG column is not copied when a table is created using a sub-query" }, { "code": null, "e": 31200, "s": 31182, "text": "None of the above" }, { "code": null, "e": 31277, "s": 31200, "text": "Answer: C. The CTAS method to create a table doesn't copies the LONG column." }, { "code": null, "e": 31370, "s": 31277, "text": "61.\tWhich of the following data types cannot be used with a GROUP BY and an ORDER BY clause?" }, { "code": null, "e": 31396, "s": 31370, "text": "\nCLOB\nVARCHAR2\nCHAR\nLONG\n" }, { "code": null, "e": 31401, "s": 31396, "text": "CLOB" }, { "code": null, "e": 31410, "s": 31401, "text": "VARCHAR2" }, { "code": null, "e": 31415, "s": 31410, "text": "CHAR" }, { "code": null, "e": 31420, "s": 31415, "text": "LONG" }, { "code": null, "e": 31495, "s": 31420, "text": "Answer: D. LONG data types cannot be used in GROUP BY and ORDER BY clause." }, { "code": null, "e": 31542, "s": 31495, "text": "62.\tHow many LONG columns can a table contain?" }, { "code": null, "e": 31582, "s": 31542, "text": "\nNone\n\nMaximum 2\n\nMinimum 2\n\nOnly one\n\n" }, { "code": null, "e": 31588, "s": 31582, "text": "None\n" }, { "code": null, "e": 31599, "s": 31588, "text": "Maximum 2\n" }, { "code": null, "e": 31610, "s": 31599, "text": "Minimum 2\n" }, { "code": null, "e": 31620, "s": 31610, "text": "Only one\n" }, { "code": null, "e": 31684, "s": 31620, "text": "Answer: D. A table can contain maximum one column of LONG type." }, { "code": null, "e": 31751, "s": 31684, "text": "63.Which of the following data types cannot be constrained in SQL?" }, { "code": null, "e": 31777, "s": 31751, "text": "\nVARCHAR2\nLONG\nCHAR\nDATE\n" }, { "code": null, "e": 31786, "s": 31777, "text": "VARCHAR2" }, { "code": null, "e": 31791, "s": 31786, "text": "LONG" }, { "code": null, "e": 31796, "s": 31791, "text": "CHAR" }, { "code": null, "e": 31801, "s": 31796, "text": "DATE" }, { "code": null, "e": 31864, "s": 31801, "text": "Answer: B. Constraints cannot be created on LONG type columns." }, { "code": null, "e": 31958, "s": 31864, "text": "64.\tWhich of the following data types can you use if you want a date with fractional seconds?" }, { "code": null, "e": 32002, "s": 31958, "text": "\nDATE\nVARCHAR2\nTIMESTAMP\nNone of the above\n" }, { "code": null, "e": 32007, "s": 32002, "text": "DATE" }, { "code": null, "e": 32016, "s": 32007, "text": "VARCHAR2" }, { "code": null, "e": 32026, "s": 32016, "text": "TIMESTAMP" }, { "code": null, "e": 32044, "s": 32026, "text": "None of the above" }, { "code": null, "e": 32194, "s": 32044, "text": "Answer: C. The TIMESTAMP data type provides additional precised information of date values. It provides fractional seconds and time zone information." }, { "code": null, "e": 32312, "s": 32194, "text": "65.\tYou need to store an interval of days, hours, minutes and seconds in a column. Which of the data type would help?" }, { "code": null, "e": 32388, "s": 32312, "text": "\nTIMESTAMP\nINTERVAL YEAR TO MONTH\nINTERVAL DAY TO SECOND\nNone of the above\n" }, { "code": null, "e": 32398, "s": 32388, "text": "TIMESTAMP" }, { "code": null, "e": 32421, "s": 32398, "text": "INTERVAL YEAR TO MONTH" }, { "code": null, "e": 32444, "s": 32421, "text": "INTERVAL DAY TO SECOND" }, { "code": null, "e": 32462, "s": 32444, "text": "None of the above" }, { "code": null, "e": 32474, "s": 32462, "text": "Answer: C. " }, { "code": null, "e": 32599, "s": 32474, "text": "66.You need to find how many employees were hired in June, 2011 and June, 2012. Which of the following data types will help?" }, { "code": null, "e": 32663, "s": 32599, "text": "\nINTERVAL DAY TO SECOND\nTIMESTAMP\nDATE\nINTERVAL YEAR TO MONTH \n" }, { "code": null, "e": 32686, "s": 32663, "text": "INTERVAL DAY TO SECOND" }, { "code": null, "e": 32696, "s": 32686, "text": "TIMESTAMP" }, { "code": null, "e": 32701, "s": 32696, "text": "DATE" }, { "code": null, "e": 32725, "s": 32701, "text": "INTERVAL YEAR TO MONTH " }, { "code": null, "e": 32737, "s": 32725, "text": "Answer: D. " }, { "code": null, "e": 32773, "s": 32737, "text": "67.\tWhat is true about constraints?" }, { "code": null, "e": 32934, "s": 32773, "text": "\nThey enforce rules at the row level\nThey enforce rules at the table level\nIt is mandatory to have constraints created while creating a table\nNone of the above\n" }, { "code": null, "e": 32970, "s": 32934, "text": "They enforce rules at the row level" }, { "code": null, "e": 33008, "s": 32970, "text": "They enforce rules at the table level" }, { "code": null, "e": 33075, "s": 33008, "text": "It is mandatory to have constraints created while creating a table" }, { "code": null, "e": 33093, "s": 33075, "text": "None of the above" }, { "code": null, "e": 33537, "s": 33093, "text": "Answer: B. A constraint is a rule applied to data being added to a table. It represents business rules, policies, or procedures.Data violating the constraint isn't added to the table.A constraint can be included during table creation as part of the CREATE TABLE command or added to an existing table with the ALTER TABLE command. A constraint based on composite columns (more than one column) must be created by using the table-level approach." }, { "code": null, "e": 33570, "s": 33537, "text": "68.\tHow are constraints helpful?" }, { "code": null, "e": 33757, "s": 33570, "text": "\nThey limit the storage capacity of a table and hence save DB space\nThey prevent the modification of a table\nThey prevent deletion of a table if there are dependencies\nNone of the above\n" }, { "code": null, "e": 33824, "s": 33757, "text": "They limit the storage capacity of a table and hence save DB space" }, { "code": null, "e": 33865, "s": 33824, "text": "They prevent the modification of a table" }, { "code": null, "e": 33924, "s": 33865, "text": "They prevent deletion of a table if there are dependencies" }, { "code": null, "e": 33942, "s": 33924, "text": "None of the above" }, { "code": null, "e": 34125, "s": 33942, "text": "Answer: C. A constraint is a rule applied to data being added to a table.It represents business rules, policies, or procedures.Data violating the constraint isn't added to the table." }, { "code": null, "e": 34210, "s": 34125, "text": "69.A RAW data type column can store variable-length binary strings up to what value?" }, { "code": null, "e": 34233, "s": 34210, "text": "\n10 GB\n1 TB\n2 GB\n4 GB\n" }, { "code": null, "e": 34239, "s": 34233, "text": "10 GB" }, { "code": null, "e": 34244, "s": 34239, "text": "1 TB" }, { "code": null, "e": 34249, "s": 34244, "text": "2 GB" }, { "code": null, "e": 34254, "s": 34249, "text": "4 GB" }, { "code": null, "e": 34266, "s": 34254, "text": "Answer: C. " }, { "code": null, "e": 34326, "s": 34266, "text": "70.\tWhich of the following are valid constraints in Oracle?" }, { "code": null, "e": 34361, "s": 34326, "text": "\nINDEX\nGENERAL\nUNIQUE\nPRIMARY KEY\n" }, { "code": null, "e": 34367, "s": 34361, "text": "INDEX" }, { "code": null, "e": 34375, "s": 34367, "text": "GENERAL" }, { "code": null, "e": 34382, "s": 34375, "text": "UNIQUE" }, { "code": null, "e": 34394, "s": 34382, "text": "PRIMARY KEY" }, { "code": null, "e": 34955, "s": 34394, "text": "Answer: C, D. A NOT NULL constraint can be created only with the column-level approach. A PRIMARY KEY constraint doesn't allow duplicate or NULL values in the designated column. Only one PRIMARY KEY constraint is allowed in a table. A FOREIGN KEY constraint requires that the column entry match a referenced column entry in the table or be NULL. A UNIQUE constraint is similar to a PRIMARY KEY constraint, except it allows storing NULL values in the specified column. A CHECK constraint ensures that data meets a given condition before it's added to the table." }, { "code": null, "e": 35027, "s": 34955, "text": "71.\tWhich of the below DML operations consider constraints on a column?" }, { "code": null, "e": 35056, "s": 35027, "text": "\nINSERT\nUNION\nDELETE\nUPDATE\n" }, { "code": null, "e": 35063, "s": 35056, "text": "INSERT" }, { "code": null, "e": 35069, "s": 35063, "text": "UNION" }, { "code": null, "e": 35076, "s": 35069, "text": "DELETE" }, { "code": null, "e": 35083, "s": 35076, "text": "UPDATE" }, { "code": null, "e": 35169, "s": 35083, "text": "Answer: A, C, D. All the DML operations obey constraints on the columns of the table." }, { "code": null, "e": 35207, "s": 35169, "text": "72.\tWhen can a constraint be created?" }, { "code": null, "e": 35286, "s": 35207, "text": "\nWhile creating a table\nAfter creating a table\nBoth A and B\nNone of the above\n" }, { "code": null, "e": 35309, "s": 35286, "text": "While creating a table" }, { "code": null, "e": 35332, "s": 35309, "text": "After creating a table" }, { "code": null, "e": 35345, "s": 35332, "text": "Both A and B" }, { "code": null, "e": 35363, "s": 35345, "text": "None of the above" }, { "code": null, "e": 35522, "s": 35363, "text": "Answer: C. A constraint can be included during table creation as part of the CREATE TABLE command or added to an existing table with the ALTER TABLE command." }, { "code": null, "e": 35555, "s": 35522, "text": "73 Where are constraints stored?" }, { "code": null, "e": 35616, "s": 35555, "text": "\nIn the SGA\nIn a table\nIn data dictionary\nNone of the above\n" }, { "code": null, "e": 35627, "s": 35616, "text": "In the SGA" }, { "code": null, "e": 35638, "s": 35627, "text": "In a table" }, { "code": null, "e": 35657, "s": 35638, "text": "In data dictionary" }, { "code": null, "e": 35675, "s": 35657, "text": "None of the above" }, { "code": null, "e": 35687, "s": 35675, "text": "Answer: C. " }, { "code": null, "e": 35790, "s": 35687, "text": "74.\tYou create a constraint but do not name it. What will be the default name given to the constraint?" }, { "code": null, "e": 35831, "s": 35790, "text": "\nSYS_Cn\nSYS_constraint\nSYS_Const\nSYS_C0\n" }, { "code": null, "e": 35838, "s": 35831, "text": "SYS_Cn" }, { "code": null, "e": 35853, "s": 35838, "text": "SYS_constraint" }, { "code": null, "e": 35863, "s": 35853, "text": "SYS_Const" }, { "code": null, "e": 35870, "s": 35863, "text": "SYS_C0" }, { "code": null, "e": 36015, "s": 35870, "text": "Answer: A. By default, Oracle gives a generic name to the constraints SYS_Cn, where the n is an integer to keep the name of a constraint unique." }, { "code": null, "e": 36117, "s": 36015, "text": "75.\tWhat is the functional difference between a column-level constraint and a table-level constraint?" }, { "code": null, "e": 36326, "s": 36117, "text": "\nColumn-level constraint applies to all the columns of a table\nTable-level constraint applies to all the columns of a table\nThey both are functionally the same, only the syntax is different\nNone of the above\n" }, { "code": null, "e": 36388, "s": 36326, "text": "Column-level constraint applies to all the columns of a table" }, { "code": null, "e": 36449, "s": 36388, "text": "Table-level constraint applies to all the columns of a table" }, { "code": null, "e": 36515, "s": 36449, "text": "They both are functionally the same, only the syntax is different" }, { "code": null, "e": 36533, "s": 36515, "text": "None of the above" }, { "code": null, "e": 36687, "s": 36533, "text": "Answer: C. Functionally, the table level constraints and column level constraints work similar. Composite constraints can be defined at table level only." }, { "code": null, "e": 36736, "s": 36687, "text": "76. What is true about column-level constraints?" }, { "code": null, "e": 36904, "s": 36736, "text": "\nThey can be created before the creation of a table\nThey can be created before the defining of a column\nThey are included when the column is defined\nNone of the above\n" }, { "code": null, "e": 36955, "s": 36904, "text": "They can be created before the creation of a table" }, { "code": null, "e": 37007, "s": 36955, "text": "They can be created before the defining of a column" }, { "code": null, "e": 37052, "s": 37007, "text": "They are included when the column is defined" }, { "code": null, "e": 37070, "s": 37052, "text": "None of the above" }, { "code": null, "e": 37155, "s": 37070, "text": "Answer: C. Column level constraints are defined along with the column specification." }, { "code": null, "e": 37207, "s": 37155, "text": "77.\tWhat is true about NOT NULL constraints in SQL?" }, { "code": null, "e": 37375, "s": 37207, "text": "\nThey should be defined at the table level\nThey should be defined at the column level\nThey should be defined only on one column\nThey should be defined only on one row\n" }, { "code": null, "e": 37417, "s": 37375, "text": "They should be defined at the table level" }, { "code": null, "e": 37460, "s": 37417, "text": "They should be defined at the column level" }, { "code": null, "e": 37502, "s": 37460, "text": "They should be defined only on one column" }, { "code": null, "e": 37541, "s": 37502, "text": "They should be defined only on one row" }, { "code": null, "e": 37626, "s": 37541, "text": "Answer: B. A NOT NULL constraint can be created only with the column-level approach." }, { "code": null, "e": 37707, "s": 37626, "text": "Consider the following statement and answer the questions 78 and 79 that follow:" }, { "code": null, "e": 37858, "s": 37707, "text": "CREATE TABLE employees (\nemp_id NUMBER (6) CONSTRAINT emp_emp_id_PK PRIMARY KEY,\nfirst_name VARCHAR2(20),\nlast_name VARCHAR2(20),\nhire_date DATE \n); " }, { "code": null, "e": 37921, "s": 37858, "text": "78.Which type of constraint is created in the above statement?" }, { "code": null, "e": 38012, "s": 37921, "text": "\nColumn level constraint\nTable level constraint\nNamed constraint\nSpecification constraint\n" }, { "code": null, "e": 38036, "s": 38012, "text": "Column level constraint" }, { "code": null, "e": 38059, "s": 38036, "text": "Table level constraint" }, { "code": null, "e": 38076, "s": 38059, "text": "Named constraint" }, { "code": null, "e": 38101, "s": 38076, "text": "Specification constraint" }, { "code": null, "e": 38183, "s": 38101, "text": "Answer: A. A column level constraint is created along with the column definition." }, { "code": null, "e": 38277, "s": 38183, "text": "79.\tWhat modification can be made to the above statement to give it a table level constraint?" }, { "code": null, "e": 38447, "s": 38277, "text": "\nCONSTRAINT emp_emp_id_PK PRIMARY KEY \nCONSTRAINT emp_emp_id_PK PRIMARY KEY (EMP_ID) \nCONSTRAINT emp_emp_id_PK EMP_ID PRIMARY KEY \nCONSTRAINT PRIMARY KEY emp_emp_id_PK \n" }, { "code": null, "e": 38485, "s": 38447, "text": "CONSTRAINT emp_emp_id_PK PRIMARY KEY " }, { "code": null, "e": 38532, "s": 38485, "text": "CONSTRAINT emp_emp_id_PK PRIMARY KEY (EMP_ID) " }, { "code": null, "e": 38577, "s": 38532, "text": "CONSTRAINT emp_emp_id_PK EMP_ID PRIMARY KEY " }, { "code": null, "e": 38615, "s": 38577, "text": "CONSTRAINT PRIMARY KEY emp_emp_id_PK " }, { "code": null, "e": 38627, "s": 38615, "text": "Answer: B. " }, { "code": null, "e": 38674, "s": 38627, "text": "80.\tWhat is true about PRIMARY KEY constraint?" }, { "code": null, "e": 38998, "s": 38674, "text": "\nIt applies a NOT NULL constraint implicitly to the column on which it is defined\nIt applies a UNIQUE KEY constraint implicitly to the column on which it is defined\nIt applies a CHECK constraint implicitly to the column on which it is defined\nIt applies a DEFAULT constraint implicitly to the column on which it is defined\n" }, { "code": null, "e": 39079, "s": 38998, "text": "It applies a NOT NULL constraint implicitly to the column on which it is defined" }, { "code": null, "e": 39162, "s": 39079, "text": "It applies a UNIQUE KEY constraint implicitly to the column on which it is defined" }, { "code": null, "e": 39240, "s": 39162, "text": "It applies a CHECK constraint implicitly to the column on which it is defined" }, { "code": null, "e": 39320, "s": 39240, "text": "It applies a DEFAULT constraint implicitly to the column on which it is defined" }, { "code": null, "e": 39476, "s": 39320, "text": "Answer: A. A PRIMARY KEY constraint doesn't allow duplicate or NULL values in the designated column. Only one PRIMARY KEY constraint is allowed in a table." }, { "code": null, "e": 39548, "s": 39476, "text": "81.\tWhat among the following is true regarding a UNIQUE KEY constraint?" }, { "code": null, "e": 39803, "s": 39548, "text": "\nUNIQUE KEY constraint and PRIMARY KEY constraint are the same\nUNIQUE KEY constraint allows NULL values if there is no NOT NULL defined on the column(s)\nWe can have two identical rows when a UNIQUE KEY constraint is defined on a column\nNone of the above\n" }, { "code": null, "e": 39865, "s": 39803, "text": "UNIQUE KEY constraint and PRIMARY KEY constraint are the same" }, { "code": null, "e": 39955, "s": 39865, "text": "UNIQUE KEY constraint allows NULL values if there is no NOT NULL defined on the column(s)" }, { "code": null, "e": 40038, "s": 39955, "text": "We can have two identical rows when a UNIQUE KEY constraint is defined on a column" }, { "code": null, "e": 40056, "s": 40038, "text": "None of the above" }, { "code": null, "e": 40189, "s": 40056, "text": "Answer: B. A UNIQUE constraint is similar to a PRIMARY KEY constraint, except it allows storing NULL values in the specified column." }, { "code": null, "e": 40270, "s": 40189, "text": "Consider the following statement and answer the questions 82 and 83 that follow:" }, { "code": null, "e": 40434, "s": 40270, "text": "CREATE TABLE employees (\nemp_id NUMBER (6)\nfirst_name VARCHAR2(20),\nlast_name VARCHAR2(20),\njob VARCHAR2(20),\nhire_date DATE \nCONSTRAINT emp_job_UK UNIQUE (job)); " }, { "code": null, "e": 40509, "s": 40434, "text": "82.\tWhich of the below statements interpret the above CREATE TABLE script?" }, { "code": null, "e": 40674, "s": 40509, "text": "\nThis table cannot have two identical Job IDs\nThis table can have two or more identical Job IDs\nThis table can have NULL values in the JOB column\nNone of the above\n" }, { "code": null, "e": 40719, "s": 40674, "text": "This table cannot have two identical Job IDs" }, { "code": null, "e": 40769, "s": 40719, "text": "This table can have two or more identical Job IDs" }, { "code": null, "e": 40819, "s": 40769, "text": "This table can have NULL values in the JOB column" }, { "code": null, "e": 40837, "s": 40819, "text": "None of the above" }, { "code": null, "e": 40937, "s": 40837, "text": "Answer: A, C. A UNIQUE constraint on the JOB column will restrict duplicate value but allows nulls." }, { "code": null, "e": 41037, "s": 40937, "text": "83.\tIf the constraint emp_job_UK is modified as emp_job_PK PRIMARY KEY (job), what will be outcome?" }, { "code": null, "e": 41229, "s": 41037, "text": "\nThis change can happen only if there's no NULL value in the JOB column\nThis change can happen without any restrictions\nThis change will change the values of the column JOB\nNone of the above\n" }, { "code": null, "e": 41300, "s": 41229, "text": "This change can happen only if there's no NULL value in the JOB column" }, { "code": null, "e": 41348, "s": 41300, "text": "This change can happen without any restrictions" }, { "code": null, "e": 41401, "s": 41348, "text": "This change will change the values of the column JOB" }, { "code": null, "e": 41419, "s": 41401, "text": "None of the above" }, { "code": null, "e": 41431, "s": 41419, "text": "Answer: A. " }, { "code": null, "e": 41481, "s": 41431, "text": "84.\tWhat is true about the UNIQUE key constraint?" }, { "code": null, "e": 41777, "s": 41481, "text": "\nA unique key index is implicitly created when a UNIQUE constraint is defined on a column\nA PRIMARY KEY constraint is implicitly created when a UNIQUE constraint is defined on a column\nA NOT NULL constraint is implicitly created when a UNIQUE constraint is defined on a column\nNone of the above\n" }, { "code": null, "e": 41866, "s": 41777, "text": "A unique key index is implicitly created when a UNIQUE constraint is defined on a column" }, { "code": null, "e": 41961, "s": 41866, "text": "A PRIMARY KEY constraint is implicitly created when a UNIQUE constraint is defined on a column" }, { "code": null, "e": 42053, "s": 41961, "text": "A NOT NULL constraint is implicitly created when a UNIQUE constraint is defined on a column" }, { "code": null, "e": 42071, "s": 42053, "text": "None of the above" }, { "code": null, "e": 42228, "s": 42071, "text": "Answer: A. When a unique constraint is imposed on a table, Oracle internally creates a unique key index on the column to restrict the duplication of values." }, { "code": null, "e": 42278, "s": 42228, "text": "85.\tWhich of the following is true about indexes?" }, { "code": null, "e": 42624, "s": 42278, "text": "\nIf an UPDATE statement is executed on a table, the indexes need to be manually updated as well\nIf a DELETE statement is executed on a table, the indexes need to manually deleted as well\nWhen a table is dropped, the indexes are automatically dropped\nIf an UPDATE statement is executed on a table, the corresponding indexes are updated as well. \n" }, { "code": null, "e": 42719, "s": 42624, "text": "If an UPDATE statement is executed on a table, the indexes need to be manually updated as well" }, { "code": null, "e": 42810, "s": 42719, "text": "If a DELETE statement is executed on a table, the indexes need to manually deleted as well" }, { "code": null, "e": 42873, "s": 42810, "text": "When a table is dropped, the indexes are automatically dropped" }, { "code": null, "e": 42968, "s": 42873, "text": "If an UPDATE statement is executed on a table, the corresponding indexes are updated as well. " }, { "code": null, "e": 42983, "s": 42968, "text": "Answer: C, D. " }, { "code": null, "e": 43043, "s": 42983, "text": "86.Which of the following CREATE TABLE statements is valid?" }, { "code": null, "e": 43627, "s": 43043, "text": "\nCREATE TABLE EMPLOYEES \n(emp_id NUMBER (2) PRIMARY KEY,\nfirst_name VARCHAR(20),\nlast_name VARCHAR(20),\nhire_date DATE NOT NULL); \nCREATE TABLE EMPLOYEES \n(emp_id NUMBER (2) PRIMARY KEY NOT NULL,\nfirst_name VARCHAR(20),\nlast_name VARCHAR(20),\nhire_date DATE NOT NULL PRIMARY KEY); \nCREATE TABLE EMPLOYEES \n(emp_id NUMBER (2) PRIMARY KEY,\nfirst_name VARCHAR(20),\nlast_name VARCHAR(20),\nhire_date DATE NOT NULL UNIQUE);\nCREATE TABLE EMPLOYEES \n(emp_id NUMBER (2),\nfirst_name VARCHAR(20),\nlast_name VARCHAR(20),\nhire_date DATE NOT NULL,\nCONSTRAINT emp_emp_id_PK PRIMARY KEY (emp_id)); \n" }, { "code": null, "e": 43757, "s": 43627, "text": "CREATE TABLE EMPLOYEES \n(emp_id NUMBER (2) PRIMARY KEY,\nfirst_name VARCHAR(20),\nlast_name VARCHAR(20),\nhire_date DATE NOT NULL); " }, { "code": null, "e": 43887, "s": 43757, "text": "CREATE TABLE EMPLOYEES \n(emp_id NUMBER (2) PRIMARY KEY,\nfirst_name VARCHAR(20),\nlast_name VARCHAR(20),\nhire_date DATE NOT NULL); " }, { "code": null, "e": 44038, "s": 43887, "text": "CREATE TABLE EMPLOYEES \n(emp_id NUMBER (2) PRIMARY KEY NOT NULL,\nfirst_name VARCHAR(20),\nlast_name VARCHAR(20),\nhire_date DATE NOT NULL PRIMARY KEY); " }, { "code": null, "e": 44189, "s": 44038, "text": "CREATE TABLE EMPLOYEES \n(emp_id NUMBER (2) PRIMARY KEY NOT NULL,\nfirst_name VARCHAR(20),\nlast_name VARCHAR(20),\nhire_date DATE NOT NULL PRIMARY KEY); " }, { "code": null, "e": 44325, "s": 44189, "text": "CREATE TABLE EMPLOYEES \n(emp_id NUMBER (2) PRIMARY KEY,\nfirst_name VARCHAR(20),\nlast_name VARCHAR(20),\nhire_date DATE NOT NULL UNIQUE);" }, { "code": null, "e": 44461, "s": 44325, "text": "CREATE TABLE EMPLOYEES \n(emp_id NUMBER (2) PRIMARY KEY,\nfirst_name VARCHAR(20),\nlast_name VARCHAR(20),\nhire_date DATE NOT NULL UNIQUE);" }, { "code": null, "e": 44626, "s": 44461, "text": "CREATE TABLE EMPLOYEES \n(emp_id NUMBER (2),\nfirst_name VARCHAR(20),\nlast_name VARCHAR(20),\nhire_date DATE NOT NULL,\nCONSTRAINT emp_emp_id_PK PRIMARY KEY (emp_id)); " }, { "code": null, "e": 44791, "s": 44626, "text": "CREATE TABLE EMPLOYEES \n(emp_id NUMBER (2),\nfirst_name VARCHAR(20),\nlast_name VARCHAR(20),\nhire_date DATE NOT NULL,\nCONSTRAINT emp_emp_id_PK PRIMARY KEY (emp_id)); " }, { "code": null, "e": 44848, "s": 44791, "text": "Answer: A, C, D. All the CREATE TABLE scripts are valid." }, { "code": null, "e": 44903, "s": 44848, "text": "87.\tHow many PRIMARY KEY constraints can a table have?" }, { "code": null, "e": 44921, "s": 44903, "text": "\n0\nUnlimited\n2\n1\n" }, { "code": null, "e": 44923, "s": 44921, "text": "0" }, { "code": null, "e": 44933, "s": 44923, "text": "Unlimited" }, { "code": null, "e": 44935, "s": 44933, "text": "2" }, { "code": null, "e": 44937, "s": 44935, "text": "1" }, { "code": null, "e": 44995, "s": 44937, "text": "Answer: D. A table can have one and only one primary key." }, { "code": null, "e": 45215, "s": 44995, "text": "88.\tYou want to put a CHECK constraint on the EMP_ID such that it should be equal to the current value of a Sequence through which it is getting its values. Which of the following statements will help you achieve this?" }, { "code": null, "e": 45461, "s": 45215, "text": "\nEmp_id NUMBER (10) CONSTRAINT emp_emp_id_chk CHECK (emp_id = EMPNO.CURRVAL);\n\nEmp_id NUMBER (10) CONSTRAINT emp_emp_id_chk CHECK (emp_id = EMPNO.NEXTVAL);\n\nEmp_id NUMBER (10) CONSTRAINT emp_emp_id_chk CHECK (EMPNO.CURRVAL);\n\nNone of the above\n\n" }, { "code": null, "e": 45539, "s": 45461, "text": "Emp_id NUMBER (10) CONSTRAINT emp_emp_id_chk CHECK (emp_id = EMPNO.CURRVAL);\n" }, { "code": null, "e": 45617, "s": 45539, "text": "Emp_id NUMBER (10) CONSTRAINT emp_emp_id_chk CHECK (emp_id = EMPNO.NEXTVAL);\n" }, { "code": null, "e": 45686, "s": 45617, "text": "Emp_id NUMBER (10) CONSTRAINT emp_emp_id_chk CHECK (EMPNO.CURRVAL);\n" }, { "code": null, "e": 45705, "s": 45686, "text": "None of the above\n" }, { "code": null, "e": 45805, "s": 45705, "text": "Answer: D. You cannot use CURRVAL, NEXTVAL, LEVEL and ROWNUM pseudo columns in the CHECK constraint" }, { "code": null, "e": 45897, "s": 45805, "text": "89.\tWhich of the following commands will help in converting the foreign key values to NULL?" }, { "code": null, "e": 45955, "s": 45897, "text": "\nON DELETE CASCADE\nON DELETE SET NULL\nCASCADE\nREFERENCES\n" }, { "code": null, "e": 45973, "s": 45955, "text": "ON DELETE CASCADE" }, { "code": null, "e": 45992, "s": 45973, "text": "ON DELETE SET NULL" }, { "code": null, "e": 46000, "s": 45992, "text": "CASCADE" }, { "code": null, "e": 46011, "s": 46000, "text": "REFERENCES" }, { "code": null, "e": 46023, "s": 46011, "text": "Answer: B. " }, { "code": null, "e": 46230, "s": 46023, "text": "90.\tYou need to add a constraint to the EMPLOYEES table which restricts the addition of those employees who have salaries less than 10000. Which of the following commands will give you the required results?" }, { "code": null, "e": 46545, "s": 46230, "text": "\nALTER TABLE employees ADD CONSTRAINT emp_emp_sal_CHECK CHECK (salary >= 10000); \nALTER TABLE employees ADD CHECK CONSTRAINT emp_emp_sal_CHECK (salary>10000); \nALTER TABLE employees ADD CONSTRAINT CHECK emp_emp_sal_CHECK (salary = 10000); \nALTER TABLE employees ADD CONSTRAINT emp_emp_sal_CHECK (salary < 10000); \n" }, { "code": null, "e": 46626, "s": 46545, "text": "ALTER TABLE employees ADD CONSTRAINT emp_emp_sal_CHECK CHECK (salary >= 10000); " }, { "code": null, "e": 46707, "s": 46626, "text": "ALTER TABLE employees ADD CONSTRAINT emp_emp_sal_CHECK CHECK (salary >= 10000); " }, { "code": null, "e": 46785, "s": 46707, "text": "ALTER TABLE employees ADD CHECK CONSTRAINT emp_emp_sal_CHECK (salary>10000); " }, { "code": null, "e": 46863, "s": 46785, "text": "ALTER TABLE employees ADD CHECK CONSTRAINT emp_emp_sal_CHECK (salary>10000); " }, { "code": null, "e": 46943, "s": 46863, "text": "ALTER TABLE employees ADD CONSTRAINT CHECK emp_emp_sal_CHECK (salary = 10000); " }, { "code": null, "e": 47023, "s": 46943, "text": "ALTER TABLE employees ADD CONSTRAINT CHECK emp_emp_sal_CHECK (salary = 10000); " }, { "code": null, "e": 47097, "s": 47023, "text": "ALTER TABLE employees ADD CONSTRAINT emp_emp_sal_CHECK (salary < 10000); " }, { "code": null, "e": 47171, "s": 47097, "text": "ALTER TABLE employees ADD CONSTRAINT emp_emp_sal_CHECK (salary < 10000); " }, { "code": null, "e": 47183, "s": 47171, "text": "Answer: A. " }, { "code": null, "e": 47408, "s": 47183, "text": "91.\tYou need to add a constraint to the EMPLOYEES table which imposes a restriction that the HIRE_DATE for all the employees should be equal to SYSDATE-7. Which of the following statements will give you the required results?" }, { "code": null, "e": 47748, "s": 47408, "text": "\nALTER TABLE employees ADD CHECK CONSTRAINT emp_emp_sal_CHECK ( to_char(hire_date,'DD-MON-YY') = SYSDATE -7); \nALTER TABLE employees ADD CONSTRAINT CHECK emp_emp_sal_CHECK ( to_char(hire_date,'DD-MON-YY') = SYSDATE -7); \nALTER TABLE employees ADD emp_emp_sal_CHECK CHECK ( to_char(hire_date,'DD-MON-YY') = SYSDATE -7); \nNone of the above\n" }, { "code": null, "e": 47859, "s": 47748, "text": "ALTER TABLE employees ADD CHECK CONSTRAINT emp_emp_sal_CHECK ( to_char(hire_date,'DD-MON-YY') = SYSDATE -7); " }, { "code": null, "e": 47970, "s": 47859, "text": "ALTER TABLE employees ADD CHECK CONSTRAINT emp_emp_sal_CHECK ( to_char(hire_date,'DD-MON-YY') = SYSDATE -7); " }, { "code": null, "e": 48080, "s": 47970, "text": "ALTER TABLE employees ADD CONSTRAINT CHECK emp_emp_sal_CHECK ( to_char(hire_date,'DD-MON-YY') = SYSDATE -7); " }, { "code": null, "e": 48190, "s": 48080, "text": "ALTER TABLE employees ADD CONSTRAINT CHECK emp_emp_sal_CHECK ( to_char(hire_date,'DD-MON-YY') = SYSDATE -7); " }, { "code": null, "e": 48289, "s": 48190, "text": "ALTER TABLE employees ADD emp_emp_sal_CHECK CHECK ( to_char(hire_date,'DD-MON-YY') = SYSDATE -7); " }, { "code": null, "e": 48388, "s": 48289, "text": "ALTER TABLE employees ADD emp_emp_sal_CHECK CHECK ( to_char(hire_date,'DD-MON-YY') = SYSDATE -7); " }, { "code": null, "e": 48406, "s": 48388, "text": "None of the above" }, { "code": null, "e": 48498, "s": 48406, "text": "Answer: D. You cannot use SYSDATE, UID, USER and USERENV functions in the CHECK constraint." }, { "code": null, "e": 48574, "s": 48498, "text": "Consider the following query and answer the questions 92 to 94 that follow:" }, { "code": null, "e": 48858, "s": 48574, "text": "CREATE TABLE EMPLOYEES \n(emp_id NUMBER (2),\nfirst_name VARCHAR(20),\nlast_name VARCHAR(20),\ndept_id NUMBER (10),\nhire_date DATE DEFAULT SYSDATE \nCONSTRAINT emp_emp_id_PK PRIMARY KEY (emp_id, hire_date)\nCONSTRAINT emp_dept_FK FOREIGN KEY (dept_id) \nREFERENCES departments (dept_id)\n); " }, { "code": null, "e": 48927, "s": 48858, "text": "92.\tWhich of the below statements interpret the CREATE TABLE script?" }, { "code": null, "e": 49122, "s": 48927, "text": "\nA FOREIGN KEY constraint is defined at the table level on the column DEPT_ID\nThe FOREIGN KEY constraint defined references the DEPT_ID from the DEPARTMENTS table\nBoth A and B\nNone of the above\n" }, { "code": null, "e": 49199, "s": 49122, "text": "A FOREIGN KEY constraint is defined at the table level on the column DEPT_ID" }, { "code": null, "e": 49284, "s": 49199, "text": "The FOREIGN KEY constraint defined references the DEPT_ID from the DEPARTMENTS table" }, { "code": null, "e": 49297, "s": 49284, "text": "Both A and B" }, { "code": null, "e": 49315, "s": 49297, "text": "None of the above" }, { "code": null, "e": 49442, "s": 49315, "text": "Answer: C. The keywords FOREIGN KEY and REFERENCES are used when we define a FOREIGN KEY constraint for referential integrity." }, { "code": null, "e": 49642, "s": 49442, "text": "93.\tYou need to delete all the dependent rows in DEPARTMENTS table when you delete the EMPLOYEES table. Which of the following command will solve the purpose? (Consider the table structures as given)" }, { "code": null, "e": 50068, "s": 49642, "text": "SQL> DESC employees\n Name\t\t\t Null?\t Type\n ----------------------- -------- ----------------\n EMPLOYEE_ID\t\t NOT NULL NUMBER(6)\n FIRST_NAME\t\t\t VARCHAR2(20)\n LAST_NAME\t\t NOT NULL VARCHAR2(25)\n EMAIL\t\t\t NOT NULL VARCHAR2(25)\n PHONE_NUMBER\t\t\t VARCHAR2(20)\n HIRE_DATE\t\t NOT NULL DATE\n JOB_ID \t\t NOT NULL VARCHAR2(10)\n SALARY \t\t\t NUMBER(8,2)\n COMMISSION_PCT \t\t NUMBER(2,2)\n MANAGER_ID\t\t\t NUMBER(6)\n DEPARTMENT_ID\t\t\t NUMBER(4)" }, { "code": null, "e": 50292, "s": 50068, "text": "SQL> DESC departments\n Name\t\t\t Null?\t Type\n ----------------------- -------- ----------------\n DEPARTMENT_ID\t\t NOT NULL NUMBER(4)\n DEPARTMENT_NAME\t NOT NULL VARCHAR2(30)\n MANAGER_ID\t\t\t NUMBER(6)\n LOCATION_ID\t\t\t NUMBER(4)" }, { "code": null, "e": 50353, "s": 50292, "text": "\nON DELETE SET NULL\nON DELETE CASCADE\nDELETE ALL\nFOR UPDATE\n" }, { "code": null, "e": 50372, "s": 50353, "text": "ON DELETE SET NULL" }, { "code": null, "e": 50390, "s": 50372, "text": "ON DELETE CASCADE" }, { "code": null, "e": 50401, "s": 50390, "text": "DELETE ALL" }, { "code": null, "e": 50412, "s": 50401, "text": "FOR UPDATE" }, { "code": null, "e": 50608, "s": 50412, "text": "Answer: B. If ON DELETE CASCADE is included in the constraint definition and a record is deleted from the parent table,any corresponding records in the child table are also deleted automatically." }, { "code": null, "e": 50750, "s": 50608, "text": "94.\tThe EMPLOYEES table as shown below, has 5 employees who work in department 10. An executive from admin department issues the below query." }, { "code": null, "e": 50795, "s": 50750, "text": "DELETE FROM departments\nWHERE dept_id = 10; " }, { "code": null, "e": 50874, "s": 50795, "text": "What will be the outcome of this query? (Assume the table structures as shown)" }, { "code": null, "e": 51300, "s": 50874, "text": "SQL> DESC employees\n Name\t\t\t Null?\t Type\n ----------------------- -------- ----------------\n EMPLOYEE_ID\t\t NOT NULL NUMBER(6)\n FIRST_NAME\t\t\t VARCHAR2(20)\n LAST_NAME\t\t NOT NULL VARCHAR2(25)\n EMAIL\t\t\t NOT NULL VARCHAR2(25)\n PHONE_NUMBER\t\t\t VARCHAR2(20)\n HIRE_DATE\t\t NOT NULL DATE\n JOB_ID \t\t NOT NULL VARCHAR2(10)\n SALARY \t\t\t NUMBER(8,2)\n COMMISSION_PCT \t\t NUMBER(2,2)\n MANAGER_ID\t\t\t NUMBER(6)\n DEPARTMENT_ID\t\t\t NUMBER(4)" }, { "code": null, "e": 51524, "s": 51300, "text": "SQL> DESC departments\n Name\t\t\t Null?\t Type\n ----------------------- -------- ----------------\n DEPARTMENT_ID\t\t NOT NULL NUMBER(4)\n DEPARTMENT_NAME\t NOT NULL VARCHAR2(30)\n MANAGER_ID\t\t\t NUMBER(6)\n LOCATION_ID\t\t\t NUMBER(4)" }, { "code": null, "e": 51615, "s": 51524, "text": "\nIntegrity constraint error\n\nSuccessful execution\n\nNeither of A nor B\n\nNone of the above\n\n" }, { "code": null, "e": 51643, "s": 51615, "text": "Integrity constraint error\n" }, { "code": null, "e": 51665, "s": 51643, "text": "Successful execution\n" }, { "code": null, "e": 51685, "s": 51665, "text": "Neither of A nor B\n" }, { "code": null, "e": 51704, "s": 51685, "text": "None of the above\n" } ]
An Interesting Method to Generate Binary Numbers from 1 to n
23 Jun, 2022 Given a number n, write a function that generates and prints all binary numbers with decimal values from 1 to n. Examples: Input: n = 2 Output: 1, 10 Input: n = 5 Output: 1, 10, 11, 100, 101 Naive Method: A simple method is to run a loop from 1 to n, call decimal to binary inside the loop. Efficient Method: 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. Following is an interesting method that uses queue data structure to print binary numbers. Thanks to Vivek for suggesting this approach. Create an empty queue of strings Enqueue the first binary number “1” to queue. Now run a loop for generating and printing n binary numbers. Dequeue and Print the front of queue. Append “0” at the end of front item and enqueue it. Append “1” at the end of front item and enqueue it. Create an empty queue of strings Enqueue the first binary number “1” to queue. Now run a loop for generating and printing n binary numbers. Dequeue and Print the front of queue. Append “0” at the end of front item and enqueue it. Append “1” at the end of front item and enqueue it. Dequeue and Print the front of queue. Append “0” at the end of front item and enqueue it. Append “1” at the end of front item and enqueue it. Following is the implementation of above algorithm. C++ Java Python3 C# Javascript // C++ program to generate binary numbers from 1 to n#include <bits/stdc++.h>using namespace std; // This function uses queue data structure to print binary// numbersvoid generatePrintBinary(int n){ // Create an empty queue of strings queue<string> q; // Enqueue the first binary number q.push("1"); // This loops is like BFS of a tree with 1 as root // 0 as left child and 1 as right child and so on while (n--) { // print the front of queue string s1 = q.front(); q.pop(); cout << s1 << "\n"; string s2 = s1; // Store s1 before changing it // Append "0" to s1 and enqueue it q.push(s1.append("0")); // Append "1" to s2 and enqueue it. Note that s2 // contains the previous front q.push(s2.append("1")); }} // Driver program to test above functionint main(){ int n = 10; generatePrintBinary(n); return 0;} // Java program to generate binary numbers from 1 to n import java.util.LinkedList;import java.util.Queue; public class GenerateBNo { // This function uses queue data structure to print // binary numbers static void generatePrintBinary(int n) { // Create an empty queue of strings Queue<String> q = new LinkedList<String>(); // Enqueue the first binary number q.add("1"); // This loops is like BFS of a tree with 1 as root // 0 as left child and 1 as right child and so on while (n-- > 0) { // print the front of queue String s1 = q.peek(); q.remove(); System.out.println(s1); // Store s1 before changing it String s2 = s1; // Append "0" to s1 and enqueue it q.add(s1 + "0"); // Append "1" to s2 and enqueue it. Note that s2 // contains the previous front q.add(s2 + "1"); } } // Driver program to test above function public static void main(String[] args) { int n = 10; generatePrintBinary(n); }}// This code is contributed by Sumit Ghosh # Python program to generate binary numbers from# 1 to n # This function uses queue data structure to print binary numbers def generatePrintBinary(n): # Create an empty queue from queue import Queue q = Queue() # Enqueue the first binary number q.put("1") # This loop is like BFS of a tree with 1 as root # 0 as left child and 1 as right child and so on while(n > 0): n -= 1 # Print the front of queue s1 = q.get() print (s1) s2 = s1 # Store s1 before changing it # Append "0" to s1 and enqueue it q.put(s1+"0") # Append "1" to s2 and enqueue it. Note that s2 # contains the previous front q.put(s2+"1") # Driver program to test above functionn = 10generatePrintBinary(n) # This code is contributed by Nikhil Kumar Singh(nickzuck_007) // C# program to generate binary// numbers from 1 to nusing System;using System.Collections.Generic; class GFG { // This function uses queue data // structure to print binary numbers public static void generatePrintBinary(int n) { // Create an empty queue of strings LinkedList<string> q = new LinkedList<string>(); // Enqueue the first binary number q.AddLast("1"); // This loops is like BFS of a tree // with 1 as root 0 as left child // and 1 as right child and so on while (n-- > 0) { // print the front of queue string s1 = q.First.Value; q.RemoveFirst(); Console.WriteLine(s1); // Store s1 before changing it string s2 = s1; // Append "0" to s1 and enqueue it q.AddLast(s1 + "0"); // Append "1" to s2 and enqueue it. // Note that s2 contains the previous front q.AddLast(s2 + "1"); } } // Driver Code public static void Main(string[] args) { int n = 10; generatePrintBinary(n); }} // This code is contributed by Shrikant13 <script> // JavaScript program to generate binary numbers from 1 to n // This function uses queue data structure to print binary// numbersfunction generatePrintBinary(n){ // Create an empty queue of strings var q = []; // Enqueue the first binary number q.push("1"); // This loops is like BFS of a tree with 1 as root // 0 as left child and 1 as right child and so on while (n--) { // print the front of queue var s1 = q[0]; q.shift(); document.write( s1 + "<br>"); var s2 = s1; // Store s1 before changing it // Append "0" to s1 and enqueue it q.push(s1+"0"); // Append "1" to s2 and enqueue it. Note that s2 // contains the previous front q.push(s2+"1"); }} // Driver program to test above functionvar n = 10;generatePrintBinary(n); </script> 1 10 11 100 101 110 111 1000 1001 1010 Time Complexity: O(n) Space Complexity: O(n) as extra space is required in this method This article is contributed by Abhishek. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above shrikanth13 gp6 kumarmenish8 rrrtnx amartyaghoshgfg surinderdawra388 technophpfij hardikkoriintern Amazon Queue Amazon Queue Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures What is Priority Queue | Introduction to Priority Queue Sliding Window Maximum (Maximum of all subarrays of size k) What is Data Structure: Types, Classifications and Applications Queue - Linked List Implementation Minimum steps to reach target by a Knight | Set 1 Array implementation of queue (Simple) Circular Queue | Set 1 (Introduction and Array Implementation) Priority Queue in Python Print Nodes in Top View of Binary Tree
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Jun, 2022" }, { "code": null, "e": 168, "s": 54, "text": "Given a number n, write a function that generates and prints all binary numbers with decimal values from 1 to n. " }, { "code": null, "e": 179, "s": 168, "text": "Examples: " }, { "code": null, "e": 248, "s": 179, "text": "Input: n = 2\nOutput: 1, 10\n\nInput: n = 5\nOutput: 1, 10, 11, 100, 101" }, { "code": null, "e": 262, "s": 248, "text": "Naive Method:" }, { "code": null, "e": 349, "s": 262, "text": "A simple method is to run a loop from 1 to n, call decimal to binary inside the loop. " }, { "code": null, "e": 368, "s": 349, "text": "Efficient Method: " }, { "code": null, "e": 377, "s": 368, "text": "Chapters" }, { "code": null, "e": 404, "s": 377, "text": "descriptions off, selected" }, { "code": null, "e": 454, "s": 404, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 477, "s": 454, "text": "captions off, selected" }, { "code": null, "e": 485, "s": 477, "text": "English" }, { "code": null, "e": 509, "s": 485, "text": "This is a modal window." }, { "code": null, "e": 578, "s": 509, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 600, "s": 578, "text": "End of dialog window." }, { "code": null, "e": 738, "s": 600, "text": "Following is an interesting method that uses queue data structure to print binary numbers. Thanks to Vivek for suggesting this approach. " }, { "code": null, "e": 1020, "s": 738, "text": "Create an empty queue of strings Enqueue the first binary number “1” to queue. Now run a loop for generating and printing n binary numbers. Dequeue and Print the front of queue. Append “0” at the end of front item and enqueue it. Append “1” at the end of front item and enqueue it." }, { "code": null, "e": 1054, "s": 1020, "text": "Create an empty queue of strings " }, { "code": null, "e": 1101, "s": 1054, "text": "Enqueue the first binary number “1” to queue. " }, { "code": null, "e": 1304, "s": 1101, "text": "Now run a loop for generating and printing n binary numbers. Dequeue and Print the front of queue. Append “0” at the end of front item and enqueue it. Append “1” at the end of front item and enqueue it." }, { "code": null, "e": 1343, "s": 1304, "text": "Dequeue and Print the front of queue. " }, { "code": null, "e": 1396, "s": 1343, "text": "Append “0” at the end of front item and enqueue it. " }, { "code": null, "e": 1448, "s": 1396, "text": "Append “1” at the end of front item and enqueue it." }, { "code": null, "e": 1500, "s": 1448, "text": "Following is the implementation of above algorithm." }, { "code": null, "e": 1504, "s": 1500, "text": "C++" }, { "code": null, "e": 1509, "s": 1504, "text": "Java" }, { "code": null, "e": 1517, "s": 1509, "text": "Python3" }, { "code": null, "e": 1520, "s": 1517, "text": "C#" }, { "code": null, "e": 1531, "s": 1520, "text": "Javascript" }, { "code": "// C++ program to generate binary numbers from 1 to n#include <bits/stdc++.h>using namespace std; // This function uses queue data structure to print binary// numbersvoid generatePrintBinary(int n){ // Create an empty queue of strings queue<string> q; // Enqueue the first binary number q.push(\"1\"); // This loops is like BFS of a tree with 1 as root // 0 as left child and 1 as right child and so on while (n--) { // print the front of queue string s1 = q.front(); q.pop(); cout << s1 << \"\\n\"; string s2 = s1; // Store s1 before changing it // Append \"0\" to s1 and enqueue it q.push(s1.append(\"0\")); // Append \"1\" to s2 and enqueue it. Note that s2 // contains the previous front q.push(s2.append(\"1\")); }} // Driver program to test above functionint main(){ int n = 10; generatePrintBinary(n); return 0;}", "e": 2446, "s": 1531, "text": null }, { "code": "// Java program to generate binary numbers from 1 to n import java.util.LinkedList;import java.util.Queue; public class GenerateBNo { // This function uses queue data structure to print // binary numbers static void generatePrintBinary(int n) { // Create an empty queue of strings Queue<String> q = new LinkedList<String>(); // Enqueue the first binary number q.add(\"1\"); // This loops is like BFS of a tree with 1 as root // 0 as left child and 1 as right child and so on while (n-- > 0) { // print the front of queue String s1 = q.peek(); q.remove(); System.out.println(s1); // Store s1 before changing it String s2 = s1; // Append \"0\" to s1 and enqueue it q.add(s1 + \"0\"); // Append \"1\" to s2 and enqueue it. Note that s2 // contains the previous front q.add(s2 + \"1\"); } } // Driver program to test above function public static void main(String[] args) { int n = 10; generatePrintBinary(n); }}// This code is contributed by Sumit Ghosh", "e": 3610, "s": 2446, "text": null }, { "code": "# Python program to generate binary numbers from# 1 to n # This function uses queue data structure to print binary numbers def generatePrintBinary(n): # Create an empty queue from queue import Queue q = Queue() # Enqueue the first binary number q.put(\"1\") # This loop is like BFS of a tree with 1 as root # 0 as left child and 1 as right child and so on while(n > 0): n -= 1 # Print the front of queue s1 = q.get() print (s1) s2 = s1 # Store s1 before changing it # Append \"0\" to s1 and enqueue it q.put(s1+\"0\") # Append \"1\" to s2 and enqueue it. Note that s2 # contains the previous front q.put(s2+\"1\") # Driver program to test above functionn = 10generatePrintBinary(n) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)", "e": 4448, "s": 3610, "text": null }, { "code": "// C# program to generate binary// numbers from 1 to nusing System;using System.Collections.Generic; class GFG { // This function uses queue data // structure to print binary numbers public static void generatePrintBinary(int n) { // Create an empty queue of strings LinkedList<string> q = new LinkedList<string>(); // Enqueue the first binary number q.AddLast(\"1\"); // This loops is like BFS of a tree // with 1 as root 0 as left child // and 1 as right child and so on while (n-- > 0) { // print the front of queue string s1 = q.First.Value; q.RemoveFirst(); Console.WriteLine(s1); // Store s1 before changing it string s2 = s1; // Append \"0\" to s1 and enqueue it q.AddLast(s1 + \"0\"); // Append \"1\" to s2 and enqueue it. // Note that s2 contains the previous front q.AddLast(s2 + \"1\"); } } // Driver Code public static void Main(string[] args) { int n = 10; generatePrintBinary(n); }} // This code is contributed by Shrikant13", "e": 5608, "s": 4448, "text": null }, { "code": "<script> // JavaScript program to generate binary numbers from 1 to n // This function uses queue data structure to print binary// numbersfunction generatePrintBinary(n){ // Create an empty queue of strings var q = []; // Enqueue the first binary number q.push(\"1\"); // This loops is like BFS of a tree with 1 as root // 0 as left child and 1 as right child and so on while (n--) { // print the front of queue var s1 = q[0]; q.shift(); document.write( s1 + \"<br>\"); var s2 = s1; // Store s1 before changing it // Append \"0\" to s1 and enqueue it q.push(s1+\"0\"); // Append \"1\" to s2 and enqueue it. Note that s2 // contains the previous front q.push(s2+\"1\"); }} // Driver program to test above functionvar n = 10;generatePrintBinary(n); </script>", "e": 6452, "s": 5608, "text": null }, { "code": null, "e": 6491, "s": 6452, "text": "1\n10\n11\n100\n101\n110\n111\n1000\n1001\n1010" }, { "code": null, "e": 6514, "s": 6491, "text": "Time Complexity: O(n) " }, { "code": null, "e": 6579, "s": 6514, "text": "Space Complexity: O(n) as extra space is required in this method" }, { "code": null, "e": 6744, "s": 6579, "text": "This article is contributed by Abhishek. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 6756, "s": 6744, "text": "shrikanth13" }, { "code": null, "e": 6760, "s": 6756, "text": "gp6" }, { "code": null, "e": 6773, "s": 6760, "text": "kumarmenish8" }, { "code": null, "e": 6780, "s": 6773, "text": "rrrtnx" }, { "code": null, "e": 6796, "s": 6780, "text": "amartyaghoshgfg" }, { "code": null, "e": 6813, "s": 6796, "text": "surinderdawra388" }, { "code": null, "e": 6826, "s": 6813, "text": "technophpfij" }, { "code": null, "e": 6843, "s": 6826, "text": "hardikkoriintern" }, { "code": null, "e": 6850, "s": 6843, "text": "Amazon" }, { "code": null, "e": 6856, "s": 6850, "text": "Queue" }, { "code": null, "e": 6863, "s": 6856, "text": "Amazon" }, { "code": null, "e": 6869, "s": 6863, "text": "Queue" }, { "code": null, "e": 6967, "s": 6869, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6999, "s": 6967, "text": "Introduction to Data Structures" }, { "code": null, "e": 7055, "s": 6999, "text": "What is Priority Queue | Introduction to Priority Queue" }, { "code": null, "e": 7115, "s": 7055, "text": "Sliding Window Maximum (Maximum of all subarrays of size k)" }, { "code": null, "e": 7179, "s": 7115, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 7214, "s": 7179, "text": "Queue - Linked List Implementation" }, { "code": null, "e": 7264, "s": 7214, "text": "Minimum steps to reach target by a Knight | Set 1" }, { "code": null, "e": 7303, "s": 7264, "text": "Array implementation of queue (Simple)" }, { "code": null, "e": 7366, "s": 7303, "text": "Circular Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 7391, "s": 7366, "text": "Priority Queue in Python" } ]
Print Stack Elements from Bottom to Top
06 Aug, 2021 Given a stack s, the task is to print the elements of the stack from bottom to top, such that the elements are still present in the stack without their order being changed in the stack. Examples: Input : | 4 | | 3 | | 2 | | 1 | |________| Output :1 2 3 4 Approach 1 (Recursion): The idea is to pop the element of the stack and call the recursive function PrintStack. Once the stack becomes empty start printing the element which was popped last and the last element that was popped was the bottom-most element. Thus, elements will be printed from bottom to top. Now push back the element that was printed, this will preserve the order of the elements in the stack. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to print the elements of a// stack from bottom to top#include <bits/stdc++.h>using namespace std; // Recursive function to print stack elements// from bottom to top without changing// their ordervoid PrintStack(stack<int> s){ // If stack is empty then return if (s.empty()) return; int x = s.top(); // Pop the top element of the stack s.pop(); // Recursively call the function PrintStack PrintStack(s); // Print the stack element starting // from the bottom cout << x << " "; // Push the same element onto the stack // to preserve the order s.push(x);} // Driver codeint main(){ // Stack s stack<int> s; s.push(1); s.push(2); s.push(3); s.push(4); PrintStack(s); return 0;} // Java program to print the elements of a// stack from bottom to topimport java.util.*; class GfG{ // Recursive function to print stack elements// from bottom to top without changing// their orderstatic void PrintStack(Stack<Integer> s){ // If stack is empty then return if (s.isEmpty()) return; int x = s.peek(); // Pop the top element of the stack s.pop(); // Recursively call the function PrintStack PrintStack(s); // Print the stack element starting // from the bottom System.out.print(x + " "); // Push the same element onto the stack // to preserve the order s.push(x);} // Driver codepublic static void main(String[] args){ // Stack s Stack<Integer> s = new Stack<Integer> (); s.push(1); s.push(2); s.push(3); s.push(4); PrintStack(s);}} // This code is contributed by Prerna Saini. # Python3 program to print the elements of a# stack from bottom to top # Stack class with all functionality of a stackimport sysclass Stack: def __init__(self): self.s = [] def push(self, data): self.s.append(data) def pop(self): return self.s.pop() def peek(self): return self.s[-1] def count(self): return len(self.s) # Recursive function to print stack elements# from bottom to top without changing# their orderdef printStack(s): # if stack is empty then simply return if s.count() == 0: return x = s.peek() # pop top most element of the stack s.pop() # recursively call the function printStack printStack(s) # Print the stack element starting # from the bottom print("{} ".format(x), end = "") # Push the same element onto the stack # to preserve the order s.push(x) # Driver codeif __name__=='__main__': s=Stack() s.push(1) s.push(2) s.push(3) s.push(4) printStack(s) # This code is contributed by Vikas Kumar // C# program to print the elements of a// stack from bottom to topusing System;using System.Collections.Generic; class GfG{ // Recursive function to print stack elements// from bottom to top without changing// their orderstatic void PrintStack(Stack<int> s){ // If stack is empty then return if (s.Count == 0) return; int x = s.Peek(); // Pop the top element of the stack s.Pop(); // Recursively call the function PrintStack PrintStack(s); // Print the stack element starting // from the bottom Console.Write(x + " "); // Push the same element onto the stack // to preserve the order s.Push(x);} // Driver codepublic static void Main(){ // Stack s Stack<int> s = new Stack<int> (); s.Push(1); s.Push(2); s.Push(3); s.Push(4); PrintStack(s);}} /* This code contributed by PrinciRaj1992 */ <script> // Javascript program to print the elements// of a stack from bottom to top // Recursive function to print stack// elements from bottom to top without// changing their orderfunction PrintStack(s){ // If stack is empty then return if (s.length == 0) return; var x = s[s.length - 1]; // Pop the top element of the stack s.pop(); // Recursively call the function PrintStack PrintStack(s); // Print the stack element starting // from the bottom document.write(x + " "); // Push the same element onto the stack // to preserve the order s.push(x);} // Driver code // Stack svar s = [];s.push(1);s.push(2);s.push(3);s.push(4); PrintStack(s); // This code is contributed by importantly </script> 1 2 3 4 Time Complexity: O(N) Auxiliary Space: O(N) Approach 2 (Using another stack): The idea is to push every element into another temporary stack and then print elements of the temporary stack. C++ Java Python3 C# Javascript // C++ program to print the elements of a// stack from bottom to top#include <bits/stdc++.h>using namespace std; // Recursive function to print stack elements// from bottom to top without changing// their ordervoid PrintStack(stack<int> s){ stack<int> temp; while (s.empty() == false) { temp.push(s.top()); s.pop(); } while (temp.empty() == false) { int t = temp.top(); cout << t << " "; temp.pop(); // To restore contents of // the original stack. s.push(t); }} // Driver codeint main(){ // Stack s stack<int> s; s.push(1); s.push(2); s.push(3); s.push(4); PrintStack(s); return 0;} // Java program to print the// elements of a stack from// bottom to topimport java.util.*;class Main{ // Recursive function to print// stack elements from bottom// to top without changing// their orderpublic static void PrintStack(Stack<Integer> s){ Stack<Integer> temp = new Stack<Integer>(); while (s.empty() == false) { temp.push(s.peek()); s.pop(); } while (temp.empty() == false) { int t = temp.peek(); System.out.print(t + " "); temp.pop(); // To restore contents of // the original stack. s.push(t); }} // Driver codepublic static void main(String[] args){ // Stack s Stack<Integer> s = new Stack<Integer>(); s.push(1); s.push(2); s.push(3); s.push(4); PrintStack(s);}} // This code is contributed by divyeshrabadiya07 # Python3 program to print the elements of a# stack from bottom to top # Stack class with all functionality of a stackimport sysclass Stack: def __init__(self): self.s = [] def push(self, data): self.s.append(data) def pop(self): return self.s.pop() def peek(self): return self.s[-1] def count(self): return len(self.s) # Recursive function to print stack elements# from bottom to top without changing# their orderdef printStack(s): temp = Stack() while(s.count() > 0): temp.push(s.peek()) s.pop() while(temp.count() > 0): t = temp.peek() print("{} " . format(temp.peek()), end = "") temp.pop() # Restore the contents of original stack s.push(t) # Driver codeif __name__=='__main__': s = Stack() s.push(1) s.push(2) s.push(3) s.push(4) printStack(s) # This code is contributed by Vikash Kumar 37 // C# program to print the elements of// a stack from bottom to topusing System;using System.Collections; class GFG{ // Recursive function to print stack// elements from bottom to top without// changing their orderstatic void PrintStack(Stack s){ Stack temp = new Stack(); while (s.Count != 0) { temp.Push(s.Peek()); s.Pop(); } while (temp.Count != 0) { int t = (int)temp.Peek(); Console.Write(t + " "); temp.Pop(); // To restore contents of // the original stack. s.Push(t); }} // Driver Codepublic static void Main(string[] args){ // Stack s Stack s = new Stack(); s.Push(1); s.Push(2); s.Push(3); s.Push(4); PrintStack(s);}} // This code is contributed by rutvik_56 <script> // JavaScript program to print the elements of a// stack from bottom to top // Recursive function to print stack elements// from bottom to top without changing// their orderfunction PrintStack(s){ var temp = []; while (s.length!=0) { temp.push(s[s.length-1]); s.pop(); } while (temp.length!=0) { var t = temp[temp.length-1]; document.write( t + " "); temp.pop(); // To restore contents of // the original stack. s.push(t); }} // Driver code// Stack svar s = [];s.push(1);s.push(2);s.push(3);s.push(4);PrintStack(s); </script> 1 2 3 4 Time Complexity: O(N) Auxiliary Space: O(N) prerna saini princiraj1992 Vikash Kumar 37 rutvik_56 divyeshrabadiya07 importantly itsok pankajsharmagfg Data Structures Recursion Stack Data Structures Recursion Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar SDE SHEET - A Complete Guide for SDE Preparation What is Hashing | A Complete Tutorial Introduction to Data Structures Find if there is a path between two vertices in an undirected graph Write a program to print all permutations of a given string Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Tower of Hanoi Backtracking | Introduction
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Aug, 2021" }, { "code": null, "e": 240, "s": 54, "text": "Given a stack s, the task is to print the elements of the stack from bottom to top, such that the elements are still present in the stack without their order being changed in the stack." }, { "code": null, "e": 251, "s": 240, "text": "Examples: " }, { "code": null, "e": 348, "s": 251, "text": "Input : \n \n \n| 4 |\n| 3 |\n| 2 |\n| 1 |\n|________|\n\nOutput :1 2 3 4" }, { "code": null, "e": 758, "s": 348, "text": "Approach 1 (Recursion): The idea is to pop the element of the stack and call the recursive function PrintStack. Once the stack becomes empty start printing the element which was popped last and the last element that was popped was the bottom-most element. Thus, elements will be printed from bottom to top. Now push back the element that was printed, this will preserve the order of the elements in the stack." }, { "code": null, "e": 809, "s": 758, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 813, "s": 809, "text": "C++" }, { "code": null, "e": 818, "s": 813, "text": "Java" }, { "code": null, "e": 826, "s": 818, "text": "Python3" }, { "code": null, "e": 829, "s": 826, "text": "C#" }, { "code": null, "e": 840, "s": 829, "text": "Javascript" }, { "code": "// C++ program to print the elements of a// stack from bottom to top#include <bits/stdc++.h>using namespace std; // Recursive function to print stack elements// from bottom to top without changing// their ordervoid PrintStack(stack<int> s){ // If stack is empty then return if (s.empty()) return; int x = s.top(); // Pop the top element of the stack s.pop(); // Recursively call the function PrintStack PrintStack(s); // Print the stack element starting // from the bottom cout << x << \" \"; // Push the same element onto the stack // to preserve the order s.push(x);} // Driver codeint main(){ // Stack s stack<int> s; s.push(1); s.push(2); s.push(3); s.push(4); PrintStack(s); return 0;}", "e": 1612, "s": 840, "text": null }, { "code": "// Java program to print the elements of a// stack from bottom to topimport java.util.*; class GfG{ // Recursive function to print stack elements// from bottom to top without changing// their orderstatic void PrintStack(Stack<Integer> s){ // If stack is empty then return if (s.isEmpty()) return; int x = s.peek(); // Pop the top element of the stack s.pop(); // Recursively call the function PrintStack PrintStack(s); // Print the stack element starting // from the bottom System.out.print(x + \" \"); // Push the same element onto the stack // to preserve the order s.push(x);} // Driver codepublic static void main(String[] args){ // Stack s Stack<Integer> s = new Stack<Integer> (); s.push(1); s.push(2); s.push(3); s.push(4); PrintStack(s);}} // This code is contributed by Prerna Saini.", "e": 2481, "s": 1612, "text": null }, { "code": "# Python3 program to print the elements of a# stack from bottom to top # Stack class with all functionality of a stackimport sysclass Stack: def __init__(self): self.s = [] def push(self, data): self.s.append(data) def pop(self): return self.s.pop() def peek(self): return self.s[-1] def count(self): return len(self.s) # Recursive function to print stack elements# from bottom to top without changing# their orderdef printStack(s): # if stack is empty then simply return if s.count() == 0: return x = s.peek() # pop top most element of the stack s.pop() # recursively call the function printStack printStack(s) # Print the stack element starting # from the bottom print(\"{} \".format(x), end = \"\") # Push the same element onto the stack # to preserve the order s.push(x) # Driver codeif __name__=='__main__': s=Stack() s.push(1) s.push(2) s.push(3) s.push(4) printStack(s) # This code is contributed by Vikas Kumar", "e": 3539, "s": 2481, "text": null }, { "code": "// C# program to print the elements of a// stack from bottom to topusing System;using System.Collections.Generic; class GfG{ // Recursive function to print stack elements// from bottom to top without changing// their orderstatic void PrintStack(Stack<int> s){ // If stack is empty then return if (s.Count == 0) return; int x = s.Peek(); // Pop the top element of the stack s.Pop(); // Recursively call the function PrintStack PrintStack(s); // Print the stack element starting // from the bottom Console.Write(x + \" \"); // Push the same element onto the stack // to preserve the order s.Push(x);} // Driver codepublic static void Main(){ // Stack s Stack<int> s = new Stack<int> (); s.Push(1); s.Push(2); s.Push(3); s.Push(4); PrintStack(s);}} /* This code contributed by PrinciRaj1992 */", "e": 4406, "s": 3539, "text": null }, { "code": "<script> // Javascript program to print the elements// of a stack from bottom to top // Recursive function to print stack// elements from bottom to top without// changing their orderfunction PrintStack(s){ // If stack is empty then return if (s.length == 0) return; var x = s[s.length - 1]; // Pop the top element of the stack s.pop(); // Recursively call the function PrintStack PrintStack(s); // Print the stack element starting // from the bottom document.write(x + \" \"); // Push the same element onto the stack // to preserve the order s.push(x);} // Driver code // Stack svar s = [];s.push(1);s.push(2);s.push(3);s.push(4); PrintStack(s); // This code is contributed by importantly </script>", "e": 5163, "s": 4406, "text": null }, { "code": null, "e": 5171, "s": 5163, "text": "1 2 3 4" }, { "code": null, "e": 5218, "s": 5173, "text": "Time Complexity: O(N) Auxiliary Space: O(N) " }, { "code": null, "e": 5364, "s": 5218, "text": "Approach 2 (Using another stack): The idea is to push every element into another temporary stack and then print elements of the temporary stack. " }, { "code": null, "e": 5368, "s": 5364, "text": "C++" }, { "code": null, "e": 5373, "s": 5368, "text": "Java" }, { "code": null, "e": 5381, "s": 5373, "text": "Python3" }, { "code": null, "e": 5384, "s": 5381, "text": "C#" }, { "code": null, "e": 5395, "s": 5384, "text": "Javascript" }, { "code": "// C++ program to print the elements of a// stack from bottom to top#include <bits/stdc++.h>using namespace std; // Recursive function to print stack elements// from bottom to top without changing// their ordervoid PrintStack(stack<int> s){ stack<int> temp; while (s.empty() == false) { temp.push(s.top()); s.pop(); } while (temp.empty() == false) { int t = temp.top(); cout << t << \" \"; temp.pop(); // To restore contents of // the original stack. s.push(t); }} // Driver codeint main(){ // Stack s stack<int> s; s.push(1); s.push(2); s.push(3); s.push(4); PrintStack(s); return 0;}", "e": 6088, "s": 5395, "text": null }, { "code": "// Java program to print the// elements of a stack from// bottom to topimport java.util.*;class Main{ // Recursive function to print// stack elements from bottom// to top without changing// their orderpublic static void PrintStack(Stack<Integer> s){ Stack<Integer> temp = new Stack<Integer>(); while (s.empty() == false) { temp.push(s.peek()); s.pop(); } while (temp.empty() == false) { int t = temp.peek(); System.out.print(t + \" \"); temp.pop(); // To restore contents of // the original stack. s.push(t); }} // Driver codepublic static void main(String[] args){ // Stack s Stack<Integer> s = new Stack<Integer>(); s.push(1); s.push(2); s.push(3); s.push(4); PrintStack(s);}} // This code is contributed by divyeshrabadiya07", "e": 6863, "s": 6088, "text": null }, { "code": "# Python3 program to print the elements of a# stack from bottom to top # Stack class with all functionality of a stackimport sysclass Stack: def __init__(self): self.s = [] def push(self, data): self.s.append(data) def pop(self): return self.s.pop() def peek(self): return self.s[-1] def count(self): return len(self.s) # Recursive function to print stack elements# from bottom to top without changing# their orderdef printStack(s): temp = Stack() while(s.count() > 0): temp.push(s.peek()) s.pop() while(temp.count() > 0): t = temp.peek() print(\"{} \" . format(temp.peek()), end = \"\") temp.pop() # Restore the contents of original stack s.push(t) # Driver codeif __name__=='__main__': s = Stack() s.push(1) s.push(2) s.push(3) s.push(4) printStack(s) # This code is contributed by Vikash Kumar 37", "e": 7799, "s": 6863, "text": null }, { "code": "// C# program to print the elements of// a stack from bottom to topusing System;using System.Collections; class GFG{ // Recursive function to print stack// elements from bottom to top without// changing their orderstatic void PrintStack(Stack s){ Stack temp = new Stack(); while (s.Count != 0) { temp.Push(s.Peek()); s.Pop(); } while (temp.Count != 0) { int t = (int)temp.Peek(); Console.Write(t + \" \"); temp.Pop(); // To restore contents of // the original stack. s.Push(t); }} // Driver Codepublic static void Main(string[] args){ // Stack s Stack s = new Stack(); s.Push(1); s.Push(2); s.Push(3); s.Push(4); PrintStack(s);}} // This code is contributed by rutvik_56", "e": 8579, "s": 7799, "text": null }, { "code": "<script> // JavaScript program to print the elements of a// stack from bottom to top // Recursive function to print stack elements// from bottom to top without changing// their orderfunction PrintStack(s){ var temp = []; while (s.length!=0) { temp.push(s[s.length-1]); s.pop(); } while (temp.length!=0) { var t = temp[temp.length-1]; document.write( t + \" \"); temp.pop(); // To restore contents of // the original stack. s.push(t); }} // Driver code// Stack svar s = [];s.push(1);s.push(2);s.push(3);s.push(4);PrintStack(s); </script>", "e": 9197, "s": 8579, "text": null }, { "code": null, "e": 9205, "s": 9197, "text": "1 2 3 4" }, { "code": null, "e": 9251, "s": 9207, "text": "Time Complexity: O(N) Auxiliary Space: O(N)" }, { "code": null, "e": 9264, "s": 9251, "text": "prerna saini" }, { "code": null, "e": 9278, "s": 9264, "text": "princiraj1992" }, { "code": null, "e": 9294, "s": 9278, "text": "Vikash Kumar 37" }, { "code": null, "e": 9304, "s": 9294, "text": "rutvik_56" }, { "code": null, "e": 9322, "s": 9304, "text": "divyeshrabadiya07" }, { "code": null, "e": 9334, "s": 9322, "text": "importantly" }, { "code": null, "e": 9340, "s": 9334, "text": "itsok" }, { "code": null, "e": 9356, "s": 9340, "text": "pankajsharmagfg" }, { "code": null, "e": 9372, "s": 9356, "text": "Data Structures" }, { "code": null, "e": 9382, "s": 9372, "text": "Recursion" }, { "code": null, "e": 9388, "s": 9382, "text": "Stack" }, { "code": null, "e": 9404, "s": 9388, "text": "Data Structures" }, { "code": null, "e": 9414, "s": 9404, "text": "Recursion" }, { "code": null, "e": 9420, "s": 9414, "text": "Stack" }, { "code": null, "e": 9518, "s": 9420, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9543, "s": 9518, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 9592, "s": 9543, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 9630, "s": 9592, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 9662, "s": 9630, "text": "Introduction to Data Structures" }, { "code": null, "e": 9730, "s": 9662, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 9790, "s": 9730, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 9875, "s": 9790, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 9885, "s": 9875, "text": "Recursion" }, { "code": null, "e": 9912, "s": 9885, "text": "Program for Tower of Hanoi" } ]
iText - Formatting the Borders of a Cell
In this chapter, we will see how to format the borders of a cell in a table using iText library. You can create an empty PDF Document by instantiating the Document class. While instantiating this class, you need to pass a PdfDocument object as a parameter to its constructor. Then, to add a table to the document, you need to instantiate the Table class and add this object to the document using the add() method. You can add various types of borders like DashedBorder, SolidBorder, DottedBorder, DoubleBorder, RoundDotsBorder, etc. with various colors using the setBorder() method of the Cell class. Following are the steps to format the borders of a cell in a table. The PdfWriter class represents the DocWriter for a PDF. This class belongs to the package com.itextpdf.kernel.pdf. The constructor of this class accepts a string, representing the path of the file where the PDF is to be created. Instantiate the PdfWriter class by passing a string value (representing the path where you need to create a PDF) to its constructor, as shown below. // Creating a PdfWriter String dest = "C:/itextExamples/coloredBorders.pdf"; PdfWriter writer = new PdfWriter(dest); When an object of this type is passed to a PdfDocument (class), every element added to this document will be written to the file specified. The PdfDocument class is the class that represents the PDFDocument in iText. This class belongs to the package com.itextpdf.kernel.pdf. To instantiate this class (in writing mode), you need to pass an object of the class PdfWriter to its constructor. Instantiate the PdfDocument class by passing the above created PdfWriter object to its constructor, as shown below. // Creating a PdfDocument PdfDocument pdfDoc = new PdfDocument(writer); Once a PdfDocument object is created, you can add various elements like page, font, file attachment, and event handler using the respective methods provided by its class. The Document class of the package com.itextpdf.layout is the root element while creating a self-sufficient PDF. One of the constructors of this class accepts an object of the class PdfDocument. Instantiate the Document class by passing the object of the class PdfDocument created in the previous steps, as shown below. // Creating a Document Document document = new Document(pdfDoc); The Table class represents a two-dimensional grid filled with cells ordered in rows and columns. It belongs to the package com.itextpdf.layout.element. Instantiate the Table class as shown below. // Creating a table float [] pointColumnWidths = {200F, 200F}; Table table = new Table(pointColumnWidths); Create a cell object by instantiating the Cell class of the package com.itextpdf.layout.element add the contents of the cell using the add() method of the Cell class, as shown below. // Adding cell 1 to the table Cell cell1 = new Cell(); // Creating a cell cell1.add("Name"); // Adding content to the cell The iText library provides various classes representing the border such as DashedBorder, SolidBorder, DottedBorder, DoubleBorder, RoundDotsBorder, etc. The constructors of these classes accept two parameters: a color object representing the color of the border and an integer representing the width of the border. Choose one of this border types and instantiate the respective border by passing the color object and an integer representing the width, as shown below. Border b1 = new DashedBorder(Color.RED, 3); Now, set the border of the cell using the setBorder() method of the cell class. This method accepts an object of the type Border as a parameter. Set the border of the cell by passing the above created Border object as a parameter to the setBorder() method as shown below. c1.setBorder(b1) Finally, to add this cell to the table, call the addCell() method of the Table class and pass the cell object as a parameter to this method, as shown below. table.addCell(c1); Add the table object created in the previous step using the add() method of the Document class, as shown below. // Adding list to the document document.add(table); Close the document using the close() method of the Document class, as shown below. // Closing the document document.close(); The following Java program demonstrates how to format the border of a cell in a table using the iText library. It creates a PDF document with the name coloredBorders.pdf, adds a table to it, formats the contents of its cells, and saves it in the path C:/itextExamples/ Save this code in a file with the name FormatedBorders.java. import com.itextpdf.kernel.color.Color; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.layout.Document; import com.itextpdf.layout.border.Border; import com.itextpdf.layout.border.DashedBorder; import com.itextpdf.layout.border.DottedBorder; import com.itextpdf.layout.border.DoubleBorder; import com.itextpdf.layout.border.RoundDotsBorder; import com.itextpdf.layout.border.SolidBorder; import com.itextpdf.layout.element.Cell; import com.itextpdf.layout.element.Table; import com.itextpdf.layout.property.TextAlignment; public class FormatedBorders { public static void main(String args[]) throws Exception { // Creating a PdfWriter object String dest = "C:/itextExamples/coloredBorders.pdf"; PdfWriter writer = new PdfWriter(dest); // Creating a PdfDocument object PdfDocument pdfDoc = new PdfDocument(writer); // Creating a Document object Document doc = new Document(pdfDoc); // Creating a table float [] pointColumnWidths = {200F, 200F}; Table table = new Table(pointColumnWidths); // Adding row 1 to the table Cell c1 = new Cell(); // Adding the contents of the cell c1.add("Name"); // Setting the back ground color of the cell c1.setBackgroundColor(Color.DARK_GRAY); // Instantiating the Border class Border b1 = new DashedBorder(Color.RED, 3); // Setting the border of the cell c1.setBorder(b1); // Setting the text alignment c1.setTextAlignment(TextAlignment.CENTER); // Adding the cell to the table table.addCell(c1); Cell c2 = new Cell(); c2.add("Raju"); c1.setBorder(new SolidBorder(Color.RED, 3)); c2.setTextAlignment(TextAlignment.CENTER); table.addCell(c2); // Adding row 2 to the table Cell c3 = new Cell(); c3.add("Id"); c3.setBorder(new DottedBorder(Color.DARK_GRAY, 3)); c3.setTextAlignment(TextAlignment.CENTER); table.addCell(c3); Cell c4 = new Cell(); c4.add("001"); c4.setBorder(new DoubleBorder(Color.DARK_GRAY, 3)); c4.setTextAlignment(TextAlignment.CENTER); table.addCell(c4); // Adding row 3 to the table Cell c5 = new Cell(); c5.add("Designation"); c5.setBorder(new RoundDotsBorder(Color.RED, 3)); c5.setTextAlignment(TextAlignment.CENTER); table.addCell(c5); Cell c6 = new Cell(); c6.add("Programmer"); c6.setBorder(new RoundDotsBorder(Color.RED, 3)); c6.setTextAlignment(TextAlignment.CENTER); table.addCell(c6); // Adding Table to document doc.add(table); // Closing the document doc.close(); System.out.println("Borders added successfully.."); } } Compile and execute the saved Java file from the Command prompt using the following commands − javac FormatedBorders.java java FormatedBorders Upon execution, the above program creates a PDF document, displaying the following message. Borders added successfully If you verify the specified path, you can find the created PDF document, as shown below.
[ { "code": null, "e": 2599, "s": 2502, "text": "In this chapter, we will see how to format the borders of a cell in a table using iText library." }, { "code": null, "e": 2778, "s": 2599, "text": "You can create an empty PDF Document by instantiating the Document class. While instantiating this class, you need to pass a PdfDocument object as a parameter to its constructor." }, { "code": null, "e": 2916, "s": 2778, "text": "Then, to add a table to the document, you need to instantiate the Table class and add this object to the document using the add() method." }, { "code": null, "e": 3103, "s": 2916, "text": "You can add various types of borders like DashedBorder, SolidBorder, DottedBorder, DoubleBorder, RoundDotsBorder, etc. with various colors using the setBorder() method of the Cell class." }, { "code": null, "e": 3171, "s": 3103, "text": "Following are the steps to format the borders of a cell in a table." }, { "code": null, "e": 3400, "s": 3171, "text": "The PdfWriter class represents the DocWriter for a PDF. This class belongs to the package com.itextpdf.kernel.pdf. The constructor of this class accepts a string, representing the path of the file where the PDF is to be created." }, { "code": null, "e": 3549, "s": 3400, "text": "Instantiate the PdfWriter class by passing a string value (representing the path where you need to create a PDF) to its constructor, as shown below." }, { "code": null, "e": 3670, "s": 3549, "text": "// Creating a PdfWriter \nString dest = \"C:/itextExamples/coloredBorders.pdf\"; \nPdfWriter writer = new PdfWriter(dest); \n" }, { "code": null, "e": 3810, "s": 3670, "text": "When an object of this type is passed to a PdfDocument (class), every element added to this document will be written to the file specified." }, { "code": null, "e": 4061, "s": 3810, "text": "The PdfDocument class is the class that represents the PDFDocument in iText. This class belongs to the package com.itextpdf.kernel.pdf. To instantiate this class (in writing mode), you need to pass an object of the class PdfWriter to its constructor." }, { "code": null, "e": 4177, "s": 4061, "text": "Instantiate the PdfDocument class by passing the above created PdfWriter object to its constructor, as shown below." }, { "code": null, "e": 4253, "s": 4177, "text": "// Creating a PdfDocument \nPdfDocument pdfDoc = new PdfDocument(writer); \n" }, { "code": null, "e": 4424, "s": 4253, "text": "Once a PdfDocument object is created, you can add various elements like page, font, file attachment, and event handler using the respective methods provided by its class." }, { "code": null, "e": 4618, "s": 4424, "text": "The Document class of the package com.itextpdf.layout is the root element while creating a self-sufficient PDF. One of the constructors of this class accepts an object of the class PdfDocument." }, { "code": null, "e": 4743, "s": 4618, "text": "Instantiate the Document class by passing the object of the class PdfDocument created in the previous steps, as shown below." }, { "code": null, "e": 4812, "s": 4743, "text": "// Creating a Document \nDocument document = new Document(pdfDoc); \n" }, { "code": null, "e": 4964, "s": 4812, "text": "The Table class represents a two-dimensional grid filled with cells ordered in rows and columns. It belongs to the package com.itextpdf.layout.element." }, { "code": null, "e": 5008, "s": 4964, "text": "Instantiate the Table class as shown below." }, { "code": null, "e": 5119, "s": 5008, "text": "// Creating a table \nfloat [] pointColumnWidths = {200F, 200F}; \nTable table = new Table(pointColumnWidths); \n" }, { "code": null, "e": 5302, "s": 5119, "text": "Create a cell object by instantiating the Cell class of the package com.itextpdf.layout.element add the contents of the cell using the add() method of the Cell class, as shown below." }, { "code": null, "e": 5435, "s": 5302, "text": "// Adding cell 1 to the table \nCell cell1 = new Cell(); // Creating a cell \ncell1.add(\"Name\"); // Adding content to the cell \n" }, { "code": null, "e": 5587, "s": 5435, "text": "The iText library provides various classes representing the border such as DashedBorder, SolidBorder, DottedBorder, DoubleBorder, RoundDotsBorder, etc." }, { "code": null, "e": 5749, "s": 5587, "text": "The constructors of these classes accept two parameters: a color object representing the color of the border and an integer representing the width of the border." }, { "code": null, "e": 5902, "s": 5749, "text": "Choose one of this border types and instantiate the respective border by passing the color object and an integer representing the width, as shown below." }, { "code": null, "e": 5948, "s": 5902, "text": "Border b1 = new DashedBorder(Color.RED, 3); \n" }, { "code": null, "e": 6093, "s": 5948, "text": "Now, set the border of the cell using the setBorder() method of the cell class. This method accepts an object of the type Border as a parameter." }, { "code": null, "e": 6220, "s": 6093, "text": "Set the border of the cell by passing the above created Border object as a parameter to the setBorder() method as shown below." }, { "code": null, "e": 6238, "s": 6220, "text": "c1.setBorder(b1)\n" }, { "code": null, "e": 6395, "s": 6238, "text": "Finally, to add this cell to the table, call the addCell() method of the Table class and pass the cell object as a parameter to this method, as shown below." }, { "code": null, "e": 6415, "s": 6395, "text": "table.addCell(c1);\n" }, { "code": null, "e": 6527, "s": 6415, "text": "Add the table object created in the previous step using the add() method of the Document class, as shown below." }, { "code": null, "e": 6581, "s": 6527, "text": "// Adding list to the document \ndocument.add(table);\n" }, { "code": null, "e": 6664, "s": 6581, "text": "Close the document using the close() method of the Document class, as shown below." }, { "code": null, "e": 6708, "s": 6664, "text": "// Closing the document \ndocument.close();\n" }, { "code": null, "e": 6977, "s": 6708, "text": "The following Java program demonstrates how to format the border of a cell in a table using the iText library. It creates a PDF document with the name coloredBorders.pdf, adds a table to it, formats the contents of its cells, and saves it in the path C:/itextExamples/" }, { "code": null, "e": 7038, "s": 6977, "text": "Save this code in a file with the name FormatedBorders.java." }, { "code": null, "e": 10381, "s": 7038, "text": "import com.itextpdf.kernel.color.Color; \nimport com.itextpdf.kernel.pdf.PdfDocument; \nimport com.itextpdf.kernel.pdf.PdfWriter; \n\nimport com.itextpdf.layout.Document; \nimport com.itextpdf.layout.border.Border; \nimport com.itextpdf.layout.border.DashedBorder; \nimport com.itextpdf.layout.border.DottedBorder; \nimport com.itextpdf.layout.border.DoubleBorder; \nimport com.itextpdf.layout.border.RoundDotsBorder; \nimport com.itextpdf.layout.border.SolidBorder; \n\nimport com.itextpdf.layout.element.Cell; \nimport com.itextpdf.layout.element.Table; \nimport com.itextpdf.layout.property.TextAlignment; \n\npublic class FormatedBorders { \n public static void main(String args[]) throws Exception {\n // Creating a PdfWriter object \n String dest = \"C:/itextExamples/coloredBorders.pdf\"; \n \n PdfWriter writer = new \n PdfWriter(dest); \n\n // Creating a PdfDocument object \n PdfDocument pdfDoc = new PdfDocument(writer); \n \n // Creating a Document object \n Document doc = new Document(pdfDoc); \n \n // Creating a table \n float [] pointColumnWidths = {200F, 200F}; \n Table table = new Table(pointColumnWidths); \n \n // Adding row 1 to the table\n Cell c1 = new Cell();\n \n // Adding the contents of the cell\n c1.add(\"Name\");\n \n // Setting the back ground color of the cell\n c1.setBackgroundColor(Color.DARK_GRAY); \n \n // Instantiating the Border class \n Border b1 = new DashedBorder(Color.RED, 3);\n \n // Setting the border of the cell\n c1.setBorder(b1);\n \n // Setting the text alignment \n c1.setTextAlignment(TextAlignment.CENTER);\n \n // Adding the cell to the table \n table.addCell(c1); \n Cell c2 = new Cell(); \n c2.add(\"Raju\"); \n c1.setBorder(new SolidBorder(Color.RED, 3)); \n c2.setTextAlignment(TextAlignment.CENTER); \n table.addCell(c2);\n \n // Adding row 2 to the table \n Cell c3 = new Cell(); \n c3.add(\"Id\"); \n c3.setBorder(new DottedBorder(Color.DARK_GRAY, 3)); \n c3.setTextAlignment(TextAlignment.CENTER); \n table.addCell(c3); \n \n Cell c4 = new Cell(); \n c4.add(\"001\"); \n c4.setBorder(new DoubleBorder(Color.DARK_GRAY, 3)); \n c4.setTextAlignment(TextAlignment.CENTER); \n table.addCell(c4); \n \n // Adding row 3 to the table \n Cell c5 = new Cell(); \n c5.add(\"Designation\"); \n c5.setBorder(new RoundDotsBorder(Color.RED, 3)); \n c5.setTextAlignment(TextAlignment.CENTER); \n table.addCell(c5); \n \n Cell c6 = new Cell(); \n c6.add(\"Programmer\"); \n c6.setBorder(new RoundDotsBorder(Color.RED, 3)); \n c6.setTextAlignment(TextAlignment.CENTER); \n table.addCell(c6); \n \n // Adding Table to document \n doc.add(table); \n \n // Closing the document \n doc.close(); \n \n System.out.println(\"Borders added successfully..\"); \n } \n} " }, { "code": null, "e": 10476, "s": 10381, "text": "Compile and execute the saved Java file from the Command prompt using the following commands −" }, { "code": null, "e": 10526, "s": 10476, "text": "javac FormatedBorders.java \njava FormatedBorders\n" }, { "code": null, "e": 10618, "s": 10526, "text": "Upon execution, the above program creates a PDF document, displaying the following message." }, { "code": null, "e": 10646, "s": 10618, "text": "Borders added successfully\n" } ]
Sum of all odd natural numbers in range L and R
11 Jul, 2022 Given two integers L and R, the task is to find the sum of all odd natural numbers in range L and R inclusive. Examples: Input: L = 2, R = 5 Output: 8 3 + 5 = 8 Input: L = 7, R = 13 Output: 40 A naive approach is to traverse from L to R and summate the elements to get the answer. An efficient approach is to use the formula for calculating the sum of all odd natural numbers upto R and L-1 and then subtract sum(R)-sum(L-1).Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to print the sum// of all numbers in range L and R#include <bits/stdc++.h>using namespace std; // Function to return the sum of// all odd natural numbersint sumOdd(int n){ int terms = (n + 1) / 2; int sum = terms * terms; return sum;} // Function to return the sum// of all odd numbers in range L and Rint suminRange(int l, int r){ return sumOdd(r) - sumOdd(l - 1);} // Driver Codeint main(){ int l = 2, r = 5; cout << "Sum of odd natural numbers from L to R is " << suminRange(l, r); return 0;} // Java program to print the sum// of all numbers in range L and R import java.io.*; class GFG { // Function to return the sum of// all odd natural numbersstatic int sumOdd(int n){ int terms = (n + 1) / 2; int sum = terms * terms; return sum;} // Function to return the sum// of all odd numbers in range L and Rstatic int suminRange(int l, int r){ return sumOdd(r) - sumOdd(l - 1);} // Driver Codepublic static void main (String[] args) { int l = 2, r = 5; System.out.print( "Sum of odd natural numbers from L to R is " + suminRange(l, r)); }}// This code is contributed by shs.. # Python 3 program to print the sum# of all numbers in range L and R # Function to return the sum of# all odd natural numbersdef sumOdd(n): terms = (n + 1)//2 sum1 = terms * terms return sum1 # Function to return the sum# of all odd numbers in range L and Rdef suminRange(l, r): return sumOdd(r) - sumOdd(l - 1) # Driver codel = 2; r = 5print("Sum of odd natural number", "from L to R is", suminRange(l, r)) # This code is contributed by Shrikant13 // C# program to print the sum// of all numbers in range L and Rusing System; class GFG{ // Function to return the sum of// all odd natural numbersstatic int sumOdd(int n){ int terms = (n + 1) / 2; int sum = terms * terms; return sum;} // Function to return the sum// of all odd numbers in range L and Rstatic int suminRange(int l, int r){ return sumOdd(r) - sumOdd(l - 1);} // Driver Codepublic static void Main (){ int l = 2, r = 5; Console.WriteLine( "Sum of odd natural numbers " + "from L to R is " + suminRange(l, r));}} // This code is contributed by shs.. <?php//PHP program to print the sum// of all numbers in range L and R// Function to return the sum of// all odd natural numbersfunction sumOdd($n){ $terms = (int)($n + 1) / 2; $sum = $terms * $terms; return $sum;} // Function to return the sum// of all odd numbers in range L and Rfunction suminRange($l, $r){ return sumOdd($r) - sumOdd($l - 1);} // Driver Code $l = 2; $r = 5; echo "Sum of odd natural numbers from L to R is ", suminRange($l, $r); ?> <script> //JavaScript program to print the sum// of all numbers in range L and R // Function to return the sum of// all odd natural numbersfunction sumOdd(n){ terms = (n + 1) / 2; sum = terms * terms; return sum;} // Function to return the sum// of all odd numbers in range L and Rfunction suminRange(l, r){ return sumOdd(r) - sumOdd(l - 1);} // Driver Code let l = 2;let r = 5; document.write("Sum of odd natural numbers from L to R is "+ suminRange(l, r)); // This code is contributed by sravan kumar </script> Sum of odd natural numbers from L to R is 8 Time Complexity: O(1) Auxiliary Space: O(1) Shashank12 Sach_Code shrikanth13 sravankumar8128 subhammahato348 series series-sum Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Jul, 2022" }, { "code": null, "e": 150, "s": 28, "text": "Given two integers L and R, the task is to find the sum of all odd natural numbers in range L and R inclusive. Examples: " }, { "code": null, "e": 223, "s": 150, "text": "Input: L = 2, R = 5\nOutput: 8\n3 + 5 = 8\n\nInput: L = 7, R = 13\nOutput: 40" }, { "code": null, "e": 508, "s": 223, "text": "A naive approach is to traverse from L to R and summate the elements to get the answer. An efficient approach is to use the formula for calculating the sum of all odd natural numbers upto R and L-1 and then subtract sum(R)-sum(L-1).Below is the implementation of the above approach: " }, { "code": null, "e": 512, "s": 508, "text": "C++" }, { "code": null, "e": 517, "s": 512, "text": "Java" }, { "code": null, "e": 525, "s": 517, "text": "Python3" }, { "code": null, "e": 528, "s": 525, "text": "C#" }, { "code": null, "e": 532, "s": 528, "text": "PHP" }, { "code": null, "e": 543, "s": 532, "text": "Javascript" }, { "code": "// C++ program to print the sum// of all numbers in range L and R#include <bits/stdc++.h>using namespace std; // Function to return the sum of// all odd natural numbersint sumOdd(int n){ int terms = (n + 1) / 2; int sum = terms * terms; return sum;} // Function to return the sum// of all odd numbers in range L and Rint suminRange(int l, int r){ return sumOdd(r) - sumOdd(l - 1);} // Driver Codeint main(){ int l = 2, r = 5; cout << \"Sum of odd natural numbers from L to R is \" << suminRange(l, r); return 0;}", "e": 1084, "s": 543, "text": null }, { "code": "// Java program to print the sum// of all numbers in range L and R import java.io.*; class GFG { // Function to return the sum of// all odd natural numbersstatic int sumOdd(int n){ int terms = (n + 1) / 2; int sum = terms * terms; return sum;} // Function to return the sum// of all odd numbers in range L and Rstatic int suminRange(int l, int r){ return sumOdd(r) - sumOdd(l - 1);} // Driver Codepublic static void main (String[] args) { int l = 2, r = 5; System.out.print( \"Sum of odd natural numbers from L to R is \" + suminRange(l, r)); }}// This code is contributed by shs..", "e": 1705, "s": 1084, "text": null }, { "code": "# Python 3 program to print the sum# of all numbers in range L and R # Function to return the sum of# all odd natural numbersdef sumOdd(n): terms = (n + 1)//2 sum1 = terms * terms return sum1 # Function to return the sum# of all odd numbers in range L and Rdef suminRange(l, r): return sumOdd(r) - sumOdd(l - 1) # Driver codel = 2; r = 5print(\"Sum of odd natural number\", \"from L to R is\", suminRange(l, r)) # This code is contributed by Shrikant13", "e": 2175, "s": 1705, "text": null }, { "code": "// C# program to print the sum// of all numbers in range L and Rusing System; class GFG{ // Function to return the sum of// all odd natural numbersstatic int sumOdd(int n){ int terms = (n + 1) / 2; int sum = terms * terms; return sum;} // Function to return the sum// of all odd numbers in range L and Rstatic int suminRange(int l, int r){ return sumOdd(r) - sumOdd(l - 1);} // Driver Codepublic static void Main (){ int l = 2, r = 5; Console.WriteLine( \"Sum of odd natural numbers \" + \"from L to R is \" + suminRange(l, r));}} // This code is contributed by shs..", "e": 2776, "s": 2175, "text": null }, { "code": "<?php//PHP program to print the sum// of all numbers in range L and R// Function to return the sum of// all odd natural numbersfunction sumOdd($n){ $terms = (int)($n + 1) / 2; $sum = $terms * $terms; return $sum;} // Function to return the sum// of all odd numbers in range L and Rfunction suminRange($l, $r){ return sumOdd($r) - sumOdd($l - 1);} // Driver Code $l = 2; $r = 5; echo \"Sum of odd natural numbers from L to R is \", suminRange($l, $r); ?>", "e": 3259, "s": 2776, "text": null }, { "code": "<script> //JavaScript program to print the sum// of all numbers in range L and R // Function to return the sum of// all odd natural numbersfunction sumOdd(n){ terms = (n + 1) / 2; sum = terms * terms; return sum;} // Function to return the sum// of all odd numbers in range L and Rfunction suminRange(l, r){ return sumOdd(r) - sumOdd(l - 1);} // Driver Code let l = 2;let r = 5; document.write(\"Sum of odd natural numbers from L to R is \"+ suminRange(l, r)); // This code is contributed by sravan kumar </script>", "e": 3808, "s": 3259, "text": null }, { "code": null, "e": 3852, "s": 3808, "text": "Sum of odd natural numbers from L to R is 8" }, { "code": null, "e": 3876, "s": 3854, "text": "Time Complexity: O(1)" }, { "code": null, "e": 3898, "s": 3876, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 3909, "s": 3898, "text": "Shashank12" }, { "code": null, "e": 3919, "s": 3909, "text": "Sach_Code" }, { "code": null, "e": 3931, "s": 3919, "text": "shrikanth13" }, { "code": null, "e": 3947, "s": 3931, "text": "sravankumar8128" }, { "code": null, "e": 3963, "s": 3947, "text": "subhammahato348" }, { "code": null, "e": 3970, "s": 3963, "text": "series" }, { "code": null, "e": 3981, "s": 3970, "text": "series-sum" }, { "code": null, "e": 3994, "s": 3981, "text": "Mathematical" }, { "code": null, "e": 4007, "s": 3994, "text": "Mathematical" }, { "code": null, "e": 4014, "s": 4007, "text": "series" } ]
HTML | Layout
15 Jun, 2022 Page layout is the part of graphic design that deals with the arrangement of visual elements on a page. Page layout is used to make the web pages look better. It establishes the overall appearance, relative importance, and relationships between the graphic elements to achieve a smooth flow of information and eye movement for maximum effectiveness or impact. divs have a special class/id associated with them. <div class = "header"> ..... </div> <div class = "section"> ..... </section> <div class = "footer"> ..... </footer> Page Layout Information: Header: The part of the front end which is used at the top of the page. <header> tag is used to add a header section on web pages.s Syntax: <header> <h1> ----- </h1> <h2> ----- </h2> ---------------- ---------------- </header> Navigation bar: The navigation bar is the same as the menu list. It is used to display the content information using hyperlinks. <nav> tag is used to add the nav section(nav elements) in web pages. Syntax: <nav> <ul> <li> ..... </li> <li> ..... </li> </ul> </nav> Index / Sidebar: It holds additional information or advertisements and is not always necessary to be added to the page. Content Section: The content section is the central part where content is displayed.<main> tag is used to add the main content of the webpages. Footer: The footer section contains the contact information and other query related to web pages. The footer section is always put on the bottom of the web pages. The <footer> tag sets the footer on web pages. Syntax: <footer> ..... </footer> Example: html <!DOCTYPE html><html><head> <title>Page Layout</title> <style> .head1 { font-size:40px; color:#009900; font-weight:bold; } .head2 { font-size:17px; margin-left:10px; margin-bottom:15px; } body { margin: 0 auto; background-position:center; background-size: contain; } .menu { position: sticky; top: 0; background-color: #009900; padding:10px 0px 10px 0px; color:white; margin: 0 auto; overflow: hidden; } .menu a { float: left; color: white; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 20px; } .menu-log { right: auto; float: right; } footer { width: 100%; bottom: 0px; background-color: #000; color: #fff; position: absolute; padding-top:20px; padding-bottom:50px; text-align:center; font-size:30px; font-weight:bold; } .body_sec { margin-left:20px; } </style></head> <body> <!-- Header Section --> <header> <div class="head1">GeeksforGeeks</div> <div class="head2">A computer science portal for geeks</div> </header> <!-- Menu Navigation Bar --> <nav class="menu"> <a href="#home">HOME</a> <a href="#news">NEWS</a> <a href="#notification">NOTIFICATIONS</a> <div class="menu-log"> <a href="#login">LOGIN</a> </div> </nav> <!-- Body section --> <main class = "body_sec"> <section id="Content"> <h3>Content section</h3> </section> </main> <!-- Footer Section --> <footer>Footer Section</footer></body></html> Output: Supported Browser: Google Chrome Microsoft Edge Firefox Opera Safari HTML is the foundation of web pages and is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples. SumitBM ysachin2314 hardikkoriintern harsh464565 aditiyadav20102001 HTML-Basics Picked CSS HTML Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? 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 How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property
[ { "code": null, "e": 54, "s": 26, "text": "\n15 Jun, 2022" }, { "code": null, "e": 415, "s": 54, "text": "Page layout is the part of graphic design that deals with the arrangement of visual elements on a page. Page layout is used to make the web pages look better. It establishes the overall appearance, relative importance, and relationships between the graphic elements to achieve a smooth flow of information and eye movement for maximum effectiveness or impact. " }, { "code": null, "e": 466, "s": 415, "text": "divs have a special class/id associated with them." }, { "code": null, "e": 618, "s": 466, "text": " <div class = \"header\"> ..... </div>\n <div class = \"section\"> ..... </section>\n <div class = \"footer\"> ..... </footer>" }, { "code": null, "e": 644, "s": 618, "text": "Page Layout Information: " }, { "code": null, "e": 776, "s": 644, "text": "Header: The part of the front end which is used at the top of the page. <header> tag is used to add a header section on web pages.s" }, { "code": null, "e": 784, "s": 776, "text": "Syntax:" }, { "code": null, "e": 959, "s": 784, "text": " <header>\n <h1> ----- </h1>\n <h2> ----- </h2>\n ----------------\n ----------------\n </header>" }, { "code": null, "e": 1157, "s": 959, "text": "Navigation bar: The navigation bar is the same as the menu list. It is used to display the content information using hyperlinks. <nav> tag is used to add the nav section(nav elements) in web pages." }, { "code": null, "e": 1165, "s": 1157, "text": "Syntax:" }, { "code": null, "e": 1319, "s": 1165, "text": " <nav>\n <ul>\n <li> ..... </li>\n <li> ..... </li>\n </ul>\n </nav>" }, { "code": null, "e": 1439, "s": 1319, "text": "Index / Sidebar: It holds additional information or advertisements and is not always necessary to be added to the page." }, { "code": null, "e": 1583, "s": 1439, "text": "Content Section: The content section is the central part where content is displayed.<main> tag is used to add the main content of the webpages." }, { "code": null, "e": 1793, "s": 1583, "text": "Footer: The footer section contains the contact information and other query related to web pages. The footer section is always put on the bottom of the web pages. The <footer> tag sets the footer on web pages." }, { "code": null, "e": 1801, "s": 1793, "text": "Syntax:" }, { "code": null, "e": 1866, "s": 1801, "text": " <footer>\n .....\n </footer>" }, { "code": null, "e": 1877, "s": 1866, "text": "Example: " }, { "code": null, "e": 1882, "s": 1877, "text": "html" }, { "code": "<!DOCTYPE html><html><head> <title>Page Layout</title> <style> .head1 { font-size:40px; color:#009900; font-weight:bold; } .head2 { font-size:17px; margin-left:10px; margin-bottom:15px; } body { margin: 0 auto; background-position:center; background-size: contain; } .menu { position: sticky; top: 0; background-color: #009900; padding:10px 0px 10px 0px; color:white; margin: 0 auto; overflow: hidden; } .menu a { float: left; color: white; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 20px; } .menu-log { right: auto; float: right; } footer { width: 100%; bottom: 0px; background-color: #000; color: #fff; position: absolute; padding-top:20px; padding-bottom:50px; text-align:center; font-size:30px; font-weight:bold; } .body_sec { margin-left:20px; } </style></head> <body> <!-- Header Section --> <header> <div class=\"head1\">GeeksforGeeks</div> <div class=\"head2\">A computer science portal for geeks</div> </header> <!-- Menu Navigation Bar --> <nav class=\"menu\"> <a href=\"#home\">HOME</a> <a href=\"#news\">NEWS</a> <a href=\"#notification\">NOTIFICATIONS</a> <div class=\"menu-log\"> <a href=\"#login\">LOGIN</a> </div> </nav> <!-- Body section --> <main class = \"body_sec\"> <section id=\"Content\"> <h3>Content section</h3> </section> </main> <!-- Footer Section --> <footer>Footer Section</footer></body></html>", "e": 3879, "s": 1882, "text": null }, { "code": null, "e": 3889, "s": 3879, "text": "Output: " }, { "code": null, "e": 3908, "s": 3889, "text": "Supported Browser:" }, { "code": null, "e": 3922, "s": 3908, "text": "Google Chrome" }, { "code": null, "e": 3937, "s": 3922, "text": "Microsoft Edge" }, { "code": null, "e": 3945, "s": 3937, "text": "Firefox" }, { "code": null, "e": 3951, "s": 3945, "text": "Opera" }, { "code": null, "e": 3958, "s": 3951, "text": "Safari" }, { "code": null, "e": 4157, "s": 3958, "text": "HTML is the foundation of web pages and is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples." }, { "code": null, "e": 4165, "s": 4157, "text": "SumitBM" }, { "code": null, "e": 4177, "s": 4165, "text": "ysachin2314" }, { "code": null, "e": 4194, "s": 4177, "text": "hardikkoriintern" }, { "code": null, "e": 4206, "s": 4194, "text": "harsh464565" }, { "code": null, "e": 4225, "s": 4206, "text": "aditiyadav20102001" }, { "code": null, "e": 4237, "s": 4225, "text": "HTML-Basics" }, { "code": null, "e": 4244, "s": 4237, "text": "Picked" }, { "code": null, "e": 4248, "s": 4244, "text": "CSS" }, { "code": null, "e": 4253, "s": 4248, "text": "HTML" }, { "code": null, "e": 4280, "s": 4253, "text": "Web technologies Questions" }, { "code": null, "e": 4285, "s": 4280, "text": "HTML" }, { "code": null, "e": 4383, "s": 4285, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4431, "s": 4383, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 4493, "s": 4431, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4543, "s": 4493, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 4601, "s": 4543, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 4651, "s": 4601, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 4699, "s": 4651, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 4761, "s": 4699, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4811, "s": 4761, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 4835, "s": 4811, "text": "REST API (Introduction)" } ]
Why Transition properties does not work with display properties ?
21 Dec, 2020 When we want to use transition for display:none to display:block, transition properties do not work. The reason for this is, display:none property is used for removing block and display:block property is used for displaying block. A block cannot be partly displayed. Either it is available or unavailable. That is why the transition property does not work. So for animation, we use keyframes CSS. @keyframes animationname {keyframes-selector {css-styles;}} What does keyframes do?The @keyframes rule specifies the code for animation. When one set of CSS style is changed to another set of CSS style, the animation is created and specify whenever the style changes. It can be in percent or with the keywords “from” and “to”, which will be equivalent to 0% and 100%. Here 0% is the beginning of the animation and 100% is the end of the animation. Which Browser supports keyframes and what is prefix for that browser? Chrome & safari=> -webkit- Mozilla => -moz- Opera => -o- Code snippet: HTML <!DOCTYPE html><html> <head> <style> html, body { height: 100%; padding: 0; font: 20px/40px sans-serif; } h1 { padding: 20px; } div { width: 100%; background: pink; padding: 20px; display: none; } body:hover div { display: block; -webkit-animation: slide-down 2.3s ease-out; -moz-animation: slide-down 3.3s ease-out; } @-webkit-keyframes slide-down { 0% { opacity: 0; } 100% { opacity: 1; } } @-moz-keyframes slide-down { 0% { opacity: 0; } 100% { opacity: 1; } } </style></head> <body> <h1>Hover me</h1> <div>Hello</div></body> </html> arorakashish0911 CSS-Misc HTML-Misc CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Dec, 2020" }, { "code": null, "e": 385, "s": 28, "text": "When we want to use transition for display:none to display:block, transition properties do not work. The reason for this is, display:none property is used for removing block and display:block property is used for displaying block. A block cannot be partly displayed. Either it is available or unavailable. That is why the transition property does not work." }, { "code": null, "e": 425, "s": 385, "text": "So for animation, we use keyframes CSS." }, { "code": null, "e": 486, "s": 425, "text": "@keyframes animationname {keyframes-selector {css-styles;}}\n" }, { "code": null, "e": 874, "s": 486, "text": "What does keyframes do?The @keyframes rule specifies the code for animation. When one set of CSS style is changed to another set of CSS style, the animation is created and specify whenever the style changes. It can be in percent or with the keywords “from” and “to”, which will be equivalent to 0% and 100%. Here 0% is the beginning of the animation and 100% is the end of the animation." }, { "code": null, "e": 944, "s": 874, "text": "Which Browser supports keyframes and what is prefix for that browser?" }, { "code": null, "e": 972, "s": 944, "text": "Chrome & safari=> -webkit-" }, { "code": null, "e": 989, "s": 972, "text": "Mozilla => -moz-" }, { "code": null, "e": 1002, "s": 989, "text": "Opera => -o-" }, { "code": null, "e": 1016, "s": 1002, "text": "Code snippet:" }, { "code": null, "e": 1021, "s": 1016, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> html, body { height: 100%; padding: 0; font: 20px/40px sans-serif; } h1 { padding: 20px; } div { width: 100%; background: pink; padding: 20px; display: none; } body:hover div { display: block; -webkit-animation: slide-down 2.3s ease-out; -moz-animation: slide-down 3.3s ease-out; } @-webkit-keyframes slide-down { 0% { opacity: 0; } 100% { opacity: 1; } } @-moz-keyframes slide-down { 0% { opacity: 0; } 100% { opacity: 1; } } </style></head> <body> <h1>Hover me</h1> <div>Hello</div></body> </html>", "e": 1947, "s": 1021, "text": null }, { "code": null, "e": 1964, "s": 1947, "text": "arorakashish0911" }, { "code": null, "e": 1973, "s": 1964, "text": "CSS-Misc" }, { "code": null, "e": 1983, "s": 1973, "text": "HTML-Misc" }, { "code": null, "e": 1987, "s": 1983, "text": "CSS" }, { "code": null, "e": 1992, "s": 1987, "text": "HTML" }, { "code": null, "e": 2009, "s": 1992, "text": "Web Technologies" }, { "code": null, "e": 2036, "s": 2009, "text": "Web technologies Questions" }, { "code": null, "e": 2041, "s": 2036, "text": "HTML" } ]
Generating random Id’s in Python
28 Sep, 2021 In python there are different ways to generate id’s. Let’s see how different types of Id’s can be generated using python without using inbuilt Python libraries. Code #1 : Print 10 random values of numbers between 1 and 100. Python3 # Python3 code to demonstrate the# random generation of Integer id's import random # determines how many values# will be printedfor x in range(10): # print 10 random values # between 1 and 100 print (random.randint(1, 101)) Output : 76 72 7 78 77 19 24 23 77 96 Code #2 : Print random numbers between 1 and 100 which are multiple of 5. Python3 # Python3 code to demonstrate# the random generation of id's# which are multiple of 5 import random # determines how many# values will be printedfor x in range(10): # print 10 random values between # 1 and 100 which are multiple of 5 print (random.randint(1, 20) * 5) Output : 60 30 35 100 85 25 100 20 90 85 Drawbacks : Generating Random numbers is not unique, Same number can repeat itself. It generates only Integer values. Generating Random string id’s consists of letters and digits. This can be useful in generating passwords as its provide the encryption and decryption technique. Code #1 : Show how to generate random string id’s. Python3 # Python3 code to demonstrate the# random generation of string id's import randomimport string # Generate a random string# with 32 characters.random = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(32)]) # print the random# string of length 32print (random) Output : Rf2IdqUNkURNN6mw82kSpyxQe9ib3usX Code #2 : Using Function call Python3 # Python3 code to demonstrate# the random generation of string id's import randomimport string # defining function for random# string id with parameterdef ran_gen(size, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for x in range(size)) # function call for random string# generation with size 8 and stringprint (ran_gen(8, "AEIOSUMA23")) Output : S2M2IEAO Generating Random id’s using UUID in Python varshagumber28 python-string Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 53, "s": 25, "text": "\n28 Sep, 2021" }, { "code": null, "e": 215, "s": 53, "text": "In python there are different ways to generate id’s. Let’s see how different types of Id’s can be generated using python without using inbuilt Python libraries. " }, { "code": null, "e": 280, "s": 215, "text": "Code #1 : Print 10 random values of numbers between 1 and 100. " }, { "code": null, "e": 288, "s": 280, "text": "Python3" }, { "code": "# Python3 code to demonstrate the# random generation of Integer id's import random # determines how many values# will be printedfor x in range(10): # print 10 random values # between 1 and 100 print (random.randint(1, 101))", "e": 526, "s": 288, "text": null }, { "code": null, "e": 536, "s": 526, "text": "Output : " }, { "code": null, "e": 565, "s": 536, "text": "76\n72\n7\n78\n77\n19\n24\n23\n77\n96" }, { "code": null, "e": 639, "s": 565, "text": "Code #2 : Print random numbers between 1 and 100 which are multiple of 5." }, { "code": null, "e": 647, "s": 639, "text": "Python3" }, { "code": "# Python3 code to demonstrate# the random generation of id's# which are multiple of 5 import random # determines how many# values will be printedfor x in range(10): # print 10 random values between # 1 and 100 which are multiple of 5 print (random.randint(1, 20) * 5)", "e": 933, "s": 647, "text": null }, { "code": null, "e": 943, "s": 933, "text": "Output : " }, { "code": null, "e": 975, "s": 943, "text": "60\n30\n35\n100\n85\n25\n100\n20\n90\n85" }, { "code": null, "e": 988, "s": 975, "text": "Drawbacks : " }, { "code": null, "e": 1060, "s": 988, "text": "Generating Random numbers is not unique, Same number can repeat itself." }, { "code": null, "e": 1094, "s": 1060, "text": "It generates only Integer values." }, { "code": null, "e": 1255, "s": 1094, "text": "Generating Random string id’s consists of letters and digits. This can be useful in generating passwords as its provide the encryption and decryption technique." }, { "code": null, "e": 1308, "s": 1255, "text": "Code #1 : Show how to generate random string id’s. " }, { "code": null, "e": 1316, "s": 1308, "text": "Python3" }, { "code": "# Python3 code to demonstrate the# random generation of string id's import randomimport string # Generate a random string# with 32 characters.random = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(32)]) # print the random# string of length 32print (random)", "e": 1614, "s": 1316, "text": null }, { "code": null, "e": 1624, "s": 1614, "text": "Output : " }, { "code": null, "e": 1657, "s": 1624, "text": "Rf2IdqUNkURNN6mw82kSpyxQe9ib3usX" }, { "code": null, "e": 1687, "s": 1657, "text": "Code #2 : Using Function call" }, { "code": null, "e": 1695, "s": 1687, "text": "Python3" }, { "code": "# Python3 code to demonstrate# the random generation of string id's import randomimport string # defining function for random# string id with parameterdef ran_gen(size, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for x in range(size)) # function call for random string# generation with size 8 and stringprint (ran_gen(8, \"AEIOSUMA23\"))", "e": 2073, "s": 1695, "text": null }, { "code": null, "e": 2083, "s": 2073, "text": "Output : " }, { "code": null, "e": 2092, "s": 2083, "text": "S2M2IEAO" }, { "code": null, "e": 2137, "s": 2092, "text": "Generating Random id’s using UUID in Python " }, { "code": null, "e": 2152, "s": 2137, "text": "varshagumber28" }, { "code": null, "e": 2166, "s": 2152, "text": "python-string" }, { "code": null, "e": 2173, "s": 2166, "text": "Python" }, { "code": null, "e": 2271, "s": 2173, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2289, "s": 2271, "text": "Python Dictionary" }, { "code": null, "e": 2331, "s": 2289, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2353, "s": 2331, "text": "Enumerate() in Python" }, { "code": null, "e": 2388, "s": 2353, "text": "Read a file line by line in Python" }, { "code": null, "e": 2414, "s": 2388, "text": "Python String | replace()" }, { "code": null, "e": 2446, "s": 2414, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2475, "s": 2446, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2502, "s": 2475, "text": "Python Classes and Objects" }, { "code": null, "e": 2532, "s": 2502, "text": "Iterate over a list in Python" } ]
How to zoom-in and zoom-out image using ReactJS?
03 Dec, 2021 React is a JavaScript library for building user interfaces. React makes it painless to create interactive UIs. Design simple views for each state in your application, and React will efficiently update and render just the right components when your data changes. In ReactJS whatever we write that looks like HTML is not pure HTML actually. All the HTML looking stuff are JSX, Behind the scene, they are converted to vanilla JavaScript using babel. These all work in this way to make the developer’s life easier. Since JSX are not HTML that’s why we do have any direct reference to the HTML elements and that’s why we can’t direct fetch properties of any HTML element. To fetch the elements’ property, React gives something called as ‘ref’. Using ref we can create a direct reference to any HTML elements and get controlled over HTML elements properties. Here we use the ‘ref’ system to fetch image height and width. After getting image height and width we set a click handler and increase the dimension of the image which gets faded into the DOM property. Example: This example illustrates how to zoom an image using react index.js: Javascript import React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root')) App.js: Javascript import React, { Component } from 'react'class App extends Component{ constructor(props){ super(props) // Initializing states this.state = {height:null, width:null} // Bind context of 'this' this.handleZoomIn = this.handleZoomIn.bind(this) this.handleZoomOut = this.handleZoomOut.bind(this) // Create reference of DOM object this.imgRef = React.createRef() } componentDidMount(){ // Saving initial dimension of image as class properties this.initialHeight = this.imgRef.current.clientHeight this.initialWidth = this.imgRef.current.clientWidth } // Event handler callback for zoom in handleZoomIn(){ // Fetching current height and width const height = this.imgRef.current.clientHeight const width = this.imgRef.current.clientWidth // Increase dimension(Zooming) this.setState({ height : height + 10, width : width + 10, }) } // Event handler callback zoom out handleZoomOut(){ // Assigning original height and width this.setState({ height : this.initialHeight, width : this.initialWidth, }) } render(){ // Assign current height and width to the image const imgStyle = { height : this.state.height, width: this.state.width} return( <div> <h2>GeeksforGeeks</h2> {/* Assign reference to DOM element */} <img style={imgStyle} ref={this.imgRef} src='https://media.geeksforgeeks.org/wp-content/uploads/20200923125643/download.png' alt='gfg' /> <div> <button onClick={this.handleZoomIn}>Zoom In</button> <button onClick={this.handleZoomOut}>Zoom Out</button> </div> </div> ) }}export default App Output : simmytarika5 react-js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Dec, 2021" }, { "code": null, "e": 290, "s": 28, "text": "React is a JavaScript library for building user interfaces. React makes it painless to create interactive UIs. Design simple views for each state in your application, and React will efficiently update and render just the right components when your data changes." }, { "code": null, "e": 1083, "s": 290, "text": "In ReactJS whatever we write that looks like HTML is not pure HTML actually. All the HTML looking stuff are JSX, Behind the scene, they are converted to vanilla JavaScript using babel. These all work in this way to make the developer’s life easier. Since JSX are not HTML that’s why we do have any direct reference to the HTML elements and that’s why we can’t direct fetch properties of any HTML element. To fetch the elements’ property, React gives something called as ‘ref’. Using ref we can create a direct reference to any HTML elements and get controlled over HTML elements properties. Here we use the ‘ref’ system to fetch image height and width. After getting image height and width we set a click handler and increase the dimension of the image which gets faded into the DOM property." }, { "code": null, "e": 1150, "s": 1083, "text": "Example: This example illustrates how to zoom an image using react" }, { "code": null, "e": 1160, "s": 1150, "text": "index.js:" }, { "code": null, "e": 1171, "s": 1160, "text": "Javascript" }, { "code": "import React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))", "e": 1310, "s": 1171, "text": null }, { "code": null, "e": 1318, "s": 1310, "text": "App.js:" }, { "code": null, "e": 1329, "s": 1318, "text": "Javascript" }, { "code": "import React, { Component } from 'react'class App extends Component{ constructor(props){ super(props) // Initializing states this.state = {height:null, width:null} // Bind context of 'this' this.handleZoomIn = this.handleZoomIn.bind(this) this.handleZoomOut = this.handleZoomOut.bind(this) // Create reference of DOM object this.imgRef = React.createRef() } componentDidMount(){ // Saving initial dimension of image as class properties this.initialHeight = this.imgRef.current.clientHeight this.initialWidth = this.imgRef.current.clientWidth } // Event handler callback for zoom in handleZoomIn(){ // Fetching current height and width const height = this.imgRef.current.clientHeight const width = this.imgRef.current.clientWidth // Increase dimension(Zooming) this.setState({ height : height + 10, width : width + 10, }) } // Event handler callback zoom out handleZoomOut(){ // Assigning original height and width this.setState({ height : this.initialHeight, width : this.initialWidth, }) } render(){ // Assign current height and width to the image const imgStyle = { height : this.state.height, width: this.state.width} return( <div> <h2>GeeksforGeeks</h2> {/* Assign reference to DOM element */} <img style={imgStyle} ref={this.imgRef} src='https://media.geeksforgeeks.org/wp-content/uploads/20200923125643/download.png' alt='gfg' /> <div> <button onClick={this.handleZoomIn}>Zoom In</button> <button onClick={this.handleZoomOut}>Zoom Out</button> </div> </div> ) }}export default App", "e": 3022, "s": 1329, "text": null }, { "code": null, "e": 3031, "s": 3022, "text": "Output :" }, { "code": null, "e": 3044, "s": 3031, "text": "simmytarika5" }, { "code": null, "e": 3053, "s": 3044, "text": "react-js" }, { "code": null, "e": 3070, "s": 3053, "text": "Web Technologies" } ]
What are Events in Solidity?
24 Jun, 2022 Solidity Events are the same as events in any other programming language. An event is an inheritable member of the contract, which stores the arguments passed in the transaction logs when emitted. Generally, events are used to inform the calling application about the current state of the contract, with the help of the logging facility of EVM. Events notify the applications about the change made to the contracts and applications which can be used to execute the dependent logic. Events are defined within the contracts as global and called within their functions. Events are declared by using the event keyword, followed by an identifier and the parameter list, and ends with a semicolon. The parameter values are used to log the information or for executing the conditional logic. Its information and values are saved as part of the transactions inside the block. There is no need of providing variables, only datatypes are sufficient. An event can be called from any method by using its name and passing the required parameters. event <eventName>(parameters) ; javascript // Solidity program to demonstrate// creating an eventpragma solidity ^0.4.21; // Creating a contractcontract eventExample { // Declaring state variables uint256 public value = 0; // Declaring an event event Increment(address owner); // Defining a function for logging event function getValue(uint _a, uint _b) public { emit Increment(msg.sender); value = _a + _b; }} Output: Result in the console: Javascript logs [ { "from": "0xd9145CCE52D386f254917e481eB44e9943F39138", "topic": "0xfc3a67c9f0b5967ae4041ed898b05ec1fa49d2a3c22336247201d71be6f97120", "event": "Increment", "args": { "0": "0x5B38Da6a701c568545dCfcB03FcB875f56beddC4", "owner": "0x5B38Da6a701c568545dCfcB03FcB875f56beddC4" } }] Index in events: We can also add an index to our event. On adding the different fields to our event, we can add an index to them it helps to access them later but of course, it’s going to cost some more gas! IMP: We can add atmost 3 indexes in one event. Code: Solidity // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; contract IndexEvents { event NewTrade( uint256 indexed date, address from, address indexed to, uint256 indexed amount ); function trade(address to, uint256 amount) external { emit NewTrade(block.timestamp, msg.sender, to,amount); }} Output in the console: adding the output in the console Javascript logs [ { "from": "0xcD6a42782d230D7c13A74ddec5dD140e55499Df9", "topic": "0xa6b5ddd331f9dc412a8c258207b1c66f53c1740c72628d9913aafcb6b28d8f73", "event": "NewTrade", "args": { "0": "1655406115", "1": "0x5B38Da6a701c568545dCfcB03FcB875f56beddC4", "2": "0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2", "3": "1234", "date": "1655406115", "from": "0x5B38Da6a701c568545dCfcB03FcB875f56beddC4", "to": "0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2", "amount": "1234" } }] shivangi019717 Solidity-Events Blockchain Solidity Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Jun, 2022" }, { "code": null, "e": 534, "s": 52, "text": "Solidity Events are the same as events in any other programming language. An event is an inheritable member of the contract, which stores the arguments passed in the transaction logs when emitted. Generally, events are used to inform the calling application about the current state of the contract, with the help of the logging facility of EVM. Events notify the applications about the change made to the contracts and applications which can be used to execute the dependent logic." }, { "code": null, "e": 1086, "s": 534, "text": "Events are defined within the contracts as global and called within their functions. Events are declared by using the event keyword, followed by an identifier and the parameter list, and ends with a semicolon. The parameter values are used to log the information or for executing the conditional logic. Its information and values are saved as part of the transactions inside the block. There is no need of providing variables, only datatypes are sufficient. An event can be called from any method by using its name and passing the required parameters." }, { "code": null, "e": 1122, "s": 1086, "text": "event <eventName>(parameters) ; " }, { "code": null, "e": 1133, "s": 1122, "text": "javascript" }, { "code": "// Solidity program to demonstrate// creating an eventpragma solidity ^0.4.21; // Creating a contractcontract eventExample { // Declaring state variables uint256 public value = 0; // Declaring an event event Increment(address owner); // Defining a function for logging event function getValue(uint _a, uint _b) public { emit Increment(msg.sender); value = _a + _b; }}", "e": 1541, "s": 1133, "text": null }, { "code": null, "e": 1550, "s": 1541, "text": "Output: " }, { "code": null, "e": 1574, "s": 1550, "text": "Result in the console: " }, { "code": null, "e": 1585, "s": 1574, "text": "Javascript" }, { "code": "logs [ { \"from\": \"0xd9145CCE52D386f254917e481eB44e9943F39138\", \"topic\": \"0xfc3a67c9f0b5967ae4041ed898b05ec1fa49d2a3c22336247201d71be6f97120\", \"event\": \"Increment\", \"args\": { \"0\": \"0x5B38Da6a701c568545dCfcB03FcB875f56beddC4\", \"owner\": \"0x5B38Da6a701c568545dCfcB03FcB875f56beddC4\" } }]", "e": 1935, "s": 1585, "text": null }, { "code": null, "e": 2143, "s": 1935, "text": "Index in events: We can also add an index to our event. On adding the different fields to our event, we can add an index to them it helps to access them later but of course, it’s going to cost some more gas!" }, { "code": null, "e": 2191, "s": 2143, "text": "IMP: We can add atmost 3 indexes in one event. " }, { "code": null, "e": 2198, "s": 2191, "text": "Code: " }, { "code": null, "e": 2207, "s": 2198, "text": "Solidity" }, { "code": "// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; contract IndexEvents { event NewTrade( uint256 indexed date, address from, address indexed to, uint256 indexed amount ); function trade(address to, uint256 amount) external { emit NewTrade(block.timestamp, msg.sender, to,amount); }}", "e": 2559, "s": 2207, "text": null }, { "code": null, "e": 2616, "s": 2559, "text": "Output in the console: adding the output in the console" }, { "code": null, "e": 2627, "s": 2616, "text": "Javascript" }, { "code": "logs [ { \"from\": \"0xcD6a42782d230D7c13A74ddec5dD140e55499Df9\", \"topic\": \"0xa6b5ddd331f9dc412a8c258207b1c66f53c1740c72628d9913aafcb6b28d8f73\", \"event\": \"NewTrade\", \"args\": { \"0\": \"1655406115\", \"1\": \"0x5B38Da6a701c568545dCfcB03FcB875f56beddC4\", \"2\": \"0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2\", \"3\": \"1234\", \"date\": \"1655406115\", \"from\": \"0x5B38Da6a701c568545dCfcB03FcB875f56beddC4\", \"to\": \"0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2\", \"amount\": \"1234\" } }]", "e": 3216, "s": 2627, "text": null }, { "code": null, "e": 3231, "s": 3216, "text": "shivangi019717" }, { "code": null, "e": 3247, "s": 3231, "text": "Solidity-Events" }, { "code": null, "e": 3258, "s": 3247, "text": "Blockchain" }, { "code": null, "e": 3267, "s": 3258, "text": "Solidity" } ]
Python | All possible N combination tuples
11 Jan, 2022 Sometimes, while working with Python tuples, we might have a problem in which we need to generate all possible combination pairs till N. This can have application in mathematics domain. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using list comprehension + product()This task can be performed using list comprehension which can be used to iterate the container of N numbers and product() performs the task of formation of combinations from them. Python3 # Python3 code to demonstrate working of# All possible N combination tuples# Using list comprehension + product()from itertools import product # initialize N N = 3 # All possible N combination tuples# Using list comprehension + product()res = [ele for ele in product(range(1, N + 1), repeat = N)] # printing resultprint("Tuple Combinations till N are : " + str(res)) Tuple Combinations till N are : [(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 1), (1, 2, 2), (1, 2, 3), (1, 3, 1), (1, 3, 2), (1, 3, 3), (2, 1, 1), (2, 1, 2), (2, 1, 3), (2, 2, 1), (2, 2, 2), (2, 2, 3), (2, 3, 1), (2, 3, 2), (2, 3, 3), (3, 1, 1), (3, 1, 2), (3, 1, 3), (3, 2, 1), (3, 2, 2), (3, 2, 3), (3, 3, 1), (3, 3, 2), (3, 3, 3)] Method #2 : Using product()This task can also be performed by using just the single function. The use of list comprehension can be eliminated using the conversion to list. Python3 # Python3 code to demonstrate working of# All possible N combination tuples# Using product()from itertools import product # initialize N N = 3 # All possible N combination tuples# Using product()res = list(product(range(1, N + 1), repeat = N)) # printing resultprint("Tuple Combinations till N are : " + str(res)) Tuple Combinations till N are : [(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 1), (1, 2, 2), (1, 2, 3), (1, 3, 1), (1, 3, 2), (1, 3, 3), (2, 1, 1), (2, 1, 2), (2, 1, 3), (2, 2, 1), (2, 2, 2), (2, 2, 3), (2, 3, 1), (2, 3, 2), (2, 3, 3), (3, 1, 1), (3, 1, 2), (3, 1, 3), (3, 2, 1), (3, 2, 2), (3, 2, 3), (3, 3, 1), (3, 3, 2), (3, 3, 3)] rajeev0719singh Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Jan, 2022" }, { "code": null, "e": 278, "s": 28, "text": "Sometimes, while working with Python tuples, we might have a problem in which we need to generate all possible combination pairs till N. This can have application in mathematics domain. Let’s discuss certain ways in which this problem can be solved." }, { "code": null, "e": 506, "s": 278, "text": "Method #1 : Using list comprehension + product()This task can be performed using list comprehension which can be used to iterate the container of N numbers and product() performs the task of formation of combinations from them." }, { "code": null, "e": 514, "s": 506, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# All possible N combination tuples# Using list comprehension + product()from itertools import product # initialize N N = 3 # All possible N combination tuples# Using list comprehension + product()res = [ele for ele in product(range(1, N + 1), repeat = N)] # printing resultprint(\"Tuple Combinations till N are : \" + str(res))", "e": 884, "s": 514, "text": null }, { "code": null, "e": 1214, "s": 884, "text": "Tuple Combinations till N are : [(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 1), (1, 2, 2), (1, 2, 3), (1, 3, 1), (1, 3, 2), (1, 3, 3), (2, 1, 1), (2, 1, 2), (2, 1, 3), (2, 2, 1), (2, 2, 2), (2, 2, 3), (2, 3, 1), (2, 3, 2), (2, 3, 3), (3, 1, 1), (3, 1, 2), (3, 1, 3), (3, 2, 1), (3, 2, 2), (3, 2, 3), (3, 3, 1), (3, 3, 2), (3, 3, 3)]" }, { "code": null, "e": 1388, "s": 1216, "text": "Method #2 : Using product()This task can also be performed by using just the single function. The use of list comprehension can be eliminated using the conversion to list." }, { "code": null, "e": 1396, "s": 1388, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# All possible N combination tuples# Using product()from itertools import product # initialize N N = 3 # All possible N combination tuples# Using product()res = list(product(range(1, N + 1), repeat = N)) # printing resultprint(\"Tuple Combinations till N are : \" + str(res))", "e": 1713, "s": 1396, "text": null }, { "code": null, "e": 2043, "s": 1713, "text": "Tuple Combinations till N are : [(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 1), (1, 2, 2), (1, 2, 3), (1, 3, 1), (1, 3, 2), (1, 3, 3), (2, 1, 1), (2, 1, 2), (2, 1, 3), (2, 2, 1), (2, 2, 2), (2, 2, 3), (2, 3, 1), (2, 3, 2), (2, 3, 3), (3, 1, 1), (3, 1, 2), (3, 1, 3), (3, 2, 1), (3, 2, 2), (3, 2, 3), (3, 3, 1), (3, 3, 2), (3, 3, 3)]" }, { "code": null, "e": 2059, "s": 2043, "text": "rajeev0719singh" }, { "code": null, "e": 2080, "s": 2059, "text": "Python list-programs" }, { "code": null, "e": 2087, "s": 2080, "text": "Python" }, { "code": null, "e": 2103, "s": 2087, "text": "Python Programs" } ]
jQuery | [attribute] Selector
12 Mar, 2019 The [attribute] Selector is an inbuilt selector in jQuery, used to select all the elements with the specified attribute. Syntax: $("[attribute_name]") Parameter: attribute_name: It is the required parameter which specify the attribute to be select. Example-1: <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> $(document).ready(function() { $("[class]").css("color", "green"); }); </script></head> <body> <center> <!-- Class attribute--> <h3 class>GeeksforGeeks</h3> <p>A computer science portal for geeks</p> <!--id attribute--> <p id>Geek1</p> <!--class attribute--> <p class>Geek2</p> <p>Geek3</p> <!--class attribute--> <div class> Thank You! </div> </center></body> </html> Output: In the above example, all the elements with the specified attribute (class) are formatted into green color i.e, “GeeksforGeeks”, “Geek2” and “Thank You!”. Example-2: <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> $(document).ready(function() { $("[class]").css("color", "green"); }); </script></head> <body> <center> <!-- Class(demo) attribute--> <h3 class="demo">GeeksforGeeks</h3> <p>A computer science portal for geeks</p> <!--id attribute--> <p id>Geek1</p> <p>Geek2</p> <!--class(test) attribute--> <p class="test">Geek3</p> <!--class(sample) attribute--> <div class="sample"> Thank You! </div> </center></body> </html> Output: In the above example, all the elements with the specified attribute (class) are formatted into green color rather considering the value of the attribute. “GeeksforGeeks”, “Geek3” and “Thank You!” are formatted. jQuery-Selectors Picked JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Form validation using jQuery How to Dynamically Add/Remove Table Rows using jQuery ? Scroll to the top of the page using JavaScript/jQuery How to get the value in an input text box using jQuery ? jQuery | children() with Examples How to insert spaces/tabs in text using HTML/CSS? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Node.js fs.readFileSync() Method How to set the default value for an HTML <select> element ?
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Mar, 2019" }, { "code": null, "e": 173, "s": 52, "text": "The [attribute] Selector is an inbuilt selector in jQuery, used to select all the elements with the specified attribute." }, { "code": null, "e": 181, "s": 173, "text": "Syntax:" }, { "code": null, "e": 204, "s": 181, "text": "$(\"[attribute_name]\")\n" }, { "code": null, "e": 215, "s": 204, "text": "Parameter:" }, { "code": null, "e": 302, "s": 215, "text": "attribute_name: It is the required parameter which specify the attribute to be select." }, { "code": null, "e": 313, "s": 302, "text": "Example-1:" }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> $(document).ready(function() { $(\"[class]\").css(\"color\", \"green\"); }); </script></head> <body> <center> <!-- Class attribute--> <h3 class>GeeksforGeeks</h3> <p>A computer science portal for geeks</p> <!--id attribute--> <p id>Geek1</p> <!--class attribute--> <p class>Geek2</p> <p>Geek3</p> <!--class attribute--> <div class> Thank You! </div> </center></body> </html>", "e": 976, "s": 313, "text": null }, { "code": null, "e": 984, "s": 976, "text": "Output:" }, { "code": null, "e": 1139, "s": 984, "text": "In the above example, all the elements with the specified attribute (class) are formatted into green color i.e, “GeeksforGeeks”, “Geek2” and “Thank You!”." }, { "code": null, "e": 1150, "s": 1139, "text": "Example-2:" }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> $(document).ready(function() { $(\"[class]\").css(\"color\", \"green\"); }); </script></head> <body> <center> <!-- Class(demo) attribute--> <h3 class=\"demo\">GeeksforGeeks</h3> <p>A computer science portal for geeks</p> <!--id attribute--> <p id>Geek1</p> <p>Geek2</p> <!--class(test) attribute--> <p class=\"test\">Geek3</p> <!--class(sample) attribute--> <div class=\"sample\"> Thank You! </div> </center></body> </html>", "e": 1856, "s": 1150, "text": null }, { "code": null, "e": 1864, "s": 1856, "text": "Output:" }, { "code": null, "e": 2075, "s": 1864, "text": "In the above example, all the elements with the specified attribute (class) are formatted into green color rather considering the value of the attribute. “GeeksforGeeks”, “Geek3” and “Thank You!” are formatted." }, { "code": null, "e": 2092, "s": 2075, "text": "jQuery-Selectors" }, { "code": null, "e": 2099, "s": 2092, "text": "Picked" }, { "code": null, "e": 2106, "s": 2099, "text": "JQuery" }, { "code": null, "e": 2123, "s": 2106, "text": "Web Technologies" }, { "code": null, "e": 2221, "s": 2123, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2250, "s": 2221, "text": "Form validation using jQuery" }, { "code": null, "e": 2306, "s": 2250, "text": "How to Dynamically Add/Remove Table Rows using jQuery ?" }, { "code": null, "e": 2360, "s": 2306, "text": "Scroll to the top of the page using JavaScript/jQuery" }, { "code": null, "e": 2417, "s": 2360, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 2451, "s": 2417, "text": "jQuery | children() with Examples" }, { "code": null, "e": 2501, "s": 2451, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2534, "s": 2501, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2596, "s": 2534, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2629, "s": 2596, "text": "Node.js fs.readFileSync() Method" } ]
How to use Pickle to save and load Variables in Python?
25 Feb, 2021 Serialization is a technique used to save the state of an object from any process. We can later use this state by deserialization, to continue the process. Pickle is a python module that makes it easy to serialize or save variables and load them when needed. Unlike JSON serialization, Pickle converts the object into a binary string. JSON is text specific, but Pickle is python specific, and it can serialize the custom classes which JSON fails to serialize. Due to this feature, it is heavily used in training machine learning models. This article discusses how variables can be saved and loaded in python using pickle. In python, dumps() method is used to save variables to a pickle file. Syntax: pickle.dumps(obj, protocol=None, *, fix_imports=True, buffer_callback=None) In python, loads() is used to load saved data from a pickled file Syntax: pickle.loads(data, /, *, fix_imports=True, encoding=”ASCII”, errors=”strict”, buffers=None) Method 1: Passing the variable In dumps() method, we can pass the variable, and it will return us the binary string for the same. We can then transmit it to other python modules or save in a database. Example: Python3 import pickle # Create a variablemyvar = [{'This': 'is', 'Example': 1}, 'of', 'serialisation', ['using', 'pickle']] # Use dumps() to make it serializedserialized = pickle.dumps(myvar) print(serialized) Output: b’\x80\x04\x95K\x00\x00\x00\x00\x00\x00\x00]\x94(}\x94(\x8c\x04This\x94\x8c\x02is\x94\x8c\x07Example\x94K\x01u\x8c\x02of\x94\x8c\rserialisation\x94]\x94(\x8c\x05using\x94\x8c\x06pickle\x94ee.’ Method 2: We can directly save the variable in a file itself. Example: Python3 import pickle # Create a variablemyvar = [{'This': 'is', 'Example': 2}, 'of', 'serialisation', ['using', 'pickle']] # Open a file and use dump()with open('file.pkl', 'wb') as file: # A new file will be created pickle.dump(myvar, file) Method 1: The loads() method takes a binary string and returns the corresponding variable. If the string is invalid, it throws a PickleError. Example: Python3 import pickle # This is the result of previous codebinary_string = b'\x80\x04\x95K\x00\x00\x00\x00\x00\x00\x00]\x94(}\x94(\x8c\x04This\x94\x8c\x02is\x94\x8c\x07Example\x94K\x01u\x8c\x02of\x94\x8c\rserialisation\x94]\x94(\x8c\x05using\x94\x8c\x06pickle\x94ee.' # Use loads to load the variablemyvar = pickle.loads(binary_string) print(myvar) Output: [{‘This’: ‘is’, ‘Example’: 1}, ‘of’, ‘serialisation’, [‘using’, ‘pickle’]] Method 2: The load() method loads a pickled file and returns a deserialized variable. Example: Python3 import pickle # Open the file in binary modewith open('file.pkl', 'rb') as file: # Call load method to deserialze myvar = pickle.load(file) print(myvar) Output: [{‘This’: ‘is’, ‘Example’: 2}, ‘of’, ‘serialisation’, [‘using’, ‘pickle’]] Picked python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 52, "s": 24, "text": "\n25 Feb, 2021" }, { "code": null, "e": 674, "s": 52, "text": "Serialization is a technique used to save the state of an object from any process. We can later use this state by deserialization, to continue the process. Pickle is a python module that makes it easy to serialize or save variables and load them when needed. Unlike JSON serialization, Pickle converts the object into a binary string. JSON is text specific, but Pickle is python specific, and it can serialize the custom classes which JSON fails to serialize. Due to this feature, it is heavily used in training machine learning models. This article discusses how variables can be saved and loaded in python using pickle." }, { "code": null, "e": 744, "s": 674, "text": "In python, dumps() method is used to save variables to a pickle file." }, { "code": null, "e": 752, "s": 744, "text": "Syntax:" }, { "code": null, "e": 828, "s": 752, "text": "pickle.dumps(obj, protocol=None, *, fix_imports=True, buffer_callback=None)" }, { "code": null, "e": 894, "s": 828, "text": "In python, loads() is used to load saved data from a pickled file" }, { "code": null, "e": 902, "s": 894, "text": "Syntax:" }, { "code": null, "e": 994, "s": 902, "text": "pickle.loads(data, /, *, fix_imports=True, encoding=”ASCII”, errors=”strict”, buffers=None)" }, { "code": null, "e": 1025, "s": 994, "text": "Method 1: Passing the variable" }, { "code": null, "e": 1195, "s": 1025, "text": "In dumps() method, we can pass the variable, and it will return us the binary string for the same. We can then transmit it to other python modules or save in a database." }, { "code": null, "e": 1204, "s": 1195, "text": "Example:" }, { "code": null, "e": 1212, "s": 1204, "text": "Python3" }, { "code": "import pickle # Create a variablemyvar = [{'This': 'is', 'Example': 1}, 'of', 'serialisation', ['using', 'pickle']] # Use dumps() to make it serializedserialized = pickle.dumps(myvar) print(serialized)", "e": 1425, "s": 1212, "text": null }, { "code": null, "e": 1433, "s": 1425, "text": "Output:" }, { "code": null, "e": 1626, "s": 1433, "text": "b’\\x80\\x04\\x95K\\x00\\x00\\x00\\x00\\x00\\x00\\x00]\\x94(}\\x94(\\x8c\\x04This\\x94\\x8c\\x02is\\x94\\x8c\\x07Example\\x94K\\x01u\\x8c\\x02of\\x94\\x8c\\rserialisation\\x94]\\x94(\\x8c\\x05using\\x94\\x8c\\x06pickle\\x94ee.’" }, { "code": null, "e": 1689, "s": 1626, "text": "Method 2: We can directly save the variable in a file itself." }, { "code": null, "e": 1698, "s": 1689, "text": "Example:" }, { "code": null, "e": 1706, "s": 1698, "text": "Python3" }, { "code": "import pickle # Create a variablemyvar = [{'This': 'is', 'Example': 2}, 'of', 'serialisation', ['using', 'pickle']] # Open a file and use dump()with open('file.pkl', 'wb') as file: # A new file will be created pickle.dump(myvar, file)", "e": 1963, "s": 1706, "text": null }, { "code": null, "e": 1974, "s": 1963, "text": "Method 1: " }, { "code": null, "e": 2106, "s": 1974, "text": "The loads() method takes a binary string and returns the corresponding variable. If the string is invalid, it throws a PickleError." }, { "code": null, "e": 2115, "s": 2106, "text": "Example:" }, { "code": null, "e": 2123, "s": 2115, "text": "Python3" }, { "code": "import pickle # This is the result of previous codebinary_string = b'\\x80\\x04\\x95K\\x00\\x00\\x00\\x00\\x00\\x00\\x00]\\x94(}\\x94(\\x8c\\x04This\\x94\\x8c\\x02is\\x94\\x8c\\x07Example\\x94K\\x01u\\x8c\\x02of\\x94\\x8c\\rserialisation\\x94]\\x94(\\x8c\\x05using\\x94\\x8c\\x06pickle\\x94ee.' # Use loads to load the variablemyvar = pickle.loads(binary_string) print(myvar)", "e": 2467, "s": 2123, "text": null }, { "code": null, "e": 2475, "s": 2467, "text": "Output:" }, { "code": null, "e": 2550, "s": 2475, "text": "[{‘This’: ‘is’, ‘Example’: 1}, ‘of’, ‘serialisation’, [‘using’, ‘pickle’]]" }, { "code": null, "e": 2561, "s": 2550, "text": "Method 2: " }, { "code": null, "e": 2637, "s": 2561, "text": "The load() method loads a pickled file and returns a deserialized variable." }, { "code": null, "e": 2646, "s": 2637, "text": "Example:" }, { "code": null, "e": 2654, "s": 2646, "text": "Python3" }, { "code": "import pickle # Open the file in binary modewith open('file.pkl', 'rb') as file: # Call load method to deserialze myvar = pickle.load(file) print(myvar)", "e": 2825, "s": 2654, "text": null }, { "code": null, "e": 2833, "s": 2825, "text": "Output:" }, { "code": null, "e": 2908, "s": 2833, "text": "[{‘This’: ‘is’, ‘Example’: 2}, ‘of’, ‘serialisation’, [‘using’, ‘pickle’]]" }, { "code": null, "e": 2915, "s": 2908, "text": "Picked" }, { "code": null, "e": 2930, "s": 2915, "text": "python-utility" }, { "code": null, "e": 2937, "s": 2930, "text": "Python" }, { "code": null, "e": 3035, "s": 2937, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3067, "s": 3035, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3094, "s": 3067, "text": "Python Classes and Objects" }, { "code": null, "e": 3115, "s": 3094, "text": "Python OOPs Concepts" }, { "code": null, "e": 3138, "s": 3115, "text": "Introduction To PYTHON" }, { "code": null, "e": 3169, "s": 3138, "text": "Python | os.path.join() method" }, { "code": null, "e": 3225, "s": 3169, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3267, "s": 3225, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3309, "s": 3267, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3348, "s": 3309, "text": "Python | Get unique values from a list" } ]
Extract numbers from a text file and add them using Python - GeeksforGeeks
19 May, 2021 Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. Data file handling in Python is done in two types of files: Text file (.txt extension) Binary file (.bin extension) Here we are operating on the .txt file in Python. Through this program, we can extract numbers from the content in the text file and add them all and print the result. Reading the contents of the file, we will match the characters’ type against int. If the result of equality is true, then the number will be added to the number stored in the memory allocated to the variable ‘a’. We initiate the variable ‘a’ here with the value 0. Python3 # Python program for writing# to file file = open('GFG.txt', 'w') # Data to be writtendata ='Geeks1 f2or G8e8e3k2s0' # Writing to filefile.write(data) # Closing filefile.close() Using the above code, we opened a new file named ‘GFG’ in write mode. Using, the write() function we inserted the data allocated to the variable data in the memory. After this, we closed the file.Reading from the above-created file and extracting the integers. Python3 # Python program for reading# from file h = open('GFG.txt', 'r') # Reading from the filecontent = h.readlines() # Variable for storing the suma = 0 # Iterating through the content# Of the filefor line in content: for i in line: # Checking for the digit in # the string if i.isdigit() == True: a += int(i) print("The sum is:", a) Output: The sum is: 24 The above program emphasizes on extracting the numbers from the content stored in the text file named ‘GFG’. Furthermore, the numbers are then added after typecasting and stored in the variable ‘a’. arorakashish0911 Python file-handling-programs python-file-handling 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 Python | Get dictionary keys as a list Bar Plot in Matplotlib Multithreading in Python | Set 2 (Synchronization) Python Dictionary keys() method loops in python Python - Call function from another file Ways to filter Pandas DataFrame by column values Python | Convert set into a list Python program to find number of days between two given dates
[ { "code": null, "e": 23901, "s": 23873, "text": "\n19 May, 2021" }, { "code": null, "e": 24127, "s": 23901, "text": "Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. Data file handling in Python is done in two types of files: " }, { "code": null, "e": 24156, "s": 24127, "text": "Text file (.txt extension) " }, { "code": null, "e": 24187, "s": 24156, "text": "Binary file (.bin extension) " }, { "code": null, "e": 24356, "s": 24187, "text": "Here we are operating on the .txt file in Python. Through this program, we can extract numbers from the content in the text file and add them all and print the result. " }, { "code": null, "e": 24622, "s": 24356, "text": "Reading the contents of the file, we will match the characters’ type against int. If the result of equality is true, then the number will be added to the number stored in the memory allocated to the variable ‘a’. We initiate the variable ‘a’ here with the value 0. " }, { "code": null, "e": 24630, "s": 24622, "text": "Python3" }, { "code": "# Python program for writing# to file file = open('GFG.txt', 'w') # Data to be writtendata ='Geeks1 f2or G8e8e3k2s0' # Writing to filefile.write(data) # Closing filefile.close()", "e": 24809, "s": 24630, "text": null }, { "code": null, "e": 25071, "s": 24809, "text": "Using the above code, we opened a new file named ‘GFG’ in write mode. Using, the write() function we inserted the data allocated to the variable data in the memory. After this, we closed the file.Reading from the above-created file and extracting the integers. " }, { "code": null, "e": 25079, "s": 25071, "text": "Python3" }, { "code": "# Python program for reading# from file h = open('GFG.txt', 'r') # Reading from the filecontent = h.readlines() # Variable for storing the suma = 0 # Iterating through the content# Of the filefor line in content: for i in line: # Checking for the digit in # the string if i.isdigit() == True: a += int(i) print(\"The sum is:\", a)", "e": 25471, "s": 25079, "text": null }, { "code": null, "e": 25480, "s": 25471, "text": "Output: " }, { "code": null, "e": 25495, "s": 25480, "text": "The sum is: 24" }, { "code": null, "e": 25695, "s": 25495, "text": "The above program emphasizes on extracting the numbers from the content stored in the text file named ‘GFG’. Furthermore, the numbers are then added after typecasting and stored in the variable ‘a’. " }, { "code": null, "e": 25712, "s": 25695, "text": "arorakashish0911" }, { "code": null, "e": 25742, "s": 25712, "text": "Python file-handling-programs" }, { "code": null, "e": 25763, "s": 25742, "text": "python-file-handling" }, { "code": null, "e": 25770, "s": 25763, "text": "Python" }, { "code": null, "e": 25868, "s": 25770, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25877, "s": 25868, "text": "Comments" }, { "code": null, "e": 25890, "s": 25877, "text": "Old Comments" }, { "code": null, "e": 25926, "s": 25890, "text": "Box Plot in Python using Matplotlib" }, { "code": null, "e": 25965, "s": 25926, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 25988, "s": 25965, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 26039, "s": 25988, "text": "Multithreading in Python | Set 2 (Synchronization)" }, { "code": null, "e": 26071, "s": 26039, "text": "Python Dictionary keys() method" }, { "code": null, "e": 26087, "s": 26071, "text": "loops in python" }, { "code": null, "e": 26128, "s": 26087, "text": "Python - Call function from another file" }, { "code": null, "e": 26177, "s": 26128, "text": "Ways to filter Pandas DataFrame by column values" }, { "code": null, "e": 26210, "s": 26177, "text": "Python | Convert set into a list" } ]
Computer Vision for Beginners: Part 4 | by Jiwon Jeong | Towards Data Science
There are lots of ways out there one can adapt to make learning progress efficiently. As for me, combining studies with a little bit of fun is the best strategy. In this series of tutorials, many images have been used to demonstrate image processing concepts. It might interest you to note that people enjoyed the parts of the series where I applied the concept to the images in a funny way. And I recommend you also merge fun with studying. This is the last part of OpenCV tutorial for beginners and the complete set of the series is like follows: Understanding color models and drawing figures on imagesThe basics of image processing with filtering and gradientsFrom feature detection to face detectionContour detection and having a little bit of fun Understanding color models and drawing figures on images The basics of image processing with filtering and gradients From feature detection to face detection Contour detection and having a little bit of fun From the first series, we saw how to draw a figure on an image. We also talked about how to apply blurring and thresholding with various options. And in part 3, we discussed several detection algorithms including edge detection. There is another detection technique called contour detection which is essential in object detection. And after that, we’re going to round up this series with a little bit of fun playing with masking. This article assumes you’ve been following the previous steps or you already know those concepts. But if it’s not the case, please check the previous parts of this series. The complete code for this tutorial is available on Github as always. You may be already familiar with the word ‘contour.’ I’ve used this term several times in previous posts. A contour line indicates a curved line representing the boundary of the same values or the same intensities. A contour map is the most straightforward example we can think of. But then you may ask this. What’s the difference between edges and contours? The two terms are often used interchangeably so it could be a bit confusing. To put it simply, the concept of edges lies in a local range while the concept of contours is at the overall boundary of a figure. Edges are points whose values change significantly compared to their neighboring points. Contours, on the other hand, are closed curves which are obtained from edges and depicting a boundary of figures. You can find a further explanation here. # Load the imageimg = cv2.imread('images/pine_apple.jpg')img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)plt.imshow(img) So what we’re going to do is detecting the contour of this pineapple. Before applying the detection algorithm, we need to convert the image into grayscale and apply thresholding as follows. All of these steps are what we’ve discussed in the previous series. # Blurring for removing the noise img_blur = cv2.bilateralFilter(img, d = 7, sigmaSpace = 75, sigmaColor =75)# Convert to grayscale img_gray = cv2.cvtColor(img_blur, cv2.COLOR_RGB2GRAY)# Apply the thresholdinga = img_gray.max() _, thresh = cv2.threshold(img_gray, a/2+60, a,cv2.THRESH_BINARY_INV)plt.imshow(thresh, cmap = 'gray') Contour detection can be implemented by the functioncv2.findContours() in OpenCV and there are two important parameters here. mode is the way of finding contours, and method is the approximation method for the detection. I ask you to find other information from the documentation. # Find the contour of the figure image, contours, hierarchy = cv2.findContours( image = thresh, mode = cv2.RETR_TREE, method = cv2.CHAIN_APPROX_SIMPLE) The mode cv2.RETR_TREE finds all the promising contour lines and reconstructs a full hierarchy of nested contours. The method cv2.CHAIN_APPROX_SIMPLE returns only the endpoints that are necessary for drawing the contour line. And as you can see above, this function gives the image, the detected contours and their hierarchy as its output. The returned contour is a list of points consisting of the contour lines. To draw the outer line of the figure, we’ll sort the contours by their area. With the selected contour line, cv2.drawContours() will depict the bounding line along with the points as shown below. # Sort the contours contours = sorted(contours, key = cv2.contourArea, reverse = True)# Draw the contour img_copy = img.copy()final = cv2.drawContours(img_copy, contours, contourIdx = -1, color = (255, 0, 0), thickness = 2)plt.imshow(img_copy) It’s simple, right? Although the shadow is also added at the bottom, the outcome is pretty satisfactory. There are more things we can do with the contour. We can find the centroid of an image or calculate the area of a boundary field with the help of the notion called image moment. What does a moment mean here? The word ‘moment’ is a short period of time in common usage. But in physics terminology, a moment is the product of the distance and another physical quantity meaning how a physical quantity is distributed or located. So in computer vision, Image moment is how image pixel intensities are distributed according to their location. It’s a weighted average of image pixel intensities and we can get the centroid or spatial information from the image moment. There are three types of moments- spatial moments, central moments, and central normalized moments. We can get the image moment with the function cv2.moments() in OpenCV and it returns 24 different moments. If you print the output M as shown below, it’ll return the 24 moments in a dictionary format. # The first order of the contoursc_0 = contours[0]# image momentM = cv2.moments(c_0)print(M.keys()) I’d like to focus on the implementation of the image moments here. Additional reading resources can be found at the end of this article if you may have an interest. To get the area of the contours, we can implement the function cv2.contourArea() . Why don’t we try several contours here? If you input the first, second and third contours, you’ll get the decreasing values as shown below. This shows that the contour detection algorithm forms the hierarchy of the detected boundaries. # The area of contours print("1st Contour Area : ", cv2.contourArea(contours[0])) # 37544.5print("2nd Contour Area : ", cv2.contourArea(contours[1])) # 75.0print("3rd Contour Area : ", cv2.contourArea(contours[2])) # 54.0 The arc length of the contour can be obtained by the function cv2.arcLength() . The parameter closed indicates whether the curve should be closed or not. # The arc length of contours print(cv2.arcLength(contours[0], closed = True)) # 2473.3190print(cv2.arcLength(contours[0], closed = False)) # 2472.3190 Now let’s try plotting the centroid and the extreme points of our pineapple. We can get the centroid point with the formula as follows. # The centroid pointcx = int(M['m10'] / M['m00'])cy = int(M['m01'] / M['m00']) The extrema are the endpoints on the left and right, at the top and bottom. And we can arrange x and y coordinates separately as follows. # The extreme pointsl_m = tuple(c_0[c_0[:, :, 0].argmin()][0])r_m = tuple(c_0[c_0[:, :, 0].argmax()][0])t_m = tuple(c_0[c_0[:, :, 1].argmin()][0])b_m = tuple(c_0[c_0[:, :, 1].argmax()][0])pst = [l_m, r_m, t_m, b_m]xcor = [p[0] for p in pst]ycor = [p[1] for p in pst] Now let’s plot all these points on the image. # Plot the pointsplt.figure(figsize = (10, 16))plt.subplot(1, 2, 1)plt.imshow(image, cmap = 'gray')plt.scatter([cx], [cy], c = 'b', s = 50)plt.subplot(1, 2, 2)plt.imshow(image, cmap = 'gray')plt.scatter(xcor, ycor, c = 'b', s = 50) Besides the compact contour, we can also draw a convex contour or rectangular contour line of a figure. Let’s try a straight rectangular shape first. With the outer contour line, we’ll draw the rectangle around the object. The function cv2.boundingRect() returns the 4 points of the bounding box as shown below. # The first order of the contoursc_0 = contours[0]# Get the 4 points of the bounding rectanglex, y, w, h = cv2.boundingRect(c_0)# Draw a straight rectangle with the pointsimg_copy = img.copy()img_box = cv2.rectangle(img_copy, (x, y), (x+w, y+h), color = (255, 0, 0), thickness = 2) Note that this straight rectangle isn’t the minimum among other possible boundings. We can extract the rectangle with the minimum area with the function cv2.minAreaRect() which finds a rotated rectangle enclosing the input 2D point set. After that, we get the 4 corners of this rectangle and put them at the contour parameter as shown below. # Get the 4 points of the bounding rectangle with the minimum arearect = cv2.minAreaRect(c_0)box = cv2.boxPoints(rect)box = box.astype('int')# Draw a contour with the points img_copy = img.copy()img_box_2 = cv2.drawContours(img_copy, contours = [box], contourIdx = -1, color = (255, 0, 0), thickness = 2) Now let’s check the result and compare the two different contour boxes. plt.figure(figsize = (10, 16))plt.subplot(1, 2, 1); plt.imshow(img_box)plt.subplot(1, 2, 2); plt.imshow(img_box_2) We can also draw a convex shape contour with the function cv2.convexHull(). This takes a set of points and returns the convex hull from the given set. And by inputting this returned points as contours in cv2.drawContours() , we can get the convex contour as follows. # Detect the convex contourhull = cv2.convexHull(c_0)img_copy = img.copy()img_hull = cv2.drawContours(img_copy, contours = [hull], contourIdx = 0, color = (255, 0, 0), thickness = 2)plt.imshow(img_hull) There are so many things to cover in contour detections. I encourage you to check the documentation and explore more options by yourself. For the last exercise of this series, I’d like to have some fun time with doing image masking. We can add two different images with arithmetic operations such as image addition or bitwise operation. So our final task is attaching our Mr.pineapple on a man’s left shoulder. # Import the large imagebackpacker = cv2.imread('images/backpacker.jpg')backpacker = cv2.cvtColor(backpacker, cv2.COLOR_BGR2RGB)plt.imshow(backpacker) We’ll cut the region of interest (the shoulder part) from the large image and the small image as shown below. Note that the size of the two images (the height and the width of the image) should be the same here. # Crop the small image and the roiroi = backpacker[750:1150, 300:500]img_2 = img[40:440, 80:280]plt.figure(figsize = (6, 6))plt.subplot(1, 3, 1); plt.imshow(roi)plt.subplot(1, 3, 3); plt.imshow(img_2) The next step is making the mask for each image. We’re going to implement bitwise operation with the masks which should be a binary image. By thresholding the small image img_2 , we create the mask. And then with cv2.bitwise_not(), we make another mask which is exactly the opposite of the first one. # Creating the mask for the roi and small imageimg_gray = cv2.cvtColor(img_2, cv2.COLOR_RGB2GRAY)_, mask = cv2.threshold(img_gray, 254/2+100, 255, cv2.THRESH_BINARY)mask_inv = cv2.bitwise_not(mask)plt.figure(figsize = (6, 6))plt.subplot(1, 3, 1); plt.imshow(mask, cmap = 'gray')plt.subplot(1, 3, 3); plt.imshow(mask_inv, cmap = 'gray') If we implement the function cv2.bitwise_and() and the masks, they will pass only the white area of the image. Therefore if we apply the first mask to the roi image, we can set the background image from it. In the same way, if we apply the second one to the img_2 image, we can make the foreground image with the fruit. # Masking img_bg = cv2.bitwise_and(roi, roi, mask = mask)img_fg = cv2.bitwise_and(img_2, img_2, mask = mask_inv)dst = cv2.add(img_fg, img_bg)plt.figure(figsize = (10, 6))plt.subplot(1, 3, 1); plt.imshow(img_bg)plt.subplot(1, 3, 2); plt.imshow(img_fg)plt.subplot(1, 3, 3); plt.imshow(dst) The outcome is a bit shambles considering the shadow at the bottom but let’s keep it. If you’d like to learn how the bitwise operation works, a detailed explanation can be found here. Now we’re ready to attach this combined image to the original one. So we can simply do this by putting the dst image at the roi position as shown below. # Final outputbackpacker[750:1150, 300:500] = dstdisplay(backpacker) 😄👋 Have a nice time with the backpacker man! From part 1 to part 4, we’ve learned quite a lot about the basics of image processing and computer vision. Did you enjoy all these tutorials so far? I hope you now get confident with the skills while following this series. If you’re a complete starter in image processing, it is normal being unfamiliar with the terms and the usage of the OpenCV functions at first. The best way to practice is by implementing all of these by yourself. Pick any kind of images you like and just have fun with them. Changing color modes, rotating and resizing the image, masking and pasting it on a different image. Or you could also apply the detection technique of edges, corners and contours. While having fun by combining several preprocessing and trying different parameters, you can get used to OpenCV library faster without realizing. Image moments on Wikipedia Image moments course on Udacity Shape Matching using Hu Moments (C++/Python) Find the Center of a Blob (Centroid) using OpenCV (C++/Python) Are there errors you would love to correct? Please share your insight with us. I’m always open to talk, so feel free to leave comments below and share your thoughts. I also share interesting and useful resources on LinkedIn so feel free to follow and reach out to me. I’ll be back with another interesting story, next time. As always, please stay tuned! 😎
[ { "code": null, "e": 614, "s": 172, "text": "There are lots of ways out there one can adapt to make learning progress efficiently. As for me, combining studies with a little bit of fun is the best strategy. In this series of tutorials, many images have been used to demonstrate image processing concepts. It might interest you to note that people enjoyed the parts of the series where I applied the concept to the images in a funny way. And I recommend you also merge fun with studying." }, { "code": null, "e": 721, "s": 614, "text": "This is the last part of OpenCV tutorial for beginners and the complete set of the series is like follows:" }, { "code": null, "e": 925, "s": 721, "text": "Understanding color models and drawing figures on imagesThe basics of image processing with filtering and gradientsFrom feature detection to face detectionContour detection and having a little bit of fun" }, { "code": null, "e": 982, "s": 925, "text": "Understanding color models and drawing figures on images" }, { "code": null, "e": 1042, "s": 982, "text": "The basics of image processing with filtering and gradients" }, { "code": null, "e": 1083, "s": 1042, "text": "From feature detection to face detection" }, { "code": null, "e": 1132, "s": 1083, "text": "Contour detection and having a little bit of fun" }, { "code": null, "e": 1562, "s": 1132, "text": "From the first series, we saw how to draw a figure on an image. We also talked about how to apply blurring and thresholding with various options. And in part 3, we discussed several detection algorithms including edge detection. There is another detection technique called contour detection which is essential in object detection. And after that, we’re going to round up this series with a little bit of fun playing with masking." }, { "code": null, "e": 1804, "s": 1562, "text": "This article assumes you’ve been following the previous steps or you already know those concepts. But if it’s not the case, please check the previous parts of this series. The complete code for this tutorial is available on Github as always." }, { "code": null, "e": 2086, "s": 1804, "text": "You may be already familiar with the word ‘contour.’ I’ve used this term several times in previous posts. A contour line indicates a curved line representing the boundary of the same values or the same intensities. A contour map is the most straightforward example we can think of." }, { "code": null, "e": 2615, "s": 2086, "text": "But then you may ask this. What’s the difference between edges and contours? The two terms are often used interchangeably so it could be a bit confusing. To put it simply, the concept of edges lies in a local range while the concept of contours is at the overall boundary of a figure. Edges are points whose values change significantly compared to their neighboring points. Contours, on the other hand, are closed curves which are obtained from edges and depicting a boundary of figures. You can find a further explanation here." }, { "code": null, "e": 2730, "s": 2615, "text": "# Load the imageimg = cv2.imread('images/pine_apple.jpg')img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)plt.imshow(img)" }, { "code": null, "e": 2988, "s": 2730, "text": "So what we’re going to do is detecting the contour of this pineapple. Before applying the detection algorithm, we need to convert the image into grayscale and apply thresholding as follows. All of these steps are what we’ve discussed in the previous series." }, { "code": null, "e": 3350, "s": 2988, "text": "# Blurring for removing the noise img_blur = cv2.bilateralFilter(img, d = 7, sigmaSpace = 75, sigmaColor =75)# Convert to grayscale img_gray = cv2.cvtColor(img_blur, cv2.COLOR_RGB2GRAY)# Apply the thresholdinga = img_gray.max() _, thresh = cv2.threshold(img_gray, a/2+60, a,cv2.THRESH_BINARY_INV)plt.imshow(thresh, cmap = 'gray')" }, { "code": null, "e": 3631, "s": 3350, "text": "Contour detection can be implemented by the functioncv2.findContours() in OpenCV and there are two important parameters here. mode is the way of finding contours, and method is the approximation method for the detection. I ask you to find other information from the documentation." }, { "code": null, "e": 3887, "s": 3631, "text": "# Find the contour of the figure image, contours, hierarchy = cv2.findContours( image = thresh, mode = cv2.RETR_TREE, method = cv2.CHAIN_APPROX_SIMPLE)" }, { "code": null, "e": 4227, "s": 3887, "text": "The mode cv2.RETR_TREE finds all the promising contour lines and reconstructs a full hierarchy of nested contours. The method cv2.CHAIN_APPROX_SIMPLE returns only the endpoints that are necessary for drawing the contour line. And as you can see above, this function gives the image, the detected contours and their hierarchy as its output." }, { "code": null, "e": 4497, "s": 4227, "text": "The returned contour is a list of points consisting of the contour lines. To draw the outer line of the figure, we’ll sort the contours by their area. With the selected contour line, cv2.drawContours() will depict the bounding line along with the points as shown below." }, { "code": null, "e": 4766, "s": 4497, "text": "# Sort the contours contours = sorted(contours, key = cv2.contourArea, reverse = True)# Draw the contour img_copy = img.copy()final = cv2.drawContours(img_copy, contours, contourIdx = -1, color = (255, 0, 0), thickness = 2)plt.imshow(img_copy)" }, { "code": null, "e": 4871, "s": 4766, "text": "It’s simple, right? Although the shadow is also added at the bottom, the outcome is pretty satisfactory." }, { "code": null, "e": 5534, "s": 4871, "text": "There are more things we can do with the contour. We can find the centroid of an image or calculate the area of a boundary field with the help of the notion called image moment. What does a moment mean here? The word ‘moment’ is a short period of time in common usage. But in physics terminology, a moment is the product of the distance and another physical quantity meaning how a physical quantity is distributed or located. So in computer vision, Image moment is how image pixel intensities are distributed according to their location. It’s a weighted average of image pixel intensities and we can get the centroid or spatial information from the image moment." }, { "code": null, "e": 5835, "s": 5534, "text": "There are three types of moments- spatial moments, central moments, and central normalized moments. We can get the image moment with the function cv2.moments() in OpenCV and it returns 24 different moments. If you print the output M as shown below, it’ll return the 24 moments in a dictionary format." }, { "code": null, "e": 5935, "s": 5835, "text": "# The first order of the contoursc_0 = contours[0]# image momentM = cv2.moments(c_0)print(M.keys())" }, { "code": null, "e": 6100, "s": 5935, "text": "I’d like to focus on the implementation of the image moments here. Additional reading resources can be found at the end of this article if you may have an interest." }, { "code": null, "e": 6419, "s": 6100, "text": "To get the area of the contours, we can implement the function cv2.contourArea() . Why don’t we try several contours here? If you input the first, second and third contours, you’ll get the decreasing values as shown below. This shows that the contour detection algorithm forms the hierarchy of the detected boundaries." }, { "code": null, "e": 6641, "s": 6419, "text": "# The area of contours print(\"1st Contour Area : \", cv2.contourArea(contours[0])) # 37544.5print(\"2nd Contour Area : \", cv2.contourArea(contours[1])) # 75.0print(\"3rd Contour Area : \", cv2.contourArea(contours[2])) # 54.0" }, { "code": null, "e": 6795, "s": 6641, "text": "The arc length of the contour can be obtained by the function cv2.arcLength() . The parameter closed indicates whether the curve should be closed or not." }, { "code": null, "e": 6955, "s": 6795, "text": "# The arc length of contours print(cv2.arcLength(contours[0], closed = True)) # 2473.3190print(cv2.arcLength(contours[0], closed = False)) # 2472.3190" }, { "code": null, "e": 7091, "s": 6955, "text": "Now let’s try plotting the centroid and the extreme points of our pineapple. We can get the centroid point with the formula as follows." }, { "code": null, "e": 7170, "s": 7091, "text": "# The centroid pointcx = int(M['m10'] / M['m00'])cy = int(M['m01'] / M['m00'])" }, { "code": null, "e": 7308, "s": 7170, "text": "The extrema are the endpoints on the left and right, at the top and bottom. And we can arrange x and y coordinates separately as follows." }, { "code": null, "e": 7575, "s": 7308, "text": "# The extreme pointsl_m = tuple(c_0[c_0[:, :, 0].argmin()][0])r_m = tuple(c_0[c_0[:, :, 0].argmax()][0])t_m = tuple(c_0[c_0[:, :, 1].argmin()][0])b_m = tuple(c_0[c_0[:, :, 1].argmax()][0])pst = [l_m, r_m, t_m, b_m]xcor = [p[0] for p in pst]ycor = [p[1] for p in pst]" }, { "code": null, "e": 7621, "s": 7575, "text": "Now let’s plot all these points on the image." }, { "code": null, "e": 7853, "s": 7621, "text": "# Plot the pointsplt.figure(figsize = (10, 16))plt.subplot(1, 2, 1)plt.imshow(image, cmap = 'gray')plt.scatter([cx], [cy], c = 'b', s = 50)plt.subplot(1, 2, 2)plt.imshow(image, cmap = 'gray')plt.scatter(xcor, ycor, c = 'b', s = 50)" }, { "code": null, "e": 8165, "s": 7853, "text": "Besides the compact contour, we can also draw a convex contour or rectangular contour line of a figure. Let’s try a straight rectangular shape first. With the outer contour line, we’ll draw the rectangle around the object. The function cv2.boundingRect() returns the 4 points of the bounding box as shown below." }, { "code": null, "e": 8447, "s": 8165, "text": "# The first order of the contoursc_0 = contours[0]# Get the 4 points of the bounding rectanglex, y, w, h = cv2.boundingRect(c_0)# Draw a straight rectangle with the pointsimg_copy = img.copy()img_box = cv2.rectangle(img_copy, (x, y), (x+w, y+h), color = (255, 0, 0), thickness = 2)" }, { "code": null, "e": 8789, "s": 8447, "text": "Note that this straight rectangle isn’t the minimum among other possible boundings. We can extract the rectangle with the minimum area with the function cv2.minAreaRect() which finds a rotated rectangle enclosing the input 2D point set. After that, we get the 4 corners of this rectangle and put them at the contour parameter as shown below." }, { "code": null, "e": 9152, "s": 8789, "text": "# Get the 4 points of the bounding rectangle with the minimum arearect = cv2.minAreaRect(c_0)box = cv2.boxPoints(rect)box = box.astype('int')# Draw a contour with the points img_copy = img.copy()img_box_2 = cv2.drawContours(img_copy, contours = [box], contourIdx = -1, color = (255, 0, 0), thickness = 2)" }, { "code": null, "e": 9224, "s": 9152, "text": "Now let’s check the result and compare the two different contour boxes." }, { "code": null, "e": 9339, "s": 9224, "text": "plt.figure(figsize = (10, 16))plt.subplot(1, 2, 1); plt.imshow(img_box)plt.subplot(1, 2, 2); plt.imshow(img_box_2)" }, { "code": null, "e": 9606, "s": 9339, "text": "We can also draw a convex shape contour with the function cv2.convexHull(). This takes a set of points and returns the convex hull from the given set. And by inputting this returned points as contours in cv2.drawContours() , we can get the convex contour as follows." }, { "code": null, "e": 9865, "s": 9606, "text": "# Detect the convex contourhull = cv2.convexHull(c_0)img_copy = img.copy()img_hull = cv2.drawContours(img_copy, contours = [hull], contourIdx = 0, color = (255, 0, 0), thickness = 2)plt.imshow(img_hull)" }, { "code": null, "e": 10003, "s": 9865, "text": "There are so many things to cover in contour detections. I encourage you to check the documentation and explore more options by yourself." }, { "code": null, "e": 10276, "s": 10003, "text": "For the last exercise of this series, I’d like to have some fun time with doing image masking. We can add two different images with arithmetic operations such as image addition or bitwise operation. So our final task is attaching our Mr.pineapple on a man’s left shoulder." }, { "code": null, "e": 10427, "s": 10276, "text": "# Import the large imagebackpacker = cv2.imread('images/backpacker.jpg')backpacker = cv2.cvtColor(backpacker, cv2.COLOR_BGR2RGB)plt.imshow(backpacker)" }, { "code": null, "e": 10639, "s": 10427, "text": "We’ll cut the region of interest (the shoulder part) from the large image and the small image as shown below. Note that the size of the two images (the height and the width of the image) should be the same here." }, { "code": null, "e": 10840, "s": 10639, "text": "# Crop the small image and the roiroi = backpacker[750:1150, 300:500]img_2 = img[40:440, 80:280]plt.figure(figsize = (6, 6))plt.subplot(1, 3, 1); plt.imshow(roi)plt.subplot(1, 3, 3); plt.imshow(img_2)" }, { "code": null, "e": 11141, "s": 10840, "text": "The next step is making the mask for each image. We’re going to implement bitwise operation with the masks which should be a binary image. By thresholding the small image img_2 , we create the mask. And then with cv2.bitwise_not(), we make another mask which is exactly the opposite of the first one." }, { "code": null, "e": 11477, "s": 11141, "text": "# Creating the mask for the roi and small imageimg_gray = cv2.cvtColor(img_2, cv2.COLOR_RGB2GRAY)_, mask = cv2.threshold(img_gray, 254/2+100, 255, cv2.THRESH_BINARY)mask_inv = cv2.bitwise_not(mask)plt.figure(figsize = (6, 6))plt.subplot(1, 3, 1); plt.imshow(mask, cmap = 'gray')plt.subplot(1, 3, 3); plt.imshow(mask_inv, cmap = 'gray')" }, { "code": null, "e": 11797, "s": 11477, "text": "If we implement the function cv2.bitwise_and() and the masks, they will pass only the white area of the image. Therefore if we apply the first mask to the roi image, we can set the background image from it. In the same way, if we apply the second one to the img_2 image, we can make the foreground image with the fruit." }, { "code": null, "e": 12085, "s": 11797, "text": "# Masking img_bg = cv2.bitwise_and(roi, roi, mask = mask)img_fg = cv2.bitwise_and(img_2, img_2, mask = mask_inv)dst = cv2.add(img_fg, img_bg)plt.figure(figsize = (10, 6))plt.subplot(1, 3, 1); plt.imshow(img_bg)plt.subplot(1, 3, 2); plt.imshow(img_fg)plt.subplot(1, 3, 3); plt.imshow(dst)" }, { "code": null, "e": 12422, "s": 12085, "text": "The outcome is a bit shambles considering the shadow at the bottom but let’s keep it. If you’d like to learn how the bitwise operation works, a detailed explanation can be found here. Now we’re ready to attach this combined image to the original one. So we can simply do this by putting the dst image at the roi position as shown below." }, { "code": null, "e": 12491, "s": 12422, "text": "# Final outputbackpacker[750:1150, 300:500] = dstdisplay(backpacker)" }, { "code": null, "e": 12536, "s": 12491, "text": "😄👋 Have a nice time with the backpacker man!" }, { "code": null, "e": 12759, "s": 12536, "text": "From part 1 to part 4, we’ve learned quite a lot about the basics of image processing and computer vision. Did you enjoy all these tutorials so far? I hope you now get confident with the skills while following this series." }, { "code": null, "e": 13360, "s": 12759, "text": "If you’re a complete starter in image processing, it is normal being unfamiliar with the terms and the usage of the OpenCV functions at first. The best way to practice is by implementing all of these by yourself. Pick any kind of images you like and just have fun with them. Changing color modes, rotating and resizing the image, masking and pasting it on a different image. Or you could also apply the detection technique of edges, corners and contours. While having fun by combining several preprocessing and trying different parameters, you can get used to OpenCV library faster without realizing." }, { "code": null, "e": 13387, "s": 13360, "text": "Image moments on Wikipedia" }, { "code": null, "e": 13419, "s": 13387, "text": "Image moments course on Udacity" }, { "code": null, "e": 13464, "s": 13419, "text": "Shape Matching using Hu Moments (C++/Python)" }, { "code": null, "e": 13527, "s": 13464, "text": "Find the Center of a Blob (Centroid) using OpenCV (C++/Python)" } ]
How to handle date in JDBC?
You can insert date values in SQL using the date datatype, The java.sql.Date class maps to the SQL DATE type. The PreparedStatement interface provides a method named setDate(). Using this you can insert date into a table. This method accepts two parameters − An integer representing the parameter index of the place holder (?) to which we need to set date value. An integer representing the parameter index of the place holder (?) to which we need to set date value. a Date object representing the date value to be passed. The constructor of java.sql.Date class accepts a variable of long type representing the number of milliseconds from the epoch (standard base time I.e. January 1, 1970, 00:00:00 GMT). a Date object representing the date value to be passed. The constructor of java.sql.Date class accepts a variable of long type representing the number of milliseconds from the epoch (standard base time I.e. January 1, 1970, 00:00:00 GMT). Assume we have created a table named Emp in MySQL database with the following description − +----------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------+--------------+------+-----+---------+-------+ | Name | varchar(255) | YES | | NULL | | | DOB | date | YES | | NULL | | | Location | varchar(255) | YES | | NULL | | +----------+--------------+------+-----+---------+-------+ Following JDBC program inserts records in to this table − import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.sql.Date; public class InsertingDate { public static void main(String args[])throws Exception { //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/sampleDB"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Inserting values to a table String query = "INSERT INTO Emp(Name, DOB, Location) VALUES (?, ?, ?)"; PreparedStatement pstmt = con.prepareStatement(query); pstmt.setString(1, "Amit"); pstmt.setDate(2, new Date(622790105000L)); pstmt.setString(3, "Hyderabad"); pstmt.execute(); pstmt.setString(1, "Sumith"); pstmt.setDate(2, new Date(620611200000L)); pstmt.setString(3, "Vishakhapatnam"); pstmt.execute(); pstmt.setString(1, "Sudha"); pstmt.setDate(2, new Date(336614400000L)); pstmt.setString(3, "Vijayawada"); pstmt.execute(); System.out.println("Records inserted......"); } } Connection established...... Records inserted...... If you verify the table in MySQL database, you can observe the contents of the table as − mysql> select * from Emp; +--------+------------+----------------+ | Name | DOB | Location | +--------+------------+----------------+ | Amit | 1989-09-26 | Hyderabad | | Sumith | 2019-03-19 | Vishakhapatnam | | Sudha | 2019-03-19 | Vijayawada | +--------+------------+----------------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1172, "s": 1062, "text": "You can insert date values in SQL using the date datatype, The java.sql.Date class maps to the SQL DATE type." }, { "code": null, "e": 1321, "s": 1172, "text": "The PreparedStatement interface provides a method named setDate(). Using this you can insert date into a table. This method accepts two parameters −" }, { "code": null, "e": 1425, "s": 1321, "text": "An integer representing the parameter index of the place holder (?) to which we need to set date value." }, { "code": null, "e": 1529, "s": 1425, "text": "An integer representing the parameter index of the place holder (?) to which we need to set date value." }, { "code": null, "e": 1768, "s": 1529, "text": "a Date object representing the date value to be passed. The constructor of java.sql.Date class accepts a variable of long type representing the number of milliseconds from the epoch (standard base time I.e. January 1, 1970, 00:00:00 GMT)." }, { "code": null, "e": 2007, "s": 1768, "text": "a Date object representing the date value to be passed. The constructor of java.sql.Date class accepts a variable of long type representing the number of milliseconds from the epoch (standard base time I.e. January 1, 1970, 00:00:00 GMT)." }, { "code": null, "e": 2099, "s": 2007, "text": "Assume we have created a table named Emp in MySQL database with the following description −" }, { "code": null, "e": 2512, "s": 2099, "text": "+----------+--------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+----------+--------------+------+-----+---------+-------+\n| Name | varchar(255) | YES | | NULL | |\n| DOB | date | YES | | NULL | |\n| Location | varchar(255) | YES | | NULL | |\n+----------+--------------+------+-----+---------+-------+" }, { "code": null, "e": 2570, "s": 2512, "text": "Following JDBC program inserts records in to this table −" }, { "code": null, "e": 3725, "s": 2570, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\nimport java.sql.Date;\npublic class InsertingDate {\n public static void main(String args[])throws Exception {\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/sampleDB\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Inserting values to a table\n String query = \"INSERT INTO Emp(Name, DOB, Location) VALUES (?, ?, ?)\";\n PreparedStatement pstmt = con.prepareStatement(query);\n pstmt.setString(1, \"Amit\"); pstmt.setDate(2, new Date(622790105000L));\n pstmt.setString(3, \"Hyderabad\");\n pstmt.execute();\n pstmt.setString(1, \"Sumith\"); pstmt.setDate(2, new Date(620611200000L));\n pstmt.setString(3, \"Vishakhapatnam\");\n pstmt.execute();\n pstmt.setString(1, \"Sudha\");\n pstmt.setDate(2, new Date(336614400000L));\n pstmt.setString(3, \"Vijayawada\");\n pstmt.execute();\n System.out.println(\"Records inserted......\");\n }\n}" }, { "code": null, "e": 3777, "s": 3725, "text": "Connection established......\nRecords inserted......" }, { "code": null, "e": 3867, "s": 3777, "text": "If you verify the table in MySQL database, you can observe the contents of the table as −" }, { "code": null, "e": 4205, "s": 3867, "text": "mysql> select * from Emp;\n+--------+------------+----------------+\n| Name | DOB | Location |\n+--------+------------+----------------+\n| Amit | 1989-09-26 | Hyderabad |\n| Sumith | 2019-03-19 | Vishakhapatnam |\n| Sudha | 2019-03-19 | Vijayawada |\n+--------+------------+----------------+\n3 rows in set (0.00 sec)" } ]
How to Find the Length of a String in Dart? - GeeksforGeeks
15 Jul, 2020 To find a length of a string in the dart, we make use of length property of a string class in Dart. This method returns the length of string which in integer. Syntax: string_name.length Return Type: integer Example: Finding the length of the string in Dart. Dart // Main functionmain() { // Declaring a string variable String gfg = "Welcome to GeeksForGeeks"; // Finding the length int length = gfg.length; // Printing the length of the string print(length);} Output: 24 Explanation: The length of the string including spaces in the above example count up to 24. Note: The length of the empty string is equal to 0. Dart-String Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Flutter - Custom Bottom Navigation Bar Flutter - Flexible Widget ListView Class in Flutter Flutter - Stack Widget Android Studio Setup for Flutter Development Format Dates in Flutter Flutter - Positioned Widget Simple Calculator App using Flutter Flutter - Dialogs Dart - Static Keyword
[ { "code": null, "e": 23645, "s": 23617, "text": "\n15 Jul, 2020" }, { "code": null, "e": 23804, "s": 23645, "text": "To find a length of a string in the dart, we make use of length property of a string class in Dart. This method returns the length of string which in integer." }, { "code": null, "e": 23831, "s": 23804, "text": "Syntax: string_name.length" }, { "code": null, "e": 23852, "s": 23831, "text": "Return Type: integer" }, { "code": null, "e": 23903, "s": 23852, "text": "Example: Finding the length of the string in Dart." }, { "code": null, "e": 23908, "s": 23903, "text": "Dart" }, { "code": "// Main functionmain() { // Declaring a string variable String gfg = \"Welcome to GeeksForGeeks\"; // Finding the length int length = gfg.length; // Printing the length of the string print(length);}", "e": 24123, "s": 23908, "text": null }, { "code": null, "e": 24131, "s": 24123, "text": "Output:" }, { "code": null, "e": 24135, "s": 24131, "text": "24\n" }, { "code": null, "e": 24227, "s": 24135, "text": "Explanation: The length of the string including spaces in the above example count up to 24." }, { "code": null, "e": 24280, "s": 24227, "text": "Note: The length of the empty string is equal to 0. " }, { "code": null, "e": 24292, "s": 24280, "text": "Dart-String" }, { "code": null, "e": 24297, "s": 24292, "text": "Dart" }, { "code": null, "e": 24395, "s": 24297, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24404, "s": 24395, "text": "Comments" }, { "code": null, "e": 24417, "s": 24404, "text": "Old Comments" }, { "code": null, "e": 24456, "s": 24417, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 24482, "s": 24456, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 24508, "s": 24482, "text": "ListView Class in Flutter" }, { "code": null, "e": 24531, "s": 24508, "text": "Flutter - Stack Widget" }, { "code": null, "e": 24576, "s": 24531, "text": "Android Studio Setup for Flutter Development" }, { "code": null, "e": 24600, "s": 24576, "text": "Format Dates in Flutter" }, { "code": null, "e": 24628, "s": 24600, "text": "Flutter - Positioned Widget" }, { "code": null, "e": 24664, "s": 24628, "text": "Simple Calculator App using Flutter" }, { "code": null, "e": 24682, "s": 24664, "text": "Flutter - Dialogs" } ]
Abstract Classes in Scala - GeeksforGeeks
31 Oct, 2019 Abstraction is the process to hide the internal details and showing only the functionality. In Scala, abstraction is achieved by using an abstract class. The working of the Scala abstract class is similar to Java abstract class. In Scala, an abstract class is constructed using the abstract keyword. It contains both abstract and non-abstract methods and cannot support multiple inheritances. A class can extend only one abstract class.Syntax: abstract class class_name { // code.. } The abstract methods of abstract class are those methods which do not contain any implementation. Or in other words, the method which does not contain body is known as an abstract method.Syntax: def function_name() Example: // Scala program to illustrate how to // create an abstract class // Abstract classabstract class myauthor{ // abstract method def details()} // GFG class extends abstract classclass GFG extends myauthor{ def details() { println("Author name: Ankita Saini") println("Topic name: Abstract class in Scala") }} object Main { // Main method def main(args: Array[String]) { // objects of GFG class var obj = new GFG() obj.details() }} Output: Author name: Ankita Saini Topic name: Abstract class in Scala Following are some important observations about abstract classes in Scala. Like Java, in Scala, we are not allowed to create the instance of the abstract class. If we try to create objects of the abstract class, then the compiler will give an error as shown in the below program.Example:// Scala program to illustrate // the concept of abstract class // Abstract classabstract class myauthor{ // abstract method def details()} object Main { // Main method def main(args: Array[String]) { // Object of myauthor class var obj = new myauthor() }}Output:prog.scala:18: error: class myauthor is abstract; cannot be instantiatedvar obj = new myauthor()^one error found // Scala program to illustrate // the concept of abstract class // Abstract classabstract class myauthor{ // abstract method def details()} object Main { // Main method def main(args: Array[String]) { // Object of myauthor class var obj = new myauthor() }} Output: prog.scala:18: error: class myauthor is abstract; cannot be instantiatedvar obj = new myauthor()^one error found In Scala, an abstract class can also contain fields. These fields are accessed by the abstract class methods and by the methods of the class which inherit abstract class. As shown in the below program.Example:// Scala program to illustrate // the concept of abstract class // Abstract class with fieldsabstract class Geek{ var name : String = "GeeksforGeeks" var tutorial: String = "Scala" def portal()} // GFG class extends abstract classclass GFG extends Geek{ // Abstract class method accessing // fields of the abstract class def portal() { println("Portal name: " + name) } // GFG class method accessing // fields of the abstract class def tutdetails() { println("Tutorial name: " + tutorial) }} object Main { // Main method def main(args: Array[String]) { // objects of GFG class var obj = new GFG() obj.portal() obj.tutdetails() }}Output:Portal name: GeeksforGeeks Tutorial name: Scala // Scala program to illustrate // the concept of abstract class // Abstract class with fieldsabstract class Geek{ var name : String = "GeeksforGeeks" var tutorial: String = "Scala" def portal()} // GFG class extends abstract classclass GFG extends Geek{ // Abstract class method accessing // fields of the abstract class def portal() { println("Portal name: " + name) } // GFG class method accessing // fields of the abstract class def tutdetails() { println("Tutorial name: " + tutorial) }} object Main { // Main method def main(args: Array[String]) { // objects of GFG class var obj = new GFG() obj.portal() obj.tutdetails() }} Output: Portal name: GeeksforGeeks Tutorial name: Scala Like Java, In Scala, an abstract class can also contain a constructor and a constructor of an abstract class is called when an instance of a inherited class is created. As shown in the below program.Example:// Scala program to illustrate // the concept of abstract class // Abstract class with constructor// And the constructor contain two argumentsabstract class myauthor(name: String, topic: String){ def details()} // GFG class extends abstract classclass GFG(name: String, topic: String) extends myauthor(name, topic){ def details() { println("Author name: " + name) println("Topic name: " + topic) }} object Main { // Main method def main(args: Array[String]) { // objects of GFG class var obj = new GFG("Ankita", "Abstract class") obj.details() }}Output:Author name: Ankita Topic name: Abstract class // Scala program to illustrate // the concept of abstract class // Abstract class with constructor// And the constructor contain two argumentsabstract class myauthor(name: String, topic: String){ def details()} // GFG class extends abstract classclass GFG(name: String, topic: String) extends myauthor(name, topic){ def details() { println("Author name: " + name) println("Topic name: " + topic) }} object Main { // Main method def main(args: Array[String]) { // objects of GFG class var obj = new GFG("Ankita", "Abstract class") obj.details() }} Output: Author name: Ankita Topic name: Abstract class An abstract class can also contain only non- abstract method. This allows us to create classes that cannot be instantiated, but can only be inherited. As shown in the below program.Example:// Scala program to illustrate // the concept of abstract class // Abstract class with // non-abstract methodabstract class myauthor{ // Non-abstract method def details() { println("Welcome to GeeksforGeeks") }} // GFG class extends abstract classclass GFG extends myauthor{} object Main { // Main method def main(args: Array[String]) { // objects of GFG class var obj = new GFG() obj.details() }}Output:Welcome to GeeksforGeeks // Scala program to illustrate // the concept of abstract class // Abstract class with // non-abstract methodabstract class myauthor{ // Non-abstract method def details() { println("Welcome to GeeksforGeeks") }} // GFG class extends abstract classclass GFG extends myauthor{} object Main { // Main method def main(args: Array[String]) { // objects of GFG class var obj = new GFG() obj.details() }} Output: Welcome to GeeksforGeeks In Scala, an abstract class can contain final methods (methods that cannot be overridden). For example, the following program compiles and runs without an error. In Scala, final method is created using final keyword.Example:// Scala program to illustrate // the concept of abstract class // Abstract class with the final methodabstract class myauthor{ final def mymethod() { println("Final method") }} // GFG class extends abstract classclass GFG extends myauthor{} object Main { // Main method def main(args: Array[String]) { // objects of GFG class var obj = new GFG() obj.mymethod() }}Output:Final method // Scala program to illustrate // the concept of abstract class // Abstract class with the final methodabstract class myauthor{ final def mymethod() { println("Final method") }} // GFG class extends abstract classclass GFG extends myauthor{} object Main { // Main method def main(args: Array[String]) { // objects of GFG class var obj = new GFG() obj.mymethod() }} Output: Final method When to use abstract class in Scala:An abstract class is useful: When we want to construct a base class which needs constructor arguments. When our code will be called from Java code. Note:Traits are also used to achieve abstraction. ManasChhabra2 Scala Scala-OOPS Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Throw Keyword in Scala Scala Map Scala List filter() method with example How to install Scala on Windows? Scala List exists() method with example Scala | Arrays Scala Tutorial – Learn Scala with Step By Step Guide Scala Lists HashMap in Scala Scala | Functions Call-by-Name
[ { "code": null, "e": 23441, "s": 23413, "text": "\n31 Oct, 2019" }, { "code": null, "e": 23885, "s": 23441, "text": "Abstraction is the process to hide the internal details and showing only the functionality. In Scala, abstraction is achieved by using an abstract class. The working of the Scala abstract class is similar to Java abstract class. In Scala, an abstract class is constructed using the abstract keyword. It contains both abstract and non-abstract methods and cannot support multiple inheritances. A class can extend only one abstract class.Syntax:" }, { "code": null, "e": 23925, "s": 23885, "text": "abstract class class_name\n{\n// code..\n}" }, { "code": null, "e": 24120, "s": 23925, "text": "The abstract methods of abstract class are those methods which do not contain any implementation. Or in other words, the method which does not contain body is known as an abstract method.Syntax:" }, { "code": null, "e": 24140, "s": 24120, "text": "def function_name()" }, { "code": null, "e": 24149, "s": 24140, "text": "Example:" }, { "code": "// Scala program to illustrate how to // create an abstract class // Abstract classabstract class myauthor{ // abstract method def details()} // GFG class extends abstract classclass GFG extends myauthor{ def details() { println(\"Author name: Ankita Saini\") println(\"Topic name: Abstract class in Scala\") }} object Main { // Main method def main(args: Array[String]) { // objects of GFG class var obj = new GFG() obj.details() }}", "e": 24651, "s": 24149, "text": null }, { "code": null, "e": 24659, "s": 24651, "text": "Output:" }, { "code": null, "e": 24722, "s": 24659, "text": "Author name: Ankita Saini\nTopic name: Abstract class in Scala\n" }, { "code": null, "e": 24797, "s": 24722, "text": "Following are some important observations about abstract classes in Scala." }, { "code": null, "e": 25436, "s": 24797, "text": "Like Java, in Scala, we are not allowed to create the instance of the abstract class. If we try to create objects of the abstract class, then the compiler will give an error as shown in the below program.Example:// Scala program to illustrate // the concept of abstract class // Abstract classabstract class myauthor{ // abstract method def details()} object Main { // Main method def main(args: Array[String]) { // Object of myauthor class var obj = new myauthor() }}Output:prog.scala:18: error: class myauthor is abstract; cannot be instantiatedvar obj = new myauthor()^one error found" }, { "code": "// Scala program to illustrate // the concept of abstract class // Abstract classabstract class myauthor{ // abstract method def details()} object Main { // Main method def main(args: Array[String]) { // Object of myauthor class var obj = new myauthor() }}", "e": 25744, "s": 25436, "text": null }, { "code": null, "e": 25752, "s": 25744, "text": "Output:" }, { "code": null, "e": 25865, "s": 25752, "text": "prog.scala:18: error: class myauthor is abstract; cannot be instantiatedvar obj = new myauthor()^one error found" }, { "code": null, "e": 26895, "s": 25865, "text": "In Scala, an abstract class can also contain fields. These fields are accessed by the abstract class methods and by the methods of the class which inherit abstract class. As shown in the below program.Example:// Scala program to illustrate // the concept of abstract class // Abstract class with fieldsabstract class Geek{ var name : String = \"GeeksforGeeks\" var tutorial: String = \"Scala\" def portal()} // GFG class extends abstract classclass GFG extends Geek{ // Abstract class method accessing // fields of the abstract class def portal() { println(\"Portal name: \" + name) } // GFG class method accessing // fields of the abstract class def tutdetails() { println(\"Tutorial name: \" + tutorial) }} object Main { // Main method def main(args: Array[String]) { // objects of GFG class var obj = new GFG() obj.portal() obj.tutdetails() }}Output:Portal name: GeeksforGeeks\nTutorial name: Scala" }, { "code": "// Scala program to illustrate // the concept of abstract class // Abstract class with fieldsabstract class Geek{ var name : String = \"GeeksforGeeks\" var tutorial: String = \"Scala\" def portal()} // GFG class extends abstract classclass GFG extends Geek{ // Abstract class method accessing // fields of the abstract class def portal() { println(\"Portal name: \" + name) } // GFG class method accessing // fields of the abstract class def tutdetails() { println(\"Tutorial name: \" + tutorial) }} object Main { // Main method def main(args: Array[String]) { // objects of GFG class var obj = new GFG() obj.portal() obj.tutdetails() }}", "e": 27662, "s": 26895, "text": null }, { "code": null, "e": 27670, "s": 27662, "text": "Output:" }, { "code": null, "e": 27718, "s": 27670, "text": "Portal name: GeeksforGeeks\nTutorial name: Scala" }, { "code": null, "e": 28654, "s": 27718, "text": "Like Java, In Scala, an abstract class can also contain a constructor and a constructor of an abstract class is called when an instance of a inherited class is created. As shown in the below program.Example:// Scala program to illustrate // the concept of abstract class // Abstract class with constructor// And the constructor contain two argumentsabstract class myauthor(name: String, topic: String){ def details()} // GFG class extends abstract classclass GFG(name: String, topic: String) extends myauthor(name, topic){ def details() { println(\"Author name: \" + name) println(\"Topic name: \" + topic) }} object Main { // Main method def main(args: Array[String]) { // objects of GFG class var obj = new GFG(\"Ankita\", \"Abstract class\") obj.details() }}Output:Author name: Ankita\nTopic name: Abstract class\n" }, { "code": "// Scala program to illustrate // the concept of abstract class // Abstract class with constructor// And the constructor contain two argumentsabstract class myauthor(name: String, topic: String){ def details()} // GFG class extends abstract classclass GFG(name: String, topic: String) extends myauthor(name, topic){ def details() { println(\"Author name: \" + name) println(\"Topic name: \" + topic) }} object Main { // Main method def main(args: Array[String]) { // objects of GFG class var obj = new GFG(\"Ankita\", \"Abstract class\") obj.details() }}", "e": 29329, "s": 28654, "text": null }, { "code": null, "e": 29337, "s": 29329, "text": "Output:" }, { "code": null, "e": 29385, "s": 29337, "text": "Author name: Ankita\nTopic name: Abstract class\n" }, { "code": null, "e": 30081, "s": 29385, "text": "An abstract class can also contain only non- abstract method. This allows us to create classes that cannot be instantiated, but can only be inherited. As shown in the below program.Example:// Scala program to illustrate // the concept of abstract class // Abstract class with // non-abstract methodabstract class myauthor{ // Non-abstract method def details() { println(\"Welcome to GeeksforGeeks\") }} // GFG class extends abstract classclass GFG extends myauthor{} object Main { // Main method def main(args: Array[String]) { // objects of GFG class var obj = new GFG() obj.details() }}Output:Welcome to GeeksforGeeks\n" }, { "code": "// Scala program to illustrate // the concept of abstract class // Abstract class with // non-abstract methodabstract class myauthor{ // Non-abstract method def details() { println(\"Welcome to GeeksforGeeks\") }} // GFG class extends abstract classclass GFG extends myauthor{} object Main { // Main method def main(args: Array[String]) { // objects of GFG class var obj = new GFG() obj.details() }}", "e": 30556, "s": 30081, "text": null }, { "code": null, "e": 30564, "s": 30556, "text": "Output:" }, { "code": null, "e": 30590, "s": 30564, "text": "Welcome to GeeksforGeeks\n" }, { "code": null, "e": 31268, "s": 30590, "text": "In Scala, an abstract class can contain final methods (methods that cannot be overridden). For example, the following program compiles and runs without an error. In Scala, final method is created using final keyword.Example:// Scala program to illustrate // the concept of abstract class // Abstract class with the final methodabstract class myauthor{ final def mymethod() { println(\"Final method\") }} // GFG class extends abstract classclass GFG extends myauthor{} object Main { // Main method def main(args: Array[String]) { // objects of GFG class var obj = new GFG() obj.mymethod() }}Output:Final method\n" }, { "code": "// Scala program to illustrate // the concept of abstract class // Abstract class with the final methodabstract class myauthor{ final def mymethod() { println(\"Final method\") }} // GFG class extends abstract classclass GFG extends myauthor{} object Main { // Main method def main(args: Array[String]) { // objects of GFG class var obj = new GFG() obj.mymethod() }}", "e": 31702, "s": 31268, "text": null }, { "code": null, "e": 31710, "s": 31702, "text": "Output:" }, { "code": null, "e": 31724, "s": 31710, "text": "Final method\n" }, { "code": null, "e": 31789, "s": 31724, "text": "When to use abstract class in Scala:An abstract class is useful:" }, { "code": null, "e": 31863, "s": 31789, "text": "When we want to construct a base class which needs constructor arguments." }, { "code": null, "e": 31908, "s": 31863, "text": "When our code will be called from Java code." }, { "code": null, "e": 31958, "s": 31908, "text": "Note:Traits are also used to achieve abstraction." }, { "code": null, "e": 31972, "s": 31958, "text": "ManasChhabra2" }, { "code": null, "e": 31978, "s": 31972, "text": "Scala" }, { "code": null, "e": 31989, "s": 31978, "text": "Scala-OOPS" }, { "code": null, "e": 31995, "s": 31989, "text": "Scala" }, { "code": null, "e": 32093, "s": 31995, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32102, "s": 32093, "text": "Comments" }, { "code": null, "e": 32115, "s": 32102, "text": "Old Comments" }, { "code": null, "e": 32138, "s": 32115, "text": "Throw Keyword in Scala" }, { "code": null, "e": 32148, "s": 32138, "text": "Scala Map" }, { "code": null, "e": 32188, "s": 32148, "text": "Scala List filter() method with example" }, { "code": null, "e": 32221, "s": 32188, "text": "How to install Scala on Windows?" }, { "code": null, "e": 32261, "s": 32221, "text": "Scala List exists() method with example" }, { "code": null, "e": 32276, "s": 32261, "text": "Scala | Arrays" }, { "code": null, "e": 32329, "s": 32276, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 32341, "s": 32329, "text": "Scala Lists" }, { "code": null, "e": 32358, "s": 32341, "text": "HashMap in Scala" } ]
R and Python Plotting in Google Sheets | by Sam Terfa | Towards Data Science
This is part 2 in my n-part series on using R and Python functions inside Google Sheets formulas. If you haven’t read part 1, Using R and Python in Google Sheets Formulas, I suggest doing so to see all the magic available to you. In summary, you can use R and Python code to power custom Google Sheets cell formulas by setting up a simple API in Google Cloud Run and creating Google Apps Script functions to call your API. After the initial set up, it is quick and easy to use R and Python in any Google Sheet. Here are some highlights. As I said previously, I think Google Sheets are amazing. I stand by that statement with the caveat that graphing in Google Sheets is pretty bad. It took the longest time to even have a reasonable linear regression available, and the graph options are pretty limited. However, now you can use R and Python to create beautiful graphs on the fly inside Google Sheets by using techniques developed previously. In fact, many functions that produce image files can be used inside Google Sheets formulas with minimal additional set up. Here are some examples. base R Plotting base R Plotting 2. ggplot2 Plotting 3. Python Plotting Using matplotlib 4. k-means Cluster Plotting 5. Word Clouds The Google Sheets function IMAGE takes the URL of an image as an argument and displays it inside a cell. Based on techniques from part 1, the custom Google Apps Script functions rplot and pyplot make API calls to my /rplot and /pyplot endpoints set up on Google Cloud Run. These API calls run the rscript and pyscript arguments as code, generate a PNG of the output, upload the PNG to imgur.com via their API, and return the URL of the uploaded image. The easiest way to get started with using rplot or pyplot inside Google Sheets is to clone my rpysheets GitHub repo and use the GoogleCloudRunner R package to deploy a Google Cloud Run service for the rsheets_plotting directory and the pysheets_plotting directory. Then copy and paste the Google Cloud Run service URLs into this Google Sheets template and play. googleCloudRunner::cr_deploy_run('{LocalPath}/rsheets_plotting/')googleCloudRunner::cr_deploy_run('{LocalPath}/pysheets_plotting/') The arguments rscript and pyscript are the work horses of the /rplot and /pyplot endpoints, and each comes with its own endpoint as well. The rscript argument is read in as a string and run using R’s eval() function, while pyscript is read in and run using a mix of Python’s exec() and eval() functions. I am aware that it is dangerous to allow an untrusted source to pass in code to an eval() or exec() function. Depending on your use case, I would consider how you might modify the code I’ve written to safeguard these functions. Each variable passed into rscript and pyscript is identified and cast as a dataframe with column names, array, vector, or single value. rscript and pyscript can modify these variables and access built in values as well, but must result in the production of an image. Since R can capture plots as PNG files, this is taken care of behind the scenes, so all that is required is that a plot is attempted. However, since Python does not have a consistent way of capturing plots to PNG that I am aware of, the pyscript code must explicitly save a figure as a PNG file. The first PNG found in the working directory is uploaded to imgur.com behind the scenes. rplot Google Sheets Formula=IMAGE(rplot("g <- ggplot(data = a, mapping = aes(x,y)) + geom_point() + geom_smooth(color = 'red') + ggtitle('Sample ggplot') + theme_minimal(); plot(g)", B2:C12)) pyplot Google Sheets Formula=IMAGE(pyplot("import matplotlib.pyplot as plt; plot = a.plot(x = 0, y = 1, kind = 'scatter', title = 'Sample Python Scatterplot'); fig = plot.get_figure(); fig.savefig('output.png')", B2:C12)) For both /rplot and /pyplot, I have utilized imgur.com image hosting. You can use a different image hosting site if you like, but to use what I have done above, you will need an imgur Client ID. To obtain one, create an imgur account, and add a client to your account. Once you have the client ID, you can copy and paste it into the above scripts, or you can instead create a .creds directory with the file imgur.json inside defined in the following way. {"clientID":"{YourImgurClientID}"} I set up my client with Authorization type “Anonymous usage without user authorization” and simply upload publicly available images for demonstration purposes. You may choose to instead upload to a private album. While every update of a graph on a Google Sheet generates a unique imgur URL for the uploaded image, which is wasteful, each client can upload up to 1,250 images per day which has been enough for me. Should you use this in production, you will want to modify images when they change on update versus uploading a different image each time. Keep in mind that if you want to make money using imgur.com, you have special requirements and it is not free. Here is the Google Sheet you can simply copy and use with custom Google Sheets functions pre-defined for pyscript, pyplot, rscript, and rplot. All that you need to do is paste in your R and Python Google Cloud Run URLs once they are set up.Here is my GitHub repo with the R and Python code referenced above. Here is the Google Sheet you can simply copy and use with custom Google Sheets functions pre-defined for pyscript, pyplot, rscript, and rplot. All that you need to do is paste in your R and Python Google Cloud Run URLs once they are set up. Here is my GitHub repo with the R and Python code referenced above.
[ { "code": null, "e": 683, "s": 172, "text": "This is part 2 in my n-part series on using R and Python functions inside Google Sheets formulas. If you haven’t read part 1, Using R and Python in Google Sheets Formulas, I suggest doing so to see all the magic available to you. In summary, you can use R and Python code to power custom Google Sheets cell formulas by setting up a simple API in Google Cloud Run and creating Google Apps Script functions to call your API. After the initial set up, it is quick and easy to use R and Python in any Google Sheet." }, { "code": null, "e": 709, "s": 683, "text": "Here are some highlights." }, { "code": null, "e": 1238, "s": 709, "text": "As I said previously, I think Google Sheets are amazing. I stand by that statement with the caveat that graphing in Google Sheets is pretty bad. It took the longest time to even have a reasonable linear regression available, and the graph options are pretty limited. However, now you can use R and Python to create beautiful graphs on the fly inside Google Sheets by using techniques developed previously. In fact, many functions that produce image files can be used inside Google Sheets formulas with minimal additional set up." }, { "code": null, "e": 1262, "s": 1238, "text": "Here are some examples." }, { "code": null, "e": 1278, "s": 1262, "text": "base R Plotting" }, { "code": null, "e": 1294, "s": 1278, "text": "base R Plotting" }, { "code": null, "e": 1314, "s": 1294, "text": "2. ggplot2 Plotting" }, { "code": null, "e": 1350, "s": 1314, "text": "3. Python Plotting Using matplotlib" }, { "code": null, "e": 1378, "s": 1350, "text": "4. k-means Cluster Plotting" }, { "code": null, "e": 1393, "s": 1378, "text": "5. Word Clouds" }, { "code": null, "e": 1845, "s": 1393, "text": "The Google Sheets function IMAGE takes the URL of an image as an argument and displays it inside a cell. Based on techniques from part 1, the custom Google Apps Script functions rplot and pyplot make API calls to my /rplot and /pyplot endpoints set up on Google Cloud Run. These API calls run the rscript and pyscript arguments as code, generate a PNG of the output, upload the PNG to imgur.com via their API, and return the URL of the uploaded image." }, { "code": null, "e": 2207, "s": 1845, "text": "The easiest way to get started with using rplot or pyplot inside Google Sheets is to clone my rpysheets GitHub repo and use the GoogleCloudRunner R package to deploy a Google Cloud Run service for the rsheets_plotting directory and the pysheets_plotting directory. Then copy and paste the Google Cloud Run service URLs into this Google Sheets template and play." }, { "code": null, "e": 2339, "s": 2207, "text": "googleCloudRunner::cr_deploy_run('{LocalPath}/rsheets_plotting/')googleCloudRunner::cr_deploy_run('{LocalPath}/pysheets_plotting/')" }, { "code": null, "e": 2871, "s": 2339, "text": "The arguments rscript and pyscript are the work horses of the /rplot and /pyplot endpoints, and each comes with its own endpoint as well. The rscript argument is read in as a string and run using R’s eval() function, while pyscript is read in and run using a mix of Python’s exec() and eval() functions. I am aware that it is dangerous to allow an untrusted source to pass in code to an eval() or exec() function. Depending on your use case, I would consider how you might modify the code I’ve written to safeguard these functions." }, { "code": null, "e": 3523, "s": 2871, "text": "Each variable passed into rscript and pyscript is identified and cast as a dataframe with column names, array, vector, or single value. rscript and pyscript can modify these variables and access built in values as well, but must result in the production of an image. Since R can capture plots as PNG files, this is taken care of behind the scenes, so all that is required is that a plot is attempted. However, since Python does not have a consistent way of capturing plots to PNG that I am aware of, the pyscript code must explicitly save a figure as a PNG file. The first PNG found in the working directory is uploaded to imgur.com behind the scenes." }, { "code": null, "e": 3715, "s": 3523, "text": "rplot Google Sheets Formula=IMAGE(rplot(\"g <- ggplot(data = a, mapping = aes(x,y)) + geom_point() + geom_smooth(color = 'red') + ggtitle('Sample ggplot') + theme_minimal(); plot(g)\", B2:C12))" }, { "code": null, "e": 3937, "s": 3715, "text": "pyplot Google Sheets Formula=IMAGE(pyplot(\"import matplotlib.pyplot as plt; plot = a.plot(x = 0, y = 1, kind = 'scatter', title = 'Sample Python Scatterplot'); fig = plot.get_figure(); fig.savefig('output.png')\", B2:C12))" }, { "code": null, "e": 4392, "s": 3937, "text": "For both /rplot and /pyplot, I have utilized imgur.com image hosting. You can use a different image hosting site if you like, but to use what I have done above, you will need an imgur Client ID. To obtain one, create an imgur account, and add a client to your account. Once you have the client ID, you can copy and paste it into the above scripts, or you can instead create a .creds directory with the file imgur.json inside defined in the following way." }, { "code": null, "e": 4427, "s": 4392, "text": "{\"clientID\":\"{YourImgurClientID}\"}" }, { "code": null, "e": 5090, "s": 4427, "text": "I set up my client with Authorization type “Anonymous usage without user authorization” and simply upload publicly available images for demonstration purposes. You may choose to instead upload to a private album. While every update of a graph on a Google Sheet generates a unique imgur URL for the uploaded image, which is wasteful, each client can upload up to 1,250 images per day which has been enough for me. Should you use this in production, you will want to modify images when they change on update versus uploading a different image each time. Keep in mind that if you want to make money using imgur.com, you have special requirements and it is not free." }, { "code": null, "e": 5398, "s": 5090, "text": "Here is the Google Sheet you can simply copy and use with custom Google Sheets functions pre-defined for pyscript, pyplot, rscript, and rplot. All that you need to do is paste in your R and Python Google Cloud Run URLs once they are set up.Here is my GitHub repo with the R and Python code referenced above." }, { "code": null, "e": 5639, "s": 5398, "text": "Here is the Google Sheet you can simply copy and use with custom Google Sheets functions pre-defined for pyscript, pyplot, rscript, and rplot. All that you need to do is paste in your R and Python Google Cloud Run URLs once they are set up." } ]
Elixir - Bitwise Operators
Bitwise operators work on bits and perform bit by bit operation. Elixir provides bitwise modules as part of the package Bitwise, so in order to use these, you need to use the bitwise module. To use it, enter the following comand in your shell − use Bitwise Assume A to be 5 and B to be 6 for the following examples − Try the following code to understand all arithmetic operators in Elixir. a = 5 b = 6 use Bitwise IO.puts("a &&& b " <> to_string(a &&& b)) IO.puts("a ||| b " <> to_string(a ||| b)) IO.puts("a >>> b " <> to_string(a >>> b)) IO.puts("a <<< b" <> to_string(a <<< b)) IO.puts("a ^^^ b " <> to_string(a ^^^ b)) IO.puts("~~~a " <> to_string(~~~a)) The above program generates the following result − a &&& b 4 a ||| b 7 a >>> b 0 a <<< b 320 a ^^^ b 3 ~~~a -6 35 Lectures 3 hours Pranjal Srivastava 54 Lectures 6 hours Pranjal Srivastava, Harshit Srivastava 80 Lectures 9.5 hours Pranjal Srivastava 43 Lectures 4 hours Mohammad Nauman Print Add Notes Bookmark this page
[ { "code": null, "e": 2427, "s": 2182, "text": "Bitwise operators work on bits and perform bit by bit operation. Elixir provides bitwise modules as part of the package Bitwise, so in order to use these, you need to use the bitwise module. To use it, enter the following comand in your shell −" }, { "code": null, "e": 2440, "s": 2427, "text": "use Bitwise\n" }, { "code": null, "e": 2501, "s": 2440, "text": " Assume A to be 5 and B to be 6 for the following examples −" }, { "code": null, "e": 2574, "s": 2501, "text": "Try the following code to understand all arithmetic operators in Elixir." }, { "code": null, "e": 2850, "s": 2574, "text": "a = 5\nb = 6\n\nuse Bitwise\n\nIO.puts(\"a &&& b \" <> to_string(a &&& b))\n\nIO.puts(\"a ||| b \" <> to_string(a ||| b))\n\nIO.puts(\"a >>> b \" <> to_string(a >>> b))\n\nIO.puts(\"a <<< b\" <> to_string(a <<< b))\n\nIO.puts(\"a ^^^ b \" <> to_string(a ^^^ b))\n\nIO.puts(\"~~~a \" <> to_string(~~~a))" }, { "code": null, "e": 2901, "s": 2850, "text": "The above program generates the following result −" }, { "code": null, "e": 2962, "s": 2901, "text": "a &&& b 4\na ||| b 7\na >>> b 0\na <<< b 320\na ^^^ b 3\n~~~a -6\n" }, { "code": null, "e": 2995, "s": 2962, "text": "\n 35 Lectures \n 3 hours \n" }, { "code": null, "e": 3015, "s": 2995, "text": " Pranjal Srivastava" }, { "code": null, "e": 3048, "s": 3015, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 3088, "s": 3048, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 3123, "s": 3088, "text": "\n 80 Lectures \n 9.5 hours \n" }, { "code": null, "e": 3143, "s": 3123, "text": " Pranjal Srivastava" }, { "code": null, "e": 3176, "s": 3143, "text": "\n 43 Lectures \n 4 hours \n" }, { "code": null, "e": 3193, "s": 3176, "text": " Mohammad Nauman" }, { "code": null, "e": 3200, "s": 3193, "text": " Print" }, { "code": null, "e": 3211, "s": 3200, "text": " Add Notes" } ]
Optimizing Hyperparameters in Random Forest Classification | by Reilly Meinert | Towards Data Science
In this post, I will be taking an in-depth look at hyperparameter tuning for Random Forest Classification models using several of scikit-learn’s packages for classification and model selection. I will be analyzing the wine quality datasets from the UCI Machine Learning Repository. For the purpose of this post, I have combined the individual datasets for red and white wine, and assigned both an extra column to distinguish the color of the wine, where 0 represents a red wine and 1 represents a white wine. The purpose of this classification model is to determine whether a wine is red or white. In order to optimize this model to create the most accurate predictions, I will be focusing solely on hyperparameter adjustment and selection. Most generally, a hyperparameter is a parameter of the model that is set prior to the start of the learning process. Different models have different hyperparameters that can be set. For a Random Forest Classifier, there are several different hyperparameters that can be adjusted. In this post, I will be investigating the following four parameters: n_estimators: The n_estimators parameter specifies the number of trees in the forest of the model. The default value for this parameter is 10, which means that 10 different decision trees will be constructed in the random forest. n_estimators: The n_estimators parameter specifies the number of trees in the forest of the model. The default value for this parameter is 10, which means that 10 different decision trees will be constructed in the random forest. 2. max_depth: The max_depth parameter specifies the maximum depth of each tree. The default value for max_depth is None, which means that each tree will expand until every leaf is pure. A pure leaf is one where all of the data on the leaf comes from the same class. 3. min_samples_split: The min_samples_split parameter specifies the minimum number of samples required to split an internal leaf node. The default value for this parameter is 2, which means that an internal node must have at least two samples before it can be split to have a more specific classification. 4. min_samples_leaf: The min_samples_leaf parameter specifies the minimum number of samples required to be at a leaf node. The default value for this parameter is 1, which means that every leaf must have at least 1 sample that it classifies. More documentation regarding the hyperparameters of a RandomForestClassifier() can be found here. Hyperparameters can be adjusted manually when you call the function that creates the model. forest = RandomForestClassifier(random_state = 1, n_estimators = 10, min_samples_split = 1) Prior to beginning the adjustment of the hyperparameters, I performed an 80/20 train/test split on my data. The different hyperparameters would be tested on the training set, and once the optimized parameter values were chosen, a model would be constructed using the chosen parameters and the testing set, and then would be tested on the training set to see how accurately the model is able to classify the types of wine. forest = RandomForestClassifier(random_state = 1)modelF = forest.fit(x_train, y_train)y_predF = modelF.predict(x_test) When tested on the training set with the default values for the hyperparameters, the values of the testing set were predicted with an accuracy of 0.991538461538. Validation Curves There’s a few different ways you can choose which hyperparameters to adjust for you model. A good way to visually check for potentially optimized values of model hyperparameters is with a validation curve. A validation curve can be plotted on a graph to show how well a model performs with different values of a single hyperparameter. The following code was run to create the four validation curves seen here, with the values of param_name and param_range being adjusted accordingly for each of the four parameters that we are investigating. train_scoreNum, test_scoreNum = validation_curve( RandomForestClassifier(), X = x_train, y = y_train, param_name = 'n_estimators', param_range = num_est, cv = 3) This validation curve was created with the values [100, 300, 500, 750, 800, 1200] as the different values to be tested for n_estimators. In this image, we see that, when testing the values, the best value appears to be 750. It is important to note that, even though there appears to be a large difference between the training and cross-validation score, the training set had an average accuracy of 100% for each of the three cross-validations, and the cross-validation set had between 99.5% and 99.6% accuracy for all the values of n_estimators, which shows that this model is very accurate regardless of the number of estimators used. In this graph, we see that the highest accuracy value on the cross-validation is close to 99.3% when the max_depth is set to 15, which is the value that we will place in our model. Whole it may seem better to choose a max_depth of 30, because that value has the highest accuracy for the training score, we elect not to in order to prevent our model from overfitting the training data. In this graph, we see that the accuracy actually goes down for both the training and cross-validation sets at higher values for min_samples_split, so we will choose 5 as our number for min_samples_split. In this case, it makes sense that we would want a lower value for min_samples_split, as the default value for this parameter is 2. As we choose higher values for the minimum number of samples required before splitting an internal node, we will have more general leaf nodes, which would have a negative affect on the overall accuracy of our model. In this graph, we see that accuracy goes down for both the training and cross-validation sets for each additional increase in value of min_samples_leaf, so we will chose 1 for the value of our parameter, which again makes sense considering the default value for this parameter is 1. It is important to note that, when constructing the validation curves, the other parameters were held at their default values. For the purpose of this post, we will be using all of the optimized values together in a single model. A new Random Forest Classifier was constructed, as follows: forestVC = RandomForestClassifier(random_state = 1, n_estimators = 750, max_depth = 15, min_samples_split = 5, min_samples_leaf = 1) modelVC = forestVC.fit(x_train, y_train) y_predVC = modelVC.predict(x_test) This model resulted in an accuracy of 0.993076923077, which was more accurate than our first model, but only by .0015. Exhaustive Grid Search Another way to choose which hyperparameters to adjust is by conducting an exhaustive grid search or randomized search. Randomized searches will not be discussed in this post, but further documentation regarding their implementation can be found here. An exhaustive grid search takes in as many hyperparameters as you would like, and tries every single possible combination of the hyperparameters as well as as many cross-validations as you would like it to perform. An exhaustive grid search is a good way to determine the best hyperparameter values to use, but it can quickly become time consuming with every additional parameter value and cross-validation that you add. n_estimators = [100, 300, 500, 800, 1200]max_depth = [5, 8, 15, 25, 30]min_samples_split = [2, 5, 10, 15, 100]min_samples_leaf = [1, 2, 5, 10] hyperF = dict(n_estimators = n_estimators, max_depth = max_depth, min_samples_split = min_samples_split, min_samples_leaf = min_samples_leaf)gridF = GridSearchCV(forest, hyperF, cv = 3, verbose = 1, n_jobs = -1)bestF = gridF.fit(x_train, y_train) The code shown here took over 25 minutes to run, but did choose hyperparameters that had 100% accuracy in predicting the training models. The resulting “best” hyperparameters are as follows: max_depth = 15, min_samples_leaf = 1, min_samples_split = 2, n_estimators = 500. Again, a new Random Forest Classifier was run using these values as hyperparameters inputs. forestOpt = RandomForestClassifier(random_state = 1, max_depth = 15, n_estimators = 500, min_samples_split = 2, min_samples_leaf = 1) modelOpt = forestOpt.fit(x_train, y_train)y_pred = modelOpt.predict(x_test) This model also resulted in an accuracy of 0.993076923077 when tested using the testing set. Is adjusting hyperparameters worth it? Carefully and methodically adjusting hyperparameters can be advantageous. It can make your classification model more accurate, which will lead to more accurate predictions overall. However, it may not always be worth your while. Let’s take a look at the results of our different tests: The biggest thing to note is the overall improvement in accuracy. The hyperparameters chosen based on the results of the grid search and validation curve resulted in the same accuracy when the model was applied to our testing set: 0.993076923077. This improved our original model’s accuracy on the testing set by .0015. Considering it took over 25 minutes to run the exhaustive grid search on our 4 desired hyperparameters, it may not have been worth the time in this case. Additionally, two of the “optimized” hyperparameter values given to us by our grid search were the same as the default values for these parameters for scikit-learn’s Random Forest Classifier. When looking at the confusion matrices for each of the two optimized models, we see that both resulted in the same number of incorrect predictions for both red and white wines, as shown here: Hyperparameter tuning can be advantageous in creating a model that is better at classification. In the case of a random forest, it may not be necessary, as random forests are already very good at classification. Using exhaustive grid search to choose hyperparameter values can be very time consuming as well. However, in cases where there are only a few potential values for your hyperparameters or when your initial classification model isn’t very accurate, it might be a good idea to at least investigate the effect of changing some of the hyperparameter values in your model. Key Terms/Ideas: hyperparameters, validation curve, exhaustive grid search, cross-validation
[ { "code": null, "e": 912, "s": 171, "text": "In this post, I will be taking an in-depth look at hyperparameter tuning for Random Forest Classification models using several of scikit-learn’s packages for classification and model selection. I will be analyzing the wine quality datasets from the UCI Machine Learning Repository. For the purpose of this post, I have combined the individual datasets for red and white wine, and assigned both an extra column to distinguish the color of the wine, where 0 represents a red wine and 1 represents a white wine. The purpose of this classification model is to determine whether a wine is red or white. In order to optimize this model to create the most accurate predictions, I will be focusing solely on hyperparameter adjustment and selection." }, { "code": null, "e": 1261, "s": 912, "text": "Most generally, a hyperparameter is a parameter of the model that is set prior to the start of the learning process. Different models have different hyperparameters that can be set. For a Random Forest Classifier, there are several different hyperparameters that can be adjusted. In this post, I will be investigating the following four parameters:" }, { "code": null, "e": 1491, "s": 1261, "text": "n_estimators: The n_estimators parameter specifies the number of trees in the forest of the model. The default value for this parameter is 10, which means that 10 different decision trees will be constructed in the random forest." }, { "code": null, "e": 1721, "s": 1491, "text": "n_estimators: The n_estimators parameter specifies the number of trees in the forest of the model. The default value for this parameter is 10, which means that 10 different decision trees will be constructed in the random forest." }, { "code": null, "e": 1987, "s": 1721, "text": "2. max_depth: The max_depth parameter specifies the maximum depth of each tree. The default value for max_depth is None, which means that each tree will expand until every leaf is pure. A pure leaf is one where all of the data on the leaf comes from the same class." }, { "code": null, "e": 2293, "s": 1987, "text": "3. min_samples_split: The min_samples_split parameter specifies the minimum number of samples required to split an internal leaf node. The default value for this parameter is 2, which means that an internal node must have at least two samples before it can be split to have a more specific classification." }, { "code": null, "e": 2535, "s": 2293, "text": "4. min_samples_leaf: The min_samples_leaf parameter specifies the minimum number of samples required to be at a leaf node. The default value for this parameter is 1, which means that every leaf must have at least 1 sample that it classifies." }, { "code": null, "e": 2633, "s": 2535, "text": "More documentation regarding the hyperparameters of a RandomForestClassifier() can be found here." }, { "code": null, "e": 2725, "s": 2633, "text": "Hyperparameters can be adjusted manually when you call the function that creates the model." }, { "code": null, "e": 2817, "s": 2725, "text": "forest = RandomForestClassifier(random_state = 1, n_estimators = 10, min_samples_split = 1)" }, { "code": null, "e": 3239, "s": 2817, "text": "Prior to beginning the adjustment of the hyperparameters, I performed an 80/20 train/test split on my data. The different hyperparameters would be tested on the training set, and once the optimized parameter values were chosen, a model would be constructed using the chosen parameters and the testing set, and then would be tested on the training set to see how accurately the model is able to classify the types of wine." }, { "code": null, "e": 3358, "s": 3239, "text": "forest = RandomForestClassifier(random_state = 1)modelF = forest.fit(x_train, y_train)y_predF = modelF.predict(x_test)" }, { "code": null, "e": 3520, "s": 3358, "text": "When tested on the training set with the default values for the hyperparameters, the values of the testing set were predicted with an accuracy of 0.991538461538." }, { "code": null, "e": 3538, "s": 3520, "text": "Validation Curves" }, { "code": null, "e": 4080, "s": 3538, "text": "There’s a few different ways you can choose which hyperparameters to adjust for you model. A good way to visually check for potentially optimized values of model hyperparameters is with a validation curve. A validation curve can be plotted on a graph to show how well a model performs with different values of a single hyperparameter. The following code was run to create the four validation curves seen here, with the values of param_name and param_range being adjusted accordingly for each of the four parameters that we are investigating." }, { "code": null, "e": 4368, "s": 4080, "text": "train_scoreNum, test_scoreNum = validation_curve( RandomForestClassifier(), X = x_train, y = y_train, param_name = 'n_estimators', param_range = num_est, cv = 3)" }, { "code": null, "e": 5004, "s": 4368, "text": "This validation curve was created with the values [100, 300, 500, 750, 800, 1200] as the different values to be tested for n_estimators. In this image, we see that, when testing the values, the best value appears to be 750. It is important to note that, even though there appears to be a large difference between the training and cross-validation score, the training set had an average accuracy of 100% for each of the three cross-validations, and the cross-validation set had between 99.5% and 99.6% accuracy for all the values of n_estimators, which shows that this model is very accurate regardless of the number of estimators used." }, { "code": null, "e": 5389, "s": 5004, "text": "In this graph, we see that the highest accuracy value on the cross-validation is close to 99.3% when the max_depth is set to 15, which is the value that we will place in our model. Whole it may seem better to choose a max_depth of 30, because that value has the highest accuracy for the training score, we elect not to in order to prevent our model from overfitting the training data." }, { "code": null, "e": 5940, "s": 5389, "text": "In this graph, we see that the accuracy actually goes down for both the training and cross-validation sets at higher values for min_samples_split, so we will choose 5 as our number for min_samples_split. In this case, it makes sense that we would want a lower value for min_samples_split, as the default value for this parameter is 2. As we choose higher values for the minimum number of samples required before splitting an internal node, we will have more general leaf nodes, which would have a negative affect on the overall accuracy of our model." }, { "code": null, "e": 6223, "s": 5940, "text": "In this graph, we see that accuracy goes down for both the training and cross-validation sets for each additional increase in value of min_samples_leaf, so we will chose 1 for the value of our parameter, which again makes sense considering the default value for this parameter is 1." }, { "code": null, "e": 6513, "s": 6223, "text": "It is important to note that, when constructing the validation curves, the other parameters were held at their default values. For the purpose of this post, we will be using all of the optimized values together in a single model. A new Random Forest Classifier was constructed, as follows:" }, { "code": null, "e": 6823, "s": 6513, "text": "forestVC = RandomForestClassifier(random_state = 1, n_estimators = 750, max_depth = 15, min_samples_split = 5, min_samples_leaf = 1) modelVC = forestVC.fit(x_train, y_train) y_predVC = modelVC.predict(x_test)" }, { "code": null, "e": 6942, "s": 6823, "text": "This model resulted in an accuracy of 0.993076923077, which was more accurate than our first model, but only by .0015." }, { "code": null, "e": 6965, "s": 6942, "text": "Exhaustive Grid Search" }, { "code": null, "e": 7216, "s": 6965, "text": "Another way to choose which hyperparameters to adjust is by conducting an exhaustive grid search or randomized search. Randomized searches will not be discussed in this post, but further documentation regarding their implementation can be found here." }, { "code": null, "e": 7637, "s": 7216, "text": "An exhaustive grid search takes in as many hyperparameters as you would like, and tries every single possible combination of the hyperparameters as well as as many cross-validations as you would like it to perform. An exhaustive grid search is a good way to determine the best hyperparameter values to use, but it can quickly become time consuming with every additional parameter value and cross-validation that you add." }, { "code": null, "e": 8077, "s": 7637, "text": "n_estimators = [100, 300, 500, 800, 1200]max_depth = [5, 8, 15, 25, 30]min_samples_split = [2, 5, 10, 15, 100]min_samples_leaf = [1, 2, 5, 10] hyperF = dict(n_estimators = n_estimators, max_depth = max_depth, min_samples_split = min_samples_split, min_samples_leaf = min_samples_leaf)gridF = GridSearchCV(forest, hyperF, cv = 3, verbose = 1, n_jobs = -1)bestF = gridF.fit(x_train, y_train)" }, { "code": null, "e": 8349, "s": 8077, "text": "The code shown here took over 25 minutes to run, but did choose hyperparameters that had 100% accuracy in predicting the training models. The resulting “best” hyperparameters are as follows: max_depth = 15, min_samples_leaf = 1, min_samples_split = 2, n_estimators = 500." }, { "code": null, "e": 8441, "s": 8349, "text": "Again, a new Random Forest Classifier was run using these values as hyperparameters inputs." }, { "code": null, "e": 8689, "s": 8441, "text": "forestOpt = RandomForestClassifier(random_state = 1, max_depth = 15, n_estimators = 500, min_samples_split = 2, min_samples_leaf = 1) modelOpt = forestOpt.fit(x_train, y_train)y_pred = modelOpt.predict(x_test)" }, { "code": null, "e": 8782, "s": 8689, "text": "This model also resulted in an accuracy of 0.993076923077 when tested using the testing set." }, { "code": null, "e": 8821, "s": 8782, "text": "Is adjusting hyperparameters worth it?" }, { "code": null, "e": 9107, "s": 8821, "text": "Carefully and methodically adjusting hyperparameters can be advantageous. It can make your classification model more accurate, which will lead to more accurate predictions overall. However, it may not always be worth your while. Let’s take a look at the results of our different tests:" }, { "code": null, "e": 9965, "s": 9107, "text": "The biggest thing to note is the overall improvement in accuracy. The hyperparameters chosen based on the results of the grid search and validation curve resulted in the same accuracy when the model was applied to our testing set: 0.993076923077. This improved our original model’s accuracy on the testing set by .0015. Considering it took over 25 minutes to run the exhaustive grid search on our 4 desired hyperparameters, it may not have been worth the time in this case. Additionally, two of the “optimized” hyperparameter values given to us by our grid search were the same as the default values for these parameters for scikit-learn’s Random Forest Classifier. When looking at the confusion matrices for each of the two optimized models, we see that both resulted in the same number of incorrect predictions for both red and white wines, as shown here:" }, { "code": null, "e": 10544, "s": 9965, "text": "Hyperparameter tuning can be advantageous in creating a model that is better at classification. In the case of a random forest, it may not be necessary, as random forests are already very good at classification. Using exhaustive grid search to choose hyperparameter values can be very time consuming as well. However, in cases where there are only a few potential values for your hyperparameters or when your initial classification model isn’t very accurate, it might be a good idea to at least investigate the effect of changing some of the hyperparameter values in your model." } ]
HTML | <source> media Attribute - GeeksforGeeks
13 Dec, 2021 The HTML source media attribute accepts any valid media query that would normally be defined in a CSS. This attribute can accept several values. Syntax: <source media="media_query"> Possible Operators: Devices: Values: Note: Prefixes like “min-“ and “max-“ can be used. Example: <!DOCTYPE html><html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"></head> <body> <picture> <source media="(min-width: 600px)" srcset="img1.png"> <source media="(min-width: 400px)" srcset="img2.png"> <img src="img3.png" style="width:auto;"> </picture> </body> </html> Output: Change the browser size. Supported Browsers: The browsers supported by HTML source media attribute are listed below: Google Chrome Edge 12.0 Internet Explorer 9.0 Firefox 15.0 Apple Safari Opera Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. ManasChhabra2 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? REST API (Introduction) How to Insert Form Data into Database using PHP ? CSS to put icon inside an input element in a form HTML Cheat Sheet - A Basic Guide to HTML Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25591, "s": 25563, "text": "\n13 Dec, 2021" }, { "code": null, "e": 25736, "s": 25591, "text": "The HTML source media attribute accepts any valid media query that would normally be defined in a CSS. This attribute can accept several values." }, { "code": null, "e": 25744, "s": 25736, "text": "Syntax:" }, { "code": null, "e": 25773, "s": 25744, "text": "<source media=\"media_query\">" }, { "code": null, "e": 25793, "s": 25773, "text": "Possible Operators:" }, { "code": null, "e": 25802, "s": 25793, "text": "Devices:" }, { "code": null, "e": 25810, "s": 25802, "text": "Values:" }, { "code": null, "e": 25861, "s": 25810, "text": "Note: Prefixes like “min-“ and “max-“ can be used." }, { "code": null, "e": 25870, "s": 25861, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"></head> <body> <picture> <source media=\"(min-width: 600px)\" srcset=\"img1.png\"> <source media=\"(min-width: 400px)\" srcset=\"img2.png\"> <img src=\"img3.png\" style=\"width:auto;\"> </picture> </body> </html>", "e": 26246, "s": 25870, "text": null }, { "code": null, "e": 26279, "s": 26246, "text": "Output: Change the browser size." }, { "code": null, "e": 26371, "s": 26279, "text": "Supported Browsers: The browsers supported by HTML source media attribute are listed below:" }, { "code": null, "e": 26385, "s": 26371, "text": "Google Chrome" }, { "code": null, "e": 26395, "s": 26385, "text": "Edge 12.0" }, { "code": null, "e": 26417, "s": 26395, "text": "Internet Explorer 9.0" }, { "code": null, "e": 26430, "s": 26417, "text": "Firefox 15.0" }, { "code": null, "e": 26443, "s": 26430, "text": "Apple Safari" }, { "code": null, "e": 26449, "s": 26443, "text": "Opera" }, { "code": null, "e": 26586, "s": 26449, "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": 26600, "s": 26586, "text": "ManasChhabra2" }, { "code": null, "e": 26616, "s": 26600, "text": "HTML-Attributes" }, { "code": null, "e": 26621, "s": 26616, "text": "HTML" }, { "code": null, "e": 26638, "s": 26621, "text": "Web Technologies" }, { "code": null, "e": 26643, "s": 26638, "text": "HTML" }, { "code": null, "e": 26741, "s": 26643, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26789, "s": 26741, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 26813, "s": 26789, "text": "REST API (Introduction)" }, { "code": null, "e": 26863, "s": 26813, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 26913, "s": 26863, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 26954, "s": 26913, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 26994, "s": 26954, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27027, "s": 26994, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27072, "s": 27027, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27115, "s": 27072, "text": "How to fetch data from an API in ReactJS ?" } ]
Check if the given point lies inside given N points of a Convex Polygon - GeeksforGeeks
08 Jul, 2020 Given coordinates of the N points of a Convex Polygon. The task is to check if the given point (X, Y) lies inside the polygon. Examples: Input: N = 7, Points: {(1, 1), (2, 1), (3, 1), (4, 1), (4, 2), (4, 3), (4, 4)}, Query: X = 3, Y = 2Below is the image of plotting of the given points:Output: YES Input: N = 7, Points: {(1, 1), (2, 1), (3, 1), (4, 1), (4, 2), (4, 3), (4, 4)}, Query: X = 3, Y = 9Output: NO Approach: The idea is to use Graham Scan Algorithm to find if the given point lies inside the Convex Polygon or not. Below are some of the observations: Suppose the point (X, Y) is a point in the set of points of the convex polygon. If the Graham Scan Algorithm is used on this set of points, another set of points would be obtained, which makes up the Convex Hull. If the point (X, Y) lies inside the polygon, it won’t lie on the Convex Hull and hence won’t be present in the newly generated set of points of the Convex Hull. If the point (X, Y) lies outside the polygon, it will then lie on the Convex Hull formed and hence would be present in the newly generated set of points of the Convex Hull. Below are the steps to solve the problem: Sort the given points along with the query point in the increasing order of their abscissa values. If the abscissa values(x-coordinates) of any two points are the same, then sort them on the basis of their ordinate value.Set the bottom-left point as the start point and top-right point as the end point of the convex hull.Iterate over all the points and find out the points, forming the convex polygon, that lies in between the start and endpoints in the clockwise direction. Store these points in a vector.Iterate over all the points and find out the points, forming the convex polygon, that lies in between the start and endpoints in the counter-clockwise direction. Store these points in the vector.Check if the query point exists in the vector then the point lies outside the convex hull. So return “No”.If the point doesn’t exist in the vector, then the point lies inside the convex hull print “Yes”. Sort the given points along with the query point in the increasing order of their abscissa values. If the abscissa values(x-coordinates) of any two points are the same, then sort them on the basis of their ordinate value. Set the bottom-left point as the start point and top-right point as the end point of the convex hull. Iterate over all the points and find out the points, forming the convex polygon, that lies in between the start and endpoints in the clockwise direction. Store these points in a vector. Iterate over all the points and find out the points, forming the convex polygon, that lies in between the start and endpoints in the counter-clockwise direction. Store these points in the vector. Check if the query point exists in the vector then the point lies outside the convex hull. So return “No”. If the point doesn’t exist in the vector, then the point lies inside the convex hull print “Yes”. Below is the implementation based on the above approach: // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Sorting Function to sort pointsbool cmp(pair<int, int>& a, pair<int, int>& b){ if (a.first == b.first) return a.second < b.second; return a.first < b.first;} // Function To Check Clockwise// Orientationint cw(pair<int, int>& a, pair<int, int>& b, pair<int, int>& c){ int p = a.first * (b.second - c.second) + b.first * (c.second - a.second) + c.first * (a.second - b.second); return p < 0ll;} // Function To Check Counter// Clockwise Orientationint ccw(pair<int, int>& a, pair<int, int>& b, pair<int, int>& c){ int p = a.first * (b.second - c.second) + b.first * (c.second - a.second) + c.first * (a.second - b.second); return p > 0ll;} // Graham Scan algorithm to find Convex// Hull from given pointsvector<pair<int, int> > convexHull( vector<pair<int, int> >& v){ // Sort the points sort(v.begin(), v.end(), cmp); int n = v.size(); if (n <= 3) return v; // Set starting and ending points as // left bottom and top right pair<int, int> p1 = v[0]; pair<int, int> p2 = v[n - 1]; // Vector to store points in // upper half and lower half vector<pair<int, int> > up, down; // Insert StartingEnding Points up.push_back(p1); down.push_back(p1); // Iterate over points for (int i = 1; i < n; i++) { if (i == n - 1 || !ccw(p1, v[i], p2)) { while (up.size() > 1 && ccw(up[up.size() - 2], up[up.size() - 1], v[i])) { // Exclude this point // if we can form better up.pop_back(); } up.push_back(v[i]); } if (i == n - 1 || !cw(p1, v[i], p2)) { while (down.size() > 1 && cw(down[down.size() - 2], down[down.size() - 1], v[i])) { // Exclude this point // if we can form better down.pop_back(); } down.push_back(v[i]); } } // Combine upper and lower half for (int i = down.size() - 2; i > 0; i--) up.push_back(down[i]); // Remove duplicate points up.resize(unique(up.begin(), up.end()) - up.begin()); // Return the points on Convex Hull return up;} // Function to find if point lies inside// a convex polygonbool isInside(vector<pair<int, int> > points, pair<int, int> query){ // Include the query point in the // polygon points points.push_back(query); // Form a convex hull from the points points = convexHull(points); // Iterate over the points // of convex hull for (auto x : points) { // If the query point lies // on the convex hull // then it wasn't inside if (x == query) return false; } // Otherwise it was Inside return true;} // Driver Codeint main(){ // Points of the polygon // given in any order int n = 7; vector<pair<int, int> > points; points = { { 1, 1 }, { 2, 1 }, { 3, 1 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 } }; // Query Points pair<int, int> query = { 3, 2 }; // Check if its inside if (isInside(points, query)) { cout << "YES" << endl; } else { cout << "NO" << endl; } return 0;} YES Time Complexity: O(N * log(N))Auxiliary Space: O(N) Geometric Greedy Mathematical Sorting Greedy Mathematical Sorting Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Haversine formula to find distance between two points on a sphere Equation of circle when three points on the circle are given Program to find slope of a line Program to find line passing through 2 Points Maximum Manhattan distance between a distinct pair from N coordinates Dijkstra's shortest path algorithm | Greedy Algo-7 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Program for array rotation Write a program to print all permutations of a given string
[ { "code": null, "e": 26587, "s": 26559, "text": "\n08 Jul, 2020" }, { "code": null, "e": 26714, "s": 26587, "text": "Given coordinates of the N points of a Convex Polygon. The task is to check if the given point (X, Y) lies inside the polygon." }, { "code": null, "e": 26724, "s": 26714, "text": "Examples:" }, { "code": null, "e": 26886, "s": 26724, "text": "Input: N = 7, Points: {(1, 1), (2, 1), (3, 1), (4, 1), (4, 2), (4, 3), (4, 4)}, Query: X = 3, Y = 2Below is the image of plotting of the given points:Output: YES" }, { "code": null, "e": 26996, "s": 26886, "text": "Input: N = 7, Points: {(1, 1), (2, 1), (3, 1), (4, 1), (4, 2), (4, 3), (4, 4)}, Query: X = 3, Y = 9Output: NO" }, { "code": null, "e": 27149, "s": 26996, "text": "Approach: The idea is to use Graham Scan Algorithm to find if the given point lies inside the Convex Polygon or not. Below are some of the observations:" }, { "code": null, "e": 27362, "s": 27149, "text": "Suppose the point (X, Y) is a point in the set of points of the convex polygon. If the Graham Scan Algorithm is used on this set of points, another set of points would be obtained, which makes up the Convex Hull." }, { "code": null, "e": 27523, "s": 27362, "text": "If the point (X, Y) lies inside the polygon, it won’t lie on the Convex Hull and hence won’t be present in the newly generated set of points of the Convex Hull." }, { "code": null, "e": 27696, "s": 27523, "text": "If the point (X, Y) lies outside the polygon, it will then lie on the Convex Hull formed and hence would be present in the newly generated set of points of the Convex Hull." }, { "code": null, "e": 27738, "s": 27696, "text": "Below are the steps to solve the problem:" }, { "code": null, "e": 28644, "s": 27738, "text": "Sort the given points along with the query point in the increasing order of their abscissa values. If the abscissa values(x-coordinates) of any two points are the same, then sort them on the basis of their ordinate value.Set the bottom-left point as the start point and top-right point as the end point of the convex hull.Iterate over all the points and find out the points, forming the convex polygon, that lies in between the start and endpoints in the clockwise direction. Store these points in a vector.Iterate over all the points and find out the points, forming the convex polygon, that lies in between the start and endpoints in the counter-clockwise direction. Store these points in the vector.Check if the query point exists in the vector then the point lies outside the convex hull. So return “No”.If the point doesn’t exist in the vector, then the point lies inside the convex hull print “Yes”." }, { "code": null, "e": 28866, "s": 28644, "text": "Sort the given points along with the query point in the increasing order of their abscissa values. If the abscissa values(x-coordinates) of any two points are the same, then sort them on the basis of their ordinate value." }, { "code": null, "e": 28968, "s": 28866, "text": "Set the bottom-left point as the start point and top-right point as the end point of the convex hull." }, { "code": null, "e": 29154, "s": 28968, "text": "Iterate over all the points and find out the points, forming the convex polygon, that lies in between the start and endpoints in the clockwise direction. Store these points in a vector." }, { "code": null, "e": 29350, "s": 29154, "text": "Iterate over all the points and find out the points, forming the convex polygon, that lies in between the start and endpoints in the counter-clockwise direction. Store these points in the vector." }, { "code": null, "e": 29457, "s": 29350, "text": "Check if the query point exists in the vector then the point lies outside the convex hull. So return “No”." }, { "code": null, "e": 29555, "s": 29457, "text": "If the point doesn’t exist in the vector, then the point lies inside the convex hull print “Yes”." }, { "code": null, "e": 29612, "s": 29555, "text": "Below is the implementation based on the above approach:" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Sorting Function to sort pointsbool cmp(pair<int, int>& a, pair<int, int>& b){ if (a.first == b.first) return a.second < b.second; return a.first < b.first;} // Function To Check Clockwise// Orientationint cw(pair<int, int>& a, pair<int, int>& b, pair<int, int>& c){ int p = a.first * (b.second - c.second) + b.first * (c.second - a.second) + c.first * (a.second - b.second); return p < 0ll;} // Function To Check Counter// Clockwise Orientationint ccw(pair<int, int>& a, pair<int, int>& b, pair<int, int>& c){ int p = a.first * (b.second - c.second) + b.first * (c.second - a.second) + c.first * (a.second - b.second); return p > 0ll;} // Graham Scan algorithm to find Convex// Hull from given pointsvector<pair<int, int> > convexHull( vector<pair<int, int> >& v){ // Sort the points sort(v.begin(), v.end(), cmp); int n = v.size(); if (n <= 3) return v; // Set starting and ending points as // left bottom and top right pair<int, int> p1 = v[0]; pair<int, int> p2 = v[n - 1]; // Vector to store points in // upper half and lower half vector<pair<int, int> > up, down; // Insert StartingEnding Points up.push_back(p1); down.push_back(p1); // Iterate over points for (int i = 1; i < n; i++) { if (i == n - 1 || !ccw(p1, v[i], p2)) { while (up.size() > 1 && ccw(up[up.size() - 2], up[up.size() - 1], v[i])) { // Exclude this point // if we can form better up.pop_back(); } up.push_back(v[i]); } if (i == n - 1 || !cw(p1, v[i], p2)) { while (down.size() > 1 && cw(down[down.size() - 2], down[down.size() - 1], v[i])) { // Exclude this point // if we can form better down.pop_back(); } down.push_back(v[i]); } } // Combine upper and lower half for (int i = down.size() - 2; i > 0; i--) up.push_back(down[i]); // Remove duplicate points up.resize(unique(up.begin(), up.end()) - up.begin()); // Return the points on Convex Hull return up;} // Function to find if point lies inside// a convex polygonbool isInside(vector<pair<int, int> > points, pair<int, int> query){ // Include the query point in the // polygon points points.push_back(query); // Form a convex hull from the points points = convexHull(points); // Iterate over the points // of convex hull for (auto x : points) { // If the query point lies // on the convex hull // then it wasn't inside if (x == query) return false; } // Otherwise it was Inside return true;} // Driver Codeint main(){ // Points of the polygon // given in any order int n = 7; vector<pair<int, int> > points; points = { { 1, 1 }, { 2, 1 }, { 3, 1 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 } }; // Query Points pair<int, int> query = { 3, 2 }; // Check if its inside if (isInside(points, query)) { cout << \"YES\" << endl; } else { cout << \"NO\" << endl; } return 0;}", "e": 33178, "s": 29612, "text": null }, { "code": null, "e": 33183, "s": 33178, "text": "YES\n" }, { "code": null, "e": 33235, "s": 33183, "text": "Time Complexity: O(N * log(N))Auxiliary Space: O(N)" }, { "code": null, "e": 33245, "s": 33235, "text": "Geometric" }, { "code": null, "e": 33252, "s": 33245, "text": "Greedy" }, { "code": null, "e": 33265, "s": 33252, "text": "Mathematical" }, { "code": null, "e": 33273, "s": 33265, "text": "Sorting" }, { "code": null, "e": 33280, "s": 33273, "text": "Greedy" }, { "code": null, "e": 33293, "s": 33280, "text": "Mathematical" }, { "code": null, "e": 33301, "s": 33293, "text": "Sorting" }, { "code": null, "e": 33311, "s": 33301, "text": "Geometric" }, { "code": null, "e": 33409, "s": 33311, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33475, "s": 33409, "text": "Haversine formula to find distance between two points on a sphere" }, { "code": null, "e": 33536, "s": 33475, "text": "Equation of circle when three points on the circle are given" }, { "code": null, "e": 33568, "s": 33536, "text": "Program to find slope of a line" }, { "code": null, "e": 33614, "s": 33568, "text": "Program to find line passing through 2 Points" }, { "code": null, "e": 33684, "s": 33614, "text": "Maximum Manhattan distance between a distinct pair from N coordinates" }, { "code": null, "e": 33735, "s": 33684, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 33793, "s": 33735, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 33844, "s": 33793, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 33871, "s": 33844, "text": "Program for array rotation" } ]
Find total no of collisions taking place between the balls in which initial direction of each ball is given - GeeksforGeeks
24 Nov, 2021 Given N balls in a line. The initial direction of each ball is represented by the string consists of only ‘L’ and ‘R’ for the left and right direction respectively. It is given that both the balls reverse their direction after the collision and speed will remain the same before and after the collision. Calculate the total number of the collision that takes place.Examples: Input: str = "RRLL" Output: 4 Explanation After first collision: RLRL After second collision: LRRL After third collision: LRLR After fourth collision: LLRR Input: str = "RRLR" Output: 2 Explanation After first collision: RLRR After second collision: LRRR Approach:At each stage we have to find the no of substrings “RL”, change the substring “RL” to “LR”, and again count the no of substring “RL” in the resulting string and repeat in the following until no further substring “RL” is available. We are not going to count the no of substring “RL” on each stage as it will consume lots of time. Another way of doing this is, observe that following resulting strings we have seen on each stage –> “RRLL” -> “RLRL”-> “LRLR” ->”LLRR”. The initial string is “RRLL”. let’s have a 3rd ball whose direction is L. Now observe this L is shifting to the left side of the string. As we are exchanging “RL” to “LR”, so we are shifting that L towards the left side of the full string. Now similarly, if we continue this exchange, this L will face every R that is present on the left side of that string, so again forming “RL”. Hence, for this L, the total no of “RL” will be the total no of R which is present on the left side of that particular L. We will repeat this for each L. Hence in general, in order to count every possible substring “RL” at every stage, we will count the total no of represent of the left side of each L as these R and L will form “RL” in every stage which can be done in linear time complexity.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to Find total// no of collisions taking place between// the balls in which initial direction// of each ball is given #include <bits/stdc++.h>using namespace std; // Function to count no of collisionint count(string s){ int N, i, cnt = 0, ans = 0; // length of the string N = s.length(); for (i = 0; i < N; i++) { if (s[i] == 'R') cnt++; if (s[i] == 'L') ans += cnt; } return ans;} // Driver codeint main(){ string s = "RRLL"; cout << count(s) << endl; return 0;} // Java implementation to Find total// no of collisions taking place between// the balls in which initial direction// of each ball is givenimport java.io.*;class GFG { // Function to count// no of collisionstatic int count(String s){ int N, i, cnt = 0, ans = 0; // length of the string N = s.length(); for (i = 0; i < N; i++) { if (s.charAt(i) == 'R') cnt++; if (s.charAt(i) == 'L') ans += cnt; } return ans;} // Driver codestatic public void main(String[] args){ String s = "RRLL"; System.out.println(count(s));}} // This code is contributed by Rutvik_56 # Python3 implementation to find total# no of collisions taking place between# the balls in which initial direction# of each ball is given # Function to count no of collisiondef count(s): cnt, ans = 0, 0 # Length of the string N = len(s) for i in range(N): if (s[i] == 'R'): cnt += 1 if (s[i] == 'L'): ans += cnt return ans # Driver codes = "RRLL" print( count(s)) # This code is contributed by chitranayal // C# implementation to Find total// no of collisions taking place between// the balls in which initial direction// of each ball is givenusing System; class GFG{ // Function to count no of collisionstatic int count(String s){ int N, i, cnt = 0, ans = 0; // length of the string N = s.Length; for(i = 0; i < N; i++) { if (s[i] == 'R') cnt++; if (s[i] == 'L') ans += cnt; } return ans;} // Driver codepublic static void Main(String[] args){ String s = "RRLL"; Console.Write(count(s));}} // This code is contributed by shivanisinghss2110 <script> // Javascript implementation to Find total // no of collisions taking place between // the balls in which initial direction // of each ball is given // Function to count no of collision function count(s) { let N, i, cnt = 0, ans = 0; // length of the string N = s.length; for (i = 0; i < N; i++) { if (s[i] == 'R') cnt++; if (s[i] == 'L') ans += cnt; } return ans; } let s = "RRLL"; document.write(count(s)); // This code is contributed by divyesh072019.</script> 4 Time Complexity: O(N) Auxiliary Space: O(1) ukasp shivanisinghss2110 rutvik_56 divyesh072019 as5853535 rishavmahato348 Arrays Competitive Programming Greedy Mathematical Pattern Searching Strings Arrays Strings Greedy Mathematical Pattern Searching 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 Multidimensional Arrays in Java Introduction to Arrays Linear Search Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Competitive Programming - A Complete Guide Modulo 10^9+7 (1000000007) Prefix Sum Array - Implementation and Applications in Competitive Programming
[ { "code": null, "e": 25062, "s": 25034, "text": "\n24 Nov, 2021" }, { "code": null, "e": 25438, "s": 25062, "text": "Given N balls in a line. The initial direction of each ball is represented by the string consists of only ‘L’ and ‘R’ for the left and right direction respectively. It is given that both the balls reverse their direction after the collision and speed will remain the same before and after the collision. Calculate the total number of the collision that takes place.Examples: " }, { "code": null, "e": 25697, "s": 25438, "text": "Input: str = \"RRLL\"\nOutput: 4\n\nExplanation\nAfter first collision: RLRL\nAfter second collision: LRRL\nAfter third collision: LRLR\nAfter fourth collision: LLRR\n\nInput: str = \"RRLR\"\nOutput: 2\n\nExplanation\nAfter first collision: RLRR\nAfter second collision: LRRR" }, { "code": null, "e": 27000, "s": 25697, "text": "Approach:At each stage we have to find the no of substrings “RL”, change the substring “RL” to “LR”, and again count the no of substring “RL” in the resulting string and repeat in the following until no further substring “RL” is available. We are not going to count the no of substring “RL” on each stage as it will consume lots of time. Another way of doing this is, observe that following resulting strings we have seen on each stage –> “RRLL” -> “RLRL”-> “LRLR” ->”LLRR”. The initial string is “RRLL”. let’s have a 3rd ball whose direction is L. Now observe this L is shifting to the left side of the string. As we are exchanging “RL” to “LR”, so we are shifting that L towards the left side of the full string. Now similarly, if we continue this exchange, this L will face every R that is present on the left side of that string, so again forming “RL”. Hence, for this L, the total no of “RL” will be the total no of R which is present on the left side of that particular L. We will repeat this for each L. Hence in general, in order to count every possible substring “RL” at every stage, we will count the total no of represent of the left side of each L as these R and L will form “RL” in every stage which can be done in linear time complexity.Below is the implementation of the above approach: " }, { "code": null, "e": 27004, "s": 27000, "text": "C++" }, { "code": null, "e": 27009, "s": 27004, "text": "Java" }, { "code": null, "e": 27017, "s": 27009, "text": "Python3" }, { "code": null, "e": 27020, "s": 27017, "text": "C#" }, { "code": null, "e": 27031, "s": 27020, "text": "Javascript" }, { "code": "// C++ implementation to Find total// no of collisions taking place between// the balls in which initial direction// of each ball is given #include <bits/stdc++.h>using namespace std; // Function to count no of collisionint count(string s){ int N, i, cnt = 0, ans = 0; // length of the string N = s.length(); for (i = 0; i < N; i++) { if (s[i] == 'R') cnt++; if (s[i] == 'L') ans += cnt; } return ans;} // Driver codeint main(){ string s = \"RRLL\"; cout << count(s) << endl; return 0;}", "e": 27586, "s": 27031, "text": null }, { "code": "// Java implementation to Find total// no of collisions taking place between// the balls in which initial direction// of each ball is givenimport java.io.*;class GFG { // Function to count// no of collisionstatic int count(String s){ int N, i, cnt = 0, ans = 0; // length of the string N = s.length(); for (i = 0; i < N; i++) { if (s.charAt(i) == 'R') cnt++; if (s.charAt(i) == 'L') ans += cnt; } return ans;} // Driver codestatic public void main(String[] args){ String s = \"RRLL\"; System.out.println(count(s));}} // This code is contributed by Rutvik_56", "e": 28176, "s": 27586, "text": null }, { "code": "# Python3 implementation to find total# no of collisions taking place between# the balls in which initial direction# of each ball is given # Function to count no of collisiondef count(s): cnt, ans = 0, 0 # Length of the string N = len(s) for i in range(N): if (s[i] == 'R'): cnt += 1 if (s[i] == 'L'): ans += cnt return ans # Driver codes = \"RRLL\" print( count(s)) # This code is contributed by chitranayal", "e": 28643, "s": 28176, "text": null }, { "code": "// C# implementation to Find total// no of collisions taking place between// the balls in which initial direction// of each ball is givenusing System; class GFG{ // Function to count no of collisionstatic int count(String s){ int N, i, cnt = 0, ans = 0; // length of the string N = s.Length; for(i = 0; i < N; i++) { if (s[i] == 'R') cnt++; if (s[i] == 'L') ans += cnt; } return ans;} // Driver codepublic static void Main(String[] args){ String s = \"RRLL\"; Console.Write(count(s));}} // This code is contributed by shivanisinghss2110", "e": 29245, "s": 28643, "text": null }, { "code": "<script> // Javascript implementation to Find total // no of collisions taking place between // the balls in which initial direction // of each ball is given // Function to count no of collision function count(s) { let N, i, cnt = 0, ans = 0; // length of the string N = s.length; for (i = 0; i < N; i++) { if (s[i] == 'R') cnt++; if (s[i] == 'L') ans += cnt; } return ans; } let s = \"RRLL\"; document.write(count(s)); // This code is contributed by divyesh072019.</script>", "e": 29814, "s": 29245, "text": null }, { "code": null, "e": 29816, "s": 29814, "text": "4" }, { "code": null, "e": 29840, "s": 29818, "text": "Time Complexity: O(N)" }, { "code": null, "e": 29862, "s": 29840, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 29868, "s": 29862, "text": "ukasp" }, { "code": null, "e": 29887, "s": 29868, "text": "shivanisinghss2110" }, { "code": null, "e": 29897, "s": 29887, "text": "rutvik_56" }, { "code": null, "e": 29911, "s": 29897, "text": "divyesh072019" }, { "code": null, "e": 29921, "s": 29911, "text": "as5853535" }, { "code": null, "e": 29937, "s": 29921, "text": "rishavmahato348" }, { "code": null, "e": 29944, "s": 29937, "text": "Arrays" }, { "code": null, "e": 29968, "s": 29944, "text": "Competitive Programming" }, { "code": null, "e": 29975, "s": 29968, "text": "Greedy" }, { "code": null, "e": 29988, "s": 29975, "text": "Mathematical" }, { "code": null, "e": 30006, "s": 29988, "text": "Pattern Searching" }, { "code": null, "e": 30014, "s": 30006, "text": "Strings" }, { "code": null, "e": 30021, "s": 30014, "text": "Arrays" }, { "code": null, "e": 30029, "s": 30021, "text": "Strings" }, { "code": null, "e": 30036, "s": 30029, "text": "Greedy" }, { "code": null, "e": 30049, "s": 30036, "text": "Mathematical" }, { "code": null, "e": 30067, "s": 30049, "text": "Pattern Searching" }, { "code": null, "e": 30165, "s": 30067, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30174, "s": 30165, "text": "Comments" }, { "code": null, "e": 30187, "s": 30174, "text": "Old Comments" }, { "code": null, "e": 30235, "s": 30187, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 30279, "s": 30235, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 30311, "s": 30279, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 30334, "s": 30311, "text": "Introduction to Arrays" }, { "code": null, "e": 30348, "s": 30334, "text": "Linear Search" }, { "code": null, "e": 30391, "s": 30348, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 30432, "s": 30391, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 30475, "s": 30432, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 30502, "s": 30475, "text": "Modulo 10^9+7 (1000000007)" } ]
XAML - Dialog Box
All standalone applications have a main window that exposes some functionality and displays some data over which the application operates through its GUI. An application may also display additional windows to do the following − To display some specific information to users. To gather useful information from users. To both display and gather important information. Let’s have a look at the following example. On the main window, there is a button and a textbox. When the user clicks this button, it opens another dialog box with Yes, No, and Cancel buttons and displays a message on it that prompts the user to click a button. When the user clicks a button, then the current dialog box gets closed and shows a textbox with the information "which button has been clicked". Here is the XAML code to create and initialize a button and a textbox with some properties − <Window x:Class = "XAMLDialog.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "604"> <Grid> <Button Height = "23" Margin = "100" Name = "ShowMessageBox" VerticalAlignment = "Top" Click = "ShowMessageBox_Click">Show Message Box</Button> <TextBox Height = "23" HorizontalAlignment = "Left" Margin = "181,167,0,0" Name = "textBox1" VerticalAlignment = "Top" Width = "120" /> </Grid> </Window> Given below is the C# code to implement a button click event. using System; using System.Windows; using System.Windows.Controls; namespace XAMLDialog { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void ShowMessageBox_Click(object sender, RoutedEventArgs e) { string msgtext = "Click any button"; string txt = "My Title"; MessageBoxButton button = MessageBoxButton.YesNoCancel; MessageBoxResult result = MessageBox.Show(msgtext, txt, button); switch (result) { case MessageBoxResult.Yes: textBox1.Text = "Yes"; break; case MessageBoxResult.No: textBox1.Text = "No"; break; case MessageBoxResult.Cancel: textBox1.Text = "Cancel"; break; } } } } When you compile and execute the above code, it will produce the following output − When you click on the button, it displays another dialog box as shown below that prompts the user to click a button. Now, click the Yes button. It updates the textbox with the button content. Print Add Notes Bookmark this page
[ { "code": null, "e": 2151, "s": 1923, "text": "All standalone applications have a main window that exposes some functionality and displays some data over which the application operates through its GUI. An application may also display additional windows to do the following −" }, { "code": null, "e": 2198, "s": 2151, "text": "To display some specific information to users." }, { "code": null, "e": 2239, "s": 2198, "text": "To gather useful information from users." }, { "code": null, "e": 2289, "s": 2239, "text": "To both display and gather important information." }, { "code": null, "e": 2551, "s": 2289, "text": "Let’s have a look at the following example. On the main window, there is a button and a textbox. When the user clicks this button, it opens another dialog box with Yes, No, and Cancel buttons and displays a message on it that prompts the user to click a button." }, { "code": null, "e": 2696, "s": 2551, "text": "When the user clicks a button, then the current dialog box gets closed and shows a textbox with the information \"which button has been clicked\"." }, { "code": null, "e": 2789, "s": 2696, "text": "Here is the XAML code to create and initialize a button and a textbox with some properties −" }, { "code": null, "e": 3440, "s": 2789, "text": "<Window x:Class = \"XAMLDialog.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\"\n Title = \"MainWindow\" Height = \"350\" Width = \"604\"> \n\t\n <Grid> \n <Button Height = \"23\" \n Margin = \"100\" \n Name = \"ShowMessageBox\" \n VerticalAlignment = \"Top\" \n Click = \"ShowMessageBox_Click\">Show Message Box</Button>\n\t\t\t\n <TextBox Height = \"23\" \n HorizontalAlignment = \"Left\" \n Margin = \"181,167,0,0\" \n Name = \"textBox1\" \n VerticalAlignment = \"Top\" \n Width = \"120\" /> \n </Grid> \n</Window>" }, { "code": null, "e": 3502, "s": 3440, "text": "Given below is the C# code to implement a button click event." }, { "code": null, "e": 4462, "s": 3502, "text": "using System; \nusing System.Windows; \nusing System.Windows.Controls;\n\nnamespace XAMLDialog {\n /// <summary> \n /// Interaction logic for MainWindow.xaml \n /// </summary> \n\t\n public partial class MainWindow : Window {\n public MainWindow() { \n InitializeComponent(); \n } \n private void ShowMessageBox_Click(object sender, RoutedEventArgs e) { \n string msgtext = \"Click any button\"; \n string txt = \"My Title\"; \n MessageBoxButton button = MessageBoxButton.YesNoCancel;\n MessageBoxResult result = MessageBox.Show(msgtext, txt, button);\n\n switch (result) { \n case MessageBoxResult.Yes: \n textBox1.Text = \"Yes\"; \n break;\n case MessageBoxResult.No: \n textBox1.Text = \"No\"; \n break; \n case MessageBoxResult.Cancel: \n textBox1.Text = \"Cancel\"; \n break; \n }\n }\n }\n}" }, { "code": null, "e": 4546, "s": 4462, "text": "When you compile and execute the above code, it will produce the following output −" }, { "code": null, "e": 4690, "s": 4546, "text": "When you click on the button, it displays another dialog box as shown below that prompts the user to click a button. Now, click the Yes button." }, { "code": null, "e": 4738, "s": 4690, "text": "It updates the textbox with the button content." }, { "code": null, "e": 4745, "s": 4738, "text": " Print" }, { "code": null, "e": 4756, "s": 4745, "text": " Add Notes" } ]
Extract given rows and columns from a given dataframe in R - GeeksforGeeks
26 Mar, 2021 Extraction of given rows and columns has always been one of the most important tasks which are especially required while working on data cleaning activities. In this article, we will be discussing all the sets of commands which are used to extract given rows and columns from a given dataframe in the R programming language. A single element can be extracted if the exact position of the item is known and is passed. Syntax: df[ row , column ] Example: R df <- data.frame( c( 30, 40, 50), c( 110, 120, 130 ),c( 280, 285,290)) names(df) <- c("c1", "c2", "c3") df[3,2] Output: [1] 130 Method 1: Extraction of all rows and columns If no row and column number is specified, all rows and columns basically the complete data set is printed. Syntax: df[ ,] Example: R df <- data.frame( c( 30, 40, 50), c( 110, 120, 130 ),c( 280, 285,290)) names(df) <- c("c1", "c2", "c3") df[,] Output: c1 c2 c3 1 30 110 280 2 40 120 285 3 50 130 290 Method 2: Extraction of All rows of a column If no row number is specified, but the column number is set to the required column value, all rows of a column can be extracted. Syntax: df[,n] Example: R df <- data.frame( c( 30, 40, 50), c( 110, 120, 130 ),c( 280, 285,290)) names(df) <- c("c1", "c2", "c3") df[,1] Output: [1] 30 40 50 Method 3: extraction of All columns of a row If row number is specified, but no column number is given, all columns of a row can be extracted. Syntax: df[n,] Example: R df <- data.frame( c( 30, 40, 50), c( 110, 120, 130 ),c( 280, 285,290)) names(df) <- c("c1", "c2", "c3") df[1,] Output: c1 c2 c3 1 30 110 280 Method 4: extraction of more than one rows with all columns c in c() means ‘combine’. c function is a generic function which combines it arguments to form vectors. When row numbers to be extracted are specified and column number is not specified, selected rows with all columns are displayed. Syntax: df[ c(n,m), ] Example: R df <- data.frame( c( 30, 40, 50), c( 110, 120, 130 ),c( 280, 285,290)) names(df) <- c("c1", "c2", "c3") df[ c(1,3),] Output: c1 c2 c3 1 30 110 280 3 50 130 290 Method 5: extraction of more than one column with all rows For this number of rows to be extracted should be given with no arguments for rows. Syntax: df[,c(n,m)] Example: R df <- data.frame( c( 30, 40, 50), c( 110, 120, 130 ),c( 280, 285,290)) names(df) <- c("c1", "c2", "c3") df[,c(2,3)] Output: c2 c3 1 110 280 2 120 285 3 130 290 Method 6: extraction of range of rows with all columns If the range is specified for rows with no value for columns, this functionality can be achieved. Syntax: df[n:m,] Example: R df <- data.frame( c( 30, 40, 50), c( 110, 120, 130 ),c( 280, 285,290)) names(df) <- c("c1", "c2", "c3") df[1:2,] Output: c1 c2 c3 1 30 110 280 2 40 120 285 Method 7: extraction of a specific row from a range of columns If the row is provided with the number of the row to be extracted and column with the range our functionality can be achieved. Syntax: df[r,n:m] Example: R df <- data.frame( c( 30, 40, 50), c( 110, 120, 130 ),c( 280, 285,290)) names(df) <- c("c1", "c2", "c3") df[2,1:3] Output: c1 c2 c3 2 40 120 285 Method 8: extraction of range of rows and columns Supply rows and columns with ranges. Syntax: df[p:q, n:m] Example: R df <- data.frame( c( 30, 40, 50), c( 110, 120, 130 ),c( 280, 285,290)) names(df) <- c("c1", "c2", "c3") df[1:2, 1:3] Output: c1 c2 c3 1 30 110 280 2 40 120 285 Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) How to change Row Names of DataFrame in R ? Change Color of Bars in Barchart using ggplot2 in R How to Replace specific values in column in R DataFrame ? How to change Row Names of DataFrame in R ? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R Remove rows with NA in one column of R DataFrame
[ { "code": null, "e": 26308, "s": 26280, "text": "\n26 Mar, 2021" }, { "code": null, "e": 26633, "s": 26308, "text": "Extraction of given rows and columns has always been one of the most important tasks which are especially required while working on data cleaning activities. In this article, we will be discussing all the sets of commands which are used to extract given rows and columns from a given dataframe in the R programming language." }, { "code": null, "e": 26725, "s": 26633, "text": "A single element can be extracted if the exact position of the item is known and is passed." }, { "code": null, "e": 26734, "s": 26725, "text": "Syntax: " }, { "code": null, "e": 26753, "s": 26734, "text": "df[ row , column ]" }, { "code": null, "e": 26762, "s": 26753, "text": "Example:" }, { "code": null, "e": 26764, "s": 26762, "text": "R" }, { "code": "df <- data.frame( c( 30, 40, 50), c( 110, 120, 130 ),c( 280, 285,290)) names(df) <- c(\"c1\", \"c2\", \"c3\") df[3,2]", "e": 26880, "s": 26764, "text": null }, { "code": null, "e": 26888, "s": 26880, "text": "Output:" }, { "code": null, "e": 26896, "s": 26888, "text": "[1] 130" }, { "code": null, "e": 26941, "s": 26896, "text": "Method 1: Extraction of all rows and columns" }, { "code": null, "e": 27048, "s": 26941, "text": "If no row and column number is specified, all rows and columns basically the complete data set is printed." }, { "code": null, "e": 27057, "s": 27048, "text": "Syntax: " }, { "code": null, "e": 27065, "s": 27057, "text": " df[ ,]" }, { "code": null, "e": 27074, "s": 27065, "text": "Example:" }, { "code": null, "e": 27076, "s": 27074, "text": "R" }, { "code": "df <- data.frame( c( 30, 40, 50), c( 110, 120, 130 ),c( 280, 285,290)) names(df) <- c(\"c1\", \"c2\", \"c3\") df[,]", "e": 27190, "s": 27076, "text": null }, { "code": null, "e": 27198, "s": 27190, "text": "Output:" }, { "code": null, "e": 27211, "s": 27198, "text": " c1 c2 c3" }, { "code": null, "e": 27224, "s": 27211, "text": "1 30 110 280" }, { "code": null, "e": 27237, "s": 27224, "text": "2 40 120 285" }, { "code": null, "e": 27250, "s": 27237, "text": "3 50 130 290" }, { "code": null, "e": 27295, "s": 27250, "text": "Method 2: Extraction of All rows of a column" }, { "code": null, "e": 27424, "s": 27295, "text": "If no row number is specified, but the column number is set to the required column value, all rows of a column can be extracted." }, { "code": null, "e": 27432, "s": 27424, "text": "Syntax:" }, { "code": null, "e": 27439, "s": 27432, "text": "df[,n]" }, { "code": null, "e": 27448, "s": 27439, "text": "Example:" }, { "code": null, "e": 27450, "s": 27448, "text": "R" }, { "code": "df <- data.frame( c( 30, 40, 50), c( 110, 120, 130 ),c( 280, 285,290)) names(df) <- c(\"c1\", \"c2\", \"c3\") df[,1]", "e": 27565, "s": 27450, "text": null }, { "code": null, "e": 27573, "s": 27565, "text": "Output:" }, { "code": null, "e": 27586, "s": 27573, "text": "[1] 30 40 50" }, { "code": null, "e": 27631, "s": 27586, "text": "Method 3: extraction of All columns of a row" }, { "code": null, "e": 27729, "s": 27631, "text": "If row number is specified, but no column number is given, all columns of a row can be extracted." }, { "code": null, "e": 27737, "s": 27729, "text": "Syntax:" }, { "code": null, "e": 27744, "s": 27737, "text": "df[n,]" }, { "code": null, "e": 27753, "s": 27744, "text": "Example:" }, { "code": null, "e": 27755, "s": 27753, "text": "R" }, { "code": "df <- data.frame( c( 30, 40, 50), c( 110, 120, 130 ),c( 280, 285,290)) names(df) <- c(\"c1\", \"c2\", \"c3\") df[1,]", "e": 27871, "s": 27755, "text": null }, { "code": null, "e": 27879, "s": 27871, "text": "Output:" }, { "code": null, "e": 27892, "s": 27879, "text": " c1 c2 c3" }, { "code": null, "e": 27905, "s": 27892, "text": "1 30 110 280" }, { "code": null, "e": 27965, "s": 27905, "text": "Method 4: extraction of more than one rows with all columns" }, { "code": null, "e": 28198, "s": 27965, "text": "c in c() means ‘combine’. c function is a generic function which combines it arguments to form vectors. When row numbers to be extracted are specified and column number is not specified, selected rows with all columns are displayed." }, { "code": null, "e": 28206, "s": 28198, "text": "Syntax:" }, { "code": null, "e": 28220, "s": 28206, "text": "df[ c(n,m), ]" }, { "code": null, "e": 28229, "s": 28220, "text": "Example:" }, { "code": null, "e": 28231, "s": 28229, "text": "R" }, { "code": "df <- data.frame( c( 30, 40, 50), c( 110, 120, 130 ),c( 280, 285,290)) names(df) <- c(\"c1\", \"c2\", \"c3\") df[ c(1,3),]", "e": 28353, "s": 28231, "text": null }, { "code": null, "e": 28361, "s": 28353, "text": "Output:" }, { "code": null, "e": 28374, "s": 28361, "text": " c1 c2 c3" }, { "code": null, "e": 28387, "s": 28374, "text": "1 30 110 280" }, { "code": null, "e": 28400, "s": 28387, "text": "3 50 130 290" }, { "code": null, "e": 28459, "s": 28400, "text": "Method 5: extraction of more than one column with all rows" }, { "code": null, "e": 28543, "s": 28459, "text": "For this number of rows to be extracted should be given with no arguments for rows." }, { "code": null, "e": 28551, "s": 28543, "text": "Syntax:" }, { "code": null, "e": 28563, "s": 28551, "text": "df[,c(n,m)]" }, { "code": null, "e": 28572, "s": 28563, "text": "Example:" }, { "code": null, "e": 28574, "s": 28572, "text": "R" }, { "code": "df <- data.frame( c( 30, 40, 50), c( 110, 120, 130 ),c( 280, 285,290)) names(df) <- c(\"c1\", \"c2\", \"c3\") df[,c(2,3)]", "e": 28695, "s": 28574, "text": null }, { "code": null, "e": 28703, "s": 28695, "text": "Output:" }, { "code": null, "e": 28713, "s": 28703, "text": " c2 c3" }, { "code": null, "e": 28723, "s": 28713, "text": "1 110 280" }, { "code": null, "e": 28733, "s": 28723, "text": "2 120 285" }, { "code": null, "e": 28743, "s": 28733, "text": "3 130 290" }, { "code": null, "e": 28798, "s": 28743, "text": "Method 6: extraction of range of rows with all columns" }, { "code": null, "e": 28896, "s": 28798, "text": "If the range is specified for rows with no value for columns, this functionality can be achieved." }, { "code": null, "e": 28904, "s": 28896, "text": "Syntax:" }, { "code": null, "e": 28913, "s": 28904, "text": "df[n:m,]" }, { "code": null, "e": 28922, "s": 28913, "text": "Example:" }, { "code": null, "e": 28924, "s": 28922, "text": "R" }, { "code": "df <- data.frame( c( 30, 40, 50), c( 110, 120, 130 ),c( 280, 285,290)) names(df) <- c(\"c1\", \"c2\", \"c3\") df[1:2,]", "e": 29041, "s": 28924, "text": null }, { "code": null, "e": 29049, "s": 29041, "text": "Output:" }, { "code": null, "e": 29062, "s": 29049, "text": " c1 c2 c3" }, { "code": null, "e": 29075, "s": 29062, "text": "1 30 110 280" }, { "code": null, "e": 29088, "s": 29075, "text": "2 40 120 285" }, { "code": null, "e": 29151, "s": 29088, "text": "Method 7: extraction of a specific row from a range of columns" }, { "code": null, "e": 29278, "s": 29151, "text": "If the row is provided with the number of the row to be extracted and column with the range our functionality can be achieved." }, { "code": null, "e": 29286, "s": 29278, "text": "Syntax:" }, { "code": null, "e": 29296, "s": 29286, "text": "df[r,n:m]" }, { "code": null, "e": 29305, "s": 29296, "text": "Example:" }, { "code": null, "e": 29307, "s": 29305, "text": "R" }, { "code": "df <- data.frame( c( 30, 40, 50), c( 110, 120, 130 ),c( 280, 285,290)) names(df) <- c(\"c1\", \"c2\", \"c3\") df[2,1:3]", "e": 29426, "s": 29307, "text": null }, { "code": null, "e": 29434, "s": 29426, "text": "Output:" }, { "code": null, "e": 29447, "s": 29434, "text": " c1 c2 c3" }, { "code": null, "e": 29460, "s": 29447, "text": "2 40 120 285" }, { "code": null, "e": 29510, "s": 29460, "text": "Method 8: extraction of range of rows and columns" }, { "code": null, "e": 29547, "s": 29510, "text": "Supply rows and columns with ranges." }, { "code": null, "e": 29555, "s": 29547, "text": "Syntax:" }, { "code": null, "e": 29568, "s": 29555, "text": "df[p:q, n:m]" }, { "code": null, "e": 29577, "s": 29568, "text": "Example:" }, { "code": null, "e": 29579, "s": 29577, "text": "R" }, { "code": "df <- data.frame( c( 30, 40, 50), c( 110, 120, 130 ),c( 280, 285,290)) names(df) <- c(\"c1\", \"c2\", \"c3\") df[1:2, 1:3]", "e": 29700, "s": 29579, "text": null }, { "code": null, "e": 29708, "s": 29700, "text": "Output:" }, { "code": null, "e": 29723, "s": 29708, "text": " c1 c2 c3" }, { "code": null, "e": 29736, "s": 29723, "text": "1 30 110 280" }, { "code": null, "e": 29749, "s": 29736, "text": "2 40 120 285" }, { "code": null, "e": 29756, "s": 29749, "text": "Picked" }, { "code": null, "e": 29777, "s": 29756, "text": "R DataFrame-Programs" }, { "code": null, "e": 29789, "s": 29777, "text": "R-DataFrame" }, { "code": null, "e": 29800, "s": 29789, "text": "R Language" }, { "code": null, "e": 29811, "s": 29800, "text": "R Programs" }, { "code": null, "e": 29909, "s": 29811, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29967, "s": 29909, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 30019, "s": 29967, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 30051, "s": 30019, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 30095, "s": 30051, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 30147, "s": 30095, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 30205, "s": 30147, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 30249, "s": 30205, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 30307, "s": 30249, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 30350, "s": 30307, "text": "Replace Specific Characters in String in R" } ]
OAuth 2.0 - Quick Guide
OAuth is an open authorization protocol, which allows accessing the resources of the resource owner by enabling the client applications on HTTP services such as Facebook, GitHub, etc. It allows sharing of resources stored on one site to another site without using their credentials. It uses username and password tokens instead. OAuth 2.0 is developed by the IETF OAuth Working Group, published in October 2012. You can use OAuth 2.0 to read data of a user from another application. You can use OAuth 2.0 to read data of a user from another application. It supplies the authorization workflow for web, desktop applications, and mobile devices. It supplies the authorization workflow for web, desktop applications, and mobile devices. It is a server side web app that uses authorization code and does not interact with user credentials. It is a server side web app that uses authorization code and does not interact with user credentials. OAuth 2.0 is a simple protocol that allows to access resources of the user without sharing passwords. OAuth 2.0 is a simple protocol that allows to access resources of the user without sharing passwords. It provides user agent flows for running clients application using a scripting language, such as JavaScript. Typically, a browser is a user agent. It provides user agent flows for running clients application using a scripting language, such as JavaScript. Typically, a browser is a user agent. It accesses the data using tokens instead of using their credentials and stores data in online file system of the user such as Google Docs or Dropbox account. It accesses the data using tokens instead of using their credentials and stores data in online file system of the user such as Google Docs or Dropbox account. OAuth 2.0 is a very flexible protocol that relies on SSL (Secure Sockets Layer that ensures data between the web server and browsers remain private) to save user access token. OAuth 2.0 is a very flexible protocol that relies on SSL (Secure Sockets Layer that ensures data between the web server and browsers remain private) to save user access token. OAuth 2.0 relies on SSL which is used to ensure cryptography industry protocols and are being used to keep the data safe. OAuth 2.0 relies on SSL which is used to ensure cryptography industry protocols and are being used to keep the data safe. It allows limited access to the user's data and allows accessing when authorization tokens expire. It allows limited access to the user's data and allows accessing when authorization tokens expire. It has ability to share data for users without having to release personal information. It has ability to share data for users without having to release personal information. It is easier to implement and provides stronger authentication. It is easier to implement and provides stronger authentication. If you are adding more extension at the ends in the specification, it will produce a wide range of non-interoperable implementations, which means you have to write separate pieces of code for Facebook, Google, etc. If you are adding more extension at the ends in the specification, it will produce a wide range of non-interoperable implementations, which means you have to write separate pieces of code for Facebook, Google, etc. If your favorite sites are connected to the central hub and the central account is hacked, then it will lead to serious effects across several sites instead of just one. If your favorite sites are connected to the central hub and the central account is hacked, then it will lead to serious effects across several sites instead of just one. In this chapter, we will discuss the architectural style of OAuth 2.0. Step 1 − First, the user accesses resources using the client application such as Google, Facebook, Twitter, etc. Step 2 − Next, the client application will be provided with the client id and client password during registering the redirect URI (Uniform Resource Identifier). Step 3 − The user logs in using the authenticating application. The client ID and client password is unique to the client application on the authorization server. Step 4 − The authenticating server redirects the user to a redirect Uniform Resource Identifier (URI) using authorization code. Step 5 − The user accesses the page located at redirect URI in the client application. Step 6 − The client application will be provided with the authentication code, client id and client password, and send them to the authorization server. Step 7 − The authenticating application returns an access token to the client application. Step 8 − Once the client application gets an access token, the user starts accessing the resources of the resource owner using the client application. OAuth 2.0 has various concepts, which are briefly explained in the following table. OAuth provides some additional terms to understand the concepts of authorization. Web server delivers the web pages and uses HTTP to serve the files that forms the web pages to the users. The user agent application is used by client applications in the user's device, which acts as the scripting language instance. Native application can be used as an instance of desktop or mobile phone application, which uses the resource owner password credentials. The client credentials can be used as an authorization grant when the client is the resource owner, or when the authorization scope is limited to protected resources under the control of the client. The client requests an access token only with the help of client credentials. The client requests an access token only with the help of client credentials. The client credentials authorization flow is used to acquire access token to authorize API requests. The client credentials authorization flow is used to acquire access token to authorize API requests. Using client credentials authorization, access token which is acquired, only grants permission for your client application to search and get catalog documents. Using client credentials authorization, access token which is acquired, only grants permission for your client application to search and get catalog documents. The following figure depicts the Client Credentials Flow. The flow illustrated in the above figure consists of the following steps − Step 1 − The client authenticates with the authorization server and makes a request for access token from the token endpoint. Step 2 − The authorization server authenticates the client and provides access token if it's valid and authorized. The following table lists the concepts of Client Credentials. The authorization end point is typically URI on the authorization server in which the resource owner logs in and permits to access the data to the client application. The authorization response can be used to get the access token for accessing the owner resources in the system using the authorization code. The authorization server responds with a HTTP 400 or 401 (bad request) status codes, if an error occurs during authorization. An access token is a string that identifies a user, an application, or a page. The token includes information such as when the token will expire and which app created that token. First, it is necessary to acquire OAuth 2.0 client credentials from API console. First, it is necessary to acquire OAuth 2.0 client credentials from API console. Then, the access token is requested from the authorization server by the client. Then, the access token is requested from the authorization server by the client. It gets an access token from the response and sends the token to the API that you wish to access. It gets an access token from the response and sends the token to the API that you wish to access. You must send the user to the authorization endpoint at the beginning. Following is an example of a dummy request https://publicapi.example.com/oauth2/authorize?client_id=your_client_id&redirect_uri=your_url &response_type=code Following are the parameters and their descriptions. client_id − It should be set to the client id of your application. client_id − It should be set to the client id of your application. redirect_uri − It should be set to the URL. After the request is authorized, the user will be redirected back. redirect_uri − It should be set to the URL. After the request is authorized, the user will be redirected back. response_type − It can either be a code or a token. The code must be used for server side applications, whereas the token must be used for client side applications. In server side applications, you can make sure that the secrets are saved safely. response_type − It can either be a code or a token. The code must be used for server side applications, whereas the token must be used for client side applications. In server side applications, you can make sure that the secrets are saved safely. Following table lists the concepts of Client Credentials. The authorization code allows accessing the authorization request and grants access to the client application to fetch the owner resources. The resource owner password credentials include only one request and one response, and is useful where the resource owner has a good relationship with the client. Assertion is a package of information that makes the sharing of identity and security information across various security domains possible. The refresh tokens are used to acquire a new access tokens, which carries the information necessary to get a new access token. Access token is a type of token that is assigned by the authorization server. If the token access request, which is issued by the authorization server is invalid or unauthorized, then the authorization server returns an error response. The client provides an access token to the resource server to access protected resources. The resource server must validate and verify that the access token is valid and has not expired. There are two standard ways of sending credentials − Bearer Token − The access token can only be placed in POST request body or GET URL parameter as a fallback option in the authorization HTTP header. Bearer Token − The access token can only be placed in POST request body or GET URL parameter as a fallback option in the authorization HTTP header. They are included in the authorization header as follows − Authorization: Bearer [token-value] For Example − GET/resource/1 HTTP /1.1 Host: example.com Authorization: Bearer abc... MAC − A cryptographic Message Authentication Code (MAC) is computed using the elements of the request and is sent to the authorization header. Upon receiving the request, the MAC is then compared and computed by the resource owner. MAC − A cryptographic Message Authentication Code (MAC) is computed using the elements of the request and is sent to the authorization header. Upon receiving the request, the MAC is then compared and computed by the resource owner. The following table shows the concepts of accessing protected resource. It is used to get the authorization code token for accessing the owner resources in the system. The resource server includes the "WWW-Authenticate" response header field, if the protected resource request contains an invalid access token. There are two ways in which the access token types can be defined − By registering in the access token type's registry. By registering in the access token type's registry. By using a unique absolute URI (Uniform Resource Identifier) as its name. By using a unique absolute URI (Uniform Resource Identifier) as its name. Parameter names must obey the param-name ABNF (Augmented Backus-Naur Form is a metalanguage based on Backus-Naur Form consisting of its own syntax and derivation rules) and the syntax of parameter values must be well-defined. param-name = 1* name-char name-char = "-" / "." / "_" / DIGIT / ALPHA New authorization grant types can be assigned a distinct absolute URI for use, with the help of "grant_type" parameter. The extension grant type must be registered in the OAuth parameters registry, if it requires additional token endpoint parameters. response-type = response-name *(SP response-name) response-name = 1* response-char response-char = "_" / DIGIT / ALPHA The response type is compared as space-delimited list of values, if it has one or more space characters where the order of the values does not matter and only one order of value can be registered. The extension error codes must be registered, if the extensions they use are either a registered access token, or a registered endpoint parameter. The error code must obey the error ABNF (Augmented Backus-Naur Form) and when possible it should be prefixed by a name identifying it. error = 1 * error_char error-char = %x20-21 / %x23-5B / 5D-7E IANA stands for Internet Assigned Numbers Authority which provides the information about the registration values related to the Remote Authentication Dial In User Service (RADIUS). IANA includes the following considerations − OAuth access tokens are registered by experts with required specification. If they are satisfied with the registration, only then they will publish the specification. The registration request will be sent to the @ietf.org for reviewing with the subject ("Request for access token type: example"). Experts will either reject or accept the request within 14 days of the request. The registration template contains the following specifications − Type Name − It is the name of the request. Type Name − It is the name of the request. Token Endpoint Response Parameters − The additional access token response parameter will be registered separately in OAuth parameters registry. Token Endpoint Response Parameters − The additional access token response parameter will be registered separately in OAuth parameters registry. HTTP Authentication Scheme − The HTTP authentication scheme can be used to authenticate the resources by using the access token. HTTP Authentication Scheme − The HTTP authentication scheme can be used to authenticate the resources by using the access token. Change Controller − Give the state name as "IETF" for standard track RFCs, and for others, use the name of the responsible party. Change Controller − Give the state name as "IETF" for standard track RFCs, and for others, use the name of the responsible party. Specification Document − The specification document contains the parameter that can be used to retrieve a copy of the document. Specification Document − The specification document contains the parameter that can be used to retrieve a copy of the document. OAuth parameters registry contains registration of authorization endpoint request or response, token endpoint request or response by the experts with the required specification. The registration request will be sent to the experts and if they are satisfied with registration, then they will publish the specification. The registration template contains specifications such as Type Name, Change Controller and Specification Document as defined in the above OAuth Access Token Types Registry section, except the following specification − Parameter Usage Location − It specifies the location of the parameter such as authorization request or response, token request or response. The following table shows OAuth parameters registry containing the initial contents − client_id authorization request, token request client_secret token request response_type authorization_request redirect_uri authorization request, authorization scope authorization request or response, token request or response state authorization request or response code token request, authorization response error_description authorization response, token response error_uri authorization response, token response grant_type token request access_token authorization response, token response token_type authorization response, token response expires_in authorization response, token response username token request password token request refresh_token token request, token response This can be used to define OAuth Authorization Endpoint Response Type Registry. The response types are registered by experts with the required specification and if they are satisfied with the registration, only then they will publish the specification. The registration request will be sent to the @ietf.org for reviewing. The experts will either reject or accept the request within 14 days of the request. The registration template contains specifications such as Type Name, Change Controller and Specification Document as defined in the above OAuth Access Token Types Registry section. The following table shows the authorization endpoint response type registry containing the initial contents. This can be used to define OAuth Extensions Error Registry. The error codes along with protocol extensions such as grant types, token types, etc. are registered by experts with the required specification. If they are satisfied with the registration, then they will publish the specification. The registration request will be sent to the @ietf.org for reviewing with subject ("Request for error code: example"). Experts will either reject or accept the request within 14 days of the request. The registration template contains specifications such as Change Controller and Specification Document as defined in the above OAuth Access Token Types Registry section, except the following specifications − Error Name − It is the name of the request. Error Name − It is the name of the request. Error Usage Location − It specifies the location of the error such as authorization code grant error response, implicit grant response or token error response, etc, which specifies where the error can be used. Error Usage Location − It specifies the location of the error such as authorization code grant error response, implicit grant response or token error response, etc, which specifies where the error can be used. Related Protocol Extension − You can use protocol extensions such as extension grant type, access token type, extension parameter, etc. Related Protocol Extension − You can use protocol extensions such as extension grant type, access token type, extension parameter, etc. Print Add Notes Bookmark this page
[ { "code": null, "e": 2114, "s": 1785, "text": "OAuth is an open authorization protocol, which allows accessing the resources of the resource owner by enabling the client applications on HTTP services such as Facebook, GitHub, etc. It allows sharing of resources stored on one site to another site without using their credentials. It uses username and password tokens instead." }, { "code": null, "e": 2197, "s": 2114, "text": "OAuth 2.0 is developed by the IETF OAuth Working Group, published in October 2012." }, { "code": null, "e": 2268, "s": 2197, "text": "You can use OAuth 2.0 to read data of a user from another application." }, { "code": null, "e": 2339, "s": 2268, "text": "You can use OAuth 2.0 to read data of a user from another application." }, { "code": null, "e": 2429, "s": 2339, "text": "It supplies the authorization workflow for web, desktop applications, and mobile devices." }, { "code": null, "e": 2519, "s": 2429, "text": "It supplies the authorization workflow for web, desktop applications, and mobile devices." }, { "code": null, "e": 2621, "s": 2519, "text": "It is a server side web app that uses authorization code and does not interact with user credentials." }, { "code": null, "e": 2723, "s": 2621, "text": "It is a server side web app that uses authorization code and does not interact with user credentials." }, { "code": null, "e": 2825, "s": 2723, "text": "OAuth 2.0 is a simple protocol that allows to access resources of the user without sharing passwords." }, { "code": null, "e": 2927, "s": 2825, "text": "OAuth 2.0 is a simple protocol that allows to access resources of the user without sharing passwords." }, { "code": null, "e": 3074, "s": 2927, "text": "It provides user agent flows for running clients application using a scripting language, such as JavaScript. Typically, a browser is a user agent." }, { "code": null, "e": 3221, "s": 3074, "text": "It provides user agent flows for running clients application using a scripting language, such as JavaScript. Typically, a browser is a user agent." }, { "code": null, "e": 3380, "s": 3221, "text": "It accesses the data using tokens instead of using their credentials and stores data in online file system of the user such as Google Docs or Dropbox account." }, { "code": null, "e": 3539, "s": 3380, "text": "It accesses the data using tokens instead of using their credentials and stores data in online file system of the user such as Google Docs or Dropbox account." }, { "code": null, "e": 3715, "s": 3539, "text": "OAuth 2.0 is a very flexible protocol that relies on SSL (Secure Sockets Layer that ensures data between the web server and browsers remain private) to save user access token." }, { "code": null, "e": 3891, "s": 3715, "text": "OAuth 2.0 is a very flexible protocol that relies on SSL (Secure Sockets Layer that ensures data between the web server and browsers remain private) to save user access token." }, { "code": null, "e": 4013, "s": 3891, "text": "OAuth 2.0 relies on SSL which is used to ensure cryptography industry protocols and are being used to keep the data safe." }, { "code": null, "e": 4135, "s": 4013, "text": "OAuth 2.0 relies on SSL which is used to ensure cryptography industry protocols and are being used to keep the data safe." }, { "code": null, "e": 4234, "s": 4135, "text": "It allows limited access to the user's data and allows accessing when authorization tokens expire." }, { "code": null, "e": 4333, "s": 4234, "text": "It allows limited access to the user's data and allows accessing when authorization tokens expire." }, { "code": null, "e": 4420, "s": 4333, "text": "It has ability to share data for users without having to release personal information." }, { "code": null, "e": 4507, "s": 4420, "text": "It has ability to share data for users without having to release personal information." }, { "code": null, "e": 4571, "s": 4507, "text": "It is easier to implement and provides stronger authentication." }, { "code": null, "e": 4635, "s": 4571, "text": "It is easier to implement and provides stronger authentication." }, { "code": null, "e": 4850, "s": 4635, "text": "If you are adding more extension at the ends in the specification, it will produce a wide range of non-interoperable implementations, which means you have to write separate pieces of code for Facebook, Google, etc." }, { "code": null, "e": 5065, "s": 4850, "text": "If you are adding more extension at the ends in the specification, it will produce a wide range of non-interoperable implementations, which means you have to write separate pieces of code for Facebook, Google, etc." }, { "code": null, "e": 5235, "s": 5065, "text": "If your favorite sites are connected to the central hub and the central account is hacked, then it will lead to serious effects across several sites instead of just one." }, { "code": null, "e": 5405, "s": 5235, "text": "If your favorite sites are connected to the central hub and the central account is hacked, then it will lead to serious effects across several sites instead of just one." }, { "code": null, "e": 5476, "s": 5405, "text": "In this chapter, we will discuss the architectural style of OAuth 2.0." }, { "code": null, "e": 5589, "s": 5476, "text": "Step 1 − First, the user accesses resources using the client application such as Google, Facebook, Twitter, etc." }, { "code": null, "e": 5750, "s": 5589, "text": "Step 2 − Next, the client application will be provided with the client id and client password during registering the redirect URI (Uniform Resource Identifier)." }, { "code": null, "e": 5913, "s": 5750, "text": "Step 3 − The user logs in using the authenticating application. The client ID and client password is unique to the client application on the authorization server." }, { "code": null, "e": 6041, "s": 5913, "text": "Step 4 − The authenticating server redirects the user to a redirect Uniform Resource Identifier (URI) using authorization code." }, { "code": null, "e": 6128, "s": 6041, "text": "Step 5 − The user accesses the page located at redirect URI in the client application." }, { "code": null, "e": 6281, "s": 6128, "text": "Step 6 − The client application will be provided with the authentication code, client id and client password, and send them to the authorization server." }, { "code": null, "e": 6372, "s": 6281, "text": "Step 7 − The authenticating application returns an access token to the client application." }, { "code": null, "e": 6523, "s": 6372, "text": "Step 8 − Once the client application gets an access token, the user starts accessing the resources of the resource owner using the client application." }, { "code": null, "e": 6607, "s": 6523, "text": "OAuth 2.0 has various concepts, which are briefly explained in the following table." }, { "code": null, "e": 6689, "s": 6607, "text": "OAuth provides some additional terms to understand the concepts of authorization." }, { "code": null, "e": 6795, "s": 6689, "text": "Web server delivers the web pages and uses HTTP to serve the files that forms the web pages to the users." }, { "code": null, "e": 6922, "s": 6795, "text": "The user agent application is used by client applications in the user's device, which acts as the scripting language instance." }, { "code": null, "e": 7060, "s": 6922, "text": "Native application can be used as an instance of desktop or mobile phone application, which uses the resource owner password credentials." }, { "code": null, "e": 7259, "s": 7060, "text": "The client credentials can be used as an authorization grant when the client is the resource owner, or when the authorization scope is limited to protected resources under the control of the client." }, { "code": null, "e": 7337, "s": 7259, "text": "The client requests an access token only with the help of client credentials." }, { "code": null, "e": 7415, "s": 7337, "text": "The client requests an access token only with the help of client credentials." }, { "code": null, "e": 7516, "s": 7415, "text": "The client credentials authorization flow is used to acquire access token to authorize API requests." }, { "code": null, "e": 7617, "s": 7516, "text": "The client credentials authorization flow is used to acquire access token to authorize API requests." }, { "code": null, "e": 7777, "s": 7617, "text": "Using client credentials authorization, access token which is acquired, only grants permission for your client application to search and get catalog documents." }, { "code": null, "e": 7937, "s": 7777, "text": "Using client credentials authorization, access token which is acquired, only grants permission for your client application to search and get catalog documents." }, { "code": null, "e": 7995, "s": 7937, "text": "The following figure depicts the Client Credentials Flow." }, { "code": null, "e": 8070, "s": 7995, "text": "The flow illustrated in the above figure consists of the following steps −" }, { "code": null, "e": 8196, "s": 8070, "text": "Step 1 − The client authenticates with the authorization server and makes a request for access token from the token endpoint." }, { "code": null, "e": 8311, "s": 8196, "text": "Step 2 − The authorization server authenticates the client and provides access token if it's valid and authorized." }, { "code": null, "e": 8373, "s": 8311, "text": "The following table lists the concepts of Client Credentials." }, { "code": null, "e": 8540, "s": 8373, "text": "The authorization end point is typically URI on the authorization server in which the resource owner logs in and permits to access the data to the client application." }, { "code": null, "e": 8681, "s": 8540, "text": "The authorization response can be used to get the access token for accessing the owner resources in the system using the authorization code." }, { "code": null, "e": 8807, "s": 8681, "text": "The authorization server responds with a HTTP 400 or 401 (bad request) status codes, if an error occurs during authorization." }, { "code": null, "e": 8986, "s": 8807, "text": "An access token is a string that identifies a user, an application, or a page. The token includes information such as when the token will expire and which app created that token." }, { "code": null, "e": 9067, "s": 8986, "text": "First, it is necessary to acquire OAuth 2.0 client credentials from API console." }, { "code": null, "e": 9148, "s": 9067, "text": "First, it is necessary to acquire OAuth 2.0 client credentials from API console." }, { "code": null, "e": 9229, "s": 9148, "text": "Then, the access token is requested from the authorization server by the client." }, { "code": null, "e": 9310, "s": 9229, "text": "Then, the access token is requested from the authorization server by the client." }, { "code": null, "e": 9408, "s": 9310, "text": "It gets an access token from the response and sends the token to the API that you wish to access." }, { "code": null, "e": 9506, "s": 9408, "text": "It gets an access token from the response and sends the token to the API that you wish to access." }, { "code": null, "e": 9620, "s": 9506, "text": "You must send the user to the authorization endpoint at the beginning. Following is an example of a dummy request" }, { "code": null, "e": 9739, "s": 9620, "text": "https://publicapi.example.com/oauth2/authorize?client_id=your_client_id&redirect_uri=your_url \n &response_type=code\n" }, { "code": null, "e": 9792, "s": 9739, "text": "Following are the parameters and their descriptions." }, { "code": null, "e": 9859, "s": 9792, "text": "client_id − It should be set to the client id of your application." }, { "code": null, "e": 9926, "s": 9859, "text": "client_id − It should be set to the client id of your application." }, { "code": null, "e": 10037, "s": 9926, "text": "redirect_uri − It should be set to the URL. After the request is authorized, the user will be redirected back." }, { "code": null, "e": 10148, "s": 10037, "text": "redirect_uri − It should be set to the URL. After the request is authorized, the user will be redirected back." }, { "code": null, "e": 10395, "s": 10148, "text": "response_type − It can either be a code or a token. The code must be used for server side applications, whereas the token must be used for client side applications. In server side applications, you can make sure that the secrets are saved safely." }, { "code": null, "e": 10642, "s": 10395, "text": "response_type − It can either be a code or a token. The code must be used for server side applications, whereas the token must be used for client side applications. In server side applications, you can make sure that the secrets are saved safely." }, { "code": null, "e": 10700, "s": 10642, "text": "Following table lists the concepts of Client Credentials." }, { "code": null, "e": 10840, "s": 10700, "text": "The authorization code allows accessing the authorization request and grants access to the client application to fetch the owner resources." }, { "code": null, "e": 11003, "s": 10840, "text": "The resource owner password credentials include only one request and one response, and is useful where the resource owner has a good relationship with the client." }, { "code": null, "e": 11143, "s": 11003, "text": "Assertion is a package of information that makes the sharing of identity and security information across various security domains possible." }, { "code": null, "e": 11270, "s": 11143, "text": "The refresh tokens are used to acquire a new access tokens, which carries the information necessary to get a new access token." }, { "code": null, "e": 11348, "s": 11270, "text": "Access token is a type of token that is assigned by the authorization server." }, { "code": null, "e": 11506, "s": 11348, "text": "If the token access request, which is issued by the authorization server is invalid or unauthorized, then the authorization server returns an error response." }, { "code": null, "e": 11693, "s": 11506, "text": "The client provides an access token to the resource server to access protected resources. The resource server must validate and verify that the access token is valid and has not expired." }, { "code": null, "e": 11746, "s": 11693, "text": "There are two standard ways of sending credentials −" }, { "code": null, "e": 11894, "s": 11746, "text": "Bearer Token − The access token can only be placed in POST request body or GET URL parameter as a fallback option in the authorization HTTP header." }, { "code": null, "e": 12042, "s": 11894, "text": "Bearer Token − The access token can only be placed in POST request body or GET URL parameter as a fallback option in the authorization HTTP header." }, { "code": null, "e": 12101, "s": 12042, "text": "They are included in the authorization header as follows −" }, { "code": null, "e": 12138, "s": 12101, "text": "Authorization: Bearer [token-value]\n" }, { "code": null, "e": 12152, "s": 12138, "text": "For Example −" }, { "code": null, "e": 12225, "s": 12152, "text": "GET/resource/1 HTTP /1.1\nHost: example.com\nAuthorization: Bearer abc...\n" }, { "code": null, "e": 12457, "s": 12225, "text": "MAC − A cryptographic Message Authentication Code (MAC) is computed using the elements of the request and is sent to the authorization header. Upon receiving the request, the MAC is then compared and computed by the resource owner." }, { "code": null, "e": 12689, "s": 12457, "text": "MAC − A cryptographic Message Authentication Code (MAC) is computed using the elements of the request and is sent to the authorization header. Upon receiving the request, the MAC is then compared and computed by the resource owner." }, { "code": null, "e": 12761, "s": 12689, "text": "The following table shows the concepts of accessing protected resource." }, { "code": null, "e": 12857, "s": 12761, "text": "It is used to get the authorization code token for accessing the owner resources in the system." }, { "code": null, "e": 13000, "s": 12857, "text": "The resource server includes the \"WWW-Authenticate\" response header field, if the protected resource request contains an invalid access token." }, { "code": null, "e": 13068, "s": 13000, "text": "There are two ways in which the access token types can be defined −" }, { "code": null, "e": 13120, "s": 13068, "text": "By registering in the access token type's registry." }, { "code": null, "e": 13172, "s": 13120, "text": "By registering in the access token type's registry." }, { "code": null, "e": 13246, "s": 13172, "text": "By using a unique absolute URI (Uniform Resource Identifier) as its name." }, { "code": null, "e": 13320, "s": 13246, "text": "By using a unique absolute URI (Uniform Resource Identifier) as its name." }, { "code": null, "e": 13546, "s": 13320, "text": "Parameter names must obey the param-name ABNF (Augmented Backus-Naur Form is a metalanguage based on Backus-Naur Form consisting of its own syntax and derivation rules) and the syntax of parameter values must be well-defined." }, { "code": null, "e": 13617, "s": 13546, "text": "param-name = 1* name-char\nname-char = \"-\" / \".\" / \"_\" / DIGIT / ALPHA\n" }, { "code": null, "e": 13868, "s": 13617, "text": "New authorization grant types can be assigned a distinct absolute URI for use, with the help of \"grant_type\" parameter. The extension grant type must be registered in the OAuth parameters registry, if it requires additional token endpoint parameters." }, { "code": null, "e": 13988, "s": 13868, "text": "response-type = response-name *(SP response-name)\nresponse-name = 1* response-char\nresponse-char = \"_\" / DIGIT / ALPHA\n" }, { "code": null, "e": 14185, "s": 13988, "text": "The response type is compared as space-delimited list of values, if it has one or more space characters where the order of the values does not matter and only one order of value can be registered." }, { "code": null, "e": 14467, "s": 14185, "text": "The extension error codes must be registered, if the extensions they use are either a registered access token, or a registered endpoint parameter. The error code must obey the error ABNF (Augmented Backus-Naur Form) and when possible it should be prefixed by a name identifying it." }, { "code": null, "e": 14531, "s": 14467, "text": "error = 1 * error_char\nerror-char = %x20-21 / %x23-5B / 5D-7E\n" }, { "code": null, "e": 14712, "s": 14531, "text": "IANA stands for Internet Assigned Numbers Authority which provides the information about the registration values related to the Remote Authentication Dial In User Service (RADIUS)." }, { "code": null, "e": 14757, "s": 14712, "text": "IANA includes the following considerations −" }, { "code": null, "e": 15134, "s": 14757, "text": "OAuth access tokens are registered by experts with required specification. If they are satisfied with the registration, only then they will publish the specification. The registration request will be sent to the @ietf.org for reviewing with the subject (\"Request for access token type: example\"). Experts will either reject or accept the request within 14 days of the request." }, { "code": null, "e": 15200, "s": 15134, "text": "The registration template contains the following specifications −" }, { "code": null, "e": 15243, "s": 15200, "text": "Type Name − It is the name of the request." }, { "code": null, "e": 15286, "s": 15243, "text": "Type Name − It is the name of the request." }, { "code": null, "e": 15430, "s": 15286, "text": "Token Endpoint Response Parameters − The additional access token response parameter will be registered separately in OAuth parameters registry." }, { "code": null, "e": 15574, "s": 15430, "text": "Token Endpoint Response Parameters − The additional access token response parameter will be registered separately in OAuth parameters registry." }, { "code": null, "e": 15703, "s": 15574, "text": "HTTP Authentication Scheme − The HTTP authentication scheme can be used to authenticate the resources by using the access token." }, { "code": null, "e": 15832, "s": 15703, "text": "HTTP Authentication Scheme − The HTTP authentication scheme can be used to authenticate the resources by using the access token." }, { "code": null, "e": 15962, "s": 15832, "text": "Change Controller − Give the state name as \"IETF\" for standard track RFCs, and for others, use the name of the responsible party." }, { "code": null, "e": 16092, "s": 15962, "text": "Change Controller − Give the state name as \"IETF\" for standard track RFCs, and for others, use the name of the responsible party." }, { "code": null, "e": 16220, "s": 16092, "text": "Specification Document − The specification document contains the parameter that can be used to retrieve a copy of the document." }, { "code": null, "e": 16348, "s": 16220, "text": "Specification Document − The specification document contains the parameter that can be used to retrieve a copy of the document." }, { "code": null, "e": 16666, "s": 16348, "text": "OAuth parameters registry contains registration of authorization endpoint request or response, token endpoint request or response by the experts with the required specification. The registration request will be sent to the experts and if they are satisfied with registration, then they will publish the specification." }, { "code": null, "e": 16884, "s": 16666, "text": "The registration template contains specifications such as Type Name, Change Controller and Specification Document as defined in the above OAuth Access Token Types Registry section, except the following specification −" }, { "code": null, "e": 17024, "s": 16884, "text": "Parameter Usage Location − It specifies the location of the parameter such as authorization request or response, token request or response." }, { "code": null, "e": 17110, "s": 17024, "text": "The following table shows OAuth parameters registry containing the initial contents −" }, { "code": null, "e": 17120, "s": 17110, "text": "client_id" }, { "code": null, "e": 17157, "s": 17120, "text": "authorization request, token request" }, { "code": null, "e": 17171, "s": 17157, "text": "client_secret" }, { "code": null, "e": 17185, "s": 17171, "text": "token request" }, { "code": null, "e": 17199, "s": 17185, "text": "response_type" }, { "code": null, "e": 17221, "s": 17199, "text": "authorization_request" }, { "code": null, "e": 17234, "s": 17221, "text": "redirect_uri" }, { "code": null, "e": 17271, "s": 17234, "text": "authorization request, authorization" }, { "code": null, "e": 17277, "s": 17271, "text": "scope" }, { "code": null, "e": 17338, "s": 17277, "text": "authorization request or response, token request or response" }, { "code": null, "e": 17344, "s": 17338, "text": "state" }, { "code": null, "e": 17378, "s": 17344, "text": "authorization request or response" }, { "code": null, "e": 17383, "s": 17378, "text": "code" }, { "code": null, "e": 17421, "s": 17383, "text": "token request, authorization response" }, { "code": null, "e": 17439, "s": 17421, "text": "error_description" }, { "code": null, "e": 17478, "s": 17439, "text": "authorization response, token response" }, { "code": null, "e": 17488, "s": 17478, "text": "error_uri" }, { "code": null, "e": 17527, "s": 17488, "text": "authorization response, token response" }, { "code": null, "e": 17538, "s": 17527, "text": "grant_type" }, { "code": null, "e": 17552, "s": 17538, "text": "token request" }, { "code": null, "e": 17565, "s": 17552, "text": "access_token" }, { "code": null, "e": 17604, "s": 17565, "text": "authorization response, token response" }, { "code": null, "e": 17615, "s": 17604, "text": "token_type" }, { "code": null, "e": 17654, "s": 17615, "text": "authorization response, token response" }, { "code": null, "e": 17665, "s": 17654, "text": "expires_in" }, { "code": null, "e": 17704, "s": 17665, "text": "authorization response, token response" }, { "code": null, "e": 17713, "s": 17704, "text": "username" }, { "code": null, "e": 17727, "s": 17713, "text": "token request" }, { "code": null, "e": 17736, "s": 17727, "text": "password" }, { "code": null, "e": 17750, "s": 17736, "text": "token request" }, { "code": null, "e": 17764, "s": 17750, "text": "refresh_token" }, { "code": null, "e": 17794, "s": 17764, "text": "token request, token response" }, { "code": null, "e": 18201, "s": 17794, "text": "This can be used to define OAuth Authorization Endpoint Response Type Registry. The response types are registered by experts with the required specification and if they are satisfied with the registration, only then they will publish the specification. The registration request will be sent to the @ietf.org for reviewing. The experts will either reject or accept the request within 14 days of the request." }, { "code": null, "e": 18382, "s": 18201, "text": "The registration template contains specifications such as Type Name, Change Controller and Specification Document as defined in the above OAuth Access Token Types Registry section." }, { "code": null, "e": 18491, "s": 18382, "text": "The following table shows the authorization endpoint response type registry containing the initial contents." }, { "code": null, "e": 18982, "s": 18491, "text": "This can be used to define OAuth Extensions Error Registry. The error codes along with protocol extensions such as grant types, token types, etc. are registered by experts with the required specification. If they are satisfied with the registration, then they will publish the specification. The registration request will be sent to the @ietf.org for reviewing with subject (\"Request for error code: example\"). Experts will either reject or accept the request within 14 days of the request." }, { "code": null, "e": 19190, "s": 18982, "text": "The registration template contains specifications such as Change Controller and Specification Document as defined in the above OAuth Access Token Types Registry section, except the following specifications −" }, { "code": null, "e": 19234, "s": 19190, "text": "Error Name − It is the name of the request." }, { "code": null, "e": 19278, "s": 19234, "text": "Error Name − It is the name of the request." }, { "code": null, "e": 19488, "s": 19278, "text": "Error Usage Location − It specifies the location of the error such as authorization code grant error response, implicit grant response or token error response, etc, which specifies where the error can be used." }, { "code": null, "e": 19698, "s": 19488, "text": "Error Usage Location − It specifies the location of the error such as authorization code grant error response, implicit grant response or token error response, etc, which specifies where the error can be used." }, { "code": null, "e": 19834, "s": 19698, "text": "Related Protocol Extension − You can use protocol extensions such as extension grant type, access token type, extension parameter, etc." }, { "code": null, "e": 19970, "s": 19834, "text": "Related Protocol Extension − You can use protocol extensions such as extension grant type, access token type, extension parameter, etc." }, { "code": null, "e": 19977, "s": 19970, "text": " Print" }, { "code": null, "e": 19988, "s": 19977, "text": " Add Notes" } ]
How do I get SUM function in MySQL to return '0' if no values are found?
To return Sum as ‘0’ if no values are found, use IFNULL or COALESCE commands. The following is the syntax for IFNULL. SELECT IFNULL(SUM(NULL), 0) AS aliasName; Let us now implement the above syntax in the following query. mysql> SELECT IFNULL(SUM(NULL), 0) AS SUMOFTWO; The following is the output of the above query, which returns 0. +----------+ | SUMOFTWO | +----------+ | 0 | +----------+ 1 row in set (0.00 sec) Here is the syntax for COALESCE. mysql> SELECT COALESCE(SUM(NULL),0) as SUMOFTWO; The following is the output that returns 0 using the SUM() function. +----------+ | SUMOFTWO | +----------+ | 0 | +----------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1140, "s": 1062, "text": "To return Sum as ‘0’ if no values are found, use IFNULL or COALESCE commands." }, { "code": null, "e": 1180, "s": 1140, "text": "The following is the syntax for IFNULL." }, { "code": null, "e": 1223, "s": 1180, "text": "SELECT IFNULL(SUM(NULL), 0) AS aliasName;\n" }, { "code": null, "e": 1285, "s": 1223, "text": "Let us now implement the above syntax in the following query." }, { "code": null, "e": 1333, "s": 1285, "text": "mysql> SELECT IFNULL(SUM(NULL), 0) AS SUMOFTWO;" }, { "code": null, "e": 1398, "s": 1333, "text": "The following is the output of the above query, which returns 0." }, { "code": null, "e": 1488, "s": 1398, "text": "+----------+\n| SUMOFTWO |\n+----------+\n| 0 |\n+----------+\n1 row in set (0.00 sec)\n" }, { "code": null, "e": 1521, "s": 1488, "text": "Here is the syntax for COALESCE." }, { "code": null, "e": 1570, "s": 1521, "text": "mysql> SELECT COALESCE(SUM(NULL),0) as SUMOFTWO;" }, { "code": null, "e": 1639, "s": 1570, "text": "The following is the output that returns 0 using the SUM() function." }, { "code": null, "e": 1729, "s": 1639, "text": "+----------+\n| SUMOFTWO |\n+----------+\n| 0 |\n+----------+\n1 row in set (0.00 sec)\n" } ]
System() Function in C/C++
Given the task is to show the working of system() in C/C++. The system() function is a part of the C/C++ standard library. It is used to pass the commands that can be executed in the command processor or the terminal of the operating system, and finally returns the command after it has been completed. <stdlib.h> or <cstdlib> should be included to call this function. The syntax is as follows − int system(char command) This function returns zero if the command is executed without any errors. Input: system(“date”) Output: The current date is: Fri 12/27/2019 Explanation − The following example shows how we can use the system function to display the current date. The output is shown inside the command processor of the operating system. This shows how we can use the system() function to execute terminal commands or the command that are used inside the command processor. Input: system(“color a”) Output: The following example shows how we can use the system() function by simply passing a string into it that contains the command to be executed. Here we have given the “color a” command that is used to change the color of the text in the command processor and here it works properly. Approach used in the below program as follows − First create a variable of type char and give it some suitable size, let’s say cmd[10], so that this string can be used for storing commands. Then use the strcpy() function to store the desired command into the string that we created before. (Do include the <string.h> header file in order to use the strcpy() function) Now pass the string that is storing the command, into the system function. Start Step 1-> In function main() Declare a char cmd[10] Call function strcpy(cmd, “dir”) Call function system(cmd) Stop #include <iostream> #include<stdlib.h> #include<string.h> using namespace std; int main() { char cmd[10]; strcpy(cmd,"dir"); system(cmd); return0; } If we run the above code it will generate the following output − 12/25/2019 10:04 AM <DIR> . 12/25/2019 06:33 AM <DIR> .. 12/24/2019 09:56 AM <DIR> bin 12/25/2019 10:04 AM 183 main.cpp 12/25/2019 10:04 AM 1,564,278 main.exe 12/25/2019 06:33 AM 1,046 main.o 12/24/2019 06:33 AM <DIR> obj 12/24/2019 06:33 AM 1,062 Test.cbp 12/24/2019 06:36 AM 358 Test.layout 5 File<s> 1,566,927 bytes 4 Dir<s> 169,866,692,120 bytes free Here we have given the system function “dir” command as the input, so in return it will show us all the directories present in the computer as the output. The following method can be used to check if command processor is available in the operating system or not − This can be done by passing a Null pointer into the system() function. If the system returns a non-zero value, then it means that command processor is available. Else if the system returns zero, then it means that command processor does not exist and the system() function cannot be called. #include <iostream> #include<stdlib.h> using namespace std; int main() { if(system(Null)) cout<<”Command Processor is present”; else cout<<”Command processor is not present”; return 0; }
[ { "code": null, "e": 1122, "s": 1062, "text": "Given the task is to show the working of system() in C/C++." }, { "code": null, "e": 1365, "s": 1122, "text": "The system() function is a part of the C/C++ standard library. It is used to pass the commands that can be executed in the command processor or the terminal of the operating system, and finally returns the command after it has been completed." }, { "code": null, "e": 1431, "s": 1365, "text": "<stdlib.h> or <cstdlib> should be included to call this function." }, { "code": null, "e": 1458, "s": 1431, "text": "The syntax is as follows −" }, { "code": null, "e": 1483, "s": 1458, "text": "int system(char command)" }, { "code": null, "e": 1557, "s": 1483, "text": "This function returns zero if the command is executed without any errors." }, { "code": null, "e": 1623, "s": 1557, "text": "Input: system(“date”)\nOutput: The current date is: Fri 12/27/2019" }, { "code": null, "e": 1939, "s": 1623, "text": "Explanation − The following example shows how we can use the system function to display the current date. The output is shown inside the command processor of the operating system. This shows how we can use the system() function to execute terminal commands or the command that are used inside the command processor." }, { "code": null, "e": 1972, "s": 1939, "text": "Input: system(“color a”)\nOutput:" }, { "code": null, "e": 2253, "s": 1972, "text": "The following example shows how we can use the system() function by simply passing a string into it that contains the command to be executed. Here we have given the “color a” command that is used to change the color of the text in the command processor and here it works properly." }, { "code": null, "e": 2301, "s": 2253, "text": "Approach used in the below program as follows −" }, { "code": null, "e": 2443, "s": 2301, "text": "First create a variable of type char and give it some suitable size, let’s say cmd[10], so that this string can be used for storing commands." }, { "code": null, "e": 2621, "s": 2443, "text": "Then use the strcpy() function to store the desired command into the string that we created before. (Do include the <string.h> header file in order to use the strcpy() function)" }, { "code": null, "e": 2696, "s": 2621, "text": "Now pass the string that is storing the command, into the system function." }, { "code": null, "e": 2826, "s": 2696, "text": "Start\nStep 1-> In function main()\n Declare a char cmd[10]\n Call function strcpy(cmd, “dir”)\n Call function system(cmd)\nStop" }, { "code": null, "e": 2987, "s": 2826, "text": "#include <iostream>\n#include<stdlib.h>\n#include<string.h>\nusing namespace std;\nint main() {\n char cmd[10];\n strcpy(cmd,\"dir\");\n system(cmd);\n return0;\n}" }, { "code": null, "e": 3052, "s": 2987, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 3407, "s": 3052, "text": "12/25/2019 10:04 AM <DIR> .\n12/25/2019 06:33 AM <DIR> ..\n12/24/2019 09:56 AM <DIR> bin\n12/25/2019 10:04 AM 183 main.cpp\n12/25/2019 10:04 AM 1,564,278 main.exe\n12/25/2019 06:33 AM 1,046 main.o\n12/24/2019 06:33 AM <DIR> obj\n12/24/2019 06:33 AM 1,062 Test.cbp\n12/24/2019 06:36 AM 358 Test.layout\n5 File<s> 1,566,927 bytes\n4 Dir<s> 169,866,692,120 bytes free" }, { "code": null, "e": 3562, "s": 3407, "text": "Here we have given the system function “dir” command as the input, so in return it will show us all the directories present in the computer as the output." }, { "code": null, "e": 3671, "s": 3562, "text": "The following method can be used to check if command processor is available in the operating system or not −" }, { "code": null, "e": 3833, "s": 3671, "text": "This can be done by passing a Null pointer into the system() function. If the system returns a non-zero value, then it means that command processor is available." }, { "code": null, "e": 3962, "s": 3833, "text": "Else if the system returns zero, then it means that command processor does not exist and the system() function cannot be called." }, { "code": null, "e": 4170, "s": 3962, "text": "#include <iostream>\n#include<stdlib.h>\nusing namespace std;\nint main() {\n if(system(Null))\n cout<<”Command Processor is present”;\n else\n cout<<”Command processor is not present”;\n return 0;\n}" } ]
LISP - Set
Common Lisp does not provide a set data type. However, it provides number of functions that allows set operations to be performed on a list. You can add, remove, and search for items in a list, based on various criteria. You can also perform various set operations like: union, intersection, and set difference. Sets, like lists are generally implemented in terms of cons cells. However, for this very reason, the set operations get less and less efficient the bigger the sets get. The adjoin function allows you to build up a set. It takes an item and a list representing a set and returns a list representing the set containing the item and all the items in the original set. The adjoin function first looks for the item in the given list, if it is found, then it returns the original list; otherwise it creates a new cons cell with its car as the item and cdr pointing to the original list and returns this new list. The adjoin function also takes :key and :test keyword arguments. These arguments are used for checking whether the item is present in the original list. Since, the adjoin function does not modify the original list, to make a change in the list itself, you must either assign the value returned by adjoin to the original list or, you may use the macro pushnew to add an item to the set. Create a new source code file named main.lisp and type the following code in it. ; creating myset as an empty list (defparameter *myset* ()) (adjoin 1 *myset*) (adjoin 2 *myset*) ; adjoin did not change the original set ;so it remains same (write *myset*) (terpri) (setf *myset* (adjoin 1 *myset*)) (setf *myset* (adjoin 2 *myset*)) ;now the original set is changed (write *myset*) (terpri) ;adding an existing value (pushnew 2 *myset*) ;no duplicate allowed (write *myset*) (terpri) ;pushing a new value (pushnew 3 *myset*) (write *myset*) (terpri) When you execute the code, it returns the following result − NIL (2 1) (2 1) (3 2 1) The member group of functions allows you to check whether an element is member of a set or not. The following are the syntaxes of these functions − member item list &key :test :test-not :key member-if predicate list &key :key member-if-not predicate list &key :key These functions search the given list for a given item that satisfies the test. If no such item is found, then the functions returns nil. Otherwise, the tail of the list with the element as the first element is returned. The search is conducted at the top level only. These functions could be used as predicates. Create a new source code file named main.lisp and type the following code in it. (write (member 'zara '(ayan abdul zara riyan nuha))) (terpri) (write (member-if #'evenp '(3 7 2 5/3 'a))) (terpri) (write (member-if-not #'numberp '(3 7 2 5/3 'a 'b 'c))) When you execute the code, it returns the following result − (ZARA RIYAN NUHA) (2 5/3 'A) ('A 'B 'C) The union group of functions allows you to perform set union on two lists provided as arguments to these functions on the basis of a test. The following are the syntaxes of these functions − union list1 list2 &key :test :test-not :key nunion list1 list2 &key :test :test-not :key The union function takes two lists and returns a new list containing all the elements present in either of the lists. If there are duplications, then only one copy of the member is retained in the returned list. The nunion function performs the same operation but may destroy the argument lists. Create a new source code file named main.lisp and type the following code in it. (setq set1 (union '(a b c) '(c d e))) (setq set2 (union '(#(a b) #(5 6 7) #(f h)) '(#(5 6 7) #(a b) #(g h)) :test-not #'mismatch) ) (setq set3 (union '(#(a b) #(5 6 7) #(f h)) '(#(5 6 7) #(a b) #(g h))) ) (write set1) (terpri) (write set2) (terpri) (write set3) When you execute the code, it returns the following result − (A B C D E) (#(F H) #(5 6 7) #(A B) #(G H)) (#(A B) #(5 6 7) #(F H) #(5 6 7) #(A B) #(G H)) The union function does not work as expected without :test-not #'mismatch arguments for a list of three vectors. This is because, the lists are made of cons cells and although the values look same to us apparently, the cdr part of cells does not match, so they are not exactly same to LISP interpreter/compiler. This is the reason; implementing big sets are not advised using lists. It works fine for small sets though. The intersection group of functions allows you to perform intersection on two lists provided as arguments to these functions on the basis of a test. The following are the syntaxes of these functions − intersection list1 list2 &key :test :test-not :key nintersection list1 list2 &key :test :test-not :key These functions take two lists and return a new list containing all the elements present in both argument lists. If either list has duplicate entries, the redundant entries may or may not appear in the result. Create a new source code file named main.lisp and type the following code in it. (setq set1 (intersection '(a b c) '(c d e))) (setq set2 (intersection '(#(a b) #(5 6 7) #(f h)) '(#(5 6 7) #(a b) #(g h)) :test-not #'mismatch) ) (setq set3 (intersection '(#(a b) #(5 6 7) #(f h)) '(#(5 6 7) #(a b) #(g h))) ) (write set1) (terpri) (write set2) (terpri) (write set3) When you execute the code, it returns the following result − (C) (#(A B) #(5 6 7)) NIL The intersection function is the destructive version of intersection, i.e., it may destroy the original lists. The set-difference group of functions allows you to perform set difference on two lists provided as arguments to these functions on the basis of a test. The following are the syntaxes of these functions − set-difference list1 list2 &key :test :test-not :key nset-difference list1 list2 &key :test :test-not :key The set-difference function returns a list of elements of the first list that do not appear in the second list. Create a new source code file named main.lisp and type the following code in it. (setq set1 (set-difference '(a b c) '(c d e))) (setq set2 (set-difference '(#(a b) #(5 6 7) #(f h)) '(#(5 6 7) #(a b) #(g h)) :test-not #'mismatch) ) (setq set3 (set-difference '(#(a b) #(5 6 7) #(f h)) '(#(5 6 7) #(a b) #(g h))) ) (write set1) (terpri) (write set2) (terpri) (write set3) When you execute the code, it returns the following result − (A B) (#(F H)) (#(A B) #(5 6 7) #(F H)) 79 Lectures 7 hours Arnold Higuit Print Add Notes Bookmark this page
[ { "code": null, "e": 2201, "s": 2060, "text": "Common Lisp does not provide a set data type. However, it provides number of functions that allows set operations to be performed on a list." }, { "code": null, "e": 2372, "s": 2201, "text": "You can add, remove, and search for items in a list, based on various criteria. You can also perform various set operations like: union, intersection, and set difference." }, { "code": null, "e": 2542, "s": 2372, "text": "Sets, like lists are generally implemented in terms of cons cells. However, for this very reason, the set operations get less and less efficient the bigger the sets get." }, { "code": null, "e": 2738, "s": 2542, "text": "The adjoin function allows you to build up a set. It takes an item and a list representing a set and returns a list representing the set containing the item and all the items in the original set." }, { "code": null, "e": 2980, "s": 2738, "text": "The adjoin function first looks for the item in the given list, if it is found, then it returns the original list; otherwise it creates a new cons cell with its car as the item and cdr pointing to the original list and returns this new list." }, { "code": null, "e": 3133, "s": 2980, "text": "The adjoin function also takes :key and :test keyword arguments. These arguments are used for checking whether the item is present in the original list." }, { "code": null, "e": 3366, "s": 3133, "text": "Since, the adjoin function does not modify the original list, to make a change in the list itself, you must either assign the value returned by adjoin to the original list or, you may use the macro pushnew to add an item to the set." }, { "code": null, "e": 3447, "s": 3366, "text": "Create a new source code file named main.lisp and type the following code in it." }, { "code": null, "e": 3921, "s": 3447, "text": "; creating myset as an empty list\n(defparameter *myset* ())\n(adjoin 1 *myset*)\n(adjoin 2 *myset*)\n\n; adjoin did not change the original set\n;so it remains same\n(write *myset*)\n(terpri)\n(setf *myset* (adjoin 1 *myset*))\n(setf *myset* (adjoin 2 *myset*))\n\n;now the original set is changed\n(write *myset*)\n(terpri)\n\n;adding an existing value\n(pushnew 2 *myset*)\n\n;no duplicate allowed\n(write *myset*)\n(terpri)\n\n;pushing a new value\n(pushnew 3 *myset*)\n(write *myset*)\n(terpri)" }, { "code": null, "e": 3982, "s": 3921, "text": "When you execute the code, it returns the following result −" }, { "code": null, "e": 4007, "s": 3982, "text": "NIL\n(2 1)\n(2 1)\n(3 2 1)\n" }, { "code": null, "e": 4103, "s": 4007, "text": "The member group of functions allows you to check whether an element is member of a set or not." }, { "code": null, "e": 4155, "s": 4103, "text": "The following are the syntaxes of these functions −" }, { "code": null, "e": 4275, "s": 4155, "text": "member item list &key :test :test-not :key \nmember-if predicate list &key :key \nmember-if-not predicate list &key :key\n" }, { "code": null, "e": 4496, "s": 4275, "text": "These functions search the given list for a given item that satisfies the test. If no such item is found, then the functions returns nil. Otherwise, the tail of the list with the element as the first element is returned." }, { "code": null, "e": 4543, "s": 4496, "text": "The search is conducted at the top level only." }, { "code": null, "e": 4588, "s": 4543, "text": "These functions could be used as predicates." }, { "code": null, "e": 4669, "s": 4588, "text": "Create a new source code file named main.lisp and type the following code in it." }, { "code": null, "e": 4840, "s": 4669, "text": "(write (member 'zara '(ayan abdul zara riyan nuha)))\n(terpri)\n(write (member-if #'evenp '(3 7 2 5/3 'a)))\n(terpri)\n(write (member-if-not #'numberp '(3 7 2 5/3 'a 'b 'c)))" }, { "code": null, "e": 4901, "s": 4840, "text": "When you execute the code, it returns the following result −" }, { "code": null, "e": 4942, "s": 4901, "text": "(ZARA RIYAN NUHA)\n(2 5/3 'A)\n('A 'B 'C)\n" }, { "code": null, "e": 5081, "s": 4942, "text": "The union group of functions allows you to perform set union on two lists provided as arguments to these functions on the basis of a test." }, { "code": null, "e": 5133, "s": 5081, "text": "The following are the syntaxes of these functions −" }, { "code": null, "e": 5224, "s": 5133, "text": "union list1 list2 &key :test :test-not :key \nnunion list1 list2 &key :test :test-not :key\n" }, { "code": null, "e": 5436, "s": 5224, "text": "The union function takes two lists and returns a new list containing all the elements present in either of the lists. If there are duplications, then only one copy of the member is retained in the returned list." }, { "code": null, "e": 5520, "s": 5436, "text": "The nunion function performs the same operation but may destroy the argument lists." }, { "code": null, "e": 5601, "s": 5520, "text": "Create a new source code file named main.lisp and type the following code in it." }, { "code": null, "e": 5879, "s": 5601, "text": "(setq set1 (union '(a b c) '(c d e)))\n(setq set2 (union '(#(a b) #(5 6 7) #(f h)) \n '(#(5 6 7) #(a b) #(g h)) :test-not #'mismatch)\n)\n \n(setq set3 (union '(#(a b) #(5 6 7) #(f h)) \n '(#(5 6 7) #(a b) #(g h)))\n)\n(write set1)\n(terpri)\n(write set2)\n(terpri)\n(write set3)" }, { "code": null, "e": 5940, "s": 5879, "text": "When you execute the code, it returns the following result −" }, { "code": null, "e": 6033, "s": 5940, "text": "(A B C D E)\n(#(F H) #(5 6 7) #(A B) #(G H))\n(#(A B) #(5 6 7) #(F H) #(5 6 7) #(A B) #(G H))\n" }, { "code": null, "e": 6453, "s": 6033, "text": "The union function does not work as expected without :test-not #'mismatch arguments for a list of three vectors. This is because, the lists are made of cons cells and although the values look same to us apparently, the cdr part of cells does not match, so they are not exactly same to LISP interpreter/compiler. This is the reason; implementing big sets are not advised using lists. It works fine for small sets though." }, { "code": null, "e": 6602, "s": 6453, "text": "The intersection group of functions allows you to perform intersection on two lists provided as arguments to these functions on the basis of a test." }, { "code": null, "e": 6654, "s": 6602, "text": "The following are the syntaxes of these functions −" }, { "code": null, "e": 6759, "s": 6654, "text": "intersection list1 list2 &key :test :test-not :key \nnintersection list1 list2 &key :test :test-not :key\n" }, { "code": null, "e": 6969, "s": 6759, "text": "These functions take two lists and return a new list containing all the elements present in both argument lists. If either list has duplicate entries, the redundant entries may or may not appear in the result." }, { "code": null, "e": 7050, "s": 6969, "text": "Create a new source code file named main.lisp and type the following code in it." }, { "code": null, "e": 7349, "s": 7050, "text": "(setq set1 (intersection '(a b c) '(c d e)))\n(setq set2 (intersection '(#(a b) #(5 6 7) #(f h)) \n '(#(5 6 7) #(a b) #(g h)) :test-not #'mismatch)\n)\n \n(setq set3 (intersection '(#(a b) #(5 6 7) #(f h)) \n '(#(5 6 7) #(a b) #(g h)))\n)\n(write set1)\n(terpri)\n(write set2)\n(terpri)\n(write set3)" }, { "code": null, "e": 7410, "s": 7349, "text": "When you execute the code, it returns the following result −" }, { "code": null, "e": 7437, "s": 7410, "text": "(C)\n(#(A B) #(5 6 7))\nNIL\n" }, { "code": null, "e": 7548, "s": 7437, "text": "The intersection function is the destructive version of intersection, i.e., it may destroy the original lists." }, { "code": null, "e": 7701, "s": 7548, "text": "The set-difference group of functions allows you to perform set difference on two lists provided as arguments to these functions on the basis of a test." }, { "code": null, "e": 7753, "s": 7701, "text": "The following are the syntaxes of these functions −" }, { "code": null, "e": 7862, "s": 7753, "text": "set-difference list1 list2 &key :test :test-not :key \nnset-difference list1 list2 &key :test :test-not :key\n" }, { "code": null, "e": 7974, "s": 7862, "text": "The set-difference function returns a list of elements of the first list that do not appear in the second list." }, { "code": null, "e": 8055, "s": 7974, "text": "Create a new source code file named main.lisp and type the following code in it." }, { "code": null, "e": 8352, "s": 8055, "text": "(setq set1 (set-difference '(a b c) '(c d e)))\n(setq set2 (set-difference '(#(a b) #(5 6 7) #(f h)) \n '(#(5 6 7) #(a b) #(g h)) :test-not #'mismatch)\n)\n(setq set3 (set-difference '(#(a b) #(5 6 7) #(f h)) \n '(#(5 6 7) #(a b) #(g h)))\n)\n(write set1)\n(terpri)\n(write set2)\n(terpri)\n(write set3)" }, { "code": null, "e": 8413, "s": 8352, "text": "When you execute the code, it returns the following result −" }, { "code": null, "e": 8454, "s": 8413, "text": "(A B)\n(#(F H))\n(#(A B) #(5 6 7) #(F H))\n" }, { "code": null, "e": 8487, "s": 8454, "text": "\n 79 Lectures \n 7 hours \n" }, { "code": null, "e": 8502, "s": 8487, "text": " Arnold Higuit" }, { "code": null, "e": 8509, "s": 8502, "text": " Print" }, { "code": null, "e": 8520, "s": 8509, "text": " Add Notes" } ]
Change a Binary Tree so that every node stores sum of all nodes in left subtree - GeeksforGeeks
28 Feb, 2022 Given a Binary Tree, change the value in each node to sum of all the values in the nodes in the left subtree including its own.Examples: Input : 1 / \ 2 3 Output : 3 / \ 2 3 Input 1 / \ 2 3 / \ \ 4 5 6 Output: 12 / \ 6 3 / \ \ 4 5 6 We strongly recommend you to minimize your browser and try this yourself first.The idea is to traverse the given tree in bottom up manner. For every node, recursively compute sum of nodes in left and right subtrees. Add sum of nodes in left subtree to current node and return sum of nodes under current subtree.Below is the implementation of above idea. C++ C Java Python3 C# Javascript // C++ program to store sum of nodes// in left subtree in every node#include<bits/stdc++.h> using namespace std; // A tree nodeclass node{ public: int data; node* left, *right; /* Constructor that allocates a new node with the given data and NULL left and right pointers. */ node(int data) { this->data = data; this->left = NULL; this->right = NULL; }}; // Function to modify a Binary Tree// so that every node stores sum of// values in its left child including// its own valueint updatetree(node *root){ // Base cases if (!root) return 0; if (root->left == NULL && root->right == NULL) return root->data; // Update left and right subtrees int leftsum = updatetree(root->left); int rightsum = updatetree(root->right); // Add leftsum to current node root->data += leftsum; // Return sum of values under root return root->data + rightsum;} // Utility function to do inorder traversalvoid inorder(node* node){ if (node == NULL) return; inorder(node->left); cout<<node->data<<" "; inorder(node->right);} // Driver codeint main(){ /* Let us construct below tree 1 / \ 2 3 / \ \ 4 5 6 */ struct node *root = new node(1); root->left = new node(2); root->right = new node(3); root->left->left = new node(4); root->left->right = new node(5); root->right->right = new node(6); updatetree(root); cout << "Inorder traversal of the modified tree is: \n"; inorder(root); return 0;} // This code is contributed by rathbhupendra // C program to store sum of nodes in left subtree in every// node#include<bits/stdc++.h>using namespace std; // A tree nodestruct node{ int data; struct node* left, *right;}; // Function to modify a Binary Tree so that every node// stores sum of values in its left child including its// own valueint updatetree(node *root){ // Base cases if (!root) return 0; if (root->left == NULL && root->right == NULL) return root->data; // Update left and right subtrees int leftsum = updatetree(root->left); int rightsum = updatetree(root->right); // Add leftsum to current node root->data += leftsum; // Return sum of values under root return root->data + rightsum;} // Utility function to do inorder traversalvoid inorder(struct node* node){ if (node == NULL) return; inorder(node->left); printf("%d ", node->data); inorder(node->right);} // Utility function to create a new nodestruct node* newNode(int data){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} // Driver programint main(){ /* Let us construct below tree 1 / \ 2 3 / \ \ 4 5 6 */ struct node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->right = newNode(6); updatetree(root); cout << "Inorder traversal of the modified tree is \n"; inorder(root); return 0;} // Java program to store sum of nodes in left subtree in every// nodeclass GfG { // A tree nodestatic class node{ int data; node left, right;} // Function to modify a Binary Tree so that every node// stores sum of values in its left child including its// own valuestatic int updatetree(node root){ // Base cases if (root == null) return 0; if (root.left == null && root.right == null) return root.data; // Update left and right subtrees int leftsum = updatetree(root.left); int rightsum = updatetree(root.right); // Add leftsum to current node root.data += leftsum; // Return sum of values under root return root.data + rightsum;} // Utility function to do inorder traversalstatic void inorder(node node){ if (node == null) return; inorder(node.left); System.out.print(node.data + " "); inorder(node.right);} // Utility function to create a new nodestatic node newNode(int data){ node node = new node(); node.data = data; node.left = null; node.right = null; return(node);} // Driver programpublic static void main(String[] args){ /* Let us construct below tree 1 / \ 2 3 / \ \ 4 5 6 */ node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.right = newNode(6); updatetree(root); System.out.println("Inorder traversal of the modified tree is"); inorder(root);}} # Python3 program to store sum of nodes# in left subtree in every node # Binary Tree Node # utility that allocates a new Node# with the given keyclass newNode: # Construct to create a new node def __init__(self, key): self.data = key self.left = None self.right = None # Function to modify a Binary Tree so# that every node stores sum of values# in its left child including its own valuedef updatetree(root): # Base cases if (not root): return 0 if (root.left == None and root.right == None) : return root.data # Update left and right subtrees leftsum = updatetree(root.left) rightsum = updatetree(root.right) # Add leftsum to current node root.data += leftsum # Return sum of values under root return root.data + rightsum # Utility function to do inorder traversaldef inorder(node) : if (node == None) : return inorder(node.left) print(node.data, end = " ") inorder(node.right) # Driver Codeif __name__ == '__main__': """ Let us construct below tree 1 / \ 2 3 / \ \ 4 5 6 """ root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.right.right = newNode(6) updatetree(root) print("Inorder traversal of the modified tree is") inorder(root) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10) // C# program to store sum of nodes in left // subtree in every nodeusing System; class GfG{ // A tree nodeclass node{ public int data; public node left, right;} // Function to modify a Binary Tree so// that every node stores sum of values// in its left child including its own valuestatic int updatetree(node root){ // Base cases if (root == null) return 0; if (root.left == null && root.right == null) return root.data; // Update left and right subtrees int leftsum = updatetree(root.left); int rightsum = updatetree(root.right); // Add leftsum to current node root.data += leftsum; // Return sum of values under root return root.data + rightsum;} // Utility function to do inorder traversalstatic void inorder(node node){ if (node == null) return; inorder(node.left); Console.Write(node.data + " "); inorder(node.right);} // Utility function to create a new nodestatic node newNode(int data){ node node = new node(); node.data = data; node.left = null; node.right = null; return(node);} // Driver codepublic static void Main(){ /* Let us construct below tree 1 / \ 2 3 / \ \ 4 5 6 */ node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.right = newNode(6); updatetree(root); Console.WriteLine("Inorder traversal of the modified tree is"); inorder(root);}} /* This code is contributed by Rajput-Ji*/ <script> // Javascript program to store sum of nodes in left // subtree in every node // A tree nodeclass node{ constructor() { this.data = 0; this.left = null; this.right = null; }} // Function to modify a Binary Tree so// that every node stores sum of values// in its left child including its own valuefunction updatetree(root){ // Base cases if (root == null) return 0; if (root.left == null && root.right == null) return root.data; // Update left and right subtrees var leftsum = updatetree(root.left); var rightsum = updatetree(root.right); // Add leftsum to current node root.data += leftsum; // Return sum of values under root return root.data + rightsum;} // Utility function to do inorder traversalfunction inorder(node){ if (node == null) return; inorder(node.left); document.write(node.data + " "); inorder(node.right);} // Utility function to create a new nodefunction newNode(data){ var nod = new node(); nod.data = data; nod.left = null; nod.right = null; return(nod);} // Driver code/* Let us construct below tree 1 / \ 2 3 / \ \ 4 5 6 */var root = newNode(1);root.left = newNode(2);root.right = newNode(3);root.left.left = newNode(4);root.left.right = newNode(5);root.right.right = newNode(6);updatetree(root);document.write("Inorder traversal of the modified tree is<br>");inorder(root); // This code is contributed by rrrtnx.</script> Output: Inorder traversal of the modified tree is 4 6 5 12 3 6 Time Complexity: O(n) https://www.youtube.com/watch?v=EkmG -FKRjBQ Thanks to Gaurav Ahrirwar for suggesting this solution.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above prerna saini Rajput-Ji SHUBHAMSINGH10 rathbhupendra rrrtnx surinderdawra388 Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal AVL Tree | Set 1 (Insertion) Inorder Tree Traversal without Recursion Binary Tree | Set 3 (Types of Binary Tree) Write a Program to Find the Maximum Depth or Height of a Tree Binary Tree | Set 2 (Properties) A program to check if a binary tree is BST or not
[ { "code": null, "e": 35848, "s": 35820, "text": "\n28 Feb, 2022" }, { "code": null, "e": 35986, "s": 35848, "text": "Given a Binary Tree, change the value in each node to sum of all the values in the nodes in the left subtree including its own.Examples: " }, { "code": null, "e": 36176, "s": 35986, "text": "Input : \n 1\n / \\\n 2 3\n\nOutput :\n 3\n / \\\n 2 3\n\n\nInput\n 1\n / \\\n 2 3\n / \\ \\\n 4 5 6\nOutput:\n 12\n / \\\n 6 3\n / \\ \\\n 4 5 6" }, { "code": null, "e": 36532, "s": 36176, "text": "We strongly recommend you to minimize your browser and try this yourself first.The idea is to traverse the given tree in bottom up manner. For every node, recursively compute sum of nodes in left and right subtrees. Add sum of nodes in left subtree to current node and return sum of nodes under current subtree.Below is the implementation of above idea. " }, { "code": null, "e": 36536, "s": 36532, "text": "C++" }, { "code": null, "e": 36538, "s": 36536, "text": "C" }, { "code": null, "e": 36543, "s": 36538, "text": "Java" }, { "code": null, "e": 36551, "s": 36543, "text": "Python3" }, { "code": null, "e": 36554, "s": 36551, "text": "C#" }, { "code": null, "e": 36565, "s": 36554, "text": "Javascript" }, { "code": "// C++ program to store sum of nodes// in left subtree in every node#include<bits/stdc++.h> using namespace std; // A tree nodeclass node{ public: int data; node* left, *right; /* Constructor that allocates a new node with the given data and NULL left and right pointers. */ node(int data) { this->data = data; this->left = NULL; this->right = NULL; }}; // Function to modify a Binary Tree// so that every node stores sum of// values in its left child including// its own valueint updatetree(node *root){ // Base cases if (!root) return 0; if (root->left == NULL && root->right == NULL) return root->data; // Update left and right subtrees int leftsum = updatetree(root->left); int rightsum = updatetree(root->right); // Add leftsum to current node root->data += leftsum; // Return sum of values under root return root->data + rightsum;} // Utility function to do inorder traversalvoid inorder(node* node){ if (node == NULL) return; inorder(node->left); cout<<node->data<<\" \"; inorder(node->right);} // Driver codeint main(){ /* Let us construct below tree 1 / \\ 2 3 / \\ \\ 4 5 6 */ struct node *root = new node(1); root->left = new node(2); root->right = new node(3); root->left->left = new node(4); root->left->right = new node(5); root->right->right = new node(6); updatetree(root); cout << \"Inorder traversal of the modified tree is: \\n\"; inorder(root); return 0;} // This code is contributed by rathbhupendra", "e": 38192, "s": 36565, "text": null }, { "code": "// C program to store sum of nodes in left subtree in every// node#include<bits/stdc++.h>using namespace std; // A tree nodestruct node{ int data; struct node* left, *right;}; // Function to modify a Binary Tree so that every node// stores sum of values in its left child including its// own valueint updatetree(node *root){ // Base cases if (!root) return 0; if (root->left == NULL && root->right == NULL) return root->data; // Update left and right subtrees int leftsum = updatetree(root->left); int rightsum = updatetree(root->right); // Add leftsum to current node root->data += leftsum; // Return sum of values under root return root->data + rightsum;} // Utility function to do inorder traversalvoid inorder(struct node* node){ if (node == NULL) return; inorder(node->left); printf(\"%d \", node->data); inorder(node->right);} // Utility function to create a new nodestruct node* newNode(int data){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} // Driver programint main(){ /* Let us construct below tree 1 / \\ 2 3 / \\ \\ 4 5 6 */ struct node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->right = newNode(6); updatetree(root); cout << \"Inorder traversal of the modified tree is \\n\"; inorder(root); return 0;}", "e": 39822, "s": 38192, "text": null }, { "code": "// Java program to store sum of nodes in left subtree in every// nodeclass GfG { // A tree nodestatic class node{ int data; node left, right;} // Function to modify a Binary Tree so that every node// stores sum of values in its left child including its// own valuestatic int updatetree(node root){ // Base cases if (root == null) return 0; if (root.left == null && root.right == null) return root.data; // Update left and right subtrees int leftsum = updatetree(root.left); int rightsum = updatetree(root.right); // Add leftsum to current node root.data += leftsum; // Return sum of values under root return root.data + rightsum;} // Utility function to do inorder traversalstatic void inorder(node node){ if (node == null) return; inorder(node.left); System.out.print(node.data + \" \"); inorder(node.right);} // Utility function to create a new nodestatic node newNode(int data){ node node = new node(); node.data = data; node.left = null; node.right = null; return(node);} // Driver programpublic static void main(String[] args){ /* Let us construct below tree 1 / \\ 2 3 / \\ \\ 4 5 6 */ node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.right = newNode(6); updatetree(root); System.out.println(\"Inorder traversal of the modified tree is\"); inorder(root);}}", "e": 41367, "s": 39822, "text": null }, { "code": "# Python3 program to store sum of nodes# in left subtree in every node # Binary Tree Node # utility that allocates a new Node# with the given keyclass newNode: # Construct to create a new node def __init__(self, key): self.data = key self.left = None self.right = None # Function to modify a Binary Tree so# that every node stores sum of values# in its left child including its own valuedef updatetree(root): # Base cases if (not root): return 0 if (root.left == None and root.right == None) : return root.data # Update left and right subtrees leftsum = updatetree(root.left) rightsum = updatetree(root.right) # Add leftsum to current node root.data += leftsum # Return sum of values under root return root.data + rightsum # Utility function to do inorder traversaldef inorder(node) : if (node == None) : return inorder(node.left) print(node.data, end = \" \") inorder(node.right) # Driver Codeif __name__ == '__main__': \"\"\" Let us construct below tree 1 / \\ 2 3 / \\ \\ 4 5 6 \"\"\" root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.right.right = newNode(6) updatetree(root) print(\"Inorder traversal of the modified tree is\") inorder(root) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)", "e": 42862, "s": 41367, "text": null }, { "code": "// C# program to store sum of nodes in left // subtree in every nodeusing System; class GfG{ // A tree nodeclass node{ public int data; public node left, right;} // Function to modify a Binary Tree so// that every node stores sum of values// in its left child including its own valuestatic int updatetree(node root){ // Base cases if (root == null) return 0; if (root.left == null && root.right == null) return root.data; // Update left and right subtrees int leftsum = updatetree(root.left); int rightsum = updatetree(root.right); // Add leftsum to current node root.data += leftsum; // Return sum of values under root return root.data + rightsum;} // Utility function to do inorder traversalstatic void inorder(node node){ if (node == null) return; inorder(node.left); Console.Write(node.data + \" \"); inorder(node.right);} // Utility function to create a new nodestatic node newNode(int data){ node node = new node(); node.data = data; node.left = null; node.right = null; return(node);} // Driver codepublic static void Main(){ /* Let us construct below tree 1 / \\ 2 3 / \\ \\ 4 5 6 */ node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.right = newNode(6); updatetree(root); Console.WriteLine(\"Inorder traversal of the modified tree is\"); inorder(root);}} /* This code is contributed by Rajput-Ji*/", "e": 44432, "s": 42862, "text": null }, { "code": "<script> // Javascript program to store sum of nodes in left // subtree in every node // A tree nodeclass node{ constructor() { this.data = 0; this.left = null; this.right = null; }} // Function to modify a Binary Tree so// that every node stores sum of values// in its left child including its own valuefunction updatetree(root){ // Base cases if (root == null) return 0; if (root.left == null && root.right == null) return root.data; // Update left and right subtrees var leftsum = updatetree(root.left); var rightsum = updatetree(root.right); // Add leftsum to current node root.data += leftsum; // Return sum of values under root return root.data + rightsum;} // Utility function to do inorder traversalfunction inorder(node){ if (node == null) return; inorder(node.left); document.write(node.data + \" \"); inorder(node.right);} // Utility function to create a new nodefunction newNode(data){ var nod = new node(); nod.data = data; nod.left = null; nod.right = null; return(nod);} // Driver code/* Let us construct below tree 1 / \\ 2 3 / \\ \\ 4 5 6 */var root = newNode(1);root.left = newNode(2);root.right = newNode(3);root.left.left = newNode(4);root.left.right = newNode(5);root.right.right = newNode(6);updatetree(root);document.write(\"Inorder traversal of the modified tree is<br>\");inorder(root); // This code is contributed by rrrtnx.</script>", "e": 45918, "s": 44432, "text": null }, { "code": null, "e": 45927, "s": 45918, "text": "Output: " }, { "code": null, "e": 45982, "s": 45927, "text": "Inorder traversal of the modified tree is\n4 6 5 12 3 6" }, { "code": null, "e": 46005, "s": 45982, "text": "Time Complexity: O(n) " }, { "code": null, "e": 46042, "s": 46005, "text": "https://www.youtube.com/watch?v=EkmG" }, { "code": null, "e": 46051, "s": 46042, "text": "-FKRjBQ " }, { "code": null, "e": 46231, "s": 46051, "text": "Thanks to Gaurav Ahrirwar for suggesting this solution.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 46246, "s": 46233, "text": "prerna saini" }, { "code": null, "e": 46256, "s": 46246, "text": "Rajput-Ji" }, { "code": null, "e": 46271, "s": 46256, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 46285, "s": 46271, "text": "rathbhupendra" }, { "code": null, "e": 46292, "s": 46285, "text": "rrrtnx" }, { "code": null, "e": 46309, "s": 46292, "text": "surinderdawra388" }, { "code": null, "e": 46314, "s": 46309, "text": "Tree" }, { "code": null, "e": 46319, "s": 46314, "text": "Tree" }, { "code": null, "e": 46417, "s": 46319, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46467, "s": 46417, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 46502, "s": 46467, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 46536, "s": 46502, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 46565, "s": 46536, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 46606, "s": 46565, "text": "Inorder Tree Traversal without Recursion" }, { "code": null, "e": 46649, "s": 46606, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 46711, "s": 46649, "text": "Write a Program to Find the Maximum Depth or Height of a Tree" }, { "code": null, "e": 46744, "s": 46711, "text": "Binary Tree | Set 2 (Properties)" } ]
How to Execute Commands Remotely via SSH in Android? - GeeksforGeeks
23 Feb, 2021 The SSH protocol uses encryption to secure the connection between a client and a server. All user authentication, commands, output, and file transfers are encrypted to protect against attacks in the network. More often than not you would need to SSH into your cloud Virtual Machines or a remote shell. Usually, we need an SSH client to establish an SSH connection. For Windows, the free (libre) GUI client PuTTY is used for this purpose. Here is how it looks like accessing a remote Linux shell in PuTTY: The following tutorial illustrates how the same can be achieved in android. Note that we are going to implement this project using the Java language. Library: Apache MINA SSHD Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Adding dependencies Now we need to add the required dependencies in order to use the apache mina sshd library. Open app/src/build.gradle file in your project directory and add the following under dependencies: // Adding implementations required for apache mina library implementation ‘org.apache.mina:mina-core:3.0.0-M2’ implementation ‘org.apache.sshd:sshd-core:2.1.0’ implementation ‘org.apache.sshd:sshd-putty:2.1.0’ implementation ‘org.apache.sshd:sshd-common:2.1.0’ implementation ‘org.slf4j:slf4j-api:1.7.5’ implementation ‘org.slf4j:slf4j-simple:1.6.4’ Step 3: Add permission to the internet in your AndroidManifest.xml file Add below two lines inside your src/res/AndroidManifest.xml file inside <manifest></manifest> tags. <uses-permission android:name=”android.permission.INTERNET” /> Step 4: Modify the strings.xml file Open app > src > main > res > values > strings.xml and add the following code: XML <resources> <string name="app_name">gfg_ssh</string> <string name="host">Host</string> <string name="port">Port</string> <string name="defaultPort">22</string> <string name="username">Username</string> <string name="password">Password</string> <string name="button_send">SEND</string></resources> Step 5: Building the UI We are going to have two activities in our app. MainActivity: Here, we’ll enter the login details sshActivity: Here, we’ll see the shell output. Working with the activity_main.xml file: Now, Navigate to the app > src > main > res > layout > activity_main.xml and add the below code to the file. 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" android:background="@color/black" tools:context=".MainActivity"> <LinearLayout android:id="@+id/linear" android:layout_width="270dp" android:layout_height="413dp" android:layout_margin="50dp" android:orientation="vertical" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintWidth_percent=".8"> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:autofillHints="host" android:background="@color/white" android:ems="10" android:hint="@string/host" android:inputType="textPersonName" android:padding="10dp" android:textColor="@color/black" android:textColorHint="@color/black" app:layout_constraintWidth_percent=".8" /> <EditText android:id="@+id/portField" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="22dp" android:autofillHints="port" android:background="@color/white" android:ems="10" android:hint="@string/port" android:inputType="textPersonName" android:padding="10dp" android:textColor="@color/black" android:textColorHint="@color/black" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintWidth_percent=".8" tools:text="@string/defaultPort" /> <EditText android:id="@+id/usernameField" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="22dp" android:autofillHints="username" android:background="@color/white" android:ems="10" android:hint="@string/username" android:inputType="textPersonName" android:padding="10dp" android:textColor="@color/black" android:textColorHint="@color/black" app:layout_constraintBottom_toTopOf="@+id/passwordField" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/portField" app:layout_constraintWidth_percent=".8" /> <EditText android:id="@+id/passwordField" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="22dp" android:autofillHints="password" android:background="@color/white" android:ems="10" android:hint="@string/password" android:inputType="textPassword" android:padding="10dp" android:textColor="@color/black" android:textColorHint="@color/black" app:layout_constraintWidth_percent=".8" /> <Button android:id="@+id/button" android:layout_width="194dp" android:layout_height="61dp" android:layout_gravity="center" android:layout_marginTop="69dp" android:layout_marginBottom="373dp" android:background="#594FAA" android:onClick="authenticate" android:text="@string/button_send" android:textColor="@android:color/background_light" tools:text="@string/button_send" /> </LinearLayout></androidx.constraintlayout.widget.ConstraintLayout> First, create a new activity sshActivity by right-clicking on the activity folder (com.example.gfg_ssh) and then select New > Activity > Empty Activity and Now add the below code to the activity_ssh.xml file for UI of this activity. XML <?xml version="1.0" encoding="utf-8"?><androidx.coordinatorlayout.widget.CoordinatorLayout 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=".sshActivity"> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="688dp" android:background="@android:color/black" android:textColor="@color/white" android:textSize="18sp" /> </androidx.coordinatorlayout.widget.CoordinatorLayout> Step 6: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.EditText; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void authenticate(View view) { // Create an intent for sshActivity Intent intent = new Intent(this, sshActivity.class); // Declare fields EditText editText = (EditText) findViewById(R.id.editText); EditText portField = (EditText) findViewById(R.id.portField); EditText usernameField = (EditText) findViewById(R.id.usernameField); EditText passwordField = (EditText) findViewById(R.id.passwordField); // Get input data from fields String host = editText.getText().toString(); String port = portField.getText().toString(); String username = usernameField.getText().toString(); String password = passwordField.getText().toString(); // Pass on data to sshActivity via intent intent.putExtra("host", host); intent.putExtra("port", port); intent.putExtra("username", username); intent.putExtra("password", password); startActivity(intent); finish(); }} Step 7: Working with the sshActivity.java file This is the activity where we import the Apache MINA SSHD library and connect to our remote machine via SSH. We obtain the login data from the intent. Below is the code for the sshActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.content.Context;import android.content.Intent;import android.os.Bundle;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import org.apache.sshd.client.SshClient;import org.apache.sshd.client.channel.ClientChannel;import org.apache.sshd.client.channel.ClientChannelEvent;import org.apache.sshd.client.session.ClientSession;import org.apache.sshd.common.channel.Channel;import org.apache.sshd.server.forward.AcceptAllForwardingFilter; import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.OutputStream;import java.util.EnumSet;import java.util.concurrent.TimeUnit; public class sshActivity extends AppCompatActivity { ClientChannel channel; TextView shellOutput; String host, username, password; Integer port; String command; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ssh); // set output field shellOutput = findViewById(R.id.textView); // Get user credentials from indent Intent intent = getIntent(); host = intent.getStringExtra("host"); port = Integer.parseInt(intent.getStringExtra("port")); username = intent.getStringExtra("username"); password = intent.getStringExtra("password"); // Command which will be executed command = "pwd\n"; // Setting user.com property manually // since isn't set by default in android String key = "user.home"; Context Syscontext; Syscontext = getApplicationContext(); String val = Syscontext.getApplicationInfo().dataDir; System.setProperty(key, val); // Creating a client instance SshClient client = SshClient.setUpDefaultClient(); client.setForwardingFilter(AcceptAllForwardingFilter.INSTANCE); client.start(); // Starting new thread because network processes // can interfere with UI if started in main thread Thread thread = new Thread(new Runnable() { @Override public void run() { try { // Connection establishment and authentication try (ClientSession session = client.connect(username, host, port).verify(10000).getSession()) { session.addPasswordIdentity(password); session.auth().verify(50000); System.out.println("Connection establihed"); // Create a channel to communicate channel = session.createChannel(Channel.CHANNEL_SHELL); System.out.println("Starting shell"); ByteArrayOutputStream responseStream = new ByteArrayOutputStream(); channel.setOut(responseStream); // Open channel channel.open().verify(5, TimeUnit.SECONDS); try (OutputStream pipedIn = channel.getInvertedIn()) { pipedIn.write(command.getBytes()); pipedIn.flush(); } // Close channel channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(5)); // Output after converting to string type String responseString = new String(responseStream.toByteArray()); System.out.println(responseString); shellOutput.setText(responseString); } catch (IOException e) { e.printStackTrace(); } finally { client.stop(); } } catch (Exception e) { e.printStackTrace(); } } }); thread.start(); }} Logging in: SSH command execution: Android-Misc Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? Android Listview in Java with Example Retrofit with Kotlin Coroutine in Android How to Change the Background Color After Clicking the Button in Android? 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": 25116, "s": 25088, "text": "\n23 Feb, 2021" }, { "code": null, "e": 25621, "s": 25116, "text": "The SSH protocol uses encryption to secure the connection between a client and a server. All user authentication, commands, output, and file transfers are encrypted to protect against attacks in the network. More often than not you would need to SSH into your cloud Virtual Machines or a remote shell. Usually, we need an SSH client to establish an SSH connection. For Windows, the free (libre) GUI client PuTTY is used for this purpose. Here is how it looks like accessing a remote Linux shell in PuTTY:" }, { "code": null, "e": 25797, "s": 25621, "text": "The following tutorial illustrates how the same can be achieved in android. Note that we are going to implement this project using the Java language. Library: Apache MINA SSHD" }, { "code": null, "e": 25826, "s": 25797, "text": "Step 1: Create a New Project" }, { "code": null, "e": 25988, "s": 25826, "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": 26016, "s": 25988, "text": "Step 2: Adding dependencies" }, { "code": null, "e": 26206, "s": 26016, "text": "Now we need to add the required dependencies in order to use the apache mina sshd library. Open app/src/build.gradle file in your project directory and add the following under dependencies:" }, { "code": null, "e": 26265, "s": 26206, "text": "// Adding implementations required for apache mina library" }, { "code": null, "e": 26317, "s": 26265, "text": "implementation ‘org.apache.mina:mina-core:3.0.0-M2’" }, { "code": null, "e": 26366, "s": 26317, "text": "implementation ‘org.apache.sshd:sshd-core:2.1.0’" }, { "code": null, "e": 26416, "s": 26366, "text": "implementation ‘org.apache.sshd:sshd-putty:2.1.0’" }, { "code": null, "e": 26467, "s": 26416, "text": "implementation ‘org.apache.sshd:sshd-common:2.1.0’" }, { "code": null, "e": 26510, "s": 26467, "text": "implementation ‘org.slf4j:slf4j-api:1.7.5’" }, { "code": null, "e": 26556, "s": 26510, "text": "implementation ‘org.slf4j:slf4j-simple:1.6.4’" }, { "code": null, "e": 26628, "s": 26556, "text": "Step 3: Add permission to the internet in your AndroidManifest.xml file" }, { "code": null, "e": 26728, "s": 26628, "text": "Add below two lines inside your src/res/AndroidManifest.xml file inside <manifest></manifest> tags." }, { "code": null, "e": 26791, "s": 26728, "text": "<uses-permission android:name=”android.permission.INTERNET” />" }, { "code": null, "e": 26827, "s": 26791, "text": "Step 4: Modify the strings.xml file" }, { "code": null, "e": 26906, "s": 26827, "text": "Open app > src > main > res > values > strings.xml and add the following code:" }, { "code": null, "e": 26910, "s": 26906, "text": "XML" }, { "code": "<resources> <string name=\"app_name\">gfg_ssh</string> <string name=\"host\">Host</string> <string name=\"port\">Port</string> <string name=\"defaultPort\">22</string> <string name=\"username\">Username</string> <string name=\"password\">Password</string> <string name=\"button_send\">SEND</string></resources>", "e": 27228, "s": 26910, "text": null }, { "code": null, "e": 27252, "s": 27228, "text": "Step 5: Building the UI" }, { "code": null, "e": 27300, "s": 27252, "text": "We are going to have two activities in our app." }, { "code": null, "e": 27350, "s": 27300, "text": "MainActivity: Here, we’ll enter the login details" }, { "code": null, "e": 27397, "s": 27350, "text": "sshActivity: Here, we’ll see the shell output." }, { "code": null, "e": 27438, "s": 27397, "text": "Working with the activity_main.xml file:" }, { "code": null, "e": 27547, "s": 27438, "text": "Now, Navigate to the app > src > main > res > layout > activity_main.xml and add the below code to the file." }, { "code": null, "e": 27551, "s": 27547, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"@color/black\" tools:context=\".MainActivity\"> <LinearLayout android:id=\"@+id/linear\" android:layout_width=\"270dp\" android:layout_height=\"413dp\" android:layout_margin=\"50dp\" android:orientation=\"vertical\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintWidth_percent=\".8\"> <EditText android:id=\"@+id/editText\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:autofillHints=\"host\" android:background=\"@color/white\" android:ems=\"10\" android:hint=\"@string/host\" android:inputType=\"textPersonName\" android:padding=\"10dp\" android:textColor=\"@color/black\" android:textColorHint=\"@color/black\" app:layout_constraintWidth_percent=\".8\" /> <EditText android:id=\"@+id/portField\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"22dp\" android:autofillHints=\"port\" android:background=\"@color/white\" android:ems=\"10\" android:hint=\"@string/port\" android:inputType=\"textPersonName\" android:padding=\"10dp\" android:textColor=\"@color/black\" android:textColorHint=\"@color/black\" app:layout_constraintHorizontal_bias=\"0.5\" app:layout_constraintWidth_percent=\".8\" tools:text=\"@string/defaultPort\" /> <EditText android:id=\"@+id/usernameField\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"22dp\" android:autofillHints=\"username\" android:background=\"@color/white\" android:ems=\"10\" android:hint=\"@string/username\" android:inputType=\"textPersonName\" android:padding=\"10dp\" android:textColor=\"@color/black\" android:textColorHint=\"@color/black\" app:layout_constraintBottom_toTopOf=\"@+id/passwordField\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.5\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/portField\" app:layout_constraintWidth_percent=\".8\" /> <EditText android:id=\"@+id/passwordField\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"22dp\" android:autofillHints=\"password\" android:background=\"@color/white\" android:ems=\"10\" android:hint=\"@string/password\" android:inputType=\"textPassword\" android:padding=\"10dp\" android:textColor=\"@color/black\" android:textColorHint=\"@color/black\" app:layout_constraintWidth_percent=\".8\" /> <Button android:id=\"@+id/button\" android:layout_width=\"194dp\" android:layout_height=\"61dp\" android:layout_gravity=\"center\" android:layout_marginTop=\"69dp\" android:layout_marginBottom=\"373dp\" android:background=\"#594FAA\" android:onClick=\"authenticate\" android:text=\"@string/button_send\" android:textColor=\"@android:color/background_light\" tools:text=\"@string/button_send\" /> </LinearLayout></androidx.constraintlayout.widget.ConstraintLayout>", "e": 31696, "s": 27551, "text": null }, { "code": null, "e": 31929, "s": 31696, "text": "First, create a new activity sshActivity by right-clicking on the activity folder (com.example.gfg_ssh) and then select New > Activity > Empty Activity and Now add the below code to the activity_ssh.xml file for UI of this activity." }, { "code": null, "e": 31933, "s": 31929, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.coordinatorlayout.widget.CoordinatorLayout 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=\".sshActivity\"> <TextView android:id=\"@+id/textView\" android:layout_width=\"match_parent\" android:layout_height=\"688dp\" android:background=\"@android:color/black\" android:textColor=\"@color/white\" android:textSize=\"18sp\" /> </androidx.coordinatorlayout.widget.CoordinatorLayout>", "e": 32557, "s": 31933, "text": null }, { "code": null, "e": 32605, "s": 32557, "text": "Step 6: Working with the MainActivity.java file" }, { "code": null, "e": 32795, "s": 32605, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 32800, "s": 32795, "text": "Java" }, { "code": "import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.EditText; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void authenticate(View view) { // Create an intent for sshActivity Intent intent = new Intent(this, sshActivity.class); // Declare fields EditText editText = (EditText) findViewById(R.id.editText); EditText portField = (EditText) findViewById(R.id.portField); EditText usernameField = (EditText) findViewById(R.id.usernameField); EditText passwordField = (EditText) findViewById(R.id.passwordField); // Get input data from fields String host = editText.getText().toString(); String port = portField.getText().toString(); String username = usernameField.getText().toString(); String password = passwordField.getText().toString(); // Pass on data to sshActivity via intent intent.putExtra(\"host\", host); intent.putExtra(\"port\", port); intent.putExtra(\"username\", username); intent.putExtra(\"password\", password); startActivity(intent); finish(); }}", "e": 34200, "s": 32800, "text": null }, { "code": null, "e": 34247, "s": 34200, "text": "Step 7: Working with the sshActivity.java file" }, { "code": null, "e": 34521, "s": 34247, "text": "This is the activity where we import the Apache MINA SSHD library and connect to our remote machine via SSH. We obtain the login data from the intent. Below is the code for the sshActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 34526, "s": 34521, "text": "Java" }, { "code": "import android.content.Context;import android.content.Intent;import android.os.Bundle;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import org.apache.sshd.client.SshClient;import org.apache.sshd.client.channel.ClientChannel;import org.apache.sshd.client.channel.ClientChannelEvent;import org.apache.sshd.client.session.ClientSession;import org.apache.sshd.common.channel.Channel;import org.apache.sshd.server.forward.AcceptAllForwardingFilter; import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.OutputStream;import java.util.EnumSet;import java.util.concurrent.TimeUnit; public class sshActivity extends AppCompatActivity { ClientChannel channel; TextView shellOutput; String host, username, password; Integer port; String command; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ssh); // set output field shellOutput = findViewById(R.id.textView); // Get user credentials from indent Intent intent = getIntent(); host = intent.getStringExtra(\"host\"); port = Integer.parseInt(intent.getStringExtra(\"port\")); username = intent.getStringExtra(\"username\"); password = intent.getStringExtra(\"password\"); // Command which will be executed command = \"pwd\\n\"; // Setting user.com property manually // since isn't set by default in android String key = \"user.home\"; Context Syscontext; Syscontext = getApplicationContext(); String val = Syscontext.getApplicationInfo().dataDir; System.setProperty(key, val); // Creating a client instance SshClient client = SshClient.setUpDefaultClient(); client.setForwardingFilter(AcceptAllForwardingFilter.INSTANCE); client.start(); // Starting new thread because network processes // can interfere with UI if started in main thread Thread thread = new Thread(new Runnable() { @Override public void run() { try { // Connection establishment and authentication try (ClientSession session = client.connect(username, host, port).verify(10000).getSession()) { session.addPasswordIdentity(password); session.auth().verify(50000); System.out.println(\"Connection establihed\"); // Create a channel to communicate channel = session.createChannel(Channel.CHANNEL_SHELL); System.out.println(\"Starting shell\"); ByteArrayOutputStream responseStream = new ByteArrayOutputStream(); channel.setOut(responseStream); // Open channel channel.open().verify(5, TimeUnit.SECONDS); try (OutputStream pipedIn = channel.getInvertedIn()) { pipedIn.write(command.getBytes()); pipedIn.flush(); } // Close channel channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(5)); // Output after converting to string type String responseString = new String(responseStream.toByteArray()); System.out.println(responseString); shellOutput.setText(responseString); } catch (IOException e) { e.printStackTrace(); } finally { client.stop(); } } catch (Exception e) { e.printStackTrace(); } } }); thread.start(); }}", "e": 38524, "s": 34526, "text": null }, { "code": null, "e": 38536, "s": 38524, "text": "Logging in:" }, { "code": null, "e": 38559, "s": 38536, "text": "SSH command execution:" }, { "code": null, "e": 38572, "s": 38559, "text": "Android-Misc" }, { "code": null, "e": 38580, "s": 38572, "text": "Android" }, { "code": null, "e": 38585, "s": 38580, "text": "Java" }, { "code": null, "e": 38590, "s": 38585, "text": "Java" }, { "code": null, "e": 38598, "s": 38590, "text": "Android" }, { "code": null, "e": 38696, "s": 38598, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38735, "s": 38696, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 38785, "s": 38735, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 38823, "s": 38785, "text": "Android Listview in Java with Example" }, { "code": null, "e": 38865, "s": 38823, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 38938, "s": 38865, "text": "How to Change the Background Color After Clicking the Button in Android?" }, { "code": null, "e": 38953, "s": 38938, "text": "Arrays in Java" }, { "code": null, "e": 38997, "s": 38953, "text": "Split() String method in Java with examples" }, { "code": null, "e": 39019, "s": 38997, "text": "For-each loop in Java" }, { "code": null, "e": 39055, "s": 39019, "text": "Arrays.sort() in Java with examples" } ]
DATE/TIME Functions in SQL. Tutorial on how to use CAST, EXTRACT... | by Jason Lee | Towards Data Science
Working with dates and times is a common practice when working in SQL. Using dates, we can calculate changes over time, trends in the data, perform interval arithmetic. To better understand the impacts of the underlying business problem. “time-series data” as a sequence of data points, measuring the same thing over time, stored in time order. Some common uses of time-series data Stock price movement Sensor tracking (e.g., weather tracking) Rental services (e.g., bike or scooter rentals) For this tutorial, I will assume you have intermediate SQL skills. We will be covering three functions and working with PostgreSQL syntax. CASTEXTRACTDATE_TRUNC CAST EXTRACT DATE_TRUNC Each of these functions can be useful when breaking down datasets with a lot of data. We will see the benefits of each one as we go through the code with some examples. A CAST function converts the selected data type into another. Pretty straight forward. It changes one type into your preferred type. The syntax is below. CAST(expression AS datatype) Below is an example of how it can be applied to date and time. SELECT NOW(), CAST(NOW() AS TIMESTAMP), CAST(NOW() AS DATE), CAST(NOW() AS TIME), CURRENT_DATE, CURRENT_TIME In this query, we expect to have 6 outputs. If you are unfamiliar with NOW(), CURRENT_DATE, CURRENT_TIME they are SQL functions that retrieve the current time or date. Below are all the outputs from the query in order. (note — you will get different numbers since the functions call the exact time or date) 2020–03–28 23:18:20.261879+00:00 2020–03–28 23:18:20.261879 2020–03–28 23:18:20.261879 2020–03–28 23:18:20.261879+00:00 Looking at the first result from the NOW() used on its own, we get a full timestamp value, including the timezone. Now as we go down to the second output, we used CAST to only retrieve the TIMESTAMP, which does not include the timezone from the NOW(). Now we can see how cast works. We pass in a value we want to be converted and then state the type we want. Next, we use CAST() on NOW() but pass in DATE as our desired type. We now get a timestamp stripped to only the year/month/day format. Similarly, look at the CAST() function with NOW() and only TIME, and we get just the time value with no date. We can see how the CAST function works with time, and the last two outputs using CURRENT_DATE and CURRENT_TIME are just there for you to see the comparison of results. SQL also allows CAST() functions to be used with types that are not timestamped. SELECT CAST(1.34 AS INT), CAST(1 AS BOOLEAN), CAST(2.65 AS DEC(3,0)) The results from this query are, 1 → Since an integer can’t have decimals, it will round to the nearest integer value true → 1 as a boolean is true, and 0 is false 3 → using the DEC() we can also do the reverse of our first integer CAST. In SQL, you can also use INTERVAL to add more time to any timestamp you have. For the examples below, you don't need to use the CAST() function, but I've chosen to do so only to have the date. SELECT CAST(NOW() AS DATE) AS TODAY_DATE, CAST((INTERVAL '3 DAYS' + NOW()) AS DATE) AS three_days, CAST((INTERVAL '3 WEEKS' + NOW()) AS DATE) AS three_weeks, CAST((INTERVAL '3 MONTHS' + NOW()) AS DATE) AS three_months, CAST((INTERVAL '3 YEARS' + NOW()) AS DATE) AS three_years We can see that using the INTERVAL in addition to the length of the interval in days, weeks, months or years adds more time to whatever date you have — in this example the current date is obtained from NOW(). Next, we can look at pulling a specific format out of a timestamp. The goal is to extract a portion out of a timestamp. For example, if we want just the month from the date 12/10/2018, we would get December (12). Let’s take a look at EXTRACT syntax EXTRACT(part FROM date) We state the type of extraction we want as part and then the source to be extracted date. EXTRACTis an import tool in time series data analysis. It helps you isolate groups in your timestamps to aggregate data based on precise timings. For example, if a car rental store wanted to find the busiest rentalHOUR on MONDAYS every MAY, you can do that with EXTRACT. You can drill down the details and see more valuable insights. Let’s assume we run NOW() and our timestamp is 2020–03–29 00:27:51.677318+00:00, we can use EXTRACTto get the following. SELECT EXTRACT(MINUTE FROM NOW()) AS MINUTE, EXTRACT(HOUR FROM NOW()) AS HOUR, EXTRACT(DAY FROM NOW()) AS DAY, EXTRACT(WEEK FROM NOW()) AS WEEK, EXTRACT(MONTH FROM NOW()) AS MONTH, EXTRACT(YEAR FROM NOW()) AS YEAR, EXTRACT(DOW FROM NOW()) AS DAY_OF_WEEK, EXTRACT(DOY FROM NOW()) AS DAY_OF_YEAR, EXTRACT(QUARTER FROM NOW()) AS QUARTER, EXTRACT(TIMEZONE FROM NOW()) AS TIMEZONE We see that we can go into great detail in how we want to extract information out of our timestamps. Note — DOW — The day of the week is Sunday(0) to Saturday(6). We can build on the rental car example earlier and see how it would work. SELECT EXTRACT(HOUR FROM RENTAL_DATE) AS HOUR, COUNT(*) as RENTALS FROM RENTAL WHERE EXTRACT(DOW FROM RENTAL_DATE) = 1 AND EXTRACT(MONTH FROM RENTAL_DATE) = 5GROUP BY 1ORDER BY RENTALS DESC Remember we want the busiest rentalHOUR on MONDAYS every MAY . First, we use EXTRCT in the SELECT to state, we want only the HOUR and the total COUNT . We then pass in two EXTRACT functions for in the WHERE clause to filter only MONDAYS and MAY. Looking at the table below 11 am is the most popular rental time every Monday in May with a total of 11 rentals. Truncate — to shorten by or as if by cutting off The purpose of truncating a date in SQL is to return an interval at an absolute precision. The precision values are a subset of the field identifiers that can be used with the EXTRACT. DATE_TRUNC will return an interval or timestamp rather than a number. The syntax for DATE_TRUNC, time_column is the database column that contains the timestamp you'd like to round, and ‘[interval]’ dictates your desired precision level. DATE_TRUNC(‘[interval]’, time_column) Let’s assume our NOW() returns the same 2020–03–29 00:27:51.677318+00:00, we can use date_part to get the following. SELECT CAST(DATE_TRUNC('DAY', NOW()) AS DATE) AS DAY, CAST(DATE_TRUNC('WEEK', NOW()) AS DATE) AS WEEK, CAST(DATE_TRUNC('MONTH', NOW()) AS DATE) AS MONTH, CAST(DATE_TRUNC('YEAR', NOW()) AS DATE) AS YEAR Think of using DATE_TRUNC as getting the interval of where it is currently, and each level of an interval is how the date gets trimmed. Note — we did not need to use CAST in this example. I used it to ensure the format was clean for analysis. We can use DATE_TRUNC on the rental car scenario from earlier, and try to find which day in the year regardless of time is more popular for rentals. SELECT CAST(DATE_TRUNC('DAY', RENTAL_DATE) AS DATE) AS RENTAL_DAY, COUNT(*) AS RENTALSFROM RENTALGROUP BY RENTAL_DAYORDER BY RENTALS DESC Now that we have seen how to use CAST, EXTRACT, and DATE_TRUNC we can bring together some of the techniques we learned into one practical example. For this example, we will add a new time function called AGE — which takes in 2 dates as an argument and outputs the "AGE" or the time in years and months between the dates. Let’s wrap up this tutorial by extracting a list of customers who had the longest rental duration ( AGE ) from 2019–05–01 + 30 days. SELECT CUSTOMER_ID, EXTRACT(DOW FROM RENTAL_DATE) AS DAY_OF_WEEK, AGE(RETURN_DATE, RENTAL_DATE) AS RENTAL_DAYSFROM RENTALWHERE RENTAL_DATE BETWEEN CAST('2019-05-01' AS TIMESTAMP) AND CAST('2019-05-01' AS TIMESTAMP) + INTERVAL '30 DAY'ORDER BY 3 DESC I hope you feel comfortable working with timestamps in SQL. You have learned to use CAST , EXTRACT, INTERVAL,DATE_TRUNC , and AGE. You should be well equipped to tackle trend related analysis, and dive deeper into the data to find insights you may not have been able to find before! If you are interested in more SQL tutorials, check out my other posts. How to use CTEs in SQL Introduction to Window Functions Creating Tables in SQL Connect with me on Linkedin or Github
[ { "code": null, "e": 410, "s": 172, "text": "Working with dates and times is a common practice when working in SQL. Using dates, we can calculate changes over time, trends in the data, perform interval arithmetic. To better understand the impacts of the underlying business problem." }, { "code": null, "e": 517, "s": 410, "text": "“time-series data” as a sequence of data points, measuring the same thing over time, stored in time order." }, { "code": null, "e": 554, "s": 517, "text": "Some common uses of time-series data" }, { "code": null, "e": 575, "s": 554, "text": "Stock price movement" }, { "code": null, "e": 616, "s": 575, "text": "Sensor tracking (e.g., weather tracking)" }, { "code": null, "e": 664, "s": 616, "text": "Rental services (e.g., bike or scooter rentals)" }, { "code": null, "e": 803, "s": 664, "text": "For this tutorial, I will assume you have intermediate SQL skills. We will be covering three functions and working with PostgreSQL syntax." }, { "code": null, "e": 825, "s": 803, "text": "CASTEXTRACTDATE_TRUNC" }, { "code": null, "e": 830, "s": 825, "text": "CAST" }, { "code": null, "e": 838, "s": 830, "text": "EXTRACT" }, { "code": null, "e": 849, "s": 838, "text": "DATE_TRUNC" }, { "code": null, "e": 1018, "s": 849, "text": "Each of these functions can be useful when breaking down datasets with a lot of data. We will see the benefits of each one as we go through the code with some examples." }, { "code": null, "e": 1172, "s": 1018, "text": "A CAST function converts the selected data type into another. Pretty straight forward. It changes one type into your preferred type. The syntax is below." }, { "code": null, "e": 1201, "s": 1172, "text": "CAST(expression AS datatype)" }, { "code": null, "e": 1264, "s": 1201, "text": "Below is an example of how it can be applied to date and time." }, { "code": null, "e": 1391, "s": 1264, "text": "SELECT NOW(), CAST(NOW() AS TIMESTAMP), CAST(NOW() AS DATE), CAST(NOW() AS TIME), CURRENT_DATE, CURRENT_TIME" }, { "code": null, "e": 1698, "s": 1391, "text": "In this query, we expect to have 6 outputs. If you are unfamiliar with NOW(), CURRENT_DATE, CURRENT_TIME they are SQL functions that retrieve the current time or date. Below are all the outputs from the query in order. (note — you will get different numbers since the functions call the exact time or date)" }, { "code": null, "e": 1731, "s": 1698, "text": "2020–03–28 23:18:20.261879+00:00" }, { "code": null, "e": 1758, "s": 1731, "text": "2020–03–28 23:18:20.261879" }, { "code": null, "e": 1769, "s": 1758, "text": "2020–03–28" }, { "code": null, "e": 1785, "s": 1769, "text": "23:18:20.261879" }, { "code": null, "e": 1796, "s": 1785, "text": "2020–03–28" }, { "code": null, "e": 1818, "s": 1796, "text": "23:18:20.261879+00:00" }, { "code": null, "e": 2177, "s": 1818, "text": "Looking at the first result from the NOW() used on its own, we get a full timestamp value, including the timezone. Now as we go down to the second output, we used CAST to only retrieve the TIMESTAMP, which does not include the timezone from the NOW(). Now we can see how cast works. We pass in a value we want to be converted and then state the type we want." }, { "code": null, "e": 2421, "s": 2177, "text": "Next, we use CAST() on NOW() but pass in DATE as our desired type. We now get a timestamp stripped to only the year/month/day format. Similarly, look at the CAST() function with NOW() and only TIME, and we get just the time value with no date." }, { "code": null, "e": 2589, "s": 2421, "text": "We can see how the CAST function works with time, and the last two outputs using CURRENT_DATE and CURRENT_TIME are just there for you to see the comparison of results." }, { "code": null, "e": 2670, "s": 2589, "text": "SQL also allows CAST() functions to be used with types that are not timestamped." }, { "code": null, "e": 2749, "s": 2670, "text": "SELECT CAST(1.34 AS INT), CAST(1 AS BOOLEAN), CAST(2.65 AS DEC(3,0))" }, { "code": null, "e": 2782, "s": 2749, "text": "The results from this query are," }, { "code": null, "e": 2867, "s": 2782, "text": "1 → Since an integer can’t have decimals, it will round to the nearest integer value" }, { "code": null, "e": 2913, "s": 2867, "text": "true → 1 as a boolean is true, and 0 is false" }, { "code": null, "e": 2987, "s": 2913, "text": "3 → using the DEC() we can also do the reverse of our first integer CAST." }, { "code": null, "e": 3180, "s": 2987, "text": "In SQL, you can also use INTERVAL to add more time to any timestamp you have. For the examples below, you don't need to use the CAST() function, but I've chosen to do so only to have the date." }, { "code": null, "e": 3472, "s": 3180, "text": "SELECT CAST(NOW() AS DATE) AS TODAY_DATE, CAST((INTERVAL '3 DAYS' + NOW()) AS DATE) AS three_days, CAST((INTERVAL '3 WEEKS' + NOW()) AS DATE) AS three_weeks, CAST((INTERVAL '3 MONTHS' + NOW()) AS DATE) AS three_months, CAST((INTERVAL '3 YEARS' + NOW()) AS DATE) AS three_years" }, { "code": null, "e": 3681, "s": 3472, "text": "We can see that using the INTERVAL in addition to the length of the interval in days, weeks, months or years adds more time to whatever date you have — in this example the current date is obtained from NOW()." }, { "code": null, "e": 3894, "s": 3681, "text": "Next, we can look at pulling a specific format out of a timestamp. The goal is to extract a portion out of a timestamp. For example, if we want just the month from the date 12/10/2018, we would get December (12)." }, { "code": null, "e": 3930, "s": 3894, "text": "Let’s take a look at EXTRACT syntax" }, { "code": null, "e": 3954, "s": 3930, "text": "EXTRACT(part FROM date)" }, { "code": null, "e": 4378, "s": 3954, "text": "We state the type of extraction we want as part and then the source to be extracted date. EXTRACTis an import tool in time series data analysis. It helps you isolate groups in your timestamps to aggregate data based on precise timings. For example, if a car rental store wanted to find the busiest rentalHOUR on MONDAYS every MAY, you can do that with EXTRACT. You can drill down the details and see more valuable insights." }, { "code": null, "e": 4499, "s": 4378, "text": "Let’s assume we run NOW() and our timestamp is 2020–03–29 00:27:51.677318+00:00, we can use EXTRACTto get the following." }, { "code": null, "e": 4968, "s": 4499, "text": "SELECT EXTRACT(MINUTE FROM NOW()) AS MINUTE, EXTRACT(HOUR FROM NOW()) AS HOUR, EXTRACT(DAY FROM NOW()) AS DAY, EXTRACT(WEEK FROM NOW()) AS WEEK, EXTRACT(MONTH FROM NOW()) AS MONTH, EXTRACT(YEAR FROM NOW()) AS YEAR, EXTRACT(DOW FROM NOW()) AS DAY_OF_WEEK, EXTRACT(DOY FROM NOW()) AS DAY_OF_YEAR, EXTRACT(QUARTER FROM NOW()) AS QUARTER, EXTRACT(TIMEZONE FROM NOW()) AS TIMEZONE" }, { "code": null, "e": 5131, "s": 4968, "text": "We see that we can go into great detail in how we want to extract information out of our timestamps. Note — DOW — The day of the week is Sunday(0) to Saturday(6)." }, { "code": null, "e": 5205, "s": 5131, "text": "We can build on the rental car example earlier and see how it would work." }, { "code": null, "e": 5407, "s": 5205, "text": "SELECT EXTRACT(HOUR FROM RENTAL_DATE) AS HOUR, COUNT(*) as RENTALS FROM RENTAL WHERE EXTRACT(DOW FROM RENTAL_DATE) = 1 AND EXTRACT(MONTH FROM RENTAL_DATE) = 5GROUP BY 1ORDER BY RENTALS DESC" }, { "code": null, "e": 5766, "s": 5407, "text": "Remember we want the busiest rentalHOUR on MONDAYS every MAY . First, we use EXTRCT in the SELECT to state, we want only the HOUR and the total COUNT . We then pass in two EXTRACT functions for in the WHERE clause to filter only MONDAYS and MAY. Looking at the table below 11 am is the most popular rental time every Monday in May with a total of 11 rentals." }, { "code": null, "e": 5815, "s": 5766, "text": "Truncate — to shorten by or as if by cutting off" }, { "code": null, "e": 6070, "s": 5815, "text": "The purpose of truncating a date in SQL is to return an interval at an absolute precision. The precision values are a subset of the field identifiers that can be used with the EXTRACT. DATE_TRUNC will return an interval or timestamp rather than a number." }, { "code": null, "e": 6237, "s": 6070, "text": "The syntax for DATE_TRUNC, time_column is the database column that contains the timestamp you'd like to round, and ‘[interval]’ dictates your desired precision level." }, { "code": null, "e": 6275, "s": 6237, "text": "DATE_TRUNC(‘[interval]’, time_column)" }, { "code": null, "e": 6392, "s": 6275, "text": "Let’s assume our NOW() returns the same 2020–03–29 00:27:51.677318+00:00, we can use date_part to get the following." }, { "code": null, "e": 6606, "s": 6392, "text": "SELECT CAST(DATE_TRUNC('DAY', NOW()) AS DATE) AS DAY, CAST(DATE_TRUNC('WEEK', NOW()) AS DATE) AS WEEK, CAST(DATE_TRUNC('MONTH', NOW()) AS DATE) AS MONTH, CAST(DATE_TRUNC('YEAR', NOW()) AS DATE) AS YEAR" }, { "code": null, "e": 6849, "s": 6606, "text": "Think of using DATE_TRUNC as getting the interval of where it is currently, and each level of an interval is how the date gets trimmed. Note — we did not need to use CAST in this example. I used it to ensure the format was clean for analysis." }, { "code": null, "e": 6998, "s": 6849, "text": "We can use DATE_TRUNC on the rental car scenario from earlier, and try to find which day in the year regardless of time is more popular for rentals." }, { "code": null, "e": 7145, "s": 6998, "text": "SELECT CAST(DATE_TRUNC('DAY', RENTAL_DATE) AS DATE) AS RENTAL_DAY, COUNT(*) AS RENTALSFROM RENTALGROUP BY RENTAL_DAYORDER BY RENTALS DESC" }, { "code": null, "e": 7292, "s": 7145, "text": "Now that we have seen how to use CAST, EXTRACT, and DATE_TRUNC we can bring together some of the techniques we learned into one practical example." }, { "code": null, "e": 7466, "s": 7292, "text": "For this example, we will add a new time function called AGE — which takes in 2 dates as an argument and outputs the \"AGE\" or the time in years and months between the dates." }, { "code": null, "e": 7599, "s": 7466, "text": "Let’s wrap up this tutorial by extracting a list of customers who had the longest rental duration ( AGE ) from 2019–05–01 + 30 days." }, { "code": null, "e": 7888, "s": 7599, "text": "SELECT CUSTOMER_ID, EXTRACT(DOW FROM RENTAL_DATE) AS DAY_OF_WEEK, AGE(RETURN_DATE, RENTAL_DATE) AS RENTAL_DAYSFROM RENTALWHERE RENTAL_DATE BETWEEN CAST('2019-05-01' AS TIMESTAMP) AND CAST('2019-05-01' AS TIMESTAMP) + INTERVAL '30 DAY'ORDER BY 3 DESC" }, { "code": null, "e": 8171, "s": 7888, "text": "I hope you feel comfortable working with timestamps in SQL. You have learned to use CAST , EXTRACT, INTERVAL,DATE_TRUNC , and AGE. You should be well equipped to tackle trend related analysis, and dive deeper into the data to find insights you may not have been able to find before!" }, { "code": null, "e": 8242, "s": 8171, "text": "If you are interested in more SQL tutorials, check out my other posts." }, { "code": null, "e": 8265, "s": 8242, "text": "How to use CTEs in SQL" }, { "code": null, "e": 8298, "s": 8265, "text": "Introduction to Window Functions" }, { "code": null, "e": 8321, "s": 8298, "text": "Creating Tables in SQL" } ]
Interactive Ternary Plots with Plotly | by Soner Yıldırım | Towards Data Science
Plotly Python (plotly.py) is an open-source plotting library built on plotly javascript (plotly.js). One of the things I like about plotly.py is that it offers a high-level API (plotly express) and a low level API (graph objects) to create visualizations. With plotly express, we can create a dynamic and informative plot with very few lines of code. On the other hand, we need to write more code with graph objects but have more control over what we create. In this post, we will create ternary plots using plotly express. Ternary plots depict the ratios of three variables by positioning the data points in a triangle accordingly. It gives us an overview whether the observations lean towards a certain variable. Each corner of the triangle is labelled with one variable. Thus, we can only compare three variables. Consider we are evaluating three car brands on lots of measurements. Each brand has a rating on each measurement. By plotting these measurements on a ternary plot, we get an idea if one brand is more dominant than others. For instance, one brand might be prominent in terms of safety related measures. I could not find a dataset that compares car brands in many different measures but I was able to find an interesting one which is adataset that has RGB values of colors. Each color is made up of a combination of red, green, and blue (RGB). The colors change according to the ratios of these three main colors. The dataset that is available here on data.world website includes RGB values for 746 different colors. I did not even know if some of those colors existed. There are some weird color names such as “Alizarin crimson”, “Bazaar”, and “Charcoal”. We will use ternary plot to get an overview about the RGB components of this wide range of colors. Let’s first read the dataset into a pandas dataframe and take a look at it. import numpy as npimport pandas as pddf = pd.read_csv("/content/colorhexa_com.csv")print(df.shape)df.head() For now, I’m only interested in the name of the color and RGB components so I will only take those columns and change the names of colors. new_cols = {'Red (8 bit)':'Red', 'Green (8 bit)':'Green', 'Blue (8 bit)':'Blue'}df.rename(columns=new_cols, inplace=True)df = df[['Name', 'Red', 'Green', 'Blue']]df.head() I also want to add a marker for each color name that indicates the RGB color which contributes most. I will use nested loops but feel free to try out your own way. winners = []for i in range(len(df)): if df.iloc[i,1] > df.iloc[i,2] and df.iloc[i,1] > df.iloc[i,3]: winner = "Red" elif df.iloc[i,2] > df.iloc[i,3]: winner = "Green" else: winner = "Blue" winners.append(winner)df['winner'] = winnersdf.head() Let’s first create a simple ternary plot that positions each color according to RGB component values. We will use plotly express which is the high-level API of plotly python. import plotly.express as pxfig = px.scatter_ternary(df, a="Red", b="Green", c="Blue", hover_name="Name")fig.show() Most of the colors are around the center of triangle but there is a slight incline towards red. We also have colors located on the edges of triangle. Those colors only include two of three RGB colors. Not surprisingly, the colors on the corners contain only one component. For instance, navy blue has only blue component. We pass the “Name” column hover_name parameter which allow to see the name of the color when hovering on a point. We can make the plot look better by using color parameter. A title would be nice to have as well. fig = px.scatter_ternary(df, a="Red", b="Green", c="Blue", hover_name="Name",color="winner", color_discrete_map = {"Blue": "blue", "Green": "green", "Red":"red"},title="RGB Distribution of Colors")fig.show() The dots representing the data points (rows in the dataframe) have equal size but plotly allows to add informative power to the size of the dots as well. Let’s use one of the built-in datasets to show how the size parameter can be used. df_election = px.data.election()print(df_election.shape)df_election.head() This election datasets contain the number of votes received by three candidates in 58 districts. “Total” column includes the total number of votes in the district which I think is proportional to the population of the district. We can pass the “total” column to the size parameter and see a particular candidate are winning more of the bigger districts. fig = px.scatter_ternary(df_election, a="Joly", b="Coderre", c="Bergeron",hover_name="district",color="winner", size="total", size_max=15,title="District Election Results")fig.show() “Coderre” leads by far. The districts won by “Joly” have relatively smaller sizes. One interesting thing that I realize is that the districts won by Coderre lean towards Joly more than they lean towards Bergeron. When we hover on data points, we see that Joly is usually the second candidate. Thus, Joly might have received more votes although the districts won by Joly seem smaller. Let’s check by counting the total number of votes for each candidate. print("Total number of votes for Coderre is {}".format(df_election.Coderre.sum()))print("Total number of votes for Bergeron is {}".format(df_election.Bergeron.sum()))print("Total number of votes for Joly is {}".format(df_election.Joly.sum())) Yes! Joly has more votes than Bergeron. In addition to the size, we can also use the shape of data points to deliver information. For instance, the “result” column takes two values: We can pass this column as an argument to the symbol parameter. fig = px.scatter_ternary(df_election, a="Joly", b="Coderre", c="Bergeron",hover_name="district",color="winner", size="total", size_max=15,title="District Election Results", symbol="result")fig.show() We have an idea if a particular candidate wins by majority or plurality. We have covered ternary plots with plotly. Of course, this is just a little of what can be done with this amazing library. There are many other plot types that we can dynamically create with plotly. Its syntax is easy to understand as well. I will try to cover more complex plots in the upcoming posts. You can also check the plotly documentation which I think is well-documented with many different examples. Just like any other topic, the best way to get familiar with plotly is to practice. Thus, I suggest creating lots of plots to sharpen your skills. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 506, "s": 47, "text": "Plotly Python (plotly.py) is an open-source plotting library built on plotly javascript (plotly.js). One of the things I like about plotly.py is that it offers a high-level API (plotly express) and a low level API (graph objects) to create visualizations. With plotly express, we can create a dynamic and informative plot with very few lines of code. On the other hand, we need to write more code with graph objects but have more control over what we create." }, { "code": null, "e": 864, "s": 506, "text": "In this post, we will create ternary plots using plotly express. Ternary plots depict the ratios of three variables by positioning the data points in a triangle accordingly. It gives us an overview whether the observations lean towards a certain variable. Each corner of the triangle is labelled with one variable. Thus, we can only compare three variables." }, { "code": null, "e": 1166, "s": 864, "text": "Consider we are evaluating three car brands on lots of measurements. Each brand has a rating on each measurement. By plotting these measurements on a ternary plot, we get an idea if one brand is more dominant than others. For instance, one brand might be prominent in terms of safety related measures." }, { "code": null, "e": 1476, "s": 1166, "text": "I could not find a dataset that compares car brands in many different measures but I was able to find an interesting one which is adataset that has RGB values of colors. Each color is made up of a combination of red, green, and blue (RGB). The colors change according to the ratios of these three main colors." }, { "code": null, "e": 1818, "s": 1476, "text": "The dataset that is available here on data.world website includes RGB values for 746 different colors. I did not even know if some of those colors existed. There are some weird color names such as “Alizarin crimson”, “Bazaar”, and “Charcoal”. We will use ternary plot to get an overview about the RGB components of this wide range of colors." }, { "code": null, "e": 1894, "s": 1818, "text": "Let’s first read the dataset into a pandas dataframe and take a look at it." }, { "code": null, "e": 2002, "s": 1894, "text": "import numpy as npimport pandas as pddf = pd.read_csv(\"/content/colorhexa_com.csv\")print(df.shape)df.head()" }, { "code": null, "e": 2141, "s": 2002, "text": "For now, I’m only interested in the name of the color and RGB components so I will only take those columns and change the names of colors." }, { "code": null, "e": 2313, "s": 2141, "text": "new_cols = {'Red (8 bit)':'Red', 'Green (8 bit)':'Green', 'Blue (8 bit)':'Blue'}df.rename(columns=new_cols, inplace=True)df = df[['Name', 'Red', 'Green', 'Blue']]df.head()" }, { "code": null, "e": 2477, "s": 2313, "text": "I also want to add a marker for each color name that indicates the RGB color which contributes most. I will use nested loops but feel free to try out your own way." }, { "code": null, "e": 2733, "s": 2477, "text": "winners = []for i in range(len(df)): if df.iloc[i,1] > df.iloc[i,2] and df.iloc[i,1] > df.iloc[i,3]: winner = \"Red\" elif df.iloc[i,2] > df.iloc[i,3]: winner = \"Green\" else: winner = \"Blue\" winners.append(winner)df['winner'] = winnersdf.head()" }, { "code": null, "e": 2908, "s": 2733, "text": "Let’s first create a simple ternary plot that positions each color according to RGB component values. We will use plotly express which is the high-level API of plotly python." }, { "code": null, "e": 3023, "s": 2908, "text": "import plotly.express as pxfig = px.scatter_ternary(df, a=\"Red\", b=\"Green\", c=\"Blue\", hover_name=\"Name\")fig.show()" }, { "code": null, "e": 3345, "s": 3023, "text": "Most of the colors are around the center of triangle but there is a slight incline towards red. We also have colors located on the edges of triangle. Those colors only include two of three RGB colors. Not surprisingly, the colors on the corners contain only one component. For instance, navy blue has only blue component." }, { "code": null, "e": 3459, "s": 3345, "text": "We pass the “Name” column hover_name parameter which allow to see the name of the color when hovering on a point." }, { "code": null, "e": 3557, "s": 3459, "text": "We can make the plot look better by using color parameter. A title would be nice to have as well." }, { "code": null, "e": 3765, "s": 3557, "text": "fig = px.scatter_ternary(df, a=\"Red\", b=\"Green\", c=\"Blue\", hover_name=\"Name\",color=\"winner\", color_discrete_map = {\"Blue\": \"blue\", \"Green\": \"green\", \"Red\":\"red\"},title=\"RGB Distribution of Colors\")fig.show()" }, { "code": null, "e": 4002, "s": 3765, "text": "The dots representing the data points (rows in the dataframe) have equal size but plotly allows to add informative power to the size of the dots as well. Let’s use one of the built-in datasets to show how the size parameter can be used." }, { "code": null, "e": 4077, "s": 4002, "text": "df_election = px.data.election()print(df_election.shape)df_election.head()" }, { "code": null, "e": 4431, "s": 4077, "text": "This election datasets contain the number of votes received by three candidates in 58 districts. “Total” column includes the total number of votes in the district which I think is proportional to the population of the district. We can pass the “total” column to the size parameter and see a particular candidate are winning more of the bigger districts." }, { "code": null, "e": 4614, "s": 4431, "text": "fig = px.scatter_ternary(df_election, a=\"Joly\", b=\"Coderre\", c=\"Bergeron\",hover_name=\"district\",color=\"winner\", size=\"total\", size_max=15,title=\"District Election Results\")fig.show()" }, { "code": null, "e": 5068, "s": 4614, "text": "“Coderre” leads by far. The districts won by “Joly” have relatively smaller sizes. One interesting thing that I realize is that the districts won by Coderre lean towards Joly more than they lean towards Bergeron. When we hover on data points, we see that Joly is usually the second candidate. Thus, Joly might have received more votes although the districts won by Joly seem smaller. Let’s check by counting the total number of votes for each candidate." }, { "code": null, "e": 5311, "s": 5068, "text": "print(\"Total number of votes for Coderre is {}\".format(df_election.Coderre.sum()))print(\"Total number of votes for Bergeron is {}\".format(df_election.Bergeron.sum()))print(\"Total number of votes for Joly is {}\".format(df_election.Joly.sum()))" }, { "code": null, "e": 5351, "s": 5311, "text": "Yes! Joly has more votes than Bergeron." }, { "code": null, "e": 5493, "s": 5351, "text": "In addition to the size, we can also use the shape of data points to deliver information. For instance, the “result” column takes two values:" }, { "code": null, "e": 5557, "s": 5493, "text": "We can pass this column as an argument to the symbol parameter." }, { "code": null, "e": 5757, "s": 5557, "text": "fig = px.scatter_ternary(df_election, a=\"Joly\", b=\"Coderre\", c=\"Bergeron\",hover_name=\"district\",color=\"winner\", size=\"total\", size_max=15,title=\"District Election Results\", symbol=\"result\")fig.show()" }, { "code": null, "e": 5830, "s": 5757, "text": "We have an idea if a particular candidate wins by majority or plurality." }, { "code": null, "e": 6387, "s": 5830, "text": "We have covered ternary plots with plotly. Of course, this is just a little of what can be done with this amazing library. There are many other plot types that we can dynamically create with plotly. Its syntax is easy to understand as well. I will try to cover more complex plots in the upcoming posts. You can also check the plotly documentation which I think is well-documented with many different examples. Just like any other topic, the best way to get familiar with plotly is to practice. Thus, I suggest creating lots of plots to sharpen your skills." } ]
Apache Presto - concat(string1, ..., stringN)
presto:default> select concat('tut','orials','point') as string_concat; string_concat ---------------- tutorialspoint The above output is concatenation of the given strings. 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": 2079, "s": 2006, "text": "presto:default> select concat('tut','orials','point') as string_concat; " }, { "code": null, "e": 2131, "s": 2079, "text": " string_concat \n---------------- \n tutorialspoint \n" }, { "code": null, "e": 2187, "s": 2131, "text": "The above output is concatenation of the given strings." }, { "code": null, "e": 2222, "s": 2187, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 2241, "s": 2222, "text": " Arnab Chakraborty" }, { "code": null, "e": 2276, "s": 2241, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 2297, "s": 2276, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 2330, "s": 2297, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 2343, "s": 2330, "text": " Nilay Mehta" }, { "code": null, "e": 2378, "s": 2343, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 2396, "s": 2378, "text": " Bigdata Engineer" }, { "code": null, "e": 2429, "s": 2396, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 2447, "s": 2429, "text": " Bigdata Engineer" }, { "code": null, "e": 2480, "s": 2447, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 2498, "s": 2480, "text": " Bigdata Engineer" }, { "code": null, "e": 2505, "s": 2498, "text": " Print" }, { "code": null, "e": 2516, "s": 2505, "text": " Add Notes" } ]
Setup and use Jupyter (IPython) Notebooks on AWS | by Michael Galarnyk | Towards Data Science
A while ago, I wrote a post, “Start a Jupyter (IPython) Notebook Server on AWS”. While that approach allows for multiple people to access the server with just a password, it suffers from being complicated to setup. Most people just want to use a Jupyter Notebook using their AWS resources without the hassle. With that, here is how you do it. Starting a Jupyter Notebook on AWS SSH to your EC2 instance. If you don’t know how to do this or would like a reference, please see this tutorial. SSH to your EC2 instance. If you don’t know how to do this or would like a reference, please see this tutorial. 2. Make sure you have installed Anaconda. If you don’t have it installed, you do it using this tutorial. 3. Type the following command in your terminal: jupyter notebook --no-browser --port=8888 The reason why we add “ — no-browser” is because if we don’t, you might get an error like “Jupyter Notebook requires JavaScript”. Having said that, if you get that error, you can ignore the error by pressing Q and then press Y to confirm. SSH to your Jupyter Notebook 4. Open a new terminal and SSH to your Jupyter Notebook. Your command should be similar to the one below. If you don’t know how to do this, please see tutorial. ssh -i thisIsmyKey.pem -L 8000:localhost:8888 ubuntu@ec2–34–227–222–100.compute-1.amazonaws.com -i Specifies an alternate identification file to use for public key authentication. Basically for this tutorial, I have my key in current directory. -L specifies that the given port on the local (client) host is to be forwarded to the given host and port on the remote side (AWS). This means that whatever is running on the second port number (i.e. 8888) on AWS will appear on the first port number (i.e. 8000) on your local computer. You should change 8888 to the port which Jupyter Notebook is running on. 99.9% of the time Jupyter will run on port 8888. Optionally change port 8000 to one of your choosing (for example, if 8000 is used by another process). 5. Open your browser and go to localhost:8000 6. (Optional) If you want to use different conda environments (including the ability to access both Python 2 and Python 3 environments in Jupyter Notebooks, please see this tutorial). Please let me know if you have any questions either here, on the youtube video page, or through Twitter!
[ { "code": null, "e": 514, "s": 171, "text": "A while ago, I wrote a post, “Start a Jupyter (IPython) Notebook Server on AWS”. While that approach allows for multiple people to access the server with just a password, it suffers from being complicated to setup. Most people just want to use a Jupyter Notebook using their AWS resources without the hassle. With that, here is how you do it." }, { "code": null, "e": 549, "s": 514, "text": "Starting a Jupyter Notebook on AWS" }, { "code": null, "e": 661, "s": 549, "text": "SSH to your EC2 instance. If you don’t know how to do this or would like a reference, please see this tutorial." }, { "code": null, "e": 773, "s": 661, "text": "SSH to your EC2 instance. If you don’t know how to do this or would like a reference, please see this tutorial." }, { "code": null, "e": 878, "s": 773, "text": "2. Make sure you have installed Anaconda. If you don’t have it installed, you do it using this tutorial." }, { "code": null, "e": 926, "s": 878, "text": "3. Type the following command in your terminal:" }, { "code": null, "e": 968, "s": 926, "text": "jupyter notebook --no-browser --port=8888" }, { "code": null, "e": 1207, "s": 968, "text": "The reason why we add “ — no-browser” is because if we don’t, you might get an error like “Jupyter Notebook requires JavaScript”. Having said that, if you get that error, you can ignore the error by pressing Q and then press Y to confirm." }, { "code": null, "e": 1236, "s": 1207, "text": "SSH to your Jupyter Notebook" }, { "code": null, "e": 1397, "s": 1236, "text": "4. Open a new terminal and SSH to your Jupyter Notebook. Your command should be similar to the one below. If you don’t know how to do this, please see tutorial." }, { "code": null, "e": 1493, "s": 1397, "text": "ssh -i thisIsmyKey.pem -L 8000:localhost:8888 ubuntu@ec2–34–227–222–100.compute-1.amazonaws.com" }, { "code": null, "e": 1642, "s": 1493, "text": "-i Specifies an alternate identification file to use for public key authentication. Basically for this tutorial, I have my key in current directory." }, { "code": null, "e": 2153, "s": 1642, "text": "-L specifies that the given port on the local (client) host is to be forwarded to the given host and port on the remote side (AWS). This means that whatever is running on the second port number (i.e. 8888) on AWS will appear on the first port number (i.e. 8000) on your local computer. You should change 8888 to the port which Jupyter Notebook is running on. 99.9% of the time Jupyter will run on port 8888. Optionally change port 8000 to one of your choosing (for example, if 8000 is used by another process)." }, { "code": null, "e": 2199, "s": 2153, "text": "5. Open your browser and go to localhost:8000" }, { "code": null, "e": 2383, "s": 2199, "text": "6. (Optional) If you want to use different conda environments (including the ability to access both Python 2 and Python 3 environments in Jupyter Notebooks, please see this tutorial)." } ]
Node.js - Domain Module
Node.js domain module is used to intercept unhandled error. These unhandled error can be intercepted using internal binding or external binding. If errors are not handled at all, then they will simply crash the Node application. Internal Binding − Error emitter is executing its code within the run method of a domain. Internal Binding − Error emitter is executing its code within the run method of a domain. External Binding − Error emitter is added explicitly to a domain using its add method. External Binding − Error emitter is added explicitly to a domain using its add method. This module can be imported using the following syntax. var domain = require("domain") The domain class of domain module is used to provide functionality of routing errors and uncaught exceptions to the active Domain object. It is a child class of EventEmitter. To handle the errors that it catches, listen to its error event. It is created using the following syntax − var domain = require("domain"); var child = domain.create(); domain.run(function) Run the supplied function in the context of the domain, implicitly binding all event emitters, timers, and lowl evel requests that are created in that context. This is the most basic way to use a domain. domain.add(emitter) Explicitly adds an emitter to the domain. If any event handlers called by the emitter throw an error, or if the emitter emits an error event, it will be routed to the domain's error event, just like with implicit binding. domain.remove(emitter) The opposite of domain.add(emitter). Removes domain handling from the specified emitter. domain.bind(callback) The returned function will be a wrapper around the supplied callback function. When the returned function is called, any errors that are thrown will be routed to the domain's error event. domain.intercept(callback) This method is almost identical to domain.bind(callback). However, in addition to catching thrown errors, it will also intercept Error objects sent as the first argument to the function. domain.enter() The enter method is plumbing used by the run, bind, and intercept methods to set the active domain. It sets domain.active and process.domain to the domain, and implicitly pushes the domain onto the domain stack managed by the domain module (see domain.exit() for details on the domain stack). The call to enter delimits the beginning of a chain of asynchronous calls and I/O operations bound to a domain. domain.exit() The exit method exits the current domain, popping it off the domain stack. Whenever the execution switches to the context of a different chain of asynchronous calls, it's important to ensure that the current domain is exited. The call to exit delimits either the end of or an interruption to the chain of asynchronous calls and I/O operations bound to a domain. domain.dispose() Once dispose has been called, the domain will no longer be used by callbacks bound into the domain via run, bind, or intercept, and a dispose event is emit domain.members An array of timers and event emitters that have been explicitly added to the domain. Create a js file named main.js with the following code − var EventEmitter = require("events").EventEmitter; var domain = require("domain"); var emitter1 = new EventEmitter(); // Create a domain var domain1 = domain.create(); domain1.on('error', function(err) { console.log("domain1 handled this error ("+err.message+")"); }); // Explicit binding domain1.add(emitter1); emitter1.on('error',function(err) { console.log("listener handled this error ("+err.message+")"); }); emitter1.emit('error',new Error('To be handled by listener')); emitter1.removeAllListeners('error'); emitter1.emit('error',new Error('To be handled by domain1')); var domain2 = domain.create(); domain2.on('error', function(err) { console.log("domain2 handled this error ("+err.message+")"); }); // Implicit binding domain2.run(function() { var emitter2 = new EventEmitter(); emitter2.emit('error',new Error('To be handled by domain2')); }); domain1.remove(emitter1); emitter1.emit('error', new Error('Converted to exception. System will crash!')); Now run the main.js to see the result − $ node main.js Verify the Output. listener handled this error (To be handled by listener) domain1 handled this error (To be handled by domain1) domain2 handled this error (To be handled by domain2) events.js:72 throw er; // Unhandled 'error' event ^ Error: Converted to exception. System will crash! at Object. (/web/com/1427722220_30772/main.js:40:24) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Function.Module.runMain (module.js:497:10) at startup (node.js:119:16) at node.js:906:3 44 Lectures 7.5 hours Eduonix Learning Solutions 88 Lectures 17 hours Eduonix Learning Solutions 32 Lectures 1.5 hours Richard Wells 8 Lectures 33 mins Anant Rungta 9 Lectures 2.5 hours SHIVPRASAD KOIRALA 97 Lectures 6 hours Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2247, "s": 2018, "text": "Node.js domain module is used to intercept unhandled error. These unhandled error can be intercepted using internal binding or external binding. If errors are not handled at all, then they will simply crash the Node application." }, { "code": null, "e": 2337, "s": 2247, "text": "Internal Binding − Error emitter is executing its code within the run method of a domain." }, { "code": null, "e": 2427, "s": 2337, "text": "Internal Binding − Error emitter is executing its code within the run method of a domain." }, { "code": null, "e": 2514, "s": 2427, "text": "External Binding − Error emitter is added explicitly to a domain using its add method." }, { "code": null, "e": 2601, "s": 2514, "text": "External Binding − Error emitter is added explicitly to a domain using its add method." }, { "code": null, "e": 2657, "s": 2601, "text": "This module can be imported using the following syntax." }, { "code": null, "e": 2689, "s": 2657, "text": "var domain = require(\"domain\")\n" }, { "code": null, "e": 2972, "s": 2689, "text": "The domain class of domain module is used to provide functionality of routing errors and uncaught exceptions to the active Domain object. It is a child class of EventEmitter. To handle the errors that it catches, listen to its error event. It is created using the following syntax −" }, { "code": null, "e": 3034, "s": 2972, "text": "var domain = require(\"domain\");\nvar child = domain.create();\n" }, { "code": null, "e": 3055, "s": 3034, "text": "domain.run(function)" }, { "code": null, "e": 3259, "s": 3055, "text": "Run the supplied function in the context of the domain, implicitly binding all event emitters, timers, and lowl evel requests that are created in that context. This is the most basic way to use a domain." }, { "code": null, "e": 3279, "s": 3259, "text": "domain.add(emitter)" }, { "code": null, "e": 3501, "s": 3279, "text": "Explicitly adds an emitter to the domain. If any event handlers called by the emitter throw an error, or if the emitter emits an error event, it will be routed to the domain's error event, just like with implicit binding." }, { "code": null, "e": 3524, "s": 3501, "text": "domain.remove(emitter)" }, { "code": null, "e": 3613, "s": 3524, "text": "The opposite of domain.add(emitter). Removes domain handling from the specified emitter." }, { "code": null, "e": 3635, "s": 3613, "text": "domain.bind(callback)" }, { "code": null, "e": 3823, "s": 3635, "text": "The returned function will be a wrapper around the supplied callback function. When the returned function is called, any errors that are thrown will be routed to the domain's error event." }, { "code": null, "e": 3850, "s": 3823, "text": "domain.intercept(callback)" }, { "code": null, "e": 4037, "s": 3850, "text": "This method is almost identical to domain.bind(callback). However, in addition to catching thrown errors, it will also intercept Error objects sent as the first argument to the function." }, { "code": null, "e": 4052, "s": 4037, "text": "domain.enter()" }, { "code": null, "e": 4457, "s": 4052, "text": "The enter method is plumbing used by the run, bind, and intercept methods to set the active domain. It sets domain.active and process.domain to the domain, and implicitly pushes the domain onto the domain stack managed by the domain module (see domain.exit() for details on the domain stack). The call to enter delimits the beginning of a chain of asynchronous calls and I/O operations bound to a domain." }, { "code": null, "e": 4471, "s": 4457, "text": "domain.exit()" }, { "code": null, "e": 4833, "s": 4471, "text": "The exit method exits the current domain, popping it off the domain stack. Whenever the execution switches to the context of a different chain of asynchronous calls, it's important to ensure that the current domain is exited. The call to exit delimits either the end of or an interruption to the chain of asynchronous calls and I/O operations bound to a domain." }, { "code": null, "e": 4850, "s": 4833, "text": "domain.dispose()" }, { "code": null, "e": 5006, "s": 4850, "text": "Once dispose has been called, the domain will no longer be used by callbacks bound into the domain via run, bind, or intercept, and a dispose event is emit" }, { "code": null, "e": 5021, "s": 5006, "text": "domain.members" }, { "code": null, "e": 5106, "s": 5021, "text": "An array of timers and event emitters that have been explicitly added to the domain." }, { "code": null, "e": 5163, "s": 5106, "text": "Create a js file named main.js with the following code −" }, { "code": null, "e": 6154, "s": 5163, "text": "var EventEmitter = require(\"events\").EventEmitter;\nvar domain = require(\"domain\");\n\nvar emitter1 = new EventEmitter();\n\n// Create a domain\nvar domain1 = domain.create();\n\ndomain1.on('error', function(err) {\n console.log(\"domain1 handled this error (\"+err.message+\")\");\n});\n\n// Explicit binding \ndomain1.add(emitter1);\n\nemitter1.on('error',function(err) {\n console.log(\"listener handled this error (\"+err.message+\")\");\n});\n\nemitter1.emit('error',new Error('To be handled by listener'));\nemitter1.removeAllListeners('error');\nemitter1.emit('error',new Error('To be handled by domain1'));\n\nvar domain2 = domain.create();\n\ndomain2.on('error', function(err) {\n console.log(\"domain2 handled this error (\"+err.message+\")\");\n});\n\n// Implicit binding\ndomain2.run(function() {\n var emitter2 = new EventEmitter();\n emitter2.emit('error',new Error('To be handled by domain2')); \n});\n\ndomain1.remove(emitter1);\nemitter1.emit('error', new Error('Converted to exception. System will crash!'));" }, { "code": null, "e": 6194, "s": 6154, "text": "Now run the main.js to see the result −" }, { "code": null, "e": 6210, "s": 6194, "text": "$ node main.js\n" }, { "code": null, "e": 6229, "s": 6210, "text": "Verify the Output." }, { "code": null, "e": 6842, "s": 6229, "text": "listener handled this error (To be handled by listener)\ndomain1 handled this error (To be handled by domain1)\ndomain2 handled this error (To be handled by domain2)\n\nevents.js:72 throw er; // Unhandled 'error' event\n ^\nError: Converted to exception. System will crash!\n at Object. (/web/com/1427722220_30772/main.js:40:24)\n at Module._compile (module.js:456:26)\n at Object.Module._extensions..js (module.js:474:10)\n at Module.load (module.js:356:32)\n at Function.Module._load (module.js:312:12)\n at Function.Module.runMain (module.js:497:10)\n at startup (node.js:119:16)\n at node.js:906:3\n" }, { "code": null, "e": 6877, "s": 6842, "text": "\n 44 Lectures \n 7.5 hours \n" }, { "code": null, "e": 6905, "s": 6877, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6939, "s": 6905, "text": "\n 88 Lectures \n 17 hours \n" }, { "code": null, "e": 6967, "s": 6939, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 7002, "s": 6967, "text": "\n 32 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7017, "s": 7002, "text": " Richard Wells" }, { "code": null, "e": 7048, "s": 7017, "text": "\n 8 Lectures \n 33 mins\n" }, { "code": null, "e": 7062, "s": 7048, "text": " Anant Rungta" }, { "code": null, "e": 7096, "s": 7062, "text": "\n 9 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7116, "s": 7096, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 7149, "s": 7116, "text": "\n 97 Lectures \n 6 hours \n" }, { "code": null, "e": 7169, "s": 7149, "text": " Skillbakerystudios" }, { "code": null, "e": 7176, "s": 7169, "text": " Print" }, { "code": null, "e": 7187, "s": 7176, "text": " Add Notes" } ]
Explain Merge Sort in Python
Merge sort is a sorting technique. It is an efficient sorting algorithm with a time complexity of (n logn) where n is the length of the array to be sorted. Merge sort is an algorithm that follows the Divide and Conquers paradigm. It continuously divides the array into two equal halves. Later it starts sorting the lists having a single element each and continuously merges the sorted lists to form the complete sorted list. Hence, we obtain a sorted array. Example The purple boxes and black arrows show the splitting of the list into two halves. The green boxes and red arrows show the merging of the two sorted lists. Splitting the list into two halves is quite easy and it is done recursively until we have only one element left. Later the merging procedure is done which is actually where we apply the logic of merging the two sorted lists together. The merge function takes the two sorted arrays to be merged. The frontmost element of a1 is compared with the frontmost element of a2. The smallest of two is added to list c and the pointer of that array is incremented. Live Demo def merge(a1,a2): c=[] x=0 y=0 while(x<len(a1) and y<len(a2)): if(a1[x]<a2[y]): c.append(a1[x]) x+=1 else: c.append(a2[y]) y+=1 while(x<len(a1)): c.append(a1[x]) x+=1 while(y<len(a2)): c.append(a2[y]) y+=1 return c def mergesort(array): if(len(array)==1): return array mid=(len(array))//2 a1=mergesort(array[:mid]) a2=mergesort(array[mid:]) return merge(a1,a2) array=[2,3,1,5,4,6,8,10,7,9] print(mergesort(array)) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[ { "code": null, "e": 1218, "s": 1062, "text": "Merge sort is a sorting technique. It is an efficient sorting algorithm with a time complexity of (n logn) where n is the length of the array to be sorted." }, { "code": null, "e": 1487, "s": 1218, "text": "Merge sort is an algorithm that follows the Divide and Conquers paradigm. It continuously divides the array into two equal halves. Later it starts sorting the lists having a single element each and continuously merges the sorted lists to form the complete sorted list." }, { "code": null, "e": 1520, "s": 1487, "text": "Hence, we obtain a sorted array." }, { "code": null, "e": 1528, "s": 1520, "text": "Example" }, { "code": null, "e": 1610, "s": 1528, "text": "The purple boxes and black arrows show the splitting of the list into two halves." }, { "code": null, "e": 1683, "s": 1610, "text": "The green boxes and red arrows show the merging of the two sorted lists." }, { "code": null, "e": 1917, "s": 1683, "text": "Splitting the list into two halves is quite easy and it is done recursively until we have only one element left. Later the merging procedure is done which is actually where we apply the logic of merging the two sorted lists together." }, { "code": null, "e": 2137, "s": 1917, "text": "The merge function takes the two sorted arrays to be merged. The frontmost element of a1 is compared with the frontmost element of a2. The smallest of two is added to list c and the pointer of that array is incremented." }, { "code": null, "e": 2148, "s": 2137, "text": " Live Demo" }, { "code": null, "e": 2677, "s": 2148, "text": "def merge(a1,a2):\n c=[]\n x=0\n y=0\n while(x<len(a1) and y<len(a2)):\n if(a1[x]<a2[y]):\n c.append(a1[x])\n x+=1\n else:\n c.append(a2[y])\n y+=1\n while(x<len(a1)):\n c.append(a1[x])\n x+=1\n while(y<len(a2)):\n c.append(a2[y])\n y+=1\n return c\n\ndef mergesort(array):\n if(len(array)==1):\n return array\n mid=(len(array))//2\n a1=mergesort(array[:mid])\n a2=mergesort(array[mid:])\n return merge(a1,a2)\narray=[2,3,1,5,4,6,8,10,7,9]\nprint(mergesort(array))" }, { "code": null, "e": 2709, "s": 2677, "text": "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" } ]
How to get the value of custom attribute in jQuery?
To get the value in jQuery, use the data-attributes with the data() method. You can try to run the following code to implement how to get the value of custom attribute: Live Demo <html> <head> <title>Selector Example</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function() { alert($('#my_id').data('original-title')); }); </script> </head> <body> <strong id="my_id" data-original-title="Hello">Demo</strong> </body> </html>
[ { "code": null, "e": 1231, "s": 1062, "text": "To get the value in jQuery, use the data-attributes with the data() method. You can try to run the following code to implement how to get the value of custom attribute:" }, { "code": null, "e": 1241, "s": 1231, "text": "Live Demo" }, { "code": null, "e": 1650, "s": 1241, "text": "<html>\n <head>\n <title>Selector Example</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n <script>\n\n $(document).ready(function() {\n alert($('#my_id').data('original-title'));\n });\n \n </script>\n </head>\n <body>\n <strong id=\"my_id\" data-original-title=\"Hello\">Demo</strong>\n </body>\n</html>" } ]
How to Change Axis Scales in R Plots? - GeeksforGeeks
19 Dec, 2021 In this article, we will learn how to change Axis Scales in the R Programming Language. To change the axis scales on a plot in base R Language, we can use the xlim() and ylim() functions. The xlim() and ylim() functions are convenience functions that set the limit of the x-axis and y-axis respectively. This function takes a vector as an argument which contains the values of lower axis limit and higher axis limit. Syntax: plot( df$xaxis, df$yaxis, xlim, ylim) where, df: determines the data frame in use. xaxis and yaxis: determine the axis variables for plotting. xlim: determines the vector that contains x-axis limits. ylim: determines the vector that contains y-axis limits. Example: Basic example where plot axis limits are set from 0 to 2 for the x-axis and from 18 to 20 for the y-axis. R # create sample data framesample_data <- data.frame(x=rnorm(100), y=rnorm(100)+20) # create plot with custom axis scalesplot(sample_data$x, sample_data$y, xlim=c(0,2), ylim=c(18,20)) Output: Output To convert the axis scale log scale in the base R plot, we use the log argument of the plot() function. The log argument converts the given axis into its log scale alternative. This helps us in visualizing the skew data frames. Syntax: plot( df$xaxis, df$yaxis, log) where, df: determines the data frame in use. xaxis and yaxis: determine the axis variables for plotting. log: determines the axis which has to be converted in log scale. Example: Basic example where the x-axis has been converted to its log scale alternative. R # create sample data framesample_data <- data.frame(x=rnorm(100), y=rnorm(100)+20) # create plot with log x-axis scaleplot(sample_data$x, sample_data$y, log='x') Output: Output To change the axis scales on a plot made using the ggplot2 package in the R Language, we can use the xlim() and ylim() functions. These functions can be used along with the ggplot() function by adding them using plus(+) symbol The xlim() and ylim() functions are convenience functions that set the limit of the x-axis and y-axis respectively. This function takes a vector as an argument which contains the values of lower axis limit and higher axis limit. Syntax: ggplot() + xlim() +ylim() where, xlim(): takes two values as input that are lower x-axis limit and higher x-axis limit. ylim(): takes two values as input that are lower y-axis limit and higher y-axis limit. Example: Here, is a basic example of a ggplot2 plot where plot axis limits are set from 0 to 2 for the x-axis and from 18 to 20 for the y-axis. R # load library ggplot2library(ggplot2) # create sample data framesample_data <- data.frame(x=rnorm(100), y=rnorm(100)+20) # create plot with custom axis scalesggplot(sample_data, aes(x=x, y=y))+ geom_point()+ xlim(0,2)+ ylim(18,20) Output: Output To convert the axis scale log scale in the R plot made using the ggplot2 package, we use the scale_y_continuous() and scale_y_continuous() functions along with the trans argument for the x-axis and the y-axis transformation respectively. The trans argument takes a logarithmic identifier as an argument and then converts the axis into the given log scale alternative. This helps us in visualizing the skew data frames. Syntax: plot + scale_x_continuous( trans ) + scale_y_continuous( trans ) where, trans: determines the exact log scale for transformation Example: Basic example of a ggplot2 plot where the x-axis has been converted to its log scale alternative. R # load library ggplot2library(ggplot2) # create sample data framesample_data <- data.frame(x=rnorm(100), y=rnorm(100)+20) # create plot with log x-axis sclaeggplot(sample_data, aes(x=x, y=y))+ geom_point()+ scale_x_continuous( trans= 'log10') Output: Output Picked R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Replace specific values in column in R DataFrame ? Loops in R (for, while, repeat) Filter data by multiple conditions in R using Dplyr How to change Row Names of DataFrame in R ? Change Color of Bars in Barchart using ggplot2 in R Printing Output of an R Program Remove rows with NA in one column of R DataFrame How to Split Column Into Multiple Columns in R DataFrame? K-Means Clustering in R Programming Creating a Data Frame from Vectors in R Programming
[ { "code": null, "e": 24672, "s": 24644, "text": "\n19 Dec, 2021" }, { "code": null, "e": 24760, "s": 24672, "text": "In this article, we will learn how to change Axis Scales in the R Programming Language." }, { "code": null, "e": 25089, "s": 24760, "text": "To change the axis scales on a plot in base R Language, we can use the xlim() and ylim() functions. The xlim() and ylim() functions are convenience functions that set the limit of the x-axis and y-axis respectively. This function takes a vector as an argument which contains the values of lower axis limit and higher axis limit." }, { "code": null, "e": 25135, "s": 25089, "text": "Syntax: plot( df$xaxis, df$yaxis, xlim, ylim)" }, { "code": null, "e": 25142, "s": 25135, "text": "where," }, { "code": null, "e": 25180, "s": 25142, "text": "df: determines the data frame in use." }, { "code": null, "e": 25240, "s": 25180, "text": "xaxis and yaxis: determine the axis variables for plotting." }, { "code": null, "e": 25297, "s": 25240, "text": "xlim: determines the vector that contains x-axis limits." }, { "code": null, "e": 25354, "s": 25297, "text": "ylim: determines the vector that contains y-axis limits." }, { "code": null, "e": 25469, "s": 25354, "text": "Example: Basic example where plot axis limits are set from 0 to 2 for the x-axis and from 18 to 20 for the y-axis." }, { "code": null, "e": 25471, "s": 25469, "text": "R" }, { "code": "# create sample data framesample_data <- data.frame(x=rnorm(100), y=rnorm(100)+20) # create plot with custom axis scalesplot(sample_data$x, sample_data$y, xlim=c(0,2), ylim=c(18,20))", "e": 25684, "s": 25471, "text": null }, { "code": null, "e": 25692, "s": 25684, "text": "Output:" }, { "code": null, "e": 25699, "s": 25692, "text": "Output" }, { "code": null, "e": 25927, "s": 25699, "text": "To convert the axis scale log scale in the base R plot, we use the log argument of the plot() function. The log argument converts the given axis into its log scale alternative. This helps us in visualizing the skew data frames." }, { "code": null, "e": 25966, "s": 25927, "text": "Syntax: plot( df$xaxis, df$yaxis, log)" }, { "code": null, "e": 25973, "s": 25966, "text": "where," }, { "code": null, "e": 26011, "s": 25973, "text": "df: determines the data frame in use." }, { "code": null, "e": 26071, "s": 26011, "text": "xaxis and yaxis: determine the axis variables for plotting." }, { "code": null, "e": 26136, "s": 26071, "text": "log: determines the axis which has to be converted in log scale." }, { "code": null, "e": 26225, "s": 26136, "text": "Example: Basic example where the x-axis has been converted to its log scale alternative." }, { "code": null, "e": 26227, "s": 26225, "text": "R" }, { "code": "# create sample data framesample_data <- data.frame(x=rnorm(100), y=rnorm(100)+20) # create plot with log x-axis scaleplot(sample_data$x, sample_data$y, log='x')", "e": 26415, "s": 26227, "text": null }, { "code": null, "e": 26423, "s": 26415, "text": "Output:" }, { "code": null, "e": 26430, "s": 26423, "text": "Output" }, { "code": null, "e": 26886, "s": 26430, "text": "To change the axis scales on a plot made using the ggplot2 package in the R Language, we can use the xlim() and ylim() functions. These functions can be used along with the ggplot() function by adding them using plus(+) symbol The xlim() and ylim() functions are convenience functions that set the limit of the x-axis and y-axis respectively. This function takes a vector as an argument which contains the values of lower axis limit and higher axis limit." }, { "code": null, "e": 26894, "s": 26886, "text": "Syntax:" }, { "code": null, "e": 26920, "s": 26894, "text": "ggplot() + xlim() +ylim()" }, { "code": null, "e": 26927, "s": 26920, "text": "where," }, { "code": null, "e": 27014, "s": 26927, "text": "xlim(): takes two values as input that are lower x-axis limit and higher x-axis limit." }, { "code": null, "e": 27101, "s": 27014, "text": "ylim(): takes two values as input that are lower y-axis limit and higher y-axis limit." }, { "code": null, "e": 27110, "s": 27101, "text": "Example:" }, { "code": null, "e": 27245, "s": 27110, "text": "Here, is a basic example of a ggplot2 plot where plot axis limits are set from 0 to 2 for the x-axis and from 18 to 20 for the y-axis." }, { "code": null, "e": 27247, "s": 27245, "text": "R" }, { "code": "# load library ggplot2library(ggplot2) # create sample data framesample_data <- data.frame(x=rnorm(100), y=rnorm(100)+20) # create plot with custom axis scalesggplot(sample_data, aes(x=x, y=y))+ geom_point()+ xlim(0,2)+ ylim(18,20)", "e": 27527, "s": 27247, "text": null }, { "code": null, "e": 27535, "s": 27527, "text": "Output:" }, { "code": null, "e": 27542, "s": 27535, "text": "Output" }, { "code": null, "e": 27961, "s": 27542, "text": "To convert the axis scale log scale in the R plot made using the ggplot2 package, we use the scale_y_continuous() and scale_y_continuous() functions along with the trans argument for the x-axis and the y-axis transformation respectively. The trans argument takes a logarithmic identifier as an argument and then converts the axis into the given log scale alternative. This helps us in visualizing the skew data frames." }, { "code": null, "e": 28034, "s": 27961, "text": "Syntax: plot + scale_x_continuous( trans ) + scale_y_continuous( trans )" }, { "code": null, "e": 28098, "s": 28034, "text": "where, trans: determines the exact log scale for transformation" }, { "code": null, "e": 28205, "s": 28098, "text": "Example: Basic example of a ggplot2 plot where the x-axis has been converted to its log scale alternative." }, { "code": null, "e": 28207, "s": 28205, "text": "R" }, { "code": "# load library ggplot2library(ggplot2) # create sample data framesample_data <- data.frame(x=rnorm(100), y=rnorm(100)+20) # create plot with log x-axis sclaeggplot(sample_data, aes(x=x, y=y))+ geom_point()+ scale_x_continuous( trans= 'log10')", "e": 28491, "s": 28207, "text": null }, { "code": null, "e": 28499, "s": 28491, "text": "Output:" }, { "code": null, "e": 28506, "s": 28499, "text": "Output" }, { "code": null, "e": 28513, "s": 28506, "text": "Picked" }, { "code": null, "e": 28524, "s": 28513, "text": "R Language" }, { "code": null, "e": 28622, "s": 28524, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28631, "s": 28622, "text": "Comments" }, { "code": null, "e": 28644, "s": 28631, "text": "Old Comments" }, { "code": null, "e": 28702, "s": 28644, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 28734, "s": 28702, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 28786, "s": 28734, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 28830, "s": 28786, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 28882, "s": 28830, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 28914, "s": 28882, "text": "Printing Output of an R Program" }, { "code": null, "e": 28963, "s": 28914, "text": "Remove rows with NA in one column of R DataFrame" }, { "code": null, "e": 29021, "s": 28963, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29057, "s": 29021, "text": "K-Means Clustering in R Programming" } ]
World Population from 1955 to 2020 Bar Chart Race | by Durgesh Samariya | Towards Data Science
Welcome back to my 100 Days of Data Science Challenge Journey. On day 6, I worked on Bar Chart Race Animation using Python. For today’s task, I will be using the Countries Population from 1955 to 2020 dataset available on Kaggle. You can read my previous days stories here: towardsdatascience.com Recently, I come across a medium post on announcement off Official Release of bar_chart_race by Ted Petrou. In his article, he provides an excellent tutorial on how to create Bar Chart Race using bar_chart_race package. Check out the official document here. Installation of Bar Chart Race package Import required libraries Loading Data Creating Bar Chart Race Install with pip: pip3 install bar_chart_race or using anaconda: conda install -c conda-forge bar_chart_race For this project, we only need Pandas, Bar_Chart_Race libraries. # to load dataimport pandas as pd#bar chart raceimport bar_chart_race as bcr %time population = pd.read_csv('./data/Countries Population from 1995 to 2020.csv') In bar chart race, your data must be in a specific format: each entry represents a single time each feature have some single particular value time should be set as .index Let’s have a look at how our data is looking. population.head() So it’s clear that our data is not in the appropriate format to feed in bar_chart_race. First, make relevant changes in data. Step 1 — Remove all columns except Year, Country, and Population. pop = population.drop(['Yearly % Change', 'Yearly Change', 'Migrants (net)', 'Median Age', 'Fertility Rate', 'Density (P/Km2)', 'Urban Pop %', 'Urban Population', 'Country\'s Share of World Pop %', 'World Population', 'Country Global Rank' ], axis = 1) Step 2 — Create pivot_table from the pop data frame where Year is an index; each country as column and Population as value. df = pop.pivot_table('Population',['Year'], 'Country') Sometimes your data is not in order, so make sure you order the time column. In our case, its Year. df.sort_values(list(df.columns),inplace=True)df = df.sort_index()df Now our data is ready, so let’s create a bar chart race. You can simply use .bar_chart_race()method from bcr. bcr.bar_chart_race(df) The above give step is very simple and not as attractive as I want. So let’s customize it. Let’s have a look at the final code. You can find all features and different possibilities in bar_chart_plot documentation. bcr.bar_chart_race( df=df, filename=None, orientation='h', sort='desc', n_bars=10, fixed_order=False, fixed_max=True, steps_per_period=10, interpolate_period=False, label_bars=True, bar_size=.90, period_label={'x': .99, 'y': .25, 'ha': 'right', 'va':'center'}, period_summary_func=lambda v, r: {'x': .99, 'y': .18, 's': f'Population{v.nlargest(39).sum():,.0f}', 'ha': 'right', 'size': 8, 'family': 'Courier New'}, period_length=500, figsize=(6.5,5), dpi=144, cmap='dark12', title='Population by Country', title_size='', bar_label_size=7, tick_label_size=5, shared_fontdict={'family' : 'Helvetica','color' : '.1'}, scale='linear', writer=None, fig=None, bar_kwargs={'alpha': .7}, filter_column_colors=True) I would like to thanks Ted Petrou for creating such a great library and Tutorials. Apart from that, thanks to Vinay Shaw — author of this kernel, who introduced me to this beautiful library. That’s it for today. Today, I learned and created my first bar chart race visualization. In future looking forward to create something interesting from it. I hope this article was helpful to you. All the codes of data analysis and visuals can be found at this GitHub repository or Kaggle kernel. Thanks for reading. I appreciate any feedback. towardsdatascience.com If you like my work and want to support me, I’d greatly appreciate it if you follow me on my social media channels: The best way to support me is by following me on Medium. Subscribe to my new YouTube channel. Sign up on my email list.
[ { "code": null, "e": 402, "s": 172, "text": "Welcome back to my 100 Days of Data Science Challenge Journey. On day 6, I worked on Bar Chart Race Animation using Python. For today’s task, I will be using the Countries Population from 1955 to 2020 dataset available on Kaggle." }, { "code": null, "e": 446, "s": 402, "text": "You can read my previous days stories here:" }, { "code": null, "e": 469, "s": 446, "text": "towardsdatascience.com" }, { "code": null, "e": 727, "s": 469, "text": "Recently, I come across a medium post on announcement off Official Release of bar_chart_race by Ted Petrou. In his article, he provides an excellent tutorial on how to create Bar Chart Race using bar_chart_race package. Check out the official document here." }, { "code": null, "e": 766, "s": 727, "text": "Installation of Bar Chart Race package" }, { "code": null, "e": 792, "s": 766, "text": "Import required libraries" }, { "code": null, "e": 805, "s": 792, "text": "Loading Data" }, { "code": null, "e": 829, "s": 805, "text": "Creating Bar Chart Race" }, { "code": null, "e": 847, "s": 829, "text": "Install with pip:" }, { "code": null, "e": 875, "s": 847, "text": "pip3 install bar_chart_race" }, { "code": null, "e": 894, "s": 875, "text": "or using anaconda:" }, { "code": null, "e": 938, "s": 894, "text": "conda install -c conda-forge bar_chart_race" }, { "code": null, "e": 1003, "s": 938, "text": "For this project, we only need Pandas, Bar_Chart_Race libraries." }, { "code": null, "e": 1080, "s": 1003, "text": "# to load dataimport pandas as pd#bar chart raceimport bar_chart_race as bcr" }, { "code": null, "e": 1164, "s": 1080, "text": "%time population = pd.read_csv('./data/Countries Population from 1995 to 2020.csv')" }, { "code": null, "e": 1223, "s": 1164, "text": "In bar chart race, your data must be in a specific format:" }, { "code": null, "e": 1259, "s": 1223, "text": "each entry represents a single time" }, { "code": null, "e": 1306, "s": 1259, "text": "each feature have some single particular value" }, { "code": null, "e": 1335, "s": 1306, "text": "time should be set as .index" }, { "code": null, "e": 1381, "s": 1335, "text": "Let’s have a look at how our data is looking." }, { "code": null, "e": 1399, "s": 1381, "text": "population.head()" }, { "code": null, "e": 1525, "s": 1399, "text": "So it’s clear that our data is not in the appropriate format to feed in bar_chart_race. First, make relevant changes in data." }, { "code": null, "e": 1591, "s": 1525, "text": "Step 1 — Remove all columns except Year, Country, and Population." }, { "code": null, "e": 1844, "s": 1591, "text": "pop = population.drop(['Yearly % Change', 'Yearly Change', 'Migrants (net)', 'Median Age', 'Fertility Rate', 'Density (P/Km2)', 'Urban Pop %', 'Urban Population', 'Country\\'s Share of World Pop %', 'World Population', 'Country Global Rank' ], axis = 1)" }, { "code": null, "e": 1968, "s": 1844, "text": "Step 2 — Create pivot_table from the pop data frame where Year is an index; each country as column and Population as value." }, { "code": null, "e": 2023, "s": 1968, "text": "df = pop.pivot_table('Population',['Year'], 'Country')" }, { "code": null, "e": 2123, "s": 2023, "text": "Sometimes your data is not in order, so make sure you order the time column. In our case, its Year." }, { "code": null, "e": 2191, "s": 2123, "text": "df.sort_values(list(df.columns),inplace=True)df = df.sort_index()df" }, { "code": null, "e": 2248, "s": 2191, "text": "Now our data is ready, so let’s create a bar chart race." }, { "code": null, "e": 2301, "s": 2248, "text": "You can simply use .bar_chart_race()method from bcr." }, { "code": null, "e": 2324, "s": 2301, "text": "bcr.bar_chart_race(df)" }, { "code": null, "e": 2539, "s": 2324, "text": "The above give step is very simple and not as attractive as I want. So let’s customize it. Let’s have a look at the final code. You can find all features and different possibilities in bar_chart_plot documentation." }, { "code": null, "e": 3350, "s": 2539, "text": "bcr.bar_chart_race( df=df, filename=None, orientation='h', sort='desc', n_bars=10, fixed_order=False, fixed_max=True, steps_per_period=10, interpolate_period=False, label_bars=True, bar_size=.90, period_label={'x': .99, 'y': .25, 'ha': 'right', 'va':'center'}, period_summary_func=lambda v, r: {'x': .99, 'y': .18, 's': f'Population{v.nlargest(39).sum():,.0f}', 'ha': 'right', 'size': 8, 'family': 'Courier New'}, period_length=500, figsize=(6.5,5), dpi=144, cmap='dark12', title='Population by Country', title_size='', bar_label_size=7, tick_label_size=5, shared_fontdict={'family' : 'Helvetica','color' : '.1'}, scale='linear', writer=None, fig=None, bar_kwargs={'alpha': .7}, filter_column_colors=True)" }, { "code": null, "e": 3541, "s": 3350, "text": "I would like to thanks Ted Petrou for creating such a great library and Tutorials. Apart from that, thanks to Vinay Shaw — author of this kernel, who introduced me to this beautiful library." }, { "code": null, "e": 3837, "s": 3541, "text": "That’s it for today. Today, I learned and created my first bar chart race visualization. In future looking forward to create something interesting from it. I hope this article was helpful to you. All the codes of data analysis and visuals can be found at this GitHub repository or Kaggle kernel." }, { "code": null, "e": 3857, "s": 3837, "text": "Thanks for reading." }, { "code": null, "e": 3884, "s": 3857, "text": "I appreciate any feedback." }, { "code": null, "e": 3907, "s": 3884, "text": "towardsdatascience.com" }, { "code": null, "e": 4023, "s": 3907, "text": "If you like my work and want to support me, I’d greatly appreciate it if you follow me on my social media channels:" }, { "code": null, "e": 4080, "s": 4023, "text": "The best way to support me is by following me on Medium." }, { "code": null, "e": 4117, "s": 4080, "text": "Subscribe to my new YouTube channel." } ]
How to create "next" and "previous" buttons with CSS?
Following is the code to create next and previous buttons with CSS − Live Demo <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style> a { text-decoration: none; display: inline-block; padding: 20px; font-size: 35px; width: 40px; text-align: center; } .back:hover { background-color: #ddd; color: black; } .next:hover { background-color: rgb(121, 37, 133); color: white; } .back { border-radius: 50%; background-color: #acacac; color: black; } .next { border-radius: 50%; background-color: rgb(68, 30, 112); color: white; } </style> </head> <body> <h1>Previous and Next Button Example</h1> <a href="#" class="back">‹</a> <a href="#" class="next">›</a> </body> </html> The above code will produce the following output −
[ { "code": null, "e": 1131, "s": 1062, "text": "Following is the code to create next and previous buttons with CSS −" }, { "code": null, "e": 1142, "s": 1131, "text": " Live Demo" }, { "code": null, "e": 1832, "s": 1142, "text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<style>\na {\n text-decoration: none;\n display: inline-block;\n padding: 20px;\n font-size: 35px;\n width: 40px;\n text-align: center;\n}\n.back:hover {\n background-color: #ddd;\n color: black;\n}\n.next:hover {\n background-color: rgb(121, 37, 133);\n color: white;\n}\n.back {\n border-radius: 50%;\n background-color: #acacac;\n color: black;\n}\n.next {\n border-radius: 50%;\n background-color: rgb(68, 30, 112);\n color: white;\n}\n</style>\n</head>\n<body>\n<h1>Previous and Next Button Example</h1>\n<a href=\"#\" class=\"back\">‹</a>\n<a href=\"#\" class=\"next\">›</a>\n</body>\n</html>" }, { "code": null, "e": 1883, "s": 1832, "text": "The above code will produce the following output −" } ]
Java byte Keyword
❮ Java Keywords byte myNum = 100; System.out.println(myNum); Try it Yourself » The byte keyword is a data type that can store whole numbers from -128 to 127. Read more about data types in our Java Data Types Tutorial. ❮ Java Keywords 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": 18, "s": 0, "text": "\n❮ Java Keywords\n" }, { "code": null, "e": 64, "s": 18, "text": "byte myNum = 100;\nSystem.out.println(myNum);\n" }, { "code": null, "e": 84, "s": 64, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 163, "s": 84, "text": "The byte keyword is a data type that can store whole numbers from -128 to 127." }, { "code": null, "e": 223, "s": 163, "text": "Read more about data types in our Java Data Types Tutorial." }, { "code": null, "e": 241, "s": 223, "text": "\n❮ Java Keywords\n" }, { "code": null, "e": 274, "s": 241, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 316, "s": 274, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 423, "s": 316, "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": 442, "s": 423, "text": "[email protected]" } ]
Python 3 - os.chdir() Method
The method chdir() changes the current working directory to the given path.It returns None in all the cases. Following is the syntax for chdir() method − os.chdir(path) path − This is complete path of the directory to be changed to a new location. This method does not return any value. It throws FileNotFoundError if specified path is not found The following example shows the usage of chdir() method. #!/usr/bin/python3 import os path = "d:\\python3" #change path for linux # Now change the directory os.chdir( path ) # Check current working directory. retval = os.getcwd() print ("Directory changed successfully %s" % retval) When we run the above program, it produces the following result − Directory changed successfully d:\python3 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": 2449, "s": 2340, "text": "The method chdir() changes the current working directory to the given path.It returns None in all the cases." }, { "code": null, "e": 2494, "s": 2449, "text": "Following is the syntax for chdir() method −" }, { "code": null, "e": 2510, "s": 2494, "text": "os.chdir(path)\n" }, { "code": null, "e": 2589, "s": 2510, "text": "path − This is complete path of the directory to be changed to a new location." }, { "code": null, "e": 2687, "s": 2589, "text": "This method does not return any value. It throws FileNotFoundError if specified path is not found" }, { "code": null, "e": 2744, "s": 2687, "text": "The following example shows the usage of chdir() method." }, { "code": null, "e": 2974, "s": 2744, "text": "#!/usr/bin/python3\nimport os\n\npath = \"d:\\\\python3\" #change path for linux\n\n# Now change the directory\nos.chdir( path )\n\n# Check current working directory.\nretval = os.getcwd()\n\nprint (\"Directory changed successfully %s\" % retval)" }, { "code": null, "e": 3040, "s": 2974, "text": "When we run the above program, it produces the following result −" }, { "code": null, "e": 3083, "s": 3040, "text": "Directory changed successfully d:\\python3\n" }, { "code": null, "e": 3120, "s": 3083, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3136, "s": 3120, "text": " Malhar Lathkar" }, { "code": null, "e": 3169, "s": 3136, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3188, "s": 3169, "text": " Arnab Chakraborty" }, { "code": null, "e": 3223, "s": 3188, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3245, "s": 3223, "text": " In28Minutes Official" }, { "code": null, "e": 3279, "s": 3245, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3307, "s": 3279, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3342, "s": 3307, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3356, "s": 3342, "text": " Lets Kode It" }, { "code": null, "e": 3389, "s": 3356, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3406, "s": 3389, "text": " Abhilash Nelson" }, { "code": null, "e": 3413, "s": 3406, "text": " Print" }, { "code": null, "e": 3424, "s": 3413, "text": " Add Notes" } ]
Apache Derby - Procedures
This chapter teaches you how to create and drop procedures in Derby. You can create a procedure using the CREATE PROCEDURE statement. Following is the syntax of the CREATE PROCEDURE statement. CREATE PROCEDURE procedure_name (parameter_type parameter_name1, parameter_type parameter_name2 . . . .) parameter_style; Suppose, we have created a table in Derby as shown below. CREATE TABLE Emp ( Id INT NOT NULL GENERATED ALWAYS AS IDENTITY, Name VARCHAR(255), Salary INT NOT NULL, Location VARCHAR(255), Phone_Number BIGINT ); And inserted values in it as follows − INSERT INTO Employees(Name, Salary, Location) VALUES ('Amit', 30000, 'Hyderabad'), ('Kalyan', 40000, 'Vishakhapatnam'), ('Renuka', 50000, 'Delhi'), ('Archana', 15000, 'Mumbai'), ('Trupthi', 45000, 'Kochin')"; Following example creates a procedure named Update_Procedure which accepts JAVA parameters. ij> CREATE PROCEDURE Update_Procedure(IN id INTEGER, IN name VARCHAR(10)) PARAMETER STYLE JAVA READS SQL DATA LANGUAGE JAVA EXTERNAL NAME 'ProcedureExample.testProc'; > 0 rows inserted/updated/deleted Where ProcedureExample class looks like − import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class ProcedureExample { public static void testProc(int salary, String name) throws Exception { String connectionURL = "jdbc:derby:MYDATABASE;create=true"; Connection conn = DriverManager.getConnection(connectionURL); String query = "UPDATE Employees SET SALARY = ? WHERE NAME = ?"; PreparedStatement pstmt = conn.prepareStatement(query); pstmt.setInt(1, salary); pstmt.setString (2, name); pstmt.executeUpdate(); } } You can verify the list of procedures using SHOW PROCEDURES query. ij> SHOW PROCEDURES; PROCEDURE_SCHEM |PROCEDURE_NAME |REMARKS ------------------------------------------------------------------------ APP |UPDATE_PROCEDURE |ProcedureExample.te& SALES |EXAMPLE_ PROCEDURE |com.example.sales.c& SQLJ |INSTALL_JAR |org.apache.derby.ca& SQLJ |REMOVE_JAR |org.apache.derby.ca& SQLJ |REPLACE_JAR |org.apache.derby.ca& SYSCS_UTIL |SYSCS_BACKUP_DATABASE|org.apache.derby.ca& . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Here you can observe the newly created procedure. You can drop a procedure using the DROP PROCEDURE statement. Following is the syntax of the DROP PROCEDURE statement. DROP PROCEDURE procedure_name; Following example drops a procedure named Update_Procedure created above. ij> DROP PROCEDURE Update_Procedure; > 0 rows inserted/updated/deleted 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": 2249, "s": 2180, "text": "This chapter teaches you how to create and drop procedures in Derby." }, { "code": null, "e": 2314, "s": 2249, "text": "You can create a procedure using the CREATE PROCEDURE statement." }, { "code": null, "e": 2373, "s": 2314, "text": "Following is the syntax of the CREATE PROCEDURE statement." }, { "code": null, "e": 2496, "s": 2373, "text": "CREATE PROCEDURE procedure_name (parameter_type parameter_name1, parameter_type\nparameter_name2 . . . .) parameter_style;\n" }, { "code": null, "e": 2554, "s": 2496, "text": "Suppose, we have created a table in Derby as shown below." }, { "code": null, "e": 2718, "s": 2554, "text": "CREATE TABLE Emp ( Id INT NOT NULL GENERATED ALWAYS AS IDENTITY,\n Name VARCHAR(255),\n Salary INT NOT NULL,\n Location VARCHAR(255),\n Phone_Number BIGINT\n);\n" }, { "code": null, "e": 2757, "s": 2718, "text": "And inserted values in it as follows −" }, { "code": null, "e": 2982, "s": 2757, "text": "INSERT INTO Employees(Name, Salary, Location) VALUES\n ('Amit', 30000, 'Hyderabad'),\n ('Kalyan', 40000, 'Vishakhapatnam'),\n ('Renuka', 50000, 'Delhi'),\n ('Archana', 15000, 'Mumbai'),\n ('Trupthi', 45000, 'Kochin')\";\n" }, { "code": null, "e": 3074, "s": 2982, "text": "Following example creates a procedure named Update_Procedure which accepts JAVA parameters." }, { "code": null, "e": 3276, "s": 3074, "text": "ij> CREATE PROCEDURE Update_Procedure(IN id INTEGER, IN name VARCHAR(10))\nPARAMETER STYLE JAVA READS SQL DATA LANGUAGE JAVA EXTERNAL NAME\n'ProcedureExample.testProc';\n> 0 rows inserted/updated/deleted\n" }, { "code": null, "e": 3318, "s": 3276, "text": "Where ProcedureExample class looks like −" }, { "code": null, "e": 3886, "s": 3318, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\npublic class ProcedureExample {\n public static void testProc(int salary, String name) throws Exception {\n String connectionURL = \"jdbc:derby:MYDATABASE;create=true\";\n Connection conn = DriverManager.getConnection(connectionURL);\n String query = \"UPDATE Employees SET SALARY = ? WHERE NAME = ?\";\n PreparedStatement pstmt = conn.prepareStatement(query);\n pstmt.setInt(1, salary);\n pstmt.setString (2, name);\n pstmt.executeUpdate();\n }\n}" }, { "code": null, "e": 3953, "s": 3886, "text": "You can verify the list of procedures using SHOW PROCEDURES query." }, { "code": null, "e": 4667, "s": 3953, "text": "ij> SHOW PROCEDURES;\nPROCEDURE_SCHEM |PROCEDURE_NAME |REMARKS\n------------------------------------------------------------------------\nAPP |UPDATE_PROCEDURE |ProcedureExample.te&\nSALES |EXAMPLE_ PROCEDURE |com.example.sales.c&\nSQLJ |INSTALL_JAR |org.apache.derby.ca&\nSQLJ |REMOVE_JAR |org.apache.derby.ca&\nSQLJ |REPLACE_JAR |org.apache.derby.ca&\nSYSCS_UTIL |SYSCS_BACKUP_DATABASE|org.apache.derby.ca&\n. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n" }, { "code": null, "e": 4717, "s": 4667, "text": "Here you can observe the newly created procedure." }, { "code": null, "e": 4778, "s": 4717, "text": "You can drop a procedure using the DROP PROCEDURE statement." }, { "code": null, "e": 4835, "s": 4778, "text": "Following is the syntax of the DROP PROCEDURE statement." }, { "code": null, "e": 4867, "s": 4835, "text": "DROP PROCEDURE procedure_name;\n" }, { "code": null, "e": 4941, "s": 4867, "text": "Following example drops a procedure named Update_Procedure created above." }, { "code": null, "e": 5013, "s": 4941, "text": "ij> DROP PROCEDURE Update_Procedure;\n> 0 rows inserted/updated/deleted\n" }, { "code": null, "e": 5048, "s": 5013, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5067, "s": 5048, "text": " Arnab Chakraborty" }, { "code": null, "e": 5102, "s": 5067, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5123, "s": 5102, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 5156, "s": 5123, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 5169, "s": 5156, "text": " Nilay Mehta" }, { "code": null, "e": 5204, "s": 5169, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5222, "s": 5204, "text": " Bigdata Engineer" }, { "code": null, "e": 5255, "s": 5222, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 5273, "s": 5255, "text": " Bigdata Engineer" }, { "code": null, "e": 5306, "s": 5273, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 5324, "s": 5306, "text": " Bigdata Engineer" }, { "code": null, "e": 5331, "s": 5324, "text": " Print" }, { "code": null, "e": 5342, "s": 5331, "text": " Add Notes" } ]
Calculate the Cumulative Minima of a Vector in R Programming - cummin() Function - GeeksforGeeks
15 Jun, 2020 cummin() function in R Language is used to calculate the cumulative minima of the values of vector passed as arguments. Syntax: cummin(x) Parameters:x: numeric object Example 1: # R program to cumulative minima # Calling cummin() functioncummin(2:6)cummin(-2:-6)cummin(1.8:4.2) Output: [1] 2 2 2 2 2 [1] -2 -3 -4 -5 -6 [1] 1.8 1.8 1.8 Example 2: # R program to cumulative minima # Creating vectorsx1 <- c(3, 6, 4, 2, 6, 7)x2 <- c(-4, 6, 3) # Calling cummin() functioncummin(x1)cummin(x2) Output: [1] 3 3 3 2 2 2 [1] -4 -4 -4 Since, the minima is calculated for the values in increasing order and hence the above code shows two cumulative values for first vector. R Vector-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) How to change Row Names of DataFrame in R ? Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? Printing Output of an R Program How to Split Column Into Multiple Columns in R DataFrame? R Programming Language - Introduction
[ { "code": null, "e": 25771, "s": 25743, "text": "\n15 Jun, 2020" }, { "code": null, "e": 25891, "s": 25771, "text": "cummin() function in R Language is used to calculate the cumulative minima of the values of vector passed as arguments." }, { "code": null, "e": 25909, "s": 25891, "text": "Syntax: cummin(x)" }, { "code": null, "e": 25938, "s": 25909, "text": "Parameters:x: numeric object" }, { "code": null, "e": 25949, "s": 25938, "text": "Example 1:" }, { "code": "# R program to cumulative minima # Calling cummin() functioncummin(2:6)cummin(-2:-6)cummin(1.8:4.2)", "e": 26050, "s": 25949, "text": null }, { "code": null, "e": 26058, "s": 26050, "text": "Output:" }, { "code": null, "e": 26108, "s": 26058, "text": "[1] 2 2 2 2 2\n[1] -2 -3 -4 -5 -6\n[1] 1.8 1.8 1.8\n" }, { "code": null, "e": 26119, "s": 26108, "text": "Example 2:" }, { "code": "# R program to cumulative minima # Creating vectorsx1 <- c(3, 6, 4, 2, 6, 7)x2 <- c(-4, 6, 3) # Calling cummin() functioncummin(x1)cummin(x2)", "e": 26263, "s": 26119, "text": null }, { "code": null, "e": 26271, "s": 26263, "text": "Output:" }, { "code": null, "e": 26301, "s": 26271, "text": "[1] 3 3 3 2 2 2\n[1] -4 -4 -4\n" }, { "code": null, "e": 26439, "s": 26301, "text": "Since, the minima is calculated for the values in increasing order and hence the above code shows two cumulative values for first vector." }, { "code": null, "e": 26457, "s": 26439, "text": "R Vector-Function" }, { "code": null, "e": 26468, "s": 26457, "text": "R Language" }, { "code": null, "e": 26566, "s": 26468, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26624, "s": 26566, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 26676, "s": 26624, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 26708, "s": 26676, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 26752, "s": 26708, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 26804, "s": 26752, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 26839, "s": 26804, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 26877, "s": 26839, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 26909, "s": 26877, "text": "Printing Output of an R Program" }, { "code": null, "e": 26967, "s": 26909, "text": "How to Split Column Into Multiple Columns in R DataFrame?" } ]
Convert large list to dataframe in R - GeeksforGeeks
18 Jul, 2021 In this article, we will discuss how to convert a large list to a dataframe in the R Programming Language. First, create a large list. Then use the Map function on the list and convert it to dataframe using the as.data.frame function in R. The map function applies a function and transforms the given input to each element of a list or vector. We will be using as.data.frame function inside the map to convert each element of a given list to a dataframe. After mapping and converting each element of the list to a dataframe, the next step is to take the entire large list and convert it to a data table or dataframe using the rbindlist function in R. Syntax : rbindlist( l, fill = FALSE, use.names = “check”, idcol = NULL) Parameters : l : This is a list of data.table or data.frame or list objects. fill : This is false by default. If we specify this as true, then it automatically fills the missing columns with NAs. use.names : By default, it is specified as check which implies all the elements may not have same names in the same order. If it is specified as true, then we bind by matching column names and if false, then we bind by matching positions. idcol : It basically creates a column in the result, displaying which list item those particular rows came from. You can also use system.time() function to calculate the elapsed time for conversion. Example: Converting a large list to dataframe using rbindlist() method R library(Matrix)library(data.table) # Creating the large listdata <- matrix(data = 1, nrow = 300, ncol = 3)list_data <- rep(list(data), 18000) # Mapping -> converting the list to # dataframelist_data <- Map(as.data.frame, list_data) # Converting the large list to dataframe# using the rbindlist functiondatarbind <- rbindlist(list_data) # Print the dataframedatarbind Output : fig : Large list to dataframe We will be using ldply() function of the ‘plyr‘ package. Syntax: ldply(large_list) Parameter: large_list: pass your large list Import the required packages, then pass your list which you want to convert to a dataframe into ldply() function as an argument. Example: Converting a large list to dataframe using plyr package R library(Matrix)library(plyr) # Creating the large listdata <- matrix(data = 1, nrow = 300, ncol = 3) # Replicating the listlist_data <- rep(list(data), 18000) ldply(list_data) Output: 1 2 3 1 1 1 1 2 1 1 1 3 1 1 1 4 1 1 1 5 1 1 1 6 1 1 1 7 1 1 1 8 1 1 1 9 1 1 1 10 1 1 1 11 1 1 1 12 1 1 1 13 1 1 1 14 1 1 1 15 1 1 1 16 1 1 1 17 1 1 1 18 1 1 1 . . . Picked R DataFrame-Programs R List-Programs R-DataFrame R-List R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to Change Axis Scales in R Plots? Replace Specific Characters in String in R How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Convert Matrix to Dataframe in R
[ { "code": null, "e": 25340, "s": 25312, "text": "\n18 Jul, 2021" }, { "code": null, "e": 25448, "s": 25340, "text": "In this article, we will discuss how to convert a large list to a dataframe in the R Programming Language. " }, { "code": null, "e": 25796, "s": 25448, "text": "First, create a large list. Then use the Map function on the list and convert it to dataframe using the as.data.frame function in R. The map function applies a function and transforms the given input to each element of a list or vector. We will be using as.data.frame function inside the map to convert each element of a given list to a dataframe." }, { "code": null, "e": 25992, "s": 25796, "text": "After mapping and converting each element of the list to a dataframe, the next step is to take the entire large list and convert it to a data table or dataframe using the rbindlist function in R." }, { "code": null, "e": 26002, "s": 25992, "text": "Syntax : " }, { "code": null, "e": 26065, "s": 26002, "text": "rbindlist( l, fill = FALSE, use.names = “check”, idcol = NULL)" }, { "code": null, "e": 26078, "s": 26065, "text": "Parameters :" }, { "code": null, "e": 26142, "s": 26078, "text": "l : This is a list of data.table or data.frame or list objects." }, { "code": null, "e": 26261, "s": 26142, "text": "fill : This is false by default. If we specify this as true, then it automatically fills the missing columns with NAs." }, { "code": null, "e": 26500, "s": 26261, "text": "use.names : By default, it is specified as check which implies all the elements may not have same names in the same order. If it is specified as true, then we bind by matching column names and if false, then we bind by matching positions." }, { "code": null, "e": 26613, "s": 26500, "text": "idcol : It basically creates a column in the result, displaying which list item those particular rows came from." }, { "code": null, "e": 26699, "s": 26613, "text": "You can also use system.time() function to calculate the elapsed time for conversion." }, { "code": null, "e": 26770, "s": 26699, "text": "Example: Converting a large list to dataframe using rbindlist() method" }, { "code": null, "e": 26772, "s": 26770, "text": "R" }, { "code": "library(Matrix)library(data.table) # Creating the large listdata <- matrix(data = 1, nrow = 300, ncol = 3)list_data <- rep(list(data), 18000) # Mapping -> converting the list to # dataframelist_data <- Map(as.data.frame, list_data) # Converting the large list to dataframe# using the rbindlist functiondatarbind <- rbindlist(list_data) # Print the dataframedatarbind", "e": 27143, "s": 26772, "text": null }, { "code": null, "e": 27152, "s": 27143, "text": "Output :" }, { "code": null, "e": 27182, "s": 27152, "text": "fig : Large list to dataframe" }, { "code": null, "e": 27240, "s": 27182, "text": "We will be using ldply() function of the ‘plyr‘ package. " }, { "code": null, "e": 27266, "s": 27240, "text": "Syntax: ldply(large_list)" }, { "code": null, "e": 27277, "s": 27266, "text": "Parameter:" }, { "code": null, "e": 27310, "s": 27277, "text": "large_list: pass your large list" }, { "code": null, "e": 27439, "s": 27310, "text": "Import the required packages, then pass your list which you want to convert to a dataframe into ldply() function as an argument." }, { "code": null, "e": 27504, "s": 27439, "text": "Example: Converting a large list to dataframe using plyr package" }, { "code": null, "e": 27506, "s": 27504, "text": "R" }, { "code": "library(Matrix)library(plyr) # Creating the large listdata <- matrix(data = 1, nrow = 300, ncol = 3) # Replicating the listlist_data <- rep(list(data), 18000) ldply(list_data)", "e": 27685, "s": 27506, "text": null }, { "code": null, "e": 27693, "s": 27685, "text": "Output:" }, { "code": null, "e": 27923, "s": 27693, "text": " 1 2 3\n1 1 1 1\n2 1 1 1\n3 1 1 1\n4 1 1 1\n5 1 1 1\n6 1 1 1\n7 1 1 1\n8 1 1 1\n9 1 1 1\n10 1 1 1\n11 1 1 1\n12 1 1 1\n13 1 1 1\n14 1 1 1\n15 1 1 1\n16 1 1 1\n17 1 1 1\n18 1 1 1\n.\n.\n." }, { "code": null, "e": 27930, "s": 27923, "text": "Picked" }, { "code": null, "e": 27951, "s": 27930, "text": "R DataFrame-Programs" }, { "code": null, "e": 27967, "s": 27951, "text": "R List-Programs" }, { "code": null, "e": 27979, "s": 27967, "text": "R-DataFrame" }, { "code": null, "e": 27986, "s": 27979, "text": "R-List" }, { "code": null, "e": 27997, "s": 27986, "text": "R Language" }, { "code": null, "e": 28008, "s": 27997, "text": "R Programs" }, { "code": null, "e": 28106, "s": 28008, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28158, "s": 28106, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 28193, "s": 28158, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 28251, "s": 28193, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28289, "s": 28251, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 28332, "s": 28289, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 28390, "s": 28332, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28433, "s": 28390, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 28482, "s": 28433, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 28532, "s": 28482, "text": "How to filter R dataframe by multiple conditions?" } ]
PyQt5 – Block signals of push button - GeeksforGeeks
22 Apr, 2020 In this article we will see how we can block the signals of the button, blocking signals means stopping the button to do his assigned task. It is used to make a button deactive. In order to do this we will use blockSignals method which belongs to QObject class. Syntax : button.blockSignals(True) Argument : It takes bool as argument. Action performed: It blocks the signal of button. Code : # importing librariesfrom PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a push button button = QPushButton("CLICK", self) # setting geometry of button button.setGeometry(200, 150, 100, 30) # adding action to a button button.clicked.connect(self.clickme) # blocking signals of the button button.blockSignals(True) # action method def clickme(self): # printing pressed print("pressed") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output :When this button will be clicked nothing will happen. Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Reading and Writing to text files in Python Create a Pandas DataFrame from Lists *args and **kwargs in Python Selecting rows in pandas DataFrame based on conditions
[ { "code": null, "e": 24514, "s": 24486, "text": "\n22 Apr, 2020" }, { "code": null, "e": 24692, "s": 24514, "text": "In this article we will see how we can block the signals of the button, blocking signals means stopping the button to do his assigned task. It is used to make a button deactive." }, { "code": null, "e": 24776, "s": 24692, "text": "In order to do this we will use blockSignals method which belongs to QObject class." }, { "code": null, "e": 24811, "s": 24776, "text": "Syntax : button.blockSignals(True)" }, { "code": null, "e": 24849, "s": 24811, "text": "Argument : It takes bool as argument." }, { "code": null, "e": 24899, "s": 24849, "text": "Action performed: It blocks the signal of button." }, { "code": null, "e": 24906, "s": 24899, "text": "Code :" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a push button button = QPushButton(\"CLICK\", self) # setting geometry of button button.setGeometry(200, 150, 100, 30) # adding action to a button button.clicked.connect(self.clickme) # blocking signals of the button button.blockSignals(True) # action method def clickme(self): # printing pressed print(\"pressed\") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 25955, "s": 24906, "text": null }, { "code": null, "e": 26017, "s": 25955, "text": "Output :When this button will be clicked nothing will happen." }, { "code": null, "e": 26028, "s": 26017, "text": "Python-gui" }, { "code": null, "e": 26040, "s": 26028, "text": "Python-PyQt" }, { "code": null, "e": 26047, "s": 26040, "text": "Python" }, { "code": null, "e": 26145, "s": 26047, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26154, "s": 26145, "text": "Comments" }, { "code": null, "e": 26167, "s": 26154, "text": "Old Comments" }, { "code": null, "e": 26185, "s": 26167, "text": "Python Dictionary" }, { "code": null, "e": 26220, "s": 26185, "text": "Read a file line by line in Python" }, { "code": null, "e": 26242, "s": 26220, "text": "Enumerate() in Python" }, { "code": null, "e": 26274, "s": 26242, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26316, "s": 26274, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26342, "s": 26316, "text": "Python String | replace()" }, { "code": null, "e": 26386, "s": 26342, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 26423, "s": 26386, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26452, "s": 26423, "text": "*args and **kwargs in Python" } ]
Array sum after replacing all occurrences of X by Y for Q queries - GeeksforGeeks
27 May, 2021 Given an integer array arr[] and Q queries, the task is to find the sum of the array for each query of the following type: Each query contains 2 integers X and Y, where all the occurrences of X in arr[] are to be replaced by Y. After each query, they print the sum of the array. Examples: Input: arr[] = { 1, 2, 1, 3, 2}, X[] = { 2, 3, 5 }, Y[] = { 3, 1, 2 } Output: 11 5 5 Explanation: After the 1st query, replace 2 with 3, arr[] = { 1, 3, 1, 3, 3 }, Sum = 11. After the 2nd query, replace 3 with 1, arr[] = { 1, 1, 1, 1, 1 }, Sum = 5. After the 3rd query, replace 5 with 2, arr[] = { 1, 1, 1, 1, 1 }, Sum = 5. Input: arr[] = { 12, 22, 11, 11, 2}, X[] = {2, 11, 22}, Y[] = {12, 222, 2} Output: 68 490 470 Naive Approach: The simplest approach to solve the problem mentioned above is to traverse through the array and replace all the instances of X with Y for each query and calculate the sum. Time Complexity: O(N * Q) Efficient Approach: To optimize the above method, follow the steps given below: Precompute and store the sum of the array in a variable S and store the frequencies of array elements in a Map count. Then, do the following for each query: Find the frequency of X stored on the map.Subtract X * count[X] from S.Set count[Y] = count[X] and then count[X] = 0.Add Y * count[Y] to S.Print the updated value of S. Find the frequency of X stored on the map. Subtract X * count[X] from S. Set count[Y] = count[X] and then count[X] = 0. Add Y * count[Y] to S. Print the updated value of S. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to find the sum// of the array for the given Q queries #include <bits/stdc++.h>using namespace std; // Function that print the sum of// the array for Q queriesvoid sumOfTheArrayForQuery(int* A, int N, int* X, int* Y, int Q){ int sum = 0; // Stores the frequencies // of array elements unordered_map<int, int> count; // Calculate the sum of // the initial array and // store the frequency of // each element in map for (int i = 0; i < N; i++) { sum += A[i]; count[A[i]]++; } // Iterate for all the queries for (int i = 0; i < Q; i++) { // Store query values int x = X[i], y = Y[i]; // Decrement the sum accordingly sum -= count[X[i]] * X[i]; // Increment the sum accordingly sum += count[X[i]] * Y[i]; // Set count of Y[i] count[Y[i]] += count[X[i]]; // Reset count of X[i] count[X[i]] = 0; // Print the sum cout << sum << " "; }} // Driver Codeint main(){ int arr[] = { 1, 2, 1, 3, 2 }; int X[] = { 2, 3, 5 }; int Y[] = { 3, 1, 2 }; int N = sizeof(arr) / sizeof(arr[0]); int Q = sizeof(X) / sizeof(X[0]); // Function call sumOfTheArrayForQuery(arr, N, X, Y, Q); return 0;} // Java implementation to// find the sum of the array// for the given Q queriesimport java.util.*;class GFG{ // Function that print the sum of// the array for Q queriespublic static void sumOfTheArrayForQuery(int[] A, int N, int[] X, int[] Y, int Q){ int sum = 0; // Stores the frequencies // of array elements // Create an empty hash map HashMap<Integer, Integer> count = new HashMap<>(); // Calculate the sum of // the initial array and // store the frequency of // each element in map for (int i = 0; i < N; i++) { sum += A[i]; if (count.containsKey(A[i])) { count.replace(A[i], count.get(A[i]) + 1); } else { count.put(A[i], 1); } } // Iterate for all the queries for (int i = 0; i < Q; i++) { // Store query values int x = X[i], y = Y[i]; if(count.containsKey(X[i])) { // Decrement the sum accordingly sum -= count.get(X[i]) * X[i]; // Increment the sum accordingly sum += count.get(X[i]) * Y[i]; } // Set count of Y[i] if(count.containsKey(Y[i]) && count.containsKey(X[i])) { count.replace(Y[i], count.get(Y[i]) + count.get(X[i])); } // Reset count of X[i] if(count.containsKey(X[i])) { count.replace(X[i], 0); } // Print the sum System.out.print(sum + " "); }} // Driver codepublic static void main(String[] args){ int arr[] = {1, 2, 1, 3, 2}; int X[] = {2, 3, 5}; int Y[] = {3, 1, 2}; int N = arr.length; int Q = X.length; // Function call sumOfTheArrayForQuery(arr, N, X, Y, Q);}} // This code is contributed by divyeshrabadiya07 # Python3 implementation to find the sum# of the array for the given Q queries # Function that print the sum of# the array for Q queriesdef sumOfTheArrayForQuery(A, N, X, Y, Q): sum = 0 # Stores the frequencies # of array elements count = {} # Calculate the sum of # the initial array and # store the frequency of # each element in map for i in range(N): sum += A[i] if A[i] in count: count[A[i]] += 1 else: count[A[i]] = 1 # Iterate for all the queries for i in range(Q): # Store query values x = X[i] y = Y[i] if X[i] not in count: count[X[i]] = 0 if Y[i] not in count: count[Y[i]] = 0 # Decrement the sum accordingly sum -= (count[X[i]] * X[i]) # Increment the sum accordingly sum += count[X[i]] * Y[i] # Set count of Y[i] count[Y[i]] += count[X[i]] # Reset count of X[i] count[X[i]] = 0 # Print the sum print(sum, end = " ") # Driver Codearr = [ 1, 2, 1, 3, 2, ]X = [ 2, 3, 5 ]Y = [ 3, 1, 2 ]N = len(arr)Q = len(X) # Function callsumOfTheArrayForQuery(arr, N, X, Y, Q) # This code is contributed by avanitrachhadiya2155 // C# implementation to// find the sum of the array// for the given Q queriesusing System;using System.Collections.Generic;class GFG{ // Function that print the sum of// the array for Q queriespublic static void sumOfTheArrayForQuery(int[] A, int N, int[] X, int[] Y, int Q){ int sum = 0; // Stores the frequencies // of array elements // Create an empty hash map Dictionary<int, int> count = new Dictionary<int, int>(); // Calculate the sum of // the initial array and // store the frequency of // each element in map for (int i = 0; i < N; i++) { sum += A[i]; if (count.ContainsKey(A[i])) { count[A[i]]= count[A[i]] + 1; } else { count.Add(A[i], 1); } } // Iterate for all the queries for (int i = 0; i < Q; i++) { // Store query values int x = X[i], y = Y[i]; if(count.ContainsKey(X[i])) { // Decrement the sum accordingly sum -= count[X[i]] * X[i]; // Increment the sum accordingly sum += count[X[i]] * Y[i]; } // Set count of Y[i] if(count.ContainsKey(Y[i]) && count.ContainsKey(X[i])) { count[Y[i]] = count[Y[i]] + count[X[i]]; } // Reset count of X[i] if(count.ContainsKey(X[i])) { count[X[i]] = 0; } // Print the sum Console.Write(sum + " "); }} // Driver codepublic static void Main(String[] args){ int []arr = {1, 2, 1, 3, 2}; int []X = {2, 3, 5}; int []Y = {3, 1, 2}; int N = arr.Length; int Q = X.Length; // Function call sumOfTheArrayForQuery(arr, N, X, Y, Q);}} // This code is contributed by Amit Katiyar <script> // Javascript implementation to find the sum// of the array for the given Q queries // Function that print the sum of// the array for Q queriesfunction sumOfTheArrayForQuery(A, N, X, Y, Q){ var sum = 0; // Stores the frequencies // of array elements var count = new Map(); // Calculate the sum of // the initial array and // store the frequency of // each element in map for (var i = 0; i < N; i++) { sum += A[i]; if(count.has(A[i])) count.set(A[i], count.get(A[i])+1) else count.set(A[i], 1) } // Iterate for all the queries for (var i = 0; i < Q; i++) { // Store query values var x = X[i], y = Y[i]; if(count.has(X[i])) { // Decrement the sum accordingly sum -= count.get(X[i]) * X[i]; // Increment the sum accordingly sum += count.get(X[i]) * Y[i]; } if(count.has(Y[i])) { // Set count of Y[i] count.set(Y[i], count.get(Y[i]) + count.get(X[i])); } // Reset count of X[i] count.set(X[i] , 0); // Print the sum document.write( sum + " "); }} // Driver Codevar arr = [1, 2, 1, 3, 2];var X = [2, 3, 5 ];var Y = [3, 1, 2 ];var N = arr.length;var Q = X.length;// Function callsumOfTheArrayForQuery(arr, N, X, Y, Q); </script> 11 5 5 Time Complexity: O(N), as each query has a computational complexity of O(1). Auxiliary Space: O(N) avanitrachhadiya2155 divyeshrabadiya07 amit143katiyar itsok array-range-queries cpp-map frequency-counting Arrays Competitive Programming Mathematical Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java Linear Search Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Prefix Sum Array - Implementation and Applications in Competitive Programming Top 10 Algorithms and Data Structures for Competitive Programming
[ { "code": null, "e": 26157, "s": 26129, "text": "\n27 May, 2021" }, { "code": null, "e": 26281, "s": 26157, "text": "Given an integer array arr[] and Q queries, the task is to find the sum of the array for each query of the following type: " }, { "code": null, "e": 26386, "s": 26281, "text": "Each query contains 2 integers X and Y, where all the occurrences of X in arr[] are to be replaced by Y." }, { "code": null, "e": 26437, "s": 26386, "text": "After each query, they print the sum of the array." }, { "code": null, "e": 26447, "s": 26437, "text": "Examples:" }, { "code": null, "e": 26772, "s": 26447, "text": "Input: arr[] = { 1, 2, 1, 3, 2}, X[] = { 2, 3, 5 }, Y[] = { 3, 1, 2 } Output: 11 5 5 Explanation: After the 1st query, replace 2 with 3, arr[] = { 1, 3, 1, 3, 3 }, Sum = 11. After the 2nd query, replace 3 with 1, arr[] = { 1, 1, 1, 1, 1 }, Sum = 5. After the 3rd query, replace 5 with 2, arr[] = { 1, 1, 1, 1, 1 }, Sum = 5. " }, { "code": null, "e": 26867, "s": 26772, "text": "Input: arr[] = { 12, 22, 11, 11, 2}, X[] = {2, 11, 22}, Y[] = {12, 222, 2} Output: 68 490 470 " }, { "code": null, "e": 27056, "s": 26867, "text": "Naive Approach: The simplest approach to solve the problem mentioned above is to traverse through the array and replace all the instances of X with Y for each query and calculate the sum. " }, { "code": null, "e": 27082, "s": 27056, "text": "Time Complexity: O(N * Q)" }, { "code": null, "e": 27163, "s": 27082, "text": "Efficient Approach: To optimize the above method, follow the steps given below: " }, { "code": null, "e": 27281, "s": 27163, "text": "Precompute and store the sum of the array in a variable S and store the frequencies of array elements in a Map count." }, { "code": null, "e": 27489, "s": 27281, "text": "Then, do the following for each query: Find the frequency of X stored on the map.Subtract X * count[X] from S.Set count[Y] = count[X] and then count[X] = 0.Add Y * count[Y] to S.Print the updated value of S." }, { "code": null, "e": 27532, "s": 27489, "text": "Find the frequency of X stored on the map." }, { "code": null, "e": 27562, "s": 27532, "text": "Subtract X * count[X] from S." }, { "code": null, "e": 27609, "s": 27562, "text": "Set count[Y] = count[X] and then count[X] = 0." }, { "code": null, "e": 27632, "s": 27609, "text": "Add Y * count[Y] to S." }, { "code": null, "e": 27662, "s": 27632, "text": "Print the updated value of S." }, { "code": null, "e": 27713, "s": 27662, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27717, "s": 27713, "text": "C++" }, { "code": null, "e": 27722, "s": 27717, "text": "Java" }, { "code": null, "e": 27730, "s": 27722, "text": "Python3" }, { "code": null, "e": 27733, "s": 27730, "text": "C#" }, { "code": null, "e": 27744, "s": 27733, "text": "Javascript" }, { "code": "// C++ implementation to find the sum// of the array for the given Q queries #include <bits/stdc++.h>using namespace std; // Function that print the sum of// the array for Q queriesvoid sumOfTheArrayForQuery(int* A, int N, int* X, int* Y, int Q){ int sum = 0; // Stores the frequencies // of array elements unordered_map<int, int> count; // Calculate the sum of // the initial array and // store the frequency of // each element in map for (int i = 0; i < N; i++) { sum += A[i]; count[A[i]]++; } // Iterate for all the queries for (int i = 0; i < Q; i++) { // Store query values int x = X[i], y = Y[i]; // Decrement the sum accordingly sum -= count[X[i]] * X[i]; // Increment the sum accordingly sum += count[X[i]] * Y[i]; // Set count of Y[i] count[Y[i]] += count[X[i]]; // Reset count of X[i] count[X[i]] = 0; // Print the sum cout << sum << \" \"; }} // Driver Codeint main(){ int arr[] = { 1, 2, 1, 3, 2 }; int X[] = { 2, 3, 5 }; int Y[] = { 3, 1, 2 }; int N = sizeof(arr) / sizeof(arr[0]); int Q = sizeof(X) / sizeof(X[0]); // Function call sumOfTheArrayForQuery(arr, N, X, Y, Q); return 0;}", "e": 29066, "s": 27744, "text": null }, { "code": "// Java implementation to// find the sum of the array// for the given Q queriesimport java.util.*;class GFG{ // Function that print the sum of// the array for Q queriespublic static void sumOfTheArrayForQuery(int[] A, int N, int[] X, int[] Y, int Q){ int sum = 0; // Stores the frequencies // of array elements // Create an empty hash map HashMap<Integer, Integer> count = new HashMap<>(); // Calculate the sum of // the initial array and // store the frequency of // each element in map for (int i = 0; i < N; i++) { sum += A[i]; if (count.containsKey(A[i])) { count.replace(A[i], count.get(A[i]) + 1); } else { count.put(A[i], 1); } } // Iterate for all the queries for (int i = 0; i < Q; i++) { // Store query values int x = X[i], y = Y[i]; if(count.containsKey(X[i])) { // Decrement the sum accordingly sum -= count.get(X[i]) * X[i]; // Increment the sum accordingly sum += count.get(X[i]) * Y[i]; } // Set count of Y[i] if(count.containsKey(Y[i]) && count.containsKey(X[i])) { count.replace(Y[i], count.get(Y[i]) + count.get(X[i])); } // Reset count of X[i] if(count.containsKey(X[i])) { count.replace(X[i], 0); } // Print the sum System.out.print(sum + \" \"); }} // Driver codepublic static void main(String[] args){ int arr[] = {1, 2, 1, 3, 2}; int X[] = {2, 3, 5}; int Y[] = {3, 1, 2}; int N = arr.length; int Q = X.length; // Function call sumOfTheArrayForQuery(arr, N, X, Y, Q);}} // This code is contributed by divyeshrabadiya07", "e": 30778, "s": 29066, "text": null }, { "code": "# Python3 implementation to find the sum# of the array for the given Q queries # Function that print the sum of# the array for Q queriesdef sumOfTheArrayForQuery(A, N, X, Y, Q): sum = 0 # Stores the frequencies # of array elements count = {} # Calculate the sum of # the initial array and # store the frequency of # each element in map for i in range(N): sum += A[i] if A[i] in count: count[A[i]] += 1 else: count[A[i]] = 1 # Iterate for all the queries for i in range(Q): # Store query values x = X[i] y = Y[i] if X[i] not in count: count[X[i]] = 0 if Y[i] not in count: count[Y[i]] = 0 # Decrement the sum accordingly sum -= (count[X[i]] * X[i]) # Increment the sum accordingly sum += count[X[i]] * Y[i] # Set count of Y[i] count[Y[i]] += count[X[i]] # Reset count of X[i] count[X[i]] = 0 # Print the sum print(sum, end = \" \") # Driver Codearr = [ 1, 2, 1, 3, 2, ]X = [ 2, 3, 5 ]Y = [ 3, 1, 2 ]N = len(arr)Q = len(X) # Function callsumOfTheArrayForQuery(arr, N, X, Y, Q) # This code is contributed by avanitrachhadiya2155", "e": 32037, "s": 30778, "text": null }, { "code": "// C# implementation to// find the sum of the array// for the given Q queriesusing System;using System.Collections.Generic;class GFG{ // Function that print the sum of// the array for Q queriespublic static void sumOfTheArrayForQuery(int[] A, int N, int[] X, int[] Y, int Q){ int sum = 0; // Stores the frequencies // of array elements // Create an empty hash map Dictionary<int, int> count = new Dictionary<int, int>(); // Calculate the sum of // the initial array and // store the frequency of // each element in map for (int i = 0; i < N; i++) { sum += A[i]; if (count.ContainsKey(A[i])) { count[A[i]]= count[A[i]] + 1; } else { count.Add(A[i], 1); } } // Iterate for all the queries for (int i = 0; i < Q; i++) { // Store query values int x = X[i], y = Y[i]; if(count.ContainsKey(X[i])) { // Decrement the sum accordingly sum -= count[X[i]] * X[i]; // Increment the sum accordingly sum += count[X[i]] * Y[i]; } // Set count of Y[i] if(count.ContainsKey(Y[i]) && count.ContainsKey(X[i])) { count[Y[i]] = count[Y[i]] + count[X[i]]; } // Reset count of X[i] if(count.ContainsKey(X[i])) { count[X[i]] = 0; } // Print the sum Console.Write(sum + \" \"); }} // Driver codepublic static void Main(String[] args){ int []arr = {1, 2, 1, 3, 2}; int []X = {2, 3, 5}; int []Y = {3, 1, 2}; int N = arr.Length; int Q = X.Length; // Function call sumOfTheArrayForQuery(arr, N, X, Y, Q);}} // This code is contributed by Amit Katiyar", "e": 33777, "s": 32037, "text": null }, { "code": "<script> // Javascript implementation to find the sum// of the array for the given Q queries // Function that print the sum of// the array for Q queriesfunction sumOfTheArrayForQuery(A, N, X, Y, Q){ var sum = 0; // Stores the frequencies // of array elements var count = new Map(); // Calculate the sum of // the initial array and // store the frequency of // each element in map for (var i = 0; i < N; i++) { sum += A[i]; if(count.has(A[i])) count.set(A[i], count.get(A[i])+1) else count.set(A[i], 1) } // Iterate for all the queries for (var i = 0; i < Q; i++) { // Store query values var x = X[i], y = Y[i]; if(count.has(X[i])) { // Decrement the sum accordingly sum -= count.get(X[i]) * X[i]; // Increment the sum accordingly sum += count.get(X[i]) * Y[i]; } if(count.has(Y[i])) { // Set count of Y[i] count.set(Y[i], count.get(Y[i]) + count.get(X[i])); } // Reset count of X[i] count.set(X[i] , 0); // Print the sum document.write( sum + \" \"); }} // Driver Codevar arr = [1, 2, 1, 3, 2];var X = [2, 3, 5 ];var Y = [3, 1, 2 ];var N = arr.length;var Q = X.length;// Function callsumOfTheArrayForQuery(arr, N, X, Y, Q); </script>", "e": 35157, "s": 33777, "text": null }, { "code": null, "e": 35164, "s": 35157, "text": "11 5 5" }, { "code": null, "e": 35265, "s": 35166, "text": "Time Complexity: O(N), as each query has a computational complexity of O(1). Auxiliary Space: O(N)" }, { "code": null, "e": 35286, "s": 35265, "text": "avanitrachhadiya2155" }, { "code": null, "e": 35304, "s": 35286, "text": "divyeshrabadiya07" }, { "code": null, "e": 35319, "s": 35304, "text": "amit143katiyar" }, { "code": null, "e": 35325, "s": 35319, "text": "itsok" }, { "code": null, "e": 35345, "s": 35325, "text": "array-range-queries" }, { "code": null, "e": 35353, "s": 35345, "text": "cpp-map" }, { "code": null, "e": 35372, "s": 35353, "text": "frequency-counting" }, { "code": null, "e": 35379, "s": 35372, "text": "Arrays" }, { "code": null, "e": 35403, "s": 35379, "text": "Competitive Programming" }, { "code": null, "e": 35416, "s": 35403, "text": "Mathematical" }, { "code": null, "e": 35423, "s": 35416, "text": "Arrays" }, { "code": null, "e": 35436, "s": 35423, "text": "Mathematical" }, { "code": null, "e": 35534, "s": 35436, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35602, "s": 35534, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 35646, "s": 35602, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 35669, "s": 35646, "text": "Introduction to Arrays" }, { "code": null, "e": 35701, "s": 35669, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 35715, "s": 35701, "text": "Linear Search" }, { "code": null, "e": 35758, "s": 35715, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 35801, "s": 35758, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 35842, "s": 35801, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 35920, "s": 35842, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" } ]
Algorithms | Analysis of Algorithms | Question 1 - GeeksforGeeks
28 Jun, 2021 What is time complexity of fun()? int fun(int n){ int count = 0; for (int i = n; i > 0; i /= 2) for (int j = 0; j < i; j++) count += 1; return count;} (A) O(n^2)(B) O(nLogn)(C) O(n)(D) O(nLognLogn)Answer: (C)Explanation: For a input integer n, the innermost statement of fun() is executed following times. n + n/2 + n/4 + ... 1 So time complexity T(n) can be written as T(n) = O(n + n/2 + n/4 + ... 1) = O(n) The value of count is also n + n/2 + n/4 + .. + 1 Quiz of this Question Algorithms-Analysis of Algorithms Analysis of Algorithms Algorithms Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Algorithms | Dynamic Programming | Question 2 Algorithms | Dynamic Programming | Question 3 Algorithms | Sorting | Question 9 Algorithms Quiz | Dynamic Programming | Question 8 Algorithms | Bit Algorithms | Question 3 Algorithms | Sorting | Question 5 Algorithms | Bit Algorithms | Question 2 Algorithms | Sorting | Question 6 Data Structures and Algorithms | Set 38 Algorithms | Bit Algorithms | Question 1
[ { "code": null, "e": 24958, "s": 24930, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24992, "s": 24958, "text": "What is time complexity of fun()?" }, { "code": "int fun(int n){ int count = 0; for (int i = n; i > 0; i /= 2) for (int j = 0; j < i; j++) count += 1; return count;}", "e": 25123, "s": 24992, "text": null }, { "code": null, "e": 25278, "s": 25123, "text": "(A) O(n^2)(B) O(nLogn)(C) O(n)(D) O(nLognLogn)Answer: (C)Explanation: For a input integer n, the innermost statement of fun() is executed following times." }, { "code": null, "e": 25300, "s": 25278, "text": "n + n/2 + n/4 + ... 1" }, { "code": null, "e": 25342, "s": 25300, "text": "So time complexity T(n) can be written as" }, { "code": null, "e": 25381, "s": 25342, "text": "T(n) = O(n + n/2 + n/4 + ... 1) = O(n)" }, { "code": null, "e": 25431, "s": 25381, "text": "The value of count is also n + n/2 + n/4 + .. + 1" }, { "code": null, "e": 25453, "s": 25431, "text": "Quiz of this Question" }, { "code": null, "e": 25487, "s": 25453, "text": "Algorithms-Analysis of Algorithms" }, { "code": null, "e": 25510, "s": 25487, "text": "Analysis of Algorithms" }, { "code": null, "e": 25526, "s": 25510, "text": "Algorithms Quiz" }, { "code": null, "e": 25624, "s": 25526, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25633, "s": 25624, "text": "Comments" }, { "code": null, "e": 25646, "s": 25633, "text": "Old Comments" }, { "code": null, "e": 25692, "s": 25646, "text": "Algorithms | Dynamic Programming | Question 2" }, { "code": null, "e": 25738, "s": 25692, "text": "Algorithms | Dynamic Programming | Question 3" }, { "code": null, "e": 25772, "s": 25738, "text": "Algorithms | Sorting | Question 9" }, { "code": null, "e": 25823, "s": 25772, "text": "Algorithms Quiz | Dynamic Programming | Question 8" }, { "code": null, "e": 25864, "s": 25823, "text": "Algorithms | Bit Algorithms | Question 3" }, { "code": null, "e": 25898, "s": 25864, "text": "Algorithms | Sorting | Question 5" }, { "code": null, "e": 25939, "s": 25898, "text": "Algorithms | Bit Algorithms | Question 2" }, { "code": null, "e": 25973, "s": 25939, "text": "Algorithms | Sorting | Question 6" }, { "code": null, "e": 26013, "s": 25973, "text": "Data Structures and Algorithms | Set 38" } ]
Deploying a Text Classification Model in Python | by Miguel Fernández Zafra | Towards Data Science
This article is the last of a series in which I cover the whole process of developing a machine learning project. If you have not read the previous two articles, I strongly encourage you to do it here and here. The project involves the creation of a real-time web application that gathers data from several newspapers and shows a summary of the different topics that are being discussed in the news articles. This is achieved with a supervised machine learning classification model that is able to predict the category of a given news article, a web scraping method that gets the latest news from the newspapers, and an interactive web application that shows the obtained results to the user. As I explained in the first post of this series, the reason I’m writing these articles is because I’ve noticed that most of the times, the content published on the internet, books or literature regarding data science focus on the following: we have a labeled dataset and we train models to obtain a performance metric. This means crucial concepts such as data labeling or model deployment are ignored. However, it turns out that machine learning and data science are intended to solve problems and provide useful information. So, having a model with 99% accuracy but not knowing how to take advantage of it will make us realize that we have lost our time. That’s why, in this series of posts, I try to cover, from the beginning to the very end, all the necessary steps to build a machine learning application from scratch that is useful to the final user and provides them with valuable insights or information. So, the whole process of the development of this project has been divided into three different posts: Classification model training (link) News articles web scraping (link) App creation and deployment (this post) The GitHub repo can be found here. It includes all the code and a complete report. In the first article, we developed the text classification model in Python, which allowed us to get a certain news article text and predict its category with overall good accuracy. In the second article, we created a script that web-scraped the latest news articles from different newspapers and stored the text. In this post, we’ll put all the pieces together and deploy our machine learning model so that it can provide useful, handy and real-time insights to the final user. We will follow these steps: Considerations before the deployment Creation of a Dash web application Deployment with Heroku Final thoughts At this point, we have trained a machine learning model with a dataset that contained news articles from 2004 to 2005. Our intention now is to apply this model to live, current data. It is easy to understand that this may be the first limitation of our web application, and we’ll see it with a simple example: suppose we run our web application and try to classify an article that talks about the new launch of the iPhone 11 and focuses on its amazing, state-of-the-art features such as a Retina display, 5G network support, etc... If we look back to 2004, one of the bestselling mobile phones was this one: So, it is probable that a lot of the terms that we find in the current data didn’t even exist back in 2004 and, therefore, don’t exist in our dataset. As an example, this is an extract from an article in our sample: Thousands of people queued for hours to get hold of one of the 200,000 PSPs which were shipped to retailers. The handheld console can play games, music and movies and goes on sale in Europe and North America next year. Despite the demand Sony said it would not increase the 500,000-strong stock of PSPs it plans to ship by year’s end. Some of you won’t even remember this portable console! I hope this makes the following statement straightforward: the more similar the data we used for training and the data we’ll feed into the model once deployed are, the better. If the data on both stages is not similar, we will be addressing what is called a data mismatch problem. And, although I know this may sound too obvious, in practice I have seen a lot of models which didn’t take into account this issue, which can lead to really bad performance with live data even though we had a really good one with training data and, consequently, to a useless application. And, how can we solve this? Should we try to get even higher accuracy when training our model, by spending a lot of time creating features, or with hyperparameter tuning? You guessed it right: No. The only way to address this problem is to use a more updated corpus to train the model. And there’s no magic machine learning can provide here. In order to convert our raw text articles into numbers that could be fed into the machine learning model, we first cleaned the text in several steps: removing stop words, lemmatizing, etc... After that, we applied a TF-IDF vectorization to convert text to numeric features. So, when we have our app deployed and get a new text from a newspaper, we will need to transform the raw text exactly the same as we did. As an example, we used a pre-built stop word vector from NLTK. This means that when we run our web application, we will need to somehow have available this vector so that these words can be removed. Regarding the TF-IDF vectorization, we have an important point here: as we saw in the first article, this vectorizer calculates, for a term t in a document d, the term frecuency in that document and the Inverse Document Frequency, which represents whether that term appears a lot in the corpus (and therefore it is a common term) or not (and it is an uncommon term so it is kind of “important”). And it is important to note that this corpus we’re referring to is the training corpus. This means that, when getting a single news article from the web-scraping process, the term frequency will be calculated only in that article, but the inverse document frequency will be calculated over the training corpus. So, as it happened with the modern words associated with the newest iPhone, if we get a word from our live data that is not present in the training corpus, we won’t be able to calculate a TF-IDF score. And it will be ignored. Again, we see the importance of the data mismatch problem. We will cover it in a moment, but basically our web application will consist in a python script that will be executed and will give us with the results. So, as it happened with the NLTK stop words vector, we will need to create an environment where the script can be executed and has all the necessary dependencies available: from the basic libraries (sklearn, numpy, etc...) to the trained model, the TF-IDF vectorizer, etc... Finally, we need to take care of the user experience. So, as an example, if it takes us 2 minutes to scrape the latest 5 articles from a certain newspaper, we should probably not include it as an option for the user. Once we have summarized all the things that we need to consider when deploying a model, it is clear that only focusing on getting a good accuracy in the training set and not taking into account all these considerations can lead us to a useless web application. After discussing these issues, we’ll see how to create the application with Dash and deploy it with Heroku. Dash and Heroku have really good documentation, so I won’t spend too much time with the technical details here. Both can be learnt in a few hours by anyone, and I think the methodological considerations we have been covering are much more valuable. Dash is a productive Python framework for building web applications. It is written on top of Flask, Plotly.js and React.js, and it is pretty simple to use, but works amazingly. In the Dash webpage there is a really good tutorial that covers the creation of a web application from scratch explaining each and every step: the installation, the layout (what defines how our app looks like), the callbacks (which define the “things that happen”) and some advanced concepts that will let us build the app just as we want it. In order to create the code for the web application, we can execute it locally and the application will display in the browser. This way we can make easy changes and build the app as we want before deploying it. The code that is under my web application can be found here. After we have the code ready, the last step is to deploy the application. There are many platforms that allow us to deploy a web application. Two good ones are Dash Enterprise and Heroku. I used Heroku since you can deploy an app for free (with some limitations), and for a small amount you can get a fully-operating server. Again, Heroku has a really good tutorial that can be found here. It goes step by step covering all you need to deploy the app. For this project, I deployed the app in Windows through anaconda. The steps I followed are: # after signing in to Heroku and opening the anaconda prompt# we create a new folder$ mkdir dash-app-lnclass$ cd dash-app-lnclass# initialize the folder with git$ git init After that, we create an environment file (environment.yml) in which we will indicate the dependencies we are going to need: name: dash_app_lnclass #Environment namedependencies: - python=3.6 - pip: - dash - dash-renderer - dash-core-components - dash-html-components - dash-table - plotly - gunicorn # for app deployment - nltk - scikit-learn - beautifulsoup4 - requests - pandas - numpy - lxml And activate the environment: $ conda env create$ activate dash_app_lnclass Then, we initialize the folder with app.py, requirements.txt and a Procfile: # the procfile must contain the following line of codeweb: gunicorn app:server# to create the requirements.txt file, we run the following:$ pip freeze > requirements.txt Finally, since we will be using nltk downloads (for the stopwords and other functions) and pickles, we need to add the nltk.txt file and the Pickles folder. Finally we initialize Heroku, add the files to Git and deploy: $ heroku create lnclass # change my-dash-app to a unique name$ git add . # add all files to git$ git commit -m 'Comment'$ git push heroku master # deploy code to heroku$ heroku ps:scale web=1 # run the app with a 1 heroku "dyno" The detailed instructions can be found here. Once we have followed all the steps, we will now have our web application ready to use! It can be found in this link. Please take into account that this app has not been under periodic maintenance and therefore you may experience some errors. So this series of articles has come to an end. We have covered the whole process of creating a machine learning-based application, from getting the training data to creating the application and deploying it. I hope it has been useful and has illustrated all the steps and considerations that need to be taken into account when facing a new project. I have been exposing my thoughts and advice throughout the three articles, and they can be summarized in just a couple of paragraphs: Don’t ever lose sight of the objective you’re pursuing: machine learning models are really fancy, but at the end, if they don’t provide some utility they are worthless. So it is important to always keep in mind which is the utility we are providing to the user. In addition, it is extremely beneficial to not lose the end-to-end vision of the project. As an example, when we are in the model training stage, we need to keep in mind things that are ahead that step, such as how is going to be the data when the app is deployed to avoid data mismatch. Hope these articles have been useful, and if you have any question don’t hesitate to contact me!
[ { "code": null, "e": 383, "s": 172, "text": "This article is the last of a series in which I cover the whole process of developing a machine learning project. If you have not read the previous two articles, I strongly encourage you to do it here and here." }, { "code": null, "e": 581, "s": 383, "text": "The project involves the creation of a real-time web application that gathers data from several newspapers and shows a summary of the different topics that are being discussed in the news articles." }, { "code": null, "e": 865, "s": 581, "text": "This is achieved with a supervised machine learning classification model that is able to predict the category of a given news article, a web scraping method that gets the latest news from the newspapers, and an interactive web application that shows the obtained results to the user." }, { "code": null, "e": 1267, "s": 865, "text": "As I explained in the first post of this series, the reason I’m writing these articles is because I’ve noticed that most of the times, the content published on the internet, books or literature regarding data science focus on the following: we have a labeled dataset and we train models to obtain a performance metric. This means crucial concepts such as data labeling or model deployment are ignored." }, { "code": null, "e": 1521, "s": 1267, "text": "However, it turns out that machine learning and data science are intended to solve problems and provide useful information. So, having a model with 99% accuracy but not knowing how to take advantage of it will make us realize that we have lost our time." }, { "code": null, "e": 1777, "s": 1521, "text": "That’s why, in this series of posts, I try to cover, from the beginning to the very end, all the necessary steps to build a machine learning application from scratch that is useful to the final user and provides them with valuable insights or information." }, { "code": null, "e": 1879, "s": 1777, "text": "So, the whole process of the development of this project has been divided into three different posts:" }, { "code": null, "e": 1916, "s": 1879, "text": "Classification model training (link)" }, { "code": null, "e": 1950, "s": 1916, "text": "News articles web scraping (link)" }, { "code": null, "e": 1990, "s": 1950, "text": "App creation and deployment (this post)" }, { "code": null, "e": 2073, "s": 1990, "text": "The GitHub repo can be found here. It includes all the code and a complete report." }, { "code": null, "e": 2254, "s": 2073, "text": "In the first article, we developed the text classification model in Python, which allowed us to get a certain news article text and predict its category with overall good accuracy." }, { "code": null, "e": 2386, "s": 2254, "text": "In the second article, we created a script that web-scraped the latest news articles from different newspapers and stored the text." }, { "code": null, "e": 2579, "s": 2386, "text": "In this post, we’ll put all the pieces together and deploy our machine learning model so that it can provide useful, handy and real-time insights to the final user. We will follow these steps:" }, { "code": null, "e": 2616, "s": 2579, "text": "Considerations before the deployment" }, { "code": null, "e": 2651, "s": 2616, "text": "Creation of a Dash web application" }, { "code": null, "e": 2674, "s": 2651, "text": "Deployment with Heroku" }, { "code": null, "e": 2689, "s": 2674, "text": "Final thoughts" }, { "code": null, "e": 2872, "s": 2689, "text": "At this point, we have trained a machine learning model with a dataset that contained news articles from 2004 to 2005. Our intention now is to apply this model to live, current data." }, { "code": null, "e": 3221, "s": 2872, "text": "It is easy to understand that this may be the first limitation of our web application, and we’ll see it with a simple example: suppose we run our web application and try to classify an article that talks about the new launch of the iPhone 11 and focuses on its amazing, state-of-the-art features such as a Retina display, 5G network support, etc..." }, { "code": null, "e": 3297, "s": 3221, "text": "If we look back to 2004, one of the bestselling mobile phones was this one:" }, { "code": null, "e": 3448, "s": 3297, "text": "So, it is probable that a lot of the terms that we find in the current data didn’t even exist back in 2004 and, therefore, don’t exist in our dataset." }, { "code": null, "e": 3513, "s": 3448, "text": "As an example, this is an extract from an article in our sample:" }, { "code": null, "e": 3848, "s": 3513, "text": "Thousands of people queued for hours to get hold of one of the 200,000 PSPs which were shipped to retailers. The handheld console can play games, music and movies and goes on sale in Europe and North America next year. Despite the demand Sony said it would not increase the 500,000-strong stock of PSPs it plans to ship by year’s end." }, { "code": null, "e": 3903, "s": 3848, "text": "Some of you won’t even remember this portable console!" }, { "code": null, "e": 4079, "s": 3903, "text": "I hope this makes the following statement straightforward: the more similar the data we used for training and the data we’ll feed into the model once deployed are, the better." }, { "code": null, "e": 4473, "s": 4079, "text": "If the data on both stages is not similar, we will be addressing what is called a data mismatch problem. And, although I know this may sound too obvious, in practice I have seen a lot of models which didn’t take into account this issue, which can lead to really bad performance with live data even though we had a really good one with training data and, consequently, to a useless application." }, { "code": null, "e": 4815, "s": 4473, "text": "And, how can we solve this? Should we try to get even higher accuracy when training our model, by spending a lot of time creating features, or with hyperparameter tuning? You guessed it right: No. The only way to address this problem is to use a more updated corpus to train the model. And there’s no magic machine learning can provide here." }, { "code": null, "e": 5089, "s": 4815, "text": "In order to convert our raw text articles into numbers that could be fed into the machine learning model, we first cleaned the text in several steps: removing stop words, lemmatizing, etc... After that, we applied a TF-IDF vectorization to convert text to numeric features." }, { "code": null, "e": 5227, "s": 5089, "text": "So, when we have our app deployed and get a new text from a newspaper, we will need to transform the raw text exactly the same as we did." }, { "code": null, "e": 5426, "s": 5227, "text": "As an example, we used a pre-built stop word vector from NLTK. This means that when we run our web application, we will need to somehow have available this vector so that these words can be removed." }, { "code": null, "e": 5822, "s": 5426, "text": "Regarding the TF-IDF vectorization, we have an important point here: as we saw in the first article, this vectorizer calculates, for a term t in a document d, the term frecuency in that document and the Inverse Document Frequency, which represents whether that term appears a lot in the corpus (and therefore it is a common term) or not (and it is an uncommon term so it is kind of “important”)." }, { "code": null, "e": 6133, "s": 5822, "text": "And it is important to note that this corpus we’re referring to is the training corpus. This means that, when getting a single news article from the web-scraping process, the term frequency will be calculated only in that article, but the inverse document frequency will be calculated over the training corpus." }, { "code": null, "e": 6418, "s": 6133, "text": "So, as it happened with the modern words associated with the newest iPhone, if we get a word from our live data that is not present in the training corpus, we won’t be able to calculate a TF-IDF score. And it will be ignored. Again, we see the importance of the data mismatch problem." }, { "code": null, "e": 6846, "s": 6418, "text": "We will cover it in a moment, but basically our web application will consist in a python script that will be executed and will give us with the results. So, as it happened with the NLTK stop words vector, we will need to create an environment where the script can be executed and has all the necessary dependencies available: from the basic libraries (sklearn, numpy, etc...) to the trained model, the TF-IDF vectorizer, etc..." }, { "code": null, "e": 7063, "s": 6846, "text": "Finally, we need to take care of the user experience. So, as an example, if it takes us 2 minutes to scrape the latest 5 articles from a certain newspaper, we should probably not include it as an option for the user." }, { "code": null, "e": 7324, "s": 7063, "text": "Once we have summarized all the things that we need to consider when deploying a model, it is clear that only focusing on getting a good accuracy in the training set and not taking into account all these considerations can lead us to a useless web application." }, { "code": null, "e": 7681, "s": 7324, "text": "After discussing these issues, we’ll see how to create the application with Dash and deploy it with Heroku. Dash and Heroku have really good documentation, so I won’t spend too much time with the technical details here. Both can be learnt in a few hours by anyone, and I think the methodological considerations we have been covering are much more valuable." }, { "code": null, "e": 8201, "s": 7681, "text": "Dash is a productive Python framework for building web applications. It is written on top of Flask, Plotly.js and React.js, and it is pretty simple to use, but works amazingly. In the Dash webpage there is a really good tutorial that covers the creation of a web application from scratch explaining each and every step: the installation, the layout (what defines how our app looks like), the callbacks (which define the “things that happen”) and some advanced concepts that will let us build the app just as we want it." }, { "code": null, "e": 8413, "s": 8201, "text": "In order to create the code for the web application, we can execute it locally and the application will display in the browser. This way we can make easy changes and build the app as we want before deploying it." }, { "code": null, "e": 8474, "s": 8413, "text": "The code that is under my web application can be found here." }, { "code": null, "e": 8548, "s": 8474, "text": "After we have the code ready, the last step is to deploy the application." }, { "code": null, "e": 8799, "s": 8548, "text": "There are many platforms that allow us to deploy a web application. Two good ones are Dash Enterprise and Heroku. I used Heroku since you can deploy an app for free (with some limitations), and for a small amount you can get a fully-operating server." }, { "code": null, "e": 8926, "s": 8799, "text": "Again, Heroku has a really good tutorial that can be found here. It goes step by step covering all you need to deploy the app." }, { "code": null, "e": 9018, "s": 8926, "text": "For this project, I deployed the app in Windows through anaconda. The steps I followed are:" }, { "code": null, "e": 9190, "s": 9018, "text": "# after signing in to Heroku and opening the anaconda prompt# we create a new folder$ mkdir dash-app-lnclass$ cd dash-app-lnclass# initialize the folder with git$ git init" }, { "code": null, "e": 9315, "s": 9190, "text": "After that, we create an environment file (environment.yml) in which we will indicate the dependencies we are going to need:" }, { "code": null, "e": 9630, "s": 9315, "text": "name: dash_app_lnclass #Environment namedependencies: - python=3.6 - pip: - dash - dash-renderer - dash-core-components - dash-html-components - dash-table - plotly - gunicorn # for app deployment - nltk - scikit-learn - beautifulsoup4 - requests - pandas - numpy - lxml" }, { "code": null, "e": 9660, "s": 9630, "text": "And activate the environment:" }, { "code": null, "e": 9706, "s": 9660, "text": "$ conda env create$ activate dash_app_lnclass" }, { "code": null, "e": 9783, "s": 9706, "text": "Then, we initialize the folder with app.py, requirements.txt and a Procfile:" }, { "code": null, "e": 9953, "s": 9783, "text": "# the procfile must contain the following line of codeweb: gunicorn app:server# to create the requirements.txt file, we run the following:$ pip freeze > requirements.txt" }, { "code": null, "e": 10110, "s": 9953, "text": "Finally, since we will be using nltk downloads (for the stopwords and other functions) and pickles, we need to add the nltk.txt file and the Pickles folder." }, { "code": null, "e": 10173, "s": 10110, "text": "Finally we initialize Heroku, add the files to Git and deploy:" }, { "code": null, "e": 10403, "s": 10173, "text": "$ heroku create lnclass # change my-dash-app to a unique name$ git add . # add all files to git$ git commit -m 'Comment'$ git push heroku master # deploy code to heroku$ heroku ps:scale web=1 # run the app with a 1 heroku \"dyno\"" }, { "code": null, "e": 10448, "s": 10403, "text": "The detailed instructions can be found here." }, { "code": null, "e": 10566, "s": 10448, "text": "Once we have followed all the steps, we will now have our web application ready to use! It can be found in this link." }, { "code": null, "e": 10691, "s": 10566, "text": "Please take into account that this app has not been under periodic maintenance and therefore you may experience some errors." }, { "code": null, "e": 11174, "s": 10691, "text": "So this series of articles has come to an end. We have covered the whole process of creating a machine learning-based application, from getting the training data to creating the application and deploying it. I hope it has been useful and has illustrated all the steps and considerations that need to be taken into account when facing a new project. I have been exposing my thoughts and advice throughout the three articles, and they can be summarized in just a couple of paragraphs:" }, { "code": null, "e": 11436, "s": 11174, "text": "Don’t ever lose sight of the objective you’re pursuing: machine learning models are really fancy, but at the end, if they don’t provide some utility they are worthless. So it is important to always keep in mind which is the utility we are providing to the user." }, { "code": null, "e": 11724, "s": 11436, "text": "In addition, it is extremely beneficial to not lose the end-to-end vision of the project. As an example, when we are in the model training stage, we need to keep in mind things that are ahead that step, such as how is going to be the data when the app is deployed to avoid data mismatch." } ]
Generating Random id's using UUID in Python
UUID is having the full form Universal Unique Identifier, it is a python library which supports 128 bits ids for generating random objects. As discussed, we can use it to generate unique random id for random objects. For cryptography and hashing applications, this id can be used. For generating random documents and also addresses etc. this id can be used. Method1 Example code import uuid print ("Random id using uuid1() is : ",end="") print (uuid.uuid1()) Output Random id using uuid1() is : 4adeede2-e5d8-11e8-bd27-185e0fd4f8b3 bytes − It returns id in the format of 16 byte string. int − It returns id in format of 128-bit integer. hex − As 32 character hexadecimal string, it returns random id. version − version number of UUID. variant − It determines the internal layout of UUID. time_low −Indicates the first 32 bits of id. time_mid −Indicates the next 16 bits of id. time_hi_version − Indicates the next 16 bits of id. clock_seq_hi_variant − Indicates next 8 bits of id. clock_seq_low − Indicates next 8 bits of id. node − Indicates last 48 bits of id. time − Indicates time component field of id. clock_seq − Indicates 14 bit sequence number. import uuid id = uuid.uuid1() # Representations of uuid1() print ("Different Representations of uuid1() are : ") print ("Representation in byte : ",end="") print (repr(id.bytes)) print ("Representation in int : ",end="") print (id.int) print ("Representation in hex : ",end="") print (id.hex) print("\n") # Components of uuid1() print ("Different Components of uuid1() are : ") print ("UUID Version : ",end="") print (id.version) print ("UUID Variant : ",end="") print (id.variant) print("\n") # Fields of uuid1() print ("Fields of uuid1() are : ") print ("UUID Fields : ",end="") print (id.fields) print("\n") # uuid1() Time Component print ("uuid1() time Component is : ") print ("Time component : ",end="") print (id.node) Different Representations of uuid1() are : Representation in byte : b'\x1a\xd2\xa7F\xe5\xe4\x11\xe8\xbd\x9c\x18^\x0f\xd4\xf8\xb3' Representation in int : 35653703010223099234452630771665795251 Representation in hex : 1ad2a746e5e411e8bd9c185e0fd4f8b3 Different Components of uuid1() are : UUID Version : 1 UUID Variant : specified in RFC 4122 Fields of uuid1() are : UUID Fields : (450012998, 58852, 4584, 189, 156, 26792271607987) uuid1() time Component is : Time component : 26792271607987 Method2 Example code import uuid id = uuid.uuid4() # Id generated using uuid4() print ("The id generated using uuid4() : ",end="") print (id) Output The id generated using uuid4() : 21764219-e3d9-4bd3-a768-0bbc6e376bc0
[ { "code": null, "e": 1202, "s": 1062, "text": "UUID is having the full form Universal Unique Identifier, it is a python library which supports 128 bits ids for generating random objects." }, { "code": null, "e": 1279, "s": 1202, "text": "As discussed, we can use it to generate unique random id for random objects." }, { "code": null, "e": 1343, "s": 1279, "text": "For cryptography and hashing applications, this id can be used." }, { "code": null, "e": 1420, "s": 1343, "text": "For generating random documents and also addresses etc. this id can be used." }, { "code": null, "e": 1428, "s": 1420, "text": "Method1" }, { "code": null, "e": 1441, "s": 1428, "text": "Example code" }, { "code": null, "e": 1521, "s": 1441, "text": "import uuid\nprint (\"Random id using uuid1() is : \",end=\"\")\nprint (uuid.uuid1())" }, { "code": null, "e": 1528, "s": 1521, "text": "Output" }, { "code": null, "e": 1595, "s": 1528, "text": "Random id using uuid1() is : 4adeede2-e5d8-11e8-bd27-185e0fd4f8b3\n" }, { "code": null, "e": 1650, "s": 1595, "text": "bytes − It returns id in the format of 16 byte string." }, { "code": null, "e": 1700, "s": 1650, "text": "int − It returns id in format of 128-bit integer." }, { "code": null, "e": 1764, "s": 1700, "text": "hex − As 32 character hexadecimal string, it returns random id." }, { "code": null, "e": 1798, "s": 1764, "text": "version − version number of UUID." }, { "code": null, "e": 1851, "s": 1798, "text": "variant − It determines the internal layout of UUID." }, { "code": null, "e": 1896, "s": 1851, "text": "time_low −Indicates the first 32 bits of id." }, { "code": null, "e": 1940, "s": 1896, "text": "time_mid −Indicates the next 16 bits of id." }, { "code": null, "e": 1992, "s": 1940, "text": "time_hi_version − Indicates the next 16 bits of id." }, { "code": null, "e": 2044, "s": 1992, "text": "clock_seq_hi_variant − Indicates next 8 bits of id." }, { "code": null, "e": 2089, "s": 2044, "text": "clock_seq_low − Indicates next 8 bits of id." }, { "code": null, "e": 2126, "s": 2089, "text": "node − Indicates last 48 bits of id." }, { "code": null, "e": 2171, "s": 2126, "text": "time − Indicates time component field of id." }, { "code": null, "e": 2217, "s": 2171, "text": "clock_seq − Indicates 14 bit sequence number." }, { "code": null, "e": 2943, "s": 2217, "text": "import uuid\nid = uuid.uuid1()\n# Representations of uuid1()\nprint (\"Different Representations of uuid1() are : \")\nprint (\"Representation in byte : \",end=\"\")\nprint (repr(id.bytes))\nprint (\"Representation in int : \",end=\"\")\nprint (id.int)\nprint (\"Representation in hex : \",end=\"\")\nprint (id.hex)\nprint(\"\\n\")\n# Components of uuid1()\nprint (\"Different Components of uuid1() are : \")\nprint (\"UUID Version : \",end=\"\")\nprint (id.version)\nprint (\"UUID Variant : \",end=\"\")\nprint (id.variant)\nprint(\"\\n\")\n# Fields of uuid1()\nprint (\"Fields of uuid1() are : \")\nprint (\"UUID Fields : \",end=\"\")\nprint (id.fields)\nprint(\"\\n\")\n# uuid1() Time Component\nprint (\"uuid1() time Component is : \")\nprint (\"Time component : \",end=\"\")\nprint (id.node)" }, { "code": null, "e": 3438, "s": 2943, "text": "Different Representations of uuid1() are :\nRepresentation in byte : b'\\x1a\\xd2\\xa7F\\xe5\\xe4\\x11\\xe8\\xbd\\x9c\\x18^\\x0f\\xd4\\xf8\\xb3'\nRepresentation in int : 35653703010223099234452630771665795251\nRepresentation in hex : 1ad2a746e5e411e8bd9c185e0fd4f8b3\n\nDifferent Components of uuid1() are :\nUUID Version : 1\nUUID Variant : specified in RFC 4122\n\nFields of uuid1() are :\nUUID Fields : (450012998, 58852, 4584, 189, 156, 26792271607987)\n\nuuid1() time Component is :\nTime component : 26792271607987\n" }, { "code": null, "e": 3446, "s": 3438, "text": "Method2" }, { "code": null, "e": 3459, "s": 3446, "text": "Example code" }, { "code": null, "e": 3580, "s": 3459, "text": "import uuid\nid = uuid.uuid4()\n# Id generated using uuid4()\nprint (\"The id generated using uuid4() : \",end=\"\")\nprint (id)" }, { "code": null, "e": 3587, "s": 3580, "text": "Output" }, { "code": null, "e": 3658, "s": 3587, "text": "The id generated using uuid4() : 21764219-e3d9-4bd3-a768-0bbc6e376bc0\n" } ]
JSP - Expression Language (EL)
JSP Expression Language (EL) makes it possible to easily access application data stored in JavaBeans components. JSP EL allows you to create expressions both (a) arithmetic and (b) logical. Within a JSP EL expression, you can use integers, floating point numbers, strings, the built-in constants true and false for boolean values, and null. Typically, when you specify an attribute value in a JSP tag, you simply use a string. For example − <jsp:setProperty name = "box" property = "perimeter" value = "100"/> JSP EL allows you to specify an expression for any of these attribute values. A simple syntax for JSP EL is as follows − ${expr} Here expr specifies the expression itself. The most common operators in JSP EL are . and []. These two operators allow you to access various attributes of Java Beans and built-in JSP objects. For example, the above syntax <jsp:setProperty> tag can be written with an expression like − <jsp:setProperty name = "box" property = "perimeter" value = "${2*box.width+2*box.height}"/> When the JSP compiler sees the ${} form in an attribute, it generates code to evaluate the expression and substitues the value of expresson. You can also use the JSP EL expressions within template text for a tag. For example, the <jsp:text> tag simply inserts its content within the body of a JSP. The following <jsp:text> declaration inserts <h1>Hello JSP!</h1> into the JSP output − <jsp:text> <h1>Hello JSP!</h1> </jsp:text> You can now include a JSP EL expression in the body of a <jsp:text> tag (or any other tag) with the same ${} syntax you use for attributes. For example − <jsp:text> Box Perimeter is: ${2*box.width + 2*box.height} </jsp:text> EL expressions can use parentheses to group subexpressions. For example, ${(1 + 2) * 3} equals 9, but ${1 + (2 * 3)} equals 7. To deactivate the evaluation of EL expressions, we specify the isELIgnored attribute of the page directive as below − <%@ page isELIgnored = "true|false" %> The valid values of this attribute are true and false. If it is true, EL expressions are ignored when they appear in static text or tag attributes. If it is false, EL expressions are evaluated by the container. JSP Expression Language (EL) supports most of the arithmetic and logical operators supported by Java. Following table lists out the most frequently used operators − . Access a bean property or Map entry [] Access an array or List element ( ) Group a subexpression to change the evaluation order + Addition - Subtraction or negation of a value * Multiplication / or div Division % or mod Modulo (remainder) == or eq Test for equality != or ne Test for inequality < or lt Test for less than > or gt Test for greater than <= or le Test for less than or equal >= or ge Test for greater than or equal && or and Test for logical AND || or or Test for logical OR ! or not Unary Boolean complement empty Test for empty variable values JSP EL allows you to use functions in expressions as well. These functions must be defined in the custom tag libraries. A function usage has the following syntax − ${ns:func(param1, param2, ...)} Where ns is the namespace of the function, func is the name of the function and param1 is the first parameter value. For example, the function fn:length, which is part of the JSTL library. This function can be used as follows to get the length of a string. ${fn:length("Get my length")} To use a function from any tag library (standard or custom), you must install that library on your server and must include the library in your JSP using the <taglib> directive as explained in the JSTL chapter. The JSP expression language supports the following implicit objects − pageScope Scoped variables from page scope requestScope Scoped variables from request scope sessionScope Scoped variables from session scope applicationScope Scoped variables from application scope param Request parameters as strings paramValues Request parameters as collections of strings header HTTP request headers as strings headerValues HTTP request headers as collections of strings initParam Context-initialization parameters cookie Cookie values pageContext The JSP PageContext object for the current page You can use these objects in an expression as if they were variables. The examples that follow will help you understand the concepts − The pageContext object gives you access to the pageContext JSP object. Through the pageContext object, you can access the request object. For example, to access the incoming query string for a request, you can use the following expression − ${pageContext.request.queryString} The pageScope, requestScope, sessionScope, and applicationScope variables provide access to variables stored at each scope level. For example, if you need to explicitly access the box variable in the application scope, you can access it through the applicationScope variable as applicationScope.box. The param and paramValues objects give you access to the parameter values normally available through the request.getParameter and request.getParameterValues methods. For example, to access a parameter named order, use the expression ${param.order} or ${param["order"]}. Following is the example to access a request parameter named username − <%@ page import = "java.io.*,java.util.*" %> <%String title = "Accessing Request Param";%> <html> <head> <title><% out.print(title); %></title> </head> <body> <center> <h1><% out.print(title); %></h1> </center> <div align = "center"> <p>${param["username"]}</p> </div> </body> </html> The param object returns single string values, whereas the paramValues object returns string arrays. The header and headerValues objects give you access to the header values normally available through the request.getHeader and the request.getHeaders methods. For example, to access a header named user-agent, use the expression ${header.user-agent} or ${header["user-agent"]}. Following is the example to access a header parameter named user-agent − <%@ page import = "java.io.*,java.util.*" %> <%String title = "User Agent Example";%> <html> <head> <title><% out.print(title); %></title> </head> <body> <center> <h1><% out.print(title); %></h1> </center> <div align = "center"> <p>${header["user-agent"]}</p> </div> </body> </html> The output will somewhat be like the following − User Agent Example Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; HPNTDF; .NET4.0C; InfoPath.2) Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; HPNTDF; .NET4.0C; InfoPath.2) The header object returns single string values, whereas the headerValues object returns string arrays. 108 Lectures 11 hours Chaand Sheikh 517 Lectures 57 hours Chaand Sheikh 41 Lectures 4.5 hours Karthikeya T 42 Lectures 5.5 hours TELCOMA Global 15 Lectures 3 hours TELCOMA Global 44 Lectures 15 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 2580, "s": 2239, "text": "JSP Expression Language (EL) makes it possible to easily access application data stored in JavaBeans components. JSP EL allows you to create expressions both (a) arithmetic and (b) logical. Within a JSP EL expression, you can use integers, floating point numbers, strings, the built-in constants true and false for boolean values, and null." }, { "code": null, "e": 2680, "s": 2580, "text": "Typically, when you specify an attribute value in a JSP tag, you simply use a string. For example −" }, { "code": null, "e": 2750, "s": 2680, "text": "<jsp:setProperty name = \"box\" property = \"perimeter\" value = \"100\"/>\n" }, { "code": null, "e": 2871, "s": 2750, "text": "JSP EL allows you to specify an expression for any of these attribute values. A simple syntax for JSP EL is as follows −" }, { "code": null, "e": 2880, "s": 2871, "text": "${expr}\n" }, { "code": null, "e": 3072, "s": 2880, "text": "Here expr specifies the expression itself. The most common operators in JSP EL are . and []. These two operators allow you to access various attributes of Java Beans and built-in JSP objects." }, { "code": null, "e": 3165, "s": 3072, "text": "For example, the above syntax <jsp:setProperty> tag can be written with an expression like −" }, { "code": null, "e": 3263, "s": 3165, "text": "<jsp:setProperty name = \"box\" property = \"perimeter\" \n value = \"${2*box.width+2*box.height}\"/>\n" }, { "code": null, "e": 3404, "s": 3263, "text": "When the JSP compiler sees the ${} form in an attribute, it generates code to evaluate the expression and substitues the value of expresson." }, { "code": null, "e": 3648, "s": 3404, "text": "You can also use the JSP EL expressions within template text for a tag. For example, the <jsp:text> tag simply inserts its content within the body of a JSP. The following <jsp:text> declaration inserts <h1>Hello JSP!</h1> into the JSP output −" }, { "code": null, "e": 3694, "s": 3648, "text": "<jsp:text>\n <h1>Hello JSP!</h1>\n</jsp:text>" }, { "code": null, "e": 3848, "s": 3694, "text": "You can now include a JSP EL expression in the body of a <jsp:text> tag (or any other tag) with the same ${} syntax you use for attributes. For example −" }, { "code": null, "e": 3922, "s": 3848, "text": "<jsp:text>\n Box Perimeter is: ${2*box.width + 2*box.height}\n</jsp:text>" }, { "code": null, "e": 4049, "s": 3922, "text": "EL expressions can use parentheses to group subexpressions. For example, ${(1 + 2) * 3} equals 9, but ${1 + (2 * 3)} equals 7." }, { "code": null, "e": 4167, "s": 4049, "text": "To deactivate the evaluation of EL expressions, we specify the isELIgnored attribute of the page directive as below −" }, { "code": null, "e": 4207, "s": 4167, "text": "<%@ page isELIgnored = \"true|false\" %>\n" }, { "code": null, "e": 4418, "s": 4207, "text": "The valid values of this attribute are true and false. If it is true, EL expressions are ignored when they appear in static text or tag attributes. If it is false, EL expressions are evaluated by the container." }, { "code": null, "e": 4583, "s": 4418, "text": "JSP Expression Language (EL) supports most of the arithmetic and logical operators supported by Java. Following table lists out the most frequently used operators −" }, { "code": null, "e": 4585, "s": 4583, "text": "." }, { "code": null, "e": 4621, "s": 4585, "text": "Access a bean property or Map entry" }, { "code": null, "e": 4624, "s": 4621, "text": "[]" }, { "code": null, "e": 4656, "s": 4624, "text": "Access an array or List element" }, { "code": null, "e": 4660, "s": 4656, "text": "( )" }, { "code": null, "e": 4713, "s": 4660, "text": "Group a subexpression to change the evaluation order" }, { "code": null, "e": 4715, "s": 4713, "text": "+" }, { "code": null, "e": 4724, "s": 4715, "text": "Addition" }, { "code": null, "e": 4726, "s": 4724, "text": "-" }, { "code": null, "e": 4761, "s": 4726, "text": "Subtraction or negation of a value" }, { "code": null, "e": 4763, "s": 4761, "text": "*" }, { "code": null, "e": 4778, "s": 4763, "text": "Multiplication" }, { "code": null, "e": 4787, "s": 4778, "text": "/ or div" }, { "code": null, "e": 4796, "s": 4787, "text": "Division" }, { "code": null, "e": 4805, "s": 4796, "text": "% or mod" }, { "code": null, "e": 4824, "s": 4805, "text": "Modulo (remainder)" }, { "code": null, "e": 4833, "s": 4824, "text": "== or eq" }, { "code": null, "e": 4851, "s": 4833, "text": "Test for equality" }, { "code": null, "e": 4860, "s": 4851, "text": "!= or ne" }, { "code": null, "e": 4880, "s": 4860, "text": "Test for inequality" }, { "code": null, "e": 4888, "s": 4880, "text": "< or lt" }, { "code": null, "e": 4907, "s": 4888, "text": "Test for less than" }, { "code": null, "e": 4915, "s": 4907, "text": "> or gt" }, { "code": null, "e": 4937, "s": 4915, "text": "Test for greater than" }, { "code": null, "e": 4946, "s": 4937, "text": "<= or le" }, { "code": null, "e": 4974, "s": 4946, "text": "Test for less than or equal" }, { "code": null, "e": 4983, "s": 4974, "text": ">= or ge" }, { "code": null, "e": 5014, "s": 4983, "text": "Test for greater than or equal" }, { "code": null, "e": 5024, "s": 5014, "text": "&& or and" }, { "code": null, "e": 5045, "s": 5024, "text": "Test for logical AND" }, { "code": null, "e": 5054, "s": 5045, "text": "|| or or" }, { "code": null, "e": 5074, "s": 5054, "text": "Test for logical OR" }, { "code": null, "e": 5083, "s": 5074, "text": "! or not" }, { "code": null, "e": 5108, "s": 5083, "text": "Unary Boolean complement" }, { "code": null, "e": 5114, "s": 5108, "text": "empty" }, { "code": null, "e": 5145, "s": 5114, "text": "Test for empty variable values" }, { "code": null, "e": 5309, "s": 5145, "text": "JSP EL allows you to use functions in expressions as well. These functions must be defined in the custom tag libraries. A function usage has the following syntax −" }, { "code": null, "e": 5342, "s": 5309, "text": "${ns:func(param1, param2, ...)}\n" }, { "code": null, "e": 5599, "s": 5342, "text": "Where ns is the namespace of the function, func is the name of the function and param1 is the first parameter value. For example, the function fn:length, which is part of the JSTL library. This function can be used as follows to get the length of a string." }, { "code": null, "e": 5630, "s": 5599, "text": "${fn:length(\"Get my length\")}\n" }, { "code": null, "e": 5840, "s": 5630, "text": "To use a function from any tag library (standard or custom), you must install that library on your server and must include the library in your JSP using the <taglib> directive as explained in the JSTL chapter." }, { "code": null, "e": 5910, "s": 5840, "text": "The JSP expression language supports the following implicit objects −" }, { "code": null, "e": 5920, "s": 5910, "text": "pageScope" }, { "code": null, "e": 5953, "s": 5920, "text": "Scoped variables from page scope" }, { "code": null, "e": 5966, "s": 5953, "text": "requestScope" }, { "code": null, "e": 6002, "s": 5966, "text": "Scoped variables from request scope" }, { "code": null, "e": 6015, "s": 6002, "text": "sessionScope" }, { "code": null, "e": 6051, "s": 6015, "text": "Scoped variables from session scope" }, { "code": null, "e": 6068, "s": 6051, "text": "applicationScope" }, { "code": null, "e": 6108, "s": 6068, "text": "Scoped variables from application scope" }, { "code": null, "e": 6114, "s": 6108, "text": "param" }, { "code": null, "e": 6144, "s": 6114, "text": "Request parameters as strings" }, { "code": null, "e": 6156, "s": 6144, "text": "paramValues" }, { "code": null, "e": 6201, "s": 6156, "text": "Request parameters as collections of strings" }, { "code": null, "e": 6208, "s": 6201, "text": "header" }, { "code": null, "e": 6240, "s": 6208, "text": "HTTP request headers as strings" }, { "code": null, "e": 6253, "s": 6240, "text": "headerValues" }, { "code": null, "e": 6300, "s": 6253, "text": "HTTP request headers as collections of strings" }, { "code": null, "e": 6310, "s": 6300, "text": "initParam" }, { "code": null, "e": 6344, "s": 6310, "text": "Context-initialization parameters" }, { "code": null, "e": 6351, "s": 6344, "text": "cookie" }, { "code": null, "e": 6365, "s": 6351, "text": "Cookie values" }, { "code": null, "e": 6377, "s": 6365, "text": "pageContext" }, { "code": null, "e": 6425, "s": 6377, "text": "The JSP PageContext object for the current page" }, { "code": null, "e": 6560, "s": 6425, "text": "You can use these objects in an expression as if they were variables. The examples that follow will help you understand the concepts −" }, { "code": null, "e": 6801, "s": 6560, "text": "The pageContext object gives you access to the pageContext JSP object. Through the pageContext object, you can access the request object. For example, to access the incoming query string for a request, you can use the following expression −" }, { "code": null, "e": 6837, "s": 6801, "text": "${pageContext.request.queryString}\n" }, { "code": null, "e": 6967, "s": 6837, "text": "The pageScope, requestScope, sessionScope, and applicationScope variables provide access to variables stored at each scope level." }, { "code": null, "e": 7137, "s": 6967, "text": "For example, if you need to explicitly access the box variable in the application scope, you can access it through the applicationScope variable as applicationScope.box." }, { "code": null, "e": 7303, "s": 7137, "text": "The param and paramValues objects give you access to the parameter values normally available through the request.getParameter and request.getParameterValues methods." }, { "code": null, "e": 7407, "s": 7303, "text": "For example, to access a parameter named order, use the expression ${param.order} or ${param[\"order\"]}." }, { "code": null, "e": 7479, "s": 7407, "text": "Following is the example to access a request parameter named username −" }, { "code": null, "e": 7836, "s": 7479, "text": "<%@ page import = \"java.io.*,java.util.*\" %>\n<%String title = \"Accessing Request Param\";%>\n\n<html>\n <head>\n <title><% out.print(title); %></title>\n </head>\n \n <body>\n <center>\n <h1><% out.print(title); %></h1>\n </center>\n \n <div align = \"center\">\n <p>${param[\"username\"]}</p>\n </div>\n </body>\n</html>" }, { "code": null, "e": 7937, "s": 7836, "text": "The param object returns single string values, whereas the paramValues object returns string arrays." }, { "code": null, "e": 8095, "s": 7937, "text": "The header and headerValues objects give you access to the header values normally available through the request.getHeader and the request.getHeaders methods." }, { "code": null, "e": 8213, "s": 8095, "text": "For example, to access a header named user-agent, use the expression ${header.user-agent} or ${header[\"user-agent\"]}." }, { "code": null, "e": 8286, "s": 8213, "text": "Following is the example to access a header parameter named user-agent −" }, { "code": null, "e": 8641, "s": 8286, "text": "<%@ page import = \"java.io.*,java.util.*\" %>\n<%String title = \"User Agent Example\";%>\n\n<html>\n <head>\n <title><% out.print(title); %></title>\n </head>\n \n <body>\n <center>\n <h1><% out.print(title); %></h1>\n </center>\n \n <div align = \"center\">\n <p>${header[\"user-agent\"]}</p>\n </div>\n </body>\n</html>" }, { "code": null, "e": 8690, "s": 8641, "text": "The output will somewhat be like the following −" }, { "code": null, "e": 8909, "s": 8690, "text": "User Agent Example\n\nMozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; \n SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; \n Media Center PC 6.0; HPNTDF; .NET4.0C; InfoPath.2)\n\n" }, { "code": null, "e": 9106, "s": 8909, "text": "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; \n SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; \n Media Center PC 6.0; HPNTDF; .NET4.0C; InfoPath.2)" }, { "code": null, "e": 9209, "s": 9106, "text": "The header object returns single string values, whereas the headerValues object returns string arrays." }, { "code": null, "e": 9244, "s": 9209, "text": "\n 108 Lectures \n 11 hours \n" }, { "code": null, "e": 9259, "s": 9244, "text": " Chaand Sheikh" }, { "code": null, "e": 9294, "s": 9259, "text": "\n 517 Lectures \n 57 hours \n" }, { "code": null, "e": 9309, "s": 9294, "text": " Chaand Sheikh" }, { "code": null, "e": 9344, "s": 9309, "text": "\n 41 Lectures \n 4.5 hours \n" }, { "code": null, "e": 9358, "s": 9344, "text": " Karthikeya T" }, { "code": null, "e": 9393, "s": 9358, "text": "\n 42 Lectures \n 5.5 hours \n" }, { "code": null, "e": 9409, "s": 9393, "text": " TELCOMA Global" }, { "code": null, "e": 9442, "s": 9409, "text": "\n 15 Lectures \n 3 hours \n" }, { "code": null, "e": 9458, "s": 9442, "text": " TELCOMA Global" }, { "code": null, "e": 9492, "s": 9458, "text": "\n 44 Lectures \n 15 hours \n" }, { "code": null, "e": 9500, "s": 9492, "text": " Uplatz" }, { "code": null, "e": 9507, "s": 9500, "text": " Print" }, { "code": null, "e": 9518, "s": 9507, "text": " Add Notes" } ]
Auto-HMM in Python. Automatic Model selection, training... | by MANIE TADAYON | Towards Data Science
During my Ph.D. at UCLA, I developed various models for sequential and time-series data. The hidden Markov model (HMM) was one of the earliest models I used, which worked quite well. I could not find any tutorial or any working codes on the HMM in Python/MATLAB/R. I am releasing the Auto-HMM, which is a python package to perform automatic model selection using AIC/BIC for supervised and unsupervised HMM. This package uses hmmlearn for hidden Markov model training and decoding and it includes a model selection for the optimal number of parameters (number of mixture components, number of hidden states, etc). I implemented a similar package in MATLAB and R. Please comment under this post if you would like to see the R and MATLAB implementation of the same model. The training in HMM is done through the Baum-Welch, which is the special case of the EM algorithm. The decoding is done through the Viterbi algorithm. I guess the hmmlearn package supports the MAP decoder besides the ML (Viterbi) decoder. The model selection is done through AIC and BIC, which operate by penalizing the likelihood functions. This is done automatically here by specifying the maximum number of hidden states you like and the algorithm finds the optimal number of hidden states for the discrete HMM, and optimal number mixture component, and an optimal number of hidden states for the continuous HMM. To access the code please visit my GitHub at github.com Please go over the examples in DHMM_Testing and HMM_Testing Python files. They require you to have provided your CSV file address, number of iteration for HMM model, training size, number of features (dimension of time series). As an example, the following code performs the discrete HMM for 2000 observations with 50 points in time for a maximum of 3 hidden states. The training size is set to 0.8 (0.8 * 2000 = 1600). The Feat determines the dimensionality of the time series (1 means a univariate time series). The flag determines if you would like to sort your hidden states in descending or ascending order. from Hidden_Markov_Model import *from Hidden_Markov_Model.DHMM import *Train_ratio=0.8Max_state=3Iter=1000Feat=1N=2000T=50flag=0N_symb=3Path= 'Path to CSV file'Data=pd.read_csv(Path)Data=Data.astype(int)First_DHMM=Supervised_DHMM(Train_ratio,Max_state,Iter,Feat,N,T,Data,N_symb)First_DHMM.Best_States() For more information about my recent activity and any questions, please visit my YouTube page. I have also written tsBNgen, the Python package for generating synthetic time-series data, which can be used as the input to the Auto-HMM model. To learn more about tsBNgen, please visit my YouTube page below. www.youtube.com If you have any questions or concerns you can visit my personal page at manietadayon.com To learn more about the HMM modeling and implementation please refer to the following video:
[ { "code": null, "e": 579, "s": 171, "text": "During my Ph.D. at UCLA, I developed various models for sequential and time-series data. The hidden Markov model (HMM) was one of the earliest models I used, which worked quite well. I could not find any tutorial or any working codes on the HMM in Python/MATLAB/R. I am releasing the Auto-HMM, which is a python package to perform automatic model selection using AIC/BIC for supervised and unsupervised HMM." }, { "code": null, "e": 834, "s": 579, "text": "This package uses hmmlearn for hidden Markov model training and decoding and it includes a model selection for the optimal number of parameters (number of mixture components, number of hidden states, etc). I implemented a similar package in MATLAB and R." }, { "code": null, "e": 941, "s": 834, "text": "Please comment under this post if you would like to see the R and MATLAB implementation of the same model." }, { "code": null, "e": 1180, "s": 941, "text": "The training in HMM is done through the Baum-Welch, which is the special case of the EM algorithm. The decoding is done through the Viterbi algorithm. I guess the hmmlearn package supports the MAP decoder besides the ML (Viterbi) decoder." }, { "code": null, "e": 1557, "s": 1180, "text": "The model selection is done through AIC and BIC, which operate by penalizing the likelihood functions. This is done automatically here by specifying the maximum number of hidden states you like and the algorithm finds the optimal number of hidden states for the discrete HMM, and optimal number mixture component, and an optimal number of hidden states for the continuous HMM." }, { "code": null, "e": 1602, "s": 1557, "text": "To access the code please visit my GitHub at" }, { "code": null, "e": 1613, "s": 1602, "text": "github.com" }, { "code": null, "e": 1841, "s": 1613, "text": "Please go over the examples in DHMM_Testing and HMM_Testing Python files. They require you to have provided your CSV file address, number of iteration for HMM model, training size, number of features (dimension of time series)." }, { "code": null, "e": 2226, "s": 1841, "text": "As an example, the following code performs the discrete HMM for 2000 observations with 50 points in time for a maximum of 3 hidden states. The training size is set to 0.8 (0.8 * 2000 = 1600). The Feat determines the dimensionality of the time series (1 means a univariate time series). The flag determines if you would like to sort your hidden states in descending or ascending order." }, { "code": null, "e": 2529, "s": 2226, "text": "from Hidden_Markov_Model import *from Hidden_Markov_Model.DHMM import *Train_ratio=0.8Max_state=3Iter=1000Feat=1N=2000T=50flag=0N_symb=3Path= 'Path to CSV file'Data=pd.read_csv(Path)Data=Data.astype(int)First_DHMM=Supervised_DHMM(Train_ratio,Max_state,Iter,Feat,N,T,Data,N_symb)First_DHMM.Best_States()" }, { "code": null, "e": 2834, "s": 2529, "text": "For more information about my recent activity and any questions, please visit my YouTube page. I have also written tsBNgen, the Python package for generating synthetic time-series data, which can be used as the input to the Auto-HMM model. To learn more about tsBNgen, please visit my YouTube page below." }, { "code": null, "e": 2850, "s": 2834, "text": "www.youtube.com" }, { "code": null, "e": 2922, "s": 2850, "text": "If you have any questions or concerns you can visit my personal page at" }, { "code": null, "e": 2939, "s": 2922, "text": "manietadayon.com" } ]
Softmax Regression in Python: Multi-class Classification | by Suraj Verma | Towards Data Science
In this article, we are going to look at the Softmax Regression which is used for multi-class classification problems, and implement it on the MNIST hand-written digit recognition dataset. First, we will build on Logistic Regression to understand the Softmax function, then we will look at the Cross-entropy loss, one-hot encoding, and code it alongside. Finally, we will code the training function(fit) and see our accuracy. We will also plot our predictions. We will do it all using Python NumPy and Matplotlib. We will see how we get an accuracy of 91% in both training and test set. towardsdatascience.com As we can see above, in the logistic regression model we take a vector x (which represents only a single example out of m ) of size n (features) and take a dot product with the weights and add a bias. We will call it z (linear part) which is w.X + b . After that, we apply the activation function which is sigmoid for logistic regression to calculate y_hat . y_hat = sigmoid(z) = sigmoid(w.X + b) Every edge going from X to the linear part represents a weightand every circle of linear part has a bias . Logistic Regression is used for binary classification which means there are 2 classes(0 or 1) and because of the sigmoid function we get an output(y_hat) between 0 and 1. We interpret this output(y_hat) of a logistic model as a probability of y being 1, then the probability of y being 0 becomes (1-y_hat) . A question for you — What is the shape of w in the above image? Now, we set a goal for us — To identify which digit is in the image. We will use the MNIST hand-written dataset as a motivating example to understand Softmax Regression. It has 10 classes each representing a digit from 0 to 9. Let us look at the dataset first. Loading MNIST dataset from keras.datasets and plotting. Also, splitting the training and test set. It has 60,000 examples in the training set and 10,000 examples in the test set. #Loadingfrom keras.datasets import mnist(train_X, train_y), (test_X, test_y) = mnist.load_data()#Plottingfig = plt.figure(figsize=(10,7))for i in range(15): ax = fig.add_subplot(3, 5, i+1) ax.imshow(train_X[i], cmap=plt.get_cmap('gray')) ax.set_title('Label (y): {y}'.format(y=train_y[i])) plt.axis('off') Our data has images of digits and labels representing which digit it is. Each image is grayscale and is of size 28x28 pixels. First question — How do we take an image as an input? Every image can be represented as a 3-D matrix. If we have a color image of size 28x28, we have 28 x 28 x 3 numbers to represent that image(3 for the RGB(Red-Green-Blue) channel). But we have grayscale images which means every image has only 1 channel. So, every image is just 28x28 pixels. To input an image into the model we will flatten this 28x28 into a vector of length 784(28*28) and these 784 numbers which just pixels represent the n features for every example(image) in the dataset. X_train = train_X.reshape(60000,28*28)X_test = test_X.reshape(10000,28*28) X_train is a matrix with 60,000 rows and 784 columns. m = 60,000; n = 784 Now, our y is a vector that looks like this — train_y>> array([5, 0, 4, ..., 5, 6, 8], dtype=uint8) It is a NumPy array with labels. We cannot use this for our model, we have to somehow modify it into zeros and ones which is what we call one-hot encoding. We want our y to look like this (a matrix of size 60,000 x 10)— The rows represent i’th example and i’th column tells us the label. For example, for the first example, there is a 1 where the column name is 5 and the rest are zeros. So, the label for the first example is 5 and similarly for others. For every example, there will be only one and only one column with a 1.0 and rest will be zeros. Let’s code a function to one-hot encode our labels — c = Number of classes def one_hot(y, c): # y--> label/ground truth. # c--> Number of classes. # A zero matrix of size (m, c) y_hot = np.zeros((len(y), c)) # Putting 1 for column where the label is, # Using multidimensional indexing. y_hot[np.arange(len(y)), y] = 1 return y_hot Reference — Multi-dimensional indexing in NumPy While doing multi-class classification using Softmax Regression, we have a constraint that our model will predict only one class of c classes. For our data, it means that the model will predict only one of the digits(from 0 to 9) to be in the image. We interpreted the output of the logistic model as a probability. Similarly, we want to interpret the output of a multi-class classification model as a probability distribution. So, we want our model to output a vector of size c with each value in the vector representing the probability of each class. In other words, the c’th value in the vector represents the probability of our prediction being the c’th class. Since they are all probabilities, their sum will be equal to 1. To be in accordance with the above assumptions, we use a softmax function. The softmax for the c’th class is defined as — where, z is the linear part. For example, z1 = w1.X + b1 and similarly for others. y_hat = softmax(w.X + b) c(number of classes)=10 for our data. First, we have flattened our 28x28 image into a vector of length 784, represented by x in the above image.Second, we calculate the linear part for each class →zc = wc.X + bc where, zc is the linear part of the c’th class and wc is the set of weights of the c’th class. bc is the bias for the c’th class.Third, we calculate the softmax of zc for each class using the above formula. Combining all the classes, we get a vector of size c and their sum is equal to 1. And whichever class has the highest value(probability) will be our prediction. First, we have flattened our 28x28 image into a vector of length 784, represented by x in the above image. Second, we calculate the linear part for each class →zc = wc.X + bc where, zc is the linear part of the c’th class and wc is the set of weights of the c’th class. bc is the bias for the c’th class. Third, we calculate the softmax of zc for each class using the above formula. Combining all the classes, we get a vector of size c and their sum is equal to 1. And whichever class has the highest value(probability) will be our prediction. Note that every class has a different set of weights and a different bias. Also note that the above diagram shows the x as only one example. Every zc is a (1,1) matrix. But since we have m examples, we will represent zc (z for the c’th class) as a vector of size m. Now, to combine all the z ’s classes, we will stack them side by side which will give us a matrix of size (m,c). Similarly, for every class, the set of weights is a vector of size n . So, to combine all the classes, we will stack them side by side which will give us a matrix of size (n,c). Also, we have one bias for every class, the combined biases will be a vector of size c . Combining all the classes for the softmax gives a vector of size c . And combining all the m examples give a matrix of size (m, c). X →(m,n)y →(m,c) [one hot encoded]w →(n,c)b →vector of size c X →(m,n) y →(m,c) [one hot encoded] w →(n,c) b →vector of size c Let’s write the code for the softmax function. See comments(#). def softmax(z): # z--> linear part. # subtracting the max of z for numerical stability. exp = np.exp(z - np.max(z)) # Calculating softmax for all examples. for i in range(len(z)): exp[i] /= np.sum(exp[i]) return exp Refrence — Numerically stable softmax Refrence — Derivative of Softmax For every parametric machine learning algorithm, we need a loss function, which we want to minimize (find the global minimum of) to determine the optimal parameters(w and b) which will help us make the best predictions. For softmax regression, we use the cross-entropy(CE) loss — Refrence for how to calculate derivative of loss. Refrence — Derivative of Cross Entropy Loss with Softmax Refrence — Derivative of Softmax loss function In code, the loss looks like this — loss = -np.mean(np.log(y_hat[np.arange(len(y)), y])) Again using multidimensional indexing — Multi-dimensional indexing in NumPy Note that y is not one-hot encoded in the loss function. Initialize parameters — w and b .Find optimal w and b using Gradient Descent.Use softmax(w.X + b) to predict. Initialize parameters — w and b . Find optimal w and b using Gradient Descent. Use softmax(w.X + b) to predict. def fit(X, y, lr, c, epochs): # X --> Input. # y --> true/target value. # lr --> Learning rate. # c --> Number of classes. # epochs --> Number of iterations. # m-> number of training examples # n-> number of features m, n = X.shape # Initializing weights and bias randomly. w = np.random.random((n, c)) b = np.random.random(c) # Empty list to store losses. losses = [] # Training loop. for epoch in range(epochs): # Calculating hypothesis/prediction. z = X@w + b y_hat = softmax(z) # One-hot encoding y. y_hot = one_hot(y, c) # Calculating the gradient of loss w.r.t w and b. w_grad = (1/m)*np.dot(X.T, (y_hat - y_hot)) b_grad = (1/m)*np.sum(y_hat - y_hot) # Updating the parameters. w = w - lr*w_grad b = b - lr*b_grad # Calculating loss and appending it in the list. loss = -np.mean(np.log(y_hat[np.arange(len(y)), y])) losses.append(loss) # Printing out the loss at every 100th iteration. if epoch%100==0: print('Epoch {epoch}==> Loss = {loss}' .format(epoch=epoch, loss=loss)) return w, b, losses See comments(#). # Flattening the image.X_train = train_X.reshape(60000,28*28)# Normalizing. X_train = X_train/255# Trainingw, b, l = fit(X_train, train_y, lr=0.9, c=10, epochs=1000)>> Epoch 0==> Loss = 4.765269749988195Epoch 100==> Loss = 0.41732772667703605Epoch 200==> Loss = 0.36146764856576774Epoch 300==> Loss = 0.3371995534802398Epoch 400==> Loss = 0.32295154931574305Epoch 500==> Loss = 0.31331228168677683Epoch 600==> Loss = 0.3062124554422963Epoch 700==> Loss = 0.3006810669534496Epoch 800==> Loss = 0.29619875396394774Epoch 900==> Loss = 0.29246033264255616 We can see that the loss goes down after every iteration, which means we are doing good. See comments(#). def predict(X, w, b): # X --> Input. # w --> weights. # b --> bias. # Predicting z = X@w + b y_hat = softmax(z) # Returning the class with highest probability. return np.argmax(y_hat, axis=1) def accuracy(y, y_hat): return np.sum(y==y_hat)/len(y) Let’s calculate the accuracy of our model on the training and test set. # Accuracy for training set.train_preds = predict(X_train, w, b)accuracy(train_y, train_preds)>> 0.9187666# Accuracy for test set.# Flattening and normalizing.X_test = test_X.reshape(10000,28*28)X_test = X_test/255test_preds = predict(X_test, w, b)accuracy(test_y, test_preds)>> 0.9173 Our model has an accuracy of 91.8% on the training set and an accuracy of 91.7% on the test set. Not Bad. fig = plt.figure(figsize=(15,10))for i in range(40): ax = fig.add_subplot(5, 8, i+1) ax.imshow(test_X[i], cmap=plt.get_cmap('gray')) ax.set_title('y: {y}/ y_hat: {y_hat}' .format(y=test_y[i], y_hat=test_preds) plt.axis('off') The above figure shows the predictions by the model for 40 examples in the training set. We can see that some of them are wrongly predicted, like the one encircled in red in the above picture. Thanks for reading. For questions, comments, concerns, talk to be in the response section. More ML from scratch is coming soon. Check out the Machine Learning from scratch series — Part 1: Linear Regression from scratch in Python Part 2: Locally Weighted Linear Regression in Python Part 3: Normal Equation Using Python: The Closed-Form Solution for Linear Regression Part 4: Polynomial Regression From Scratch in Python Part 5: Logistic Regression From Scratch in Python Part 6: Implementing the Perceptron Algorithm in Python
[ { "code": null, "e": 361, "s": 172, "text": "In this article, we are going to look at the Softmax Regression which is used for multi-class classification problems, and implement it on the MNIST hand-written digit recognition dataset." }, { "code": null, "e": 633, "s": 361, "text": "First, we will build on Logistic Regression to understand the Softmax function, then we will look at the Cross-entropy loss, one-hot encoding, and code it alongside. Finally, we will code the training function(fit) and see our accuracy. We will also plot our predictions." }, { "code": null, "e": 759, "s": 633, "text": "We will do it all using Python NumPy and Matplotlib. We will see how we get an accuracy of 91% in both training and test set." }, { "code": null, "e": 782, "s": 759, "text": "towardsdatascience.com" }, { "code": null, "e": 1141, "s": 782, "text": "As we can see above, in the logistic regression model we take a vector x (which represents only a single example out of m ) of size n (features) and take a dot product with the weights and add a bias. We will call it z (linear part) which is w.X + b . After that, we apply the activation function which is sigmoid for logistic regression to calculate y_hat ." }, { "code": null, "e": 1179, "s": 1141, "text": "y_hat = sigmoid(z) = sigmoid(w.X + b)" }, { "code": null, "e": 1286, "s": 1179, "text": "Every edge going from X to the linear part represents a weightand every circle of linear part has a bias ." }, { "code": null, "e": 1594, "s": 1286, "text": "Logistic Regression is used for binary classification which means there are 2 classes(0 or 1) and because of the sigmoid function we get an output(y_hat) between 0 and 1. We interpret this output(y_hat) of a logistic model as a probability of y being 1, then the probability of y being 0 becomes (1-y_hat) ." }, { "code": null, "e": 1658, "s": 1594, "text": "A question for you — What is the shape of w in the above image?" }, { "code": null, "e": 1727, "s": 1658, "text": "Now, we set a goal for us — To identify which digit is in the image." }, { "code": null, "e": 1919, "s": 1727, "text": "We will use the MNIST hand-written dataset as a motivating example to understand Softmax Regression. It has 10 classes each representing a digit from 0 to 9. Let us look at the dataset first." }, { "code": null, "e": 2098, "s": 1919, "text": "Loading MNIST dataset from keras.datasets and plotting. Also, splitting the training and test set. It has 60,000 examples in the training set and 10,000 examples in the test set." }, { "code": null, "e": 2418, "s": 2098, "text": "#Loadingfrom keras.datasets import mnist(train_X, train_y), (test_X, test_y) = mnist.load_data()#Plottingfig = plt.figure(figsize=(10,7))for i in range(15): ax = fig.add_subplot(3, 5, i+1) ax.imshow(train_X[i], cmap=plt.get_cmap('gray')) ax.set_title('Label (y): {y}'.format(y=train_y[i])) plt.axis('off')" }, { "code": null, "e": 2544, "s": 2418, "text": "Our data has images of digits and labels representing which digit it is. Each image is grayscale and is of size 28x28 pixels." }, { "code": null, "e": 2598, "s": 2544, "text": "First question — How do we take an image as an input?" }, { "code": null, "e": 2778, "s": 2598, "text": "Every image can be represented as a 3-D matrix. If we have a color image of size 28x28, we have 28 x 28 x 3 numbers to represent that image(3 for the RGB(Red-Green-Blue) channel)." }, { "code": null, "e": 3090, "s": 2778, "text": "But we have grayscale images which means every image has only 1 channel. So, every image is just 28x28 pixels. To input an image into the model we will flatten this 28x28 into a vector of length 784(28*28) and these 784 numbers which just pixels represent the n features for every example(image) in the dataset." }, { "code": null, "e": 3165, "s": 3090, "text": "X_train = train_X.reshape(60000,28*28)X_test = test_X.reshape(10000,28*28)" }, { "code": null, "e": 3219, "s": 3165, "text": "X_train is a matrix with 60,000 rows and 784 columns." }, { "code": null, "e": 3239, "s": 3219, "text": "m = 60,000; n = 784" }, { "code": null, "e": 3285, "s": 3239, "text": "Now, our y is a vector that looks like this —" }, { "code": null, "e": 3339, "s": 3285, "text": "train_y>> array([5, 0, 4, ..., 5, 6, 8], dtype=uint8)" }, { "code": null, "e": 3559, "s": 3339, "text": "It is a NumPy array with labels. We cannot use this for our model, we have to somehow modify it into zeros and ones which is what we call one-hot encoding. We want our y to look like this (a matrix of size 60,000 x 10)—" }, { "code": null, "e": 3891, "s": 3559, "text": "The rows represent i’th example and i’th column tells us the label. For example, for the first example, there is a 1 where the column name is 5 and the rest are zeros. So, the label for the first example is 5 and similarly for others. For every example, there will be only one and only one column with a 1.0 and rest will be zeros." }, { "code": null, "e": 3944, "s": 3891, "text": "Let’s code a function to one-hot encode our labels —" }, { "code": null, "e": 3966, "s": 3944, "text": "c = Number of classes" }, { "code": null, "e": 4262, "s": 3966, "text": "def one_hot(y, c): # y--> label/ground truth. # c--> Number of classes. # A zero matrix of size (m, c) y_hot = np.zeros((len(y), c)) # Putting 1 for column where the label is, # Using multidimensional indexing. y_hot[np.arange(len(y)), y] = 1 return y_hot" }, { "code": null, "e": 4310, "s": 4262, "text": "Reference — Multi-dimensional indexing in NumPy" }, { "code": null, "e": 4560, "s": 4310, "text": "While doing multi-class classification using Softmax Regression, we have a constraint that our model will predict only one class of c classes. For our data, it means that the model will predict only one of the digits(from 0 to 9) to be in the image." }, { "code": null, "e": 5039, "s": 4560, "text": "We interpreted the output of the logistic model as a probability. Similarly, we want to interpret the output of a multi-class classification model as a probability distribution. So, we want our model to output a vector of size c with each value in the vector representing the probability of each class. In other words, the c’th value in the vector represents the probability of our prediction being the c’th class. Since they are all probabilities, their sum will be equal to 1." }, { "code": null, "e": 5114, "s": 5039, "text": "To be in accordance with the above assumptions, we use a softmax function." }, { "code": null, "e": 5161, "s": 5114, "text": "The softmax for the c’th class is defined as —" }, { "code": null, "e": 5244, "s": 5161, "text": "where, z is the linear part. For example, z1 = w1.X + b1 and similarly for others." }, { "code": null, "e": 5269, "s": 5244, "text": "y_hat = softmax(w.X + b)" }, { "code": null, "e": 5307, "s": 5269, "text": "c(number of classes)=10 for our data." }, { "code": null, "e": 5849, "s": 5307, "text": "First, we have flattened our 28x28 image into a vector of length 784, represented by x in the above image.Second, we calculate the linear part for each class →zc = wc.X + bc where, zc is the linear part of the c’th class and wc is the set of weights of the c’th class. bc is the bias for the c’th class.Third, we calculate the softmax of zc for each class using the above formula. Combining all the classes, we get a vector of size c and their sum is equal to 1. And whichever class has the highest value(probability) will be our prediction." }, { "code": null, "e": 5956, "s": 5849, "text": "First, we have flattened our 28x28 image into a vector of length 784, represented by x in the above image." }, { "code": null, "e": 6154, "s": 5956, "text": "Second, we calculate the linear part for each class →zc = wc.X + bc where, zc is the linear part of the c’th class and wc is the set of weights of the c’th class. bc is the bias for the c’th class." }, { "code": null, "e": 6393, "s": 6154, "text": "Third, we calculate the softmax of zc for each class using the above formula. Combining all the classes, we get a vector of size c and their sum is equal to 1. And whichever class has the highest value(probability) will be our prediction." }, { "code": null, "e": 6468, "s": 6393, "text": "Note that every class has a different set of weights and a different bias." }, { "code": null, "e": 6534, "s": 6468, "text": "Also note that the above diagram shows the x as only one example." }, { "code": null, "e": 6772, "s": 6534, "text": "Every zc is a (1,1) matrix. But since we have m examples, we will represent zc (z for the c’th class) as a vector of size m. Now, to combine all the z ’s classes, we will stack them side by side which will give us a matrix of size (m,c)." }, { "code": null, "e": 7039, "s": 6772, "text": "Similarly, for every class, the set of weights is a vector of size n . So, to combine all the classes, we will stack them side by side which will give us a matrix of size (n,c). Also, we have one bias for every class, the combined biases will be a vector of size c ." }, { "code": null, "e": 7171, "s": 7039, "text": "Combining all the classes for the softmax gives a vector of size c . And combining all the m examples give a matrix of size (m, c)." }, { "code": null, "e": 7233, "s": 7171, "text": "X →(m,n)y →(m,c) [one hot encoded]w →(n,c)b →vector of size c" }, { "code": null, "e": 7242, "s": 7233, "text": "X →(m,n)" }, { "code": null, "e": 7269, "s": 7242, "text": "y →(m,c) [one hot encoded]" }, { "code": null, "e": 7278, "s": 7269, "text": "w →(n,c)" }, { "code": null, "e": 7298, "s": 7278, "text": "b →vector of size c" }, { "code": null, "e": 7362, "s": 7298, "text": "Let’s write the code for the softmax function. See comments(#)." }, { "code": null, "e": 7623, "s": 7362, "text": "def softmax(z): # z--> linear part. # subtracting the max of z for numerical stability. exp = np.exp(z - np.max(z)) # Calculating softmax for all examples. for i in range(len(z)): exp[i] /= np.sum(exp[i]) return exp" }, { "code": null, "e": 7661, "s": 7623, "text": "Refrence — Numerically stable softmax" }, { "code": null, "e": 7694, "s": 7661, "text": "Refrence — Derivative of Softmax" }, { "code": null, "e": 7914, "s": 7694, "text": "For every parametric machine learning algorithm, we need a loss function, which we want to minimize (find the global minimum of) to determine the optimal parameters(w and b) which will help us make the best predictions." }, { "code": null, "e": 7974, "s": 7914, "text": "For softmax regression, we use the cross-entropy(CE) loss —" }, { "code": null, "e": 8024, "s": 7974, "text": "Refrence for how to calculate derivative of loss." }, { "code": null, "e": 8081, "s": 8024, "text": "Refrence — Derivative of Cross Entropy Loss with Softmax" }, { "code": null, "e": 8128, "s": 8081, "text": "Refrence — Derivative of Softmax loss function" }, { "code": null, "e": 8164, "s": 8128, "text": "In code, the loss looks like this —" }, { "code": null, "e": 8217, "s": 8164, "text": "loss = -np.mean(np.log(y_hat[np.arange(len(y)), y]))" }, { "code": null, "e": 8293, "s": 8217, "text": "Again using multidimensional indexing — Multi-dimensional indexing in NumPy" }, { "code": null, "e": 8350, "s": 8293, "text": "Note that y is not one-hot encoded in the loss function." }, { "code": null, "e": 8460, "s": 8350, "text": "Initialize parameters — w and b .Find optimal w and b using Gradient Descent.Use softmax(w.X + b) to predict." }, { "code": null, "e": 8494, "s": 8460, "text": "Initialize parameters — w and b ." }, { "code": null, "e": 8539, "s": 8494, "text": "Find optimal w and b using Gradient Descent." }, { "code": null, "e": 8572, "s": 8539, "text": "Use softmax(w.X + b) to predict." }, { "code": null, "e": 9827, "s": 8572, "text": "def fit(X, y, lr, c, epochs): # X --> Input. # y --> true/target value. # lr --> Learning rate. # c --> Number of classes. # epochs --> Number of iterations. # m-> number of training examples # n-> number of features m, n = X.shape # Initializing weights and bias randomly. w = np.random.random((n, c)) b = np.random.random(c) # Empty list to store losses. losses = [] # Training loop. for epoch in range(epochs): # Calculating hypothesis/prediction. z = X@w + b y_hat = softmax(z) # One-hot encoding y. y_hot = one_hot(y, c) # Calculating the gradient of loss w.r.t w and b. w_grad = (1/m)*np.dot(X.T, (y_hat - y_hot)) b_grad = (1/m)*np.sum(y_hat - y_hot) # Updating the parameters. w = w - lr*w_grad b = b - lr*b_grad # Calculating loss and appending it in the list. loss = -np.mean(np.log(y_hat[np.arange(len(y)), y])) losses.append(loss) # Printing out the loss at every 100th iteration. if epoch%100==0: print('Epoch {epoch}==> Loss = {loss}' .format(epoch=epoch, loss=loss)) return w, b, losses" }, { "code": null, "e": 9844, "s": 9827, "text": "See comments(#)." }, { "code": null, "e": 10396, "s": 9844, "text": "# Flattening the image.X_train = train_X.reshape(60000,28*28)# Normalizing. X_train = X_train/255# Trainingw, b, l = fit(X_train, train_y, lr=0.9, c=10, epochs=1000)>> Epoch 0==> Loss = 4.765269749988195Epoch 100==> Loss = 0.41732772667703605Epoch 200==> Loss = 0.36146764856576774Epoch 300==> Loss = 0.3371995534802398Epoch 400==> Loss = 0.32295154931574305Epoch 500==> Loss = 0.31331228168677683Epoch 600==> Loss = 0.3062124554422963Epoch 700==> Loss = 0.3006810669534496Epoch 800==> Loss = 0.29619875396394774Epoch 900==> Loss = 0.29246033264255616" }, { "code": null, "e": 10485, "s": 10396, "text": "We can see that the loss goes down after every iteration, which means we are doing good." }, { "code": null, "e": 10502, "s": 10485, "text": "See comments(#)." }, { "code": null, "e": 10730, "s": 10502, "text": "def predict(X, w, b): # X --> Input. # w --> weights. # b --> bias. # Predicting z = X@w + b y_hat = softmax(z) # Returning the class with highest probability. return np.argmax(y_hat, axis=1)" }, { "code": null, "e": 10788, "s": 10730, "text": "def accuracy(y, y_hat): return np.sum(y==y_hat)/len(y)" }, { "code": null, "e": 10860, "s": 10788, "text": "Let’s calculate the accuracy of our model on the training and test set." }, { "code": null, "e": 11146, "s": 10860, "text": "# Accuracy for training set.train_preds = predict(X_train, w, b)accuracy(train_y, train_preds)>> 0.9187666# Accuracy for test set.# Flattening and normalizing.X_test = test_X.reshape(10000,28*28)X_test = X_test/255test_preds = predict(X_test, w, b)accuracy(test_y, test_preds)>> 0.9173" }, { "code": null, "e": 11243, "s": 11146, "text": "Our model has an accuracy of 91.8% on the training set and an accuracy of 91.7% on the test set." }, { "code": null, "e": 11252, "s": 11243, "text": "Not Bad." }, { "code": null, "e": 11512, "s": 11252, "text": "fig = plt.figure(figsize=(15,10))for i in range(40): ax = fig.add_subplot(5, 8, i+1) ax.imshow(test_X[i], cmap=plt.get_cmap('gray')) ax.set_title('y: {y}/ y_hat: {y_hat}' .format(y=test_y[i], y_hat=test_preds) plt.axis('off')" }, { "code": null, "e": 11705, "s": 11512, "text": "The above figure shows the predictions by the model for 40 examples in the training set. We can see that some of them are wrongly predicted, like the one encircled in red in the above picture." }, { "code": null, "e": 11833, "s": 11705, "text": "Thanks for reading. For questions, comments, concerns, talk to be in the response section. More ML from scratch is coming soon." }, { "code": null, "e": 11886, "s": 11833, "text": "Check out the Machine Learning from scratch series —" }, { "code": null, "e": 11935, "s": 11886, "text": "Part 1: Linear Regression from scratch in Python" }, { "code": null, "e": 11988, "s": 11935, "text": "Part 2: Locally Weighted Linear Regression in Python" }, { "code": null, "e": 12073, "s": 11988, "text": "Part 3: Normal Equation Using Python: The Closed-Form Solution for Linear Regression" }, { "code": null, "e": 12126, "s": 12073, "text": "Part 4: Polynomial Regression From Scratch in Python" }, { "code": null, "e": 12177, "s": 12126, "text": "Part 5: Logistic Regression From Scratch in Python" } ]
Keras - Reshape Layers
Reshape is used to change the shape of the input. For example, if reshape with argument (2,3) is applied to layer having input shape as (batch_size, 3, 2), then the output shape of the layer will be (batch_size, 2, 3) Reshape has one argument as follows − keras.layers.v(target_shape) A simple example to use Reshape layers is as follows − >>> from keras.models import Sequential >>> from keras.layers import Activation, Dense, Reshape >>> >>> >>> model = Sequential() >>> layer_1 = Dense(16, input_shape = (8,8)) >>> model.add(layer_1) >>> layer_2 = Reshape((16, 8)) >>> model.add(layer_2) >>> layer_2.input_shape (None, 8, 16) >>> layer_2.output_shape (None, 16, 8) >>> where, (16, 8) is set as target shape. 87 Lectures 11 hours Abhilash Nelson 61 Lectures 9 hours Abhishek And Pukhraj 57 Lectures 7 hours Abhishek And Pukhraj 52 Lectures 7 hours Abhishek And Pukhraj 52 Lectures 6 hours Abhishek And Pukhraj 68 Lectures 2 hours Mike West Print Add Notes Bookmark this page
[ { "code": null, "e": 2269, "s": 2051, "text": "Reshape is used to change the shape of the input. For example, if reshape with argument (2,3) is applied to layer having input shape as (batch_size, 3, 2), then the output shape of the layer will be (batch_size, 2, 3)" }, { "code": null, "e": 2307, "s": 2269, "text": "Reshape has one argument as follows −" }, { "code": null, "e": 2337, "s": 2307, "text": "keras.layers.v(target_shape)\n" }, { "code": null, "e": 2392, "s": 2337, "text": "A simple example to use Reshape layers is as follows −" }, { "code": null, "e": 2734, "s": 2392, "text": ">>> from keras.models import Sequential \n>>> from keras.layers import Activation, Dense, Reshape \n>>> \n>>> \n>>> model = Sequential() \n>>> layer_1 = Dense(16, input_shape = (8,8)) \n>>> model.add(layer_1) \n>>> layer_2 = Reshape((16, 8)) \n>>> model.add(layer_2) \n>>> layer_2.input_shape (None, 8, 16) \n>>> layer_2.output_shape (None, 16, 8)\n>>>" }, { "code": null, "e": 2773, "s": 2734, "text": "where, (16, 8) is set as target shape." }, { "code": null, "e": 2807, "s": 2773, "text": "\n 87 Lectures \n 11 hours \n" }, { "code": null, "e": 2824, "s": 2807, "text": " Abhilash Nelson" }, { "code": null, "e": 2857, "s": 2824, "text": "\n 61 Lectures \n 9 hours \n" }, { "code": null, "e": 2879, "s": 2857, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 2912, "s": 2879, "text": "\n 57 Lectures \n 7 hours \n" }, { "code": null, "e": 2934, "s": 2912, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 2967, "s": 2934, "text": "\n 52 Lectures \n 7 hours \n" }, { "code": null, "e": 2989, "s": 2967, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 3022, "s": 2989, "text": "\n 52 Lectures \n 6 hours \n" }, { "code": null, "e": 3044, "s": 3022, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 3077, "s": 3044, "text": "\n 68 Lectures \n 2 hours \n" }, { "code": null, "e": 3088, "s": 3077, "text": " Mike West" }, { "code": null, "e": 3095, "s": 3088, "text": " Print" }, { "code": null, "e": 3106, "s": 3095, "text": " Add Notes" } ]
Count zero, NULL and distinct values except zero and NULL with a single MySQL query
Let us first create a table − mysql> create table DemoTable( Value int ); Query OK, 0 rows affected (1.35 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values(10); Query OK, 1 row affected (0.30 sec) mysql> insert into DemoTable values(NULL); Query OK, 1 row affected (0.29 sec) mysql> insert into DemoTable values(10); Query OK, 1 row affected (0.59 sec) mysql> insert into DemoTable values(0); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable values(20); Query OK, 1 row affected (0.27 sec) mysql> insert into DemoTable values(10); Query OK, 1 row affected (0.70 sec) mysql> insert into DemoTable values(0); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(NULL); Query OK, 1 row affected (0.16 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +-------+ | Value | +-------+ | 10 | | NULL | | 10 | | 0 | | 20 | | 10 | | 0 | | NULL | +-------+ 8 rows in set (0.00 sec) Following is the query to group by on all values except null and 0 − mysql> select sum(Value is null) as NumberOfNull, sum(Value=0) as NumberOfZero, count(distinct Value > 0) as ValueExceptZeroAndNull from DemoTable; This will produce the following output − +--------------+--------------+------------------------+ | NumberOfNull | NumberOfZero | ValueExceptZeroAndNull | +--------------+--------------+------------------------+ | 2 | 2 | 2 | +--------------+--------------+------------------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1092, "s": 1062, "text": "Let us first create a table −" }, { "code": null, "e": 1176, "s": 1092, "text": "mysql> create table DemoTable(\n Value int\n);\nQuery OK, 0 rows affected (1.35 sec)" }, { "code": null, "e": 1232, "s": 1176, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1850, "s": 1232, "text": "mysql> insert into DemoTable values(10);\nQuery OK, 1 row affected (0.30 sec)\nmysql> insert into DemoTable values(NULL);\nQuery OK, 1 row affected (0.29 sec)\nmysql> insert into DemoTable values(10);\nQuery OK, 1 row affected (0.59 sec)\nmysql> insert into DemoTable values(0);\nQuery OK, 1 row affected (0.23 sec)\nmysql> insert into DemoTable values(20);\nQuery OK, 1 row affected (0.27 sec)\nmysql> insert into DemoTable values(10);\nQuery OK, 1 row affected (0.70 sec)\nmysql> insert into DemoTable values(0);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable values(NULL);\nQuery OK, 1 row affected (0.16 sec)" }, { "code": null, "e": 1910, "s": 1850, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1941, "s": 1910, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1982, "s": 1941, "text": "This will produce the following output −" }, { "code": null, "e": 2127, "s": 1982, "text": "+-------+\n| Value |\n+-------+\n| 10 |\n| NULL |\n| 10 |\n| 0 |\n| 20 |\n| 10 |\n| 0 |\n| NULL |\n+-------+\n8 rows in set (0.00 sec)" }, { "code": null, "e": 2196, "s": 2127, "text": "Following is the query to group by on all values except null and 0 −" }, { "code": null, "e": 2350, "s": 2196, "text": "mysql> select sum(Value is null) as NumberOfNull,\n sum(Value=0) as NumberOfZero,\n count(distinct Value > 0) as ValueExceptZeroAndNull\nfrom DemoTable;" }, { "code": null, "e": 2391, "s": 2350, "text": "This will produce the following output −" }, { "code": null, "e": 2700, "s": 2391, "text": "+--------------+--------------+------------------------+\n| NumberOfNull | NumberOfZero | ValueExceptZeroAndNull |\n+--------------+--------------+------------------------+\n| 2 | 2 | 2 |\n+--------------+--------------+------------------------+\n1 row in set (0.00 sec)" } ]
Dynamic Segment Trees : Online Queries for Range Sum with Point Updates - GeeksforGeeks
12 May, 2022 Prerequisites: Segment TreeGiven a number N which represents the size of the array initialized to 0 and Q queries to process where there are two types of queries: 1 P V: Put the value V at position P.2 L R: Output the sum of values from L to R. 1 P V: Put the value V at position P. 2 L R: Output the sum of values from L to R. The task is to answer these queries. Constraints: 1 ≤ N ≤ 1018 Q ≤ 105 1 ≤ L ≤ R≤ N Note: Queries are online. Therefore: L = (previousAnswer + L) % N + 1 R = (previousAnswer + R) % N + 1 Examples: Input: N = 5, Q = 5, arr[][] = {{1, 2, 3}, {1, 1, 4}, {1, 3, 5}, {1, 4, 7}, {2, 3, 4}} Output: 12 Explanation: There are five queries. Since N = 5, therefore, initially, the array is {0, 0, 0, 0, 0} For query 1: 1 2 3 array = {0, 3, 0, 0, 0} For query 2: 1 1 4 array = {4, 3, 0, 0, 0} For query 3: 1 3 5 array = {4, 3, 5, 0, 0} For query 4: 1 4 7 array = {4, 3, 5, 7, 0} For query 5: 2 3 4 Sum from [3, 4] = 7 + 5 = 12. Input: N = 3, Q = 2, arr[][] = {{1, 1, 1}, {1, 2, 2}, {1, 3, 3}} Output: 0 Approach: Here, since the updates are high, Kadane’s algorithm doesn’t work quite well. Moreover, since it is given that the queries are online, a simple segment tree would not be able to solve this problem because the constraints for the number of elements is very high. Therefore, a new type of data structure, a dynamic segment tree is used in this problem. Dynamic Segment Tree: Dynamic segment tree is not a new data structure. It is very similar to the segment tree. The following are the properties of the dynamic segment tree: Instead of using an array to represent the intervals, a node is created whenever a new interval is to be updated. The following is the structure of the node of the dynamic segment tree: C++ // Every node contains the value and// the left subtree and right subtreestruct Node { long long value; struct Node *L, *R;}; struct Node* getnode(){ struct Node* temp = new struct Node; temp->value = 0; temp->L = NULL; temp->R = NULL; return temp;} Clearly, the above structure is the same as a Binary Search Tree. In every node, we are storing the node’s value and two pointers pointing to the left and right subtree. The Interval of the root is from [1, N], the interval of the left subtree will be [1, N/2] and the interval for the right subtree will be [N/2 + 1, N]. Similarly, for every node, we can calculate the interval it is representing. Let’s say the interval of the current node is [L, R]. Then, the Interval of its left and right subtree are [L, (L + R)/2] and [(L + R)/2+1, R] respectively. Since we are creating a new node only when required, the build() function from the segment tree is completely removed. Before getting into the algorithm for the operations, let’s define the terms used in this article: Node’s interval: It is the interval the node is representing. Required interval: Interval for which the sum is to calculate. Required index: Index at which Update is required. The following is the algorithm used for the operations on the tree with the above-mentioned properties: Point Update: The following algorithm is used for the point update: Start with the root node.If the interval at the node doesn’t overlap with the required index then return.If the node is a NULL entry then create a new node with the appropriate intervals and descend into that node by going back to step 2 for every new child created.If both, intervals and the index at which the value is to be stored are equal, then store the value into at that node.If the interval at the node overlaps partially with the required index then descend into its children and continue the execution from step 2.Finding the sum for every query: The following algorithm is used to find the sum for every query: Start with the root node.If the node is a NULL or the interval at that node doesn’t overlap with the required interval, then return 0.If the interval at the node completely overlaps with the required interval then return the value stored at the node.If the interval at the node overlaps partially with the required interval then descend into its children and continue the execution from step 2 for both of its children. Point Update: The following algorithm is used for the point update: Start with the root node.If the interval at the node doesn’t overlap with the required index then return.If the node is a NULL entry then create a new node with the appropriate intervals and descend into that node by going back to step 2 for every new child created.If both, intervals and the index at which the value is to be stored are equal, then store the value into at that node.If the interval at the node overlaps partially with the required index then descend into its children and continue the execution from step 2. Start with the root node.If the interval at the node doesn’t overlap with the required index then return.If the node is a NULL entry then create a new node with the appropriate intervals and descend into that node by going back to step 2 for every new child created.If both, intervals and the index at which the value is to be stored are equal, then store the value into at that node.If the interval at the node overlaps partially with the required index then descend into its children and continue the execution from step 2. Start with the root node. If the interval at the node doesn’t overlap with the required index then return. If the node is a NULL entry then create a new node with the appropriate intervals and descend into that node by going back to step 2 for every new child created. If both, intervals and the index at which the value is to be stored are equal, then store the value into at that node. If the interval at the node overlaps partially with the required index then descend into its children and continue the execution from step 2. Finding the sum for every query: The following algorithm is used to find the sum for every query: Start with the root node.If the node is a NULL or the interval at that node doesn’t overlap with the required interval, then return 0.If the interval at the node completely overlaps with the required interval then return the value stored at the node.If the interval at the node overlaps partially with the required interval then descend into its children and continue the execution from step 2 for both of its children. Start with the root node.If the node is a NULL or the interval at that node doesn’t overlap with the required interval, then return 0.If the interval at the node completely overlaps with the required interval then return the value stored at the node.If the interval at the node overlaps partially with the required interval then descend into its children and continue the execution from step 2 for both of its children. Start with the root node. If the node is a NULL or the interval at that node doesn’t overlap with the required interval, then return 0. If the interval at the node completely overlaps with the required interval then return the value stored at the node. If the interval at the node overlaps partially with the required interval then descend into its children and continue the execution from step 2 for both of its children. Example: Lets visualize the update and sum with an example. Let N = 10 and the operations needed to perform on the tree are as follows: Insert 10 at position 1.Find the sum of value of indices from 2 to 8.Insert 3 at position 5.Find the sum of value of indices from 3 to 6. Insert 10 at position 1. Find the sum of value of indices from 2 to 8. Insert 3 at position 5. Find the sum of value of indices from 3 to 6. Initially, for the value N = 10, the tree is empty. Therefore: Insert 10 at position 1. In order to do this, create a new node until we get the required interval. Therefore: Find the sum of value of indices from 2 to 8. In order to do this, the sum from [1, 8] is found and the value [1, 2] is subtracted from it. Since the node [1, 8] is not yet created, the value of [1, 8] is the value of the root [1, 10]. Therefore: Insert 3 at position 5. In order to do this, create a new node until we get the required interval. Therefore: Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the implementation// of the Dynamic segment tree and// perform the range updates on the// given queries #include <bits/stdc++.h> using namespace std;typedef long long ll; // Structure of the nodestruct Node { ll value; struct Node *L, *R;}; // Structure to get the newly formed// nodestruct Node* getnode(){ struct Node* temp = new struct Node; temp->value = 0; temp->L = NULL; temp->R = NULL; return temp;} // Creating the Root nodestruct Node* root; // Function to perform the point update// on the dynamic segment treevoid UpdateHelper(struct Node* curr, ll index, ll L, ll R, ll val){ // If the index is not overlapping // with the index if (L > index || R < index) return; // If the index is completely overlapping // with the index if (L == R && L == index) { // Update the value of the node // to the given value curr->value = val; return; } // Computing the middle index if none // of the above base cases are satisfied ll mid = L - (L - R) / 2; ll sum1 = 0, sum2 = 0; // If the index is in the left subtree if (index <= mid) { // Create a new node if the left // subtree is is null if (curr->L == NULL) curr->L = getnode(); // Recursively call the function // for the left subtree UpdateHelper(curr->L, index, L, mid, val); } // If the index is in the right subtree else { // Create a new node if the right // subtree is is null if (curr->R == NULL) curr->R = getnode(); // Recursively call the function // for the right subtree UpdateHelper(curr->R, index, mid + 1, R, val); } // Storing the sum of the left subtree if (curr->L) sum1 = curr->L->value; // Storing the sum of the right subtree if (curr->R) sum2 = curr->R->value; // Storing the sum of the children into // the node's value curr->value = sum1 + sum2; return;} // Function to find the sum of the// values given by the rangell queryHelper(struct Node* curr, ll a, ll b, ll L, ll R){ // Return 0 if the root is null if (curr == NULL) return 0; // If the index is not overlapping // with the index, then the node // is not created. So sum is 0 if (L > b || R < a) return 0; // If the index is completely overlapping // with the index, return the node's value if (L >= a && R <= b) return curr->value; ll mid = L - (L - R) / 2; // Return the sum of values stored // at the node's children return queryHelper(curr->L, a, b, L, mid) + queryHelper(curr->R, a, b, mid + 1, R);} // Function to call the queryHelper// function to find the sum for// the queryll query(int L, int R){ return queryHelper(root, L, R, 1, 10);} // Function to call the UpdateHelper// function for the point updatevoid update(int index, int value){ UpdateHelper(root, index, 1, 10, value);} // Function to perform the operations// on the treevoid operations(){ // Creating an empty tree root = getnode(); // Update the value at position 1 to 10 update(1, 10); // Update the value at position 3 to 5 update(3, 5); // Finding sum for the range [2, 8] cout << query(2, 8) << endl; // Finding sum for the range [1, 10] cout << query(1, 10) << endl; } // Driver codeint main(){ operations(); return 0;} // Java program for the implementation// of the Dynamic segment tree and// perform the range updates on the// given queries class GFG { // Structure of the node static class Node { int value; Node L, R; } // Structure to get the newly formed // node static Node getnode() { Node temp = new Node(); temp.value = 0; temp.L = null; temp.R = null; return temp; } // Creating the Root node static Node root = new Node(); // Function to perform the point update // on the dynamic segment tree static void UpdateHelper(Node curr, int index, int L, int R, int val) { // If the index is not overlapping // with the index if (L > index || R < index) return; // If the index is completely overlapping // with the index if (L == R && L == index) { // Update the value of the node // to the given value curr.value = val; return; } // Computing the middle index if none // of the above base cases are satisfied int mid = L - (L - R) / 2; int sum1 = 0, sum2 = 0; // If the index is in the left subtree if (index <= mid) { // Create a new node if the left // subtree is is null if (curr.L == null) curr.L = getnode(); // Recursively call the function // for the left subtree UpdateHelper(curr.L, index, L, mid, val); } // If the index is in the right subtree else { // Create a new node if the right // subtree is is null if (curr.R == null) curr.R = getnode(); // Recursively call the function // for the right subtree UpdateHelper(curr.R, index, mid + 1, R, val); } // Storing the sum of the left subtree if (curr.L != null) sum1 = curr.L.value; // Storing the sum of the right subtree if (curr.R != null) sum2 = curr.R.value; // Storing the sum of the children into // the node's value curr.value = sum1 + sum2; return; } // Function to find the sum of the // values given by the range static int queryHelper(Node curr, int a, int b, int L, int R) { // Return 0 if the root is null if (curr == null) return 0; // If the index is not overlapping // with the index, then the node // is not created. So sum is 0 if (L > b || R < a) return 0; // If the index is completely overlapping // with the index, return the node's value if (L >= a && R <= b) return curr.value; int mid = L - (L - R) / 2; // Return the sum of values stored // at the node's children return queryHelper(curr.L, a, b, L, mid) + queryHelper(curr.R, a, b, mid + 1, R); } // Function to call the queryHelper // function to find the sum for // the query static int query(int L, int R) { return queryHelper(root, L, R, 1, 10); } // Function to call the UpdateHelper // function for the point update static void update(int index, int value) { UpdateHelper(root, index, 1, 10, value); } // Function to perform the operations // on the tree static void operations() { // Creating an empty tree root = getnode(); // Update the value at position 1 to 10 update(1, 10); // Update the value at position 3 to 5 update(3, 5); // Finding sum for the range [2, 8] System.out.println(query(2, 8)); // Finding sum for the range [1, 10] System.out.println(query(1, 10)); } // Driver code public static void main(String[] args) { operations(); }} // This code is contributed by sanjeev2552 # C++ program for the implementation# of the Dynamic segment tree and# perform the range updates on the# given queries # Structure of the nodeclass Node: def __init__(self): self.value=-1 self.L, self.R=None,None # Structure to get the newly formed# nodedef getnode(): temp = Node() temp.value = 0 temp.L = None temp.R = None return temp # Creating the Root noderoot=None # Function to perform the point update# on the dynamic segment treedef UpdateHelper(curr, index, L, R, val): # If the index is not overlapping # with the index if (L > index or R < index): return # If the index is completely overlapping # with the index if (L == R and L == index) : # Update the value of the node # to the given value curr.value = val return # Computing the middle index if none # of the above base cases are satisfied mid = int(L - (L - R) / 2) sum1 = 0; sum2 = 0 # If the index is in the left subtree if (index <= mid) : # Create a new node if the left # subtree is is None if (curr.L == None): curr.L = getnode() # Recursively call the function # for the left subtree UpdateHelper(curr.L, index, L, mid, val) # If the index is in the right subtree else : # Create a new node if the right # subtree is is None if (curr.R == None): curr.R = getnode() # Recursively call the function # for the right subtree UpdateHelper(curr.R, index, mid + 1, R, val) # Storing the sum of the left subtree if (curr.L): sum1 = curr.L.value # Storing the sum of the right subtree if (curr.R): sum2 = curr.R.value # Storing the sum of the children into # the node's value curr.value = sum1 + sum2 return # Function to find the sum of the# values given by the rangedef queryHelper(curr, a, b, L, R): # Return 0 if the root is None if (curr == None): return 0 # If the index is not overlapping # with the index, then the node # is not created. So sum is 0 if (L > b or R < a): return 0 # If the index is completely overlapping # with the index, return the node's value if (L >= a and R <= b): return curr.value mid = int(L - (L - R) / 2) # Return the sum of values stored # at the node's children return queryHelper(curr.L, a, b, L, mid) + queryHelper(curr.R, a, b, mid + 1, R) # Function to call the queryHelper# function to find the sum for# the querydef query(L, R): return queryHelper(root, L, R, 1, 10) # Function to call the UpdateHelper# function for the point updatedef update(index, value): UpdateHelper(root, index, 1, 10, value) # Function to perform the operations# on the treedef operations(): global root # Creating an empty tree root = getnode() # Update the value at position 1 to 10 update(1, 10) # Update the value at position 3 to 5 update(3, 5) # Finding sum for the range [2, 8] print(query(2, 8)) # Finding sum for the range [1, 10] print(query(1, 10)) # Driver codeif __name__ == '__main__': operations() using System; // C# program for the implementation// of the Dynamic segment tree and// perform the range updates on the// given queries class GFG { // Structure of the node public class Node { public int value; public Node L, R; } // Structure to get the newly formed // node static Node getnode() { Node temp = new Node(); temp.value = 0; temp.L = null; temp.R = null; return temp; } // Creating the Root node static Node root = new Node(); // Function to perform the point update // on the dynamic segment tree static void UpdateHelper(Node curr, int index, int L, int R, int val) { // If the index is not overlapping // with the index if (L > index || R < index) return; // If the index is completely overlapping // with the index if (L == R && L == index) { // Update the value of the node // to the given value curr.value = val; return; } // Computing the middle index if none // of the above base cases are satisfied int mid = L - (L - R) / 2; int sum1 = 0, sum2 = 0; // If the index is in the left subtree if (index <= mid) { // Create a new node if the left // subtree is is null if (curr.L == null) curr.L = getnode(); // Recursively call the function // for the left subtree UpdateHelper(curr.L, index, L, mid, val); } // If the index is in the right subtree else { // Create a new node if the right // subtree is is null if (curr.R == null) curr.R = getnode(); // Recursively call the function // for the right subtree UpdateHelper(curr.R, index, mid + 1, R, val); } // Storing the sum of the left subtree if (curr.L != null) sum1 = curr.L.value; // Storing the sum of the right subtree if (curr.R != null) sum2 = curr.R.value; // Storing the sum of the children into // the node's value curr.value = sum1 + sum2; return; } // Function to find the sum of the // values given by the range static int queryHelper(Node curr, int a, int b, int L, int R) { // Return 0 if the root is null if (curr == null) return 0; // If the index is not overlapping // with the index, then the node // is not created. So sum is 0 if (L > b || R < a) return 0; // If the index is completely overlapping // with the index, return the node's value if (L >= a && R <= b) return curr.value; int mid = L - (L - R) / 2; // Return the sum of values stored // at the node's children return queryHelper(curr.L, a, b, L, mid) + queryHelper(curr.R, a, b, mid + 1, R); } // Function to call the queryHelper // function to find the sum for // the query static int query(int L, int R) { return queryHelper(root, L, R, 1, 10); } // Function to call the UpdateHelper // function for the point update static void update(int index, int value) { UpdateHelper(root, index, 1, 10, value); } // Function to perform the operations // on the tree static void operations() { // Creating an empty tree root = getnode(); // Update the value at position 1 to 10 update(1, 10); // Update the value at position 3 to 5 update(3, 5); // Finding sum for the range [2, 8] Console.WriteLine(query(2, 8)); // Finding sum for the range [1, 10] Console.WriteLine(query(1, 10)); } // Driver code public static void Main(String[] args) { operations(); }} // This code is contributed by jana_sayantan. <script> // Javascript program for the implementation// of the Dynamic segment tree and perform// the range updates on the given queries // Structure of the nodeclass Node{ constructor() { this.L = null; this.R = null; this.value = 0; }} // Structure to get the newly formed// nodefunction getnode(){ let temp = new Node(); return temp;} // Creating the Root nodelet root = new Node(); // Function to perform the point update// on the dynamic segment treefunction UpdateHelper(curr, index, L, R, val){ // If the index is not overlapping // with the index if (L > index || R < index) return; // If the index is completely overlapping // with the index if (L == R && L == index) { // Update the value of the node // to the given value curr.value = val; return; } // Computing the middle index if none // of the above base cases are satisfied let mid = L - parseInt((L - R) / 2, 10); let sum1 = 0, sum2 = 0; // If the index is in the left subtree if (index <= mid) { // Create a new node if the left // subtree is is null if (curr.L == null) curr.L = getnode(); // Recursively call the function // for the left subtree UpdateHelper(curr.L, index, L, mid, val); } // If the index is in the right subtree else { // Create a new node if the right // subtree is is null if (curr.R == null) curr.R = getnode(); // Recursively call the function // for the right subtree UpdateHelper(curr.R, index, mid + 1, R, val); } // Storing the sum of the left subtree if (curr.L != null) sum1 = curr.L.value; // Storing the sum of the right subtree if (curr.R != null) sum2 = curr.R.value; // Storing the sum of the children into // the node's value curr.value = sum1 + sum2; return;} // Function to find the sum of the// values given by the rangefunction queryHelper(curr, a, b, L, R){ // Return 0 if the root is null if (curr == null) return 0; // If the index is not overlapping // with the index, then the node // is not created. So sum is 0 if (L > b || R < a) return 0; // If the index is completely overlapping // with the index, return the node's value if (L >= a && R <= b) return curr.value; let mid = L - parseInt((L - R) / 2, 10); // Return the sum of values stored // at the node's children return queryHelper(curr.L, a, b, L, mid) + queryHelper(curr.R, a, b, mid + 1, R);} // Function to call the queryHelper// function to find the sum for// the queryfunction query(L, R){ return queryHelper(root, L, R, 1, 10);} // Function to call the UpdateHelper// function for the point updatefunction update(index, value){ UpdateHelper(root, index, 1, 10, value);} // Function to perform the operations// on the treefunction operations(){ // Creating an empty tree root = getnode(); // Update the value at position 1 to 10 update(1, 10); // Update the value at position 3 to 5 update(3, 5); // Finding sum for the range [2, 8] document.write(query(2, 8) + "</br>"); // Finding sum for the range [1, 10] document.write(query(1, 10) + "</br>");} // Driver codeoperations(); // This code is contributed by mukesh07 </script> 5 15 Time Complexity: O(Q * logN) Auxiliary Space: O(N) sanjeev2552 mukesh07 pankajsharmagfg amartyaghoshgfg jana_sayantan array-range-queries Segment-Tree Advanced Data Structure Competitive Programming Data Structures Tree Data Structures Tree Segment-Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Ordered Set and GNU C++ PBDS 2-3 Trees | (Search, Insert and Deletion) Extendible Hashing (Dynamic approach to DBMS) Suffix Array | Set 1 (Introduction) Quad Tree Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Prefix Sum Array - Implementation and Applications in Competitive Programming Fast I/O for Competitive Programming
[ { "code": null, "e": 25733, "s": 25705, "text": "\n12 May, 2022" }, { "code": null, "e": 25897, "s": 25733, "text": "Prerequisites: Segment TreeGiven a number N which represents the size of the array initialized to 0 and Q queries to process where there are two types of queries: " }, { "code": null, "e": 25979, "s": 25897, "text": "1 P V: Put the value V at position P.2 L R: Output the sum of values from L to R." }, { "code": null, "e": 26017, "s": 25979, "text": "1 P V: Put the value V at position P." }, { "code": null, "e": 26062, "s": 26017, "text": "2 L R: Output the sum of values from L to R." }, { "code": null, "e": 26100, "s": 26062, "text": "The task is to answer these queries. " }, { "code": null, "e": 26115, "s": 26100, "text": "Constraints: " }, { "code": null, "e": 26128, "s": 26115, "text": "1 ≤ N ≤ 1018" }, { "code": null, "e": 26136, "s": 26128, "text": "Q ≤ 105" }, { "code": null, "e": 26149, "s": 26136, "text": "1 ≤ L ≤ R≤ N" }, { "code": null, "e": 26188, "s": 26149, "text": "Note: Queries are online. Therefore: " }, { "code": null, "e": 26221, "s": 26188, "text": "L = (previousAnswer + L) % N + 1" }, { "code": null, "e": 26254, "s": 26221, "text": "R = (previousAnswer + R) % N + 1" }, { "code": null, "e": 26265, "s": 26254, "text": "Examples: " }, { "code": null, "e": 26685, "s": 26265, "text": "Input: N = 5, Q = 5, arr[][] = {{1, 2, 3}, {1, 1, 4}, {1, 3, 5}, {1, 4, 7}, {2, 3, 4}} Output: 12 Explanation: There are five queries. Since N = 5, therefore, initially, the array is {0, 0, 0, 0, 0} For query 1: 1 2 3 array = {0, 3, 0, 0, 0} For query 2: 1 1 4 array = {4, 3, 0, 0, 0} For query 3: 1 3 5 array = {4, 3, 5, 0, 0} For query 4: 1 4 7 array = {4, 3, 5, 7, 0} For query 5: 2 3 4 Sum from [3, 4] = 7 + 5 = 12." }, { "code": null, "e": 26762, "s": 26685, "text": "Input: N = 3, Q = 2, arr[][] = {{1, 1, 1}, {1, 2, 2}, {1, 3, 3}} Output: 0 " }, { "code": null, "e": 27298, "s": 26762, "text": "Approach: Here, since the updates are high, Kadane’s algorithm doesn’t work quite well. Moreover, since it is given that the queries are online, a simple segment tree would not be able to solve this problem because the constraints for the number of elements is very high. Therefore, a new type of data structure, a dynamic segment tree is used in this problem. Dynamic Segment Tree: Dynamic segment tree is not a new data structure. It is very similar to the segment tree. The following are the properties of the dynamic segment tree: " }, { "code": null, "e": 27412, "s": 27298, "text": "Instead of using an array to represent the intervals, a node is created whenever a new interval is to be updated." }, { "code": null, "e": 27484, "s": 27412, "text": "The following is the structure of the node of the dynamic segment tree:" }, { "code": null, "e": 27488, "s": 27484, "text": "C++" }, { "code": "// Every node contains the value and// the left subtree and right subtreestruct Node { long long value; struct Node *L, *R;}; struct Node* getnode(){ struct Node* temp = new struct Node; temp->value = 0; temp->L = NULL; temp->R = NULL; return temp;}", "e": 27761, "s": 27488, "text": null }, { "code": null, "e": 27931, "s": 27761, "text": "Clearly, the above structure is the same as a Binary Search Tree. In every node, we are storing the node’s value and two pointers pointing to the left and right subtree." }, { "code": null, "e": 28083, "s": 27931, "text": "The Interval of the root is from [1, N], the interval of the left subtree will be [1, N/2] and the interval for the right subtree will be [N/2 + 1, N]." }, { "code": null, "e": 28317, "s": 28083, "text": "Similarly, for every node, we can calculate the interval it is representing. Let’s say the interval of the current node is [L, R]. Then, the Interval of its left and right subtree are [L, (L + R)/2] and [(L + R)/2+1, R] respectively." }, { "code": null, "e": 28436, "s": 28317, "text": "Since we are creating a new node only when required, the build() function from the segment tree is completely removed." }, { "code": null, "e": 28537, "s": 28436, "text": "Before getting into the algorithm for the operations, let’s define the terms used in this article: " }, { "code": null, "e": 28599, "s": 28537, "text": "Node’s interval: It is the interval the node is representing." }, { "code": null, "e": 28662, "s": 28599, "text": "Required interval: Interval for which the sum is to calculate." }, { "code": null, "e": 28713, "s": 28662, "text": "Required index: Index at which Update is required." }, { "code": null, "e": 28818, "s": 28713, "text": "The following is the algorithm used for the operations on the tree with the above-mentioned properties: " }, { "code": null, "e": 29929, "s": 28818, "text": "Point Update: The following algorithm is used for the point update: Start with the root node.If the interval at the node doesn’t overlap with the required index then return.If the node is a NULL entry then create a new node with the appropriate intervals and descend into that node by going back to step 2 for every new child created.If both, intervals and the index at which the value is to be stored are equal, then store the value into at that node.If the interval at the node overlaps partially with the required index then descend into its children and continue the execution from step 2.Finding the sum for every query: The following algorithm is used to find the sum for every query: Start with the root node.If the node is a NULL or the interval at that node doesn’t overlap with the required interval, then return 0.If the interval at the node completely overlaps with the required interval then return the value stored at the node.If the interval at the node overlaps partially with the required interval then descend into its children and continue the execution from step 2 for both of its children." }, { "code": null, "e": 30523, "s": 29929, "text": "Point Update: The following algorithm is used for the point update: Start with the root node.If the interval at the node doesn’t overlap with the required index then return.If the node is a NULL entry then create a new node with the appropriate intervals and descend into that node by going back to step 2 for every new child created.If both, intervals and the index at which the value is to be stored are equal, then store the value into at that node.If the interval at the node overlaps partially with the required index then descend into its children and continue the execution from step 2." }, { "code": null, "e": 31049, "s": 30523, "text": "Start with the root node.If the interval at the node doesn’t overlap with the required index then return.If the node is a NULL entry then create a new node with the appropriate intervals and descend into that node by going back to step 2 for every new child created.If both, intervals and the index at which the value is to be stored are equal, then store the value into at that node.If the interval at the node overlaps partially with the required index then descend into its children and continue the execution from step 2." }, { "code": null, "e": 31075, "s": 31049, "text": "Start with the root node." }, { "code": null, "e": 31156, "s": 31075, "text": "If the interval at the node doesn’t overlap with the required index then return." }, { "code": null, "e": 31318, "s": 31156, "text": "If the node is a NULL entry then create a new node with the appropriate intervals and descend into that node by going back to step 2 for every new child created." }, { "code": null, "e": 31437, "s": 31318, "text": "If both, intervals and the index at which the value is to be stored are equal, then store the value into at that node." }, { "code": null, "e": 31579, "s": 31437, "text": "If the interval at the node overlaps partially with the required index then descend into its children and continue the execution from step 2." }, { "code": null, "e": 32097, "s": 31579, "text": "Finding the sum for every query: The following algorithm is used to find the sum for every query: Start with the root node.If the node is a NULL or the interval at that node doesn’t overlap with the required interval, then return 0.If the interval at the node completely overlaps with the required interval then return the value stored at the node.If the interval at the node overlaps partially with the required interval then descend into its children and continue the execution from step 2 for both of its children." }, { "code": null, "e": 32517, "s": 32097, "text": "Start with the root node.If the node is a NULL or the interval at that node doesn’t overlap with the required interval, then return 0.If the interval at the node completely overlaps with the required interval then return the value stored at the node.If the interval at the node overlaps partially with the required interval then descend into its children and continue the execution from step 2 for both of its children." }, { "code": null, "e": 32543, "s": 32517, "text": "Start with the root node." }, { "code": null, "e": 32653, "s": 32543, "text": "If the node is a NULL or the interval at that node doesn’t overlap with the required interval, then return 0." }, { "code": null, "e": 32770, "s": 32653, "text": "If the interval at the node completely overlaps with the required interval then return the value stored at the node." }, { "code": null, "e": 32940, "s": 32770, "text": "If the interval at the node overlaps partially with the required interval then descend into its children and continue the execution from step 2 for both of its children." }, { "code": null, "e": 33077, "s": 32940, "text": "Example: Lets visualize the update and sum with an example. Let N = 10 and the operations needed to perform on the tree are as follows: " }, { "code": null, "e": 33215, "s": 33077, "text": "Insert 10 at position 1.Find the sum of value of indices from 2 to 8.Insert 3 at position 5.Find the sum of value of indices from 3 to 6." }, { "code": null, "e": 33240, "s": 33215, "text": "Insert 10 at position 1." }, { "code": null, "e": 33286, "s": 33240, "text": "Find the sum of value of indices from 2 to 8." }, { "code": null, "e": 33310, "s": 33286, "text": "Insert 3 at position 5." }, { "code": null, "e": 33356, "s": 33310, "text": "Find the sum of value of indices from 3 to 6." }, { "code": null, "e": 33421, "s": 33356, "text": "Initially, for the value N = 10, the tree is empty. Therefore: " }, { "code": null, "e": 33534, "s": 33421, "text": "Insert 10 at position 1. In order to do this, create a new node until we get the required interval. Therefore: " }, { "code": null, "e": 33783, "s": 33534, "text": "Find the sum of value of indices from 2 to 8. In order to do this, the sum from [1, 8] is found and the value [1, 2] is subtracted from it. Since the node [1, 8] is not yet created, the value of [1, 8] is the value of the root [1, 10]. Therefore: " }, { "code": null, "e": 33895, "s": 33783, "text": "Insert 3 at position 5. In order to do this, create a new node until we get the required interval. Therefore: " }, { "code": null, "e": 33946, "s": 33895, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 33950, "s": 33946, "text": "C++" }, { "code": null, "e": 33955, "s": 33950, "text": "Java" }, { "code": null, "e": 33963, "s": 33955, "text": "Python3" }, { "code": null, "e": 33966, "s": 33963, "text": "C#" }, { "code": null, "e": 33977, "s": 33966, "text": "Javascript" }, { "code": "// C++ program for the implementation// of the Dynamic segment tree and// perform the range updates on the// given queries #include <bits/stdc++.h> using namespace std;typedef long long ll; // Structure of the nodestruct Node { ll value; struct Node *L, *R;}; // Structure to get the newly formed// nodestruct Node* getnode(){ struct Node* temp = new struct Node; temp->value = 0; temp->L = NULL; temp->R = NULL; return temp;} // Creating the Root nodestruct Node* root; // Function to perform the point update// on the dynamic segment treevoid UpdateHelper(struct Node* curr, ll index, ll L, ll R, ll val){ // If the index is not overlapping // with the index if (L > index || R < index) return; // If the index is completely overlapping // with the index if (L == R && L == index) { // Update the value of the node // to the given value curr->value = val; return; } // Computing the middle index if none // of the above base cases are satisfied ll mid = L - (L - R) / 2; ll sum1 = 0, sum2 = 0; // If the index is in the left subtree if (index <= mid) { // Create a new node if the left // subtree is is null if (curr->L == NULL) curr->L = getnode(); // Recursively call the function // for the left subtree UpdateHelper(curr->L, index, L, mid, val); } // If the index is in the right subtree else { // Create a new node if the right // subtree is is null if (curr->R == NULL) curr->R = getnode(); // Recursively call the function // for the right subtree UpdateHelper(curr->R, index, mid + 1, R, val); } // Storing the sum of the left subtree if (curr->L) sum1 = curr->L->value; // Storing the sum of the right subtree if (curr->R) sum2 = curr->R->value; // Storing the sum of the children into // the node's value curr->value = sum1 + sum2; return;} // Function to find the sum of the// values given by the rangell queryHelper(struct Node* curr, ll a, ll b, ll L, ll R){ // Return 0 if the root is null if (curr == NULL) return 0; // If the index is not overlapping // with the index, then the node // is not created. So sum is 0 if (L > b || R < a) return 0; // If the index is completely overlapping // with the index, return the node's value if (L >= a && R <= b) return curr->value; ll mid = L - (L - R) / 2; // Return the sum of values stored // at the node's children return queryHelper(curr->L, a, b, L, mid) + queryHelper(curr->R, a, b, mid + 1, R);} // Function to call the queryHelper// function to find the sum for// the queryll query(int L, int R){ return queryHelper(root, L, R, 1, 10);} // Function to call the UpdateHelper// function for the point updatevoid update(int index, int value){ UpdateHelper(root, index, 1, 10, value);} // Function to perform the operations// on the treevoid operations(){ // Creating an empty tree root = getnode(); // Update the value at position 1 to 10 update(1, 10); // Update the value at position 3 to 5 update(3, 5); // Finding sum for the range [2, 8] cout << query(2, 8) << endl; // Finding sum for the range [1, 10] cout << query(1, 10) << endl; } // Driver codeint main(){ operations(); return 0;}", "e": 37451, "s": 33977, "text": null }, { "code": "// Java program for the implementation// of the Dynamic segment tree and// perform the range updates on the// given queries class GFG { // Structure of the node static class Node { int value; Node L, R; } // Structure to get the newly formed // node static Node getnode() { Node temp = new Node(); temp.value = 0; temp.L = null; temp.R = null; return temp; } // Creating the Root node static Node root = new Node(); // Function to perform the point update // on the dynamic segment tree static void UpdateHelper(Node curr, int index, int L, int R, int val) { // If the index is not overlapping // with the index if (L > index || R < index) return; // If the index is completely overlapping // with the index if (L == R && L == index) { // Update the value of the node // to the given value curr.value = val; return; } // Computing the middle index if none // of the above base cases are satisfied int mid = L - (L - R) / 2; int sum1 = 0, sum2 = 0; // If the index is in the left subtree if (index <= mid) { // Create a new node if the left // subtree is is null if (curr.L == null) curr.L = getnode(); // Recursively call the function // for the left subtree UpdateHelper(curr.L, index, L, mid, val); } // If the index is in the right subtree else { // Create a new node if the right // subtree is is null if (curr.R == null) curr.R = getnode(); // Recursively call the function // for the right subtree UpdateHelper(curr.R, index, mid + 1, R, val); } // Storing the sum of the left subtree if (curr.L != null) sum1 = curr.L.value; // Storing the sum of the right subtree if (curr.R != null) sum2 = curr.R.value; // Storing the sum of the children into // the node's value curr.value = sum1 + sum2; return; } // Function to find the sum of the // values given by the range static int queryHelper(Node curr, int a, int b, int L, int R) { // Return 0 if the root is null if (curr == null) return 0; // If the index is not overlapping // with the index, then the node // is not created. So sum is 0 if (L > b || R < a) return 0; // If the index is completely overlapping // with the index, return the node's value if (L >= a && R <= b) return curr.value; int mid = L - (L - R) / 2; // Return the sum of values stored // at the node's children return queryHelper(curr.L, a, b, L, mid) + queryHelper(curr.R, a, b, mid + 1, R); } // Function to call the queryHelper // function to find the sum for // the query static int query(int L, int R) { return queryHelper(root, L, R, 1, 10); } // Function to call the UpdateHelper // function for the point update static void update(int index, int value) { UpdateHelper(root, index, 1, 10, value); } // Function to perform the operations // on the tree static void operations() { // Creating an empty tree root = getnode(); // Update the value at position 1 to 10 update(1, 10); // Update the value at position 3 to 5 update(3, 5); // Finding sum for the range [2, 8] System.out.println(query(2, 8)); // Finding sum for the range [1, 10] System.out.println(query(1, 10)); } // Driver code public static void main(String[] args) { operations(); }} // This code is contributed by sanjeev2552", "e": 41386, "s": 37451, "text": null }, { "code": "# C++ program for the implementation# of the Dynamic segment tree and# perform the range updates on the# given queries # Structure of the nodeclass Node: def __init__(self): self.value=-1 self.L, self.R=None,None # Structure to get the newly formed# nodedef getnode(): temp = Node() temp.value = 0 temp.L = None temp.R = None return temp # Creating the Root noderoot=None # Function to perform the point update# on the dynamic segment treedef UpdateHelper(curr, index, L, R, val): # If the index is not overlapping # with the index if (L > index or R < index): return # If the index is completely overlapping # with the index if (L == R and L == index) : # Update the value of the node # to the given value curr.value = val return # Computing the middle index if none # of the above base cases are satisfied mid = int(L - (L - R) / 2) sum1 = 0; sum2 = 0 # If the index is in the left subtree if (index <= mid) : # Create a new node if the left # subtree is is None if (curr.L == None): curr.L = getnode() # Recursively call the function # for the left subtree UpdateHelper(curr.L, index, L, mid, val) # If the index is in the right subtree else : # Create a new node if the right # subtree is is None if (curr.R == None): curr.R = getnode() # Recursively call the function # for the right subtree UpdateHelper(curr.R, index, mid + 1, R, val) # Storing the sum of the left subtree if (curr.L): sum1 = curr.L.value # Storing the sum of the right subtree if (curr.R): sum2 = curr.R.value # Storing the sum of the children into # the node's value curr.value = sum1 + sum2 return # Function to find the sum of the# values given by the rangedef queryHelper(curr, a, b, L, R): # Return 0 if the root is None if (curr == None): return 0 # If the index is not overlapping # with the index, then the node # is not created. So sum is 0 if (L > b or R < a): return 0 # If the index is completely overlapping # with the index, return the node's value if (L >= a and R <= b): return curr.value mid = int(L - (L - R) / 2) # Return the sum of values stored # at the node's children return queryHelper(curr.L, a, b, L, mid) + queryHelper(curr.R, a, b, mid + 1, R) # Function to call the queryHelper# function to find the sum for# the querydef query(L, R): return queryHelper(root, L, R, 1, 10) # Function to call the UpdateHelper# function for the point updatedef update(index, value): UpdateHelper(root, index, 1, 10, value) # Function to perform the operations# on the treedef operations(): global root # Creating an empty tree root = getnode() # Update the value at position 1 to 10 update(1, 10) # Update the value at position 3 to 5 update(3, 5) # Finding sum for the range [2, 8] print(query(2, 8)) # Finding sum for the range [1, 10] print(query(1, 10)) # Driver codeif __name__ == '__main__': operations()", "e": 44584, "s": 41386, "text": null }, { "code": "using System; // C# program for the implementation// of the Dynamic segment tree and// perform the range updates on the// given queries class GFG { // Structure of the node public class Node { public int value; public Node L, R; } // Structure to get the newly formed // node static Node getnode() { Node temp = new Node(); temp.value = 0; temp.L = null; temp.R = null; return temp; } // Creating the Root node static Node root = new Node(); // Function to perform the point update // on the dynamic segment tree static void UpdateHelper(Node curr, int index, int L, int R, int val) { // If the index is not overlapping // with the index if (L > index || R < index) return; // If the index is completely overlapping // with the index if (L == R && L == index) { // Update the value of the node // to the given value curr.value = val; return; } // Computing the middle index if none // of the above base cases are satisfied int mid = L - (L - R) / 2; int sum1 = 0, sum2 = 0; // If the index is in the left subtree if (index <= mid) { // Create a new node if the left // subtree is is null if (curr.L == null) curr.L = getnode(); // Recursively call the function // for the left subtree UpdateHelper(curr.L, index, L, mid, val); } // If the index is in the right subtree else { // Create a new node if the right // subtree is is null if (curr.R == null) curr.R = getnode(); // Recursively call the function // for the right subtree UpdateHelper(curr.R, index, mid + 1, R, val); } // Storing the sum of the left subtree if (curr.L != null) sum1 = curr.L.value; // Storing the sum of the right subtree if (curr.R != null) sum2 = curr.R.value; // Storing the sum of the children into // the node's value curr.value = sum1 + sum2; return; } // Function to find the sum of the // values given by the range static int queryHelper(Node curr, int a, int b, int L, int R) { // Return 0 if the root is null if (curr == null) return 0; // If the index is not overlapping // with the index, then the node // is not created. So sum is 0 if (L > b || R < a) return 0; // If the index is completely overlapping // with the index, return the node's value if (L >= a && R <= b) return curr.value; int mid = L - (L - R) / 2; // Return the sum of values stored // at the node's children return queryHelper(curr.L, a, b, L, mid) + queryHelper(curr.R, a, b, mid + 1, R); } // Function to call the queryHelper // function to find the sum for // the query static int query(int L, int R) { return queryHelper(root, L, R, 1, 10); } // Function to call the UpdateHelper // function for the point update static void update(int index, int value) { UpdateHelper(root, index, 1, 10, value); } // Function to perform the operations // on the tree static void operations() { // Creating an empty tree root = getnode(); // Update the value at position 1 to 10 update(1, 10); // Update the value at position 3 to 5 update(3, 5); // Finding sum for the range [2, 8] Console.WriteLine(query(2, 8)); // Finding sum for the range [1, 10] Console.WriteLine(query(1, 10)); } // Driver code public static void Main(String[] args) { operations(); }} // This code is contributed by jana_sayantan.", "e": 48101, "s": 44584, "text": null }, { "code": "<script> // Javascript program for the implementation// of the Dynamic segment tree and perform// the range updates on the given queries // Structure of the nodeclass Node{ constructor() { this.L = null; this.R = null; this.value = 0; }} // Structure to get the newly formed// nodefunction getnode(){ let temp = new Node(); return temp;} // Creating the Root nodelet root = new Node(); // Function to perform the point update// on the dynamic segment treefunction UpdateHelper(curr, index, L, R, val){ // If the index is not overlapping // with the index if (L > index || R < index) return; // If the index is completely overlapping // with the index if (L == R && L == index) { // Update the value of the node // to the given value curr.value = val; return; } // Computing the middle index if none // of the above base cases are satisfied let mid = L - parseInt((L - R) / 2, 10); let sum1 = 0, sum2 = 0; // If the index is in the left subtree if (index <= mid) { // Create a new node if the left // subtree is is null if (curr.L == null) curr.L = getnode(); // Recursively call the function // for the left subtree UpdateHelper(curr.L, index, L, mid, val); } // If the index is in the right subtree else { // Create a new node if the right // subtree is is null if (curr.R == null) curr.R = getnode(); // Recursively call the function // for the right subtree UpdateHelper(curr.R, index, mid + 1, R, val); } // Storing the sum of the left subtree if (curr.L != null) sum1 = curr.L.value; // Storing the sum of the right subtree if (curr.R != null) sum2 = curr.R.value; // Storing the sum of the children into // the node's value curr.value = sum1 + sum2; return;} // Function to find the sum of the// values given by the rangefunction queryHelper(curr, a, b, L, R){ // Return 0 if the root is null if (curr == null) return 0; // If the index is not overlapping // with the index, then the node // is not created. So sum is 0 if (L > b || R < a) return 0; // If the index is completely overlapping // with the index, return the node's value if (L >= a && R <= b) return curr.value; let mid = L - parseInt((L - R) / 2, 10); // Return the sum of values stored // at the node's children return queryHelper(curr.L, a, b, L, mid) + queryHelper(curr.R, a, b, mid + 1, R);} // Function to call the queryHelper// function to find the sum for// the queryfunction query(L, R){ return queryHelper(root, L, R, 1, 10);} // Function to call the UpdateHelper// function for the point updatefunction update(index, value){ UpdateHelper(root, index, 1, 10, value);} // Function to perform the operations// on the treefunction operations(){ // Creating an empty tree root = getnode(); // Update the value at position 1 to 10 update(1, 10); // Update the value at position 3 to 5 update(3, 5); // Finding sum for the range [2, 8] document.write(query(2, 8) + \"</br>\"); // Finding sum for the range [1, 10] document.write(query(1, 10) + \"</br>\");} // Driver codeoperations(); // This code is contributed by mukesh07 </script>", "e": 51546, "s": 48101, "text": null }, { "code": null, "e": 51551, "s": 51546, "text": "5\n15" }, { "code": null, "e": 51605, "s": 51553, "text": "Time Complexity: O(Q * logN) Auxiliary Space: O(N) " }, { "code": null, "e": 51617, "s": 51605, "text": "sanjeev2552" }, { "code": null, "e": 51626, "s": 51617, "text": "mukesh07" }, { "code": null, "e": 51642, "s": 51626, "text": "pankajsharmagfg" }, { "code": null, "e": 51658, "s": 51642, "text": "amartyaghoshgfg" }, { "code": null, "e": 51672, "s": 51658, "text": "jana_sayantan" }, { "code": null, "e": 51692, "s": 51672, "text": "array-range-queries" }, { "code": null, "e": 51705, "s": 51692, "text": "Segment-Tree" }, { "code": null, "e": 51729, "s": 51705, "text": "Advanced Data Structure" }, { "code": null, "e": 51753, "s": 51729, "text": "Competitive Programming" }, { "code": null, "e": 51769, "s": 51753, "text": "Data Structures" }, { "code": null, "e": 51774, "s": 51769, "text": "Tree" }, { "code": null, "e": 51790, "s": 51774, "text": "Data Structures" }, { "code": null, "e": 51795, "s": 51790, "text": "Tree" }, { "code": null, "e": 51808, "s": 51795, "text": "Segment-Tree" }, { "code": null, "e": 51906, "s": 51808, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 51935, "s": 51906, "text": "Ordered Set and GNU C++ PBDS" }, { "code": null, "e": 51977, "s": 51935, "text": "2-3 Trees | (Search, Insert and Deletion)" }, { "code": null, "e": 52023, "s": 51977, "text": "Extendible Hashing (Dynamic approach to DBMS)" }, { "code": null, "e": 52059, "s": 52023, "text": "Suffix Array | Set 1 (Introduction)" }, { "code": null, "e": 52069, "s": 52059, "text": "Quad Tree" }, { "code": null, "e": 52112, "s": 52069, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 52155, "s": 52112, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 52196, "s": 52155, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 52274, "s": 52196, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" } ]
Profit and loss | Set-2 - GeeksforGeeks
26 Jul, 2020 Question 1: The cost price of 12 books is equal to the selling price of 10 books. The gain percent is :Solution : Given 12 CP = 10 SPCP/SP = 10/12 = 5/6Profit = SP – CP=> 6 – 5 = 1Profit (%) = profit/CP x 100=> 1/5 x 100=> 20 % Question 2: If the loss% on article is 15%. Then the ratio of cost price and selling price will beSolution : Loss % = 15 %= 15/100= 3/20Loss= 3 and CP = 20SP = CP – L= 20 – 3 = 17CP : SP = 20 : 17 Question 3: Ram goes from place P to Q to buy an article costing 20% less at Q. Although he spends Rs 200 on travelling, still he gains Rs 200 compared to buying at P. His profit percent is:Solution : Let the price at P = 100athen price at Q = 80a (20% less)Acc. to question100a – (80a + 200) = 20020a = 400a = 20Price at P = 100×20 = 2000Price at Q including travelling = 80×20 + 200 = 1800Profit (%) = [(2000 – 1800) / 2000]x100=200/20 = 10%Hence, his profit is 10%. Question 4: The price of a TV and a refrigerator set are in ratio 3:5. If the refrigerator cost Rs 4400 more than the TV set, then the price of the TV isSolution : Acc. to questionTV/Ref. = 3/5Difference in ratio = 22 -> 44001 -> 2200The price of the TV = 3×2200 = Rs 6600 Question 5: A house and a shop were sold for Rs. 1 lakh each. In this transaction, the house sale resulted into 20% loss whereas the shop sale into 20% profit. The entire transaction resulted in:Solution : Acc. to question House Shop CP 10 10 |-20% |+20% SP 8 12 Make SP equal CP 10x12 10x8 -> 200 |-20% |+20% |-8 SP 8x12 12x8 -> 192 Given that192 -> 2 lakh1 -> 1/968 unit -> 8/96 -> 1/12 lakhHence, in entire transaction loss is 1/12 lakh. Question 6: A shopkeeper sells a chair at a profit of 20%. If he had bought the table at 10% less cost and sold for Rs 60 more, he would have gained 40%. The cost price of the chair is:Solution : Let 100 units is the CP of chair.Sells at profit 20% than SP = 120If buys 10% less and sells at 40% profit than SP = 126 -10% (CP)100 ______________(New CP)90 |+20% |+40% (SP)120 (New SP)126 So, difference in SP and New SP is given 60126 – 120 = 66 -> 601 -> 10100 -> 1000Hence, the cost price of chair is Rs 1000. Question 7: By selling a bicycle of Rs 3360 a shopkeeper gain 12%. If the profit is reduced to 8%, then the selling price will beSolution :SP of bicycle = Rs 3360Profit % = 12 %CP = (SP/100+P)x100CP = (3360/112) x 100New profit% = 8%New SP = CPx(100+P%)/100= (3360/112)x100x(108/100)= 3240Hence, the selling price of bicycle is Rs 3240. Question 8: A man purchased an article of Rs 2500 and sold it at 40% above the cost price. If he has to pay Rs 250 as tax on it his net profit percentage will be:Solution : CP = 2500P =40%Profit = CPx25/100= 2500×40/100= 1000Net profit = profit – tax= 1000 – 250 = 750Net profit % = 750/2500 x 100=30%Hence, net profit percent is 30%. Question 9: A sells an item to B at a profit of 25%. B sells it to C at a profit of 20%. If C pays Rs 900 for it, the cost price of the bicycle for A is :Solution : Acc. to question A B C 100___25% profit____ 125____20% profit___150 Now, 150 unit -> 9001 unit -> 6100 unit -> 600Hence, the cost price of the bicycle is 600. Question 10: A increase of 20% in the price of apple enabled a purchaser to obtain 4 apple less of Rs 72. The price of 16 apple before increase wasSolution :Acc. to question Price 5 20% increase 6 Commodity 6 1 unit less 5 |x4 | |x4 24 apples 4 apples 20 apples He purchased 24 apples of Rs 72 before increase of price and 4 less apples after increase.24 apples = Rs 721 apple = Rs 316 apples = Rs 48 Question 11: Shyam buys some chocolates at 2 for a rupee and sells them at 5 for a rupee. His loss percent is:Solution : Acc. to question Chocolates Price CP 2x5=10 1x5=5 loss 3 SP 5x2=10 1x2=2 make chocolates same and we loss Rs 3 here.So, Loss% = 3/5 x 100= 60% Question 12: By selling 100 oranges, a shopkeeper gains the selling price of 20 oranges. His gain percent is:Solution : Let SP of 1 orange is Rs 1.SP of 100 orange is Rs 100.CP of 1 orange is Rs a.CP of 100 orange is Rs 100a.Acc . to questionGain=SP -CP20 = 100 – 100aa = 80/100 = 4/5CP of 1 orange = 4/5CP of 100 orange = 100×4/5= 80SP of 100 orange = Rs 100gain% = 20/80 x 100 = 25%Hence, his gain percent is 25%. Question 13: A dealer makes a profit of 20% even after giving a 10% discount on the advertised price of a scooter.If he makes a profit of Rs 7200 on the sale of the scooter, the advertise price wasSolution : Let cost price and Marked price of scooter is 10 units.10profit 20% —> 1210discount 10% —> 9Acc. to question CP SP MP 10x9 12x9 9x12 10x12 Total 90 108 120 Make SP equalNow, profit = SP – CP= 108 – 90 = 1818 unit -> 72001 unit -> 400120 -> 48000Hence, the marked price of scooter was Rs 48000. Question 14: A shopkeeper allows a discount of 22% on the marked price. How much above the cost price must he mark his goods as to gain 17%?Solution : Acc. to question CP MP 100 - discount : 100 + profit 100 - 22 : 100 + 17 78 : 117 2 : 3 3-2 = 1Raised% = 1/2 x 100= 50%Hence, he has to mark his goods 50% above of CP. prakharshukla1 Placements QA - Placements Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 20 Puzzles Commonly Asked During SDE Interviews Codenation Recruitment Process Minimum changes required to make all Array elements Prime Interview Preparation Puzzle | 50 red marbles and 50 blue marbles Mixture and Alligation Probability Simple Interest Age Algebra | Set -1
[ { "code": null, "e": 25365, "s": 25337, "text": "\n26 Jul, 2020" }, { "code": null, "e": 25593, "s": 25365, "text": "Question 1: The cost price of 12 books is equal to the selling price of 10 books. The gain percent is :Solution : Given 12 CP = 10 SPCP/SP = 10/12 = 5/6Profit = SP – CP=> 6 – 5 = 1Profit (%) = profit/CP x 100=> 1/5 x 100=> 20 %" }, { "code": null, "e": 25790, "s": 25593, "text": "Question 2: If the loss% on article is 15%. Then the ratio of cost price and selling price will beSolution : Loss % = 15 %= 15/100= 3/20Loss= 3 and CP = 20SP = CP – L= 20 – 3 = 17CP : SP = 20 : 17" }, { "code": null, "e": 26259, "s": 25790, "text": "Question 3: Ram goes from place P to Q to buy an article costing 20% less at Q. Although he spends Rs 200 on travelling, still he gains Rs 200 compared to buying at P. His profit percent is:Solution : Let the price at P = 100athen price at Q = 80a (20% less)Acc. to question100a – (80a + 200) = 20020a = 400a = 20Price at P = 100×20 = 2000Price at Q including travelling = 80×20 + 200 = 1800Profit (%) = [(2000 – 1800) / 2000]x100=200/20 = 10%Hence, his profit is 10%." }, { "code": null, "e": 26532, "s": 26259, "text": "Question 4: The price of a TV and a refrigerator set are in ratio 3:5. If the refrigerator cost Rs 4400 more than the TV set, then the price of the TV isSolution : Acc. to questionTV/Ref. = 3/5Difference in ratio = 22 -> 44001 -> 2200The price of the TV = 3×2200 = Rs 6600" }, { "code": null, "e": 26755, "s": 26532, "text": "Question 5: A house and a shop were sold for Rs. 1 lakh each. In this transaction, the house sale resulted into 20% loss whereas the shop sale into 20% profit. The entire transaction resulted in:Solution : Acc. to question" }, { "code": null, "e": 26882, "s": 26755, "text": " House Shop\nCP 10 10 \n |-20% |+20%\nSP 8 12\n" }, { "code": null, "e": 26896, "s": 26882, "text": "Make SP equal" }, { "code": null, "e": 27044, "s": 26896, "text": "CP 10x12 10x8 -> 200\n |-20% |+20% |-8 \nSP 8x12 12x8 -> 192\n" }, { "code": null, "e": 27151, "s": 27044, "text": "Given that192 -> 2 lakh1 -> 1/968 unit -> 8/96 -> 1/12 lakhHence, in entire transaction loss is 1/12 lakh." }, { "code": null, "e": 27468, "s": 27151, "text": "Question 6: A shopkeeper sells a chair at a profit of 20%. If he had bought the table at 10% less cost and sold for Rs 60 more, he would have gained 40%. The cost price of the chair is:Solution : Let 100 units is the CP of chair.Sells at profit 20% than SP = 120If buys 10% less and sells at 40% profit than SP = 126" }, { "code": null, "e": 27639, "s": 27468, "text": " \n -10%\n (CP)100 ______________(New CP)90 \n |+20% |+40%\n (SP)120 (New SP)126\n" }, { "code": null, "e": 27763, "s": 27639, "text": "So, difference in SP and New SP is given 60126 – 120 = 66 -> 601 -> 10100 -> 1000Hence, the cost price of chair is Rs 1000." }, { "code": null, "e": 28100, "s": 27763, "text": "Question 7: By selling a bicycle of Rs 3360 a shopkeeper gain 12%. If the profit is reduced to 8%, then the selling price will beSolution :SP of bicycle = Rs 3360Profit % = 12 %CP = (SP/100+P)x100CP = (3360/112) x 100New profit% = 8%New SP = CPx(100+P%)/100= (3360/112)x100x(108/100)= 3240Hence, the selling price of bicycle is Rs 3240." }, { "code": null, "e": 28435, "s": 28100, "text": "Question 8: A man purchased an article of Rs 2500 and sold it at 40% above the cost price. If he has to pay Rs 250 as tax on it his net profit percentage will be:Solution : CP = 2500P =40%Profit = CPx25/100= 2500×40/100= 1000Net profit = profit – tax= 1000 – 250 = 750Net profit % = 750/2500 x 100=30%Hence, net profit percent is 30%." }, { "code": null, "e": 28617, "s": 28435, "text": "Question 9: A sells an item to B at a profit of 25%. B sells it to C at a profit of 20%. If C pays Rs 900 for it, the cost price of the bicycle for A is :Solution : Acc. to question" }, { "code": null, "e": 28710, "s": 28617, "text": " A B C\n 100___25% profit____ 125____20% profit___150\n" }, { "code": null, "e": 28801, "s": 28710, "text": "Now, 150 unit -> 9001 unit -> 6100 unit -> 600Hence, the cost price of the bicycle is 600." }, { "code": null, "e": 28975, "s": 28801, "text": "Question 10: A increase of 20% in the price of apple enabled a purchaser to obtain 4 apple less of Rs 72. The price of 16 apple before increase wasSolution :Acc. to question" }, { "code": null, "e": 29162, "s": 28975, "text": "Price 5 20% increase 6\nCommodity 6 1 unit less 5 \n |x4 | |x4\n 24 apples 4 apples 20 apples\n" }, { "code": null, "e": 29301, "s": 29162, "text": "He purchased 24 apples of Rs 72 before increase of price and 4 less apples after increase.24 apples = Rs 721 apple = Rs 316 apples = Rs 48" }, { "code": null, "e": 29439, "s": 29301, "text": "Question 11: Shyam buys some chocolates at 2 for a rupee and sells them at 5 for a rupee. His loss percent is:Solution : Acc. to question" }, { "code": null, "e": 29591, "s": 29439, "text": " Chocolates Price\nCP 2x5=10 1x5=5\n loss 3\nSP 5x2=10 1x2=2\n" }, { "code": null, "e": 29661, "s": 29591, "text": "make chocolates same and we loss Rs 3 here.So, Loss% = 3/5 x 100= 60%" }, { "code": null, "e": 30077, "s": 29661, "text": "Question 12: By selling 100 oranges, a shopkeeper gains the selling price of 20 oranges. His gain percent is:Solution : Let SP of 1 orange is Rs 1.SP of 100 orange is Rs 100.CP of 1 orange is Rs a.CP of 100 orange is Rs 100a.Acc . to questionGain=SP -CP20 = 100 – 100aa = 80/100 = 4/5CP of 1 orange = 4/5CP of 100 orange = 100×4/5= 80SP of 100 orange = Rs 100gain% = 20/80 x 100 = 25%Hence, his gain percent is 25%." }, { "code": null, "e": 30394, "s": 30077, "text": "Question 13: A dealer makes a profit of 20% even after giving a 10% discount on the advertised price of a scooter.If he makes a profit of Rs 7200 on the sale of the scooter, the advertise price wasSolution : Let cost price and Marked price of scooter is 10 units.10profit 20% —> 1210discount 10% —> 9Acc. to question" }, { "code": null, "e": 30530, "s": 30394, "text": " CP SP MP\n 10x9 12x9 \n 9x12 10x12\nTotal 90 108 120\n" }, { "code": null, "e": 30668, "s": 30530, "text": "Make SP equalNow, profit = SP – CP= 108 – 90 = 1818 unit -> 72001 unit -> 400120 -> 48000Hence, the marked price of scooter was Rs 48000." }, { "code": null, "e": 30836, "s": 30668, "text": "Question 14: A shopkeeper allows a discount of 22% on the marked price. How much above the cost price must he mark his goods as to gain 17%?Solution : Acc. to question" }, { "code": null, "e": 30975, "s": 30836, "text": " CP MP\n100 - discount : 100 + profit\n 100 - 22 : 100 + 17\n 78 : 117\n 2 : 3\n" }, { "code": null, "e": 31055, "s": 30975, "text": "3-2 = 1Raised% = 1/2 x 100= 50%Hence, he has to mark his goods 50% above of CP." }, { "code": null, "e": 31070, "s": 31055, "text": "prakharshukla1" }, { "code": null, "e": 31081, "s": 31070, "text": "Placements" }, { "code": null, "e": 31097, "s": 31081, "text": "QA - Placements" }, { "code": null, "e": 31195, "s": 31097, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31247, "s": 31195, "text": "Top 20 Puzzles Commonly Asked During SDE Interviews" }, { "code": null, "e": 31278, "s": 31247, "text": "Codenation Recruitment Process" }, { "code": null, "e": 31336, "s": 31278, "text": "Minimum changes required to make all Array elements Prime" }, { "code": null, "e": 31358, "s": 31336, "text": "Interview Preparation" }, { "code": null, "e": 31402, "s": 31358, "text": "Puzzle | 50 red marbles and 50 blue marbles" }, { "code": null, "e": 31425, "s": 31402, "text": "Mixture and Alligation" }, { "code": null, "e": 31437, "s": 31425, "text": "Probability" }, { "code": null, "e": 31453, "s": 31437, "text": "Simple Interest" }, { "code": null, "e": 31457, "s": 31453, "text": "Age" } ]
Draw a car using Turtle in Python - GeeksforGeeks
12 Jan, 2022 Prerequisite: Turtle module, Drawing Shapes There are many modules in python which depict graphical illustrations, one of them is a turtle, it is an in-built module in Python, which lets the user control a pen(turtle) to draw on the screen(drawing board). It is mostly used to illustrate figures, shapes, designs, etc. In this article, we will learn how to draw a Car using the turtle module. To draw a car in Python using the Turtle module: We are going to create different shapes using the turtle module in order to illustrate a car.Tyres can be drawn using the circle() function.The upper body can be thought of as a rectangle.The roof and windows are similar to a trapezoid.Overlapping all the above shapes in particular positions will illustrate a car. We are going to create different shapes using the turtle module in order to illustrate a car. Tyres can be drawn using the circle() function. The upper body can be thought of as a rectangle. The roof and windows are similar to a trapezoid. Overlapping all the above shapes in particular positions will illustrate a car. Let’s try to understand it better with the help of the below program: Python3 #Python program to draw car in turtle programming # Import required libraryimport turtle car = turtle.Turtle() # Below code for drawing rectangular upper bodycar.color('#008000')car.fillcolor('#008000')car.penup()car.goto(0,0)car.pendown()car.begin_fill()car.forward(370)car.left(90)car.forward(50)car.left(90)car.forward(370)car.left(90)car.forward(50)car.end_fill() # Below code for drawing window and roofcar.penup()car.goto(100, 50)car.pendown()car.setheading(45)car.forward(70)car.setheading(0)car.forward(100)car.setheading(-45)car.forward(70)car.setheading(90)car.penup()car.goto(200, 50)car.pendown()car.forward(49.50) # Below code for drawing two tyrescar.penup()car.goto(100, -10)car.pendown()car.color('#000000')car.fillcolor('#000000')car.begin_fill()car.circle(20)car.end_fill()car.penup()car.goto(300, -10)car.pendown()car.color('#000000')car.fillcolor('#000000')car.begin_fill()car.circle(20)car.end_fill() car.hideturtle() Output: chhabradhanvi Python-turtle Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25563, "s": 25535, "text": "\n12 Jan, 2022" }, { "code": null, "e": 25607, "s": 25563, "text": "Prerequisite: Turtle module, Drawing Shapes" }, { "code": null, "e": 25958, "s": 25607, "text": "There are many modules in python which depict graphical illustrations, one of them is a turtle, it is an in-built module in Python, which lets the user control a pen(turtle) to draw on the screen(drawing board). It is mostly used to illustrate figures, shapes, designs, etc. In this article, we will learn how to draw a Car using the turtle module. " }, { "code": null, "e": 26007, "s": 25958, "text": "To draw a car in Python using the Turtle module:" }, { "code": null, "e": 26323, "s": 26007, "text": "We are going to create different shapes using the turtle module in order to illustrate a car.Tyres can be drawn using the circle() function.The upper body can be thought of as a rectangle.The roof and windows are similar to a trapezoid.Overlapping all the above shapes in particular positions will illustrate a car." }, { "code": null, "e": 26417, "s": 26323, "text": "We are going to create different shapes using the turtle module in order to illustrate a car." }, { "code": null, "e": 26465, "s": 26417, "text": "Tyres can be drawn using the circle() function." }, { "code": null, "e": 26514, "s": 26465, "text": "The upper body can be thought of as a rectangle." }, { "code": null, "e": 26563, "s": 26514, "text": "The roof and windows are similar to a trapezoid." }, { "code": null, "e": 26643, "s": 26563, "text": "Overlapping all the above shapes in particular positions will illustrate a car." }, { "code": null, "e": 26714, "s": 26643, "text": " Let’s try to understand it better with the help of the below program:" }, { "code": null, "e": 26722, "s": 26714, "text": "Python3" }, { "code": "#Python program to draw car in turtle programming # Import required libraryimport turtle car = turtle.Turtle() # Below code for drawing rectangular upper bodycar.color('#008000')car.fillcolor('#008000')car.penup()car.goto(0,0)car.pendown()car.begin_fill()car.forward(370)car.left(90)car.forward(50)car.left(90)car.forward(370)car.left(90)car.forward(50)car.end_fill() # Below code for drawing window and roofcar.penup()car.goto(100, 50)car.pendown()car.setheading(45)car.forward(70)car.setheading(0)car.forward(100)car.setheading(-45)car.forward(70)car.setheading(90)car.penup()car.goto(200, 50)car.pendown()car.forward(49.50) # Below code for drawing two tyrescar.penup()car.goto(100, -10)car.pendown()car.color('#000000')car.fillcolor('#000000')car.begin_fill()car.circle(20)car.end_fill()car.penup()car.goto(300, -10)car.pendown()car.color('#000000')car.fillcolor('#000000')car.begin_fill()car.circle(20)car.end_fill() car.hideturtle()", "e": 27678, "s": 26722, "text": null }, { "code": null, "e": 27687, "s": 27678, "text": "Output: " }, { "code": null, "e": 27703, "s": 27689, "text": "chhabradhanvi" }, { "code": null, "e": 27717, "s": 27703, "text": "Python-turtle" }, { "code": null, "e": 27724, "s": 27717, "text": "Python" }, { "code": null, "e": 27822, "s": 27724, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27854, "s": 27822, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27896, "s": 27854, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27938, "s": 27896, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27994, "s": 27938, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28021, "s": 27994, "text": "Python Classes and Objects" }, { "code": null, "e": 28060, "s": 28021, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28091, "s": 28060, "text": "Python | os.path.join() method" }, { "code": null, "e": 28120, "s": 28091, "text": "Create a directory in Python" }, { "code": null, "e": 28142, "s": 28120, "text": "Defaultdict in Python" } ]
C# Program to Read a String and Find the Sum of all Digits - GeeksforGeeks
19 Oct, 2021 Given a string, our task is to first read this string from the user then find the sum of all the digits present in the given string. Examples Input : abc23d4 Output: 9 Input : 2a3hd5j Output: 10 Approach: To reada String and find the sum of all digits present in the string follow the following steps: First of all we read the string from the user using Console.ReadLine() method. Initialize a integer sum with value 0. Now iterate the string till the end. If the character value is greater than or equal to ‘0’ and less than or equal to ‘9’ (i.e. ascii value between 48 to 57) then perform character – ‘0’ (this gives value of character) and add the value to the sum. Now the sum contains the value of sum of all the digits in the strings. Example: C# // C# program to read the string from the user and// then find the sum of all digits in the stringusing System; class GFG{ public static void Main(){ string str; Console.WriteLine("Enter a string "); // Reading the string from user. str = Console.ReadLine(); int count, sum = 0; int n = str.Length; for(count = 0; count < n; count++) { // Checking if the string contains digits or not // If yes then add the numbers to find their sum if ((str[count] >= '0') && (str[count] <= '9')) { sum += (str[count] - '0'); } } Console.WriteLine("Sum = " + sum);}} Enter a string abc23d4 Sum = 9 Output 2: Enter a string 2a3hd5j Sum = 10 Explanation: In the above example, first we read the string and we will iterate each character and check if the character is an integer or not by comparing the ASCII value of the character. If the character is an integer then add the value to the sum. At the end of the iteration, the sum variable will have the total sum of digits in the string. CSharp-programs CSharp-Strings-Programs Picked C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Top 50 C# Interview Questions & Answers Switch Statement in C# Convert String to Character Array in C# C# | How to insert an element in an Array? Linked List Implementation in C#
[ { "code": null, "e": 25547, "s": 25519, "text": "\n19 Oct, 2021" }, { "code": null, "e": 25680, "s": 25547, "text": "Given a string, our task is to first read this string from the user then find the sum of all the digits present in the given string." }, { "code": null, "e": 25689, "s": 25680, "text": "Examples" }, { "code": null, "e": 25743, "s": 25689, "text": "Input : abc23d4\nOutput: 9\n\nInput : 2a3hd5j\nOutput: 10" }, { "code": null, "e": 25753, "s": 25743, "text": "Approach:" }, { "code": null, "e": 25850, "s": 25753, "text": "To reada String and find the sum of all digits present in the string follow the following steps:" }, { "code": null, "e": 25929, "s": 25850, "text": "First of all we read the string from the user using Console.ReadLine() method." }, { "code": null, "e": 25968, "s": 25929, "text": "Initialize a integer sum with value 0." }, { "code": null, "e": 26005, "s": 25968, "text": "Now iterate the string till the end." }, { "code": null, "e": 26218, "s": 26005, "text": "If the character value is greater than or equal to ‘0’ and less than or equal to ‘9’ (i.e. ascii value between 48 to 57) then perform character – ‘0’ (this gives value of character) and add the value to the sum." }, { "code": null, "e": 26290, "s": 26218, "text": "Now the sum contains the value of sum of all the digits in the strings." }, { "code": null, "e": 26299, "s": 26290, "text": "Example:" }, { "code": null, "e": 26302, "s": 26299, "text": "C#" }, { "code": "// C# program to read the string from the user and// then find the sum of all digits in the stringusing System; class GFG{ public static void Main(){ string str; Console.WriteLine(\"Enter a string \"); // Reading the string from user. str = Console.ReadLine(); int count, sum = 0; int n = str.Length; for(count = 0; count < n; count++) { // Checking if the string contains digits or not // If yes then add the numbers to find their sum if ((str[count] >= '0') && (str[count] <= '9')) { sum += (str[count] - '0'); } } Console.WriteLine(\"Sum = \" + sum);}}", "e": 26957, "s": 26302, "text": null }, { "code": null, "e": 26988, "s": 26957, "text": "Enter a string\nabc23d4\nSum = 9" }, { "code": null, "e": 26998, "s": 26988, "text": "Output 2:" }, { "code": null, "e": 27030, "s": 26998, "text": "Enter a string\n2a3hd5j\nSum = 10" }, { "code": null, "e": 27377, "s": 27030, "text": "Explanation: In the above example, first we read the string and we will iterate each character and check if the character is an integer or not by comparing the ASCII value of the character. If the character is an integer then add the value to the sum. At the end of the iteration, the sum variable will have the total sum of digits in the string." }, { "code": null, "e": 27393, "s": 27377, "text": "CSharp-programs" }, { "code": null, "e": 27417, "s": 27393, "text": "CSharp-Strings-Programs" }, { "code": null, "e": 27424, "s": 27417, "text": "Picked" }, { "code": null, "e": 27427, "s": 27424, "text": "C#" }, { "code": null, "e": 27525, "s": 27427, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27548, "s": 27525, "text": "Extension Method in C#" }, { "code": null, "e": 27576, "s": 27548, "text": "HashSet in C# with Examples" }, { "code": null, "e": 27593, "s": 27576, "text": "C# | Inheritance" }, { "code": null, "e": 27615, "s": 27593, "text": "Partial Classes in C#" }, { "code": null, "e": 27644, "s": 27615, "text": "C# | Generics - Introduction" }, { "code": null, "e": 27684, "s": 27644, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 27707, "s": 27684, "text": "Switch Statement in C#" }, { "code": null, "e": 27747, "s": 27707, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 27790, "s": 27747, "text": "C# | How to insert an element in an Array?" } ]
How to click anywhere on the page except one element using jQuery ? - GeeksforGeeks
20 Dec, 2019 A web-page containing many elements and the task is to click anywhere on the page except one element using jQuery. There are two methods to solve this problem which are discussed below: Approach 1: This approach calls a function when a click event happens. First check the id of the targeted element and return the function if it matches. Else, perform some operation to let the know that somewhere is clicked. Example: This example implements the above approach. <!DOCTYPE HTML> <html> <head> <title> How to click anywhere of page except one element using jQuery ? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> body { height: auto; } #t { height: 100px; width: 350px; background: green; color: white; text-align:justify; } </style></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksforGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <textarea id = "t"> jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM), and JavaScript. Elaborating the terms, jQuery simplifies HTML document traversing and manipulation, browser event handling, DOM animations, Ajax interactions, and cross-browser JavaScript development. </textarea> <br> <button onclick = "gfg_Run()"> click here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click anywhere on the body " + "except textarea to see effect."; $('body').click(function(evnt) { if(evnt.target.id == "t") return; if($(evnt.target).closest('t').length) return; el_down.innerHTML = "Clicked on the " + "body except textarea."; }); </script> </body> </html> Output: Before clicking on the button: After clicking on the element: Approach 2: This approach calls a function when any click event happens. If it is other HTML element then do nothing. Else, use event.stopPropagation() method to stop the event from occurring. Example: This example implements the above approach. <!DOCTYPE HTML> <html> <head> <title> How to click anywhere of page except one element using jQuery ? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> body { height: auto; } #t { height: 100px; width: 350px; background: green; color: white; text-align:justify; } </style></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksforGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <textarea id = "t"> jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM), and JavaScript. Elaborating the terms, jQuery simplifies HTML document traversing and manipulation, browser event handling, DOM animations, Ajax interactions, and cross-browser JavaScript development. </textarea> <br> <button onclick = "gfg_Run()"> click here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click anywhere on the body" + " except textarea to see effect."; $('html').click(function() { el_down.innerHTML = "Clicked on the body" + " except textarea."; }); $('#t').click(function(event) { event.stopPropagation(); }); </script> </body> </html> Output: Before clicking on the button: After clicking on the element: JavaScript-Misc jQuery-Misc JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26570, "s": 26542, "text": "\n20 Dec, 2019" }, { "code": null, "e": 26756, "s": 26570, "text": "A web-page containing many elements and the task is to click anywhere on the page except one element using jQuery. There are two methods to solve this problem which are discussed below:" }, { "code": null, "e": 26768, "s": 26756, "text": "Approach 1:" }, { "code": null, "e": 26827, "s": 26768, "text": "This approach calls a function when a click event happens." }, { "code": null, "e": 26909, "s": 26827, "text": "First check the id of the targeted element and return the function if it matches." }, { "code": null, "e": 26981, "s": 26909, "text": "Else, perform some operation to let the know that somewhere is clicked." }, { "code": null, "e": 27034, "s": 26981, "text": "Example: This example implements the above approach." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to click anywhere of page except one element using jQuery ? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> body { height: auto; } #t { height: 100px; width: 350px; background: green; color: white; text-align:justify; } </style></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksforGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <textarea id = \"t\"> jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM), and JavaScript. Elaborating the terms, jQuery simplifies HTML document traversing and manipulation, browser event handling, DOM animations, Ajax interactions, and cross-browser JavaScript development. </textarea> <br> <button onclick = \"gfg_Run()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); el_up.innerHTML = \"Click anywhere on the body \" + \"except textarea to see effect.\"; $('body').click(function(evnt) { if(evnt.target.id == \"t\") return; if($(evnt.target).closest('t').length) return; el_down.innerHTML = \"Clicked on the \" + \"body except textarea.\"; }); </script> </body> </html>", "e": 28963, "s": 27034, "text": null }, { "code": null, "e": 28971, "s": 28963, "text": "Output:" }, { "code": null, "e": 29002, "s": 28971, "text": "Before clicking on the button:" }, { "code": null, "e": 29033, "s": 29002, "text": "After clicking on the element:" }, { "code": null, "e": 29045, "s": 29033, "text": "Approach 2:" }, { "code": null, "e": 29106, "s": 29045, "text": "This approach calls a function when any click event happens." }, { "code": null, "e": 29151, "s": 29106, "text": "If it is other HTML element then do nothing." }, { "code": null, "e": 29226, "s": 29151, "text": "Else, use event.stopPropagation() method to stop the event from occurring." }, { "code": null, "e": 29279, "s": 29226, "text": "Example: This example implements the above approach." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to click anywhere of page except one element using jQuery ? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> body { height: auto; } #t { height: 100px; width: 350px; background: green; color: white; text-align:justify; } </style></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksforGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <textarea id = \"t\"> jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM), and JavaScript. Elaborating the terms, jQuery simplifies HTML document traversing and manipulation, browser event handling, DOM animations, Ajax interactions, and cross-browser JavaScript development. </textarea> <br> <button onclick = \"gfg_Run()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); el_up.innerHTML = \"Click anywhere on the body\" + \" except textarea to see effect.\"; $('html').click(function() { el_down.innerHTML = \"Clicked on the body\" + \" except textarea.\"; }); $('#t').click(function(event) { event.stopPropagation(); }); </script> </body> </html>", "e": 31139, "s": 29279, "text": null }, { "code": null, "e": 31147, "s": 31139, "text": "Output:" }, { "code": null, "e": 31178, "s": 31147, "text": "Before clicking on the button:" }, { "code": null, "e": 31209, "s": 31178, "text": "After clicking on the element:" }, { "code": null, "e": 31225, "s": 31209, "text": "JavaScript-Misc" }, { "code": null, "e": 31237, "s": 31225, "text": "jQuery-Misc" }, { "code": null, "e": 31248, "s": 31237, "text": "JavaScript" }, { "code": null, "e": 31265, "s": 31248, "text": "Web Technologies" }, { "code": null, "e": 31292, "s": 31265, "text": "Web technologies Questions" }, { "code": null, "e": 31390, "s": 31292, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31430, "s": 31390, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31491, "s": 31430, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 31532, "s": 31491, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 31554, "s": 31532, "text": "JavaScript | Promises" }, { "code": null, "e": 31608, "s": 31554, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 31648, "s": 31608, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31681, "s": 31648, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31724, "s": 31681, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 31774, "s": 31724, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
LINQ | Equality Operator | SequenceEqual - GeeksforGeeks
22 May, 2019 The equality operator is used to check whether the given two sequences are identically equal or not. In LINQ, the equality operation contains only one operator that is known as SequenceEqual. It is used to check whether the given elements in the sequence or collection are equal or not. If the given sequences or collections are equal then it returns true otherwise return false. It compares the value and the numbers of elements, if the collection or sequence has primitive data types. It checks the references of the objects, if the collection has complex type elements. It does not support query syntax in C# and VB.Net languages. It support method syntax in both C# and VB.Net languages. It present in both the Queryable and Enumerable class. It is implemented by using deferred execution. You are allowed to use IEqualityComparer class to compare two collections of complex type using SequenceEqual method. Example 1: // C# program to check the given// sequences are equal or notusing System;using System.Linq; class GFG { static public void Main() { // Data source char[] sequence1 = {'p', 'q', 'r', 's', 'y', 'z'}; char[] sequence2 = {'p', 'q', 'r', 's', 'y', 'z'}; // Display the sequences Console.WriteLine("Sequence 1 is: "); foreach(var s1 in sequence1) { Console.WriteLine(s1); } Console.WriteLine("Sequence 2 is: "); foreach(var s2 in sequence2) { Console.WriteLine(s2); } // Check the given sequences are equal or // not Using SequenceEqual function var result = sequence1.SequenceEqual(sequence2); Console.WriteLine("Given Sequences are equal: {0}", result); }} Sequence 1 is: p q r s y z Sequence 2 is: p q r s y z Given Sequences are equal: True Example 2: // C# program to check the names of// the employee are equal or notusing System;using System.Linq;using System.Collections.Generic; // Employee detailspublic class Employee1 { public int emp_id1 { get; set; } public string emp_name1 { get; set; } public string emp_lang1 { get; set; }} // Employee detailspublic class Employee2 { public int emp_id2 { get; set; } public string emp_name2 { get; set; } public string emp_lang2 { get; set; }} public class GFG { // Main method static public void Main() { List<Employee1> emp1 = new List<Employee1>() { new Employee1() {emp_id1 = 209, emp_name1 = "Anjita", emp_lang1 = "C#"}, new Employee1() {emp_id1 = 210, emp_name1 = "Soniya", emp_lang1 = "C"}, new Employee1() {emp_id1 = 211, emp_name1 = "Rohit", emp_lang1 = "Java"}, }; List<Employee2> emp2 = new List<Employee2>() { new Employee2() {emp_id2 = 209, emp_name2 = "Anjita", emp_lang2 = "Scala"}, new Employee2() {emp_id2 = 210, emp_name2 = "Soniya", emp_lang2 = "Python"}, new Employee2() {emp_id2 = 211, emp_name2 = "Rohit", emp_lang2 = "Ruby"}, }; // Query to check the names of // the employee are equal or not // Using SequenceEqual method var res = emp1.Select(e => e.emp_name1).SequenceEqual(emp2.Select(e => e.emp_name2)); Console.WriteLine(res); }} True CSharp LINQ C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Top 50 C# Interview Questions & Answers Switch Statement in C# C# | How to insert an element in an Array? Convert String to Character Array in C# Linked List Implementation in C#
[ { "code": null, "e": 25547, "s": 25519, "text": "\n22 May, 2019" }, { "code": null, "e": 25927, "s": 25547, "text": "The equality operator is used to check whether the given two sequences are identically equal or not. In LINQ, the equality operation contains only one operator that is known as SequenceEqual. It is used to check whether the given elements in the sequence or collection are equal or not. If the given sequences or collections are equal then it returns true otherwise return false." }, { "code": null, "e": 26034, "s": 25927, "text": "It compares the value and the numbers of elements, if the collection or sequence has primitive data types." }, { "code": null, "e": 26120, "s": 26034, "text": "It checks the references of the objects, if the collection has complex type elements." }, { "code": null, "e": 26181, "s": 26120, "text": "It does not support query syntax in C# and VB.Net languages." }, { "code": null, "e": 26239, "s": 26181, "text": "It support method syntax in both C# and VB.Net languages." }, { "code": null, "e": 26294, "s": 26239, "text": "It present in both the Queryable and Enumerable class." }, { "code": null, "e": 26341, "s": 26294, "text": "It is implemented by using deferred execution." }, { "code": null, "e": 26459, "s": 26341, "text": "You are allowed to use IEqualityComparer class to compare two collections of complex type using SequenceEqual method." }, { "code": null, "e": 26470, "s": 26459, "text": "Example 1:" }, { "code": "// C# program to check the given// sequences are equal or notusing System;using System.Linq; class GFG { static public void Main() { // Data source char[] sequence1 = {'p', 'q', 'r', 's', 'y', 'z'}; char[] sequence2 = {'p', 'q', 'r', 's', 'y', 'z'}; // Display the sequences Console.WriteLine(\"Sequence 1 is: \"); foreach(var s1 in sequence1) { Console.WriteLine(s1); } Console.WriteLine(\"Sequence 2 is: \"); foreach(var s2 in sequence2) { Console.WriteLine(s2); } // Check the given sequences are equal or // not Using SequenceEqual function var result = sequence1.SequenceEqual(sequence2); Console.WriteLine(\"Given Sequences are equal: {0}\", result); }}", "e": 27283, "s": 26470, "text": null }, { "code": null, "e": 27372, "s": 27283, "text": "Sequence 1 is: \np\nq\nr\ns\ny\nz\nSequence 2 is: \np\nq\nr\ns\ny\nz\nGiven Sequences are equal: True\n" }, { "code": null, "e": 27383, "s": 27372, "text": "Example 2:" }, { "code": "// C# program to check the names of// the employee are equal or notusing System;using System.Linq;using System.Collections.Generic; // Employee detailspublic class Employee1 { public int emp_id1 { get; set; } public string emp_name1 { get; set; } public string emp_lang1 { get; set; }} // Employee detailspublic class Employee2 { public int emp_id2 { get; set; } public string emp_name2 { get; set; } public string emp_lang2 { get; set; }} public class GFG { // Main method static public void Main() { List<Employee1> emp1 = new List<Employee1>() { new Employee1() {emp_id1 = 209, emp_name1 = \"Anjita\", emp_lang1 = \"C#\"}, new Employee1() {emp_id1 = 210, emp_name1 = \"Soniya\", emp_lang1 = \"C\"}, new Employee1() {emp_id1 = 211, emp_name1 = \"Rohit\", emp_lang1 = \"Java\"}, }; List<Employee2> emp2 = new List<Employee2>() { new Employee2() {emp_id2 = 209, emp_name2 = \"Anjita\", emp_lang2 = \"Scala\"}, new Employee2() {emp_id2 = 210, emp_name2 = \"Soniya\", emp_lang2 = \"Python\"}, new Employee2() {emp_id2 = 211, emp_name2 = \"Rohit\", emp_lang2 = \"Ruby\"}, }; // Query to check the names of // the employee are equal or not // Using SequenceEqual method var res = emp1.Select(e => e.emp_name1).SequenceEqual(emp2.Select(e => e.emp_name2)); Console.WriteLine(res); }}", "e": 29216, "s": 27383, "text": null }, { "code": null, "e": 29222, "s": 29216, "text": "True\n" }, { "code": null, "e": 29234, "s": 29222, "text": "CSharp LINQ" }, { "code": null, "e": 29237, "s": 29234, "text": "C#" }, { "code": null, "e": 29335, "s": 29237, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29358, "s": 29335, "text": "Extension Method in C#" }, { "code": null, "e": 29386, "s": 29358, "text": "HashSet in C# with Examples" }, { "code": null, "e": 29403, "s": 29386, "text": "C# | Inheritance" }, { "code": null, "e": 29425, "s": 29403, "text": "Partial Classes in C#" }, { "code": null, "e": 29454, "s": 29425, "text": "C# | Generics - Introduction" }, { "code": null, "e": 29494, "s": 29454, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 29517, "s": 29494, "text": "Switch Statement in C#" }, { "code": null, "e": 29560, "s": 29517, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 29600, "s": 29560, "text": "Convert String to Character Array in C#" } ]
How to Find Hidden Web Directories with Dirsearch - GeeksforGeeks
28 Jul, 2021 Dirsearch tool is a Python language-based tool, which is command-line only. Dirsearch lights when it comes to recursive scanning, so for every directory it identifies, it will go back through and crawl the directory for some additional directories. Dirsearch tool is an advanced command-line tool designed to brute-force directories and files in web servers or web path scanners. As Dirsearch is an advanced tool, it allows hackers to perform a complex web directories discovery, with a customized wordlist, impressive performance, speed, high accuracy, advanced correction, and modern brute-force techniques with relevant outputs. Dirsearch perform Recursive brute forcingDirsearch perform Target enumeration from an IP rangeDirsearch perform Sub-directories brute forcingDirsearch is Easy and simple to useDirsearch is MultithreadingDirsearch has Support for every HTTP methodDirsearch has Quiet modeDirsearch has Debug mode Dirsearch perform Recursive brute forcing Dirsearch perform Target enumeration from an IP range Dirsearch perform Sub-directories brute forcing Dirsearch is Easy and simple to use Dirsearch is Multithreading Dirsearch has Support for every HTTP method Dirsearch has Quiet mode Dirsearch has Debug mode Note: Make Sure You have Python Installed on your System, as this is python-based tool. Step 1: Fire up your Kali Linux terminal and move to Desktop using the following command. cd Desktop Step 2: You are on Desktop now create a new directory called Dirsearch using the following command. In this directory, we will complete the installation of the Dirsearch tool. mkdir Dirsearch cd Dirsearch Step 3: Now you have to install the tool. You have to clone the tool from Github. git clone https://github.com/maurosoria/dirsearch.git Step 4: The tool has been downloaded successfully in the dirsearch directory. Now list out the contents of the tool by using the below command. ls Step 5: You can observe that there is a new directory created of the dirsearch tool that has been generated while we were installing the tool.Now move to that directory using the below command: cd dirsearch Step 6: Download the required packages for running the tool, use the following command. pip3 install -r requirements.txt Step 7: Now we are done with our installation, Use the below command to view the help (gives better understanding of tool) index of the tool. python3 dirsearch.py --help python3 dirsearch.py -u https://example.com Extensions (php,html,js): python3 dirsearch.py -e php,html,js -u https://example.com Using Wordlist: python3 dirsearch.py -e php,html,js -u https://example.com -w /usr/share/wordlists/dirb/common.txt Simple Recursive Scan: python3 dirsearch.py -e php,html,js -u https://geeksforgeeks.org -r Max Recursion Depth: python3 dirsearch.py -e php,html,js -u https://geeksforgeeks.org -r -R 3 Using Threads: python3 dirsearch.py -e php,htm,js,bak,zip,tgz,txt -u https://geeksforgeeks.org -t 30 Prefixes: python3 dirsearch.py -e php -u https://geeksforgeeks.org –prefixes .,admin,_,~ Suffixes: python3 dirsearch.py -e php -u https://geeksforgeeks.org –suffixes ~,/ Excluding Extensions: python3 dirsearch.py -e asp,aspx,htm,js -u https://geeksforgeeks.org -X php,jsp,jspx python3 dirsearch.py -e php,html,js -u https://geeksforgeeks.org -i 200,204,400,403 -x 500,502,429 python3 dirsearch.py -e php,html,js -u https://geeksforgeeks.org –subdirs admin/,folder/,/ python3 dirsearch.py -e php,html,js -u https://geeksforgeeks.org –proxy 127.0.0.1:8080 python3 dirsearch.py -e php -u https://geeksforgeeks.org -o report.txt Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. scp command in Linux with Examples Docker - COPY Instruction mv command in Linux with examples SED command in Linux | Set 2 chown command in Linux with Examples nohup Command in Linux with Examples Named Pipe or FIFO with example C program Thread functions in C/C++ uniq Command in LINUX with examples Start/Stop/Restart Services Using Systemctl in Linux
[ { "code": null, "e": 25651, "s": 25623, "text": "\n28 Jul, 2021" }, { "code": null, "e": 26284, "s": 25651, "text": "Dirsearch tool is a Python language-based tool, which is command-line only. Dirsearch lights when it comes to recursive scanning, so for every directory it identifies, it will go back through and crawl the directory for some additional directories. Dirsearch tool is an advanced command-line tool designed to brute-force directories and files in web servers or web path scanners. As Dirsearch is an advanced tool, it allows hackers to perform a complex web directories discovery, with a customized wordlist, impressive performance, speed, high accuracy, advanced correction, and modern brute-force techniques with relevant outputs." }, { "code": null, "e": 26579, "s": 26284, "text": "Dirsearch perform Recursive brute forcingDirsearch perform Target enumeration from an IP rangeDirsearch perform Sub-directories brute forcingDirsearch is Easy and simple to useDirsearch is MultithreadingDirsearch has Support for every HTTP methodDirsearch has Quiet modeDirsearch has Debug mode" }, { "code": null, "e": 26621, "s": 26579, "text": "Dirsearch perform Recursive brute forcing" }, { "code": null, "e": 26675, "s": 26621, "text": "Dirsearch perform Target enumeration from an IP range" }, { "code": null, "e": 26723, "s": 26675, "text": "Dirsearch perform Sub-directories brute forcing" }, { "code": null, "e": 26759, "s": 26723, "text": "Dirsearch is Easy and simple to use" }, { "code": null, "e": 26787, "s": 26759, "text": "Dirsearch is Multithreading" }, { "code": null, "e": 26831, "s": 26787, "text": "Dirsearch has Support for every HTTP method" }, { "code": null, "e": 26856, "s": 26831, "text": "Dirsearch has Quiet mode" }, { "code": null, "e": 26881, "s": 26856, "text": "Dirsearch has Debug mode" }, { "code": null, "e": 26969, "s": 26881, "text": "Note: Make Sure You have Python Installed on your System, as this is python-based tool." }, { "code": null, "e": 27059, "s": 26969, "text": "Step 1: Fire up your Kali Linux terminal and move to Desktop using the following command." }, { "code": null, "e": 27070, "s": 27059, "text": "cd Desktop" }, { "code": null, "e": 27247, "s": 27070, "text": "Step 2: You are on Desktop now create a new directory called Dirsearch using the following command. In this directory, we will complete the installation of the Dirsearch tool." }, { "code": null, "e": 27276, "s": 27247, "text": "mkdir Dirsearch\ncd Dirsearch" }, { "code": null, "e": 27358, "s": 27276, "text": "Step 3: Now you have to install the tool. You have to clone the tool from Github." }, { "code": null, "e": 27412, "s": 27358, "text": "git clone https://github.com/maurosoria/dirsearch.git" }, { "code": null, "e": 27556, "s": 27412, "text": "Step 4: The tool has been downloaded successfully in the dirsearch directory. Now list out the contents of the tool by using the below command." }, { "code": null, "e": 27559, "s": 27556, "text": "ls" }, { "code": null, "e": 27753, "s": 27559, "text": "Step 5: You can observe that there is a new directory created of the dirsearch tool that has been generated while we were installing the tool.Now move to that directory using the below command:" }, { "code": null, "e": 27766, "s": 27753, "text": "cd dirsearch" }, { "code": null, "e": 27854, "s": 27766, "text": "Step 6: Download the required packages for running the tool, use the following command." }, { "code": null, "e": 27887, "s": 27854, "text": "pip3 install -r requirements.txt" }, { "code": null, "e": 28029, "s": 27887, "text": "Step 7: Now we are done with our installation, Use the below command to view the help (gives better understanding of tool) index of the tool." }, { "code": null, "e": 28057, "s": 28029, "text": "python3 dirsearch.py --help" }, { "code": null, "e": 28101, "s": 28057, "text": "python3 dirsearch.py -u https://example.com" }, { "code": null, "e": 28127, "s": 28101, "text": "Extensions (php,html,js):" }, { "code": null, "e": 28186, "s": 28127, "text": "python3 dirsearch.py -e php,html,js -u https://example.com" }, { "code": null, "e": 28202, "s": 28186, "text": "Using Wordlist:" }, { "code": null, "e": 28301, "s": 28202, "text": "python3 dirsearch.py -e php,html,js -u https://example.com -w /usr/share/wordlists/dirb/common.txt" }, { "code": null, "e": 28324, "s": 28301, "text": "Simple Recursive Scan:" }, { "code": null, "e": 28392, "s": 28324, "text": "python3 dirsearch.py -e php,html,js -u https://geeksforgeeks.org -r" }, { "code": null, "e": 28413, "s": 28392, "text": "Max Recursion Depth:" }, { "code": null, "e": 28486, "s": 28413, "text": "python3 dirsearch.py -e php,html,js -u https://geeksforgeeks.org -r -R 3" }, { "code": null, "e": 28501, "s": 28486, "text": "Using Threads:" }, { "code": null, "e": 28587, "s": 28501, "text": "python3 dirsearch.py -e php,htm,js,bak,zip,tgz,txt -u https://geeksforgeeks.org -t 30" }, { "code": null, "e": 28597, "s": 28587, "text": "Prefixes:" }, { "code": null, "e": 28676, "s": 28597, "text": "python3 dirsearch.py -e php -u https://geeksforgeeks.org –prefixes .,admin,_,~" }, { "code": null, "e": 28686, "s": 28676, "text": "Suffixes:" }, { "code": null, "e": 28757, "s": 28686, "text": "python3 dirsearch.py -e php -u https://geeksforgeeks.org –suffixes ~,/" }, { "code": null, "e": 28779, "s": 28757, "text": "Excluding Extensions:" }, { "code": null, "e": 28864, "s": 28779, "text": "python3 dirsearch.py -e asp,aspx,htm,js -u https://geeksforgeeks.org -X php,jsp,jspx" }, { "code": null, "e": 28963, "s": 28864, "text": "python3 dirsearch.py -e php,html,js -u https://geeksforgeeks.org -i 200,204,400,403 -x 500,502,429" }, { "code": null, "e": 29054, "s": 28963, "text": "python3 dirsearch.py -e php,html,js -u https://geeksforgeeks.org –subdirs admin/,folder/,/" }, { "code": null, "e": 29141, "s": 29054, "text": "python3 dirsearch.py -e php,html,js -u https://geeksforgeeks.org –proxy 127.0.0.1:8080" }, { "code": null, "e": 29212, "s": 29141, "text": "python3 dirsearch.py -e php -u https://geeksforgeeks.org -o report.txt" }, { "code": null, "e": 29223, "s": 29212, "text": "Kali-Linux" }, { "code": null, "e": 29235, "s": 29223, "text": "Linux-Tools" }, { "code": null, "e": 29246, "s": 29235, "text": "Linux-Unix" }, { "code": null, "e": 29344, "s": 29246, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29379, "s": 29344, "text": "scp command in Linux with Examples" }, { "code": null, "e": 29405, "s": 29379, "text": "Docker - COPY Instruction" }, { "code": null, "e": 29439, "s": 29405, "text": "mv command in Linux with examples" }, { "code": null, "e": 29468, "s": 29439, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 29505, "s": 29468, "text": "chown command in Linux with Examples" }, { "code": null, "e": 29542, "s": 29505, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 29584, "s": 29542, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 29610, "s": 29584, "text": "Thread functions in C/C++" }, { "code": null, "e": 29646, "s": 29610, "text": "uniq Command in LINUX with examples" } ]
Python | Create simple animation for console-based application - GeeksforGeeks
17 Apr, 2019 As we know Python is a scripting language, and can be easily used to automate simple tasks. In this article, we will learn how to create a simple console-based animation, which can be used while developing a console based project as a utility. We will try to replicate the loading animation as shown below: We will be using following modules – sys module os module time module Below is the Python implementation: # importing the necessary packagesimport timeimport sysimport os # Function for implementing the loading animationdef load_animation(): # String to be displayed when the application is loading load_str = "starting your console application..." ls_len = len(load_str) # String for creating the rotating line animation = "|/-\\" anicount = 0 # used to keep the track of # the duration of animation counttime = 0 # pointer for travelling the loading string i = 0 while (counttime != 100): # used to change the animation speed # smaller the value, faster will be the animation time.sleep(0.075) # converting the string to list # as string is immutable load_str_list = list(load_str) # x->obtaining the ASCII code x = ord(load_str_list[i]) # y->for storing altered ASCII code y = 0 # if the character is "." or " ", keep it unaltered # switch uppercase to lowercase and vice-versa if x != 32 and x != 46: if x>90: y = x-32 else: y = x + 32 load_str_list[i]= chr(y) # for storing the resultant string res ='' for j in range(ls_len): res = res + load_str_list[j] # displaying the resultant string sys.stdout.write("\r"+res + animation[anicount]) sys.stdout.flush() # Assigning loading string # to the resultant string load_str = res anicount = (anicount + 1)% 4 i =(i + 1)% ls_len counttime = counttime + 1 # for windows OS if os.name =="nt": os.system("cls") # for linux / Mac OS else: os.system("clear") # Driver programif __name__ == '__main__': load_animation() # Your desired code continues from here # s = input("Enter your name: ") s ="David" sys.stdout.write("Hello "+str(s)+"\n") Output: python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25563, "s": 25535, "text": "\n17 Apr, 2019" }, { "code": null, "e": 25807, "s": 25563, "text": "As we know Python is a scripting language, and can be easily used to automate simple tasks. In this article, we will learn how to create a simple console-based animation, which can be used while developing a console based project as a utility." }, { "code": null, "e": 25870, "s": 25807, "text": "We will try to replicate the loading animation as shown below:" }, { "code": null, "e": 25907, "s": 25870, "text": "We will be using following modules –" }, { "code": null, "e": 25941, "s": 25907, "text": "sys module\nos module\ntime module\n" }, { "code": null, "e": 25978, "s": 25941, "text": " Below is the Python implementation:" }, { "code": "# importing the necessary packagesimport timeimport sysimport os # Function for implementing the loading animationdef load_animation(): # String to be displayed when the application is loading load_str = \"starting your console application...\" ls_len = len(load_str) # String for creating the rotating line animation = \"|/-\\\\\" anicount = 0 # used to keep the track of # the duration of animation counttime = 0 # pointer for travelling the loading string i = 0 while (counttime != 100): # used to change the animation speed # smaller the value, faster will be the animation time.sleep(0.075) # converting the string to list # as string is immutable load_str_list = list(load_str) # x->obtaining the ASCII code x = ord(load_str_list[i]) # y->for storing altered ASCII code y = 0 # if the character is \".\" or \" \", keep it unaltered # switch uppercase to lowercase and vice-versa if x != 32 and x != 46: if x>90: y = x-32 else: y = x + 32 load_str_list[i]= chr(y) # for storing the resultant string res ='' for j in range(ls_len): res = res + load_str_list[j] # displaying the resultant string sys.stdout.write(\"\\r\"+res + animation[anicount]) sys.stdout.flush() # Assigning loading string # to the resultant string load_str = res anicount = (anicount + 1)% 4 i =(i + 1)% ls_len counttime = counttime + 1 # for windows OS if os.name ==\"nt\": os.system(\"cls\") # for linux / Mac OS else: os.system(\"clear\") # Driver programif __name__ == '__main__': load_animation() # Your desired code continues from here # s = input(\"Enter your name: \") s =\"David\" sys.stdout.write(\"Hello \"+str(s)+\"\\n\")", "e": 28114, "s": 25978, "text": null }, { "code": null, "e": 28122, "s": 28114, "text": "Output:" }, { "code": null, "e": 28137, "s": 28122, "text": "python-utility" }, { "code": null, "e": 28144, "s": 28137, "text": "Python" }, { "code": null, "e": 28242, "s": 28144, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28274, "s": 28242, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28316, "s": 28274, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28358, "s": 28316, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28385, "s": 28358, "text": "Python Classes and Objects" }, { "code": null, "e": 28441, "s": 28385, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28480, "s": 28441, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28502, "s": 28480, "text": "Defaultdict in Python" }, { "code": null, "e": 28533, "s": 28502, "text": "Python | os.path.join() method" }, { "code": null, "e": 28562, "s": 28533, "text": "Create a directory in Python" } ]
Execute main() multiple times without using any other function or condition or recursion in Java - GeeksforGeeks
01 Apr, 2019 Given task is to execute main() multiple times without using any other function and without recursion() and without error. Given condition is that if executing main() n times then you can only call him (n-1) times. Solution: class Test { // static block static { main(new String[] { "Hello" }); } public static void main(String[] args) { System.out.println("Hii"); }} Hii Hii Explanation: Static block is executed even before the main() executed. Here first, main() get called by static block and then JVM(Java Virtual Machine) call the main(). So, main() is executed two times by calling only one time. java-basics main Interview Experiences Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience for SDE-1 (Off-Campus) Amazon AWS Interview Experience for SDE-1 Difference between ANN, CNN and RNN Amazon Interview Experience for SDE-1 (Off-Campus) 2022 Zoho Interview | Set 3 (Off-Campus) For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples Reverse a string in Java HashMap in Java with Examples
[ { "code": null, "e": 26273, "s": 26245, "text": "\n01 Apr, 2019" }, { "code": null, "e": 26488, "s": 26273, "text": "Given task is to execute main() multiple times without using any other function and without recursion() and without error. Given condition is that if executing main() n times then you can only call him (n-1) times." }, { "code": null, "e": 26498, "s": 26488, "text": "Solution:" }, { "code": "class Test { // static block static { main(new String[] { \"Hello\" }); } public static void main(String[] args) { System.out.println(\"Hii\"); }}", "e": 26678, "s": 26498, "text": null }, { "code": null, "e": 26687, "s": 26678, "text": "Hii\nHii\n" }, { "code": null, "e": 26915, "s": 26687, "text": "Explanation: Static block is executed even before the main() executed. Here first, main() get called by static block and then JVM(Java Virtual Machine) call the main(). So, main() is executed two times by calling only one time." }, { "code": null, "e": 26927, "s": 26915, "text": "java-basics" }, { "code": null, "e": 26932, "s": 26927, "text": "main" }, { "code": null, "e": 26954, "s": 26932, "text": "Interview Experiences" }, { "code": null, "e": 26959, "s": 26954, "text": "Java" }, { "code": null, "e": 26964, "s": 26959, "text": "Java" }, { "code": null, "e": 27062, "s": 26964, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27113, "s": 27062, "text": "Amazon Interview Experience for SDE-1 (Off-Campus)" }, { "code": null, "e": 27155, "s": 27113, "text": "Amazon AWS Interview Experience for SDE-1" }, { "code": null, "e": 27191, "s": 27155, "text": "Difference between ANN, CNN and RNN" }, { "code": null, "e": 27247, "s": 27191, "text": "Amazon Interview Experience for SDE-1 (Off-Campus) 2022" }, { "code": null, "e": 27283, "s": 27247, "text": "Zoho Interview | Set 3 (Off-Campus)" }, { "code": null, "e": 27305, "s": 27283, "text": "For-each loop in Java" }, { "code": null, "e": 27356, "s": 27305, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27392, "s": 27356, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 27417, "s": 27392, "text": "Reverse a string in Java" } ]
numpy.negative() in Python - GeeksforGeeks
28 Nov, 2018 numpy.negative() function is used when we want to compute the negative of array elements. It returns element-wise negative value of an array or negative value of a scalar. Syntax : numpy.negative(arr, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj], ufunc ‘negative’) Parameters :arr : [array_like or scalar] Input array.dtype : The type of the returned array. By default, the dtype of arr is used.out : [ndarray, optional] A location into which the result is stored. -> If provided, it must have a shape that the inputs broadcast to. -> If not provided or None, a freshly-allocated array is returned.where : [array_like, optional] Values of True indicate to calculate the ufunc at that position, values of False indicate to leave the value in the output alone.**kwargs : Allows to pass keyword variable length of argument to a function. Used when we want to handle named argument in a function. Return : [ndarray or scalar] Returned array or scalar = -(input arr or scalar ) Code #1 : Working # Python program explaining# numpy.negative() function import numpy as geekin_num = 10 print ("Input number : ", in_num) out_num = geek.negative(in_num) print ("negative of input number : ", out_num) Output : Input number : 10 negative of input number : -10 Code #2 : # Python program explaining# numpy.negative function import numpy as geek in_arr = geek.array([[2, -7, 5], [-6, 2, 0]]) print ("Input array : ", in_arr) out_arr = geek.negative(in_arr) print ("negative of array elements: ", out_arr) Output : Input array : [[ 2. 2. 2.] [ 2. 2. nan]] product of array elements: 32.0Input array : [[ 2 -7 5] [-6 2 0]] negative of array elements: [[-2 7 -5] [ 6 -2 0]] Python numpy-Mathematical Function Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n28 Nov, 2018" }, { "code": null, "e": 25709, "s": 25537, "text": "numpy.negative() function is used when we want to compute the negative of array elements. It returns element-wise negative value of an array or negative value of a scalar." }, { "code": null, "e": 25861, "s": 25709, "text": "Syntax : numpy.negative(arr, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj], ufunc ‘negative’)" }, { "code": null, "e": 26491, "s": 25861, "text": "Parameters :arr : [array_like or scalar] Input array.dtype : The type of the returned array. By default, the dtype of arr is used.out : [ndarray, optional] A location into which the result is stored. -> If provided, it must have a shape that the inputs broadcast to. -> If not provided or None, a freshly-allocated array is returned.where : [array_like, optional] Values of True indicate to calculate the ufunc at that position, values of False indicate to leave the value in the output alone.**kwargs : Allows to pass keyword variable length of argument to a function. Used when we want to handle named argument in a function." }, { "code": null, "e": 26571, "s": 26491, "text": "Return : [ndarray or scalar] Returned array or scalar = -(input arr or scalar )" }, { "code": null, "e": 26589, "s": 26571, "text": "Code #1 : Working" }, { "code": "# Python program explaining# numpy.negative() function import numpy as geekin_num = 10 print (\"Input number : \", in_num) out_num = geek.negative(in_num) print (\"negative of input number : \", out_num) ", "e": 26796, "s": 26589, "text": null }, { "code": null, "e": 26805, "s": 26796, "text": "Output :" }, { "code": null, "e": 26858, "s": 26805, "text": "Input number : 10\nnegative of input number : -10\n" }, { "code": null, "e": 26869, "s": 26858, "text": " Code #2 :" }, { "code": "# Python program explaining# numpy.negative function import numpy as geek in_arr = geek.array([[2, -7, 5], [-6, 2, 0]]) print (\"Input array : \", in_arr) out_arr = geek.negative(in_arr) print (\"negative of array elements: \", out_arr) ", "e": 27111, "s": 26869, "text": null }, { "code": null, "e": 27120, "s": 27111, "text": "Output :" }, { "code": null, "e": 27299, "s": 27120, "text": "Input array : [[ 2. 2. 2.]\n [ 2. 2. nan]]\nproduct of array elements: 32.0Input array : [[ 2 -7 5]\n [-6 2 0]]\nnegative of array elements: [[-2 7 -5]\n [ 6 -2 0]]\n" }, { "code": null, "e": 27334, "s": 27299, "text": "Python numpy-Mathematical Function" }, { "code": null, "e": 27347, "s": 27334, "text": "Python-numpy" }, { "code": null, "e": 27354, "s": 27347, "text": "Python" }, { "code": null, "e": 27452, "s": 27354, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27484, "s": 27452, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27526, "s": 27484, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27568, "s": 27526, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27595, "s": 27568, "text": "Python Classes and Objects" }, { "code": null, "e": 27651, "s": 27595, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27690, "s": 27651, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27712, "s": 27690, "text": "Defaultdict in Python" }, { "code": null, "e": 27743, "s": 27712, "text": "Python | os.path.join() method" }, { "code": null, "e": 27772, "s": 27743, "text": "Create a directory in Python" } ]
Levels in a File Management System - GeeksforGeeks
02 Mar, 2020 Prerequisite – File SystemThe management of files and the management of device are interlinked with each other. Given below is an hierarchy used to perform the required functions of an I/O system efficiently. The highest level module called Basic File System passes the information given to it to Logical File System, which in turn, notifies the Physical File System, that works with Device Manager. Each level of the hierarchy is implemented using structured and modular programming, and the information is passed from higher positioned module to lower positioned module. Through this, they perform required services and continue the communication down the chain. The lowest level int his chain communicates with the physical device and interacts with the Device Manager. Lets take an example- Example: Read record number 17 from File X into Y: X is the name of a direct access file previously opened for input and Y is the name of a data record previously defined within the program and occupying specific memory location. As the file X has already been opened, the file directory has already been searched to verify the existence of the file. Relevant information about the file X has been brought into the Operating System’s active file table, and this information includes the the size of the file, the address of it’s first physical record, it’s protection and access control information. This information is used by the Basic File System, which activates the Access Control Verification Module to verify if the user is permitted to perform this operation or not. If the user is permitted, then information and control is passed to Logical File System. If not permitted, the access is denied and the information and control are not passed. The information passed down to the Logical File System is used to convert the record number into it’s byte address using the formula: CBA = (RN - 1) * RL This result and information is passed down to the Physical File System, which computes the location where the desired record would physically reside. If there are more than one record in that block, it will compute the offset of the record within that block using the formula: block number = integers (byte address / physical block size) + address of first physical record offset = remainder (byte address / physical block size) This information is passed onto the Device Interface Module, which transforms the block number to the actual cylinder/surface/record combination needed to retrieve the information from the physical storage device. Once retrieved, device scheduling algorithm comes into play. The information is places in the buffer and control returns to the physical file system, which copies the information to the desired memory location. Once finished, the message “All clear” is passed to all the modules. Any other command is handled the same way. At the point when the control reaches the device handler, the allocation module is called as it is responsible for keeping track of unused memory areas. Note:At each level of the file management system, the process of examining whether the request is valid or not occurs. First occurs at the directory level when the file system checks if the file exists or not. Next occurs when the access control verification module checks whether access is allowed or not. Next occurs when the logical file system checks if the requested byte is within the file’s limits. In the last the verification occurs when the device interface module checks if the storage device exists or not. Thus, an operation of every user command needs the coordinated effort of every module of the file system. Technical Scripter 2019 GATE CS Operating Systems Technical Scripter Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Differences between IPv4 and IPv6 Preemptive and Non-Preemptive Scheduling Difference between Clustered and Non-clustered index Phases of a Compiler Introduction of Process Synchronization Banker's Algorithm in Operating System Program for FCFS CPU Scheduling | Set 1 Paging in Operating System Introduction of Deadlock in Operating System Program for Round Robin scheduling | Set 1
[ { "code": null, "e": 25627, "s": 25599, "text": "\n02 Mar, 2020" }, { "code": null, "e": 25836, "s": 25627, "text": "Prerequisite – File SystemThe management of files and the management of device are interlinked with each other. Given below is an hierarchy used to perform the required functions of an I/O system efficiently." }, { "code": null, "e": 26027, "s": 25836, "text": "The highest level module called Basic File System passes the information given to it to Logical File System, which in turn, notifies the Physical File System, that works with Device Manager." }, { "code": null, "e": 26400, "s": 26027, "text": "Each level of the hierarchy is implemented using structured and modular programming, and the information is passed from higher positioned module to lower positioned module. Through this, they perform required services and continue the communication down the chain. The lowest level int his chain communicates with the physical device and interacts with the Device Manager." }, { "code": null, "e": 26422, "s": 26400, "text": "Lets take an example-" }, { "code": null, "e": 26473, "s": 26422, "text": "Example: Read record number 17 from File X into Y:" }, { "code": null, "e": 26652, "s": 26473, "text": "X is the name of a direct access file previously opened for input and Y is the name of a data record previously defined within the program and occupying specific memory location." }, { "code": null, "e": 27022, "s": 26652, "text": "As the file X has already been opened, the file directory has already been searched to verify the existence of the file. Relevant information about the file X has been brought into the Operating System’s active file table, and this information includes the the size of the file, the address of it’s first physical record, it’s protection and access control information." }, { "code": null, "e": 27373, "s": 27022, "text": "This information is used by the Basic File System, which activates the Access Control Verification Module to verify if the user is permitted to perform this operation or not. If the user is permitted, then information and control is passed to Logical File System. If not permitted, the access is denied and the information and control are not passed." }, { "code": null, "e": 27507, "s": 27373, "text": "The information passed down to the Logical File System is used to convert the record number into it’s byte address using the formula:" }, { "code": null, "e": 27527, "s": 27507, "text": "CBA = (RN - 1) * RL" }, { "code": null, "e": 27804, "s": 27527, "text": "This result and information is passed down to the Physical File System, which computes the location where the desired record would physically reside. If there are more than one record in that block, it will compute the offset of the record within that block using the formula:" }, { "code": null, "e": 27978, "s": 27804, "text": "block number = integers (byte address / physical block size) \n + address of first physical record\n\noffset = remainder (byte address / physical block size)" }, { "code": null, "e": 28192, "s": 27978, "text": "This information is passed onto the Device Interface Module, which transforms the block number to the actual cylinder/surface/record combination needed to retrieve the information from the physical storage device." }, { "code": null, "e": 28403, "s": 28192, "text": "Once retrieved, device scheduling algorithm comes into play. The information is places in the buffer and control returns to the physical file system, which copies the information to the desired memory location." }, { "code": null, "e": 28668, "s": 28403, "text": "Once finished, the message “All clear” is passed to all the modules. Any other command is handled the same way. At the point when the control reaches the device handler, the allocation module is called as it is responsible for keeping track of unused memory areas." }, { "code": null, "e": 29187, "s": 28668, "text": "Note:At each level of the file management system, the process of examining whether the request is valid or not occurs. First occurs at the directory level when the file system checks if the file exists or not. Next occurs when the access control verification module checks whether access is allowed or not. Next occurs when the logical file system checks if the requested byte is within the file’s limits. In the last the verification occurs when the device interface module checks if the storage device exists or not." }, { "code": null, "e": 29293, "s": 29187, "text": "Thus, an operation of every user command needs the coordinated effort of every module of the file system." }, { "code": null, "e": 29317, "s": 29293, "text": "Technical Scripter 2019" }, { "code": null, "e": 29325, "s": 29317, "text": "GATE CS" }, { "code": null, "e": 29343, "s": 29325, "text": "Operating Systems" }, { "code": null, "e": 29362, "s": 29343, "text": "Technical Scripter" }, { "code": null, "e": 29380, "s": 29362, "text": "Operating Systems" }, { "code": null, "e": 29478, "s": 29380, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29512, "s": 29478, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 29553, "s": 29512, "text": "Preemptive and Non-Preemptive Scheduling" }, { "code": null, "e": 29606, "s": 29553, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 29627, "s": 29606, "text": "Phases of a Compiler" }, { "code": null, "e": 29667, "s": 29627, "text": "Introduction of Process Synchronization" }, { "code": null, "e": 29706, "s": 29667, "text": "Banker's Algorithm in Operating System" }, { "code": null, "e": 29746, "s": 29706, "text": "Program for FCFS CPU Scheduling | Set 1" }, { "code": null, "e": 29773, "s": 29746, "text": "Paging in Operating System" }, { "code": null, "e": 29818, "s": 29773, "text": "Introduction of Deadlock in Operating System" } ]
Sorting DataFrame in R using Dplyr - GeeksforGeeks
28 Jul, 2021 In this article, we will discuss about how to sort a dataframe in R programming language using Dplyr package. The package Dplyr in R programming language provides a function called arrange() function which is useful for sorting the dataframe. Syntax : arrange(.data, ...) The methods given below show how this function can be used in various ways to sort a dataframe. Sorting in ascending order is the default sorting order in arrange() function. The attribute to sort by should be given as an argument to this function. Example: Sorting the dataframe in ascending order R # Installing the loading the packageinstall.packages("dplyr") library(dplyr) # Creating dataframegfg = data.frame(Customers = c("Roohi", "James", "Satish", "Heera", "Sehnaaz", "Joe","Raj", "Simran", "Priya","Tejaswi"), Product = c("Product A", "Product B", "Product C", "Product A", "Product D", "Product B", "Product D", "Product C", "Product D", "Product A"), Salary = c(514.65, 354.99, 345.44, 989.56, 767.50, 576.90, 878.67, 904.56,123.45, 765.78) ) gfg # Sorting the dataframe in ascending orderarrange(gfg, Salary) Output : For sorting our dataframe in descending order, we will use desc() function along with the arrange() function. We will also use % operator for comparison of the dataframe column which we are taking for sorting purpose. Example: Sorting the dataframe in descending order R library(dplyr) # Creating dataframegfg = data.frame(Customers = c("Roohi", "James", "Satish", "Heera", "Sehnaaz", "Joe", "Raj", "Simran", "Priya", "Tejaswi"), Product = c("Product A", "Product B", "Product C", "Product A", "Product D", "Product B", "Product D", "Product C", "Product D", "Product A"), Salary = c(514.65, 354.99, 345.44, 989.56, 767.50, 576.90, 878.67, 904.56,123.45, 765.78)) # Sorting the dataframe in descending # ordergfg %>% arrange(desc(Salary)) Output : We will now sort our dataframe using multiple variables using the arrange() function. The attributes should be given to the function separated by a column. For example, in the given example the dataframe is sorted by salary column in descending order and product column in ascending order. We will use the % operator for comparing data to be sorted in descending order. Example: Sorting the dataframe using multiple variables R library(dplyr) # Creating dataframegfg = data.frame(Customers = c("Roohi", "James", "Satish", "Heera", "Sehnaaz", "Joe", "Raj", "Simran", "Priya", "Tejaswi"), Product = c("Product A", "Product B", "Product C", "Product A", "Product D", "Product B", "Product D", "Product C", "Product D", "Product A"), Salary = c(514.65, 354.99, 345.44, 989.56, 767.50, 576.90, 878.67, 904.56,123.45, 765.78)) # Sorting the dataframe using # multiple variablesgfg %>% arrange(Product, desc(Salary)) Output : Picked R Dplyr R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to import an Excel File into R ? Time Series Analysis in R R - if statement How to filter R dataframe by multiple conditions?
[ { "code": null, "e": 26487, "s": 26459, "text": "\n28 Jul, 2021" }, { "code": null, "e": 26730, "s": 26487, "text": "In this article, we will discuss about how to sort a dataframe in R programming language using Dplyr package. The package Dplyr in R programming language provides a function called arrange() function which is useful for sorting the dataframe." }, { "code": null, "e": 26740, "s": 26730, "text": "Syntax : " }, { "code": null, "e": 26760, "s": 26740, "text": "arrange(.data, ...)" }, { "code": null, "e": 26856, "s": 26760, "text": "The methods given below show how this function can be used in various ways to sort a dataframe." }, { "code": null, "e": 27009, "s": 26856, "text": "Sorting in ascending order is the default sorting order in arrange() function. The attribute to sort by should be given as an argument to this function." }, { "code": null, "e": 27059, "s": 27009, "text": "Example: Sorting the dataframe in ascending order" }, { "code": null, "e": 27061, "s": 27059, "text": "R" }, { "code": "# Installing the loading the packageinstall.packages(\"dplyr\") library(dplyr) # Creating dataframegfg = data.frame(Customers = c(\"Roohi\", \"James\", \"Satish\", \"Heera\", \"Sehnaaz\", \"Joe\",\"Raj\", \"Simran\", \"Priya\",\"Tejaswi\"), Product = c(\"Product A\", \"Product B\", \"Product C\", \"Product A\", \"Product D\", \"Product B\", \"Product D\", \"Product C\", \"Product D\", \"Product A\"), Salary = c(514.65, 354.99, 345.44, 989.56, 767.50, 576.90, 878.67, 904.56,123.45, 765.78) ) gfg # Sorting the dataframe in ascending orderarrange(gfg, Salary)", "e": 27860, "s": 27061, "text": null }, { "code": null, "e": 27869, "s": 27860, "text": "Output :" }, { "code": null, "e": 28087, "s": 27869, "text": "For sorting our dataframe in descending order, we will use desc() function along with the arrange() function. We will also use % operator for comparison of the dataframe column which we are taking for sorting purpose." }, { "code": null, "e": 28138, "s": 28087, "text": "Example: Sorting the dataframe in descending order" }, { "code": null, "e": 28140, "s": 28138, "text": "R" }, { "code": "library(dplyr) # Creating dataframegfg = data.frame(Customers = c(\"Roohi\", \"James\", \"Satish\", \"Heera\", \"Sehnaaz\", \"Joe\", \"Raj\", \"Simran\", \"Priya\", \"Tejaswi\"), Product = c(\"Product A\", \"Product B\", \"Product C\", \"Product A\", \"Product D\", \"Product B\", \"Product D\", \"Product C\", \"Product D\", \"Product A\"), Salary = c(514.65, 354.99, 345.44, 989.56, 767.50, 576.90, 878.67, 904.56,123.45, 765.78)) # Sorting the dataframe in descending # ordergfg %>% arrange(desc(Salary))", "e": 28868, "s": 28140, "text": null }, { "code": null, "e": 28877, "s": 28868, "text": "Output :" }, { "code": null, "e": 29247, "s": 28877, "text": "We will now sort our dataframe using multiple variables using the arrange() function. The attributes should be given to the function separated by a column. For example, in the given example the dataframe is sorted by salary column in descending order and product column in ascending order. We will use the % operator for comparing data to be sorted in descending order." }, { "code": null, "e": 29303, "s": 29247, "text": "Example: Sorting the dataframe using multiple variables" }, { "code": null, "e": 29305, "s": 29303, "text": "R" }, { "code": "library(dplyr) # Creating dataframegfg = data.frame(Customers = c(\"Roohi\", \"James\", \"Satish\", \"Heera\", \"Sehnaaz\", \"Joe\", \"Raj\", \"Simran\", \"Priya\", \"Tejaswi\"), Product = c(\"Product A\", \"Product B\", \"Product C\", \"Product A\", \"Product D\", \"Product B\", \"Product D\", \"Product C\", \"Product D\", \"Product A\"), Salary = c(514.65, 354.99, 345.44, 989.56, 767.50, 576.90, 878.67, 904.56,123.45, 765.78)) # Sorting the dataframe using # multiple variablesgfg %>% arrange(Product, desc(Salary))", "e": 30048, "s": 29305, "text": null }, { "code": null, "e": 30057, "s": 30048, "text": "Output :" }, { "code": null, "e": 30064, "s": 30057, "text": "Picked" }, { "code": null, "e": 30072, "s": 30064, "text": "R Dplyr" }, { "code": null, "e": 30083, "s": 30072, "text": "R Language" }, { "code": null, "e": 30181, "s": 30083, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30233, "s": 30181, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 30268, "s": 30233, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 30306, "s": 30268, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 30364, "s": 30306, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 30407, "s": 30364, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 30456, "s": 30407, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 30493, "s": 30456, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 30519, "s": 30493, "text": "Time Series Analysis in R" }, { "code": null, "e": 30536, "s": 30519, "text": "R - if statement" } ]
Implement Interface using Abstract Class in Java - GeeksforGeeks
09 Feb, 2021 Interface contains only abstract methods that can’t be instantiated and it is declared by keyword interface. A class that is declared with the abstract keyword is known as an abstract class in Java. This is a class that usually contains at least one abstract method which can’t be instantiated and It is also possible for the class to have no methods at all. The instance of an abstract class can’t be created. Now as all methods in an interface are abstract methods therefore we can implement it using Abstract Class. 1. Let’s create an Interface at first: Java // creating an interface named GFGinterface GFG { void learnCoding(); void learnProgrammingLanguage(); void contribute();} Here the three non-implemented methods are the abstract methods 2. Now let’s implement the interface in an Abstract class named Student: Java // creating an abstract class named Student which is// implementing the interface,GFGabstract class Student implements GFG { // Overriding two methods of the interfacem,GFG @Override public void learnCoding() { System.out.println( "Let's make coding a habit with GFG"); } @Override public void learnProgrammingLanguage() { System.out.println( "Let's master all fundamentals of java with the help of GFG"); }} Here we have overridden two abstract methods of the interface GFG. 3. Now let’s create a class GEEK which extends the abstract class, Student: As previously mentioned, we can’t create an instance of our abstract class therefore we need to make a non-abstract class. Java // creating an non-abstract class// GEEK which is extending Studentclass GEEK extends Student { // overriding the remaining method of the interface,GFG @Override public void contribute() { System.out.println( "Now let's help others by contributing in GFG"); }} Here we have overridden the remaining method of the interface GFG. Below is the overall implementation of the problem statement: Java // Implemention of Interface using Abstract Class in Java // Interface GFGinterface GFG { void learnCoding(); void learnProgrammingLanguage(); void contribute();} // Abstract class Student implementing from GFG interfaceabstract class Student implements GFG { // Overriding the methods @Override public void learnCoding() { System.out.println( "Let's make coding a habit with GFG"); } @Override public void learnProgrammingLanguage() { System.out.println( "Let's master all fundamentals of java with the help of GFG"); }} // Extend the GEEK class by Student abstract classclass GEEK extends Student { @Override public void contribute() { System.out.println( "Now let's help others by contributing in GFG"); }} // Driver codepublic class Main { public static void main(String[] args) { // New GEEK object is created GEEK gfgStudent = new GEEK(); // Calls to the multiple functions gfgStudent.learnCoding(); gfgStudent.learnProgrammingLanguage(); gfgStudent.contribute(); }} Output: Let's make coding a habit with GFG Let's master all fundamentals of java with the help of GFG Now let's help others by contributing in GFG Java-Abstract Class and Interface java-interfaces Picked Technical Scripter 2020 Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Internal Working of HashMap in Java Comparator Interface in Java with Examples Strings in Java
[ { "code": null, "e": 25251, "s": 25223, "text": "\n09 Feb, 2021" }, { "code": null, "e": 25662, "s": 25251, "text": "Interface contains only abstract methods that can’t be instantiated and it is declared by keyword interface. A class that is declared with the abstract keyword is known as an abstract class in Java. This is a class that usually contains at least one abstract method which can’t be instantiated and It is also possible for the class to have no methods at all. The instance of an abstract class can’t be created." }, { "code": null, "e": 25770, "s": 25662, "text": "Now as all methods in an interface are abstract methods therefore we can implement it using Abstract Class." }, { "code": null, "e": 25809, "s": 25770, "text": "1. Let’s create an Interface at first:" }, { "code": null, "e": 25814, "s": 25809, "text": "Java" }, { "code": "// creating an interface named GFGinterface GFG { void learnCoding(); void learnProgrammingLanguage(); void contribute();}", "e": 25946, "s": 25814, "text": null }, { "code": null, "e": 26011, "s": 25946, "text": "Here the three non-implemented methods are the abstract methods" }, { "code": null, "e": 26084, "s": 26011, "text": "2. Now let’s implement the interface in an Abstract class named Student:" }, { "code": null, "e": 26089, "s": 26084, "text": "Java" }, { "code": "// creating an abstract class named Student which is// implementing the interface,GFGabstract class Student implements GFG { // Overriding two methods of the interfacem,GFG @Override public void learnCoding() { System.out.println( \"Let's make coding a habit with GFG\"); } @Override public void learnProgrammingLanguage() { System.out.println( \"Let's master all fundamentals of java with the help of GFG\"); }}", "e": 26559, "s": 26089, "text": null }, { "code": null, "e": 26627, "s": 26559, "text": "Here we have overridden two abstract methods of the interface GFG." }, { "code": null, "e": 26703, "s": 26627, "text": "3. Now let’s create a class GEEK which extends the abstract class, Student:" }, { "code": null, "e": 26826, "s": 26703, "text": "As previously mentioned, we can’t create an instance of our abstract class therefore we need to make a non-abstract class." }, { "code": null, "e": 26831, "s": 26826, "text": "Java" }, { "code": "// creating an non-abstract class// GEEK which is extending Studentclass GEEK extends Student { // overriding the remaining method of the interface,GFG @Override public void contribute() { System.out.println( \"Now let's help others by contributing in GFG\"); }}", "e": 27126, "s": 26831, "text": null }, { "code": null, "e": 27193, "s": 27126, "text": "Here we have overridden the remaining method of the interface GFG." }, { "code": null, "e": 27255, "s": 27193, "text": "Below is the overall implementation of the problem statement:" }, { "code": null, "e": 27260, "s": 27255, "text": "Java" }, { "code": "// Implemention of Interface using Abstract Class in Java // Interface GFGinterface GFG { void learnCoding(); void learnProgrammingLanguage(); void contribute();} // Abstract class Student implementing from GFG interfaceabstract class Student implements GFG { // Overriding the methods @Override public void learnCoding() { System.out.println( \"Let's make coding a habit with GFG\"); } @Override public void learnProgrammingLanguage() { System.out.println( \"Let's master all fundamentals of java with the help of GFG\"); }} // Extend the GEEK class by Student abstract classclass GEEK extends Student { @Override public void contribute() { System.out.println( \"Now let's help others by contributing in GFG\"); }} // Driver codepublic class Main { public static void main(String[] args) { // New GEEK object is created GEEK gfgStudent = new GEEK(); // Calls to the multiple functions gfgStudent.learnCoding(); gfgStudent.learnProgrammingLanguage(); gfgStudent.contribute(); }}", "e": 28385, "s": 27260, "text": null }, { "code": null, "e": 28393, "s": 28385, "text": "Output:" }, { "code": null, "e": 28532, "s": 28393, "text": "Let's make coding a habit with GFG\nLet's master all fundamentals of java with the help of GFG\nNow let's help others by contributing in GFG" }, { "code": null, "e": 28566, "s": 28532, "text": "Java-Abstract Class and Interface" }, { "code": null, "e": 28582, "s": 28566, "text": "java-interfaces" }, { "code": null, "e": 28589, "s": 28582, "text": "Picked" }, { "code": null, "e": 28613, "s": 28589, "text": "Technical Scripter 2020" }, { "code": null, "e": 28618, "s": 28613, "text": "Java" }, { "code": null, "e": 28637, "s": 28618, "text": "Technical Scripter" }, { "code": null, "e": 28642, "s": 28637, "text": "Java" }, { "code": null, "e": 28740, "s": 28642, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28755, "s": 28740, "text": "Stream In Java" }, { "code": null, "e": 28776, "s": 28755, "text": "Constructors in Java" }, { "code": null, "e": 28795, "s": 28776, "text": "Exceptions in Java" }, { "code": null, "e": 28825, "s": 28795, "text": "Functional Interfaces in Java" }, { "code": null, "e": 28871, "s": 28825, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28888, "s": 28871, "text": "Generics in Java" }, { "code": null, "e": 28909, "s": 28888, "text": "Introduction to Java" }, { "code": null, "e": 28945, "s": 28909, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 28988, "s": 28945, "text": "Comparator Interface in Java with Examples" } ]
Shutil Module in Python - GeeksforGeeks
07 Oct, 2021 Shutil module offers high-level operation on a file like a copy, create, and remote operation on the file. It comes under Python’s standard utility modules. This module helps in automating the process of copying and removal of files and directories. In this article, we will learn this module. shutil.copy() method in Python is used to copy the content of the source file to the destination file or directory. It also preserves the file’s permission mode but other metadata of the file like the file’s creation and modification times is not preserved.The source must represent a file but the destination can be a file or a directory. If the destination is a directory then the file will be copied into the destination using the base filename from the source. Also, the destination must be writable. If the destination is a file and already exists then it will be replaced with the source file otherwise a new file will be created. Syntax: shutil.copy(source, destination, *, follow_symlinks = True) Parameter: source: A string representing the path of the source file. destination: A string representing the path of the destination file or directory. follow_symlinks (optional) : The default value of this parameter is True. If it is False and source represents a symbolic link then destination will be created as a symbolic link. Return Type: This method returns a string which represents the path of newly created file. Example 1: Python3 # Python program to explain shutil.copy() method # importing shutil module import shutil source = "path/main.py"destination ="path/main2.py" # Copy the content of # source to destination dest = shutil.copy(source, destination) # Print path of newly # created file print("Destination path:", dest) Output: Destination path: path/main2.py Example 2: If the destination is a directory. Python3 # importing shutil module import shutil # Source path source = "path/main.py" # Destination path destination = "path/gfg/" # Copy the content of # source to destination dest = shutil.copy(source, destination) # Print path of newly # created file print("Destination path:", dest) Output: path/gfg/main.py shutil.copy2() method in Python is used to copy the content of the source file to the destination file or directory. This method is identical to shutil.copy() method but it also tries to preserve the file’s metadata. Syntax: shutil.copy2(source, destination, *, follow_symlinks = True) Parameter: source: A string representing the path of the source file. destination: A string representing the path of the destination file or directory. follow_symlinks (optional) : The default value of this parameter is True. If it is False and source represents a symbolic link then it attempts to copy all metadata from the source symbolic link to the newly-created destination symbolic link. This functionality is platform dependent. Return Type: This method returns a string which represents the path of newly created file. Python3 # Python program to explain shutil.copy2() method # importing os module import os # importing shutil module import shutil # path path = 'csv/' # List files and directories # in '/home/User/Documents' print("Before copying file:") print(os.listdir(path)) # Source path source = "csv/main.py" # Print the metadeta # of source file metadata = os.stat(source) print("Metadata:", metadata, "\n") # Destination path destination = "csv/gfg/check.txt" # Copy the content of # source to destination dest = shutil.copy2(source, destination) # List files and directories # in "/home / User / Documents" print("After copying file:") print(os.listdir(path)) # Print the metadata # of the destination file matadata = os.stat(destination) print("Metadata:", metadata) # Print path of newly # created file print("Destination path:", dest) Output: Before copying file: [‘archive (2)’, ‘c.jpg’, ‘c.PNG’, ‘Capture.PNG’, ‘cc.jpg’, ‘check.zip’, ‘cv.csv’, ‘d.png’, ‘Done! Terms And Conditions Generator – The Fastest Free Terms and Conditions Generator!.pdf’, ‘file1.csv’, ‘gfg’, ‘haarcascade_frontalface_alt2.xml’, ‘log_transformed.jpg’, ‘main.py’, ‘nba.csv’, ‘new_gfg.png’, ‘r.gif’, ‘Result -_ Terms and Conditions are Ready!.pdf’, ‘rockyou.txt’, ‘sample.txt’] Metadata: os.stat_result(st_mode=33206, st_ino=2251799814202896, st_dev=1689971230, st_nlink=1, st_uid=0, st_gid=0, st_size=1916, st_atime=1612953710, st_mtime=1612613202, st_ctime=1612522940) After copying file: [‘archive (2)’, ‘c.jpg’, ‘c.PNG’, ‘Capture.PNG’, ‘cc.jpg’, ‘check.zip’, ‘cv.csv’, ‘d.png’, ‘Done! Terms And Conditions Generator – The Fastest Free Terms and Conditions Generator!.pdf’, ‘file1.csv’, ‘gfg’, ‘haarcascade_frontalface_alt2.xml’, ‘log_transformed.jpg’, ‘main.py’, ‘nba.csv’, ‘new_gfg.png’, ‘r.gif’, ‘Result -_ Terms and Conditions are Ready!.pdf’, ‘rockyou.txt’, ‘sample.txt’] Metadata: os.stat_result(st_mode=33206, st_ino=2251799814202896, st_dev=1689971230, st_nlink=1, st_uid=0, st_gid=0, st_size=1916, st_atime=1612953710, st_mtime=1612613202, st_ctime=1612522940) Destination path: csv/gfg/check.txt Example 2: If the destination is a directory Python3 # Python program to explain shutil.copy2() method # importing os module import os # importing shutil module import shutil # Source path source = "csv/main.py" # Destination path destination = "csv/gfg/" # Copy the content of # source to destination dest = shutil.copy2(source, destination) # List files and directories # in "/home / User / Desktop" print("After copying file:") print(os.listdir(destination)) # Print path of newly # created file print("Destination path:", dest) Output: After copying file: [‘cc.jpg’, ‘check.txt’, ‘log_transformed.jpg’, ‘main.py’, ‘main2.py’] Destination path: csv/gfg/main.py shutil.copyfile() method in Python is used to copy the content of the source file to the destination file. The metadata of the file is not copied. Source and destination must represent a file and destination must be writable. If the destination already exists then it will be replaced with the source file otherwise a new file will be created. If source and destination represent the same file then SameFileError exception will be raised. Syntax: shutil.copyfile(source, destination, *, follow_symlinks = True) Parameter: source: A string representing the path of the source file. destination: A string representing the path of the destination file. follow_symlinks (optional) : The default value of this parameter is True. If False and source represents a symbolic link then a new symbolic link will be created instead of copying the file. Return Type: This method returns a string which represents the path of newly created file. Python3 # Python program to explain shutil.copyfile() method # importing shutil module import shutil # Source path source = "csv/main.py" # Destination path destination = "csv/gfg/main_2.py" dest = shutil.copyfile(source, destination) print("Destination path:", dest) Output: Destination path: csv/gfg/main_2.py shutil.copytree() method recursively copies an entire directory tree rooted at source (src) to the destination directory. The destination directory, named by (dst) must not already exist. It will be created during copying. Syntax: shutil.copytree(src, dst, symlinks = False, ignore = None, copy_function = copy2, igonre_dangling_symlinks = False) Parameters:src: A string representing the path of the source directory.dest: A string representing the path of the destination.symlinks (optional) : This parameter accepts True or False, depending on which the metadata of the original links or linked links will be copied to the new tree.ignore (optional) : If ignore is given, it must be a callable that will receive as its arguments the directory being visited by copytree(), and a list of its contents, as returned by os.listdir().copy_function (optional): The default value of this parameter is copy2. We can use other copy function like copy() for this parameter.igonre_dangling_symlinks (optional) : This parameter value when set to True is used to put a silence on the exception raised if the file pointed by the symlink doesn’t exist. Return Value: This method returns a string which represents the path of newly created directory. Python3 # Python program to explain shutil.copytree() method # importing os module import os # importing shutil module import shutil # path path = 'C:/Users/ksaty/csv/gfg' print("Before copying file:") print(os.listdir(path)) # Source path src = 'C:/Users/ksaty/csv/gfg' # Destination path dest = 'C:/Users/ksaty/csv/gfg/dest' # Copy the content of # source to destination destination = shutil.copytree(src, dest) print("After copying file:") print(os.listdir(path)) # Print path of newly # created file print("Destination path:", destination) Output: Before copying file: [‘cc.jpg’, ‘check.txt’, ‘log_transformed.jpg’, ‘main.py’, ‘main2.py’, ‘main_2.py’] After copying file: [‘cc.jpg’, ‘check.txt’, ‘dest’, ‘log_transformed.jpg’, ‘main.py’, ‘main2.py’, ‘main_2.py’] Destination path: C:/Users/ksaty/csv/gfg/dest shutil.rmtree() is used to delete an entire directory tree, the path must point to a directory (but not a symbolic link to a directory). Syntax: shutil.rmtree(path, ignore_errors=False, onerror=None) Parameters:path: A path-like object representing a file path. A path-like object is either a string or bytes object representing a path.ignore_errors: If ignore_errors is true, errors resulting from failed removals will be ignored.oneerror: If ignore_errors is false or omitted, such errors are handled by calling a handler specified by onerror. Python3 # Python program to demonstrate # shutil.rmtree() import shutil import os # location location = "csv/gfg/" # directory dir = "dest" # path path = os.path.join(location, dir) # removing directory shutil.rmtree(path) shutil.which() method tells the path to an executable application that would be run if the given cmd was called. This method can be used to find a file on a computer which is present on the PATH. Syntax: shutil.which(cmd, mode = os.F_OK | os.X_OK, path = None)Parameters:cmd: A string representing the file.mode: This parameter specifies mode by which method should execute. os.F_OK tests existence of the path and os.X_OK Checks if path can be executed or we can say mode determines if the file exists and executable.path: This parameter specifies the path to be used, if no path is specified then the results of os.environ() are usedReturn Value: This method returns the path to an executable application Python3 # importing shutil module import shutil # file search cmd = 'anaconda' # Using shutil.which() method locate = shutil.which(cmd) # Print result print(locate) Output: D:\Installation_bulk\Scripts\anaconda.EXE python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n07 Oct, 2021" }, { "code": null, "e": 25831, "s": 25537, "text": "Shutil module offers high-level operation on a file like a copy, create, and remote operation on the file. It comes under Python’s standard utility modules. This module helps in automating the process of copying and removal of files and directories. In this article, we will learn this module." }, { "code": null, "e": 26468, "s": 25831, "text": "shutil.copy() method in Python is used to copy the content of the source file to the destination file or directory. It also preserves the file’s permission mode but other metadata of the file like the file’s creation and modification times is not preserved.The source must represent a file but the destination can be a file or a directory. If the destination is a directory then the file will be copied into the destination using the base filename from the source. Also, the destination must be writable. If the destination is a file and already exists then it will be replaced with the source file otherwise a new file will be created." }, { "code": null, "e": 26536, "s": 26468, "text": "Syntax: shutil.copy(source, destination, *, follow_symlinks = True)" }, { "code": null, "e": 26547, "s": 26536, "text": "Parameter:" }, { "code": null, "e": 26606, "s": 26547, "text": "source: A string representing the path of the source file." }, { "code": null, "e": 26688, "s": 26606, "text": "destination: A string representing the path of the destination file or directory." }, { "code": null, "e": 26868, "s": 26688, "text": "follow_symlinks (optional) : The default value of this parameter is True. If it is False and source represents a symbolic link then destination will be created as a symbolic link." }, { "code": null, "e": 26959, "s": 26868, "text": "Return Type: This method returns a string which represents the path of newly created file." }, { "code": null, "e": 26970, "s": 26959, "text": "Example 1:" }, { "code": null, "e": 26978, "s": 26970, "text": "Python3" }, { "code": "# Python program to explain shutil.copy() method # importing shutil module import shutil source = \"path/main.py\"destination =\"path/main2.py\" # Copy the content of # source to destination dest = shutil.copy(source, destination) # Print path of newly # created file print(\"Destination path:\", dest) ", "e": 27283, "s": 26978, "text": null }, { "code": null, "e": 27291, "s": 27283, "text": "Output:" }, { "code": null, "e": 27323, "s": 27291, "text": "Destination path: path/main2.py" }, { "code": null, "e": 27369, "s": 27323, "text": "Example 2: If the destination is a directory." }, { "code": null, "e": 27377, "s": 27369, "text": "Python3" }, { "code": "# importing shutil module import shutil # Source path source = \"path/main.py\" # Destination path destination = \"path/gfg/\" # Copy the content of # source to destination dest = shutil.copy(source, destination) # Print path of newly # created file print(\"Destination path:\", dest) ", "e": 27675, "s": 27377, "text": null }, { "code": null, "e": 27683, "s": 27675, "text": "Output:" }, { "code": null, "e": 27700, "s": 27683, "text": "path/gfg/main.py" }, { "code": null, "e": 27917, "s": 27700, "text": "shutil.copy2() method in Python is used to copy the content of the source file to the destination file or directory. This method is identical to shutil.copy() method but it also tries to preserve the file’s metadata." }, { "code": null, "e": 27986, "s": 27917, "text": "Syntax: shutil.copy2(source, destination, *, follow_symlinks = True)" }, { "code": null, "e": 27997, "s": 27986, "text": "Parameter:" }, { "code": null, "e": 28056, "s": 27997, "text": "source: A string representing the path of the source file." }, { "code": null, "e": 28138, "s": 28056, "text": "destination: A string representing the path of the destination file or directory." }, { "code": null, "e": 28423, "s": 28138, "text": "follow_symlinks (optional) : The default value of this parameter is True. If it is False and source represents a symbolic link then it attempts to copy all metadata from the source symbolic link to the newly-created destination symbolic link. This functionality is platform dependent." }, { "code": null, "e": 28514, "s": 28423, "text": "Return Type: This method returns a string which represents the path of newly created file." }, { "code": null, "e": 28522, "s": 28514, "text": "Python3" }, { "code": "# Python program to explain shutil.copy2() method # importing os module import os # importing shutil module import shutil # path path = 'csv/' # List files and directories # in '/home/User/Documents' print(\"Before copying file:\") print(os.listdir(path)) # Source path source = \"csv/main.py\" # Print the metadeta # of source file metadata = os.stat(source) print(\"Metadata:\", metadata, \"\\n\") # Destination path destination = \"csv/gfg/check.txt\" # Copy the content of # source to destination dest = shutil.copy2(source, destination) # List files and directories # in \"/home / User / Documents\" print(\"After copying file:\") print(os.listdir(path)) # Print the metadata # of the destination file matadata = os.stat(destination) print(\"Metadata:\", metadata) # Print path of newly # created file print(\"Destination path:\", dest) ", "e": 29371, "s": 28522, "text": null }, { "code": null, "e": 29379, "s": 29371, "text": "Output:" }, { "code": null, "e": 29400, "s": 29379, "text": "Before copying file:" }, { "code": null, "e": 29789, "s": 29400, "text": "[‘archive (2)’, ‘c.jpg’, ‘c.PNG’, ‘Capture.PNG’, ‘cc.jpg’, ‘check.zip’, ‘cv.csv’, ‘d.png’, ‘Done! Terms And Conditions Generator – The Fastest Free Terms and Conditions Generator!.pdf’, ‘file1.csv’, ‘gfg’, ‘haarcascade_frontalface_alt2.xml’, ‘log_transformed.jpg’, ‘main.py’, ‘nba.csv’, ‘new_gfg.png’, ‘r.gif’, ‘Result -_ Terms and Conditions are Ready!.pdf’, ‘rockyou.txt’, ‘sample.txt’]" }, { "code": null, "e": 29983, "s": 29789, "text": "Metadata: os.stat_result(st_mode=33206, st_ino=2251799814202896, st_dev=1689971230, st_nlink=1, st_uid=0, st_gid=0, st_size=1916, st_atime=1612953710, st_mtime=1612613202, st_ctime=1612522940) " }, { "code": null, "e": 30003, "s": 29983, "text": "After copying file:" }, { "code": null, "e": 30392, "s": 30003, "text": "[‘archive (2)’, ‘c.jpg’, ‘c.PNG’, ‘Capture.PNG’, ‘cc.jpg’, ‘check.zip’, ‘cv.csv’, ‘d.png’, ‘Done! Terms And Conditions Generator – The Fastest Free Terms and Conditions Generator!.pdf’, ‘file1.csv’, ‘gfg’, ‘haarcascade_frontalface_alt2.xml’, ‘log_transformed.jpg’, ‘main.py’, ‘nba.csv’, ‘new_gfg.png’, ‘r.gif’, ‘Result -_ Terms and Conditions are Ready!.pdf’, ‘rockyou.txt’, ‘sample.txt’]" }, { "code": null, "e": 30585, "s": 30392, "text": "Metadata: os.stat_result(st_mode=33206, st_ino=2251799814202896, st_dev=1689971230, st_nlink=1, st_uid=0, st_gid=0, st_size=1916, st_atime=1612953710, st_mtime=1612613202, st_ctime=1612522940)" }, { "code": null, "e": 30621, "s": 30585, "text": "Destination path: csv/gfg/check.txt" }, { "code": null, "e": 30666, "s": 30621, "text": "Example 2: If the destination is a directory" }, { "code": null, "e": 30674, "s": 30666, "text": "Python3" }, { "code": "# Python program to explain shutil.copy2() method # importing os module import os # importing shutil module import shutil # Source path source = \"csv/main.py\" # Destination path destination = \"csv/gfg/\" # Copy the content of # source to destination dest = shutil.copy2(source, destination) # List files and directories # in \"/home / User / Desktop\" print(\"After copying file:\") print(os.listdir(destination)) # Print path of newly # created file print(\"Destination path:\", dest) ", "e": 31164, "s": 30674, "text": null }, { "code": null, "e": 31172, "s": 31164, "text": "Output:" }, { "code": null, "e": 31192, "s": 31172, "text": "After copying file:" }, { "code": null, "e": 31262, "s": 31192, "text": "[‘cc.jpg’, ‘check.txt’, ‘log_transformed.jpg’, ‘main.py’, ‘main2.py’]" }, { "code": null, "e": 31296, "s": 31262, "text": "Destination path: csv/gfg/main.py" }, { "code": null, "e": 31640, "s": 31296, "text": "shutil.copyfile() method in Python is used to copy the content of the source file to the destination file. The metadata of the file is not copied. Source and destination must represent a file and destination must be writable. If the destination already exists then it will be replaced with the source file otherwise a new file will be created." }, { "code": null, "e": 31735, "s": 31640, "text": "If source and destination represent the same file then SameFileError exception will be raised." }, { "code": null, "e": 31807, "s": 31735, "text": "Syntax: shutil.copyfile(source, destination, *, follow_symlinks = True)" }, { "code": null, "e": 31818, "s": 31807, "text": "Parameter:" }, { "code": null, "e": 31877, "s": 31818, "text": "source: A string representing the path of the source file." }, { "code": null, "e": 31946, "s": 31877, "text": "destination: A string representing the path of the destination file." }, { "code": null, "e": 32137, "s": 31946, "text": "follow_symlinks (optional) : The default value of this parameter is True. If False and source represents a symbolic link then a new symbolic link will be created instead of copying the file." }, { "code": null, "e": 32228, "s": 32137, "text": "Return Type: This method returns a string which represents the path of newly created file." }, { "code": null, "e": 32236, "s": 32228, "text": "Python3" }, { "code": "# Python program to explain shutil.copyfile() method # importing shutil module import shutil # Source path source = \"csv/main.py\" # Destination path destination = \"csv/gfg/main_2.py\" dest = shutil.copyfile(source, destination) print(\"Destination path:\", dest) ", "e": 32503, "s": 32236, "text": null }, { "code": null, "e": 32511, "s": 32503, "text": "Output:" }, { "code": null, "e": 32547, "s": 32511, "text": "Destination path: csv/gfg/main_2.py" }, { "code": null, "e": 32770, "s": 32547, "text": "shutil.copytree() method recursively copies an entire directory tree rooted at source (src) to the destination directory. The destination directory, named by (dst) must not already exist. It will be created during copying." }, { "code": null, "e": 32894, "s": 32770, "text": "Syntax: shutil.copytree(src, dst, symlinks = False, ignore = None, copy_function = copy2, igonre_dangling_symlinks = False)" }, { "code": null, "e": 33687, "s": 32894, "text": "Parameters:src: A string representing the path of the source directory.dest: A string representing the path of the destination.symlinks (optional) : This parameter accepts True or False, depending on which the metadata of the original links or linked links will be copied to the new tree.ignore (optional) : If ignore is given, it must be a callable that will receive as its arguments the directory being visited by copytree(), and a list of its contents, as returned by os.listdir().copy_function (optional): The default value of this parameter is copy2. We can use other copy function like copy() for this parameter.igonre_dangling_symlinks (optional) : This parameter value when set to True is used to put a silence on the exception raised if the file pointed by the symlink doesn’t exist." }, { "code": null, "e": 33784, "s": 33687, "text": "Return Value: This method returns a string which represents the path of newly created directory." }, { "code": null, "e": 33792, "s": 33784, "text": "Python3" }, { "code": "# Python program to explain shutil.copytree() method # importing os module import os # importing shutil module import shutil # path path = 'C:/Users/ksaty/csv/gfg' print(\"Before copying file:\") print(os.listdir(path)) # Source path src = 'C:/Users/ksaty/csv/gfg' # Destination path dest = 'C:/Users/ksaty/csv/gfg/dest' # Copy the content of # source to destination destination = shutil.copytree(src, dest) print(\"After copying file:\") print(os.listdir(path)) # Print path of newly # created file print(\"Destination path:\", destination) ", "e": 34342, "s": 33792, "text": null }, { "code": null, "e": 34350, "s": 34342, "text": "Output:" }, { "code": null, "e": 34371, "s": 34350, "text": "Before copying file:" }, { "code": null, "e": 34454, "s": 34371, "text": "[‘cc.jpg’, ‘check.txt’, ‘log_transformed.jpg’, ‘main.py’, ‘main2.py’, ‘main_2.py’]" }, { "code": null, "e": 34474, "s": 34454, "text": "After copying file:" }, { "code": null, "e": 34565, "s": 34474, "text": "[‘cc.jpg’, ‘check.txt’, ‘dest’, ‘log_transformed.jpg’, ‘main.py’, ‘main2.py’, ‘main_2.py’]" }, { "code": null, "e": 34611, "s": 34565, "text": "Destination path: C:/Users/ksaty/csv/gfg/dest" }, { "code": null, "e": 34748, "s": 34611, "text": "shutil.rmtree() is used to delete an entire directory tree, the path must point to a directory (but not a symbolic link to a directory)." }, { "code": null, "e": 34811, "s": 34748, "text": "Syntax: shutil.rmtree(path, ignore_errors=False, onerror=None)" }, { "code": null, "e": 35157, "s": 34811, "text": "Parameters:path: A path-like object representing a file path. A path-like object is either a string or bytes object representing a path.ignore_errors: If ignore_errors is true, errors resulting from failed removals will be ignored.oneerror: If ignore_errors is false or omitted, such errors are handled by calling a handler specified by onerror." }, { "code": null, "e": 35165, "s": 35157, "text": "Python3" }, { "code": "# Python program to demonstrate # shutil.rmtree() import shutil import os # location location = \"csv/gfg/\" # directory dir = \"dest\" # path path = os.path.join(location, dir) # removing directory shutil.rmtree(path) ", "e": 35389, "s": 35165, "text": null }, { "code": null, "e": 35585, "s": 35389, "text": "shutil.which() method tells the path to an executable application that would be run if the given cmd was called. This method can be used to find a file on a computer which is present on the PATH." }, { "code": null, "e": 36096, "s": 35585, "text": "Syntax: shutil.which(cmd, mode = os.F_OK | os.X_OK, path = None)Parameters:cmd: A string representing the file.mode: This parameter specifies mode by which method should execute. os.F_OK tests existence of the path and os.X_OK Checks if path can be executed or we can say mode determines if the file exists and executable.path: This parameter specifies the path to be used, if no path is specified then the results of os.environ() are usedReturn Value: This method returns the path to an executable application" }, { "code": null, "e": 36104, "s": 36096, "text": "Python3" }, { "code": "# importing shutil module import shutil # file search cmd = 'anaconda' # Using shutil.which() method locate = shutil.which(cmd) # Print result print(locate)", "e": 36275, "s": 36104, "text": null }, { "code": null, "e": 36283, "s": 36275, "text": "Output:" }, { "code": null, "e": 36325, "s": 36283, "text": "D:\\Installation_bulk\\Scripts\\anaconda.EXE" }, { "code": null, "e": 36340, "s": 36325, "text": "python-modules" }, { "code": null, "e": 36347, "s": 36340, "text": "Python" }, { "code": null, "e": 36445, "s": 36347, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36477, "s": 36445, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 36519, "s": 36477, "text": "Check if element exists in list in Python" }, { "code": null, "e": 36561, "s": 36519, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 36588, "s": 36561, "text": "Python Classes and Objects" }, { "code": null, "e": 36644, "s": 36588, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 36666, "s": 36644, "text": "Defaultdict in Python" }, { "code": null, "e": 36705, "s": 36666, "text": "Python | Get unique values from a list" }, { "code": null, "e": 36736, "s": 36705, "text": "Python | os.path.join() method" }, { "code": null, "e": 36765, "s": 36736, "text": "Create a directory in Python" } ]
fdisk command in Linux with examples - GeeksforGeeks
20 Jan, 2021 fdisk also known as format disk is a dialog-driven command in Linux used for creating and manipulating disk partition table. It is used for the view, create, delete, change, resize, copy and move partitions on a hard drive using the dialog-driven interface. fdisk allows you to create a maximum of four primary partitions and the number of logical partition depends on the size of the hard disk you are using. It allows the user: To Create space for new partitions. Organizing space for new drives. Re-organizing old drives. Copying or Moving data to new disks(partitions). Synopsis: fdisk [options] device or fdisk -l [device...] 1. View All Disk Partitions:The first thing to do before doing any thing with the disks and partition is to view basic details about all available partition in the system. The below command is used to list the partitions on your system and see their /dev names. For example /dev/sda, /dev/sdb or /dev/sdc. $ sudo fdisk -l 2. View Partition on a Specific Disk: Below command is used to view all disk partitions on device /dev/sda. $ sudo fdisk -l /dev/sda 3. View all fdisk Commands: To see all the command which are available under fdisk command you can use /dev/sda partition with fdisk command. $ sudo fdisk /dev/sda Note: This will prompt for a command. Type m for seeing all the operations which can perform on /dev/sda. After pressing m you will get: 4. Create a Hard Disk Partition: For this go inside the hard drive partition that is the /dev/sda partition, and use the following command: $ sudo fdisk /dev/sda Now you have to type n to create new partition and then type p for making a primary partition and e for making an extended or logical partition depending on the type of partition to make. Run w command to write the changes and reboot your system. 5. Delete a Hard Disk Partition: To delete a partition for the hard disk and free up space occupied by that partition for example /dev/sdb. Go to the command menu using following: $ sudo fdisk /dev/sda and then type d to go to the delete partition menu. It will prompt the partition number you want to delete(type the number). Run w command to write the changes and reboot the system. 6. How to view the size of your Partition: $ sudo fdisk -s /dev/sda Note: To check for the manual page of fdisk command, use the following command: $ man fdisk To see the help message and listing of all options, use the following command option: $ sudo fdisk -h Akanksha_Rai Vishwajith.K linux-command Linux-system-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C tar command in Linux with examples curl command in Linux with Examples Conditional Statements | Shell Script UDP Server-Client implementation in C Tail command in Linux with examples Cat command in Linux with examples touch command in Linux with Examples echo command in Linux with Examples Compiling with g++
[ { "code": null, "e": 25253, "s": 25225, "text": "\n20 Jan, 2021" }, { "code": null, "e": 25684, "s": 25253, "text": "fdisk also known as format disk is a dialog-driven command in Linux used for creating and manipulating disk partition table. It is used for the view, create, delete, change, resize, copy and move partitions on a hard drive using the dialog-driven interface. fdisk allows you to create a maximum of four primary partitions and the number of logical partition depends on the size of the hard disk you are using. It allows the user: " }, { "code": null, "e": 25720, "s": 25684, "text": "To Create space for new partitions." }, { "code": null, "e": 25753, "s": 25720, "text": "Organizing space for new drives." }, { "code": null, "e": 25779, "s": 25753, "text": "Re-organizing old drives." }, { "code": null, "e": 25828, "s": 25779, "text": "Copying or Moving data to new disks(partitions)." }, { "code": null, "e": 25840, "s": 25828, "text": "Synopsis: " }, { "code": null, "e": 25889, "s": 25840, "text": "fdisk [options] device\n\nor\n\nfdisk -l [device...]" }, { "code": null, "e": 26196, "s": 25889, "text": "1. View All Disk Partitions:The first thing to do before doing any thing with the disks and partition is to view basic details about all available partition in the system. The below command is used to list the partitions on your system and see their /dev names. For example /dev/sda, /dev/sdb or /dev/sdc. " }, { "code": null, "e": 26212, "s": 26196, "text": "$ sudo fdisk -l" }, { "code": null, "e": 26322, "s": 26212, "text": "2. View Partition on a Specific Disk: Below command is used to view all disk partitions on device /dev/sda. " }, { "code": null, "e": 26347, "s": 26322, "text": "$ sudo fdisk -l /dev/sda" }, { "code": null, "e": 26491, "s": 26347, "text": "3. View all fdisk Commands: To see all the command which are available under fdisk command you can use /dev/sda partition with fdisk command. " }, { "code": null, "e": 26513, "s": 26491, "text": "$ sudo fdisk /dev/sda" }, { "code": null, "e": 26652, "s": 26513, "text": "Note: This will prompt for a command. Type m for seeing all the operations which can perform on /dev/sda. After pressing m you will get: " }, { "code": null, "e": 26794, "s": 26652, "text": "4. Create a Hard Disk Partition: For this go inside the hard drive partition that is the /dev/sda partition, and use the following command: " }, { "code": null, "e": 26816, "s": 26794, "text": "$ sudo fdisk /dev/sda" }, { "code": null, "e": 27006, "s": 26816, "text": "Now you have to type n to create new partition and then type p for making a primary partition and e for making an extended or logical partition depending on the type of partition to make. " }, { "code": null, "e": 27066, "s": 27006, "text": "Run w command to write the changes and reboot your system. " }, { "code": null, "e": 27248, "s": 27066, "text": "5. Delete a Hard Disk Partition: To delete a partition for the hard disk and free up space occupied by that partition for example /dev/sdb. Go to the command menu using following: " }, { "code": null, "e": 27270, "s": 27248, "text": "$ sudo fdisk /dev/sda" }, { "code": null, "e": 27397, "s": 27270, "text": "and then type d to go to the delete partition menu. It will prompt the partition number you want to delete(type the number). " }, { "code": null, "e": 27456, "s": 27397, "text": "Run w command to write the changes and reboot the system. " }, { "code": null, "e": 27501, "s": 27456, "text": "6. How to view the size of your Partition: " }, { "code": null, "e": 27526, "s": 27501, "text": "$ sudo fdisk -s /dev/sda" }, { "code": null, "e": 27534, "s": 27526, "text": "Note: " }, { "code": null, "e": 27608, "s": 27534, "text": "To check for the manual page of fdisk command, use the following command:" }, { "code": null, "e": 27620, "s": 27608, "text": "$ man fdisk" }, { "code": null, "e": 27706, "s": 27620, "text": "To see the help message and listing of all options, use the following command option:" }, { "code": null, "e": 27722, "s": 27706, "text": "$ sudo fdisk -h" }, { "code": null, "e": 27737, "s": 27724, "text": "Akanksha_Rai" }, { "code": null, "e": 27750, "s": 27737, "text": "Vishwajith.K" }, { "code": null, "e": 27764, "s": 27750, "text": "linux-command" }, { "code": null, "e": 27786, "s": 27764, "text": "Linux-system-commands" }, { "code": null, "e": 27793, "s": 27786, "text": "Picked" }, { "code": null, "e": 27804, "s": 27793, "text": "Linux-Unix" }, { "code": null, "e": 27902, "s": 27804, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27940, "s": 27902, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 27975, "s": 27940, "text": "tar command in Linux with examples" }, { "code": null, "e": 28011, "s": 27975, "text": "curl command in Linux with Examples" }, { "code": null, "e": 28049, "s": 28011, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 28087, "s": 28049, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 28123, "s": 28087, "text": "Tail command in Linux with examples" }, { "code": null, "e": 28158, "s": 28123, "text": "Cat command in Linux with examples" }, { "code": null, "e": 28195, "s": 28158, "text": "touch command in Linux with Examples" }, { "code": null, "e": 28231, "s": 28195, "text": "echo command in Linux with Examples" } ]
Array formed using sum of absolute differences of that element with all other elements - GeeksforGeeks
18 May, 2021 Given a sorted array arr[] of N distinct positive integers. The task is to generate an array such that the element at each index in the new array is the sum of absolute differences of the corresponding element with all other elements of the given array. Input: arr[] = [2, 3, 5]Output: [4, 3, 5]Explanation: distance(2) = |2 – 3| + |2 – 5| = 4distance(3) = |3 – 2| + |3 – 5| = 3distance(5) = |5 – 2| + |5 – 3| = 5Therefore, we will return [4, 3, 5] Input: arr[] = [2, 3, 5, 6]Output: [8, 6, 6, 8]Explanation: distance(2) = |2 – 3| + |2 – 5| + |2 – 6|= 8distance(3) = |3 – 2| + |3 – 5| + |3 – 6|= 6distance(5) = |5 – 2| + |5 – 3| + |5 – 6|= 6distance(6) = |6 – 2| + |6 – 3| + |6 – 5|= 8Therefore, we will return [8, 6, 6, 8] Naive Approach: The idea is to generate all possible pairs for each element in the array arr[] and add the summation of the absolute difference of the pairs for each element in the new array. Print the array after the above steps for all the elements. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to return the new arrayvector<int> calculate(int* arr, int n){ // Initialize the Arraylist vector<int> ans; // Sum of absolute differences // of element with all elements for(int i = 0; i < n; i++) { // Initialize int sum to 0 int sum = 0; for(int j = 0; j < n; j++) { sum += abs(arr[i] - arr[j]); } // Add the value of sum to ans ans.push_back(sum); } // Return the final ans return ans;} // Driver Codeint main(){ // Given array arr[] int arr[] = { 2, 3, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call vector<int> ans = calculate(arr, n); cout << "["; for(auto itr : ans) cout << itr << ", "; cout << "]"; return 0;}// This code is contributed by jrishabh99 // Java program for the above approachimport java.util.*; class GFG { // Function to return the new array private static List<Integer> calculate(int[] arr) { // Length of the arraylist int n = arr.length; // Initialize the Arraylist List<Integer> ans = new ArrayList<Integer>(); // Sum of absolute differences // of element with all elements for (int i = 0; i < arr.length; i++) { // Initialize int sum to 0 int sum = 0; for (int j = 0; j < arr.length; j++) { sum += Math.abs(arr[i] - arr[j]); } // Add the value of sum to ans ans.add(sum); } // Return the final ans return ans; } // Driver Code public static void main(String[] args) { // Given array arr[] int[] arr = { 2, 3, 5, 6 }; // Function Call System.out.println(calculate(arr)); }} # Python3 program for the above approach # Function to return the new array# private static List<Integer>def calculate(arr): # Length of the arraylist n = len(arr) # Initialize the Arraylist ans = [] # Sum of absolute differences # of element with all elements for i in range(n): # Initialize sum to 0 sum = 0 for j in range(len(arr)): sum += abs(arr[i] - arr[j]) # Add the value of sum to ans ans.append(sum) # Return the final ans return ans # Driver Codeif __name__ == '__main__': # Given array arr[] arr = [ 2, 3, 5, 6 ] # Function call print(calculate(arr)) # This code is contributed by mohit kumar 29 // C# program for the above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Function to return the new arrayprivate static List<int> calculate(int[] arr){ // Length of the arraylist int n = arr.Length; // Initialize the Arraylist List<int> ans = new List<int>(); // Sum of absolute differences // of element with all elements for(int i = 0; i < arr.Length; i++) { // Initialize int sum to 0 int sum = 0; for(int j = 0; j < arr.Length; j++) { sum += Math.Abs(arr[i] - arr[j]); } // Add the value of sum to ans ans.Add(sum); } // Return the final ans return ans;} // Driver Codepublic static void Main(string[] args){ // Given array arr[] int[] arr = { 2, 3, 5, 6 }; List<int> tmp = calculate(arr); Console.Write("["); for(int i = 0; i < tmp.Count; i++) { if(i != tmp.Count - 1) { Console.Write(tmp[i] + ", "); } else { Console.Write(tmp[i]); } } Console.Write("]");}} // This code is contributed by rutvik_56 <script> // Javascript program for// the above approach // Function to return the new array function calculate(arr) { // Length of the arraylist let n = arr.length; // Initialize the Arraylist let ans = []; // Sum of absolute differences // of element with all elements for (let i = 0; i < arr.length; i++) { // Initialize let sum to 0 let sum = 0; for (let j = 0; j < arr.length; j++) { sum += Math.abs(arr[i] - arr[j]); } // Add the value of sum to ans ans.push(sum); } // Return the final ans return ans; } // Driver Code // Given array arr[] let arr = [ 2, 3, 5, 6 ]; // Function Call document.write(calculate(arr)); </script> [8, 6, 6, 8] Time Complexity: O(N^2)Auxiliary Space: O(N) Efficient Approach: To optimize the above approach the idea is to keep track of the accumulated subtraction of the values to the left and of the sum of values to the right. The sum of the difference of all the pairs for each element is given by: num_of_elements_to_the_left * current_value -num_of_elements_to_the_right * current_value Find the sum of all the elements in the given array(say sum). Initialize sub as 0. Traverse the given array and for each element do the following: Subtract the current value arr[i] from the sum.Add the difference of all the pairs for each element using the formula to the resultant array: Subtract the current value arr[i] from the sum. Add the difference of all the pairs for each element using the formula to the resultant array: sub + (i * arr[i]) - ((n - i - 1) * arr[i]) + sum Subtract the current value arr[i] from the sum. Print the resultant array after the above steps. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the// above approach#include <bits/stdc++.h>using namespace std; // Function to return list of// total Distance of each element// from other elements in arrayvector<int> calculate(int arr[], int n){ int sub = 0; int sum = 0; // Initialize the arraylist vector<int> ans; // Keep track of the // accumulated of the // sum of values to right for (int i = n - 1; i >= 0; i--) sum += arr[i]; // Keep track of the // accumulated subtraction // of the values to the left for (int i = 0; i < n; i++) { sum -= arr[i]; // Add the value to the // resultant array ans[] ans.push_back(sub + (i * arr[i]) - ((n - i - 1) * arr[i]) + sum); sub -= arr[i]; } // Return the final // answer return ans;} // Driver Codeint main(){ // Initialize the array int arr[] = {2, 3, 5, 6}; int n = sizeof(arr) / sizeof(arr[0]); vector<int> ans = (calculate(arr, n)); for (int i = 0; i < n; i++) cout << ans[i] << " ";} // This code is contributed by Chitranayal // Java program for the above approachimport java.util.*; class GFG { // Function to return list of // total Distance of each element // from other elements in array private static List<Integer> calculate(int[] arr) { // Length of the array int n = arr.length; int sub = 0; int sum = 0; // Initialize the arraylist List<Integer> ans = new ArrayList<Integer>(); // Keep track of the accumulated // of the sum of values to right for (int i = n - 1; i >= 0; i--) sum += arr[i]; // Keep track of the accumulated // subtraction of the values to the left for (int i = 0; i < arr.length; i++) { sum -= arr[i]; // Add the value to the resultant // array ans[] ans.add(sub + (i * arr[i]) - ((n - i - 1) * arr[i]) + sum); sub -= arr[i]; } // return the final answer return ans; } // Driver Code public static void main(String[] args) { // Initialize the array int[] arr = { 2, 3, 5, 6 }; // Function Call System.out.println(calculate(arr)); }} # Python3 program for the above approach # Function to return list of# total Distance of each element# from other elements in arraydef calculate (arr): # Length of the array n = len(arr) sub = 0 Sum = 0 # Initialize the ArrayList ans = [] # Keep track of the accumulated # of the sum of values to right for i in range(n - 1, -1, -1): Sum += arr[i] # Keep track of the accumulated # subtraction of values to left for i in range(len(arr)): Sum -= arr[i] # Add the value to the resultant # array ans[] ans.append(sub + (i * arr[i]) - ((n - i - 1) * arr[i]) + Sum) sub -= arr[i] # Return the final answer return ans # Driver Codeif __name__ == '__main__': # Initialize the array arr = [ 2, 3, 5, 6 ] # Function call print(calculate(arr)) # This code is contributed by himanshu77 // C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to return list of// total Distance of each element// from other elements in arrayprivate static List<int> calculate(int[] arr){ // Length of the array int n = arr.Length; int sub = 0; int sum = 0; // Initialize the arraylist List<int> ans = new List<int>(); // Keep track of the accumulated // of the sum of values to right for(int i = n - 1; i >= 0; i--) sum += arr[i]; // Keep track of the accumulated // subtraction of the values to the left for(int i = 0; i < arr.Length; i++) { sum -= arr[i]; // Add the value to the resultant // array ans[] ans.Add(sub + (i * arr[i]) - ((n - i - 1) * arr[i]) + sum); sub -= arr[i]; } // return the readonly answer return ans;} // Driver Codepublic static void Main(String[] args){ // Initialize the array int[] arr = { 2, 3, 5, 6 }; // Function Call Console.Write("[ "); foreach(int i in calculate(arr)) Console.Write(i + ", "); Console.Write("]");}} // This code is contributed by amal kumar choubey <script>// Javascript program for the// above approach // Function to return list of// total Distance of each element// from other elements in arrayfunction calculate(arr, n){ var sub = 0; var sum = 0; // Initialize the arraylist var ans = []; // Keep track of the // accumulated of the // sum of values to right for (var i = n - 1; i >= 0; i--) sum += arr[i]; // Keep track of the // accumulated subtraction // of the values to the left for (var i = 0; i < n; i++) { sum -= arr[i]; // Add the value to the // resultant array ans[] ans.push(sub + (i * arr[i]) - ((n - i - 1) * arr[i]) + sum); sub -= arr[i]; } // Return the final // answer return ans;} // Driver Code// Initialize the arrayvar arr = [2, 3, 5, 6]var n = arr.length;var ans = (calculate(arr, n)); for (var i = 0; i < n; i++) document.write( ans[i] + " "); // This code is contributed by famously.</script> [8, 6, 6, 8] Time Complexity: O(N)Space Complexity: O(N) mohit kumar 29 rutvik_56 Amal Kumar Choubey himanshu77 jrishabh99 ukasp target_2 famously Arrays Greedy Mathematical Arrays Greedy Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Write a program to print all permutations of a given string Huffman Coding | Greedy Algo-3
[ { "code": null, "e": 26441, "s": 26413, "text": "\n18 May, 2021" }, { "code": null, "e": 26695, "s": 26441, "text": "Given a sorted array arr[] of N distinct positive integers. The task is to generate an array such that the element at each index in the new array is the sum of absolute differences of the corresponding element with all other elements of the given array." }, { "code": null, "e": 26891, "s": 26695, "text": "Input: arr[] = [2, 3, 5]Output: [4, 3, 5]Explanation: distance(2) = |2 – 3| + |2 – 5| = 4distance(3) = |3 – 2| + |3 – 5| = 3distance(5) = |5 – 2| + |5 – 3| = 5Therefore, we will return [4, 3, 5]" }, { "code": null, "e": 27169, "s": 26891, "text": "Input: arr[] = [2, 3, 5, 6]Output: [8, 6, 6, 8]Explanation: distance(2) = |2 – 3| + |2 – 5| + |2 – 6|= 8distance(3) = |3 – 2| + |3 – 5| + |3 – 6|= 6distance(5) = |5 – 2| + |5 – 3| + |5 – 6|= 6distance(6) = |6 – 2| + |6 – 3| + |6 – 5|= 8Therefore, we will return [8, 6, 6, 8]" }, { "code": null, "e": 27421, "s": 27169, "text": "Naive Approach: The idea is to generate all possible pairs for each element in the array arr[] and add the summation of the absolute difference of the pairs for each element in the new array. Print the array after the above steps for all the elements." }, { "code": null, "e": 27472, "s": 27421, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27476, "s": 27472, "text": "C++" }, { "code": null, "e": 27481, "s": 27476, "text": "Java" }, { "code": null, "e": 27489, "s": 27481, "text": "Python3" }, { "code": null, "e": 27492, "s": 27489, "text": "C#" }, { "code": null, "e": 27503, "s": 27492, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to return the new arrayvector<int> calculate(int* arr, int n){ // Initialize the Arraylist vector<int> ans; // Sum of absolute differences // of element with all elements for(int i = 0; i < n; i++) { // Initialize int sum to 0 int sum = 0; for(int j = 0; j < n; j++) { sum += abs(arr[i] - arr[j]); } // Add the value of sum to ans ans.push_back(sum); } // Return the final ans return ans;} // Driver Codeint main(){ // Given array arr[] int arr[] = { 2, 3, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call vector<int> ans = calculate(arr, n); cout << \"[\"; for(auto itr : ans) cout << itr << \", \"; cout << \"]\"; return 0;}// This code is contributed by jrishabh99", "e": 28441, "s": 27503, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG { // Function to return the new array private static List<Integer> calculate(int[] arr) { // Length of the arraylist int n = arr.length; // Initialize the Arraylist List<Integer> ans = new ArrayList<Integer>(); // Sum of absolute differences // of element with all elements for (int i = 0; i < arr.length; i++) { // Initialize int sum to 0 int sum = 0; for (int j = 0; j < arr.length; j++) { sum += Math.abs(arr[i] - arr[j]); } // Add the value of sum to ans ans.add(sum); } // Return the final ans return ans; } // Driver Code public static void main(String[] args) { // Given array arr[] int[] arr = { 2, 3, 5, 6 }; // Function Call System.out.println(calculate(arr)); }}", "e": 29443, "s": 28441, "text": null }, { "code": "# Python3 program for the above approach # Function to return the new array# private static List<Integer>def calculate(arr): # Length of the arraylist n = len(arr) # Initialize the Arraylist ans = [] # Sum of absolute differences # of element with all elements for i in range(n): # Initialize sum to 0 sum = 0 for j in range(len(arr)): sum += abs(arr[i] - arr[j]) # Add the value of sum to ans ans.append(sum) # Return the final ans return ans # Driver Codeif __name__ == '__main__': # Given array arr[] arr = [ 2, 3, 5, 6 ] # Function call print(calculate(arr)) # This code is contributed by mohit kumar 29", "e": 30145, "s": 29443, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Function to return the new arrayprivate static List<int> calculate(int[] arr){ // Length of the arraylist int n = arr.Length; // Initialize the Arraylist List<int> ans = new List<int>(); // Sum of absolute differences // of element with all elements for(int i = 0; i < arr.Length; i++) { // Initialize int sum to 0 int sum = 0; for(int j = 0; j < arr.Length; j++) { sum += Math.Abs(arr[i] - arr[j]); } // Add the value of sum to ans ans.Add(sum); } // Return the final ans return ans;} // Driver Codepublic static void Main(string[] args){ // Given array arr[] int[] arr = { 2, 3, 5, 6 }; List<int> tmp = calculate(arr); Console.Write(\"[\"); for(int i = 0; i < tmp.Count; i++) { if(i != tmp.Count - 1) { Console.Write(tmp[i] + \", \"); } else { Console.Write(tmp[i]); } } Console.Write(\"]\");}} // This code is contributed by rutvik_56", "e": 31305, "s": 30145, "text": null }, { "code": "<script> // Javascript program for// the above approach // Function to return the new array function calculate(arr) { // Length of the arraylist let n = arr.length; // Initialize the Arraylist let ans = []; // Sum of absolute differences // of element with all elements for (let i = 0; i < arr.length; i++) { // Initialize let sum to 0 let sum = 0; for (let j = 0; j < arr.length; j++) { sum += Math.abs(arr[i] - arr[j]); } // Add the value of sum to ans ans.push(sum); } // Return the final ans return ans; } // Driver Code // Given array arr[] let arr = [ 2, 3, 5, 6 ]; // Function Call document.write(calculate(arr)); </script>", "e": 32186, "s": 31305, "text": null }, { "code": null, "e": 32199, "s": 32186, "text": "[8, 6, 6, 8]" }, { "code": null, "e": 32244, "s": 32199, "text": "Time Complexity: O(N^2)Auxiliary Space: O(N)" }, { "code": null, "e": 32490, "s": 32244, "text": "Efficient Approach: To optimize the above approach the idea is to keep track of the accumulated subtraction of the values to the left and of the sum of values to the right. The sum of the difference of all the pairs for each element is given by:" }, { "code": null, "e": 32580, "s": 32490, "text": "num_of_elements_to_the_left * current_value -num_of_elements_to_the_right * current_value" }, { "code": null, "e": 32642, "s": 32580, "text": "Find the sum of all the elements in the given array(say sum)." }, { "code": null, "e": 32663, "s": 32642, "text": "Initialize sub as 0." }, { "code": null, "e": 32869, "s": 32663, "text": "Traverse the given array and for each element do the following: Subtract the current value arr[i] from the sum.Add the difference of all the pairs for each element using the formula to the resultant array:" }, { "code": null, "e": 32917, "s": 32869, "text": "Subtract the current value arr[i] from the sum." }, { "code": null, "e": 33012, "s": 32917, "text": "Add the difference of all the pairs for each element using the formula to the resultant array:" }, { "code": null, "e": 33062, "s": 33012, "text": "sub + (i * arr[i]) - ((n - i - 1) * arr[i]) + sum" }, { "code": null, "e": 33110, "s": 33062, "text": "Subtract the current value arr[i] from the sum." }, { "code": null, "e": 33159, "s": 33110, "text": "Print the resultant array after the above steps." }, { "code": null, "e": 33210, "s": 33159, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 33214, "s": 33210, "text": "C++" }, { "code": null, "e": 33219, "s": 33214, "text": "Java" }, { "code": null, "e": 33227, "s": 33219, "text": "Python3" }, { "code": null, "e": 33230, "s": 33227, "text": "C#" }, { "code": null, "e": 33241, "s": 33230, "text": "Javascript" }, { "code": "// C++ program for the// above approach#include <bits/stdc++.h>using namespace std; // Function to return list of// total Distance of each element// from other elements in arrayvector<int> calculate(int arr[], int n){ int sub = 0; int sum = 0; // Initialize the arraylist vector<int> ans; // Keep track of the // accumulated of the // sum of values to right for (int i = n - 1; i >= 0; i--) sum += arr[i]; // Keep track of the // accumulated subtraction // of the values to the left for (int i = 0; i < n; i++) { sum -= arr[i]; // Add the value to the // resultant array ans[] ans.push_back(sub + (i * arr[i]) - ((n - i - 1) * arr[i]) + sum); sub -= arr[i]; } // Return the final // answer return ans;} // Driver Codeint main(){ // Initialize the array int arr[] = {2, 3, 5, 6}; int n = sizeof(arr) / sizeof(arr[0]); vector<int> ans = (calculate(arr, n)); for (int i = 0; i < n; i++) cout << ans[i] << \" \";} // This code is contributed by Chitranayal", "e": 34320, "s": 33241, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG { // Function to return list of // total Distance of each element // from other elements in array private static List<Integer> calculate(int[] arr) { // Length of the array int n = arr.length; int sub = 0; int sum = 0; // Initialize the arraylist List<Integer> ans = new ArrayList<Integer>(); // Keep track of the accumulated // of the sum of values to right for (int i = n - 1; i >= 0; i--) sum += arr[i]; // Keep track of the accumulated // subtraction of the values to the left for (int i = 0; i < arr.length; i++) { sum -= arr[i]; // Add the value to the resultant // array ans[] ans.add(sub + (i * arr[i]) - ((n - i - 1) * arr[i]) + sum); sub -= arr[i]; } // return the final answer return ans; } // Driver Code public static void main(String[] args) { // Initialize the array int[] arr = { 2, 3, 5, 6 }; // Function Call System.out.println(calculate(arr)); }}", "e": 35589, "s": 34320, "text": null }, { "code": "# Python3 program for the above approach # Function to return list of# total Distance of each element# from other elements in arraydef calculate (arr): # Length of the array n = len(arr) sub = 0 Sum = 0 # Initialize the ArrayList ans = [] # Keep track of the accumulated # of the sum of values to right for i in range(n - 1, -1, -1): Sum += arr[i] # Keep track of the accumulated # subtraction of values to left for i in range(len(arr)): Sum -= arr[i] # Add the value to the resultant # array ans[] ans.append(sub + (i * arr[i]) - ((n - i - 1) * arr[i]) + Sum) sub -= arr[i] # Return the final answer return ans # Driver Codeif __name__ == '__main__': # Initialize the array arr = [ 2, 3, 5, 6 ] # Function call print(calculate(arr)) # This code is contributed by himanshu77", "e": 36487, "s": 35589, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to return list of// total Distance of each element// from other elements in arrayprivate static List<int> calculate(int[] arr){ // Length of the array int n = arr.Length; int sub = 0; int sum = 0; // Initialize the arraylist List<int> ans = new List<int>(); // Keep track of the accumulated // of the sum of values to right for(int i = n - 1; i >= 0; i--) sum += arr[i]; // Keep track of the accumulated // subtraction of the values to the left for(int i = 0; i < arr.Length; i++) { sum -= arr[i]; // Add the value to the resultant // array ans[] ans.Add(sub + (i * arr[i]) - ((n - i - 1) * arr[i]) + sum); sub -= arr[i]; } // return the readonly answer return ans;} // Driver Codepublic static void Main(String[] args){ // Initialize the array int[] arr = { 2, 3, 5, 6 }; // Function Call Console.Write(\"[ \"); foreach(int i in calculate(arr)) Console.Write(i + \", \"); Console.Write(\"]\");}} // This code is contributed by amal kumar choubey", "e": 37711, "s": 36487, "text": null }, { "code": "<script>// Javascript program for the// above approach // Function to return list of// total Distance of each element// from other elements in arrayfunction calculate(arr, n){ var sub = 0; var sum = 0; // Initialize the arraylist var ans = []; // Keep track of the // accumulated of the // sum of values to right for (var i = n - 1; i >= 0; i--) sum += arr[i]; // Keep track of the // accumulated subtraction // of the values to the left for (var i = 0; i < n; i++) { sum -= arr[i]; // Add the value to the // resultant array ans[] ans.push(sub + (i * arr[i]) - ((n - i - 1) * arr[i]) + sum); sub -= arr[i]; } // Return the final // answer return ans;} // Driver Code// Initialize the arrayvar arr = [2, 3, 5, 6]var n = arr.length;var ans = (calculate(arr, n)); for (var i = 0; i < n; i++) document.write( ans[i] + \" \"); // This code is contributed by famously.</script>", "e": 38670, "s": 37711, "text": null }, { "code": null, "e": 38683, "s": 38670, "text": "[8, 6, 6, 8]" }, { "code": null, "e": 38729, "s": 38685, "text": "Time Complexity: O(N)Space Complexity: O(N)" }, { "code": null, "e": 38744, "s": 38729, "text": "mohit kumar 29" }, { "code": null, "e": 38754, "s": 38744, "text": "rutvik_56" }, { "code": null, "e": 38773, "s": 38754, "text": "Amal Kumar Choubey" }, { "code": null, "e": 38784, "s": 38773, "text": "himanshu77" }, { "code": null, "e": 38795, "s": 38784, "text": "jrishabh99" }, { "code": null, "e": 38801, "s": 38795, "text": "ukasp" }, { "code": null, "e": 38810, "s": 38801, "text": "target_2" }, { "code": null, "e": 38819, "s": 38810, "text": "famously" }, { "code": null, "e": 38826, "s": 38819, "text": "Arrays" }, { "code": null, "e": 38833, "s": 38826, "text": "Greedy" }, { "code": null, "e": 38846, "s": 38833, "text": "Mathematical" }, { "code": null, "e": 38853, "s": 38846, "text": "Arrays" }, { "code": null, "e": 38860, "s": 38853, "text": "Greedy" }, { "code": null, "e": 38873, "s": 38860, "text": "Mathematical" }, { "code": null, "e": 38971, "s": 38873, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39039, "s": 38971, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 39083, "s": 39039, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 39131, "s": 39083, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 39154, "s": 39131, "text": "Introduction to Arrays" }, { "code": null, "e": 39186, "s": 39154, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 39237, "s": 39186, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 39288, "s": 39237, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 39346, "s": 39288, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 39406, "s": 39346, "text": "Write a program to print all permutations of a given string" } ]
How to detect touch screen device using JavaScript? - GeeksforGeeks
24 Jan, 2022 Sometimes you might be looking for some features to include into your web-app that should only be available to devices with a touch screen. You may need this detection while introducing newer smarter controls for touch screen users in the game app or a GPS and navigation application. While there are many JavaScript libraries such as Modernizer, jQuery, etc, that are explicitly designed to do such kind of tasks.It is noted that the device supports touch events doesn’t necessarily mean that it is exclusively a touch screen device. Many of the high-end ultrabooks are touch enabled. So for better user experience, you should consider a few more attributes alongside checking for a touch screen device.To perform this check, targeting all possible browsers out there, we will be using following three properties; ontouchstart: An event handler that handles event triggered after touching a DOM element. maxTouchPoints: A read-only property of a Navigator interface returns the maximum number of simultaneous touch contact points that the device supports. msMaxTouchPoints: Same as above, just with vendor prefix “ms” to target browsers IE 10 and below. Syntax: javascript function is_touch_enabled() { return ( 'ontouchstart' in window ) || ( navigator.maxTouchPoints > 0 ) || ( navigator.msMaxTouchPoints > 0 );} Example: This example displays an image if it detect touch screen device otherwise image will not display. html <!DOCTYPE html><html> <head> <title> Detect touch screen device using JavaScript </title></head> <body> <p> Detect touch screen device using JavaScript </p> <p> If touch screen detected then display an image otherwise image will not display </p> <div id="GFG"></div> <script type="text/javascript"> function is_touch_enabled() { return ( 'ontouchstart' in window ) || ( navigator.maxTouchPoints > 0 ) || ( navigator.msMaxTouchPoints > 0 ); } var src ="https://write.geeksforgeeks.org/wp-content/uploads/gfg-39.png"; if( is_touch_enabled() ) { var img = "<img src=" + src + " height='100'/>";; } else { var img = ""; } document.getElementById('GFG').innerHTML = img; </script></body> </html> Output: Output on non-touch screen: Output on touch screen: Example 2: In this example, a <div> is draggable only if the device is touch-enabled. html <!DOCTYPE html><html> <head> <title> Detect touch screen device using JavaScript </title> <link href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet"> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.3/jquery.ui.touch-punch.min.js"> </script> <style> #draggable { width: 150px; height: 50px; text-align: center; } </style> <script> function is_touch_enabled() { return ( 'ontouchstart' in window ) || ( navigator.maxTouchPoints > 0 ) || ( navigator.msMaxTouchPoints > 0 ); } if( is_touch_enabled() ) { $(function() { $( "#draggable" ).draggable(); }); } </script></head> <body> <div id="draggable" class="ui-widget-content"> <p>Draggable Elements!</p> </div></body> </html> Output: Output on non-touch screen: Output on touch screen: avtarkumar719 as5853535 JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Difference Between PUT and PATCH Request Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 26313, "s": 26285, "text": "\n24 Jan, 2022" }, { "code": null, "e": 27130, "s": 26313, "text": "Sometimes you might be looking for some features to include into your web-app that should only be available to devices with a touch screen. You may need this detection while introducing newer smarter controls for touch screen users in the game app or a GPS and navigation application. While there are many JavaScript libraries such as Modernizer, jQuery, etc, that are explicitly designed to do such kind of tasks.It is noted that the device supports touch events doesn’t necessarily mean that it is exclusively a touch screen device. Many of the high-end ultrabooks are touch enabled. So for better user experience, you should consider a few more attributes alongside checking for a touch screen device.To perform this check, targeting all possible browsers out there, we will be using following three properties; " }, { "code": null, "e": 27220, "s": 27130, "text": "ontouchstart: An event handler that handles event triggered after touching a DOM element." }, { "code": null, "e": 27372, "s": 27220, "text": "maxTouchPoints: A read-only property of a Navigator interface returns the maximum number of simultaneous touch contact points that the device supports." }, { "code": null, "e": 27470, "s": 27372, "text": "msMaxTouchPoints: Same as above, just with vendor prefix “ms” to target browsers IE 10 and below." }, { "code": null, "e": 27480, "s": 27470, "text": "Syntax: " }, { "code": null, "e": 27491, "s": 27480, "text": "javascript" }, { "code": "function is_touch_enabled() { return ( 'ontouchstart' in window ) || ( navigator.maxTouchPoints > 0 ) || ( navigator.msMaxTouchPoints > 0 );}", "e": 27656, "s": 27491, "text": null }, { "code": null, "e": 27765, "s": 27656, "text": "Example: This example displays an image if it detect touch screen device otherwise image will not display. " }, { "code": null, "e": 27770, "s": 27765, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> Detect touch screen device using JavaScript </title></head> <body> <p> Detect touch screen device using JavaScript </p> <p> If touch screen detected then display an image otherwise image will not display </p> <div id=\"GFG\"></div> <script type=\"text/javascript\"> function is_touch_enabled() { return ( 'ontouchstart' in window ) || ( navigator.maxTouchPoints > 0 ) || ( navigator.msMaxTouchPoints > 0 ); } var src =\"https://write.geeksforgeeks.org/wp-content/uploads/gfg-39.png\"; if( is_touch_enabled() ) { var img = \"<img src=\" + src + \" height='100'/>\";; } else { var img = \"\"; } document.getElementById('GFG').innerHTML = img; </script></body> </html> ", "e": 28715, "s": 27770, "text": null }, { "code": null, "e": 28725, "s": 28715, "text": "Output: " }, { "code": null, "e": 28755, "s": 28725, "text": "Output on non-touch screen: " }, { "code": null, "e": 28781, "s": 28755, "text": "Output on touch screen: " }, { "code": null, "e": 28869, "s": 28781, "text": "Example 2: In this example, a <div> is draggable only if the device is touch-enabled. " }, { "code": null, "e": 28874, "s": 28869, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> Detect touch screen device using JavaScript </title> <link href=\"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\" rel=\"stylesheet\"> <script src=\"https://code.jquery.com/jquery-1.10.2.js\"></script> <script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.3/jquery.ui.touch-punch.min.js\"> </script> <style> #draggable { width: 150px; height: 50px; text-align: center; } </style> <script> function is_touch_enabled() { return ( 'ontouchstart' in window ) || ( navigator.maxTouchPoints > 0 ) || ( navigator.msMaxTouchPoints > 0 ); } if( is_touch_enabled() ) { $(function() { $( \"#draggable\" ).draggable(); }); } </script></head> <body> <div id=\"draggable\" class=\"ui-widget-content\"> <p>Draggable Elements!</p> </div></body> </html> ", "e": 30038, "s": 28874, "text": null }, { "code": null, "e": 30048, "s": 30038, "text": "Output: " }, { "code": null, "e": 30078, "s": 30048, "text": "Output on non-touch screen: " }, { "code": null, "e": 30106, "s": 30080, "text": "Output on touch screen: " }, { "code": null, "e": 30126, "s": 30112, "text": "avtarkumar719" }, { "code": null, "e": 30136, "s": 30126, "text": "as5853535" }, { "code": null, "e": 30152, "s": 30136, "text": "JavaScript-Misc" }, { "code": null, "e": 30159, "s": 30152, "text": "Picked" }, { "code": null, "e": 30170, "s": 30159, "text": "JavaScript" }, { "code": null, "e": 30187, "s": 30170, "text": "Web Technologies" }, { "code": null, "e": 30214, "s": 30187, "text": "Web technologies Questions" }, { "code": null, "e": 30312, "s": 30214, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30352, "s": 30312, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30397, "s": 30352, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30458, "s": 30397, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30530, "s": 30458, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 30571, "s": 30530, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 30611, "s": 30571, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30644, "s": 30611, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30689, "s": 30644, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30732, "s": 30689, "text": "How to fetch data from an API in ReactJS ?" } ]
How to break _.each() function in Underscore.js ? - GeeksforGeeks
02 Jun, 2020 It is not possible to break the _.each function. The reason is that the _.each function works similarly to the forEach function and imitates its native behavior. It does not allow us to break the loop or escape from it except by throwing an exception. However, one can use different methods like: Throw Exception _.find() function _.some() function Throw Exception: One can throw an exception from each on getting the desired value. Syntax: try { _(arrayName).each(function(elementName){ // your code with condition where // exception is to be thrown }) } catch(exception){ // dont do anything here } Example: <script> var arr = [10, 20, 30, 40]; var cnt = 0; try { _(arr).each(function (value) { if (value == 30) { throw new Error(); } // Write your own code to // use the other values, // for example: console.log(cnt++); }) } catch (e) { // Don't do anything here }</script> Output:0 1 Output: Here exception is thrown when the value 30 is detected. Otherwise the count (cnt) is incremented by 1 _.find() Function: The _.find() function can be used to break the loop when the required value is found. The result can be stored in an external variable. _.find(arayName, function(elementName){ if(elementName == value){ return false; } // Write your own code } Example: <script> var arr = [10, 20, 30, 40]; var cnt = 0; _.find(arr, function (value) { if (value == 30) { return false; } // Write your own code // to use the other values, // for example: console.log(cnt++); });</script> Output:0 1 Output: Here the _.find() function returns false when the value 30 is reached. Otherwise the count (cnt) is incremented by 1 Note: One can also include the finally block after the catch block. _.some() Function: The _.some() function is similar to the _.find() function and stops traversing the list once the required value is detected. Result can be stored in an external variable. Syntax: _.some(arayName, function(elementName){ if(elementName==value){ return false; } // Write your own code } Example: <script> var arr = [10, 20, 30, 40]; var cnt = 0; _.some(arr, function (value) { if (value == 30) { return false; } // Write your own code // to use the other values, // for example: console.log(cnt++); });</script> Output:0 1 Output: Here the _.some() function returns false when the value 30 is detected. Otherwise the count (cnt) is incremented by 1. JavaScript - Underscore.js Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 34847, "s": 34819, "text": "\n02 Jun, 2020" }, { "code": null, "e": 35144, "s": 34847, "text": "It is not possible to break the _.each function. The reason is that the _.each function works similarly to the forEach function and imitates its native behavior. It does not allow us to break the loop or escape from it except by throwing an exception. However, one can use different methods like:" }, { "code": null, "e": 35160, "s": 35144, "text": "Throw Exception" }, { "code": null, "e": 35178, "s": 35160, "text": "_.find() function" }, { "code": null, "e": 35196, "s": 35178, "text": "_.some() function" }, { "code": null, "e": 35280, "s": 35196, "text": "Throw Exception: One can throw an exception from each on getting the desired value." }, { "code": null, "e": 35288, "s": 35280, "text": "Syntax:" }, { "code": null, "e": 35481, "s": 35288, "text": "try {\n _(arrayName).each(function(elementName){\n // your code with condition where \n // exception is to be thrown\n })\n}\ncatch(exception){\n // dont do anything here\n}\n" }, { "code": null, "e": 35490, "s": 35481, "text": "Example:" }, { "code": "<script> var arr = [10, 20, 30, 40]; var cnt = 0; try { _(arr).each(function (value) { if (value == 30) { throw new Error(); } // Write your own code to // use the other values, // for example: console.log(cnt++); }) } catch (e) { // Don't do anything here }</script>", "e": 35879, "s": 35490, "text": null }, { "code": null, "e": 35890, "s": 35879, "text": "Output:0 1" }, { "code": null, "e": 35898, "s": 35890, "text": "Output:" }, { "code": null, "e": 36000, "s": 35898, "text": "Here exception is thrown when the value 30 is detected. Otherwise the count (cnt) is incremented by 1" }, { "code": null, "e": 36155, "s": 36000, "text": "_.find() Function: The _.find() function can be used to break the loop when the required value is found. The result can be stored in an external variable." }, { "code": null, "e": 36287, "s": 36155, "text": "_.find(arayName, function(elementName){\n if(elementName == value){\n return false;\n }\n // Write your own code\n}\n" }, { "code": null, "e": 36296, "s": 36287, "text": "Example:" }, { "code": "<script> var arr = [10, 20, 30, 40]; var cnt = 0; _.find(arr, function (value) { if (value == 30) { return false; } // Write your own code // to use the other values, // for example: console.log(cnt++); });</script>", "e": 36580, "s": 36296, "text": null }, { "code": null, "e": 36591, "s": 36580, "text": "Output:0 1" }, { "code": null, "e": 36599, "s": 36591, "text": "Output:" }, { "code": null, "e": 36716, "s": 36599, "text": "Here the _.find() function returns false when the value 30 is reached. Otherwise the count (cnt) is incremented by 1" }, { "code": null, "e": 36784, "s": 36716, "text": "Note: One can also include the finally block after the catch block." }, { "code": null, "e": 36974, "s": 36784, "text": "_.some() Function: The _.some() function is similar to the _.find() function and stops traversing the list once the required value is detected. Result can be stored in an external variable." }, { "code": null, "e": 36982, "s": 36974, "text": "Syntax:" }, { "code": null, "e": 37113, "s": 36982, "text": "_.some(arayName, function(elementName){\n if(elementName==value){\n return false;\n }\n \n // Write your own code\n}\n" }, { "code": null, "e": 37122, "s": 37113, "text": "Example:" }, { "code": "<script> var arr = [10, 20, 30, 40]; var cnt = 0; _.some(arr, function (value) { if (value == 30) { return false; } // Write your own code // to use the other values, // for example: console.log(cnt++); });</script>", "e": 37406, "s": 37122, "text": null }, { "code": null, "e": 37417, "s": 37406, "text": "Output:0 1" }, { "code": null, "e": 37425, "s": 37417, "text": "Output:" }, { "code": null, "e": 37544, "s": 37425, "text": "Here the _.some() function returns false when the value 30 is detected. Otherwise the count (cnt) is incremented by 1." }, { "code": null, "e": 37571, "s": 37544, "text": "JavaScript - Underscore.js" }, { "code": null, "e": 37578, "s": 37571, "text": "Picked" }, { "code": null, "e": 37589, "s": 37578, "text": "JavaScript" }, { "code": null, "e": 37606, "s": 37589, "text": "Web Technologies" }, { "code": null, "e": 37633, "s": 37606, "text": "Web technologies Questions" }, { "code": null, "e": 37731, "s": 37633, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37771, "s": 37731, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 37816, "s": 37771, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 37877, "s": 37816, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 37949, "s": 37877, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 38018, "s": 37949, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 38058, "s": 38018, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 38091, "s": 38058, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 38136, "s": 38091, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 38179, "s": 38136, "text": "How to fetch data from an API in ReactJS ?" } ]
How to use Thread in Tkinter Python - GeeksforGeeks
17 Dec, 2020 Prerequisite: Python GUI – tkinter multithreading Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create the GUI applications. Creating a GUI using tkinter is an easy task. While Creating a GUI there will be a need to do multiple work/operation at backend. Suppose we want to perform 4 operations simultaneously. The problem here is, each operation executes one by one. During execution of one operation the GUI window will also not move and this is why we need threading. Both implementation is given below which obviously will help understand their differences better. Working without threads, makes the process delayed. Also, the window will not move until full execution takes place. Approach Create Normal Tkinter Window Add Button with command Execute Tkinter Program: Python3 # Import Modulefrom tkinter import *import timefrom threading import * # Create Objectroot = Tk() # Set geometryroot.geometry("400x400") def work(): print("sleep time start") for i in range(10): print(i) time.sleep(1) print("sleep time stop") # Create ButtonButton(root, text="Click Me", command=work).pack() # Execute Tkinterroot.mainloop() Output: Approach Create Normal Tkinter Window Add Button with command for threading Execute Tkinter Program: Python3 # Import Modulefrom tkinter import *import timefrom threading import * # Create Objectroot = Tk() # Set geometryroot.geometry("400x400") # use threading def threading(): # Call work function t1=Thread(target=work) t1.start() # work functiondef work(): print("sleep time start") for i in range(10): print(i) time.sleep(1) print("sleep time stop") # Create ButtonButton(root,text="Click Me",command = threading).pack() # Execute Tkinterroot.mainloop() Output: Python-threading Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25562, "s": 25534, "text": "\n17 Dec, 2020" }, { "code": null, "e": 25577, "s": 25562, "text": "Prerequisite: " }, { "code": null, "e": 25598, "s": 25577, "text": "Python GUI – tkinter" }, { "code": null, "e": 25613, "s": 25598, "text": "multithreading" }, { "code": null, "e": 25967, "s": 25613, "text": "Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create the GUI applications. Creating a GUI using tkinter is an easy task." }, { "code": null, "e": 26365, "s": 25967, "text": "While Creating a GUI there will be a need to do multiple work/operation at backend. Suppose we want to perform 4 operations simultaneously. The problem here is, each operation executes one by one. During execution of one operation the GUI window will also not move and this is why we need threading. Both implementation is given below which obviously will help understand their differences better." }, { "code": null, "e": 26482, "s": 26365, "text": "Working without threads, makes the process delayed. Also, the window will not move until full execution takes place." }, { "code": null, "e": 26491, "s": 26482, "text": "Approach" }, { "code": null, "e": 26520, "s": 26491, "text": "Create Normal Tkinter Window" }, { "code": null, "e": 26545, "s": 26520, "text": "Add Button with command " }, { "code": null, "e": 26561, "s": 26545, "text": "Execute Tkinter" }, { "code": null, "e": 26570, "s": 26561, "text": "Program:" }, { "code": null, "e": 26578, "s": 26570, "text": "Python3" }, { "code": "# Import Modulefrom tkinter import *import timefrom threading import * # Create Objectroot = Tk() # Set geometryroot.geometry(\"400x400\") def work(): print(\"sleep time start\") for i in range(10): print(i) time.sleep(1) print(\"sleep time stop\") # Create ButtonButton(root, text=\"Click Me\", command=work).pack() # Execute Tkinterroot.mainloop()", "e": 26958, "s": 26578, "text": null }, { "code": null, "e": 26966, "s": 26958, "text": "Output:" }, { "code": null, "e": 26975, "s": 26966, "text": "Approach" }, { "code": null, "e": 27004, "s": 26975, "text": "Create Normal Tkinter Window" }, { "code": null, "e": 27043, "s": 27004, "text": "Add Button with command for threading " }, { "code": null, "e": 27059, "s": 27043, "text": "Execute Tkinter" }, { "code": null, "e": 27068, "s": 27059, "text": "Program:" }, { "code": null, "e": 27076, "s": 27068, "text": "Python3" }, { "code": "# Import Modulefrom tkinter import *import timefrom threading import * # Create Objectroot = Tk() # Set geometryroot.geometry(\"400x400\") # use threading def threading(): # Call work function t1=Thread(target=work) t1.start() # work functiondef work(): print(\"sleep time start\") for i in range(10): print(i) time.sleep(1) print(\"sleep time stop\") # Create ButtonButton(root,text=\"Click Me\",command = threading).pack() # Execute Tkinterroot.mainloop()", "e": 27571, "s": 27076, "text": null }, { "code": null, "e": 27579, "s": 27571, "text": "Output:" }, { "code": null, "e": 27596, "s": 27579, "text": "Python-threading" }, { "code": null, "e": 27611, "s": 27596, "text": "Python-tkinter" }, { "code": null, "e": 27618, "s": 27611, "text": "Python" }, { "code": null, "e": 27716, "s": 27618, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27748, "s": 27716, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27790, "s": 27748, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27832, "s": 27790, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27859, "s": 27832, "text": "Python Classes and Objects" }, { "code": null, "e": 27915, "s": 27859, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27937, "s": 27915, "text": "Defaultdict in Python" }, { "code": null, "e": 27976, "s": 27937, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28007, "s": 27976, "text": "Python | os.path.join() method" }, { "code": null, "e": 28036, "s": 28007, "text": "Create a directory in Python" } ]
Find sum of non-repeating (distinct) elements in an array - GeeksforGeeks
24 May, 2021 Given an integer array with repeated elements, the task is to find sum of all distinct elements in array.Examples: Input : arr[] = {12, 10, 9, 45, 2, 10, 10, 45,10}; Output : 78 Here we take 12, 10, 9, 45, 2 for sum because it's distinct elements Input : arr[] = {1, 10, 9, 4, 2, 10, 10, 45 , 4}; Output : 71 A Simple Solution is to use two nested loops. The outer loop picks an element one by one starting from the leftmost element. The inner loop checks if the element is present on left side of it. If present, then ignores the element.Time Complexity : O(n2) Auxiliary Space : O(1)A Better Solution of this problem is that using sorting technique we firstly sort all elements of array in ascending order and and find one by one distinct elements in array. C++ Java Python3 C# Javascript // C++ Find the sum of all non-repeated// elements in an array#include<bits/stdc++.h>using namespace std; // Find the sum of all non-repeated elements// in an arrayint findSum(int arr[], int n){ // sort all elements of array sort(arr, arr + n); int sum = 0; for (int i=0; i<n; i++) { if (arr[i] != arr[i+1]) sum = sum + arr[i]; } return sum;} // Driver codeint main(){ int arr[] = {1, 2, 3, 1, 1, 4, 5, 6}; int n = sizeof(arr)/sizeof(int); cout << findSum(arr, n); return 0;} import java.util.Arrays; // Java Find the sum of all non-repeated// elements in an arraypublic class GFG { // Find the sum of all non-repeated elements// in an array static int findSum(int arr[], int n) { // sort all elements of array Arrays.sort(arr); int sum = arr[0]; for (int i = 0; i < n-1; i++) { if (arr[i] != arr[i + 1]) { sum = sum + arr[i+1]; } } return sum; } // Driver code public static void main(String[] args) { int arr[] = {1, 2, 3, 1, 1, 4, 5, 6}; int n = arr.length; System.out.println(findSum(arr, n)); }} # Python3 Find the sum of all non-repeated# elements in an array # Find the sum of all non-repeated elements# in an arraydef findSum(arr, n): # sort all elements of array arr.sort() sum = arr[0] for i in range(0,n-1): if (arr[i] != arr[i+1]): sum = sum + arr[i+1] return sum # Driver codedef main(): arr= [1, 2, 3, 1, 1, 4, 5, 6] n = len(arr) print(findSum(arr, n)) if __name__ == '__main__': main()# This code is contributed by 29AjayKumar // C# Find the sum of all non-repeated// elements in an arrayusing System;class GFG{ // Find the sum of all non-repeated elements // in an array static int findSum(int []arr, int n) { // sort all elements of array Array.Sort(arr); int sum = arr[0]; for (int i = 0; i < n - 1; i++) { if (arr[i] != arr[i + 1]) { sum = sum + arr[i + 1]; } } return sum; } // Driver code public static void Main() { int []arr = {1, 2, 3, 1, 1, 4, 5, 6}; int n = arr.Length; Console.WriteLine(findSum(arr, n)); }} // This code is contributed by 29AjayKumar <script> // JavaScript Program to find the sum of all non-repeated// elements in an array // Find the sum of all non-repeated elements// in an arrayfunction findSum(arr, n){ // sort all elements of array arr.sort(); let sum = 0; for (let i=0; i<n; i++) { if (arr[i] != arr[i+1]) sum = sum + arr[i]; } return sum;} // Driver code let arr = [1, 2, 3, 1, 1, 4, 5, 6]; let n = arr.length; document.write(findSum(arr, n)); // This code is contributed by Surbhi Tyagi </script> Output: 21 Time Complexity : O(n log n) Space Complexity : O(1)An Efficient solution of this problem is that using unordered_set we run a single for loop and which value comes first time its add in sum variable and store in hash table that for next time we not use this value. C++ Java Python3 C# Javascript // C++ Find the sum of all non- repeated// elements in an array#include<bits/stdc++.h>using namespace std; // Find the sum of all non-repeated elements// in an arrayint findSum(int arr[],int n){ int sum = 0; // Hash to store all element of array unordered_set< int > s; for (int i=0; i<n; i++) { if (s.find(arr[i]) == s.end()) { sum += arr[i]; s.insert(arr[i]); } } return sum;} // Driver codeint main(){ int arr[] = {1, 2, 3, 1, 1, 4, 5, 6}; int n = sizeof(arr)/sizeof(int); cout << findSum(arr, n); return 0;} // Java Find the sum of all non- repeated// elements in an arrayimport java.util.*; class GFG{ // Find the sum of all non-repeated elements // in an array static int findSum(int arr[], int n) { int sum = 0; // Hash to store all element of array HashSet<Integer> s = new HashSet<Integer>(); for (int i = 0; i < n; i++) { if (!s.contains(arr[i])) { sum += arr[i]; s.add(arr[i]); } } return sum; } // Driver code public static void main(String[] args) { int arr[] = {1, 2, 3, 1, 1, 4, 5, 6}; int n = arr.length; System.out.println(findSum(arr, n)); }} // This code is contributed by Rajput-Ji # Python3 Find the sum of all# non- repeated elements in an array # Find the sum of all non-repeated# elements in an arraydef findSum(arr, n): s = set() sum = 0 # Hash to store all element # of array for i in range(n): if arr[i] not in s: s.add(arr[i]) for i in s: sum = sum + i return sum # Driver codearr = [1, 2, 3, 1, 1, 4, 5, 6]n = len(arr)print(findSum(arr, n)) # This code is contributed by Shrikant13 // C# Find the sum of all non- repeated// elements in an arrayusing System;using System.Collections.Generic; class GFG{ // Find the sum of all non-repeated elements // in an array static int findSum(int []arr, int n) { int sum = 0; // Hash to store all element of array HashSet<int> s = new HashSet<int>(); for (int i = 0; i < n; i++) { if (!s.Contains(arr[i])) { sum += arr[i]; s.Add(arr[i]); } } return sum; } // Driver code public static void Main(String[] args) { int []arr = {1, 2, 3, 1, 1, 4, 5, 6}; int n = arr.Length; Console.WriteLine(findSum(arr, n)); }} // This code is contributed by Rajput-Ji <script> // Javascript program Find the sum of all non- repeated// elements in an array // Find the sum of all non-repeated elements // in an array function findSum(arr, n) { let sum = 0; // Hash to store all element of array let s = new Set(); for (let i = 0; i < n; i++) { if (!s.has(arr[i])) { sum += arr[i]; s.add(arr[i]); } } return sum; } // Driver code let arr = [1, 2, 3, 1, 1, 4, 5, 6]; let n = arr.length; document.write(findSum(arr, n)); </script> Output: 21 Time Complexity: O(n) Auxiliary Space: O(n) Method #3:Using Built-in python functions: Approach: Calculate the frequencies using Counter() function Convert the frequency keys to the list. Calculate the sum of the list. Below is the implementation of the above approach. Python3 # Python program for the above approachfrom collections import Counter # Function to return the sum of distinct elementsdef sumOfElements(arr, n): # Counter function is used to # calculate frequency of elements of array freq = Counter(arr) # Converting keys of freq dictionary to list lis = list(freq.keys()) # Return sum of list return sum(lis) # Driver codeif __name__ == "__main__": arr = [1, 2, 3, 1, 1, 4, 5, 6] n = len(arr) print(sumOfElements(arr, n)) # This code is contributed by vikkycirus Output: 21 This article is contributed by DANISH_RAZA. 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. shrikanth13 princiraj1992 29AjayKumar Rajput-Ji SachinDiwakar1 surbhityagi15 vikkycirus avijitmondal1998 Oxigen Wallet Arrays Hash Sorting Oxigen Wallet Arrays Hash Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Internal Working of HashMap in Java Count pairs with given sum Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing)
[ { "code": null, "e": 25990, "s": 25962, "text": "\n24 May, 2021" }, { "code": null, "e": 26106, "s": 25990, "text": "Given an integer array with repeated elements, the task is to find sum of all distinct elements in array.Examples: " }, { "code": null, "e": 26303, "s": 26106, "text": "Input : arr[] = {12, 10, 9, 45, 2, 10, 10, 45,10};\nOutput : 78\nHere we take 12, 10, 9, 45, 2 for sum\nbecause it's distinct elements \n\nInput : arr[] = {1, 10, 9, 4, 2, 10, 10, 45 , 4};\nOutput : 71" }, { "code": null, "e": 26756, "s": 26303, "text": "A Simple Solution is to use two nested loops. The outer loop picks an element one by one starting from the leftmost element. The inner loop checks if the element is present on left side of it. If present, then ignores the element.Time Complexity : O(n2) Auxiliary Space : O(1)A Better Solution of this problem is that using sorting technique we firstly sort all elements of array in ascending order and and find one by one distinct elements in array. " }, { "code": null, "e": 26760, "s": 26756, "text": "C++" }, { "code": null, "e": 26765, "s": 26760, "text": "Java" }, { "code": null, "e": 26773, "s": 26765, "text": "Python3" }, { "code": null, "e": 26776, "s": 26773, "text": "C#" }, { "code": null, "e": 26787, "s": 26776, "text": "Javascript" }, { "code": "// C++ Find the sum of all non-repeated// elements in an array#include<bits/stdc++.h>using namespace std; // Find the sum of all non-repeated elements// in an arrayint findSum(int arr[], int n){ // sort all elements of array sort(arr, arr + n); int sum = 0; for (int i=0; i<n; i++) { if (arr[i] != arr[i+1]) sum = sum + arr[i]; } return sum;} // Driver codeint main(){ int arr[] = {1, 2, 3, 1, 1, 4, 5, 6}; int n = sizeof(arr)/sizeof(int); cout << findSum(arr, n); return 0;}", "e": 27316, "s": 26787, "text": null }, { "code": "import java.util.Arrays; // Java Find the sum of all non-repeated// elements in an arraypublic class GFG { // Find the sum of all non-repeated elements// in an array static int findSum(int arr[], int n) { // sort all elements of array Arrays.sort(arr); int sum = arr[0]; for (int i = 0; i < n-1; i++) { if (arr[i] != arr[i + 1]) { sum = sum + arr[i+1]; } } return sum; } // Driver code public static void main(String[] args) { int arr[] = {1, 2, 3, 1, 1, 4, 5, 6}; int n = arr.length; System.out.println(findSum(arr, n)); }}", "e": 27964, "s": 27316, "text": null }, { "code": " # Python3 Find the sum of all non-repeated# elements in an array # Find the sum of all non-repeated elements# in an arraydef findSum(arr, n): # sort all elements of array arr.sort() sum = arr[0] for i in range(0,n-1): if (arr[i] != arr[i+1]): sum = sum + arr[i+1] return sum # Driver codedef main(): arr= [1, 2, 3, 1, 1, 4, 5, 6] n = len(arr) print(findSum(arr, n)) if __name__ == '__main__': main()# This code is contributed by 29AjayKumar", "e": 28466, "s": 27964, "text": null }, { "code": "// C# Find the sum of all non-repeated// elements in an arrayusing System;class GFG{ // Find the sum of all non-repeated elements // in an array static int findSum(int []arr, int n) { // sort all elements of array Array.Sort(arr); int sum = arr[0]; for (int i = 0; i < n - 1; i++) { if (arr[i] != arr[i + 1]) { sum = sum + arr[i + 1]; } } return sum; } // Driver code public static void Main() { int []arr = {1, 2, 3, 1, 1, 4, 5, 6}; int n = arr.Length; Console.WriteLine(findSum(arr, n)); }} // This code is contributed by 29AjayKumar", "e": 29158, "s": 28466, "text": null }, { "code": "<script> // JavaScript Program to find the sum of all non-repeated// elements in an array // Find the sum of all non-repeated elements// in an arrayfunction findSum(arr, n){ // sort all elements of array arr.sort(); let sum = 0; for (let i=0; i<n; i++) { if (arr[i] != arr[i+1]) sum = sum + arr[i]; } return sum;} // Driver code let arr = [1, 2, 3, 1, 1, 4, 5, 6]; let n = arr.length; document.write(findSum(arr, n)); // This code is contributed by Surbhi Tyagi </script>", "e": 29681, "s": 29158, "text": null }, { "code": null, "e": 29690, "s": 29681, "text": "Output: " }, { "code": null, "e": 29693, "s": 29690, "text": "21" }, { "code": null, "e": 29960, "s": 29693, "text": "Time Complexity : O(n log n) Space Complexity : O(1)An Efficient solution of this problem is that using unordered_set we run a single for loop and which value comes first time its add in sum variable and store in hash table that for next time we not use this value. " }, { "code": null, "e": 29964, "s": 29960, "text": "C++" }, { "code": null, "e": 29969, "s": 29964, "text": "Java" }, { "code": null, "e": 29977, "s": 29969, "text": "Python3" }, { "code": null, "e": 29980, "s": 29977, "text": "C#" }, { "code": null, "e": 29991, "s": 29980, "text": "Javascript" }, { "code": "// C++ Find the sum of all non- repeated// elements in an array#include<bits/stdc++.h>using namespace std; // Find the sum of all non-repeated elements// in an arrayint findSum(int arr[],int n){ int sum = 0; // Hash to store all element of array unordered_set< int > s; for (int i=0; i<n; i++) { if (s.find(arr[i]) == s.end()) { sum += arr[i]; s.insert(arr[i]); } } return sum;} // Driver codeint main(){ int arr[] = {1, 2, 3, 1, 1, 4, 5, 6}; int n = sizeof(arr)/sizeof(int); cout << findSum(arr, n); return 0;}", "e": 30581, "s": 29991, "text": null }, { "code": "// Java Find the sum of all non- repeated// elements in an arrayimport java.util.*; class GFG{ // Find the sum of all non-repeated elements // in an array static int findSum(int arr[], int n) { int sum = 0; // Hash to store all element of array HashSet<Integer> s = new HashSet<Integer>(); for (int i = 0; i < n; i++) { if (!s.contains(arr[i])) { sum += arr[i]; s.add(arr[i]); } } return sum; } // Driver code public static void main(String[] args) { int arr[] = {1, 2, 3, 1, 1, 4, 5, 6}; int n = arr.length; System.out.println(findSum(arr, n)); }} // This code is contributed by Rajput-Ji", "e": 31338, "s": 30581, "text": null }, { "code": "# Python3 Find the sum of all# non- repeated elements in an array # Find the sum of all non-repeated# elements in an arraydef findSum(arr, n): s = set() sum = 0 # Hash to store all element # of array for i in range(n): if arr[i] not in s: s.add(arr[i]) for i in s: sum = sum + i return sum # Driver codearr = [1, 2, 3, 1, 1, 4, 5, 6]n = len(arr)print(findSum(arr, n)) # This code is contributed by Shrikant13", "e": 31795, "s": 31338, "text": null }, { "code": "// C# Find the sum of all non- repeated// elements in an arrayusing System;using System.Collections.Generic; class GFG{ // Find the sum of all non-repeated elements // in an array static int findSum(int []arr, int n) { int sum = 0; // Hash to store all element of array HashSet<int> s = new HashSet<int>(); for (int i = 0; i < n; i++) { if (!s.Contains(arr[i])) { sum += arr[i]; s.Add(arr[i]); } } return sum; } // Driver code public static void Main(String[] args) { int []arr = {1, 2, 3, 1, 1, 4, 5, 6}; int n = arr.Length; Console.WriteLine(findSum(arr, n)); }} // This code is contributed by Rajput-Ji", "e": 32568, "s": 31795, "text": null }, { "code": "<script> // Javascript program Find the sum of all non- repeated// elements in an array // Find the sum of all non-repeated elements // in an array function findSum(arr, n) { let sum = 0; // Hash to store all element of array let s = new Set(); for (let i = 0; i < n; i++) { if (!s.has(arr[i])) { sum += arr[i]; s.add(arr[i]); } } return sum; } // Driver code let arr = [1, 2, 3, 1, 1, 4, 5, 6]; let n = arr.length; document.write(findSum(arr, n)); </script>", "e": 33192, "s": 32568, "text": null }, { "code": null, "e": 33202, "s": 33192, "text": "Output: " }, { "code": null, "e": 33205, "s": 33202, "text": "21" }, { "code": null, "e": 33250, "s": 33205, "text": "Time Complexity: O(n) Auxiliary Space: O(n) " }, { "code": null, "e": 33293, "s": 33250, "text": "Method #3:Using Built-in python functions:" }, { "code": null, "e": 33303, "s": 33293, "text": "Approach:" }, { "code": null, "e": 33354, "s": 33303, "text": "Calculate the frequencies using Counter() function" }, { "code": null, "e": 33394, "s": 33354, "text": "Convert the frequency keys to the list." }, { "code": null, "e": 33425, "s": 33394, "text": "Calculate the sum of the list." }, { "code": null, "e": 33476, "s": 33425, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 33484, "s": 33476, "text": "Python3" }, { "code": "# Python program for the above approachfrom collections import Counter # Function to return the sum of distinct elementsdef sumOfElements(arr, n): # Counter function is used to # calculate frequency of elements of array freq = Counter(arr) # Converting keys of freq dictionary to list lis = list(freq.keys()) # Return sum of list return sum(lis) # Driver codeif __name__ == \"__main__\": arr = [1, 2, 3, 1, 1, 4, 5, 6] n = len(arr) print(sumOfElements(arr, n)) # This code is contributed by vikkycirus", "e": 34028, "s": 33484, "text": null }, { "code": null, "e": 34036, "s": 34028, "text": "Output:" }, { "code": null, "e": 34039, "s": 34036, "text": "21" }, { "code": null, "e": 34458, "s": 34039, "text": "This article is contributed by DANISH_RAZA. 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": 34470, "s": 34458, "text": "shrikanth13" }, { "code": null, "e": 34484, "s": 34470, "text": "princiraj1992" }, { "code": null, "e": 34496, "s": 34484, "text": "29AjayKumar" }, { "code": null, "e": 34506, "s": 34496, "text": "Rajput-Ji" }, { "code": null, "e": 34521, "s": 34506, "text": "SachinDiwakar1" }, { "code": null, "e": 34535, "s": 34521, "text": "surbhityagi15" }, { "code": null, "e": 34546, "s": 34535, "text": "vikkycirus" }, { "code": null, "e": 34563, "s": 34546, "text": "avijitmondal1998" }, { "code": null, "e": 34577, "s": 34563, "text": "Oxigen Wallet" }, { "code": null, "e": 34584, "s": 34577, "text": "Arrays" }, { "code": null, "e": 34589, "s": 34584, "text": "Hash" }, { "code": null, "e": 34597, "s": 34589, "text": "Sorting" }, { "code": null, "e": 34611, "s": 34597, "text": "Oxigen Wallet" }, { "code": null, "e": 34618, "s": 34611, "text": "Arrays" }, { "code": null, "e": 34623, "s": 34618, "text": "Hash" }, { "code": null, "e": 34631, "s": 34623, "text": "Sorting" }, { "code": null, "e": 34729, "s": 34631, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34797, "s": 34729, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 34841, "s": 34797, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 34889, "s": 34841, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 34912, "s": 34889, "text": "Introduction to Arrays" }, { "code": null, "e": 34944, "s": 34912, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 35029, "s": 34944, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 35065, "s": 35029, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 35092, "s": 35065, "text": "Count pairs with given sum" }, { "code": null, "e": 35123, "s": 35092, "text": "Hashing | Set 1 (Introduction)" } ]
How to use conditional operator in jQuery a template? - GeeksforGeeks
23 Apr, 2021 In this article, we will learn to use ternary or conditional operator in jQuery. The Ternary or Conditional operator takes three operands, a condition followed by question mark followed by two expressions to execute with a semicolon (:) in between the two expressions. Syntax: condition ? expression1 : expression2 Example: Now let us try an example to find how a conditional operator is used in the jQuery template. HTML <!DOCTYPE HTML><html><head> <script src="https://code.jquery.com/jquery-3.5.0.js"></script></head> <body style="text-align:center;"> <h2 style="color:green">GeeksforGeeks</h2> <div style="background-color:red"> <p>Click the button to change the background color .</p> <button>Click me!</button> </div> <script> function toggleColor(){ tag = $('div'); // Ternary Operator (add/remove background color) // If tag color is green convert it to red otherwise convert to green. tag.css('background') == 'green' ? tag.css({'background':'red'}) : tag.css({'background':'green'}); } $('button').on('click', function(){ toggleColor(); }); </script></body></html> Output: ternary operator Picked JQuery Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show and Hide div elements using radio buttons? How to prevent Body from scrolling when a modal is opened using jQuery ? jQuery | ajax() Method jQuery | removeAttr() with Examples How to get the value in an input text box using jQuery ? jQuery | attr() Method Difference Between JavaScript and jQuery jQuery | parent() & parents() with Examples How to submit a form using ajax in jQuery ? jQuery | focus() with Examples
[ { "code": null, "e": 26980, "s": 26952, "text": "\n23 Apr, 2021" }, { "code": null, "e": 27061, "s": 26980, "text": "In this article, we will learn to use ternary or conditional operator in jQuery." }, { "code": null, "e": 27249, "s": 27061, "text": "The Ternary or Conditional operator takes three operands, a condition followed by question mark followed by two expressions to execute with a semicolon (:) in between the two expressions." }, { "code": null, "e": 27257, "s": 27249, "text": "Syntax:" }, { "code": null, "e": 27295, "s": 27257, "text": "condition ? expression1 : expression2" }, { "code": null, "e": 27397, "s": 27295, "text": "Example: Now let us try an example to find how a conditional operator is used in the jQuery template." }, { "code": null, "e": 27402, "s": 27397, "text": "HTML" }, { "code": "<!DOCTYPE HTML><html><head> <script src=\"https://code.jquery.com/jquery-3.5.0.js\"></script></head> <body style=\"text-align:center;\"> <h2 style=\"color:green\">GeeksforGeeks</h2> <div style=\"background-color:red\"> <p>Click the button to change the background color .</p> <button>Click me!</button> </div> <script> function toggleColor(){ tag = $('div'); // Ternary Operator (add/remove background color) // If tag color is green convert it to red otherwise convert to green. tag.css('background') == 'green' ? tag.css({'background':'red'}) : tag.css({'background':'green'}); } $('button').on('click', function(){ toggleColor(); }); </script></body></html>", "e": 28119, "s": 27402, "text": null }, { "code": null, "e": 28127, "s": 28119, "text": "Output:" }, { "code": null, "e": 28144, "s": 28127, "text": "ternary operator" }, { "code": null, "e": 28151, "s": 28144, "text": "Picked" }, { "code": null, "e": 28158, "s": 28151, "text": "JQuery" }, { "code": null, "e": 28256, "s": 28158, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28311, "s": 28256, "text": "How to Show and Hide div elements using radio buttons?" }, { "code": null, "e": 28384, "s": 28311, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 28407, "s": 28384, "text": "jQuery | ajax() Method" }, { "code": null, "e": 28443, "s": 28407, "text": "jQuery | removeAttr() with Examples" }, { "code": null, "e": 28500, "s": 28443, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 28523, "s": 28500, "text": "jQuery | attr() Method" }, { "code": null, "e": 28564, "s": 28523, "text": "Difference Between JavaScript and jQuery" }, { "code": null, "e": 28608, "s": 28564, "text": "jQuery | parent() & parents() with Examples" }, { "code": null, "e": 28652, "s": 28608, "text": "How to submit a form using ajax in jQuery ?" } ]
Batch Script - CD
This batch command helps in making changes to a different directory, or displays the current directory. cd The following example shows how the cd command can be used in a variety of ways. @echo off Rem The cd without any parameters is used to display the current working directory cd Rem Changing the path to Program Files cd\Program Files cd Rem Changing the path to Program Files cd %USERPROFILE% cd Rem Changing to the parent directory cd.. cd Rem Changing to the parent directory two levels up cd..\.. cd The above command will display the following output after changing to the various folder locations. C:\Users\Administrator C:\Program Files C:\Users\Administrator C:\Users C:\ Print Add Notes Bookmark this page
[ { "code": null, "e": 2273, "s": 2169, "text": "This batch command helps in making changes to a different directory, or displays the current directory." }, { "code": null, "e": 2277, "s": 2273, "text": "cd\n" }, { "code": null, "e": 2358, "s": 2277, "text": "The following example shows how the cd command can be used in a variety of ways." }, { "code": null, "e": 2679, "s": 2358, "text": "@echo off\nRem The cd without any parameters is used to display the current working directory\ncd\nRem Changing the path to Program Files\ncd\\Program Files\ncd\nRem Changing the path to Program Files\ncd %USERPROFILE%\ncd\nRem Changing to the parent directory\ncd..\ncd\nRem Changing to the parent directory two levels up\ncd..\\..\ncd" }, { "code": null, "e": 2779, "s": 2679, "text": "The above command will display the following output after changing to the various folder locations." }, { "code": null, "e": 2856, "s": 2779, "text": "C:\\Users\\Administrator\nC:\\Program Files\nC:\\Users\\Administrator\nC:\\Users\nC:\\\n" }, { "code": null, "e": 2863, "s": 2856, "text": " Print" }, { "code": null, "e": 2874, "s": 2863, "text": " Add Notes" } ]
Sum of all substrings of a number | Practice | GeeksforGeeks
Given an integer S represented as a string, the task is to get the sum of all possible sub-strings of this string. As the answer will be large, print it modulo 10^9+7. Example 1: Input: S = 1234 Output: 1670 Explanation: Sum = 1 + 2 + 3 + 4 + 12 + 23 + 34 + 123 + 234 + 1234 = 1670 Example 2: Input: S = 421 Output: 491 Explanation: Sum = 4 + 2 + 1 + 42 + 21 Your Task: You only need to complete the function sumSubstrings that takes S as an argument and returns the answer modulo 1000000007. Expected Time Complexity: O(N). Expected Auxiliary Space: O(N). Constraints: 1 <= |S| <= 104 0 vinamrajha1 week ago long long sumSubstrings(string s){ // your code here long long n = s.length(); long long dp[n],sum=0, d = 1e9+7; dp[0] = (s[0]-48)%d; for(long long i =1; i<n; ++i)dp[i] = ((i+1)*(s[i]-48)+10*dp[i-1])%d; for(long long i =0; i<n; ++i) sum = (sum+dp[i])%d; return sum; } 0 mdzeya3 months ago //java code using dynamic programming class Solution { //Function to find sum of all possible substrings of the given string. public static long sumSubstrings(String s) { //Your code here long sum[]=new long[s.length()]; long a=Character.getNumericValue(s.charAt(0)); sum[0]=a; long result=sum[0]; //sumofdigit[i] = (i+1)*num[i] + 10*sumofdigit[i-1] for(int i=1;i<s.length();i++) { long k=Character.getNumericValue(s.charAt(i)); sum[i]=(i+1)*k+10*sum[i-1]%1000000007; result+=sum[i]%1000000007; } return result%1000000007; }} -9 sumit dutta4 months ago Naive Solution : long long sumSubstrings(string s){ // your code here int n = s.length(); int mod = 1000000007; int res=0; for(int i=0 ; i<n ; i++) { string curr = ""; for(int j=i ; j<n ; j++) { curr += s[j]; res += stoi(curr); } } return res%mod; } -1 raghvan084 months ago dp solution long long sumSubstrings(string s){ // your code here int n=s.size(); long long dp[n]; dp[0]=(s[0]-'0')%1000000007; long long sum=dp[0]; for(int i=1;i<s.size();i++) { dp[i]=((i+1)*(s[i]-'0')+10*dp[i-1])%1000000007; sum=(sum+dp[i])%1000000007; } return sum%1000000007; } 0 chakresh245 months ago public static long sumSubstrings(String s) { int n = s.length(); long [] dp = new long[n]; long m = 1000000007; dp[0] = ((long)s.charAt(0))-48; for(int j = 1;j<n;j++) dp[j] = (dp[j-1]*10+(j+1)*(((long)s.charAt(j))-48))%m; long sum = 0; for(int i=0;i<n;i++){ sum = (sum+dp[i])%m; } return sum; } 0 abc123programming6 months ago JAVA SOLUTION: class Solution{ //Function to find sum of all possible substrings of the given string. public static long sumSubstrings(String s) { int n=s.length(); long dp[]=new long[n]; dp[0]=s.charAt(0)-'0'; long res=dp[0]; for(int i=1;i<n;i++){ dp[i]=(((i+1)*(s.charAt(i)-'0')) + (10 * dp[i-1])%1000000007); res = (res+dp[i])%1000000007; } return res%1000000007; }} 0 iamrbkfarhan7 months ago class Solution { public: //Function to find sum of all possible substrings of the given string. long long sumSubstrings(string s){ // your code here long long prev_res = s[0] - '0'; long long res = prev_res % 1000000007; long sub_res; for(int i = 1; i < s.size(); i++) { sub_res = ((i+1)*(s[i] - '0') + 10 * prev_res)%1000000007; res = (res + sub_res)% 1000000007; prev_res = sub_res; } return res; } }; 0 armanyppph This comment was deleted. 0 BHOOPEN SAWANT9 months ago BHOOPEN SAWANT Correct C++ soln - https://uploads.disquscdn.c... 0 Anonymous9 months ago Anonymous Recursive Approach : https://ide.geeksforgeeks.o... We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 406, "s": 238, "text": "Given an integer S represented as a string, the task is to get the sum of all possible sub-strings of this string.\nAs the answer will be large, print it modulo 10^9+7." }, { "code": null, "e": 417, "s": 406, "text": "Example 1:" }, { "code": null, "e": 521, "s": 417, "text": "Input:\nS = 1234\nOutput: 1670\nExplanation: Sum = 1 + 2 + 3 + 4 + 12 +\n23 + 34 + 123 + 234 + 1234 = 1670\n" }, { "code": null, "e": 532, "s": 521, "text": "Example 2:" }, { "code": null, "e": 598, "s": 532, "text": "Input:\nS = 421\nOutput: 491\nExplanation: Sum = 4 + 2 + 1 + 42 + 21" }, { "code": null, "e": 732, "s": 598, "text": "Your Task:\nYou only need to complete the function sumSubstrings that takes S as an argument and returns the answer modulo 1000000007." }, { "code": null, "e": 796, "s": 732, "text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(N)." }, { "code": null, "e": 825, "s": 796, "text": "Constraints:\n1 <= |S| <= 104" }, { "code": null, "e": 827, "s": 825, "text": "0" }, { "code": null, "e": 848, "s": 827, "text": "vinamrajha1 week ago" }, { "code": null, "e": 1168, "s": 848, "text": "long long sumSubstrings(string s){\n // your code here\n long long n = s.length();\n long long dp[n],sum=0, d = 1e9+7;\n dp[0] = (s[0]-48)%d;\n for(long long i =1; i<n; ++i)dp[i] = ((i+1)*(s[i]-48)+10*dp[i-1])%d;\n for(long long i =0; i<n; ++i) sum = (sum+dp[i])%d;\n return sum;\n }" }, { "code": null, "e": 1170, "s": 1168, "text": "0" }, { "code": null, "e": 1189, "s": 1170, "text": "mdzeya3 months ago" }, { "code": null, "e": 1792, "s": 1189, "text": "//java code using dynamic programming\nclass Solution\n{\n //Function to find sum of all possible substrings of the given string.\n public static long sumSubstrings(String s)\n {\n //Your code here\n long sum[]=new long[s.length()];\n long a=Character.getNumericValue(s.charAt(0));\n sum[0]=a;\n long result=sum[0];\n //sumofdigit[i] = (i+1)*num[i] + 10*sumofdigit[i-1]\n for(int i=1;i<s.length();i++)\n {\n long k=Character.getNumericValue(s.charAt(i));\n sum[i]=(i+1)*k+10*sum[i-1]%1000000007;\n result+=sum[i]%1000000007;\n }\n return result%1000000007;\n}}" }, { "code": null, "e": 1795, "s": 1792, "text": "-9" }, { "code": null, "e": 1819, "s": 1795, "text": "sumit dutta4 months ago" }, { "code": null, "e": 2187, "s": 1819, "text": "Naive Solution : long long sumSubstrings(string s){ // your code here int n = s.length(); int mod = 1000000007; int res=0; for(int i=0 ; i<n ; i++) { string curr = \"\"; for(int j=i ; j<n ; j++) { curr += s[j]; res += stoi(curr); } } return res%mod; }" }, { "code": null, "e": 2190, "s": 2187, "text": "-1" }, { "code": null, "e": 2212, "s": 2190, "text": "raghvan084 months ago" }, { "code": null, "e": 2224, "s": 2212, "text": "dp solution" }, { "code": null, "e": 2573, "s": 2224, "text": "long long sumSubstrings(string s){ // your code here int n=s.size(); long long dp[n]; dp[0]=(s[0]-'0')%1000000007; long long sum=dp[0]; for(int i=1;i<s.size();i++) { dp[i]=((i+1)*(s[i]-'0')+10*dp[i-1])%1000000007; sum=(sum+dp[i])%1000000007; } return sum%1000000007; }" }, { "code": null, "e": 2575, "s": 2573, "text": "0" }, { "code": null, "e": 2598, "s": 2575, "text": "chakresh245 months ago" }, { "code": null, "e": 3011, "s": 2598, "text": "public static long sumSubstrings(String s)\n {\n \n int n = s.length();\n long [] dp = new long[n];\n long m = 1000000007;\n dp[0] = ((long)s.charAt(0))-48;\n for(int j = 1;j<n;j++)\n dp[j] = (dp[j-1]*10+(j+1)*(((long)s.charAt(j))-48))%m;\n \n long sum = 0;\n for(int i=0;i<n;i++){\n sum = (sum+dp[i])%m;\n }\n return sum;\n }" }, { "code": null, "e": 3017, "s": 3015, "text": "0" }, { "code": null, "e": 3047, "s": 3017, "text": "abc123programming6 months ago" }, { "code": null, "e": 3062, "s": 3047, "text": "JAVA SOLUTION:" }, { "code": null, "e": 3494, "s": 3062, "text": "class Solution{ //Function to find sum of all possible substrings of the given string. public static long sumSubstrings(String s) { int n=s.length(); long dp[]=new long[n]; dp[0]=s.charAt(0)-'0'; long res=dp[0]; for(int i=1;i<n;i++){ dp[i]=(((i+1)*(s.charAt(i)-'0')) + (10 * dp[i-1])%1000000007); res = (res+dp[i])%1000000007; } return res%1000000007; }}" }, { "code": null, "e": 3496, "s": 3494, "text": "0" }, { "code": null, "e": 3521, "s": 3496, "text": "iamrbkfarhan7 months ago" }, { "code": null, "e": 4037, "s": 3523, "text": "class Solution\n{\n public:\n //Function to find sum of all possible substrings of the given string.\n long long sumSubstrings(string s){\n \n // your code here\n long long prev_res = s[0] - '0';\n long long res = prev_res % 1000000007;\n long sub_res;\n \n for(int i = 1; i < s.size(); i++)\n {\n sub_res = ((i+1)*(s[i] - '0') + 10 * prev_res)%1000000007;\n \n res = (res + sub_res)% 1000000007;\n prev_res = sub_res;\n }\n \n return res;\n }\n};" }, { "code": null, "e": 4039, "s": 4037, "text": "0" }, { "code": null, "e": 4050, "s": 4039, "text": "armanyppph" }, { "code": null, "e": 4076, "s": 4050, "text": "This comment was deleted." }, { "code": null, "e": 4078, "s": 4076, "text": "0" }, { "code": null, "e": 4105, "s": 4078, "text": "BHOOPEN SAWANT9 months ago" }, { "code": null, "e": 4120, "s": 4105, "text": "BHOOPEN SAWANT" }, { "code": null, "e": 4171, "s": 4120, "text": "Correct C++ soln - https://uploads.disquscdn.c..." }, { "code": null, "e": 4173, "s": 4171, "text": "0" }, { "code": null, "e": 4195, "s": 4173, "text": "Anonymous9 months ago" }, { "code": null, "e": 4205, "s": 4195, "text": "Anonymous" }, { "code": null, "e": 4257, "s": 4205, "text": "Recursive Approach : https://ide.geeksforgeeks.o..." }, { "code": null, "e": 4403, "s": 4257, "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": 4439, "s": 4403, "text": " Login to access your submissions. " }, { "code": null, "e": 4449, "s": 4439, "text": "\nProblem\n" }, { "code": null, "e": 4459, "s": 4449, "text": "\nContest\n" }, { "code": null, "e": 4522, "s": 4459, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4670, "s": 4522, "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": 4878, "s": 4670, "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": 4984, "s": 4878, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
SQL Window Function — Demonstrated with Real Interview Questions from Leetcode | by Sherwin Zheng | Towards Data Science
By Sherwin Zheng The window function is a must know in SQL interviews now, though it has just been available on, for example, MySQL 8.0 since its release on 19 April 2018. Readers of this article are assumed to know SQL window functions other than basic SQL syntax. If you are not familiar with it and want to learn more, please refer to this [link] which I used for my learning. Please be noted that the syntax may differ on various SQL platforms. This article will introduce you to several common applications of it that are tested during the interview using examples from Leetcode.com The most recent Leetcode question 1596. The Most Frequently Ordered Products for Each Customer inspired me to write about this theme because it linked a bunch of knowledge points together, including the window function and its application from easy to intermediate, correlated subquery and its relationship with the window function, and the execution sequence of SQL statements. First of all, let’s start with a simple question: what is the highest salary in each department? I think the answer pops up in your mind quickly: SELECT MAX(salary) with GROUP BY department . However, what if the interviewer wants to crank it up, saying that the company wants to find out not only the highest salary but also the employee name corresponding to that salary. How do you write the query? In this sense, it is similar to the Level of Detail (LOD) operation in Tableau. This is Leetcode [184. Department Highest Salary] There are two ways to tackle this problem: window function or correlated subquery, either one should work. You may find that they are equivalent while the window function is more concise and easier to write. With the window function, easy-peasy, just write the code below While with a correlated subquery, the code cost more time to run For each row in the outer table, the correlated subquery will look up into the inner table in the WHERE clause, and compare the row in the outer table to those corresponding in the subquery. It is not limited to EXIST but can also give RANK() by using COUNT() with the WHERE statement. Other good practice questions on Leetcode are: [178. Rank Scores] (hard coding DESNE_RANK) [177. Nth Highest Salary] [185. Department Top Three Salaries] My solutions to 178 are here. It may not be the best practice, but it is a good illustration showing how the mechanism works. A brief note: Correlated subquery + COUNT() = RANK(), which gives gaps when tie Correlated subquery + COUNT(DISTINCT ) = DENSE_RANK(), which eliminate gaps when tie Why is their equivalence worth mentioning? Well, if you are so lucky that your SQL platform does not support window function, you would have to engineer an equivalent one using a correlated subquery to achieve the same effect. So it is still good to know. A sum-up of the above two examples: We can find the least value in each group using GROUP BY + MIN(), but if we want to know its corresponding value under other fields, we need to use the window function to give a rank, equivalent to correlated subquery in the older SQL version or LOD in Tableau. Let’s ramp it up again. What if we want to know the rank of “annual salary”, but it is not yet here for us to ORDER BY in our window function before summing their “monthly payments” up? For example, write a SQL query to find the most frequently ordered product(s) for each customer. orders table+----------+------------+-------------+------------+| order_id | order_date | customer_id | product_id |+----------+------------+-------------+------------+| 1 | 2020-07-31 | 1 | 1 || 2 | 2020-07-30 | 2 | 2 || 3 | 2020-08-29 | 3 | 3 || 4 | 2020-07-29 | 4 | 1 || 5 | 2020-06-10 | 1 | 2 || 6 | 2020-08-01 | 2 | 1 || 7 | 2020-08-01 | 3 | 3 || 8 | 2020-08-03 | 1 | 2 || 9 | 2020-08-07 | 2 | 3 || 10 | 2020-07-15 | 1 | 2 |+----------+------------+-------------+------------+ Questions in the previous section are simple because the ranking field — salary — is presented. But in the table above, each row records a “product” purchased by a customer, with duplications. If we adopt the previous reasoning, we need to (1) write a subquery: GROUP BY customer_id, product_id and COUNT(product_id) AS cnt, then(2) use cnt as the ranking field for the window function, and (3) filter the result in the WHERE clause, such as rnk = 1 in a third query because we cannot use window function in the WHERE statement. However, we can actually combine t1 and t2 into one query as follows In the beginning, it is not instinctive to me when combining PARTITION BY with GROUP BY: on which partition/group is the query based? But it unraveled after I reviewed the query order of execution: FROM and JOIN s.WHERE ...GROUP BY ...HAVING ...SELECT ...DISTINCT ...ORDER BY ...LIMIT / OFFSET. FROM and JOIN s. WHERE ... GROUP BY ... HAVING ... SELECT ... DISTINCT ... ORDER BY ... LIMIT / OFFSET. It is relevant to know that window functions are executed at the same stage as SELECT, so is everything coming with it, including PARTITION BY . Therefore, the actual execution step by step would be as below (Note: the code in the previous chunk won’t present CNT in the result, but it will calculate it as illustrated). This is [Leetcode 1596. The Most Frequently Ordered Products for Each Customer] A further thought by me was that what if we wanted to know the second most, or even the nth most-purchased product as we compare this question to [177. Nth Highest Salary]. How would you modify the code in the last chunk? change rnk = 1 to rnk = 2, or change rnk = 1 to rnk = 2 and change RANK() to DENSE_RANK() at the same time? It is for you to think. After reading this article, you should be familiar with the relationship. Mastering this type of data granularity question is helpful in many aspects. We started by introducing the value and usage of the window function and comparing it to simple GROUP BY. Then we gained deeper understandings about both window function and correlated subquery. Lastly, we learned how to rank any level of detail with data of higher granularity. After this article, you should be able to handle this type of question whether in an interview or production and dig insights from any level of detail by practicing your SQL expertise with window functions. About me Sherwin is a Master of Science in Business Analytics at Wake Forest University, with an undergraduate major in Management Science at Sun Yat-sen University and a minor in Big Data from Rotterdam School of Management (RSM), Erasmus University. Check my LinkedIn or Github for more.
[ { "code": null, "e": 189, "s": 172, "text": "By Sherwin Zheng" }, { "code": null, "e": 344, "s": 189, "text": "The window function is a must know in SQL interviews now, though it has just been available on, for example, MySQL 8.0 since its release on 19 April 2018." }, { "code": null, "e": 621, "s": 344, "text": "Readers of this article are assumed to know SQL window functions other than basic SQL syntax. If you are not familiar with it and want to learn more, please refer to this [link] which I used for my learning. Please be noted that the syntax may differ on various SQL platforms." }, { "code": null, "e": 760, "s": 621, "text": "This article will introduce you to several common applications of it that are tested during the interview using examples from Leetcode.com" }, { "code": null, "e": 1139, "s": 760, "text": "The most recent Leetcode question 1596. The Most Frequently Ordered Products for Each Customer inspired me to write about this theme because it linked a bunch of knowledge points together, including the window function and its application from easy to intermediate, correlated subquery and its relationship with the window function, and the execution sequence of SQL statements." }, { "code": null, "e": 1331, "s": 1139, "text": "First of all, let’s start with a simple question: what is the highest salary in each department? I think the answer pops up in your mind quickly: SELECT MAX(salary) with GROUP BY department ." }, { "code": null, "e": 1671, "s": 1331, "text": "However, what if the interviewer wants to crank it up, saying that the company wants to find out not only the highest salary but also the employee name corresponding to that salary. How do you write the query? In this sense, it is similar to the Level of Detail (LOD) operation in Tableau. This is Leetcode [184. Department Highest Salary]" }, { "code": null, "e": 1879, "s": 1671, "text": "There are two ways to tackle this problem: window function or correlated subquery, either one should work. You may find that they are equivalent while the window function is more concise and easier to write." }, { "code": null, "e": 1943, "s": 1879, "text": "With the window function, easy-peasy, just write the code below" }, { "code": null, "e": 2008, "s": 1943, "text": "While with a correlated subquery, the code cost more time to run" }, { "code": null, "e": 2294, "s": 2008, "text": "For each row in the outer table, the correlated subquery will look up into the inner table in the WHERE clause, and compare the row in the outer table to those corresponding in the subquery. It is not limited to EXIST but can also give RANK() by using COUNT() with the WHERE statement." }, { "code": null, "e": 2341, "s": 2294, "text": "Other good practice questions on Leetcode are:" }, { "code": null, "e": 2385, "s": 2341, "text": "[178. Rank Scores] (hard coding DESNE_RANK)" }, { "code": null, "e": 2411, "s": 2385, "text": "[177. Nth Highest Salary]" }, { "code": null, "e": 2448, "s": 2411, "text": "[185. Department Top Three Salaries]" }, { "code": null, "e": 2574, "s": 2448, "text": "My solutions to 178 are here. It may not be the best practice, but it is a good illustration showing how the mechanism works." }, { "code": null, "e": 2588, "s": 2574, "text": "A brief note:" }, { "code": null, "e": 2654, "s": 2588, "text": "Correlated subquery + COUNT() = RANK(), which gives gaps when tie" }, { "code": null, "e": 2739, "s": 2654, "text": "Correlated subquery + COUNT(DISTINCT ) = DENSE_RANK(), which eliminate gaps when tie" }, { "code": null, "e": 2995, "s": 2739, "text": "Why is their equivalence worth mentioning? Well, if you are so lucky that your SQL platform does not support window function, you would have to engineer an equivalent one using a correlated subquery to achieve the same effect. So it is still good to know." }, { "code": null, "e": 3031, "s": 2995, "text": "A sum-up of the above two examples:" }, { "code": null, "e": 3293, "s": 3031, "text": "We can find the least value in each group using GROUP BY + MIN(), but if we want to know its corresponding value under other fields, we need to use the window function to give a rank, equivalent to correlated subquery in the older SQL version or LOD in Tableau." }, { "code": null, "e": 3317, "s": 3293, "text": "Let’s ramp it up again." }, { "code": null, "e": 3479, "s": 3317, "text": "What if we want to know the rank of “annual salary”, but it is not yet here for us to ORDER BY in our window function before summing their “monthly payments” up?" }, { "code": null, "e": 3576, "s": 3479, "text": "For example, write a SQL query to find the most frequently ordered product(s) for each customer." }, { "code": null, "e": 4317, "s": 3576, "text": "orders table+----------+------------+-------------+------------+| order_id | order_date | customer_id | product_id |+----------+------------+-------------+------------+| 1 | 2020-07-31 | 1 | 1 || 2 | 2020-07-30 | 2 | 2 || 3 | 2020-08-29 | 3 | 3 || 4 | 2020-07-29 | 4 | 1 || 5 | 2020-06-10 | 1 | 2 || 6 | 2020-08-01 | 2 | 1 || 7 | 2020-08-01 | 3 | 3 || 8 | 2020-08-03 | 1 | 2 || 9 | 2020-08-07 | 2 | 3 || 10 | 2020-07-15 | 1 | 2 |+----------+------------+-------------+------------+" }, { "code": null, "e": 4510, "s": 4317, "text": "Questions in the previous section are simple because the ranking field — salary — is presented. But in the table above, each row records a “product” purchased by a customer, with duplications." }, { "code": null, "e": 4846, "s": 4510, "text": "If we adopt the previous reasoning, we need to (1) write a subquery: GROUP BY customer_id, product_id and COUNT(product_id) AS cnt, then(2) use cnt as the ranking field for the window function, and (3) filter the result in the WHERE clause, such as rnk = 1 in a third query because we cannot use window function in the WHERE statement." }, { "code": null, "e": 4915, "s": 4846, "text": "However, we can actually combine t1 and t2 into one query as follows" }, { "code": null, "e": 5113, "s": 4915, "text": "In the beginning, it is not instinctive to me when combining PARTITION BY with GROUP BY: on which partition/group is the query based? But it unraveled after I reviewed the query order of execution:" }, { "code": null, "e": 5210, "s": 5113, "text": "FROM and JOIN s.WHERE ...GROUP BY ...HAVING ...SELECT ...DISTINCT ...ORDER BY ...LIMIT / OFFSET." }, { "code": null, "e": 5227, "s": 5210, "text": "FROM and JOIN s." }, { "code": null, "e": 5237, "s": 5227, "text": "WHERE ..." }, { "code": null, "e": 5250, "s": 5237, "text": "GROUP BY ..." }, { "code": null, "e": 5261, "s": 5250, "text": "HAVING ..." }, { "code": null, "e": 5272, "s": 5261, "text": "SELECT ..." }, { "code": null, "e": 5285, "s": 5272, "text": "DISTINCT ..." }, { "code": null, "e": 5298, "s": 5285, "text": "ORDER BY ..." }, { "code": null, "e": 5314, "s": 5298, "text": "LIMIT / OFFSET." }, { "code": null, "e": 5635, "s": 5314, "text": "It is relevant to know that window functions are executed at the same stage as SELECT, so is everything coming with it, including PARTITION BY . Therefore, the actual execution step by step would be as below (Note: the code in the previous chunk won’t present CNT in the result, but it will calculate it as illustrated)." }, { "code": null, "e": 5715, "s": 5635, "text": "This is [Leetcode 1596. The Most Frequently Ordered Products for Each Customer]" }, { "code": null, "e": 5937, "s": 5715, "text": "A further thought by me was that what if we wanted to know the second most, or even the nth most-purchased product as we compare this question to [177. Nth Highest Salary]. How would you modify the code in the last chunk?" }, { "code": null, "e": 5967, "s": 5937, "text": "change rnk = 1 to rnk = 2, or" }, { "code": null, "e": 6045, "s": 5967, "text": "change rnk = 1 to rnk = 2 and change RANK() to DENSE_RANK() at the same time?" }, { "code": null, "e": 6143, "s": 6045, "text": "It is for you to think. After reading this article, you should be familiar with the relationship." }, { "code": null, "e": 6499, "s": 6143, "text": "Mastering this type of data granularity question is helpful in many aspects. We started by introducing the value and usage of the window function and comparing it to simple GROUP BY. Then we gained deeper understandings about both window function and correlated subquery. Lastly, we learned how to rank any level of detail with data of higher granularity." }, { "code": null, "e": 6706, "s": 6499, "text": "After this article, you should be able to handle this type of question whether in an interview or production and dig insights from any level of detail by practicing your SQL expertise with window functions." }, { "code": null, "e": 6715, "s": 6706, "text": "About me" } ]
Deep Learning #3: More on CNNs & Handling Overfitting | by Rutger Ruizendaal | Towards Data Science
This post is part of a series on deep learning. Check-out part 1 and part 2. Welcome to the third entry in this series on deep learning! This week I will explore some more parts of the Convolutional Neural Network (CNN) and will also discuss how to deal with underfitting and overfitting. So what exactly is a convolution? As you might remember from my previous blog entries we basically take a small filter and slide this filter over the whole image. Next, the pixel values of the image are multiplied with the pixel values in the filter. The beauty in using deep learning is that we do not have to think about how these filters should look. Through Stochastic Gradient Descent (SGD) the network is able to learn the optimal filters. The filters are initialized at random and are location-invariant. This means that they can find something everywhere in the image. At the same time the model also learns where in the image it has found this thing. Zero padding is a helpful tool when applying this filters. All this does, is at extra borders of zero pixels around the image. This allows us to also capture the edges of the images when sliding the filter over the image. You might wonder what size the filters should be. Research has shown that smaller filters generally perform better. In this case we use filters of size 3x3. When we slide these filters over our image we basically create another image. Therefore, if our original image was 30x30 the output of a convolutional layer with 12 filters will be 30x30x12. Now we have a tensor, which basically is a matrix with over 2 dimensions. Now you also know where the name TensorFlow comes from. After each convolutional layer (or multiple) we typically have a max pooling layer. This layer simply reduces the amount of pixels in the image. For example, we can take a square of our image and replace this with only the highest value on the square. Because of Max Poling our filters can explore bigger parts of the image. Additionally, because of the loss in pixels we typically increase the number of filters after used max pooling. In theory every model architecture will work and should be able to provide a good solution to your problem. However, some architectures do it much faster than others. A very bad architecture might take longer training than the amount of years you have left ... Therefore, it is useful to think about the architecture of your model and why we use things like max pooling and change the amount of filters used. To finish this part on CNNs, this page provides a great video that visualizes what happens inside a CNN. How do you know if your model is underfitting? Your model is underfitting if the accuracy on the validation set is higher than the accuracy on the training set. Additionally, if the whole model performs bad this is also called underfitting. For example, using a linear model for image recognition will generally result in an underfitting model. Alternatively, when experiencing underfitting in your deep neural network this is probably caused by dropout. Dropout randomly sets activations to zero during the training process to avoid overfitting. This does not happen during prediction on the validation/test set. If this is the case you can remove dropout. If the model is now massively overfitting you can start adding dropout in small pieces. As a general rule: Start by overfitting the model, then take measures against overfitting. Overfitting happens when your model fits too well to the training set. It then becomes difficult for the model to generalize to new examples that were not in the training set. For example, your model recognizes specific images in your training set instead of general patterns. Your training accuracy will be higher than the accuracy on the validation/test set. So what can we do to reduce overfitting? Steps for reducing overfitting: Add more dataUse data augmentationUse architectures that generalize wellAdd regularization (mostly dropout, L1/L2 regularization are also possible)Reduce architecture complexity. Add more data Use data augmentation Use architectures that generalize well Add regularization (mostly dropout, L1/L2 regularization are also possible) Reduce architecture complexity. The first step is of course to collect more data. However, in most cases you will not be able to. Let’s assume you have collected all the data. The next step is data augmentation: something that is always recommended to use. Data augmentation includes things like randomly rotating the image, zooming in, adding a color filter etc. Data augmentation only happens to the training set and not on the validation/test set. It can be useful to check if you are using too much data augmentation. For example, if you zoom in so much that features of a cat are not visible anymore, than the model is not going to get better from training on these images. Let’s explore some data augmentation! For followers of the Fast AI course: be aware that the notebook uses ‘width_zoom_range’ as one of the data augmentation arguments. However, this option is not available anymore in Keras. Let’s now have a look at the image after performing data augmentation. All of the ‘cats’ are still clearly recognizable as cats to me. The third step is to use an architecture that generalizes well. However, much more important is the fourth step: adding regularization. The three most popular options are: dropout, L1 regularization and L2 regularization. In deep learning you will mostly see dropout, which I discussed earlier. Dropout deletes a random sample of the activations (makes them zero) in training. In the Vgg model this is only applied in the fully connected layers at the end of the model. However, it can also be applied to the convolutional layers. Be aware that dropout causes information to get lost. If you lose something in the first layer, it gets lost for the whole network. Therefore, a good practice is to start with a low dropout in the first layer and then gradually increase it. The fifth and final option is to reduce the network complexity. In reality, various forms of regularization should be enough to deal with overfitting in most cases. Finally, let’s discuss batch normalization. This is something you should always do! Batch normalization is a relatively new concept and therefore was not yet implemented in the Vgg model. Standardizing the inputs of your model is something that you have definitely heard about if you are into machine learning. Batch normalization takes this a step further. Batch normalization adds a ‘normalization layer’ after each convolutional layer. This allows the model to converge much faster in training and therefore also allows you to use higher learning rates. Simply standardizing the weights in each activation layer will not work. Stochastic Gradient Descent is very stubborn. If wants to make one of the weights very high it will simply do it the next time. With batch normalization the model learns that it can adjust all the weights instead of one each time. The MNIST handwritten digits dataset is one of the most famous datasets in machine learning. The dataset also is a great way to experiment with everything we now know about CNNs. Kaggle also hosts the MNIST dataset. This code I quickly wrote is all that is necessary to score 96.8% accuracy on this dataset. import pandas as pdfrom sklearn.ensemble import RandomForestClassifiertrain = pd.read_csv('train_digits.csv')test = pd.read_csv('test_digits.csv')X = train.drop('label', axis=1)y = train['label']rfc = RandomForestClassifier(n_estimators=300)pred = rfc.fit(X, y).predict(test)
[ { "code": null, "e": 249, "s": 172, "text": "This post is part of a series on deep learning. Check-out part 1 and part 2." }, { "code": null, "e": 461, "s": 249, "text": "Welcome to the third entry in this series on deep learning! This week I will explore some more parts of the Convolutional Neural Network (CNN) and will also discuss how to deal with underfitting and overfitting." }, { "code": null, "e": 1121, "s": 461, "text": "So what exactly is a convolution? As you might remember from my previous blog entries we basically take a small filter and slide this filter over the whole image. Next, the pixel values of the image are multiplied with the pixel values in the filter. The beauty in using deep learning is that we do not have to think about how these filters should look. Through Stochastic Gradient Descent (SGD) the network is able to learn the optimal filters. The filters are initialized at random and are location-invariant. This means that they can find something everywhere in the image. At the same time the model also learns where in the image it has found this thing." }, { "code": null, "e": 1500, "s": 1121, "text": "Zero padding is a helpful tool when applying this filters. All this does, is at extra borders of zero pixels around the image. This allows us to also capture the edges of the images when sliding the filter over the image. You might wonder what size the filters should be. Research has shown that smaller filters generally perform better. In this case we use filters of size 3x3." }, { "code": null, "e": 1821, "s": 1500, "text": "When we slide these filters over our image we basically create another image. Therefore, if our original image was 30x30 the output of a convolutional layer with 12 filters will be 30x30x12. Now we have a tensor, which basically is a matrix with over 2 dimensions. Now you also know where the name TensorFlow comes from." }, { "code": null, "e": 2073, "s": 1821, "text": "After each convolutional layer (or multiple) we typically have a max pooling layer. This layer simply reduces the amount of pixels in the image. For example, we can take a square of our image and replace this with only the highest value on the square." }, { "code": null, "e": 2258, "s": 2073, "text": "Because of Max Poling our filters can explore bigger parts of the image. Additionally, because of the loss in pixels we typically increase the number of filters after used max pooling." }, { "code": null, "e": 2772, "s": 2258, "text": "In theory every model architecture will work and should be able to provide a good solution to your problem. However, some architectures do it much faster than others. A very bad architecture might take longer training than the amount of years you have left ... Therefore, it is useful to think about the architecture of your model and why we use things like max pooling and change the amount of filters used. To finish this part on CNNs, this page provides a great video that visualizes what happens inside a CNN." }, { "code": null, "e": 3518, "s": 2772, "text": "How do you know if your model is underfitting? Your model is underfitting if the accuracy on the validation set is higher than the accuracy on the training set. Additionally, if the whole model performs bad this is also called underfitting. For example, using a linear model for image recognition will generally result in an underfitting model. Alternatively, when experiencing underfitting in your deep neural network this is probably caused by dropout. Dropout randomly sets activations to zero during the training process to avoid overfitting. This does not happen during prediction on the validation/test set. If this is the case you can remove dropout. If the model is now massively overfitting you can start adding dropout in small pieces." }, { "code": null, "e": 3609, "s": 3518, "text": "As a general rule: Start by overfitting the model, then take measures against overfitting." }, { "code": null, "e": 4011, "s": 3609, "text": "Overfitting happens when your model fits too well to the training set. It then becomes difficult for the model to generalize to new examples that were not in the training set. For example, your model recognizes specific images in your training set instead of general patterns. Your training accuracy will be higher than the accuracy on the validation/test set. So what can we do to reduce overfitting?" }, { "code": null, "e": 4043, "s": 4011, "text": "Steps for reducing overfitting:" }, { "code": null, "e": 4222, "s": 4043, "text": "Add more dataUse data augmentationUse architectures that generalize wellAdd regularization (mostly dropout, L1/L2 regularization are also possible)Reduce architecture complexity." }, { "code": null, "e": 4236, "s": 4222, "text": "Add more data" }, { "code": null, "e": 4258, "s": 4236, "text": "Use data augmentation" }, { "code": null, "e": 4297, "s": 4258, "text": "Use architectures that generalize well" }, { "code": null, "e": 4373, "s": 4297, "text": "Add regularization (mostly dropout, L1/L2 regularization are also possible)" }, { "code": null, "e": 4405, "s": 4373, "text": "Reduce architecture complexity." }, { "code": null, "e": 4630, "s": 4405, "text": "The first step is of course to collect more data. However, in most cases you will not be able to. Let’s assume you have collected all the data. The next step is data augmentation: something that is always recommended to use." }, { "code": null, "e": 5090, "s": 4630, "text": "Data augmentation includes things like randomly rotating the image, zooming in, adding a color filter etc. Data augmentation only happens to the training set and not on the validation/test set. It can be useful to check if you are using too much data augmentation. For example, if you zoom in so much that features of a cat are not visible anymore, than the model is not going to get better from training on these images. Let’s explore some data augmentation!" }, { "code": null, "e": 5277, "s": 5090, "text": "For followers of the Fast AI course: be aware that the notebook uses ‘width_zoom_range’ as one of the data augmentation arguments. However, this option is not available anymore in Keras." }, { "code": null, "e": 5412, "s": 5277, "text": "Let’s now have a look at the image after performing data augmentation. All of the ‘cats’ are still clearly recognizable as cats to me." }, { "code": null, "e": 6349, "s": 5412, "text": "The third step is to use an architecture that generalizes well. However, much more important is the fourth step: adding regularization. The three most popular options are: dropout, L1 regularization and L2 regularization. In deep learning you will mostly see dropout, which I discussed earlier. Dropout deletes a random sample of the activations (makes them zero) in training. In the Vgg model this is only applied in the fully connected layers at the end of the model. However, it can also be applied to the convolutional layers. Be aware that dropout causes information to get lost. If you lose something in the first layer, it gets lost for the whole network. Therefore, a good practice is to start with a low dropout in the first layer and then gradually increase it. The fifth and final option is to reduce the network complexity. In reality, various forms of regularization should be enough to deal with overfitting in most cases." }, { "code": null, "e": 6537, "s": 6349, "text": "Finally, let’s discuss batch normalization. This is something you should always do! Batch normalization is a relatively new concept and therefore was not yet implemented in the Vgg model." }, { "code": null, "e": 6906, "s": 6537, "text": "Standardizing the inputs of your model is something that you have definitely heard about if you are into machine learning. Batch normalization takes this a step further. Batch normalization adds a ‘normalization layer’ after each convolutional layer. This allows the model to converge much faster in training and therefore also allows you to use higher learning rates." }, { "code": null, "e": 7210, "s": 6906, "text": "Simply standardizing the weights in each activation layer will not work. Stochastic Gradient Descent is very stubborn. If wants to make one of the weights very high it will simply do it the next time. With batch normalization the model learns that it can adjust all the weights instead of one each time." }, { "code": null, "e": 7518, "s": 7210, "text": "The MNIST handwritten digits dataset is one of the most famous datasets in machine learning. The dataset also is a great way to experiment with everything we now know about CNNs. Kaggle also hosts the MNIST dataset. This code I quickly wrote is all that is necessary to score 96.8% accuracy on this dataset." } ]
Why do we use question mark literal in Python regular expression?
The question mark literal is used in different ways in Python Regular Expressions As a special character '?' causes the resulting RE to match 0 or 1 repetitions of the preceding RE. ab? will match either ‘a’ or ‘ab’ The question mark literal '?' is used following ways as per Python docs. *?, +?, ?? The '*', '+', and '?' qualifiers are all greedy; they match as much text as possible. Sometimes this behaviour isn’t desired; if the RE <.*> is matched against '<a> b <c>', it will match the entire string, and not just '<a>'. Adding ? after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using the RE <.*?> will match only '<a>'.
[ { "code": null, "e": 1144, "s": 1062, "text": "The question mark literal is used in different ways in Python Regular Expressions" }, { "code": null, "e": 1278, "s": 1144, "text": "As a special character '?' causes the resulting RE to match 0 or 1 repetitions of the preceding RE. ab? will match either ‘a’ or ‘ab’" }, { "code": null, "e": 1351, "s": 1278, "text": "The question mark literal '?' is used following ways as per Python docs." }, { "code": null, "e": 1362, "s": 1351, "text": "*?, +?, ??" }, { "code": null, "e": 1767, "s": 1362, "text": "The '*', '+', and '?' qualifiers are all greedy; they match as much text as possible. Sometimes this behaviour isn’t desired; if the RE <.*> is matched against '<a> b <c>', it will match the entire string, and not just '<a>'. Adding ? after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using the RE <.*?> will match only '<a>'." } ]